メインコンテンツへスキップ

ethers.jsを使用したトークンの送金

ETHERS.JS
ERC-20
トークン
初級
キム・ヨンジュン
2021年4月6日
3 分で読めます

ethers.js(5.0)を使用したトークンの送金

このチュートリアルで学べること

  • ethers.jsのインポート
  • トークンの送金
  • ネットワークのトラフィック状況に応じたガス価格の設定

はじめに

まず、JavaScriptにethers.jsライブラリをインポートする必要があります。 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: トランザクションに署名し、実際にトークンを送金するための送信者の秘密鍵

注意

sendTransaction() が内部で処理を行うため、signTransaction(tx) は削除されています。

送金手順

1. ネットワーク (テストネット) への接続

プロバイダの設定 (Infura)

ロプステンテストネットへの接続

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() // ガス価格

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 finished!")
})

使用方法

成功!

image of transaction done successfully

send_token()