1

I wrote a very simple smart contract. The goal is to:

  1. transfer some Ether from an account A to the smart-contract
  2. and then from the smart-contract to another account B.

Here is the contract:

pragma solidity ^0.8.0;

contract MyContract {

    function fundContract() external payable {

    }

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

    function transferAmount(address payable _recipient) external payable {
        _recipient.transfer(msg.value);
    }

    function callAmount(address payable _recipient) external payable {
        (bool success,  bytes memory data) = _recipient.call{value:msg.value}("");
        require(success, "Transaction Failed!");

    }

}

I was able to achieve to transfer 5 ETH from an account A to the smart contract by using the following commands on the truffle console:

MyContract.deployed().then(function(i) { contract=i;})
contract.fundContract({value: 500000000000000000})
contract.getBalance().then(function(r){result=r;})
parseFloat(result)

However when I try to send 1 ETH from the smart contract to another account B using these line of code:

contract.transferAmount('0x60407B3b7a3acd2dAE922610129433B915A3C238', {value:100000000000000000})

or

contract.callAmount('0x60407B3b7a3acd2dAE922610129433B915A3C238', {value:100000000000000000})

the amount is subtracted from the user's balance (account A) rather than the smart-contract, which appears to have 5 ETH instead of 4 ETH (since I am trying to transfer 1 ETH). What am I doing wrong? Would you be able to suggest a smart and elegant way to achieve this goal (send 1 ETH from the smart-contract balance to account B)?

1 Answer 1

1

When calling transferAmount, you're supplying value, meaning you're sending additional ETH to the contract - which you don't want. transferAmount then continues to send this value to the recipient (using msg.value).

Instead of having transferAmount payable and sending ETH to it, add another parameter to transferAmount: uint _amount. Then this is the amount you should transfer to the recipient.

1

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.