© Wei-Meng Lee 2019
W.-M. LeeBeginning Ethereum Smart Contracts Programminghttps://doi.org/10.1007/978-1-4842-5086-0_7

7. Testing Smart Contracts Using Ganache

Wei-Meng Lee1 
(1)
Ang Mo Kio, Singapore
 

In Chapter 4, you learned how to create your own private test Ethereum network using the Ethereum client – Geth. While Geth is not that difficult to use to set up an Ethereum blockchain, it still takes considerable effort to set one up. In addition, you also need to create accounts and perform mining in order to obtain Ethers so that you can use them to deploy Smart Contracts and for performing transactions.

A much better option is to use a tool that can emulate an Ethereum blockchain, together with all the required accounts so that you can just focus on testing your Smart Contracts. Well, such tool does exist, and it is called – Ganache.

Ganache is a personal Ethereum blockchain that allows you to test and deploy your Smart Contracts without needing to connect to a real blockchain or set up your own blockchain using an Ethereum client like Geth.

Tip

Ganache was previous known as TestRPC.

In this chapter, you will learn how to download and install Ganache and how to test and deploy your Smart Contracts onto Ganache.

Downloading and Installing Ganache

Ganache comes in two flavors – as a desktop GUI app and as a command line tool. They are both available on the Windows, Mac, and Linux platforms. In the following sections, you will learn how to install the desktop as well as the command-line version of Ganache.

Command-Line Interface

The command-line version of Ganache is a Node.js-based Ethereum client. It uses EthereumJS library to simulate full client behavior and make developing Ethereum applications much faster. It also includes all popular RPC functions and features (like events) and can be run deterministically to make development a breeze.

To install command-line version of Ganache, you would need to install Node.js on your computer. You can then use npm to install the tool.

In Terminal (or Command Prompt), type the following command to install the Ganache command-line interface (CLI):
$ npm install -g ganache-cli
Once the Ganache CLI is installed, you can launch Ganache using the following command:
$ ganache-cli
You will see the following:
Ganache CLI v6.3.0 (ganache-core: 2.4.0)
Available Accounts
==================
(0) 0xce2a65ca22188ac0f4efe35f5936f3c0dc530246 (~100 ETH)
(1) 0x7dd09408274683cf2968034f1a64846069ea2e0f (~100 ETH)
(2) 0xdb8c5742be2a5ded84cdd742335f5224b77d847d (~100 ETH)
(3) 0x76270d1ea676939ab6ea29dcb4d9320b6855ff0d (~100 ETH)
(4) 0xf3183fb25c7305689de42ae603993eb9bfc410d7 (~100 ETH)
(5) 0x2b0b625aaa7b7474567223179f17899d5b28257a (~100 ETH)
(6) 0x947f22c0de05ce218e5f80c116fd94a0bc379896 (~100 ETH)
(7) 0x5fd0f170ca98bf45e1f04256a544ade5a31952b0 (~100 ETH)
(8) 0xb3326cfa9180f7f54ebfbec433027a52e672d3b2 (~100 ETH)
(9) 0x0f36e01ce6b6db257c55d5ffe2d13690734a6c77 (~100 ETH)
Private Keys
==================
(0) 0xb822773982826eb87481f50ac4a3a6df8e3ff533a64b2c0a67604666e51f18cc
(1) 0x81db3467f2827785aa82b2374de46ad82468c4ef97b3dbafcb7421be78351032
(2) 0x4a5a3ef65431fa3ea41a21ed6fcebf9f8105ea4415b1c155b2fe9568105b93f1
(3) 0xffc74b45809c25c5c4fcd6ef3a80e2259a6eddda1c0cb03bd94f47a57e04e897
(4) 0x48481c042b93f74adb353ba5439e7071d0903922f0f4b7917412e4cf2354cf4e
(5) 0xc3952aba303a774ebfe646918ae6a263974abfdc9a6979bab32d47c211cb770b
(6) 0xe920e8da927b72705879c2f52d95a97d4cc4a7d1a9280e5484dc0a4cd713694f
(7) 0x6c9b8d4a7399320f81f7aa773084b498a15fdfc754004a802814ba33b41386c1
(8) 0x84a6415c523e4b140218232597bf93081c225f5e041ee88ca7145f456a873748
(9) 0x8c93dd96ae7e58e9bfe8d399f5e71032cf9117b9b193ec030ea0b814d6e289a9
HD Wallet
==================
Mnemonic:      gospel oval arm true goat luggage play into artwork sound marble soft
Base HD Path:  m/44'/60'/0'/0/{account_index}
Gas Price
==================
20000000000
Gas Limit
==================
6721975
Listening on 127.0.0.1:8545
Observe from the preceding output:
  • Ganache has pre-created 10 user accounts, each with 100 Ethers.

  • The section titled “Available Accounts” shows the account addresses of the ten accounts. The section titled “Private Keys” shows the corresponding private keys of each of the ten accounts.

  • The Ganache CLI is also listening at a local port with port number 8545.

