Overview
The purpose of this page is to give you a sense of everything js-conflux-sdk can do and serve as a quick reference guide

Pre-requisites

  1. 1.
    Node.js environment to install this SDK
  2. 2.
    Conflux account with some CFX (Use FluentWallet to create account and get testnet CFX from faucet)
  3. 3.
    Conflux RPC endpoint, for example https://test.confluxrpc.com is a testnet RPC endpoint

Initialize

After installing js-conflux-sdk (via npm), you’ll need to specify the provider url. You can use the mainnet(https://main.confluxrpc.com), or testnet(https://test.confluxrpc.com), or run your own Conflux node.

Testnet

With a RPC endpoint we can initialize a Conflux object, which can be used to send JSON RPC request.
1
const { Conflux } = require('js-conflux-sdk');
2
// initialize a Conflux object
3
const conflux = new Conflux({
4
url: 'https://test.confluxrpc.com',
5
logger: console, // for debug
6
networkId: 1, // networkId is also need to pass
7
});
Copied!
1
// Conflux class also have a static method `create`, can be used to create a new instance with no need to set networkId option
2
async function main() {
3
const conflux = await Conflux.create({
4
url: "https://test.confluxrpc.com",
5
});
6
}
Copied!
Besides url and logger you can pass other options to initialize a Conflux object

Add account

Private keys are required to approve any transaction made on your behalf, conflux.wallet provide utility help you manage your accounts
1
conflux.wallet.addPrivateKey('0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef');
Copied!
Only after you add your account to wallet, then you can use them send transactions.

Send JSON-RPC request

There are a lot methods on cfx object which are one-to-one with Conflux node RPC methods. All conflux methods will return a promise, so you can use it with async/await syntax.
1
async function main() {
2
// get balance
3
const balance = await conflux.cfx.getBalance('cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957');
4
console.log(balance.toString()); // 10098788868004995614504
5
}
6
7
main();
Copied!
Besides balance you can get a lot blockchain information through it, for example: nonce, block, transaction, receipt and so on. You can check API and RPC

Conflux hex address

Note: from Conflux-rust v1.1.1 we have import a new base32 encoded address, the hex address can not be used then.
In Conflux network there are three kind address:
  • Normal address 0x1 prefix: 0x1386B4185A223EF49592233b69291bbe5a80C527
  • Contract address 0x8 prefix: 0x80a17fd515c1fc819e87e606c058490ac1f14ca7
  • Internal contract address 0x0888 prefix: 0x0888000000000000000000000000000000000000
So normally a ethereum's address cann't used as conflux address, otherwise it starts with 0x1
Notice: one address can have two form checksumed and not checksumed, these two actually are same account. For example 0x1386B4185A223EF49592233b69291bbe5a80C527 and 0x1386b4185a223ef49592233b69291bbe5a80c527 which point to same account.

Conflux base32 checksum address

From conflux-rust 1.1.1 Conflux has switch to base32Checksum address for example cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957. It was introduced by CIP37. js-conflux-sdk add support for it from version 1.5.10, check here for details.

Send Transaction

1
// first add account's private key to wallet
2
const account = conflux.wallet.addPrivateKey('0xxxxxxxxxx');
3
const targetAddress = 'cfxtest:xxxxxxx';
4
let hash = await conflux.cfx.sendTransaction({
5
from: account.address,
6
to: targetAddress,
7
value: 1 // the unit is drip
8
});
9
10
// check tx status through it's hash
11
let transaction = await conflux.cfx.getTransactionByHash(hash); // normally need half minute to get transaction info
12
console.log(transaction);
Copied!
Check here for details

chainId

chainId is used to distinguish different network and prevent replay attack, currently:
  • mainnet: 1029
  • testnet: 1

RPC endpoint

Hex value and epochNumber and tags

You can find the epochNumber doc at official developer RPC doc

JSBI

Because in blockchain world there are a lot big numbers (uint256), only modern JS VM and Node.js support BigInt, so we use JSBI in browser environment to handle these big number. For how to use JSBI check it's documentation
Note: jsbi currently cann't pretty log, you need convert it to string before log.
1
const max = JSBI.BigInt(Number.MAX_SAFE_INTEGER);
2
console.log(String(max));
3
// → '9007199254740991'
4
console.log(max.toString()); // directly log a jsbi is very ugly
5
// JSBI(2) [ -1, 2097151, sign: false ]
Copied!
Note: When a js integer is bigger than Number.MAX_SAFE_INTEGER (2^53 - 1 or 9,007,199,254,740,991) you should use BigInt to contain it.

Drip

In Conflux network there are there unit: CFX, Drip, Gdrip. Drip is the minimum unit in Conflux 1 CFX=10^18Drip, 1Gdrip=10^9Drip. When getting account's balance, send transaction, specify gasPrice, all unit will be Drip. The SDK has provide a class Drip, which can use to easily convert between different unit.
1
import {Drip} from "js-conflux-sdk"
2
3
let drip1 = Drip.fromCFX(1);
4
console.log(drip1);
5
// 1000-000-000-000-000-000
6
let drip2 = Drip.fromGDrip(1);
7
console.log(drip1);
8
// 1000-000-000
9
let drip3 = new Drip(1);
10
console.log(drip3);
11
// 1
12
console.log(drip3.toCFX());
13
// 1
14
console.log(drip1.toGdrip());
15
// 1000-000-000
Copied!

Websocket provider

The SDK also provide a websocket provider, and the default Conflux node ws port is 12535.
1
const { Conflux } = require('js-conflux-sdk');
2
3
async function main() {
4
// initialize a Conflux object
5
const conflux = new Conflux({
6
url: 'ws://localhost:12535',
7
logger: console, // for debug
8
});
9
// get balance
10
const balance = await conflux.cfx.getBalance('cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957');
11
console.log(balance.toString()); // 10098788868004995614504
12
13
// you need manual close the websocket connection
14
conflux.close();
15
}
16
17
main();
Copied!

Pub/Sub

Conflux node support pub/sub makes it possible to query certain items on an ongoing basis, without polling through the JSON-RPC HTTP interface, currently three topics are supported: newHeads, epochs, logs, for detail explain of Pub/Sub check the official doc
Use JS SDK it will be very easy to use Pub/Sub.
1
const { Conflux } = require('js-conflux-sdk');
2
3
async function main() {
4
const conflux = new Conflux({
5
url: 'ws://localhost:12535',
6
});
7
// sub
8
let newHeadEmitter = await conflux.subscribeNewHeads();
9
newHeadEmitter.on('data', console.log);
10
let logEmitter = await conflux.subscribeLogs();
11
logEmitter.on('data', console.log);
12
let epochEmitter = await conflux.subscribeEpochs();
13
epochEmitter.on('data', console.log);
14
// unsubscribe
15
conflux.unsubscribe(epochEmitter);
16
}
17
18
main();
Copied!

Interact with contract

Quick demo of interact with contract: query balance of one CRC20 token
1
async function main() {
2
const FC_ADDRESS = "cfx:achc8nxj7r451c223m18w2dwjnmhkd6rxawrvkvsy2";
3
const contract = conflux.CRC20(FC_ADDRESS);
4
const balance = await contract.balanceOf('cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957');
5
console.log(`FC balance: ${balance}`);
6
}
Copied!
You can use this SDK get and update contract state, we have a complete documentation for you.

Type conversion

If you want convert a hex to number, or uint, you can use format, for example:
1
const { format } = require('js-conflux-sdk');
2
format.uInt('0x10');
3
// 16
4
format.bigUInt('0.0')
5
// 0n
6
format.hex(1)
7
// "0x01"
Copied!

Sign

The SDK also provide most common used crypto utilities in sign
1
const { sign } = require('js-conflux-sdk');
2
// generate a random buffer
3
let buf = sign.randomBuffer(0);
4
//
5
let keccakHash = sign.keccak256(buf);
6
// random generate a private key
7
let privateKey = sign.randomPrivateKey(buf);
8
// get public key from private key
9
let pubKey = sign.privateKeyToPublicKey(privateKey);
10
// get address from public key
11
let address = sign.publicKeyToAddress(pubKey);
12
// use private key sign (ecdsa) a buffer
13
let signResult = sign.ecdsaSign(buf, privateKey);
14
// recover public key from signature and buf, then convert it to address
15
sign.publicKeyToAddress(sign.ecdsaRecover(buf, sign.ecdsaSign(signResult, privateKey)))
Copied!