Search code examples
ethereumblockchainsoliditysmartcontractsremix

Transfer ether from account A to contract and then contract to account B


I am trying to write a code that:

  1. Send 10000000000000000 wei (0.01 ether) from metamask accountA to a smart contract
  2. Send ether from smart contract to accountB

I have written the code bellow and deployed via metamask. The amount 0.01 goes in the smart contract and I can check the balance is correct.


contract ONE {

    address payable public  owner;

    constructor()  payable   {
        owner=payable(msg.sender);
    }

    receive () external payable {}

function sendViaCall(address payable _to ) payable external  {

        (bool sent, ) = _to.call{value: msg.value}("");
        require(sent, "Failed to send Ether");
        
    }

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

However when I try to send ether from the contract to an accountB, this is not working.

I write the address on the box bellow and call the function on metamask, but it is not sending ether to Account B.

enter image description here

what I am doing wrong ?

Appreciate any help.


Solution

  • Your code is running and not throwing error because msg.value is 0. every time you call sendViaCall, you are sending a 0 amount.

    If you want to send msg.value alongside the function call on Remix, Remix does not have this functionality (Or maybe I could not figure out). In front end setup, when we call a contract function, we pass the last argument to the function {value:amountToSend} and this was received as msg.value inside the contract function.

    If you want to test sending balance, you could use address(this).balance

    function sendViaCall(address payable _to ) external payable  {
        (bool sent, ) = _to.call{value: address(this).balance}("");
        require(sent, "Failed to send Ether");
    }