@polkadot/api#ApiPromise TypeScript Examples

The following examples show how to use @polkadot/api#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: util.tsx    From crust-apps with Apache License 2.0 7 votes vote down vote up
export function getContractForAddress (api: ApiPromise, address: string | null): Contract | null {
  if (!address) {
    return null;
  } else {
    const abi = getContractAbi(address);

    return abi
      ? new Contract(api, abi, address)
      : null;
  }
}
Example #2
Source File: chain-api.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
createApi = (endpoints: string | string[], apiOptions?: ApiOptions): ApiPromise => {
  const wsProvider = new WsProvider(endpoints);

  return new ApiPromise(
    createApiOptions({
      types: {
        ...TYPES,
        ...apiOptions?.types
      },
      provider: wsProvider,
      ...apiOptions
    })
  );
}
Example #3
Source File: InputCandyNumber.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function getValuesFromString (api: ApiPromise, value: string, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [string, BN, boolean] {
  const [valueBn, isValid] = inputToBn(api, value, si, bitLength, isZeroable, maxValue);

  return [
    value,
    valueBn,
    isValid
  ];
}
Example #4
Source File: sendTx.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
sendTx = (api: ApiPromise, extrinsic: SubmittableExtrinsic<'promise'>): Promise<SubmittableResult> => {
  return new Promise((resolve, reject) => {
    extrinsic
      .send((result) => {
        handleTxResponse(result, api)
          .then(({ result }) => {
            resolve(result);
          })
          .catch((err) => {
            reject(err);
          });
      })
      .catch((error) => {
        reject(error);
      });
  });
}
Example #5
Source File: ConvictionDropdown.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function createOptions (api: ApiPromise, t: TFunction, blockTime: number): { text: string; value: number }[] {
  return [
    { text: t<string>('0.1x voting balance, no lockup period'), value: 0 },
    ...CONVICTIONS.map(([value, lock, bnLock]): { text: string; value: number } => ({
      text: t<string>('{{value}}x voting balance, locked for {{lock}}x enactment ({{period}} days)', {
        replace: {
          lock,
          period: (bnLock.mul(api.consts.democracy.enactmentPeriod.muln(blockTime).div(BN_THOUSAND)).toNumber() / SEC_DAY).toFixed(2),
          value
        }
      }),
      value
    }))
  ];
}
Example #6
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
setBond = async (
  account: DotAccount,
  stashKey: KeyringPair,
  bond: string,
) => {
  console.log("Setting bond for account and stashKey:");
  console.log(account);
  console.log(stashKey);

  const { controllerKey } = account;
  const WS_PROVIDER_URL: string = "wss://kusama-rpc.polkadot.io/";
  const wsProvider = new WsProvider(WS_PROVIDER_URL);
  const api: ApiPromise = await ApiPromise.create({ provider: wsProvider });
  const result = await api.tx.staking
    .bond(controllerKey, bond, "Stash")
    .signAndSend(stashKey);

  console.log("Set Bond Result:");
  console.log(result);
  return result;
}
Example #7
Source File: lib.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
// if needed these could become some kind of event emitter

  /* Lifecycle */
  constructor(endpoint: string, onNodeConnectionUpdate?: (connected: boolean) => unknown) {
    const provider = new WsProvider(endpoint)
    provider.on('connected', () => {
      this.logConnectionData(endpoint)
      onNodeConnectionUpdate?.(true)
    })
    provider.on('disconnected', () => {
      onNodeConnectionUpdate?.(false)
    })
    provider.on('error', () => {
      onNodeConnectionUpdate?.(false)
    })

    this.api = new ApiPromise({ provider, types })
    const extrinsics = new JoystreamLibExtrinsics(this.api, () => this.selectedAccountId, endpoint)
    this.extrinsics = proxy(extrinsics)
  }
Example #8
Source File: functions.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
export async function getChangeAction(api: ApiPromise, method: string, blockHeight:number, blockHash:Hash, eventIndex: number, event: EventRecord): Promise<ActionData|null> {
  const getBlock = await api.rpc.chain.getBlock(blockHash) as SignedBlock
  const extrinsics = getBlock.block.extrinsics as Vec<Extrinsic>
  for (let n=0; n<extrinsics.length; n++) {
    const extSection = extrinsics[n].method.section
    const extMethod = extrinsics[n].method.method
    let extrinscIndex = 0
    console.log(`Extrinsics section=${extSection}, Event method=${extMethod}`)
    if (extSection == "content" && extMethod == method) {
      extrinscIndex +=1
      if (eventIndex == extrinscIndex) {
        const extrinsic = extrinsics[n]
        const actor = extrinsic.args[0] as Actor
        const ent = event.event.data[1]
        let entityId:number = +(ent.toString())
        const video:ActionData = {
          blockHeight,
          action: method,
          entityId,
          signer: extrinsic.signer.toString(),
          actor: actor.toHuman()
        }
        return video
      }
    }
  }
  return null
}
Example #9
Source File: Nominate.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function createExtrinsic (api: ApiPromise, targets: string[], amount: Map<string, BN>) {
  const tmp = [];

  for (const entry of amount.entries()) {
    tmp.push([entry[0], entry[1]]);
  }

  return api.tx.utility.batch(tmp.map((e) => api.tx.staking.guarantee(e)));
}
Example #10
Source File: tokenomics.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
async getMintInfo(
    api: ApiPromise,
    mintId: MintId,
    startHash: Hash,
    endHash: Hash
  ): Promise<MintStatistics> {
    const startMint: Mint = await getMint(api, startHash, mintId);
    const endMint: Mint = await getMint(api, endHash, mintId);
    let stats = new MintStatistics();
    stats.startMinted = getTotalMinted(startMint);
    stats.endMinted = getTotalMinted(endMint);
    stats.diffMinted = stats.endMinted - stats.startMinted;
    stats.percMinted = getPercent(stats.startMinted, stats.endMinted);
    return stats;
  }
Example #11
Source File: PayButton.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function createExtrinsics (api: ApiPromise, payout: PayoutValidator | PayoutValidator[]): SubmittableExtrinsic<'promise'>[] | null {
  if (Array.isArray(payout)) {
    if (payout.length === 1) {
      return createExtrinsics(api, payout[0]);
    }

    return createBatches(api, payout.reduce((payouts: SinglePayout[], { eras, validatorId }): SinglePayout[] => {
      eras.forEach(({ era }): void => {
        payouts.push({ era, validatorId });
      });

      return payouts;
    }, []));
  }

  const { eras, validatorId } = payout;

  return eras.length === 1
    ? [api.tx.staking.rewardStakers(validatorId, eras[0].era)]
    : createBatches(api, eras.map((era): SinglePayout => ({ era: era.era, validatorId })));
}
Example #12
Source File: get-code.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
async function main () {
  const provider = new WsProvider('ws://127.0.0.1:9944');

  const api = await ApiPromise.create({ provider, types })

  let current_block_hash = await api.rpc.chain.getBlockHash();

  console.log('getting code as of block hash', current_block_hash.toString())

  const substrateWasm = await api.query.substrate.code.at(current_block_hash.toString());
  // const substrateWasm = await api.rpc.state.getStorage('0x'+Buffer.from(':code').toString('hex'), current_block_hash);

  console.log(substrateWasm.toHex());

  api.disconnect();
}
Example #13
Source File: BondExtra.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function calcBalance (api: ApiPromise, stakingInfo?: DeriveStakingAccount, stashBalance?: DeriveBalancesAll): BN | null {
  if (stakingInfo && stakingInfo.stakingLedger && stashBalance) {
    const sumUnlocking = (stakingInfo.unlocking || []).reduce((acc, { value }) => acc.iadd(value), new BN(0));
    const redeemable = stakingInfo.redeemable || BN_ZERO;
    const available = stashBalance.freeBalance.sub(stakingInfo.stakingLedger.active.unwrap()).sub(sumUnlocking).sub(redeemable);

    return available.gt(api.consts.balances.existentialDeposit)
      ? available.sub(api.consts.balances.existentialDeposit)
      : BN_ZERO;
  }

  return null;
}
Example #14
Source File: council.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
async function getProposals(api: ApiPromise, range: BlockRange) {
  let startProposalCount = Number(
    (
      (await api.query.proposalsEngine.proposalCount.at(
        range.startBlockHash
      )) as U32
    ).toBigInt()
  );
  let endProposalCount = Number(
    (
      (await api.query.proposalsEngine.proposalCount.at(
        range.endBlockHash
      )) as U32
    ).toBigInt()
  );

  let proposals = new Array<ProposalInfo>();
  for (let i = startProposalCount - 1; i <= endProposalCount; i++) {
    try {
      const proposal = await getProposal(api, range, i);
      if (proposal) proposals.push(proposal);
    } catch (e) {
      console.error(`Failed to fetch proposal ${i}: ${e.message}`);
    }
  }

  return proposals;
}
Example #15
Source File: useExtensions.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
async function getExtensionInfo (api: ApiPromise, extension: InjectedExtension): Promise<ExtensionKnown | null> {
  if (!extension.metadata) {
    return null;
  }

  try {
    const metadata = extension.metadata;
    const known = await metadata.get();

    return {
      extension,
      known,
      update: async (def: MetadataDef): Promise<boolean> => {
        let isOk = false;

        try {
          isOk = await metadata.provide(def);

          if (isOk) {
            saveProperties(api, extension);
            triggerAll();
          }
        } catch (error) {
          // ignore
        }

        return isOk;
      }
    };
  } catch (error) {
    return null;
  }
}
Example #16
Source File: api.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getBlockHash = (
  api: ApiPromise,
  block: BlockNumber | number
): Promise<Hash> => {
  try {
    return api.rpc.chain.getBlockHash(block);
  } catch (e) {
    return api.rpc.chain.getFinalizedHead();
  }
}
Example #17
Source File: useExtensions.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
// determines if the extension has current properties
function hasCurrentProperties (api: ApiPromise, { extension }: ExtensionKnown): boolean {
  const allProperties = store.get(`properties:${api.genesisHash.toHex()}`, {}) as SavedProperties;

  // when we don't have properties yet, assume nothing has changed and store
  if (!allProperties[extension.name]) {
    saveProperties(api, extension);

    return true;
  }

  const { ss58Format, tokenDecimals, tokenSymbol } = allProperties[extension.name];

  return ss58Format === api.registry.chainSS58 &&
    tokenDecimals === api.registry.chainDecimals[0] &&
    tokenSymbol === api.registry.chainTokens[0];
}
Example #18
Source File: index.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
addBlock = async (
  api: ApiPromise,
  header: { number: number; author: string }
) => {
  const id = +header.number
  const exists = await Block.findByPk(id) 
  if (exists) {
    console.error(`TODO handle fork`, String(header.author))
  }

  await processBlock(api, id)
  
  // logging
  //const handle = await getHandleOrKey(api, key)
  const q = queue.length ? chalk.green(` [${queue.length}:${processing}]`) : ''
  console.log(`[Joystream] block ${id} ${q}`)
}
Example #19
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
async function retrieveInfo (api: ApiPromise): Promise<Partial<Info>> {
  try {
    const [blockNumber, health, peers, extrinsics] = await Promise.all([
      api.derive.chain.bestNumber(),
      api.rpc.system.health().catch(() => null),
      api.rpc.system.peers().catch(() => null),
      api.rpc.author.pendingExtrinsics().catch(() => null)
    ]);

    return { blockNumber, extrinsics, health, peers };
  } catch (error) {
    return {};
  }
}
Example #20
Source File: index.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
addBlockRange = async (
  api: ApiPromise,
  startBlock: number,
  endBlock: number
) => {
  for (let block = startBlock; block <= endBlock; block++) {
    queue.push(() => processBlock(api, block))
  }
}
Example #21
Source File: Claim.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
// Depending on isOldClaimProcess, construct the correct tx.
// FIXME We actually want to return the constructed extrinsic here (probably in useMemo)
function constructTx (api: ApiPromise, systemChain: string, accountId: string, ethereumSignature: string | null, kind: StatementKind | undefined, isOldClaimProcess: boolean, ethereumTxHash: string): ConstructTx {
  if (!ethereumSignature) {
    return {};
  }

  return isOldClaimProcess || !kind
    ? { params: [accountId, ethereumTxHash, ethereumSignature], tx: api.tx.claims.claimCsm }
    : { params: [accountId, ethereumSignature, getStatement(systemChain, kind)?.sentence], tx: api.tx.claims.claimAttest };
}
Example #22
Source File: api.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getCouncilElectionStatus = async (
  api: ApiPromise,
  hash: Hash
): Promise<ElectionInfo> => {
  const durations = await getCouncilElectionDurations(api, hash);
  const round = await getCouncilRound(api, hash);
  const stage: ElectionStage = await getCouncilElectionStage(api, hash);
  const stageEndsAt: number = Number(stage.value as BlockNumber);
  const termEndsAt: number = await getCouncilTermEnd(api, hash);
  return { round, stageEndsAt, termEndsAt, stage, durations };
}
Example #23
Source File: PreClaim.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
// Depending on isOldClaimProcess, construct the correct tx.
// FIXME We actually want to return the constructed extrinsic here (probably in useMemo)
function constructTx (api: ApiPromise, accountId: string, ethereumSignature: string | null, kind: StatementKind | undefined, isOldClaimProcess: boolean, ethereumTxHash: string): ConstructTx {
  if (!ethereumSignature) {
    return {};
  }

  return isOldClaimProcess || !kind
    ? { params: [accountId, ethereumSignature], tx: api.tx.claims.claimCru18 }
    : { params: [accountId, ethereumSignature], tx: api.tx.claims.claimCru18 };
}
Example #24
Source File: index.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
processEvents = async (api: ApiPromise, blockId: number, eraId: number, hash: string) => {
  processing = `events block ${blockId}`
  try {
    const blockEvents = await api.query.system.events.at(hash)
    blockEvents.forEach(async ({ event }: EventRecord) => {
      let { section, method, data } = event
      if(section == 'staking' && method == 'Reward') {
        const addressCredited = data[0].toString()
        await Event.create({ blockId, section, method, data: JSON.stringify(data) })
        Account.findOne(
          {
            where: {
              key: addressCredited
            }
          }
        ).then(async (beneficiaryAccount: Account) => {
          let address = ''
          if (beneficiaryAccount == null) {
            address = (await Account.create({key: addressCredited}, {returning: true})).get({plain: true}).id
          } else {
            address = beneficiaryAccount.get({plain: true}).id
          }
          await ValidatorStats.upsert(
            {
              accountId: address, 
              eraId: eraId,
              rewards: Number(data[1])
            }
          )  
        })
      }
    })
  } catch (e) {
    console.log(`failed to fetch events for block  ${blockId} ${hash}`)
  }
}
Example #25
Source File: ProxyOverview.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function createExtrinsic (api: ApiPromise, batchPrevious: SubmittableExtrinsic<'promise'>[], batchAdded: SubmittableExtrinsic<'promise'>[]): SubmittableExtrinsic<'promise'> | null {
  if (batchPrevious.length + batchAdded.length === 1) {
    return batchPrevious.length
      ? batchPrevious[0]
      : batchAdded[0];
  }

  return isFunction(api.tx.utility.batchAll)
    ? api.tx.utility.batchAll([...batchPrevious, ...batchAdded])
    : api.tx.utility.batch([...batchPrevious, ...batchAdded]);
}
Example #26
Source File: joyApi.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
constructor(endpoint?: string) {
    const wsEndpoint = endpoint || process.env.REACT_APP_WS_PROVIDER || "ws://127.0.0.1:9944";
    this.endpoint = wsEndpoint;
    this.isReady = (async () => {
      const api = await new ApiPromise({ provider: new WsProvider(wsEndpoint), types })
        .isReadyOrError;
      return api;
    })();
  }
Example #27
Source File: endpoint.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export function findMissingApis (api: ApiPromise, needsApi?: (string | string[])[]): (string | string[])[] {
  if (!needsApi) {
    return [];
  }

  return needsApi.filter((endpoint: string | string[]): boolean => {
    const hasApi = Array.isArray(endpoint)
      ? endpoint.reduce((hasApi, endpoint) => hasApi || hasEndpoint(api, endpoint), false)
      : hasEndpoint(api, endpoint);

    return !hasApi;
  });
}
Example #28
Source File: test-alpha.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
export default async function test(ACC: string) {
  const web3 = new Web3(wsProviderUrl);
  let balance = await web3.eth.getBalance(ACC);
  console.log("BALANCE WEB3", balance.toString());

  const wsProvider = new WsProvider(wsProviderUrl);
  const polkadotApi = await ApiPromise.create({
    provider: wsProvider,
    typesBundle: typesBundlePre900 as any,
  });
  const account = await polkadotApi.query.system.account(ACC);
  // console.log("BALANCE API", account.data.feeFrozen.toString());
  // console.log("BALANCE API", account.data.miscFrozen.toString());
  // console.log("BALANCE API", account.data.reserved.toString());
  console.log("BALANCE API", account.data.free.toString());

  const block = await web3.eth.getBlock("latest");
  console.log("block", block);
}
Example #29
Source File: api.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getAccounts = async (
  api: ApiPromise
): Promise<AccountBalance[]> => {
  let accounts: AccountBalance[] = [];
  const entries = await api.query.system.account.entries();
  for (const account of entries) {
    const accountId = String(account[0].toHuman());
    const balance = account[1].data.toJSON() as unknown as AccountData;
    accounts.push({ accountId, balance });
  }
  return accounts;
}