I for the life of me cannot figure out how to simply call a function from a smart contract when a button is pressed on the front end. I have been reading over the docs and watching countless tutorials over the past week and still cannot figure out how to call a transaction.
It's merely a simple buyToken function, but I think the problem has something to do with the signer because when I console.log signer
it returns null. Everything works fine when I comment out the contract call, but as soon I call it I get a nasty error: "Error: Transaction reverted without a reason string"
Heres the smart contract function
function buyToken() public payable {
uint buyAmount = msg.value * rate;
require (bartoken.balanceOf(address(this)) >= buyAmount, 'Insufficient balance');
bartoken.transfer(msg.sender, buyAmount);
emit TokenBought(msg.sender, address(bartoken), buyAmount);
}
And here's the Front-end (Reactjs & ethersjs)
async function buyTokens(e) {
e.preventDefault();
if (typeof window.ethereum !== 'undefined'){
const provider = new ethers.providers.Web3Provider(window.ethereum);
const account = await window.ethereum.request({ method: 'eth_requestAccounts' })
const signer = provider.getSigner();
const exchange = new ethers.Contract('CONTRACT_ADDRESS', abi, signer);
}
}
bartoken
inbartoken.balanceOf....
? Assuming you are replacing 'CONTRACT_ADDRESS' with a proper address, you'll also need to call the function with an amount, i.e. the msg.value. Something like:await exchange.buyToken({ value: ethers.utils.parseEther(_eth) })