Contract Hooks
Contract interactions based on wagmi.sh (v0.5.9)
Install dependencies
npm install wagmi ethers
useContractWrite
// import contract information and hook
import { useContractWrite } from 'wagmi'
import { DEPLOYED_CONTRACT_ADDRESS, CONTRACT_ABI, CONTRACT_CHAIN_ID } from '../constants'
// instantiate contract function
const { write } = useContractWrite({
addressOrName: DEPLOYED_CONTRACT_ADDRESS,
chainId: CONTRACT_CHAIN_ID,
contractInterface: CONTRACT_ABI,
functionName: 'writeSomeStuff',
args: [firstParam, secondParam],
overrides: {
from: address,
value: amountInWei,
},
onMutate({ args, overrides }) {
console.log('Mutate', { args, overrides })
},
onError(error) {
console.log('Error', error)
},
onSuccess(data) {
console.log('Success', data)
},
})
// call function
<button onClick={() => write()}>
Call Function
</button>
useContractReads
// import contract information and hook
import { useContractReads } from 'wagmi'
import { DEPLOYED_CONTRACT_ADDRESS, CONTRACT_ABI, CONTRACT_CHAIN_ID } from '../constants'
// create contract instance
const contract = {
addressOrName: DEPLOYED_CONTRACT_ADDRESS,
contractInterface: CONTRACT_ABI,
}
// instantiate read function
const { data, isError, isLoading } = useContractReads({
contracts: [
{
...contract,
functionName: 'firstGetterFunction',
args: [firstParam, secondParam],
chainId: CONTRACT_CHAIN_ID,
},
{
...contract,
functionName: 'secondGetterFunction',
args: addr,
chainId: CONTRACT_CHAIN_ID,
},
],
onSuccess(data) {
console.log('first read result', data[0])
console.log('second read result', data[1])
},
onError(error) {
console.log('Error', error)
},
})
References: https://wagmi.sh/
Last updated