|
Jagveer Singh Oodles

Jagveer Singh (Backend-Sr. Lead Development)

Experience:6+ yrs

Jagveer Singh is a skilled Backend developer with approx 4+ years of experience. He is knowledgeable in various cutting-edge technologies such as Blockchain, solidity, ethereum, hardhat, Advance Spring-Boot, hibernate, Apache, and databases. He is proficient in developing smart contracts, implementing APIs, testing and deploying web services, enhancing codes, and delivering on various client projects like v-empire and nitroEx. His valuable contributions to his company can be attributed to his proficiency in exploring new technologies through reading, coupled with his analytical and creative thinking skills.

Jagveer Singh Oodles
Jagveer Singh
(Sr. Lead Development)

Jagveer Singh is a skilled Backend developer with approx 4+ years of experience. He is knowledgeable in various cutting-edge technologies such as Blockchain, solidity, ethereum, hardhat, Advance Spring-Boot, hibernate, Apache, and databases. He is proficient in developing smart contracts, implementing APIs, testing and deploying web services, enhancing codes, and delivering on various client projects like v-empire and nitroEx. His valuable contributions to his company can be attributed to his proficiency in exploring new technologies through reading, coupled with his analytical and creative thinking skills.

LanguageLanguages

DotENGLISH

Fluent

DotHindi

Fluent

Skills
Skills

DotSpring Boot

80%

DotERC-1155

80%

DotJava

80%

DotSmart Contract

100%

DotChainlink

80%

DotUniswap

80%

DotGanache

80%

DotOpenZeppelin

80%

DotTruffle

80%

DotSolidity

100%

DotZKsync

80%

DotVyper

80%

DotHardhat

80%

DotAnchor

80%

DotGnosis Safe

80%

DotEtherscan

80%

DotTRON (TRX)

80%

DotEthers.js

100%

DotThe Graph

80%

DotBitcoin (BTC)

100%

DotEthereum

80%

DotMetaMask

80%

DotIPFS

80%

DotChainstack

80%

DotCoinbase API

80%

DotBlockchain

80%

DotRemix IDE

80%

Dotweb4.js

80%

DotERC-721

80%

DotStellar (XLM)

80%
ExpWork Experience / Trainings / Internship

Jun 2020-Present

Sr. Lead Development

Gurugram


Oodles Technologies

Gurugram

Jun 2020-Present

Aug 2018-Jul 2020

Software Developer

Noida


DiGi Spice

Noida

Aug 2018-Jul 2020

EducationEducation

2014-2018

Dot

Dr. A. P. J. Abdul Kalam Technical University

B.Tech-Computer Science

Top Blog Posts
Understanding Decentralized Oracle Network Development with Chainlink

Blockchains, while secure, cannot access real-world data on their own. This limitation creates challenges for blockchain development (dApps) that require external information, like price feeds or weather data. Chainlink, a leading decentralized oracle network (DON), solves this problem by securely connecting smart contracts to off-chain data sources.

 

You may also like | Oracle Development Using Ethereum Smart Contracts

 

How Chainlink Works

 

Chainlink uses a decentralized network of independent nodes, known as oracles, to fetch, verify, and deliver external data to smart contracts. These oracles bridge the gap between blockchain and real-world information, ensuring data accuracy and preventing tampering. Chainlink's decentralized structure avoids single points of failure, making the system more reliable.

 

Also, check | Blockchain Oracles | Making Smart Contracts Talk to the World


Architecture of Chainlink's Decentralized Oracle Network

 

                     							+-----------------------------+
                     							|     Decentralized Oracle     |
                     							|          Network (DON)       |
                     							+-----------------------------+
                                       							|
                         							+-------------+-------------+
            							+------------v----------+   +------------v----------+
            							|   Oracle Node 1        |   |   Oracle Node 2        |
            							|   - Fetches data       |   |   - Fetches data       |
            							+------------------------+   +------------------------+
                         							|                            |
            							+------------+----------+   +------------+----------+
            							|  Aggregation Contract  |   |  Aggregation Contract  |
            							+------------------------+   +------------------------+
                         							|                            |
              							+----------v---------+     +------------v--------+
              							|   Smart Contract    |     |   Smart Contract    |
              							+---------------------+     +---------------------+


Steps to Build with Chainlink

 

  • Smart Contract Development: Create a smart contract specifying the conditions for data requests. Chainlink libraries enable smart contracts to communicate with external oracles.
  • Chainlink Node Setup: Set up oracles to retrieve data from trusted sources like APIs. Multiple nodes ensure decentralization and data accuracy.
  • Requesting Data: Smart contracts send data requests, which Chainlink nodes process by retrieving the required information from external sources.
  • Data Aggregation: The aggregation contract collects and verifies data from different nodes, ensuring accuracy before delivering it to the smart contract.

     

Also, Read | A Comprehensive Guide to Blockchain Oracle
 

Conclusion

 

Chainlink empowers blockchain developers to securely integrate off-chain data into their dApps. Its decentralized oracle network is crucial for industries like DeFi, insurance, and gaming, making Chainlink a vital component for creating trust-minimized, real-world applications. If you are looking to build a decentralized Oracle network with Chainlink to empower your project, connect with our skilled smart contract developers to get started.  

Category: Blockchain
How to Create a Yield Farming Contract

Yield farming, also known as liquidity mining, is a popular method in decentralized finance (DeFi) where users can earn rewards by staking their cryptocurrency assets in a liquidity pool. This article will explain the concept of yield farming and provide an example of a simple yield farming smart contract. If you are looking to develop your DeFi project, explore our DeFi development services

 

How Yield Farming Works

 

In yield farming, users deposit their crypto assets into a DeFi protocol's smart contract, known as a liquidity pool. These assets are then utilized by the protocol for various operations such as lending, borrowing, or trading. In exchange, the protocol rewards users with interest or additional cryptocurrency tokens.

 

You may also like | Yield Farming | Fuelling the Decentralized Finance (DeFI) Space

 

Components of a Yield Farming Contract

 

A basic yield farming contract typically includes:

 

Liquidity Pool: Where users deposit their assets.

Reward Distribution: Reward concept to distribute rewards to users.

Staking Mechanism: Method used to stake allowed tokens.

Unstaking Mechanism: Allows users to withdraw their staked tokens and any earned rewards.

 

Also, Check | LSDFi  | Exploring Why It Is the Hottest DeFi

 

Sample Yield Farming Contract


 Below is a simple example of a yield farming contract written in Solidity, a widely used programming language for creating Ethereum smart contracts.

 

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IERC20 {
    function transferFrom(address senderAddress, address recipientAddress, uint256 value) external returns (bool);
    function transfer(address recipientAddress, uint256 value) external returns (bool);
}

contract YieldFarm {
    IERC20 public stakingToken;
    IERC20 public rewardToken;

    mapping(address => uint256) public stakedBalance;
    mapping(address => uint256) public rewards;
    uint256 public totalStaked;
    uint256 public rewardRate;

    event Staked(address indexed user, uint256 amount);
    event Unstaked(address indexed user, uint256 amount);
    event RewardClaimed(address indexed user, uint256 amount);

    constructor(IERC20 _stakingTokenAddress, IERC20 _rewardTokenAddress, uint256 _rewardRateValue) {
        stakingToken = _stakingTokenAddress;
        rewardToken = _rewardTokenAddress;
        rewardRate = _rewardRateValue;
    }

    function stake(uint256 amount) external {
        require(amount > 0, "Amount can not be zero");
        stakingToken.transferFrom(msg.sender, address(this), amount);
        stakedBalance[msg.sender] += amount;
        totalStaked += amount;
        emit Staked(msg.sender, amount);
    }

    function unstake(uint256 amount) external {
        require(stakedBalance[msg.sender] >= amount, "Insufficient staked balance");
        stakingToken.transfer(msg.sender, amount);
        stakedBalance[msg.sender] -= amount;
        totalStaked -= amount;
        emit Unstaked(msg.sender, amount);
    }

    function claimRewards() external {
        uint256 reward = calculateRewardTokens(msg.sender);
        rewards[msg.sender] = 0;
        rewardToken.transfer(msg.sender, reward);
        emit RewardClaimed(msg.sender, reward);
    }

    function calculateRewardTokens(address userAddress) public view returns (uint256) {
        return stakedBalance[user] * rewardRate;
    }
}

 

