Chapter 4. Deploying your first smart contract

This chapter covers

  • Deploying a contract onto the Ethereum network
  • Interacting with the contract over the network
  • Nodeless contract deployment and interaction with MetaMask

In the first two chapters, you started building SimpleCoin, your basic cryptocurrency. You did so in the Remix IDE and tried out its minimal functionality through its JavaScript-based EVM emulator. The experience was useful to help you understand from a conceptual point of view what a smart contract looks like and how to activate and interact with it. But SimpleCoin still looks like a bit of code running in an IDE. Now that you’re becoming familiar with the Ethereum platform, you may be wondering, “Wouldn’t it be nice to see SimpleCoin in action in a more realistic environment?” That’s exactly what you’ll be doing in this chapter.

You’ll deploy the SimpleCoin contract onto the Ethereum network, and then you’ll interact with it in a couple of ways. First, you’ll go through the Ethereum wallet, which requires you to import a copy of the blockchain locally, and then you’ll go through MetaMask, a third-party tool that allows you to connect to the Ether-eum network without accessing an Ethereum client or the wallet.

4.1. Deploying a contract onto the network

You’re probably used to deploying centralized applications on servers. If you’ve ever developed a web application, for example, you might have initially developed all the layers on your desktop computer. Then, after the application was mature enough for users or testers to test it, you deployed its components into the user acceptance testing (UAT) environment on one or more servers. A typical deployment for a web application might include

  • One web server that hosts static and dynamic web pages
  • One or more application servers that host the services the web pages use
  • One or more database servers that persist the data that the services use

The deployment of a decentralized application is quite different. Even a simple decentralized application consisting of only one smart contract, like your SimpleCoin application, would get deployed across the entire Ethereum network. As you might recall from the development view I introduced in chapter 2, section 2.1.3, a smart contract gets deployed as a special transaction whose payload is compiled EVM bytecode. You submit the deployment transaction through a local node, which propagates it throughout the Ethereum network until it hits mining nodes. The smart contract only gets deployed after a mining node has successfully processed the deployment transaction containing the contract EVM bytecode to a new block that gets appended to the blockchain. That block is then replicated throughout the Ethereum network, as shown in figure 4.1.

You have two options for deploying contracts onto the network:

  • Manually, through the Ethereum wallet
  • Through terminal commands, on geth’s interactive console

Figure 4.1. A contract written in a high-level language such as Solidity is compiled into EVM bytecode and deployed to the network through a deployment transaction containing the contract EVM bytecode, which is executed through a local full node of the network. The deployment transaction is propagated throughout the network; then it’s processed by a mining node and included in a new block that gets replicated throughout the network. It’s like any other transaction, except that what’s being stored on the blockchain isn’t Ether or data but EVM bytecode.

In this chapter, you’ll deploy the SimpleCoin contract manually. By doing so, you’ll go through the deployment process in a visual and intuitive way that will help you learn quickly.

Once you get used to deploying contracts through the Ethereum wallet, you’ll be ready for the next step: command-based deployment. Though it may seem slightly intimidating at first, deploying contracts through geth’s console is a useful exercise because it helps you understand the platform more thoroughly. You’ll explore this in the next several chapters. For now, I’ll quickly recap what you know:

  • The mechanisms to trigger deployment—You know that you can deploy contracts manually through the Ethereum wallet or by using commands on geth’s console. (You’ll see these in action soon.)
  • What happens during deployment—The contract’s bytecode gets stored on the blockchain following the execution of its deployment transaction.

But what exactly is the Ethereum network? I’ll answer that question in the next section.

4.1.1. Ethereum public networks

When you connected to Ethereum in the previous chapter, you might not have noticed that you connected to two different networks:

  • From the Ethereum wallet, you connected to Ropsten, a public test network.
  • From geth, you connected to Mainnet, the public production network.

Ropsten is the public test network that Ethereum provides for mining based on proof of work (PoW), which is the current algorithm used in the public production network. If you followed the instructions I gave you, your Ethereum wallet is already pointing to the Ropsten network, and you only have fake Ether in your accounts, which you generated through CPU mining.

