|
Vishal Yadav Oodles

Vishal Yadav (Manager-Technical Project Manager)

Experience:5+ yrs

Vishal is a highly skilled backend developer with extensive 3+ years experience in developing various blockchain platforms. He has a comprehensive understanding of the technologies and has hands-on expertise in Node.js, Ethereum, Layer 1 and Layer 2 solutions, smart contract development, and databases like MySQL and MongoDB. He has a proven track record of working on a range of blockchain-related projects, including token development, staking, governance, indexes, bridges, NFT, marketplace, ICO/IDO, and more. He is adept at managing trading bots, and developing centralized exchanges, and has a creative mind with excellent analytical skills.

Vishal Yadav Oodles
Vishal Yadav
(Technical Project Manager)

Vishal is a highly skilled backend developer with extensive 3+ years experience in developing various blockchain platforms. He has a comprehensive understanding of the technologies and has hands-on expertise in Node.js, Ethereum, Layer 1 and Layer 2 solutions, smart contract development, and databases like MySQL and MongoDB. He has a proven track record of working on a range of blockchain-related projects, including token development, staking, governance, indexes, bridges, NFT, marketplace, ICO/IDO, and more. He is adept at managing trading bots, and developing centralized exchanges, and has a creative mind with excellent analytical skills.

LanguageLanguages

DotEnglish

Bilingual

DotHindi

Fluent

Skills
Skills

DotRemix IDE

80%

DotGnosis Safe

60%

DotChainlink

80%

DotUniswap

80%

DotCoinbase API

60%

DotGanache

60%

DotAnchor

80%

DotSolidity

100%

DotMetaMask

80%

DotHardhat

80%

DotTruffle

80%

DotGolang

60%

DotPostgres

80%

DotTechnical Project Management

100%

DotSmart Contract

100%

DotNode Js

100%

DotClient Handling

80%

DotERC-721

80%

DotOpenZeppelin

80%

DotCosmos IBC

60%

DotEthers.js

100%

DotERC-1155

60%

DotZKsync

60%

DotThe Graph

60%

DotIPFS

80%

DotBitcoin (BTC)

100%

DotEthereum

100%

DotEtherscan

80%

DotDyanmoDB

80%
ExpWork Experience / Trainings / Internship

Aug 2019-Present

Technical Project Manager

Unit No. 117- 120, Welldone Tech Park, Sector 48, Sohna Road, Gurugram, Haryana- 122018, IN.


Oodles Technologies

Unit No. 117- 120, Welldone Tech Park, Sector 48, Sohna Road, Gurugram, Haryana- 122018, IN.

Aug 2019-Present

EducationEducation

2015-2019

Dot

World college of Technology and Management

B.Tech-Computer science

Top Blog Posts
How to Create Your Own Private Blockchain using Cosmos

Cosmos is an open-source blockchain app development project that aims to connect other blockchains to each other to establish an easily usable, fast scalable, interoperable, and low-fee hub for basically any use of a blockchain. Cosmos internet of blockchains would allow different blockchains to communicate with each other in a decentralized way a way where one person or one single organization is not able to completely control so how is Cosmos planning on actually making this dream a reality this is where the cosmos Hub and zone model come in hubs are often very important for systems to really take off with a high number of users and Cosmos is no different in Cosmos they took a look at the cryptocurrency landscape and saw a lot of spokes but no Hub in other words they saw a large number of blockchains with interesting use cases but the methods of communicating between these chains still left a lot to be desired in fact one of the largest vulnerabilities out there are blockchain bridges which is a tool used to move money from one chain to another Cosmos created what they call a hub and zones model they have a central Hub that facilitates the transfer of tokens across various chains the founder of the Tinder mint protocol which later became Cosmos. Cosmos provides an SDK that can be used to create your own custom blockchain solution. Please check the steps below to set up the local system.

 

 

Check out | Understanding the Importance of Cross Chain dApps

 

Prerequisite

 

  • Node.js

 

  •  Step 1 : Take clone of the project and change the directory to the main root folder folder of the project  

 

git clone https://github.com/cosmos/cosmos-sdk 
  • Step 2: Initialize application
 ./build/simd init demo \ --home ./private/.simapp \ --chain-id learning-chain-1 
  • Step 3: Prepare sample account, a test account with alice name is created
 ./build/simd keys add alice \ --home ./private/.simapp \ --keyring-backend test
  • Step 4: Become validator
 // Give initial balance to account 
 ./build/simd add-genesis-account alice 100000000stake \ --home ./private/.simapp \ --keyring-backend test 
 
 // Now include bootstrap transaction in genesis 
 ./build/simd add-genesis-account alice 100000000stake \ --home ./private/.simapp \ --keyring-backend test 
 
 // Now we need to collect all genesis transaction 
 ./build/simd add-genesis-account alice 100000000stake \ --home ./private/.simapp \ --keyring-backend test
  • Step 5: Create blocks 
 ./build/simd start \ --home ./private/.simapp 

 

Read Also | Build a Blockchain or dApp on Cosmos Network

 

Conclusion



Now, a simple Cosmos node is running. In the next blog, we will focus on how to interact with this blockchain node. Connect with our blockchain developers today. 

Category: Blockchain
How to Create and Deploy an ERC404 token contract

ERC404 is a new concept in the realm of crypto token development that combines the functionality of NFT and ERC20 tokens. This is an experimental token and is not included under EIP, due to its experimental status project owner can do customization as per their need. This token will act as both ERC20 and NFT, it has two types of transfer function. In the first transfer function, only the receiver address and amount are passed which will be used to transfer fraction tokens (ERC-20 tokens), and in other transfer functions, a receiver address, ID, and the amount will be passed.  To access the NFT, we can use the standard NFT function like setting the base URI, and getting the URI from the token ID. The major difference in this standard is that you get both the functionalities under same hood.

 

See the example below to get an understanding of how ER404 works and how you can create your custom ERC404 token, for more about token standards, check out Unexplored ERC Token Standards On Ethereum.

 

The Core Library for the ERC404 Library

 

