DApp – My First Solidity Contract

As explained in my previous post my first smart contract is based on the “Withdrawal from Contracts” example from the Solidity Common Patterns documentation. In this post I review some of the Solidity code I learned.

Smart Contract Intro

The example in the documentation was inspired by the King of the Ether game and the rules of the contract are:

  • To play a user submits a value of X Ether paid from his address
  • If X > historicHighest:
  • user is king
  • old king can collect previous payments
  • historicHighest = X

The contract itself is:

pragma solidity ^0.4.2;

contract WithdrawalContract {
    address public richest;
    uint public mostSent;
    mapping (address => uint) pendingWithdrawals;

    function WithdrawalContract() payable {
        richest = msg.sender;
        mostSent = msg.value;
    }

    event BecameRichestEvent(address sender, uint amount);
    event FailedRichestEvent(address sender, uint amount);
    event Collected(uint amount);

    function BecomeRichest() payable returns (bool) {

        if (msg.value > mostSent) {
            pendingWithdrawals[richest] += msg.value;
            richest = msg.sender;
            mostSent = msg.value;
            BecameRichestEvent(msg.sender, msg.value);
            return true;
        } else {
            FailedRichestEvent(msg.sender, msg.value);
            return false;
        }
 }

function withdraw() {
    uint amount = pendingWithdrawals[msg.sender];
    // Remember to zero the pending refund before
    // sending to prevent re-entrancy attacks
    pendingWithdrawals[msg.sender] = 0;
    msg.sender.transfer(amount);
    Collected(amount);
 }
}

Solidity Specifics

I found this Introduction to Smart Contracts documentation a good source of information.

Addresses – address public richest;

Type address — holds a 20byte Ethereum address. Here it’s used to save the address of the user who is currently the richest.

public allows other contracts to access the variable.

An address has various member functions as detailed here. One of these is address.transfer(uint256 amount) which sends the given amount of Wei to the address. In this case transfer is used in the Withdraw function to safely send Ether to a valid users address.

Mappings - mapping (address => uint) pendingWithdrawals;

The next line, mapping (address => uint) public balances; also creates a public state variable, but it is a more complex datatype.

Mappings can be seen as hash tables. pendinWithdrawals maps addresses to unsigned integers. For example:

pendingWithdrawals[0xc7975434577b0d57248e1de03fcc6f27cd6cc742] = 7;

Maps the value 7 to address 0xc7975434577b0d57248e1de03fcc6f27cd6cc742 and can be called using:

x = pendingWithdrawals[0xc7975434577b0d57248e1de03fcc6f27cd6cc742]; 

x = 7

Transactions & Constructors – function WithdrawalContract() payable

This is a constructor – a function that is run when the contract is first created.

The payable modifier means the function is a transaction. A transaction is the transfer of data between two accounts (good explanation here). A transaction contains some standard data e.g. sender address or the amount of wei being transferred. We can access the transaction data using the global msg variable.

In this case msg is used to set the initial richest address to msg.sender which is the address of the person deploying the contract. It also saves the mostSent as the msg.value which is the number of wei sent during the deployment.

Events – event BecameRichestEvent(address sender, uint amount);

The front end of the application, in my case Web3.js, listens for Solidity events being fired so it can update the interface. For example the BecameRichest event fires when a new account becomes the richest.

The event is fired by the line:

BecameRichestEvent(msg.sender, msg.value);

The listener will have access to the sender and value data passed to the call.

In the next post I plan to detail some of the front end functionality, including how to listen for events.

Ethereum Work – Beginners Sending & Receiving Eth

Intro

I’ve been following the Status project for some time and recently they announced their virtual hackathon. I’d been planning on diving into the Ethereum/Decentralised App development world and thought this would be an ideal time to start and I pretty quickly saw how powerful and relatively simple this can be.

As a complete beginner to working with the blockchain I found it better to begin by forgetting about the Status part and even the Dapp part and just see how to interact with a blockchain. Basically you can send some Eth between accounts using one function – that’s impressive.

Setup

I figured you need to get set-up with three things to get going:

1. A blockchain

Normally this would be the Ethereum blockchain but whenever you run a smart contract on Ethereum you must pay for the computation using gas. Testnets simulate the Ethereum network on you local machine and allow you to experiment for free. I installed testrpc.

2. web3.js

web3.js is a Javascript library which runs in a browser, connects to a local blockchain node and allows you to make calls on the blockchain. It does this using remote procedure calls (RPC) which basically means passing messages in JSON format.

3. Truffle

Truffle is a development environment for Ethereum that makes development a lot easier. For this exercise I’m just using the Truffle console to interact with web3.js manually. It’s way more powerful than that, which I hope show during some more posts in the future.

The Action

Start the testnet

To begin the testrpc testnet needs to be started by entering the following command:

testrpc -p 8546
This just means a simulated Eth client is listening on my laptops IP address on port 8546.
When it starts gives a list of test wallets that are loaded with 100Eth (unfortunately not real Eth, just Eth for the simulated environment). These are handy for experimenting with. My output showed:
Available Accounts
 ==================
 (0) 0xc7975434577b0d57248e1de03fcc6f27cd6cc742
 (1) 0x74dcfef837aff77d7c43d44d1d69b1eef5d708a6
 (2) 0xac63a31fd24d692997e577c02524f81eb223cd1d
 (3) 0x86fd495d744d13d43d00aa700dc9517a92eb9eae
 (4) .......

Run web3 commands

Truffle has a console tool that can be used to run web3 commands. To start it just type (keep testrpc running in separate window):

truffle console

Then try:

web3.eth.accounts

you should see a list of the same accounts you saw when you started testrpc.

Send send send

So now the really cool part. To transfer Eth between accounts all you need to enter is:

var sender = web3.eth.accounts[0];
Which shows the first address in your list, in my case: ‘0x72ddd46949fddd6add06d99a3f64357a18506470′
var receiver = web3.eth.accounts[1]
Which shows the second address in your list, in my case:
‘0x05fc7ea9e73061234d45381e8cc2e1995d4d02da’
To show the current balances in both accounts:
web3.eth.getBalance(sender)

web3.eth.getBalance(receiver)

These should both return,

{ [String: '100000000000000000000'] s: 1, e: 20, c: [ 1000000 ] }
which shows 100Eth in both accounts.
We’ll transfer 0.01Eth:
var amount = web3.toWei(0.01, 'ether')
 And the actual transfer (this could have been run by itself right from the start but the above steps make the process a bit clearer):
web3.eth.sendTransaction({from:sender, to:receiver, value: amount})
 This returns a transaction address like: ‘0x9e9963f4782b4248b2cd42d8af17e85d64d049e052da335e3517f4a8a69aa064’
To confirm the transfer we can check the balances again:
web3.eth.getBalance(sender) this time shows:
{ [String: ‘99989999999999979000’] s: 1, e: 19, c: [ 999899, 99999999979000 ] }
web3.eth.getBalance(receiver) this time shows:

{ [String: ‘100010000000000000000’] s: 1, e: 20, c: [ 1000100 ] }

So 0.01Eth has been transferred!
If you look in your testrpc window you should see the transaction information on the blockchain, something like:
0x9e9963f4782b4248b2cd42d8af17e85d64d049e052da335e3517f4a8a69aa064
 Gas usage: 0x5208
 Block Number: 0x01
 Block Time: Tue Jun 06 2017 19:34:54 GMT+0100 (BST)

So with as little as one command you can transfer value electronically, cryptographically proven and with minimal fee. From a pure tech geek point of view that’s awesome, no wonder people get excited about this stuff!