Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DRAFT] chore: update sc provider #6075

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions packages/rpc-provider/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,14 @@
"tslib": "^2.8.1"
},
"devDependencies": {
"@substrate/connect": "0.8.11"
"@substrate/connect": "^2.1.2"
},
"optionalDependencies": {
"@substrate/connect": "0.8.11"
"peerDependencies": {
"@substrate/connect": "^2.1.2"
},
"peerDependenciesMeta": {
"@substrate/connect": {
"optional": true
}
}
}
80 changes: 48 additions & 32 deletions packages/rpc-provider/src/substrate-connect/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const wait = (ms: number) =>
setTimeout(resolve, ms)
);

function healthCheckerMock (): MockedHealthChecker {
function healthCheckerMock(): MockedHealthChecker {
let cb: (health: SmoldotHealth) => void = () => undefined;
let sendJsonRpc: (request: string) => void = () => undefined;
let isActive = false;
Expand All @@ -66,7 +66,7 @@ function healthCheckerMock (): MockedHealthChecker {
};
}

function healthCheckerFactory () {
function healthCheckerFactory() {
const _healthCheckers: MockedHealthChecker[] = [];

return {
Expand All @@ -82,13 +82,29 @@ function healthCheckerFactory () {
};
}

function getFakeChain (spec: string, callback: Sc.JsonRpcCallback): MockChain {
function getFakeChain(spec: string): MockChain {
const _receivedRequests: string[] = [];
let _isTerminated = false;

let terminateInterceptor = Function.prototype;
let sendJsonRpcInterceptor = Function.prototype;

const responseQueue: string[] = []

const nextJsonRpcResponse = async () => {
while (responseQueue.length === 0) {
await new Promise((resolve) => setTimeout(resolve, 0));
}
return responseQueue.shift()!;
}

async function* jsonRpcResponsesGenerator(): AsyncIterableIterator<string> {
while (true) {
const response = await nextJsonRpcResponse();
yield response;
}
}

return {
_getLatestRequest: () => _receivedRequests[_receivedRequests.length - 1],
_isTerminated: () => _isTerminated,
Expand All @@ -101,14 +117,15 @@ function getFakeChain (spec: string, callback: Sc.JsonRpcCallback): MockChain {
},
_spec: () => spec,
_triggerCallback: (response) => {
callback(
typeof response === 'string'
? response
: stringify(response)
);
const message = typeof response === 'string'
? response
: stringify(response)
responseQueue.push(message)

},
addChain: (chainSpec, jsonRpcCallback) =>
Promise.resolve(getFakeChain(chainSpec, jsonRpcCallback ?? noop)),
nextJsonRpcResponse,
jsonRpcResponses: jsonRpcResponsesGenerator(),
addChain: (chainSpec) => Promise.resolve(getFakeChain(chainSpec)),
remove: () => {
terminateInterceptor();
_isTerminated = true;
Expand All @@ -120,11 +137,27 @@ function getFakeChain (spec: string, callback: Sc.JsonRpcCallback): MockChain {
};
}

function getFakeClient () {
function getFakeClient() {
const chains: MockChain[] = [];
let addChainInterceptor: Promise<void> = Promise.resolve();
let addWellKnownChainInterceptor: Promise<void> = Promise.resolve();

const addChain: Sc.AddChain = async (chainSpec) => addChainInterceptor.then(() => {
const result = getFakeChain(chainSpec);

chains.push(result);

return result;
})

const addWellKnownChain: Sc.AddWellKnownChain = async (wellKnownChain) => addWellKnownChainInterceptor.then(() => {
const result = getFakeChain(wellKnownChain);

chains.push(result);

return result;
})

return {
_chains: () => chains,
_setAddChainInterceptor: (interceptor: Promise<void>) => {
Expand All @@ -133,29 +166,12 @@ function getFakeClient () {
_setAddWellKnownChainInterceptor: (interceptor: Promise<void>) => {
addWellKnownChainInterceptor = interceptor;
},
addChain: (chainSpec: string, cb: Sc.JsonRpcCallback): Promise<MockChain> =>
addChainInterceptor.then(() => {
const result = getFakeChain(chainSpec, cb);

chains.push(result);

return result;
}),
addWellKnownChain: (
wellKnownChain: string,
cb: Sc.JsonRpcCallback
): Promise<MockChain> =>
addWellKnownChainInterceptor.then(() => {
const result = getFakeChain(wellKnownChain, cb);

chains.push(result);

return result;
})
addChain,
addWellKnownChain
};
}

function connectorFactory (): MockSc {
function connectorFactory(): MockSc {
const clients: ReturnType<typeof getFakeClient>[] = [];
const latestClient = () => clients[clients.length - 1];

Expand All @@ -175,7 +191,7 @@ function connectorFactory (): MockSc {
} as unknown as MockSc;
}

function setChainSyncyingStatus (isSyncing: boolean): void {
function setChainSyncyingStatus(isSyncing: boolean): void {
getCurrentHealthChecker()._triggerHealthUpdate({
isSyncing,
peers: 1,
Expand Down
28 changes: 20 additions & 8 deletions packages/rpc-provider/src/substrate-connect/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export class ScProvider implements ProviderInterface {
#chain: Promise<ScType.Chain> | null = null;
#isChainReady = false;

public constructor (Sc: SubstrateConnect, spec: string | ScType.WellKnownChain, sharedSandbox?: ScProvider) {
public constructor (Sc: SubstrateConnect, spec: ScType.WellKnownChain | (string & {}), sharedSandbox?: ScProvider) {
if (!isObject(Sc) || !isObject(Sc.WellKnownChain) || !isFunction(Sc.createScClient)) {
throw new Error('Expected an @substrate/connect interface as first parameter to ScProvider');
}
Expand Down Expand Up @@ -133,13 +133,13 @@ export class ScProvider implements ProviderInterface {
}

const response = JSON.parse(hcRes) as JsonRpcResponse<string>;
let decodedResponse: string | Error;
let decodedResponse: string | Error;

try {
decodedResponse = this.#coder.decodeResponse(response);
} catch (e) {
decodedResponse = e as Error;
}
try {
decodedResponse = this.#coder.decodeResponse(response);
} catch (e) {
decodedResponse = e as Error;
}

// It's not a subscription message, but rather a standar RPC response
if (response.params?.subscription === undefined || !response.method) {
Expand All @@ -166,7 +166,19 @@ export class ScProvider implements ProviderInterface {
? client.addWellKnownChain
: client.addChain;

this.#chain = addChain(this.#spec as ScType.WellKnownChain, onResponse).then((chain) => {
this.#chain = addChain(this.#spec as ScType.WellKnownChain).then((chain) => {
// Process JSON-RPC responses
void (async () => {
try {
for await (const response of chain.jsonRpcResponses) {
onResponse(response);
}
} catch (error) {
l.error('Error processing JSON-RPC responses:', error);
this.#eventemitter.emit('error', error);
}
})();

hc.setSendJsonRpc(chain.sendJsonRpc);

this.#isChainReady = false;
Expand Down
Loading