Search code examples
blockchainethereumsoliditysmartcontracts

How to transfer eth from an account to a contract?


I'm fresh on solidity, when I use remix to test my contract, I want to transfer some eth from my account to the smart contract. I have tried this code, but it seems to transfer the eth from the contract but not my account.

    function addStaker (uint _stakeAmount) public membership(master, msg.sender) returns(bool) {
    if(!members[msg.sender].alreadyExist) {
        Member memory newMember = Member(msg.sender, true);
        members[msg.sender] = newMember;
        bool sent = payable(address(this)).send(_stakeAmount);
        require(sent, "invalid balance");
        return true;
    } else {
        return false;
    }
}

How could I transfer eth from my account to the smart contract?


Solution

  • A smart contract is not able to pull a contract-specified amount of ETH from an address. The amount needs to always be specified and signed by the sender.

    The contract can only validate the sent amount:

    function addStaker() public payable {
        require(msg.value == 1 ether);
    }
    

    How to chose the amount depends on the wallet software you're using. In case of Remix, there's the "Value" input in the "Deploy & Run Transactions" tab, where you specify the amount of ETH sent with the transaction.