abstract contract ERC404 is Ownable2Step {
    // Events
    event ERC20Transfer(
        address indexed from,
        address indexed to,
        uint256 amount
    );
    event Approval(
        address indexed owner,
        address indexed spender,
        uint256 amount
    );
    event Transfer(
        address indexed from,
        address indexed to,
        uint256 indexed id
    );
    event ERC721Approval(
        address indexed owner,
        address indexed spender,
        uint256 indexed id
    );
    event ApprovalForAll(
        address indexed owner,
        address indexed operator,
        bool approved
    );

    // Errors
    error NotFound();
    error AlreadyExists();
    error InvalidRecipient();
    error InvalidSender();
    error UnsafeRecipient();
    error Unauthorized();
    error InvalidOwner();

    // Metadata
    /// @dev Token name
    string public name;

    /// @dev Token symbol
    string public symbol;

    /// @dev Decimals for fractional representation
    uint8 public immutable decimals;

    /// @dev Total supply in fractionalized representation
    uint256 public immutable totalSupply;

    /// @dev Current mint counter, monotonically increasing to ensure accurate ownership
    uint256 public minted;

    // Mappings
    /// @dev Balance of user in fractional representation
    mapping(address => uint256) public balanceOf;

    /// @dev Allowance of user in fractional representation
    mapping(address => mapping(address => uint256)) public allowance;

    /// @dev Approval in native representaion
    mapping(uint256 => address) public getApproved;

    /// @dev Approval for all in native representation
    mapping(address => mapping(address => bool)) public isApprovedForAll;

    /// @dev Owner of id in native representation
    mapping(uint256 => address) internal _ownerOf;

    /// @dev Array of owned ids in native representation
    mapping(address => uint256[]) internal _owned;

    /// @dev Tracks indices for the _owned mapping
    mapping(uint256 => uint256) internal _ownedIndex;

    /// @dev Addresses whitelisted from minting / burning for gas savings (pairs, routers, etc)
    mapping(address => bool) public whitelist;

    // Constructor
    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals,
        uint256 _totalNativeSupply,
        address _owner
    ) Ownable(_owner) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;
        totalSupply = _totalNativeSupply * (10 ** decimals);
    }

    /// @notice Initialization function to set pairs / etc
    ///         saving gas by avoiding mint / burn on unnecessary targets
    function setWhitelist(address target, bool state) public onlyOwner {
        whitelist[target] = state;
    }

    /// @notice Function to find owner of a given native token
    function ownerOf(uint256 id) public view virtual returns (address owner) {
        owner = _ownerOf[id];

        if (owner == address(0)) {
            revert NotFound();
        }
    }

    /// @notice tokenURI must be implemented by child contract
    function tokenURI(uint256 id) public view virtual returns (string memory);

    /// @notice Function for token approvals
    /// @dev This function assumes id / native if amount less than or equal to current max id
    function approve(
        address spender,
        uint256 amountOrId
    ) public virtual returns (bool) {
        if (amountOrId <= minted && amountOrId > 0) {
            address owner = _ownerOf[amountOrId];

            if (msg.sender != owner && !isApprovedForAll[owner][msg.sender]) {
                revert Unauthorized();
            }

            getApproved[amountOrId] = spender;

            emit Approval(owner, spender, amountOrId);
        } else {
            allowance[msg.sender][spender] = amountOrId;

            emit Approval(msg.sender, spender, amountOrId);
        }

        return true;
    }

    /// @notice Function native approvals
    function setApprovalForAll(address operator, bool approved) public virtual {
        isApprovedForAll[msg.sender][operator] = approved;

        emit ApprovalForAll(msg.sender, operator, approved);
    }

    /// @notice Function for mixed transfers
    /// @dev This function assumes id / native if amount less than or equal to current max id
    function transferFrom(
        address from,
        address to,
        uint256 amountOrId
    ) public virtual {
        if (amountOrId <= minted) {
            if (from != _ownerOf[amountOrId]) {
                revert InvalidSender();
            }

            if (to == address(0)) {
                revert InvalidRecipient();
            }

            if (
                msg.sender != from &&
                !isApprovedForAll[from][msg.sender] &&
                msg.sender != getApproved[amountOrId]
            ) {
                revert Unauthorized();
            }

            balanceOf[from] -= _getUnit();

            unchecked {
                balanceOf[to] += _getUnit();
            }

            _ownerOf[amountOrId] = to;
            delete getApproved[amountOrId];

            // update _owned for sender
            uint256 updatedId = _owned[from][_owned[from].length - 1];
            _owned[from][_ownedIndex[amountOrId]] = updatedId;
            // pop
            _owned[from].pop();
            // update index for the moved id
            _ownedIndex[updatedId] = _ownedIndex[amountOrId];
            // push token to to owned
            _owned[to].push(amountOrId);
            // update index for to owned
            _ownedIndex[amountOrId] = _owned[to].length - 1;

            emit Transfer(from, to, amountOrId);
            emit ERC20Transfer(from, to, _getUnit());
        } else {
            uint256 allowed = allowance[from][msg.sender];

            if (allowed != type(uint256).max)
                allowance[from][msg.sender] = allowed - amountOrId;

            _transfer(from, to, amountOrId);
        }
    }

    /// @notice Function for fractional transfers
    function transfer(
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        return _transfer(msg.sender, to, amount);
    }

    /// @notice Function for native transfers with contract support
    function safeTransferFrom(
        address from,
        address to,
        uint256 id
    ) public virtual {
        transferFrom(from, to, id);

        if (
            to.code.length != 0 &&
            ERC721Receiver(to).onERC721Received(msg.sender, from, id, "") !=
            ERC721Receiver.onERC721Received.selector
        ) {
            revert UnsafeRecipient();
        }
    }

    /// @notice Function for native transfers with contract support and callback data
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        bytes calldata data
    ) public virtual {
        transferFrom(from, to, id);

        if (
            to.code.length != 0 &&
            ERC721Receiver(to).onERC721Received(msg.sender, from, id, data) !=
            ERC721Receiver.onERC721Received.selector
        ) {
            revert UnsafeRecipient();
        }
    }

    /// @notice Internal function for fractional transfers
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual returns (bool) {
        uint256 unit = _getUnit();
        uint256 balanceBeforeSender = balanceOf[from];
        uint256 balanceBeforeReceiver = balanceOf[to];

        balanceOf[from] -= amount;

        unchecked {
            balanceOf[to] += amount;
        }

        // Skip burn for certain addresses to save gas
        if (!whitelist[from]) {
            uint256 tokens_to_burn = (balanceBeforeSender / unit) -
                (balanceOf[from] / unit);
            for (uint256 i = 0; i < tokens_to_burn; i++) {
                _burn(from);
            }
        }

        // Skip minting for certain addresses to save gas
        if (!whitelist[to]) {
            uint256 tokens_to_mint = (balanceOf[to] / unit) -
                (balanceBeforeReceiver / unit);
            for (uint256 i = 0; i < tokens_to_mint; i++) {
                _mint(to);
            }
        }

        emit ERC20Transfer(from, to, amount);
        return true;
    }

    // Internal utility logic
    function _getUnit() internal view returns (uint256) {
        return 10 ** decimals;
    }

    function _mint(address to) internal virtual {
        if (to == address(0)) {
            revert InvalidRecipient();
        }

        unchecked {
            minted++;
        }

        uint256 id = minted;

        if (_ownerOf[id] != address(0)) {
            revert AlreadyExists();
        }

        _ownerOf[id] = to;
        _owned[to].push(id);
        _ownedIndex[id] = _owned[to].length - 1;

        emit Transfer(address(0), to, id);
    }

    function _burn(address from) internal virtual {
        if (from == address(0)) {
            revert InvalidSender();
        }

        uint256 id = _owned[from][_owned[from].length - 1];
        _owned[from].pop();
        delete _ownedIndex[id];
        delete _ownerOf[id];
        delete getApproved[id];

        emit Transfer(from, address(0), id);
    }

    function _setNameSymbol(
        string memory _name,
        string memory _symbol
    ) internal {
        name = _name;
        symbol = _symbol;
    }
}

 

Note: You can use Openzeppelin for import libraries like ownable2step, pausable, ERC721, etc.

 

The next step will be to inherit this library into the main contract to use the functionality.

 

contract SampleToken is ERC404, Pausable, ReentrancyGuard {
    string public baseTokenURI;
    using Strings for uint256;

    constructor(
        address _owner,
        uint256 _initialSupply,
        uint8 _decimal
    ) ERC404("Sample", "SAMPLE", _decimal, _initialSupply, _owner) {
        balanceOf[_owner] = _initialSupply * 10 ** _decimal;
    }

    function _mint(
        address to
    ) internal override whenNotPaused{
        return super._mint(to);
    }

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal override virtual whenNotPaused returns (bool){
        return super._transfer(from, to, amount);
    }

    function setTokenURI(string memory _tokenURI) public onlyOwner {
        baseTokenURI = _tokenURI;
    }

    function setNameSymbol(
        string memory _name,
        string memory _symbol
    ) public onlyOwner {
        _setNameSymbol(_name, _symbol);
    }

    function tokenURI(uint256 id) public view override returns (string memory) {
        return bytes(baseTokenURI).length > 0 ? string.concat(baseTokenURI, id.toString(), ".json") : "";
    }
}

 

Now the contracts are ready, we can either use remix or hardhat for deployment over the network. After the deployment, the owner will get the initial supply of tokens. In the above example, mint is only overridden internally but not used after that, you can write your custom logic for minting NFT, and after that use that same mint function to mint NFT. For setting the base URI use the function "setTokenURI".

 

Conclusion:

 

This blog gives you a brief idea about ERC404 and how we can create a token with this Ethereum token standard, you can write your custom on top of this code base to add functionality like tax, whitelisting, blacklist, reflection mechanism, etc. Connect with our smart contract developers to get started with your project/token development. 

Category: Blockchain
A Brief Introduction to the Intricacies of Dynamic NFTs

A dynamic NFT, or dNFT, is like a special kind of digital collectible that can change itself based on certain conditions. Regular NFTs are already popular online, with famous people creating their own collections using NFT development services. But now, dNFTs are the new thing. They can adapt and update themselves depending on what's happening around them. This makes them more flexible and opens up new possibilities. In this article, we'll explain what NFTs are, how dNFTs take them to the next level, and some ways people are using them. 

 

How Dynamic NFTs are Different

 

Regular NFTs are the usual ones you see, like digital art or game items. They're also used for making digital versions of real things like property deeds or patents. But there's a drawback – once these NFTs are made, their details can't be updated.

For things like tokenizing real-world stuff or making games where progress matters, you need updates. That's where dynamic NFTs come in. They're like a mix of the regular ones and something that can change. So, a dynamic NFT is an NFT that can update itself based on certain conditions, thanks to some smart contract magic. This means it keeps its original identity but can also freshen up its details when needed.


