how to play ganache in browser

When developing a Web3 project, it helps to have a local blockchain devnet For testing. Ganache is one of the most popular tools for this in the Ethereum ecosystem and Truffle’s part. Ganache allows you to set up a native blockchain with various settings to fully test your smart contracts before deployment.

Viewing the output of the local blockchain in the terminal helps you understand how your project will behave in a live environment. Even more useful is the ability to set the output to a variable to manipulate some front-end code. Some users may not be aware that you can do this by running ganache in your browser.

This article explains how to run Ganache in your browser and highlights three great new features that will make developing your Web3 projects easier.

ganache in browser

Running a local blockchain instance to test your smart contracts is an essential step in the Web3 development process. By testing this way, you confirm that things are working correctly before using a node service, such as Infura, to deploy your contracts on a testnet either mainnet, This minimizes the risk of exceeding the daily limits and ensures that you only need to deploy once. Ganache is an excellent tool that emulates the Ethereum network and allows developers to:

However, many people using this tool may be unaware that since v7.0.0.0, Ganache can also run in your browser. Running in a browser allows you to set the output of the local blockchain to a variable that you can use to test your frontend code. This visual process helps you understand how your users will interact with your project and enables you to test your dApp completely offline (when using a local instance).

By first running Ganache in the browser and fine-tuning your dapp’s response, you can easily switch the provider to your node service API when things are working as intended. Additionally, since the latest update to Ganache (v7.3.2 at the time of writing), you can now fork the Ethereum mainnet when running Ganache in the browser. It allows you to interact with real accounts and contracts through its front-end code.

Project

In this section, we will build a basic smart contract using Truffle and its VS Code extension. Then, we’ll first deploy our contract to Ganache via the command line. Later, we will create a simple front end to use Ganache in the browser and interact with our deployed contract.

Requirements

For this project, we will be using the following:

Step 1 – Installation

First, we can run the command node --version In our terminal to make sure that NodeJS and NPM are properly installed on our machine.

Next, we will install Truffle and Ganache by running the following commands:

npm install -g truffle ganache

Checking Version Numbers with Truffle and Ganache truffle --version And ganache --version respectively will tell us if both the tools were installed successfully.

Next step is to install VS Code, then navigate to extension Tab into the editor and search Truffle for VS Code,

Truffle for VS Code

Now with everything set up, we are ready to start work on the project.

Step 2 – Install the Project

With the Truffle for VS Code extension, we can easily create a new Truffle project through the VS Code command palette. press ctrl + shift + P To open the command palette in the editor, type more truffle To see a list of commands we can use. to select Truffle: New Solidity Project and then create a basic project to create a new project in the desired folder.

fungus

This creates an initial project with a simple folder structure and example code that we can use if we wish.

ability to use console.log There is another great new feature recently available for Ganache in our smart contract code. Before we create the smart contract for our project, let’s set it up by installing the required packages. Navigate to the project folder in Terminal and type the following command:

npm install @ganache/console.log

Step 3 – Write the Smart Contract

The smart contract for our project will be a basic one that we can donate some ETH to and request to see the balance.

In contracts folder, create a new file and call it SimpleContract.sol, Next, fill it in with the following smart contract code:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
 
import '@ganache/console.log/console.sol';
 
contract SimpleContract {
 
 
  constructor() {
    console.log('\n\n#################################################\n'
    '####         Now Deploying Contract          ####\n'
    '#################################################'
    );
  }
 
 
  function donate() public payable {
    console.log('Successfully Donated ', msg.value);
  }
 
 
  function getBalance() public view returns (uint256) {
    console.log("This contract's balance is:", address(this).balance);
    return address(this).balance;
  }
 
  // Needed in order to receive payments
  receive() external payable {}
 
}

The code in our smart contract is relatively simple. It displays a message in the console when we deploy our smart contract, provides functionality to donate ETH and query the balance, and prints the message in the console when the function is called.

Step 4 – Deploy to Ganache

After installing the Truffle for VS Code extension, we can easily deploy by right-clicking on the smart contract file and choosing Deploy contract. However, if we want to view our console messages, we have to use our own terminal instead of the terminal built into VS Code. This could potentially change in the future, but for now, we need to create a simple migration script to do the deployment.