Also, Explore | Crypto Staking Platform Development: A Step-by-Step Guide 

 

Testing the Contract 

 

To test this contract, set up a development environment using tools like Hardhat. Here's a basic test script:

 

const { expect } = require("chai");

describe("YieldFarm", function () {
  let stakingToken, rewardToken, yieldFarm;
  let ownerAddress, user1, user2;

  beforeEach(async function () {
    [ownerAddress, user1, user2, _] = await ethers.getSigners();

    const Token = await ethers.getContractFactory("Token");
    stakingToken = await Token.deploy("Staking Token", "STK", 1000000);
    rewardToken = await Token.deploy("Reward Token", "RWD", 1000000);

    const YieldFarm = await ethers.getContractFactory("YieldFarm");
    yieldFarm = await YieldFarm.deploy(stakingToken.address, rewardToken.address, 1);

    await stakingToken.transfer(user1.address, 1000);
    await stakingToken.transfer(user2.address, 1000);
    await rewardToken.transfer(yieldFarm.address, 1000);
  });

  it("Stake and earn", async function () {
    await stakingToken.connect(user1).approve(yieldFarm.address, 100);
    await yieldFarm.connect(user1).stake(100);
    expect(await stakingToken.balanceOf(user1.address)).to.equal(900);
    expect(await stakingToken.balanceOf(yieldFarm.address)).to.equal(100);

    await yieldFarm.connect(user1).claimRewards();
    expect(await rewardToken.balanceOf(user1.address)).to.equal(100);
  });

  it("Should allow users to unstake tokens", async function () {
    await stakingToken.connect(user1).approve(yieldFarm.address, 100);
    await yieldFarm.connect(user1).stake(100);

    await yieldFarm.connect(user1).unstake(100);
    expect(await stakingToken.balanceOf(user1.address)).to.equal(1000);
  });
});

 

Also, Discover | DeFi Trends for 2024 and Beyond | Insights and Projections

 

Conclusion


Yield farming is a fundamental aspect of DeFi, enabling users to earn rewards by providing liquidity to protocols. The provided contract is a simplified example to illustrate the core concepts. In real-world applications, additional security measures and optimizations are essential. If you are looking for more information about smart contracts for DeFi development, connect with our skilled blockchain developers

Category: Blockchain
How To Build "Buy Me a Coffee" DeFi dApp Using Solidity

Blockchain technology enables the development of innovative applications like a decentralized "Buy Me a Coffee" application. This guide will walk you through developing and deploying a smart contract for this purpose using Alchemy, Hardhat, Ethers.js, and the Ethereum Sepolia testnet. By the end, you'll know how to: Build, test, and deploy smart contracts with Hardhat. Connect MetaMask to Sepolia via an Alchemy RPC endpoint. Obtain Sepolia ETH from a faucet. Interact with the contract using Ethers.js and build a frontend for the application. For more about smart contracts, visit our smart contract development services

 

Also, Read | Solidity Smart Contract Vulnerabilities and Ways To Mitigate Them

 

Detailed steps for building "Buy Me a Coffee" DeFi dApp Using Solidity 

 

Prerequisites

 

Before starting, ensure you have:

 

  • npm version 8.5.5 or higher. 
  • node version 16.13.1 or higher. 
  • An Alchemy account. 

 

Step 1: Project Setup 

 

1- Create a new directory and then navigate into it: 

 

mkdir BuyMeACoffee-contracts cd BuyMeACoffee-contracts 

 

2- Initialize a new npm project:     

 

npm init -y

 

3- Install Hardhat:     

 

npm install --save-dev hardhat

 

4- Generate a Hardhat project:     

 

npx hardhat

 

Select "Create a JavaScript project" and agree to the defaults. 

 

5- Verify the setup by running tests:      

 

 npx hardhat test 

 

Step 2: Writing the Smart Contract

 

 1. Create the smart contract file: Copy BuyMeACoffee.sol and replace its content with:      

 

// SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; contract BuyMeACoffee 
{ 
 	event NewMemo(address indexed from, uint256 timestamp, string name, string message);
  	struct Memos { address from; uint256 timestamp; string name; string message; } 
 	address payable owner; Memos[] memos; 
	constructor() { owner = payable(msg.sender); } 
	function fetchMemosDetails() public view returns (Memos[] memory) { return memos; } 
	function buyCoffees(string memory _name, string memory _message) public payable { 
		require(msg.value > 0, "can't buy coffee for free!");
		memos.push(Memos(msg.sender, block.timestamp, _name, _message)); emit NewMemo(msg.sender, block.timestamp, _name, _message); 
	} 
	function withdrawTips() public { 
		require(owner.send(address(this).balance)); 
	} 
} 

 

Also, Read | LSDFi | Exploring Why It Is the Hottest DeFi

 

Step 3: Testing the Contract 

 

1- Create a test script: Copy buy-coffee.js and use the following code:      

 

const hre = require("hardhat"); 
async function getBalance(address) { 
	const balanceBigInt = await hre.ethers.provider.getBalance(address); 
	return hre.ethers.utils.formatEther(balanceBigInt); 
} 
async function printBalances(addresses) { 
 	for (const [index, address] of addresses.entries()) {
   	console.log(Address ${index} balance: , 
   	await getBalance(address)); 
 	} 
} 
async function printMemos(memos) { 
	for (const memo of memos) { 
		console.log(At ${memo.timestamp}, ${memo.name} (${memo.from}) said: "${memo.message}"); 
	} 
} 
async function main() { 
	const [owner, tipper3, tipper2, tipper] = await hre.ethers.getSigners(); 
	const BuyMeACoffee = await hre.ethers.getContractFactory("BuyMeACoffee"); 
	const buyMeACoffee = await BuyMeACoffee.deploy(); await buyMeACoffee.deployed(); 
	console.log("BuyMeACoffee deployed to:", buyMeACoffee.address); 
	const addresses = [owner.address, tipper.address, buyMeACoffee.address]; 
	console.log("== start =="); await printBalances(addresses); 
	const tip = { value: hre.ethers.utils.parseEther("1") }; 
	await buyMeACoffee.connect(tipper).buyCoffees("Carolina", "You're the best!", tip); 
	await buyMeACoffee.connect(tipper2).buyCoffees("Vitto", "Amazing teacher", tip);
	await buyMeACoffee.connect(tipper3).buyCoffees("Kay", "I love my Proof of Knowledge", tip);
	console.log("== bought coffee =="); 
	await printBalances(addresses); 
	await buyMeACoffee.connect(owner).withdrawTips(); 
	console.log("== withdrawTips =="); 
	await printBalances(addresses); 
	console.log("== memos =="); 
	const memos = await buyMeACoffee.fetchMemosDetails(); 
	printMemos(memos); 
} main() .then(() => process.exit(0)) .catch((error) => { 
	console.error(error); process.exit(1); 
}); 

 