Tip

You will learn how to interact with Ganache through its port in a later section in this chapter.

Graphical User Interface

If you do not want to mess with the command-line interface version of Ganache, you can use the desktop version of it with a graphical user interface. To download the desktop version of Ganache, go to https://truffleframework.com/ganache and click the Download button. For the Mac version, you will download a DMG file. Once it is unzipped, simply drag the Ganache icon and drop it onto the Applications folder (see Figure 7-1).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig1_HTML.jpg
Figure 7-1

Installing the Ganache on the Mac

To run it, double-click the Ganache application in the Applications folder. When you start Ganache for the first time, click the Quickstart button. Figure 7-2 shows Ganache up and running. It shows a list of 10 user accounts, each with 100 Ethers.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig2_HTML.jpg
Figure 7-2

Ganache showing the list of users it has pre-created and the amount of Ethers each account has

Tip

Observe that for the desktop version of Ganache, it is listening at port 7545 (which you can change), instead of the 8545 in the CLI version of Ganache.

If you want to see the private key of each account, click the key icon displayed next to each account (see Figure 7-3).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig3_HTML.jpg
Figure 7-3

Revealing the private key of an account

Tip

Knowing the private key of each account is important if you want to import that that account into a wallet, such as MetaMask.

When you click the BLOCKS tab, you will see that at the moment there is only one single block (Block 0; see Figure 7-4), which is the genesis block of the blockchain.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig4_HTML.jpg
Figure 7-4

Examining the block(s) in the blockchain

Creating a Smart Contract

Now that you have learned how to install the two different flavors of Ganache, let’s now write a Smart Contract and see how you can deploy it onto Ganache. For illustration, I shall use the desktop version of Ganache.

Using the Remix IDE on Chrome, create the following contract and name it as ProofOfExistence.sol:

Caution

For the Remix IDE, ensure that you are loading it using http and not https.This is because Ganache only accept connections to it using http. If you load the Remix IDE using https, you would have problems connecting to Ganache later on.

pragma solidity ^0.5.1;
contract ProofOfExistence {
  mapping (bytes32 => bool) private proofs;
  // store a proof of existence in the contract state
  function storeProof(bytes32 proof) private {
    proofs[proof] = true;
  }
  // calculate and store the proof for a document
  function notarize(string memory document) public {
    storeProof(proofFor(document));
  }
  // helper function to get a document's sha256
  function proofFor(string memory document) private
  pure returns (bytes32) {
    return sha256(bytes(document));
  }
  // check if a document has been notarized
  function checkDocument(string memory document) public
  view returns (bool) {
    return proofs[proofFor(document)];
  }
}
The preceding Smart Contract does the following:
  • It allows users to pass in a string through the notarize() function so that the hash of the string can be stored on the blockchain using the proofs state variable (which is of type mapping, which is like as associative array).

  • It allows users to verify if a string was previously recorded in the blockchain by calling the checkDocument() function and checking if the hash of the string exists in the proofs state variable.

This Smart Contract acts as a simple notarizer in which a user can store a string (e.g., containing an idea) on the blockchain and proving it later on that this idea was already invented earlier.

Deploying the Contract to Ganache

With the Smart Contract created, you shall now deploy it to Ganache. Under the Run tab in the Remix IDE, select Web3 Provider as the environment (see Figure 7-5).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig5_HTML.jpg
Figure 7-5

Connecting the Remix IDE to Ganache

Remix IDE will now prompt you if you want to connect to an Ethereum node. Click OK. In the next screen, enter the Web3 Provider’s endpoint URL (see Figure 7-6).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig6_HTML.jpg
Figure 7-6

Entering the endpoint URL of Ganache

The preceding endpoint URL is where the Ethereum node (which is Ganache in this case) is listening at. Recall that desktop version of Ganache is listening at port number 7545. Hence, be sure to specify this port number. If you are using the CLI version of Ganache, the port number is then 8545.

Tip

If you have problems in connecting to the rpc (error message: “Not possible to connect to the Web3 provider. Make sure the provider is running and a connection is open (via IPC or RPC).”), this is likely due to the fact that you are using the https version of Remix. To resolve this, simply load Remix using http.

Once the Web3 Provider is connected, you can deploy the contract to Ganache. To do so, click the Deploy button under the name of the contract (see Figure 7-7).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig7_HTML.jpg
Figure 7-7

Deploying the Smart Contract

Tip

Be sure to turn on auto compile in the Remix IDE so that your contract is automatically compiled as you type in the code for the contract.

Once the contract has been deployed, you should be able to see the two functions (see Figure 7-8).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig8_HTML.jpg
Figure 7-8

