本页目录
wallet_watchAsset
请求钱包跟踪新代币。这会提示用户将指定的代币添加到钱包的代币列表中。
参数
object 包含:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
type | string | 是 | 代币类型;本页演示 ERC20 |
options | object | 是 | 代币详情 |
options.address | string | 是 | 代币合约地址 |
options.symbol | string | 是 | 代币代码,1–11 个字符 |
options.decimals | number | 是 | 代币精度 |
options.image | string | 否 | 代币图标 URL |
返回值
boolean - 如果添加成功返回 true,否则返回 false
示例
const wasAdded = await window.$onekey.ethereum.request({
method: 'wallet_watchAsset',
params: {
type: 'ERC20',
options: {
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
symbol: 'USDC',
decimals: 6,
image: 'https://cryptologos.cc/logos/usd-coin-usdc-logo.png'
}
}
})
if (wasAdded) {
console.log('Token added to wallet')
} else {
console.log('User declined to add token')
}添加多个代币
const tokens = [
{
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
symbol: 'USDC',
decimals: 6
},
{
address: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
symbol: 'USDT',
decimals: 6
},
{
address: '<TOKEN_CONTRACT_ADDRESS>',
symbol: 'DAI',
decimals: 18
}
]
async function addTokens(tokenList) {
for (const token of tokenList) {
try {
await window.$onekey.ethereum.request({
method: 'wallet_watchAsset',
params: {
type: 'ERC20',
options: token
}
})
} catch (error) {
console.error(`Failed to add ${token.symbol}:`, error)
}
}
}添加自定义项目代币
async function suggestToken() {
const chainId = await window.$onekey.ethereum.request({
method: 'eth_chainId'
})
// Different addresses per network
const tokenAddresses = {
'0x1': '0x...MainnetAddress',
'0x89': '0x...PolygonAddress',
'0xa4b1': '0x...ArbitrumAddress'
}
const address = tokenAddresses[chainId]
if (!address) {
throw new Error('Token not available on this network')
}
return window.$onekey.ethereum.request({
method: 'wallet_watchAsset',
params: {
type: 'ERC20',
options: {
address,
symbol: 'TOKEN',
decimals: 18,
image: 'https://example.com/token-logo.png'
}
}
})
}错误码
| 错误码 | 消息 | 说明 |
|---|---|---|
| 4001 | User rejected the request | 用户拒绝添加代币 |
| -32602 | Invalid params | 代币参数无效 |
说明
- 本页介绍
ERC20;其他类型需在目标钱包版本中验证。 - 钱包可能已显示该代币,此时仍可返回
true。 - 图标应使用可访问的 HTTPS URL。
- 代币代码应与链上信息一致,方便用户辨认。
- 规范见 EIP-747 。
最后更新于