Skip to Content
dApp 接入

eth_call

立即执行消息调用,不会在区块链上创建交易。用于从智能合约读取数据。


参数

索引类型说明
0object交易调用对象
1string区块号或标签(latest、earliest、pending)

交易调用对象

字段类型必填说明
tostring是合约地址
datastring否编码后的函数调用数据
fromstring否发送方地址(提供上下文)
gasstring否Gas 限制(十六进制)
gasPricestring否Gas 价格(十六进制)
valuestring否金额,单位 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())

错误码

错误码消息说明
-32000Execution reverted合约调用回滚
-32602Invalid params调用参数无效

说明

  • 该方法不会产生链上 gas 费用,也不会修改状态。
  • from 地址可选,但可能影响某些合约的执行结果。
  • 根据用途选择区块标签;latest 表示该端点可见的最新区块。
  • 复杂合约交互可使用 ethers.js 或 web3.js。

示例中的代币地址位于 Ethereum 主网。编码 balanceOf 参数前,请确认网络,并替换为完整的 20 字节账户地址。

最后更新于