先贴代码:
import Web3 from 'web3';
import fs from 'fs'
import Tx from 'ethereumjs-tx'
var myAddress = "*************************";
var destAddress = "*****************";
var contractAddress = "*********************";
var agentAPIKEY = "************************"
var transferAmount = 10000 * 10 ** 18;
const web3 = new Web3("https://rpc-mumbai.maticvigil.com")
web3.eth.defaultAccount = myAddress
web3.eth.getChainId((err, chainid) => {
if (err != null) {
console.log('区块链ID:' + chainid + ' 错误信息:' + err)
return
}
var abiArray = JSON.parse(fs.readFileSync('../json/erc20.json', 'utf-8'));
const Contract = new web3.eth.Contract(
abiArray,
contractAddress,
{
from: myAddress,
})
const encodedABI = Contract.methods.transfer(destAddress, BigInt(transferAmount)).encodeABI()
web3.eth.getTransactionCount(myAddress, 'pending', (error, txCount) => {
if (!error) {
const txObject = {
chainId: web3.utils.toHex(chainid),
nonce: web3.utils.toHex(txCount),
from: myAddress,
to: contractAddress,
value: "0x00",
gasLimit: web3.utils.toHex(210000),
gasPrice: web3.utils.toHex(8),
data: encodedABI
}
console.log('txObject = ', txObject)
const tx = new Tx.Transaction(txObject)
const privateKey = Buffer.from(agentAPIKEY, "hex")
tx.sign(privateKey)
const serializedTx = tx.serialize()
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), (err, txHash) => {
if (err) console.error('错误 = ', err)
else console.log('txHash = ', txHash)
})
}
})
})
运行报错:
Error: Returned error: invalid sender
有懂的朋友还望不吝赐教,谢谢。