Search code examples
ethereumweb3js

unable to withdraw from the contract


I have a very simple contract, and it works on remix. I'm able to deposit (fallback) and withdraw. I want to do it on my webapp with web3js library.

the contract has these functions

fallback() external payable {}

 modifier onlyOwner(address caller) {
        require(caller == _owner, "You are not the owner of the contract");
        _;
    }

function getContractAmount(address caller) public view onlyOwner(caller) returns (uint256){
    return address(this).balance;
}

function withdraw() external {
  address payable to = payable(msg.sender);
  to.transfer(getContractAmount(to));
}

on my webapp I'm able to interact with the other function of my contract, so I imported address contract and ABI as well.

I have this function

contract.methods.withdraw().call().then((res) => {
    console.dir(res)
    $('#info').html(res);
  })
    .catch(revertReason => {
      console.log({ revertReason });
      $('#info').text(revertReason);
    }
 )

But I'm not able to retrieve the amount of my smart contract (yes the smart contract has ether)

with console.dir, I get "u"


Solution

  • The call() method is for read-only calls.

    Since the withdraw() function changes the state, you need to send() a transaction.

    contract.methods.withdraw().send({
        from: senderAddress
    })
    

    Your web3 instance or the node needs to know the private key to the senderAddress Use wallet.add() to add the private key to the web3 instance.