@polkadot/types/interfaces#BlockHash TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#BlockHash. 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: block.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
getBlockDetails = async (
  api: ApiPromise,
  blockHash: BlockHash | string | any
): Promise<BlockDetails> => {
  debug(`Querying ${blockHash}`);

  const [{ block }, records] = await Promise.all([
    api.rpc.chain.getBlock(blockHash),
    await (await api.at(blockHash)).query.system.events(),
  ]);

  const fees = await Promise.all(
    block.extrinsics.map((ext) => api.rpc.payment.queryInfo(ext.toHex(), block.header.parentHash))
  );

  const txWithEvents = mapExtrinsics(block.extrinsics, records, fees);

  return {
    block,
    txWithEvents,
  } as any as BlockDetails;
}
Example #2
Source File: index.ts    From parity-bridges-ui with GNU General Public License v3.0 6 votes vote down vote up
getLatestReceivedNonce = async (
  blockNumber: string,
  sourceChain: string,
  targetChain: string,
  laneId: string,
  apiCalls: ApiCalls
) => {
  const { targetApi, stateCall, createType } = apiCalls;
  const { latestReceivedNonceMethodName } = getSubstrateDynamicNames(sourceChain);
  const blockHash = (await targetApi.rpc.chain.getBlockHash(blockNumber)) as BlockHash;
  const latestReceivedNonceCall = await stateCall(
    targetChain,
    latestReceivedNonceMethodName,
    laneId,
    blockHash.toJSON()
  );

  const latestReceivedNonceCallType = createType(targetChain, MESSAGE_NONCE_TYPE, latestReceivedNonceCall);
  const latestReceivedNonce = latestReceivedNonceCallType.toString();
  return parseInt(latestReceivedNonce);
}
Example #3
Source File: index.ts    From parity-bridges-ui with GNU General Public License v3.0 6 votes vote down vote up
checkMessageDispatchedEvent = async (
  targetApi: ApiPromise,
  blockNumber: string | null,
  messageNonce: string | null
) => {
  if (!blockNumber || !messageNonce) {
    return TransactionStatusEnum.IN_PROGRESS;
  }
  const blockHash = (await targetApi.rpc.chain.getBlockHash(blockNumber)) as BlockHash;
  const signedBlock = (await targetApi.rpc.chain.getBlock(blockHash)) as SignedBlock;
  const allRecords = (await targetApi.query.system.events.at(signedBlock.block.header.hash)) as Vec<any>;

  let status = TransactionStatusEnum.FAILED;
  signedBlock.block.extrinsics.forEach((ext, index) => {
    const events = allRecords.filter(({ phase }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index));
    const found = events.find(({ event: { method, data } }) => {
      return method === MESSAGE_DISPATCH_EVENT && deepFind(data, messageNonce) && deepFind(data, OK);
    });
    if (found) {
      status = TransactionStatusEnum.COMPLETED;
    }
  });
  return status;
}
Example #4
Source File: vaults.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
async list(atBlock?: BlockHash): Promise<VaultExt<BitcoinUnit>[]> {
        const vaultsMap = await (atBlock
            ? this.api.query.vaultRegistry.vaults.entriesAt(atBlock)
            : this.api.query.vaultRegistry.vaults.entries());
        return Promise.all(
            vaultsMap
                .filter((v) => v[1].isSome)
                .map((v) => this.parseVault(v[1].value as VaultRegistryVault, this.btcNetwork))
        );
    }