2- Run the script:      

 

 npx hardhat run scripts/buy-coffee.js

 

Step 4: Deploying to Sepolia Testnet 

 

1- Create a deployment script: 

 

Create scripts/deploy.js with:     

 

 const hre = require("hardhat"); 
 async function main() { 
 	const BuyMeACoffee = await hre.ethers.getContractFactory("BuyMeACoffee"); 
 	const buyMeACoffee = await BuyMeACoffee.deploy(); 
 	await buyMeACoffee.deployed(); 
 	console.log("BuyMeACoffee deployed to:", buyMeACoffee.address); 
 } main() .then(() => process.exit(0)) .catch((error) => { 
 	console.error(error); process.exit(1); 
 }); 

 

2- Configure Hardhat for Sepolia: Edit hardhat.config.js:      

 

require("@nomiclabs/hardhat-ethers"); 
require("@nomiclabs/hardhat-waffle"); 
require("dotenv").config(); 
const SEPOLIA_URL = process.env.SEPOLIA_URL; 
const PRIVATE_KEY = process.env.PRIVATE_KEY;     
module.exports = { 
	solidity: "0.8.4", 
	networks: { 
		sepolia: { url: SEPOLIA_URL, accounts: [PRIVATE_KEY] } 
	} 
};

 

 3- Install dotenv:      

 

npm install dotenv

 

 4- Create a .env file:     

 

 touch .env 

 

5- Add your Alchemy and MetaMask details:      

 

SEPOLIA_URL=https://eth-sepolia.alchemyapi.io/v2/ PRIVATE_KEY=

 

Also, Read | Identifying Smart Contract Orchestration Patterns in Solidity

 

Conclusion

 

Developing a decentralized "Buy Me a Coffee" dApp using Solidity enables secure, transparent microtransactions. This blockchain-based approach ensures immutable and verifiable transactions, fostering trust and eliminating intermediaries to reduce fees and increase efficiency. It's a perfect solution for content creators and small businesses, promoting decentralized finance. Are you looking for smart contract developers? Join us in creating secure, transparent dApps and shaping the future of decentralized payment solutions. Start building today! 

 

References

 

- Ethereum Stack Exchange

- Medium

Category: Blockchain
A Step by Step Tutorial of Building a Cross Chain NFT Bridge

In the rapidly evolving landscape of blockchain technology, interoperability has become a key focus for businesses and developers alike. One area experiencing explosive growth is the world of NFT development services. As NFTs (non-fungible tokens) extend their reach across multiple blockchain networks, the need for secure and efficient mechanisms to transfer these assets between chains is more urgent than ever. In this comprehensive guide, we provide a step-by-step tutorial on building a cross-chain NFT bridge. This tutorial is designed for B2B professionals and developers seeking to enhance their technical capabilities while leveraging cutting-edge blockchain interoperability.

 

In this tutorial, we cover the underlying concepts, necessary architecture, coding examples, and best practices for deploying a robust cross-chain NFT bridge. By the end, you will understand the entire process—from setting up your development environment to deploying smart contracts and building off-chain relayers—allowing you to implement a solution tailored to your business needs.

 

Understanding Cross-Chain NFT Bridges

 

What Is a Cross-Chain NFT Bridge?

 

A cross-chain NFT bridge is a mechanism that allows NFTs to move seamlessly between two or more blockchain networks. With NFTs primarily built on blockchains such as Ethereum, Binance Smart Chain, or Solana, cross-chain bridges enable asset liquidity and wider market participation. The process generally involves locking an NFT on the source blockchain and minting a corresponding representation on the destination blockchain.

 

Why Cross-Chain Bridges Are Essential

 

  • Interoperability: Businesses often operate across multiple blockchain networks. A cross-chain NFT bridge helps in integrating assets and liquidity across these diverse environments.
  • Market Expansion: By allowing NFTs to exist on multiple chains, projects can access broader markets and communities, enhancing overall value.
  • Cost Efficiency: Some blockchains offer lower transaction fees or faster confirmations, making cross-chain transfers attractive for cost-sensitive operations.
  • Resilience and Redundancy: Diversifying assets across chains can enhance security and mitigate risks associated with a single-chain failure.

 

Also, Read | Building a Solana NFT Rarity Ranking Tool

 

Architecture and Key Components

 

Core Components of a Cross-Chain NFT Bridge

 

Smart Contracts on Source and Destination Chains:

 

  • Locking Contract: Responsible for locking the NFT on the source chain.
  • Minting Contract: Handles the minting or releasing of the NFT on the destination chain.

 

Relayer or Oracle System:

 

  • A trusted intermediary (or set of nodes) that listens for events (e.g., NFT locked) on the source chain and triggers corresponding actions on the destination chain.

 

User Interface (UI):

 

  • A frontend portal that allows users to initiate NFT transfers, view statuses, and receive notifications.

 

Off-Chain Orchestration Layer:

 

  • A backend service that manages communication between the source and destination chains, ensuring data integrity and security.

 

Also, Check | Building a Cross-Chain NFT Bridge using Solana Wormhole

 

How It Works

 

Locking Phase:


The NFT owner initiates a transfer by locking their NFT in the source chain's smart contract. This action triggers an event that is detected by the relayer.

 

Verification Phase:


The relayer verifies the locking transaction and prepares to mint a representation on the destination chain.

 

Minting Phase:


Once verified, the relayer calls the minting contract on the destination chain to create a new NFT that corresponds to the locked asset.

 

Reversal Process:


The process can be reversed to move the NFT back to the original chain by burning the minted NFT and unlocking the original asset.

 

Also, Discover | How to Create an NFT Rental Marketplace using ERC 4907

 

Tools and Technologies

 

To build a robust cross-chain NFT bridge, you'll need to leverage several tools and technologies:

 

  • Solidity: For writing smart contracts on Ethereum-compatible networks.
  • Hardhat or Truffle: Development environments for compiling, testing, and deploying smart contracts.
  • Web3.js or Ethers.js: JavaScript libraries for interacting with the blockchain.
  • Node.js: For building off-chain relayer services.
  • React or Vue.js: For building the frontend interface.
  • IPFS (Optional): For decentralized file storage if metadata needs to be preserved off-chain.
  • Oracle Services (Optional): For enhanced trust and verification.

     

Step 1: Setting Up the Development Environment

 

Before you begin coding, ensure that your development environment is correctly set up.

 

Prerequisites

 

  • Node.js and npm: Install from nodejs.org.
  • Hardhat:

     

    npm install --save-dev hardhat
    

     

  • MetaMask: For testing transactions on public testnets.
  • Ganache (Optional): For local blockchain simulation.

     

Initializing Your Hardhat Project

 

Create a new project directory and initialize Hardhat:

 

mkdir cross-chain-nft-bridge
cd cross-chain-nft-bridge
npx hardhat init

 

Follow the interactive prompts to set up your basic project structure. Your project should now have folders for contracts, scripts, and tests.

 

Step 2: Writing the NFT Bridge Smart Contracts

 

Now, we will create two essential smart contracts: one for locking NFTs and another for minting them on the destination chain.

 

Example: NFT Bridge Contract

 

