跳转到主要内容

使用 ethers.js 发送代币

ETHERS.JS
ERC-20
代币
初级
金容俊
2021年4月6日
3 分钟阅读

使用 ethers.js (5.0) 发送代币

在本教程中,你将学习如何

  • 导入 ethers.js
  • 转账代币
  • 根据网络拥堵情况设置 Gas 价格

准备工作

首先,我们必须将 ethers.js 库导入到我们的 JavaScript 中 引入 ethers.js (5.0)

安装

/home/ricmoo> npm install --save ethers

浏览器中的 ES6

<script type="module">
  import { ethers } from "https://cdn.ethers.io/lib/ethers-5.0.esm.min.js"
  // 在此处编写您的代码...
</script>

浏览器中的 ES3 (UMD)

<script
  src="https://cdn.ethers.io/lib/ethers-5.0.umd.min.js"
  type="application/javascript"
></script>

参数

  1. contract_address:代币合约地址(当你要转账的代币不是以太币时,需要合约地址)
  2. send_token_amount:你要发送给接收者的金额
  3. to_address:接收者的地址
  4. send_account:发送者的地址
  5. private_key:发送者的私钥,用于签署交易并实际转账代币

注意

移除了 signTransaction(tx),因为 sendTransaction() 会在内部执行此操作。

发送步骤

1. 连接到网络(测试网)

设置提供者 (Infura)

连接到 Ropsten 测试网

window.ethersProvider = new ethers.providers.InfuraProvider("ropsten")

2. 创建钱包

let wallet = new ethers.Wallet(private_key)

3. 将钱包连接到网络

let walletSigner = wallet.connect(window.ethersProvider)

4. 获取当前 Gas 价格

window.ethersProvider.getGasPrice() // Gas 价格

5. 定义交易

下面定义的这些变量依赖于 send_token()

交易参数

  1. send_account:代币发送者的地址
  2. to_address:代币接收者的地址
  3. send_token_amount:要发送的代币数量
  4. gas_limit:gas 上限
  5. gas_price:Gas 价格

有关如何使用,请参见下文

const tx = {
  from: send_account,
  to: to_address,
  value: ethers.utils.parseEther(send_token_amount),
  nonce: window.ethersProvider.getTransactionCount(send_account, "latest"),
  gasLimit: ethers.utils.hexlify(gas_limit), // 100000
  gasPrice: gas_price,
}

6. 转账

walletSigner.sendTransaction(tx).then((transaction) => {
  console.dir(transaction)
  alert("Send finished!")
})

如何使用

成功!

image of transaction done successfully

send_token()