0

I have a contract in which, I want to withdraw my ethers using a function. It works fine in remix, but in web3 It does not work and throws VM Exception while processing transaction: invalid opcode","code":-32000 note that, I have enough ether in my contract

my contract(sol v.8) code is :

pragma solidity ^0.8.0;

contract TestEther {

address payable wallet;

fallback() external {}

constructor(address _wallet) {
                                                                
  wallet = payable(_wallet);                                   
}

function sendEther() public payable {
    
}  

function withdraw(uint _amount) public {

    require(_amount <= address(this).balance, "not enough");
    payable(wallet).transfer(_amount);
 }
}

web 3 code using react (removed the extra codes here):

sendEther = (amount) => {
this.state.ether.methods.sendEther().send({ from: accounts[0], value: 
amount }).on('transactionHash', (hash) => {
 })
}

withdraw = (amount) => {
this.state.ether.methods.withdraw(amount).send({from: 
accounts[0]}).on('transactionHash', (hash) => {
 })
}

The Send ether method works fine, but the withdraw doesn't work with Web3 (works fine in Remix)

I use the same way in web3 to withdraw erc20 tokens like this, and it works fine. But it cant withdraw ether.

2
  • What do you mean, withdraw ether ? What is the contract code ? – Florian Castelain Jan 18 at 16:02
  • @ Florian Castelian It is in the question. look at the withdraw function – Amin Jan 19 at 5:52
0

Some how, this works fine in test networks like Rinkeby I used ganache in remix and it still fails.

I think the problem is ganache, I don't know how to fix it. But for some reasons ganache doesn't support this line code:

anyAddress.transfer(amount);

maybe some one can find the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.