Providers

A Provider abstracts a connection to the blockchain, for issuing queries and sending signed state changing transactions.

The JsonRpcProvider allow you to connect to blockchain nodes that you control or have access to, including mainnet, testnets, or localnets.


Connecting to Blockchain

There are several methods to connect to the blockchain network provided. If you are not running your own local blockchain node, it is recommended that you use the getDefaultProvider() method.

mxw . getDefaultProvider( [ network = “homestead” ] )   => Provider

This is the recommended method of connecting to the blockchain network if you are not running your own blockchain node.

This creates a FallbackProvider backed by multiple backends.

get a standard network provider
let provider = mxw.getDefaultProvider("homestead");

JsonRpcProvider ( inherits from Provider )

prototype . connection

An object describing the connection of the JSON-RPC endpoint with the properties:

  • url — the JSON-RPC URL
  • timeout — the RPC request timeout in milliseconds (default: 120,000 ms)
  • user — a username to use for Basic Authentication (optional)
  • password — a password to use for Basic Authentication (optional)
  • allowInsecure — allows Basic Authentication over an insecure HTTP network
new mxw . providers . JsonRpcProvider( [ urlOrInfo = “http://localhost:26657” ] [ , network ] )

Connect to the JSON-RPC API URL urlorInfo of an blockchain node.

The urlOrInfo may also be specified as an object with the properties:

  • url — the JSON-RPC URL (required)
  • timeout — the RPC request timeout in milliseconds (default: 60,000 ms)
  • user — a username to use for Basic Authentication (optional)
  • password — a password to use for Basic Authentication (optional)
  • allowInsecure — allow Basic Authentication over an insecure HTTP network (default: false)

Also See: JSON-RPC provider-specific Properties and Operations

connect to a default provider
// You can use any standard network name
//  - "homestead"
//  - "testnet"

let provider = mxw.getDefaultProvider('testnet');
connect to private trusted node
let provider = new mxw.providers.JsonRpcProvider({
    url: "https://x.x.x.x",
    timeout: 60000
}, "mxw");
connect to private customized node
let provider = new mxw.providers.JsonRpcProvider({
    url: "https://x.x.x.x",
    timeout: 60000
}, {
    chainId: "awesome",
    name: "awesome"
});

Properties

All properties are immutable unless otherwise specified, and will reflect their default values if left unspecified.

Provider

prototype . blockNumber
The most recent block number (block height) this provider has seen and has triggered events for. If no block has been seen, this is null.
prototype . polling

mutable

If the provider is currently polling because it is actively watching for events. This may be set to enable/disable polling temporarily or disabled permanently to allow a node process to exit.

prototype . pollingInterval

mutable

The frequency (in milliseconds) that the provider is polling. The default interval is 4 seconds.

This may make sense to lower for polling a local node. When polling external nodes, setting this too low may result in the service blocking your IP address or otherwise throttling your API calls.

Network

A network repsents various properties of a network, such as mainnet (i.e. “homestead”), testnet or private networks.

prototype . getNetwork ( )   => Promise<Network>

A Promise that resolves to a Network object describing the connected network and chain. A network has the following properties:

  • name — the name of the network (e.g. “homestead”)
  • chainId — the chain ID (network ID) of the connected network
get a standard network
let network = mxw.providers.getNetwork('homestead');
// {
//    chainId: "mxw",
//    name: "homestead"
// }
a custom development network
let network = {
    chainId: "localnet",
    name: "local"
}

Account

prototype . getBalance ( addressOrName )   => Promise<BigNumber>
Returns a Promise with the balance (as a BigNumber) of the addressOrName.
prototype . getTransactionCount ( addressOrName )   => Promise<BigNumber>
Returns a Promise with the number of sent transactions (as a BigNumber) from the addressOrName. This is also the nonce required to send a new transaction.
prototype . getAccountNumber ( addressOrName )   => Promise<BigNumber>
Returns a Promise with the account number of wallet (as a BigNumber) from the addressOrName.
get the balance of an account
let address = "mxw12h2a2ky8cyldm5qhm6xluu0ggapeztzcypww4c";

provider.getBalance(address).then((balance) => {

    // balance is a BigNumber (in cin); format is as a string (in mxw)
    let mxwString = mxw.utils.formatMxw(balance);

    console.log("Balance: " + mxwString);
});
get the transaction count of an account
let address = "mxw12h2a2ky8cyldm5qhm6xluu0ggapeztzcypww4c";

provider.getTransactionCount(address).then((nonce) => {
    console.log("Total Transactions Ever Sent: " + nonce.toString());
});
get the account number
let address = "mxw12h2a2ky8cyldm5qhm6xluu0ggapeztzcypww4c";

provider.getAccountNumber(address).then((accountNumber) => {
    console.log("Account number: " + accountNumber.toString());
});

Blockchain Status

prototype . getBlockNumber ( )   => Promise<number>
Returns a Promise with the latest block number (as a Number).
prototype . getBlock ( blockHashOrBlockNumber )   => Promise<Block>
Returns a Promise with the block at blockHashOrBlockNumber. (See: Block Responses)
prototype . getTransactionReceipt ( transactionHash )   => Promise<TransactionReceipt>
Returns a Promise with the transaction receipt with transactionHash. (See: Transaction Receipts)
prototype . getTransactionFee ( route, transactionType, overrides, … )   => Promise<TransactionFee>

Returns a Promise that resolves to the estimated transaction fee structure.

The valid routes and transaction types are:
  • kyc — the route for kyc module
    • kyc-whitelist — the whitelist transaction type
    • kyc-revokeWhitelist — the revoke whitelist transaction type
  • bank — the route for bank module
    • bank-send — the MXW transfer transaction type
  • token — the route for token module
    • token-mintFungibleToken — the mint transaction type
    • token-burnFungibleToken — the burn transaction type
    • token-freeze — the freeze transaction type
    • token-unfreeze — the unfreeze transaction type
    • token-createFungibleToken — the create transaction type
    • token-setFungibleTokenStatus — the set status transaction type
  • nameservice — the route for name service module
    • nameservice-createAlias — the create transaction type
    • nameservice-setAliasStatus — the set status transaction type
the transaction fee structure
{
    amount: [
        {
            // The denomination should be in cin
            denom: string,

            // The fee amount in cin
            amount: BigNumberish
        }
    ],
    // Reserved for future
    gas: BigNumberish
}
query the transaction fee
let value = utils.parseMxw("10").toString();
provider.getTransactionFee("bank", "bank-send", null, value).then((fee) => {
    console.log("Fee:", fee);
});
get latest block number
provider.getBlockNumber().then((blockNumber) => {
    console.log("Latest block number: " + blockNumber);
});
blocks
// Block Number
provider.getBlock(12345).then((block) => {
    console.log(block);
});
query transaction receipt
let transactionHash = "0x434c7fe4c7c7068289f0d369e428b7a3bf3882c3253f2b7f9529c0985a1cb500"

provider.getTransactionReceipt(transactionHash).then((receipt) => {
    console.log(receipt);
});

Waiting for Transactions

prototype . waitForTransaction ( transactionHash )   => Promise<TransactionReceipt>
Return a Promise which resolves to the Transaction Receipt once transactionHash is validated.
transaction validated
provider.waitForTransaction(transactionHash).then((receipt) => {
    console.log('Transaction validated: ' + receipt.hash);
    console.log(receipt);
});

Objects and Types

There are several common objects and types that are commonly used as input parameters or return types for various provider calls.


Block Tag

A block tag is used to uniquely identify a block’s position in the blockchain:

a Number or hex string:
Each block has a block number (eg. 1202 or "0x4b2").
“latest”:
The most recently validated block.
“pending”:
The block that is currently being validated.

Block Responses

{
    // The block height
    blockNumber: 221950,

    results: {
        // The transaction was validated in the block
        transactions: [
            {
                // Transaction hash (unique identifier)
                hash: "0x47bef4762a8b5646f03b346e64cebde005370a2d4c0610c833fa17828ad1878e",
                nonce: 77,
                transactionIndex: 0

                tags: [
                    {
                        // the event owner
                        address: "mxw1mklypleqjhemrlt6z625rzqa0jl6namdmmqnx4",

                        // The transaction event was emitted to
                        event: {
                            // the event hash for first 20 bytes SHA256 of event identifier
                            // e.g: SHA256 of Transferred(string,string,bignumber)
                            hash: "0x2cadcfb0c336769d503d557b26fcf1e91819e7e5",

                            // The parameter of this event
                            params: [
                                "mxw1mklypleqjhemrlt6z625rzqa0jl6namdmmqnx4",
                                "mxw1ngx32epz5v5gyunepkarfh4lt0g6mqr79aq3ex",
                                "100000000000000000000000"
                            ],
                            transactionIndex: 0,    // the transaction index in the block
                            eventIndex: 0           // the event index of this transaction
                        }
                    }
                ],

                // The transaction log messages
                logs: [
                    {
                        success: true,
                        info: {
                            nonce: 77,
                            hash: "0x47bef4762a8b5646f03b346e64cebde005370a2d4c0610c833fa17828ad1878e"
                        }
                    }
                ]
            }
        ]
    }
}

Transaction Requests

Any property which accepts a number may also be specified as a BigNumber or hex string. Any property may also be given as a Promise which resolves to the expected type.

{
    type: "auth/StdTx",
    value: {
        // Transaction system fee in 18 decimals (cin)
        fee: {
            amount: [
                {
                    amount: "10000000000000000000",
                    denom: "cin"
                }
            ],
            gas: "200000"
        },

        // Transaction memo that can fits in 256 UTF8 characters
        memo: "",

        msg: [
            {
                // Transaction type
                type: "mxw/MsgSend",

                // Transaction message payload
                value: {
                    amount: [
                        {
                            amount: "100000000000000000000000",
                            denom: "cin"
                        }
                    ],
                    fromAddress: "mxw1mklypleqjhemrlt6z625rzqa0jl6namdmmqnx4",
                    toAddress: "mxw1ngx32epz5v5gyunepkarfh4lt0g6mqr79aq3ex"
                }
            }
        ],

        // Transaction signatures
        signatures: [
            {
                signature: "8F0GZv1QsMihuCrOS92x1TbpN0qhUNzhr+JuuHMD4x5O4jFuZPI8PIMAt0EqyCK2teF2SEiRYRm4RntXJulkWA==",
                pubKey: {
                    type: "tendermint/PubKeySecp256k1",
                    valu: "AvUZonVWLNSnH6s7WCdVgJEtQx1lLgtwsqjtFk4Yqabt"
                }
            }
        ]
    }
}

Transaction Receipts

{
    // Transaction hash (unique identifier)
    hash: "0x30080e4120ee65abdd2f7f9ba3ef2b42c34fb3e03de676d2f116a3a44ce65b74",

    // The block this transaction was validated to
    blockNumber: 350476,    // the block height
    nonce: 265,             // the transaction sequence
    index: 0,               // the transaction index always set 0 in receipt

    // Transaction status
    status: 1,              // 1 indicated successful, 0 indicated failure during execution
    confirmations: 2        // the number of block from latest block

    result: {
        tags: [
            {
                // The transaction event was emitted to
                address: "mxw1mklypleqjhemrlt6z625rzqa0jl6namdmmqnx4",  // the event producer
                event: {
                    // the event hash for first 20 bytes SHA256 of event identifier
                    // e.g: SHA256 of Transferred(string,string,bignumber)
                    hash: "0x2cadcfb0c336769d503d557b26fcf1e91819e7e5",
                    // The parameter of this event
                    params: [
                        "mxw1mklypleqjhemrlt6z625rzqa0jl6namdmmqnx4",
                        "mxw1ngx32epz5v5gyunepkarfh4lt0g6mqr79aq3ex",
                        "100000000000000000000000"
                    ],
                    transactionIndex: 0,    // the transaction index always set 0 in receipt
                    eventIndex: 0           // the event index of this transaction
                }
            }
        ],

        // Transaction logs
        logs: [
            {
                success: true,
                info: {
                    nonce: 265
                }
            }
        ]
    },

    // Transaction payload
    data: {
        type: "auth/StdTx",
        value: {
            fee: {
                amount: [
                    {
                        amount: "10000000000000000000",
                        denom: "cin"
                    }
                ],
                gas: "200000"
            },
            memo: "",
            msg: [
                {
                    type: "cosmos-sdk/MsgSend",
                    value: {
                        amount: [
                            {
                                amount: "100000000000000000000000",
                                denom: "cin"
                            }
                        ],
                        fromAddress: "mxw1mklypleqjhemrlt6z625rzqa0jl6namdmmqnx4",
                        toAddress: "mxw1ngx32epz5v5gyunepkarfh4lt0g6mqr79aq3ex"
                    }
                }
            ],
            signatures: [
                {
                    signature: "8F0GZv1QsMihuCrOS92x1TbpN0qhUNzhr+JuuHMD4x5O4jFuZPI8PIMAt0EqyCK2teF2SEiRYRm4RntXJulkWA==",
                    pubKey: {
                        type: "tendermint/PubKeySecp256k1",
                        valu: "AvUZonVWLNSnH6s7WCdVgJEtQx1lLgtwsqjtFk4Yqabt"
                    }
                }
            ]
        }
    }
}

Provider Specific Extra API Calls

JsonRpcProvider

prototype . send ( method , params )   => Promise<any>
Send the JSON-RPC method with params. This is useful for calling non-standard or less common JSON-RPC methods. A Promise is returned which will resolve to the parsed JSON result.
send vendor specific JSON-RPC API
jsonRpcProvider.send('status', [ ]).then((result) => {
    console.log(result);
});