|
Mohd  Yasar Oodles

Mohd Yasar (Backend-Sr. Associate Consultant L2 - Development)

Experience:2+ yrs

Mohd Yasar is a skilled Backend Developer, with proficiency in NodeJs, MongoDB, MySql, Docker, Solidity, NFT's, and microservices architecture. He has extensive experience in developing secure and scalable solutions for complex applications, and has delivered successful projects such as Scaffold, Cryptomining, Mintlab, WalletPort, Data Management in Distributed Systems, and Bluechain, meeting the clients' requirements. Overall, he seems to have a diverse skill set and a strong foundation in developing scalable and reliable projects using a variety of technologies.

Mohd  Yasar Oodles
Mohd Yasar
(Sr. Associate Consultant L2 - Development)

Mohd Yasar is a skilled Backend Developer, with proficiency in NodeJs, MongoDB, MySql, Docker, Solidity, NFT's, and microservices architecture. He has extensive experience in developing secure and scalable solutions for complex applications, and has delivered successful projects such as Scaffold, Cryptomining, Mintlab, WalletPort, Data Management in Distributed Systems, and Bluechain, meeting the clients' requirements. Overall, he seems to have a diverse skill set and a strong foundation in developing scalable and reliable projects using a variety of technologies.

LanguageLanguages

DotEnglish

Conversational

DotHindi

Fluent

Skills
Skills

DotEthers.js

100%

DotBlockchain

80%

DotSolidity

80%

DotDyanmoDB

60%

DotNode Js

80%

DotJavascript

80%

DotPostgres

60%

DotWeb3.js

80%
ExpWork Experience / Trainings / Internship

May 2022-Present

Associate Consultant - Development

Gurugram


Oodles Technologies

Gurugram

May 2022-Present

EducationEducation

2018-2022

Dot

Uttar Pradesh Textile Technology Institute, Kanpur

B. Tech-Textile Technology

Top Blog Posts
How to Create a Liquid Staking Pool

The world of decentralized finance (DeFi) has been revolutionized by innovations such as staking pools. Liquid staking pools, in particular, offer a unique way for users to stake their cryptocurrencies while retaining liquidity. In this blog post, we will explore what a liquid staking pool is, why it is beneficial, and how to create one. If you are looking for more information about DeFi, visit our DeFi development services 

 

What is Liquid Staking?

 

Liquid staking allows users to stake their cryptocurrencies in a network to earn rewards while still having access to their staked assets. Unlike traditional staking, where assets are locked up for a period, liquid staking issues a derivative token representing the staked assets. We can trade this derivative token, use it in other DeFi protocols, or exchange it for my original staked assets and rewards. 

 

How to Create a Liquid Staking Pool

 

Creating a liquid staking pool involves several steps, including setting up a smart contract, issuing derivative tokens, and integrating with DeFi protocols. Below, we'll walk through a simplified example using Solidity, the programming language for Ethereum smart contracts.

 

You may also like | Crypto Staking Platform Development: A Step-by-Step Guide

 

Step 1: Setting Up the Smart Contract

 

First, you'll need to set up a smart contract to handle staking and issuing derivative tokens. Here's a basic example:

 

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

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

contract LiquidStakingPool is ERC20, Ownable {
    ERC20 public stakedToken;
    uint256 public totalStaked;

    constructor(address _stakedToken) ERC20("Staked Token", "sTOKEN") {
        stakedToken = ERC20(_stakedToken);
    }

    function stake(uint256 _amount) external {
        require(_amount > 0, "Cannot stake 0 tokens");

        stakedToken.transferFrom(msg.sender, address(this), _amount);
        _mint(msg.sender, _amount);
        totalStaked += _amount;
    }

    function unstake(uint256 _amount) external {
        require(_amount > 0, "Cannot unstake 0 tokens");
        require(balanceOf(msg.sender) >= _amount, "Insufficient balance");

        _burn(msg.sender, _amount);
        stakedToken.transfer(msg.sender, _amount);
        totalStaked -= _amount;
    }
}

 

In this example, the LiquidStakingPool contract allows users to stake an ERC20 token and receive a derivative token (sTOKEN). The stake function transfers the staked tokens to the contract and mints an equivalent amount of sTOKEN. The unstake function burns the sTOKEN and transfers the original staked tokens back to the user.

 

Step 2: Issuing Derivative Tokens

 

The derivative tokens (sTOKEN) represent the user's share in the staking pool. They can be used in various DeFi protocols for additional yield opportunities.

 

Also, Explore | Exploring the Potential of Liquid Staking Derivatives (LSD)

 

Step 3: Integrating with DeFi Protocols

 

To maximize the benefits of liquid staking, you can integrate your staking pool with other DeFi protocols. For example, you can create a liquidity pool on a decentralized exchange (DEX) for the derivative tokens or use them as collateral in lending platforms.

 

Explore More | An Explainer to Liquidity Staking Solution

 

Conclusion

 

Creating a liquid staking pool can provide numerous benefits to users, including liquidity, flexibility, and compounding rewards. By following the steps outlined in this guide, you can create your own liquid staking pool and contribute to the growing DeFi ecosystem. If you are looking for more DeFi development services, connect with our blockchain developers for more information. 

Category: Blockchain
How To Create My Scalping Bot Using Node.js

Scalping in crypto trading refers to a strategy that involves taking advantage of small price movements within a short time frame. This blog post will guide you through creating a basic scalping bot using Node.js as a part of crypto trading bot development in Blockchain. It is a popular JavaScript runtime, ideal for building fast and scalable network applications. 

 

Read Also | Building a Chatbot based on Blockchain 

 

Prerequisites 

 

Before diving into the code, ensure you have the following: Basic understanding of JavaScript and Node.js Node.js installed on your machine An account with a cryptocurrency exchange that supports API trading (e.g., Binance) 

 

Setting Up the Project

 

 First, let's set up our Node.js project. Open your terminal and create a new directory for your project:

 

 plaintext mkdir crypto-scalping-bot cd crypto-scalping-bot npm init -y

 This initializes a new Node.js project. Next, install the required packages: 

 

plaintext npm install axios node-binance-api technicalindicators 

These packages include: axios for making HTTP requests. node-binance-api for interacting with the Binance API. technical indicators for calculating technical indicators. 

 

Connecting to the Binance API

 

Create a new file called index.js in your project directory. We'll start by setting up the connection to the Binance API: 

 

plaintext const Binance = require('node-binance-api'); 
const axios = require('axios'); 
plaintext const binance = new Binance().options({ APIKEY: 'your-api-key', APISECRET: 'your-api-secret' });

 Replace 'your-api-key' and 'your-api-secret' with your actual Binance API key and secret.

 

 

Fetching Market Data 

 

To make informed trading decisions, our bot needs to fetch current market data. We'll fetch candlestick data (OHLC) to analyze price movements: 

plaintext const getMarketData = async (symbol, interval) => { 
try { const candles = await binance.candlesticks(symbol, interval); 
return candles.map(candle => ({ 
openTime: candle[0], open: parseFloat(candle[1]), high: parseFloat(candle[2]), low: parseFloat(candle[3]), close: parseFloat(candle[4]), volume: parseFloat(candle[5]) 
}));
} catch (error) { 
console.error('Error fetching market data:', error); 
}
};
plaintext (async () =>; { 
const marketData = await getMarketData('BTCUSDT', '1m'); 
console.log(marketData); 
})(); 

This function retrieves candlestick data for a specified symbol and interval. The BTCUSDT pair and a 1-minute interval are used here as an example. 

Implementing a Simple Scalping Strategy

 

We'll use the Relative Strength Index (RSI) as our technical indicator to identify potential buy and sell signals. First, we need to calculate the RSI: 

