Subscribe to get access to this video

and the whole library of videos, sample code, and tutorials.

The safer way to send funds from a contract

The safer way to .send funds – Why sending funds can fail

If you send funds to a ‘normal’ address, it won’t fail, it will just accept your funds.

But in Ethereum, your contract can send funds to another contract. And when you send funds to contract, that contract can run logic too. And you can’t tell from the address whether it is going to a normal account or a contract account.

Sometimes the contract receiving your funds will run logic that fails. You need to be prepared for that.

In fact, sometimes the contract receiving your funds is malicious and designed to deliberately fail. We’ll walk through an attack scenario like this in a future video. But for now, know that when you send funds, it might fail, and you need to deal with that.

Withdrawing funds from the bank

Now let’s withdraw these funds. Let’s start with two rules:

  1. You have to withdraw all of your funds, that is, no partial withdrawals right now. And
  2. An address can only withdraw their own funds

Here is a buggy and wrong way to do this:

  function withdraw() {
    // DON'T DO THIS
    balances[msg.sender] = 0;

What’s wrong with this code?

Well, the problem is that we’re sending the funds, and then clearing the balance, without checking to see if the .send succeeded.

One failure scenario here is that the send fails because the receiving contract runs out of gas. Then we set their balance to zero, but the Ether wasn’t transferred! In this case, we’d unfairly clear their balance, but keep their Ether in the bank.


Subscribe to get the full text of this lesson

and the entire library of videos, sample code, and tutorials.