πŸ’ΎBackend Integration Guide

πŸ’‘ Integration guide for an application where the user has no direct contact with the blockchain, and that requires backend interactions with the blockchain.

In the following, we will show you how to build a REST API using Express.js to enable the framework-agnostic communication with your newly deployed smart contracts. This API serves as an intermediary, enabling your backend system of any framework or programming language to easily interact with your newly deployed smart contracts.

Step 1: Setup Project

Initialize a new Node.js project and install required packages.

mkdir my-smart-contract-api
cd my-smart-contract-api
npm init -y
npm install express web3 dotenv cors

Step 2: Configure Environment

Create a .env file in your project root and add the following:

INFURA_ENDPOINT=https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY
CONTRACT_ADDRESS=YOUR_CONTRACT_ADDRESS
PRIVATE_KEY=YOUR_PRIVATE_KEY
PORT=3000

Step 3: Initialize Express and Web3

In index.js, set up Express, Web3, and your contract.

// Imports
const express = require('express');
const Web3 = require('web3');
const cors = require('cors');
require('dotenv').config();

// Initialize the Express app
const app = express();
app.use(express.json());
app.use(cors());

// Initialize Web3 functionalities
const web3 = new Web3(process.env.INFURA_ENDPOINT);
const account = web3.eth.accounts.privateKeyToAccount(process.env.PRIVATE_KEY);
web3.eth.accounts.wallet.add(account);
const contractABI = [/* ABI array here */];
const contractAddress = process.env.CONTRACT_ADDRESS;
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Start the server
app.listen(process.env.PORT, () => {
  console.log(`Server running on port ${process.env.PORT}`);
});

Step 4: Define API Endpoints

Implement endpoints to interact with each function of your smart contract.

// Write to smart contract
app.post('/api/writeFunction', async (req, res) => {
  try {
    const { arg1, arg2 } = req.body;
    await contract.methods.writeFunction(arg1, arg2)
      .send({ from: account.address, gas: 1000000 })
      .then((tx) => res.send(tx));
  } catch (error) {
    res.status(500).send(error.toString());
  }
});

// Read from smart contract
app.get('/api/readFunction', async (req, res) => {
  try {
    const data = await contract.methods.readFunction().call();
    res.send(data);
  } catch (error) {
    res.status(500).send(error.toString());
  }
});

Step 5: Deploying your REST API

Once you have defined all endpoints you need, deploy your API on the backend hosting service of your choice.

In the following, we show the process for a deployment on Heroku.

Prerequisites:

  • Heroku CLI installed on your computer.

  • A Heroku account.

1. Install and Login to Heroku CLI

If you haven't already, download and install the Heroku CLI from Heroku's website. Once installed, open your terminal and log in:

heroku login

This will open a web browser for you to log in to your Heroku account.

2. Initialize a Git Repository

Navigate to your project directory and initialize a Git repository if you haven’t done so:

cd path/to/your/project
git init
git add .
git commit -m "Initial commit"

3. Create Heroku App, optionally with Custom Name and Region

Create a new Heroku application with your preferred name and region. Replace your-app-name with the desired name and choose either us or eu for the region:

heroku create your-app-name --region eu

4. Set Environment Variables in Heroku

Configure the environment variables required by your application directly in Heroku. Ensure you replace these placeholder values with your actual configuration details:

heroku config:set INFURA_ENDPOINT="Your Infura Endpoint"
heroku config:set CONTRACT_ADDRESS="Your Smart Contract Address"
heroku config:set PRIVATE_KEY="Your Private Key"
# Set other necessary environment variables

5. Deploy to Heroku

Deploy your application to Heroku by pushing your code:

git push heroku master

6. Verify the Deployment

After the deployment process completes, ensure that your application is running correctly:

heroku logs --tail

This command shows real-time logs from your Heroku app, which is useful for troubleshooting.

Troubleshooting Common Issues

  • Incorrect Commands: Verify that all commands are executed correctly without typos.

  • Environment Variables: Ensure all environment variables are set accurately on Heroku.

  • Heroku Logs: Check the Heroku logs for detailed error information if you encounter issues.

  • Resource Limitations: Sometimes, the selected region may have limitations. If you face deployment issues, try switching the region or reach out to Heroku support for assistance.

Step 6: Integrating your API with Existing Web2 Systems

After the deployment was successful, we integrate the REST API with your existing Web2 systems to interact with the smart contract.

Utilize HTTP clients like axios or fetch our similar services for your programming language and framework of choice in your backend to call our freshly deployed REST API:

const axios = require('axios');

async function callSmartContractFunction() {
  try {
    const response = await axios.post('<https://your-heroku-app.herokuapp.com/api/functionName1>', {
      arg1: 'value1',
      arg2: 'value2'
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}
callSmartContractFunction();

Conclusion

With this setup, you've created a fully functional Express.js REST API that interacts with your smart contracts. This API enables your existing backend systems to interact with blockchain technology seamlessly. Remember to test thoroughly before deploying to production. And if you have any questions, please don’t hesitate to reach out to us via developers@onino.io!

Last updated