plaintext const { RSI } = require('technicalindicators'); 
plaintext const calculateRSI = (prices, period = 14) =>
{ 
	return RSI.calculate({ values: prices, period }); 
}; 

Now, let's implement the scalping strategy based on the RSI: 

plaintext const executeTrade = async (symbol, side, quantity) => { 
	try { const order = await binance.marketOrder(symbol, side, quantity); 
		console.log('Order executed:', order); 
	} catch (error) { 
		console.error('Error executing trade:', error); 
	}
 }; 
 const scalpingStrategy = async (symbol) => { 
 const marketData = await getMarketData(symbol, '1m'); 
 const closingPrices = marketData.map(data => data.close);
 const rsiValues = calculateRSI(closingPrices); 
 const lastRSI = rsiValues[rsiValues.length - 1]; 
 console.log('Last RSI:', lastRSI); 
 const quantity = 0.001; // Example quantity if (lastRSI < 30) { 
 // Buy signal 
 await executeTrade(symbol, 'BUY', quantity); 
 } else if (lastRSI > 70) { 
 // Sell signal 
 await executeTrade(symbol, 'SELL', quantity); 
 } 
 }; 
 setInterval(() => { scalpingStrategy('BTCUSDT'); }, 60000); // Run every minute

 In this strategy, we fetch the latest market data every minute and calculate the RSI based on the closing prices. If the RSI is below 30, we execute a buy order. If it is above 70, we execute a sell order. 

 

Also, Learn About | How to create Trading Signals using TradingView via Webhook

 

Conclusion

 

This post demonstrated how to create a basic scalping bot using Node.js and the Binance API. While this is a simple example, real-world trading bots require more robust error handling, risk management, and advanced strategies. Always test your bots thoroughly and be aware of the risks involved in automated trading. Contact our blockchain developers today for expert assistance in your blockchain project. 

 

References (Click the Link): Medium 

Category: Blockchain
How to Create a Simple Supply Chain Smart Contract

Smart contract development holds immense potential in supply chain management. By leveraging the transparency, immutability, and automation features of blockchain, supply chain smart contracts can streamline operations, enhance trust among stakeholders, and mitigate the risk of fraud or errors. 

 

In this blog, we'll delve into the creation of a simple supply chain smart contract using Solidity. We'll break down the code step by step, explaining each component and its role in the contract's functionality.

 

You may also like | Supply Chain Development with Blockchain

 

Developing a Simple Supply Chain Smart Contracts

 

Let's start by examining the structure of our supply chain smart contract. The contract consists of several key components:

 

1. Enum for Order Status: We define an enumeration named Status to represent the different stages an order can be in—Pending, Shipped, and Delivered. This enum helps in tracking the progress of orders within the supply chain.

 

enum Status {
 Pending,
 Shipped,
 Delivered
}

 

2. Order Struct: Next, we define a struct named Order to encapsulate the details of each order. It includes fields such as the seller's address, the buyer's address, the price of the order, and its current status.

 

struct Order {
 address seller;
 address buyer;
 uint256 price;
 Status status;
}

 

3. Mapping for Orders: We declare a mapping named orders to store instances of the Order struct. Each order is associated with a unique order ID, which serves as the key in the mapping.

 

mapping(uint256 => Order) public orders;

 

4. State Variables: We declare a state variable—orderCount to keep track of the total number of orders and public to allow external access, and to increment order IDs sequentially.

 

You may also like | Blockchain for Procurement Management | Enabling Opportunities

 

uint256 public orderCount;

 

5. Events: We define three events—OrderCreated, OrderShipped, and OrderDelivered—to emit notifications whenever a new order is created, shipped, or delivered, respectively. Events provide a way to log and track important contract actions.

 

Also, Read | NFT Integration for Remodelling Supply Chain Processes

 

event OrderCreated(
 uint256 orderId,
 address indexed seller,
 address indexed buyer,
 uint256 price
);
event OrderShipped(uint256 orderId);
event OrderDelivered(uint256 orderId);

 

Discuss the Functions Defined within the Smart Contract and its Respective Functionalities

 

1. createOrder: This function allows sellers to create new orders by specifying the buyer's address and the price of the order. It validates the input parameters, increments the orderCount, creates a new Order instance, and stores it in the mapping of the order. Additionally, it emits the OrderCreated event to notify interested parties.

 

function createOrder(address _buyer, uint256 _price) external {
  require(_buyer != address(0), "Invalid buyer address");
  require(_price > 0, "Price must be greater than zero");

  orderCount++;
  orders[orderCount] = Order(msg.sender, _buyer, _price, Status.Pending);

  emit OrderCreated(orderCount, msg.sender, _buyer, _price);
}

 

2. shipOrder: Sellers use this function to mark an order as shipped once they have dispatched the goods. The function verifies that the caller is the seller of the specified order and that the order is in the "Pending" status. If the conditions are met, it updates the order status to "Shipped" and emits the OrderShipped event.

 

function shipOrder(uint256 _orderId) external {
  require(_orderId > 0 && _orderId <= orderCount, "Invalid order ID");
  require(
    msg.sender == orders[_orderId].seller,
    "Only seller can ship the order"
  );
  require(
    orders[_orderId].status == Status.Pending,
    "Order has already been shipped or delivered"
  );

  orders[_orderId].status = Status.Shipped;


  emit OrderShipped(_orderId);
}

 

3. deliverOrder: Buyers invoke this function to confirm the delivery of an order. Similar to the shipOrder function, it checks the caller's address and the current status of the order. If the conditions are satisfied, it updates the order status to "Delivered" and emits the OrderDelivered event.

function deliverOrder(uint256 _orderId) external {
  require(_orderId > 0 && _orderId <= orderCount, "Invalid order ID");
  require(
    msg.sender == orders[_orderId].buyer,
    "Only buyer can confirm delivery"
  );
  require(
    orders[_orderId].status == Status.Shipped,
    "Order has not been shipped yet"
  );

  orders[_orderId].status = Status.Delivered;

  emit OrderDelivered(_orderId);
}

 

You may also like  | Reimagining Supply Chain Management with NFTs

 

In conclusion, we have explored the development of a supply chain smart contract using Solidity. By employing blockchain technology and smart contracts, supply chain management processes can be made more efficient, transparent, and secure. The code provided in this article serves as a foundation for building more complex supply chain solutions, incorporating additional features such as payment processing, product tracking, and inventory management.
 

Here is the whole code for the smart contract:

 

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

contract SupplyChain {
    enum Status {
        Pending,
        Shipped,
        Delivered
    }

    struct Order {
        address seller;
        address buyer;
        uint256 price;
        Status status;
    }

    mapping(uint256 => Order) public orders;
    uint256 public orderCount;

    event OrderCreated(
        uint256 orderId,
        address indexed seller,
        address indexed buyer,
        uint256 price
    );
    event OrderShipped(uint256 orderId);
    event OrderDelivered(uint256 orderId);

    function createOrder(address _buyer, uint256 _price) external {
        require(_buyer != address(0), "Invalid buyer address");
        require(_price > 0, "Price must be greater than zero");

        orderCount++;
        orders[orderCount] = Order(msg.sender, _buyer, _price, Status.Pending);

        emit OrderCreated(orderCount, msg.sender, _buyer, _price);
    }

    function shipOrder(uint256 _orderId) external {
        require(_orderId > 0 && _orderId <= orderCount, "Invalid order ID");
        require(
            msg.sender == orders[_orderId].seller,
            "Only seller can ship the order"
        );
        require(
            orders[_orderId].status == Status.Pending,
            "Order has already been shipped or delivered"
        );

        orders[_orderId].status = Status.Shipped;

        emit OrderShipped(_orderId);
    }

    function deliverOrder(uint256 _orderId) external {
        require(_orderId > 0 && _orderId <= orderCount, "Invalid order ID");
        require(
            msg.sender == orders[_orderId].buyer,
            "Only buyer can confirm delivery"
        );
        require(
            orders[_orderId].status == Status.Shipped,
            "Order has not been shipped yet"
        );

        orders[_orderId].status = Status.Delivered;

        emit OrderDelivered(_orderId);
    }
}

 