Since NFTs can be super unique and made in lots of different ways, they're kind of like customizable digital tokens. But here's the thing – most dynamic NFTs need to tweak their details so that regular folks can actually notice the changes.

 

Also, Explore | Unlocking Value: Exploring the World of NFT Lending

 

Use cases

 

Dynamic NFTs can do more than just change their details. Let's say you find a secret spot in an augmented reality app – a dynamic NFT could be created as a reward. These NFTs can also have "hidden traits" that show up based on how people interact with them, not just in their details.

In projects where art is created on the fly (like generative NFT art), each token has different traits, some rarer than others. These traits are saved in the NFT's metadata, which also includes a link to the image or video of the NFT.

 

Also, Explore | NFT-Based Loyalty Programs: Revamping Customer Engagement

 

Here's another way metadata changes come in handy: when we turn real things into digital tokens. Think of it like this – if we make an NFT for a house, we'd want it to show stuff like when it was last fixed, how old it is, its value, and other details that might change. So, to make NFTs for these kinds of things work, they need to be able to update with new information.

 

A Quick Guide to Beacon Chain Ethereum 2.0

Ethereum 2.0, also known as Beacon Chain, represents a significant upgrade in the Ethereum blockchain development space. One of its key changes is the transition from proof of work to proof of stake consensus model, introducing validators instead of miners. Becoming an ETH2 validator requires a stake of 32 ETH, although staking pools offer alternatives for those with less ETH.

 

Limitations of Ethereum

 

High Transaction Fees

 

Ethereum's proof of work consensus relies on miners and high-end hardware, leading to significant gas fees during peak hours, sometimes reaching hundreds of dollars per transaction.

 

Scalability

 

The Ethereum network's capacity of around 15 transactions per second poses a scalability challenge, hindering user onboarding and project launches. Ethereum 2.0 aims to support thousands of transactions per second to address this limitation.

 

Security

 

Ensuring network security is paramount in a decentralized ecosystem. Ethereum 2.0 enhances security measures to mitigate various attacks, including the infamous 51% attack. By transitioning from proof of work to proof of stake, ETH2 aims to reduce energy consumption while maintaining network integrity.

 

You may also like | Biggest Upgrade of Ethereum, Dencun (Deneb-Cancun) Explained

 

Working

 

Proof of Work

In Ethereum's proof of work model, miners validate transactions by expending substantial energy resources. This approach, while effective, consumes significant energy and is susceptible to 51% of attacks.

 

Proof of Stake

 

Ethereum 2.0's proof of stake model eliminates miners, relying instead on validators who stake their ETH to secure the network. Validators are incentivized to validate transactions and are subject to a slashing mechanism, losing their stake if they attempt to attack the network.

 

Also, Read | Exploring Token Standards Beyond Ethereum

 

Security

 

Proof of stake introduces a slashing mechanism to deter attacks, requiring attackers to control a significant portion of validators, which necessitates owning a large amount of liquidity.

 

Conclusion

 

Ethereum 2.0 represents a crucial evolution for the Ethereum network, addressing key limitations while enhancing security and scalability. As a leading Blockchain Development Company based in Gurugram, we offer expertise in developing Ethereum projects. Contact our expert blockchain developers to discuss your requirements and leverage the potential of Ethereum 2.0.

Category: Blockchain
Avalanche: An Innovative Blockchain Offering Diverse Use Cases

Avalanche platform built by Avalabs is a decentralized proof of stake blockchain, it allows users to create their multifunctional blockchain and dApps using the smart contract.

 

Avalanche blockchain is designed to solve older blockchain platform limitations like slow transaction speed, centralization, and scalability. It uses a unique consensus protocol promising high throughput capabilities, low latency, and resistance to attacks.

 

Avalanche uses solidity language for smart contracts that allow Ethereum's projects to easily migrate to the avalanche platform.

 

Features

 

Avalanche is EVM compatible that allows Ethereum or similar EVM-based blockchain to be easily run on the avalanche blockchain. According to the creators, the blockchain can handle the order of 4,500 transactions per second. In comparison with other blockchains 7 transactions/second for bitcoin and 14 transactions/second for Ethereum, it can also achieve finality in 3 seconds. This makes the platform more suitable for massive calling dAppas.


Avalanche Consensus

 

Avalanche uses a proof of stake consensus mechanism. In the POW system blockchain depends on miners to mine new blocks or validate the transaction, in POS (proof of stake) instead of setting up expensive mining equipment users need to stake AVAX tokens to qualify as Validators.

 

Avalanche's Workings

 

Avalanche is built with three interoperable blockchains: Contract Chain (C-Chain), Exchange Chain (X-Chain), and Platform Chain(P-Chain).

 

X Chain: It is used for the creation of new assets like fungible and non-fungible tokens. AVAX token will be used to collateralize the assets.

 

C Chain: It is an EVM implementation that is used for smart contract development and deployment. The platform also provides a bunch of tools for developers to easily migrate applications to Avalanche.

 

P-Chain: It is used for creating subnets and coordinating validators. It is also responsible for hosting network Defi features like staking protocols.

 

"Snowman" consensus is used by both P-Chain and C-Chain that provides security for smart contracts. X-Chain uses DAG optimized consensus a scalable and secure protocol for achieving finality in seconds.

 

Connect with our blockchain development experts if you have a project in mind that you would like to discuss. 

Using Merkle Proof for Whitelisting Your Token Mechanism

Introduction:

 

Cryptocurrency is one of the trending topics in recent times. People are moving toward blockchain technology and new project are continuously launching daily along with the utility token like ERC20, ERC721, and ERC1155 this gave the chances for users/investors to participate in projects at early stages but with these bad elements like hackers or whales get the chances to manipulate new tokens so whitelisting become one of the important features at the time of launch. If we store every user address at the smart contract level then it will take too many gas fees, especially for blockchain like Ethereum.

 

Merkle proof solves these problems by only needing to save one root key in the smart contract. It works by hashing the corresponding hash moving way up in the tree till the root hash is achieved. You can see more details for Merkle proof from the links in the reference section.

 

Merkle proof concept is not limited to whitelist only you can use this any way you want based on the requirement. Please see the below section to understand its works.

 

Step 1: Installing libraries and importing your files.

 

// Install Merkle proof js library. Run this command in the root folder of the project directory.

npm i merkletreejs

npm i keccak256

 

// Import in your javascript files using these codes.

const { MerkleTree } = require('merkletreejs')

const keccak256 = require('keccak256')

 

Step 2: Adding users' addresses and generating root keys.

 

// List of address that need to be whitelisted

const addresses = ['0x000000000000000000000000000000000000dEaD', '0x0000000000000000000000000000000000000000', '0x1234567890123456789012345678901234567890']

// Create an instance with Merkle proof.

const leaf nodes = addresses.map(addr =>keccak256(addr));

const tree = new MerkleTree(leafnodes, keccak256)

// This will generate the key that needs to be stored in smart contract

const root = tree.getRoot().toString('hex');

console.log("Root ",root);

 

Step 3: Generate leaf and proof 

 

// Generating proof with leaf that will be passed to smart contract during the transaction.

// During transaction smart will also generate leaf with root and msg.sender address and verify the same

 

const proof = tree.getHexProof(leafnodes[0]);

 

Step 4: Integrate with smart contract.

 

// Import from Merkle proof library from openzeppelin.

import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";


 

// Using inside contract function. merleRoot should be stored inside the contract either at deployment or later by the owner.

// Proof needs to be generated via frontend/backend and passed in the function parameter. The leaf will be generated by a smart contract to compare.

bytes32 leaf = keccak256(abi.encodePacked(msg.sender));

require(MerkleProof.verify(proof, merkleRoot, leaf), "INVALID PROOF");

 

Conclusion

 

Using this Merkle proof concept you can easily whitelist users without saving every user's details in the smart contract. This helps a lot in blockchain like Ethereum which charges too many fees for transactions.

 

Reference:
 

https://medium.com/crypto-0-nite/merkle-proofs-explained-6dd429623dc5

https://ethereum.org/en/developers/tutorials/merkle-proofs-for-offline-data-integrity/

https://docs.openzeppelin.com/contracts/3.x/api/cryptography

Automatically create NFT images using HashLips art

Introduction: 

Hashlips art engine is used to automatically generate the instance of multiple arts based on the different layers.

In order to generate the image, we need to upload the image layer/traits that the code will pick to generate art. In order to do that we need to create a folder named "layer" in the root directory of the project. Now suppose if we want to create art for the face we can create multiple folders like head, eye, nose, and ears inside the layer. Inside this folder, we can put a different images for eyes like blue, brown, black eyes.