In migration folder, create a new script called 1_SimpleContract.js and input the following code:

const SimpleContract = artifacts.require("SimpleContract");

module.exports = function (deployer) {
  deployer.deploy(SimpleContract);
};

Next, open a new terminal window and start ganache:

This Terminal window is where we’ll see our console messages appear when they appear. Now we have two terminal windows open: one with ganache running and the other open in the folder of our truffle project.

In the Terminal window that opens instead of our Truffle project, type the following command to start the deployment:

truffle migrate --network development 

If the deployment is successful, we can see our console message printed in the terminal:

to console

Great! Our contract is live on our local Ganache instance! We will keep Ganache running for now so that we can interact with our contract using the browser. Before we get to that, copy contract address from the output in terminal where we typed migrate command. We will use this address to point to the front end of our smart contract.

contract address

Step 5 – Build the Frontend

establish

For the front end of this project, we will be using React. Navigate to a new empty folder and type:

npx create-react-app ganache-browser-test

Next, we will install Web3.JS to easily interact with our smart contract. Navigate to our new project folder and install Web3.JS with this command:

cd ganache-browser-test
npm install web3

Newer versions of create-react-app do not work well with Web3.JS, so we need to install a specific version of React Scripts. We can do this with this command:

npm install --save-exact react-scripts@4.0.3

Finally, to use Ganache in our browser, we’ll install it directly as a dependency:

Alternatively, you can add a CDN link to the HTML to access Ganache from the browser:

<script src="https://cdn.jsdelivr.net/npm/ganache@7.3.2/dist/web/ganache.min.js"></script>

Before we start working on the frontend code, we need to create a file containing the ABI of our contract so that we can interact with our smart contract. We can copy that file directly from our truffle project. navigate to construction contract folder in our truffle project and copy SimpleContract.json file.

explorer

Next, open our frontend project in the editor and create a new folder called abi, paste in that folder SimpleContract.json file. The file structure for our front end now looks like this:

open editor

frontend code

With all kind of setup, we can start working on our front end. First, open app.js file in SRC Replace the folder and boilerplate code with:

, } export default app;” data-lang=”text/javascript”>

import { useState } from 'react';
import './App.css';
import SimpleContract from './abi/SimpleContract.json';
 
const ganache = require('ganache');
const Web3 = require('web3');
 
const options = {}  
const provider = ganache.provider(options);
 
const web3 = new Web3('http://127.0.0.1:8545');  
 
const CONTRACT_ADDRESS = 'YOUR_CONTRACT_ADDRESS'  
const USER_ADDRESS = web3.utils.toChecksumAddress('YOUR_ACCOUNT_ADDRESS');
 
const contractInstance = new web3.eth.Contract(SimpleContract.abi, CONTRACT_ADDRESS);
 
 
const App = () => {
  const [contractBalance, setContractBalance] = useState(0);
 
  const donate = async () => {
    const donationAmount = document.querySelector('#donationAmount').value;
 
    const response = await contractInstance.methods.donate().send({
      from: USER_ADDRESS,
      value: web3.utils.toWei(donationAmount)
    });
 
    console.log('donate response:', response);
 
  };
 
 
  const getBalance = async () => {
    const response = await contractInstance.methods.getBalance().call();
 
    console.log('getBalance response:', response);
 
    setContractBalance(web3.utils.fromWei(response));
 
  }
 
 
  return (
    <div className="App">
      <header className="App-header">
        <h1>Ganache In The Browser</h1>
 
        <div>
          <input
            type="number"
            id='donationAmount'
            defaultValue={0.01}
          />
          <label htmlFor="donationAmount">ETH</label>
          <br></br>
          <button
            id='donate'
            type="button"
            onClick={donate}
          >
            Donate
          </button>
        </div>
 
        <div>
          <button
            id='getBalance'
            type="button"
            onClick={getBalance}
          >
            Get Contract Balance
          </button>
        </div>
 
        <div>
          <p>
            {contractBalance} ETH
          </p>
        </div>
       
      </header>
    </div>
  );
}
 
export default App;

Leave a Comment