For more information about solutions development for supply chain management powered by blockchain and smart contracts, connect with our skilled smart contract developers

Category: Blockchain
Create a Basic Smart Wallet Using the ERC4337 Standard

The ERC-4337 standard introduces a new account abstraction layer for Ethereum, enabling a more flexible and user-friendly approach to account management, especially for smart contract wallets. It allows transactions to be sent by smart contracts on behalf of users, opening up possibilities for paying transaction fees in tokens other than ETH, setting transaction parameters, and more complex account recovery mechanisms. For more information, visit Smart Contract Development Services

 

Creating a Smart Wallet using ERC4337 Token Standard 

 

Prerequisites:

 

Node.js and npm: Ensure that you have Node.js and npm installed on your machine.

Hardhat: Development framework for Ethereum, allowing for smart contract compilation, testing, and deployment.

Code Editor: Choose a code editor of your preference to code the smart contract. Example - VS Code.

 

Below is a simplified example of a smart contract that follows the ERC-4337 standard. This contract acts as a basic smart wallet that can hold funds and execute transactions on behalf of its owner.

 

Also, Explore | BRC-20 Wallet Development | What You Need To Know

 

Define the interface for ERC-20 tokens

 

interface IERC20 {
    //Transfer function
    function transfer(address to, uint amt) external returns (bool);
    //Approve function
    function approve(address spender, uint amt) external returns (bool);
    //Transfer from function
    function transferFrom(address from, address to, uint amt) external returns (bool);
    //Balance function
    function balanceOf(address _account) external view returns (uint);
}

 

Deposit and Withdrawal:

 

Functions are provided to deposit ETH into the wallet (deposit) and withdraw ERC20 tokens (withdrawToken). The contract can also receive ETH directly thanks to the receive function.

 

// Deposit funds into the wallet
    function deposit() external payable {}
// Withdraw ERC20 tokens from the wallet
    function withdrawERC20Token(IERC20 token, address to, uint256 amount) external onlyOwner {
        require(token.transfer(to, amount), "Token transfer failed");
    }
// Allow wallet to receive ETH
    receive() external payable {}

 

Transaction Execution: 

 

The executeTransaction function allows the owner to execute arbitrary transactions, sending ETH and data to other contracts or addresses

 

// Execute a transaction from the wallet
    function executeTransaction(address payable to, uint256 value, bytes calldata data) external onlyOwner {
        (bool success, ) = to.call{value: value}(data);
        require(success, "Transaction failed");
    }

 

Modifiers and Safety Checks

 

The onlyOwner modifier ensures that only the wallet owner can execute certain functions, adding a layer of security.

 

modifier onlyOwner() {
        require(msg.sender == owner, "Not the owner");
        _;
    }

 

Also, Explore | MPC Wallet Development | Enhancing Crypto Asset Security

 

This example is a basic illustration and can be extended with more features like multi-signature control, transaction limits, and recovery options to create a more robust and user-friendly smart wallet that leverages the ERC-4337 standard. You can find the whole code for the example below:

 

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

interface IERC20 {
    //Transfer function
    function transfer(address to, uint amt) external returns (bool);
    //Approve function
    function approve(address spender, uint amt) external returns (bool);
    //Transfer from function
    function transferFrom(address from, address to, uint amt) external returns (bool);
    //Balance function
    function balanceOf(address _account) external view returns (uint);
}

contract BasicSmartWallet {
    address public owner;

    modifier onlyOwner() {
        require(msg.sender == owner, "Not the owner");
        _;
    }

    constructor(address _owner) {
        owner = _owner;
    }

    // Deposit funds into the wallet
    function deposit() external payable {}

    // Execute a transaction from the wallet
    function executeTransaction(address payable to, uint256 value, bytes calldata data) external onlyOwner {
        (bool success, ) = to.call{value: value}(data);
        require(success, "Transaction failed");
    }

    // Allow wallet to receive ETH
    receive() external payable {}

    // Withdraw ERC20 tokens from the wallet
    function withdrawERC20Token(IERC20 token, address to, uint256 amount) external onlyOwner {
        require(token.transfer(to, amount), "Token transfer failed");
    }

    // Approve an allowance for an ERC20 token
    function approveToken(IERC20 token, address spender, uint256 amount) external onlyOwner {
        require(token.approve(spender, amount), "Token approve failed");
    }
}

 

If you are interested in developing similar or more complex blockchain-based solutions, like crypto wallets, smart contracts, or DeFi solutions, connect with our skilled smart contract developers to get started. 

Category: Blockchain
A Complete Guide on How to Create SPL Tokens on Solana

Solana, with its high throughput and low transaction costs, has emerged as a prominent blockchain for developing decentralized applications using Solana blockchain development services. The Solana Program Library (SPL) facilitates the creation of various tokens, from fungible to non-fungible assets. In this blog, we will explore how to create SPL tokens on Solana using JavaScript.

 

SPL Token Development

 

Prerequisites:

 

  • Node.js and npm: Ensure that you have Node.js and npm installed on your machine.
  • Solana Wallet: You'll need a Solana wallet to interact with the blockchain. Example - Phantom.
  • Code Editor: Choose a code editor of your choice. Example - VS Code.

 

Getting Started:

 

Follow the instructions below to create your own SPL tokens on Solana:

 

  • Initialize a Node.js Project: 


Create a new Node.js project for creating your spl-token by running the following commands in your terminal:

 

mkdir solana-spl-token

cd solana-spl-token

npm init -y

 

You may also like | Creating a Staking Smart Contract on Solana using Anchor

 

  • Install Required Packages: 


Install the necessary npm packages for interacting with the Solana blockchain

 

npm install @solana/web3.js @solana/spl-token bs58

 

  • Write token creation script:


Connect to a solana cluster.

 

const connection = new Connection(

   'https://api.devnet.solana.com',

   'confirmed'

 );

 

Add your wallet's secret key which will be used to create the token and pay for the network and transaction costs (your wallet needs to have SOL for the network fees).

 

const privateKey = ‘';

const walletKeypair = Keypair.fromSecretKey(

   new Uint8Array(bs58.decode(privateKey))

 );

 

Create a new SPL token using the “createMint” function provided by @solana/spl-token library. We are setting the mint authority and freeze authority of the token to the wallet whose secret key is used above.

 

const mint = await createMint(

   connection,

   walletKeypair, // payer

   walletKeypair.publicKey, // mint authority

   walletKeypair.publicKey, // freeze authority

   9 // Decimals for the token

 );

 

Run this command and execute the code to create your SPL token:

 

node createToken.js

 

Below is the output:

 

SPL Token created successfully!

Token Public Key: Ej1vq1r1y6ChmqX4fLri4ZJKG32RQzc3CiHYcPWZDL6Z

 

Also, Read | What Makes Solana Blockchain Development Stand Out

 

Conclusion:

 

You have successfully created SPL tokens on the Solana blockchain. This guide serves as a starting point, and you can further customize your token creation script based on your project requirements. You can find the whole code for this blog post here.

 

If you are looking to develop dAapps, NFT, or deFi projects on Solana blockchain, our solana developers can assist you with the most efficient development services. 

Category: Blockchain
Top Design Patterns in Node JS to Master