If you left your geth client running from the previous chapter, it’s pointing to Mainnet, the production network. Ether moved between accounts in this network is real. You should use this network only to perform transactions against production Dapps; you should avoid it during development.

Another public test network called Kovan is available, and it supports mining performed with a new algorithm called Proof of Authority. So far, this has only been implemented in the Parity client, so it’s outside the scope of this book.

In the next section, you’ll deploy the SimpleCoin contract to Ropsten through the wallet. As a result, you don’t need to make any environmental configuration changes yet.

4.1.2. Deploying SimpleCoin with the Ethereum wallet

Start up the Ethereum wallet—make sure the sync mode is Fast or Full and wait until it’s fully synchronized—and open the Contracts screen by clicking Contracts on the top bar, near the top-right corner. You’ll see two main options:

  • Deploy New Contract—You can deploy a new contract by supplying its Solidity code.
  • Watch Contract—You can reference a contract that already has been deployed so you can interact with it.

Click Deploy New Contract. When the Deploy Contract screen opens, you can decide which account will become the contract owner. Choose Account 1, and then click the Solidity Contract Source Code tab at the bottom of the screen and paste the SimpleCoin code from the end of chapter 3, as shown in the following listing. (Make sure the constructor and functions are declared as public to be compiled in the wallet; I’ll explain function access modifiers such as public in chapter 5.)

Listing 4.1. Latest version of SimpleCoin (from chapter 3)
pragma solidity ^0.4.0;

contract SimpleCoin {
    mapping (address => uint256) public coinBalance;
    
    event Transfer(address indexed from, address indexed to, uint256 value);

    constructor(uint256 _initialSupply) public {
        coinBalance[msg.sender] = _initialSupply;   
    }

    function transfer(address _to, uint256 _amount) public {
        require(coinBalance[msg.sender] > _amount);

        require(coinBalance[_to] + _amount >= coinBalance[_to] );
        coinBalance[msg.sender] -= _amount;  
        coinBalance[_to] += _amount;   
        emit Transfer(msg.sender, _to, _amount);  
   }
}

Once you’ve pasted the code, the wallet will compile it into EVM bytecode, and a drop-down list will appear on the right-hand side. Pick Simple Coin from the list and enter 10000 as the constructor parameter. Finally, click Deploy at the bottom of the screen, as shown in figure 4.2.

Figure 4.2. After you enter the Solidity code of a contract, the wallet compiles it into EVM bytecode. Supply the contract parameters, click Deploy, and a new dialog box will confirm the deployment transaction.

A new dialog box will appear, as shown in figure 4.3. You’ll be asked to enter the password and to send the deployment transaction. Remember: you need Ether in your account to be able to submit the transaction! Once you send the deployment transaction, you can check its status in the Latest Transactions section of the wallet main screen. There you can see that the deployment transaction is treated like any other transaction.

Figure 4.3. A dialog box asks you to enter the password of the account that you’ll deploy the contract from. After you supply it and click Send, a deployment transaction is generated and sent to the network.

Once the contract has received all the necessary network confirmations, which you can view in the Latest Transactions panel (see figure 4.4), go back to the Contracts screen. You’ll see Simple Coin with a balance of zero Ether (figure 4.5).

Figure 4.4. After a contract transaction has been submitted to the network, you can monitor its network confirmations in the Latest Transactions panel of the Contracts screen.

Figure 4.5. After the contract receives 12 confirmations, which makes it very likely the deployment transaction is permanently stored on the blockchain, a deployed contract appears in the Contracts panel.

Definition

Transaction confirmations indicate the depth of the transaction in the blockchain. A new confirmation is received as soon as a new block is appended to the blockchain after the block containing the transaction in question. The probability of a block reversal decreases exponentially as the number of confirmations increase, so a transaction is considered consolidated after 12 confirmations. (That means 12 blocks have been added to the blockchain after the block containing the transaction.)

Congratulations! You’ve deployed your first contract on the Ethereum network. Now you can interact with the contract, much as you did earlier with Remix. You can start by moving SimpleCoin tokens between accounts and verifying the expected balances.

4.2. Interacting with the contract