Example #5
Source File: block.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
getBlockExtrinsic = async (
  api: ApiPromise,
  blockHash: string | BlockHash,
  section: string,
  method: string
) => {
  const apiAt = await api.at(blockHash);
  const [{ block }, records] = await Promise.all([
    api.rpc.chain.getBlock(blockHash),
    apiAt.query.system.events(),
  ]);
  const extIndex = block.extrinsics.findIndex(
    (ext) => ext.method.section == section && ext.method.method == method
  );
  const extrinsic = extIndex > -1 ? block.extrinsics[extIndex] : null;

  const events = records
    .filter(({ phase }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(extIndex))
    .map(({ event }) => event);
  const resultEvent = events.find(
    (event) =>
      event.section === "system" &&
      (event.method === "ExtrinsicSuccess" || event.method === "ExtrinsicFailed")
  );
  return { block, extrinsic, events, resultEvent };
}
Example #6
Source File: block.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
export async function createAndFinalizeBlock(
  api: ApiPromise,
  parentHash?: BlockHash,
  finalize: boolean = true
): Promise<{
  duration: number;
  hash: BlockHash;
}> {
  const startTime: number = Date.now();
  let hash = undefined;
  try {
    if (parentHash == undefined) {
      hash = (await api.rpc.engine.createBlock(true, finalize)).toJSON()["hash"];
    } else {
      hash = (await api.rpc.engine.createBlock(true, finalize, parentHash)).toJSON()["hash"];
    }
  } catch (e) {
    console.log("ERROR DURING BLOCK FINALIZATION", e);
  }

  return {
    duration: Date.now() - startTime,
    hash,
  };
}
Example #7
Source File: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
processTips = async (
  api: ApiPromise,
  events: EventRecord[],
  report: MintingAndBurningData,
  hash: BlockHash
) => {
  const { burning } = report;
  if (events.length > 0) {
    const block = await getBlock(api, hash);
    const burnExtrinsics = filterBlockExtrinsicsByMethods(block, [
      "utility.batch",
      "staking.bond",
      "session.setKeys",
      "staking.nominate",
      "members.buyMembership",
    ]);
    for (const item of burnExtrinsics) {
      const ext = item as unknown as Extrinsic;
      const tip = ext.tip.toNumber();
      burning.tokensBurned += tip;
    }
  }
}
Example #8
Source File: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
reloadRecurringRewards = async (
  api: ApiPromise,
  recurringRewards: RecurringRewards,
  blockNumber: number,
  hash: BlockHash
) => {
  const totalRewards = Number(
    await api.query.recurringRewards.rewardRelationshipsCreated.at(hash)
  );
  recurringRewards.rewards = {};
  for (let id = 0; id < totalRewards; ++id) {
    const reward = (
      await api.query.recurringRewards.rewardRelationships.at(hash, id)
    ).toJSON() as unknown as RewardRelationship;
    if (reward.next_payment_at_block && reward.amount_per_payout) {
      const paymentBlock = reward.next_payment_at_block as unknown as number;
      if (paymentBlock == blockNumber + 1) {
        if (recurringRewards.rewards[paymentBlock] === undefined) {
          recurringRewards.rewards[paymentBlock] = [];
        }
        const mint = (
          await getMint(api, hash, reward.mint_id)
        ).toJSON() as unknown as Mint;

        const nextBlockPaymentFromCurrentMint = recurringRewards.rewards[
          paymentBlock
        ]
          .filter((r) => r.mint_id == reward.mint_id)
          .reduce((sum, current) => sum + Number(current.amount_per_payout), 0);
        if (
          nextBlockPaymentFromCurrentMint + Number(reward.amount_per_payout) <=
          Number(mint.capacity)
        ) {
          recurringRewards.rewards[paymentBlock].push(reward);
        }
      }
    }
  }
}
Example #9
Source File: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
processMembershipCreation = async (
  api: ApiPromise,
  hash: BlockHash,
  events: Vec<EventRecord>,
  report: MintingAndBurningData
) => {
  const membershipEvents = filterByEvent("members.MemberRegistered", events);
  const { burning } = report;
  if (membershipEvents.length > 0) {
    const block = await getBlock(api, hash);
    // intentionally skipping `members.addScreenedMember` because there is no paid fee in this case
    const extrinsics = filterBlockExtrinsicsByMethod(
      block,
      "members.buyMembership"
    );
    for await (const ext of extrinsics) {
      const data = ext.toHuman() as unknown as ExtrinsicsData;
      const paidTermId = Number(data.method.args[0]);
      const terms = await getPaidMembershipTermsById(api, hash, paidTermId);
      const membershipCreationFee = Number(terms.fee);
      burning.totalMembershipCreation += membershipCreationFee;
    }
    membershipEvents.forEach((event) => {
      const { data } = event.event;
      const dataJson = data.toJSON() as object[];
      const memberId = dataJson[0] as unknown as number;
      const accountId = dataJson[0] as unknown as string;
      burning.membershipCreation.push({ memberId, accountId });
    });
  }
}
Example #10
Source File: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getSpendingProposalAmount = async (
  api: ApiPromise,
  hash: BlockHash,
  proposalId: number
): Promise<number | undefined> => {
  const proposalInfo = (await api.query.proposalsEngine.proposals.at(
    hash,
    proposalId
  )) as ProposalOf;
  const finalizedData = proposalInfo.status.asFinalized;
  const proposalDetail =
    (await api.query.proposalsCodex.proposalDetailsByProposalId.at(
      hash,
      proposalId
    )) as ProposalDetails;
  if (
    finalizedData.proposalStatus.isApproved &&
    finalizedData.proposalStatus.asApproved.isExecuted &&
    proposalDetail.isSpending
  ) {
    const spendingParams = proposalDetail.asSpending;
    return Number(spendingParams[0]);
  }
  return undefined;
}
Example #11
Source File: index.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
getBlockHash = (api: ApiPromise, blockId: number) =>
  api.rpc.chain.getBlockHash(blockId).then((hash: BlockHash) => hash.toString())
Example #12
Source File: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
processProposals = async (
  api: ApiPromise,
  events: Vec<EventRecord>,
  report: MintingAndBurningData,
  hash: BlockHash
) => {
  const proposalEvents = filterByEvent(
    "proposalsEngine.ProposalStatusUpdated",
    events
  );
  const { minting, burning } = report;
  if (proposalEvents.length > 0) {
    for (const event of proposalEvents) {
      const { data } = event.event;
      const dataJson = data.toJSON() as object[];
      const proposalId = dataJson[0] as unknown as number;
      const block = await getBlock(api, hash);
      const cancelledProposals = filterBlockExtrinsicsByMethod(
        block,
        "proposalsEngine.cancelProposal"
      );
      for (const {} of cancelledProposals) {
        burning.totalProposalCancellationFee += 10000; // TODO get proposal cancellation fee from chains
        burning.cancelledProposals.push(proposalId);
      }
      const proposalStatusWrapper = dataJson[1] as unknown as ProposalStatus;
      const finalizationData = (
        proposalStatusWrapper as unknown as {
          [key: string]: FinalizationData[];
        }
      )["finalized"] as unknown as FinalizationData;
      for await (const key of Object.keys(finalizationData.proposalStatus)) {
        if (key.toString() === "expired" || key.toString() === "rejected") {
          burning.totalProposalCancellationFee += 5000; // TODO get proposal rejected/expired fee from chains
        }
      }

      const spendingProposalAmount = await getSpendingProposalAmount(
        api,
        hash,
        proposalId
      );
      if (
        spendingProposalAmount &&
        minting.spendingProposals.filter(
          (p) =>
            p.proposalId === proposalId && p.amount === spendingProposalAmount
        ).length === 0
      ) {
        minting.spendingProposals.push({
          proposalId,
          amount: spendingProposalAmount,
        });
        minting.totalSpendingProposalsMint += spendingProposalAmount;
      }
    }
  }
}
Example #13
Source File: Blocks.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Get blockHash by number
   * @param number number of block
   * @returns blockHash
   */
  async getBlockHash(number: AnyNumber | BlockNumber): Promise<BlockHash> {
    return await this.api.rpc.chain.getBlockHash(number);
  }
Example #14
Source File: Blocks.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Get hash of last finalized block
   * @returns Hash of finalized head
   */
  async getFinalizedHead(): Promise<BlockHash> {
    return this.api.rpc.chain.getFinalizedHead();
  }
Example #15
Source File: system.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
async getCurrentActiveBlockNumber(atBlock?: BlockHash): Promise<number> {
        const block = atBlock || (await this.api.rpc.chain.getFinalizedHead());
        return (await this.api.query.security.activeBlockCount.at(block)).toNumber();
    }
Example #16
Source File: system.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
async getBlockHash(blockNumber: number): Promise<BlockHash> {
        return await this.api.query.system.blockHash(blockNumber);
    }
Example #17
Source File: getBlock.test.ts    From metamask-snap-polkadot with Apache License 2.0 4 votes vote down vote up
describe('Test rpc handler function: getBlock', function() {

  const walletStub = new WalletMock();

  afterEach(function() {
    walletStub.reset();
  });

  it('should return block on block id as number', async function () {
    // api stub
    const apiStub = {rpc: {chain: {getBlock: sinon.stub(), getBlockHash: sinon.stub()}}};
    apiStub.rpc.chain.getBlockHash.returns(
      hexToU8a("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75") as BlockHash
    );
    // eslint-disable-next-line max-len
    apiStub.rpc.chain.getBlock.returns({block:{hash: {toHex: (): string => "0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75"}, header: {number: 10}}});
    const api = apiStub as unknown as ApiPromise;
    const result = await getBlock(1, api);
    expect(result).not.to.be.null;
    expect(result.hash).to.be.eq("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75");
    expect(result.number).to.be.eq("10");
    expect(apiStub.rpc.chain.getBlockHash).to.have.been.calledOnceWith(1);
    // eslint-disable-next-line max-len
    expect(apiStub.rpc.chain.getBlock).to.have.been.calledOnceWith(hexToU8a("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75") as BlockHash);
  });

  it('should return block on block id as string', async function () {
    // api stub
    const apiStub = {rpc: {chain: {getBlock: sinon.stub(), getBlockHash: sinon.stub()}}};
    apiStub.rpc.chain.getBlockHash.returns(
      hexToU8a("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75") as BlockHash
    );
    // eslint-disable-next-line max-len
    apiStub.rpc.chain.getBlock.returns({block:{hash: {toHex: (): string => "0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75"}, header: {number: 10}}});
    const api = apiStub as unknown as ApiPromise;
    const result = await getBlock("1", api);
    expect(result).not.to.be.null;
    expect(result.hash).to.be.eq("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75");
    expect(result.number).to.be.eq("10");
    expect(apiStub.rpc.chain.getBlockHash).to.have.been.calledOnceWith(1);
    // eslint-disable-next-line max-len
    expect(apiStub.rpc.chain.getBlock).to.have.been.calledOnceWith(hexToU8a("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75") as BlockHash);
  });

  it('should return block on block hash as string', async function () {
    // api stub
    const apiStub = {rpc: {chain: {getBlock: sinon.stub()}}};
    apiStub.rpc.chain.getBlock.returns({});
    // eslint-disable-next-line max-len
    apiStub.rpc.chain.getBlock.returns({block:{hash: {toHex: (): string => "0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75"}, header: {number: 10}}});
    const api = apiStub as unknown as ApiPromise;
    // eslint-disable-next-line max-len
    const result = await getBlock("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75", api);
    expect(result).not.to.be.null;
    expect(result.hash).to.be.eq("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75");
    expect(result.number).to.be.eq("10");
    // eslint-disable-next-line max-len
    expect(apiStub.rpc.chain.getBlock).to.have.been.calledOnceWith("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75");
  });

  it('should return latest block on "latest" as parameter', async function () {
    // api stub
    const apiStub = {rpc: {chain: {getBlock: sinon.stub(), getHeader: sinon.stub()}}};
    apiStub.rpc.chain.getBlock.returns({});
    // eslint-disable-next-line max-len
    apiStub.rpc.chain.getBlock.returns({block:{hash: {toHex: (): string => "0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75"}, header: {number: 10}}});
    // eslint-disable-next-line max-len
    apiStub.rpc.chain.getHeader.returns({hash: hexToU8a("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75") as H256});
    const api = apiStub as unknown as ApiPromise;
    const result = await getBlock("latest", api);
    expect(result).not.to.be.null;
    expect(result.hash).to.be.eq("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75");
    expect(result.number).to.be.eq("10");
    expect(apiStub.rpc.chain.getHeader).to.have.been.calledOnce;
    // eslint-disable-next-line max-len
    expect(apiStub.rpc.chain.getBlock).to.have.been.calledOnceWith(hexToU8a("0xc9fb400866641ca80ef3e760d904fe15a8c9eda6ff1bd769b0628e26e82d5c75") as BlockHash);
  });

  it('should return null on invalid string as parameter', async function () {
    const api = {} as unknown as ApiPromise;
    const result = await getBlock("zz", api);
    expect(result).to.be.null;
  });

  it('should return null on empty parameters object', async function () {
    const api = {} as unknown as ApiPromise;
    const result = await getBlock(null, api);
    expect(result).to.be.null;
  });

});