Skip to content

Commit

Permalink
Adjust light relay/para mappings (polkadot-js#8059)
Browse files Browse the repository at this point in the history
* Adjust light relay/para mappings

* Adjust resolveJsonModule
  • Loading branch information
jacogr authored Aug 27, 2022
1 parent 596ee25 commit 81d5fbf
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 42 deletions.
59 changes: 26 additions & 33 deletions packages/react-api/src/Api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,29 @@

import type { LinkOption } from '@polkadot/apps-config/endpoints/types';
import type { InjectedExtension } from '@polkadot/extension-inject/types';
import type { ProviderInterface, ProviderStats } from '@polkadot/rpc-provider/types';
import type { ProviderStats } from '@polkadot/rpc-provider/types';
import type { ChainProperties, ChainType } from '@polkadot/types/interfaces';
import type { KeyringStore } from '@polkadot/ui-keyring/types';
import type { ApiProps, ApiState } from './types';

import React, { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import store from 'store';

import { ApiPromise, WsProvider } from '@polkadot/api';
import { ApiPromise, ScProvider, WsProvider } from '@polkadot/api';
import { deriveMapCache, setDeriveCache } from '@polkadot/api-derive/util';
import { ethereumChains, typesBundle } from '@polkadot/apps-config';
import { web3Accounts, web3Enable } from '@polkadot/extension-dapp';
import { TokenUnit } from '@polkadot/react-components/InputNumber';
import { StatusContext } from '@polkadot/react-components/Status';
import { useApiUrl, useEndpoint } from '@polkadot/react-hooks';
import ApiSigner from '@polkadot/react-signer/signers/ApiSigner';
import { ScProvider, WellKnownChain } from '@polkadot/rpc-provider/substrate-connect';
import { keyring } from '@polkadot/ui-keyring';
import { settings } from '@polkadot/ui-settings';
import { formatBalance, isNumber, isTestChain, objectSpread, stringify } from '@polkadot/util';
import { defaults as addressDefaults } from '@polkadot/util-crypto/address/defaults';

import ApiContext from './ApiContext';
import { lightSpecs } from './light-client-specs';
import { lightSpecs, relaySpecs } from './lightClient';
import registry from './typeRegistry';
import { decodeUrlTypes } from './urlTypes';

Expand Down Expand Up @@ -235,44 +234,40 @@ async function loadOnReady (api: ApiPromise, endpoint: LinkOption | null, inject
};
}

function getLightProvider (chain = 'polkadot') {
const [relayArg, paraArg] = chain.split('/');

const wellKnown = () => {
switch (relayArg) {
case 'kusama':
return WellKnownChain.ksmcc3;
case 'polkadot':
return WellKnownChain.polkadot;
case 'rococo':
return WellKnownChain.rococo_v2_2;
case 'westend':
return WellKnownChain.westend2;
default:
throw new Error(`Unable to construct light chain ${chain}`);
}
};
/**
* @internal
* Creates a ScProvider from a <relay>[/parachain] string
*/
function getLightProvider (chain: string): ScProvider {
const [sc, relayName, paraName] = chain.split('/');

if (sc !== 'substrate-connect') {
throw new Error(`Cannot connect to non substrate-connect protocol ${chain}`);
} else if (!relaySpecs[relayName] || (paraName && (!lightSpecs[relayName] || !lightSpecs[relayName][paraName]))) {
throw new Error(`Unable to construct light chain ${chain}`);
}

const relay = new ScProvider(wellKnown());
const relay = new ScProvider(relaySpecs[relayName]);

return paraArg && lightSpecs[paraArg]
? new ScProvider(JSON.stringify(lightSpecs[paraArg]), relay)
return paraName
? new ScProvider(lightSpecs[relayName][paraName], relay)
: relay;
}

/**
* @internal
*/
async function createApi (apiUrl: string, signer: ApiSigner, onError: (error: unknown) => void): Promise<Record<string, Record<string, string>>> {
const types = getDevTypes();
const isLight = apiUrl.startsWith('light://');

try {
const providers = [0].map((): ProviderInterface =>
isLight
? getLightProvider(apiUrl.replace('light://substrate-connect/', ''))
: new WsProvider(apiUrl)
);
const provider = isLight
? getLightProvider(apiUrl.replace('light://', ''))
: new WsProvider(apiUrl);

api = new ApiPromise({
provider: providers[0],
provider,
registry,
signer,
types,
Expand All @@ -281,9 +276,7 @@ async function createApi (apiUrl: string, signer: ApiSigner, onError: (error: un

// See https://github.com/polkadot-js/api/pull/4672#issuecomment-1078843960
if (isLight) {
for (let i = 0; i < providers.length; i++) {
await providers[i].connect();
}
await provider.connect();
}
} catch (error) {
onError(error);
Expand Down
28 changes: 28 additions & 0 deletions packages/react-api/src/lightClient/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2017-2022 @polkadot/react-api authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { ScProvider } from '@polkadot/api';

import { specs as kusama } from './kusama';

export const lightSpecs: Record<string, Record<string, string>> =
Object
.entries<Record<string, unknown>>({ kusama })
.reduce((relays: Record<string, Record<string, string>>, [k, s]) => {
relays[k] = Object
.entries<unknown>(s)
.reduce((paras: Record<string, string>, [k, v]) => {
paras[k] = JSON.stringify(v);

return paras;
}, {});

return relays;
}, {});

export const relaySpecs: Record<string, string> = {
kusama: ScProvider.WellKnownChain.ksmcc3,
polkadot: ScProvider.WellKnownChain.polkadot,
rococo: ScProvider.WellKnownChain.rococo_v2_2,
westend: ScProvider.WellKnownChain.westend2
};
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
// Copyright 2017-2022 @polkadot/react-api authors & contributors
// SPDX-License-Identifier: Apache-2.0

/* eslint sort-keys: ["error", "asc", { caseSensitive: false }] */

import gmSpec from './gm.json';
import tinkernetSpec from './tinkernet.json';
import gm from './gm.json' assert { type: 'json' };
import tinkernet from './tinkernet.json' assert { type: 'json' };

// Add your imported spec here in alphabetical order.
// The key here reflects the URL of the light client endpoint.
// e.g. light://substrate-connect/kusama/gm
export const lightSpecs: Record<string, unknown> = {
gm: gmSpec,
tinkernet: tinkernetSpec
export const specs: Record<string, unknown> = {
gm,
tinkernet
};
1 change: 1 addition & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"compilerOptions": {
"composite": false,
"jsx": "react",
"resolveJsonModule": true,
"paths": {
"@polkadot/apps/*": ["apps/src/*"],
"@polkadot/apps": ["apps/src"],
Expand Down
3 changes: 1 addition & 2 deletions tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
"extends": "./tsconfig.base.json",
"compilerOptions": {
"baseUrl": "./packages",
"outDir": "./build",
"resolveJsonModule": true,
"outDir": "./build"
},
"exclude": [
"build/**/*",
Expand Down

0 comments on commit 81d5fbf

Please sign in to comment.