DEV Community

Ian de Jesus
Ian de Jesus

Posted on

Wagmi Essentials

Simulate contracts to get error messages before user tries it

const { data, error, status } = useSimulateContract({
    abi: BookingFactoryABI,
    address: process.env.NEXT_PUBLIC_BOOKING_FACTORY_ADDRESS as any,
    functionName: 'createBooking',
    args: [1n, 'simulate'],
  })
Enter fullscreen mode Exit fullscreen mode

Estimate gas price for transaction to check if user has enough balance


  useEffect(() => {
    const a = async () => {
      if (publicClient) {
        const a = await estimateContractGas(publicClient, {
          abi: BookingFactoryABI,
          address: process.env.NEXT_PUBLIC_BOOKING_FACTORY_ADDRESS as any,
          functionName: 'createBooking',
          args: [1n, 'simulate'],
        })
        console.log(a, 'gasss')
      }
    }
    a()
  }, [publicClient])
Enter fullscreen mode Exit fullscreen mode

Watch contract events to to retrieve write transaction reults

  useEffect(() => {
    if (publicClient) {
      publicClient.watchContractEvent({
        abi: BookingFactoryABI,
        eventName: 'BookingCreated',
        onLogs: (logs) => {
          console.log(logs)
        },
      })
    }
  }, [publicClient])
Enter fullscreen mode Exit fullscreen mode

Wait for transaction receipt after on success in writecontractasync to get events for that transaction

await writeContractAsync(
      {
        abi: BookingFactoryABI,
        address: process.env.NEXT_PUBLIC_BOOKING_FACTORY_ADDRESS as any,
        functionName: 'createBooking',
        args: [influencersRequired, bookingId],
      },
      {
        onError: (error) => {
          setIsLoading(false)
        },
        onSuccess: async (hash) => {
          if (publicClient) {
            const receipt = await waitForTransactionReceipt(publicClient, {
              hash,
            })

            const bookingIdInBytes = keccak256(toBytes(bookingId))
            const log = receipt.logs.find((log) => log.topics[1] === bookingIdInBytes)

            if (log) {
              await axios.post('/api/booking/set-blockchain-address', {
                booking_id: bookingId,
                blockchain_address: log.topics[0],
              })

              // window.open('/dashboard/my-bookings', '_self')
            }
          }

          setIsLoading(false)
        },
      },
    )
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs