how to make contract fetch ether from an account

287 views Asked by At

I am new to solidity. I was playing around and wanted to know if I could make a contract fetch ether from one account and transfer it to another account. Thank You

2

There are 2 answers

2
Shane Fontaine On BEST ANSWER

The short answer is that you cannot use a contract to fetch ether from another address. If some form of this was possible, it would be hard to prevent malicious actors from doing this to everybody.

The longer answer is that in Solidity, it is more favorable to pull transactions rather than to push them. Keeping this in mind, you should not attempt to fetch ether from an account, but rather you should design the contract in such a way that the account involved would pull their allocation out of the contract. You can do one of two things:

  1. User1 sends the ether into a contract that automatically forwards the funds to User2 (though I'm not sure why you would use a contract in that case).
  2. User1 sends funds to the contract and have User2 retrieve the funds in a second transaction.

Both of these work, but you cannot have the contract fetch ether from the first user automatically.

There are ways where this is seemingly possible, but it is done with a pre-signed transaction from User1, which is most likely what you are not trying to achieve.

0
Raghav Sood On

Unless the account you are retrieving the ether from is also a contract and provides a method allowing ether withdrawal, this is not possible. A contract cannot autonomously retrieve ether from a externally owned account.

An alternative is to move your ether to the Wrapped Ether (WETH) contract, which provides you an ether-backed ERC20 token instead, which then gives you access to approve() and transferFrom()