Web3js

如何在nodejs上通過web3發送erc20令牌

  • April 11, 2021

我的交易順利通過,而他們正在等待數據欄位顯示我正在發送的令牌數量,但是當交易通過時,數據欄位為空。這是我的程式碼:

const abi = My_Contract.abi
const web3 = new Web3('https://rinkeby.infura.io/v3/INFURA_PROJECT_ID')
const gasprice= await web3.eth.getGasPrice()
var count = await web3.eth.getTransactionCount(myAccount)
const token = new web3.eth.Contract(abi, My_Contract.networks[4].address)

var amountInDecimal = 166
const txObject = {
 from: myAccount,
 nonce: "0x" + count.toString(16),
 to: '0x153ed6D60AcaE6E915907233F10663462FF67622',
 gas: 100000,
 value:"0x0",
 data:token.methods.transfer('0x153ed6D60AcaE6E915907233F10663462FF67622', 
 web3.utils.toHex(web3.utils.toWei(amountInDecimal.toString(), "ether"))).encodeABI(),
 gasPrice:gasprice
}
console.log(txObject)
web3.eth.accounts.signTransaction(txObject, privateKey, (err, res) => {
 if (err) {
   console.log('err',err)
 }
 else {
   console.log('res', res)
 }
 const raw = res.rawTransaction
 web3.eth.sendSignedTransaction(raw, (err, txHash) => {
   if (err) {
     console.log(err)
   }
   else {
     console.log("txHash:", txHash)
   }
 })
})

當我通過 truffle 控制台呼叫傳輸函式時,它執行良好。請幫忙,我快死了

問題是您將傳輸消息發送到令牌收件人地址。要從合約執行功能,交易必須以合約地址為目標。

const token = new web3.eth.Contract(abi, My_Contract.networks[4].address)

const txObject = {
 ..
 to: '0x153ed6D60AcaE6E915907233F10663462FF67622',        // <--- Recipient
 ..
}

應該是代幣合約

const token = new web3.eth.Contract(abi, My_Contract.networks[4].address)

const txObject = {
 ..
 to: My_Contract.networks[4].address,                     // <--- Token
 ..
}

引用自:https://ethereum.stackexchange.com/questions/97001