A Developer Guide to Connecting a Smart Contract to Angular

Posted By : Gopal

May 28, 2021

Connecting Angular Application to a Smart Contract using Web3 Library

Smart contracts are digitally self-executing contracts that run on the Ethereum blockchain. Once they've been created they cannot change. Once they are deployed to a blockchain, their code cannot be updated like any other application.

 

How a Smart Contract Works?

 

A smart contract works like a vending machine by dispensing the item to a buyer and transferring cryptoCurrency payments instantly to a seller.


Steps to Integrate the Angular App to a Smart Contract  

 

1) First step is to install web3.js using npm.

 

npm install web3 (This is the main package of web3.js)

 

2) You need a wallet account in order to make transactions.

 

I am using MetaMask

 

How to connect metamask to Application

 

<button (click)= "openMetaMask()"> Connect Wallet</button>

openMetaMask(){
    this.contractService.openMetamask().then(resp =>{

    })
  }

 

Create a service and import web3.js into your service file. I've created a service called contract.service.ts.

 

import { Injectable } from '@angular/core';
import Web3 from "web3";

declare const window: any;


@Injectable({
    providedIn: 'root'
})
export class ContractService {
    window:any;
    constructor() { }
    private getAccounts = async () => {
        try {
            return await window.ethereum.request({ method: 'eth_accounts' });
        } catch (e) {
            return [];
        }
    }

    public openMetamask = async () => {
        window.web3 = new Web3(window.ethereum);
        let addresses = await this.getAccounts();
        console.log("service",addresses)
        if (!addresses.length) {
            try {
                addresses = await window.ethereum.enable();
            } catch (e) {
                return false;
            }
        }
        return addresses.length ? addresses[0] : null;
    };
    
}

 

What is ABI and why it needs to interact with contracts?

 

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

 

ABI is the interface between two program modules, one is often at the level of machine code. The interface is the de facto method for encoding/decoding data into/out of the machine code.

 

We need two things to interact 

 

ABI
Address

 

and we can use Address and ABI in the same services

 

import { Injectable } from '@angular/core';
import Web3 from "web3";
declare const window: any;
const Address ='there will be address'
const abi = [
    {
      "inputs": [],
      "stateMutability": "nonpayable",
      "type": "constructor"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": false,
          "internalType": "",
        }
      ],
      "name": "Token",
      "type": "event"
    },
]


ABI would be like that there  is name Token which is actually the function name 

 


@Injectable({
    providedIn: 'root'
})
export class ContractService {
    window:any;
    constructor() { }

    public Token = async () => {
        try {
                const contract = new window.web3.eth.Contract(
                    abi,
                    Address,
                );
                const token = await contract.methods.Token().call();
                console.log("token",token)
                return token
            
        }
        catch (error) {
            const errorMessage = error.message;
            console.log(errorMessage)
       
        }
    }
}

 

We are using the .call method instead of the .send method
.call for getting something and .send to send something.
 

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

April 4, 2024 at 08:10 am

Your comment is awaiting moderation.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.

Chat with Us
Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text