wallet_watchAsset
请求 UKey Wallet 将某个代币加入用户的钱包资产列表。调用后钱包会展示确认界面,由用户决定是否添加。
入参
参数为一个对象:
| 字段 | 类别 | 必填 | 说明 |
|---|---|---|---|
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.$ukey.ethereum.request({
method: "wallet_watchAsset",
requestParams: {
type: "ERC20",
options: {
address: "0x2b4d6f8091a3c5e7f9b1d3f507192b4d6f8091a3",
symbol: "TOKA",
decimals: 6,
image: "https://cryptologos.cc/logos/usd-coin-usdc-logo.png",
},
},
});
if (wasAdded) {
console.log("代币已经加入钱包");
} else {
console.log("用户拒绝了添加代币");
}
添加多个代币
const tokens = [
{
address: "0x2b4d6f8091a3c5e7f9b1d3f507192b4d6f8091a3",
symbol: "TOKA",
decimals: 6,
},
{
address: "0x4b6d8f0123456789abcdef0123456789abcdef01",
symbol: "TOKB",
decimals: 6,
},
{
address: "0xc4d2e1f0a9876543210fedcba9876543210abcde",
symbol: "TOKC",
decimals: 18,
},
];
async function registerTokenBatch(tokenList) {
for (const token of tokenList) {
try {
await window.$ukey.ethereum.request({
method: "wallet_watchAsset",
requestParams: {
type: "ERC20",
options: token,
},
});
} catch (error) {
console.error(`加入 ${token.symbol} 失败:`, error);
}
}
}
按当前网络添加项目代币
async function requestTokenTracking() {
const chainId = await window.$ukey.ethereum.request({
method: "eth_chainId",
});
// 不同网络下对应的代币地址
const tokenAddresses = {
"0x1": "0x2b4d6f8091a3c5e7f9b1d3f507192b4d6f8091a3",
"0x89": "0x4b6d8f0123456789abcdef0123456789abcdef01",
"0xa4b1": "0xc4d2e1f0a9876543210fedcba9876543210abcde",
};
const address = tokenAddresses[chainId];
if (!address) {
throw new Error("此网络上没有该代币");
}
return window.$ukey.ethereum.request({
method: "wallet_watchAsset",
requestParams: {
type: "ERC20",
options: {
address,
symbol: "TOKEN",
decimals: 18,
image: "https://demo.example/token-logo.png",
},
},
});
}
错误码
| 错误码 | 消息 | 说明 |
|---|---|---|
| 4001 | 用户取消了本次请求 | 用户取消了添加代币确认 |
| -32602 | Invalid params | 代币参数无效 |
说明
- 目前仅支持
ERC20类型。 - 添加前请根据当前
eth_chainId选择正确的代币合约地址。 - 钱包可能已经跟踪该代币,此时仍可能返回
true。 - 图片 URL 应使用 HTTPS,并确保可被用户环境访问。
- 代币符号、精度和链上信息应保持一致,避免用户误认资产。
- 遵循 EIP-747 规范。