Executing smart contracts in your browser using Truffle, Ganache, Browserify, and Web3
Tags: trufflesuite, ethereum, javascript, blockchain
Published: 2021-06-26 02:19:59

---
title: Executing smart contracts in your browser using Truffle, Ganache, Browserify, and Web3
published: true
date: 2021-06-20 16:10:18 UTC
tags: trufflesuite,ethereum,javascript,blockchain
canonical_url: https://medium.com/coinmonks/executing-smart-contracts-in-your-browser-using-truffle-ganache-browserify-and-web3-200574d13064
---

_The opinions stated here are my own, not those of my company._

There are a variety of tools to build a blockchain-based web app. For example, you can see a simple banking app below:

![](https://cdn-images-1.medium.com/max/938/1*iC2AxAJHP_s3IvhPPRWqmg.png)<figcaption>Simple Bank on the web, with deposit/withdraw smart contracts</figcaption>

These contracts were written in [Solidity](https://docs.soliditylang.org/en/v0.8.3/) and executed through [Truffle](https://www.trufflesuite.com/). While I could verify they worked, getting them to run in a browser environment was hard. In fact, there is basically no documentation on the integration of these technologies.

This blog post gives you a setup of everything together, but does not go into the specifics of building a simple bank. Instead this will be for a more generic example.

### Truffle

Let’s say you already have your MyContract.sol Solidity contract. Use Truffle to deploy it to your blockchain network. In my case, I am using Ganache. This runs locally (on port 7545).

When you run the truffle migrate command, take note of several properties of the output.

```
$ truffle deploy

   Replacing 'MyContract'
   ----------------------
   > transaction hash: 0x562f463faa3666e948a08ea96f96ae239aff9f48298f6096ecbd09404903027e
   > Blocks: 0 Seconds: 0

   **> contract address: 0x941F4963540B1df054343d115767B9cb3E3cDc3D**  
> block number: 3
   > block timestamp: 1617929065
   **> account: 0xA866B5C54e06fF40cA96d93b7B7FaE1809D0d858**  
> balance: 99.98373884
   > gas used: 390433 (0x5f521)
   > gas price: 20 gwei
   > value sent: 0 ETH
   > total cost: 0.00780866 ETH

   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost: 0.01626116 ETH
```

Save the contract address and account address. Since we’ll be using a web browser, create a new index.js file and save these as constants:

{% gist https://gist.github.com/Fleker/e818c1dd8c978b0805d0eb17d514a714 %}

Create a package.json file in our root project directory to install our dependencies. NPM can use [package files](https://docs.npmjs.com/about-packages-and-modules) to define your project and what it needs. It allows us to define dependencies and build scripts in a single file for greater convenience. This file is used in the industry.

{% gist https://gist.github.com/Fleker/61907a25bc08904d059c9769cee6f8a7 %}

Be sure to run npm install to download everything.

Note that, when Truffle builds your contracts, there is created a build/contracts/MyContract.json. Take note of this file, we’ll be using it later.

### Setting up Web3

[Web3](https://web3js.readthedocs.io/en/v1.3.4/index.html) is essentially the binding between the [Ganache test network](https://www.trufflesuite.com/ganache) and your smart contracts. It lets you access your accounts and execute contracts in a Node environment.

Note that a Node environment is different from a browser environment in subtle but important ways even though they both run JavaScript. We can use a tool like [Browserify](http://browserify.org/) to _transpile_ our index.js into a bundle.js that can run in a browser.

This is what the scripts.build field in package.json means. When you run npm run build, we execute that command.

To connect to our Ganache network, we can add a single line to our index.js :

{% gist https://gist.github.com/Fleker/4a99b50d6168c5a6a47ac9a9b12b3721 %}

To aid debugging, I recommend setting up window.web3 = web3 in your index.js as well. This will let you more effectively debug and execute commands in browser DevTools.

![](https://cdn-images-1.medium.com/max/511/1*UvREYvu5pU6m4FrOvHJN-A.png)<figcaption>You can execute commands directly in DevTools to get a feel for them</figcaption>

How do we know this worked? Let’s add an element to display our account & balance with an index.html file:

{% gist https://gist.github.com/Fleker/9342e7516473f15c52fafa6fe85a1a30 %}

Update our index.js file with an event listener. When the page loads, execute the updateBalance function. By extracting this to a separate function, we can call this in response to contract execution.

{% gist https://gist.github.com/Fleker/16153b35d5d4bef594e2ced68bbabac2 %}

Now regenerate bundle.js and open index.html in the browser. You should see the address and balance appear automatically on the screen.

If you have made it to this point, you’ve successfully setup Web3.

### Setting up contracts

Now that we’ve connected to Web3, let’s connect to the contract itself. Here is where our previously created JSON file will be handy.

Note that again we are binding the object to the window (objects in JavaScript are [pass-by-reference](https://medium.com/nodesimplified/javascript-pass-by-value-and-pass-by-reference-in-javascript-fcf10305aa9c)) to help debug commands right in the console.

The Web3 contract instantiation requires the contract ABI, which is part of the larger JSON bundle. We also pass in the contract address we obtained earlier:

{% gist https://gist.github.com/Fleker/2ef4be7a31506aad5647f1afd6e2fc01 %}

Note that I am note entirely sure that my use of [defaultAccount](https://web3js.readthedocs.io/en/v1.3.4/web3-eth-contract.html#defaultaccount) is accurate here. But my code does work so I won’t complain.

Now our contracts should be in our execution environment, so we can start executing contracts.

### Executing smart contracts

There are generally two kinds of smart contract commands: calls and sends. A call is generally mapped to a view in Solidity: a method that doesn’t involve a transaction. This may be seen as a “getter”. Sends actually create a transaction and change the contract state, like a Solidity payable.

We can see some of each in our contract. First let’s add a button and a label for our response on the webpage:

{% gist https://gist.github.com/Fleker/a5ab6d3ec7fafdb71dac717d7ccbf65f %}

{% gist https://gist.github.com/Fleker/55f76d8adbb8505445ed6e7ae38d02fb %}

You can see the entire process play out in the click event listener on the button. We also disable it during execution as a way of debouncing.

We send an event with our account and a hard-coded value. Later we can call a second method to read the balance and display on the page.

There are a number of asynchronous operations here. Reading [the guide on Promises from Mozilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) will provide a good background here.

### Troubleshooting

Along my development path, I came across an obscure error when trying to do anything with my contract:

> Error: Returned values aren’t valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.

It took me some time to ascertain why this was happening. Googling the error did not provide a single answer. It turned out that my contract address was wrong. I needed to use the one from Truffle and not my wallet address from Ganache.

I hope this guide helps you at least get started. As this programming environment is new, there are scant resources. While some tools may have their own docs, there isn’t much in the way of integration guides.

This is what I got from my own experience and development rather than any insider information on any tool. Of course, at the rapid pace of development, this post may be quickly obsolete.

> Join [Coinmonks Telegram Channel](https://t.me/coincodecap) and learn about crypto trading and investing

#### Also, Read

- [Grid Trading Bots](https://blog.coincodecap.com/grid-trading) | [Cryptohopper Review](https://medium.com/coinmonks/cryptohopper-review-a388ff5bae88) | [Crypto Trading Bot](https://blog.coincodecap.com/best-crypto-trading-bots)
- [Crypto Copy Trading Platforms](https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c) |[How to buy Bitcoin on WazirX](https://medium.com/coinmonks/buy-bitcoin-on-wazirx-2d12b7989af1)
- [CoinLoan Review](https://medium.com/coinmonks/coinloan-review-18128b9badc4) | [Crypto.com Review](https://medium.com/coinmonks/crypto-com-review-f143dca1f74c) | [Huobi Margin Trading](https://medium.com/coinmonks/huobi-margin-trading-b3b06cdc1519)
- [YouHodler vs CoinLoan vs Hodlnaut](https://medium.com/coinmonks/youhodler-vs-coinloan-vs-hodlnaut-b1050acde55a) | [Cryptohopper vs HaasBot](https://blog.coincodecap.com/cryptohopper-vs-haasbot)
- [Top paid cryptocurrency and blockchain courses](https://blog.coincodecap.com/blockchain-courses) | [Binance Review](https://medium.com/coinmonks/binance-review-ee10d3bf3b6e)
- [MXC Exchange Review](https://medium.com/coinmonks/mxc-exchange-review-3af0ec1cba8c) | [Pionex vs Binance](https://blog.coincodecap.com/pionex-vs-binance) | [Pionex Arbitrage Bot](https://blog.coincodecap.com/pionex-arbitrage-bot)
- [How to buy Bitcoin in India?](https://medium.com/coinmonks/buy-bitcoin-in-india-feb50ddfef94) | [WazirX Review](https://medium.com/coinmonks/wazirx-review-5c811b074f5b) | [BitMEX Review](https://blog.coincodecap.com/bitmex-review)
- [Bitcoin exchange in India](https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9) | [Bitcoin Savings Account](https://medium.com/coinmonks/bitcoin-savings-account-e65b13f92451) | [HitBTC Review](https://medium.com/coinmonks/hitbtc-review-c5143c5d53c2)

* * *