Below is a simplified Solidity contract that demonstrates the locking and unlocking mechanism for an NFT. In practice, you may need additional functions for signature verification and multi-signature approvals, especially in a B2B environment.

 

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract NFTBridge is ERC721 {
    address public admin;
    mapping(uint256 => bool) public lockedTokens;

    event NFTLocked(address indexed owner, uint256 tokenId);
    event NFTUnlocked(address indexed owner, uint256 tokenId);

    constructor() ERC721("MyNFT", "MNFT") {
         admin = msg.sender;
    }

    // Lock the NFT on the source chain
    function lockNFT(uint256 tokenId) external {
         require(ownerOf(tokenId) == msg.sender, "Not the owner");
         require(!lockedTokens[tokenId], "Token already locked");

         lockedTokens[tokenId] = true;
         // Transfer the NFT to the contract to lock it
         transferFrom(msg.sender, address(this), tokenId);
         emit NFTLocked(msg.sender, tokenId);
    }

    // Unlock the NFT on the source chain (typically triggered by a relayer)
    function unlockNFT(address recipient, uint256 tokenId) external {
         require(msg.sender == admin, "Only admin can unlock");
         require(lockedTokens[tokenId], "Token is not locked");

         lockedTokens[tokenId] = false;
         // Transfer NFT back to the recipient
         _transfer(address(this), recipient, tokenId);
         emit NFTUnlocked(recipient, tokenId);
    }
}

 

Explanation

 

Locking Functionality:


The lockNFT function verifies ownership, locks the token by updating a mapping, and then transfers the NFT to the contract address, ensuring it cannot be transferred until unlocked.

 

Unlocking Functionality:


The unlockNFT function allows the admin (or a designated relayer) to unlock and transfer the NFT back to a recipient on the same chain.

 

This contract forms the backbone of your cross-chain NFT bridge. In a production environment, additional security measures, such as multi-signature approvals and oracle-based verification, should be incorporated.

 

Also, Explore | How to Implement an On-Chain NFT Allowlist

 

Step 3: Bridging Process Explained

 

The Bridging Workflow

 

Initiate Transfer:


The NFT owner initiates the transfer by calling the lockNFT function on the source chain's contract. The NFT is then held by the smart contract, and an event is emitted.

 

Event Monitoring:


An off-chain relayer service listens for the NFTLocked event. This service is critical as it acts as the bridge between the two blockchain networks.

 

Validation and Verification:


The relayer verifies that the NFT has been successfully locked on the source chain. It may also perform additional checks like verifying a digital signature.

 

Minting on Destination Chain:


Once validated, the relayer triggers a transaction on the destination chain. Here, a corresponding mint function is executed to create an NFT that represents the original asset.

 

Reverse Process:


To move the NFT back, the relayer listens for a burn event on the destination chain and then calls the unlockNFT function on the source chain contract, returning the original NFT to the owner.

 

Off-Chain Relayer Code Sample

 

Below is a Node.js code snippet using ethers.js to monitor events and call the unlocking function:

 

const { ethers } = require("ethers");

// Connect to the source chain
const providerSource = new ethers.providers.JsonRpcProvider("https://source-chain-node.example.com");
const providerDest = new ethers.providers.JsonRpcProvider("https://destination-chain-node.example.com");

const sourceBridgeAddress = "0xYourSourceBridgeAddress";
const destBridgeAddress = "0xYourDestBridgeAddress";

// ABI for NFTBridge contract
const nftBridgeABI = [
  "event NFTLocked(address indexed owner, uint256 tokenId)",
  "function unlockNFT(address recipient, uint256 tokenId) external"
];

const sourceBridgeContract = new ethers.Contract(sourceBridgeAddress, nftBridgeABI, providerSource);
const adminPrivateKey = "0xYourAdminPrivateKey";
const wallet = new ethers.Wallet(adminPrivateKey, providerDest);
const destBridgeContract = new ethers.Contract(destBridgeAddress, nftBridgeABI, wallet);

// Listen for NFTLocked events on the source chain
sourceBridgeContract.on("NFTLocked", async (owner, tokenId) => {
  console.log(`Detected locked NFT - Owner: ${owner}, TokenID: ${tokenId}`);
  
  // Validate event details and prepare to unlock NFT on destination chain
  try {
    const tx = await destBridgeContract.unlockNFT(owner, tokenId);
    await tx.wait();
    console.log(`Unlocked NFT on destination chain for ${owner}`);
  } catch (error) {
    console.error("Error unlocking NFT:", error);
  }
});

 

Explanation

 

Event Listener:


The relayer listens for NFTLocked events from the source bridge contract. Once an event is detected, the relayer verifies the event and prepares a transaction to unlock the NFT on the destination chain.

 

Transaction Execution:


Using ethers.js, the code creates and sends a transaction from the admin wallet to the destination bridge contract's unlockNFT function. This automated process is vital for ensuring a smooth, near-real-time bridging experience.

 

You may also like | A Guide to Implementing NFT Royalties on ERC-721 & ERC-1155

 

Step 4: Deploying the Smart Contracts

 

Deploying your smart contracts to both source and destination blockchains is a critical step. Using Hardhat, you can deploy contracts with a simple deployment script.

 

Example Deployment Script (deploy.js)

 

async function main() {
  const [deployer] = await ethers.getSigners();
  console.log("Deploying contracts with the account:", deployer.address);

  const NFTBridge = await ethers.getContractFactory("NFTBridge");
  const nftBridge = await NFTBridge.deploy();
  
  await nftBridge.deployed();
  console.log("NFTBridge deployed to:", nftBridge.address);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
     console.error(error);
     process.exit(1);
  });

 

Deployment Steps

 

Compile Contracts:

 

npx hardhat compile

 

Deploy to Testnet or Local Network:

 

npx hardhat run scripts/deploy.js --network rinkeby

 

Verify Deployment:


Use blockchain explorers such as Etherscan to verify that your contracts are live and properly functioning.

 

Step 5: Building the Off-Chain Relayer and Orchestration Layer

 

A robust off-chain system is critical to monitor events and orchestrate bridging actions between chains.

 

Key Components of the Off-Chain Layer

 

  • Event Listeners:
    Scripts or services that continuously listen for specific blockchain events.
  • Transaction Processors:
    Modules that validate and process bridging transactions.
  • Logging and Monitoring:
    Integrate tools like Prometheus and Grafana for real-time performance monitoring.
  • Security and Error Handling:
    Ensure proper error handling, retry mechanisms, and secure key management.

 

You may also like to explore | How to Mint an NFT on Polygon using Ethers.js

 

Best Practices

 

  • Decentralization:
    Use multiple relayer nodes to avoid single points of failure.
  • Redundancy:
    Implement fallback strategies in case one node goes offline.
  • Security Audits:
    Regularly audit your codebase and relayer infrastructure for vulnerabilities.

 

Step 6: Developing a User-Friendly Frontend Interface

 

A professional frontend interface is essential for user adoption and overall success. The UI should enable users to:

 

  • Initiate NFT transfers with clear instructions.
  • Monitor the status of their bridging transactions.
  • Access support and FAQs.

 

Technology Stack

 

  • React:
    Build dynamic and responsive UIs.
  • Web3.js/Ethers.js:
    Integrate blockchain interactions directly into the frontend.
  • Tailwind CSS/Material-UI:
    For professional, modern design.

 

Sample React Component

 

Below is a simplified React component that allows users to lock an NFT:

 

import React, { useState } from 'react';
import { ethers } from 'ethers';

const LockNFT = ({ bridgeContractAddress, provider }) => {
  const [tokenId, setTokenId] = useState('');

  const lockNFT = async () => {
    const signer = provider.getSigner();
    const contract = new ethers.Contract(bridgeContractAddress, [
      "function lockNFT(uint256 tokenId) external"
    ], signer);

    try {
      const tx = await contract.lockNFT(tokenId);
      await tx.wait();
      alert("NFT locked successfully!");
    } catch (error) {
      console.error("Lock NFT error:", error);
      alert("Error locking NFT.");
    }
  };

  return (
    <div>
      <h2>Lock Your NFT</h2>
      <input
        type="number"
        placeholder="Enter Token ID"
        value={tokenId}
        onChange={(e) => setTokenId(e.target.value)}
      />
      <button onClick={lockNFT}>Lock NFT</button>
    </div>
  );
};

