@polkadot/types/interfaces#ChainProperties TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#ChainProperties. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: substrate.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
getSubstrateApi = async (nodeUrl?: string) => {
  if (api) return api

  const rpcEndpoint = nodeUrl || 'ws://127.0.0.1:9944/';
  const provider = new WsProvider(rpcEndpoint);

  logger.info(`Connecting to Substrate node at ${rpcEndpoint}...`);
  api = new ApiPromise({ provider, typesBundle })
  await api.isReady

  const properties = await api.rpc.system.properties() as ChainProperties
  const tokenSymbol = properties.tokenSymbol.unwrapOr(undefined)?.map((x: Text) => x.toString());
  const tokenDecimals = properties.tokenDecimals.unwrapOr(undefined)?.map((x: U32) => x.toNumber());

  registry.setChainProperties(properties)

  formatBalance.setDefaults({
    decimals: tokenDecimals,
    unit: tokenSymbol
  });

  return api
}
Example #2
Source File: Api.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
async function retrieve(api: ApiPromise, injectedPromise: Promise<InjectedExtension[]>): Promise<ChainData> {
  const [chainProperties, systemChain, systemChainType, systemName, systemVersion, injectedAccounts] =
    await Promise.all([
      api.rpc.system.properties(),
      api.rpc.system.chain(),
      api.rpc.system.chainType
        ? api.rpc.system.chainType()
        : Promise.resolve(registry.createType('ChainType', 'Live') as ChainType),
      api.rpc.system.name(),
      api.rpc.system.version(),
      getInjectedAccounts(injectedPromise),
    ]);

  return {
    injectedAccounts,
    properties: registry.createType('ChainProperties', {
      ss58Format: api.consts.system?.ss58Prefix || chainProperties.ss58Format,
      tokenDecimals: chainProperties.tokenDecimals,
      tokenSymbol: chainProperties.tokenSymbol,
    }) as ChainProperties,
    systemChain: (systemChain || '<unknown>').toString(),
    systemChainType,
    systemName: systemName.toString(),
    systemVersion: systemVersion.toString(),
  };
}
Example #3
Source File: Args.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
// eslint-disable-next-line complexity
function formatAddressValue(value: string | string[], chain: Chain) {
  const encodeAddr = (addr: string) => {
    try {
      // eslint-disable-next-line no-magic-numbers
      const formatVal = addr.padStart(66, '0x');

      return encodeAddress(formatVal, +chain.ss58Format);
    } catch (err) {
      console.error('? ~ file: Args.tsx ~ line 57 ~ formatAddressValue ~ err', err);

      return addr;
    }
  };

  if (isString(value)) {
    // eslint-disable-next-line no-magic-numbers
    if (value.length < 12 && /^\d+$/.test(value)) {
      const registry = new TypeRegistry();

      registry.setChainProperties(
        registry.createType('ChainProperties', { ss58Format: +chain.ss58Format }) as ChainProperties
      );

      const ss58 = registry.createType('AccountIndex', +value).toString();

      return <SubscanLink address={ss58} copyable />;
    }
    // eslint-disable-next-line no-magic-numbers
    if (value.length > 60) {
      return <SubscanLink address={encodeAddr(value)} copyable />;
    }

    return <SubscanLink address={value} copyable />;
  }

  if (isArray(value)) {
    return (
      <>
        {value.map((item: string) => (
          <SubscanLink address={encodeAddr(item)} copyable key={item} />
        ))}
      </>
    );
  }

  return null;
}
Example #4
Source File: Api.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
// eslint-disable-next-line complexity
async function loadOnReady(
  api: ApiPromise,
  injectedPromise: Promise<InjectedExtension[]>,
  store: KeyringStore | undefined,
  types: Record<string, Record<string, string>>
): Promise<ApiState> {
  registry.register(types);
  const { injectedAccounts, properties, systemChain, systemChainType, systemName, systemVersion } = await retrieve(
    api,
    injectedPromise
  );
  const ss58Format = settings.prefix === -1 ? properties.ss58Format.unwrapOr(DEFAULT_SS58).toNumber() : settings.prefix;
  const tokenSymbol = properties.tokenSymbol.unwrapOr([formatBalance.getDefaults().unit, ...DEFAULT_AUX]);
  const tokenDecimals = properties.tokenDecimals.unwrapOr([DEFAULT_DECIMALS]);
  const isEthereum = ethereumChains.includes(api.runtimeVersion.specName.toString());
  const isDevelopment = systemChainType.isDevelopment || systemChainType.isLocal || isTestChain(systemChain);

  // explicitly override the ss58Format as specified
  registry.setChainProperties(
    registry.createType('ChainProperties', { ss58Format, tokenDecimals, tokenSymbol }) as ChainProperties
  );

  // first setup the UI helpers
  formatBalance.setDefaults({
    decimals: (tokenDecimals as BN[]).map((b) => b.toNumber()),
    unit: tokenSymbol[0].toString(),
  });
  TokenUnit.setAbbr(tokenSymbol[0].toString());

  // finally load the keyring
  const isLoaded = isKeyringLoaded();

  if (!isLoaded) {
    keyring.loadAll(
      {
        isDevelopment,
        ss58Format,
        store,
        type: isEthereum ? 'ethereum' : 'ed25519',
      },
      injectedAccounts
    );
  }

  const defaultSection = Object.keys(api.tx)[0];
  const defaultMethod = Object.keys(api.tx[defaultSection])[0];
  const apiDefaultTx = api.tx[defaultSection][defaultMethod];
  const apiDefaultTxSudo = (api.tx.system && api.tx.system.setCode) || apiDefaultTx;

  setDeriveCache(api.genesisHash.toHex(), deriveMapCache);

  return {
    apiDefaultTx,
    apiDefaultTxSudo,
    hasInjectedAccounts: injectedAccounts.length !== 0,
    isApiReady: true,
    isDevelopment: isEthereum ? false : isDevelopment,
    isEthereum,
    specName: api.runtimeVersion.specName.toString(),
    specVersion: api.runtimeVersion.specVersion.toString(),
    systemChain,
    systemName,
    systemVersion,
  };
}