Network Provider

A Network 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 = “localnet” ] )   => Provider

This creates a FallbackProvider backed by multiple backends.

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

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

JsonRpcProvider ( inherits from Provider )

prototype . connection

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

  • url : string url (the JSON-RPC URL)
  • timeout : int RPC request timeout in milliseconds (default: 120,000 ms)
  • user : string username (a username to use for Basic Authentication) optional
  • password : string password ( a password to use for Basic Authentication) optional
  • allowInsecure : boolean allowable of Basic Authentication over an insecure HTTP network (default: false)
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 : string url (the JSON-RPC URL) *required
  • timeout : int RPC request timeout in milliseconds (default: 60,000 ms)
  • user : string username (a username to use for Basic Authentication) optional
  • password : string password ( a password to use for Basic Authentication) optional
  • allowInsecure : boolean allowable of 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 networkProvider = mxw.getDefaultProvider('localnet');
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

Not all properties are mutable unless otherwise specified, and will reflect thier default values if left unspecified.

Provider Variables

prototype . blockNumber

return 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.

data type: integer

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.

data type: boolean

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.

data type: integer

Network

A network represents various properties of a network, such as mainnet (i.e. “testnet”), 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:

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

Account

Wallet using in this part are dummy wallet, it doesn’t have “real” user

prototype . getBalance ( AddressOrName )   => Promise<BigNumber>
Returns a Promise with the balance (as a BigNumber) of the AddressOrName.
get the balance of an account
let address = "mxw1x7tp9tt7mu0jm6qdmljgntvzzp53lrtndr7h8x";

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);
});

//expected result:
//Balance: 0.0
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.
get the transaction count of an account
let address = "mxw1x7tp9tt7mu0jm6qdmljgntvzzp53lrtndr7h8x";

provider.getTransactionCount(address).then((nonce) => {
    console.log("Total Transactions Ever Sent: " + nonce.toString());
});

//expected result:
//Total Transactions Ever Sent: 0
prototype . getAccountNumber ( AddressOrName )   => Promise<BigNumber>
Returns a Promise with the account number of wallet (as a BigNumber) from the AddressOrName.
get the account number
let address = "mxw1x7tp9tt7mu0jm6qdmljgntvzzp53lrtndr7h8x";

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

//expected result:
//Account number:0

Blockchain Status

prototype . getBlockNumber ( )   => Promise<number>
Returns a Promise with the latest block number (as a Number).
get latest block number
provider.getBlockNumber().then((blockNumber) => {
    console.log("Latest block number: " + blockNumber);
});
// expected result:
// Latest block number: "*integer* latest block number"
prototype . getBlock ( blockHashOrBlockNumber )   => Promise<Block>
Returns a Promise with the block at blockHashOrBlockNumber. (See: Block Responses)
blocks
// Block Number
provider.getBlock(12345).then((block) => {
    console.log(block);
});
//expected result:
//block response, click on the link above for more infomation
prototype . getTransactionReceipt ( transactionHash )   => Promise<TransactionReceipt>
Returns a Promise with the transaction receipt with transactionHash. (See: Transaction Receipts)
query transaction receipt
let transactionHash = "0x434c7fe4c7c7068289f0d369e428b7a3bf3882c3253f2b7f9529c0985a1cb500"

provider.getTransactionReceipt(transactionHash).then((receipt) => {
    console.log(receipt);
});
//expected result:
//transaction receipt, click on the link above for more infomation
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").then((fee) => {
    console.log("Fee:", fee);
});

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);
});

//expected result:
//transaction receipt, click on the link above for more details

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.

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
//method parameter is based on vendor RPC API
jsonRpcProvider.send('status', [ ]).then((result) => {
    console.log(result);
});
// expected result:
// "status of the provider for this case"