Now code will use this randomly pick an image from each layer in order to create art. Also customize order by 

 

Step 1: Project setup and installing dependency


//Clone project
git clone https://github.com/HashLips/hashlips_art_engine.git
// Install dependency
npm install


 

Step 2: Uploading images layers

Upload all image layer layers, folders as mentioned above.

 

Step 3: Configure setting

Now we need to configure the setting to generate art. Go to folder src/config.js and in layer configurations, we need to mention how much art you want to generate in "growEditionSizeTo" after that in "layersOrder" you need to mention which layer to use during the build process. You can also use different types of layers please see the example below.

const layerConfigurations = [
  {
    // Creates up to 10 artworks
    growEditionSizeTo: 10,
    layersOrder: [
      { name: "Eye" },
      { name: "Hair" },
      { name: "Mouth" },
      { name: "Nose" },
      { name: "Ear" },
      { name: "Headwear" },
    ],
  },
  {
    // Creates an additional 40 artworks
    growEditionSizeTo: 50,
    layersOrder: [
      { name: "Eye" },
      { name: "Hair" },
      { name: "Mouth" },
      { name: "Nose" },
      { name: "Ear" },
      { name: "Headwear" },
      { name: "Mask" },
    ],
  },
];


 

Step 4: Build images


npm run build  // You can check all the generated images in the build folder.

 

Conclusion: Using this tool you can easily generate thousands of artworks in a few simple steps.
 

Security Analysis of your Smart Contracts using Mythx

The smart contract has been a key part to work with block-chain technologies like Ethereum, Binance, Matic, KCC, etc. In recent times we have seen that many old or new projects are moving towards blockchain to implement the business logic over block-chain. Both Ethereum and Bitcoin are two of the most famous blockchain but ethereum provided extra functionality of smart contracts using that users can implement their custom application logic over the blockchain. So for such implementation, Ethereum is most trusted by users followed by Binance, Matic, and others that also follow the same structure. Users can also create their custom tokens like ERC20, ERC721 over these networks.

 

Need to do the security analysis

 

Security is the main reason users move from a centralized approach to a decentralized one. You need to make sure smart contract has no issue but these smart contracts are written by humans and there are high chances that issues will be there. We have seen in the past where hackers exploit these bugs to steal funds like the DAO attack in June 2016 which cause a loss of $60 million and not even hacker sometime issues was there user face the bugs and platform loss millions of dollars like in case of parity wallet.

 


Solution

 

To solve these issues platform choose to do the auditing of smart contract but auditing is also done by humans that also has chances of error. So recommend method is along with audits you need to use any security analysis tool like Mythix. You can use mythix actually at the time of development. You can use these development tools like truffle where you can run scans at the time of compilation with just one single command.

 

Usage

 

First, you need to register over Mythx for an API key. Mythx provides both free versions and paid versions based on the tool you want to use.

 

Prerequisites

 

  1. Python
  2. Mythx API key

 

Step 1 Install Mythx CLI.

 

 pip install mythx-cli

 

Step 2 Configure the Mythx by exporting.

 

//Private key obtained from Mythx dashboard
export MYTHX_API_KEY=PRV_KEY

 

Step 3 Scan contract. 

 

Details: Mythx provide different type of scans like quick, deep, etc. In the free version,n only a quick scan is available but it also covers most of the things. The quick scan takes up to 30 seconds for a scan. Deep scans use various algorithms to do the complete analysis of contracts. It takes up to 50 minutes with a deep scan.

 

mythx analyze --async --mode quick path_for_contract

 

Conclusion

 

This blog gives you a brief overview of smart contract security issues and how to avoid them. Mythx can be further integrated with other tools like Remix, Vscode, Truffle. Please go to the link below to get more details about this.

Link: https://docs.mythx.io/
 

An Introduction to Casper Network and How to Set Up its Environment

Casper Network is a Proof of stake blockchain built over CBC Casper specification. Using a proof of stake architecture enables sharding a database scaling method. Businesses can use Casper for creating permissioned or private applications. The key feature that Casper provides is predictable gas fees, Upgradeable contracts, and WebAssembly. 

 

The native coin of the Casper Network is CSPR. As PoS blockchain uses the validators to participate in consensus mechanisms for making it secure and uphold the network. So this CSPR coin is used to pay the validators as a reward, also users have to pay gas fees in CSPR for on-chain actions.

 

Currently, Casper Network is not live yet and their coin is available on the coin list for the initial sale.

 

In this blog, we are going to show to set up the environment for the Casper Network contract development. Currently, Casper uses Rust to write smart contracts like we use solidity with Ethereum/Binance.

 

Prerequisites:- 

 

  1. Rust
  2. Cmake
  3. Google Protobuf Compiler

 

Step 1: Install dependencies 

 

cargo install cargo-casper

 

Step 2: Setup your Project. By using this command it will create a new project and its structure with a sample contract and its corresponding test cases.

 

cargo casper my-project


Step 3: Now you have the project set up at your end. You need to compile the contract and run the corresponding in order to test all things are working fine.

 

// Install required tools
cd contract
rustup install $(cat rust-toolchain)
rustup target add --toolchain $(cat rust-toolchain) wasm32-unknown-unknown

// Compile and create a build
cargo build --release

// Run test cases

cd ../tests
cargo test


Step 4: Once this sample code is working. You can use the code of this repository for standard ERC20 over Casper Network. Simply replace the main.rs and test folder from Repository.

Link: https://github.com/casper-ecosystem/erc20

 

Step 5: Install the Casper Client. This is a CLI tool that can be used to interact with blockchain and contracts.

 

curl -JLO https://bintray.com/casperlabs/debian/download_file?file_path=casper-client_0.9.3-0_amd64.deb
sudo apt install -y ./casper-client_0.9.3-0_amd64.deb

// For interacting with contracts
casper-client put-deploy  --session-hash <HEX STRING> --session-entry-point <FUNCTION_NAME>

 

Conclusion: By following this blog you will get an idea about Casper and how we can create your contract over the network.

Migrating a Project from Ethereum to Binance Smart Chain

Ethereum has recently reached its all-time around $2036 and the increase in gas fees makes the DeFi protocols barely usable. DeFi protocol is one of the major reasons for the success of crypto in the year 2020 but is continuing to boom in 2021 but rising gas fees has been a concern for investors/traders and looking for alternatives with lower gas fees.

 

Binance Smart Chain 

 

Binance smart chain provides similar functionality with much lower gas fees. Its mechanism is hybrid EOS' dPoS( delegated proof of stake) and PoA(proof of authority) while ethereum work on PoW(Proof of work). Ethereum is also planning to move to PoS with ETH 2.0 but it will take another two years till it is completely rolled out.

 

Ethereum disadvantage is acting as a growth factor for the Binance smart chain. Now several Defi projects are moving from ethereum to the Binance smart chain due to lower fees and high scalability. As a result, the price of the BNB token increased by more than 500 percent last month.

 

Migrating a Project from Ethereum to Binance Smart Chain

 

To migrate your ethereum project from Ethereum to project you first have to convert your ethereum based asset in BNB.

 

Suppose you have ERC20 running over the ethereum network and there are thousands of users. Now to convert/get that token over the binance chain you have to use a bridge where two versions of the token are held one is for the ethereum network and another one is for the Binance network. Now if one the user holds 20 tokens over ethereum then he can send those to the bridge and these tokens will be locked and the equivalent number of Binance versions will be provided to the user. The process will be the same if the user wants to convert from the Binance version to the Ethereum version.

 

Currently, on a binance bridge, it supports a limited number of tokens but we can create a custom with the same logic. 

 

Once your main assets are moved now you can deploy the remaining contract over binance. Smart contract structure and deployment process, unit testing all the things are same over Binance smart chain as it is on Ethereum.

For testing, you can use the remix browser with Metamask to deploy some test contracts. If you are using Metamask as a provider, you need to add a custom RPC that is provided over Binance official documentation.

 

Below are some details that will help you in the process

Binance testnet faucet(You can use your ethereum wallet in metamask just need to update the RPC):

 

Faucet: https://testnet.binance.org/faucet-smart

 

Testnet RPC: https://data-seed-prebsc-1-s1.binance.org:8545/

 

ChainID Testnet: 97

 

Like on Ethereum, we have Uniswap, on the Binance, we have Pancake Swap. It is similar to Uniswap but with some modifications.

 

