Wagmi Essentials

iandjx

Ian de Jesus

Posted on February 24, 2024

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
๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
iandjx
Ian de Jesus

Posted on February 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About