Subscribe to get access to this video

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

Payable Contracts, payable Functions

A contract can own funds.

Remember how in the geth console we’d check the balances of our accounts?

// eth.accounts[0]
eth.getBalance("0xfe1e5f629c0913aac3bd727aa009f9b6de23777e")

What’s happening here? That hash is the address of our account, and the Ethereum blockchain stores the number of Ether assigned to that account.

We can do the exact same thing with contracts! Remember that our contract is deployed to a particular address? That address is also the contracts account address. And that account can hold a balance.

Making Bank

Let’s create a simple Bank contract:

// Bank-001.sol
pragma solidity ^0.4.11;

contract Bank {
  event DepositMade(
    address sentBy,
    uint amount
  );

  function deposit() payable {
    DepositMade(msg.sender, msg.value);
  }
}

We start by creating a new contract called Bank, and we’ll emit an event DepositMade, whenever the deposit function is called.

Our deposit function has a new modifier payable. Payable functions are functions with can accept Ether value when called.

That is, when we send the transaction, we send, not only the function arguments but an additional amount of Ether from our account, to the contract. We can use that value in our function.

When we call contract functions, there are a number of global, or context, variables that we can access. This is the first time we’ve talked about these. Here we are going to use two:

  • msg.sender and
  • msg.value

msg.sender is the address of the incoming transaction. So if we call this message from our account, msg.sender would be our account address.

 

Subscribe to get the full text of this lesson

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