Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save falcon11/4fc2e21ad8eae3060851aacaf36f9a8b to your computer and use it in GitHub Desktop.
Save falcon11/4fc2e21ad8eae3060851aacaf36f9a8b to your computer and use it in GitHub Desktop.
usdt(erc20) transfer demo
// Created by Chih.Lun.Kang
// 網路上找的範例大部分都不能用,後來嘗試數次只有這方法可行
// 主網的appid => 539ab33xxxx,要去Infura申請,在上面建立一個project
// #### NOTE #### : 要特別注意本身轉帳的帳號要儲備足夠數量的 eth 跟 btc
// #### 注意 #### : 目前使用人工轉換儲值手續費,建議在幣價好的時候一次換匯才划算
const USDTJSON = require('./build/contracts/USDT.json')
const Web3 = require('web3')
const Tx = require('ethereumjs-tx').Transaction
const rpcEndpoint = `https://mainnet.infura.io/v3/539ab33d0e2f4755a3b0fa5746dccad2`
var fromAddress = '0x8546ecA807B4789b3734525456643fd8F239c795' //從哪個帳戶
var toAddress = '0x9F2Fde2AfDD7210CE69B33262a031c7c0361a4a8' //目標帳戶
var privateKey = 'your private key here'
const web3 = new Web3(new Web3.providers.HttpProvider(rpcEndpoint))
// USDT contract 連結 https://etherscan.io/address/0xdac17f958d2ee523a2206206994597c13d831ec7#code
const ContractAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7';
const USDT = new web3.eth.Contract(USDTJSON.abi, ContractAddress,{from: fromAddress})
let amount = web3.utils.toHex(2710)
async function main() {
web3.eth.getTransactionCount(fromAddress)
.then((count) => {
let rawTransaction = {
'from': fromAddress,
'gasPrice': web3.utils.toHex(20 * 1e9),
'gasLimit': web3.utils.toHex(210000),
'to': ContractAddress,
'value': 0x0,
'data': USDT.methods.transfer(toAddress, amount).encodeABI(),
'nonce': web3.utils.toHex(count)
}
let transaction = new Tx(rawTransaction)
transaction.sign(Buffer.from(privateKey, 'hex'))
web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
.on('transactionHash', console.log)
})
}
main().then(() => {
}).catch((e) => {
console.log("error", e);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment