Docs

Docs

  • Develop
  • Validate
  • Integrate
  • Learn

›erdjs

Welcome to Elrond

  • Welcome to Elrond

Technology

  • Architecture Overview
  • Glossary
  • Entities
  • Chronology
  • Secure Proof of Stake
  • Adaptive State Sharding
  • The Elrond WASM VM
  • Cross Shard Transactions

Wallet

  • Wallets - Overview
  • Web Wallet
  • Maiar Web Wallet Extension
  • Webhooks
  • Ledger

Tokens

  • Native Tokens
  • ESDT tokens
  • NFT tokens

Validators

  • Validators - Overview
  • System Requirements
  • Install a Mainnet Node

    • Scripts & User config
    • Installing a Validator Node
    • Optional Configurations
    • How to use the Docker Image

    Install a Testnet/Devnet Node

    • Scripts & User config
    • Installing a Validator Node
    • Manage a validator node
    • How to use the Docker Image

    Manage your keys

    • Validator Keys
    • Wallet Keys
    • Protecting your keys

    Staking, Unstaking, Unjailing

    • Staking, unstaking and unjailing
    • Staking
    • Unjailing
    • The Staking Smart Contract
  • The Delegation Manager
  • Convert An Existing Validator Into A Staking Pool
  • Merging A Validator Into An Existing Delegation Smart Contract
  • Rating
  • Elrond Node upgrades
  • Node redundancy
  • Import DB
  • Node CLI
  • Node Databases
  • Useful Links & Tools
  • FAQs

Developers

  • Developers - Overview
  • Tutorials

    • Build a dApp in 15 minutes
    • Build a Microservice for your dApp
    • The Crowdfunding Smart Contract (part 1)
    • The Crowdfunding Smart Contract (part 2)
    • The Counter Smart Contract
    • Custom Wallet Connect

    Signing Transactions

    • Signing Transactions
    • Tools for signing
    • Signing programmatically

    Gas and Fees

    • Overview
    • EGLD transfers (move balance transactions)
    • System Smart Contracts
    • User-defined Smart Contracts

    Developer reference

    • The Elrond Serialization Format
    • Smart contract annotations
    • Smart contract modules
    • Smart contract to smart contract calls
    • Smart Contract Developer Best Practices
    • Code Metadata
    • Smart Contract API Functions
    • Storage Mappers
    • Rust Testing Framework
    • Rust Testing Framework Functions Reference
    • Rust Smart Contract Debugging
    • Random Numbers in Smart Contracts

    Developers Best Practices

    • Basics
    • BigUint Operations
    • The dynamic allocation problem
    • Multi-values

    Mandos tests reference

    • Mandos Overview
    • Mandos Structure
    • Mandos Simple Values
    • Mandos Complex Values
    • Embedding Mandos code in Go
  • Constants
  • Built-In Functions
  • Account storage
  • Setup a Local Testnet
  • Set up a Local Testnet (advanced)
  • Creating Wallets

SDK and Tools

  • SDKs and Tools - Overview
  • REST API

    • REST API overview
    • api.elrond.com
    • Gateway overview
    • Addresses
    • Transactions
    • Network
    • Nodes
    • Blocks
    • Virtual Machine
    • Versions and Changelog
  • Proxy
  • Elasticsearch
  • erdpy

    • erdpy
    • Installing erdpy
    • Configuring erdpy
    • erdpy CLI
    • Deriving the Wallet PEM file
    • Sending bulk transactions
    • Writing and running erdpy scripts
    • Smart contract interactions

    erdjs

    • erdjs
    • Cookbook
    • Extending erdjs
    • Writing and testing interactions
    • Migration guides
    • Signing Providers for dApps
  • erdgo
  • erdcpp
  • erdjava
  • erdkotlin
  • erdwalletjs-cli

Integrators

  • Integrators - Overview
  • EGLD integration guide
  • ESDT tokens integration guide
  • Observing Squad
  • Accounts Management
  • Creating Transactions
  • Querying the Blockchain

Extending erdjs

important

Documentation in this section is preliminary and subject to change.

This tutorial will guide you through the process of extending and tailoring certain modules from erdjs.

Extending the Network Providers

The default classes from @elrondnetwork/erdjs-network-providers should only be used as a starting point. As your dApp matures, make sure you switch to using your own network provider, tailored to your requirements (whether deriving from the default ones or writing a new one, from scratch) that directly interacts with the Elrond API (or Gateway).

Performing HTTP requests from scratch

One can broadcast transactions and GET resources from the Elrond API (or Gateway) by performing simple HTTP requests using the axios utility. Below are a few examples:

Broadcasting a transaction:

import axios, { AxiosResponse } from "axios";

let tx = new Transaction({ /* provide the fields */ });
// ... sign the transaction using a dApp / signing provider
let data = tx.toSendable();
let url = "https://devnet-api.elrond.com/transactions";
let response: AxiosResponse = await axios.post(url, data, {
    headers: {
        "Content-Type": "application/json",
    }
});
let txHash = response.data.txHash;

Fetching a transaction:

let url = `https://devnet-api.elrond.com/transactions/${txHash}`;
let response = await axios.get(url);
let transactionOnNetwork = TransactionOnNetwork.fromApiHttpResponse(txHash, response.data);

Querying a smart contract (with parsing the results):

let query = contract.createQuery({
    func: new ContractFunction("foobar"),
    args: [new AddressValue(addressOfAlice)],
    caller: new Address("erd1...")
});

let url = "https://devnet-api.elrond.com/query";
let data = {
    scAddress: query.address.bech32(),
    caller: query.caller?.bech32() ? query.caller.bech32() : undefined,
    funcName: query.func.toString(),
    value: query.value ? query.value.toString() : undefined,
    args: query.getEncodedArguments()
};

let response: AxiosResponse = await axios.post(url, data, {
    headers: {
        "Content-Type": "application/json",
    }
});

let queryResponse = {
    returnCode: response.data.returnCode,
    returnMessage: response.data.returnMessage,
    getReturnDataParts: () => response.data.returnData.map((item) => Buffer.from(item || "", "base64"));
};

let endpointDefinition = contract.getEndpoint("foobar");
let { firstValue, secondValue, returnCode } = resultsParser.parseQueryResponse(queryResponse, endpointDefinition);

Extending a default Network Provider

You can also derive from the default network providers (ApiNetworkProvider and ProxyNetworkProvider) and overwrite / add additional methods, making use of doGetGeneric() and doPostGeneric().

export class MyTailoredNetworkProvider extends ApiNetworkProvider {
    async getEconomics(): Promise<{totalSupply: number, marketCap: number}> {
        let response = await this.doGetGeneric("economics");
        return { totalSupply: response.totalSupply, marketCap: response.marketCap }
    }

    // ... other methods
}

Customizing the transaction awaiting

If, for some reason, the default transaction completion detection algorithm provided by erdjs does not satisfy your requirements, you may want to use a different strategy for transaction awaiting, such as:

await transactionWatcher.awaitAllEvents(transaction, ["mySpecialEventFoo", "mySpecialEventBar"]);
await transactionWatcher.awaitAnyEvents(transaction, ["mySpecialEventFoo", "mySpecialEventBar"]);

Extending the contract results parser

If, for some reason (e.g. a bug), the default ResultsParser provided by erdjs does not satisfy your requirements, you may want to extend it and override the method createBundleWithCustomHeuristics():

export class MyTailoredResultsParser extends ResultsParser {
    protected createBundleWithCustomHeuristics(transaction: ITransactionOnNetwork, transactionMetadata: TransactionMetadata): UntypedOutcomeBundle | null {
        let returnMessage: string = "<< extract the message from the input transaction object >>";
        let values: Buffer[] = [
            Buffer.from("<< extract 1st result from the input transaction object >>"),
            Buffer.from("<< extract 2nd result from the input transaction object >>"),
            Buffer.from("<< extract 3rd result from the input transaction object >>"),
            // ...
        ]

        return {
            returnCode: ReturnCode.Ok,
            returnMessage: returnMessage,
            values: values
        };
    }
}
important

When the default ResultsParser misbehaves, please open an issue on GitHub, and also provide as much details as possible about the unparsable results (e.g. provide a dump of the transaction object if possible - make sure to remove any sensitive information).

← CookbookWriting and testing interactions →
  • Extending the Network Providers
    • Performing HTTP requests from scratch
    • Extending a default Network Provider
  • Customizing the transaction awaiting
  • Extending the contract results parser
Made withby the Elrond team.
GithubChat
Main siteWalletExplorerBridgeDocsGrowthMaiarMaiar Exchange