Skip to content

Commit b2a8a82

Browse files
committed
Implementation of the RPC using JavaScript proxies
1 parent e3f892d commit b2a8a82

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { IJsonRpcTransport } from '@solana/rpc-transport';
2+
import { rpc } from '../rpc';
3+
4+
describe('rpc', () => {
5+
let transport: jest.Mocked<IJsonRpcTransport>;
6+
beforeEach(() => {
7+
transport = { send: jest.fn() };
8+
});
9+
describe('a method call without params', () => {
10+
beforeEach(async () => {
11+
await rpc.getBlockHeight(transport);
12+
});
13+
it('calls `send` on the supplied transport with the function name as the method name and `undefined` params', () => {
14+
expect(transport.send).toHaveBeenCalledWith('getBlockHeight', undefined);
15+
});
16+
});
17+
describe('a method call with params', () => {
18+
const params = [1, undefined, { commitment: 'finalized' }] as const;
19+
beforeEach(async () => {
20+
await rpc.getBlocks(transport, ...params);
21+
});
22+
it('calls `send` on the supplied transport with the function name as the method name and the supplied params', () => {
23+
expect(transport.send).toHaveBeenCalledWith('getBlocks', params);
24+
});
25+
});
26+
});

packages/rpc-core/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './rpc';

packages/rpc-core/src/rpc.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { IJsonRpcTransport } from '@solana/rpc-transport';
2+
import { JsonRpcApi } from './types/jsonRpcApi';
3+
4+
export const rpc = /* #__PURE__ */ new Proxy<JsonRpcApi>({} as JsonRpcApi, {
5+
defineProperty() {
6+
return false;
7+
},
8+
deleteProperty() {
9+
return false;
10+
},
11+
get<TMethodName extends keyof JsonRpcApi>(target: JsonRpcApi, p: TMethodName) {
12+
if (target[p] == null) {
13+
const method = p.toString();
14+
target[p] = async function (transport: IJsonRpcTransport, ...params: Parameters<JsonRpcApi[TMethodName]>) {
15+
const normalizedParams = params.length ? params : undefined;
16+
const result = await transport.send(method, normalizedParams);
17+
return result;
18+
} as unknown as JsonRpcApi[TMethodName];
19+
}
20+
return target[p];
21+
},
22+
});

0 commit comments

Comments
 (0)