跳转到主要内容

使用 ethers.js 发送代币

ETHERS.JS
ERC-20
代币
初学者
Kim YongJun
2021年4月6日
3 分钟阅读

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

在本教程中,你将学习如何:{#you-learn-about}

  • 导入 ethers.js
  • 转账代币
  • 根据网络流量情况设置燃料价格

开始上手

开始前,我们必须先将 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. 获取当前燃料价格

window.ethersProvider.getGasPrice() // gasPrice

5. 定义交易

下面定义的变量取决于 send_token()

交易参数

  1. send_account:代币发送方的地址
  2. to_address:代币接收方的地址
  3. send_token_amount:要发送的代币数量
  4. gas_limit:燃料限制
  5. gas_price:燃料价格

请参阅下文了解如何使用

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_token()

页面最后更新: 2026年3月3日

这篇教程对您有帮助吗?