diff --git a/packages/api/src/augment/consts.ts b/packages/api/src/augment/consts.ts index 625bf8332a..c31c589440 100644 --- a/packages/api/src/augment/consts.ts +++ b/packages/api/src/augment/consts.ts @@ -51,6 +51,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' { /** * The amount of funds a contract should deposit in order to offset * the cost of one byte. + * * Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day, * then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent. * But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000, @@ -59,6 +60,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' { rentDepositOffset: AugmentedConst; /** * Number of block delay an extrinsic claim surcharge has. + * * When claim surcharge is called by an extrinsic the rent is checked * for current_block - delay **/ @@ -86,6 +88,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' { cooloffPeriod: AugmentedConst; /** * The minimum period of locking and the period between a proposal being approved and enacted. + * * It should generally be a little more than the unstake period to ensure that * voting stakers have an opportunity to remove themselves from the system in the case where * they are on the losing side of a vote. diff --git a/packages/api/src/augment/query.ts b/packages/api/src/augment/query.ts index 179c1eed3b..e1649bd42c 100644 --- a/packages/api/src/augment/query.ts +++ b/packages/api/src/augment/query.ts @@ -72,6 +72,7 @@ declare module '@polkadot/api/types/storage' { initialized: AugmentedQuery Observable>> & QueryableStorageEntry; /** * How late the current block is compared to its parent. + * * This entry is populated as part of block execution and is cleaned up * on block finalization. Querying this storage entry outside of block * execution context should always yield zero. @@ -83,7 +84,9 @@ declare module '@polkadot/api/types/storage' { nextRandomness: AugmentedQuery Observable> & QueryableStorageEntry; /** * The epoch randomness for the *current* epoch. + * * # Security + * * This MUST NOT be used for gambling, as it can be influenced by a * malicious validator in the short term. It MAY be used in many * cryptographic protocols, however, so long as one remembers that this @@ -94,9 +97,11 @@ declare module '@polkadot/api/types/storage' { randomness: AugmentedQuery Observable> & QueryableStorageEntry; /** * Randomness under construction. + * * We make a tradeoff between storage accesses and list length. * We store the under-construction randomness in segments of up to * `UNDER_CONSTRUCTION_SEGMENT_LENGTH`. + * * Once a segment reaches this length, we begin the next one. * We reset all segments and return to `0` at the beginning of every * epoch. @@ -108,8 +113,10 @@ declare module '@polkadot/api/types/storage' { [index: string]: QueryableStorageEntry; /** * The balance of an account. + * * NOTE: THIS MAY NEVER BE IN EXISTENCE AND YET HAVE A `total().is_zero()`. If the total * is ever zero, then the entry *MUST* be removed. + * * NOTE: This is only used in the case that this module is used to store balances. **/ account: AugmentedQuery Observable> & QueryableStorageEntry; @@ -120,6 +127,7 @@ declare module '@polkadot/api/types/storage' { locks: AugmentedQuery Observable>> & QueryableStorageEntry; /** * Storage version of the pallet. + * * This is set to v2.0.0 for new networks. **/ storageVersion: AugmentedQuery Observable> & QueryableStorageEntry; @@ -310,11 +318,13 @@ declare module '@polkadot/api/types/storage' { /** * The set of registrars. Not expected to get very big as can only be added through a * special origin (likely a council motion). + * * The index into this can be cast to `RegistrarIndex` to get a valid value. **/ registrars: AugmentedQuery Observable>>> & QueryableStorageEntry; /** * Alternative "sub" identities of this account. + * * The first item is the deposit, the second is a vector of the accounts. **/ subsOf: AugmentedQuery Observable]>>> & QueryableStorageEntry; @@ -333,6 +343,7 @@ declare module '@polkadot/api/types/storage' { authoredBlocks: AugmentedQueryDoubleMap Observable> & QueryableStorageEntry; /** * The block number after which it's ok to send heartbeats in current session. + * * At the beginning of each session we set this to a value that should * fall roughly in the middle of the session duration. * The idea is to first wait for the validators to produce a block @@ -373,7 +384,9 @@ declare module '@polkadot/api/types/storage' { reports: AugmentedQuery Observable>> & QueryableStorageEntry; /** * Enumerates all reports of a kind along with the time they happened. + * * All reports are sorted by the time of offence. + * * Note that the actual type of this mapping is `Vec`, this is because values of * different types are not supported at the moment so we are doing the manual serialization. **/ @@ -392,12 +405,14 @@ declare module '@polkadot/api/types/storage' { [index: string]: QueryableStorageEntry; /** * Active recovery attempts. + * * First account is the account to be recovered, and the second account * is the user trying to recover the account. **/ activeRecoveries: AugmentedQueryDoubleMap Observable>> & QueryableStorageEntry; /** * The list of allowed proxy accounts. + * * Map from the user who can access it to the recovered account. **/ proxy: AugmentedQuery Observable>> & QueryableStorageEntry; @@ -425,6 +440,7 @@ declare module '@polkadot/api/types/storage' { currentIndex: AugmentedQuery Observable> & QueryableStorageEntry; /** * Indices of disabled validators. + * * The set is cleared when `on_session_ending` returns a new set of identities. **/ disabledValidators: AugmentedQuery Observable>> & QueryableStorageEntry; @@ -523,6 +539,7 @@ declare module '@polkadot/api/types/storage' { [index: string]: QueryableStorageEntry; /** * The active era information, it holds index and start. + * * The active era is the era currently rewarded. * Validator set of this era must be equal to `SessionInterface::validators`. **/ @@ -533,6 +550,7 @@ declare module '@polkadot/api/types/storage' { bonded: AugmentedQuery Observable>> & QueryableStorageEntry; /** * A mapping from still-bonded eras to the first session index of that era. + * * Must contains information for eras for the range: * `[active_era - bounding_duration; active_era]` **/ @@ -544,6 +562,7 @@ declare module '@polkadot/api/types/storage' { canceledSlashPayout: AugmentedQuery Observable> & QueryableStorageEntry; /** * The current era index. + * * This is the latest planned era, depending on how the Session pallet queues the validator * set, it might be active or not. **/ @@ -564,18 +583,23 @@ declare module '@polkadot/api/types/storage' { erasRewardPoints: AugmentedQuery Observable> & QueryableStorageEntry; /** * Exposure of validator at era. + * * This is keyed first by the era index to allow bulk deletion and then the stash account. + * * Is it removed after `HISTORY_DEPTH` eras. * If stakers hasn't been set or has been removed then empty exposure is returned. **/ erasStakers: AugmentedQueryDoubleMap Observable> & QueryableStorageEntry; /** * Clipped Exposure of validator at era. + * * This is similar to [`ErasStakers`] but number of nominators exposed is reduced to the * `T::MaxNominatorRewardedPerValidator` biggest stakers. * (Note: the field `total` and `own` of the exposure remains unchanged). * This is used to limit the i/o cost for the nominator payout. + * * This is keyed fist by the era index to allow bulk deletion and then the stash account. + * * Is it removed after `HISTORY_DEPTH` eras. * If stakers hasn't been set or has been removed then empty exposure is returned. **/ @@ -591,12 +615,15 @@ declare module '@polkadot/api/types/storage' { erasTotalStake: AugmentedQuery Observable> & QueryableStorageEntry; /** * Similar to `ErasStakers`, this holds the preferences of validators. + * * This is keyed first by the era index to allow bulk deletion and then the stash account. + * * Is it removed after `HISTORY_DEPTH` eras. **/ erasValidatorPrefs: AugmentedQueryDoubleMap Observable> & QueryableStorageEntry; /** * The total validator era payout for the last `HISTORY_DEPTH` eras. + * * Eras that haven't finished yet or has been removed doesn't have reward. **/ erasValidatorReward: AugmentedQuery Observable>> & QueryableStorageEntry; @@ -606,7 +633,9 @@ declare module '@polkadot/api/types/storage' { forceEra: AugmentedQuery Observable> & QueryableStorageEntry; /** * Number of eras to keep in history. + * * Information is kept for eras in `[current_era - history_depth; current_era]`. + * * Must be more than the number of eras delayed by session otherwise. * I.e. active era must always be in history. * I.e. `active_era > current_era - history_depth` must be guaranteed. @@ -663,6 +692,7 @@ declare module '@polkadot/api/types/storage' { slashingSpans: AugmentedQuery Observable>> & QueryableStorageEntry; /** * The percentage of the slash that is distributed to reporters. + * * The rest of the slashed value is handled by the `Slash`. **/ slashRewardFraction: AugmentedQuery Observable> & QueryableStorageEntry; @@ -684,6 +714,7 @@ declare module '@polkadot/api/types/storage' { /** * True if network has been upgraded to this version. * Storage version of the pallet. + * * This is set to v3.0.0 for new networks. **/ storageVersion: AugmentedQuery Observable> & QueryableStorageEntry; @@ -745,9 +776,11 @@ declare module '@polkadot/api/types/storage' { /** * Mapping between a topic (represented by T::Hash) and a vector of indexes * of events in the `>` list. + * * All topic vectors have deterministic storage locations depending on the topic. This * allows light-clients to leverage the changes trie storage tracking mechanism and * in case of changes fetch the list of events of interest. + * * The value has the type `(T::BlockNumber, EventIndex)` because if we used only just * the `EventIndex` then in case if the topic has the same contents on the next block * no notification will be triggered thus the event might be lost. diff --git a/packages/api/src/augment/tx.ts b/packages/api/src/augment/tx.ts index 6c673fdbdb..c669af724a 100644 --- a/packages/api/src/augment/tx.ts +++ b/packages/api/src/augment/tx.ts @@ -41,11 +41,14 @@ declare module '@polkadot/api/types/submittable' { forceTransfer: AugmentedSubmittable<(source: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, dest: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, value: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Set the balances of a given account. + * * This will alter `FreeBalance` and `ReservedBalance` in storage. it will * also decrease the total issuance of the system (`TotalIssuance`). * If the new free or reserved balance is below the existential deposit, * it will reset the account nonce (`frame_system::AccountNonce`). + * * The dispatch origin for this call is `root`. + * * # * - Independent of the arguments. * - Contains a limited number of reads and writes. @@ -54,29 +57,37 @@ declare module '@polkadot/api/types/submittable' { setBalance: AugmentedSubmittable<(who: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, newFree: Compact | AnyNumber | Uint8Array, newReserved: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Transfer some liquid free balance to another account. + * * `transfer` will set the `FreeBalance` of the sender and receiver. * It will decrease the total issuance of the system by the `TransferFee`. * If the sender's account is below the existential deposit as a result * of the transfer, the account will be reaped. + * * The dispatch origin for this call must be `Signed` by the transactor. + * * # * - Dependent on arguments but not critical, given proper implementations for * input config types. See related functions below. * - It contains a limited number of reads and writes internally and no complex computation. + * * Related functions: + * * - `ensure_can_withdraw` is always called internally but has a bounded complexity. * - Transferring balances to accounts that did not exist before will cause * `T::OnNewAccount::on_new_account` to be called. * - Removing enough funds from an account will trigger `T::DustRemoval::on_unbalanced`. * - `transfer_keep_alive` works the same way as `transfer`, but has an additional * check that the transfer will not kill the origin account. + * * # **/ transfer: AugmentedSubmittable<(dest: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, value: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Same as the [`transfer`] call, but with a check that the transfer will not kill the * origin account. + * * 99% of the time you want [`transfer`] instead. + * * [`transfer`]: struct.Module.html#method.transfer **/ transferKeepAlive: AugmentedSubmittable<(dest: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, value: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; @@ -85,6 +96,7 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * Makes a call to an account, optionally transferring some balance. + * * * If the account is a smart-contract account, the associated code will be * executed and any value will be transferred. * * If the account is a regular account, any value will be transferred. @@ -95,13 +107,16 @@ declare module '@polkadot/api/types/submittable' { /** * Allows block producers to claim a small reward for evicting a contract. If a block producer * fails to do so, a regular users will be allowed to claim the reward. + * * If contract is not evicted as a result of this call, no actions are taken and * the sender is not eligible for the reward. **/ claimSurcharge: AugmentedSubmittable<(dest: AccountId | string | Uint8Array, auxSender: Option | null | object | string | Uint8Array) => SubmittableExtrinsic>; /** * Instantiates a new contract from the `codehash` generated by `put_code`, optionally transferring some balance. + * * Instantiation is executed as follows: + * * - The destination address is computed based on the sender and hash of the code. * - The smart-contract account is created at the computed address. * - The `ctor_code` is executed in the context of the newly-created account. Buffer returned @@ -117,6 +132,7 @@ declare module '@polkadot/api/types/submittable' { putCode: AugmentedSubmittable<(code: Bytes | string | Uint8Array) => SubmittableExtrinsic>; /** * Updates the schedule for metering contracts. + * * The schedule must have a greater version than the stored schedule. **/ updateSchedule: AugmentedSubmittable<(schedule: Schedule | { version?: any; putCodePerByteCost?: any; growMemCost?: any; regularOpCost?: any; returnDataPerByteCost?: any; eventDataPerByteCost?: any; eventPerTopicCost?: any; eventBaseCost?: any; sandboxDataReadCost?: any; sandboxDataWriteCost?: any; transferCost?: any; maxEventTopics?: any; maxStackHeight?: any; maxMemoryPages?: any; enablePrintln?: any; maxSubjectLen?: any } | string | Uint8Array) => SubmittableExtrinsic>; @@ -126,8 +142,10 @@ declare module '@polkadot/api/types/submittable' { /** * May be called by any signed account after the voting duration has ended in order to * finish voting and close the proposal. + * * Abstentions are counted as rejections unless there is a prime member set and the prime * member cast an approval. + * * - the weight of `proposal` preimage. * - up to three events deposited. * - one read, two removals, one mutation. (plus three static reads.) @@ -139,6 +157,7 @@ declare module '@polkadot/api/types/submittable' { close: AugmentedSubmittable<(proposal: Hash | string | Uint8Array, index: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Dispatch a proposal from a member using the `Member` origin. + * * Origin must be a member of the collective. **/ execute: AugmentedSubmittable<(proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic>; @@ -151,8 +170,10 @@ declare module '@polkadot/api/types/submittable' { propose: AugmentedSubmittable<(threshold: Compact | AnyNumber | Uint8Array, proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic>; /** * Set the collective's membership. + * * - `new_members`: The new member list. Be nice to the chain and * - `prime`: The prime member whose vote sets the default. + * * Requires root origin. **/ setMembers: AugmentedSubmittable<(newMembers: Vec | (AccountId | string | Uint8Array)[], prime: Option | null | object | string | Uint8Array) => SubmittableExtrinsic>; @@ -168,9 +189,13 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * Specify a proxy that is already open to us. Called by the stash. + * * NOTE: Used to be called `set_proxy`. + * * The dispatch origin of this call must be _Signed_. + * * - `proxy`: The account that will be activated as proxy. + * * # * - One extra DB entry. * # @@ -178,8 +203,11 @@ declare module '@polkadot/api/types/submittable' { activateProxy: AugmentedSubmittable<(proxy: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Cancel a proposal queued for enactment. + * * The dispatch origin of this call must be _Root_. + * * - `which`: The index of the referendum to cancel. + * * # * - One DB change. * - O(d) where d is the items in the dispatch queue. @@ -188,8 +216,11 @@ declare module '@polkadot/api/types/submittable' { cancelQueued: AugmentedSubmittable<(which: ReferendumIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Remove a referendum. + * * The dispatch origin of this call must be _Root_. + * * - `ref_index`: The index of the referendum to cancel. + * * # * - `O(1)`. * # @@ -197,7 +228,9 @@ declare module '@polkadot/api/types/submittable' { cancelReferendum: AugmentedSubmittable<(refIndex: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Clears all public proposals. + * * The dispatch origin of this call must be _Root_. + * * # * - `O(1)`. * - One DB clear. @@ -206,8 +239,11 @@ declare module '@polkadot/api/types/submittable' { clearPublicProposals: AugmentedSubmittable<() => SubmittableExtrinsic>; /** * Clear the proxy. Called by the proxy. + * * NOTE: Used to be called `resign_proxy`. + * * The dispatch origin of this call must be _Signed_. + * * # * - One DB clear. * # @@ -215,10 +251,15 @@ declare module '@polkadot/api/types/submittable' { closeProxy: AugmentedSubmittable<() => SubmittableExtrinsic>; /** * Deactivate the proxy, but leave open to this account. Called by the stash. + * * The proxy must already be active. + * * NOTE: Used to be called `remove_proxy`. + * * The dispatch origin of this call must be _Signed_. + * * - `proxy`: The account that will be deactivated as proxy. + * * # * - One DB clear. * # @@ -226,18 +267,23 @@ declare module '@polkadot/api/types/submittable' { deactivateProxy: AugmentedSubmittable<(proxy: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Delegate the voting power (with some given conviction) of the sending account. + * * The balance delegated is locked for as long as it's delegated, and thereafter for the * time appropriate for the conviction's lock period. + * * The dispatch origin of this call must be _Signed_, and the signing account must either: * - be delegating already; or * - have no voting activity (if there is, then it will need to be removed/consolidated * through `reap_vote` or `unvote`). + * * - `to`: The account whose voting the `target` account's voting power will follow. * - `conviction`: The conviction that will be attached to the delegated votes. When the * account is undelegated, the funds will be locked for the corresponding period. * - `balance`: The amount of the account's balance to be used in delegating. This must * not be more than the account's current balance. + * * Emits `Delegated`. + * * # * # **/ @@ -245,8 +291,11 @@ declare module '@polkadot/api/types/submittable' { /** * Schedule an emergency cancellation of a referendum. Cannot happen twice to the same * referendum. + * * The dispatch origin of this call must be `CancellationOrigin`. + * * -`ref_index`: The index of the referendum to cancel. + * * # * - `O(1)`. * # @@ -259,8 +308,11 @@ declare module '@polkadot/api/types/submittable' { /** * Schedule a referendum to be tabled once it is legal to schedule an external * referendum. + * * The dispatch origin of this call must be `ExternalOrigin`. + * * - `proposal_hash`: The preimage hash of the proposal. + * * # * - `O(1)`. * - One DB change. @@ -270,10 +322,14 @@ declare module '@polkadot/api/types/submittable' { /** * Schedule a negative-turnout-bias referendum to be tabled next once it is legal to * schedule an external referendum. + * * The dispatch of this call must be `ExternalDefaultOrigin`. + * * - `proposal_hash`: The preimage hash of the proposal. + * * Unlike `external_propose`, blacklisting has no effect on this and it may replace a * pre-scheduled `external_propose` call. + * * # * - `O(1)`. * - One DB change. @@ -283,10 +339,14 @@ declare module '@polkadot/api/types/submittable' { /** * Schedule a majority-carries referendum to be tabled next once it is legal to schedule * an external referendum. + * * The dispatch of this call must be `ExternalMajorityOrigin`. + * * - `proposal_hash`: The preimage hash of the proposal. + * * Unlike `external_propose`, blacklisting has no effect on this and it may replace a * pre-scheduled `external_propose` call. + * * # * - `O(1)`. * - One DB change. @@ -297,13 +357,17 @@ declare module '@polkadot/api/types/submittable' { * Schedule the currently externally-proposed majority-carries referendum to be tabled * immediately. If there is no externally-proposed referendum currently, or if there is one * but it is not a majority-carries referendum then it fails. + * * The dispatch of this call must be `FastTrackOrigin`. + * * - `proposal_hash`: The hash of the current external proposal. * - `voting_period`: The period that is allowed for voting on this proposal. Increased to * `FastTrackVotingPeriod` if too low. * - `delay`: The number of block after voting has ended in approval and this should be * enacted. This doesn't have a minimum amount. + * * Emits `Started`. + * * # * - One DB clear. * - One DB change. @@ -314,9 +378,13 @@ declare module '@polkadot/api/types/submittable' { /** * Register the preimage for an upcoming proposal. This requires the proposal to be * in the dispatch queue. No deposit is needed. + * * The dispatch origin of this call must be _Signed_. + * * - `encoded_proposal`: The preimage of a proposal. + * * Emits `PreimageNoted`. + * * # * - Dependent on the size of `encoded_proposal` and length of dispatch queue. * # @@ -325,9 +393,13 @@ declare module '@polkadot/api/types/submittable' { /** * Register the preimage for an upcoming proposal. This doesn't require the proposal to be * in the dispatch queue but does require a deposit, returned once enacted. + * * The dispatch origin of this call must be _Signed_. + * * - `encoded_proposal`: The preimage of a proposal. + * * Emits `PreimageNoted`. + * * # * - Dependent on the size of `encoded_proposal` but protected by a * required deposit. @@ -336,10 +408,15 @@ declare module '@polkadot/api/types/submittable' { notePreimage: AugmentedSubmittable<(encodedProposal: Bytes | string | Uint8Array) => SubmittableExtrinsic>; /** * Become a proxy. + * * This must be called prior to a later `activate_proxy`. + * * Origin must be a Signed. + * * - `target`: The account whose votes will later be proxied. + * * `close_proxy` must be called before the account can be destroyed. + * * # * - One extra DB entry. * # @@ -347,11 +424,15 @@ declare module '@polkadot/api/types/submittable' { openProxy: AugmentedSubmittable<(target: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Propose a sensitive action to be taken. + * * The dispatch origin of this call must be _Signed_ and the sender must * have funds to cover the deposit. + * * - `proposal_hash`: The hash of the proposal preimage. * - `value`: The amount of deposit (must be at least `MinimumDeposit`). + * * Emits `Proposed`. + * * # * - `O(P)` * - P is the number proposals in the `PublicProps` vec. @@ -361,10 +442,13 @@ declare module '@polkadot/api/types/submittable' { propose: AugmentedSubmittable<(proposalHash: Hash | string | Uint8Array, value: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Delegate the voting power (with some given conviction) of a proxied account. + * * The balance delegated is locked for as long as it's delegated, and thereafter for the * time appropriate for the conviction's lock period. + * * The dispatch origin of this call must be _Signed_, and the signing account must have * been set as the proxy account for `target`. + * * - `target`: The account whole voting power shall be delegated and whose balance locked. * This account must either: * - be delegating already; or @@ -375,18 +459,24 @@ declare module '@polkadot/api/types/submittable' { * account is undelegated, the funds will be locked for the corresponding period. * - `balance`: The amount of the account's balance to be used in delegating. This must * not be more than the account's current balance. + * * Emits `Delegated`. + * * # * # **/ proxyDelegate: AugmentedSubmittable<(to: AccountId | string | Uint8Array, conviction: Conviction | 'None'|'Locked1x'|'Locked2x'|'Locked3x'|'Locked4x'|'Locked5x'|'Locked6x' | number | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Remove a proxied vote for a referendum. + * * Exactly equivalent to `remove_vote` except that it operates on the account that the * sender is a proxy for. + * * The dispatch origin of this call must be _Signed_ and the signing account must be a * proxy for some other account which has a registered vote for the referendum of `index`. + * * - `index`: The index of referendum of the vote to be removed. + * * # * - `O(R + log R)` where R is the number of referenda that `target` has voted on. * # @@ -394,11 +484,15 @@ declare module '@polkadot/api/types/submittable' { proxyRemoveVote: AugmentedSubmittable<(index: ReferendumIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Undelegate the voting power of a proxied account. + * * Tokens may be unlocked following once an amount of time consistent with the lock period * of the conviction with which the delegation was issued. + * * The dispatch origin of this call must be _Signed_ and the signing account must be a * proxy for some other account which is currently delegating. + * * Emits `Undelegated`. + * * # * - O(1). * # @@ -407,9 +501,12 @@ declare module '@polkadot/api/types/submittable' { /** * Vote in a referendum on behalf of a stash. If `vote.is_aye()`, the vote is to enact * the proposal; otherwise it is a vote to keep the status quo. + * * The dispatch origin of this call must be _Signed_. + * * - `ref_index`: The index of the referendum to proxy vote for. * - `vote`: The vote configuration. + * * # * - `O(1)`. * - One DB change, one DB entry. @@ -418,12 +515,17 @@ declare module '@polkadot/api/types/submittable' { proxyVote: AugmentedSubmittable<(refIndex: Compact | AnyNumber | Uint8Array, vote: AccountVote | { Standard: any } | { Split: any } | string | Uint8Array) => SubmittableExtrinsic>; /** * Remove an expired proposal preimage and collect the deposit. + * * The dispatch origin of this call must be _Signed_. + * * - `proposal_hash`: The preimage hash of a proposal. + * * This will only work after `VotingPeriod` blocks from the time that the preimage was * noted, if it's the same account doing it. If it's a different account, then it'll only * work an additional `EnactmentPeriod` later. + * * Emits `PreimageReaped`. + * * # * - One DB clear. * # @@ -431,14 +533,18 @@ declare module '@polkadot/api/types/submittable' { reapPreimage: AugmentedSubmittable<(proposalHash: Hash | string | Uint8Array) => SubmittableExtrinsic>; /** * Remove a vote for a referendum. + * * If the `target` is equal to the signer, then this function is exactly equivalent to * `remove_vote`. If not equal to the signer, then the vote must have expired, * either because the referendum was cancelled, because the voter lost the referendum or * because the conviction period is over. + * * The dispatch origin of this call must be _Signed_. + * * - `target`: The account of the vote to be removed; this account must have voted for * referendum `index`. * - `index`: The index of referendum of the vote to be removed. + * * # * - `O(R + log R)` where R is the number of referenda that `target` has voted on. * # @@ -446,6 +552,7 @@ declare module '@polkadot/api/types/submittable' { removeOtherVote: AugmentedSubmittable<(target: AccountId | string | Uint8Array, index: ReferendumIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Remove a vote for a referendum. + * * If: * - the referendum was cancelled, or * - the referendum is ongoing, or @@ -455,6 +562,7 @@ declare module '@polkadot/api/types/submittable' { * - the account made a split vote * ...then the vote is removed cleanly and a following call to `unlock` may result in more * funds being available. + * * If, however, the referendum has ended and: * - it finished corresponding to the vote of the account, and * - the account made a standard vote with conviction, and @@ -462,9 +570,12 @@ declare module '@polkadot/api/types/submittable' { * ...then the lock will be aggregated into the overall account's lock, which may involve * *overlocking* (where the two locks are combined into a single lock that is the maximum * of both the amount locked and the time is it locked for). + * * The dispatch origin of this call must be _Signed_, and the signer must have a vote * registered for referendum `index`. + * * - `index`: The index of referendum of the vote to be removed. + * * # * - `O(R + log R)` where R is the number of referenda that `target` has voted on. * # @@ -472,9 +583,12 @@ declare module '@polkadot/api/types/submittable' { removeVote: AugmentedSubmittable<(index: ReferendumIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Signals agreement with a particular proposal. + * * The dispatch origin of this call must be _Signed_ and the sender * must have funds to cover the deposit, equal to the original deposit. + * * - `proposal`: The index of the proposal to second. + * * # * - `O(S)`. * - S is the number of seconds a proposal already has. @@ -484,11 +598,15 @@ declare module '@polkadot/api/types/submittable' { second: AugmentedSubmittable<(proposal: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Undelegate the voting power of the sending account. + * * Tokens may be unlocked following once an amount of time consistent with the lock period * of the conviction with which the delegation was issued. + * * The dispatch origin of this call must be _Signed_ and the signing account must be * currently delegating. + * * Emits `Undelegated`. + * * # * - O(1). * # @@ -496,8 +614,11 @@ declare module '@polkadot/api/types/submittable' { undelegate: AugmentedSubmittable<() => SubmittableExtrinsic>; /** * Unlock tokens that have an expired lock. + * * The dispatch origin of this call must be _Signed_. + * * - `target`: The account to remove the lock on. + * * # * - `O(1)`. * # @@ -505,9 +626,13 @@ declare module '@polkadot/api/types/submittable' { unlock: AugmentedSubmittable<(target: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Veto and blacklist the external proposal hash. + * * The dispatch origin of this call must be `VetoOrigin`. + * * - `proposal_hash`: The preimage hash of the proposal to veto and blacklist. + * * Emits `Vetoed`. + * * # * - Two DB entries. * - One DB clear. @@ -520,9 +645,12 @@ declare module '@polkadot/api/types/submittable' { /** * Vote in a referendum. If `vote.is_aye()`, the vote is to enact the proposal; * otherwise it is a vote to keep the status quo. + * * The dispatch origin of this call must be _Signed_. + * * - `ref_index`: The index of the referendum to vote for. * - `vote`: The vote configuration. + * * # * - `O(R)`. * - R is the number of referendums the voter has voted on. @@ -536,9 +664,12 @@ declare module '@polkadot/api/types/submittable' { /** * Remove a particular member from the set. This is effective immediately and the bond of * the outgoing member is slashed. + * * If a runner-up is available, then the best runner-up will be removed and replaces the * outgoing member. Otherwise, a new phragmen round is started. + * * Note that this does not affect the designated block number of the next election. + * * # * #### State * Reads: O(do_phragmen) @@ -548,6 +679,7 @@ declare module '@polkadot/api/types/submittable' { removeMember: AugmentedSubmittable<(who: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic>; /** * Remove `origin` as a voter. This removes the lock and returns the bond. + * * # * #### State * Reads: O(1) @@ -571,9 +703,11 @@ declare module '@polkadot/api/types/submittable' { * Report `target` for being an defunct voter. In case of a valid report, the reporter is * rewarded by the bond amount of `target`. Otherwise, the reporter itself is removed and * their bond is slashed. + * * A defunct voter is defined to be: * - a voter whose current submitted votes are all invalid. i.e. all of them are no * longer a candidate nor an active member. + * * # * #### State * Reads: O(NLogM) given M current candidates and N votes for `target`. @@ -583,11 +717,13 @@ declare module '@polkadot/api/types/submittable' { reportDefunctVoter: AugmentedSubmittable<(target: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic>; /** * Submit oneself for candidacy. + * * A candidate will either: * - Lose at the end of the term and forfeit their deposit. * - Win and become a member. Members will eventually get their stash back. * - Become a runner-up. Runners-ups are reserved members in case one gets forcefully * removed. + * * # * #### State * Reads: O(LogN) Given N candidates. @@ -597,12 +733,15 @@ declare module '@polkadot/api/types/submittable' { submitCandidacy: AugmentedSubmittable<() => SubmittableExtrinsic>; /** * Vote for a set of candidates for the upcoming round of election. + * * The `votes` should: * - not be empty. * - be less than the number of candidates. + * * Upon voting, `value` units of `who`'s balance is locked and a bond amount is reserved. * It is the responsibility of the caller to not place all of their balance into the lock * and keep some for further transactions. + * * # * #### State * Reads: O(1) @@ -630,9 +769,13 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * Add a registrar to the system. + * * The dispatch origin for this call must be `RegistrarOrigin` or `Root`. + * * - `account`: the account of the registrar. + * * Emits `RegistrarAdded` if successful. + * * # * - `O(R)` where `R` registrar-count (governance-bounded and code-bounded). * - One storage mutation (codec `O(R)`). @@ -645,11 +788,16 @@ declare module '@polkadot/api/types/submittable' { addRegistrar: AugmentedSubmittable<(account: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Cancel a previous request. + * * Payment: A previously reserved deposit is returned on success. + * * The dispatch origin for this call must be _Signed_ and the sender must have a * registered identity. + * * - `reg_index`: The index of the registrar whose judgement is no longer requested. + * * Emits `JudgementUnrequested` if successful. + * * # * - `O(R + X)`. * - One balance-reserve operation. @@ -663,10 +811,14 @@ declare module '@polkadot/api/types/submittable' { cancelRequest: AugmentedSubmittable<(regIndex: RegistrarIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Clear an account's identity info and all sub-accounts and return all deposits. + * * Payment: All reserved balances on the account are returned. + * * The dispatch origin for this call must be _Signed_ and the sender must have a registered * identity. + * * Emits `IdentityCleared` if successful. + * * # * - `O(R + S + X)` * - where `R` registrar-count (governance-bounded). @@ -683,13 +835,18 @@ declare module '@polkadot/api/types/submittable' { clearIdentity: AugmentedSubmittable<() => SubmittableExtrinsic>; /** * Remove an account's identity and sub-account information and slash the deposits. + * * Payment: Reserved balances from `set_subs` and `set_identity` are slashed and handled by * `Slash`. Verification request deposits are not returned; they should be cancelled * manually using `cancel_request`. + * * The dispatch origin for this call must be _Root_ or match `T::ForceOrigin`. + * * - `target`: the account whose identity the judgement is upon. This must be an account * with a registered identity. + * * Emits `IdentityKilled` if successful. + * * # * - `O(R + S + X)`. * - One balance-reserve operation. @@ -701,13 +858,17 @@ declare module '@polkadot/api/types/submittable' { killIdentity: AugmentedSubmittable<(target: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic>; /** * Provide a judgement for an account's identity. + * * The dispatch origin for this call must be _Signed_ and the sender must be the account * of the registrar whose index is `reg_index`. + * * - `reg_index`: the index of the registrar whose judgement is being made. * - `target`: the account whose identity the judgement is upon. This must be an account * with a registered identity. * - `judgement`: the judgement of the registrar of index `reg_index` about `target`. + * * Emits `JudgementGiven` if successful. + * * # * - `O(R + X)`. * - One balance-transfer operation. @@ -720,16 +881,22 @@ declare module '@polkadot/api/types/submittable' { provideJudgement: AugmentedSubmittable<(regIndex: Compact | AnyNumber | Uint8Array, target: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, judgement: IdentityJudgement | { Unknown: any } | { FeePaid: any } | { Reasonable: any } | { KnownGood: any } | { OutOfDate: any } | { LowQuality: any } | { Erroneous: any } | string | Uint8Array) => SubmittableExtrinsic>; /** * Request a judgement from a registrar. + * * Payment: At most `max_fee` will be reserved for payment to the registrar if judgement * given. + * * The dispatch origin for this call must be _Signed_ and the sender must have a * registered identity. + * * - `reg_index`: The index of the registrar whose judgement is requested. * - `max_fee`: The maximum fee that may be paid. This should just be auto-populated as: + * * ```nocompile * Self::registrars().get(reg_index).unwrap().fee * ``` + * * Emits `JudgementRequested` if successful. + * * # * - `O(R + X)`. * - One balance-reserve operation. @@ -743,10 +910,13 @@ declare module '@polkadot/api/types/submittable' { requestJudgement: AugmentedSubmittable<(regIndex: Compact | AnyNumber | Uint8Array, maxFee: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Change the account associated with a registrar. + * * The dispatch origin for this call must be _Signed_ and the sender must be the account * of the registrar whose index is `index`. + * * - `index`: the index of the registrar whose fee is to be set. * - `new`: the new account ID. + * * # * - `O(R)`. * - One storage mutation `O(R)`. @@ -756,10 +926,13 @@ declare module '@polkadot/api/types/submittable' { setAccountId: AugmentedSubmittable<(index: Compact | AnyNumber | Uint8Array, updated: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Set the fee required for a judgement to be requested from a registrar. + * * The dispatch origin for this call must be _Signed_ and the sender must be the account * of the registrar whose index is `index`. + * * - `index`: the index of the registrar whose fee is to be set. * - `fee`: the new fee. + * * # * - `O(R)`. * - One storage mutation `O(R)`. @@ -770,10 +943,13 @@ declare module '@polkadot/api/types/submittable' { setFee: AugmentedSubmittable<(index: Compact | AnyNumber | Uint8Array, fee: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Set the field information for a registrar. + * * The dispatch origin for this call must be _Signed_ and the sender must be the account * of the registrar whose index is `index`. + * * - `index`: the index of the registrar whose fee is to be set. * - `fields`: the fields that the registrar concerns themselves with. + * * # * - `O(R)`. * - One storage mutation `O(R)`. @@ -783,11 +959,16 @@ declare module '@polkadot/api/types/submittable' { setFields: AugmentedSubmittable<(index: Compact | AnyNumber | Uint8Array, fields: IdentityFields) => SubmittableExtrinsic>; /** * Set an account's identity information and reserve the appropriate deposit. + * * If the account already has identity information, the deposit is taken as part payment * for the new deposit. + * * The dispatch origin for this call must be _Signed_. + * * - `info`: The identity information. + * * Emits `IdentitySet` if successful. + * * # * - `O(X + X' + R)` * - where `X` additional-field-count (deposit-bounded and code-bounded) @@ -803,11 +984,15 @@ declare module '@polkadot/api/types/submittable' { setIdentity: AugmentedSubmittable<(info: IdentityInfo | { additional?: any; display?: any; legal?: any; web?: any; riot?: any; email?: any; pgpFingerprint?: any; image?: any; twitter?: any } | string | Uint8Array) => SubmittableExtrinsic>; /** * Set the sub-accounts of the sender. + * * Payment: Any aggregate balance reserved by previous `set_subs` calls will be returned * and an amount `SubAccountDeposit` will be reserved for each item in `subs`. + * * The dispatch origin for this call must be _Signed_ and the sender must have a registered * identity. + * * - `subs`: The identity's (new) sub-accounts. + * * # * - `O(P + S)` * - where `P` old-subs-count (hard- and deposit-bounded). @@ -833,10 +1018,15 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * Assign an previously unassigned index. + * * Payment: `Deposit` is reserved from the sender account. + * * The dispatch origin for this call must be _Signed_. + * * - `index`: the index to be claimed. This must not be in use. + * * Emits `IndexAssigned` if successful. + * * # * - `O(1)`. * - One storage mutation (codec `O(1)`). @@ -848,10 +1038,14 @@ declare module '@polkadot/api/types/submittable' { /** * Force an index to an account. This doesn't require a deposit. If the index is already * held, then any deposit is reimbursed to its current owner. + * * The dispatch origin for this call must be _Root_. + * * - `index`: the index to be (re-)assigned. * - `new`: the new owner of the index. This function is a no-op if it is equal to sender. + * * Emits `IndexAssigned` if successful. + * * # * - `O(1)`. * - One storage mutation (codec `O(1)`). @@ -862,10 +1056,15 @@ declare module '@polkadot/api/types/submittable' { forceTransfer: AugmentedSubmittable<(updated: AccountId | string | Uint8Array, index: AccountIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Free up an index owned by the sender. + * * Payment: Any previous deposit placed for the index is unreserved in the sender account. + * * The dispatch origin for this call must be _Signed_ and the sender must own the index. + * * - `index`: the index to be freed. This must be owned by the sender. + * * Emits `IndexFreed` if successful. + * * # * - `O(1)`. * - One storage mutation (codec `O(1)`). @@ -877,10 +1076,14 @@ declare module '@polkadot/api/types/submittable' { /** * Assign an index already owned by the sender to another account. The balance reservation * is effectively transferred to the new account. + * * The dispatch origin for this call must be _Signed_. + * * - `index`: the index to be re-assigned. This must be owned by the sender. * - `new`: the new owner of the index. This function is a no-op if it is equal to sender. + * * Emits `IndexAssigned` if successful. + * * # * - `O(1)`. * - One storage mutation (codec `O(1)`). @@ -894,11 +1097,14 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * Send a call through a recovered account. + * * The dispatch origin for this call must be _Signed_ and registered to * be able to make calls on behalf of the recovered account. + * * Parameters: * - `account`: The recovered account you want to make a call on-behalf-of. * - `call`: The call you want to make with the recovered account. + * * # * - The weight of the `call` + 10,000. * - One storage lookup to check account is recovered by `who`. O(1) @@ -907,10 +1113,13 @@ declare module '@polkadot/api/types/submittable' { asRecovered: AugmentedSubmittable<(account: AccountId | string | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic>; /** * Cancel the ability to use `as_recovered` for `account`. + * * The dispatch origin for this call must be _Signed_ and registered to * be able to make calls on behalf of the recovered account. + * * Parameters: * - `account`: The recovered account you are able to call on-behalf-of. + * * # * - One storage mutation to check account is recovered by `who`. O(1) * # @@ -918,12 +1127,15 @@ declare module '@polkadot/api/types/submittable' { cancelRecovered: AugmentedSubmittable<(account: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Allow a successful rescuer to claim their recovered account. + * * The dispatch origin for this call must be _Signed_ and must be a "rescuer" * who has successfully completed the account recovery process: collected * `threshold` or more vouches, waited `delay_period` blocks since initiation. + * * Parameters: * - `account`: The lost account that you want to claim has been successfully * recovered by you. + * * # * Key: F (len of friends in config), V (len of vouching friends) * - One storage read to get the recovery configuration. O(1), Codec O(F) @@ -931,6 +1143,7 @@ declare module '@polkadot/api/types/submittable' { * - One storage read to get the current block number. O(1) * - One storage write. O(1), Codec O(V). * - One event. + * * Total Complexity: O(F + V) * # **/ @@ -938,27 +1151,35 @@ declare module '@polkadot/api/types/submittable' { /** * As the controller of a recoverable account, close an active recovery * process for your account. + * * Payment: By calling this function, the recoverable account will receive * the recovery deposit `RecoveryDeposit` placed by the rescuer. + * * The dispatch origin for this call must be _Signed_ and must be a * recoverable account with an active recovery process for it. + * * Parameters: * - `rescuer`: The account trying to rescue this recoverable account. + * * # * Key: V (len of vouching friends) * - One storage read/remove to get the active recovery process. O(1), Codec O(V) * - One balance call to repatriate reserved. O(X) * - One event. + * * Total Complexity: O(V + X) * # **/ closeRecovery: AugmentedSubmittable<(rescuer: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Create a recovery configuration for your account. This makes your account recoverable. + * * Payment: `ConfigDepositBase` + `FriendDepositFactor` * #_of_friends balance * will be reserved for storing the recovery configuration. This deposit is returned * in full when the user calls `remove_recovery`. + * * The dispatch origin for this call must be _Signed_. + * * Parameters: * - `friends`: A list of friends you trust to vouch for recovery attempts. * Should be ordered and contain no duplicate values. @@ -967,6 +1188,7 @@ declare module '@polkadot/api/types/submittable' { * the length of the list of friends. * - `delay_period`: The number of blocks after a recovery attempt is initialized * that needs to pass before the account can be recovered. + * * # * - Key: F (len of friends) * - One storage read to check that account is not already recoverable. O(1). @@ -974,19 +1196,24 @@ declare module '@polkadot/api/types/submittable' { * - One currency reserve operation. O(X) * - One storage write. O(1). Codec O(F). * - One event. + * * Total Complexity: O(F + X) * # **/ createRecovery: AugmentedSubmittable<(friends: Vec | (AccountId | string | Uint8Array)[], threshold: u16 | AnyNumber | Uint8Array, delayPeriod: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Initiate the process for recovering a recoverable account. + * * Payment: `RecoveryDeposit` balance will be reserved for initiating the * recovery process. This deposit will always be repatriated to the account * trying to be recovered. See `close_recovery`. + * * The dispatch origin for this call must be _Signed_. + * * Parameters: * - `account`: The lost account that you want to recover. This account * needs to be recoverable (i.e. have a recovery configuration). + * * # * - One storage read to check that account is recoverable. O(F) * - One storage read to check that this recovery process hasn't already started. O(1) @@ -994,25 +1221,31 @@ declare module '@polkadot/api/types/submittable' { * - One storage read to get the current block number. O(1) * - One storage write. O(1). * - One event. + * * Total Complexity: O(F + X) * # **/ initiateRecovery: AugmentedSubmittable<(account: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Remove the recovery process for your account. Recovered accounts are still accessible. + * * NOTE: The user must make sure to call `close_recovery` on all active * recovery attempts before calling this function else it will fail. + * * Payment: By calling this function the recoverable account will unreserve * their recovery configuration deposit. * (`ConfigDepositBase` + `FriendDepositFactor` * #_of_friends) + * * The dispatch origin for this call must be _Signed_ and must be a * recoverable account (i.e. has a recovery configuration). + * * # * Key: F (len of friends) * - One storage read to get the prefix iterator for active recoveries. O(1) * - One storage read/remove to get the recovery configuration. O(1), Codec O(F) * - One balance call to unreserved. O(X) * - One event. + * * Total Complexity: O(F + X) * # **/ @@ -1020,10 +1253,13 @@ declare module '@polkadot/api/types/submittable' { /** * Allow ROOT to bypass the recovery process and set an a rescuer account * for a lost account directly. + * * The dispatch origin for this call must be _ROOT_. + * * Parameters: * - `lost`: The "lost account" to be recovered. * - `rescuer`: The "rescuer account" which can call as the lost account. + * * # * - One storage write O(1) * - One event @@ -1033,14 +1269,18 @@ declare module '@polkadot/api/types/submittable' { /** * Allow a "friend" of a recoverable account to vouch for an active recovery * process for that account. + * * The dispatch origin for this call must be _Signed_ and must be a "friend" * for the recoverable account. + * * Parameters: * - `lost`: The lost account that you want to recover. * - `rescuer`: The account trying to rescue the lost account that you * want to vouch for. + * * The combination of these two parameters must point to an active recovery * process. + * * # * Key: F (len of friends in config), V (len of vouching friends) * - One storage read to get the recovery configuration. O(1), Codec O(F) @@ -1049,6 +1289,7 @@ declare module '@polkadot/api/types/submittable' { * - One binary search to confirm caller has not already vouched. O(logV) * - One storage write. O(1), Codec O(V). * - One event. + * * Total Complexity: O(F + logF + V + logV) * # **/ @@ -1059,7 +1300,9 @@ declare module '@polkadot/api/types/submittable' { /** * Removes any session key(s) of the function caller. * This doesn't take effect until the next session. + * * The dispatch origin of this function must be signed. + * * # * - Complexity: `O(1)` in number of key types. * Actual cost depends on the number of length of `T::Keys::key_ids()` which is fixed. @@ -1073,7 +1316,9 @@ declare module '@polkadot/api/types/submittable' { * Sets the session key(s) of the function caller to `keys`. * Allows an account to set its session key prior to becoming a validator. * This doesn't take effect until the next session. + * * The dispatch origin of this function must be signed. + * * # * - Complexity: `O(1)` * Actual cost depends on the number of length of `T::Keys::key_ids()` which is fixed. @@ -1089,11 +1334,15 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * A user outside of the society can make a bid for entry. + * * Payment: `CandidateDeposit` will be reserved for making a bid. It is returned * when the bid becomes a member, or if the bid calls `unbid`. + * * The dispatch origin for this call must be _Signed_. + * * Parameters: * - `value`: A one time payment the bid would like to receive when joining the society. + * * # * Key: B (len of bids), C (len of candidates), M (len of members), X (balance reserve) * - Storage Reads: @@ -1114,54 +1363,70 @@ declare module '@polkadot/api/types/submittable' { * - Events: * - One event for new bid. * - Up to one event for AutoUnbid if bid.len() > MAX_BID_COUNT. + * * Total Complexity: O(M + B + C + logM + logB + X) * # **/ bid: AugmentedSubmittable<(value: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * As a member, vote on the defender. + * * The dispatch origin for this call must be _Signed_ and a member. + * * Parameters: * - `approve`: A boolean which says if the candidate should be * approved (`true`) or rejected (`false`). + * * # * - Key: M (len of members) * - One storage read O(M) and O(log M) search to check user is a member. * - One storage write to add vote to votes. O(1) * - One event. + * * Total Complexity: O(M + logM) * # **/ defenderVote: AugmentedSubmittable<(approve: bool | boolean | Uint8Array) => SubmittableExtrinsic>; /** * Found the society. + * * This is done as a discrete action in order to allow for the * module to be included into a running chain and can only be done once. + * * The dispatch origin for this call must be from the _FounderSetOrigin_. + * * Parameters: * - `founder` - The first member and head of the newly founded society. * - `max_members` - The initial max number of members for the society. * - `rules` - The rules of this society concerning membership. + * * # * - Two storage mutates to set `Head` and `Founder`. O(1) * - One storage write to add the first member to society. O(1) * - One event. + * * Total Complexity: O(1) * # **/ found: AugmentedSubmittable<(founder: AccountId | string | Uint8Array, maxMembers: u32 | AnyNumber | Uint8Array, rules: Bytes | string | Uint8Array) => SubmittableExtrinsic>; /** * Allow suspended judgement origin to make judgement on a suspended candidate. + * * If the judgement is `Approve`, we add them to society as a member with the appropriate * payment for joining society. + * * If the judgement is `Reject`, we either slash the deposit of the bid, giving it back * to the society treasury, or we ban the voucher from vouching again. + * * If the judgement is `Rebid`, we put the candidate back in the bid pool and let them go * through the induction process again. + * * The dispatch origin for this call must be from the _SuspensionJudgementOrigin_. + * * Parameters: * - `who` - The suspended candidate to be judged. * - `judgement` - `Approve`, `Reject`, or `Rebid`. + * * # * Key: B (len of bids), M (len of members), X (balance action) * - One storage read to check `who` is a suspended candidate. @@ -1182,21 +1447,27 @@ declare module '@polkadot/api/types/submittable' { * - Up to one additional event if unvouch takes place. * - One storage removal. * - One event for the judgement. + * * Total Complexity: O(M + logM + B + X) * # **/ judgeSuspendedCandidate: AugmentedSubmittable<(who: AccountId | string | Uint8Array, judgement: SocietyJudgement | 'Rebid'|'Reject'|'Approve' | number | Uint8Array) => SubmittableExtrinsic>; /** * Allow suspension judgement origin to make judgement on a suspended member. + * * If a suspended member is forgiven, we simply add them back as a member, not affecting * any of the existing storage items for that member. + * * If a suspended member is rejected, remove all associated storage items, including * their payouts, and remove any vouched bids they currently have. + * * The dispatch origin for this call must be from the _SuspensionJudgementOrigin_. + * * Parameters: * - `who` - The suspended member to be judged. * - `forgive` - A boolean representing whether the suspension judgement origin * forgives (`true`) or rejects (`false`) a suspended member. + * * # * Key: B (len of bids), M (len of members) * - One storage read to check `who` is a suspended member. O(1) @@ -1206,17 +1477,22 @@ declare module '@polkadot/api/types/submittable' { * - Up to one additional event if unvouch takes place. * - One storage removal. O(1) * - One event for the judgement. + * * Total Complexity: O(M + logM + B) * # **/ judgeSuspendedMember: AugmentedSubmittable<(who: AccountId | string | Uint8Array, forgive: bool | boolean | Uint8Array) => SubmittableExtrinsic>; /** * Transfer the first matured payout for the sender and remove it from the records. + * * NOTE: This extrinsic needs to be called multiple times to claim multiple matured payouts. + * * Payment: The member will receive a payment equal to their first matured * payout to their free balance. + * * The dispatch origin for this call must be _Signed_ and a member with * payouts remaining. + * * # * Key: M (len of members), P (number of payouts for a particular member) * - One storage read O(M) and O(log M) search to check signer is a member. @@ -1224,6 +1500,7 @@ declare module '@polkadot/api/types/submittable' { * - One storage read O(1) to get the current block number. * - One currency transfer call. O(X) * - One storage write or removal to update the member's payouts. O(P) + * * Total Complexity: O(M + logM + P + X) * # **/ @@ -1231,12 +1508,16 @@ declare module '@polkadot/api/types/submittable' { /** * Allows root origin to change the maximum number of members in society. * Max membership count must be greater than 1. + * * The dispatch origin for this call must be from _ROOT_. + * * Parameters: * - `max` - The maximum number of members for the society. + * * # * - One storage write to update the max. O(1) * - One event. + * * Total Complexity: O(1) * # **/ @@ -1245,28 +1526,36 @@ declare module '@polkadot/api/types/submittable' { * A bidder can remove their bid for entry into society. * By doing so, they will have their candidate deposit returned or * they will unvouch their voucher. + * * Payment: The bid deposit is unreserved if the user made a bid. + * * The dispatch origin for this call must be _Signed_ and a bidder. + * * Parameters: * - `pos`: Position in the `Bids` vector of the bid who wants to unbid. + * * # * Key: B (len of bids), X (balance unreserve) * - One storage read and write to retrieve and update the bids. O(B) * - Either one unreserve balance action O(X) or one vouching storage removal. O(1) * - One event. + * * Total Complexity: O(B + X) * # **/ unbid: AugmentedSubmittable<(pos: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Annul the founding of the society. + * * The dispatch origin for this call must be Signed, and the signing account must be both * the `Founder` and the `Head`. This implies that it may only be done when there is one * member. + * * # * - Two storage reads O(1). * - Four storage removals O(1). * - One event. + * * Total Complexity: O(1) * # **/ @@ -1274,26 +1563,33 @@ declare module '@polkadot/api/types/submittable' { /** * As a vouching member, unvouch a bid. This only works while vouched user is * only a bidder (and not a candidate). + * * The dispatch origin for this call must be _Signed_ and a vouching member. + * * Parameters: * - `pos`: Position in the `Bids` vector of the bid who should be unvouched. + * * # * Key: B (len of bids) * - One storage read O(1) to check the signer is a vouching member. * - One storage mutate to retrieve and update the bids. O(B) * - One vouching storage removal. O(1) * - One event. + * * Total Complexity: O(B) * # **/ unvouch: AugmentedSubmittable<(pos: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * As a member, vote on a candidate. + * * The dispatch origin for this call must be _Signed_ and a member. + * * Parameters: * - `candidate`: The candidate that the member would like to bid on. * - `approve`: A boolean which says if the candidate should be * approved (`true`) or rejected (`false`). + * * # * Key: C (len of candidates), M (len of members) * - One storage read O(M) and O(log M) search to check user is a member. @@ -1301,24 +1597,30 @@ declare module '@polkadot/api/types/submittable' { * - One storage read O(C) and O(C) search to check that user is a candidate. * - One storage write to add vote to votes. O(1) * - One event. + * * Total Complexity: O(M + logM + C) * # **/ vote: AugmentedSubmittable<(candidate: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, approve: bool | boolean | Uint8Array) => SubmittableExtrinsic>; /** * As a member, vouch for someone to join society by placing a bid on their behalf. + * * There is no deposit required to vouch for a new bid, but a member can only vouch for * one bid at a time. If the bid becomes a suspended candidate and ultimately rejected by * the suspension judgement origin, the member will be banned from vouching again. + * * As a vouching member, you can claim a tip if the candidate is accepted. This tip will * be paid as a portion of the reward the member will receive for joining the society. + * * The dispatch origin for this call must be _Signed_ and a member. + * * Parameters: * - `who`: The user who you would like to vouch for. * - `value`: The total reward to be paid between you and the candidate if they become * a member in the society. * - `tip`: Your cut of the total `value` payout when the candidate is inducted into * the society. Tips larger than `value` will be saturated upon payout. + * * # * Key: B (len of bids), C (len of candidates), M (len of members) * - Storage Reads: @@ -1342,6 +1644,7 @@ declare module '@polkadot/api/types/submittable' { * - Events: * - One event for vouch. * - Up to one event for AutoUnbid if bid.len() > MAX_BID_COUNT. + * * Total Complexity: O(M + B + C + logM + logB + X) * # **/ @@ -1352,13 +1655,18 @@ declare module '@polkadot/api/types/submittable' { /** * Take the origin account as a stash and lock up `value` of its balance. `controller` will * be the account that controls it. + * * `value` must be more than the `minimum_balance` specified by `T::Currency`. + * * The dispatch origin for this call must be _Signed_ by the stash account. + * * Emits `Bonded`. + * * # * - Independent of the arguments. Moderate complexity. * - O(1). * - Three extra DB entries. + * * NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned * unless the `origin` falls below _existential deposit_ and gets removed as dust. * # @@ -1367,12 +1675,16 @@ declare module '@polkadot/api/types/submittable' { /** * Add some extra amount that have appeared in the stash `free_balance` into the balance up * for staking. + * * Use this if there are additional funds in your stash account that you wish to bond. * Unlike [`bond`] or [`unbond`] this function does not impose any limitation on the amount * that can be added. + * * The dispatch origin for this call must be _Signed_ by the stash, not the controller and * it can be only called when [`EraElectionStatus`] is `Closed`. + * * Emits `Bonded`. + * * # * - Independent of the arguments. Insignificant complexity. * - O(1). @@ -1384,6 +1696,7 @@ declare module '@polkadot/api/types/submittable' { * Cancel enactment of a deferred slash. Can be called by either the root origin or * the `T::SlashCancelOrigin`. * passing the era and indices of the slashes for that era to kill. + * * # * - One storage write. * # @@ -1391,9 +1704,12 @@ declare module '@polkadot/api/types/submittable' { cancelDeferredSlash: AugmentedSubmittable<(era: EraIndex | AnyNumber | Uint8Array, slashIndices: Vec | (u32 | AnyNumber | Uint8Array)[]) => SubmittableExtrinsic>; /** * Declare no desire to either validate or nominate. + * * Effects will be felt at the beginning of the next era. + * * The dispatch origin for this call must be _Signed_ by the controller, not the stash. * And, it can be only called when [`EraElectionStatus`] is `Closed`. + * * # * - Independent of the arguments. Insignificant complexity. * - Contains one read. @@ -1404,6 +1720,7 @@ declare module '@polkadot/api/types/submittable' { /** * Force there to be a new era at the end of the next session. After this, it will be * reset to normal (non-forced) behaviour. + * * # * - No arguments. * # @@ -1411,6 +1728,7 @@ declare module '@polkadot/api/types/submittable' { forceNewEra: AugmentedSubmittable<() => SubmittableExtrinsic>; /** * Force there to be a new era at the end of sessions indefinitely. + * * # * - One storage write * # @@ -1418,6 +1736,7 @@ declare module '@polkadot/api/types/submittable' { forceNewEraAlways: AugmentedSubmittable<() => SubmittableExtrinsic>; /** * Force there to be no new eras indefinitely. + * * # * - No arguments. * # @@ -1429,10 +1748,13 @@ declare module '@polkadot/api/types/submittable' { forceUnstake: AugmentedSubmittable<(stash: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Declare the desire to nominate `targets` for the origin controller. + * * Effects will be felt at the beginning of the next era. This can only be called when * [`EraElectionStatus`] is `Closed`. + * * The dispatch origin for this call must be _Signed_ by the controller, not the stash. * And, it can be only called when [`EraElectionStatus`] is `Closed`. + * * # * - The transaction's complexity is proportional to the size of `targets`, * which is capped at CompactAssignments::LIMIT. @@ -1444,7 +1766,9 @@ declare module '@polkadot/api/types/submittable' { * **This extrinsic will be removed after `MigrationEra + HistoryDepth` has passed, giving * opportunity for users to claim all rewards before moving to Simple Payouts. After this * time, you should use `payout_stakers` instead.** + * * Make one nominator's payout for one era. + * * - `who` is the controller account of the nominator to pay out. * - `era` may not be lower than one following the most recently paid era. If it is higher, * then it indicates an instruction to skip the payout of all previous eras. @@ -1454,9 +1778,12 @@ declare module '@polkadot/api/types/submittable' { * `(validator, index of `who` in clipped exposure of validator)`. * If it is incomplete, then less than the full reward will be paid out. * It must not exceed `MAX_NOMINATIONS`. + * * WARNING: once an era is payed for a validator such validator can't claim the payout of * previous era. + * * WARNING: Incorrect arguments here can result in loss of payout. Be very careful. + * * # * - Number of storage read of `O(validators)`; `validators` is the argument of the call, * and is bounded by `MAX_NOMINATIONS`. @@ -1470,12 +1797,16 @@ declare module '@polkadot/api/types/submittable' { payoutNominator: AugmentedSubmittable<(era: EraIndex | AnyNumber | Uint8Array, validators: Vec> | ([AccountId | string | Uint8Array, u32 | AnyNumber | Uint8Array])[]) => SubmittableExtrinsic>; /** * Pay out all the stakers behind a single validator for a single era. + * * - `validator_stash` is the stash account of the validator. Their nominators, up to * `T::MaxNominatorRewardedPerValidator`, will also receive their rewards. * - `era` may be any era between `[current_era - history_depth; current_era]`. + * * The origin of this call must be _Signed_. Any account can call this function, even if * it is not one of the stakers. + * * This can only be called when [`EraElectionStatus`] is `Closed`. + * * # * - Time complexity: at most O(MaxNominatorRewardedPerValidator). * - Contains a limited number of reads and writes. @@ -1486,13 +1817,18 @@ declare module '@polkadot/api/types/submittable' { * **This extrinsic will be removed after `MigrationEra + HistoryDepth` has passed, giving * opportunity for users to claim all rewards before moving to Simple Payouts. After this * time, you should use `payout_stakers` instead.** + * * Make one validator's payout for one era. + * * - `who` is the controller account of the validator to pay out. * - `era` may not be lower than one following the most recently paid era. If it is higher, * then it indicates an instruction to skip the payout of all previous eras. + * * WARNING: once an era is payed for a validator such validator can't claim the payout of * previous era. + * * WARNING: Incorrect arguments here can result in loss of payout. Be very careful. + * * # * - Time complexity: O(1). * - Contains a limited number of reads and writes. @@ -1503,14 +1839,18 @@ declare module '@polkadot/api/types/submittable' { * Remove all data structure concerning a staker/stash once its balance is zero. * This is essentially equivalent to `withdraw_unbonded` except it can be called by anyone * and the target `stash` must have no funds left. + * * This can be called from any origin. + * * - `stash`: The stash account to reap. Its balance must be zero. **/ reapStash: AugmentedSubmittable<(stash: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Rebond a portion of the stash scheduled to be unlocked. + * * The dispatch origin must be signed by the controller, and it can be only called when * [`EraElectionStatus`] is `Closed`. + * * # * - Time complexity: O(1). Bounded by `MAX_UNLOCKING_CHUNKS`. * - Storage changes: Can't increase storage, only decrease it. @@ -1519,8 +1859,11 @@ declare module '@polkadot/api/types/submittable' { rebond: AugmentedSubmittable<(value: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * (Re-)set the controller of a stash. + * * Effects will be felt at the beginning of the next era. + * * The dispatch origin for this call must be _Signed_ by the stash, not the controller. + * * # * - Independent of the arguments. Insignificant complexity. * - Contains a limited number of reads. @@ -1530,6 +1873,7 @@ declare module '@polkadot/api/types/submittable' { setController: AugmentedSubmittable<(controller: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic>; /** * Set history_depth value. + * * Origin must be root. **/ setHistoryDepth: AugmentedSubmittable<(newHistoryDepth: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; @@ -1539,8 +1883,11 @@ declare module '@polkadot/api/types/submittable' { setInvulnerables: AugmentedSubmittable<(validators: Vec | (AccountId | string | Uint8Array)[]) => SubmittableExtrinsic>; /** * (Re-)set the payment target for a controller. + * * Effects will be felt at the beginning of the next era. + * * The dispatch origin for this call must be _Signed_ by the controller, not the stash. + * * # * - Independent of the arguments. Insignificant complexity. * - Contains a limited number of reads. @@ -1554,23 +1901,33 @@ declare module '@polkadot/api/types/submittable' { setValidatorCount: AugmentedSubmittable<(updated: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Submit a phragmen result to the chain. If the solution: + * * 1. is valid. * 2. has a better score than a potentially existing solution on chain. + * * then, it will be _put_ on chain. + * * A solution consists of two pieces of data: + * * 1. `winners`: a flat vector of all the winners of the round. * 2. `assignments`: the compact version of an assignment vector that encodes the edge * weights. + * * Both of which may be computed using [`phragmen`], or any other algorithm. + * * Additionally, the submitter must provide: + * * - The `score` that they claim their solution has. + * * Both validators and nominators will be represented by indices in the solution. The * indices should respect the corresponding types ([`ValidatorIndex`] and * [`NominatorIndex`]). Moreover, they should be valid when used to index into * [`SnapshotValidators`] and [`SnapshotNominators`]. Any invalid index will cause the * solution to be rejected. These two storage items are set during the election window and * may be used to determine the indices. + * * A solution is valid if: + * * 0. It is submitted when [`EraElectionStatus`] is `Open`. * 1. Its claimed score is equal to the score computed on-chain. * 2. Presents the correct number of winners. @@ -1579,37 +1936,49 @@ declare module '@polkadot/api/types/submittable' { * or billion). * 4. For each edge, all targets are actually nominated by the voter. * 5. Has correct self-votes. + * * A solutions score is consisted of 3 parameters: + * * 1. `min { support.total }` for each support of a winner. This value should be maximized. * 2. `sum { support.total }` for each support of a winner. This value should be minimized. * 3. `sum { support.total^2 }` for each support of a winner. This value should be * minimized (to ensure less variance) + * * # * E: number of edges. m: size of winner committee. n: number of nominators. d: edge degree * (16 for now) v: number of on-chain validator candidates. + * * NOTE: given a solution which is reduced, we can enable a new check the ensure `|E| < n + * m`. We don't do this _yet_, but our offchain worker code executes it nonetheless. + * * major steps (all done in `check_and_replace_solution`): + * * - Storage: O(1) read `ElectionStatus`. * - Storage: O(1) read `PhragmenScore`. * - Storage: O(1) read `ValidatorCount`. * - Storage: O(1) length read from `SnapshotValidators`. + * * - Storage: O(v) reads of `AccountId` to fetch `snapshot_validators`. * - Memory: O(m) iterations to map winner index to validator id. * - Storage: O(n) reads `AccountId` to fetch `snapshot_nominators`. * - Memory: O(n + m) reads to map index to `AccountId` for un-compact. + * * - Storage: O(e) accountid reads from `Nomination` to read correct nominations. * - Storage: O(e) calls into `slashable_balance_of_vote_weight` to convert ratio to staked. + * * - Memory: build_support_map. O(e). * - Memory: evaluate_support: O(E). + * * - Storage: O(e) writes to `QueuedElected`. * - Storage: O(1) write to `QueuedScore` + * * The weight of this call is 1/10th of the blocks total weight. * # **/ submitElectionSolution: AugmentedSubmittable<(winners: Vec | (ValidatorIndex | AnyNumber | Uint8Array)[], compactAssignments: CompactAssignments | { votes1?: any; votes2?: any; votes3?: any; votes4?: any; votes5?: any; votes6?: any; votes7?: any; votes8?: any; votes9?: any; votes10?: any; votes11?: any; votes12?: any; votes13?: any; votes14?: any; votes15?: any; votes16?: any } | string | Uint8Array, score: PhragmenScore, era: EraIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Unsigned version of `submit_election_solution`. + * * Note that this must pass the [`ValidateUnsigned`] check which only allows transactions * from the local node to be included. In other words, only the block author can include a * transaction in the block. @@ -1619,15 +1988,21 @@ declare module '@polkadot/api/types/submittable' { * Schedule a portion of the stash to be unlocked ready for transfer out after the bond * period ends. If this leaves an amount actively bonded less than * T::Currency::minimum_balance(), then it is increased to the full amount. + * * Once the unlock period is done, you can call `withdraw_unbonded` to actually move * the funds out of management ready for transfer. + * * No more than a limited number of unlocking chunks (see `MAX_UNLOCKING_CHUNKS`) * can co-exists at the same time. In that case, [`Call::withdraw_unbonded`] need * to be called first to remove some of the chunks (if possible). + * * The dispatch origin for this call must be _Signed_ by the controller, not the stash. * And, it can be only called when [`EraElectionStatus`] is `Closed`. + * * Emits `Unbonded`. + * * See also [`Call::withdraw_unbonded`]. + * * # * - Independent of the arguments. Limited but potentially exploitable complexity. * - Contains a limited number of reads. @@ -1641,9 +2016,12 @@ declare module '@polkadot/api/types/submittable' { unbond: AugmentedSubmittable<(value: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Declare the desire to validate for the origin controller. + * * Effects will be felt at the beginning of the next era. + * * The dispatch origin for this call must be _Signed_ by the controller, not the stash. * And, it can be only called when [`EraElectionStatus`] is `Closed`. + * * # * - Independent of the arguments. Insignificant complexity. * - Contains a limited number of reads. @@ -1653,12 +2031,17 @@ declare module '@polkadot/api/types/submittable' { validate: AugmentedSubmittable<(prefs: ValidatorPrefs | { commission?: any } | string | Uint8Array) => SubmittableExtrinsic>; /** * Remove any unlocked chunks from the `unlocking` queue from our management. + * * This essentially frees up that balance to be used by the stash account to do * whatever it wants. + * * The dispatch origin for this call must be _Signed_ by the controller, not the stash. * And, it can be only called when [`EraElectionStatus`] is `Closed`. + * * Emits `Withdrawn`. + * * See also [`Call::unbond`]. + * * # * - Could be dependent on the `origin` argument and how much `unlocking` chunks exist. * It implies `consolidate_unlocked` which loops over `Ledger.unlocking`, which is @@ -1673,7 +2056,9 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * Authenticates the current sudo key and sets the given AccountId (`new`) as the new sudo key. + * * The dispatch origin for this call must be _Signed_. + * * # * - O(1). * - Limited storage reads. @@ -1683,7 +2068,9 @@ declare module '@polkadot/api/types/submittable' { setKey: AugmentedSubmittable<(updated: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic>; /** * Authenticates the sudo key and dispatches a function call with `Root` origin. + * * The dispatch origin for this call must be _Signed_. + * * # * - O(1). * - Limited storage reads. @@ -1695,7 +2082,9 @@ declare module '@polkadot/api/types/submittable' { /** * Authenticates the sudo key and dispatches a function call with `Signed` origin from * a given account. + * * The dispatch origin for this call must be _Signed_. + * * # * - O(1). * - Limited storage reads. @@ -1713,6 +2102,7 @@ declare module '@polkadot/api/types/submittable' { fillBlock: AugmentedSubmittable<(ratio: Perbill | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Kill all storage items with a key that starts with the given prefix. + * * # * - `O(P)` where `P` amount of keys with prefix `prefix` * - `P` storage deletions. @@ -1721,6 +2111,7 @@ declare module '@polkadot/api/types/submittable' { killPrefix: AugmentedSubmittable<(prefix: Key | string | Uint8Array) => SubmittableExtrinsic>; /** * Kill some items from storage. + * * # * - `O(VK)` where `V` length of `keys` and `K` length of one key * - `V` storage deletions. @@ -1729,6 +2120,7 @@ declare module '@polkadot/api/types/submittable' { killStorage: AugmentedSubmittable<(keys: Vec | (Key | string | Uint8Array)[]) => SubmittableExtrinsic>; /** * Make some on-chain remark. + * * # * - `O(1)` * # @@ -1736,6 +2128,7 @@ declare module '@polkadot/api/types/submittable' { remark: AugmentedSubmittable<(remark: Bytes | string | Uint8Array) => SubmittableExtrinsic>; /** * Set the new changes trie configuration. + * * # * - `O(D)` where `D` length of `Digest` * - 1 storage write or delete (codec `O(1)`). @@ -1745,6 +2138,7 @@ declare module '@polkadot/api/types/submittable' { setChangesTrieConfig: AugmentedSubmittable<(changesTrieConfig: Option | null | object | string | Uint8Array) => SubmittableExtrinsic>; /** * Set the new runtime code. + * * # * - `O(C + S)` where `C` length of `code` and `S` complexity of `can_set_code` * - 1 storage write (codec `O(C)`). @@ -1755,6 +2149,7 @@ declare module '@polkadot/api/types/submittable' { setCode: AugmentedSubmittable<(code: Bytes | string | Uint8Array) => SubmittableExtrinsic>; /** * Set the new runtime code without doing any checks of the given `code`. + * * # * - `O(C)` where `C` length of `code` * - 1 storage write (codec `O(C)`). @@ -1764,6 +2159,7 @@ declare module '@polkadot/api/types/submittable' { setCodeWithoutChecks: AugmentedSubmittable<(code: Bytes | string | Uint8Array) => SubmittableExtrinsic>; /** * Set the number of pages in the WebAssembly environment's heap. + * * # * - `O(1)` * - 1 storage write. @@ -1772,6 +2168,7 @@ declare module '@polkadot/api/types/submittable' { setHeapPages: AugmentedSubmittable<(pages: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Set some items of storage. + * * # * - `O(I)` where `I` length of `items` * - `I` storage writes (`O(1)`). @@ -1781,6 +2178,7 @@ declare module '@polkadot/api/types/submittable' { /** * Kill the sending account, assuming there are no references outstanding and the composite * data is equal to its default value. + * * # * - `O(K)` with `K` being complexity of `on_killed_account` * - 1 storage read and deletion. @@ -1795,8 +2193,10 @@ declare module '@polkadot/api/types/submittable' { /** * May be called by any signed account after the voting duration has ended in order to * finish voting and close the proposal. + * * Abstentions are counted as rejections unless there is a prime member set and the prime * member cast an approval. + * * - the weight of `proposal` preimage. * - up to three events deposited. * - one read, two removals, one mutation. (plus three static reads.) @@ -1808,6 +2208,7 @@ declare module '@polkadot/api/types/submittable' { close: AugmentedSubmittable<(proposal: Hash | string | Uint8Array, index: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Dispatch a proposal from a member using the `Member` origin. + * * Origin must be a member of the collective. **/ execute: AugmentedSubmittable<(proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic>; @@ -1820,8 +2221,10 @@ declare module '@polkadot/api/types/submittable' { propose: AugmentedSubmittable<(threshold: Compact | AnyNumber | Uint8Array, proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic>; /** * Set the collective's membership. + * * - `new_members`: The new member list. Be nice to the chain and * - `prime`: The prime member whose vote sets the default. + * * Requires root origin. **/ setMembers: AugmentedSubmittable<(newMembers: Vec | (AccountId | string | Uint8Array)[], prime: Option | null | object | string | Uint8Array) => SubmittableExtrinsic>; @@ -1837,12 +2240,15 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * Add a member `who` to the set. + * * May only be called from `AddOrigin` or root. **/ addMember: AugmentedSubmittable<(who: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Swap out the sending member for some other key `new`. + * * May only be called from `Signed` origin of a current member. + * * Prime membership is passed from the origin account to `new`, if extant. **/ changeKey: AugmentedSubmittable<(updated: AccountId | string | Uint8Array) => SubmittableExtrinsic>; @@ -1852,12 +2258,14 @@ declare module '@polkadot/api/types/submittable' { clearPrime: AugmentedSubmittable<() => SubmittableExtrinsic>; /** * Remove a member `who` from the set. + * * May only be called from `RemoveOrigin` or root. **/ removeMember: AugmentedSubmittable<(who: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Change the membership to a new set, disregarding the existing membership. Be nice and * pass `members` pre-sorted. + * * May only be called from `ResetOrigin` or root. **/ resetMembers: AugmentedSubmittable<(members: Vec | (AccountId | string | Uint8Array)[]) => SubmittableExtrinsic>; @@ -1867,7 +2275,9 @@ declare module '@polkadot/api/types/submittable' { setPrime: AugmentedSubmittable<(who: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Swap out one member `remove` for another `add`. + * * May only be called from `SwapOrigin` or root. + * * Prime membership is *not* passed from `remove` to `add`, if extant. **/ swapMember: AugmentedSubmittable<(remove: AccountId | string | Uint8Array, add: AccountId | string | Uint8Array) => SubmittableExtrinsic>; @@ -1876,11 +2286,15 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * Set the current time. + * * This call should be invoked exactly once per block. It will panic at the finalization * phase, if this call hasn't been invoked by that time. + * * The timestamp should be greater than the previous one by the amount specified by * `MinimumPeriod`. + * * The dispatch origin for this call must be `Inherent`. + * * # * - `O(T)` where `T` complexity of `on_timestamp_set` * - 2 storage mutations (codec `O(1)`). @@ -1894,6 +2308,7 @@ declare module '@polkadot/api/types/submittable' { /** * Approve a proposal. At a later time, the proposal will be allocated to the beneficiary * and the original deposit will be returned. + * * # * - O(1). * - Limited storage reads. @@ -1903,10 +2318,14 @@ declare module '@polkadot/api/types/submittable' { approveProposal: AugmentedSubmittable<(proposalId: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Close and payout a tip. + * * The dispatch origin for this call must be _Signed_. + * * The tip identified by `hash` must have finished its countdown period. + * * - `hash`: The identity of the open tip for which a tip value is declared. This is formed * as the hash of the tuple of the original tip `reason` and the beneficiary account ID. + * * # * - `O(T)` * - One storage retrieval (codec `O(T)`) and two removals. @@ -1918,6 +2337,7 @@ declare module '@polkadot/api/types/submittable' { * Put forward a suggestion for spending. A deposit proportional to the value * is reserved and slashed if the proposal is rejected. It is returned once the * proposal is awarded. + * * # * - O(1). * - Limited storage reads. @@ -1927,6 +2347,7 @@ declare module '@polkadot/api/types/submittable' { proposeSpend: AugmentedSubmittable<(value: Compact | AnyNumber | Uint8Array, beneficiary: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic>; /** * Reject a proposed spend. The original deposit will be slashed. + * * # * - O(1). * - Limited storage reads. @@ -1936,13 +2357,18 @@ declare module '@polkadot/api/types/submittable' { rejectProposal: AugmentedSubmittable<(proposalId: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Report something `reason` that deserves a tip and claim any eventual the finder's fee. + * * The dispatch origin for this call must be _Signed_. + * * Payment: `TipReportDepositBase` will be reserved from the origin account, as well as * `TipReportDepositPerByte` for each byte in `reason`. + * * - `reason`: The reason for, or the thing that deserves, the tip; generally this will be * a UTF-8-encoded URL. * - `who`: The account which should be credited for the tip. + * * Emits `NewTip` if successful. + * * # * - `O(R)` where `R` length of `reason`. * - One balance operation. @@ -1953,13 +2379,18 @@ declare module '@polkadot/api/types/submittable' { reportAwesome: AugmentedSubmittable<(reason: Bytes | string | Uint8Array, who: AccountId | string | Uint8Array) => SubmittableExtrinsic>; /** * Retract a prior tip-report from `report_awesome`, and cancel the process of tipping. + * * If successful, the original deposit will be unreserved. + * * The dispatch origin for this call must be _Signed_ and the tip identified by `hash` * must have been reported by the signing account through `report_awesome` (and not * through `tip_new`). + * * - `hash`: The identity of the open tip for which a tip value is declared. This is formed * as the hash of the tuple of the original tip `reason` and the beneficiary account ID. + * * Emits `TipRetracted` if successful. + * * # * - `O(T)` * - One balance operation. @@ -1970,15 +2401,19 @@ declare module '@polkadot/api/types/submittable' { retractTip: AugmentedSubmittable<(hash: Hash | string | Uint8Array) => SubmittableExtrinsic>; /** * Declare a tip value for an already-open tip. + * * The dispatch origin for this call must be _Signed_ and the signing account must be a * member of the `Tippers` set. + * * - `hash`: The identity of the open tip for which a tip value is declared. This is formed * as the hash of the tuple of the hash of the original tip `reason` and the beneficiary * account ID. * - `tip_value`: The amount of tip that the sender would like to give. The median tip * value of active tippers will be given to the `who`. + * * Emits `TipClosing` if the threshold of tippers has been reached and the countdown period * has started. + * * # * - `O(T)` * - One storage mutation (codec `O(T)`), one storage read `O(1)`. @@ -1988,14 +2423,18 @@ declare module '@polkadot/api/types/submittable' { tip: AugmentedSubmittable<(hash: Hash | string | Uint8Array, tipValue: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Give a tip for something new; no finder's fee will be taken. + * * The dispatch origin for this call must be _Signed_ and the signing account must be a * member of the `Tippers` set. + * * - `reason`: The reason for, or the thing that deserves, the tip; generally this will be * a UTF-8-encoded URL. * - `who`: The account which should be credited for the tip. * - `tip_value`: The amount of tip that the sender would like to give. The median tip * value of active tippers will be given to the `who`. + * * Emits `NewTip` if successful. + * * # * - `O(R + T)` where `R` length of `reason`, `T` is the number of tippers. `T` is * naturally capped as a membership set, `R` is limited through transaction-size. @@ -2010,10 +2449,13 @@ declare module '@polkadot/api/types/submittable' { /** * Register approval for a dispatch to be made from a deterministic composite account if * approved by a total of `threshold - 1` of `other_signatories`. + * * Payment: `MultisigDepositBase` will be reserved if this is the first approval, plus * `threshold` times `MultisigDepositFactor`. It is returned once this dispatch happens or * is cancelled. + * * The dispatch origin for this call must be _Signed_. + * * - `threshold`: The total number of approvals for this dispatch before it is executed. * - `other_signatories`: The accounts (other than the sender) who can approve this * dispatch. May not be empty. @@ -2021,7 +2463,9 @@ declare module '@polkadot/api/types/submittable' { * not the first approval, then it must be `Some`, with the timepoint (block number and * transaction index) of the first approval transaction. * - `call_hash`: The hash of the call to be executed. + * * NOTE: If this is the final approval, you will want to use `as_multi` instead. + * * # * - `O(S)`. * - Up to one balance-reserve or unreserve operation. @@ -2040,11 +2484,15 @@ declare module '@polkadot/api/types/submittable' { /** * Register approval for a dispatch to be made from a deterministic composite account if * approved by a total of `threshold - 1` of `other_signatories`. + * * If there are enough, then dispatch the call. + * * Payment: `MultisigDepositBase` will be reserved if this is the first approval, plus * `threshold` times `MultisigDepositFactor`. It is returned once this dispatch happens or * is cancelled. + * * The dispatch origin for this call must be _Signed_. + * * - `threshold`: The total number of approvals for this dispatch before it is executed. * - `other_signatories`: The accounts (other than the sender) who can approve this * dispatch. May not be empty. @@ -2052,11 +2500,14 @@ declare module '@polkadot/api/types/submittable' { * not the first approval, then it must be `Some`, with the timepoint (block number and * transaction index) of the first approval transaction. * - `call`: The call to be executed. + * * NOTE: Unless this is the final approval, you will generally want to use * `approve_as_multi` instead, since it only requires a hash of the call. + * * Result is equivalent to the dispatched result if `threshold` is exactly `1`. Otherwise * on success, result is `Ok` and the result from the interior call, if it was executed, * may be found in the deposited `MultisigExecuted` event. + * * # * - `O(S + Z + Call)`. * - Up to one balance-reserve or unreserve operation. @@ -2076,7 +2527,9 @@ declare module '@polkadot/api/types/submittable' { asMulti: AugmentedSubmittable<(threshold: u16 | AnyNumber | Uint8Array, otherSignatories: Vec | (AccountId | string | Uint8Array)[], maybeTimepoint: Option | null | object | string | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic>; /** * Send a call through an indexed pseudonym of the sender. + * * The dispatch origin for this call must be _Signed_. + * * # * - The weight of the `call` + 10,000. * # @@ -2084,13 +2537,18 @@ declare module '@polkadot/api/types/submittable' { asSub: AugmentedSubmittable<(index: u16 | AnyNumber | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic>; /** * Send a batch of dispatch calls. + * * This will execute until the first one fails and then stop. + * * May be called from any origin. + * * - `calls`: The calls to be dispatched from the same origin. + * * # * - The sum of the weights of the `calls`. * - One event. * # + * * This will return `Ok` in all circumstances. To determine the success of the batch, an * event is deposited. If a call failed and the batch was interrupted, then the * `BatchInterrupted` event is deposited, along with the number of successful calls made @@ -2101,13 +2559,16 @@ declare module '@polkadot/api/types/submittable' { /** * Cancel a pre-existing, on-going multisig transaction. Any deposit reserved previously * for this operation will be unreserved on success. + * * The dispatch origin for this call must be _Signed_. + * * - `threshold`: The total number of approvals for this dispatch before it is executed. * - `other_signatories`: The accounts (other than the sender) who can approve this * dispatch. May not be empty. * - `timepoint`: The timepoint (block number and transaction index) of the first approval * transaction for this dispatch. * - `call_hash`: The hash of the call to be executed. + * * # * - `O(S)`. * - Up to one balance-reserve or unreserve operation. @@ -2125,9 +2586,12 @@ declare module '@polkadot/api/types/submittable' { [index: string]: SubmittableExtrinsicFunction; /** * Unlock any vested funds of the sender account. + * * The dispatch origin for this call must be _Signed_ and the sender must have funds still * locked under this module. + * * Emits either `VestingCompleted` or `VestingUpdated`. + * * # * - `O(1)`. * - One balance-lock operation. @@ -2138,10 +2602,14 @@ declare module '@polkadot/api/types/submittable' { vest: AugmentedSubmittable<() => SubmittableExtrinsic>; /** * Unlock any vested funds of a `target` account. + * * The dispatch origin for this call must be _Signed_. + * * - `target`: The account whose vested funds should be unlocked. Must have funds still * locked under this module. + * * Emits either `VestingCompleted` or `VestingUpdated`. + * * # * - `O(1)`. * - Up to one account lookup. @@ -2153,11 +2621,15 @@ declare module '@polkadot/api/types/submittable' { vestOther: AugmentedSubmittable<(target: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic>; /** * Create a vested transfer. + * * The dispatch origin for this call must be _Signed_. + * * - `target`: The account that should be transferred the vested funds. * - `amount`: The amount of funds to transfer and will be vested. * - `schedule`: The vesting schedule attached to the transfer. + * * Emits `VestingCreated`. + * * # * - Creates a new storage entry, but is protected by a minimum transfer * amount needed to succeed. diff --git a/packages/typegen/package.json b/packages/typegen/package.json index e989e34134..96c1766485 100644 --- a/packages/typegen/package.json +++ b/packages/typegen/package.json @@ -41,6 +41,7 @@ "@polkadot/rpc-provider": "1.13.0-beta.6", "@polkadot/types": "1.13.0-beta.6", "@polkadot/util": "^2.10.0-beta.1", + "handlebars": "^4.7.6", "websocket": "^1.0.31", "yargs": "^15.3.1" }, diff --git a/packages/typegen/src/generate/consts.ts b/packages/typegen/src/generate/consts.ts index 6802fd4a1b..705c79f812 100644 --- a/packages/typegen/src/generate/consts.ts +++ b/packages/typegen/src/generate/consts.ts @@ -2,7 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { ModuleMetadataLatest } from '@polkadot/types/interfaces/metadata'; +import Handlebars from 'handlebars'; import staticData from '@polkadot/metadata/Metadata/static'; import Metadata from '@polkadot/metadata/Metadata'; @@ -10,29 +10,10 @@ import { TypeRegistry } from '@polkadot/types/create'; import * as defaultDefs from '@polkadot/types/interfaces/definitions'; import { stringCamelCase } from '@polkadot/util'; -import { FOOTER, HEADER, TypeImports, createDocComments, createImportCode, createImports, indent, registerDefinitions, setImports, writeFile } from '../util'; +import { createImports, compareName, readTemplate, registerDefinitions, setImports, writeFile } from '../util'; -// Generate types for one module -/** @internal */ -function generateModule (allDefs: object, { constants, name }: ModuleMetadataLatest, imports: TypeImports, isStrict: boolean): string[] { - if (!constants.length) { - return []; - } - - if (!isStrict) { - setImports(allDefs, imports, ['Codec']); - } - - return [indent(4)(`${stringCamelCase(name.toString())}: {`)] - .concat(isStrict ? '' : indent(6)('[index: string]: AugmentedConst;')) - .concat(constants.sort((a, b) => a.name.localeCompare(b.name.toString())).map(({ documentation, name, type }): string => { - setImports(allDefs, imports, [type.toString()]); - - return createDocComments(6, documentation) + - indent(6)(`${stringCamelCase(name.toString())}: AugmentedConst<${type}>;`); - })) - .concat([indent(4)('};')]); -} +const template = readTemplate('consts'); +const generateForMetaTemplate = Handlebars.compile(template); /** @internal */ function generateForMeta (meta: Metadata, dest: string, extraTypes: Record }>>, isStrict: boolean): void { @@ -42,27 +23,47 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: Record { return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs); }, {}); - const body = meta.asLatest.modules.sort((a, b) => a.name.localeCompare(b.name.toString())).reduce((acc, mod): string[] => { - return acc.concat(generateModule(allDefs, mod, imports, isStrict)); - }, [] as string[]); - const header = createImportCode(HEADER('chain'), imports, [ + + const modules = meta.asLatest.modules + .sort(compareName) + .filter((mod) => mod.constants.length > 0) + .map(({ constants, name }) => { + if (!isStrict) { + setImports(allDefs, imports, ['Codec']); + } + + const items = constants + .sort(compareName) + .map(({ documentation, name, type }) => { + setImports(allDefs, imports, [type.toString()]); + + return { + docs: documentation, + name: stringCamelCase(name.toString()), + type: type.toString() + }; + }); + + return { + items, + name: stringCamelCase(name.toString()) + }; + }); + + const types = [ ...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({ file: packagePath, types: Object.keys(imports.localTypes[packagePath]) })) - ]); - const interfaceStart = [ - "declare module '@polkadot/metadata/Decorated/consts/types' {", - indent(2)('export interface Constants {\n') - ].join('\n'); - const interfaceEnd = `\n${indent(2)('}')}\n}`; + ]; - return header - .concat(interfaceStart) - .concat(isStrict ? '' : indent(4)('[index: string]: ModuleConstants;\n')) - .concat(body.join('\n')) - .concat(interfaceEnd) - .concat(FOOTER); + return generateForMetaTemplate({ + headerType: 'chain', + imports, + isStrict, + modules, + types + }); }); } diff --git a/packages/typegen/src/generate/interfaceRegistry.ts b/packages/typegen/src/generate/interfaceRegistry.ts index 5383fa18b1..3c8082bdb5 100644 --- a/packages/typegen/src/generate/interfaceRegistry.ts +++ b/packages/typegen/src/generate/interfaceRegistry.ts @@ -2,17 +2,22 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import Handlebars from 'handlebars'; + import Raw from '@polkadot/types/codec/Raw'; import * as defaultDefinitions from '@polkadot/types/interfaces/definitions'; import * as defaultPrimitives from '@polkadot/types/primitive'; -import { FOOTER, HEADER, createImportCode, createImports, getDerivedTypes, indent, setImports, writeFile } from '../util'; +import { createImports, getDerivedTypes, readTemplate, setImports, writeFile } from '../util'; const primitiveClasses = { ...defaultPrimitives, Raw }; +const template = readTemplate('interfaceRegistry'); +const generateInterfaceTypesTemplate = Handlebars.compile(template); + /** @internal */ export function generateInterfaceTypes (importDefinitions: { [importPath: string]: object }, dest: string): void { writeFile(dest, (): string => { @@ -21,52 +26,43 @@ export function generateInterfaceTypes (importDefinitions: { [importPath: string const imports = createImports(importDefinitions); const definitions = imports.definitions; - const primitives = Object + const items: string[] = []; + + Object .keys(primitiveClasses) .filter((name): boolean => !!name.indexOf('Generic')) - .reduce((accumulator, primitiveName): string => { + .forEach((primitiveName) => { setImports(definitions, imports, [primitiveName]); - return [ - accumulator, - getDerivedTypes(definitions, primitiveName, primitiveName, imports).map(indent(4)).join('\n') - ].join('\n'); - }, ''); + items.push(...getDerivedTypes(definitions, primitiveName, primitiveName, imports)); + }); const existingTypes: Record = {}; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const srml = Object.entries(definitions).reduce((accumulator, [_defName, { types }]): string => { + Object.entries(definitions).forEach(([, { types }]) => { setImports(definitions, imports, Object.keys(types)); const uniqueTypes = Object.keys(types).filter((type) => !existingTypes[type]); - uniqueTypes.forEach((type) => { existingTypes[type] = true; }); + uniqueTypes.forEach((type) => { + existingTypes[type] = true; + items.push(...getDerivedTypes(definitions, type, types[type], imports)); + }); + }); - return [ - accumulator, - ...uniqueTypes.map((type): string => - getDerivedTypes(definitions, type, types[type], imports).map(indent(4)).join('\n') - ) - ].join('\n'); - }, ''); - - const header = createImportCode(HEADER('defs'), imports, [ + const types = [ ...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({ file: packagePath, types: Object.keys(imports.localTypes[packagePath]) })) - ]); + ]; - const interfaceStart = "declare module '@polkadot/types/types/registry' {\n export interface InterfaceTypes {"; - const interfaceEnd = '\n }\n}'; - - return header - .concat(interfaceStart) - .concat(primitives) - .concat(srml) - .concat(interfaceEnd) - .concat(FOOTER); + return generateInterfaceTypesTemplate({ + headerType: 'defs', + imports, + items, + types + }); }); } diff --git a/packages/typegen/src/generate/query.ts b/packages/typegen/src/generate/query.ts index 39c8832160..d831724bed 100644 --- a/packages/typegen/src/generate/query.ts +++ b/packages/typegen/src/generate/query.ts @@ -2,7 +2,9 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { ModuleMetadataLatest, StorageEntryMetadataLatest } from '@polkadot/types/interfaces/metadata'; +import Handlebars from 'handlebars'; + +import { StorageEntryMetadataLatest } from '@polkadot/types/interfaces/metadata'; import { Registry } from '@polkadot/types/types'; import staticData from '@polkadot/metadata/Metadata/static'; @@ -12,7 +14,7 @@ import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey'; import { TypeRegistry } from '@polkadot/types/create'; import { stringCamelCase } from '@polkadot/util'; -import { FOOTER, HEADER, TypeImports, createDocComments, createImportCode, createImports, formatType, getSimilarTypes, indent, registerDefinitions, setImports, writeFile } from '../util'; +import { TypeImports, createImports, compareName, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util'; // From a storage entry metadata, we return [args, returnType] /** @internal */ @@ -60,28 +62,8 @@ function entrySignature (allDefs: object, registry: Registry, storageEntry: Stor throw new Error(`entryArgs: Cannot parse args of entry ${storageEntry.name}`); } -// Generate types for one module -/** @internal */ -function generateModule (allDefs: object, registry: Registry, { name, storage }: ModuleMetadataLatest, imports: TypeImports, isStrict: boolean): string[] { - if (storage.isNone) { - return []; - } - - return [indent(4)(`${stringCamelCase(name.toString())}: {`)] - .concat(isStrict ? '' : indent(6)('[index: string]: QueryableStorageEntry;')) - .concat(storage.unwrap().items.sort((a, b) => a.name.localeCompare(b.name.toString())).map((storageEntry): string => { - const [args, returnType] = entrySignature(allDefs, registry, storageEntry, imports); - let entryType = 'AugmentedQuery'; - - if (storageEntry.type.isDoubleMap) { - entryType = `${entryType}DoubleMap`; - } - - return createDocComments(6, storageEntry.documentation) + - indent(6)(`${stringCamelCase(storageEntry.name.toString())}: ${entryType} Observable<${returnType}>>${isStrict ? '' : ' & QueryableStorageEntry'};`); - })) - .concat([indent(4)('};')]); -} +const template = readTemplate('query'); +const generateForMetaTemplate = Handlebars.compile(template); /** @internal */ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record }>>, isStrict: boolean): void { @@ -91,13 +73,39 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => { return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs); }, {}); - const body = meta.asLatest.modules.sort((a, b) => a.name.localeCompare(b.name.toString())).reduce((acc: string[], mod): string[] => { - return acc.concat(generateModule(allDefs, registry, mod, imports, isStrict)); - }, []); + + const modules = meta.asLatest.modules + .sort(compareName) + .filter((mod) => !mod.storage.isNone) + .map(({ name, storage }) => { + const items = storage.unwrap().items + .sort(compareName) + .map((storageEntry) => { + const [args, returnType] = entrySignature(allDefs, registry, storageEntry, imports); + let entryType = 'AugmentedQuery'; + + if (storageEntry.type.isDoubleMap) { + entryType = `${entryType}DoubleMap`; + } + + return { + args, + docs: storageEntry.documentation, + entryType, + name: stringCamelCase(storageEntry.name.toString()), + returnType + }; + }); + + return { + items, + name: stringCamelCase(name.toString()) + }; + }); imports.typesTypes.Observable = true; - const header = createImportCode(HEADER('chain'), imports, [ + const types = [ ...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({ file: packagePath, types: Object.keys(imports.localTypes[packagePath]) @@ -106,24 +114,15 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr file: '@polkadot/api/types', types: ['ApiTypes'] } - ]); - const interfaceStart = [ - "declare module '@polkadot/api/types/storage' {", - indent(2)('export interface AugmentedQueries {\n') - ].join('\n'); - const interfaceEnd = `\n${indent(2)('}')}\n\n`; - const queryableStorageInterface = indent(2)('export interface QueryableStorage extends AugmentedQueries {') - .concat('\n') - .concat(isStrict ? '' : indent(4)('[index: string]: QueryableModuleStorage;\n')) - .concat(indent(2)('}\n')); + ]; - return header - .concat(interfaceStart) - .concat(body.join('\n')) - .concat(interfaceEnd) - .concat(queryableStorageInterface) - .concat('}') - .concat(FOOTER); + return generateForMetaTemplate({ + headerType: 'chain', + imports, + isStrict, + modules, + types + }); }); } diff --git a/packages/typegen/src/generate/rpc.ts b/packages/typegen/src/generate/rpc.ts index cb90b3f115..37c6980ffd 100644 --- a/packages/typegen/src/generate/rpc.ts +++ b/packages/typegen/src/generate/rpc.ts @@ -2,13 +2,18 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import Handlebars from 'handlebars'; + import { TypeRegistry } from '@polkadot/types/create'; import * as definitions from '@polkadot/types/interfaces/definitions'; -import { FOOTER, HEADER, createDocComments, createImportCode, createImports, getSimilarTypes, setImports, writeFile, indent } from '../util'; +import { createImports, getSimilarTypes, readTemplate, setImports, writeFile } from '../util'; const StorageKeyTye = 'StorageKey | string | Uint8Array | any'; +const template = readTemplate('rpc'); +const generateRpcTypesTemplate = Handlebars.compile(template); + /** @internal */ export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.ts'): void { writeFile(dest, (): string => { @@ -22,62 +27,80 @@ export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.t .keys(definitions) .filter((key) => Object.keys(definitions[key as 'babe'].rpc || {}).length !== 0) .sort(); - const body = rpcKeys.reduce((allSections, section): string[] => { - const allMethods = Object.keys(definitions[section as 'babe'].rpc).sort().map((methodName): string => { + const modules = rpcKeys.map((section) => { + const allMethods = Object.keys(definitions[section as 'babe'].rpc).sort().map((methodName) => { const def = definitions[section as 'babe'].rpc[methodName]; + let args; + let type; + let generic; + // These are too hard to type with generics, do manual overrides if (section === 'state') { setImports(allDefs, imports, ['Codec', 'Hash', 'StorageKey', 'Vec']); if (methodName === 'getStorage') { - return createDocComments(6, [def.description]) + indent(6)(`getStorage: AugmentedRpc<(key: ${StorageKeyTye}, block?: Hash | Uint8Array | string) => Observable>;`); + generic = 'T = Codec'; + args = [`key: ${StorageKeyTye}, block?: Hash | Uint8Array | string`]; + type = 'T'; } else if (methodName === 'queryStorage') { - return createDocComments(6, [def.description]) + indent(6)(`queryStorage: AugmentedRpc<(keys: Vec | (${StorageKeyTye})[], fromBlock?: Hash | Uint8Array | string, toBlock?: Hash | Uint8Array | string) => Observable<[Hash, T][]>>;`); + generic = 'T = Codec[]'; + args = [`keys: Vec | (${StorageKeyTye})[], fromBlock?: Hash | Uint8Array | string, toBlock?: Hash | Uint8Array | string`]; + type = '[Hash, T][]'; } else if (methodName === 'queryStorageAt') { - return createDocComments(6, [def.description]) + indent(6)(`queryStorageAt: AugmentedRpc<(keys: Vec | (${StorageKeyTye})[], at?: Hash | Uint8Array | string) => Observable>;`); + generic = 'T = Codec[]'; + args = [`keys: Vec | (${StorageKeyTye})[], at?: Hash | Uint8Array | string`]; + type = 'T'; } else if (methodName === 'subscribeStorage') { - return createDocComments(6, [def.description]) + indent(6)(`subscribeStorage: AugmentedRpc<(keys?: Vec | (${StorageKeyTye})[]) => Observable>;`); + generic = 'T = Codec[]'; + args = [`keys?: Vec | (${StorageKeyTye})[]`]; + type = 'T'; } } - setImports(allDefs, imports, [def.type]); + if (args === undefined) { + setImports(allDefs, imports, [def.type]); + args = def.params.map((param: any) => { + const similarTypes = getSimilarTypes(definitions, registry, param.type, imports); - const args = def.params.map((param: any): string => { - const similarTypes = getSimilarTypes(definitions, registry, param.type, imports); + setImports(allDefs, imports, [param.type, ...similarTypes]); - setImports(allDefs, imports, [param.type, ...similarTypes]); + return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`; + }); - return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`; - }); + type = def.type; + generic = ''; + } - return createDocComments(6, [def.description]) + indent(6)(`${methodName}: AugmentedRpc<(${args.join(', ')}) => Observable<${def.type}>>;`); + return { + args: args.join(', '), + docs: [def.description], + generic, + name: methodName, + type + }; }); - return allSections.concat( - [ - ` ${section}: {`, - ...allMethods, - ' };' - ].join('\n') - ); - }, []).join('\n'); + return { + items: allMethods, + name: section + }; + }); imports.typesTypes.Observable = true; - const header = createImportCode(HEADER('chain'), imports, [ + const types = [ ...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({ file: packagePath, types: Object.keys(imports.localTypes[packagePath]) })) - ]); - const interfaceStart = "declare module '@polkadot/rpc-core/types.jsonrpc' {\n export interface RpcInterface {\n"; - const interfaceEnd = '\n }\n}'; + ]; - return header - .concat(interfaceStart) - .concat(body) - .concat(interfaceEnd) - .concat(FOOTER); + return generateRpcTypesTemplate({ + headerType: 'chain', + imports, + modules, + types + }); }); } diff --git a/packages/typegen/src/generate/tsDef.ts b/packages/typegen/src/generate/tsDef.ts index bf8c0b9758..1b0bc4af33 100644 --- a/packages/typegen/src/generate/tsDef.ts +++ b/packages/typegen/src/generate/tsDef.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import Handlebars from 'handlebars'; + import { TypeDef, TypeDefInfo } from '@polkadot/types/create/types'; import path from 'path'; @@ -9,7 +11,7 @@ import { getTypeDef } from '@polkadot/types/create'; import * as defaultDefinitions from '@polkadot/types/interfaces/definitions'; import { isString, stringCamelCase, stringUpperFirst } from '@polkadot/util'; -import { FOOTER, HEADER, TypeImports, createImportCode, createImports, exportInterface, exportType, formatType, setImports, writeFile } from '../util'; +import { TypeImports, createImports, exportInterface, exportType, readTemplate, formatType, setImports, writeFile } from '../util'; interface Imports extends TypeImports { interfaces: [string, string][]; @@ -181,22 +183,37 @@ function generateInterfaces (definitions: object, { types }: { types: Record }, outputDir: string): void { const imports = { ...createImports(importDefinitions, { types }), interfaces: [] } as Imports; const definitions = imports.definitions; const interfaces = generateInterfaces(definitions, { types }, imports); - const sortedDefs = interfaces.sort((a, b): number => a[0].localeCompare(b[0])).map(([, definition]): string => definition).join('\n\n'); + const items = interfaces.sort((a, b): number => a[0].localeCompare(b[0])).map(([, definition]): string => definition); - const header = createImportCode(HEADER('defs'), imports, [ + const importTypes = [ ...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({ file: packagePath, types: Object.keys(imports.localTypes[packagePath]) })) - ]); + ]; - writeFile(path.join(outputDir, defName, 'types.ts'), () => header.concat(sortedDefs).concat(`\n\nexport type PHANTOM_${defName.toUpperCase()} = '${defName}';`).concat(FOOTER), true); - writeFile(path.join(outputDir, defName, 'index.ts'), () => HEADER('defs').concat('export * from \'./types\';').concat(FOOTER), true); + writeFile(path.join(outputDir, defName, 'types.ts'), () => generateTsDefModuleTypesTemplate({ + headerType: 'defs', + imports, + items, + name: defName, + types: importTypes + }), true); + writeFile(path.join(outputDir, defName, 'index.ts'), () => generateTsDefIndexTemplate({ headerType: 'defs' }), true); } /** @internal */ @@ -210,17 +227,13 @@ export function generateTsDef (importDefinitions: { [importPath: string]: object generateTsDefFor(importDefinitions, defName, obj, outputDir); }); - return HEADER('defs') - .concat( - Object - .keys(definitions) - .map((moduleName): string => `export * from './${moduleName}/types';`) - .join('\n') - ) - .concat(FOOTER); + return generateTsDefTypesTemplate({ + headerType: 'defs', + items: Object.keys(definitions) + }); }); - writeFile(path.join(outputDir, 'index.ts'), () => HEADER('defs').concat('export * from \'./types\';').concat(FOOTER), true); + writeFile(path.join(outputDir, 'index.ts'), () => generateTsDefIndexTemplate({ headerType: 'defs' }), true); } /** @internal */ diff --git a/packages/typegen/src/generate/tx.ts b/packages/typegen/src/generate/tx.ts index a7b14176dd..43dcc82916 100644 --- a/packages/typegen/src/generate/tx.ts +++ b/packages/typegen/src/generate/tx.ts @@ -2,7 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { ModuleMetadataLatest } from '@polkadot/types/interfaces/metadata'; +import Handlebars from 'handlebars'; + import { Registry } from '@polkadot/types/types'; import staticData from '@polkadot/metadata/Metadata/static'; @@ -12,7 +13,7 @@ import { Text } from '@polkadot/types/primitive'; import { TypeRegistry } from '@polkadot/types/create'; import { stringCamelCase } from '@polkadot/util'; -import { FOOTER, HEADER, TypeImports, createDocComments, createImportCode, createImports, formatType, getSimilarTypes, indent, registerDefinitions, setImports, writeFile } from '../util'; +import { createImports, compareName, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util'; const MAPPED_NAMES: Record = { new: 'updated' @@ -24,39 +25,8 @@ function mapName (_name: Text): string { return MAPPED_NAMES[name] || name; } -// Generate types for one module -/** @internal */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -function generateModule (registry: Registry, allDefs: object, { calls, name }: ModuleMetadataLatest, imports: TypeImports, isStrict: boolean): string[] { - const allCalls = calls.unwrapOr(null); - - if (!allCalls?.length) { - return []; - } - - setImports(allDefs, imports, ['Call', 'Extrinsic', 'SubmittableExtrinsic']); - - return [indent(4)(`${stringCamelCase(name.toString())}: {`)] - .concat(isStrict ? '' : indent(6)('[index: string]: SubmittableExtrinsicFunction;')) - .concat(allCalls.sort((a, b) => a.name.localeCompare(b.name.toString())).map(({ args, documentation, name }): string => { - const params = args - .map(({ name, type }): [string, string, string] => { - const typeStr = type.toString(); - const similarTypes = getSimilarTypes(allDefs, registry, typeStr, imports).map((type): string => formatType(allDefs, type, imports)); - const nameStr = mapName(name); - - setImports(allDefs, imports, [...similarTypes.filter((type): boolean => !type.startsWith('(') && !type.startsWith('{')), typeStr]); - - return [`${nameStr}: ${similarTypes.join(' | ')}`, nameStr, typeStr]; - }) - .map(([full]): string => full) - .join(', '); - - return createDocComments(6, documentation) + - indent(6)(`${stringCamelCase(name.toString())}: AugmentedSubmittable<(${params}) => SubmittableExtrinsic>;`); - })) - .concat([indent(4)('};')]); -} +const template = readTemplate('tx'); +const generateForMetaTemplate = Handlebars.compile(template); /** @internal */ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record }>>, isStrict: boolean): void { @@ -66,10 +36,42 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => { return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs); }, {}); - const body = meta.asLatest.modules.sort((a, b) => a.name.localeCompare(b.name.toString())).reduce((acc, mod): string[] => { - return acc.concat(generateModule(registry, allDefs, mod, imports, isStrict)); - }, [] as string[]); - const header = createImportCode(HEADER('chain'), imports, [ + + const modules = meta.asLatest.modules + .sort(compareName) + .filter(({ calls }) => calls.unwrapOr([]).length) + .map(({ calls, name }) => { + setImports(allDefs, imports, ['Call', 'Extrinsic', 'SubmittableExtrinsic']); + + const items = calls.unwrap() + .sort(compareName) + .map(({ args, documentation, name }) => { + const params = args + .map(({ name, type }) => { + const typeStr = type.toString(); + const similarTypes = getSimilarTypes(allDefs, registry, typeStr, imports).map((type): string => formatType(allDefs, type, imports)); + const nameStr = mapName(name); + + setImports(allDefs, imports, [...similarTypes.filter((type): boolean => !type.startsWith('(') && !type.startsWith('{')), typeStr]); + + return `${nameStr}: ${similarTypes.join(' | ')}`; + }) + .join(', '); + + return { + docs: documentation, + name: stringCamelCase(name.toString()), + params + }; + }); + + return { + items, + name: stringCamelCase(name.toString()) + }; + }); + + const types = [ ...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({ file: packagePath, types: Object.keys(imports.localTypes[packagePath]) @@ -78,25 +80,15 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr file: '@polkadot/api/types', types: ['ApiTypes', 'SubmittableExtrinsic'] } - ]); - const interfaceStart = [ - "declare module '@polkadot/api/types/submittable' {", - indent(2)('export interface AugmentedSubmittables {\n') - ].join('\n'); - const interfaceEnd = `\n${indent(2)('}')}\n\n`; - const submittableExtrinsicsInterface = indent(2)('export interface SubmittableExtrinsics extends AugmentedSubmittables {') - .concat('\n') - .concat(indent(4)('(extrinsic: Call | Extrinsic | Uint8Array | string): SubmittableExtrinsic;\n')) - .concat(isStrict ? '' : indent(4)('[index: string]: SubmittableModuleExtrinsics;\n')) - .concat(indent(2)('}\n')); + ]; - return header - .concat(interfaceStart) - .concat(body.join('\n')) - .concat(interfaceEnd) - .concat(submittableExtrinsicsInterface) - .concat('}') - .concat(FOOTER); + return generateForMetaTemplate({ + headerType: 'chain', + imports, + isStrict, + modules, + types + }); }); } diff --git a/packages/typegen/src/templates/consts.hbs b/packages/typegen/src/templates/consts.hbs new file mode 100644 index 0000000000..5c2aaf30d5 --- /dev/null +++ b/packages/typegen/src/templates/consts.hbs @@ -0,0 +1,23 @@ +{{> header }} + +{{{ imports }}} + +declare module '@polkadot/metadata/Decorated/consts/types' { + export interface Constants { + {{#unless isStrict}} + [index: string]: ModuleConstants; + {{/unless}} + {{#each modules}} + {{{name}}}: { + {{#unless @root.isStrict}} + [index: string]: AugmentedConst; + {{/unless}} + {{~#each items}} + {{> docs}} + {{{name}}}: AugmentedConst<{{{type}}}>; + {{/each}} + }; + {{/each}} + } +} +{{> footer }} diff --git a/packages/typegen/src/templates/docs.hbs b/packages/typegen/src/templates/docs.hbs new file mode 100644 index 0000000000..236ddef337 --- /dev/null +++ b/packages/typegen/src/templates/docs.hbs @@ -0,0 +1,7 @@ +{{#if docs.length}} +/** +{{#each docs}} + * {{#trim}}{{{this}}}{{/trim}} +{{/each}} + **/ +{{/if}} diff --git a/packages/typegen/src/templates/footer.hbs b/packages/typegen/src/templates/footer.hbs new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/typegen/src/templates/header.hbs b/packages/typegen/src/templates/header.hbs new file mode 100644 index 0000000000..c122d997ad --- /dev/null +++ b/packages/typegen/src/templates/header.hbs @@ -0,0 +1,2 @@ +// Auto-generated via `yarn polkadot-types-from-{{headerType}}`, do not edit +/* eslint-disable */ diff --git a/packages/typegen/src/templates/interfaceRegistry.hbs b/packages/typegen/src/templates/interfaceRegistry.hbs new file mode 100644 index 0000000000..db8003fa3d --- /dev/null +++ b/packages/typegen/src/templates/interfaceRegistry.hbs @@ -0,0 +1,12 @@ +{{> header }} + +{{{ imports }}} + +declare module '@polkadot/types/types/registry' { + export interface InterfaceTypes { + {{#each items}} + {{{this}}} + {{/each}} + } +} +{{> footer }} diff --git a/packages/typegen/src/templates/query.hbs b/packages/typegen/src/templates/query.hbs new file mode 100644 index 0000000000..b27883ebec --- /dev/null +++ b/packages/typegen/src/templates/query.hbs @@ -0,0 +1,26 @@ +{{> header }} + +{{{ imports }}} + +declare module '@polkadot/api/types/storage' { + export interface AugmentedQueries { + {{#each modules}} + {{{name}}}: { + {{#unless @root.isStrict}} + [index: string]: QueryableStorageEntry; + {{/unless}} + {{~#each items}} + {{> docs}} + {{{name}}}: {{{entryType}}} Observable<{{{returnType}}}>>{{#unless @root.isStrict}} & QueryableStorageEntry{{/unless}}; + {{/each}} + }; + {{/each}} + } + + export interface QueryableStorage extends AugmentedQueries { + {{#unless isStrict}} + [index: string]: QueryableModuleStorage; + {{/unless}} + } +} +{{> footer }} diff --git a/packages/typegen/src/templates/rpc.hbs b/packages/typegen/src/templates/rpc.hbs new file mode 100644 index 0000000000..cf606eb4c4 --- /dev/null +++ b/packages/typegen/src/templates/rpc.hbs @@ -0,0 +1,17 @@ +{{> header }} + +{{{ imports }}} + +declare module '@polkadot/rpc-core/types.jsonrpc' { + export interface RpcInterface { + {{#each modules}} + {{{name}}}: { + {{#each items}} + {{> docs}} + {{{name}}}: AugmentedRpc<{{#if generic}}<{{{generic}}}>{{/if}}({{{args}}}) => Observable<{{{type}}}>>; + {{/each}} + }; + {{/each}} + } +} +{{> footer }} diff --git a/packages/typegen/src/templates/tsDef/index.hbs b/packages/typegen/src/templates/tsDef/index.hbs new file mode 100644 index 0000000000..610253d7a3 --- /dev/null +++ b/packages/typegen/src/templates/tsDef/index.hbs @@ -0,0 +1,4 @@ +{{> header }} + +export * from './types'; +{{> footer }} diff --git a/packages/typegen/src/templates/tsDef/moduleTypes.hbs b/packages/typegen/src/templates/tsDef/moduleTypes.hbs new file mode 100644 index 0000000000..66736104d8 --- /dev/null +++ b/packages/typegen/src/templates/tsDef/moduleTypes.hbs @@ -0,0 +1,11 @@ +{{> header }} + +{{{ imports }}} + +{{#each items}} +{{{this}}} + +{{/each}} + +export type PHANTOM_{{#upper}}{{{name}}}{{/upper}} = '{{{name}}}'; +{{> footer }} diff --git a/packages/typegen/src/templates/tsDef/types.hbs b/packages/typegen/src/templates/tsDef/types.hbs new file mode 100644 index 0000000000..1fc94d735a --- /dev/null +++ b/packages/typegen/src/templates/tsDef/types.hbs @@ -0,0 +1,6 @@ +{{> header }} + +{{#each items}} +export * from './{{{this}}}/types'; +{{/each}} +{{> footer }} diff --git a/packages/typegen/src/templates/tx.hbs b/packages/typegen/src/templates/tx.hbs new file mode 100644 index 0000000000..0f9885c4db --- /dev/null +++ b/packages/typegen/src/templates/tx.hbs @@ -0,0 +1,27 @@ +{{> header }} + +{{{ imports }}} + +declare module '@polkadot/api/types/submittable' { + export interface AugmentedSubmittables { + {{#each modules}} + {{{name}}}: { + {{#unless @root.isStrict}} + [index: string]: SubmittableExtrinsicFunction; + {{/unless}} + {{~#each items}} + {{> docs}} + {{{name}}}: AugmentedSubmittable<({{{params}}}) => SubmittableExtrinsic>; + {{/each}} + }; + {{/each}} + } + + export interface SubmittableExtrinsics extends AugmentedSubmittables { + (extrinsic: Call | Extrinsic | Uint8Array | string): SubmittableExtrinsic; + {{#unless isStrict}} + [index: string]: SubmittableModuleExtrinsics; + {{/unless}} + } +} +{{> footer }} diff --git a/packages/typegen/src/util/docs.ts b/packages/typegen/src/util/docs.ts index b97c855c4f..6e3c61ccba 100644 --- a/packages/typegen/src/util/docs.ts +++ b/packages/typegen/src/util/docs.ts @@ -2,22 +2,10 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { Text } from '@polkadot/types'; +import Handlebars from 'handlebars'; -import { indent } from './formatting'; +import { readTemplate } from './file'; -type AnyString = Text | string; -type Arg = [AnyString, AnyString]; - -export function createDocComments (spaces: number, docs: AnyString[], args: Arg[] = []): string { - const contents = [ - ...docs.map((doc): string => doc.toString().trim()).filter((doc): boolean => !!doc), - ...args.map(([name, type]): string => `@param ${name} ${type}`) - ].map((d): string => ` * ${d}`); - - return contents.length - ? ['/**', ...contents, ' **/\n'] - .map((s): string => indent(spaces)(s)) - .join('\n') - : ''; -} +Handlebars.registerPartial({ + docs: Handlebars.compile(readTemplate('docs')) +}); diff --git a/packages/typegen/src/util/file.ts b/packages/typegen/src/util/file.ts index 07add191f2..920a6f1caf 100644 --- a/packages/typegen/src/util/file.ts +++ b/packages/typegen/src/util/file.ts @@ -19,3 +19,7 @@ export function writeFile (dest: string, generator: () => string, noLog?: boolea !noLog && console.log(''); } + +export function readTemplate (path: string): string { + return fs.readFileSync(`${__dirname}/../templates/${path}.hbs`).toString(); +} diff --git a/packages/typegen/src/util/formatting.spec.ts b/packages/typegen/src/util/formatting.spec.ts deleted file mode 100644 index 71eeb5ad88..0000000000 --- a/packages/typegen/src/util/formatting.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2017-2020 @polkadot/typegen authors & contributors -// This software may be modified and distributed under the terms -// of the Apache-2.0 license. See the LICENSE file for details. - -import { indent } from './formatting'; - -describe('formatting', () => { - it('should indent correctly', () => { - expect(indent(2)('foo')).toBe(' foo'); - }); -}); diff --git a/packages/typegen/src/util/formatting.ts b/packages/typegen/src/util/formatting.ts index cac8c1d3e7..4fb72b39d9 100644 --- a/packages/typegen/src/util/formatting.ts +++ b/packages/typegen/src/util/formatting.ts @@ -2,59 +2,74 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import Handlebars from 'handlebars'; + import { TypeDef, TypeDefInfo } from '@polkadot/types/create/types'; import { getTypeDef } from '@polkadot/types/create'; import { paramsNotation } from '@polkadot/types/codec/utils'; import { setImports, TypeImports } from './imports'; - -export const HEADER = (type: 'chain' | 'defs'): string => `// Auto-generated via \`yarn polkadot-types-from-${type}\`, do not edit\n/* eslint-disable */\n\n`; -export const FOOTER = '\n'; +import { readTemplate } from './file'; const TYPES_NON_PRIMITIVE = ['Metadata']; -// creates the import lines -/** @internal */ -export function createImportCode (header: string, imports: TypeImports, checks: { file: string; types: string[] }[]): string { - return [ - { - file: '@polkadot/types/types', - types: Object.keys(imports.typesTypes) - }, - { - file: '@polkadot/types/codec', - types: Object - .keys(imports.codecTypes) - .filter((name): boolean => name !== 'Tuple') - }, - { - file: '@polkadot/types/extrinsic', - types: Object.keys(imports.extrinsicTypes) - }, - { - file: '@polkadot/types/generic', - types: Object.keys(imports.genericTypes) - }, - { - file: '@polkadot/types/primitive', - types: Object - .keys(imports.primitiveTypes) - .filter((name): boolean => !TYPES_NON_PRIMITIVE.includes(name)) - }, - { - file: '@polkadot/types', - types: Object - .keys(imports.primitiveTypes) - .filter((name): boolean => TYPES_NON_PRIMITIVE.includes(name)) - }, - ...checks - ].reduce((result, { file, types }): string => { - return types.length - ? `${result}import { ${types.sort().join(', ')} } from '${file}';\n` - : result; - }, header) + '\n'; -} +export const HEADER = (type: 'chain' | 'defs'): string => `// Auto-generated via \`yarn polkadot-types-from-${type}\`, do not edit\n/* eslint-disable */\n\n`; + +Handlebars.registerPartial({ + footer: Handlebars.compile(readTemplate('footer')), + header: Handlebars.compile(readTemplate('header')) +}); + +Handlebars.registerHelper({ + imports () { + const { imports, types } = this as any; + + return [ + { + file: '@polkadot/types/types', + types: Object.keys(imports.typesTypes) + }, + { + file: '@polkadot/types/codec', + types: Object + .keys(imports.codecTypes) + .filter((name): boolean => name !== 'Tuple') + }, + { + file: '@polkadot/types/extrinsic', + types: Object.keys(imports.extrinsicTypes) + }, + { + file: '@polkadot/types/generic', + types: Object.keys(imports.genericTypes) + }, + { + file: '@polkadot/types/primitive', + types: Object + .keys(imports.primitiveTypes) + .filter((name): boolean => !TYPES_NON_PRIMITIVE.includes(name)) + }, + { + file: '@polkadot/types', + types: Object + .keys(imports.primitiveTypes) + .filter((name): boolean => TYPES_NON_PRIMITIVE.includes(name)) + }, + ...types + ].reduce((result, { file, types }): string => { + return types.length + ? `${result}import { ${types.sort().join(', ')} } from '${file}';\n` + : result; + }, ''); + }, + trim (options) { + return options.fn(this).trim(); + }, + upper (options) { + return options.fn(this).toUpperCase(); + } +}); // helper to generate a `export interface extends {} /** @internal */ @@ -273,13 +288,3 @@ export function formatType (definitions: object, type: string | TypeDef, imports } } } - -/** - * Indent a string with `n` spaces before. - */ -/** @internal */ -export function indent (n: number, char = ' '): (str: string) => string { - return function (str: string): string { - return `${char.repeat(n)}${str}`; - }; -} diff --git a/packages/typegen/src/util/index.ts b/packages/typegen/src/util/index.ts index 18fe8767aa..c0d2852297 100644 --- a/packages/typegen/src/util/index.ts +++ b/packages/typegen/src/util/index.ts @@ -8,3 +8,6 @@ export * from './file'; export * from './formatting'; export * from './imports'; export * from './register'; + +export const compareName = (a: { name: { toString(): string } }, b: { name: { toString(): string } }): number => + a.name.toString().localeCompare(b.name.toString()); diff --git a/yarn.lock b/yarn.lock index 88a97836b0..490b629c7b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2837,6 +2837,7 @@ __metadata: "@polkadot/util": ^2.10.0-beta.1 "@types/websocket": ^1.0.0 "@types/yargs": ^15.0.4 + handlebars: ^4.7.6 websocket: ^1.0.31 yargs: ^15.3.1 bin: