Class Provider

Class to connect with the RPC node

Hierarchy

  • Provider

Implements

Constructors

  • Example

    const provider = new Provider([
    "https://api.koinos.io",
    "https://api.koinosblocks.com"
    ]);

    Parameters

    • rpcNodes: string | string[]

      URL of the rpc node, or array of urls to switch between them when someone is down

    Returns Provider

Properties

currentNodeId: number

Index of current node in rpcNodes

onError: ((error: Error, currentNode: string, newNode: string) => boolean)

Type declaration

    • (error: Error, currentNode: string, newNode: string): boolean
    • Function triggered when a node is down. Returns a boolean determining if the call should be aborted.

      Example

      const provider = new Provider(["https://api.koinos.io"]);

      provider.onError = (error, node, newNode) => {
      console.log(`Error from node ${node}: ${error.message}`);
      console.log(`changing node to ${newNode}`);
      const abort = false;
      return abort;
      }

      Parameters

      • error: Error
      • currentNode: string

        node that threw the error

      • newNode: string

        node used for the next iteration

      Returns boolean

rpcNodes: string[]

Array of URLs of RPC nodes

Methods

  • Function to make jsonrpc requests to the RPC node

    Returns

    Result of jsonrpc response

    To know the full list of possible calls check the services listed in the rpc folder of koinos-proto and the corresponding proto files.

    Example

    Let's take "account_history" as an example. Go to account_history_rpc.proto. The account_history_request message has 1 single method: get_account_history.

    Now search the message get_account_history_request. This message is telling us the expected fields in the body of the call:

    message get_account_history_request {
    bytes address = 1 [(btype) = ADDRESS];
    optional uint64 seq_num = 2 [jstype = JS_STRING];
    uint64 limit = 3 [jstype = JS_STRING];
    bool ascending = 4;
    bool irreversible = 5;
    }

    And search the message get_account_history_response to see the format of the response:

    message get_account_history_response {
    repeated account_history_entry values = 1;
    }

    With this information we can now call the RPC node. It should be done in this way:

    const provider = new Provider(["https://api.koinos.io"]);
    const result = await provider.call(
    "account_history.get_account_history",
    {
    address: "1z629tURV9KAK6Q5yqFDozwSHeWshxXQe",
    limit: 2,
    ascending: true,
    irreversible: true,
    }
    );
    console.log(result);

    // {
    // "values": [
    // {
    // "trx": {
    // "transaction": {
    // "id": "0x12205b566701d6afcf1f5e45b5e9f5443def75728c219f7c1e897ed0ce1ef491223c",
    // "header": {
    // "chain_id": "EiBZK_GGVP0H_fXVAM3j6EAuz3-B-l3ejxRSewi7qIBfSA==",
    // "rc_limit": "961224079493",
    // "nonce": "KAE=",
    // "operation_merkle_root": "EiA32K_GrZ2VsvWSrM4QZhyEmvm8ID1P6aE4vP00RnY9hg==",
    // "payer": "1HyzBsd7nmyUp8dyCJqJZoQRUnzifVzP18"
    // },
    // "operations": [
    // {
    // "call_contract": {
    // "contract_id": "15DJN4a8SgrbGhhGksSBASiSYjGnMU8dGL",
    // "entry_point": 670398154,
    // "args": "ChkAukkLSXtxbRNRTBtDrdAwDI7I6Ot9GxFHEhkACsvmdCIUj89udQ1R5iLPLXzqJoHdliWrGIDC1y8="
    // }
    // }
    // ],
    // "signatures": [
    // "ICBdTcH6jzhDpl9ZB0ZqNcvSy8wiOokHFtkQ66Lc04K1LhXd77tqaQdMhJOAfYotg5npVmfSgyO9CwgLJmtMIjg="
    // ]
    // },
    // "receipt": {
    // "id": "0x12205b566701d6afcf1f5e45b5e9f5443def75728c219f7c1e897ed0ce1ef491223c",
    // "payer": "1HyzBsd7nmyUp8dyCJqJZoQRUnzifVzP18",
    // "max_payer_rc": "961224079493",
    // "rc_limit": "961224079493",
    // "rc_used": "3009833",
    // "disk_storage_used": "112",
    // "network_bandwidth_used": "313",
    // "compute_bandwidth_used": "561439",
    // "events": [
    // {
    // "sequence": 2,
    // "source": "15DJN4a8SgrbGhhGksSBASiSYjGnMU8dGL",
    // "name": "koinos.contracts.token.transfer_event",
    // "data": "ChkAukkLSXtxbRNRTBtDrdAwDI7I6Ot9GxFHEhkACsvmdCIUj89udQ1R5iLPLXzqJoHdliWrGIDC1y8=",
    // "impacted": [
    // "1z629tURV9KAK6Q5yqFDozwSHeWshxXQe",
    // "1HyzBsd7nmyUp8dyCJqJZoQRUnzifVzP18"
    // ]
    // }
    // ]
    // }
    // }
    // },
    // {
    // "seq_num": "1",
    // "trx": {
    // "transaction": {
    // "id": "0x1220a08183a5237e57a08e1ae539017c4253ddfbc23f9b7b6f5e263669aacd3fed47",
    // "header": {
    // "chain_id": "EiBZK_GGVP0H_fXVAM3j6EAuz3-B-l3ejxRSewi7qIBfSA==",
    // "rc_limit": "100000000",
    // "nonce": "KAE=",
    // "operation_merkle_root": "EiBAmutXQlPyAGctNBNhKEUUEUtwj2KQeNrdFBqpN9RWDg==",
    // "payer": "1z629tURV9KAK6Q5yqFDozwSHeWshxXQe"
    // },
    // "operations": [
    // {
    // "call_contract": {
    // "contract_id": "15DJN4a8SgrbGhhGksSBASiSYjGnMU8dGL",
    // "entry_point": 670398154,
    // "args": "ChkACsvmdCIUj89udQ1R5iLPLXzqJoHdliWrEhkAukkLSXtxbRNRTBtDrdAwDI7I6Ot9GxFHGJBO"
    // }
    // }
    // ],
    // "signatures": [
    // "IF5FBloKjEfnqlGJRL_aPy4L36On-Q8XXzpAQagK_X-xZ6DgioBhZOhKEnhKyhaoROAgGwRuy6BsdRqya8fCHU8="
    // ]
    // },
    // "receipt": {
    // "id": "0x1220a08183a5237e57a08e1ae539017c4253ddfbc23f9b7b6f5e263669aacd3fed47",
    // "payer": "1z629tURV9KAK6Q5yqFDozwSHeWshxXQe",
    // "max_payer_rc": "100000000",
    // "rc_limit": "100000000",
    // "rc_used": "2657385",
    // "disk_storage_used": "35",
    // "network_bandwidth_used": "309",
    // "compute_bandwidth_used": "566375",
    // "events": [
    // {
    // "sequence": 2,
    // "source": "15DJN4a8SgrbGhhGksSBASiSYjGnMU8dGL",
    // "name": "koinos.contracts.token.transfer_event",
    // "data": "ChkACsvmdCIUj89udQ1R5iLPLXzqJoHdliWrEhkAukkLSXtxbRNRTBtDrdAwDI7I6Ot9GxFHGJBO",
    // "impacted": [
    // "1HyzBsd7nmyUp8dyCJqJZoQRUnzifVzP18",
    // "1z629tURV9KAK6Q5yqFDozwSHeWshxXQe"
    // ]
    // }
    // ]
    // }
    // }
    // }
    // ]
    // }

    Type Parameters

    • T = unknown

    Parameters

    • method: string

      jsonrpc method

    • params: unknown

      jsonrpc params

    Returns Promise<T>

  • Parameters

    • account: string

    Returns Promise<string>

  • Function to get a block by its height

    Example

    const provider = new Provider("https://api.koinos.io");
    const block = await provider.getBlock(14951433);
    console.log(block);

    // {
    // block_id: '0x1220d5e848eb0f69c590c24cbea4391f89a1055f540bc265c60f6b13c4cc0055ec36',
    // block_height: '14951433',
    // block: {
    // id: '0x1220d5e848eb0f69c590c24cbea4391f89a1055f540bc265c60f6b13c4cc0055ec36',
    // header: {
    // previous: '0x1220a3c4cbc57ccee4d02b4a1849a9e504122ee93b904deff711d926def2ea2cc878',
    // height: '14951433',
    // timestamp: '1713854518430',
    // previous_state_merkle_root: 'EiCPcnYosMvEBYeCcJrdIJJG0mp4TJ796UGxa0NY6EvzbQ==',
    // transaction_merkle_root: 'EiBGPKwttckB7c_BafwnHHmHTBa9S1vKBKauj_yLVNb0tg==',
    // signer: '1EPZaqve43k9Jq5mNeT2ydCjUiytTTU4U',
    // approved_proposals: [Array]
    // },
    // transactions: [ [Object] ],
    // signature: 'ClEDnHKX1F-pQVbFhmz2qnrwGfP-RbEfTdRFUrvmhmqMeoejtmm2Q0yIPbD5kN5xpIEb
    // 8vVwsIJ3lTrgFz2E8w0Paxkgv1E_gMaYNq5UUqtHnl0SIhIgAAbuPHmfMKh9R0Yi5y1D
    // TpjjdN0DYKaIUseXzLiLg_QaQR9jRinZf0g_qo2_4wOx9gDBunIij0r5CycHrNMsuT_V
    // _UvrJOYuwj7aUCA-qnF2tCBQoNQZ3ww7WvKHrMdChxxy'
    // },
    // receipt: {
    // id: '0x1220d5e848eb0f69c590c24cbea4391f89a1055f540bc265c60f6b13c4cc0055ec36',
    // height: '14951433',
    // disk_storage_used: '35',
    // network_bandwidth_used: '760',
    // compute_bandwidth_used: '5253506',
    // events: [ [Object], [Object] ],
    // transaction_receipts: [ [Object] ],
    // disk_storage_charged: '35',
    // network_bandwidth_charged: '760',
    // compute_bandwidth_charged: '5180427',
    // state_delta_entries: [
    // [Object], [Object],
    // [Object], [Object],
    // [Object], [Object],
    // [Object], [Object],
    // [Object], [Object]
    // ]
    // }
    // }

    Use the options to get less information. This helps to reduce the bandwidth of the call.

    Example

    const provider = new Provider("https://api.koinos.io");
    const block = await provider.getBlock(14951433, {
    returnReceipt: false,
    returnBlock: false
    });
    console.log(block);

    // {
    // block_id: '0x1220d5e848eb0f69c590c24cbea4391f89a1055f540bc265c60f6b13c4cc0055ec36',
    // block_height: '14951433'
    // }

    Parameters

    Returns Promise<{ block: BlockJson; block_height: string; block_id: string; receipt: BlockReceipt }>

  • Function to get consecutive blocks in descending order

    Parameters

    • height: number

      Starting block height

    • numBlocks: number = 1

      Number of blocks to fetch

    • Optional idRef: string

      Block ID reference to speed up searching blocks. This ID must be from a greater block height. By default it gets the ID from the block head.

    • Optional opts: GetBlockOptions

    Returns Promise<{ block: BlockJson; block_height: string; block_id: string; receipt: BlockReceipt }[]>

  • Function to get the chain

    Returns Promise<string>

  • Function to get info from the head block in the blockchain

    Example

    const provider = new Provider("https://api.koinos.io");
    const headInfo = await provider.getHeadInfo();
    console.log(headInfo);

    // {
    // head_topology: {
    // id: '0x12209f7c9b4d695eefd6f87465d490654e495fe25a3d7d2e1eb80658acdc49bad962',
    // height: '14957951',
    // previous: '0x1220bc3b94e3a2adc3ca09d61a4418df1f4acfa78a69686f592877c194ea50642cd2'
    // },
    // last_irreversible_block: '14957891',
    // head_state_merkle_root: 'EiCriqXooNUXBG23EUKLz2qq3h9ZAC8w1W7w185YQ9MzIA==',
    // head_block_time: '1713874497290'
    // }

    Returns Promise<{ head_block_time: string; head_state_merkle_root: string; head_topology: BlockTopology; last_irreversible_block: string }>

  • Function to call "chain.get_account_nonce" (number of transactions for a particular account) and return the next nonce. This call is used when creating new transactions. The result is encoded in base64url

    Returns

    Nonce

    Parameters

    • account: string

      account address

    Returns Promise<string>

  • Function to call "chain.get_account_nonce" to return the number of transactions for a particular account. If you are creating a new transaction consider using Provider.getNextNonce.

    Returns

    Nonce

    Parameters

    • account: string

      account address

    • deserialize: boolean = true

      If set true it will deserialize the nonce and return it as number (default). If set false it will return the nonce encoded as received from the RPC.

    Returns Promise<string | number>

  • Funciont to call "chain.get_resource_limits" to get resource limits

    Returns Promise<{ resource_limit_data: { compute_bandwidth_cost: string; compute_bandwidth_limit: string; disk_storage_cost: string; disk_storage_limit: string; network_bandwidth_cost: string; network_bandwidth_limit: string } }>

  • Get transactions by id and their corresponding block ids

    Parameters

    • transactionIds: string[]

    Returns Promise<{ transactions: { containing_blocks: string[]; transaction: TransactionJson }[] }>

  • Function to get the address of a system contract

    Example

    • ```ts const provider = new Provider("https://api.koinos.io"); const result = await provider.invokeGetContractAddress("koin"); console.log(result);

    // { value: { address: '15DJN4a8SgrbGhhGksSBASiSYjGnMU8dGL' } } ```

    Parameters

    • name: string

      contract name

    Returns Promise<{ value: { address: string } }>

  • Function to get the contract metadata of a specific contract.

    Example

    const provider = new Provider("https://api.koinos.io");
    const result = await provider.invokeGetContractMetadata("15DJN4a8SgrbGhhGksSBASiSYjGnMU8dGL");
    console.log(result);

    // {
    // value: {
    // hash: '0x1220c57e3573189868970a3a1662a667c366b15015d9b7900ffed415c5e944036e88',
    // system: true,
    // authorizes_call_contract: true,
    // authorizes_transaction_application: true,
    // authorizes_upload_contract: true
    // }
    // }

    Parameters

    • contractId: string

      contract ID

    Returns Promise<{ value: { authorizes_call_contract: boolean; authorizes_transaction_application: boolean; authorizes_upload_contract: boolean; hash: string; system: boolean } }>

  • Function to call "chain.invoke_system_call" to invoke a system call.

    Type Parameters

    • T = Record<string, unknown>

    Parameters

    • serializer: Serializer
    • nameOrId: string | number
    • args: Record<string, unknown>
    • Optional callerData: { caller: string; caller_privilege: number }
      • caller: string
      • caller_privilege: number

    Returns Promise<T>

  • Function to call "chain.read_contract" to read a contract. This function is used by Contract class when read methods are invoked.

    Parameters

    Returns Promise<{ logs: string; result: string }>

  • Function to call "chain.submit_transaction" to send a signed transaction to the blockchain.

    It also has the option to not broadcast the transaction (to not include the transaction the mempool), which is useful if you want to test the interaction with a contract and check the possible events triggered.

    Returns

    It returns the receipt received from the RPC node and the transaction with the arrow function "wait" (see wait)

    Parameters

    • transaction: TransactionJson | TransactionJsonWait

      Transaction

    • broadcast: boolean = true

      Option to broadcast the transaction to the whole network. By default it is true.

    Returns Promise<{ receipt: TransactionReceipt; transaction: TransactionJsonWait }>

  • Function to call "chain.submit_block" to send a signed block to the blockchain.

    Parameters

    Returns Promise<Record<string, never>>

  • Function to wait for a transaction to be mined.

    Example

    const blockNumber = await provider.wait(txId);
    // const blockNumber = await provider.wait(txId, "byBlock", 15000);
    // const blockId = await provider.wait(txId, "byTransactionId", 15000);
    console.log("Transaction mined")

    Parameters

    • txId: string

      transaction id

    • type: "byBlock" | "byTransactionId" = "byBlock"

      Type must be "byBlock" (default) or "byTransactionId". byBlock will query the blockchain to get blocks and search for the transaction there. byTransactionId will query the "transaction store" microservice to search the transaction by its id. If non of them is specified the function will use "byBlock" (as "byTransactionId" requires the transaction store, which is an optional microservice).

      When byBlock is used it returns the block number.

      When byTransactionId is used it returns the block id.

    • timeout: number = 15000

      Timeout in milliseconds. By default it is 15000

    Returns Promise<{ blockId: string; blockNumber?: number }>

Generated using TypeDoc