Wagmi Essentials

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'],
  })

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])

Watch contract events to to retrieve write transaction reults

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

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)
        },
      },
    )
Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
january-1,-1970-=>-january-19,-2038-error!

January 1, 1970 => January 19, 2038 Error!

Next Post
refactoring-for-performance

Refactoring for Performance

Related Posts