web3对接锦囊-2-添加代币

269 阅读1分钟

初始化钱包

喜欢哪个装哪个,我呢,一直用的都是OKX,所以这里也是推荐下哈OKX

项目

先说下本小节涉及的内容主要是如何向已有的钱包中添加自定义的代币(据我所知,大部分百倍币、千倍币都是小种,这些小种的币没上交易所的时候,也就是有较大潜力的,不过对于我们想去了解的人有很大的门槛,地一个问题就是这个代币我应该如何添加,所以本小节先演示下如何通过代码的形式去做这个事情)

初始化项目

越简单越好了啊,这次代码检查插件、路由插件啊我们都不要了~

mkdir s2 && cd s2
vue init webpack .

核心代码块

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button @click="addCoin">新增代币</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    async addCoin () {
    // 添加一个自定义代币的基础参数
      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);
}
    }
  }
}
</script>