Utilizing the 1inch DEX Aggregator in Your Smart Contract Solution

DEX aggregator

 

DEX or decentralized exchange is a cryptocurrency exchange platform that runs without the involvement of authority or a third party. This allows users to retain control of their funds traded or stored on DEX, it provides more security than the centralized exchanges. The emergence of DEX aggregators has significantly driven the growth of decentralized crypto exchanges.

 

DEX aggregators provide liquidity from various exchanges and offer users better swap rates for tokens than they could get from any particular DEX. They can optimize swap fees, token prices, and slippage. Thus, it offers a better rate for users.

 

Also, Check | Decrypting Fundamentals of DeFi Aggregator Development

 

How to Integrate the 1Inch DEX Aggregator into Your Smart Contract 

 

To use an aggregator, you have to call the methods of the OneSplitAudit contract. This contract provides various methods like getexpected return through which you can get the amount you will get for the swap this way users can also control slippage for swapping. 

 

Prerequisites

 

  • Import 1inch audit contract/interface into your main contract

 

Get Expected Return 

 

Get the return amount for swapped tokens. This function returns the expected return amount of the desired token.

 

Parameters details: 

fromToken - Address of trading off token.
destToken - Address of desired token.
amount - Amount for from Token.
parts -    Number of pieces volume could be splitted.
flags - For enabling disabling feature

function getExpectedReturn(
    IERC20 fromToken,
    IERC20 destToken,
    uint256 amount,
    uint256 parts,
    uint256 flags
)
    public
    view
    returns(
        uint256 returnAmount,
        uint256[] memory distribution
    )

 

 

Swap Tokens

 

Swap amount of fromToken to destToken

Parameters details: 
minReturn Minimum expected return, else revert transaction

function swap(
    IERC20 fromToken,
    IERC20 destToken,
    uint256 amount,
    uint256 minReturn,
    uint256[] memory distribution,
    uint256 flags
) public payable returns(uint256)

 

Also, Visit | Cross-Chain DEX for Seamless Interoperability and Liquidity

 

Conclusion

 

This blog gives you a brief idea about the DEX aggregator and how you can use 1inch to integrate it into your smart contracts.

 

At Oodles, we have a blockchain development team comprising of skilled blockchain and smart contract developers. They are deft in using their skills and expertise to develop and deliver complex business solutions. Reach out to us to discuss the feasibility of your concept and how we can help you turn it into realization.  

Understanding Oracles and Their Implementation in Smart Contract

Oracle Smart Contracts

 

Ethereum is the most popular blockchain for creating Dapp. It provides flexibility to the users/developers to write and deploy their contracts over the blockchain and integrate with Dapps. A smart contract provides a lot of functionality that we can use. However, there is some limit on these contracts.

 

Smart contracts and blockchain cannot fetch data from external networks. It means they can only do that from their network. In any other traditional languages, we can create any API and later call these APIs to use anywhere we want. But, in the case of blockchain, we cannot do that. We need to use any service/adapter through which we can get the data from external data. 

 

Here, we need Oracle smart contract to get the data from external sources and use it inside Smart Contracts.

 

Oracle Contracts

 

Oracle is a smart contract service through which we can get the data from an external contract. In this, we create a smart contract that will provide the data to others. Here, we need to set up a service at the backend or any other platform. It updates findings on this smart contract. One of the most popular Oracle platforms is Chainlink. In Chainlink, users can set up their node and run the adapter that will do the backend. Now you can publish this link on the chain-link market and get rewards if anyone uses your service. 

 

Oracle charges some fees for providing service. But, with proper knowledge, you can set up your oracle services.

 

Types of Oracle Smart Contracts

 

Software Oracles 

 

These oracle deals with data that is available online like temperature, flight price, products price, etc.

 

Hardware Oracles

 

These are the oracle where we can only get the data through any hardware setup. For reference, we have set up a server that is only accessible to a particular company/person and needs to update that price to the smart contract.

 

Inbound Oracle

 

Get the data from an external network like APIs.

 

Outbound Oracles

 

Oracles to send the data to the external network similar to calling post API.

 

Consensus Oracles

 

These oracles get the information from human consensus and prediction markets like Gnosis and Augur.

 

Conclusion 

 

By following this blog, you will get an overview of what an oracle is, why we need to use it, and how it works. You can either use an existing oracle service or create yours based on the requirements.

 

How to Overcome Slippage Situation in DeFi Projects

Slippage is an unavoidable factor in decentralized finance (DeFi) projects. But how can you tackle it? This blog gives you a list of DeFi platforms and their strategies to overcome the slippage.

 

Understanding Slippage

 

Slippage is referred to as the difference between the actual price and the expected. It is one of the key points to take into consideration while creating or using any DeFi platform. It will inevitably impact your trades.

 

Suppose you want to buy a token, then you use a Defi platform to purchase that token. The platform will give you the number of tokens you will receive for the entered/submitted amount. Then, you start buying.

 

During your transaction processing if some users buy/sell that particular token in large quantities, then it will affect the price of crypto-tokens. It will lead to a change in the token price. So, you will either get more or fewer cryptos than the stated quantity. 

 

These price changes are called slippage, and several DeFis are using various methods to overcome this problem. 

 

Explore | NFT and DeFi Solutions | Disrupting the Financial Space

 

Strategies by DeFi Platforms to Avoid Slippage

 

Here is the list of several Defi platforms and strategies they are using to avoid slippage:

 

Uniswap

 

Uniswap uses an AMM (automated market-making) strategy to manage slippage and liquidity. It has a liquidity pooling system that enables rewarding trading fees to liquidity contributors for supporting the network. By using this network of providers, Uniswap completes the orders for crypto traders.

 

The platform creates a unique way to overcome slippage. The mechanism prevents traders from buying entire liquidity for a pool that makes the price higher for larger orders. We can resolve it by having a large number of providers, which will grow eventually as the platform grows.

 

Learn to Develop a Decentralized Crypto Exchange like Uniswap

 

Kyber

 

It uses a diversified liquidity system that includes liquidity pools, makers, token holders, and token projects. These contributors interact with a smart contract. Kyber created this smart contract to enable setting up a reserve. There are three types of reserves, namely an Orderbook Reserve, an Automated Price Reserve, and a Fed Price Reserve.

 

This diversified model helps Kyber to maintain a large supply of liquidity and foster an ecosystem for crypto usage.

 

Bancor

 

Bancor created a self-balancing mechanism. They have developed their token, BNT, which will act as the intermediate for managing the reserve balance. Using this contract doesn't require matchmaking and uses its token for doing the balancing. As long as a crypto-token has a BNT reserve.

 

Similarly, several other platforms are using their machines to prevent this slippage problem.

 

Check It Out | Driving DeFi Revolution with Smart Contracts

 

Conclusion

 

In this, we get to know about the slippage problem and how different DeFi platforms are using various mechanisms to prevent this problem. You can use this mechanism to overcome the slippage problem.

 

Looking for a blockchain service firm to provide DeFi solutions? Oodles is the right choice. Our blockchain developers have expertise in building decentralized finance solutions. Contact us today to get started.

Identifying Smart Contract Orchestration Patterns in Solidity

Decentralized systems and Dapps are getting lots of attention these days. Today everyone wants to get their hands on the decentralized application and get the mosts of the blockchain. Smart contracts are the core parts of the Dapps. As the use of Dapp is increasing day by day so the size of these contracts is also increasing day by day and these can't be held in a single contract. Even a simple Dapp consists of several smart contracts and ethereum has a limit of 24 Kb and also the sanity slips away as the contract becomes more complex. Here the orchestration patterns come into play to divide the functionality into parts. Before digging more into the concepts we first have to understand what is an orchestration after that we can understand how we can implement smart contracts.

 

Understanding the concept of Orchestration

 

In general, Orchestration is the joining of different data, service, code, or software to achieve a final product. Suppose you have data/code that is spread over 10 different servers and you want to use that under the same hood so you can achieve this by using the orchestration.

 

This concept is also used by various technology hubs one of its examples is Netflix Conductor.

 

Implementation with Solidity

 

In order to achieve this functionality break down your code into various manageable contracts and here you will find a contract that will call the function of other contracts.

 

Nowadays you can see most the popular platform uses the factory contract to initialize other contract or in simple words deploy all the other required contract. One of the most popular that uses this functionality is Uniswap. The Uniswap team solved the contract size problem with a simple check, but if you look more into the same you can find more examples of orchestration examples that are being coded from scratch for each project.

 

