Skip to content

Instantly share code, notes, and snippets.

@itoonx
Created April 22, 2021 12:29
Show Gist options
  • Save itoonx/f9c96c3e03c8e1ecb5eee2c3f2f72380 to your computer and use it in GitHub Desktop.
Save itoonx/f9c96c3e03c8e1ecb5eee2c3f2f72380 to your computer and use it in GitHub Desktop.
const fs = require('fs')
const path = require('path')
const httpStatus = require('http-status')
const EthereumTx = require('ethereumjs-tx')
const etherwallet = require('ethereumjs-wallet')
const { web3, engine } = require('../../config/web3provider')
const getERC20Balance = async (address_without_0x, contractAddress) => {
return new Promise(async (resolve, reject) => {
// '0x70a08231' is the contract 'balanceOf()' ERC20 token function in hex. A zero buffer is required and then we add the previously defined address with tokens
let contractData = ('0x70a08231000000000000000000000000' + address_without_0x)
// Now we call the token contract with the variables from above, response will be a big number string
web3.eth.call({
to: contractAddress, // Contract address, used call the token balance of the address in question
data: contractData // Combination of contractData and tknAddress, required to call the balance of an address
}, (err, result) => {
if (result) {
// Convert the result to a usable number string
var tokens = web3.toBigNumber(result).toString()
resolve(web3.fromWei(tokens, 'ether'))
} else {
reject(err)
}
})
})
}
module.exports = async (req, res) => {
let contract_address = '0x0000000000085d4780B73119b644AE5ecd22b376' // TUSD
let send_to_address_with_0x = '0xFaF30e58A5ba4454E4a323Fe897A2d66E4CBe176'
let token_amount = 0.1
let private_key_buffer = ''
let network_id = 1 // 1 = mainnet, 3 = ropsten
// sender wallet
let wallet = etherwallet.fromPrivateKey(Buffer.from(private_key_buffer, 'hex'))
// sender address
let address = wallet.getAddress().toString('hex')
console.log('Address', address)
// console.log(web3)
let contractAddress = contract_address
// contract ABI
let contractABI = JSON.parse(fs.readFileSync(path.join(__dirname, '../../../../shared/ethereum/abi/StandardERC20.json'), 'utf8'))
// create contract instance
let contract = new web3.eth.contract(contractABI).at(contractAddress)
// sender balance
let senderBalance = await getERC20Balance(address, contractAddress)
// get balance of sender and send rest of balance
// var weiAmount
// if (send_all === 'all') {
// weiAmount = senderBalance
// } else {
// }
let weiAmount = parseInt(web3.toWei(token_amount, 'ether'))
// validate address
let isAddress = web3.isAddress(send_to_address_with_0x)
if (!isAddress) {
return res.status(httpStatus.BAD_REQUEST).json({
msg: 'Invalid address'
})
}
// validate amount
if (weiAmount < 0 ) {
return res.status(httpStatus.BAD_REQUEST).json({
msg: 'Not enough balance'
})
}
web3.eth.getTransactionCount(`0x${address}`, (err, nonce) => {
const gasLimit = 861947
let gasPrice
if (network_id === 1) {
gasPrice = 6000000000 // 6 GWei
} else if (network_id === 3) {
gasPrice = 410000000000 // 41 GWei
} else {
gasPrice = 21000000000 // 2 GWei by defualt
}
const txParams = {
nonce: web3.toHex( nonce ),
gasPrice: web3.toHex( gasPrice ), // fixed rate 0.00001 ETH
gasLimit: web3.toHex( gasLimit ), // converts the gwei price to wei
"to": contractAddress,
"value": "0x00",
"data": contract.transfer.getData(send_to_address_with_0x, weiAmount, {from: `0x${address}`}),
// EIP 155 chainId - mainnet: 1, ropsten: 3
chainId: network_id
}
const tx = new EthereumTx(txParams)
tx.sign(Buffer.from(private_key_buffer, 'hex'))
const serializedTx = tx.serialize()
/**
* We're ready! Submit the raw transaction details to the provider configured above.
*/
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), (err, hash) => {
if (err) console.log('sendRawTransaction error:', err)
if (hash) {
return res.status(httpStatus.OK).json({
hash
})
}
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment