跳转到内容

读取链上数据

读取链上数据

调用合约 view 函数

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
// 读取 ERC-20 余额
const balance = await client.readContract({
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
abi: erc20Abi,
functionName: 'balanceOf',
args: ['0x...'],
})

监听事件

// 监听 Transfer 事件
const unwatch = client.watchContractEvent({
address: '0x...',
abi,
eventName: 'Transfer',
onLogs: (logs) => console.log(logs),
})
// 停止监听
unwatch()

查询历史日志

const logs = await client.getLogs({
address: '0x...',
event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'),
fromBlock: 19000000n,
toBlock: 'latest',
})

延伸阅读