Another big example of such an Orchestration pattern is the DAO contract. Here several contracts are being deployed that are ERC20 token for tokens/votes, timelock for execution, governance for voting. Together with all these contracts, complete decentralized voting functionality can be achieved. Here ERC20 contract will manage the voted who can vote, how much voted will calculate for any user, Governance handles the proposal part (any particular proposal on which user vote) here user can vote, timelock contract will handle the execution of the required methods in the case of success.

 

In a similar, you can also add your own custom layer of the contract to add more security or customize this as per your functionality.

 

Conclusion

 

By using this blog you will get an overview of the Orchestration pattern and how this can be achieved using the solidity.

 

Reference Links: https://hackernoon.com/identifying-smart-contract-orchestration-patterns-in-solidity-pd223x20

An InDepth Insight Into the Decentralized Finance or DeFi Space

Defi or Decentralized finance is a financial service that is built over the blockchain to provide a more secure, reliable service than the traditional financial services. Most DeFi applications are built over the Ethereum network, which is the second-largest blockchain network. Ethereum provides more flexibility in terms of the smart contract. Programming Languages like Solidity are specifically designed for creating and deploying such smart contracts. Let's suppose, a user wants to set conditions stating that token will only be sent after a particular time and after meeting certain conditions then this can be achieved through ethereum smart contracts.

 

Some of the most popular Defi concepts are.

 

Decentralized exchanges(Dex)

 

Decentralized exchanges help users to exchange digital currencies for other digital currencies, like U.S. dollars for bitcoin or ether for DAI. DEXs are the most popular type of Defi concept, which allows users to trade cryptocurrencies. 

 

In DEX two principles are involved behind this.

 

 

On-chain order book mode

 

This is the classic way of using the Decentralized Exchange. In this, all functionality is on-chain like recharge, maker, taker, and withdrawal all will happen on-chain. Below is the sample flow diagram to explain this.

 

 

 

Off-chain order book. This mode takes advantage of both securities of the Decentralized system and the efficiency of the centralized system. Currently, Ethereum Decentralized Exchange IDEX is the representative of this model.

 

 

 

Stablecoins

This platform is used to use external currencies like the Euro and Dollar within the decentralized applications. A cryptocurrency that's tied to an asset outside of cryptocurrency to stabilize the price. The value of digital currencies changes frequently and fiat currencies face various policies and regulations that make the stablecoin best choice for Defi.

 

"Wrapped" bitcoins (WBTC)

 

A method to send/using Bitcoin on the ethereum network. This helps the user to use the bitcoin in ethereum Defi. Users can earn interest by lending bitcoin on such platforms.

 

Lending platforms

 

By using these platforms the use of  intermediaries like banks is removed through smart contracts.

 

Yield farming

 

 This is one of the new concepts in the context of Defi. Here the users who are willing to take risks can provide their token for farming and will get large returns.

 

Liquidity mining

 

 These Defi platforms give users some free tokens for using the platform.
 

Conclusion

 

Defi implements the concepts of the financial market in a decentralized network. With the help of DeFi, we can create any functionality like the traditional financial platform. But like traditional concepts, it also involves risks. By using these Defi applications, you can generate a passive income by lending money, or use farming for larger returns. Finally, with help of DEX, you can convert your token into any other digital currencies or actual currency.

A Guide to Understanding Locking Mechanism for ERC20 Token

In this article, acquaint yourself with the technical intricacies involved in the locking and unlocking mechanism of the ERC20 token within Ethereum blockchain development, while exploring its pros and cons.

 

Understanding ERC20 Token

 

ERC20 is a cryptocurrency token that is used to develop Ethereum-based tokens. An ERC20 token is a blockchain-based asset that is similar to the ether, Bitcoin, and Bitcoin cash. ERC20 token runs over the Ethereum network.

 

Ethereum is a decentralized network similar to Bitcoin, provides lots of functionalities, and has its currency known as ether. It also provides users/companies to create their digital currencies, in return, they need to spend some transaction fees while doing any transaction on the Ethereum network. ERC20 is the most popular standard for creating its token/asset over the network. Ethereum provides a variety of tools for developers to create tokens and other functionality using smart contracts.

 

Suggested Read | ERC-20 Token Standard | Development Essentials

 

Locking Mechanisms

 

Locking mechanisms help the owner to control the supply of tokens. By using this mechanism, a user can lock and later unlock their tokens. Usually, they use it when they want to Lock their tokens, similar to savings.   

 

The locking mechanism works in two parts.

 

First is the locking of tokens. We can only unlock them once they are locked. Usually, while deploying the contract, you can lock them. It is not necessary to Lock them at the time of deployment. We can Lock them at any other time. In this flow, we are Locking at the time of deployment. We can set the owner or any other user as an admin that will handle the locking/unlocking part.

 

 

Second is the unlocking of these tokens. Your tokens get unlocked when the lock time is completed. Also, the admin can unlock them. You remove this condition from the code, but it will create a security issue as anyone can unlock them.

 

 

Check It Out | Exploring Token Standards Beyond Ethereum

 

Advantages of the Locking Mechanism

 

  • Users can lock their tokens. Suppose a user wants to reduce their extra spending then, in that case, they can lock their token. 
  • The mechanism can come into use in DeFi, where the user can lock their token and will get the returns for the same.
  • It is used in reward distribution mechanisms like the lottery system.

 

Disadvantages of the Locking Mechanism

 

  • Once your tokens get locked, you cannot unlock them until the time is completed.

 

Also, Discover | ERC-4337: Ethereum’s Account Abstraction Proposal

 

Steps to Achieve a Locking Mechanism

 

Below are the steps that you can follow to achieve the locking mechanism:

 

Step 1: Open remx.ethereum.org and connect your Metamask wallet to it.

 

Step 2: Import the required dependency for the contract.

 

import "./tests/standardcontract/StandardToken.sol";  //Import standard token file available on Oppenzepplin
import "./tests/ERC1132.sol";   // Import ERC1132 standard file. This is the main file for the locking mechanism

 

Step 3: Lock and unlock function for tokens.

 

// Lock functions
 function lock(bytes32 _reason, uint256 _amount, uint256 _time)
        public
        returns (bool)
    {
        uint256 validUntil = now.add(_time); 
        require(tokensLocked(msg.sender, _reason) == 0, ALREADY_LOCKED);
        require(_amount != 0, AMOUNT_ZERO);
        if (locked[msg.sender][_reason].amount == 0)
            lockReason[msg.sender].push(_reason);
        transfer(address(this), _amount);
        locked[msg.sender][_reason] = lockToken(_amount, validUntil, false);
        emit Locked(msg.sender, _reason, _amount, validUntil);
        return true;
    }
  // Unlock function
      function unlock(address _of)
        public
        returns (uint256 unlockableTokens)
    {
        uint256 lockedTokens;
        for (uint256 i = 0; i < lockReason[_of].length; i++) {
            lockedTokens = tokensUnlockable(_of, lockReason[_of][i]);
            if (lockedTokens > 0) {
                unlockableTokens = unlockableTokens.add(lockedTokens);
                locked[_of][lockReason[_of][i]].claimed = true;
                emit Unlocked(_of, lockReason[_of][i], lockedTokens);
            }
        }  
        if (unlockableTokens > 0)
            this.transfer(_of, unlockableTokens);
    }

 

Step 4: Get the Locked amount and extend the lock

 

 // Extend lock 
 function extendLock(bytes32 _reason, uint256 _time)
        public
        returns (bool)
    {
        require(tokensLocked(msg.sender, _reason) > 0, NOT_LOCKED);
        locked[msg.sender][_reason].validity = locked[msg.sender][_reason].validity.add(_time);
        emit Locked(msg.sender, _reason, locked[msg.sender][_reason].amount, locked[msg.sender][_reason].validity);
        return true;
    }
 // Get locked amount
  function tokensLocked(address _of, bytes32 _reason)
        public
        view
        returns (uint256 amount)
    {
        if (!locked[_of][_reason].claimed)
            amount = locked[_of][_reason].amount;
    }

 

You May Also Like | ERC-20 Token Standard | Things You Must Know

 

Conclusion

 

By following the above steps, you can integrate the locking mechanism on your ERC20 without the need to be dependent on any external service. If you are interested in developing an ERC20 token, then connect with our Ethereum blockchain developers

An Overview of Stellar Network and JS SDK

Introduction: Stellar is a decentralized open-source blockchain network that provides a platform for the exchange of currencies over the globe. On Stellar Network you can build banking applications, mobile wallets, and any other application that involves transactions. Some of the important components of Stellar Network are as follows.

 

