Executing First Blockchain Transaction

Use Contract address and ABI to send your first blockchain transaction

In this section, we'll use web3.js to send our first blockchain transaction. In previous section we initialized our web3 object, now we'll use that to create an instance of our deployed contract and then calling the methods defined in our smart contract.

Declare Contract Address

Address of the deployed contract on ethereum blockchain

/** 
 * This is a random Address.
 * Change this address to your deployed contract address
 **/
const contractAddress = "0xa67767B5ed6Fa6Fc19baBD4F18ffe72EAbC85FdA";

Declare Contract ABI

The Contract Application Binary Interface (ABI) is the standard way to interact with contracts in the Ethereum ecosystem, both from outside the blockchain and for contract-to-contract interaction.

const contractAbi = [
	{
		"constant": false,
		"inputs": [
			{
				"internalType": "string",
				"name": "newQuote",
				"type": "string"
			}
		],
		"name": "setQuote",
		"outputs": [],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "owner",
		"outputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "quote",
		"outputs": [
			{
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	}
]

Make sure web3 is Initialized before this step

Form an Instance of the contract

let myContract = new web3.eth.Contract(contractAbi, contractAddress);

Send the transaction to update the current quote and current owner

async function setQuote() {
	await myContract.methods.setQuote("Transaction fees from users hampers UX!").send({from: userAccount});
}

Call the function of our contract to retrieve current quote and current owner

async function getQuote() {
	return await myContract.methods.getQuote().call({from: userAccount});
}

Complete Working Code Snippet

This example is built using ReactJS. Below is a simple function component in React. To keep it simple, css code is not mentioned in the code.

import React, { useState, useEffect } from "react";
import Web3 from 'web3'
let myContract;
/**
 * This is a random Address.
 * Change this address to your deployed contract address
 **/
const contractAddress = "0xa67767B5ed6Fa6Fc19baBD4F18ffe72EAbC85FdA";
const contractAbi = [
	{
		"constant": false,
		"inputs": [
			{
				"name": "newQuote",
				"type": "string"
			}
		],
		"name": "setQuote",
		"outputs": [],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "getQuote",
		"outputs": [
			{
				"name": "currentQuote",
				"type": "string"
			},
			{
				"name": "currentOwner",
				"type": "address"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "owner",
		"outputs": [
			{
				"name": "",
				"type": "address"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "quote",
		"outputs": [
			{
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	}
]

let web3;

function App() {
  const [owner, setOwner] = useState("Default Owner Address");
  const [quote, setQuote] = useState("This is a default quote");
  const [newQuote, setNewQuote] = useState("");

  useEffect(() => {
    if (window.ethereum) {
      // Modern DApp browsers
      web3 = new Web3(window.ethereum);
      try {
        window.ethereum.enable().then(()=>{
          startApp();
        });
      } catch (error) {
        // User denied account access
        console.log(error);
      }
    } else if (window.web3) {
      // Legacy dapp browsers
      web3 = new Web3(window.web3.currentProvider);
      startApp();
    } else {
      // Non-dapp browsers
      console.log("Non-Ethereum browser detected. You should consider trying MetaMask!");
    }
  }, []);

  const onQuoteChange = event => {
    setNewQuote(event.target.value);
  };

  async function startApp() {
    myContract = new web3.eth.Contract(contractAbi, contractAddress);
    // Get quote from blockchain on app start
    getQuote();
  }

  async function getQuote() {
    let result = await myContract.methods.getQuote().call();
    setOwner(result.currentOwner);
    setQuote(result.currentQuote);
  }

  async function setQuoteOnBlockchain() {
    await myContract.methods.setQuote(newQuote).send({from: window.ethereum.selectedAddress});
    getQuote();
  }

  async function onButtonClickMeta() {
    setQuoteOnBlockchain();
  }

  return (
    <div className="App">
      *Use this DApp only on Kovan Network
      <header className="App-header">
        <h1>Quotes</h1>
        <section className="main">
          <div className="mb-wrap mb-style-2">
            <blockquote cite="http://www.gutenberg.org/ebboks/11">
              <h4>{quote} </h4>
            </blockquote>
          </div>

          <div className="mb-attribution">
            <p className="mb-author">- {owner}</p>
          </div>
        </section>
        <section>
          <div className="submit-container">
            <div className="submit-row">
              <input size="100"
                border-radius="15"
                type="text"
                placeholder="Enter your quote"
                onChange={onQuoteChange}
                value={newQuote}
              />
              <button type="button" className="button" onClick={onButtonClickMeta}>Submit</button>
            </div>
          </div>
        </section>
      </header>
    </div >
  );
}

export default App;

Congratulations! You Just Built Your First DApp

Last updated