export default LockNFT;

 

Explanation

 

  • User Input:
    The component captures the token ID from the user.
  • Blockchain Interaction:
    It interacts with the smart contract via ethers.js, invoking the lockNFT function.
  • User Feedback:
    Basic error handling and alerts ensure users are informed of success or failure.

 

Security Considerations

 

Security is paramount in any cross-chain bridging solution. Key areas to focus on include:

 

  • Smart Contract Audits:
    Regularly audit your smart contracts to identify vulnerabilities such as reentrancy, integer overflows, and access control issues.
  • Oracle Trust:
    If using an off-chain relayer or oracle, ensure that the system is decentralized and that trust is not placed on a single entity.
  • Key Management:
    Secure the private keys used in off-chain services and relayers using hardware security modules (HSMs) or equivalent solutions.
  • Rate Limiting and Throttling:
    Prevent abuse by implementing rate limiting on API endpoints and transaction submissions.
  • Fallback and Redundancy:
    Design your system to gracefully handle failures, including retry mechanisms and alternative paths for transaction execution.

 

Also, Check | How to Get the Transaction History of an NFT

 

Testing and Deployment

 

Testing Strategies

 

  • Unit Testing: Write comprehensive unit tests for your smart contracts using Hardhat or Truffle. Use frameworks like Mocha and Chai for assertions.
  • Integration Testing: Test the interaction between smart contracts, relayer services, and the frontend. Simulate cross-chain transfers on local networks.
  • Security Testing: Employ static analysis tools such as MythX, Slither, or Oyente to scan for vulnerabilities in your smart contracts.
  • User Acceptance Testing (UAT): Engage with a select group of users or internal teams to validate the user experience and system reliability.

 

Deployment Best Practices

 

  • Staged Rollouts: Deploy your solution on a testnet first, then gradually roll out to the mainnet while monitoring performance.
  • Continuous Monitoring: Use monitoring tools to track transaction success rates, relayer uptime, and system performance.
  • Post-Deployment Audits: Conduct a final audit after deployment to ensure that no vulnerabilities have been introduced during the deployment process.

 

Conclusion

 

Building a cross-chain NFT bridge is a multifaceted project that requires a deep understanding of both blockchain technology and system architecture. In this tutorial, we have walked through the entire process—from conceptualizing the solution and setting up your development environment to writing smart contracts, building an off-chain relayer, and developing a user-friendly interface.

 

As NFTs continue to redefine digital ownership and as blockchain ecosystems become increasingly interconnected, cross-chain bridges will play an essential role in facilitating liquidity, enhancing security, and driving interoperability across networks. By leveraging the strategies and code examples provided in this guide, B2B developers and enterprises can deploy a secure, efficient, and scalable solution that meets the growing demand for cross-chain NFT transfers.

 

Continuous innovation, rigorous testing, and a focus on security will ensure your cross-chain NFT bridge remains robust and adaptable in an ever-evolving market. Embrace these best practices and technical insights to create a seamless user experience and a competitive edge in the dynamic world of blockchain interoperability.

 

You might also be interested in | How to Create a Compressed NFT on Solana

 

FAQ

 

Q1: What is a cross-chain NFT bridge?

 

A: A cross-chain NFT bridge is a mechanism that allows NFTs to be transferred securely between different blockchain networks. The process typically involves locking the NFT on the source chain and minting a corresponding token on the destination chain.

 

Q2: Why do businesses need cross-chain NFT bridges?

 

A: Cross-chain bridges enable interoperability, allowing businesses to tap into multiple blockchain ecosystems, reduce transaction costs, enhance liquidity, and reach a broader audience. This capability is especially crucial for enterprises looking to expand their digital asset strategies across diverse networks.

 

Q3: What are the main components of a cross-chain NFT bridge?

 

A: The key components include smart contracts on both source and destination chains, an off-chain relayer or oracle to monitor events and trigger actions, a user-friendly frontend interface, and a backend orchestration layer for robust security and performance.

 

Q4: How is security ensured in a cross-chain NFT bridge?

 

A: Security is maintained through rigorous smart contract audits, decentralized relayer systems, secure key management practices, and robust error handling mechanisms. Implementing fallback strategies and continuous monitoring further enhances the overall security of the system.

 

Q5: Can this solution be integrated into existing NFT platforms?

 

A: Yes, the cross-chain NFT bridge solution can be integrated into existing NFT platforms. The modular architecture allows developers to adapt and extend the smart contracts, off-chain relayers, and frontend interfaces to match the specific needs of different NFT ecosystems.

 

Q6: What tools and technologies are essential for developing a cross-chain NFT bridge?

 

A: Essential tools include Solidity for smart contract development, Hardhat or Truffle for deployment, ethers.js or web3.js for blockchain interactions, Node.js for off-chain relayer services, and React or Vue.js for the frontend interface.

 

This tutorial has provided you with a detailed roadmap to build your own cross-chain NFT bridge. From understanding the core concepts to implementing code and deploying a secure solution, you now have a comprehensive guide to unlock the potential of blockchain interoperability in the NFT space. Embrace these techniques and best practices to drive innovation and create a competitive edge in the evolving digital asset landscape. However, if you are lookin for trusted NFT development, connect with our NFT developers to get started. 

 

Category: Blockchain
How to Run and Setup a Full Node on Polkadot

Polkadot is a decentralized protocol used to enable interoperability in a blockchain. Generally is a layer-0 protocol so the developer is willing to develop or build Kusama, parachain on Polkadot. By running a node on its ecosystem, it eliminates all the risks of third-party infrastructure across the decentralized world. In this article, we explore the Polkadot blockchain application development architecture and the steps to run and set up a full node. 

 

Overview of Polkadot’s Architecture

 

Polkadot uses proof of stake, proof of work, and combined consensus to make the Polkadot network more scalable and efficient. Polkadot contains a multichain architecture with shared security and true interoperability.

 

Components of Polkadot’s Architecture

 

Shared Security - Provide security to all the parachains and units then for communication. 

Relay chain - Used to unite all the parachain on the polkadot.

Parathread and Parachain Slots - Used to manage the chain and responsible for the security and easy upgradability.

 

Interoperability of Polkadot’s Architecture

 

  • XCM
  • Bridges

 

Types of Polkadot Nodes

 

  • Full Node
  • Archive Node
  • Light Node

 

Suggested Read | Why Develop a DApp (Decentralized Application) on Polkadot

 

Steps to Run and Setup a Full Node on Polkadot in Linux

 

Step 1: Run this command to download polkadot.

 

sudo chmod +x polkadot

 

Step 2: Run the command and search node on telemetry.

 

./target/release/Polkadot --name "Node's Name"

 

Step 3: Get Substrate and Follow all these commands step-by-step to add substrate doc regarding the installation.

 

git clone https://github.com/paritytech/polkadot Polkadot
cd Polkadot
./scripts/init.sh
cargo build --release

 

Step 4: Build and Clone

 

git clone http://github.com/paritytech/polkadot Polkadot
cd Polkadot
./scripts/init.sh
cargo build --release

 

Step 5: Run 

 

The Binary will reflect in the target/release folder, Now the given command and use -the the-help flag to check which flag we can use to run the node. and if you want to connect your node remotely then you need to use -rpc-cors.  



 

./target/release/Polkadot --name "Node's Name"



 

Note: The syncing process will take time based on the bandwidth of your system, RAM, disk space, and disk speed.



 

Step 5: Run and archive node



 

./target/release/Polkadot --name "node's name" --pruning archive



 

Note: If we run a simple sync node then we will keep only past blocks record and we can use the –wasm-execution Compiled flag to quadruple synchronization speed.

 

Check It Out | A Compact Guide to Understanding Polkadot Blockchain

 

Conclusion

 

In this article, we have learned how to setup and run a full node on Polkadot and need to run given commands step-by-step to set up a node smoothly on your system. If you are interested in integrating blockchain technology into your applications, then connect with our blockchain developers

Understanding Delegate Calls in Smart Contract

Delegate calls in smart contract generally used to interact with other smart contract where Delegation is the one of the way. When a smart contract uses a delegate call to call a method, it executes and loads the method code from other smart contracts.

 

When a method executes by delegation call then the following values do not change

 

  • msg.sender
  • msg.value
  • address(this)

 

The smart contract that execute and loads the function of smart contract using delegate calls can write and read state variables and the smart contract that holds the methods is not subjected to writes or reads.

 

If Smart Contract A utilizes a deligate call to another Smart Contract B then the following statements will be true:

 

  1. Smart Contract A state variables can be 'write and read'.
  2. Smart Contract B state variables never 'write and read'.

 

Smart Contract B functions can be read and write the variables of both Smart Contract A and B.

 

Examples

 

Smart Contract A has the following things:

 

  • address(this) == 0x514910771AF9Ca656af840dff83E8264EcF986CA
  • State variable called “string tName” is “TestTokenA.”
  • External method ‘init()’ used to delegate call to Smart Contract B setTName(string calldata _newTName)’ method.


Smart Contract B has the following things:

 

  • address(this) == 0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE
  • State variable called “string tName” is “TestTokenB.”
  • external method ‘setTName(string calldata _newTName)’ that updates the ‘tName’ state variable to the ‘_newTName’.

 

When we call the ‘init()’ method in Smart Contract A with 1 ETH:

 

1. These values will be set:

 

  • address(this) == 0x514910771AF9Ca656af840dff83E8264EcF986CA
  • msg.sender == 0x868dae27Eb45B26835D69b15C525c8B73FF20e3B
  • msg.value == 1 ETH

 

2. When‘init()’ method calls the ’setTName’ method in Smart Contract B then these values are returned:

 

  • address(this) == 0x514910771AF9Ca656af840dff83E8264EcF986CA
  • msg.sender == 0x868dae27Eb45B26835D69b15C525c8B73FF20e3B
  • msg.value == 1 ETH

 

3. In Smart Contract A, the value of the ‘tName’ state variable is changes.

 

Conclusion



In this article, we have learned how to delegate calls in a smart contract from Contract A to B and how state variables and functions work.

How to create a dApp on Polkadot

What is Polkadot?

 

Polkadot is a next-generation blockchain that can bring all blockchains together and allow them to operate on a large scale. The main feature of Polkadot is to exchange data between different blockchains. The Polkadot design provides several advantages over many legacy networks, including transparent governance, cross-chain composability, and scalability upgradeability.

 

Polkadot Architecture

 

Polkadot combines Parachains and numerous heterogeneous blockchains into a unified network. All these chains are secure and connected by relay chains. They can use bridges to communicate these chains with external networks.

 

The following components of Polkadot perform consensus roles:-

 

  • Parachains
  • Fishermen
  • Bridges - Used to communicate chains with external networks such as Ethereum and Bitcoin
  • Relay Chain - Heart of Polkadot blockchain that is used for cross-chain interoperability, network consensus, and security
  • Nominators
  • Collators - Provide proof of validators and maintenance of shards 
  • Validators

 

Advantages of Polkadot:-

 

  • Scalability
  • Heterogeneous Sharding
  • Transparent governance
  • Upgradability
  • Cross-chain composability

 

Build a dApp on Polkadot


Substrate provides all the components needed for the development of a dApp on Polkadot. It helps to build customized projects as per requirement.

 

Prerequisites to develop a dApp on Polkadot:-

  • Knowledge of Rust Programming
  • Basic knowledge of software programming
  • Use of terminal

 

Step 1:-

 

Set up an application using Substrate

 

1. Clone Substrate node template

  • git clone https://github.com/substrate-developer-hub/substrate-node-template

 

2. Run Nightly build with Rust

  • rustup update nightly
  • rustup target add wasm32-unknown-unknown --toolchain nightly

 

3. Change the directory into Substrate node template folder

  • cd substrate-node-template
  • git checkout latest

 

4. Commands to compile and run the node template within a project

  • cargo build --release

 

Step 2:-

 

Test and deploy your dApp on Polkadot

 

You may use Rococo to test your application. Rococo is a Polkadot Parachain testnet that employs Proof of Mechanism consensus. You can also another Polkadot Parachain testnet called Westend. But, Rococo will be more convenient as compared to Westend. You can deploy dApp after testing.

 

Conclusion

 

In this post, we have covered the development process of dApp on the Polkadot blockchain. Now, you will be able to create a dApp for enhanced interoperability, scalability, and more.

Category: Blockchain
How to participate in an ICO

 

ICOs(Initial Coin Offerings) or token sales are next-generation crowdfunding where users can buy new tokens by participating in ICOs. Still, there are lacking standards in the blockchain ecosystem, which make the token sale hard for a normal person. Most of the ICOs are running on different blockchains like Ethereum, Binance, etc., through a smart contract that collects stable or native tokens. It converts them into new tokens according to the price presented by the start-up company. This complete process happens entirely P2P without any broker, middle person, or exchange.

 

Buy ICO Tokens

 

Most of the time, all start-ups provide a step-by-step guide to participating in token sales with screen-shots for each step. Also, you should join their social media channels, including telegram or slack, and follow all the news of ICOs. All ICOs start either at a previously specified block number or, sometimes, you can use blockchain explore to check current block numbers information.

 

When the token sale starts, you need to send ETH or specified token on the sale contract or wallet address specified by the team. After sending ETH, there are a couple of scenarios:

 

- You receive your new tokens after the token sale ends.

- You need to wait for some days for your tokens.

- You will need to withdraw/redeem your tokens manually.

- You need to redeem your token in vesting form.

 

Note - Sometimes, hackers manipulate ICO websites, so you need to cross-check the new sale token and sale contract. It is to address on their main website and social channels.

 

Secure your Tokens

 

After receiving your tokens in a wallet, we need to send/transfer them to a more secure wallet. Also, you need some ETH for a gas fee to transfer your token to another secure wallet.

 

Conclusion

 

In this post, you will know how to participate in a token sale in easy steps.

 

We are a Blockchain Development Company based in Gurugram, and if you want to explore more about Initial Coin Offering (ICO), please feel free to connect with our expert team.

 

 

Protecting your Solidity Smart Contracts from Reentrancy Attacks

Reentrancy Attack occurs when any function of a smart contract contains an external call with another untrusted smart contract. If attackers found any vulnerable function in the contract then the attackers can control the untrusted contract, By this, they can make repeating interactions and a recursive call back to that function that would have otherwise they can completely withdraw all ethers from your smart contract.


Types of reentrancy attacks

1- Single function - Single function Reentrancy Attack is the easiest and simplest to prevent. This reentrancy attack occurs when the unsecured function and the attacker function are the same in which the attacker is trying to recursively call. In a single function reentrancy attack, a vulnerable function makes an external call using send, call, or transfer.


Single function Reentrancy Attack Example:-

function withdrawFund() external {
          uint256 userAmount = _balances[msg.sender];
          require(msg.sender.call.value(userAmount)());
          _balances[msg.sender] = 0;
}

After msg.sender.call.value(userAmount)() attacker can create a fallback method in an untrusted smart contract, and then the fallback method can call withdrawFund again, and this can transfer more funds before _balances[msg.sender] = 0.


2- Cross-function reentrancy attack - Cross-function reentrancy attack is the most dangerous attack in which attacks are harder to detect. This attack can possible when a vulnerable function shares a state with another function of the contract.

Cross-function reentrancy attack example:-

function transferFund(address _to, uint _amount) external {
    if (_balances[msg.sender] >= _amount) {
        _balances[_to] += _amount;
        _balances[msg.sender] -= _amount;
    }
}

function withdrawFund() external {
    uint256 _amount = _balances[msg.sender];
    require(msg.sender.call.value(_amount)());
    _balances[msg.sender] = 0;
}

In this example, withdrawFund function calls the attacker’s fallback function by msg.sender.call.value(_amount)()) same as single function reentrancy attack.

The main difference is that the fallback function makes a call  transferFund function instead of recursively calling withdrawFund. And by this transfer fund method transfer balance that has already been sent.


Prevent reentrancy attacks

1-
Try to use it in place to secure your contract.
2- Identify untrusted methods and don't use any untrusted methods if they are untrusted.
3- Try to use Mutex

Mutex:-

function withdrawFund() external {
    require(!_lock);
    _lock = true;
    uint256 _amount = _balances[msg.sender];
    require(msg.sender.call.value(_amount)());
    _balances[msg.sender] = 0;    
    _lock = false;
}
Uniswap V3 Oracle Updates

Uniswap is a decentralized finance exchange that is used to trade cryptocurrencies and provide liquidity. It automate transaction between ERC20 or cryptocurrencies tokens on ethereum blockchain through the use of solidity smart contracts. Currently, There are three version of Uniswap Protocol. V1 and V2 are open source with GPL licensed and V3 is also open source with slight modifications.


Uniswap V2 Oracle TWAP Contract:-

In Uniswap V2 Oracle, We use cumulative price variable in the core contract weighted by the amout of time price existed, this variable represents the sum of uniswap price of every seconds in the entire history of the contract. Where these variables can we used by any external contracts to get or track accurate TWAP(time-weighted average prices) across any time interval.

The TWAP reads the cumulative price from an uniswap pair contract from the beginning to end of the desired interval. The difference of cumulative price and divided by the length of the interval to create a TWAP of that period can be the result of TWAP price.

Formula to get token price from uniswap v2 Oracle TWAP Contract:-
TWAP = (Price Cumulative2 - Price Cumulative1)/(Timestamp2 - Timestamp1)


Uniswap V3 Oracle:-


In Uniswap V3, Pool contract can serve as oracle contract, it offers to get history price and liqudity data. In Uniswap V3 Tick accumulator stores the cumulative sum of tick and the tick value increase monotonically. When any pool is created, each token is assigned either token1 or token0 based on contract address of ERC20 token.

In Uniswap V3, We use this formula to get Token price:-
 P(i) = 1.0001^(i)      Where i -> Tick value


Example:-
Suppose, if we want to get ETH price in USDT by using Uniswap WETH/USDT pair.

Where Tick value is -194643 then,
price = 1.0001^(-194643) = 3525.206397

Tick -194643 gives us a price of WETH as 3525.206397 in term of USDT.
     

Understanding Binance Smart Chain Bridge for Cross Chain Transfers

Binance Smart Chain is a fully decentralized application, the main goal of fast trading while being able to handle a large number of transactions. Like in Ehereum we pay ETH for the gas fee, in Binance Smart Chain we use BNB for the gas fee.
 

Binance Smart Chain is a decentralized blockchain that delivers programmability and smart contracts to the Binance Chain.

 

Binance Smart Chain-Ethereum bridge

 

Ethereum-Binance Smart Chain bridge is developed by Binance and used for transfer/bridge pegged assets cross-chain, i.e. transfer assets in or out of Binance smart chain. Binance bridge service providing access to inter-blockchain liquidity for Binance Chain.


Peg-In Procedure:-
 

Peg-In Procedure allows users to swap their crypto assets to the equivalent of pegged tokens on Binance Smart Chain. The following steps are taken:

  1. The user first needs to create a swap request to on Binance Bridge Service.
  2. Bridge Provider allocates a deposit address to the user.
  3. The user needs to deposit the agreed amount of tokens to this address. If the equivalent amount of token is not sent before the deadline, the tokens are refundable.
  4. Binance Bridge Provider takes notice of the upcoming token transfer from the user and sends the equivalent pegged amount of tokens to the receiver’s address.
  5. Binance Bridge Provider will lock the pegged user's tokens.
  6. The user can see all the changes of his token balance of these pegged tokens.

 

Peg-Out Procedure:-

 

Peg-Out Procedure allows users to swap their crypto assets to the equivalent of pegged tokens on Binance Smart Chain. The following steps are taken:

 

  1. The user first needs to create a swap request to on Binance Bridge Service.
  2. Bridge Provider allocates a deposit address to the user.
  3. The user needs to deposit the agreed amount of tokens to this address. If the equivalent amount of token is not sent before the deadline, the tokens are refundable.
  4. Binance Bridge Provider takes notice of the upcoming token transfer from the user and sends the equivalent pegged amount of tokens to the receiver’s address.
  5. Binance Bridge Provider will lock the pegged user's tokens.
  6. The user can see all the changes of his token balance of these pegged tokens.

 

Gas Fee for Transactions

 

When any users swap their tokens from Binance Smart Chain-Etherum bridge then they need to pay some amount of gas fee to create a transaction on Binance Smart Chain. so users must have some BNB in their wallets for the gas fees.

 

How to Fo Smart Contracts Unit Testing with Truffle

Unit testing plays a crucial role in any smart contract-based protocol. They should be run on every commit. They are checked by the community and unit test is mandatorily checked by auditors. Generally, unit-testing is needed to ensure the code is working the way we expected.

 

Prerequisites

 

  • Visual studio code
  • Npm
  • Truffle

 

List of some top farmworks used for smart contract unit testing

 

  • Truffle
  • Mocha
  • Chai
  • OpenZepplin Test Helper

 

Start With the Token

 

First of all, we need the token so we will have something to test. You can write your complete code by yourself. But in this, we will write a unit tests for a simple ERC20 token:


 

// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;


import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

import "@openzeppelin/contracts/access/Ownable.sol";

 

contract TestMintable is ERC20, Ownable {

     constructor(address _holder, uint256 _initialSupply) ERC20("TestMintable", "Test") public {
           _mint(_holder, _initialSupply)
     }

     function mint(address to, uint256 _amount) public onlyOwner
     {
        _mint(to, _amount);
     }
}

 

Our Smart Contract is ready in which we have a constructor and one mint method to mint new tokens and the mint method can only be called by the Owner.

 

Compile Smart Contract

 

 

Run the command:-

        truffle compile

 

Write Unit Test Cases

 

var testMintable = artifacts.require('TestMintable');

contract('TestMintable', function(accounts) {

  let instance;

  before(async () => {

    instance = await testMintable.deployed(accounts[0], 1000);

  });

  it('Token Name should be TestMintable',async () => {

    let tokenName = await instance.name.call({from: accounts[0]});          

    assert.equal(tokenName, "TestMintable","Incorrect name.");

  });


  it('Token Symbol should be Test',async () => {

    let tokenSymbol = await instance.symbol.call({from: accounts[0]});          

    assert.equal(tokenSymbol, "Test","Incorrect symbol.");

  });

  it('Total Supply should be 1000',async () => {

    let supply = await instance.totalSupply.call({from: accounts[0]});         

    assert.equal(supply.toString(), "1000","Incorrect Supply.");       

  });

  it('Mint New Tokens',async () => {

    let result = await instance.mint.sendTransaction(accounts[1], 1000, {from: accounts[0]}); 
    let balance = await instance.balanceOf.call(accounts[1], {from: accounts[1]});           
    assert.equal(balance, 1000, "Incorrect balance.");  

  });

  it('Should throw error when minter caller is not owner',async () => {

    try{

      let result = await instance.mint.sendTransaction(accounts[1], 1000, {from: accounts[1]});

      assert.fail(true,false,"Ownable: caller is not the owner"); 

    }

    catch(err){

        assert.include(String(err),'revert','throws different error');

    }

  });

});

 

Run Test Cases

 

Run the command:-

        truffle test

 

Conclusion

 

In this post, we implemented unit test cases for our smart contract using truffle frameworks and executed tests with Truffle successfully.

 

 

A Developer Guide to Building your First Smart Contract

Developers code smart contracts in solidity language. It gets stored on the blockchain and executes automatically in terms of the agreement between a seller and a buyer. In a smart contract solution, certain conditions have to be fulfilled to execute the order successfully.

 

Prerequisites

 

  • Remix Online IDE

 

Structure of a Smart Contract

 

Solidity smart contract is the collection of following

 

  • Function:- In function, apply the logic to transition the state of the contract.
  • Data:- Maintain the current state of the contract.

 

Pragma

 

Pragma is used to enable checks and certain compiler futures. The below statement defines that the smart contract will not compile earlier than 0.5.0 and compiler version after 0.7.0

 

pragma solidity >=0.5.0 <=0.7.0

 

Contract Declaration

 

To declare a contract we use the "contract" keyword. This declares an empty contract which is identified by the name “BuyOrder”.

 

contract BuyOrder {

}

 

Introducing Variables

 

In Solidity language, variables are of two types

 

  • Reference Type:- These types of variables passed by reference and do not fit into 256 bit.
  • Value Type:- These types of variables are passed by value and used as function arguments or in assignments.

 

Adding Data into the Smart Contract

 

Add variables:- Let us add a variable quantity which will be of the data type of integer. Unsigned integer variables are represented by uint256, here 256 is signifying the 256 bits storage. 

 

contract BuyOrder {

uint256 quantity;

}

 

Defining the constructor:- Constructor is always called when the contract is deployed on any node. the constructor initializes the contract with some values. In this scenario, we are initializing the quantity value to 50 when the contract is deployed.

 

constructor() public {

quantity = 50;

}

 

Adding getter functions:- Getter methods are used to read the stored value and the function declaration looks like function <function name> <access modifier> <state> <return value>.

 

function getQuantity() public view returns(uint256) {

return quantity;

}

 

Adding setter functions:- Setter methods are used to write/update the stored value.

 

function setQuantity(uint256 _newQuanity) public {

quantity = _newQuanity;

}

 

After Plugging all this together, Overall contract should look like

 

pragma solidity >=0.5.0 <=0.7.0;

contract BuyOrder {

uint256 quantity;

constructor() public {

         quantity = 50;

}

function getQuantity() public view returns(uint256) {

          return quantity;

}

function setQuantity(uint256 _newQuanity) public {

          quantity = _newQuanity;

}

}

 

Deploying Contract:- 

 

We can use Remix Online IDE to test and deploy the smart contract. Remix Ide completely browser-based where you can write and deploy your smart contract. it also provides you an online solidity compiler to compile your smart contract.

1:- Create a new file and name the file BuyOrder.sol.

2:- Copy and paste the whole contract in the buy order.sol file.

3:- Click on the second icon on the left side of IDE and select the compile to compile the code.

4:- Click on compile BuyOrder.sol.

5:- Once the smart contract compiles successfully, click on the third icon Deploy and Run Transaction to deploy the contract.

6:- Click on the deploy button to deploy the contract. 

 

Conclusion

 

This is an example to build your first smart contract on Remix Online IDE and this can only be checked on the local environment.

 

Interacting with Ethereum Smart Contracts through Web3.js Library


A Smart Contract is a transaction protocol that is self-executing as per the terms of an agreement between seller and buyer, existing on a blockchain platform. Most smart contracts are stored on the Ethereum blockchain. The smart contract codes control all the transactions on a blockchain, and execution is trackable and irreversible. All smart contracts written in smart contract-specific programming languages are compiled in bytecode.

 

Solidity is a language that we can use to code smart contracts code. Smart contract syntax is very similar to Javascript, and EVM (Ethereum Virtual Machine) is used to read and execute the Smart Contract. We can execute the solidity programs by using an online IDE (integrated development environment) called Remix or local machines.

 

Prerequisites

 

  • JavaScript Library Web3.js
  • MetaMask Wallet

 

Steps to Interact with a Smart Contract through Web3.js:-

 

Step 1:- First we need to add/install the Metamask extension in any browser like Google Chrome, Firefox, etc. 

 

Step 2:- Web3.js is the official Ethereum JavaScript API and it is used to interact with Ethereum smart contract.

 

  • Install Web3.js library by using npm :-
                           npm install web3 --save
                           import web3 from 'web3';

 

  • Import Web3.js library nn HTML file :- 
                          <script src="https://cdn.jsdelivr.net/gh/ethereum/[email protected]/dist/web3.min.js"></script> 

 

Step 3:- In this step, we are connecting the MetaMask wallet with a dApp. If the user's wallet is in lock status then it will ask for unlocking Metamask wallet, otherwise, it will directly connect the user's Metamask wallet with the dApp application.

 

async function connectWallet() {
       if (window.ethereum) {
          window.web3 = new Web3(window.ethereum);  }

          conn = await window.ethereum.enable();

        ethconnected = conn.length > 0
        if (ethconnected) {
            ethaddress = conn[0]    // get wallet address
        }
         web3.eth.getAccounts().then(console.log);

         return true;
}

 

 Step 4:- In this step, we are creating a contract object with the help of a web3 object and we will use this contract object to call Ethereum smart contract methods.

 

contract = new web3.eth.Contract(<contract Abi>, <contract address>);

 

Step 5:- In this step, we are calling the balanceOf() method of smart contract to get user balance.

 

You may also like to read | How to use Blockchain in the Metaverse | Oodles Blockchain

 

contract.methods.balanceOf(ethaddress).call().then(function (balance) {
        console.log(balance);
})

 

Step 6:- In this step, we are calling the add() method of smart contract to add two numbers and after successful transaction creation, it will return you a transaction hash value. You can use this transaction hash value to check the transaction status on etherscan.io.

 

    contract.methods.add("10", "20").send({ from: ethaddress }, async function (error, transactonHash) {
        console.log(transactonHash);
    })

 

Conclusion

 

This is a simple example to interact with an Ethereum smart contract by using the Web3.js library and this can only be checked in a local environment.

 

 

For more information about Ethereum smart contracts development, you may connect with our skilled smart contract developers.

Banner

Don't just hire talent,
But build your dream team

Our experience in providing the best talents in accordance with diverse industry demands sets us apart from the rest. Hire a dedicated team of experts to build & scale your project, achieve delivery excellence, and maximize your returns. Rest assured, we will help you start and launch your project, your way – with full trust and transparency!