0%

eth | web3.js 转账 erc20 代币

这里是转账在主网上发的类 erc20 代币。

以虎符智能链为例。


环境


  • ethereumjs-tx: ^1.3.7
  • web3: ^1.3.6

方法一


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import Web3 from "web3"
import Tx from "ethereumjs-tx"
import Abi_Decoder from "abi-decoder"

let w3 = new Web3(new Web3.providers.HttpProvider("https://http-mainnet.hoosmartchain.com"));
let contractAddr = "0x09e6030537f0582d51C00bdC2d590031d9b1c86c";
let tokenContractABI = [
{
"constant": true,
"inputs": [{"name": "who", "type": "address"}],
"name": "balanceOf",
"outputs": [{"name": "", "type": "uint256"}],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false, "inputs": [{"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"}],
"name": "transfer", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"
}]
let tokenContract = new w3.eth.Contract(tokenContractABI, contractAddr);

const send_hoo = () => {
tokenContract.methods.balanceOf("0x046DFD38e4eeB06073782e3DADFB8e56cAC360cE").call().then((balance) => {
console.log(balance);

w3.eth.getTransactionCount("0x046DFD38e4eeB06073782e3DADFB8e56cAC360cE", ((error, count) => {
if (error) {
return
}
console.log(count);

let rawTx = {
from: '0x046DFD38e4eeB06073782e3DADFB8e56cAC360cE',
to: '0x09e6030537f0582d51C00bdC2d590031d9b1c86c',
value: w3.utils.toHex(w3.utils.toWei('0', 'ether')),
nonce: w3.utils.toHex(count),
gasLimit: w3.utils.toHex(8000000),
gasPrice: w3.utils.toHex(w3.utils.toWei('1', 'gwei')),
data: tokenContract.methods.transfer("0x26b1724D9F6CA5DEe5DAA308f197dF7eafe4EB93", w3.utils.toHex(w3.utils.toWei('10', 'ether'))).encodeABI()
}

console.log(rawTx)

let tx = new Tx(rawTx);
tx.sign(new Buffer('985f728fccaf62a98b44d***私钥', 'hex'));
let serializedTx = tx.serialize();
let raw = '0x' + serializedTx.toString('hex')
w3.eth.sendSignedTransaction(raw, (err, txHash) => {
console.log('txHash:', txHash)
console.log(err)
})
}))
})
}

send_hoo();

该方法和主网币转账比起来,主要是多了

data: tokenContract.methods.transfer("0x26b1724D9F6CA5DEe5DAA308f197dF7eafe4EB93", w3.utils.toHex(w3.utils.toWei('10', 'ether'))).encodeABI()
请我喝杯咖啡吧~