Add api.{errors, events, query, tx}.<method>.<section>.is(...) (#2984)

* api.{event, error}.<section>.is<Type>

* Full generation, with checkTypes

* .is

* Extrinsic with arg type definition

* decorate is

* Call is

* Remove hasOrigin

* Renames

* Query is

* Fix extrinsic is

* Backwards compatibility for generated types

* event with optional AnyTuple

* Cleanups

* Cleanups

* Adjust

* Cleanup
This commit is contained in:
Jaco Greeff
2020-12-27 11:15:02 +01:00
committed by GitHub
parent 025a745258
commit 0967dbba6b
48 changed files with 2987 additions and 524 deletions
File diff suppressed because it is too large Load Diff
+842
View File
@@ -0,0 +1,842 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { Bytes, Option, Vec, bool, u16, u32 } from '@polkadot/types';
import type { ITuple } from '@polkadot/types/types';
import type { BalanceStatus } from '@polkadot/types/interfaces/balances';
import type { MemberCount, ProposalIndex } from '@polkadot/types/interfaces/collective';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { PropIndex, ReferendumIndex } from '@polkadot/types/interfaces/democracy';
import type { VoteThreshold } from '@polkadot/types/interfaces/elections';
import type { AuthorityList } from '@polkadot/types/interfaces/grandpa';
import type { RegistrarIndex } from '@polkadot/types/interfaces/identity';
import type { Kind, OpaqueTimeSlot } from '@polkadot/types/interfaces/offences';
import type { ProxyType } from '@polkadot/types/interfaces/proxy';
import type { AccountId, AccountIndex, AssetId, Balance, BlockNumber, CallHash, Hash, PhantomData } from '@polkadot/types/interfaces/runtime';
import type { TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { IdentificationTuple, SessionIndex } from '@polkadot/types/interfaces/session';
import type { ElectionCompute, EraIndex } from '@polkadot/types/interfaces/staking';
import type { DispatchError, DispatchInfo, DispatchResult } from '@polkadot/types/interfaces/system';
import type { BountyIndex } from '@polkadot/types/interfaces/treasury';
import type { Timepoint } from '@polkadot/types/interfaces/utility';
import type { ApiTypes } from '@polkadot/api/types';
declare module '@polkadot/api/types/events' {
export interface AugmentedEvents<ApiType> {
assets: {
[key: string]: AugmentedEvent<ApiType>;
/**
* Some assets were destroyed. \[asset_id, owner, balance\]
**/
Burned: AugmentedEvent<ApiType, [AssetId, AccountId, Balance]>;
/**
* Some asset class was created. \[asset_id, creator, owner\]
**/
Created: AugmentedEvent<ApiType, [AssetId, AccountId, AccountId]>;
/**
* An asset class was destroyed.
**/
Destroyed: AugmentedEvent<ApiType, [AssetId]>;
/**
* Some asset class was force-created. \[asset_id, owner\]
**/
ForceCreated: AugmentedEvent<ApiType, [AssetId, AccountId]>;
/**
* Some assets was transferred by an admin. \[asset_id, from, to, amount\]
**/
ForceTransferred: AugmentedEvent<ApiType, [AssetId, AccountId, AccountId, Balance]>;
/**
* Some account `who` was frozen. \[asset_id, who\]
**/
Frozen: AugmentedEvent<ApiType, [AssetId, AccountId]>;
/**
* Some assets were issued. \[asset_id, owner, total_supply\]
**/
Issued: AugmentedEvent<ApiType, [AssetId, AccountId, Balance]>;
/**
* The maximum amount of zombies allowed has changed. \[asset_id, max_zombies\]
**/
MaxZombiesChanged: AugmentedEvent<ApiType, [AssetId, u32]>;
/**
* The owner changed \[asset_id, owner\]
**/
OwnerChanged: AugmentedEvent<ApiType, [AssetId, AccountId]>;
/**
* The management team changed \[asset_id, issuer, admin, freezer\]
**/
TeamChanged: AugmentedEvent<ApiType, [AssetId, AccountId, AccountId, AccountId]>;
/**
* Some account `who` was thawed. \[asset_id, who\]
**/
Thawed: AugmentedEvent<ApiType, [AssetId, AccountId]>;
/**
* Some assets were transferred. \[asset_id, from, to, amount\]
**/
Transferred: AugmentedEvent<ApiType, [AssetId, AccountId, AccountId, Balance]>;
};
balances: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A balance was set by root. \[who, free, reserved\]
**/
BalanceSet: AugmentedEvent<ApiType, [AccountId, Balance, Balance]>;
/**
* Some amount was deposited (e.g. for transaction fees). \[who, deposit\]
**/
Deposit: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* An account was removed whose balance was non-zero but below ExistentialDeposit,
* resulting in an outright loss. \[account, balance\]
**/
DustLost: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* An account was created with some free balance. \[account, free_balance\]
**/
Endowed: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* Some balance was reserved (moved from free to reserved). \[who, value\]
**/
Reserved: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* Some balance was moved from the reserve of the first account to the second account.
* Final argument indicates the destination balance type.
* \[from, to, balance, destination_status\]
**/
ReserveRepatriated: AugmentedEvent<ApiType, [AccountId, AccountId, Balance, BalanceStatus]>;
/**
* Transfer succeeded. \[from, to, value\]
**/
Transfer: AugmentedEvent<ApiType, [AccountId, AccountId, Balance]>;
/**
* Some balance was unreserved (moved from reserved to free). \[who, value\]
**/
Unreserved: AugmentedEvent<ApiType, [AccountId, Balance]>;
};
bounties: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A bounty is awarded to a beneficiary. \[index, beneficiary\]
**/
BountyAwarded: AugmentedEvent<ApiType, [BountyIndex, AccountId]>;
/**
* A bounty proposal is funded and became active. \[index\]
**/
BountyBecameActive: AugmentedEvent<ApiType, [BountyIndex]>;
/**
* A bounty is cancelled. \[index\]
**/
BountyCanceled: AugmentedEvent<ApiType, [BountyIndex]>;
/**
* A bounty is claimed by beneficiary. \[index, payout, beneficiary\]
**/
BountyClaimed: AugmentedEvent<ApiType, [BountyIndex, Balance, AccountId]>;
/**
* A bounty expiry is extended. \[index\]
**/
BountyExtended: AugmentedEvent<ApiType, [BountyIndex]>;
/**
* New bounty proposal. \[index\]
**/
BountyProposed: AugmentedEvent<ApiType, [BountyIndex]>;
/**
* A bounty proposal was rejected; funds were slashed. \[index, bond\]
**/
BountyRejected: AugmentedEvent<ApiType, [BountyIndex, Balance]>;
};
contracts: {
[key: string]: AugmentedEvent<ApiType>;
/**
* Code with the specified hash has been stored.
* \[code_hash\]
**/
CodeStored: AugmentedEvent<ApiType, [Hash]>;
/**
* An event deposited upon execution of a contract from the account.
* \[account, data\]
**/
ContractExecution: AugmentedEvent<ApiType, [AccountId, Bytes]>;
/**
* Contract has been evicted and is now in tombstone state.
* \[contract, tombstone\]
*
* # Params
*
* - `contract`: `AccountId`: The account ID of the evicted contract.
* - `tombstone`: `bool`: True if the evicted contract left behind a tombstone.
**/
Evicted: AugmentedEvent<ApiType, [AccountId, bool]>;
/**
* Contract deployed by address at the specified address. \[owner, contract\]
**/
Instantiated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/**
* Restoration for a contract has been successful.
* \[donor, dest, code_hash, rent_allowance\]
*
* # Params
*
* - `donor`: `AccountId`: Account ID of the restoring contract
* - `dest`: `AccountId`: Account ID of the restored contract
* - `code_hash`: `Hash`: Code hash of the restored contract
* - `rent_allowance: `Balance`: Rent allowance of the restored contract
**/
Restored: AugmentedEvent<ApiType, [AccountId, AccountId, Hash, Balance]>;
/**
* Triggered when the current \[schedule\] is updated.
**/
ScheduleUpdated: AugmentedEvent<ApiType, [u32]>;
};
council: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A motion was approved by the required threshold.
* \[proposal_hash\]
**/
Approved: AugmentedEvent<ApiType, [Hash]>;
/**
* A proposal was closed because its threshold was reached or after its duration was up.
* \[proposal_hash, yes, no\]
**/
Closed: AugmentedEvent<ApiType, [Hash, MemberCount, MemberCount]>;
/**
* A motion was not approved by the required threshold.
* \[proposal_hash\]
**/
Disapproved: AugmentedEvent<ApiType, [Hash]>;
/**
* A motion was executed; result will be `Ok` if it returned without error.
* \[proposal_hash, result\]
**/
Executed: AugmentedEvent<ApiType, [Hash, DispatchResult]>;
/**
* A single member did some action; result will be `Ok` if it returned without error.
* \[proposal_hash, result\]
**/
MemberExecuted: AugmentedEvent<ApiType, [Hash, DispatchResult]>;
/**
* A motion (given hash) has been proposed (by given account) with a threshold (given
* `MemberCount`).
* \[account, proposal_index, proposal_hash, threshold\]
**/
Proposed: AugmentedEvent<ApiType, [AccountId, ProposalIndex, Hash, MemberCount]>;
/**
* A motion (given hash) has been voted on by given account, leaving
* a tally (yes votes and no votes given respectively as `MemberCount`).
* \[account, proposal_hash, voted, yes, no\]
**/
Voted: AugmentedEvent<ApiType, [AccountId, Hash, bool, MemberCount, MemberCount]>;
};
democracy: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A proposal \[hash\] has been blacklisted permanently.
**/
Blacklisted: AugmentedEvent<ApiType, [Hash]>;
/**
* A referendum has been cancelled. \[ref_index\]
**/
Cancelled: AugmentedEvent<ApiType, [ReferendumIndex]>;
/**
* An account has delegated their vote to another account. \[who, target\]
**/
Delegated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/**
* A proposal has been enacted. \[ref_index, is_ok\]
**/
Executed: AugmentedEvent<ApiType, [ReferendumIndex, bool]>;
/**
* An external proposal has been tabled.
**/
ExternalTabled: AugmentedEvent<ApiType, []>;
/**
* A proposal has been rejected by referendum. \[ref_index\]
**/
NotPassed: AugmentedEvent<ApiType, [ReferendumIndex]>;
/**
* A proposal has been approved by referendum. \[ref_index\]
**/
Passed: AugmentedEvent<ApiType, [ReferendumIndex]>;
/**
* A proposal could not be executed because its preimage was invalid.
* \[proposal_hash, ref_index\]
**/
PreimageInvalid: AugmentedEvent<ApiType, [Hash, ReferendumIndex]>;
/**
* A proposal could not be executed because its preimage was missing.
* \[proposal_hash, ref_index\]
**/
PreimageMissing: AugmentedEvent<ApiType, [Hash, ReferendumIndex]>;
/**
* A proposal's preimage was noted, and the deposit taken. \[proposal_hash, who, deposit\]
**/
PreimageNoted: AugmentedEvent<ApiType, [Hash, AccountId, Balance]>;
/**
* A registered preimage was removed and the deposit collected by the reaper.
* \[proposal_hash, provider, deposit, reaper\]
**/
PreimageReaped: AugmentedEvent<ApiType, [Hash, AccountId, Balance, AccountId]>;
/**
* A proposal preimage was removed and used (the deposit was returned).
* \[proposal_hash, provider, deposit\]
**/
PreimageUsed: AugmentedEvent<ApiType, [Hash, AccountId, Balance]>;
/**
* A motion has been proposed by a public account. \[proposal_index, deposit\]
**/
Proposed: AugmentedEvent<ApiType, [PropIndex, Balance]>;
/**
* A referendum has begun. \[ref_index, threshold\]
**/
Started: AugmentedEvent<ApiType, [ReferendumIndex, VoteThreshold]>;
/**
* A public proposal has been tabled for referendum vote. \[proposal_index, deposit, depositors\]
**/
Tabled: AugmentedEvent<ApiType, [PropIndex, Balance, Vec<AccountId>]>;
/**
* An \[account\] has cancelled a previous delegation operation.
**/
Undelegated: AugmentedEvent<ApiType, [AccountId]>;
/**
* An \[account\] has been unlocked successfully.
**/
Unlocked: AugmentedEvent<ApiType, [AccountId]>;
/**
* An external proposal has been vetoed. \[who, proposal_hash, until\]
**/
Vetoed: AugmentedEvent<ApiType, [AccountId, Hash, BlockNumber]>;
};
elections: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A candidate was slashed due to failing to obtain a seat as member or runner-up
**/
CandidateSlashed: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* Internal error happened while trying to perform election.
**/
ElectionError: AugmentedEvent<ApiType, []>;
/**
* No (or not enough) candidates existed for this round. This is different from
* `NewTerm(\[\])`. See the description of `NewTerm`.
**/
EmptyTerm: AugmentedEvent<ApiType, []>;
/**
* A \[member\] has been removed. This should always be followed by either `NewTerm` or
* `EmptyTerm`.
**/
MemberKicked: AugmentedEvent<ApiType, [AccountId]>;
/**
* A \[member\] has renounced their candidacy.
**/
MemberRenounced: AugmentedEvent<ApiType, [AccountId]>;
/**
* A new term with \[new_members\]. This indicates that enough candidates existed to run the
* election, not that enough have has been elected. The inner value must be examined for
* this purpose. A `NewTerm(\[\])` indicates that some candidates got their bond slashed and
* none were elected, whilst `EmptyTerm` means that no candidates existed to begin with.
**/
NewTerm: AugmentedEvent<ApiType, [Vec<ITuple<[AccountId, Balance]>>]>;
/**
* A seat holder (member or runner-up) was slashed due to failing to retaining their position.
**/
SeatHolderSlashed: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* A voter was reported with the the report being successful or not.
* \[voter, reporter, success\]
**/
VoterReported: AugmentedEvent<ApiType, [AccountId, AccountId, bool]>;
};
grandpa: {
[key: string]: AugmentedEvent<ApiType>;
/**
* New authority set has been applied. \[authority_set\]
**/
NewAuthorities: AugmentedEvent<ApiType, [AuthorityList]>;
/**
* Current authority set has been paused.
**/
Paused: AugmentedEvent<ApiType, []>;
/**
* Current authority set has been resumed.
**/
Resumed: AugmentedEvent<ApiType, []>;
};
identity: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A name was cleared, and the given balance returned. \[who, deposit\]
**/
IdentityCleared: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* A name was removed and the given balance slashed. \[who, deposit\]
**/
IdentityKilled: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* A name was set or reset (which will remove all judgements). \[who\]
**/
IdentitySet: AugmentedEvent<ApiType, [AccountId]>;
/**
* A judgement was given by a registrar. \[target, registrar_index\]
**/
JudgementGiven: AugmentedEvent<ApiType, [AccountId, RegistrarIndex]>;
/**
* A judgement was asked from a registrar. \[who, registrar_index\]
**/
JudgementRequested: AugmentedEvent<ApiType, [AccountId, RegistrarIndex]>;
/**
* A judgement request was retracted. \[who, registrar_index\]
**/
JudgementUnrequested: AugmentedEvent<ApiType, [AccountId, RegistrarIndex]>;
/**
* A registrar was added. \[registrar_index\]
**/
RegistrarAdded: AugmentedEvent<ApiType, [RegistrarIndex]>;
/**
* A sub-identity was added to an identity and the deposit paid. \[sub, main, deposit\]
**/
SubIdentityAdded: AugmentedEvent<ApiType, [AccountId, AccountId, Balance]>;
/**
* A sub-identity was removed from an identity and the deposit freed.
* \[sub, main, deposit\]
**/
SubIdentityRemoved: AugmentedEvent<ApiType, [AccountId, AccountId, Balance]>;
/**
* A sub-identity was cleared, and the given deposit repatriated from the
* main identity account to the sub-identity account. \[sub, main, deposit\]
**/
SubIdentityRevoked: AugmentedEvent<ApiType, [AccountId, AccountId, Balance]>;
};
imOnline: {
[key: string]: AugmentedEvent<ApiType>;
/**
* At the end of the session, no offence was committed.
**/
AllGood: AugmentedEvent<ApiType, []>;
/**
* A new heartbeat was received from `AuthorityId` \[authority_id\]
**/
HeartbeatReceived: AugmentedEvent<ApiType, [AuthorityId]>;
/**
* At the end of the session, at least one validator was found to be \[offline\].
**/
SomeOffline: AugmentedEvent<ApiType, [Vec<IdentificationTuple>]>;
};
indices: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A account index was assigned. \[index, who\]
**/
IndexAssigned: AugmentedEvent<ApiType, [AccountId, AccountIndex]>;
/**
* A account index has been freed up (unassigned). \[index\]
**/
IndexFreed: AugmentedEvent<ApiType, [AccountIndex]>;
/**
* A account index has been frozen to its current account ID. \[index, who\]
**/
IndexFrozen: AugmentedEvent<ApiType, [AccountIndex, AccountId]>;
};
multisig: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A multisig operation has been approved by someone.
* \[approving, timepoint, multisig, call_hash\]
**/
MultisigApproval: AugmentedEvent<ApiType, [AccountId, Timepoint, AccountId, CallHash]>;
/**
* A multisig operation has been cancelled. \[cancelling, timepoint, multisig, call_hash\]
**/
MultisigCancelled: AugmentedEvent<ApiType, [AccountId, Timepoint, AccountId, CallHash]>;
/**
* A multisig operation has been executed. \[approving, timepoint, multisig, call_hash\]
**/
MultisigExecuted: AugmentedEvent<ApiType, [AccountId, Timepoint, AccountId, CallHash, DispatchResult]>;
/**
* A new multisig operation has begun. \[approving, multisig, call_hash\]
**/
NewMultisig: AugmentedEvent<ApiType, [AccountId, AccountId, CallHash]>;
};
offences: {
[key: string]: AugmentedEvent<ApiType>;
/**
* There is an offence reported of the given `kind` happened at the `session_index` and
* (kind-specific) time slot. This event is not deposited for duplicate slashes. last
* element indicates of the offence was applied (true) or queued (false)
* \[kind, timeslot, applied\].
**/
Offence: AugmentedEvent<ApiType, [Kind, OpaqueTimeSlot, bool]>;
};
proxy: {
[key: string]: AugmentedEvent<ApiType>;
/**
* An announcement was placed to make a call in the future. \[real, proxy, call_hash\]
**/
Announced: AugmentedEvent<ApiType, [AccountId, AccountId, Hash]>;
/**
* Anonymous account has been created by new proxy with given
* disambiguation index and proxy type. \[anonymous, who, proxy_type, disambiguation_index\]
**/
AnonymousCreated: AugmentedEvent<ApiType, [AccountId, AccountId, ProxyType, u16]>;
/**
* A proxy was executed correctly, with the given \[result\].
**/
ProxyExecuted: AugmentedEvent<ApiType, [DispatchResult]>;
};
recovery: {
[key: string]: AugmentedEvent<ApiType>;
/**
* Lost account has been successfully recovered by rescuer account.
* \[lost, rescuer\]
**/
AccountRecovered: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/**
* A recovery process for lost account by rescuer account has been closed.
* \[lost, rescuer\]
**/
RecoveryClosed: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/**
* A recovery process has been set up for an \[account\].
**/
RecoveryCreated: AugmentedEvent<ApiType, [AccountId]>;
/**
* A recovery process has been initiated for lost account by rescuer account.
* \[lost, rescuer\]
**/
RecoveryInitiated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/**
* A recovery process has been removed for an \[account\].
**/
RecoveryRemoved: AugmentedEvent<ApiType, [AccountId]>;
/**
* A recovery process for lost account by rescuer account has been vouched for by sender.
* \[lost, rescuer, sender\]
**/
RecoveryVouched: AugmentedEvent<ApiType, [AccountId, AccountId, AccountId]>;
};
scheduler: {
[key: string]: AugmentedEvent<ApiType>;
/**
* Canceled some task. \[when, index\]
**/
Canceled: AugmentedEvent<ApiType, [BlockNumber, u32]>;
/**
* Dispatched some task. \[task, id, result\]
**/
Dispatched: AugmentedEvent<ApiType, [TaskAddress, Option<Bytes>, DispatchResult]>;
/**
* Scheduled some task. \[when, index\]
**/
Scheduled: AugmentedEvent<ApiType, [BlockNumber, u32]>;
};
session: {
[key: string]: AugmentedEvent<ApiType>;
/**
* New session has happened. Note that the argument is the \[session_index\], not the block
* number as the type might suggest.
**/
NewSession: AugmentedEvent<ApiType, [SessionIndex]>;
};
society: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A \[candidate\] was dropped (due to an excess of bids in the system).
**/
AutoUnbid: AugmentedEvent<ApiType, [AccountId]>;
/**
* A membership bid just happened. The given account is the candidate's ID and their offer
* is the second. \[candidate_id, offer\]
**/
Bid: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* A \[candidate\] has been suspended
**/
CandidateSuspended: AugmentedEvent<ApiType, [AccountId]>;
/**
* A \[member\] has been challenged
**/
Challenged: AugmentedEvent<ApiType, [AccountId]>;
/**
* A vote has been placed for a defending member \[voter, vote\]
**/
DefenderVote: AugmentedEvent<ApiType, [AccountId, bool]>;
/**
* Some funds were deposited into the society account. \[value\]
**/
Deposit: AugmentedEvent<ApiType, [Balance]>;
/**
* The society is founded by the given identity. \[founder\]
**/
Founded: AugmentedEvent<ApiType, [AccountId]>;
/**
* A group of candidates have been inducted. The batch's primary is the first value, the
* batch in full is the second. \[primary, candidates\]
**/
Inducted: AugmentedEvent<ApiType, [AccountId, Vec<AccountId>]>;
/**
* A \[member\] has been suspended
**/
MemberSuspended: AugmentedEvent<ApiType, [AccountId]>;
/**
* A new \[max\] member count has been set
**/
NewMaxMembers: AugmentedEvent<ApiType, [u32]>;
/**
* A suspended member has been judged. \[who, judged\]
**/
SuspendedMemberJudgement: AugmentedEvent<ApiType, [AccountId, bool]>;
/**
* A \[candidate\] was dropped (by their request).
**/
Unbid: AugmentedEvent<ApiType, [AccountId]>;
/**
* Society is unfounded. \[founder\]
**/
Unfounded: AugmentedEvent<ApiType, [AccountId]>;
/**
* A \[candidate\] was dropped (by request of who vouched for them).
**/
Unvouch: AugmentedEvent<ApiType, [AccountId]>;
/**
* A vote has been placed \[candidate, voter, vote\]
**/
Vote: AugmentedEvent<ApiType, [AccountId, AccountId, bool]>;
/**
* A membership bid just happened by vouching. The given account is the candidate's ID and
* their offer is the second. The vouching party is the third. \[candidate_id, offer, vouching\]
**/
Vouch: AugmentedEvent<ApiType, [AccountId, Balance, AccountId]>;
};
staking: {
[key: string]: AugmentedEvent<ApiType>;
/**
* An account has bonded this amount. \[stash, amount\]
*
* NOTE: This event is only emitted when funds are bonded via a dispatchable. Notably,
* it will not be emitted for staking rewards when they are added to stake.
**/
Bonded: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* The era payout has been set; the first balance is the validator-payout; the second is
* the remainder from the maximum amount of reward.
* \[era_index, validator_payout, remainder\]
**/
EraPayout: AugmentedEvent<ApiType, [EraIndex, Balance, Balance]>;
/**
* An old slashing report from a prior era was discarded because it could
* not be processed. \[session_index\]
**/
OldSlashingReportDiscarded: AugmentedEvent<ApiType, [SessionIndex]>;
/**
* The staker has been rewarded by this amount. \[stash, amount\]
**/
Reward: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* One validator (and its nominators) has been slashed by the given amount.
* \[validator, amount\]
**/
Slash: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* A new solution for the upcoming election has been stored. \[compute\]
**/
SolutionStored: AugmentedEvent<ApiType, [ElectionCompute]>;
/**
* A new set of stakers was elected with the given \[compute\].
**/
StakingElection: AugmentedEvent<ApiType, [ElectionCompute]>;
/**
* An account has unbonded this amount. \[stash, amount\]
**/
Unbonded: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* An account has called `withdraw_unbonded` and removed unbonding chunks worth `Balance`
* from the unlocking queue. \[stash, amount\]
**/
Withdrawn: AugmentedEvent<ApiType, [AccountId, Balance]>;
};
sudo: {
[key: string]: AugmentedEvent<ApiType>;
/**
* The \[sudoer\] just switched identity; the old key is supplied.
**/
KeyChanged: AugmentedEvent<ApiType, [AccountId]>;
/**
* A sudo just took place. \[result\]
**/
Sudid: AugmentedEvent<ApiType, [DispatchResult]>;
/**
* A sudo just took place. \[result\]
**/
SudoAsDone: AugmentedEvent<ApiType, [DispatchResult]>;
};
system: {
[key: string]: AugmentedEvent<ApiType>;
/**
* `:code` was updated.
**/
CodeUpdated: AugmentedEvent<ApiType, []>;
/**
* An extrinsic failed. \[error, info\]
**/
ExtrinsicFailed: AugmentedEvent<ApiType, [DispatchError, DispatchInfo]>;
/**
* An extrinsic completed successfully. \[info\]
**/
ExtrinsicSuccess: AugmentedEvent<ApiType, [DispatchInfo]>;
/**
* An \[account\] was reaped.
**/
KilledAccount: AugmentedEvent<ApiType, [AccountId]>;
/**
* A new \[account\] was created.
**/
NewAccount: AugmentedEvent<ApiType, [AccountId]>;
};
technicalCommittee: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A motion was approved by the required threshold.
* \[proposal_hash\]
**/
Approved: AugmentedEvent<ApiType, [Hash]>;
/**
* A proposal was closed because its threshold was reached or after its duration was up.
* \[proposal_hash, yes, no\]
**/
Closed: AugmentedEvent<ApiType, [Hash, MemberCount, MemberCount]>;
/**
* A motion was not approved by the required threshold.
* \[proposal_hash\]
**/
Disapproved: AugmentedEvent<ApiType, [Hash]>;
/**
* A motion was executed; result will be `Ok` if it returned without error.
* \[proposal_hash, result\]
**/
Executed: AugmentedEvent<ApiType, [Hash, DispatchResult]>;
/**
* A single member did some action; result will be `Ok` if it returned without error.
* \[proposal_hash, result\]
**/
MemberExecuted: AugmentedEvent<ApiType, [Hash, DispatchResult]>;
/**
* A motion (given hash) has been proposed (by given account) with a threshold (given
* `MemberCount`).
* \[account, proposal_index, proposal_hash, threshold\]
**/
Proposed: AugmentedEvent<ApiType, [AccountId, ProposalIndex, Hash, MemberCount]>;
/**
* A motion (given hash) has been voted on by given account, leaving
* a tally (yes votes and no votes given respectively as `MemberCount`).
* \[account, proposal_hash, voted, yes, no\]
**/
Voted: AugmentedEvent<ApiType, [AccountId, Hash, bool, MemberCount, MemberCount]>;
};
technicalMembership: {
[key: string]: AugmentedEvent<ApiType>;
/**
* Phantom member, never used.
**/
Dummy: AugmentedEvent<ApiType, [PhantomData]>;
/**
* One of the members' keys changed.
**/
KeyChanged: AugmentedEvent<ApiType, []>;
/**
* The given member was added; see the transaction for who.
**/
MemberAdded: AugmentedEvent<ApiType, []>;
/**
* The given member was removed; see the transaction for who.
**/
MemberRemoved: AugmentedEvent<ApiType, []>;
/**
* The membership was reset; see the transaction for who the new set is.
**/
MembersReset: AugmentedEvent<ApiType, []>;
/**
* Two members were swapped; see the transaction for who.
**/
MembersSwapped: AugmentedEvent<ApiType, []>;
};
tips: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A new tip suggestion has been opened. \[tip_hash\]
**/
NewTip: AugmentedEvent<ApiType, [Hash]>;
/**
* A tip suggestion has been closed. \[tip_hash, who, payout\]
**/
TipClosed: AugmentedEvent<ApiType, [Hash, AccountId, Balance]>;
/**
* A tip suggestion has reached threshold and is closing. \[tip_hash\]
**/
TipClosing: AugmentedEvent<ApiType, [Hash]>;
/**
* A tip suggestion has been retracted. \[tip_hash\]
**/
TipRetracted: AugmentedEvent<ApiType, [Hash]>;
};
treasury: {
[key: string]: AugmentedEvent<ApiType>;
/**
* Some funds have been allocated. \[proposal_index, award, beneficiary\]
**/
Awarded: AugmentedEvent<ApiType, [ProposalIndex, Balance, AccountId]>;
/**
* Some of our funds have been burnt. \[burn\]
**/
Burnt: AugmentedEvent<ApiType, [Balance]>;
/**
* Some funds have been deposited. \[deposit\]
**/
Deposit: AugmentedEvent<ApiType, [Balance]>;
/**
* New proposal. \[proposal_index\]
**/
Proposed: AugmentedEvent<ApiType, [ProposalIndex]>;
/**
* A proposal was rejected; funds were slashed. \[proposal_index, slashed\]
**/
Rejected: AugmentedEvent<ApiType, [ProposalIndex, Balance]>;
/**
* Spending has finished; this is the amount that rolls over until next spend.
* \[budget_remaining\]
**/
Rollover: AugmentedEvent<ApiType, [Balance]>;
/**
* We have ended a spend period and will now allocate funds. \[budget_remaining\]
**/
Spending: AugmentedEvent<ApiType, [Balance]>;
};
utility: {
[key: string]: AugmentedEvent<ApiType>;
/**
* Batch of dispatches completed fully with no error.
**/
BatchCompleted: AugmentedEvent<ApiType, []>;
/**
* Batch of dispatches did not complete fully. Index of first failing dispatch given, as
* well as the error. \[index, error\]
**/
BatchInterrupted: AugmentedEvent<ApiType, [u32, DispatchError]>;
};
vesting: {
[key: string]: AugmentedEvent<ApiType>;
/**
* An \[account\] has become fully vested. No further vesting can happen.
**/
VestingCompleted: AugmentedEvent<ApiType, [AccountId]>;
/**
* The amount vested has been updated. This could indicate more funds are available. The
* balance given is the amount which is left unvested (and thus locked).
* \[account, unvested\]
**/
VestingUpdated: AugmentedEvent<ApiType, [AccountId, Balance]>;
};
}
export interface DecoratedEvents<ApiType extends ApiTypes> extends AugmentedEvents<ApiType> {
[key: string]: ModuleEvents<ApiType>;
}
}
+2
View File
@@ -2,6 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
import './consts';
import './errors';
import './events';
import './query';
import './rpc';
import './tx';
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+15 -2
View File
@@ -6,9 +6,9 @@ import type { RpcInterface } from '@polkadot/rpc-core/types';
import type { Option, Raw, StorageKey, Text, u64 } from '@polkadot/types';
import type { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import type { StorageEntry } from '@polkadot/types/primitive/types';
import type { AnyFunction, CallFunction, Codec, CodecArg as Arg, DefinitionRpc, DefinitionRpcSub, InterfaceTypes, Registry, RegistryTypes } from '@polkadot/types/types';
import type { AnyFunction, AnyTuple, CallFunction, Codec, CodecArg as Arg, DefinitionRpc, DefinitionRpcSub, IMethod, InterfaceTypes, IStorageKey, Registry, RegistryTypes } from '@polkadot/types/types';
import type { SubmittableExtrinsic } from '../submittable/types';
import type { ApiInterfaceRx, ApiOptions, ApiTypes, DecoratedRpc, DecoratedRpcSection, DecorateMethod, PaginationOptions, QueryableConsts, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
import type { ApiInterfaceRx, ApiOptions, ApiTypes, DecoratedErrors, DecoratedEvents, DecoratedRpc, DecoratedRpcSection, DecorateMethod, PaginationOptions, QueryableConsts, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
import BN from 'bn.js';
@@ -57,6 +57,10 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
protected _derive?: ReturnType<Decorate<ApiType>['_decorateDerive']>;
protected _errors: DecoratedErrors<ApiType> = {} as DecoratedErrors<ApiType>;
protected _events: DecoratedEvents<ApiType> = {} as DecoratedEvents<ApiType>;
protected _extrinsics?: SubmittableExtrinsics<ApiType>;
protected _extrinsicType: number = EXTRINSIC_DEFAULT_VERSION;
@@ -195,6 +199,8 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
// this API
augmentObject('query', this._decorateStorage(decoratedMeta, this._decorateMethod), this._query, fromEmpty);
augmentObject('consts', decoratedMeta.consts, this._consts, fromEmpty);
augmentObject('errors', decoratedMeta.errors, this._errors, fromEmpty);
augmentObject('events', decoratedMeta.events, this._events, fromEmpty);
// rx
augmentObject(null, this._decorateStorage(decoratedMeta, this._rxDecorateMethod), this._rx.query, fromEmpty);
@@ -338,6 +344,10 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const decorated = (...params: Arg[]): SubmittableExtrinsic<ApiType> =>
creator(method(...params));
// pass through the `.is`
decorated.is = (other: IMethod<AnyTuple>) =>
method.is(other);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this._decorateFunctionMeta(method as any, decorated as any) as unknown as SubmittableExtrinsicFunction<ApiType>;
}
@@ -371,6 +381,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
decorated.hash = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<Hash> =>
this._rpcCore.state.getStorageHash(getArgs(arg1, arg2)));
decorated.is = <A extends AnyTuple> (key: IStorageKey<AnyTuple>): key is IStorageKey<A> =>
key.section === creator.section && key.method === creator.method;
decorated.key = (arg1?: Arg, arg2?: Arg): string =>
u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]);
+15 -1
View File
@@ -5,7 +5,7 @@ import type { Metadata } from '@polkadot/metadata';
import type { RpcInterface } from '@polkadot/rpc-core/types';
import type { Text } from '@polkadot/types';
import type { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import type { ApiInterfaceRx, ApiTypes, DecoratedRpc, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics } from '../types';
import type { ApiInterfaceRx, ApiTypes, DecoratedErrors, DecoratedEvents, DecoratedRpc, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics } from '../types';
import { assertReturn } from '@polkadot/util';
@@ -54,6 +54,20 @@ export abstract class Getters<ApiType extends ApiTypes> extends Init<ApiType> {
return assertResult(this._derive);
}
/**
* @description Errors from metadata
*/
public get errors (): DecoratedErrors<ApiType> {
return assertResult(this._errors);
}
/**
* @description Events from metadata
*/
public get events (): DecoratedEvents<ApiType> {
return assertResult(this._events);
}
/**
* @description Returns the version of extrinsics in-use on this chain
*/
+57 -3
View File
@@ -3,8 +3,9 @@
// Simple non-runnable checks to test type definitions in the editor itself
import type { AccountId, Balance, Header, Index } from '@polkadot/types/interfaces';
import type { IExtrinsic, IMethod } from '@polkadot/types/types';
import type { StorageKey } from '@polkadot/types';
import type { AccountId, Balance, DispatchError, EventRecord, Header, Index } from '@polkadot/types/interfaces';
import type { AnyTuple, IExtrinsic, IMethod } from '@polkadot/types/types';
import { ApiPromise } from '@polkadot/api';
import { HeaderExtended } from '@polkadot/api-derive';
@@ -34,6 +35,39 @@ async function derive (api: ApiPromise): Promise<void> {
console.log('fees', fees);
}
function errors (api: ApiPromise): void {
const someError = {} as DispatchError;
// existing
console.log(api.errors.vesting.AmountLow.is(someError));
// non-existing error, existing module
console.log(api.errors.vesting.Something.is(someError));
// something random
console.log(api.errors.something.Random.is(someError));
}
function events (api: ApiPromise): void {
const eventRecord = {} as EventRecord;
// existing
if (api.events.balances.Transfer.is(eventRecord)) {
// the types are correctly expanded
const [from, to, amount] = eventRecord.event.data;
console.log(from.toHuman(), to.toHuman(), amount.toBn());
}
// something random
if (api.events.something.Random.is(eventRecord)) {
// the types are just codec
const [a, b] = eventRecord.event.data;
console.log(a.toHuman(), b.toHuman());
}
}
async function query (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
const intentions = await api.query.staking.bonded();
@@ -102,6 +136,16 @@ async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise<void
const entries = await api.query.system.events.range(['0x12345', '0x7890']);
console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`).join(', ')}`);
// is
const key = {} as StorageKey;
if (api.query.balances.account.is(key)) {
const [accountId] = key.args;
// should be AccountId type
console.log(accountId.toHuman());
}
}
async function rpc (api: ApiPromise): Promise<void> {
@@ -143,7 +187,7 @@ async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
// transfer, also allows for BigInt inputs here
const transfer = api.tx.balances.transfer(pairs.bob.address, 123456789n);
console.log('transfer casted', transfer as IMethod, transfer as IExtrinsic);
console.log('transfer casted', transfer as IMethod<AnyTuple>, transfer as IExtrinsic<AnyTuple>);
// simple "return the hash" variant
console.log('hash:', (await transfer.signAndSend(pairs.alice)).toHex());
@@ -179,6 +223,14 @@ async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
// it handles enum inputs correctly
await api.tx.democracy.proxyVote(123, { Split: { nay: 456, yay: 123 } }).signAndSend(pairs.alice);
// is
if (api.tx.balances.transfer.is(second)) {
const [recipientId, balance] = second.args;
// should be LookupSource & Balance types
console.log(recipientId.toHuman(), balance.toNumber());
}
}
async function main (): Promise<void> {
@@ -189,6 +241,8 @@ async function main (): Promise<void> {
Promise.all([
consts(api),
derive(api),
errors(api),
events(api),
query(api, pairs),
queryExtra(api, pairs),
rpc(api),
+16
View File
@@ -0,0 +1,16 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { IsError } from '@polkadot/metadata/decorate/types';
import type { ApiTypes } from './base';
// In errors we don't need the ApiType, however add it for consistency
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedErrors<ApiType extends ApiTypes> { }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type AugmentedError<ApiType extends ApiTypes> = IsError;
export interface ModuleErrors<ApiType extends ApiTypes> {
[key: string]: AugmentedError<ApiType>;
}
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { IsEvent } from '@polkadot/metadata/decorate/types';
import type { AnyTuple } from '@polkadot/types/types';
import type { ApiTypes } from './base';
// In events we don't need the ApiType, however add it for consistency
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedEvents<ApiType extends ApiTypes> { }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type AugmentedEvent<ApiType extends ApiTypes, T extends AnyTuple = AnyTuple> = IsEvent<T>;
export interface ModuleEvents<ApiType extends ApiTypes> {
[key: string]: AugmentedEvent<ApiType, AnyTuple>;
}
+2
View File
@@ -23,6 +23,8 @@ export { ApiBase } from '../base';
export * from '../submittable/types';
export * from './base';
export * from './consts';
export * from './errors';
export * from './events';
export * from './rpc';
export * from './storage';
export * from './submittable';
+10 -9
View File
@@ -4,7 +4,7 @@
import type { StorageKey, u64 } from '@polkadot/types';
import type { Hash } from '@polkadot/types/interfaces';
import type { StorageEntry } from '@polkadot/types/primitive/types';
import type { AnyFunction, Callback, Codec, CodecArg } from '@polkadot/types/types';
import type { AnyFunction, AnyTuple, Callback, Codec, CodecArg, IStorageKey } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs';
import type { ApiTypes, MethodResult, ObsInnerType, PaginationOptions, PromiseOrObs, UnsubscribePromise } from './base';
@@ -28,20 +28,21 @@ export interface StorageEntryPromiseOverloads {
// This is the most generic typings we can have for a storage entry function
type GenericStorageEntryFunction = (arg1?: CodecArg, arg2?: CodecArg) => Observable<Codec>
export type QueryableStorageEntry<ApiType extends ApiTypes> =
export type QueryableStorageEntry<ApiType extends ApiTypes, A extends AnyTuple = AnyTuple> =
ApiType extends 'rxjs'
// eslint-disable-next-line no-use-before-define
? AugmentedQuery<'rxjs', GenericStorageEntryFunction>
? AugmentedQuery<'rxjs', GenericStorageEntryFunction, A>
// eslint-disable-next-line no-use-before-define
: AugmentedQuery<'promise', GenericStorageEntryFunction> & StorageEntryPromiseOverloads;
: AugmentedQuery<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloads;
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction> {
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple> {
at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>;
creator: StorageEntry;
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, T][]>;
entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, T][]>;
entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey, T][]>;
hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>;
is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>;
key: (...args: Parameters<F>) => string;
keyPrefix: () => string;
keys: (arg?: any) => PromiseOrObs<ApiType, StorageKey[]>;
@@ -55,7 +56,7 @@ export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunctio
}
export interface QueryableModuleStorage<ApiType extends ApiTypes> {
[index: string]: QueryableStorageEntry<ApiType>;
[index: string]: QueryableStorageEntry<ApiType, AnyTuple>;
}
export type QueryableStorageMultiArg<ApiType extends ApiTypes> =
@@ -79,10 +80,10 @@ export type QueryableStorageMulti<ApiType extends ApiTypes> =
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedQueries<ApiType extends ApiTypes> { }
export interface StorageEntryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction> extends StorageEntryBase<ApiType, F> {
export interface StorageEntryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple> extends StorageEntryBase<ApiType, F, A> {
keyPrefix: (key1?: Parameters<F>[0]) => string;
}
export type AugmentedQuery<ApiType extends ApiTypes, F extends AnyFunction> = MethodResult<ApiType, F> & StorageEntryBase<ApiType, F>
export type AugmentedQuery<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> = MethodResult<ApiType, F> & StorageEntryBase<ApiType, F, A>;
export type AugmentedQueryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction> = MethodResult<ApiType, F> & StorageEntryDoubleMap<ApiType, F>
export type AugmentedQueryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> = MethodResult<ApiType, F> & StorageEntryDoubleMap<ApiType, F, A>;
+5 -4
View File
@@ -1,19 +1,20 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { AnyFunction, CallBase } from '@polkadot/types/types';
import type { AnyFunction, AnyTuple, CallBase } from '@polkadot/types/types';
import type { SubmittableExtrinsic } from '../submittable/types';
import type { ApiTypes } from './base';
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedSubmittables<ApiType extends ApiTypes> { }
export type AugmentedSubmittable<T extends AnyFunction> = T & CallBase;
export type AugmentedSubmittable<T extends AnyFunction, A extends AnyTuple = AnyTuple> = T & CallBase<A>;
export interface SubmittableExtrinsicFunction<ApiType extends ApiTypes> extends CallBase {
export interface SubmittableExtrinsicFunction<ApiType extends ApiTypes, A extends AnyTuple = AnyTuple> extends CallBase<A> {
(...params: any[]): SubmittableExtrinsic<ApiType>;
}
export interface SubmittableModuleExtrinsics<ApiType extends ApiTypes> {
[index: string]: SubmittableExtrinsicFunction<ApiType>;
// only with is<Type> augmentation
[index: string]: SubmittableExtrinsicFunction<ApiType>; // | AugmentedIsSubmittable<ApiType, AnyTuple>;
}
@@ -20,7 +20,7 @@ function init (meta: string): [Constants, TypeRegistry] {
return [decorateConstants(registry, metadata.asLatest), registry];
}
describe('fromMetadata', (): void => {
describe('decorateConstants', (): void => {
it('should return constants with the correct type and value', (): void => {
const [consts, registry] = init(rpcMetadata);
@@ -9,21 +9,19 @@ import { hexToU8a, stringCamelCase } from '@polkadot/util';
/** @internal */
export function decorateConstants (registry: Registry, { modules }: MetadataLatest): Constants {
return modules.reduce((result: Constants, moduleMetadata): Constants => {
if (moduleMetadata.constants.isEmpty) {
return modules.reduce((result: Constants, { constants, name }): Constants => {
if (constants.isEmpty) {
return result;
}
const { name } = moduleMetadata;
// For access, we change the index names, i.e. Democracy.EnactmentPeriod -> democracy.enactmentPeriod
result[stringCamelCase(name)] = moduleMetadata.constants.reduce((newModule: ModuleConstants, meta): ModuleConstants => {
result[stringCamelCase(name)] = constants.reduce((newModule: ModuleConstants, meta): ModuleConstants => {
// convert to the natural type as received
const type = meta.type.toString();
const codec = registry.createType(type as 'Raw', hexToU8a(meta.value.toHex())) as unknown as ConstantCodec;
const codec = registry.createType(type as 'Raw', hexToU8a(meta.value.toHex())) as unknown;
codec.meta = meta;
newModule[stringCamelCase(meta.name)] = codec;
(codec as Record<string, unknown>).meta = meta;
newModule[stringCamelCase(meta.name)] = codec as ConstantCodec;
return newModule;
}, {} as ModuleConstants);
@@ -0,0 +1,42 @@
// Copyright 2017-2020 @polkadot/metadata authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { DispatchError, MetadataLatest } from '@polkadot/types/interfaces';
import type { Registry } from '@polkadot/types/types';
import type { Errors, ModuleErrors } from '../types';
import { stringCamelCase } from '@polkadot/util';
function isError (dispatchError: DispatchError, sectionIndex: number, errorIndex: number): boolean {
if (!dispatchError.isModule) {
return false;
}
const { error, index } = dispatchError.asModule;
return index.eq(sectionIndex) && error.eq(errorIndex);
}
/** @internal */
export function decorateErrors (_: Registry, { modules }: MetadataLatest, metaVersion: number): Errors {
return modules.reduce((result: Errors, { errors, index, name }, _sectionIndex): Errors => {
if (!errors.length) {
return result;
}
const sectionIndex = metaVersion === 12 ? index.toNumber() : _sectionIndex;
result[stringCamelCase(name)] = errors.reduce((newModule: ModuleErrors, meta, errorIndex): ModuleErrors => {
// we don't camelCase the error name
newModule[meta.name.toString()] = {
is: (dispatchError: DispatchError): boolean =>
isError(dispatchError, sectionIndex, errorIndex),
meta
};
return newModule;
}, {} as ModuleErrors);
return result;
}, {} as Errors);
}
@@ -0,0 +1,36 @@
// Copyright 2017-2020 @polkadot/metadata authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { MetadataLatest } from '@polkadot/types/interfaces';
import type { AnyTuple, IEventRecord, Registry } from '@polkadot/types/types';
import type { Events, ModuleEvents } from '../types';
import { stringCamelCase } from '@polkadot/util';
function isEvent <T extends AnyTuple> (eventRecord: IEventRecord<AnyTuple>, sectionIndex: number, eventIndex: number): eventRecord is IEventRecord<T> {
return eventRecord.event.index[0] === sectionIndex && eventRecord.event.index[0] === eventIndex;
}
/** @internal */
export function decorateEvents (_: Registry, { modules }: MetadataLatest, metaVersion: number): Events {
return modules.reduce((result: Events, { events, index, name }, _sectionIndex): Events => {
if (!events.isSome) {
return result;
}
const sectionIndex = metaVersion === 12 ? index.toNumber() : _sectionIndex;
result[stringCamelCase(name)] = events.unwrap().reduce((newModule: ModuleEvents, meta, eventIndex): ModuleEvents => {
// we don't camelCase the event name
newModule[meta.name.toString()] = {
is: <T extends AnyTuple> (eventRecord: IEventRecord<AnyTuple>): eventRecord is IEventRecord<T> =>
isEvent(eventRecord, sectionIndex, eventIndex),
meta
};
return newModule;
}, {} as ModuleEvents);
return result;
}, {} as Events);
}
@@ -2,10 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
import type { Call, FunctionMetadataLatest } from '@polkadot/types/interfaces';
import type { AnyJson, CallFunction, Registry } from '@polkadot/types/types';
import type { AnyJson, AnyTuple, CallFunction, IMethod, Registry } from '@polkadot/types/types';
import { assert, stringCamelCase } from '@polkadot/util';
function isTx <A extends AnyTuple> (tx: IMethod<AnyTuple>, callIndex: Uint8Array): tx is IMethod<A> {
return tx.callIndex[0] === callIndex[0] && tx.callIndex[1] === callIndex[1];
}
/** @internal */
export function createUnchecked (registry: Registry, section: string, callIndex: Uint8Array, callMetadata: FunctionMetadataLatest): CallFunction {
const expectedArgs = callMetadata.args;
@@ -20,6 +24,9 @@ export function createUnchecked (registry: Registry, section: string, callIndex:
}, callMetadata);
};
extrinsicFn.is = <A extends AnyTuple> (tx: IMethod<AnyTuple>): tx is IMethod<A> =>
isTx(tx, callIndex);
extrinsicFn.callIndex = callIndex;
extrinsicFn.meta = callMetadata;
extrinsicFn.method = funcName;
@@ -16,7 +16,7 @@ const metadata = new Metadata(registry, metadataStatic);
registry.setMetadata(metadata);
const extrinsics = decorateExtrinsics(registry, metadata.asLatest);
const extrinsics = decorateExtrinsics(registry, metadata.asLatest, metadata.version);
describe('extrinsics', (): void => {
it('encodes an actual transfer (actual data)', (): void => {
@@ -53,7 +53,7 @@ describe('extrinsics', (): void => {
});
});
describe('fromMetadata', (): void => {
describe('decorateExtrinsics', (): void => {
it('should throw if an incorrect number of args is supplied', (): void => {
expect(() => extrinsics.balances.setBalance()).toThrowError(/expects 3 arguments/);
});
@@ -78,4 +78,11 @@ describe('fromMetadata', (): void => {
])
);
});
it('has working .is', (): void => {
const tx = extrinsics.balances.setBalance('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF', 2, 3);
expect(extrinsics.balances.setBalance.is(tx)).toBe(true);
expect(extrinsics.balances.transfer.is(tx)).toBe(false);
});
});
@@ -10,13 +10,11 @@ import { stringCamelCase } from '@polkadot/util';
import { createUnchecked } from './createUnchecked';
/** @internal */
export function decorateExtrinsics (registry: Registry, { modules }: MetadataLatest): Extrinsics {
const isIndexed = modules.some(({ index }) => !index.eqn(255));
export function decorateExtrinsics (registry: Registry, { modules }: MetadataLatest, metaVersion: number): Extrinsics {
return modules
.filter(({ calls }) => calls.isSome)
.reduce((result: Extrinsics, { calls, index, name }, _sectionIndex): Extrinsics => {
const sectionIndex = isIndexed
const sectionIndex = metaVersion === 12
? index.toNumber()
: _sectionIndex;
const section = stringCamelCase(name);
+1 -1
View File
@@ -27,7 +27,7 @@ describe('Decorated', () => {
});
it('should return properly-encoded transactions', (): void => {
const tx = decorateExtrinsics(registry, metadata.asLatest);
const tx = decorateExtrinsics(registry, metadata.asLatest, metadata.version);
expect(
registry.createType('Extrinsic', tx.timestamp.set([10101])).toU8a()
+5 -1
View File
@@ -8,6 +8,8 @@ import { assert } from '@polkadot/util';
import { Metadata } from '../Metadata';
import { decorateConstants } from './constants';
import { decorateErrors } from './errors';
import { decorateEvents } from './events';
import { decorateExtrinsics } from './extrinsics';
import { decorateStorage } from './storage';
@@ -21,8 +23,10 @@ export function expandMetadata (registry: Registry, metadata: Metadata): Decorat
return {
consts: decorateConstants(registry, latest),
errors: decorateErrors(registry, latest, metadata.version),
events: decorateEvents(registry, latest, metadata.version),
query: decorateStorage(registry, latest, metadata.version),
tx: decorateExtrinsics(registry, latest)
tx: decorateExtrinsics(registry, latest, metadata.version)
};
}
@@ -11,7 +11,7 @@ import { decorateStorage } from '..';
const keyring = createTestPairs({ type: 'ed25519' });
describe('fromMetadata', (): void => {
describe('decorateStorage', (): void => {
describe('latest', (): void => {
const registry = new TypeRegistry();
const metadata = new Metadata(registry, rpcMetadata);
+29 -7
View File
@@ -1,15 +1,31 @@
// Copyright 2017-2020 @polkadot/metadata authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ModuleConstantMetadataLatest } from '@polkadot/types/interfaces';
import type { DispatchError, ErrorMetadataLatest, EventMetadataLatest, ModuleConstantMetadataLatest } from '@polkadot/types/interfaces';
import type { StorageEntry } from '@polkadot/types/primitive/types';
import type { CallFunction, Codec } from '@polkadot/types/types';
import type { AnyTuple, CallFunction, Codec, IEventRecord } from '@polkadot/types/types';
export interface ConstantCodec extends Codec {
meta: ModuleConstantMetadataLatest;
readonly meta: ModuleConstantMetadataLatest;
}
export type ModuleConstants = Record<string, ConstantCodec>
export interface IsError {
readonly meta: ErrorMetadataLatest;
is: (dispatchError: DispatchError) => boolean;
}
export interface IsEvent <T extends AnyTuple> {
readonly meta: EventMetadataLatest;
is: (record: IEventRecord<AnyTuple>) => record is IEventRecord<T>;
}
export type ModuleConstants = Record<string, ConstantCodec>;
export type ModuleErrors = Record<string, IsError>;
export type ModuleEvents = Record<string, IsEvent<AnyTuple>>;
export type ModuleExtrinsics = Record<string, CallFunction>;
@@ -17,12 +33,18 @@ export type ModuleStorage = Record<string, StorageEntry>
export type Constants = Record<string, ModuleConstants>;
export type Errors = Record<string, ModuleErrors>;
export type Events = Record<string, ModuleEvents>;
export type Extrinsics = Record<string, ModuleExtrinsics>
export type Storage = Record<string, ModuleStorage>;
export interface DecoratedMeta {
consts: Constants;
query: Storage;
tx: Extrinsics
readonly consts: Constants;
readonly errors: Errors;
readonly events: Events;
readonly query: Storage;
readonly tx: Extrinsics
}
+4 -2
View File
@@ -7,7 +7,7 @@ import yargs from 'yargs';
import { formatNumber } from '@polkadot/util';
import { WebSocket } from '@polkadot/x-ws';
import { generateDefaultConsts, generateDefaultQuery, generateDefaultRpc, generateDefaultTx } from './generate';
import { generateDefaultConsts, generateDefaultErrors, generateDefaultEvents, generateDefaultQuery, generateDefaultRpc, generateDefaultTx } from './generate';
import { HEADER, writeFile } from './util';
function generate (metaHex: string, pkg: string | undefined, output: string, isStrict?: boolean): void {
@@ -19,6 +19,8 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS
: {};
generateDefaultConsts(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict);
generateDefaultErrors(path.join(process.cwd(), output, 'augment-api-errors.ts'), metaHex, isStrict);
generateDefaultEvents(path.join(process.cwd(), output, 'augment-api-events.ts'), metaHex, extraTypes, isStrict);
generateDefaultQuery(path.join(process.cwd(), output, 'augment-api-query.ts'), metaHex, extraTypes, isStrict);
generateDefaultRpc(path.join(process.cwd(), output, 'augment-api-rpc.ts'), extraTypes);
generateDefaultTx(path.join(process.cwd(), output, 'augment-api-tx.ts'), metaHex, extraTypes, isStrict);
@@ -28,7 +30,7 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS
HEADER('chain'),
...[
'@polkadot/api/augment/rpc',
...['consts', 'query', 'tx', 'rpc'].filter((key) => !!key).map((key) => `./augment-api-${key}`)
...['consts', 'errors', 'events', 'query', 'tx', 'rpc'].filter((key) => !!key).map((key) => `./augment-api-${key}`)
].map((path) => `import '${path}';\n`)
].join('')
);
+60
View File
@@ -0,0 +1,60 @@
// Copyright 2017-2020 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import Handlebars from 'handlebars';
import { Metadata } from '@polkadot/metadata/Metadata';
import staticData from '@polkadot/metadata/static';
import { TypeRegistry } from '@polkadot/types/create';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, readTemplate, writeFile } from '../util';
const template = readTemplate('errors');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (meta: Metadata, dest: string, isStrict: boolean): void {
writeFile(dest, (): string => {
const imports = createImports({});
const modules = meta.asLatest.modules
.sort(compareName)
.filter((mod) => mod.errors.length > 0)
.map(({ errors, name }) => ({
items: errors
.sort(compareName)
.map(({ documentation, name }) => ({
docs: documentation,
name: name.toString()
})),
name: stringCamelCase(name)
}));
const types = [
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
];
return generateForMetaTemplate({
headerType: 'chain',
imports,
isStrict,
modules,
types
});
});
}
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultErrors (dest = 'packages/api/src/augment/errors.ts', data = staticData, isStrict = false): void {
const registry = new TypeRegistry();
const metadata = new Metadata(registry, data);
registry.setMetadata(metadata);
return generateForMeta(metadata, dest, isStrict);
}
+80
View File
@@ -0,0 +1,80 @@
// Copyright 2017-2020 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import Handlebars from 'handlebars';
import { Metadata } from '@polkadot/metadata/Metadata';
import staticData from '@polkadot/metadata/static';
import { TypeRegistry } from '@polkadot/types/create';
import * as defaultDefs from '@polkadot/types/interfaces/definitions';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, formatType, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
const template = readTemplate('events');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>>, isStrict: boolean): void {
writeFile(dest, (): string => {
const allTypes: Record<string, Record<string, { types: Record<string, unknown> }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const imports = createImports(allTypes);
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
}, {});
const modules = meta.asLatest.modules
.sort(compareName)
.filter((mod) => mod.events.isSome)
.map(({ events, name }) => ({
items: events
.unwrap()
.sort(compareName)
.map(({ args, documentation, name }) => {
const types = args.map((type) => formatType(allDefs, type.toString(), imports));
setImports(allDefs, imports, types);
return {
docs: documentation,
name: name.toString(),
type: types.join(', ')
};
}),
name: stringCamelCase(name)
}));
const types = [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
];
return generateForMetaTemplate({
headerType: 'chain',
imports,
isStrict,
modules,
types
});
});
}
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data = staticData, extraTypes: Record<string, Record<string, { types: Record<string, any> }>> = {}, isStrict = false): void {
const registry = new TypeRegistry();
registerDefinitions(registry, extraTypes);
const metadata = new Metadata(registry, data);
registry.setMetadata(metadata);
return generateForMeta(metadata, dest, extraTypes, isStrict);
}
+2
View File
@@ -2,6 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
export { generateDefaultConsts } from './consts';
export { generateDefaultErrors } from './errors';
export { generateDefaultEvents } from './events';
export { generateDefaultInterface } from './interfaceRegistry';
export { generateDefaultQuery } from './query';
export { generateDefaultRpc } from './rpc';
+6 -3
View File
@@ -18,13 +18,13 @@ import { ModuleTypes } from '../util/imports';
// From a storage entry metadata, we return [args, returnType]
/** @internal */
function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] {
function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string, string] {
const outputType = unwrapStorageType(storageEntry.type, storageEntry.modifier.isOptional);
if (storageEntry.type.isPlain) {
setImports(allDefs, imports, [storageEntry.type.asPlain.toString()]);
return ['', formatType(allDefs, outputType, imports)];
return ['', '', formatType(allDefs, outputType, imports)];
} else if (storageEntry.type.isMap) {
// Find similar types of the `key` type
const similarTypes = getSimilarTypes(registry, allDefs, storageEntry.type.asMap.key.toString(), imports);
@@ -35,6 +35,7 @@ function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registr
]);
return [
formatType(allDefs, storageEntry.type.asMap.key.toString(), imports),
`arg: ${similarTypes.join(' | ')}`,
formatType(allDefs, outputType, imports)
];
@@ -53,6 +54,7 @@ function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registr
const key2Types = similarTypes2.join(' | ');
return [
[formatType(allDefs, storageEntry.type.asDoubleMap.key1.toString(), imports), formatType(allDefs, storageEntry.type.asDoubleMap.key2.toString(), imports)].join(', '),
`key1: ${key1Types}, key2: ${key2Types}`,
formatType(allDefs, outputType, imports)
];
@@ -80,7 +82,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
const items = storage.unwrap().items
.sort(compareName)
.map((storageEntry) => {
const [args, returnType] = entrySignature(allDefs, registry, storageEntry, imports);
const [args, params, returnType] = entrySignature(allDefs, registry, storageEntry, imports);
let entryType = 'AugmentedQuery';
if (storageEntry.type.isDoubleMap) {
@@ -92,6 +94,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
docs: storageEntry.documentation,
entryType,
name: stringCamelCase(storageEntry.name),
params,
returnType
};
});
+2 -1
View File
@@ -12,7 +12,7 @@ import * as defaultDefs from '@polkadot/types/interfaces/definitions';
import { Text } from '@polkadot/types/primitive';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
import { compareName, createImports, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
const MAPPED_NAMES: Record<string, string> = {
new: 'updated'
@@ -57,6 +57,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
.join(', ');
return {
args: args.map(({ type }) => formatType(allDefs, type.toString(), imports)).join(', '),
docs: documentation,
name: stringCamelCase(name),
params
+3 -1
View File
@@ -1,12 +1,14 @@
// Copyright 2017-2020 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { generateDefaultConsts, generateDefaultInterface, generateDefaultQuery, generateDefaultRpc, generateDefaultTsDef, generateDefaultTx } from './generate';
import { generateDefaultConsts, generateDefaultErrors, generateDefaultEvents, generateDefaultInterface, generateDefaultQuery, generateDefaultRpc, generateDefaultTsDef, generateDefaultTx } from './generate';
export function main (): void {
generateDefaultInterface();
generateDefaultConsts();
generateDefaultErrors();
generateDefaultEvents();
generateDefaultQuery();
generateDefaultTx();
generateDefaultRpc();
+26
View File
@@ -0,0 +1,26 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/api/types/errors' {
export interface AugmentedErrors<ApiType> {
{{#each modules}}
{{{name}}}: {
{{#unless @root.isStrict}}
[key: string]: AugmentedError<ApiType>;
{{/unless}}
{{~#each items}}
{{> docs}}
{{{name}}}: AugmentedError<ApiType>;
{{/each}}
};
{{/each}}
}
export interface DecoratedErrors<ApiType extends ApiTypes> extends AugmentedErrors<ApiType> {
{{#unless isStrict}}
[key: string]: ModuleErrors<ApiType>;
{{/unless}}
}
}
{{> footer }}
+26
View File
@@ -0,0 +1,26 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/api/types/events' {
export interface AugmentedEvents<ApiType> {
{{#each modules}}
{{{name}}}: {
{{#unless @root.isStrict}}
[key: string]: AugmentedEvent<ApiType>;
{{/unless}}
{{~#each items}}
{{> docs}}
{{{name}}}: AugmentedEvent<ApiType, [{{{type}}}]>;
{{/each}}
};
{{/each}}
}
export interface DecoratedEvents<ApiType extends ApiTypes> extends AugmentedEvents<ApiType> {
{{#unless isStrict}}
[key: string]: ModuleEvents<ApiType>;
{{/unless}}
}
}
{{> footer }}
+1 -1
View File
@@ -11,7 +11,7 @@ declare module '@polkadot/api/types/storage' {
{{/unless}}
{{~#each items}}
{{> docs}}
{{{name}}}: {{{entryType}}}<ApiType, ({{{args}}}) => Observable<{{{returnType}}}>>{{#unless @root.isStrict}} & QueryableStorageEntry<ApiType>{{/unless}};
{{{name}}}: {{{entryType}}}<ApiType, ({{{params}}}) => Observable<{{{returnType}}}>, [{{{args}}}]>{{#unless @root.isStrict}} & QueryableStorageEntry<ApiType, [{{{args}}}]>{{/unless}};
{{/each}}
};
{{/each}}
+1 -1
View File
@@ -11,7 +11,7 @@ declare module '@polkadot/api/types/submittable' {
{{/unless}}
{{~#each items}}
{{> docs}}
{{{name}}}: AugmentedSubmittable<({{{params}}}) => SubmittableExtrinsic<ApiType>>;
{{{name}}}: AugmentedSubmittable<({{{params}}}) => SubmittableExtrinsic<ApiType>, [{{{args}}}]>;
{{/each}}
};
{{/each}}
+1 -1
View File
@@ -88,7 +88,7 @@ function injectEvents (registry: Registry, metadata: Metadata, metadataEvents: R
// create extrinsic mapping from metadata
function injectExtrinsics (registry: Registry, metadata: Metadata, metadataCalls: Record<string, CallFunction>): void {
const extrinsics = decorateExtrinsics(registry, metadata.asLatest);
const extrinsics = decorateExtrinsics(registry, metadata.asLatest, metadata.version);
// decorate the extrinsics
Object.values(extrinsics).forEach((methods): void =>
+16 -16
View File
@@ -4,7 +4,7 @@
import type { EcdsaSignature, Ed25519Signature, ExtrinsicUnknown, ExtrinsicV4, Sr25519Signature } from '../interfaces/extrinsics';
import type { FunctionMetadataLatest } from '../interfaces/metadata/types';
import type { Address, Balance, Call, Index } from '../interfaces/runtime';
import type { AnyJson, AnyU8a, ArgsDef, Codec, ExtrinsicPayloadValue, IExtrinsic, IKeyringPair, InterfaceTypes, Registry, SignatureOptions } from '../types';
import type { AnyJson, AnyTuple, AnyU8a, ArgsDef, ExtrinsicPayloadValue, IExtrinsic, IKeyringPair, IMethod, InterfaceTypes, Registry, SignatureOptions } from '../types';
import type { GenericExtrinsicEra } from './ExtrinsicEra';
import type { ExtrinsicValueV4 } from './v4/Extrinsic';
@@ -34,11 +34,11 @@ const VERSIONS: (keyof InterfaceTypes)[] = [
export { EXTRINSIC_VERSION as LATEST_EXTRINSIC_VERSION } from './v4/Extrinsic';
abstract class ExtrinsicBase extends Base<ExtrinsicVx | ExtrinsicUnknown> {
abstract class ExtrinsicBase<A extends AnyTuple> extends Base<ExtrinsicVx | ExtrinsicUnknown> {
/**
* @description The arguments passed to for the call, exposes args so it is compatible with [[Call]]
*/
public get args (): Codec[] {
public get args (): A {
return this.method.args;
}
@@ -77,13 +77,6 @@ abstract class ExtrinsicBase extends Base<ExtrinsicVx | ExtrinsicUnknown> {
return this.toU8a().length;
}
/**
* @description `true` is method has `Origin` argument (compatibility with [Call])
*/
public get hasOrigin (): boolean {
return this.method.hasOrigin;
}
/**
* @description `true` id the extrinsic is signed
*/
@@ -108,8 +101,8 @@ abstract class ExtrinsicBase extends Base<ExtrinsicVx | ExtrinsicUnknown> {
/**
* @description The [[Call]] this extrinsic wraps
*/
public get method (): Call {
return (this._raw as ExtrinsicVx).method;
public get method (): IMethod<A> {
return (this._raw as ExtrinsicVx).method as unknown as IMethod<A>;
}
/**
@@ -153,6 +146,13 @@ abstract class ExtrinsicBase extends Base<ExtrinsicVx | ExtrinsicUnknown> {
public get version (): number {
return this.type | (this.isSigned ? BIT_SIGNED : BIT_UNSIGNED);
}
/**
* @description Checks if the source matches this in type
*/
public is (other: IMethod<AnyTuple>): other is IMethod<A> {
return this.method.is(other);
}
}
/**
@@ -167,7 +167,7 @@ abstract class ExtrinsicBase extends Base<ExtrinsicVx | ExtrinsicUnknown> {
* - signed, to create a transaction
* - left as is, to create an inherent
*/
export class GenericExtrinsic extends ExtrinsicBase implements IExtrinsic {
export class GenericExtrinsic<A extends AnyTuple = AnyTuple> extends ExtrinsicBase<A> implements IExtrinsic<A> {
constructor (registry: Registry, value: GenericExtrinsic | ExtrinsicValue | AnyU8a | Call | undefined, { version }: CreateOptions = {}) {
super(registry, GenericExtrinsic._decodeExtrinsic(registry, value, version));
}
@@ -216,7 +216,7 @@ export class GenericExtrinsic extends ExtrinsicBase implements IExtrinsic {
/**
* @description Injects an already-generated signature into the extrinsic
*/
public addSignature (signer: Address | Uint8Array | string, signature: Uint8Array | string, payload: ExtrinsicPayloadValue | Uint8Array | string): GenericExtrinsic {
public addSignature (signer: Address | Uint8Array | string, signature: Uint8Array | string, payload: ExtrinsicPayloadValue | Uint8Array | string): GenericExtrinsic<A> {
(this._raw as ExtrinsicVx).addSignature(signer, signature, payload);
return this;
@@ -225,7 +225,7 @@ export class GenericExtrinsic extends ExtrinsicBase implements IExtrinsic {
/**
* @description Sign the extrinsic with a specific keypair
*/
public sign (account: IKeyringPair, options: SignatureOptions): GenericExtrinsic {
public sign (account: IKeyringPair, options: SignatureOptions): GenericExtrinsic<A> {
(this._raw as ExtrinsicVx).sign(account, options);
return this;
@@ -234,7 +234,7 @@ export class GenericExtrinsic extends ExtrinsicBase implements IExtrinsic {
/**
* @describe Adds a fake signature to the extrinsic
*/
public signFake (signer: Address | Uint8Array | string, options: SignatureOptions): GenericExtrinsic {
public signFake (signer: Address | Uint8Array | string, options: SignatureOptions): GenericExtrinsic<A> {
(this._raw as ExtrinsicVx).signFake(signer, options);
return this;
@@ -16,7 +16,7 @@ const keyring = createTestPairs({ type: 'ed25519' }, false);
registry.setMetadata(metadata);
const tx = decorateExtrinsics(registry, metadata.asLatest);
const tx = decorateExtrinsics(registry, metadata.asLatest, metadata.version);
describe('ExtrinsicV4', (): void => {
it.only('constructs a sane Uint8Array (default)', (): void => {
-25
View File
@@ -27,29 +27,4 @@ describe('Call', (): void => {
new Call(registry, '0x0601').toU8a()
).toEqual(new Uint8Array([6, 1, 0, 0, 0])); // balances.setBalance
});
describe('hasOrigin', (): void => {
const test = {
args: [],
callIndex: [2, 2] // timestamp
};
it('is false with no arguments', (): void => {
expect(
new Call(registry, test, { args: [] } as any).hasOrigin
).toEqual(false);
});
it('is false with first argument as non-Origin', (): void => {
expect(
new Call(registry, test, { args: [{ name: 'a', type: 'u32' }] } as any).hasOrigin
).toEqual(false);
});
it('is false with first argument as non-Origin', (): void => {
expect(
new Call(registry, test, { args: [{ name: 'a', type: 'Origin' }] } as any).hasOrigin
).toEqual(true);
});
});
});
+11 -13
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { FunctionArgumentMetadataLatest, FunctionMetadataLatest } from '../interfaces/metadata';
import type { AnyJson, AnyU8a, ArgsDef, CallFunction, Codec, IMethod, Registry } from '../types';
import type { AnyJson, AnyTuple, AnyU8a, ArgsDef, CallFunction, IMethod, Registry } from '../types';
import { isHex, isObject, isU8a, u8aToU8a } from '@polkadot/util';
@@ -117,7 +117,7 @@ export class GenericCallIndex extends U8aFixed {
* @description
* Extrinsic function descriptor
*/
export class GenericCall extends Struct implements IMethod {
export class GenericCall<A extends AnyTuple = AnyTuple> extends Struct implements IMethod<A> {
protected _meta: FunctionMetadataLatest;
constructor (registry: Registry, value: unknown, meta?: FunctionMetadataLatest) {
@@ -159,9 +159,9 @@ export class GenericCall extends Struct implements IMethod {
/**
* @description The arguments for the function call
*/
public get args (): Codec[] {
public get args (): A {
// FIXME This should return a Struct instead of an Array
return [...(this.get('args') as Struct).values()];
return [...(this.get('args') as Struct).values()] as A;
}
/**
@@ -185,15 +185,6 @@ export class GenericCall extends Struct implements IMethod {
return (this.get('args') as Struct).toU8a();
}
/**
* @description `true` if the `Origin` type is on the method (extrinsic method)
*/
public get hasOrigin (): boolean {
const firstArg = this.meta.args[0];
return !!firstArg && firstArg.type.toString() === 'Origin';
}
/**
* @description The [[FunctionMetadata]]
*/
@@ -229,6 +220,13 @@ export class GenericCall extends Struct implements IMethod {
return this.sectionName;
}
/**
* @description Checks if the source matches this in type
*/
public is (other: IMethod<AnyTuple>): other is IMethod<A> {
return other.callIndex[0] === this.callIndex[0] && other.callIndex[1] === this.callIndex[1];
}
/**
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
*/
+3 -3
View File
@@ -4,7 +4,7 @@
import type { TypeDef } from '../create/types';
import type { EventMetadataLatest } from '../interfaces/metadata';
import type { EventId } from '../interfaces/system';
import type { AnyJson, Constructor, Registry } from '../types';
import type { AnyJson, Codec, Constructor, IEvent, IEventData, Registry } from '../types';
import { Struct } from '../codec/Struct';
import { Tuple } from '../codec/Tuple';
@@ -15,7 +15,7 @@ import { Null } from '../primitive/Null';
* @description
* Wrapper for the actual data that forms part of an [[Event]]
*/
export class GenericEventData extends Tuple {
export class GenericEventData extends Tuple implements IEventData {
readonly #meta: EventMetadataLatest;
readonly #method: string;
@@ -68,7 +68,7 @@ export class GenericEventData extends Tuple {
* A representation of a system event. These are generated via the [[Metadata]] interfaces and
* specific to a specific Substrate runtime
*/
export class GenericEvent extends Struct {
export class GenericEvent extends Struct implements IEvent<Codec[]> {
// Currently we _only_ decode from Uint8Array, since we expect it to
// be used via EventRecord
constructor (registry: Registry, _value?: Uint8Array) {
+12 -8
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { StorageEntryMetadataLatest, StorageEntryTypeLatest, StorageHasher } from '../interfaces/metadata';
import type { AnyJson, AnyU8a, Codec, InterfaceTypes, Registry } from '../types';
import type { AnyJson, AnyTuple, AnyU8a, Codec, InterfaceTypes, IStorageKey, Registry } from '../types';
import type { StorageEntry } from './types';
import { assert, isFunction, isString, isU8a } from '@polkadot/util';
@@ -85,7 +85,7 @@ function decodeStorageKey (value?: AnyU8a | StorageKey | StorageEntry | [Storage
throw new Error(`Unable to convert input ${value as string} to StorageKey`);
}
function decodeHashers (registry: Registry, value: Uint8Array, hashers: [StorageHasher, string][]): Codec[] {
function decodeHashers <A extends AnyTuple> (registry: Registry, value: Uint8Array, hashers: [StorageHasher, string][]): A {
// the storage entry is xxhashAsU8a(prefix, 128) + xxhashAsU8a(method, 128), 256 bits total
let offset = 32;
@@ -99,13 +99,13 @@ function decodeHashers (registry: Registry, value: Uint8Array, hashers: [Storage
result.push(decoded);
return result;
}, []);
}, []) as A;
}
/** @internal */
function decodeArgsFromMeta (registry: Registry, value: Uint8Array, meta?: StorageEntryMetadataLatest): Codec[] {
function decodeArgsFromMeta <A extends AnyTuple> (registry: Registry, value: Uint8Array, meta?: StorageEntryMetadataLatest): A {
if (!meta || !(meta.type.isDoubleMap || meta.type.isMap)) {
return [];
return [] as unknown as A;
}
if (meta.type.isMap) {
@@ -130,10 +130,10 @@ function decodeArgsFromMeta (registry: Registry, value: Uint8Array, meta?: Stora
* A representation of a storage key (typically hashed) in the system. It can be
* constructed by passing in a raw key or a StorageEntry with (optional) arguments.
*/
export class StorageKey extends Bytes {
export class StorageKey<A extends AnyTuple = AnyTuple> extends Bytes implements IStorageKey<A> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore This is assigned via this.decodeArgsFromMeta()
private _args: Codec[];
private _args: A;
private _meta?: StorageEntryMetadataLatest;
@@ -188,7 +188,7 @@ export class StorageKey extends Bytes {
/**
* @description Return the decoded arguments (applicable to map/doublemap with decodable values)
*/
public get args (): Codec[] {
public get args (): A {
return this._args;
}
@@ -220,6 +220,10 @@ export class StorageKey extends Bytes {
return this._section;
}
public is (key: IStorageKey<AnyTuple>): key is IStorageKey<A> {
return key.section === this.section && key.method === this.method;
}
/**
* @description Sets the meta for this key
*/
+11 -7
View File
@@ -3,15 +3,19 @@
import type { FunctionMetadataLatest } from '../interfaces/metadata';
import type { Call } from '../interfaces/runtime';
import type { AnyTuple } from './codec';
import type { IMethod } from './interfaces';
export interface CallBase {
callIndex: Uint8Array;
meta: FunctionMetadataLatest;
method: string;
section: string;
export interface CallBase<A extends AnyTuple> {
readonly callIndex: Uint8Array;
readonly meta: FunctionMetadataLatest;
readonly method: string;
readonly section: string;
is: (tx: IMethod<AnyTuple>) => tx is IMethod<A>;
toJSON: () => any;
}
export interface CallFunction extends CallBase {
(...args: any[]): Call;
export interface CallFunction<A extends AnyTuple = AnyTuple> extends CallBase<A> {
(...args: any[]): Call & IMethod<A>;
}
+2
View File
@@ -13,6 +13,8 @@ export type AnyNumber = BN | BigInt | Uint8Array | number | string;
export type AnyString = string | string;
export type AnyTuple = Codec[];
export type AnyU8a = Uint8Array | number[] | string;
// helper to extract keys from an array
+27
View File
@@ -0,0 +1,27 @@
// Copyright 2017-2020 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { EventMetadataLatest } from '../interfaces/metadata';
import type { Hash } from '../interfaces/runtime';
import type { EventId, Phase } from '../interfaces/system';
import type { Codec } from './codec';
import type { ITuple } from './interfaces';
export interface IEventRecord<T extends Codec[]> {
readonly phase: Phase;
readonly event: IEvent<T>;
readonly topics: Hash[];
}
export interface IEventData {
readonly meta: EventMetadataLatest;
readonly method: string;
readonly section: string;
}
export interface IEvent<T extends Codec[]> {
readonly data: ITuple<T> & IEventData;
readonly index: EventId;
readonly method: string;
readonly section: string;
}
+4 -4
View File
@@ -5,7 +5,7 @@ import type { ExtrinsicStatus } from '../interfaces/author';
import type { EcdsaSignature, Ed25519Signature, Sr25519Signature } from '../interfaces/extrinsics';
import type { Address, Balance, Call, H256, Index } from '../interfaces/runtime';
import type { DispatchError, DispatchInfo, EventRecord } from '../interfaces/system';
import type { AnyJson, AnyNumber, AnyU8a, Codec } from './codec';
import type { AnyJson, AnyNumber, AnyTuple, AnyU8a, Codec } from './codec';
import type { ICompact, IKeyringPair, IMethod, IRuntimeVersion } from './interfaces';
export interface ISubmittableResult {
@@ -173,7 +173,7 @@ export interface ExtrinsicPayloadValue {
blockHash: AnyU8a;
era: AnyU8a | IExtrinsicEra;
genesisHash: AnyU8a;
method: AnyU8a | IMethod;
method: AnyU8a | IMethod<AnyTuple>;
nonce: AnyNumber;
specVersion: AnyNumber;
tip: AnyNumber;
@@ -198,9 +198,9 @@ export interface IExtrinsicImpl extends IExtrinsicSignable<IExtrinsicImpl>, Code
readonly version: number;
}
export interface IExtrinsic extends IExtrinsicSignable<IExtrinsic>, ExtrinsicSignatureBase, IMethod {
export interface IExtrinsic<A extends AnyTuple = AnyTuple> extends IExtrinsicSignable<IExtrinsic<A>>, ExtrinsicSignatureBase, IMethod<A> {
readonly length: number;
readonly method: Call;
readonly method: IMethod<A>;
readonly type: number;
readonly version: number;
}
+1
View File
@@ -8,6 +8,7 @@ export * from '../create/types';
export * from './calls';
export * from './codec';
export * from './definitions';
export * from './events';
export * from './extrinsic';
export * from './interfaces';
export * from './registry';
+18 -6
View File
@@ -3,9 +3,9 @@
import type BN from 'bn.js';
import type { SignOptions } from '@polkadot/keyring/types';
import type { FunctionMetadataLatest } from '../interfaces/metadata';
import type { FunctionMetadataLatest, StorageEntryMetadataLatest } from '../interfaces/metadata';
import type { Hash } from '../interfaces/runtime';
import type { ArgsDef, Codec } from './codec';
import type { AnyTuple, ArgsDef, Codec } from './codec';
export interface ICompact<T> extends Codec {
toBigInt (): BigInt;
@@ -18,17 +18,19 @@ export interface IKeyringPair {
address: string;
addressRaw: Uint8Array;
publicKey: Uint8Array;
sign: (data: Uint8Array, options?: SignOptions) => Uint8Array;
}
export interface IMethod extends Codec {
readonly args: Codec[];
export interface IMethod<A extends AnyTuple = AnyTuple> extends Codec {
readonly args: A;
readonly argsDef: ArgsDef;
readonly callIndex: Uint8Array;
readonly data: Uint8Array;
readonly hash: Hash;
readonly hasOrigin: boolean;
readonly meta: FunctionMetadataLatest;
is: (tx: IMethod<AnyTuple>) => tx is IMethod<A>;
}
export interface IRuntimeVersion {
@@ -44,9 +46,19 @@ export interface IRuntimeVersion {
readonly transactionVersion: BN;
}
export interface IStorageKey<A extends AnyTuple> {
readonly args: A;
readonly meta: StorageEntryMetadataLatest | undefined;
readonly method: string | undefined;
readonly outputType: string;
readonly section: string | undefined;
is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>;
}
// A type alias for [Type1, Type2] & Codec, representing a tuple (Type1, Type2)
// FIXME Implement this generic <Sub> on Tuple.ts itself.
export type ITuple<Sub extends Codec[]> = Sub & Codec
export type ITuple<Sub extends AnyTuple> = Sub & Codec
export interface IU8a extends Uint8Array, Codec {
bitLength (): number;