I have deployed a simple ERC20 smart contract from open zeppelin in my local blockchain, and I am trying to fetch the balance of account when a user makes a get request to my server with the account address.
Using the account address given by the user, I am trying to get the balance of the account and send it back to the user.
TOKEN SMART CONTRACT IS BELOW:
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
contract TestToken is ERC20, Ownable, ERC20Permit {
constructor(address initialOwner)
ERC20("TestToken", "TTK")
Ownable(initialOwner)
ERC20Permit("TestToken")
{}
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
function getBalance(address account) public view returns(uint256){
return(balanceOf(account));
}
}
SERVER SIDE CODE IS BELOW:
const express = require('express');
const hre = require('hardhat');
var bodyParser = require('body-parser')
const app = express();
const port = 3000;
const contadd = '0x5FbDB2315678afecb367f032d93F642f64180aa3';
async function loadcontract(address){
const [signer] = await hre.ethers.getSigners();
const testToken = await hre.ethers.getContractAt('TestToken',contadd,signer);
const transaction = await testToken.getBalance(address);
const data = Promise.resolve(transaction);
return data
}
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", async (req,res)=>{
console.log(req.body);
const address = req.body.address;
const balance = await loadcontract(address);
res.send(balance);
});
app.listen(port,()=>{
console.log(`Server is running on ${port}`);
});
ERROR I AM FACING: When I try to fetch the contract, I am getting the below error.
MY DEPLOY SCRIPT:
let TestToken;
async function main () {
// We get the contract to deploy
const [Deployer] = await hre.ethers.getSigners();
console.log("Deploying contracts with the account:", Deployer.address);
const DeployerAdd = await Deployer.getAddress();
TestToken = await hre.ethers.deployContract("TestToken",[DeployerAdd]);
console.log('TestToken deployed to:', TestToken.address);
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
I tried debugging this, and seems like the fetching the token balance using the "getBalance" function is causing the issue, but not sure why.
THINGS I HAVE TRIED:
- I made sure the contract is already deployed and I am able to get the contract instance.
- Tried to fetch the balance in my deploy script and it seems to work there, i get a response as big number.
Please let me know if any other information is needed.