@polkadot/api/types#ApiTypes TypeScript Examples

The following examples show how to use @polkadot/api/types#ApiTypes. 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: test-xcm-para.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
execFromAllMembersOfTechCommittee = async <Call extends SubmittableExtrinsic<ApiTypes>>(
  parachainApi: ApiPromise,
  polkadotCall: Call,
  key_1: KeyringPair,
  key_2: KeyringPair,
  index: Number
) => {
  let lengthBound = polkadotCall.encodedLength;
  const { events: proposalEvents } = await createBlockWithExtrinsicParachain(
    parachainApi,
    key_1,
    parachainApi.tx.techCommitteeCollective.propose(2, polkadotCall, lengthBound)
  );

  const proposalHash = proposalEvents
    .find((e) => e.method.toString() == "Proposed")
    .data[2].toHex() as string;

  await createBlockWithExtrinsicParachain(
    parachainApi,
    key_1,
    parachainApi.tx.techCommitteeCollective.vote(proposalHash, index, true)
  );

  await createBlockWithExtrinsicParachain(
    parachainApi,
    key_2,
    parachainApi.tx.techCommitteeCollective.vote(proposalHash, index, true)
  );

  await createBlockWithExtrinsicParachain(
    parachainApi,
    key_2,
    parachainApi.tx.techCommitteeCollective.close(proposalHash, index, 1_000_000_000, lengthBound)
  );
}
Example #2
Source File: test-precompile-democracy.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
notePreimagePrecompile = async <
  Call extends SubmittableExtrinsic<ApiType>,
  ApiType extends ApiTypes
>(
  context: DevTestContext,
  iFace: Interface,
  proposal: Call
): Promise<`0x${string}`> => {
  const encodedProposal = proposal.method.toHex();

  const data = iFace.encodeFunctionData(
    // action
    "note_preimage",
    [encodedProposal]
  );

  const tx = await createTransaction(context, {
    from: GENESIS_ACCOUNT,
    privateKey: GENESIS_ACCOUNT_PRIVATE_KEY,
    value: "0x0",
    gas: "0x200000",
    gasPrice: GAS_PRICE,
    to: ADDRESS_DEMO_PRECOMPILE,
    data,
  });

  await context.createBlock({
    transactions: [tx],
  });
  // return encodedHash
  return blake2AsHex(encodedProposal);
}
Example #3
Source File: governance.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
notePreimage = async <
  Call extends SubmittableExtrinsic<ApiType>,
  ApiType extends ApiTypes
>(
  context: DevTestContext,
  proposal: Call,
  account: KeyringPair
): Promise<string> => {
  const encodedProposal = proposal.method.toHex() || "";
  await context.polkadotApi.tx.democracy.notePreimage(encodedProposal).signAndSend(account);
  await context.createBlock();

  return blake2AsHex(encodedProposal);
}
Example #4
Source File: governance.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
execFromTwoThirdsOfCouncil = async <
  Call extends SubmittableExtrinsic<ApiType>,
  ApiType extends ApiTypes
>(
  context: DevTestContext,
  polkadotCall: Call
) => {
  // Council members
  const charleth = await keyring.addFromUri(CHARLETH_PRIV_KEY, null, "ethereum");
  const dorothy = await keyring.addFromUri(DOROTHY_PRIV_KEY, null, "ethereum");

  // Charleth submit the proposal to the council (and therefore implicitly votes for)
  let lengthBound = polkadotCall.encodedLength;
  const { events: proposalEvents } = await createBlockWithExtrinsic(
    context,
    charleth,
    context.polkadotApi.tx.councilCollective.propose(2, polkadotCall, lengthBound)
  );
  const proposalHash = proposalEvents
    .find((e) => e.method.toString() == "Proposed")
    .data[2].toHex() as string;

  // Dorothy vote for this proposal and close it
  await Promise.all([
    context.polkadotApi.tx.councilCollective.vote(proposalHash, 0, true).signAndSend(charleth),
    context.polkadotApi.tx.councilCollective.vote(proposalHash, 0, true).signAndSend(dorothy),
  ]);
  await context.createBlock();

  return await createBlockWithExtrinsic(
    context,
    dorothy,
    context.polkadotApi.tx.councilCollective.close(proposalHash, 0, 1_000_000_000, lengthBound)
  );
}
Example #5
Source File: substrate-rpc.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
createBlockWithExtrinsic = async <
  Call extends SubmittableExtrinsic<ApiType>,
  ApiType extends ApiTypes
>(
  context: DevTestContext,
  sender: AddressOrPair,
  polkadotCall: Call
) => {
  // This should return a string, but is a bit complex to handle type properly so any will suffice
  const extrinsicHash = (await polkadotCall.signAndSend(sender)) as any;

  // We create the block which is containing the extrinsic
  const blockResult = await context.createBlock();

  // We retrieve the events for that block
  const allRecords: EventRecord[] = (await (
    await context.polkadotApi.at(blockResult.block.hash)
  ).query.system.events()) as any;

  // We retrieve the block (including the extrinsics)
  const blockData = await context.polkadotApi.rpc.chain.getBlock(blockResult.block.hash);

  const extrinsicIndex = blockData.block.extrinsics.findIndex(
    (ext) => ext.hash.toHex() == extrinsicHash
  );
  if (extrinsicIndex < 0) {
    throw new Error(`Extrinsic ${extrinsicHash} is missing in the block ${blockResult.block.hash}`);
  }
  const extrinsic = blockData.block.extrinsics[extrinsicIndex];

  // We retrieve the events associated with the extrinsic
  const events = allRecords
    .filter(
      ({ phase }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.toNumber() == extrinsicIndex
    )
    .map(({ event }) => event);

  return { extrinsic, events };
}
Example #6
Source File: substrate-rpc.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
createBlockWithExtrinsicParachain = async <
  Call extends SubmittableExtrinsic<ApiType>,
  ApiType extends ApiTypes
>(
  api: ApiPromise,
  sender: AddressOrPair,
  polkadotCall: Call
): Promise<{ extrinsic: GenericExtrinsic<AnyTuple>; events: Event[] }> => {
  console.log("-------------- EXTRINSIC CALL -------------------------------");
  // This should return a Uint8Array
  const extrinsicHash = (await polkadotCall.signAndSend(sender)) as unknown as Uint8Array;

  // We create the block which is containing the extrinsic
  //const blockResult = await context.createBlock();
  return await tryLookingForEvents(api, extrinsicHash);
}
Example #7
Source File: transaction.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
async sendLogged<T extends AnyTuple>(
        transaction: SubmittableExtrinsic<"promise">,
        successEventType?: AugmentedEvent<ApiTypes, T>,
        onlyInBlock?: boolean
    ): Promise<ISubmittableResult> {
        if (this.account === undefined) {
            return Promise.reject(new Error(ACCOUNT_NOT_SET_ERROR_MESSAGE));
        }
        return DefaultTransactionAPI.sendLogged(this.api, this.account, transaction, successEventType, onlyInBlock);
    }
Example #8
Source File: transaction.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
static async waitForEvent<T extends AnyTuple>(
        api: ApiPromise,
        event: AugmentedEvent<ApiTypes, T>,
        timeoutMs: number
    ): Promise<boolean> {
        // Use this function with a timeout.
        // Unless the awaited event occurs, this Promise will never resolve.
        let timeoutHandle: NodeJS.Timeout;
        const timeoutPromise = new Promise((_, reject) => {
            timeoutHandle = setTimeout(() => reject(), timeoutMs);
        });

        await Promise.race([
            new Promise<void>((resolve, _reject) => {
                api.query.system.events((eventsVec) => {
                    const events = eventsVec.toArray();
                    if (this.doesArrayContainEvent(events, event)) {
                        resolve();
                    }
                });
            }),
            timeoutPromise,
        ]).then((_) => {
            clearTimeout(timeoutHandle);
        });

        return true;
    }
Example #9
Source File: transaction.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
static doesArrayContainEvent<T extends AnyTuple>(
        events: EventRecord[],
        eventType: AugmentedEvent<ApiTypes, T>
    ): boolean {
        for (const { event } of events) {
            if (eventType.is(event)) {
                return true;
            }
        }
        return false;
    }
Example #10
Source File: issueRedeem.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
/**
 * @param events The EventRecord array returned after sending a transaction
 * @param methodToCheck The name of the event method whose existence to check
 * @returns The id associated with the transaction. If the EventRecord array does not
 * contain required events, the function throws an error.
 */
export function getRequestIdsFromEvents(
    events: EventRecord[],
    eventToFind: AugmentedEvent<ApiTypes, AnyTuple>,
    api: ApiPromise
): Hash[] {
    const ids = new Array<Hash>();
    for (const { event } of events) {
        if (eventToFind.is(event)) {
            // the redeem id has type H256 and is the first item of the event data array
            const id = api.createType("Hash", event.data[0]);
            ids.push(id);
        }
    }

    if (ids.length > 0) return ids;
    throw new Error("Transaction failed");
}
Example #11
Source File: substrate-rpc.ts    From polkadot-launch with MIT License 6 votes vote down vote up
createBlockWithExtrinsicParachain = async <
	Call extends SubmittableExtrinsic<ApiType>,
	ApiType extends ApiTypes
>(
	api: ApiPromise,
	sender: AddressOrPair,
	polkadotCall: Call
): Promise<{ extrinsic: GenericExtrinsic<AnyTuple>; events: Event[] }> => {
	console.log("-------------- EXTRINSIC CALL -------------------------------");
	// This should return a Uint8Array
	const extrinsicHash = (await polkadotCall.signAndSend(
		sender
	)) as unknown as Uint8Array;

	// We create the block which is containing the extrinsic
	//const blockResult = await context.createBlock();
	return await tryLookingForEvents(api, extrinsicHash);
}
Example #12
Source File: governance.ts    From moonbeam with GNU General Public License v3.0 5 votes vote down vote up
execFromAllMembersOfTechCommittee = async <
  Call extends SubmittableExtrinsic<ApiType>,
  ApiType extends ApiTypes
>(
  context: DevTestContext,
  polkadotCall: Call
) => {
  // Tech committee members
  const alith = await keyring.addFromUri(ALITH_PRIV_KEY, null, "ethereum");
  const baltathar = await keyring.addFromUri(BALTATHAR_PRIV_KEY, null, "ethereum");

  // Alith submit the proposal to the council (and therefore implicitly votes for)
  let lengthBound = polkadotCall.encodedLength;
  const { events: proposalEvents } = await createBlockWithExtrinsic(
    context,
    alith,
    context.polkadotApi.tx.techCommitteeCollective.propose(2, polkadotCall, lengthBound)
  );
  const proposalHash = proposalEvents
    .find((e) => e.method.toString() == "Proposed")
    .data[2].toHex() as string;

  // Get proposal count
  const proposalCount = await context.polkadotApi.query.techCommitteeCollective.proposalCount();

  // Alith, Baltathar vote for this proposal and close it
  await Promise.all([
    context.polkadotApi.tx.techCommitteeCollective
      .vote(proposalHash, Number(proposalCount) - 1, true)
      .signAndSend(alith),
    context.polkadotApi.tx.techCommitteeCollective
      .vote(proposalHash, Number(proposalCount) - 1, true)
      .signAndSend(baltathar),
  ]);

  await context.createBlock();
  await context.createBlock();
  return await createBlockWithExtrinsic(
    context,
    baltathar,
    context.polkadotApi.tx.techCommitteeCollective.close(
      proposalHash,
      Number(proposalCount) - 1,
      1_000_000_000,
      lengthBound
    )
  );
}
Example #13
Source File: redeem.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
private getRedeemIdsFromEvents(events: EventRecord[], event: AugmentedEvent<ApiTypes, AnyTuple>): Hash[] {
        return getRequestIdsFromEvents(events, event, this.api);
    }
Example #14
Source File: transaction.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
static async sendLogged<T extends AnyTuple>(
        api: ApiPromise,
        account: AddressOrPair,
        transaction: SubmittableExtrinsic<"promise">,
        successEventType?: AugmentedEvent<ApiTypes, T>,
        onlyInBlock?: boolean
    ): Promise<ISubmittableResult> {
        const { unsubscribe, result } = await new Promise((resolve, reject) => {
            let unsubscribe: () => void;
            // When passing { nonce: -1 } to signAndSend the API will use system.accountNextIndex to determine the nonce
            transaction
                .signAndSend(account, { nonce: -1 }, (result: ISubmittableResult) => callback({ unsubscribe, result }))
                .then((u: () => void) => (unsubscribe = u))
                .catch((error) => reject(error));

            function callback(callbackObject: { unsubscribe: () => void; result: ISubmittableResult }): void {
                const status = callbackObject.result.status;
                if (onlyInBlock) {
                    if (status.isInBlock) {
                        resolve(callbackObject);
                    }
                } else {
                    if (status.isFinalized) {
                        resolve(callbackObject);
                    }
                }
            }
        });

        if (onlyInBlock) {
            console.log(`Transaction included at blockHash ${result.status.asInBlock}`);
        } else {
            console.log(`Transaction finalized at blockHash ${result.status.asFinalized}`);
        }
        unsubscribe(result);

        // Print all events for debugging
        DefaultTransactionAPI.printEvents(api, result.events);

        const dispatchError = result.dispatchError;
        if (dispatchError) {
            // Construct error message
            let message = "The transaction failed.";
            // Runtime error in one of the parachain modules
            if (dispatchError.isModule) {
                // for module errors, we have the section indexed, lookup
                const decoded = api.registry.findMetaError(dispatchError.asModule);
                const { docs, name, section } = decoded;
                message = message.concat(` The error code is ${section}.${name}. ${docs.join(" ")}`);
                // Bad origin
            } else if (dispatchError.isBadOrigin) {
                message = message.concat(` The error is caused by using an incorrect account.
                The error code is BadOrigin ${dispatchError}.`);
            }
            // Other, CannotLookup, no extra info
            else {
                message = message.concat(` The error is ${dispatchError}.`);
            }
            console.log(message);
            return Promise.reject(new Error(message));
        }
        return result;
    }