Skip to content

Commit

Permalink
fix: wrong test type in cases
Browse files Browse the repository at this point in the history
Signed-off-by: homura <[email protected]>
  • Loading branch information
homura committed Mar 28, 2023
1 parent 18d1379 commit 47db3b0
Show file tree
Hide file tree
Showing 12 changed files with 124 additions and 14 deletions.
49 changes: 49 additions & 0 deletions docs/rpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,15 @@ await window.ckb.request({ method: "wallet_enable" })

- `FullOwnership`

- `CkbMethods`

**`RpcMethods`**

## Table of contents

### Methods

- [ckb\_getBlockchainInfo](#ckb_getblockchaininfo)
- [wallet\_enable](#wallet_enable)
- [wallet\_fullOwnership\_getLiveCells](#wallet_fullownership_getlivecells)
- [wallet\_fullOwnership\_getOffChainLocks](#wallet_fullownership_getoffchainlocks)
Expand All @@ -36,6 +39,52 @@ await window.ckb.request({ method: "wallet_enable" })

## Methods

### ckb\_getBlockchainInfo

**ckb_getBlockchainInfo**(): `Promise`<`ChainInfo`\>

get the current chain info, useful when the app needs to determine what network Nexus is connected to.

**`Example`**

```ts
await window.ckb.request({ method: "ckb_getBlockchainInfo" })
```

#### Returns

`Promise`<`ChainInfo`\>

[ChainInfo](https://github.com/nervosnetwork/ckb/blob/develop/rpc/README.md#method-get_blockchain_info)
<details>
<summary>show return data example</summary>

```json
{
"alerts": [
{
"id": "0x2a",
"message": "An example alert message!",
"notice_until": "0x24bcca57c00",
"priority": "0x1"
}
],
"chain": "ckb",
"difficulty": "0x1f4003",
"epoch": "0x7080018000001",
"isInitialBlockDownload": true,
"medianime": "0x5cd2b105"
}
```

</details>

#### Inherited from

CkbMethods.ckb\_getBlockchainInfo

___

### wallet\_enable

**wallet_enable**(): `Promise`<{ `nickname`: `string` }\>
Expand Down
1 change: 1 addition & 0 deletions packages/extension-chrome/__tests__/helpers/mockBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ export function createMockBackend(options?: { hasHistory(lock: Script): Promisab
hasHistories: async ({ locks }) => Promise.all(locks.map((lock) => options?.hasHistory(lock) ?? false)),
resolveTx: errors.unimplemented,
getLiveCellsByLocks: errors.unimplemented,
getBlockchainInfo: errors.unimplemented,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,36 @@ import { createBackend } from '../../../../src/services/ownership/backend';
import fetchMock from 'jest-fetch-mock';
import { ScriptConfig, predefined } from '@ckb-lumos/config-manager/lib';

// TODO: replace it with an internal server
const SNAPSHOT_CKB_RPC = 'https://testnet.ckb.dev';

describe('load secp256k1 cellDeps', () => {
beforeEach(() => {
fetchMock.disableMocks();
});
it('should backendUtils.loadSecp256k1ScriptDep return expected config', async () => {
// this test case will actually fetch on-chain data, so we increase the timeout
jest.setTimeout(10000);
// TODO: replace it with an internal server
const SNAPSHOT_CKB_RPC = 'https://testnet.ckb.dev';
const backend = createBackend({ nodeUrl: SNAPSHOT_CKB_RPC });

const res = await backend.getSecp256k1Blake160ScriptConfig({ networkId: 'someId' });

expect(res).toMatchSnapshot();
const predefinedConfig = predefined.AGGRON4.SCRIPTS.SECP256K1_BLAKE160;
expect(res).toEqual({ ...predefinedConfig, SHORT_ID: undefined } as ScriptConfig);
// this test case will actually fetch on-chain data, so we increase the timeout
}, 5000);
});

describe('getBlockchainInfo', () => {
beforeEach(() => {
fetchMock.disableMocks();
});

it('should backend fetch expected blockchain info', async () => {
const backend = createBackend({ nodeUrl: SNAPSHOT_CKB_RPC });
const res = await backend.getBlockchainInfo();

expect(res.chain).toBe('ckb_testnet');
}, 5000);
});

describe('hasHistory', () => {
Expand Down
1 change: 1 addition & 0 deletions packages/extension-chrome/src/background/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import './patch';
import '../rpc/walletImpl';
import '../rpc/debugImpl';
import '../rpc/ckbImpl';
import { createLogger, LIB_VERSION } from '@nexus-wallet/utils';
import { Endpoint, onMessage } from 'webext-bridge';
import { createServer } from '../rpc';
Expand Down
6 changes: 6 additions & 0 deletions packages/extension-chrome/src/rpc/ckbImpl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { addMethod } from './server';

addMethod('ckb_getBlockchainInfo', async (_, { resolveService }) => {
const backend = await resolveService('backendProvider').resolve();
return backend.getBlockchainInfo();
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import chunk from 'lodash/chunk';
import isEqual from 'lodash/isEqual';
import { RPC as RpcType } from '@ckb-lumos/rpc/lib/types/rpc';
import { NexusCommonErrors } from '../../../errors';
import { createRpcClient, loadSecp256k1ScriptDep, toQueryParam, toCell, toScript } from './backendUtils';
import { createRpcClient, loadSecp256k1ScriptDep, toCell, toQueryParam, toScript } from './backendUtils';
import { ChainInfo } from '@ckb-lumos/base';
import { ResultFormatter } from '@ckb-lumos/rpc';

type GetLiveCellsResult = Paginate<Cell> & { lastLock?: Script };

Expand All @@ -27,6 +29,8 @@ export interface Backend {
}): Promise<Paginate<Cell> & { lastLock?: Script }>;

resolveTx(tx: Transaction): Promise<TransactionSkeletonType>;

getBlockchainInfo(): Promise<ChainInfo>;
}

// TODO better make it persisted in localstorage/db
Expand Down Expand Up @@ -161,6 +165,11 @@ export function createBackend(_payload: { nodeUrl: string }): Backend {
};
return createTransactionSkeleton(tx, fetcher);
},

getBlockchainInfo: async () => {
const res = await client.request<RpcType.BlockchainInfo>('get_blockchain_info', null);
return ResultFormatter.toBlockchainInfo(res);
},
};
}

Expand Down
33 changes: 33 additions & 0 deletions packages/protocol/src/ckb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { ChainInfo } from '@ckb-lumos/base';

export interface CkbMethods {
/**
* get the current chain info, useful when the app needs to determine what network Nexus is connected to.
* @example
* await window.ckb.request({ method: "ckb_getBlockchainInfo" })
* @returns {@link https://github.com/nervosnetwork/ckb/blob/develop/rpc/README.md#method-get_blockchain_info ChainInfo}
* <details>
* <summary>show return data example</summary>
*
* ```json
* {
* "alerts": [
* {
* "id": "0x2a",
* "message": "An example alert message!",
* "notice_until": "0x24bcca57c00",
* "priority": "0x1"
* }
* ],
* "chain": "ckb",
* "difficulty": "0x1f4003",
* "epoch": "0x7080018000001",
* "isInitialBlockDownload": true,
* "medianime": "0x5cd2b105"
* }
* ```
*
* </details>
*/
ckb_getBlockchainInfo(): Promise<ChainInfo>;
}
3 changes: 2 additions & 1 deletion packages/protocol/src/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ export interface Events {
* Network name, similar to Ethereum's network version, "ckb" for mainnet, "ckb_testnet" for testnet
*
* @see {@link https://github.com/nervosnetwork/ckb/blob/develop/rpc/README.md#type-chaininfo CKB Chaininfo}
* @see {@link https://github.com/nervosnetwork/ckb/tree/f56e66cfb3170fb420ac6e0ddfda7232b3e410e4/resource/specs chain specs}
*/
export type NetworkName = 'ckb' | 'ckb_testnet' | string;
export type NetworkName = 'ckb' | 'ckb_testnet' | 'ckb_dev' | string;
3 changes: 2 additions & 1 deletion packages/protocol/src/rpc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { FullOwnership } from './ownership';
import { Wallet } from './wallet';
import { CkbMethods } from './ckb';

/**
* Exposed RPC methods for the wallet, the `debug_` prefix is for development purpose only,
Expand All @@ -12,4 +13,4 @@ import { Wallet } from './wallet';
* await window.ckb.request({ method: "wallet_enable" })
* ```
*/
export interface RpcMethods extends Wallet, FullOwnership {}
export interface RpcMethods extends Wallet, FullOwnership, CkbMethods {}
6 changes: 1 addition & 5 deletions packages/types/src/services/ConfigService.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { NetworkName } from '@nexus-wallet/protocol';
import { Promisable } from '../base';

export interface ConfigService {
Expand Down Expand Up @@ -98,8 +99,3 @@ export interface NetworkConfig {
networkName: NetworkName;
rpcUrl: string;
}

/**
* {@link https://github.com/nervosnetwork/ckb/blob/develop/rpc/README.md#type-chaininfo network type}
*/
export type NetworkName = 'ckb' | 'ckb_testnet' | string;
2 changes: 1 addition & 1 deletion packages/types/src/services/EventService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { NetworkName } from './ConfigService';
import { NetworkName } from '@nexus-wallet/protocol';

/**
* emit event to injected CKB provider
Expand Down
2 changes: 1 addition & 1 deletion packages/types/src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ export type { GrantService } from './GrantService';
export type { KeystoreService } from './KeystoreService';
export type { NotificationService, PlatformService } from './NotificationService';
export type { OwnershipService } from './OwnershipService';
export type { Config, ConfigService, NetworkConfig, NetworkName, TrustedHost } from './ConfigService';
export type { Config, ConfigService, NetworkConfig, TrustedHost } from './ConfigService';

0 comments on commit 47db3b0

Please sign in to comment.