Node.js provides a scalable and efficient platform for highly efficient web and mobile app development. As the usage of Node.js for building backend applications is increasing day by day, it becomes crucial to adopt best practices and design patterns to ensure maintainability, scalability, and code reusability. In this blog post, we will be looking at some of the design patterns that can be implemented to obtain maintainability, scalability, and code reusability.

 

Design Patterns in Node.js

 

Singleton pattern
 

In the singleton design pattern, we make sure that a class has only one instance which is available globally for a whole application. This design pattern can be used when there is a need to control access to some shared resources eg- a database connection or a file. By using this pattern you can avoid unnecessary duplication and improve the efficiency of your application. 

 

Also, Explore | Essentials of Efficient UI/UX Design in Mobile App Development

 

Below is an example of the singleton pattern for a database connection. In this example class, “DatabaseConnection” follows the singleton design pattern and maintains only one instance of the database connection, whenever this class is instantiated, first it checks if an instance is already present, if not then only it creates a new connection to the database otherwise it just returns the already available instance.

 

/**
 * Singleton Pattern - Representing a class for Database connection
 */
class DatabaseConnection {
  constructor(str) {
    // check for instance
    if (!DatabaseConnection.instance) {
      this.connection = // create database connection
      this.testStr = str
      DatabaseConnection.instance = this;
    }
    // return instance
    return DatabaseConnection.instance;
  }
}
// create instance of class
const dbInstance1 = new DatabaseConnection("1");
const dbInstance2 = new DatabaseConnection("2");
console.log(dbInstance1.testStr)
console.log(dbInstance2.testStr)
Output of the above code:
1
1

 

Chain of Responsibility or Middleware pattern


The Middleware pattern is a key element in Node.js frameworks like Express. It involves a chain of functions that process an incoming request and response. Each middleware function has access to the request, response objects, and the next middleware function in the stack. This pattern is excellent for handling tasks such as authentication, logging, and error handling in a modular and reusable way.

 

You may also like | Native vs. Hybrid vs. Web | Choosing Mobile App Development

 

Below is an example of a chain of responsibility pattern implemented using the middleware functionality in Node.js. The code defines two middleware functions “middleware1” and “middleware2” which are used by the "app". Whenever a request comes to our "app" first it passes through "middleware1" and then through “middleware2” before moving to the business logic.

 

/**
 * Middleware Pattern - Representing middleware usage in Node.js
 */

// First middleware
const middleware1 = (req, res, next) => {
  // perform some tasks
  console.log("Inside middleware 1");
  next();
};

// Second middleware
const middleware2 = (req, res, next) => {
  // perform some tasks
  console.log("Inside middleware 2");
  next();
};

app.use(middleware1);
app.use(middleware2);
Output of the above code:
Inside middleware 1
Inside middleware 2

 

Facade pattern:

 
The Facade pattern provides a simple interface to a complex system, hiding its complexities. In Node.js, this can be applied to create a unified API for different modules or subsystems. By doing so, developers can interact with a simplified interface while the underlying complexities are managed behind the scenes.

 

Also, Read |  Cloud-based App Development | A Quintessential Guide

 

Below is an example of facade pattern implementation using a payment gateway class. “PaymentGateway” is a class that implements the functionality of handling payments internally, i.e., the complex processes of verifying a payment or processing the transaction are hidden from the client code, this makes the implementation more robust.

 

/**
 * Facade Pattern - Representing a Payment Gateway that hides its complexities
 */
class PaymentFacade {
  processPayment(amount) {
    // Create an instance of payment gateway
    const paymentGateway = new PaymentGateway();
    // Use the payment gateway to verify payment without knowing the underlying logic
    paymentGateway.verifyPayment();
    paymentGateway.processTransaction(amount);
    return 'Payment successful';
  }
}

 

Observer pattern


In the Observer design pattern an object, known as the subject (publisher), maintains a list of its dependents (subscriber or observer) who subscribe to events from the publisher, they are then informed about these events via different methods from the publisher. This pattern establishes a one-to-many relationship between the subject and its observers, allowing multiple objects to react to the changes in another object without being tightly coupled. 

 

In the below example, the “NewsAgency” is the subject or publisher which publishes news to it's observers, and “NewsReader” instances are observers. When the “NewsAgency” updates its news, all registered observers are notified and respond accordingly.

 

/**
 * Observer Pattern - Representing a News Agency that published news to News Readers
 */
 
// Subject or Publisher
class NewsAgency {
  constructor() {
    // List of observers for this news agency
    this.observers = [];
    this.news = null;
  }

  // Add observers
  addObserver(observer) {
    this.observers.push(observer);
  }

  // Remove observer
  removeObserver(observer) {
    this.observers = this.observers.filter((obs) => obs !== observer);
  }

  // Set News
  setNews(news) {
    this.news = news;
    // Notify the observers about the News
    this.notifyObservers();
  }

  // Notify the observers about the News
  notifyObservers() {
    this.observers.forEach((observer) => observer.update(this.news));
  }
}

// Observer or Subscriber
class NewsReader {
  constructor(name) {
    this.name = name;
  }

  update(news) {
    console.log(`${this.name} received news: ${news}`);
  }
}

// Instance of Publisher
const bbc = new NewsAgency();

// Instances of Subscribers
const john = new NewsReader('John');
const alice = new NewsReader('Alice');

// Add subscirbers to publisher
bbc.addObserver(john);

// Set News which also notifies the subscribers
bbc.setNews('Breaking News: Design patterns in Node.js');
Output of the above code:
John received news: Breaking News: Design patterns in Node.js

 

Conclusion

 

After looking at the above design patterns, now it is time to understand that before applying any design pattern to your application it's important to understand the context, requirement, and scalability of your application and then decide which pattern or a combination of patterns can help you develop the application in a more modular way. In case if you are looking for web and mobile app development, our skilled web and mobile app developers can help you get started quickly. 

An Exhaustive Guide to Ethereum Smart Contract Testing

Smart contracts have become a fundamental building block of decentralized applications (DApps) on blockchain platforms like Ethereum. After smart contract development, rigorous testing is essential to ensure the security and reliability of these contracts. In this blog post, we will learn about the tools and how to test a smart contract.

 

Ethereum Smart Contract Testing

 

Before starting with the testing, it is important to understand various types of testing and tools and frameworks used to test smart contracts for Ethereum.

 

Types of Testing for Solidity Smart Contracts

 

There are several types of testing for Solidity smart contracts, each serving a specific purpose:

 

  • Unit Testing: This involves testing individual functions or methods within a contract. It is the most granular level of testing and helps identify code-level issues.
  • Integration Testing: Integration testing focuses on how different parts of the smart contract interact with each other. It ensures that the contract's components work together harmoniously.
  • Functional Testing: Functional tests verify that the contract behaves as expected from an end-user perspective. It tests whether the contract correctly executes its intended functionality.
  • Security Audits: Security audits, often performed by external experts, identify vulnerabilities, including those that could lead to hacks or exploits.
  • Gas Usage Testing: Testing the gas usage of your contract helps optimize its efficiency and minimize transaction costs for users.

 

Tools and Framework

 

Several tools and frameworks are available to help test Solidity smart contracts:

 

  • Truffle: Truffle is a widely used development and testing framework for Ethereum. It provides various tools to compile, test, and deploy smart contracts.
  • Hardhat: Hardhat is an Ethereum development environment that includes a testing framework. It offers extensive support for writing tests and running them in a local environment.
  • Remix: Remix is an in-browser development and testing tool for Ethereum smart contracts. It is an excellent choice for quick contract testing and debugging.

 

Suggested Post | Analyzing Solidity and Vyper for Smart Contracts Programming

 

