aiShare Your Requirements
Mohd  Yasar Oodles

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

Experience: 3+ 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

SkillsSkills

DotSolidity

80%

DotNode Js

80%

DotBlockchain

80%

DotDyanmoDB

60%

DotEthers.js

100%

DotRaydium

100%

DotWeb3.js

80%

DotJavascript

80%

DotPostgres

60%
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
Integrating HL7 and FHIR in Healthcare App for Data Exchange Healthcare systems often use different software that doesn't easily share information with each other. For example, hospitals, labs, pharmacies, and insurance systems may all store and manage data in their own way, making communication difficult. To solve this problem, two important standards are used:HL7 v2 → An older messaging standard used to send data between systemsFHIR → A modern standard that uses APIs to share data in a simple and flexible wayIn this guide, we'll learn how to use both HL7 and FHIR together with Node.js to help different healthcare systems exchange data smoothly and work better together.Architecture OverviewA typical integration architecture looks like this:[ HL7 Source Systems ] ↓[ Integration Layer (Node.js) ] ↓[ FHIR Server / API ] ↓[ Web / Mobile Apps ]Our Node.js service acts as:HL7 message receiverParser and transformerFHIR API clientSetting up the projectInitialize a new Node.js project:mkdir hl7-fhir-integration cd hl7-fhir-integration npm init -yInstall dependencies:npm install express axios body-parser npm install hl7-standardReceiving HL7 messagesHL7 messages are often sent over TCP (MLLP protocol), but for simplicity, we'll simulate receiving them via HTTP.// server.js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.text({ type: '*/*' })); app.post('/hl7', (req, res) => { const hl7Message = req.body; console.log('Received HL7 Message:\n', hl7Message); // Process message here res.send('ACK'); }); app.listen(3000, () => { console.log('HL7 Receiver running on port 3000'); }); Also, Check | Patient Portal Development with React.js and FirebaseParsing HL7 messagesWe'll use the "hl7-standard" library to parse HL7 messages.Example HL7 message:MSH|^~\&|HIS|Hospital|LAB|LabSystem|20250401||ADT^A01|12345|P|2.5 PID|1||12345||John^Doe||19900101|MParsing it:const HL7 = require('hl7-standard'); function parseHL7(message) { const hl7 = new HL7(message); hl7.transform((err) => { console.log('Transforming HL7 Message...', err); if (err) throw err; }); const pid = hl7.get('PID'); if (!pid) { throw new Error('PID segment not found'); } return { id: pid['PID.3'] || null, firstName: pid['PID.5']?.['PID.5.1'] || null, lastName: pid['PID.5']?.['PID.5.2'] || null, dob: pid['PID.7'] || null, gender: pid['PID.8'] || null, }; }Mapping HL7 to FHIRNow we convert parsed HL7 data into a FHIR-compliant resource.function mapToFHIRPatient(data) { return { resourceType: 'Patient', id: data.id, name: [{ given: [data.firstName], family: data.lastName }], birthDate: data.dob, gender: data.gender === 'M' ? 'male' : 'female', }; }Putting it all togetherUpdate the /hl7 endpointapp.post('/hl7', async (req, res) => { const hl7Message = req.body; console.log('Received HL7 Message:\n', hl7Message); try { const parsed = parseHL7(hl7Message); const fhirPatient = mapToFHIRPatient(parsed); console.log('Mapped FHIR Patient:\n', JSON.stringify(fhirPatient, null, 2)); res.send('MSA|AA|12345'); // ACK } catch (err) { console.error(err); res.status(500).send('MSA|AE|12345'); // Error ACK } });You may also like | FHIR and Blockchain | A New Age of Healthcare Data ManagementHandling different HL7 message typesHL7 is event-driven, which means every message corresponds to a real-world clinical event—such as a patient being admitted, a lab result being generated, or a doctor placing an order.Because of this, each HL7 message type has a different structure and meaning, and therefore requires different transformation logic when converting into FHIR resources.Instead of using a one-size-fits-all approach, our integration layer should:Identify the message type (from the MSH segment)Route the message to the correct handlerApply specific transformation logic for that typeExample: Mapping OBX -> Observationfunction mapToObservation(obx) { return { resourceType: 'Observation', status: 'final', code: { text: obx[3][0] }, valueString: obx[5][0], }; }ResultTest with example HL7 message:curl -X POST http://localhost:3000/hl7 -H "Content-Type: text/plain" --data-binary $'MSH|^~\\&|HIS|Hospital|LAB|LabSystem|20250401||ADT^A01|12345|P|2.5\r\nPID|1||12345||John^Doe||19900101|M'In the console you can see the FHIR record:Mapped FHIR Patient: { "resourceType": "Patient", "id": "12345", "name": [ { "given": [ "John" ], "family": "Doe" } ], "birthDate": "19900101", "gender": "male" }ConclusionIn conclusion, integrating HL7 and FHIR enables healthcare systems to bridge the gap between legacy messaging and modern API-driven architectures. By using Node.js as an integration layer, developers can efficiently parse, transform, and route healthcare data in real time. This approach not only improves interoperability but also enhances data accessibility and system scalability. Ultimately, adopting these standards leads to more connected, efficient, and patient-centric healthcare solutions. For more about healthcare app development, connect with our healthcare developers.
Category: Health & Wellness
A Dev Guide to Placing Orders using Hyperliquid API IntroductionHyperliquid is a high-performancedecentralized perpetual exchange offering low-latency trading. For developers building algorithmic strategies, bots, or integrations, Hyperliquid exposes both REST and WebSocket APIs. This guide provides a step-by-step walk-through of how to place a basic order using the REST API in Node.js.This script demonstrates how to place a limit sell order for the HYPE token on the Hyperliquid testnet using JavaScript. It utilizes the ethers library for wallet management and the @nktkas/hyperliquid SDK to interact with Hyperliquid's API.Overview of Hyperliquid's Use CasesHyperliquid offers fast, API-based access to decentralized perpetual trading. Developers commonly use it to:Build bots for placing and managing ordersMonitor positions, funding rates, and liquidationsSimulate and test strategies on the testnetIntegrate trading data into dashboards or analytics toolsTrigger trades based on on-chain or external signalsIts design supports both simple scripts and complex trading systems with low latency.Who Should Use This Guide?This guide is for developers who want to:Place limit orders using Hyperliquid's REST APITest trading logic in a controlled testnet environmentIntegrate order placement into existing apps or botsUnderstand how the Hyperliquid SDK interacts with wallets and marketsIf you're familiar with JavaScript and basic API workflows, you'll find this walkthrough easy to follow.Prerequisites for Integrating Hyperliquid API in Your Crypto Trading SystemNode.js and npmethers and @nktkas/hyperliquid npm packagesHyperliquid API Integration: Setting Up Imports and Configuring Your Environmentimport * as hl from '@nktkas/hyperliquid'; import { ethers } from 'ethers'; const privateKey = 'YOUR_PRIVATE_KEY'; // Set up a connection to the Hyperliquid API (using the testnet environment) const transport = new hl.HttpTransport({ isTestnet: true }); // Initialize a wallet instance using the provided private key to sign transactions const wallet = new ethers.Wallet(privateKey); // Set up the ExchangeClient for placing orders and handling trading operations const exchangeClient = new hl.ExchangeClient({ wallet, transport, isTestnet: true, }); // Set up the InfoClient to retrieve market data and other relevant information const infoClient = new hl.InfoClient({ transport }); Component Explanations:HttpTransport : Establishes a connection to the Hyperliquid API. TheisTestnet flag ensures you're working with the testnet environment.ethers.Wallet : Creates a wallet instance using your private key. This wallet is used for signing transactions.ExchangeClient : Manages order placements and various trading operations.InfoClient : Provides access to market metadata and informational endpoints.Also, Explore |Creating a Custom Hyperliquid Dashboard: Track Live Holdings in ReactPreparing for a Smooth IntegrationChecklist Before You BeginClarify Your Requirements:Define the specific functionality you need from the system or API.Review API Documentation:Understand the endpoints, authentication methods, and rate limits.Set Up Your Development Environment:Ensure dependencies are installed and your environment is ready for integration.Prepare Authentication Credentials:Securely store your API keys or tokens.Use Test Environment:Start integration in a test or staging environment to avoid issues in production.As highlighted in the officialHyperliquid API documentation, integrating with their testnet environment is crucial for ensuring stable deployments. We've followed these guidelines extensively when deploying automated strategies for our clients, ensuring a smooth and risk-free integration before moving to production.Tips for Avoiding Common Setup MistakesTest First:Always validate the integration in a controlled environment before going live.Monitor Rate Limits:Ensure you don't exceed API rate limits by optimizing your calls.Map Data Correctly:Double-check the data formats to avoid integration errors.Secure Sensitive Data:Use environment variables to store API keys, not hardcoded values.Handle Errors Efficiently:Implement error handling and logging to quickly identify and fix issues.Plan for Scalability:Make sure your integration can handle increased traffic as your system grows.Main function:async function main() { try { // Retrieve market metadata for available assets and trading pairs const [meta] = await infoClient.metaAndAssetCtxs(); // Find the index of the 'HYPE' asset within the available assets const assetIndex = meta.universe.findIndex( (asset) => asset.name === 'HYPE' ); // Check if the HYPE asset exists if (assetIndex === -1) { throw new Error('HYPE asset not found.'); } // Define order parameters const orderParams = { orders: [ { a: assetIndex, // Asset index for HYPE b: false, // false for sell, true for buy p: '100', // Limit price (string format) s: '0.1', // Order size (string format) r: false, // No reduce-only flag t: { limit: { tif: 'Gtc', // Time-in-force: 'Good 'til canceled' }, }, }, ], grouping: 'na', // No specific grouping for the order }; // Place the order on the Hyperliquid exchange const response = await exchangeClient.order(orderParams); console.log('Order placed successfully:', response); } catch (error) { // Error handling: Log any issues that occur during the order placement process console.error('Error placing order:', error); console.error( 'Error details:', error.response ? error.response.response.data : error.message ); }}Explanation:Retrieve Market Metadata:The functionmetaAndAssetCtxs() fetches metadata about available trading pairs from the Hyperliquid API.Find Asset Index:The code searches for the index of the 'HYPE' asset in the available assets list. This index is needed to specify the asset when placing an order.Order Parameters:a: Specifies the asset index for 'HYPE'.b: A boolean flag indicating the order side (false for sell,true for buy).p: The limit price, set to100 in this case.s: The order size, set to0.1 HYPE.r: A flag indicating whether the order is reduce-only (set tofalse here).t: Time-in-force setting (Gtc means the order is good until canceled).grouping: Set to'na', meaning no specific grouping for this order.Place Order:The functionexchangeClient.order(orderParams) sends the order to the Hyperliquid exchange, where it gets processed.Error Handling:Any errors encountered during the order process are caught, logged, and detailed error messages are provided for debugging.You may also like |How to Fetch Transaction History on Ethereum usingWeb3.pyDeveloper Best PracticesKeeping Your Integration SecureUse Secure Authentication:Always implement OAuth, API keys, or other secure authentication methods, and avoid hardcoding credentials in your codebase.Encrypt Sensitive Data:Ensure that sensitive data such as API keys, user details, and transaction information is encrypted both in transit and at rest.Follow Least Privilege Principle:Grant the minimum required permissions for users or services to access the integration.Regularly Rotate Keys and Tokens:Periodically change API keys and authentication tokens to reduce the risk of unauthorized access.Managing API Reliability Over TimeMonitor API Usage and Performance:Track API calls and error rates to identify potential issues before they impact your application.Handle API Downtime Gracefully:Implement retries with exponential backoff and fallback mechanisms to ensure smooth user experience during downtime.Check for Deprecations and Updates:Regularly review API documentation for breaking changes, new features, or deprecations that could affect your integration.Implement Logging and Alerts:Set up logging for all API interactions and create alerts for failures or unexpected behavior.Testing Your Integration Before Going LiveTest in a Sandbox Environment:Use a sandbox or testnet environment to simulate real-world scenarios and detect issues early.Test for Edge Cases:Ensure your integration handles unexpected inputs, errors, and edge cases such as rate limit breaches or invalid data formats.Verify Data Accuracy:Double-check that the data returned by the API is correct, and ensure your application properly handles it.Perform Load Testing:Simulate high traffic to identify performance bottlenecks and optimize your integration for scalability.Important considerations:Account Initialization:Ensure that the wallet address derived from your private key has been initialized on Hyperliquid.Without proper initialization, you may encounter the following error: User or API Wallet does not exist.Collateral Requirements:Collateral is required, even for spot trades.Hyperliquid mandates a minimum amount of USDC collateral in your perpetuals account.For example, to sell 0.1 HYPE at $100, you'll need at least$10 USDC as collateral.Testnet vs. Mainnet:The script is configured fortestnet (isTestnet: true).Ensure that you're interacting with the correct network based on your environment—testnet for testing and mainnet for live transactions.Error Messages:Pay close attention to error messages returned by the API.These messages offer valuable insights into issues such asinsufficient margin orincorrect asset indices.Also, Discover |Stablecoin Development with CDP (Collateralized Debt Positions)Conclusion.This guide outlines a simple and efficient approach for placing limit sell orders on the Hyperliquid testnet using the REST API in Node.js. By utilizing the @nktkas/hyperliquid SDK and ethers.js for wallet management, you can easily integrate order placement into your algorithmic strategies or trading bots.However, it's important to keep in mind a few key considerations:Wallet Initialization: Ensure that your wallet address is properly initialized on Hyperliquid.Collateral Requirements: Make sure you meet the necessary collateral requirements.Network Selection: Double-check that you're interacting with the correct network (testnet vs. mainnet).With this setup, you'll be able to execute trades efficiently, taking full advantage of Hyperliquid's low-latency and high-performance decentralized exchange.By integratingHyperliquid API, we enabled our clients to benefit from low-latency trading and efficient order management. This has helped them streamline their trading operations, optimize their strategies, and ultimately save time. We continue to recommendHyperliquid API for clients seeking high-performance decentralized trading solutions.If you are planning to launch your own DEX like Hyperliquid, connect with our skilledblockchain developers to get started.Frequently Asked Questions (FAQ)1. What is the best API for crypto trading?Popular options includeBinance API,Coinbase API, andHyperliquid API for decentralized trading.2. Which platform uses AI to automate crypto trading?Platforms like3Commas andHaasOnline use AI for automated trading.3. How to withdraw crypto with API?You can withdraw crypto via thewithdraw endpoint by authenticating and providing wallet details.4. What platform do most crypto traders use?The most commonly used platforms areBinance andCoinbase.5. What is the best automated crypto trading platform for beginners?Commas andCryptohopper are ideal for beginners due to their user-friendly interfaces.6. How do you make money from crypto trading bots?Crypto trading bots make money by executing profitable trades based on predefined strategies.7. How can I test my crypto trading strategy with a testnet?You can test strategies risk-free onHyperliquid orBinance Testnet by simulating real-market conditions.
Category: Blockchain Development & Web3 Solutions
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 servicesWhat 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 PoolCreating 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 GuideStep 1: Setting Up the Smart ContractFirst, 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 TokensThe 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 ProtocolsTo 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 SolutionConclusionCreating 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 Development & Web3 Solutions
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 BlockchainPrerequisitesBefore 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 ProjectFirst, 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 -yThis 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 APICreate a new file calledindex.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 DataTo 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. TheBTCUSDT pair and a 1-minute interval are used here as an example.Implementing a Simple Scalping StrategyWe'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 minuteIn 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 WebhookConclusionThis 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 Development & Web3 Solutions
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 BlockchainDeveloping a Simple Supply Chain Smart ContractsLet'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 Opportunitiesuint256 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 Processesevent 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 Functionalities1. 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 NFTsIn 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 Development & Web3 Solutions
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 StandardPrerequisites: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 KnowDefine the interface for ERC-20 tokensinterface 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 ChecksThe 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 SecurityThis 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 Development & Web3 Solutions
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 DevelopmentPrerequisites: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 -yYou may also like | Creating a Staking Smart Contract on Solana using AnchorInstall Required Packages:Install the necessary npm packages for interacting with the Solana blockchainnpm install @solana/web3.js @solana/spl-token bs58Write 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.jsBelow is the output:SPL Token created successfully! Token Public Key: Ej1vq1r1y6ChmqX4fLri4ZJKG32RQzc3CiHYcPWZDL6ZAlso, Read | What Makes Solana Blockchain Development Stand OutConclusion: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 Development & Web3 Solutions
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.jsSingleton 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 DevelopmentBelow 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 1Chain 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 DevelopmentBelow 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 2Facade 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 GuideBelow 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.jsConclusionAfter 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 TestingBefore 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 ContractsThere 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 FrameworkSeveral 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 ProgrammingTest Case for an ERC-20 Smart ContractIn 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 ToolsSmart Contract Development with OodlesSmart 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.