0

I want to send ether to the function called deposit()

mapping(address => uint256) public balance;


constructor() {

}

function deposit (address _tokenAddress) payable public {
    IERC20(_tokenAddress).transferFrom(msg.sender, address(this), msg.value);
    balance[msg.sender] += msg.value;
}

I'm able to send ERC20 token to this fn, however not sure how to send the ether as well, as the ether doesn't have the address.

Another approach would be to have two different methods, each for ERC20 and ether. However this is not ideal. Any help would be appreciated.

2 Answers 2

1

If you want to send ETH, you should set amount of ether as: msg.value

For doing this just need input amount of ETH in FrontEnd, if you testing your smart contract with Remix, input your amount into VALUE box

1
  • Yes, I'm aware of this. However, it doesn't solve the issue I mentioned. Dec 10, 2022 at 15:30
0

You want to send ETH & ERC20 token in one function, for doing this you need 2 amount:

amount for ERC20 token msg.value for ETH

and set your ERC20 Token by address

I edit your code that you can do this:

mapping(address => uint256) public balance;

constructor() {

}

function deposit (address _tokenAddress, uint256 _amount) payable public {

    // This line transfer your ERC20 token:
    IERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amount);

    // And this line update your balance:
    balance[msg.sender] += msg.value;

    // For transfer ETH, It doesn't need to write code anymore, you just 
    // Need to input amount of ETH as msg.value in frontend, as i say in 
    // Last answer
}

Note that this way you can send ETH into contract, If you want send ETH from contract you need to define payable address like that:

function sendEthFromContract(address payable userAddress) public payable {
}

and set amount as msg.value

I hope that makes sense

1
  • Okay as said before. For me to write tests for this function I will need the eth address which doesn't exists. Dec 12, 2022 at 10:04

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.