Test Case for an ERC-20 Smart Contract

 

In this section, we will test an ERC20 smart contract using the Hardhat environment. Below are the test cases for a standard ERC20 smart contract:

 

The “beforeEach” function deploys a new smart contract in the test environment for every “it” block in the test cases. Each “it” block has a description that denotes the functionality that the block tests.

 

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

describe("Token contract", function () {
  let Token;
  let token;
  let owner;
  let buyer;

  beforeEach(async function () {
    Token = await ethers.getContractFactory("MyToken");
    token = await Token.deploy(1000);
    [owner, buyer] = await ethers.getSigners();
  });

  describe("Deployment", function () {
    it("Should return the right owner as set during deployment", async function () {
      expect(await token.balanceOf(owner.address)).to.equal(1000);
    });

    it("Should return the total supply as set during deployment", async function () {
      expect(await token.totalSupply()).to.equal(1000);
    });
  });

  describe("Transactions", function () {
    it("Should transfer tokens between different accounts", async function () {
      await token.transfer(buyer.address, 100);
      expect(await token.balanceOf(owner.address)).to.equal(900);
      expect(await token.balanceOf(buyer.address)).to.equal(100);
    });

    it("Should fail if sender doesn’t have enough tokens for transfer", async function () {
      const initialOwnerBalance = await token.balanceOf(owner.address);

      await expect(
        token.transfer(buyer.address, 10000)
      ).to.be.revertedWithoutReason();

      expect(await token.balanceOf(owner.address)).to.equal(initialOwnerBalance);
    });

    it("Should update allowance after approve", async function () {
      await token.approve(buyer.address, 100);
      expect(await token.allowance(owner.address, buyer.address)).to.equal(100);
    });

    it("Should transfer tokens from one account to another with allowance", async function () {
      await token.approve(buyer.address, 100);
      await token.transferFrom(owner.address, buyer.address, 100);

      expect(await token.balanceOf(owner.address)).to.equal(900);
      expect(await token.balanceOf(buyer.address)).to.equal(100);
      expect(await token.allowance(owner.address, buyer.address)).to.equal(0);
    });

    it("Should fail if sender doesn’t have enough allowance", async function () {
      await token.approve(buyer.address, 99);

      await expect(
        token.transferFrom(owner.address, buyer.address, 100)
      ).to.be.revertedWith("ERC20: transfer amount exceeds allowance");
    });
  });
});

 

Also, Discover: A Definitive Guide to Smart Contract Development Tools

 

Smart Contract Development with Oodles

 

Smart contracts developers at Oodles Blockchain have expertise in programming languages like Solidity, Elixir, Rust, Golang, and more. you can automate your business with our smart contract development services. Connect with our smart contract developers to discuss your project requirements.

Everything You Need to Know About Derivative Trading

Derivative is a contract whose value is derived from an underlying asset. The underlying asset can be a stock, bond, commodity, currency, or even an index. Derivatives essentially act as contracts between two parties, speculating on the future value of the underlying asset. They enable investors to speculate on price movements, hedge against potential risks, or gain exposure to various markets. Derivates trading can also take place in the crypto space with the help of crypto exchange development services.

 

Types of derivatives:

 

Futures Contracts:

 

Futures contract is an agreement to buy or sell an asset at a pre-agreed price on a specific future date. They provide investors with the opportunity to profit from price movements without owning the underlying asset.

 

Options Contracts:

 

Options give the holder the right, but not the obligation, to buy (call option) or sell (put option) an asset at a predetermined price within a specified period. Options provide flexibility and can be used for speculation, hedging, or generating income.

 

Swaps:

 

Swaps involve the exchange of cash flows or assets between two parties over a specific period. The most common types of swaps include interest rate swaps, currency swaps, and commodity swaps. Swaps are often utilized by institutions to manage interest rates, currency, or commodity risks.

 

Derivative Trading Strategies

 

Speculation:

 

Traders can invest with a hope of gain but with a risk of loss on the future price movements of the underlying asset. They can go long (buy) if they expect the price to rise or go short (sell) if they anticipate a decline. The speculation involves taking calculated risks based on market analysis, trends, and other factors.

 

Hedging:

 

Derivatives are often used for hedging purposes to mitigate potential risks. For example, a farmer may enter into a futures contract to sell their crop at a predetermined price, protecting them from adverse price movements. Hedging helps reduce exposure to volatility and safeguards against potential losses.

 

Arbitrage:

 

Arbitrage involves exploiting price discrepancies between different markets or related securities. Traders identify opportunities where the same asset is priced differently, allowing them to buy low and sell high to capture risk-free profits.

 

Spread Trading:

 

Spread trading is basically about taking opposite positions(put/call) in related derivatives contracts. For instance, a trader might buy a call option on a particular stock and simultaneously sell a call option on the same stock with a higher strike price. Spread trading aims to profit from the price difference between the two options.

 

Risk Considerations

 

While derivative trading can be lucrative, it is crucial to recognize and manage the associated risks:

 

Market Risk:

 

Derivative prices are influenced by market conditions and can be highly volatile. Unforeseen events, economic indicators, and geopolitical factors can significantly impact prices, leading to substantial gains or losses.

 

Counterparty Risk:

 

Derivatives are typically traded over-the-counter (OTC), which involves counterparty risk. If the other party defaults on their obligations, it can result in financial loss. Trading on regulated exchanges reduces this risk by providing clearing and settlement mechanisms.

 

Leverage Risk:

 

Derivatives often provide leverage, allowing traders to control a larger position with a smaller initial investment. Traders should move with caution and use risk management strategies in order to their capital because leverage does both boost profits and also amplify losses.

 

Derivative trading offers opportunities for profit, risk management, and market participation. By understanding the various derivative instruments, trading strategies, and associated risks, investors can make informed decisions. However, it is essential to gain knowledge, seek professional advice, and engage in thorough market analysis before venturing into derivative trading. With the right approach and risk management, derivative trading can be a powerful tool in the hands of skilled investors.
 

If you are looking for development services for a project related to derivatives trading, you may connect with our skilled web and mobile app developers to get started.

Create Your Own Cryptocurrency with JavaScript

Cryptocurrency is a decentralized form of digital currency that operates independently of a central bank or government. Cryptocurrency development relies on blockchain technology, which is a distributed ledger that records all transactions across multiple computers or nodes. In this blog post, we will simulate a blockchain with javascript code in which users can have wallets that contain public and private keys.

 

Cryptocurrency Development with JavaScript

 

We will simulate a blockchain using JavaScript code, where users can possess wallets containing public and private keys. Within this simulation, users have the ability to initiate transactions that are subsequently incorporated into blocks, eventually forming a complete blockchain structure.

 

For the implementation, we will have 4 classes - Transaction, Block, Wallet, and Chain.



Transaction Class

 

This class simulates the transaction on a blockchain

 

Constructor:

 

  • The constructor method is called when a new instance of the Transaction class is created.
  • It takes three parameters: amount, senderAddress, and receiverAddress.
  • These parameters represent the amount of the transaction and the addresses of the sender and receiver, respectively.
  • Inside the constructor, the values are assigned to the corresponding properties of the transaction object.

 

toString() method:

 

  • This method converts the transaction object to a string representation.
  • It returns a JSON string representation of the transaction object using JSON.stringify(this).
  • The ‘this’ keyword refers to the current transaction object.

 

Suggested Post | MPC Wallet Development | Enhancing Crypto Asset Security

 

Block Class

 

This class simulates the blocks on the blockchain.

 

Constructor:

 

  • The constructor method is called when a new instance of the Block class is created.
  • It takes three parameters: previousHash, transaction, and timestamp.
  • previousHash represents the hash of the previous block in the chain.
  • transaction is the transaction associated with the current block.
  • timestamp is an optional parameter representing the timestamp of when the block was created. If not provided, the current timestamp (obtained using Date.now()) is used.
  • Inside the constructor, the values are assigned to the corresponding properties of the block object.

 

getHash() method:

 

  • This method calculates and returns the hash of the block.
  • It converts the block object to a JSON string representation using JSON.stringify(this).
  • It then uses the SHA-256 algorithm from the crypto module to compute the hash of the JSON string.
  • The resulting hash is returned as a hexadecimal string.

 

toString() method:

 

  • This method converts the block object to a string representation.
  • It returns a JSON string representation of the block object using JSON.stringify(this).
  • The ‘this’ keyword refers to the current block object.

 

Also, Visit | AI Crypto Trading Bots | Reshaping Crypto Trading

 

Wallet Class

 

This class simulates the wallet on the blockchain.

 

Constructor:

 

  • The constructor method is called when a new instance of the Wallet class is created.
  • Inside the constructor, a key pair is generated using the crypto.generateKeyPairSync() function from the crypto module.
  • The generateKeyPairSync() function generates a public-private key pair using the RSA encryption algorithm.
  • The key pair is then stored in the privateKey and publicKey properties of the wallet object.

 

send(amount, receiverAddress) method:

 

  • This method facilitates a transaction by creating a new Transaction object, signing it with the sender's private key, and inserting a new block into the blockchain.
  • It takes two parameters: amount (the amount to be sent in the transaction) and receiverAddress (the address of the recipient).
  • Inside the method, a new Transaction object is created using the provided amount, the wallet's publicKey as the sender's address, and the receiverAddress as the recipient's address.
  • The crypto.createSign() function is used to create a sign object with the SHA-256 hashing algorithm.
  • The update() method of the sign object is called with the transaction converted to a string using transaction.toString().
  • The sign() method is then called on the sign object, passing the wallet's privateKey to sign the transaction.
  • The resulting signature is passed along with the transaction and the wallet's publicKey to the insertBlock() method of the Chain class, adding a new block to the blockchain.

 

Chain Class

 

This class simulates the blockchain itself.

 

Constructor:

 

  • The constructor method is called when a new instance of the Chain class is created.
  • Inside the constructor, the initial state of the blockchain is set by creating a genesis block.
  • The genesis block is created using an empty string as the previous hash and a default transaction with zero amount and arbitrary sender and receiver addresses.
  • The genesis block is then stored as the first block in the chain array.

 

getPreviousBlockHash() method:

 

  • This method returns the hash of the previous block in the chain.
  • It retrieves the last block in the chain array using this.chain[this.chain.length - 1].
  • The getHash() method of the block object is called to obtain its hash.

 

insertBlock(transaction, senderAddress, sig) method:

 

  • This method inserts a new block into the blockchain after verifying the integrity and authenticity of the provided transaction.
  • It takes three parameters: transaction (the transaction to be included in the block), senderAddress (the address of the transaction sender), and sig (the signature of the transaction signed by the sender).
  • Inside the method, a crypto.createVerify() object is created with the SHA-256 hashing algorithm to perform the verification.
  • The update() method of the verify object is called with the string representation of the transaction obtained using transaction.toString().
  • The verify() method is then called on the verify object, passing the senderAddress and the sig to verify the signature.
  • If the signature is valid, a new block is created using the getPreviousBlockHash() method to retrieve the previous block's hash.
  • The new block is added to the chain array using this.chain.push(block).

 

getBalance(address) method:

 

  • This method calculates and returns the balance of a user based on their address.
  • It takes one parameter: address (the address of the user).
  • Inside the method, a variable named balance is initialized to zero.
  • The method iterates over each block in the chain array using forEach().
  • For each block, it checks if the senderAddress of the block's transaction matches the given address. If true, it subtracts the transaction amount from the balance.
  • It also checks if the receiverAddress of the block's transaction matches the given address. If true, it adds the transaction amount to the balance.
  • Finally, the calculated balance is returned.

 

Check It Out | Hiring Smart Contract Developers Made Easy​​​​​​​

​​​​​​​

const crypto = require('crypto');

 

// Transaction class to demostrate transactions on blockchain

class Transaction {

 // A transaction will have amount, sender address, reciever address

 constructor(amount, senderAddress, recieverAddress) {

   this.amount = amount;

   this.senderAddress = senderAddress;

   this.recieverAddress = recieverAddress;

 }

 

 // Convert the transaction details to string

 toString() {

   return JSON.stringify(this);

 }

}

 

// Block class to demonstrate blocks in blockchain

class Block {

 // A block consists of hash of previous block, transactions and time

 constructor(previousHash, transaction, timestamp = Date.now()) {

   this.previousHash = previousHash;

   this.transaction = transaction;

   this.timestamp = timestamp;

 }

 

 // Function to get the hash of the block

 getHash() {

   const json = JSON.stringify(this);

   const hash = crypto.createHash('SHA256');

   hash.update(json).end();

   const hex = hash.digest('hex');

   return hex;

 }

 

 // Convert the block details to string

 toString() {

   return JSON.stringify(this);

 }

}

 

class Wallet {

 constructor() {

   // Create public and private keys at the time of instantiation

   const keys = crypto.generateKeyPairSync('rsa', {

     modulusLength: 2048,

     publicKeyEncoding: { type: 'spki', format: 'pem' },

     privateKeyEncoding: { type: 'pkcs8', format: 'pem' },

   });

   this.privateKey = keys.privateKey;

   this.publicKey = keys.publicKey;

 }

 

 // Function to send the transaction

 send(amount, recieverAddress) {

   const transaction = new Transaction(

     amount,

     this.publicKey,

     recieverAddress

   );

   const shaSign = crypto.createSign('SHA256');

   // add the transaction json

   shaSign.update(transaction.toString()).end();

   // sign the SHA with the private key

   const signature = shaSign.sign(this.privateKey);

   Chain.instance.insertBlock(transaction, this.publicKey, signature);

 }

}

 

// Chain class to demonstrate the blockchain itself

class Chain {

 // Only instance of the chain class

 static instance = new Chain();

 

 // initializing our chain with no records

 constructor() {

   this.chain = [new Block('', new Transaction(0, 'abc', 'xyz'))];

 }

 

 // Returns the hash of the previous block

 getPreviousBlockHash() {

   // sending the entire block itself

   return this.chain[this.chain.length - 1].getHash();

 }

 

 // Add new block in the chain

 insertBlock(transaction, senderAddress, sig) {

   // create verifier

   const verify = crypto.createVerify('SHA256');

   // add the transaction JSON

   verify.update(transaction.toString());

 

   // Verify it with the sender's public key

   const isValid = verify.verify(senderAddress, sig);

 

   if (isValid) {

     const block = new Block(this.getPreviousBlockHash(), transaction);

     console.log('Block added: ', block.toString());

     this.chain.push(block);

   }

 }

 

 // Function to get the balance of a user

 getBalance(address) {

   let balance = 0;

   this.chain.forEach((block) => {

     if (block.transaction.senderAddress === address) {

       balance -= block.transaction.amount;

     }

 

     if (block.transaction.recieverAddress === address) {

       balance += block.transaction.amount;

     }

   });

   return balance;

 }

}

 

const satoshi = new Wallet();

const vitalik = new Wallet();

const sid = new Wallet();

 

satoshi.send(50, vitalik.publicKey);

vitalik.send(23, sid.publicKey);

sid.send(5, vitalik.publicKey);

 

const vitalikBal = Chain.instance.getBalance(vitalik.publicKey);

const sidBal = Chain.instance.getBalance(sid.publicKey);

 

console.log(Chain.instance);

