1、useContractReaduseContractRead主要就是用来调用合约的读取方法的,比如solidity里面带有view和pure的方法,是不需要gas费的。参数address是合约地址,在区块浏览器可以查询到参数abi就是合约的ABI,在区块浏览器可以查询到chainId就是
useContractRead主要就是用来调用合约的读取方法的,比如solidity里面带有view和pure的方法,是不需要gas费的。 参数address是合约地址,在区块浏览器可以查询到 参数abi就是合约的ABI,在区块浏览器可以查询到 chainId就是要查询的链,不填的话默认是当前链, functionName是方法名称,可以看一下ABI上有哪些方法, args就是方法所需的参数,参数一定要和方法对应,否则会报错的哈。
import {useContractRead, erc20ABI,erc721ABI,erc4626ABI, } from 'wagmi'
import bigTimeABI from '../../assets/abi/bigTimeABI.json'
const index: React.FC = () => {
const abi = JSON.parse(bigTimeABI.result)
//const abi = erc20ABI
const result = useContractRead({
address: '0x64Bc2cA1Be492bE7185FAA2c8835d9b824c8a194',
abi,
chainId就是要查询的链,不填的话默认是当前链,
: 1,
functionName: 'balanceOf',
args: ['0x0dxxxxxxxxxxxxxxxxxxxxxxxxxxxx'],
})
return ( );
};
返回结果如下:
可以同时调用多个合约读取方法。
const result = useContractReads({
contracts: [
{
address: '0x64Bc2cA1Be492bE7185FAA2c8835d9b824c8a194',
abi,
chainId: 1,
functionName: 'balanceOf',
args: ['0x0dxxxxxxxxxxxxxxxxxxxxxxxxxxxx'],
},
{
address: '0x64Bc2cA1Be492bE7185FAA2c8835d9b824c8a194',
abi,
chainId: 1,
functionName: 'balanceOf',
args: ['0x0dyyyyyyyyyyyyyyyyyyyyyyyyyy'],
}
]
})
返回结果如下:
useContractInfiniteReads主要是用来读取合约带有分页返回值的方法, 比如有1000条数据,但是默认只返回100条,有10页,这种方法就适合用这个hook, 我这里暂时没有这种例子,所以就不实验了。
useContractWrite调用合约的可写方法,调用的话数据会上链,是需要gas费的。 useContractWrite会返回write方法,调用write方法才会写入。
import { Layout, Button, Row } from 'antd';
import React from 'react';
import {useAccount, useContractWrite, useContractRead, erc20ABI,erc721ABI,erc4626ABI, Address, } from 'wagmi'
const index: React.FC = () => {
const accountInfo = useAccount();
let fromAddress:Address = accountInfo?.address as Address;
let toAddress:Address = '0xyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
let contractAddress:Address = '0x47cE7E72334Fe164954D4f9dd95f3D20A26e8e2b'
const abi = erc20ABI
function balanceOf(address:Address){
const balance = useContractRead({
address: contractAddress,
abi,
chainId: 80001, //polygon mumbai测试网
functionName: 'balanceOf',
args: [address],
onSuccess(data) {
console.log(address, data)
},
})
}
balanceOf(fromAddress)
balanceOf(toAddress)
const {write} = useContractWrite({
address: contractAddress,
abi,
chainId: 80001,
functionName: 'transfer',
args: [toAddress, BigInt(0.1 * 10**18)],
onSuccess(data) {
console.log('转成成功', data)
},
})
return (
<Layout>
<Row>
<w3m-button />
</Row>
<Row>
<Button disabled={!write} onClick={() => write?.()}>转账</Button>
</Row>
</Layout>
);
};
export default index;
调用write方法以后,会消耗gas:
方法调用成功以后,会调用传参的onSuccess方法
useContractEvent是监听某个合约的某个事件
useContractEvent({
chainId: 1, //链ID
address: '0x64Bc2cA1Be492bE7185FAA2c8835d9b824c8a194', //合约地址
abi: erc20ABI, //合约ABI
eventName: 'Transfer', //事件名称
listener(log) { //监听回调,监听事件以后,会调用这个方法
console.log(log)
},
})
listener返回值如下:
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!