Skip to content

Instantly share code, notes, and snippets.

@sanjukurian
Last active August 8, 2022 12:51
Show Gist options
  • Save sanjukurian/2122882b1297cc410a92b025a4d5664c to your computer and use it in GitHub Desktop.
Save sanjukurian/2122882b1297cc410a92b025a4d5664c to your computer and use it in GitHub Desktop.
View balance, make a transaction and see transaction details of erc20 tokens(TUSD in the code) and connected via infura
const config = require("../../config/config");
import path from 'path'
import Web3 from 'Web3'
import fs from 'fs'
const web3 = new Web3(`https://rinkeby.infura.io/v3/` + config.infura_api_key);
const getWallet = async (walletId) => {
try {
var abiArray = JSON.parse(fs.readFileSync(path.resolve(__dirname, './tusdABI.json'), 'utf-8'));
var contractAddress = "0x0000000000085d4780B73119b644AE5ecd22b376";
var contract = new web3.eth.Contract(abiArray, contractAddress, {from: walletId});
contract.methods.balanceOf(walletId).call((err, balance) => {
if (err)
throw {success: false, error: {message: "Unable to fetch Balance", stack: err}};
else
return {
success: true,
data: {balance: web3.utils.fromWei(balance, 'ether'), address: walletId}
};
});
} catch (ex) {
console.log(ex);
return ex;
}
};
const send = async (address, receiver, amount, my_privkey) => {
try {
web3.eth.getTransactionCount(address, (err, count) => {
if(err)
throw {success: false, error: {message: "Unable to transfer", stack: err}};
else {
var rawTransaction = {
"from": address,
"nonce": web3.utils.toHex(count),
'gasLimit': web3.utils.toHex(21000),
'gasPrice': web3.utils.toHex(web3.utils.toWei('1','gwei')),
"to": contractAddress,
"value": "0x0",
"data": contract.methods.transfer(receiver, web3.utils.toHex(web3.utils.toWei(amount,'ether'))).encodeABI(),
"chainId": web3.utils.toHex('1')
};
web3.eth.accounts.signTransaction(rawTransaction, my_privkey, (err, signed) => {
if(!err){
web3.eth.sendSignedTransaction(signed.rawTransaction, (err, receipt) => {
if(err)
throw {success: false, error: {message: "Unable to transfer", stack: err}};
else
return {success: true, data: {txn: receipt}};
});
} else throw {success: false, error: {message: "Unable to transfer", stack: err}};
});
}
});
} catch (ex) {
console.log(ex);
return ex;
}
};
const getTxnDetails = async (txn) => {
try {
web3.eth.getTransactionReceipt(txn, (err, reciept) => {
if (!err)
return {success: true, data: {receipt: reciept}};
else throw {success: false, error: {message: "Unable to find transaction", stack: err}}
})
} catch (ex) {
console.log(ex);
return ex;
}
};
@ialirazakhokhar
Copy link

Hey dear Sanju,I am learning that how to get the balance of a token and show it on the webpage but I can't figure out how to do this. Can you help me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment