types#ApiPromise TypeScript Examples

The following examples show how to use types#ApiPromise. 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: chainProps.ts    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
export async function getChainProperties(api: ApiPromise): Promise<ChainProperties | null> {
  const [chainProperties, systemName, systemVersion, systemChain, systemChainType] =
    await Promise.all([
      api.rpc.system.properties(),
      api.rpc.system.name(),
      api.rpc.system.version(),
      (await api.rpc.system.chain()).toString(),
      api.rpc.system.chainType
        ? api.rpc.system.chainType()
        : Promise.resolve(registry.createType('ChainType', 'Live')),
      api.rpc.system,
    ]);

  const result = {
    systemName: systemName.toString(),
    systemVersion: systemVersion.toString(),
    systemChainType,
    systemChain,
    tokenDecimals: chainProperties.tokenDecimals.isSome
      ? chainProperties.tokenDecimals.unwrap().toArray()[0].toNumber()
      : DEFAULT_DECIMALS,
    tokenSymbol: chainProperties.tokenSymbol.isSome
      ? chainProperties.tokenSymbol
          .unwrap()
          .toArray()
          .map(s => s.toString())[0]
      : 'Unit',
  };

  return result;
}
Example #2
Source File: createInstantiateTx.ts    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
export function createInstantiateTx(
  api: ApiPromise,
  {
    argValues,
    codeHash,
    constructorIndex,
    weight: gasLimit,
    value,
    metadata,
    salt,
    storageDepositLimit,
  }: InstantiateData
): SubmittableExtrinsic<'promise'> | null {
  const wasm = metadata?.info.source.wasm;
  const isValid = codeHash || !!wasm;

  if (isValid && metadata && isNumber(constructorIndex) && metadata && argValues) {
    const constructor = metadata.findConstructor(constructorIndex);

    const options = {
      gasLimit,
      salt: salt ? encodeSalt(salt) : null,
      storageDepositLimit: storageDepositLimit || undefined,
      value: value && constructor.isPayable ? api.registry.createType('Balance', value) : undefined,
    };

    const codeOrBlueprint = codeHash
      ? new BlueprintPromise(api, metadata, codeHash)
      : new CodePromise(api, metadata, wasm && wasm.toU8a());

    const transformed = transformUserInput(api.registry, constructor.args, argValues);

    return constructor.args.length > 0
      ? codeOrBlueprint.tx[constructor.method](options, ...transformed)
      : codeOrBlueprint.tx[constructor.method](options);
  } else {
    throw new Error('Unknown error');
  }
}
Example #3
Source File: blockTime.ts    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
export function blockTimeMs(a: OrFalsy<ApiPromise>): BN {
  return (a?.consts.babe?.expectedBlockTime || // Babe
    // POW, eg. Kulupu
    a?.consts.difficulty?.targetBlockTime ||
    // Check against threshold to determine value validity
    (a?.consts.timestamp?.minimumPeriod.gte(THRESHOLD)
      ? // Default minimum period config
        a.consts.timestamp.minimumPeriod.mul(BN_TWO)
      : a?.query.parachainSystem
      ? // default guess for a parachain
        DEFAULT_TIME.mul(BN_TWO)
      : // default guess for others
        DEFAULT_TIME)) as BN;
}
Example #4
Source File: index.ts    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
export function toBalance(api: ApiPromise, value: string | number): BN {
  const asString = isNumber(value) ? value.toString() : value;
  const siPower = new BN(api.registry.chainDecimals[0]);

  const isDecimalValue = /^(\d+)\.(\d+)$/.exec(asString);

  if (isDecimalValue) {
    const div = new BN(asString.replace(/\.\d*$/, ''));
    const modString = asString.replace(/^\d+\./, '').substr(0, api.registry.chainDecimals[0]);
    const mod = new BN(modString);

    return div
      .mul(BN_TEN.pow(siPower))
      .add(mod.mul(BN_TEN.pow(new BN(siPower.subn(modString.length)))));
  } else {
    return new BN(asString.replace(/[^\d]/g, '')).mul(BN_TEN.pow(siPower));
  }
}
Example #5
Source File: index.ts    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
export function toSats(api: ApiPromise, balance: BN | number): BN {
  let bn: BN;

  if (isNumber(balance)) {
    bn = new BN(balance);
  } else {
    bn = balance;
  }

  return bn.mul(BN_TEN.pow(new BN(api.registry.chainDecimals[0])));
}
Example #6
Source File: useArgValues.ts    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
function fromArgs(api: ApiPromise, keyring: Keyring, args: AbiParam[] | null): ArgValues {
  const result: ArgValues = {};

  (args || []).forEach(({ name, type }) => {
    result[name] = getInitValue(api.registry, keyring, type);
  });

  return result;
}
Example #7
Source File: useMetadata.ts    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
function deriveFromJson(
  options: DeriveOptions,
  source?: Record<string, unknown>,
  api?: ApiPromise | null
): MetadataState {
  if (!source) {
    return EMPTY;
  }

  let value: Abi | undefined = undefined;

  try {
    value = new Abi(source, api?.registry.getChainProperties());

    const name = options.name || value.info.contract.name.toString();

    return {
      source,
      name,
      value,
      isSupplied: true,
      ...validate(value, options),
    };
  } catch (e) {
    console.error(e);

    return {
      source,
      name: '',
      value,
      isSupplied: true,
      ...validate(value, options),
    };
  }
}
Example #8
Source File: index.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
export function maximumBlockWeight(api: OrFalsy<ApiPromise>): Weight {
  return api?.consts.system.blockWeights
    ? api.consts.system.blockWeights.maxBlock
    : (api?.consts.system.maximumBlockWeight as Weight) || MAX_CALL_WEIGHT;
}
Example #9
Source File: index.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
export function fromSats(api: ApiPromise, sats: BN): string {
  const pow = BN_TEN.pow(new BN(api.registry.chainDecimals[0]));
  const [div, mod] = [sats.div(pow), sats.mod(pow)];

  return `${div.toString()}${!mod.eqn(0) ? `.${mod.toString()}` : ''}`;
}
Example #10
Source File: index.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
export async function getContractInfo(api: ApiPromise, address: string) {
  return (await api.query.contracts.contractInfoOf(address)).unwrapOr(null);
}
Example #11
Source File: index.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
export async function checkOnChainCode(api: ApiPromise, codeHash: string): Promise<boolean> {
  return isValidCodeHash(codeHash)
    ? (await api.query.contracts.codeStorage(codeHash)).isSome
    : false;
}
Example #12
Source File: index.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
export async function filterOnChainCode(api: ApiPromise, items: CodeBundleDocument[]) {
  const codes: CodeBundleDocument[] = [];
  for (const item of items) {
    const isOnChain = await checkOnChainCode(api, item.codeHash);
    isOnChain && codes.push(item);
  }
  return codes;
}
Example #13
Source File: InputBalance.tsx    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
function getStringValue(api: ApiPromise, value: OrFalsy<BN>) {
  if (!value) {
    return '';
  }

  return fromBalance(fromSats(api, value || BN_ZERO));
}
Example #14
Source File: useWeight.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
function getEstimatedMegaGas(api: ApiPromise, estimatedWeight: OrFalsy<BN>, withBuffer = true): BN {
  return (estimatedWeight || maximumBlockWeight(api)).div(BN_MILLION).addn(withBuffer ? 1 : 0);
}
Example #15
Source File: useWeight.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
function getDefaultMegaGas(api: OrFalsy<ApiPromise>, estimatedWeight?: OrFalsy<BN>): BN {
  if (api && estimatedWeight) {
    return getEstimatedMegaGas(api, estimatedWeight);
  }

  return maximumBlockWeight(api).div(BN_MILLION).div(BN_TEN);
}