本页目录
发送交易
使用 eth_sendTransaction 请求已连接账户发送交易。钱包会让用户检查并批准。请求成功后返回交易哈希,不代表交易已确认或执行成功。
示例
const provider = window.$onekey?.ethereum;
if (!provider) throw new Error('OneKey Ethereum provider is unavailable.');
const [from] = await provider.request({ method: 'eth_requestAccounts' });
const chainId = await provider.request({ method: 'eth_chainId' });
// Check chainId against your application's intended network before continuing.
const to = '<RECIPIENT_EVM_ADDRESS>'; // Replace with a valid address.
try {
const txHash = await provider.request({
method: 'eth_sendTransaction',
params: [{
from,
to,
value: '0x0',
}],
});
console.log('Submitted transaction:', txHash);
} catch (error) {
console.error(error.code, error.message);
}由用户操作触发此流程,发送前替换收款地址和金额。在同一链查询 eth_getTransactionReceipt,以确认交易是否已被打包及其执行状态;待处理交易尚无回执。
交易参数
| 参数 | 含义 |
|---|---|
from | 已连接且获准发送交易的账户 |
to | 收款地址;仅创建合约时可省略 |
value | 最小单位的原生币金额,以十六进制数量表示;Ethereum 中单位为 wei |
data | 十六进制编码的合约调用数据或创建合约的字节码 |
gas | 可选的 gas 上限;表示 gas 数量,不是 gas 价格 |
gasPrice | 旧版交易的可选每单位 gas 费用 |
maxFeePerGas、maxPriorityFeePerGas | EIP-1559 交易的费用字段;不可与 gasPrice 同时使用 |
nonce | 账户的交易序号;通常由钱包管理 |
金额计算应使用可精确表示整数的方式,转换为 wei 时避免浮点计算。除非应用确有需要,否则让钱包估算手续费。用户可以在钱包中检查或调整交易详情。
网络与账户变化
准备交易前读取 eth_chainId,并按 Provider API 的说明处理 chainChanged 和 accountsChanged。发生变化后,重新构建依赖账户或网络的交易数据。
演示
最后更新于