Skip to content
Advertisement

How to make Node.JS function that calls solidity withdraw function?

I can’t get JS properly to call my solidity function withdraw funds. I have got solidity:

function withdrawFunds() public {
    require(msg.sender == owner, "You are not the owner");
    (bool success, ) = payable(owner).call {
        value: address(this).balance
    }("");
    require(success);
}

And it works, but I cant figure out how to properly call it in JS.

So far I have this in JS:

const withdrawFunds = async () => {
    try {
        await Contractoftickets.methods.withdrawFunds().call({
            from: address,
        })
        setSuccessMsg(`Funds withdrawn!`)
    }
}

It executes but it currently does not withdraw funds.

Advertisement

Answer

With ethers.js you can do it like this:

const withdrawFunds = async () => {
   try {
      const Contractoftickets = ethers.getContract(contractAddress, contractInterfaceOrABI)
      await Contractoftickets.withdrawFunds()
      setSuccessMsg(`Funds withdrawn!`)
  }
}

I’ll recommend you to go through ethers docs for more details. A simple note, you’ve to install ethers and connect your wallet with it before using it like above.

Advertisement