0
 pragma solidity >=0.7.0 <0.9.0;

 contract StructMapping {

    mapping(address => uint) public balanceReceived;

    function getBalance() public view returns(uint) {
        return address(this).balance;
    }  

    function sendMoney() public payable {
        balanceReceived[msg.sender] += msg.value;
    }

    function withdrawAllMoney(address payable _to) public {
        uint balanceToSend = balanceReceived[msg.sender];
        balanceReceived[msg.sender] = 0;
        _to.transfer(balanceToSend);
    }

}

requirements: remix web ide, solidity file with above code opened in remix, two metamask wallets

steps to reproduce:

  1. save file and open through remix
  2. injected web3 (connect metamask wallet A)
  3. deploy contract
  4. send from wallet A to the deployed contract using remix interactive feature
  5. copy address of the contract and send from metamask wallet B

When I try to perform step 5 the transaction in my metamask from wallet b which is on a different machine fails says not enough gas. How can I send from this remote wallet and have it interact with the contract, im assuming it is just sending it like its a wallet address and timesout.

1 Answer 1

0

When you send money to a smart contract, you'll have to call a payable function. It's not possible directly via Metamask, as Metamask merely sends a transaction without any data unless specifically requested to do so via its API. To send send money, you can change your Metamask to wallet B and call sendMoney() function of the contract along with some ETH.

If you want your smart contract to accept money without being called via specific function, you can define a receive function like this.

receive() external payable {
    sendMoney();
}

This tells the contract to accept payment (those sent as normal transactions as you mentioned). This is a security feature of solidity to safeguard accidental sending of ETH to smart contracts which might not have a withdrawal mechanism.

4
  • thank you that was what I was missing Commented Jan 16, 2022 at 14:19
  • also if you see this I am not able to transfer out, when I send from that external address not connected to the contract currently I then cant withdraw out to external wallets. Is there another built in function like receive or is there a declaration other than public or external for the withdraw function. Commented Jan 16, 2022 at 16:26
  • withdrawAllMoney should work in just the way you've written. There isn't else that needs to be added.
    – pbsh
    Commented Jan 16, 2022 at 16:57
  • yea you're right messed something up lol Commented Jan 16, 2022 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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