How to transfer eth from an account to a contract?

Viewed 3504

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?

2 Answers

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.

If you want to implement a defi contract (since your function name is addStaker) that accepts staked coins from ERC20 tokens, the implementation is different. But if you just want to send money to contract from your metamask account, you have to mark the function payable.

 function pay() public payable {
            //  msg.value is the amount of wei sent with the message to the contract. 
            // with this you are setting a minimum amount
            require(msg.value > .01 ether);
            // add your logic
    }
Related