The Smart Contract deployed with the two functions showing

Tip

Click the down arrow if you don’t see the two functions – notarize and checkDocument.

Examining Ganache

If you now look at Ganache, you will see that the first account has a balance of 99.99 Ethers (see Figure 7-9).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig9_HTML.jpg
Figure 7-9

Examining the balance of the first account in Ganache

This is because when you deploy the contract through Remix IDE, Remix IDE uses the first account (by default) in Ganache to pay for the contract deployment. You can change the account to use in the Remix IDE by selecting the Account to use under the Run tab (see Figure 7-10).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig10_HTML.jpg
Figure 7-10

Changing the account to use in the Remix IDE

Also, under the BLOCKS tab in Ganache, you now see that there is an additional block – Block 1 (see Figure 7-11). This newly created block contains the contract that has been just deployed.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig11_HTML.jpg
Figure 7-11

The Ganache blockchain now has an additional block containing the deployed contract

Under the TRANSACTIONS tab, you would be able to see a new transaction (see Figure 7-12), which is the transaction that deployed the contract.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig12_HTML.jpg
Figure 7-12

Ganache now shows a new transaction involving the contract deployment

In the LOGS tab, you would be able to see the activities that go on behind the scene in Ganache (see Figure 7-13).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig13_HTML.jpg
Figure 7-13

The LOGS tab shows the activities of Ganache behind the scene

Testing the Contract

Let’s now test out the contract. Enter the string “Hello, Smart Contract!” into the text box next to the notarize button (see Figure 7-14). Then, click the notarize button. Next, enter the same string into the text box displayed next to the checkDocument button and click the checkDocument button. You should be able to see the result “0: bool:true”. This indicates that the original was stored successfully on the blockchain and then you can verify its existence on the blockchain.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig14_HTML.jpg
Figure 7-14

Storing and verifying the existence of the string in the blockchain

If you enter a different string into the text box displayed next to the checkDocument button, say “Hello, Solidity!” (see Figure 7-15) and then click the checkDocument button, you should be able to see the result “0: bool:false”.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig15_HTML.jpg
Figure 7-15

Entering a different string other than the original string will yield a result of false

If you examine Ganache now, you will be able to see the new block created on the blockchain (see Figure 7-16), as well as the new transaction (which is a contract call) that is performed when you click the notarize button.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig16_HTML.jpg
Figure 7-16

Examining Ganache, which has a new block in the blockchain as well as a new transaction

Connecting MetaMask to Ganache

Since Ganache is a blockchain, you should be able to connect your MetaMask to it. So, let’s see how you can do it.

In MetaMask, click the down arrow and select Custom RPC (see Figure 7-17).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig17_HTML.jpg
Figure 7-17

Connecting MetaMask to a custom RPC

Tip

If you are using the CLI version of Ganache, you can directly select the Localhost 8545 menu item.

You will now see the Settings page (see Figure 7-18). Scroll down the page, and under the New Network header, enter http://127.0.0.1:7545. This is the endpoint URL that Ganache (desktop version) is listening at. Once this is entered, click the “X” button to close the window.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig18_HTML.jpg
Figure 7-18

Entering the endpoint URL for Ganache

When you now click the down arrow again, you will see a new item named “http://127.0.0.1:7545” (see Figure 7-19). Select it.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig19_HTML.jpg
Figure 7-19

Selecting the newly added RPC to connect to Ganache

You will now see that your existing account has 0 ETH (see Figure 7-20). This is because your existing account is not valid in this new blockchain (which Ganache is hosting).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig20_HTML.jpg
Figure 7-20

The existing account in MetaMask has no Ethers in the blockchain hosted by Ganache

You need to import the account(s) from Ganache into MetaMask if you want to see their balance. To do so, click the account icon in MetaMask and select Import Account (see Figure 7-21).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig21_HTML.jpg
Figure 7-21

Importing an account in MetaMask

In the New Account page, enter the private key of the first account in Ganache (see Figure 7-22). Then, click IMPORT.
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig22_HTML.jpg
Figure 7-22

Entering the private key of the first account in Ganache

The account from Ganache should now be imported into MetaMask (see Figure 7-23).
../images/471881_1_En_7_Chapter/471881_1_En_7_Fig23_HTML.jpg
Figure 7-23

The account in Ganache imported into MetaMask

You can try to import the other accounts from Ganache into MetaMask. You then send Ethers from one account into another.

The ability to connect MetaMask to Ganache is very useful, especially in later chapters where we talk about interacting with your Smart Contracts via the web3.js APIs.

Summary

In this chapter, you learned how to test your Smart Contract in a stand-alone blockchain hosted by Ganache. Using Ganache allows you to simulate running a blockchain without accessing a real one. And it makes testing your Smart Contracts efficient and effortless.

..................Content has been hidden....................

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