@polkadot/types#Text TypeScript Examples

The following examples show how to use @polkadot/types#Text. 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: rpcs.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export function getAllRpc (registry: Registry, chain: Text, { specName }: RuntimeVersion): Record<string, Record<string, DefinitionRpcExt>> {
  return Object
    .entries(getSpecRpc(registry, chain, specName))
    .reduce((all: Record<string, Record<string, DefinitionRpcExt>>, [section, contents]): Record<string, Record<string, DefinitionRpcExt>> => {
      all[section] ??= toExt(section, contents);

      return all;
    }, { ...jsonrpc });
}
Example #2
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 #3
Source File: utils.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
export class OptionText extends Option<Text> {
  constructor (value?: OptionTextType) {
    const textOrNull = nonEmptyStr(value) ? value : new Null(registry)
    super(registry, 'Text', textOrNull)
  }
}
Example #4
Source File: utils.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
export class OptionOptionText extends Option<Option<Text>> {
  constructor (value?: OptionTextType) {
    super(registry, 'Option<Text>', new OptionText(value))
  }
}
Example #5
Source File: getConfigs.ts    From parity-bridges-ui with GNU General Public License v3.0 6 votes vote down vote up
getConfigs = async (apiPromise: ApiPromise): Promise<Configs> => {
  const properties = apiPromise.registry.getChainProperties();
  const { ss58Format } = properties!;
  const systemChain = await apiPromise.rpc.system.chain();
  const chainName = (systemChain as Text).split(' ')[0];

  let logoUrl;
  try {
    logoUrl = require(`../assets/chainsLogos/${chainName.toLowerCase()}.png`).default;
  } catch (e) {
    logoUrl = require('../assets/chainsLogos/local.png').default;
  }

  return { chainName, ss58Format: parseInt(ss58Format.toString()), logoUrl };
}
Example #6
Source File: rpcs.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export function getAllRpc(
  registry: Registry,
  chain: Text,
  { specName }: RuntimeVersion
): Record<string, Record<string, DefinitionRpcExt>> {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  return Object.entries(getSpecRpc(registry, chain, specName)).reduce(
    (
      all: Record<string, Record<string, DefinitionRpcExt>>,
      [section, contents]
    ): Record<string, Record<string, DefinitionRpcExt>> => {
      all[section] = all[section] ?? toExt(section, contents);

      return all;
    },
    { ...jsonrpc }
  );
}
Example #7
Source File: index.ts    From substrate-api-explorer with Apache License 2.0 5 votes vote down vote up
function formatDocs(docs: Vec<Text>) {
  return docs.map((text) => text.toString()).join()
}
Example #8
Source File: string.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
export function toCamelCase(array: string[] | Text[]): string {
  let result = stringCamelCase(array.join('_'));
  result = result.slice(0, 1).toUpperCase() + result.slice(1, result.length);
  return result;
}
Example #9
Source File: useApiCalls.ts    From parity-bridges-ui with GNU General Public License v3.0 4 votes vote down vote up
useApiCalls = (): ApiCallsContextType => {
  const { sourceChainDetails, targetChainDetails } = useSourceTarget();
  const {
    apiConnection: { api: sourceApi },
    chain: sourceChain
  } = sourceChainDetails;
  const { keyringPairs, keyringPairsReady } = useKeyringContext();
  const { getValuesByChain } = useChainGetters();

  const createType = useCallback(
    (chain, type, data) => {
      const { api } = getValuesByChain(chain);
      return api.registry.createType(type, data);
    },
    [getValuesByChain]
  );

  const stateCall = useCallback(
    (chain: string, methodName: string | Text, data: string | Uint8Array | Bytes, at) => {
      const { api } = getValuesByChain(chain);

      const params: [string | Text, string | Uint8Array | Bytes] = [methodName, data];
      if (at) {
        params.push(at);
      }

      return api.rpc.state.call<Codec>(...params);
    },
    [getValuesByChain]
  );

  const internalTransfer = useCallback(
    async (dispatchers, transfersData) => {
      const { dispatchTransaction, dispatchMessage } = dispatchers;
      const { receiverAddress, transferAmount, account } = transfersData;
      const type = TransactionTypes.INTERNAL_TRANSFER;

      const id = Date.now().toString();
      dispatchTransaction(TransactionActionCreators.setTransactionRunning(true));

      try {
        const transfer = sourceApi.tx.balances.transfer(receiverAddress, transferAmount);
        const options: Partial<SignerOptions> = {
          nonce: -1
        };
        let sourceAccount: string | KeyringPair = account;
        if (account.meta.isInjected) {
          const injector = await web3FromSource(account.meta.source as string);
          options.signer = injector.signer;
          sourceAccount = account.address;
        }

        const transactionDisplayPayload = {
          sourceAccount: account?.address || sourceAccount,
          transferAmount: transferAmount.toNumber(),
          receiverAddress
        };

        const unsub = await transfer.signAndSend(sourceAccount, { ...options }, async ({ status }) => {
          const steps = createEmptyInternalSteps(sourceChain);
          if (status.isReady) {
            dispatchTransaction(
              TransactionActionCreators.createTransactionStatus({
                block: null,
                blockHash: null,
                deliveryBlock: null,
                id,
                input: transferAmount,
                messageNonce: null,
                receiverAddress,
                sourceAccount: account.address,
                senderName: getName(account),
                sourceChain,
                status: TransactionStatusEnum.IN_PROGRESS,
                targetChain: '',
                type,
                transactionDisplayPayload,
                payloadHex: transfer.toHex(),
                steps
              })
            );
          }

          if (status.isBroadcast) {
            dispatchMessage(MessageActionsCreators.triggerInfoMessage({ message: 'Transaction was broadcasted' }));
            dispatchTransaction(TransactionActionCreators.reset());
          }

          if (status.isInBlock) {
            try {
              const res = (await sourceApi.rpc.chain.getBlock(status.asInBlock)) as SignedBlock;
              const block = res.block.header.number.toString();
              dispatchTransaction(
                TransactionActionCreators.updateTransactionStatus(
                  {
                    block,
                    blockHash: status.asInBlock.toString()
                  },
                  id
                )
              );
            } catch (e) {
              if (e instanceof Error) {
                logger.error(e.message);
                throw new Error('Issue reading block information.');
              }
            }
          }

          if (status.isFinalized) {
            dispatchTransaction(
              TransactionActionCreators.updateTransactionStatus(
                {
                  status: TransactionStatusEnum.FINALIZED
                },
                id
              )
            );
            logger.info(`Transaction finalized at blockHash ${status.asFinalized}`);
            unsub();
          }
        });
      } catch (e) {
        if (e instanceof Error) {
          dispatchMessage(MessageActionsCreators.triggerErrorMessage({ message: e.message }));
          logger.error(e.message);
        }
      } finally {
        dispatchTransaction(TransactionActionCreators.setTransactionRunning(false));
      }
    },
    [sourceApi.rpc.chain, sourceApi.tx.balances, sourceChain]
  );

  const updateSenderAccountsInformation = useCallback(
    async (dispatchAccount) => {
      const formatBalanceAddress = (data: any, api: ApiPromise): BalanceState => {
        return {
          chainTokens: data.registry.chainTokens[0],
          formattedBalance: formatBalance(data.free, {
            decimals: api.registry.chainDecimals[0],
            withUnit: api.registry.chainTokens[0],
            withSi: true
          }),
          free: data.free
        };
      };

      if (!keyringPairsReady || !keyringPairs.length) {
        return {};
      }

      const getAccountInformation = async (sourceRole: any, targetRole: any) => {
        const {
          apiConnection: { api: sourceApi },
          chain: sourceChain,
          configs: sourceConfigs
        } = sourceRole;
        const {
          apiConnection: { api: targetApi },
          configs: targetConfigs
        } = targetRole;

        const accounts = await Promise.all(
          keyringPairs.map(async ({ address, meta }) => {
            const sourceAddress = encodeAddress(address, sourceConfigs.ss58Format);
            const toDerive = {
              ss58Format: targetConfigs.ss58Format,
              address: sourceAddress || '',
              bridgeId: getBridgeId(targetApi, sourceChain)
            };
            const { data } = await sourceApi.query.system.account(sourceAddress);
            const sourceBalance = formatBalanceAddress(data, sourceApi);

            const companionAddress = getDeriveAccount(toDerive);
            const { data: dataCompanion } = await targetApi.query.system.account(companionAddress);
            const targetBalance = formatBalanceAddress(dataCompanion, targetApi);

            const name = (meta.name as string).toLocaleUpperCase();

            return {
              account: { address: sourceAddress, balance: sourceBalance, name },
              companionAccount: { address: companionAddress, balance: targetBalance, name }
            };
          })
        );

        return accounts;
      };

      const sourceAddresses = await getAccountInformation(sourceChainDetails, targetChainDetails);
      const targetAddresses = await getAccountInformation(targetChainDetails, sourceChainDetails);

      dispatchAccount(
        AccountActionCreators.setDisplaySenderAccounts({
          [sourceChainDetails.chain]: sourceAddresses,
          [targetChainDetails.chain]: targetAddresses
        })
      );
    },
    [keyringPairs, keyringPairsReady, sourceChainDetails, targetChainDetails]
  );

  return { createType, stateCall, internalTransfer, updateSenderAccountsInformation };
}