Compare commits

..
44 Commits
Author SHA1 Message Date
Github Actions c412f7fa11 [CI Skip] 1.13.1
skip-checks: true
2020-05-06 18:33:13 +00:00
Jaco Greeff a1ad90c2b4 1.13 (#2248)
* 1.13

* Add grandpa_roundState RPC

* RPC interfaces
2020-05-06 20:22:18 +02:00
Github Actions 92f62bfa15 [CI Skip] 1.13.0-beta.19
skip-checks: true
2020-05-06 16:48:28 +00:00
Jaco Greeff fa9c5778be Adjust Centrifuge versions (#2247) 2020-05-06 18:37:44 +02:00
Github Actions e6f877621a [CI Skip] 1.13.0-beta.18
skip-checks: true
2020-05-06 15:22:36 +00:00
Jaco Greeff 5c35a70e9d Centrifuge Chain Node (#2246) 2020-05-06 17:11:33 +02:00
Github Actions a287096cc3 [CI Skip] 1.13.0-beta.17
skip-checks: true
2020-05-06 13:47:59 +00:00
Jaco Greeff c35f31bfbd Adjust mock timeouts (#2244)
* Adjust mock timeouts

* Play with timeouts some more...

* Ooops, overzealous search-and-replace
2020-05-06 15:36:20 +02:00
Jaco Greeff 718afa91e3 Multiple endpoints CHANGELOG (#2243) 2020-05-06 15:10:37 +02:00
Hoani BrysonandJaco Greeff 102a06b0f2 Multiple Endpoint support for WsProvider (#2234)
* Fix incorrect ws connect test cases

* Make endpoint an array of endpoints

* Add requirement that WsProvider endpoint arrays must not be empty

* Simple endpoint increment

* Add multi-endpoint test for endpoint closing its connection

* Implement endpoint round robin

* Revert change to mock's TEST_WS_URL

* Address Lint errors

* Change endpoint variable to plural in WsProvider

Co-authored-by: Jaco Greeff <jacogr@gmail.com>

* Review corrections to WsProvider

* Grouping improvement in WsProvider connect

* Correct endpoint logging to only show the specific endpoint involved

* Correct ordering of endpoint increment on connect

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-05-06 14:42:30 +02:00
Github Actions 58f0df1ef0 [CI Skip] 1.13.0-beta.16
skip-checks: true
2020-05-06 12:08:40 +00:00
Jaco Greeff a458589222 Fix CompactAssignment decoding (#2242)
* Fix CompactAssignment decoding

* CHANGELOG
2020-05-06 13:56:17 +02:00
Github Actions deef4ce4c7 [CI Skip] 1.13.0-beta.15
skip-checks: true
2020-05-06 08:36:29 +00:00
Jaco Greeff f5d2449407 Grandpa Equivocation types (#2239)
* Grandpa Equivocation types

* typo
2020-05-06 10:25:37 +02:00
Github Actions 8bb1d1259e [CI Skip] 1.13.0-beta.14
skip-checks: true
2020-05-06 08:23:10 +00:00
Jaco Greeff abd860d548 Bump deps (#2240)
* Bump deps

* Jest revert
2020-05-06 10:11:58 +02:00
Github Actions 25936d882f [CI Skip] 1.13.0-beta.13
skip-checks: true
2020-05-06 06:29:54 +00:00
Keith YeungandJaco Greeff 9deaff54e4 Make the 2nd argument to SubmittableExtrinsic.sign/signAsync optional (#2238)
* Make the 2nd argument to SubmittableExtrinsic.sign/signAsync optional

* Use default argument for optionsOrNonce

Co-authored-by: Jaco Greeff <jacogr@gmail.com>

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-05-06 08:17:51 +02:00
Github Actions bc479a995b [CI Skip] 1.13.0-beta.12
skip-checks: true
2020-05-05 09:44:03 +00:00
Jaco Greeff 458b7fa7e4 Update with latest Substrate metadata (#2233) 2020-05-05 11:33:04 +02:00
Github Actions 2fc17a66e1 [CI Skip] 1.13.0-beta.11
skip-checks: true
2020-05-05 05:26:31 +00:00
codingsh 94f81db568 #2182 - add: search for docs (#2232) 2020-05-05 07:16:39 +02:00
Github Actions e83d97c849 [CI Skip] 1.13.0-beta.10
skip-checks: true
2020-05-05 05:09:33 +00:00
Joshy Orndorff 4a497fa970 minor typo: RC -> RPC (#2229) 2020-05-05 06:58:52 +02:00
Github Actions cb40d459b5 [CI Skip] 1.13.0-beta.9
skip-checks: true
2020-05-04 18:40:00 +00:00
Jaco Greeff c70cdb351f Additional modules/methods in RPC samples 2020-05-04 20:29:02 +02:00
Github Actions 001aa0d011 [CI Skip] 1.13.0-beta.8
skip-checks: true
2020-05-04 15:58:01 +00:00
Jaco Greeff 961d27ad46 Update CHANGELOG.md 2020-05-04 17:47:09 +02:00
Github Actions 1c09bb69dd [CI Skip] 1.13.0-beta.7
skip-checks: true
2020-05-04 13:32:30 +00:00
Xiliang ChenandJaco Greeff 174510a928 use handlebars for code generation (#2228)
* use handlebars for code generation

* update docs

* fix isStrict

* fix lint

* Apply suggestions from code review

Co-authored-by: Jaco Greeff <jacogr@gmail.com>

* convert consts

* keep empty lines in doc comments

* update rpc

* update tx

* update interfaceRegistry

* update tsDef

* remove no longer used code

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-05-04 15:21:09 +02:00
Github Actions 39ed76f2de [CI Skip] 1.13.0-beta.6
skip-checks: true
2020-05-04 12:20:51 +00:00
Jaco Greeff 7d1c93db59 Update CHANGELOG.md 2020-05-04 14:08:18 +02:00
Github Actions e9b1b4ee77 [CI Skip] 1.13.0-beta.5
skip-checks: true
2020-05-01 19:11:49 +00:00
Jaco Greeff 2367978f6e Remove polkadot metadata (not mainatained, outdated) (#2227) 2020-05-01 21:01:08 +02:00
Github Actions e77050b9f5 [CI Skip] 1.13.0-beta.4
skip-checks: true
2020-04-30 13:24:43 +00:00
Jaco Greeff 844d1a2928 Allow failures on preimage (instead of swallow) (#2225) 2020-04-30 15:14:56 +02:00
Github Actions 6a70beda0f [CI Skip] 1.13.0-beta.3
skip-checks: true
2020-04-30 09:16:39 +00:00
Alexander Krupenkin 05a834b822 Fix extrinsic ECDSA signatures (#2222)
* Fix extrinsic ECDSA signatures

* Fix lint
2020-04-30 11:04:55 +02:00
Github Actions 6a3af506a4 [CI Skip] 1.13.0-beta.2
skip-checks: true
2020-04-30 07:37:46 +00:00
Jaco Greeff c82b85ef79 Bump deps (#2224) 2020-04-30 09:27:04 +02:00
Github Actions 91ab81ef60 [CI Skip] 1.13.0-beta.1
skip-checks: true
2020-04-30 05:47:17 +00:00
Jaco Greeff 3665690444 Beta bump (#2223) 2020-04-30 07:37:12 +02:00
Github Actions 03dcefceb5 [CI Skip] 1.12.2
skip-checks: true
2020-04-29 22:56:16 +00:00
Jaco Greeff e84be032f4 1.12.2 (stable util) 2020-04-30 00:46:45 +02:00
76 changed files with 2755 additions and 8689 deletions
+1
View File
@@ -2,3 +2,4 @@
1.4.2
1.6.2
1.11.2
1.12.2
+16
View File
@@ -1,3 +1,19 @@
# 1.13.1 May 6, 2020
- Add support for ECDSA keypairs in extrinsic signers (Thanks to https://github.com/akru)
- Rework type generation to use templating for better maintenance (Thanks to https://github.com/xlc)
- Adjust extrinsic `sign/signAsync` signature to optional options (Thanks to https://github.com/KiChjang)
- Support round-robin endpoints in the `WsProvider` with array of urls (Thanks to https://github.com/hoani)
- Remove static test-only metadata for Polkadot dev chains (not updated regularly, Substrate dev to remain)
- Revert error swallow for wrong preimage data (temp. override for Kusama upgrade with no migration)
- Fix `.encodedLength` calculation on `[Type; N]` types
- Update types & metadata as per latest Substrate master
- Adjust Centrifuge starting version
# 1.12.2 Apr 30, 2020
- Update @polkadot/util to stable 2.9.1 (sadly missed in the previous version, stable should match to stable)
# 1.12.1 Apr 29, 2020
- Fix `CompactAssignments` types (Thanks to https://github.com/arjanz)
+8 -2
View File
@@ -20,7 +20,8 @@ module.exports = {
},
{ text: 'GitHub', link: 'https://github.com/polkadot-js/api' }
],
search: false,
search: true,
searchMaxSuggestions: 10,
sidebar: [
{
title: 'Getting started',
@@ -97,5 +98,10 @@ module.exports = {
['/types/', '@polkadot/types'],
'/CONTRIBUTING.md'
]
}
},
plugins: [
['@vuepress/search', {
searchMaxSuggestions: 10
}]
]
};
+3
View File
@@ -1,5 +1,8 @@
$accentColor = #fd8824
$textColor = #2c3e50
$borderColor = #eaecef
$codeBgColor = #282c34
$arrowBgColor = #ccc
.home .hero .description,
.home .feature h2,
+9 -4
View File
@@ -1,6 +1,6 @@
# Custom RPC
In previous sections we looked at the injection of types, as in use and defined in modules from the node. Another area that can be customized is RC definitions, and like with the types, the API provides the capability to add user-defined RPCs (in addition to the Polkadot/Substrate base) to allow use of these RPCs via the API.
In previous sections we looked at the injection of types, as in use and defined in modules from the node. Another area that can be customized is RPC definitions, and like with the types, the API provides the capability to add user-defined RPCs (in addition to the Polkadot/Substrate base) to allow use of these RPCs via the API.
## Custom definitions
@@ -25,9 +25,14 @@ const api = await ApiPromise.create({
}
],
type: 'Balance'
}
}
}
},
anotherMethod: { ... },
...
},
anotherModule: { ... },
...
},
...
});
```
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "1.12.1"
"version": "1.13.1"
}
+5 -4
View File
@@ -24,13 +24,14 @@
"test:watch": "polkadot-dev-run-test --watch"
},
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/core": "^7.9.6",
"@babel/register": "^7.9.0",
"@babel/runtime": "^7.9.2",
"@polkadot/dev": "^0.52.11",
"@polkadot/ts": "^0.3.18",
"@babel/runtime": "^7.9.6",
"@polkadot/dev": "^0.52.15",
"@polkadot/ts": "^0.3.19",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^25.2.1",
"@vuepress/plugin-search": "^1.4.1",
"copyfiles": "^2.2.0"
}
}
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-contract",
"version": "1.12.1",
"version": "1.13.1",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
"keywords": [
@@ -26,11 +26,11 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/api": "1.12.1",
"@polkadot/rpc-core": "1.12.1",
"@polkadot/types": "1.12.1",
"@polkadot/util": "^2.9.0-beta.3",
"@babel/runtime": "^7.9.6",
"@polkadot/api": "1.13.1",
"@polkadot/rpc-core": "1.13.1",
"@polkadot/types": "1.13.1",
"@polkadot/util": "^2.9.1",
"bn.js": "^5.1.1",
"rxjs": "^6.5.5"
}
+9 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "1.12.1",
"version": "1.13.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"keywords": [
@@ -27,18 +27,18 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/api": "1.12.1",
"@polkadot/rpc-core": "1.12.1",
"@polkadot/rpc-provider": "1.12.1",
"@polkadot/types": "1.12.1",
"@polkadot/util": "^2.9.0-beta.3",
"@polkadot/util-crypto": "^2.9.0-beta.3",
"@babel/runtime": "^7.9.6",
"@polkadot/api": "1.13.1",
"@polkadot/rpc-core": "1.13.1",
"@polkadot/rpc-provider": "1.13.1",
"@polkadot/types": "1.13.1",
"@polkadot/util": "^2.9.1",
"@polkadot/util-crypto": "^2.9.1",
"bn.js": "^5.1.1",
"memoizee": "^0.4.14",
"rxjs": "^6.5.5"
},
"devDependencies": {
"@polkadot/keyring": "^2.9.0-beta.3"
"@polkadot/keyring": "^2.9.1"
}
}
+12 -12
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api",
"version": "1.12.1",
"version": "1.13.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
"keywords": [
@@ -26,21 +26,21 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/api-derive": "1.12.1",
"@polkadot/keyring": "^2.9.0-beta.3",
"@polkadot/metadata": "1.12.1",
"@polkadot/rpc-core": "1.12.1",
"@polkadot/rpc-provider": "1.12.1",
"@polkadot/types": "1.12.1",
"@polkadot/types-known": "1.12.1",
"@polkadot/util": "^2.9.0-beta.3",
"@polkadot/util-crypto": "^2.9.0-beta.3",
"@babel/runtime": "^7.9.6",
"@polkadot/api-derive": "1.13.1",
"@polkadot/keyring": "^2.9.1",
"@polkadot/metadata": "1.13.1",
"@polkadot/rpc-core": "1.13.1",
"@polkadot/rpc-provider": "1.13.1",
"@polkadot/types": "1.13.1",
"@polkadot/types-known": "1.13.1",
"@polkadot/util": "^2.9.1",
"@polkadot/util-crypto": "^2.9.1",
"bn.js": "^5.1.1",
"eventemitter3": "^4.0.0",
"rxjs": "^6.5.5"
},
"devDependencies": {
"@polkadot/keyring": "^2.9.0-beta.3"
"@polkadot/keyring": "^2.9.1"
}
}
+3
View File
@@ -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<BalanceOf>;
/**
* 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<BlockNumber>;
/**
* 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.
+37 -4
View File
@@ -5,10 +5,10 @@ import { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
import { Option, U8aFixed, Vec } from '@polkadot/types/codec';
import { Bytes, Data, bool, u32, u64 } from '@polkadot/types/primitive';
import { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
import { BabeAuthorityWeight, MaybeVrf, Randomness } from '@polkadot/types/interfaces/babe';
import { BabeAuthorityWeight, MaybeRandomness, Randomness } from '@polkadot/types/interfaces/babe';
import { AccountData, BalanceLock, ReleasesBalances } from '@polkadot/types/interfaces/balances';
import { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
import { AuthorityId, RawVRFOutput } from '@polkadot/types/interfaces/consensus';
import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { CodeHash, ContractInfo, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
import { PreimageStatus, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy';
import { VoteThreshold } from '@polkadot/types/interfaces/elections';
@@ -69,9 +69,10 @@ declare module '@polkadot/api/types/storage' {
* Temporary value (cleared at block finalization) which is `Some`
* if per-block initialization has already been called for current block.
**/
initialized: AugmentedQuery<ApiType, () => Observable<Option<MaybeVrf>>> & QueryableStorageEntry<ApiType>;
initialized: AugmentedQuery<ApiType, () => Observable<Option<MaybeRandomness>>> & QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>;
/**
* 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,22 +97,26 @@ declare module '@polkadot/api/types/storage' {
randomness: AugmentedQuery<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>;
/**
* 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.
**/
segmentIndex: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
underConstruction: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<RawVRFOutput>>> & QueryableStorageEntry<ApiType>;
underConstruction: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<Randomness>>> & QueryableStorageEntry<ApiType>;
};
balances: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>> & QueryableStorageEntry<ApiType>;
@@ -120,6 +127,7 @@ declare module '@polkadot/api/types/storage' {
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<BalanceLock>>> & QueryableStorageEntry<ApiType>;
/**
* Storage version of the pallet.
*
* This is set to v2.0.0 for new networks.
**/
storageVersion: AugmentedQuery<ApiType, () => Observable<ReleasesBalances>> & QueryableStorageEntry<ApiType>;
@@ -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<ApiType, () => Observable<Vec<Option<RegistrarInfo>>>> & QueryableStorageEntry<ApiType>;
/**
* Alternative "sub" identities of this account.
*
* The first item is the deposit, the second is a vector of the accounts.
**/
subsOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>> & QueryableStorageEntry<ApiType>;
@@ -333,6 +343,7 @@ declare module '@polkadot/api/types/storage' {
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>> & QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, (arg: ReportIdOf | string | Uint8Array) => Observable<Option<OffenceDetails>>> & QueryableStorageEntry<ApiType>;
/**
* 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<u8>`, 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<ApiType>;
/**
* 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<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ActiveRecovery>>> & QueryableStorageEntry<ApiType>;
/**
* The list of allowed proxy accounts.
*
* Map from the user who can access it to the recovered account.
**/
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
@@ -425,6 +440,7 @@ declare module '@polkadot/api/types/storage' {
currentIndex: AugmentedQuery<ApiType, () => Observable<SessionIndex>> & QueryableStorageEntry<ApiType>;
/**
* Indices of disabled validators.
*
* The set is cleared when `on_session_ending` returns a new set of identities.
**/
disabledValidators: AugmentedQuery<ApiType, () => Observable<Vec<u32>>> & QueryableStorageEntry<ApiType>;
@@ -523,6 +539,7 @@ declare module '@polkadot/api/types/storage' {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<EraRewardPoints>> & QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Exposure>> & QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<ValidatorPrefs>> & QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<Option<BalanceOf>>> & QueryableStorageEntry<ApiType>;
@@ -606,7 +633,9 @@ declare module '@polkadot/api/types/storage' {
forceEra: AugmentedQuery<ApiType, () => Observable<Forcing>> & QueryableStorageEntry<ApiType>;
/**
* 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<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<SlashingSpans>>> & QueryableStorageEntry<ApiType>;
/**
* The percentage of the slash that is distributed to reporters.
*
* The rest of the slashed value is handled by the `Slash`.
**/
slashRewardFraction: AugmentedQuery<ApiType, () => Observable<Perbill>> & QueryableStorageEntry<ApiType>;
@@ -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<ApiType, () => Observable<ReleasesStaking>> & QueryableStorageEntry<ApiType>;
@@ -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 `<Events<T>>` 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.
+7
View File
@@ -13,6 +13,7 @@ import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
import { CreatedBlock } from '@polkadot/types/interfaces/engine';
import { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import { ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import { StorageKind } from '@polkadot/types/interfaces/offchain';
import { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import { RpcMethods } from '@polkadot/types/interfaces/rpc';
@@ -140,6 +141,12 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
**/
finalizeBlock: AugmentedRpc<(hash: BlockHash | string | Uint8Array, justification?: Justification | string | Uint8Array) => Observable<bool>>;
};
grandpa: {
/**
* Returns the state of the current best round state as well as the ongoing background rounds
**/
roundState: AugmentedRpc<() => Observable<ReportedRoundStates>>;
};
offchain: {
/**
* Get offchain local storage under given key and prefix
File diff suppressed because it is too large Load Diff
+17
View File
@@ -49,5 +49,22 @@ describe('ApiRx', (): void => {
})
);
});
it('allows the second argument to signAsync to be omitted', () => {
const signer = new SingleAccountSigner(registry, keyring.alice_session);
ApiRx.create({ provider, registry, signer }).pipe(
switchMap((api: ApiRx): Observable<SubmittableExtrinsic<'rxjs'>> =>
api.tx.balances
.transfer(keyring.eve.address, 12345)
.signAsync(keyring.alice_session)
),
map((tx: SubmittableExtrinsic<'rxjs'>): void => {
expect(tx.signature.toHex()).toEqual(
'0x97f3cfe5088fcd575313e983f45d02b0f630e7b94ff9a3ac50e20cd096a8f554fda73d42ead891b5a1d3ce5607d83f20b0c6570b555e949cfb5763d0abcd590b'
);
})
);
});
});
});
+4 -4
View File
@@ -60,7 +60,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
}
// sign a transaction, returning the this to allow chaining, i.e. .sign(...).send()
public sign (account: IKeyringPair, optionsOrNonce: Partial<SignerOptions>): this {
public sign (account: IKeyringPair, optionsOrNonce?: Partial<SignerOptions>): this {
super.sign(account, this.#makeSignOptions(this.#optionsOrNonce(optionsOrNonce), {}));
return this;
@@ -69,7 +69,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
// signs a transaction, returning `this` to allow chaining. E.g.: `sign(...).send()`
//
// also supports signing through external signers
public signAsync (account: AddressOrPair, optionsOrNonce: Partial<SignerOptions>): SubmittableThis<ApiType, this> {
public signAsync (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): SubmittableThis<ApiType, this> {
return decorateMethod(
(): Observable<this> =>
this.#observeSign(account, optionsOrNonce).pipe(mapTo(this))
@@ -164,7 +164,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
return [options, statusCb];
}
#observeSign = (account: AddressOrPair, optionsOrNonce: Partial<SignerOptions>): Observable<number | undefined> => {
#observeSign = (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): Observable<number | undefined> => {
const address = isKeyringPair(account) ? account.address : account.toString();
const options = this.#optionsOrNonce(optionsOrNonce);
let updateId: number | undefined;
@@ -224,7 +224,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
// NOTE here we actually override nonce if it was specified (backwards compat for
// the previous signature - don't let userspace break, but allow then time to upgrade)
#optionsOrNonce = (optionsOrNonce: Partial<SignerOptions>): Partial<SignerOptions> => {
#optionsOrNonce = (optionsOrNonce: Partial<SignerOptions> = {}): Partial<SignerOptions> => {
return isBn(optionsOrNonce) || isNumber(optionsOrNonce)
? { nonce: optionsOrNonce }
: optionsOrNonce;
+2 -2
View File
@@ -50,9 +50,9 @@ export interface SubmittableExtrinsic<ApiType extends ApiTypes> extends Extrinsi
send(statusCb: Callback<ISubmittableResult>): SubmittableResultSubscription<ApiType>;
sign(account: IKeyringPair, _options: Partial<SignatureOptions>): this;
sign(account: IKeyringPair, _options?: Partial<SignatureOptions>): this;
signAsync(account: AddressOrPair, _options: Partial<SignatureOptions>): SubmittableThis<ApiType, this>;
signAsync(account: AddressOrPair, _options?: Partial<SignatureOptions>): SubmittableThis<ApiType, this>;
signAndSend(account: AddressOrPair, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType>;
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/metadata",
"version": "1.12.1",
"version": "1.13.1",
"description": "Helpers to extract information from runtime metadata",
"main": "index.js",
"publishConfig": {
@@ -26,14 +26,14 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/types": "1.12.1",
"@polkadot/types-known": "1.12.1",
"@polkadot/util": "^2.9.0-beta.3",
"@polkadot/util-crypto": "^2.9.0-beta.3",
"@babel/runtime": "^7.9.6",
"@polkadot/types": "1.13.1",
"@polkadot/types-known": "1.13.1",
"@polkadot/util": "^2.9.1",
"@polkadot/util-crypto": "^2.9.1",
"bn.js": "^5.1.1"
},
"devDependencies": {
"@polkadot/keyring": "^2.9.0-beta.3"
"@polkadot/keyring": "^2.9.1"
}
}
@@ -4,8 +4,6 @@
import { TypeRegistry } from '@polkadot/types';
import polkadotJson from './static-polkadot.json';
import polkadotData from './static.polkadot';
import substrateJson from './static-substrate.json';
import substrateData from './static';
import { decodeLatestSubstrate, defaultValues, toLatest } from '../util/testUtil';
@@ -19,13 +17,3 @@ describe('MetadataV11 (substrate)', (): void => {
defaultValues(registry, substrateData);
});
describe('MetadataV11 (polkadot)', (): void => {
const registry = new TypeRegistry();
decodeLatestSubstrate(registry, 11, polkadotData, polkadotJson);
toLatest(registry, 11, polkadotData);
defaultValues(registry, polkadotData);
});
File diff suppressed because it is too large Load Diff
@@ -364,10 +364,8 @@
" data is equal to its default value.",
"",
" # <weight>",
" - `O(K)` with `K` being complexity of `on_killed_account`",
" - `O(1)`",
" - 1 storage read and deletion.",
" - 1 call to `on_killed_account` callback with unknown complexity `K`",
" - 1 event.",
" # </weight>"
]
}
@@ -430,7 +428,7 @@
{
"name": "DbWeight",
"type": "RuntimeDbWeight",
"value": "0x008793030000000000c2eb0b00000000",
"value": "0x40787d010000000000e1f50500000000",
"documentation": [
" The weight of runtime database operations the runtime can invoke."
]
@@ -438,7 +436,7 @@
{
"name": "BlockExecutionWeight",
"type": "Weight",
"value": "0x0000000000000000",
"value": "0x00f2052a01000000",
"documentation": [
" The base weight of executing a block, independent of the transactions in the block."
]
@@ -446,7 +444,7 @@
{
"name": "ExtrinsicBaseWeight",
"type": "Weight",
"value": "0x8096980000000000",
"value": "0x4059730700000000",
"documentation": [
" The base weight of an Extrinsic in the block, independent of the of extrinsic being executed."
]
@@ -540,8 +538,9 @@
" - `calls`: The calls to be dispatched from the same origin.",
"",
" # <weight>",
" - The sum of the weights of the `calls`.",
" - One event.",
" - Base weight: 14.39 + .987 * c µs",
" - Plus the sum of the weights of the `calls`.",
" - Plus one additional event. (repeat read/write)",
" # </weight>",
"",
" This will return `Ok` in all circumstances. To determine the success of the batch, an",
@@ -569,7 +568,8 @@
" The dispatch origin for this call must be _Signed_.",
"",
" # <weight>",
" - The weight of the `call` + 10,000.",
" - Base weight: 2.861 µs",
" - Plus the weight of the `call`",
" # </weight>"
]
},
@@ -634,6 +634,15 @@
" - Storage: inserts one item, value size bounded by `MaxSignatories`, with a",
" deposit taken for its lifetime of",
" `MultisigDepositBase + threshold * MultisigDepositFactor`.",
" -------------------------------",
" - Base Weight:",
" - Create: 46.55 + 0.089 * S µs",
" - Approve: 34.03 + .112 * S µs",
" - Complete: 40.36 + .225 * S µs",
" - DB Weight:",
" - Reads: Multisig Storage, [Caller Account]",
" - Writes: Multisig Storage, [Caller Account]",
" - Plus Call Weight",
" # </weight>"
]
},
@@ -689,6 +698,13 @@
" - Storage: inserts one item, value size bounded by `MaxSignatories`, with a",
" deposit taken for its lifetime of",
" `MultisigDepositBase + threshold * MultisigDepositFactor`.",
" ----------------------------------",
" - Base Weight:",
" - Create: 44.71 + 0.088 * S",
" - Approve: 31.48 + 0.116 * S",
" - DB Weight:",
" - Read: Multisig Storage, [Caller Account]",
" - Write: Multisig Storage, [Caller Account]",
" # </weight>"
]
},
@@ -734,6 +750,11 @@
" - One event.",
" - I/O: 1 read `O(S)`, one remove.",
" - Storage: removes one item.",
" ----------------------------------",
" - Base Weight: 37.6 + 0.084 * S",
" - DB Weight:",
" - Read: Multisig Storage, [Caller Account]",
" - Write: Multisig Storage, [Caller Account]",
" # </weight>"
]
}
@@ -993,7 +1014,7 @@
"Map": {
"hasher": "Twox64Concat",
"key": "u32",
"value": "Vec<RawVRFOutput>",
"value": "Vec<Randomness>",
"linked": false
}
},
@@ -1004,7 +1025,7 @@
"name": "Initialized",
"modifier": "Optional",
"type": {
"Plain": "MaybeVrf"
"Plain": "MaybeRandomness"
},
"fallback": "0x00",
"documentation": [
@@ -1035,7 +1056,7 @@
{
"name": "EpochDuration",
"type": "u64",
"value": "0xc800000000000000",
"value": "0x1400000000000000",
"documentation": [
" The number of **slots** that an epoch takes. We couple sessions to",
" epochs, i.e. we start a new session once the new epoch begins."
@@ -1107,8 +1128,11 @@
"",
" # <weight>",
" - `O(T)` where `T` complexity of `on_timestamp_set`",
" - 2 storage mutations (codec `O(1)`).",
" - 1 storage read and 1 storage mutation (codec `O(1)`). (because of `DidUpdate::take` in `on_finalize`)",
" - 1 event handler `on_timestamp_set` `O(T)`.",
" - Benchmark: 8.523 (min squares analysis)",
" - NOTE: This benchmark was done for a runtime with insignificant `on_timestamp_set` handlers.",
" New benchmarking is needed when adding new handlers.",
" # </weight>"
]
}
@@ -1500,7 +1524,10 @@
" - 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.",
"",
" ---------------------------------",
" - Base Weight: 73.64 µs, worst case scenario (account created, account removed)",
" - DB Weight: 1 Read and 1 Write to destination account",
" - Origin account is already in memory, so no DB operations for them.",
" # </weight>"
]
},
@@ -1533,6 +1560,11 @@
" # <weight>",
" - Independent of the arguments.",
" - Contains a limited number of reads and writes.",
" ---------------------",
" - Base Weight:",
" - Creating: 27.56 µs",
" - Killing: 35.11 µs",
" - DB Weight: 1 Read, 1 Write to `who`",
" # </weight>"
]
},
@@ -1579,7 +1611,12 @@
"",
" 99% of the time you want [`transfer`] instead.",
"",
" [`transfer`]: struct.Module.html#method.transfer"
" [`transfer`]: struct.Module.html#method.transfer",
" # <weight>",
" - Cheaper than transfer because account cannot be killed.",
" - Base Weight: 51.4 µs",
" - DB Weight: 1 Read and 1 Write to dest (sender is in overlay already)",
" #</weight>"
]
}
],
@@ -5584,15 +5621,18 @@
"Vec<(AccountId,Balance)>"
],
"documentation": [
" A new term with new members. This indicates that enough candidates existed, not that",
" enough have has been elected. The inner value must be examined for this purpose."
" A new term with new members. This indicates that enough candidates existed to run the",
" election, not that enough have has been elected. The inner value must be examined for",
" this purpose. A `NewTerm([])` indicates that some candidates got their bond slashed and",
" none were elected, whilst `EmptyTerm` means that no candidates existed to begin with."
]
},
{
"name": "EmptyTerm",
"args": [],
"documentation": [
" No (or not enough) candidates existed for this round."
" No (or not enough) candidates existed for this round. This is different from",
" `NewTerm([])`. See the description of `NewTerm`."
]
},
{
@@ -6230,9 +6270,9 @@
" proposal is awarded.",
"",
" # <weight>",
" - O(1).",
" - Limited storage reads.",
" - One DB change, one extra DB entry.",
" - Complexity: O(1)",
" - DbReads: `ProposalCount`, `origin account`",
" - DbWrites: `ProposalCount`, `Proposals`, `origin account`",
" # </weight>"
]
},
@@ -6248,9 +6288,9 @@
" Reject a proposed spend. The original deposit will be slashed.",
"",
" # <weight>",
" - O(1).",
" - Limited storage reads.",
" - One DB clear.",
" - Complexity: O(1)",
" - DbReads: `Proposals`, `rejected proposer account`",
" - DbWrites: `Proposals`, `rejected proposer account`",
" # </weight>"
]
},
@@ -6267,9 +6307,9 @@
" and the original deposit will be returned.",
"",
" # <weight>",
" - O(1).",
" - Limited storage reads.",
" - One DB change.",
" - Complexity: O(1).",
" - DbReads: `Proposals`, `Approvals`",
" - DbWrite: `Approvals`",
" # </weight>"
]
},
@@ -6300,10 +6340,10 @@
" Emits `NewTip` if successful.",
"",
" # <weight>",
" - `O(R)` where `R` length of `reason`.",
" - One balance operation.",
" - One storage mutation (codec `O(R)`).",
" - One event.",
" - Complexity: `O(R)` where `R` length of `reason`.",
" - encoding and hashing of 'reason'",
" - DbReads: `Reasons`, `Tips`, `who account data`",
" - DbWrites: `Tips`, `who account data`",
" # </weight>"
]
},
@@ -6330,10 +6370,10 @@
" Emits `TipRetracted` if successful.",
"",
" # <weight>",
" - `O(T)`",
" - One balance operation.",
" - Two storage removals (one read, codec `O(T)`).",
" - One event.",
" - Complexity: `O(1)`",
" - Depends on the length of `T::Hash` which is fixed.",
" - DbReads: `Tips`, `origin account`",
" - DbWrites: `Reasons`, `Tips`, `origin account`",
" # </weight>"
]
},
@@ -6368,10 +6408,13 @@
" Emits `NewTip` if successful.",
"",
" # <weight>",
" - `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.",
" - Two storage insertions (codecs `O(R)`, `O(T)`), one read `O(1)`.",
" - One event.",
" - Complexity: `O(R + T)` where `R` length of `reason`, `T` is the number of tippers.",
" - `O(T)`: decoding `Tipper` vec of length `T`",
" `T` is charged as upper bound given by `ContainsLengthBound`.",
" The actual cost depends on the implementation of `T::Tippers`.",
" - `O(R)`: hashing and encoding of reason of length `R`",
" - DbReads: `Tippers`, `Reasons`",
" - DbWrites: `Reasons`, `Tips`",
" # </weight>"
]
},
@@ -6403,9 +6446,15 @@
" has started.",
"",
" # <weight>",
" - `O(T)`",
" - One storage mutation (codec `O(T)`), one storage read `O(1)`.",
" - Up to one event.",
" - Complexity: `O(T)` where `T` is the number of tippers.",
" decoding `Tipper` vec of length `T`, insert tip and check closing,",
" `T` is charged as upper bound given by `ContainsLengthBound`.",
" The actual cost depends on the implementation of `T::Tippers`.",
"",
" Actually weight could be lower as it depends on how many tips are in `OpenTip` but it",
" is weighted as if almost full i.e of length `T-1`.",
" - DbReads: `Tippers`, `Tips`",
" - DbWrites: `Tips`",
" # </weight>"
]
},
@@ -6428,9 +6477,12 @@
" as the hash of the tuple of the original tip `reason` and the beneficiary account ID.",
"",
" # <weight>",
" - `O(T)`",
" - One storage retrieval (codec `O(T)`) and two removals.",
" - Up to three balance operations.",
" - Complexity: `O(T)` where `T` is the number of tippers.",
" decoding `Tipper` vec of length `T`.",
" `T` is charged as upper bound given by `ContainsLengthBound`.",
" The actual cost depends on the implementation of `T::Tippers`.",
" - DbReads: `Tips`, `Tippers`, `tip finder`",
" - DbWrites: `Reasons`, `Tips`, `Tippers`, `tip finder`",
" # </weight>"
]
}
@@ -7162,7 +7214,7 @@
{
"name": "Sudid",
"args": [
"bool"
"DispatchResult"
],
"documentation": [
" A sudo just took place."
@@ -7280,7 +7332,18 @@
"type": "Signature"
}
],
"documentation": []
"documentation": [
" # <weight>",
" - Complexity: `O(K + E)` where K is length of `Keys` and E is length of",
" `Heartbeat.network_state.external_address`",
"",
" - `O(K)`: decoding of length `K`",
" - `O(E)`: decoding/encoding of length `E`",
" - DbReads: pallet_session `Validators`, pallet_session `CurrentIndex`, `Keys`,",
" `ReceivedHeartbeats`",
" - DbWrites: `ReceivedHeartbeats`",
" # </weight>"
]
}
],
"events": [
@@ -7545,9 +7608,7 @@
" - `O(R)` where `R` registrar-count (governance-bounded and code-bounded).",
" - One storage mutation (codec `O(R)`).",
" - One event.",
" - Benchmarks:",
" - 78.71 + R * 0.965 µs (min squares analysis)",
" - 94.28 + R * 0.991 µs (min squares analysis)",
" - Benchmark: 24.63 + R * 0.53 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7578,9 +7639,7 @@
" - One balance reserve operation.",
" - One storage mutation (codec-read `O(X' + R)`, codec-write `O(X + R)`).",
" - One event.",
" - Benchmarks:",
" - 136.6 + R * 0.62 + X * 2.62 µs (min squares analysis)",
" - 146.2 + R * 0.372 + X * 2.98 µs (min squares analysis)",
" - Benchmark: 59.44 + R * 0.389 + X * 1.434 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7613,9 +7672,7 @@
" - One storage read (codec complexity `O(P)`).",
" - One storage write (codec complexity `O(S)`).",
" - One storage-exists (`IdentityOf::contains_key`).",
" - Benchmarks:",
" - 115.2 + P * 5.11 + S * 6.67 µs (min squares analysis)",
" - 121 + P * 4.852 + S * 7.111 µs (min squares analysis)",
" - Benchmark: 39.43 + P * 2.522 + S * 3.698 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7641,8 +7698,8 @@
" - `2` storage reads and `S + 2` storage deletions.",
" - One event.",
" - Benchmarks:",
" - 152.3 + R * 0.306 + S * 4.967 + X * 1.697 µs (min squares analysis)",
" - 139.5 + R * 0.466 + S * 5.304 + X * 1.895 µs (min squares analysis)",
" - 57.36 + R * 0.019 + S * 2.577 + X * 0.874 µs (median slopes analysis)",
" - 57.06 + R * 0.006 + S * 2.579 + X * 0.878 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7681,9 +7738,7 @@
" - One balance-reserve operation.",
" - Storage: 1 read `O(R)`, 1 mutate `O(X + R)`.",
" - One event.",
" - Benchmarks:",
" - 154 + R * 0.932 + X * 3.302 µs (min squares analysis)",
" - 172.9 + R * 0.69 + X * 3.304 µs (min squares analysis)",
" - Benchmark: 59.02 + R * 0.488 + X * 1.7 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7712,9 +7767,7 @@
" - One balance-reserve operation.",
" - One storage mutation `O(R + X)`.",
" - One event.",
" - Benchmarks:",
" - 135.3 + R * 0.574 + X * 3.394 µs (min squares analysis)",
" - 144.3 + R * 0.316 + X * 3.53 µs (min squares analysis)",
" - Benchmark: 50.05 + R * 0.321 + X * 1.688 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7742,8 +7795,7 @@
" # <weight>",
" - `O(R)`.",
" - One storage mutation `O(R)`.",
" - Benchmarks:",
" - 23.81 + R * 0.774 µs (min squares analysis)",
" - Benchmark: 8.848 + R * 0.425 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7771,7 +7823,7 @@
" # <weight>",
" - `O(R)`.",
" - One storage mutation `O(R)`.",
" - Benchmark: 24.59 + R * 0.832 µs (min squares analysis)",
" - Benchmark: 10.05 + R * 0.438 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7799,7 +7851,7 @@
" # <weight>",
" - `O(R)`.",
" - One storage mutation `O(R)`.",
" - Benchmark: 22.85 + R * 0.853 µs (min squares analysis)",
" - Benchmark: 8.985 + R * 0.413 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7838,7 +7890,7 @@
" - Up to one account-lookup operation.",
" - Storage: 1 read `O(R)`, 1 mutate `O(R + X)`.",
" - One event.",
" - Benchmark: 110.7 + R * 1.066 + X * 3.402 µs (min squares analysis)",
" - Benchmark: 47.77 + R * 0.336 + X * 1.664 µs (min squares analysis)",
" # </weight>"
]
},
@@ -7869,7 +7921,7 @@
" - One balance-reserve operation.",
" - `S + 2` storage mutations.",
" - One event.",
" - Benchmark: 167.4 + R * 1.107 + S * 5.343 + X * 2.294 µs (min squares analysis)",
" - Benchmark: 101.9 + R * 0.091 + S * 2.589 + X * 0.871 µs (min squares analysis)",
" # </weight>"
]
}
@@ -9598,9 +9650,13 @@
"",
" # <weight>",
" - `O(1)`.",
" - One balance-lock operation.",
" - One storage read (codec `O(1)`) and up to one removal.",
" - One event.",
" - DbWeight: 2 Reads, 2 Writes",
" - Reads: Vesting Storage, Balances Locks, [Sender Account]",
" - Writes: Vesting Storage, Balances Locks, [Sender Account]",
" - Benchmark:",
" - Unlocked: 48.76 + .048 * l µs (min square analysis)",
" - Locked: 44.43 + .284 * l µs (min square analysis)",
" - Using 50 µs fixed. Assuming less than 50 locks on any user, else we may want factor in number of locks.",
" # </weight>"
]
},
@@ -9624,10 +9680,13 @@
"",
" # <weight>",
" - `O(1)`.",
" - Up to one account lookup.",
" - One balance-lock operation.",
" - One storage read (codec `O(1)`) and up to one removal.",
" - One event.",
" - DbWeight: 3 Reads, 3 Writes",
" - Reads: Vesting Storage, Balances Locks, Target Account",
" - Writes: Vesting Storage, Balances Locks, Target Account",
" - Benchmark:",
" - Unlocked: 44.3 + .294 * l µs (min square analysis)",
" - Locked: 48.16 + .103 * l µs (min square analysis)",
" - Using 50 µs fixed. Assuming less than 50 locks on any user, else we may want factor in number of locks.",
" # </weight>"
]
},
@@ -9655,8 +9714,12 @@
" Emits `VestingCreated`.",
"",
" # <weight>",
" - Creates a new storage entry, but is protected by a minimum transfer",
"\t amount needed to succeed.",
" - `O(1)`.",
" - DbWeight: 3 Reads, 3 Writes",
" - Reads: Vesting Storage, Balances Locks, Target Account, [Sender Account]",
" - Writes: Vesting Storage, Balances Locks, Target Account, [Sender Account]",
" - Benchmark: 100.3 + .365 * l µs (min square analysis)",
" - Using 100 µs fixed. Assuming less than 50 locks on any user, else we may want factor in number of locks.",
" # </weight>"
]
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-core",
"version": "1.12.1",
"version": "1.13.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
"keywords": [
@@ -26,15 +26,15 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/metadata": "1.12.1",
"@polkadot/rpc-provider": "1.12.1",
"@polkadot/types": "1.12.1",
"@polkadot/util": "^2.9.0-beta.3",
"@babel/runtime": "^7.9.6",
"@polkadot/metadata": "1.13.1",
"@polkadot/rpc-provider": "1.13.1",
"@polkadot/types": "1.13.1",
"@polkadot/util": "^2.9.1",
"memoizee": "^0.4.14",
"rxjs": "^6.5.5"
},
"devDependencies": {
"@polkadot/keyring": "^2.9.0-beta.3"
"@polkadot/keyring": "^2.9.1"
}
}
+9 -18
View File
@@ -89,6 +89,8 @@ export default class Rpc implements RpcInterface {
public readonly engine!: RpcInterface['engine'];
public readonly grandpa!: RpcInterface['grandpa'];
public readonly offchain!: RpcInterface['offchain'];
public readonly payment!: RpcInterface['payment'];
@@ -436,24 +438,13 @@ export default class Rpc implements RpcInterface {
this.#storageCache.set(hexKey, value);
if (meta.modifier.isOptional) {
try {
return new Option(
this.registry,
createClass(this.registry, type),
isEmpty
? null
: createTypeUnsafe(this.registry, type, [input], true)
);
} catch (error) {
if (type === 'PreimageStatus') {
return new Option(
this.registry,
createClass(this.registry, type)
);
}
throw error;
}
return new Option(
this.registry,
createClass(this.registry, type),
isEmpty
? null
: createTypeUnsafe(this.registry, type, [input], true)
);
}
return createTypeUnsafe(this.registry, type, [
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-provider",
"version": "1.12.1",
"version": "1.13.1",
"description": "Transport providers for the API",
"main": "index.js",
"keywords": [
@@ -26,18 +26,18 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/metadata": "1.12.1",
"@polkadot/types": "1.12.1",
"@polkadot/util": "^2.9.0-beta.3",
"@polkadot/util-crypto": "^2.9.0-beta.3",
"@babel/runtime": "^7.9.6",
"@polkadot/metadata": "1.13.1",
"@polkadot/types": "1.13.1",
"@polkadot/util": "^2.9.1",
"@polkadot/util-crypto": "^2.9.1",
"bn.js": "^5.1.1",
"eventemitter3": "^4.0.0",
"isomorphic-fetch": "^2.2.1",
"websocket": "^1.0.31"
},
"devDependencies": {
"@polkadot/keyring": "^2.9.0-beta.3",
"@polkadot/keyring": "^2.9.1",
"mock-socket": "^9.0.3",
"nock": "^12.0.3"
}
+22 -9
View File
@@ -65,7 +65,7 @@ const l = logger('api-ws');
export default class WsProvider implements WSProviderInterface {
readonly #coder: Coder;
readonly #endpoint: string;
readonly #endpoints: string[];
readonly #eventemitter: EventEmitter;
@@ -77,6 +77,8 @@ export default class WsProvider implements WSProviderInterface {
#autoConnectMs: number;
#endpointIndex: number;
#isConnected = false;
#subscriptions: Record<string, WsStateSubscription> = {};
@@ -84,16 +86,25 @@ export default class WsProvider implements WSProviderInterface {
#websocket: WebSocket | null;
/**
* @param {string} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`
* @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings.
* @param {boolean} autoConnect Whether to connect automatically or not.
*/
constructor (endpoint: string = defaults.WS_URL, autoConnectMs: number | false = 1000) {
assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`);
constructor (endpoint: string | string[] = defaults.WS_URL, autoConnectMs: number | false = 1000) {
const endpoints = Array.isArray(endpoint)
? endpoint
: [endpoint];
assert(endpoints.length !== 0, 'WsProvider requires at least one Endpoint');
endpoints.forEach((endpoint) => {
assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`);
});
this.#eventemitter = new EventEmitter();
this.#autoConnectMs = autoConnectMs || 0;
this.#coder = new Coder();
this.#endpoint = endpoint;
this.#endpointIndex = -1;
this.#endpoints = endpoints;
this.#websocket = null;
if (autoConnectMs > 0) {
@@ -112,7 +123,7 @@ export default class WsProvider implements WSProviderInterface {
* @description Returns a clone of the object
*/
public clone (): WsProvider {
return new WsProvider(this.#endpoint);
return new WsProvider(this.#endpoints);
}
/**
@@ -122,9 +133,11 @@ export default class WsProvider implements WSProviderInterface {
*/
public async connect (): Promise<void> {
try {
this.#endpointIndex = (this.#endpointIndex + 1) % this.#endpoints.length;
const WS = await getWSClass();
this.#websocket = new WS(this.#endpoint);
this.#websocket = new WS(this.#endpoints[this.#endpointIndex]);
this.#websocket.onclose = this.#onSocketClose;
this.#websocket.onerror = this.#onSocketError;
this.#websocket.onmessage = this.#onSocketMessage;
@@ -268,7 +281,7 @@ export default class WsProvider implements WSProviderInterface {
#onSocketClose = (event: CloseEvent): void => {
if (this.#autoConnectMs > 0) {
l.error(`disconnected from ${this.#endpoint} code: '${event.code}' reason: '${event.reason}'`);
l.error(`disconnected from ${this.#endpoints[this.#endpointIndex]} code: '${event.code}' reason: '${event.reason}'`);
}
this.#isConnected = false;
@@ -363,7 +376,7 @@ export default class WsProvider implements WSProviderInterface {
#onSocketOpen = (): boolean => {
assert(!isNull(this.#websocket), 'WebSocket cannot be null in onOpen');
l.debug((): any[] => ['connected to', this.#endpoint]);
l.debug((): any[] => ['connected to', this.#endpoints[this.#endpointIndex]]);
this.#isConnected = true;
+103 -12
View File
@@ -6,17 +6,25 @@ import WsProvider from './';
import { Mock } from './../mock/types';
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
function sleepMs (ms = 0): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
describe('onConnect', (): void => {
let mock: Mock;
let mocks: Mock[];
beforeEach((): void => {
mock = mockWs([]);
jest.setTimeout(30000);
mocks = [mockWs([])];
});
afterEach((): void => {
if (mock) {
mock.done();
}
jest.setTimeout(5000);
mocks.forEach((m) => {
if (m) {
m.done();
}
});
});
it('Does not connect when autoConnect is false', (): void => {
@@ -25,19 +33,102 @@ describe('onConnect', (): void => {
expect(provider.isConnected()).toBe(false);
});
it('Does connect when autoConnect is true', (): void => {
const provider: WsProvider = new WsProvider(TEST_WS_URL, 1000);
it('Does connect when autoConnect is true', async () => {
const provider: WsProvider = new WsProvider(TEST_WS_URL, 1);
expect(provider.isConnected()).not.toBe(true);
await sleepMs(100); // Hack to give the provider time to connect
expect(provider.isConnected()).toBe(true);
});
it('Creates a new WebSocket instance by calling the connect() method', (): void => {
const provider: WsProvider = new WsProvider(TEST_WS_URL, 0);
it('Creates a new WebSocket instance by calling the connect() method', async () => {
const provider: WsProvider = new WsProvider(TEST_WS_URL, false);
expect(provider.isConnected()).toBe(false);
expect(mocks[0].server.clients().length).toBe(0);
provider.connect();
await provider.connect();
await sleepMs(100); // Hack to give the provider time to connect
expect(provider.isConnected()).not.toBe(true);
expect(provider.isConnected()).toBe(true);
expect(mocks[0].server.clients().length).toBe(1);
});
it('Connects to first endpoint when an array is given', async () => {
const provider: WsProvider = new WsProvider([TEST_WS_URL], 1);
await provider.connect();
await sleepMs(100); // Hack to give the provider time to connect
expect(provider.isConnected()).toBe(true);
});
it('Connects to the second endpoint when the first is unreachable', async () => {
/* eslint-disable @typescript-eslint/no-empty-function */
jest.spyOn(console, 'error').mockImplementation((): void => {});
const endpoints: string[] = ['ws://localhost:9956', TEST_WS_URL];
const provider: WsProvider = new WsProvider(endpoints, 1);
await sleepMs(100); // Hack to give the provider time to connect
expect(provider.isConnected()).toBe(true);
});
it('Connects to the second endpoint when the first is dropped', async () => {
const endpoints: string[] = [TEST_WS_URL, 'ws://localhost:9957'];
mocks.push(mockWs([], endpoints[1]));
const provider: WsProvider = new WsProvider(endpoints, 1);
await sleepMs(100); // Hack to give the provider time to connect
// Check that first server is connected
expect(mocks[0].server.clients().length).toBe(1);
expect(mocks[1].server.clients().length).toBe(0);
// Close connection from first server
mocks[0].server.clients()[0].close();
await sleepMs(100);
// Check that second server is connected
expect(mocks[1].server.clients().length).toBe(1);
expect(provider.isConnected()).toBe(true);
});
it('Round-robin of endpoints on WsProvider', async () => {
const rounds = 5;
const endpoints: string[] = [
TEST_WS_URL,
'ws://localhost:9956',
'ws://localhost:9957',
'ws://invalid:9956',
'ws://localhost:9958'
];
mocks.push(mockWs([], endpoints[1]));
mocks.push(mockWs([], endpoints[2]));
mocks.push(mockWs([], endpoints[4]));
const mockNext = [
mocks[1],
mocks[2],
mocks[3],
mocks[0]
];
const provider: WsProvider = new WsProvider(endpoints, 1);
for (let round = 0; round < rounds; round++) {
for (let index = 0; index < mocks.length; index++) {
await sleepMs(100); // Hack to give the provider time to connect
// Check that first server is connected and the next one isn't
expect(mocks[index].server.clients().length).toBe(1);
expect(mockNext[index].server.clients().length).toBe(0);
expect(provider.isConnected()).toBe(true);
// Close connection from first server
mocks[index].server.clients()[0].close();
}
}
});
});
@@ -29,3 +29,42 @@ describe('Ws', (): void => {
).toEqual(false);
});
});
describe('Endpoint Parsing', (): void => {
it('Succeeds when WsProvider endpoint is a valid string', () => {
/* eslint-disable no-new */
new WsProvider(TEST_WS_URL, 0);
});
it('Throws when WsProvider endpoint is an invalid string', () => {
expect(() => {
/* eslint-disable no-new */
new WsProvider('http://127.0.0.1:9955', 0);
}).toThrowError(/^Endpoint should start with /);
});
it('Succeeds when WsProvider endpoint is a valid array', () => {
const endpoints: string[] = ['ws://127.0.0.1:9955', 'wss://testnet.io:9944', 'ws://mychain.com:9933'];
/* eslint-disable no-new */
new WsProvider(endpoints, 0);
});
it('Throws when WsProvider endpoint is an empty array', () => {
const endpoints: string[] = [];
expect(() => {
/* eslint-disable no-new */
new WsProvider(endpoints, 0);
}).toThrowError('WsProvider requires at least one Endpoint');
});
it('Throws when WsProvider endpoint is an invalid array', () => {
const endpoints: string[] = ['ws://127.0.0.1:9955', 'http://bad.co:9944', 'ws://mychain.com:9933'];
expect(() => {
/* eslint-disable no-new */
new WsProvider(endpoints, 0);
}).toThrowError(/^Endpoint should start with /);
});
});
+2 -4
View File
@@ -6,8 +6,6 @@ import { Server } from 'mock-socket';
const TEST_WS_URL = 'ws://localhost:9955';
let server: Server;
interface Scope {
body: { [index: string]: {} };
requests: number;
@@ -52,8 +50,8 @@ function createReply ({ id, reply: { result } }: ReplyDef): any {
}
// scope definition returned
function mockWs (requests: { method: string }[]): Scope {
server = new Server(TEST_WS_URL);
function mockWs (requests: { method: string }[], wsUrl: string = TEST_WS_URL): Scope {
const server = new Server(wsUrl);
let requestCount = 0;
const scope: Scope = {
+9 -8
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/typegen",
"version": "1.12.1",
"version": "1.13.1",
"description": "Type generation scripts",
"main": "index.js",
"bin": {
@@ -33,14 +33,15 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
"dependencies": {
"@babel/core": "^7.9.0",
"@babel/core": "^7.9.6",
"@babel/register": "^7.9.0",
"@babel/runtime": "^7.9.2",
"@polkadot/api": "1.12.1",
"@polkadot/metadata": "1.12.1",
"@polkadot/rpc-provider": "1.12.1",
"@polkadot/types": "1.12.1",
"@polkadot/util": "^2.9.0-beta.3",
"@babel/runtime": "^7.9.6",
"@polkadot/api": "1.13.1",
"@polkadot/metadata": "1.13.1",
"@polkadot/rpc-provider": "1.13.1",
"@polkadot/types": "1.13.1",
"@polkadot/util": "^2.9.1",
"handlebars": "^4.7.6",
"websocket": "^1.0.31",
"yargs": "^15.3.1"
},
+40 -39
View File
@@ -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<object & Codec>;'))
.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<string, Record<string, { types: Record<string, any> }>>, isStrict: boolean): void {
@@ -42,27 +23,47 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<strin
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(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
});
});
}
@@ -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<string, boolean> = {};
// 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
});
});
}
+44 -45
View File
@@ -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<ApiType>;'))
.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}<ApiType, (${args}) => Observable<${returnType}>>${isStrict ? '' : ' & QueryableStorageEntry<ApiType>'};`);
}))
.concat([indent(4)('};')]);
}
const template = readTemplate('query');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>>, 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<ApiType> {\n')
].join('\n');
const interfaceEnd = `\n${indent(2)('}')}\n\n`;
const queryableStorageInterface = indent(2)('export interface QueryableStorage<ApiType extends ApiTypes> extends AugmentedQueries<ApiType> {')
.concat('\n')
.concat(isStrict ? '' : indent(4)('[index: string]: QueryableModuleStorage<ApiType>;\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
});
});
}
+54 -31
View File
@@ -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<string[]>((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<<T = Codec>(key: ${StorageKeyTye}, block?: Hash | Uint8Array | string) => Observable<T>>;`);
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<<T = Codec[]>(keys: Vec<StorageKey> | (${StorageKeyTye})[], fromBlock?: Hash | Uint8Array | string, toBlock?: Hash | Uint8Array | string) => Observable<[Hash, T][]>>;`);
generic = 'T = Codec[]';
args = [`keys: Vec<StorageKey> | (${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<<T = Codec[]>(keys: Vec<StorageKey> | (${StorageKeyTye})[], at?: Hash | Uint8Array | string) => Observable<T>>;`);
generic = 'T = Codec[]';
args = [`keys: Vec<StorageKey> | (${StorageKeyTye})[], at?: Hash | Uint8Array | string`];
type = 'T';
} else if (methodName === 'subscribeStorage') {
return createDocComments(6, [def.description]) + indent(6)(`subscribeStorage: AugmentedRpc<<T = Codec[]>(keys?: Vec<StorageKey> | (${StorageKeyTye})[]) => Observable<T>>;`);
generic = 'T = Codec[]';
args = [`keys?: Vec<StorageKey> | (${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
});
});
}
+28 -15
View File
@@ -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<str
});
}
const templateIndex = readTemplate('tsDef/index');
const generateTsDefIndexTemplate = Handlebars.compile(templateIndex);
const templateModuleTypes = readTemplate('tsDef/moduleTypes');
const generateTsDefModuleTypesTemplate = Handlebars.compile(templateModuleTypes);
const templateTypes = readTemplate('tsDef/types');
const generateTsDefTypesTemplate = Handlebars.compile(templateTypes);
/** @internal */
function generateTsDefFor (importDefinitions: { [importPath: string]: object }, defName: string, { types }: { types: Record<string, any> }, 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 */
+49 -57
View File
@@ -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<string, string> = {
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<ApiType>;'))
.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<ApiType>>;`);
}))
.concat([indent(4)('};')]);
}
const template = readTemplate('tx');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>>, 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<ApiType> {\n')
].join('\n');
const interfaceEnd = `\n${indent(2)('}')}\n\n`;
const submittableExtrinsicsInterface = indent(2)('export interface SubmittableExtrinsics<ApiType extends ApiTypes> extends AugmentedSubmittables<ApiType> {')
.concat('\n')
.concat(indent(4)('(extrinsic: Call | Extrinsic | Uint8Array | string): SubmittableExtrinsic<ApiType>;\n'))
.concat(isStrict ? '' : indent(4)('[index: string]: SubmittableModuleExtrinsics<ApiType>;\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
});
});
}
+23
View File
@@ -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<object & Codec>;
{{/unless}}
{{~#each items}}
{{> docs}}
{{{name}}}: AugmentedConst<{{{type}}}>;
{{/each}}
};
{{/each}}
}
}
{{> footer }}
+7
View File
@@ -0,0 +1,7 @@
{{#if docs.length}}
/**
{{#each docs}}
* {{#trim}}{{{this}}}{{/trim}}
{{/each}}
**/
{{/if}}
@@ -0,0 +1,2 @@
// Auto-generated via `yarn polkadot-types-from-{{headerType}}`, do not edit
/* eslint-disable */
@@ -0,0 +1,12 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/types/types/registry' {
export interface InterfaceTypes {
{{#each items}}
{{{this}}}
{{/each}}
}
}
{{> footer }}
+26
View File
@@ -0,0 +1,26 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/api/types/storage' {
export interface AugmentedQueries<ApiType> {
{{#each modules}}
{{{name}}}: {
{{#unless @root.isStrict}}
[index: string]: QueryableStorageEntry<ApiType>;
{{/unless}}
{{~#each items}}
{{> docs}}
{{{name}}}: {{{entryType}}}<ApiType, ({{{args}}}) => Observable<{{{returnType}}}>>{{#unless @root.isStrict}} & QueryableStorageEntry<ApiType>{{/unless}};
{{/each}}
};
{{/each}}
}
export interface QueryableStorage<ApiType extends ApiTypes> extends AugmentedQueries<ApiType> {
{{#unless isStrict}}
[index: string]: QueryableModuleStorage<ApiType>;
{{/unless}}
}
}
{{> footer }}
+17
View File
@@ -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 }}
@@ -0,0 +1,4 @@
{{> header }}
export * from './types';
{{> footer }}
@@ -0,0 +1,11 @@
{{> header }}
{{{ imports }}}
{{#each items}}
{{{this}}}
{{/each}}
export type PHANTOM_{{#upper}}{{{name}}}{{/upper}} = '{{{name}}}';
{{> footer }}
@@ -0,0 +1,6 @@
{{> header }}
{{#each items}}
export * from './{{{this}}}/types';
{{/each}}
{{> footer }}
+27
View File
@@ -0,0 +1,27 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/api/types/submittable' {
export interface AugmentedSubmittables<ApiType> {
{{#each modules}}
{{{name}}}: {
{{#unless @root.isStrict}}
[index: string]: SubmittableExtrinsicFunction<ApiType>;
{{/unless}}
{{~#each items}}
{{> docs}}
{{{name}}}: AugmentedSubmittable<({{{params}}}) => SubmittableExtrinsic<ApiType>>;
{{/each}}
};
{{/each}}
}
export interface SubmittableExtrinsics<ApiType extends ApiTypes> extends AugmentedSubmittables<ApiType> {
(extrinsic: Call | Extrinsic | Uint8Array | string): SubmittableExtrinsic<ApiType>;
{{#unless isStrict}}
[index: string]: SubmittableModuleExtrinsics<ApiType>;
{{/unless}}
}
}
{{> footer }}
+5 -17
View File
@@ -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'))
});
+4
View File
@@ -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();
}
@@ -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');
});
});
+59 -54
View File
@@ -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 <Name> extends <Base> {<Body>}
/** @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}`;
};
}
+3
View File
@@ -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());
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/types-known",
"version": "1.12.1",
"version": "1.13.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
"keywords": [
@@ -26,9 +26,9 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/types": "1.12.1",
"@polkadot/util": "^2.9.0-beta.3",
"@babel/runtime": "^7.9.6",
"@polkadot/types": "1.13.1",
"@polkadot/util": "^2.9.1",
"bn.js": "^5.1.1"
},
"devDependencies": {
@@ -6,7 +6,8 @@ import { OverrideVersionedType } from '@polkadot/types/types';
const versioned: OverrideVersionedType[] = [
{
minmax: [1000, undefined],
// most chains started at 1000 (Fulvous at 224)
minmax: [1, undefined],
types: {
Address: 'AccountId',
LookupSource: 'AccountId',
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/types",
"version": "1.12.1",
"version": "1.13.1",
"description": "Implementation of the Parity codec",
"main": "index.js",
"keywords": [
@@ -26,17 +26,17 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/metadata": "1.12.1",
"@polkadot/util": "^2.9.0-beta.3",
"@polkadot/util-crypto": "^2.9.0-beta.3",
"@babel/runtime": "^7.9.6",
"@polkadot/metadata": "1.13.1",
"@polkadot/util": "^2.9.1",
"@polkadot/util-crypto": "^2.9.1",
"@types/bn.js": "^4.11.6",
"bn.js": "^5.1.1",
"memoizee": "^0.4.14",
"rxjs": "^6.5.5"
},
"devDependencies": {
"@polkadot/keyring": "^2.9.0-beta.3",
"@types/memoizee": "^0.4.3"
"@polkadot/keyring": "^2.9.1",
"@types/memoizee": "^0.4.4"
}
}
+40 -3
View File
@@ -7,7 +7,7 @@ import { BlockAttestations, IncludedBlocks, MoreAttestations } from '@polkadot/t
import { RawAuraPreDigest } from '@polkadot/types/interfaces/aura';
import { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
import { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
import { BabeAuthorityWeight, BabeBlockWeight, BabeWeight, EpochAuthorship, MaybeVrf, Randomness, RawBabePreDigest, RawBabePreDigestCompat, RawBabePreDigestPrimary, RawBabePreDigestPrimaryTo159, RawBabePreDigestSecondary, RawBabePreDigestSecondaryTo159, RawBabePreDigestTo159, SlotNumber, VrfData, VrfProof } from '@polkadot/types/interfaces/babe';
import { BabeAuthorityWeight, BabeBlockWeight, BabeWeight, EpochAuthorship, MaybeRandomness, MaybeVrf, Randomness, RawBabePreDigest, RawBabePreDigestCompat, RawBabePreDigestPrimary, RawBabePreDigestPrimaryTo159, RawBabePreDigestSecondary, RawBabePreDigestSecondaryTo159, RawBabePreDigestTo159, SlotNumber, VrfData, VrfProof } from '@polkadot/types/interfaces/babe';
import { AccountData, BalanceLock, BalanceLockTo212, Reasons, ReleasesBalances, VestingSchedule, WithdrawReasons } from '@polkadot/types/interfaces/balances';
import { BlockHash } from '@polkadot/types/interfaces/chain';
import { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
@@ -21,7 +21,7 @@ import { CreatedBlock, ImportedAux } from '@polkadot/types/interfaces/engine';
import { Account, Log } from '@polkadot/types/interfaces/evm';
import { EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV1, ExtrinsicPayloadV2, ExtrinsicPayloadV3, ExtrinsicPayloadV4, ExtrinsicSignatureV1, ExtrinsicSignatureV2, ExtrinsicSignatureV3, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV1, ExtrinsicV2, ExtrinsicV3, ExtrinsicV4, ImmortalEra, MortalEra, MultiSignature, Signature, SignerPayload, Sr25519Signature } from '@polkadot/types/interfaces/extrinsics';
import { AssetOptions, Owner, PermissionLatest, PermissionVersions, PermissionsV1 } from '@polkadot/types/interfaces/genericAsset';
import { AuthorityIndex, AuthorityList, AuthorityWeight, NextAuthority, PendingPause, PendingResume, SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import { AuthorityIndex, AuthorityList, AuthorityWeight, Equivocation, EquivocationProof, GrandpaEquivocation, GrandpaPrevote, KeyOwnerProof, NextAuthority, PendingPause, PendingResume, Precommits, Prevotes, ReportedRoundStates, RoundState, SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import { IdentityFields, IdentityInfo, IdentityInfoAdditional, IdentityJudgement, RegistrarIndex, RegistrarInfo, Registration, RegistrationJudgement } from '@polkadot/types/interfaces/identity';
import { AuthIndex, AuthoritySignature, Heartbeat, OpaqueMultiaddr, OpaqueNetworkState, OpaquePeerId } from '@polkadot/types/interfaces/imOnline';
import { CallMetadataV0, DoubleMapTypeLatest, DoubleMapTypeV10, DoubleMapTypeV11, DoubleMapTypeV3, DoubleMapTypeV4, DoubleMapTypeV5, DoubleMapTypeV6, DoubleMapTypeV7, DoubleMapTypeV8, DoubleMapTypeV9, ErrorMetadataV10, ErrorMetadataV11, ErrorMetadataV8, ErrorMetadataV9, EventMetadataLatest, EventMetadataV0, EventMetadataV1, EventMetadataV10, EventMetadataV11, EventMetadataV2, EventMetadataV3, EventMetadataV4, EventMetadataV5, EventMetadataV6, EventMetadataV7, EventMetadataV8, EventMetadataV9, ExtrinsicMetadataLatest, ExtrinsicMetadataV11, FunctionArgumentMetadataLatest, FunctionArgumentMetadataV0, FunctionArgumentMetadataV1, FunctionArgumentMetadataV10, FunctionArgumentMetadataV11, FunctionArgumentMetadataV2, FunctionArgumentMetadataV3, FunctionArgumentMetadataV4, FunctionArgumentMetadataV5, FunctionArgumentMetadataV6, FunctionArgumentMetadataV7, FunctionArgumentMetadataV8, FunctionArgumentMetadataV9, FunctionMetadataLatest, FunctionMetadataV0, FunctionMetadataV1, FunctionMetadataV10, FunctionMetadataV11, FunctionMetadataV2, FunctionMetadataV3, FunctionMetadataV4, FunctionMetadataV5, FunctionMetadataV6, FunctionMetadataV7, FunctionMetadataV8, FunctionMetadataV9, MapTypeLatest, MapTypeV0, MapTypeV10, MapTypeV11, MapTypeV2, MapTypeV3, MapTypeV4, MapTypeV5, MapTypeV6, MapTypeV7, MapTypeV8, MapTypeV9, MetadataAll, MetadataLatest, MetadataV0, MetadataV1, MetadataV10, MetadataV11, MetadataV2, MetadataV3, MetadataV4, MetadataV5, MetadataV6, MetadataV7, MetadataV8, MetadataV9, ModuleConstantMetadataLatest, ModuleConstantMetadataV10, ModuleConstantMetadataV11, ModuleConstantMetadataV6, ModuleConstantMetadataV7, ModuleConstantMetadataV8, ModuleConstantMetadataV9, ModuleMetadataLatest, ModuleMetadataV0, ModuleMetadataV1, ModuleMetadataV10, ModuleMetadataV11, ModuleMetadataV2, ModuleMetadataV3, ModuleMetadataV4, ModuleMetadataV5, ModuleMetadataV6, ModuleMetadataV7, ModuleMetadataV8, ModuleMetadataV9, OuterDispatchCallV0, OuterDispatchMetadataV0, OuterEventEventMetadataEventsV0, OuterEventEventMetadataV0, OuterEventMetadataV0, PlainTypeLatest, PlainTypeV0, PlainTypeV10, PlainTypeV11, PlainTypeV2, PlainTypeV3, PlainTypeV4, PlainTypeV5, PlainTypeV6, PlainTypeV7, PlainTypeV8, PlainTypeV9, RuntimeModuleMetadataV0, StorageEntryMetadataLatest, StorageEntryMetadataV10, StorageEntryMetadataV11, StorageEntryMetadataV6, StorageEntryMetadataV7, StorageEntryMetadataV8, StorageEntryMetadataV9, StorageEntryModifierLatest, StorageEntryModifierV10, StorageEntryModifierV11, StorageEntryModifierV6, StorageEntryModifierV7, StorageEntryModifierV8, StorageEntryModifierV9, StorageEntryTypeLatest, StorageEntryTypeV10, StorageEntryTypeV11, StorageEntryTypeV6, StorageEntryTypeV7, StorageEntryTypeV8, StorageEntryTypeV9, StorageFunctionMetadataV0, StorageFunctionMetadataV1, StorageFunctionMetadataV2, StorageFunctionMetadataV3, StorageFunctionMetadataV4, StorageFunctionMetadataV5, StorageFunctionModifierV0, StorageFunctionModifierV1, StorageFunctionModifierV2, StorageFunctionModifierV3, StorageFunctionModifierV4, StorageFunctionModifierV5, StorageFunctionTypeV0, StorageFunctionTypeV1, StorageFunctionTypeV2, StorageFunctionTypeV3, StorageFunctionTypeV4, StorageFunctionTypeV5, StorageHasher, StorageHasherV10, StorageHasherV11, StorageHasherV4, StorageHasherV5, StorageHasherV6, StorageHasherV7, StorageHasherV8, StorageHasherV9, StorageMetadataLatest, StorageMetadataV0, StorageMetadataV10, StorageMetadataV11, StorageMetadataV7, StorageMetadataV8, StorageMetadataV9 } from '@polkadot/types/interfaces/metadata';
@@ -33,7 +33,7 @@ import { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recov
import { RpcMethods } from '@polkadot/types/interfaces/rpc';
import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, DispatchClass, DispatchInfo, DispatchInfoTo190, Fixed128, Fixed64, H160, H256, H512, Hash, Header, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, ModuleId, Moment, Origin, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, RuntimeDbWeight, Seal, SealV0, SignedBlock, StorageData, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';
import { SchedulePeriod, SchedulePriority, Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import { FullIdentification, IdentificationTuple, Keys, SessionIndex, SessionKeys1, SessionKeys2, SessionKeys3, SessionKeys4, SessionKeys5, SessionKeys6 } from '@polkadot/types/interfaces/session';
import { FullIdentification, IdentificationTuple, Keys, MembershipProof, SessionIndex, SessionKeys1, SessionKeys2, SessionKeys3, SessionKeys4, SessionKeys5, SessionKeys6, ValidatorCount } from '@polkadot/types/interfaces/session';
import { Bid, BidKind, SocietyJudgement, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import { ActiveEraInfo, CompactAssignments, CompactScore, ElectionCompute, ElectionResult, ElectionStatus, EraIndex, EraPoints, EraRewardPoints, EraRewards, Exposure, Forcing, IndividualExposure, KeyType, MomentOf, Nominations, NominatorIndex, OffchainAccuracy, PerU16, PhragmenScore, Points, ReleasesStaking, RewardDestination, RewardPoint, SlashJournalEntry, SlashingSpans, SlashingSpansTo204, SpanIndex, SpanRecord, StakingLedger, StakingLedgerTo223, StakingLedgerTo240, UnappliedSlash, UnappliedSlashOther, UnlockChunk, ValidatorIndex, ValidatorPrefs, ValidatorPrefsTo145, ValidatorPrefsTo196 } from '@polkadot/types/interfaces/staking';
import { ApiId, KeyValueOption, ReadProof, RuntimeVersion, RuntimeVersionApi, StorageChangeSet } from '@polkadot/types/interfaces/state';
@@ -300,6 +300,9 @@ declare module '@polkadot/types/types/registry' {
'Compact<BabeBlockWeight>': Compact<BabeBlockWeight>;
'Option<BabeBlockWeight>': Option<BabeBlockWeight>;
'Vec<BabeBlockWeight>': Vec<BabeBlockWeight>;
MaybeRandomness: MaybeRandomness;
'Option<MaybeRandomness>': Option<MaybeRandomness>;
'Vec<MaybeRandomness>': Vec<MaybeRandomness>;
MaybeVrf: MaybeVrf;
'Option<MaybeVrf>': Option<MaybeVrf>;
'Vec<MaybeVrf>': Vec<MaybeVrf>;
@@ -630,6 +633,21 @@ declare module '@polkadot/types/types/registry' {
'Compact<AuthorityWeight>': Compact<AuthorityWeight>;
'Option<AuthorityWeight>': Option<AuthorityWeight>;
'Vec<AuthorityWeight>': Vec<AuthorityWeight>;
Equivocation: Equivocation;
'Option<Equivocation>': Option<Equivocation>;
'Vec<Equivocation>': Vec<Equivocation>;
EquivocationProof: EquivocationProof;
'Option<EquivocationProof>': Option<EquivocationProof>;
'Vec<EquivocationProof>': Vec<EquivocationProof>;
GrandpaEquivocation: GrandpaEquivocation;
'Option<GrandpaEquivocation>': Option<GrandpaEquivocation>;
'Vec<GrandpaEquivocation>': Vec<GrandpaEquivocation>;
GrandpaPrevote: GrandpaPrevote;
'Option<GrandpaPrevote>': Option<GrandpaPrevote>;
'Vec<GrandpaPrevote>': Vec<GrandpaPrevote>;
KeyOwnerProof: KeyOwnerProof;
'Option<KeyOwnerProof>': Option<KeyOwnerProof>;
'Vec<KeyOwnerProof>': Vec<KeyOwnerProof>;
NextAuthority: NextAuthority;
'Option<NextAuthority>': Option<NextAuthority>;
'Vec<NextAuthority>': Vec<NextAuthority>;
@@ -639,6 +657,18 @@ declare module '@polkadot/types/types/registry' {
PendingResume: PendingResume;
'Option<PendingResume>': Option<PendingResume>;
'Vec<PendingResume>': Vec<PendingResume>;
Precommits: Precommits;
'Option<Precommits>': Option<Precommits>;
'Vec<Precommits>': Vec<Precommits>;
Prevotes: Prevotes;
'Option<Prevotes>': Option<Prevotes>;
'Vec<Prevotes>': Vec<Prevotes>;
ReportedRoundStates: ReportedRoundStates;
'Option<ReportedRoundStates>': Option<ReportedRoundStates>;
'Vec<ReportedRoundStates>': Vec<ReportedRoundStates>;
RoundState: RoundState;
'Option<RoundState>': Option<RoundState>;
'Vec<RoundState>': Vec<RoundState>;
SetId: SetId;
'Compact<SetId>': Compact<SetId>;
'Option<SetId>': Option<SetId>;
@@ -760,10 +790,17 @@ declare module '@polkadot/types/types/registry' {
IdentificationTuple: IdentificationTuple;
'Option<IdentificationTuple>': Option<IdentificationTuple>;
'Vec<IdentificationTuple>': Vec<IdentificationTuple>;
MembershipProof: MembershipProof;
'Option<MembershipProof>': Option<MembershipProof>;
'Vec<MembershipProof>': Vec<MembershipProof>;
SessionIndex: SessionIndex;
'Compact<SessionIndex>': Compact<SessionIndex>;
'Option<SessionIndex>': Option<SessionIndex>;
'Vec<SessionIndex>': Vec<SessionIndex>;
ValidatorCount: ValidatorCount;
'Compact<ValidatorCount>': Compact<ValidatorCount>;
'Option<ValidatorCount>': Option<ValidatorCount>;
'Vec<ValidatorCount>': Vec<ValidatorCount>;
Bid: Bid;
'Option<Bid>': Option<Bid>;
'Vec<Bid>': Vec<Bid>;
+9 -1
View File
@@ -44,13 +44,21 @@ describe('Tuple', (): void => {
testDecode('hex', '0x1c62617a7a696e6745000000');
testDecode('Uint8Array', Uint8Array.from([28, 98, 97, 122, 122, 105, 110, 103, 69, 0, 0, 0]));
it('decodes reusing instanciated inputs', (): void => {
it('decodes reusing instantiated inputs', (): void => {
const foo = new Text(registry, 'bar');
expect(
(new Tuple(registry, [Text], [foo]))[0]
).toBe(foo);
});
it('decodes properly from complex types', (): void => {
const INPUT = '0xcc0200000000';
const test = registry.createType('(u32, [u32; 0], u16)' as any, INPUT);
expect(test.encodedLength).toEqual(4 + 0 + 2);
expect(test.toHex()).toEqual(INPUT);
});
});
describe('encoding', (): void => {
+9 -1
View File
@@ -61,7 +61,7 @@ describe('Vec', (): void => {
expect(vector.Type).toEqual('Text');
});
it('decodes reusing instanciated inputs', (): void => {
it('decodes reusing instantiated inputs', (): void => {
const foo = new Text(registry, 'bar');
expect(
@@ -79,6 +79,14 @@ describe('Vec', (): void => {
expect((first[1] as AccountId).toString()).toEqual('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua');
});
it('decodes a complex type via construction', (): void => {
const INPUT = '0x08cc0200000000ce0200000001';
const test = createTypeUnsafe(registry, 'Vec<(u32, [u32; 0], u16)>' as any, [INPUT]);
expect((test as Vec<any>).length).toEqual(2);
expect(test.toHex()).toEqual(INPUT);
});
describe('vector-like functions', (): void => {
it('allows retrieval of a specific item', (): void => {
expect(
+15 -1
View File
@@ -18,7 +18,7 @@ describe('VecFixed', (): void => {
expect(new VecFixed(registry, Text, 2, new Uint8Array([0x00, 0x04, 0x31])).toHex()).toEqual('0x000431');
});
it('decodes reusing instanciated inputs', (): void => {
it('decodes reusing instance inputs', (): void => {
const foo = new Text(registry, 'bar');
expect(
@@ -43,5 +43,19 @@ describe('VecFixed', (): void => {
// each entry length 1 << 2, char as hex (0x31 === `1`), one empty
expect(test.toHex()).toEqual('0x043104320433000435');
});
it('has empty Uint8Array when length is 0', (): void => {
const test = new (VecFixed.with(Text, 0))(registry);
expect(test.encodedLength).toEqual(0);
expect(test.toU8a()).toEqual(new Uint8Array([]));
});
it('has equivalent to 1 Uint8Array when length is 1', (): void => {
const test = new (VecFixed.with(Text, 1))(registry, ['hello']);
expect(test.encodedLength).toEqual(1 + 5);
expect(test.toU8a()).toEqual(new Uint8Array([20, 104, 101, 108, 108, 111]));
});
});
});
+14 -5
View File
@@ -59,12 +59,21 @@ export default class VecFixed<T extends Codec> extends AbstractArray<T> {
return new this._Type(this.registry).toRawType();
}
public toU8a (): Uint8Array {
// we override, we don't add the length prefix for outselves, and at the same time we
// ignore isBare on entries, since they should be properly encoded at all times
const encoded = this.map((entry): Uint8Array => entry.toU8a());
/**
* @description The length of the value when encoded as a Uint8Array
*/
public get encodedLength (): number {
return this.toU8a().length;
}
return u8aConcat(...encoded);
public toU8a (): Uint8Array {
// we override, we don't add the length prefix for ourselves, and at the same time we
// ignore isBare on entries, since they should be properly encoded at all times
const encoded = this.map((entry) => entry.toU8a());
return encoded.length
? u8aConcat(...encoded)
: new Uint8Array([]);
}
/**
@@ -48,5 +48,9 @@ export default {
LockStakingStatus: {
extra: {},
types: {}
},
ValidateEquivocationReport: {
extra: {},
types: {}
}
} as ExtDef;
@@ -7,6 +7,8 @@ import { Address, Balance, Call, Index } from '../../interfaces/runtime';
import { ExtrinsicPayloadValue, IExtrinsicSignature, IKeyringPair, Registry, SignatureOptions } from '../../types';
import { ExtrinsicSignatureOptions } from '../types';
import { blake2AsU8a } from '@polkadot/util-crypto';
import Compact from '../../codec/Compact';
import Struct from '../../codec/Struct';
import { EMPTY_U8A, IMMORTAL_ERA } from '../constants';
@@ -138,7 +140,10 @@ export default class ExtrinsicSignatureV1 extends Struct implements IExtrinsicSi
* @description Generate a payload and applies the signature from a keypair
*/
public sign (method: Call, account: IKeyringPair, options: SignatureOptions): IExtrinsicSignature {
const signer = this.registry.createType('Address', account.publicKey);
const address = account.publicKey.length > 32
? blake2AsU8a(account.publicKey, 256)
: account.publicKey;
const signer = this.registry.createType('Address', address);
const payload = this.createPayload(method, options);
const signature = this.registry.createType('Signature', payload.sign(account));
@@ -7,6 +7,8 @@ import { Address, Balance, Call, Index } from '../../interfaces/runtime';
import { ExtrinsicPayloadValue, IExtrinsicSignature, IKeyringPair, Registry, SignatureOptions } from '../../types';
import { ExtrinsicSignatureOptions } from '../types';
import { blake2AsU8a } from '@polkadot/util-crypto';
import Compact from '../../codec/Compact';
import Struct from '../../codec/Struct';
import { EMPTY_U8A, IMMORTAL_ERA } from '../constants';
@@ -134,7 +136,10 @@ export default class ExtrinsicSignatureV2 extends Struct implements IExtrinsicSi
* @description Generate a payload and applies the signature from a keypair
*/
public sign (method: Call, account: IKeyringPair, options: SignatureOptions): IExtrinsicSignature {
const signer = this.registry.createType('Address', account.publicKey);
const address = account.publicKey.length > 32
? blake2AsU8a(account.publicKey, 256)
: account.publicKey;
const signer = this.registry.createType('Address', address);
const payload = this.createPayload(method, options);
const signature = this.registry.createType('Signature', payload.sign(account));
@@ -5,6 +5,8 @@
import { Address, Call } from '../../interfaces/runtime';
import { ExtrinsicPayloadValue, IExtrinsicSignature, IKeyringPair, SignatureOptions } from '../../types';
import { blake2AsU8a } from '@polkadot/util-crypto';
import { IMMORTAL_ERA } from '../constants';
import ExtrinsicSignatureV2 from '../v2/ExtrinsicSignature';
import ExtrinsicPayloadV3 from './ExtrinsicPayload';
@@ -45,7 +47,10 @@ export default class ExtrinsicSignatureV3 extends ExtrinsicSignatureV2 {
* @description Generate a payload and applies the signature from a keypair
*/
public sign (method: Call, account: IKeyringPair, options: SignatureOptions): IExtrinsicSignature {
const signer = this.registry.createType('Address', account.publicKey);
const address = account.publicKey.length > 32
? blake2AsU8a(account.publicKey, 256)
: account.publicKey;
const signer = this.registry.createType('Address', address);
const payload = this.createPayload(method, options);
const signature = this.registry.createType('Signature', payload.sign(account));
@@ -8,6 +8,7 @@ import { ExtrinsicPayloadValue, IExtrinsicSignature, IKeyringPair, Registry, Sig
import { ExtrinsicSignatureOptions } from '../types';
import { u8aConcat } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
import Compact from '../../codec/Compact';
import Struct from '../../codec/Struct';
@@ -140,7 +141,10 @@ export default class ExtrinsicSignatureV4 extends Struct implements IExtrinsicSi
* @description Generate a payload and applies the signature from a keypair
*/
public sign (method: Call, account: IKeyringPair, options: SignatureOptions): IExtrinsicSignature {
const signer = this.registry.createType('Address', account.publicKey);
const address = account.publicKey.length > 32
? blake2AsU8a(account.publicKey, 256)
: account.publicKey;
const signer = this.registry.createType('Address', address);
const payload = this.createPayload(method, options);
const signature = this.registry.createType('MultiSignature', payload.sign(account));
@@ -18,6 +18,7 @@ export default {
types: {
BabeAuthorityWeight: 'u64',
BabeBlockWeight: 'u32',
MaybeRandomness: 'Option<Randomness>',
MaybeVrf: 'Option<VrfData>',
// TODO Remove as soon as merged and metadata static updated
BabeWeight: 'u64',
@@ -20,6 +20,9 @@ export interface EpochAuthorship extends Struct {
readonly secondary: Vec<u64>;
}
/** @name MaybeRandomness */
export interface MaybeRandomness extends Option<Randomness> {}
/** @name MaybeVrf */
export interface MaybeVrf extends Option<VrfData> {}
@@ -8,11 +8,38 @@
import { Definitions } from '../../types';
export default {
rpc: {},
rpc: {
roundState: {
description: 'Returns the state of the current best round state as well as the ongoing background rounds',
params: [],
type: 'ReportedRoundStates'
}
},
types: {
AuthorityIndex: 'u64',
AuthorityList: 'Vec<NextAuthority>',
AuthorityWeight: 'u64',
Equivocation: {
_enum: {
Prevote: 'GrandpaEquivocation',
Precommit: 'GrandpaEquivocation'
}
},
EquivocationProof: {
setId: 'SetId',
equivocation: 'Equivocation'
},
GrandpaEquivocation: {
roundNumber: 'u64',
identity: 'AuthorityId',
first: '(GrandpaPrevote, AuthoritySignature)',
second: '(GrandpaPrevote, AuthoritySignature)'
},
GrandpaPrevote: {
targetHash: 'Hash',
targetNumber: 'BlockNumber'
},
KeyOwnerProof: 'MembershipProof',
NextAuthority: '(AuthorityId, AuthorityWeight)',
PendingPause: {
/// Block at which the intention to pause was scheduled.
@@ -26,6 +53,26 @@ export default {
/// Number of blocks after which the change will be enacted.
delay: 'BlockNumber'
},
Precommits: {
currentWeight: 'u32',
missing: 'BTreeSet<AuthorityId>'
},
Prevotes: {
currentWeight: 'u32',
missing: 'BTreeSet<AuthorityId>'
},
ReportedRoundStates: {
setId: 'u32',
best: 'RoundState',
background: 'Vec<RoundState>'
},
RoundState: {
round: 'u32',
totalWeight: 'u32',
thresholdWeight: 'u32',
prevotes: 'Prevotes',
precommits: 'Precommits'
},
SetId: 'u64',
StoredPendingChange: {
scheduledAt: 'BlockNumber',
+64 -3
View File
@@ -2,10 +2,12 @@
/* eslint-disable */
import { ITuple } from '@polkadot/types/types';
import { Enum, Struct, Vec } from '@polkadot/types/codec';
import { u64 } from '@polkadot/types/primitive';
import { BTreeSet, Enum, Struct, Vec } from '@polkadot/types/codec';
import { u32, u64 } from '@polkadot/types/primitive';
import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { BlockNumber } from '@polkadot/types/interfaces/runtime';
import { AuthoritySignature } from '@polkadot/types/interfaces/imOnline';
import { BlockNumber, Hash } from '@polkadot/types/interfaces/runtime';
import { MembershipProof } from '@polkadot/types/interfaces/session';
/** @name AuthorityIndex */
export interface AuthorityIndex extends u64 {}
@@ -16,6 +18,37 @@ export interface AuthorityList extends Vec<NextAuthority> {}
/** @name AuthorityWeight */
export interface AuthorityWeight extends u64 {}
/** @name Equivocation */
export interface Equivocation extends Enum {
readonly isPrevote: boolean;
readonly asPrevote: GrandpaEquivocation;
readonly isPrecommit: boolean;
readonly asPrecommit: GrandpaEquivocation;
}
/** @name EquivocationProof */
export interface EquivocationProof extends Struct {
readonly setId: SetId;
readonly equivocation: Equivocation;
}
/** @name GrandpaEquivocation */
export interface GrandpaEquivocation extends Struct {
readonly roundNumber: u64;
readonly identity: AuthorityId;
readonly first: ITuple<[GrandpaPrevote, AuthoritySignature]>;
readonly second: ITuple<[GrandpaPrevote, AuthoritySignature]>;
}
/** @name GrandpaPrevote */
export interface GrandpaPrevote extends Struct {
readonly targetHash: Hash;
readonly targetNumber: BlockNumber;
}
/** @name KeyOwnerProof */
export interface KeyOwnerProof extends MembershipProof {}
/** @name NextAuthority */
export interface NextAuthority extends ITuple<[AuthorityId, AuthorityWeight]> {}
@@ -31,6 +64,34 @@ export interface PendingResume extends Struct {
readonly delay: BlockNumber;
}
/** @name Precommits */
export interface Precommits extends Struct {
readonly currentWeight: u32;
readonly missing: BTreeSet<AuthorityId>;
}
/** @name Prevotes */
export interface Prevotes extends Struct {
readonly currentWeight: u32;
readonly missing: BTreeSet<AuthorityId>;
}
/** @name ReportedRoundStates */
export interface ReportedRoundStates extends Struct {
readonly setId: u32;
readonly best: RoundState;
readonly background: Vec<RoundState>;
}
/** @name RoundState */
export interface RoundState extends Struct {
readonly round: u32;
readonly totalWeight: u32;
readonly thresholdWeight: u32;
readonly prevotes: Prevotes;
readonly precommits: Precommits;
}
/** @name SetId */
export interface SetId extends u64 {}
@@ -34,6 +34,12 @@ export default {
...keyTypes,
FullIdentification: 'Exposure',
IdentificationTuple: '(ValidatorId, FullIdentification)',
SessionIndex: 'u32'
MembershipProof: {
session: 'SessionIndex',
trieNodes: 'Vec<Vec<u8>>',
validatorCount: 'ValidatorCount'
},
SessionIndex: 'u32',
ValidatorCount: 'u32'
}
} as Definitions;
+12 -1
View File
@@ -2,7 +2,8 @@
/* eslint-disable */
import { ITuple } from '@polkadot/types/types';
import { u32 } from '@polkadot/types/primitive';
import { Struct, Vec } from '@polkadot/types/codec';
import { Bytes, u32 } from '@polkadot/types/primitive';
import { AccountId, ValidatorId } from '@polkadot/types/interfaces/runtime';
import { Exposure } from '@polkadot/types/interfaces/staking';
@@ -15,6 +16,13 @@ export interface IdentificationTuple extends ITuple<[ValidatorId, FullIdentifica
/** @name Keys */
export interface Keys extends SessionKeys4 {}
/** @name MembershipProof */
export interface MembershipProof extends Struct {
readonly session: SessionIndex;
readonly trieNodes: Vec<Bytes>;
readonly validatorCount: ValidatorCount;
}
/** @name SessionIndex */
export interface SessionIndex extends u32 {}
@@ -36,4 +44,7 @@ export interface SessionKeys5 extends ITuple<[AccountId, AccountId, AccountId, A
/** @name SessionKeys6 */
export interface SessionKeys6 extends ITuple<[AccountId, AccountId, AccountId, AccountId, AccountId, AccountId]> {}
/** @name ValidatorCount */
export interface ValidatorCount extends u32 {}
export type PHANTOM_SESSION = 'session';
File diff suppressed because one or more lines are too long
@@ -24,24 +24,24 @@ export default {
start: 'Option<Moment>'
},
CompactAssignments: {
votes1: 'Vec<(ValidatorIndex, [CompactScore; 0], NominatorIndex)>',
votes2: 'Vec<(ValidatorIndex, [CompactScore; 1], NominatorIndex)>',
votes3: 'Vec<(ValidatorIndex, [CompactScore; 2], NominatorIndex)>',
votes4: 'Vec<(ValidatorIndex, [CompactScore; 3], NominatorIndex)>',
votes5: 'Vec<(ValidatorIndex, [CompactScore; 4], NominatorIndex)>',
votes6: 'Vec<(ValidatorIndex, [CompactScore; 5], NominatorIndex)>',
votes7: 'Vec<(ValidatorIndex, [CompactScore; 6], NominatorIndex)>',
votes8: 'Vec<(ValidatorIndex, [CompactScore; 7], NominatorIndex)>',
votes9: 'Vec<(ValidatorIndex, [CompactScore; 8], NominatorIndex)>',
votes10: 'Vec<(ValidatorIndex, [CompactScore; 9], NominatorIndex)>',
votes11: 'Vec<(ValidatorIndex, [CompactScore; 10], NominatorIndex)>',
votes12: 'Vec<(ValidatorIndex, [CompactScore; 11], NominatorIndex)>',
votes13: 'Vec<(ValidatorIndex, [CompactScore; 12], NominatorIndex)>',
votes14: 'Vec<(ValidatorIndex, [CompactScore; 13], NominatorIndex)>',
votes15: 'Vec<(ValidatorIndex, [CompactScore; 14], NominatorIndex)>',
votes16: 'Vec<(ValidatorIndex, [CompactScore; 15], NominatorIndex)>'
votes1: 'Vec<(NominatorIndex, [CompactScore; 0], ValidatorIndex)>',
votes2: 'Vec<(NominatorIndex, [CompactScore; 1], ValidatorIndex)>',
votes3: 'Vec<(NominatorIndex, [CompactScore; 2], ValidatorIndex)>',
votes4: 'Vec<(NominatorIndex, [CompactScore; 3], ValidatorIndex)>',
votes5: 'Vec<(NominatorIndex, [CompactScore; 4], ValidatorIndex)>',
votes6: 'Vec<(NominatorIndex, [CompactScore; 5], ValidatorIndex)>',
votes7: 'Vec<(NominatorIndex, [CompactScore; 6], ValidatorIndex)>',
votes8: 'Vec<(NominatorIndex, [CompactScore; 7], ValidatorIndex)>',
votes9: 'Vec<(NominatorIndex, [CompactScore; 8], ValidatorIndex)>',
votes10: 'Vec<(NominatorIndex, [CompactScore; 9], ValidatorIndex)>',
votes11: 'Vec<(NominatorIndex, [CompactScore; 10], ValidatorIndex)>',
votes12: 'Vec<(NominatorIndex, [CompactScore; 11], ValidatorIndex)>',
votes13: 'Vec<(NominatorIndex, [CompactScore; 12], ValidatorIndex)>',
votes14: 'Vec<(NominatorIndex, [CompactScore; 13], ValidatorIndex)>',
votes15: 'Vec<(NominatorIndex, [CompactScore; 14], ValidatorIndex)>',
votes16: 'Vec<(NominatorIndex, [CompactScore; 15], ValidatorIndex)>'
},
CompactScore: '(u16, OffchainAccuracy)',
CompactScore: '(ValidatorIndex, OffchainAccuracy)',
ElectionCompute: {
_enum: ['OnChain', 'Signed', 'Authority']
},
+17 -17
View File
@@ -14,26 +14,26 @@ export interface ActiveEraInfo extends Struct {
/** @name CompactAssignments */
export interface CompactAssignments extends Struct {
readonly votes1: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes2: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes3: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes4: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes5: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes6: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes7: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes8: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes9: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes10: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes11: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes12: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes13: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes14: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes15: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes16: Vec<ITuple<[ValidatorIndex, Vec<CompactScore>, NominatorIndex]>>;
readonly votes1: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes2: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes3: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes4: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes5: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes6: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes7: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes8: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes9: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes10: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes11: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes12: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes13: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes14: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes15: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
readonly votes16: Vec<ITuple<[NominatorIndex, Vec<CompactScore>, ValidatorIndex]>>;
}
/** @name CompactScore */
export interface CompactScore extends ITuple<[u16, OffchainAccuracy]> {}
export interface CompactScore extends ITuple<[ValidatorIndex, OffchainAccuracy]> {}
/** @name ElectionCompute */
export interface ElectionCompute extends Enum {
+906 -863
View File
File diff suppressed because it is too large Load Diff