Send Crypto Coin or Token with NodeJS Web3
April 05, 2022
Send Crypto Coin or Token with NodeJS Web3
Installation
Node.js
npm install web3
npm i dotenv
Index.js
const dotenv = require('dotenv');
dotenv.config();
const Web3 = require('web3')
const privateKey = process.env.YOUR_PRIVATE_KEY;
const provider =process.env.PROVIDER;
const Web3js = new Web3(new Web3.providers.HttpProvider(provider));
const tokenAddress = ""; // Token contract address
let SendIngAmount='1'; //SENDING
let toAddress = ''; // where to send it
let fromAddress = ''; // your wallet
let contractABI = [
// transfer
{
'constant': false,
'inputs': [
{
'name': '_to',
'type': 'address'
},
{
'name': '_value',
'type': 'uint256'
}
],
'name': 'transfer',
'outputs': [
{
'name': '',
'type': 'bool'
}
],
'type': 'function'
}
]
let contract = new Web3js.eth.Contract(contractABI, tokenAddress, { from: fromAddress })
let amount = Web3js.utils.toHex(Web3js.utils.toWei(SendIngAmount)); //1 DEMO Token
let data = contract.methods.transfer(toAddress, amount).encodeABI()
const SendToken=()=> {
let txObj = {
gas: Web3js.utils.toHex(100000),
"to": tokenAddress,
"value": "0x00",
"data": data,
"from": fromAddress
}
Web3js.eth.accounts.signTransaction(txObj, privateKey, (err, signedTx) => {
if (err) {
console.info(err)
return err
} else {
console.log(signedTx)
return Web3js.eth.sendSignedTransaction(signedTx.rawTransaction, (err, res) => {
if (err) {
console.log(err)
} else {
console.log(res)
}
})
}
})
}
SendToken();