Before starting to move SimpleCoin tokens, go back to the wallet’s main screen and add two more accounts. (Remember to take note of the related passwords.) These extra accounts will become handy when testing contract operations. I recommend you copy all the account addresses you have in your wallet to a temporary text file. Table 4.1 shows what it would contain in my case.

Table 4.1. Ethereum wallet account addresses

Account name

Account address

Main account 0xedDE06bC0e45645e2f105972BDefC220ED37Ae10
Account 2 0x4e6C30154768b6bc3Da693b1B28C6bd14302b578
Account 3 0x70e36bE8AB8f6Cf66C0C953cF9c63aB63f3FeF02
Account 4 0xc99048E9B98D3FcF8b5f0D5644794B562f9A2ea4
Tip

To copy an address, select it, and then click Copy Address. Alternatively, you can use the usual Ctrl+C shortcut. Either way, the wallet will ask you to confirm you want to go ahead with this operation. (There is risk that malware may replace the address.)

Now go back to the Contracts screen and click SimpleCoin. At the top of the screen, just below the name of the contract, you’ll see the contract address, which is the account address of the contract in the blockchain. You’ll notice that the area associated with the SimpleCoin contract is logically divided into two parts: Read from Contract on the left and Write on Contract on the right. This arrangement is similar to the color codes you saw in Remix for read-only functionality (blue) and write functionality (red).

4.2.1. Checking coin balances

You can first check the coin balance of all accounts by entering the address of each account next to the coin balance textbox. The expected balances are shown in table 4.2.

Table 4.2. Expected account balances

Account address

Account balance

0xedDE06bC0e45645e2f105972BDefC220ED37Ae10 10,000
0x4e6C30154768b6bc3Da693b1B28C6bd14302b578 0
0x70e36bE8AB8f6Cf66C0C953cF9c63aB63f3FeF02 0
0xc99048E9B98D3FcF8b5f0D5644794B562f9A2ea4 0

