SENDING TOKENS USING ETHERS.JS


From: https://ethereum.org/fr/developers/tutorials/send-token-etherjs/

Installing
/home/ricmoo> npm install --save ethers

ES6 in the Browser


ES3(UMD) in the Browser

Parameters

  • contract_address: Token contract address (contract address is needed when the token you want to transfer is not ether)
  • send_token_amount: The amount you want to send to the receiver
  • to_address: The receiver’s address
  • send_account: The sender’s address
  • private_key: Private key of the sender to sign the transaction and actually transfer the tokens
  • NOTICE
    signTransaction(tx) is removed because sendTransaction() does it internally.

SENDING PROCEDURES
1. Connect to network (testnet)
Set Provider (Infura)
Connect to Ropsten testnet

window.provider = new InfuraProvider(“ropsten”)

2. Create wallet
let wallet = new ethers.Wallet(private_key)

3. Connect Wallet to net
let walletSigner = wallet.connect(window.ethersProvider)

4. Get current gas price
window.ethersProvider.getGasPrice() // gasPrice

5. Define Transaction
These variables defined below are dependent on send_token()

Transaction parameters

  • send_account: address of the token sender
  • to_address: address of the token receiver
  • send_token_amount: the amount of tokens to send
  • gas_limit: gas limit
  • gas_price: gas price

See below for how to use

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. Transfer
walletSigner.sendTransaction(tx).then((transaction) => {
console.dir(transaction)
alert(“Send finished!”)
})

HOW TO USE IT

let private_key =
  "41559d28e936dc92104ff30691519693fc753ffbee6251a611b9aa1878f12a4d"
let send_token_amount = "1"
let to_address = "0x4c10D2734Fb76D3236E522509181CC3Ba8DE0e80"
let send_address = "0xda27a282B5B6c5229699891CfA6b900A716539E6"
let gas_limit = "0x100000"
let wallet = new ethers.Wallet(private_key)
let walletSigner = wallet.connect(window.ethersProvider)
let contract_address = ""
window.ethersProvider = new ethers.providers.InfuraProvider("ropsten")

send_token(
  contract_address,
  send_token_amount,
  to_address,
  send_address,
  private_key
)

Afficher tout
Success!
image of transaction done successfully

SEND_TOKEN()

function send_token(
  contract_address,
  send_token_amount,
  to_address,
  send_account,
  private_key
) {
  let wallet = new ethers.Wallet(private_key)
  let walletSigner = wallet.connect(window.ethersProvider)

  window.ethersProvider.getGasPrice().then((currentGasPrice) => {
    let gas_price = ethers.utils.hexlify(parseInt(currentGasPrice))
    console.log(`gas_price: ${gas_price}`)

    if (contract_address) {
      // general token send
      let contract = new ethers.Contract(
        contract_address,
        send_abi,
        walletSigner
      )

      // How many tokens?
      let numberOfTokens = ethers.utils.parseUnits(send_token_amount, 18)
      console.log(`numberOfTokens: ${numberOfTokens}`)

      // Send tokens
      contract.transfer(to_address, numberOfTokens).then((transferResult) => {
        console.dir(transferResult)
        alert("sent token")
      })
    } // ether send
    else {
      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,
      }
      console.dir(tx)
      try {
        walletSigner.sendTransaction(tx).then((transaction) => {
          console.dir(transaction)
          alert("Send finished!")
        })
      } catch (error) {
        alert("failed to send!!")
      }
    }
  })
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.