API Horizon: It is a RESTful API server through which applications can connect to the Stellar Network. Horizon provides API through which can be used by developers to connect to the Network directly. Currently, Stellar.org provide the JavaScript, Go, and Java SDKs to connect with Horizon, also some other SDKs are maintained by the community like  Ruby, Python, and C#.

 

Stellar Core: It is the backbone of Network. Every Horizon connects to the core behind the scenes. Complete Network is the collection of Core some are connected with Horizon while others are used to provide reliability to the Network. All the complex tasks are handled by these COREs.

 

Assets: Network can be used to hold any currency like BTC, Ether, Dollar, etc. Any asset can be traded with another asset. All the assets have asset type and issuer. Any account on Stellar can issue an asset and these accounts are called Anchors.

There are various SDKs provided by Stellar in this blog we will JS SDK to create an account and create transaction. This SDK can be used on browser or Node.JS


Step 1: Install SDK and require it in Application.

// Run in project directory inside the terminal 

sudo npm i stellar-sdk

// Require it in Application.
var StellarSdk = require("stellar-sdk");
const fetch = require('node-fetch');
var server = new StellarSdk.Server("https://horizon-testnet.stellar.org"); //To connect with test horizon

 

Step 2: Create account on Stellar. Unlike other blockchains you need to maintain some minimum balance on the account i.e. 2 Lumens.

const pair = StellarSdk.Keypair.random();

pair.secret();
pair.publicKey();


// After create key pair fund them with some Lumens 

(async function main() {
    try {
      const response = await fetch(
        `https://friendbot.stellar.org?addr=${encodeURIComponent(
          pair.publicKey(),
        )}`,
      );
      const responseJSON = await response.json();
      console.log("SUCCESS! You have a new account :)\n");
      server.loadAccount(pair.publicKey()).then(function(sucess){console.log("Success ",sucess)
    console.log("Public key: "+pair.publicKey()+" Secret: "+pair.secret());
    }).catch(error=>{console.log("error",error)});
    } catch (e) {
      console.error("ERROR!", e);
    }
  })();

 

Step 3: Send Transaction on Stellar.

server.accounts()
  .accountId(source.publicKey())
  .call()
  .then(({ sequence }) => {
    const account = new StellarSdk.Account(source.publicKey(), sequence)
    const transaction = new StellarSdk.TransactionBuilder(account, {
      fee: StellarSdk.BASE_FEE,
      networkPassphrase: Networks.TESTNET
    })
      .addOperation(StellarSdk.Operation.createAccount({
        destination: destination.publicKey(),
        startingBalance: '25'
      }))
      .setTimeout(30)
      .build()
    transaction.sign(StellarSdk.Keypair.fromSecret(source.secret()))
    return server.submitTransaction(transaction)
  })
  .then(results => {
    console.log('Transaction', results._links.transaction.href)
    console.log('New Keypair', destination.publicKey(), destination.secret())
  })

 

Conclusion: In this blog, we get the overview of the Stellar blockchain and get a hand on it Js SDK how it can be used in Application.
 

How to Transfer Ethereum Token using NodeJS

This article gives you a step-by-step guide to transferring an Ethereum token using NodeJS.

 

Ethereum

 

Ethereum is the second-largest blockchain-powered cryptocurrency after bitcoin. It enables developers to program over its blockchain platform to create new types of dApps and smart contract solutions.

 

Ethereum is a decentralized platform that means any government, private organization, or centralized authority cannot control it. People can use applications built with the Ethereum blockchain from any part of the world with an internet connection.

 

Check Out: An Introductory Guide to Ethereum 2.0 | A Major Upgrade

 

Functioning of Ethereum Network

 

Smart contracts define how things get done in the Ethereum system. A smart contract is a set of governance rules used to achieve any business goal. Solidity language is used to write smart contracts.

 

You can create a token over the Ethereum network using a smart contract. Network users can utilize these tokens as digital currencies. One of the most popular types of tokens on Ethereum is an ERC20 token. 

 

The smart contract can be used for various business purposes. It can be used to support other contracts in a similar way software libraries work.

 

Types of Tokens on Ethereum

 

  • ERC20: These are fungible tokens, they hold a specific value.
  • ERC721: These are non-fungible tokens. They hold unique assets like documents and certificates that are not interchangeable.

 

Read More about Ethereum ERC Token Standard

 

How to Transfer Ethereum Token using NodeJS

 

To connect tokens to any network, you can use an infra API key, set up a local node, and sync it with Mainent or another testnet.

 

Prerequisites

 

  • NodeJS
  • Infra API
  • Smart contract ABI and address

 

Steps to Transfer Ethereum Token using NodeJS

 

Step 1: Install the required dependencies for Ethereum

 

npm install web3
npm install ethereumjs-tx

 

Step 2: Create a connection to testnet

 

const Web3 = require("web3");
const Tx = require('ethereumjs-tx');

// Create connection with test net
var web3=new Web3("Infura API endpoint);

var contractAbi = ABI //ABI in JSON format
var contractAddress = Contract_Address

var sender = Sender_Address
var private = Sender_privatekey

var receiver = Reciever_Address
var amountInDecimal = 1 //Amount of token

 

Step 3: Create a signed transaction and send tokens

 

const myContract = new web3.eth.Contract(contractAbi, contractAddress);
var privateKey = new Buffer(private, 'hex')

var txObject = {};
txObject.nonce = web3.utils.toHex(result);
txObject.gasLimit = web3.utils.toHex(90000);

txObject.gasPrice = web3.utils.toHex(10);
txObject.to = contractAddress;
txObject.from = sender;
txObject.value = '0x';

// Calling transfer function of contract and encode it in AB format
txObject.data = myContract.methods.transfer( receiver, web3.utils.toHex(
web3.utils.toWei(amountInDecimal.toString(), "ether"))).encodeABI();

//Sign transaction before sending
var tx = new Tx(txObject);
tx.sign(privateKey);
var serializedTx = tx.serialize();
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('transactionHash', ((data) => {
         console.log(data);
   }));
}).catch(err => {
   console.log(err);
})

 

Also, Read: ERC-20 Token Standard | A Compact Guide to Development

 

Conclusion

 

By following the above steps you can create your code to send tokens from one account to another account. You don't need to rely on any third-party software to interact with the Ethereum network. You can simply send tokens with very few lines of code.

How to set up an Ethereum private node.

Ethereum is a blockchain, as well as a cryptocurrency, used to facilitate digital payments. It is a blockchain-based decentralized, open-source software platform application development. Ethereum is the most popular digital currency in the world after bitcoin. Currently, one Ether costs $237.19. A Russian-Canadian programmer, Vitalik Buterin, created Ethereum blockchain.

 

Bitcoin is only a peer to peer network-based electronic cash system. So, users use bitcoin mainly for digital transactions only. However, if you want to do more than just digital payments, Ethereum comes into play. With the help of Ethereum, you can convert your centralized application into a decentralized application. Ethereum lets a user create/deploy there smart contract solutions and distributed apps (DApps). To deploy code on Ethereum, you need to use EVM, which comes into use to compile/execute a smart contract code. EVM can facilitate compilation/execution of languages like Solidity by directly converting it into opcode first.

To use Ethereum and develop your DApp, you can sync with the testnet and mainnet provided by Ethereum. Usually, syncing an Ethereum node takes a lot of time. Ethereum provides several testnet options like Ropsten, Kovan, and Rinkeby. You can also create a separate Ethereum node on your local system that provides more control over the node. Ethereum provides libraries that let a user configure a private node on their local system, and it works the same as the main Ethereum node.

 

By following the given steps you can create your own Ethereum node at your local system.

 

 

Prerequisites-
OS: Ubuntu

 

Step 1: Install the required libraries for Ethereum

//Open terminal and type following commands
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install software-properties-common
sudo apt-get install ethereum

 

Step 2: Create a separate directory, configure files, and new accounts for the private node

//Open terminal and type following commands

mkdir -p Myethereum && cd Myethereum //Create a directory where all node details will be stored

mkdir -p private && cd private  //Create a sub directory with Mail directory

// Inside private directory enters the following command.

puppeth  // A list be shown to select type of Node you want to create.


// Initialise the genesis block and create account

geth --datadir ~/Myethereum/private init test.json

geth --datadir . account new  //Create new Ethereum account

 

Step 3: Create a shell script to start the node

// Create a new script 

touch node.sh //

// Copy following code inside node.sh. Please update the directory path as per your system.

