本页目录
eth_call
立即执行消息调用,不会在区块链上创建交易。用于从智能合约读取数据。
参数
| 索引 | 类型 | 说明 |
|---|---|---|
| 0 | object | 交易调用对象 |
| 1 | string | 区块号或标签(latest、earliest、pending) |
交易调用对象
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
to | string | 是 | 合约地址 |
data | string | 否 | 编码后的函数调用数据 |
from | string | 否 | 发送方地址(提供上下文) |
gas | string | 否 | Gas 限制(十六进制) |
gasPrice | string | 否 | Gas 价格(十六进制) |
value | string | 否 | 金额,单位 wei(十六进制) |
返回值
string - 调用的返回数据(十六进制编码)
示例
读取 ERC-20 余额
// balanceOf(address) selector: 0x70a08231
const address = '0xYourAddress...'.slice(2).padStart(64, '0')
const data = '0x70a08231' + address
const balance = await window.$onekey.ethereum.request({
method: 'eth_call',
params: [{
to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
data: data
}, 'latest']
})
console.log('Balance:', BigInt(balance).toString())读取合约名称
// name() selector: 0x06fdde03
const name = await window.$onekey.ethereum.request({
method: 'eth_call',
params: [{
to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
data: '0x06fdde03'
}, 'latest']
})
// Decode the result (ABI encoded string)
// Decode `name` with your ABI library's string decoder.
console.log('ABI-encoded contract name:', name)使用 ethers.js
import { Contract, BrowserProvider } from 'ethers'
const provider = new BrowserProvider(window.$onekey.ethereum)
const contract = new Contract(
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
['function balanceOf(address) view returns (uint256)'],
provider
)
const balance = await contract.balanceOf('0xYourAddress...')
console.log('USDC Balance:', balance.toString())错误码
| 错误码 | 消息 | 说明 |
|---|---|---|
| -32000 | Execution reverted | 合约调用回滚 |
| -32602 | Invalid params | 调用参数无效 |
说明
- 该方法不会产生链上 gas 费用,也不会修改状态。
from地址可选,但可能影响某些合约的执行结果。- 根据用途选择区块标签;
latest表示该端点可见的最新区块。 - 复杂合约交互可使用 ethers.js 或 web3.js。
示例中的代币地址位于 Ethereum 主网。编码 balanceOf 参数前,请确认网络,并替换为完整的 20 字节账户地址。
最后更新于