接入钱包
添加代币

添加代币#

当用户打开欧易 Web3 钱包时,钱包上会显示各种包括代币的资产。默认情况下,欧易 Web3 钱包会自动检测一些主流的代币并自动显示该代币,但是其他大多数的代币需要用户自行添加。

虽然使用界面上的”添加代币“按钮也能达到此效果,但过程较为繁琐,而且由于涉及到用户与合约地址的互动,成本和出错概率都会增加。 相反,使用 EIP-747 中定义的 wallet_watchAsset API 可以改善用户添加代币时的体验,同时增加安全性。

例子#

如果您想把推荐代币功能添加到自己的网络应用中,可以参考以下代码:

const tokenAddress = '0xd00981105e61274c8a5cd5a88fe7e037d935b513';
const tokenSymbol = 'TUT';
const tokenDecimals = 18;
const tokenImage = 'http://placekitten.com/200/300';
try {
  // wasAdded is a boolean. Like any RPC method, an error may be thrown.
  const wasAdded = await okxwallet.request({
    method: 'wallet_watchAsset',
    params: {
      type: 'ERC20', // Initially only supports ERC20, but eventually more!
      options: {
        address: tokenAddress, // The address that the token is at.
        symbol: tokenSymbol, // A ticker symbol or shorthand, up to 5 chars.
        decimals: tokenDecimals, // The number of decimals in the token
        image: tokenImage, // A string url of the token logo
      },
    },
  });

  if (wasAdded) {
    console.log('Thanks for your interest!');
  } else {
    console.log('Your loss!');
  }
} catch (error) {
  console.log(error);
}

下面列举了实时的网络应用案例,您输入代币细节后,即可通过一个简单的链接来分享该信息。