Build a simple UI to connect with Smart Contract (Remix + WEB3)

Posted on by

I’ve been messing around a bit more with Solidity and Web3, and wanted to make a simple tutorial on how to connect smart contract code you may have on Remix IDE(https://remix.ethereum.org).

Prerequisites to installing a Web3 Provider for our solidity smart contract:

  • Install Node (https://nodejs.org/en/)
  • Install the Ethereum Ganache Cli (https://github.com/trufflesuite/ganache-cli). This will essentially allow you to connect with the Ethereum smart contract, as well as create default private and public keys. To do so, go on your command line, and run: npm install -g ganache-cli
  • After that, run: ganache-cli on your command line. If there are any errors make sure to add npm’s bin to your path.

Next Steps

    1. Open up another tab on your command line (Whether it may be terminal/gitbash), and create a directory for a new project, and then cd into that directory. We are opening another tab, because we want our ethereum ganache to be running, so we can hook it up with our smart contract as well as our front end javascript code. Add a simple index.html to this directory.
    2. Go on Remix, and make sure your smart contract code is on there. From there, click on Run -> Environment -> Choose Web3 Provider -> Click Ok (Default’s to localhost:8545)
    3. Deploy the contract on Remix, by clicking “Deploy”. From there you should see the notification of a contract being created on your command line. Picture: 
    4. Go to the index.html that you created inside step #1, and reference the web3 CDN.


. Awesome! Now you’re ready to get started to call your contract, and any functions inside your contract.

  1. Install MetaMask. From there, set up MetaMask, and once you click on the browser plugin change it from the Main Ethereum Network -> LocalHost:8545
  2. After that go to your Remix -> Compile -> Details -> Copy the ABI Code. Save it somewhere.
  3. Go on Remix -> Run -> And copy the contract address you deployed.

Now paste this code into your index.html:

if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);

  // set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.defaultAccount = web3.eth.accounts[0];
var bettingSchemeContract = web3.eth.contract(COPYPASTEABICODEHERE)
var bettingScheme = bettingSchemeContract.at('PASTE CONTRACT ADDRESS HERE');
console.log(bettingScheme);
} else {
console.log("Install MetaMask!")
}

 

Now you’re ready to interact with your contract with ease by directly colling bettingScheme.function()

Comments

Leave a comment

Your email address will not be published.
Required fields are marked *