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.
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
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:
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:
But what exactly is the Ethereum network? I’ll answer that question in the next section.
When you connected to Ethereum in the previous chapter, you might not have noticed that you connected to two different networks:
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.
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:
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.)
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.
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.
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).
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.
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.
Account name |
Account address |
---|---|
Main account | 0xedDE06bC0e45645e2f105972BDefC220ED37Ae10 |
Account 2 | 0x4e6C30154768b6bc3Da693b1B28C6bd14302b578 |
Account 3 | 0x70e36bE8AB8f6Cf66C0C953cF9c63aB63f3FeF02 |
Account 4 | 0xc99048E9B98D3FcF8b5f0D5644794B562f9A2ea4 |
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).
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.
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/.)
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.
Account address |
Account balance |
---|---|
0xedDE06bC0e45645e2f105972BDefC220ED37Ae10 | 9,850 |
0x4e6C30154768b6bc3Da693b1B28C6bd14302b578 | 0 |
0x70e36bE8AB8f6Cf66C0C953cF9c63aB63f3FeF02 | 150 |
0xc99048E9B98D3FcF8b5f0D5644794B562f9A2ea4 | 0 |
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.
Account address |
Account balance |
---|---|
0xedDE06bC0e45645e2f105972BDefC220ED37Ae10 | 9,850 |
0x4e6C30154768b6bc3Da693b1B28C6bd14302b578 | 50 |
0x70e36bE8AB8f6Cf66C0C953cF9c63aB63f3FeF02 | 100 |
0xc99048E9B98D3FcF8b5f0D5644794B562f9A2ea4 | 0 |
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
Well done! You’ve redeployed SimpleCoin on Ropsten through MetaMask. Now you can see how you can interact with it 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.
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.
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.