geth --networkid 4224 --mine --minerthreads 1 --datadir "~/desktop/Username/Myethereum/private" --nodiscover --rpc --rpcport "8545" --port "30303" --rpccorsdomain "*" --nat "any" --rpcapi eth,web3,personal,net --unlock 0 --password ~/Myethereum/private/password.sec --ipcpath "~/Library/Ethereum/geth.ipc"

// To start a node

chmod +x node.sh //Make script executable

./node.sh  //Run the node

Now, your Private Ethereum node is running and you can it status/logs under terminal.

 

Step 4: Attach the node to the geth console

// Type the following command in a separate console.
geth attach

OR

geth attach http://localhost:8545

// Mining

miner.start()  // Start Minig
miner.stop()   // Stop Minig
eth.minig      // Mining status

 

Conclusion: 

The above command can be used to set up your own Ethereum node. Node created is similar to Ethereum mainnet, and you can mine ether, deploy smart contract, and create new accounts.

Integrating AWS Elastic Transcoder With NodeJS Application

Introduction

Elastic transcoding is a media transcoding service provided by AWS. It is highly scalable, cost-effective, and easy to use. It is used to convert media into a suitable format which is playable on different devices like smartphones, tablet, PC, smart tv, etc.

Elastic transcoder converts/transcode video into other formats based on PresetId. Before starting video transcoding, you have to set up an Elastic Transcoder on AWS and get PipelineID for it.

PresetId: AWS provides a list of transcoding formats likes HLS streaming, MPEG-DASH, Webm or you can simply transcode it to different resolutions. All these formats have a unique PresetId which can be used to initiate a transcoding job.


Prerequisites

  • AWS IAM account with access to AWS Elastic transcoder
  • NodeJS
  • NPM

 

1. Install the AWS SDK for NodeJs and configure it.

//Install AWS SDK
npm I aws-sdk

//Create a S3 object and configure it as per credentials

const AWS = require('aws-sdk');

//Create a object that contains access keys
var credentials = {
       accessKeyId: process.env.AWS_ACCESS_KEY,
       secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
};

//Create an Object to start the transcoding Job.
var Etrans = new AWS.ElasticTranscoder({
      apiVersion: '2012–09–25', //Different API versions are provided by s3
      region: 'us-east-1', //Bucket Region
      credentials: credentials,
      videoBucket: 'Bucket_Name',
});

 

2. Create a new transcoding job.

//Create a JSON object to be passed as parameter
var params = {
      PipelineId: pipelineId, //PipelineId of Elastic transcoder
      OutputKeyPrefix: newKey + '/',
      Input: {
      Key: srcKey,  //Source path of video 
      FrameRate: 'auto',
      Resolution: 'auto',
      AspectRatio: 'auto',
      Interlaced: 'auto',
      Container: 'auto'
      },
      Outputs: [{
      Key: 'transcoded/video',
      PresetId: 'Preset_ID',
      "SegmentDuration":'3', //Duration in segment on which transcoding is done as we chose HLS streaming
      ThumbnailPattern: 'poster-{count}', //It is used to create snapshot of Video
      }]
      }

//To create a new Job

Etrans.createJob(params, function(err, data){
      if (err)
      {
        console.log('error is :', err); 
      } 
      else {
        console.log('data is',data);
      }
})

 

3. Read the transcoding Job-status.

// Transcoding Job can take some time so you need to add ReadJob to check status.

 Etrans.readJob({ Id: data.transcodeId }, (err, data) => {
        if (err){
        console.log(err);
        reject(err);
        } 
        else{
         console.log(data)
        }
})

 

Conclusion

The above code can be used to transcode any video stored on the s3 bucket into the required format. Basically, transcoding service is used to convert media into streaming formats.

Deploying NodeJS Application On AWS Lambda

AWS Lambda is a serverless computing service that is used to run code on events and manages the computing tasks required by the code. Lambda is a Function as a Service that is used to build the serverless application that is triggered by events. An application can be deployed on Lambda by creating zip and upload directly to s3 or by setting the serverless framework which can be used to directly upload from the system. In this blog, we are using the serverless framework to deploy on AWS Lambda.

 

Pricing is a crucial factor in AWS development services. AWS Lambda costs $0.20 per 1Million requests and $0.0000166667 for every GB-second which is much less than the standard Amazon EC2 pricing and you don't have to pay for the idle time.

 

Prerequisites

  • AWS IAM account with access to lambda
  • NodeJS
  • NPM

 

1. Install the Serverless Framework and configure it.

//Open Terminal and run these commands
//Install Serverless

npm install -g serverless

//Configure serverless with AWS access key and Secret key.

serverless config credentials --provider aws --secret AWS_SECRET_KEY --key AWS_ACCESS_KEY 

 

2. Install serverless-http in the working directory and update app.js/server.js code.

//Open working directory in terminal and run command
npm install serverless-http

//Update main app/server.js code and remove default create the server code and add the following code.

const serverless = require('serverless-http');
const express = require('express');
let app = express();
module.exports.app = serverless(app);

 

3. Create handler.js and serverless.yml in the root folder of the working directory.

//serverless.yml code

# `service` block defines the name of the service
service: servicename

# `provider` block defines service environment
provider:
  name: aws
  runtime: nodejs10.x

# `functions` block defines functions to be deployed
functions:
  app:
    handler: handler.app
    events: 
      - http: 
          path: /
          method: ANY
          cors: true
      - http: 
          path: /{proxy+}
          method: ANY
          cors: true


//handler.js code

module.exports.app = require('./server/app').app;

 

4. Deploy code on AWS lambda.

// Open working directory in terminal and run command
sudo serverless deploy

 

Conclusion

The above code mention how NodeJS/Express application can be deployed on AWS Lambda using a serverless framework. By using the serverless framework you don't create zip and upload on s3 for each change only one command is required to deploy on AWS Lambda/s3.

Mailchimp Email Service Integration With NodeJS

Mailchimp is an email marketing service and automation platform that helps you manage and talk to your clients and other interested parties. Mailchimp allows you to create a list of an audience where you can send Emails to all audiences or a particular user with the help of Campaigns. Campaigns allow you to use custom or prebuild Email templates from Mailchimp Dashboard so you don't have to manually create an Email format in your backend just call a campaign from your Node application.

 

Creating a Mailchimp Account and Using It In NodeJS Application

Step 1: Create a trial Mailchimp account. Now from dashboard go to API keys option under the Account tab. Get the API key for your account or create a new one.

Step 2: Now go the audience tab and create a new audience and from settings copy its unique ID later to be used in the configuration.

Step 3: Install Mailchimp dependency. Open your project directory and run the command mentioned below.

npm install mailchimp

 

Step 4: Add Mailchimp credential in .env or configuration and create an object for Mailchimp.

// Add Mailchimp Credentials in .env file.

APIKEY = "Mailchimp_Key_obtained_from_step 1"
UNIQUEID = "Audience_ID_obtained_from_step 2"


// Create Mailchimp object in you JS file
var MailChimp = require('mailchimp').MailChimpAPI;
var apiKey = process.env.APIKEY;
global.MailChimpAPI = new MailChimp(apiKey, {
    version: '2.0'
});

 

Step 5: Create a function to subscribe to the Audience or send mail.

// Function to subscribe to Audience
var subscribeUser = function(userInfo) {
        var userData = {
            "id": process.env.UNIQUEID,    //Audience Unique ID
            "email": {
                "email": userInfo.email,   //Client Email
            },
            "merge_vars": {
                FNAME: userInfo.firstName, //Client Name
                LNAME: userInfo.lastName   //Last Name
            }

        }
        MailChimpAPI.call('lists', 'subscribe', userData, function(error, data) {
            if (error)
                CustomLogger.error("Error in subscribing user", error.message);
            else
                CustomLogger.debug(JSON.stringify(data)); // Do something with your data!
        });
    }

//Function to call Campaign. Complete APIs documentation for all functions can be found under the Mailchimp developer guide.

var subscribeUser = function(userInfo) {
       MailChimpAPI.call('campaigns', 'list', { start: 0, limit: 30 }, function (error, data) {
             if (error)
               CustomLogger.error(error.message);
             else
               CustomLogger.debug(JSON.stringify(data)); // Do something with your data!
        });
}

 

Conclusion

In the above code we have integrated Mailchimp Email services in our Node JS Application. We can subscribe to Mailchimp Email service from the Audience and fetch campaign details form these functions. All other functions are similar to these functions only required to change the parameters.

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!