Skip to content

Commit

Permalink
Add unit test for light-client-js
Browse files Browse the repository at this point in the history
  • Loading branch information
Officeyutong committed Dec 3, 2024
1 parent 2b09a41 commit 8a56c8f
Show file tree
Hide file tree
Showing 6 changed files with 270 additions and 34 deletions.
7 changes: 7 additions & 0 deletions light-client-js/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** @type {import('ts-jest').JestConfigWithTsJest} **/
module.exports = {
testEnvironment: "node",
transform: {
"^.+.tsx?$": ["ts-jest",{}],
},
};
13 changes: 9 additions & 4 deletions light-client-js/package.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
{
{
"name": "light-client-js",
"version": "1.0.0",
"main": "dist/index.js",
"license": "MIT",
"devDependencies": {
"@jest/globals": "^29.7.0",
"@types/jest": "^29.5.14",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.1",
"typescript": "^5.7.2",
"webpack": "^5.96.1",
"webpack-cli": "^5.1.4"
},
"dependencies": {
"@ckb-ccc/core": "0.1.0-alpha.6",
"light-client-db-worker": "file:../light-client-db-worker",
"light-client-wasm": "file:../light-client-wasm",
"stream-browserify": "^3.0.0",
"@ckb-ccc/core": "0.1.0-alpha.6"
"stream-browserify": "^3.0.0"
},
"scripts": {
"build-debug": "webpack --mode=development --stats-children",
"build": "webpack --mode=production",
"serve": "webpack serve"
"serve": "webpack serve",
"test": "jest"
},
"exports": {
".": "./dist/index.js"
Expand Down
10 changes: 5 additions & 5 deletions light-client-js/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ClientFindCellsResponse, ClientFindTransactionsGroupedResponse, ClientFindTransactionsResponse, ClientIndexerSearchKeyLike, ClientIndexerSearchKeyTransactionLike, ClientTransactionResponse } from "@ckb-ccc/core";
import { FetchResponse, JsonRpcLocalNode, JsonRpcRemoteNode, JsonRpcScriptStatus, LocalNode, localNodeTo, NetworkFlag, RemoteNode, remoteNodeTo, ScriptStatus, scriptStatusFrom, scriptStatusTo, LightClientWasmSetScriptsCommand, transformFetchResponse, cccOrderToLightClientWasmOrder, GetTransactionsResponse, TxWithCell, TxWithCells, lightClientGetTransactionsResultTo } from "./types";
import { FetchResponse, LocalNode, localNodeTo, NetworkFlag, RemoteNode, remoteNodeTo, ScriptStatus, scriptStatusFrom, scriptStatusTo, LightClientSetScriptsCommand, transformFetchResponse, cccOrderToLightClientWasmOrder, GetTransactionsResponse, TxWithCell, TxWithCells, lightClientGetTransactionsResultTo, LightClientLocalNode, LightClientRemoteNode, LightClientScriptStatus } from "./types";
import { ClientBlock, ClientBlockHeader, Hex, hexFrom, HexLike, Num, numFrom, NumLike, numToHex, TransactionLike } from "@ckb-ccc/core/barrel";
import { JsonRpcBlockHeader, JsonRpcTransformers } from "@ckb-ccc/core/advancedBarrel";
const DEFAULT_BUFFER_SIZE = 50 * (1 << 20);
Expand Down Expand Up @@ -111,28 +111,28 @@ class LightClient {
* @returns LocalNode
*/
async localNodeInfo(): Promise<LocalNode> {
return localNodeTo(await this.invokeLightClientCommand("local_node_info") as JsonRpcLocalNode);
return localNodeTo(await this.invokeLightClientCommand("local_node_info") as LightClientLocalNode);
}
/**
* Returns the connected peers' information.
* @returns
*/
async getPeers(): Promise<RemoteNode[]> {
return (await this.invokeLightClientCommand("get_peers") as JsonRpcRemoteNode[]).map(x => remoteNodeTo(x));
return (await this.invokeLightClientCommand("get_peers") as LightClientRemoteNode[]).map(x => remoteNodeTo(x));
}
/**
* Set some scripts to filter
* @param scripts Array of script status
* @param command An optional enum parameter to control the behavior of set_scripts
*/
async setScripts(scripts: ScriptStatus[], command?: LightClientWasmSetScriptsCommand): Promise<void> {
async setScripts(scripts: ScriptStatus[], command?: LightClientSetScriptsCommand): Promise<void> {
await this.invokeLightClientCommand("set_scripts", [scripts.map(x => scriptStatusFrom(x)), command]);
}
/**
* Get filter scripts status
*/
async getScripts(): Promise<ScriptStatus[]> {
return (await this.invokeLightClientCommand("get_scripts") as JsonRpcScriptStatus[]).map(x => scriptStatusTo(x));
return (await this.invokeLightClientCommand("get_scripts") as LightClientScriptStatus[]).map(x => scriptStatusTo(x));
}
/**
* See https://github.com/nervosnetwork/ckb-indexer#get_cells
Expand Down
205 changes: 205 additions & 0 deletions light-client-js/src/types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import { expect, test } from "@jest/globals";
import { cccOrderToLightClientWasmOrder, FetchResponse, GetTransactionsResponse, lightClientGetTransactionsResultTo, LightClientLocalNode, LightClientOrder, LightClientRemoteNode, LightClientScriptStatus, LightClientTxWithCell, LightClientTxWithCells, LocalNode, localNodeTo, RemoteNode, remoteNodeTo, scriptStatusFrom, scriptStatusTo, transformFetchResponse, TxWithCell, TxWithCells } from "./types";
import { Transaction } from "@ckb-ccc/core";
test("test transform fetch response", () => {
const a: FetchResponse<number> = { status: "fetched", data: 1 };
const b: FetchResponse<number> = { status: "added", timestamp: 0n };
const fn = (a: number) => a + 1;
expect(transformFetchResponse(a, fn)).toStrictEqual({ status: "fetched", data: 2 });
expect(transformFetchResponse(b, fn)).toStrictEqual(b);
})

test("test scriptStatusTo/From", () => {
const raw: LightClientScriptStatus = {
script: {
code_hash: "0xabcd1234",
hash_type: "data",
args: "0x0011223344"
},
script_type: "lock",
block_number: 1234n
};
const transformed = scriptStatusTo(raw);

expect(scriptStatusFrom(transformed)).toStrictEqual(raw);
});

test("test remoteNodeTo", () => {
const raw: LightClientRemoteNode = {
version: "1",
node_id: "111",
addresses: [
{ address: "test", score: 123n }
],
connected_duration: 234n,
protocols: [
{ id: 1n, version: "1" }
],
sync_state: {
proved_best_known_header: {
compact_target: "0x12",
dao: "0x04d0bc8a6028d30c0000c16ff286230066cbed490e00000000a38cdc1afbfe06",
epoch: "0x11112222333333",
extra_hash: "0x45",
hash: "0x56",
nonce: "0x67",
number: "0x78",
parent_hash: "0x89",
proposals_hash: "0x90",
timestamp: "0xab",
transactions_root: "0xbc",
version: "0xcd"
}
}
};
const newVal: RemoteNode = {
version: "1",
nodeId: "111",
addresses: [
{ address: "test", score: 123n }
],
connestedDuration: 234n,
protocols: [
{ id: 1n, version: "1" }
],
syncState: {
provedBestKnownHeader: {
compactTarget: 0x12n,
dao: {
c: 924126743650684932n,
ar: 10000000000000000n,
s: 61369863014n,
u: 504116301100000000n
},
epoch: [3355443n, 8738n, 4369n],
extraHash: "0x45",
hash: "0x56",
nonce: 0x67n,
number: 0x78n,
parentHash: "0x89",
proposalsHash: "0x90",
timestamp: 0xabn,
transactionsRoot: "0xbc",
version: 0xcdn
},
requestedBestKnownHeader: undefined
}
};
expect(remoteNodeTo(raw)).toStrictEqual(newVal);
});

test("test localNodeTo", () => {
const raw: LightClientLocalNode = {
version: "aaa",
node_id: "bbb",
active: false,
addresses: [
{ address: "111", score: 123n }
],
protocols: [
{ id: 1n, name: "test", support_version: ["a", "b", "c"] }
],
connections: 123n
}
const expectedVal: LocalNode = {
version: "aaa",
nodeId: "bbb",
active: false,
addresses: [
{ address: "111", score: 123n }
],
protocols: [
{ id: 1n, name: "test", supportVersion: ["a", "b", "c"] }
],
connections: 123n
};
expect(localNodeTo(raw)).toStrictEqual(expectedVal);
});

test("test cccOrderToLightClientWasmOrder", () => {
expect(cccOrderToLightClientWasmOrder("asc")).toBe(LightClientOrder.Asc);
expect(cccOrderToLightClientWasmOrder("desc")).toBe(LightClientOrder.Desc);
});

test("test lightClientGetTransactionsResultTo", () => {
expect(lightClientGetTransactionsResultTo({ last_cursor: "0x1234", objects: [] })).toStrictEqual({ lastCursor: "0x1234", transactions: [] });
expect(lightClientGetTransactionsResultTo({
last_cursor: "0x1234", objects: [
{
block_number: "0x1234",
io_index: 1234,
io_type: "input",
transaction: {
cell_deps: [],
header_deps: [],
inputs: [],
outputs: [],
outputs_data: [],
version: "0x123",
witnesses: ["0x"]
},
tx_index: 2222
} as LightClientTxWithCell
]
})).toStrictEqual({
lastCursor: "0x1234",
transactions: [
{
blockNumber: 0x1234n,
ioIndex: 1234n,
ioType: "input",
transaction: Transaction.from({
cellDeps: [],
headerDeps: [],
inputs: [],
outputs: [],
outputsData: [],
version: 0x123n,
witnesses: ["0x"]
}),
txIndex: 2222n
}
]
} as GetTransactionsResponse<TxWithCell>);

expect(lightClientGetTransactionsResultTo({
last_cursor: "0x1234", objects: [
{
block_number: "0x1234",
tx_index: 123,
transaction: {
cell_deps: [],
header_deps: [],
inputs: [],
outputs: [],
outputs_data: [],
version: "0x123",
witnesses: ["0x"]
},
cells: [
["input", 111]
]
} as LightClientTxWithCells
]
})).toStrictEqual({
lastCursor: "0x1234",
transactions: [
{
blockNumber: 0x1234n,
txIndex: 123n,
transaction: Transaction.from({
cellDeps: [],
headerDeps: [],
inputs: [],
outputs: [],
outputsData: [],
version: 0x123n,
witnesses: ["0x"]
}),
cells: [
["input", 111]
]
}
]
} as GetTransactionsResponse<TxWithCells>);
});
Loading

0 comments on commit 8a56c8f

Please sign in to comment.