console.log('Vitalik has: ', vitalikBal);

console.log('Sid has: ', sidBal);


 
How to Create Your Own Whale Alert

What is a Whale Alert?

 

A whale alert is a notification system that notifies the user whenever a large amount of cryptocurrency is moved or traded. Whale alerts keep track of the blockchain transactions and/or wallets that have a large number of cryptocurrencies and have the ability to influence the market with their actions.

 

To detect large transactions, whale alert services use different algorithms to analyze the blockchain and identify transactions that meet certain criteria, such as transactions that involve a large amount of cryptocurrency or transactions that involve specific wallets or addresses known to belong to whales.

 

You may also like to explore | Cryptocurrency Development Services

 

Once a large transaction is detected, the whale alert service sends out an alert through various channels, such as social media, email, or mobile notifications. The alert typically includes information about the transaction, such as the amount of cryptocurrency involved, the sender and recipient addresses, and the time and date of the transaction.

 

In this guide, we will create our whale alert using NodeJs and web3.js library.

 

Creating your own Whale Alert

 

To make a whale alert service you need to decide a few things before starting the development:

 

  1. First, you need to decide which blockchain to target- we will use the Ethereum blockchain for our whale alert.
  2. Setup a blockchain node- we will use the web3.js library to connect to an Ethereum node.
  3. Keep track and analyze the transactions- we will listen to the blockchain transactions using web3.js and alert if the value of any transaction is greater than a specified value.
  4. Create an alert- Decide how you want to give alerts to users, some possible options are sending emails or making a tweet, etc. To keep things simple we will just log the details of the transaction in the console.

 

Below is the code for our custom whale alert - We are keeping track of the transactions of each block and if the value of any transaction is greater than the threshold value, then the code will print an alert in the console with the details of the transaction.

 

The threshold value set in our example is 0.5 ethers, you can change the value on line 8 and use the whale alert according to your requirements.

 

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

const INFURA_URL = '';

// Connect to Blockchain node

const provider = new ethers.JsonRpcProvider(INFURA_URL);

 

// Threshold value

const THRESHOLD = ethers.parseEther('0.5');

 

console.log('Welcome to our Custom Whale Alert!\n');

 

// Whenever a new block is created,

// the callback function is called with the blockNumber

provider.on('block', async (blockNumber) => {

 console.log(`Watching ${blockNumber} Block\n`);

 // Getting the block details

 const block = await provider.getBlock(blockNumber);

 const transactions = block.transactions;

 // Looping over the transactions of the block

 for (const transactionHash of transactions) {

   const transaction = await provider.getTransaction(transactionHash);

   // Check if the 'value' of the current transaction

   // is greater than the THRESHOLD value

   if (transaction.value > THRESHOLD) {

     // Create an alert

     console.log(

       'WHALE ALERT\n',

       `Transaction Hash: ${transaction.hash}\n`,

       `Sender's Address: ${transaction.from}\n`,

       `Reciever's Address: ${transaction.to}\n`

     );

   }

 }

});

Create a dApp using Substrate Framework

Substrate is a framework designed to make it easier for the developer to build custom blockchain applications. To use Substrate, developers can download the Substrate development kit and start building their own blockchain applications. The development kit includes tools for building, testing, and deploying Substrate-based applications.

 

In this blog post, we will be building a simple dApp which stores a value and multiplies it by some value whenever a function is executed. We will also write unit test cases for testing the contract.

 

Developing a dApp with Substrate

 

Installation:

 

Before starting the development process you need to have Rust installed. For installing Rust you can refer to this link. After installing rust you need to update your development environment to develop smart contracts. Follow the steps below to update your development environment.

 

  • Add the rust-src compiler component: rustup component add rust-src
  • Install the latest version of cargo-contract: cargo install --force --locked cargo-contract --version 2.0.0-rc
  • Verify the installation and explore the commands available by running the following command: cargo contract --help
  • Install the substrate contracts node: cargo install contracts-node --git https://github.com/paritytech/substrate-contracts-node.git --tag <latest-tag> --force --locked

 

Note - You can find the latest tag here.

 

  • You can verify the installation by running the following command: substrate-contracts-node --version

 

Before moving forward make sure that you have followed all the above steps and that you have:

 

  • Rust installed and set up your development environment.
  • Substrate contracts node installed locally.

 

Building the Dapp:

 

Smart contracts on the substrate start as projects, which are created by using the cargo contract commands. Creating a new project provides us with the template starter files, we will modify these starter files to build the logic of our dApp.

 

  • Open a terminal in your working directory and run the command to create a new project:

cargo contract new multiplicator

  • Change to the new project directory and open the lib.rs file in a code editor.
  • By default, the flipper smart contract source code in the template lib.rs file has instances of "flipper" modified to "multiplicator" (our project name).
  • Replace the code in lib.rs file with the code below.

 

#![cfg_attr(not(feature = "std"), no_std)]

 

#[ink::contract]

mod multiplicator {

 

   /// Defines the storage of your contract.

   /// Add new fields to the below struct in order

   /// to add new static storage fields to your contract.

   #[ink(storage)]

   pub struct Multiplicator {

       /// Stores a single `i32` value on the storage.

       value: i32,

   }

 

   impl Multiplicator {

       /// Constructor that initializes the `i32` value to the given `init_value`.

       #[ink(constructor)]

       pub fn new(init_value: i32) -> Self {

           Self { value: init_value }

       }

 

       /// Constructor that initializes the `i32` value to 1.

       /// Constructors can delegate to other constructors.

       #[ink(constructor)]

       pub fn default() -> Self {

           Self::new(1)

       }

 

       /// Multiply value by 2.

       #[ink(message)]

       pub fn mul_by_2(&mut self) {

           self.value = self.value * 2;

       }

 

       /// Multiply value by the passed parameter.

       #[ink(message)]

       pub fn mul(&mut self, by: i32) {

           self.value = self.value * by;

       }

 

       /// Simply returns the current value of our `i32`.

       #[ink(message)]

       pub fn get(&self) -> i32 {

           self.value

       }

   }

 

   /// Unit tests

   #[cfg(test)]

   mod tests {

       /// Imports all the definitions from the outer scope so we can use them here.

       use super::*;

 

       /// We test if the default constructor does its job.

       #[ink::test]

       fn default_works() {

           let multiplicator = Multiplicator::default();

           assert_eq!(multiplicator.get(), 1);

       }

 

       /// We test if the other constructor does its job.

       #[ink::test]

       fn other_constructor_works() {

           let multiplicator = Multiplicator::new(2);

           assert_eq!(multiplicator.get(), 2);

       }

 

       /// We test if the other mul_by_2 function does its job.

       #[ink::test]

       fn mul_by_2_works() {

           let mut multiplicator = Multiplicator::default();

           assert_eq!(multiplicator.get(), 1);

           multiplicator.mul_by_2();

           assert_eq!(multiplicator.get(), 2);

       }

 

       /// We test if the other mul function does its job.

       #[ink::test]

       fn mul_works() {

           let mut multiplicator = Multiplicator::new(2);

           assert_eq!(multiplicator.get(), 2);

           multiplicator.mul(2);

           assert_eq!(multiplicator.get(), 4);

       }

   }

}

 

Now, let's understand the code and the test cases:

 

  • Storage fields:

#[ink(storage)] - This macro indicates that the struct defined below defines the storage fields of the contract.

 

  • Constructors:

#[ink(constructor)] - This macro indicates that it is a constructor. We have 2 constructors in our code. One [ default() ] which initializes the ‘value’ with a default value of 1. The other [ new(init_value: i32) ] which initializes the ‘value’ with the ‘init_value’ passed as parameter.

 

  • Functions:

 

We have 3 public functions defined in the contract. #[ink(message)] - This macro indicates that it is a public function.

 

  1. mul_by_2(&mut self) - It does not take any arguments. ‘mut’ indicates that this function can mutate the state variables of the contract. ‘self’ is passed to give reference to the contract. This function just simply multiples the current value by 2 and updates the ‘value’ with the result.
  2. mul(&mut self, by: i32) - It takes one argument ‘by’ which is multiplied with the current value and updates the ‘value’ with the result.
  3. get(&self) - It just simply returns the current value of ‘value’. Note that ‘mut’ keyword is not present in this function as this function does not change the state of the contract. 

 

  • Tests:

#[cfg(test)] - This macro defines the test cases for the contract.

#[ink::test] - This macro defines the functions which test the contract.

 

If you have a project in mind and need information on getting started with dApp development with Substrate, you may connect with our skilled blockchain developers.
 

 

How to Develop a DEX on BSC

Decentralized exchanges (DEXs) are gaining in popularity as an alternative to centralized exchanges. Built using crypto exchange development services, they offer users more control over their assets and a higher level of security. Binance Smart Chain (BSC) is a decentralized platform that runs on a smart contract-enabled blockchain and is compatible with Ethereum Virtual Machine (EVM). In this blog post, we will guide you through the steps to develop your own DEX on Binance Smart Chain.

 

Develop a DEX on BSC 

 

Step 1: Familiarize yourself with Binance Smart Chain and its features

 

Before you start developing your DEX, it is important to understand the features and capabilities of Binance Smart Chain. BSC is a decentralized platform that allows users to create and execute smart contracts and decentralized applications (DApps). It is also compatible with Ethereum Virtual Machine (EVM), which means you can use Solidity, the primary language for Ethereum development, to write smart contracts for BSC.

 

One of the key advantages of BSC is its faster transaction times and lower fees compared to Ethereum. This makes it an attractive choice for developers looking to build DApps and DEXs that require fast and cost-effective transactions.

 

Step 2: Choose a programming language

 

To develop a DEX on Binance Smart Chain, you will need to use a programming language that is supported by BSC. Some popular options include Solidity (the primary language used for Ethereum development), Rust, and Go.

 

Before choosing a programming language, consider the following factors:

 

  • Your level of experience and familiarity with the language
  • The community support and resources available for the language
  • The suitability of the language for the specific features and functionality you want to include in your DEX

 

Step 3: Set up a development environment

 

Before you start coding, you will need to set up a development environment on your local machine. This includes installing the necessary tools and libraries, such as a BSC-compatible blockchain client, a code editor, and a BSC testnet.

 

The testnet is a simulated blockchain environment that allows you to test your DEX without incurring real costs or risks. It is important to thoroughly test your DEX on the testnet before deploying it to the main BSC network.

 

Also, Explore | Atomic Swaps | The Future of Decentralized Exchanges (DEX)

 

Step 4: Design the DEX architecture

 

The next step is to decide on the overall structure and features of your DEX. This includes the trading engine, order matching algorithms, and user interface. You will also need to decide on the security measures you will implement to protect users' assets.

 

Some of the key features to consider when designing your DEX include:

 

  • Trading pairs: The types of tokens that users can trade on your DEX
  • Order types: The different types of orders that users can place, such as limit orders, market orders, and stop orders
  • Order book: The list of buy and sell orders for a particular trading pair
  • Matching algorithm: The algorithm that matches buy and sell orders to execute trades
  • User accounts: The system for registering and authenticating users on your DEX

 

Step 5: Write the smart contracts

 

Once you have designed the architecture of your DEX, you can start writing the smart contracts that will power it. These contracts will handle tasks such as registering users, processing trades, and managing the order book.

 

It is important to thoroughly test and debug your smart contracts before deploying them to the BSC testnet or main network.

 

Also, Explore | Essentials to Consider for DEX Aggregator Development

 

Step 6: Test and deploy the DEX

 

After writing and debugging your smart contracts, you can deploy your DEX smart contracts on the BSC Mainnet.

 

If you are interested in developing a decentralized crypto exchange on BSC, or on any other efficient blockchain platform like Ethereum, Cardano, etc. connect with our skilled blockchain developers to get started. 

Understanding the Importance of Cross Chain dApps

In this world of evolution, Web3 is also growing rapidly and this can be seen with the introduction of multi-chain and cross-chain dApps. With an increase in the need for blockchains to communicate with each other, these concepts of multi-chain and cross-chain dApps are revolutionary. In this blog post, we'll help you understand the differences between multi-chain and cross-chain dApps development.

 

Multi-Chain dApps

 

Multi-chain dApps are applications that are deployed on more than one blockchain, but they are isolated deployments which means that they are not connected to each other and do not communicate with each other, even if both applications are the same.

 

Whenever smart contracts of a multi-chain dApp are deployed on a new blockchain network, it creates an entirely new copy of smart contracts on that network, thus creating their own separate internal states for managing data (eg- tracking balances). These dApps have no to limited interoperability between deployments on different blockchains networks. This affects the user experience as they do not necessarily get the same experience on using the same dApp on two different blockchain networks.

 

Cross-Chain dApps 

 

Cross-chain is an emerging concept for dApps development. It involves smart contracts on different blockchain networks that can communicate and coordinate with each other. They work behind the scenes to allow end-users to access and utilize their assets and resources on one chain from another chain.

 

This concept empowers the developers to split up their applications and modularize them in order to take advantage of the unique features of different blockchain networks. For example, different smart contracts on different chains for specific functionalities and they are synced together and work as a single entity.

 

Blockchains by default do not have any mechanism to send and receive data between different networks. This functionality can be achieved by cross-chain bridges which enable an exchange of information between networks. However cross-chain dApps require more generalized bridges which are secure, reliable, and free from corruption. These all requirements can be achieved by decentralized oracles which in the past solved the issue of the inability of blockchain to access off-chain resources. The latest evolution in order to achieve this cross-chain interoperability functionality is General Message Passing (GMP).

Category: Blockchain
An Ultimate Guide to Metaverse as a Service

What is Metaverse?

 

To begin with, let's first discuss what a metaverse is all about. The metaverse is a virtual world that does not exist in reality but we can still experience and interact with it with the help of virtual reality and augmented reality. A metaverse uses a virtual representation of real-world objects and assigns unique avatars to represent them. This technique enables users to interact with avatars of other users in the virtual world.

Video games are the closest examples of what the metaverse would be around us. For example, in video games, you feel as if you are actually in that virtual world, and also your actions on the remote control decide what comes up next in that virtual world.

 

Metaverse as a service:

The introduction of Web 3.0, brings many concepts which it incorporates into itself, such as decentralization, blockchain technology, etc. The interest in the metaverse field also arises due to the introduction of this Web 3.0. 

 

The metaverse can really prove to be powerful in many aspects of life in the near future. One such example could be, you work in a 3D office in the luxury of your home, isn’t this cool? You can interact with your colleagues through their hologram avatars and whatnot. The fields in which the concept of metaverse can be applied are very vast. Let’s discuss a few:

 

Social Networking:

 

Current social media networks like Facebook, Instagram, WhatsApp, etc. provide their users with features that are only available on a screen. The introduction of a metaverse in the field of social networks can be a revolutionary step. User experience will then be more immersive and the users can then experience real-time interactions as if they were interacting in the real world.

 

Online Education:

 

As we can see, the pandemic has caused the education system to shift towards online learning and teaching with the help of video conferencing. This change has affected the students' learning as they no longer experience the environment of a classroom. The introduction of metaverse in this field would provide an immersive experience to the students and their learning can improve with the help of 3D learning tools and access to the best teachers and professors with just a click.

 

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!