What happens if you try to check the balance of an invalid address? For example, replace the last digit of the main account (starting with 0xedDE06bC) with an 8 and try to check the coin balance. You won’t be allowed to enter such an address because the wallet will consider its checksum invalid. But you will be allowed to enter any valid Ethereum address, even if it’s not associated with your accounts. (You can grab some to try from https://etherscan.io/.)

4.2.2. Transferring coins

Now you can move some coins around. You can start with a transfer of 150 SimpleCoins from the Main Account to Account 3. This is the same operation you performed on Remix in the previous chapter. Pick Transfer from the Select Function drop-down in the Write to Contract panel. All the input fields required for the coin transfer will appear, as in figure 4.6.

Pick the Main Account from the Execute From list, then set the address of Account 3 in the To field and an amount of 150. After you click Execute, you’ll be asked to enter the password of the Main account to digitally sign the transaction.

If you select the Watch Contract Events box in the Latest Events pane, you’ll soon see the details of the transaction you’ve sent. At this point, you can recheck the balances of all addresses. The expected balances are shown in table 4.3.

Table 4.3. Expected updated account balances

Account address

Account balance

0xedDE06bC0e45645e2f105972BDefC220ED37Ae10 9,850
0x4e6C30154768b6bc3Da693b1B28C6bd14302b578 0
0x70e36bE8AB8f6Cf66C0C953cF9c63aB63f3FeF02 150
0xc99048E9B98D3FcF8b5f0D5644794B562f9A2ea4 0

Figure 4.6. Checking the SimpleCoin balance is a read-only operation, so you only need to specify the input address. Transferring coins is a write operation. As seen here, you have to specify the number of coins to be transferred, the destination address, and the sending account.

Now try to move 50 coins from Account 3 to Account 2 and recheck the balances after the transaction has appeared in the Latest Events panel. You’ll notice that the only accounts listed in the Execute From drop-down list are the Main Account and Account 2. This is because the wallet doesn’t allow you to execute a transaction from an account with no Ether in it.

As you saw in chapter 2, the executing account must pay a transaction fee calculated in gas but settled in Ether to perform a transaction. For Accounts 3 and 4 to be useful, you must send some Ether to them from the Main Account. You can perform this Ether transfer from the Send screen, as you did in the previous chapter when you set up Account 2. As usual, you can monitor the Ether transfer transactions on the Latest Transactions panel and wait for them to complete. Once all accounts own some Ether, you’re ready to perform a transaction.

Go back to the SimpleCoin contract screen and pick the transfer function again. The Execute From drop-down list will now show all the accounts, so you can pick Account 3. Enter the address of Account 2 in the To textbox and 50 in the Amount field. When you click Execute, you’ll be asked for the password for Account 3, the sending account. After the transaction has been confirmed, recheck the balances. The new expected balances are shown in table 4.4.

Table 4.4. Updated account balances after second transfer

Account address

Account balance

0xedDE06bC0e45645e2f105972BDefC220ED37Ae10 9,850
0x4e6C30154768b6bc3Da693b1B28C6bd14302b578 50
0x70e36bE8AB8f6Cf66C0C953cF9c63aB63f3FeF02 100
0xc99048E9B98D3FcF8b5f0D5644794B562f9A2ea4 0
Trying to transfer unavailable coins

As you’ll remember, the code of the SimpleCoin transfer function performs some checks before modifying the balances of the sender and recipient addresses. It prevents an account from attempting to transfer unavailable coins by throwing an error. You can see what happens if you try to do so through the wallet. For example, try to move 200 coins from Account 4 to Account 3. As expected, you’ll get an error message indicating the transaction will fail, as shown in figure 4.7.

Figure 4.7. If a transaction generated from a write operation, such as SimpleCoin.transfer(), fails validation checks, it can’t be sent to the network.

You might be surprised that the error message is thrown before the transaction has even been sent out. This happens because the wallet verifies transactions locally, before sending, as any node would do. If an error is returned, the wallet doesn’t propagate the transaction to the network, and you receive an error message immediately.

Well done! You’ve fully, manually, tested SimpleCoin on the public test network.

So far, this chapter has given you an idea of how to deploy a smart contract to a public network without having to run a full Ethereum node. You performed it through the Ethereum wallet, which, under the hood, still connects to a fully synchronized copy of the blockchain. But you might be wondering whether you can achieve the same thing without having a local synchronized copy of the blockchain. The answer is yes. As we’ll explore in the next section, you can connect to a set of publicly accessible nodes exposed by a Chrome plugin called Metamask.

4.3. Nodeless deployment through MetaMask

MetaMask is a Chrome extension that connects you to an external set of Ethereum nodes, as you can see in figure 4.8. It allows you to deploy a contract to a public network and interact with it without having to install and maintain any Ethereum software. As an alternative, if you don’t want to use Chrome, you can download the Brave browser and install MetaMask as an extension. MetaMask is especially handy if you don’t develop smart contracts continuously and don’t want the inconvenience of having to update the wallet or Go Ethereum client and resynchronize the blockchain every time you resume your development.

Figure 4.8. When connecting to Ethereum through the Ethereum wallet or the Go Ethereum client console, you do so through a local node. When connecting to Ethereum through Metamask, you do so through a remote node.

In the next section, you’ll install MetaMask. Then you’ll redeploy SimpleCoin to Ropsten through MetaMask and interact with it, completely bypassing your local geth client and Ethereum wallet.

4.3.1. Installing MetaMask

You can install the MetaMask chrome extension from this url: http://mng.bz/8JzB. After adding the extension, you should see the MetaMask icon next to the browser address bar.

You can now start to set up a MetaMask wallet by clicking on the MetaMask icon. You’ll be invited to accept a privacy notice and terms and conditions (at your own risk). Then you’ll be asked to create a new password, as shown in figure 4.9.

Figure 4.9. Creation of a password to secure the MetaMask wallet

Enter your new (possibly secure) password and click Create. You’ll be advised to copy and securely store the system-generated 12-word recovery passphrase. The wallet will be created after you confirm you’ve done so, and at that point you’ll see on the top left, next to the MetaMask icon, the name of the network you’re connected to. Initially, you’re connected to Main Ethereum Network, as shown in figure 4.10.

Figure 4.10. MetaMask initially points to Main Ethereum Network.

Given that you’ll deploy SimpleCoin onto a test network, change your current network by clicking Main Ethereum Network and selecting the Ropsten Test Network from the drop-down list, as shown in figure 4.11.

Figure 4.11. It’s possible to connect to various Ethereum networks through MetaMask.

You’ll notice the default account has nothing to do with any of the accounts you have in your Ropsten Ethereum wallet. And this default test account hasn’t got any Ether, so you won’t be able to do much with it. To import some of your existing Ropsten accounts, which already contain Ether, click the menu icon on the top right, and then select Import. In the Import dialog box, you’ll see a Select Type drop-down list. Select JSON File, as shown in figure 4.12.

Figure 4.12. Dialog box for importing accounts from JSON files

Now you have to supply the JSON file containing the private key of your existing Ropsten account. Remember, the key pairs of your Ropsten account are held in the testnet keystore, which, depending on your OS, you can find in one of the locations shown in table 4.5.

Table 4.5. Testnet keystore locations

System

Keystore path

Windows C:Usersusername\%appdata%RoamingEthereum estnetkeystore
Linux ~/.ethereum/testnet/keystore
Mac ~/Library/Ethereum/testnet/keystore

The testnet keystore folder should contain a list of files whose names contain the timestamp and the account address they refer to:

  • UTC--2017-06-24T08-49-46.377533700Z--edde06bc0e45645e2f105972bdefc220ed37ae10
  • UTC--2017-06-24T13-26-18.696630000Z--4e6c30154768b6bc3da693b1b28c6bd14302b578
  • UTC--2017-06-24T18-21-36.890638200Z--70e36be8ab8f6cf66c0c953cf9c63ab63f3fef02
  • UTC--2017-06-24T18-21-47.794428600Z--c99048e9b98d3fcf8b5f0d5644794b562f9a2ea4

Although the file extension isn’t present, these are JSON files. For example, the second file on the list refers to account 4e6c30154768b6bc3da693b1b28c6bd14302b578. If you open the file with a text editor, such as Notepad in Windows, you should see JSON content similar to this:

{"address":"4e6c30154768b6bc3da693b1b28c6bd14302b578","crypto":{"cipher":"aes
-128-ctr","ciphertext":"bc7569458b99dcbbdcb0cf46402eeb83875baa6302d27e887a6d4
e2d6e31771f","cipherparams":{"iv":"f0838a98d39d532e8d96e9f7cc799712"},"kdf":"
scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"fb2dbd4f24553c
585025417b691ef11784cf6ae90aa412b73e4965ba3d4f2772"},"mac":"36ba647b1d2ff7a3d
8ca6b32731593caee920dcc19d14e91915cb98a7a244c2c"},"id":"32bb1449-60f5-4cd0-
a4d2-4608fa9fc1c3","version":3}

In the MetaMask Import Account dialog box, click Choose File, navigate to your testnet keystore, and then pick the file related to the account you want to import. You must supply the password you entered when creating this account, and then click Import. After a few seconds, you should see the details of the account you’ve imported, including the Ether contained in it, as shown in figure 4.13. Once you’ve imported a couple of your existing Ropsten accounts, you can proceed to the deployment of SimpleCoin.

Figure 4.13. After you import an account from the keystore, all its details appear on MetaMask.

4.3.2. Deploying SimpleCoin through MetaMask

To deploy SimpleCoin, first open Remix and enter the latest version of SimpleCoin, the same one you entered into the wallet, shown earlier in listing 4.1. Now pick the Injected Web3 option in the Environment drop-down list in the Run tab of the right-hand side panel, as shown in figure 4.14.

Figure 4.14. The screenshot shows how you can configure Remix to use external MetaMask nodes (rather than the local JavaScript Virtual Machine emulator) by selecting Injected Web3 in the Environment drop-down list.

Remix will detect MetaMask, and it’ll use one of the MetaMask nodes rather than the local JavaScript EVM emulator. If no account is showing in the Account drop-down list, refresh the Remix webpage and the account currently selected in MetaMask will be selected.

You can trigger SimpleCoin’s deployment by clicking the red Deploy button. Account 2, whose address starts with 0x4e6c30154, is the only option available and is currently selected in the Account drop-down list box. That account will deploy the contract.

After you click Deploy, you’ll see a dialog box summarizing information on the executing account and transaction costs for the deployment transaction. You’ll also be asked to confirm you want to go ahead with it, as you can see in figure 4.15.

Figure 4.15. After configuring Remix to point to external Metamask nodes and starting the deployment of a contract (such as SimpleCoin), you get a (deployment) transaction confirmation dialog box from Metamask. This shows information on the account executing the deployment transaction and on transaction costs. The dialog box also asks the user to confirm whether to go ahead with the deployment of the contract.

After clicking Confirm, you can check the transaction status in the bottom area of the Metamask wallet. The status will move from Submitted to Confirmed, as shown in figure 4.16.

If you click the label Transaction Number while the contract is in status Submitted, and then after it has moved to Confirmed, you’ll see the transaction details from the Etherscan website, as shown in figure 4.17. As you can see, Etherscan also shows the destination address (starting with 0x0c9189e4d6) of the contract.

Figure 4.16. It’s possible to monitor the status of the deployment transaction in the bottom area of the Metamask wallet. This will change from Submitted to Confirmed.

Figure 4.17. Transaction details from the Etherscan website, invoked when clicking the (Submitted or Confirmed) status on the MetaMask wallet

If you move back to Remix, you’ll see some deployment details below the Deploy button, including the deployment address, which is the same one you saw on the Etherscan page. You can grab the address by clicking the Copy Address link, as shown in figure 4.18.

Figure 4.18. After the completion of the deployment transaction, the contract address is shown in Remix, below the Deploy button.

Well done! You’ve redeployed SimpleCoin on Ropsten through MetaMask. Now you can see how you can interact with it through MetaMask.

4.3.3. Interacting with SimpleCoin through MetaMask

Figure 4.18 also shows that after deploying SimpleCoin, Remix displays two buttons: CoinBalance and Transfer. These are exactly the same buttons that appeared when you created the contract for the first time on the JavaScript VM, back in chapter 1. This time, though, you’ll be interacting with a contract instantiated on a real network.

The first operation you can perform is to check the token balance of Account 2, the account that deployed the contract. Enter “0x4e6c30154768b6bc3da693b1b28-c6bd14302b578” (remember, as usual, to surround the address with double quotes) and click CoinBalance. You’ll immediately get 10,000, as expected. As with checking balances through the Ethereum wallet, this operation is read-only and doesn’t produce a transaction. Consequently, you don’t need to authorize it.

Now move 250 tokens from Account 2 to Account 3. Enter this into the Transfer text box:

"0x70e36bE8AB8f6Cf66C0C953cF9c63aB63f3FeF02", 250

Click Transfer. This is a write operation, so the MetaMask transaction confirmation dialog box pops up, as shown in figure 4.19. You can authorize it from Account 2. Click Confirm and follow the transaction status in the MetaMask dialog box.

Figure 4.19. To transfer SimpleCoin tokens, which is a contract-state write operation, the sending account needs to be authorized. Subsequently, the MetaMask transaction confirmation dialog box is shown to get user confirmation.

If you click on the transaction number icon, you’ll see the transaction details in Etherscan. You can now go back to Remix and check the transaction details there as well.

Both Etherscan and Remix confirm that the move of 250 SimpleCoin tokens from Account 2 to Account 3 has been successful, but you can double-check the new balances of these accounts with the coinBalance function, which should match those in table 4.6.

Table 4.6. Account balances after transferring 250 tokens

Account address

Account balance

0x4e6C30154768b6bc3Da693b1B28C6bd14302b578 9,750
0x70e36bE8AB8f6Cf66C0C953cF9c63aB63f3FeF02 250

I’ll stop here, but I’d encourage you to generate some error messages, for example by trying to move unavailable coins, as you did previously with the Ethereum wallet. Doing so will allow you to confirm whether the contract also works correctly on MetaMask.

Summary

  • You can deploy a contract onto the Ethereum network and interact with it using the Ethereum wallet.
  • The Ethereum wallet communicates with Ethereum through a local geth instance.
  • You can deploy a contract onto the Ethereum network and interact with it using MetaMask.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset