Compare commits

...
67 Commits
Author SHA1 Message Date
Github Actions b51988193a [CI Skip] release/stable 5.3.2
skip-checks: true
2021-08-03 08:36:43 +00:00
Jaco fd31e5a6e5 5.3.2 (#3837) 2021-08-03 10:26:46 +02:00
Github Actions 074663cdb7 [CI Skip] release/beta 5.3.2-1
skip-checks: true
2021-08-03 08:07:30 +00:00
Jaco 5f5be13c08 Add missing bridges ChainId (#3836)
* Add missing bridges ChainId

* CHANGELOG
2021-08-03 09:56:35 +02:00
Jaco d60b1818d0 Update bridges types (#3835)
* Update bridges types

* BitVec

* BitVec
2021-08-03 09:39:32 +02:00
Github Actions 9c611e9414 [CI Skip] release/beta 5.3.2-0
skip-checks: true
2021-08-03 05:44:26 +00:00
Jaco da14679b65 v14 metadata bump (#3834) 2021-08-03 07:32:47 +02:00
Github Actions c88bb99b19 [CI Skip] release/stable 5.3.1
skip-checks: true
2021-08-02 09:11:40 +00:00
Jaco fc174738ec 5.3.1 (#3831) 2021-08-02 10:59:03 +02:00
Github Actions b43f1a747d [CI Skip] release/beta 5.2.2-12
skip-checks: true
2021-08-01 07:46:30 +00:00
Jaco 555b2fb5fe Flatten metadata tests & imports (#3830) 2021-08-01 09:35:01 +02:00
Github Actions 1e1ee6eb49 [CI Skip] release/beta 5.2.2-11
skip-checks: true
2021-07-30 14:58:58 +00:00
Jaco 7c4c346389 Hex/JSON metadata split (#3829)
* Hex/JSON metadata split

* revert import change

* Adjust imports

* Update tests
2021-07-30 16:45:57 +02:00
Github Actions beff353b4e [CI Skip] release/beta 5.2.2-10
skip-checks: true
2021-07-30 12:09:20 +00:00
Jaco 3172cb55f8 Add Polkadot static metadata (#3827)
* Add Polkadot static metadata

* v13 static polkadot

* v14 static polkadot

* CHANGELOG
2021-07-30 13:56:39 +02:00
Github Actions ba74ad0be9 [CI Skip] release/beta 5.2.2-9
skip-checks: true
2021-07-30 08:44:08 +00:00
Jaco 6ec7687f33 Bump static metadata (#3826) 2021-07-30 10:34:15 +02:00
Github Actions bd70b1e6ce [CI Skip] release/beta 5.2.2-8
skip-checks: true
2021-07-30 07:06:25 +00:00
Jaco 8744b95c83 Adjust PortableRegistry name matches (#3825)
* Adjust PortableRegistry name matches

* Update packages/types/src/generic/PortableRegistry.ts

* Update packages/types/src/generic/PortableRegistry.ts

* Opt

* Adjust set matching

* Extra includes check
2021-07-30 08:57:13 +02:00
Github Actions 94e6d8455d [CI Skip] release/beta 5.2.2-7
skip-checks: true
2021-07-30 06:26:56 +00:00
Jaco 70d19fcebb Kusama 9080 upgrade block (#3821) 2021-07-30 08:17:22 +02:00
Github Actions 174ba867d7 [CI Skip] release/beta 5.2.2-6
skip-checks: true
2021-07-29 11:10:28 +00:00
Jaco 36b217463a (some) Bridges types (#3823) 2021-07-29 13:00:05 +02:00
Github Actions 412c7525c0 [CI Skip] release/beta 5.2.2-5
skip-checks: true
2021-07-29 09:26:01 +00:00
Jaco 172c6f655f Update v14 metadata & PortableRegistry (#3822)
* Alin PortableRegistry with latest v14 changes

* Bump latest v14
2021-07-29 11:16:16 +02:00
Github Actions 1e3240c669 [CI Skip] release/beta 5.2.2-4
skip-checks: true
2021-07-28 10:54:16 +00:00
Jaco 43e1bf2d4a Check and match both specName/specVersion for registries (#3820) 2021-07-28 12:43:18 +02:00
Github Actions 839b2bc342 [CI Skip] release/beta 5.2.2-3
skip-checks: true
2021-07-28 05:50:31 +00:00
Jaco a281e0dc2d Adjust sorting (#3819)
* Adjust sorting

* typo
2021-07-28 07:40:46 +02:00
Github Actions 9a4893130d [CI Skip] release/beta 5.2.2-2
skip-checks: true
2021-07-28 05:34:40 +00:00
Jaco 77c45cf4c0 Fix sorting circular dependencies (#3818) 2021-07-28 07:22:42 +02:00
Github Actions ca0969b1eb [CI Skip] release/beta 5.2.2-1
skip-checks: true
2021-07-27 13:18:35 +00:00
Jaco 1df8cf9857 Bump v14 static (#3816) 2021-07-27 15:05:43 +02:00
Github Actions b7f095bcbd [CI Skip] release/beta 5.2.2-0
skip-checks: true
2021-07-27 10:34:47 +00:00
Jaco 6cc7242bdf Fix at(...) decoration (#3815)
* Fix at(...) decoration

* Add decoratedMeta/decoratedApi

* Remove intermediate
2021-07-27 12:24:49 +02:00
Jaco 48f91ae0da Adjust PortableRegistry (#3811)
* Adjust PortableRegistry

* Adjust formatting

* Additional formatting picks

* Readability

* Replacement comment
2021-07-26 09:33:15 +02:00
Github Actions 4a63026b14 [CI Skip] release/stable 5.2.1
skip-checks: true
2021-07-26 06:19:38 +00:00
Jaco a40ce72298 5.2.1 (#3810) 2021-07-26 08:07:12 +02:00
Github Actions f302d8de69 [CI Skip] release/beta 5.1.2-13
skip-checks: true
2021-07-26 05:51:34 +00:00
Lezek123 fcaebbdbb2 BTreeSet and BTreeMap - encoding and serialization fixes (#3789)
* BTreeSet and BTreeMap - encoding and serialization fixes

* Fix linter issues

* BTreeSet/BTreeMap: Support for Struct and Enum sorting

* Cleanup sorting function
2021-07-26 07:41:25 +02:00
Github Actions 9e7037af04 [CI Skip] release/beta 5.1.2-12
skip-checks: true
2021-07-25 05:41:15 +00:00
Jaco 68efac60df Allow struct alias on PortableRegistry (#3808)
* Allow struct aliasses on PortableRegistry

* Add resrved alias

* Naing adjustment

* No name for flattenned Tuple

* Add docs
2021-07-25 07:30:57 +02:00
Github Actions d763f49e8b [CI Skip] release/beta 5.1.2-11
skip-checks: true
2021-07-24 13:59:55 +00:00
Jaco 77ffd7c153 Metadata v13 to v14 conversion (#3807) 2021-07-24 15:50:06 +02:00
Jaco d1506154bd PortableRegistry support for BTreeMap (#3806)
* PortableRegistry support for BTreeMap

* Update packages/types/src/generic/PortableRegistry.ts
2021-07-24 15:49:39 +02:00
Github Actions b1254685da [CI Skip] release/beta 5.1.2-10
skip-checks: true
2021-07-24 06:43:27 +00:00
Jaco 81a2a2c688 Adjust type encoding (#3805)
* Adjust type encoding

* Adjust

* displayName adjustments
2021-07-24 08:32:36 +02:00
Github Actions 1fed997080 [CI Skip] release/beta 5.1.2-9
skip-checks: true
2021-07-23 16:13:24 +00:00
Jaco 6e620e3bb3 Short-circuit full type (with lookupIndex) (#3804)
* Short-circuit full type (with lookupIndex)

* Defaults for type expansion

* Tuple with extra spaces removed

* Fill in generated types

* Adjust generation

* Adjust tests

* Adjust
2021-07-23 18:04:14 +02:00
Github Actions 6e4c62ea99 [CI Skip] release/beta 5.1.2-8
skip-checks: true
2021-07-23 10:02:58 +00:00
Jaco 8972d2ffe9 Add type string generation to PortableRegistry (#3802)
* Add type string generation to PortableRegistry

* createClass updates

* Add missing field
2021-07-23 11:51:40 +02:00
Github Actions 091d2d30e0 [CI Skip] release/beta 5.1.2-7
skip-checks: true
2021-07-22 18:26:01 +00:00
Jaco ae7ded1767 Extensive formatting for TypeDef -> string (#3800)
* Extensive formatting for TypeDef -> string

* Remove helpers
2021-07-22 20:15:44 +02:00
Github Actions 8aa3550354 [CI Skip] release/beta 5.1.2-6
skip-checks: true
2021-07-22 17:48:31 +00:00
Jaco 196d3c5995 Pass registry to formatters (#3799) 2021-07-22 19:39:40 +02:00
Github Actions 592407d691 [CI Skip] release/beta 5.1.2-5
skip-checks: true
2021-07-22 11:28:43 +00:00
Jaco 1e3a1bb51c Allow for type overrides via path (#3797) 2021-07-22 13:18:31 +02:00
Github Actions 2ca23a85d0 [CI Skip] release/beta 5.1.2-4
skip-checks: true
2021-07-22 09:52:22 +00:00
Jaco 1a04b4a72e Fix lookup type expansion (#3796) 2021-07-22 11:43:08 +02:00
Github Actions 6dfe7c4f56 [CI Skip] release/beta 5.1.2-3
skip-checks: true
2021-07-22 09:01:44 +00:00
Jaco 3f9f7bd649 Flatten PortableRegistry type creation (#3795) 2021-07-22 10:51:56 +02:00
Github Actions e02e1302b2 [CI Skip] release/beta 5.1.2-2
skip-checks: true
2021-07-21 12:33:19 +00:00
Jaco a64dec3487 v14 static bump (w/ call param names) (#3788) 2021-07-21 14:22:16 +02:00
Github Actions 3415fbd121 [CI Skip] release/beta 5.1.2-1
skip-checks: true
2021-07-21 09:47:32 +00:00
Jaco 0be1d46be9 RPC-core createType swap (#3786)
* RPC-core createType swap

* CHANGELOG

* createType complexity
2021-07-21 11:36:10 +02:00
Github Actions 9309e9f3a1 [CI Skip] release/beta 5.1.2-0
skip-checks: true
2021-07-20 12:27:49 +00:00
Jaco 6dd019343d Adjust generation sorting (#3785) 2021-07-20 14:14:14 +02:00
136 changed files with 51446 additions and 6919 deletions
+2
View File
@@ -24,3 +24,5 @@
4.9.2
4.11.2
4.16.2
5.3.2
+46
View File
@@ -1,7 +1,53 @@
# CHANGELOG
## 5.3.2 Aug 3, 2021
Upgrade priority: Low. Recommended for users of bridges.
Contributed:
- Add missing bridges types (Thanks to https://github.com/tomusdrw)
Changes:
- Align static metadata with latest Substrate
## 5.3.1 Aug 2, 2021
Upgrade priority: Low. Recommended for users of `api.at(...)` interfaces
Changes:
- Check specName & specVersion for historic registries (caters for runtime renames)
- Fix circular dependencies in codec utils
- Fix `api.at(<blockHash>)` to decorate with the correct storage hash
- Adjustments for upcoming metadata v14 in type creation & `PortableRegistry`
- Add Kusama 9080 upgrade block
- Add v13/v14 static metadata for Polkadot
- Align static metadata with latest Substrate
## 5.2.1 Jul 26, 2021
Upgrade priority: Low. Recommended for users of `BTreeMap` and `BTreeSet`
Contributed:
- Perform sorting on `BTree{Map, Set}`, aligning with Substrate (Thanks to https://github.com/Lezek123)
Changes:
- Adjust RPC to use `registry.createType` with optionality (required for metadata v14)
- Adjust alphabetical sorting for TS type generation
- Adjustments for upcoming metadata v14 in type creation & `PortableRegistry`
- Provide the capability to convert v13 Metadata to upcoming v14
## 5.1.1 Jul 19, 2021
Upgrade priority: Low. Recommended for users of XCM with type fixes.
- **Breaking changes** With the support for v14 metadata parsing, the `documentation` fields on metadata was renamed to `docs` for consistency, aligning with the SCALE type generators.
Contributed:
+4 -4
View File
@@ -26,14 +26,14 @@
"test:watch": "polkadot-dev-run-test --watch"
},
"devDependencies": {
"@babel/core": "^7.14.6",
"@babel/core": "^7.14.8",
"@babel/register": "^7.14.5",
"@babel/runtime": "^7.14.6",
"@babel/runtime": "^7.14.8",
"@polkadot/dev": "^0.62.57",
"@polkadot/ts": "^0.4.4",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^26.0.23",
"@types/jest": "^26.0.24",
"copyfiles": "^2.4.1"
},
"version": "5.1.1"
"version": "5.3.2"
}
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-contract",
"version": "5.1.1",
"version": "5.3.2",
"type": "module",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
@@ -19,10 +19,10 @@
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/api": "5.1.1",
"@polkadot/types": "5.1.1",
"@polkadot/util": "^7.0.2",
"@babel/runtime": "^7.14.8",
"@polkadot/api": "5.3.2",
"@polkadot/types": "5.3.2",
"@polkadot/util": "^7.1.1",
"rxjs": "^7.2.0"
}
}
+3 -2
View File
@@ -24,6 +24,7 @@ const PRIMITIVE_ALIAS: Record<string, keyof InterfaceTypes> = {
const PRIMITIVE_ALWAYS = ['AccountId', 'AccountIndex', 'Address', 'Balance'];
// TODO Replace usages with PortableRegistry
export class MetaRegistry extends TypeRegistry {
public readonly metaTypeDefs: TypeDef[] = [];
@@ -119,7 +120,7 @@ export class MetaRegistry extends TypeRegistry {
const displayName = path.pop()?.toString();
return withTypeString({
return withTypeString(this, {
...(displayName
? { displayName }
: {}
@@ -243,7 +244,7 @@ export class MetaRegistry extends TypeRegistry {
name: name.toString(),
type: 'Null'
}))
: variants.map(({ fields, name }) => withTypeString({
: variants.map(({ fields, name }) => withTypeString(this, {
...this.#extractFields(fields),
name: name.toString()
}));
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-contract', version: '5.1.1' };
export const packageInfo = { name: '@polkadot/api-contract', version: '5.3.2' };
@@ -158,12 +158,12 @@
"type": "AccountId"
}
],
"type": "(AccountId, AccountId)",
"type": "(AccountId,AccountId)",
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(AccountId, AccountId)\"}}"
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(AccountId,AccountId)\"}}"
},
{
"info": 10,
@@ -181,7 +181,7 @@
"type": "AccountId"
}
],
"type": "(AccountId, AccountId)"
"type": "(AccountId,AccountId)"
},
{
"info": 6,
@@ -198,4 +198,4 @@
"info": 5,
"type": "Option<AccountId>"
}
]
]
@@ -206,12 +206,12 @@
"type": "AccountId"
}
],
"type": "(AccountId, AccountId)",
"type": "(AccountId,AccountId)",
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(AccountId, AccountId)\"}}"
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(AccountId,AccountId)\"}}"
},
{
"info": 10,
@@ -229,7 +229,7 @@
"type": "AccountId"
}
],
"type": "(AccountId, AccountId)"
"type": "(AccountId,AccountId)"
},
{
"displayName": "ValueEntry",
@@ -427,4 +427,4 @@
],
"type": "{\"_enum\":[\"NotOwner\",\"NotApproved\",\"TokenExists\",\"TokenNotFound\",\"CannotInsert\",\"CannotRemove\",\"CannotFetchValue\",\"NotAllowed\"]}"
}
]
]
@@ -63,12 +63,12 @@
"type": "AccountId"
}
],
"type": "(u32, AccountId)",
"type": "(u32,AccountId)",
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(u32, AccountId)\"}}"
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(u32,AccountId)\"}}"
},
{
"info": 10,
@@ -84,7 +84,7 @@
"type": "AccountId"
}
],
"type": "(u32, AccountId)"
"type": "(u32,AccountId)"
},
{
"displayName": "AccountId",
@@ -409,7 +409,7 @@
"type": "{\"_enum\":{\"Confirmed\":\"()\",\"ConfirmationsNeeded\":\"u32\"}}"
}
],
"type": "(u32, ConfirmationStatus)"
"type": "(u32,ConfirmationStatus)"
},
{
"displayName": "ConfirmationStatus",
@@ -511,4 +511,4 @@
"info": 5,
"type": "Option<Vec<u8>>"
}
]
]
@@ -158,12 +158,12 @@
"type": "AccountId"
}
],
"type": "(AccountId, AccountId)",
"type": "(AccountId,AccountId)",
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(AccountId, AccountId)\"}}"
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(AccountId,AccountId)\"}}"
},
{
"info": 10,
@@ -181,7 +181,7 @@
"type": "AccountId"
}
],
"type": "(AccountId, AccountId)"
"type": "(AccountId,AccountId)"
},
{
"info": 6,
@@ -202,4 +202,4 @@
"info": 5,
"type": "Option<AccountId>"
}
]
]
+9 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "5.1.1",
"version": "5.3.2",
"type": "module",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
@@ -19,16 +19,16 @@
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/api": "5.1.1",
"@polkadot/rpc-core": "5.1.1",
"@polkadot/types": "5.1.1",
"@polkadot/util": "^7.0.2",
"@polkadot/util-crypto": "^7.0.2",
"@babel/runtime": "^7.14.8",
"@polkadot/api": "5.3.2",
"@polkadot/rpc-core": "5.3.2",
"@polkadot/types": "5.3.2",
"@polkadot/util": "^7.1.1",
"@polkadot/util-crypto": "^7.1.1",
"rxjs": "^7.2.0"
},
"devDependencies": {
"@polkadot/keyring": "^7.0.2",
"@polkadot/rpc-provider": "5.1.1"
"@polkadot/keyring": "^7.1.1",
"@polkadot/rpc-provider": "5.3.2"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-derive', version: '5.1.1' };
export const packageInfo = { name: '@polkadot/api-derive', version: '5.3.2' };
+1 -1
View File
@@ -3,7 +3,7 @@
import { ApiPromise, WsProvider } from '@polkadot/api';
import { Metadata, TypeRegistry } from '@polkadot/types';
import metaStatic from '@polkadot/types/metadata/static';
import metaStatic from '@polkadot/types/metadata/static-substrate';
export function createApiWithAugmentations (): ApiPromise {
const registry = new TypeRegistry();
+10 -10
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api",
"version": "5.1.1",
"version": "5.3.2",
"type": "module",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
@@ -19,15 +19,15 @@
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/api-derive": "5.1.1",
"@polkadot/keyring": "^7.0.2",
"@polkadot/rpc-core": "5.1.1",
"@polkadot/rpc-provider": "5.1.1",
"@polkadot/types": "5.1.1",
"@polkadot/types-known": "5.1.1",
"@polkadot/util": "^7.0.2",
"@polkadot/util-crypto": "^7.0.2",
"@babel/runtime": "^7.14.8",
"@polkadot/api-derive": "5.3.2",
"@polkadot/keyring": "^7.1.1",
"@polkadot/rpc-core": "5.3.2",
"@polkadot/rpc-provider": "5.3.2",
"@polkadot/types": "5.3.2",
"@polkadot/types-known": "5.3.2",
"@polkadot/util": "^7.1.1",
"@polkadot/util-crypto": "^7.1.1",
"eventemitter3": "^4.0.7",
"rxjs": "^7.2.0"
}
+168 -3
View File
@@ -1,19 +1,59 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { Vec, u16, u32, u64 } from '@polkadot/types';
import type { Vec, bool, u16, u32, u64 } from '@polkadot/types';
import type { Codec } from '@polkadot/types/types';
import type { Schedule } from '@polkadot/types/interfaces/contracts';
import type { Balance, BalanceOf, BlockNumber, LockIdentifier, Moment, PalletId, Perbill, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
import type { Balance, BalanceOf, BlockNumber, LockIdentifier, Moment, PalletId, Perbill, Percent, Permill, RuntimeDbWeight, TransactionPriority, Weight } from '@polkadot/types/interfaces/runtime';
import type { SessionIndex } from '@polkadot/types/interfaces/session';
import type { EraIndex } from '@polkadot/types/interfaces/staking';
import type { RuntimeVersion } from '@polkadot/types/interfaces/state';
import type { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
import type { BlockLength, BlockWeights } from '@polkadot/types/interfaces/system';
import type { DepositBalanceOf } from '@polkadot/types/interfaces/uniques';
import type { ApiTypes } from '@polkadot/api/types';
declare module '@polkadot/api/types/consts' {
export interface AugmentedConsts<ApiType> {
assets: {
/**
* The amount of funds that must be reserved when creating a new approval.
**/
approvalDeposit: DepositBalanceOf & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved for an asset.
**/
assetDeposit: DepositBalanceOf & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved when adding metadata to your asset.
**/
metadataDepositBase: DepositBalanceOf & AugmentedConst<ApiType>;
/**
* The additional funds that must be reserved for the number of bytes you store in your
* metadata.
**/
metadataDepositPerByte: DepositBalanceOf & AugmentedConst<ApiType>;
/**
* The maximum length of a name or symbol stored on-chain.
**/
stringLimit: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
authorship: {
/**
* The number of blocks back we should accept uncles.
* This means that we will deal with uncle-parents that are
* `UncleGenerations + 1` before `now`.
**/
uncleGenerations: BlockNumber & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
babe: {
/**
* The amount of time, in slots, that each epoch should last.
@@ -39,6 +79,15 @@ declare module '@polkadot/api/types/consts' {
* The minimum amount required to keep an account open.
**/
existentialDeposit: Balance & AugmentedConst<ApiType>;
/**
* The maximum number of locks that should exist on an account.
* Not strictly enforced, but used for weight estimation.
**/
maxLocks: u32 & AugmentedConst<ApiType>;
/**
* The maximum number of named reserves that can exist on an account.
**/
maxReserves: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
@@ -163,10 +212,20 @@ declare module '@polkadot/api/types/consts' {
* Minimum voting period allowed for a fast-track referendum.
**/
fastTrackVotingPeriod: BlockNumber & AugmentedConst<ApiType>;
/**
* Indicator for whether an emergency origin is even allowed to happen. Some chains may want
* to set this permanently to `false`, others may want to condition it on things such as
* an upgrade having happened recently.
**/
instantAllowed: bool & AugmentedConst<ApiType>;
/**
* How often (in blocks) new public referenda are launched.
**/
launchPeriod: BlockNumber & AugmentedConst<ApiType>;
/**
* The maximum number of public proposals that can exist at any time.
**/
maxProposals: u32 & AugmentedConst<ApiType>;
/**
* The maximum number of votes for an account.
*
@@ -192,6 +251,29 @@ declare module '@polkadot/api/types/consts' {
[key: string]: Codec;
};
electionProviderMultiPhase: {
/**
* Maximum number of iteration of balancing that will be executed in the embedded miner of
* the pallet.
**/
minerMaxIterations: u32 & AugmentedConst<ApiType>;
/**
* Maximum length (bytes) that the mined solution should consume.
*
* The miner will ensure that the total length of the unsigned solution will not exceed
* this value.
**/
minerMaxLength: u32 & AugmentedConst<ApiType>;
/**
* Maximum weight that the miner should consume.
*
* The miner will ensure that the total weight of the unsigned solution will not exceed
* this value, based on [`WeightInfo::submit_unsigned`].
**/
minerMaxWeight: Weight & AugmentedConst<ApiType>;
/**
* The priority of the unsigned transaction submitted in the unsigned-phase
**/
minerTxPriority: TransactionPriority & AugmentedConst<ApiType>;
/**
* The repeat threshold of the offchain worker.
*
@@ -295,6 +377,11 @@ declare module '@polkadot/api/types/consts' {
* Must be no greater than `MaxQueueLen`.
**/
fifoQueueLen: u32 & AugmentedConst<ApiType>;
/**
* The issuance to ignore. This is subtracted from the `Currency`'s `total_issuance` to get
* the issuance by which we inflate or deflate the gilt.
**/
ignoredIssuance: BalanceOf & AugmentedConst<ApiType>;
/**
* The number of blocks between consecutive attempts to issue more gilts in an effort to
* get to the target amount to be frozen.
@@ -371,6 +458,19 @@ declare module '@polkadot/api/types/consts' {
**/
[key: string]: Codec;
};
imOnline: {
/**
* A configuration for base priority of unsigned transactions.
*
* This is exposed so that it can be tuned for particular runtime, when
* multiple pallets send unsigned transactions.
**/
unsignedPriority: TransactionPriority & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
indices: {
/**
* The deposit needed for reserving an index.
@@ -386,6 +486,12 @@ declare module '@polkadot/api/types/consts' {
* The max number of calls available in a single lottery.
**/
maxCalls: u32 & AugmentedConst<ApiType>;
/**
* Number of time we should try to generate a random number that has no modulo bias.
* The larger this number, the more potential computation is used for picking the winner,
* but also the more likely that the chosen winner is done fairly.
**/
maxGenerateRandom: u32 & AugmentedConst<ApiType>;
/**
* The Lottery's pallet id
**/
@@ -495,6 +601,22 @@ declare module '@polkadot/api/types/consts' {
**/
[key: string]: Codec;
};
scheduler: {
/**
* The maximum weight that may be scheduled per block for any dispatchables of less priority
* than `schedule::HARD_DEADLINE`.
**/
maximumWeight: Weight & AugmentedConst<ApiType>;
/**
* The maximum number of scheduled calls in the queue for a single block.
* Not strictly enforced, but used for weight estimation.
**/
maxScheduledPerBlock: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
society: {
/**
* The minimum amount of a deposit required for a bid to be made.
@@ -657,7 +779,11 @@ declare module '@polkadot/api/types/consts' {
**/
burn: Permill & AugmentedConst<ApiType>;
/**
* The treasury's module id, used for deriving its sovereign account ID.
* The maximum number of approvals that can wait in the spending queue.
**/
maxApprovals: u32 & AugmentedConst<ApiType>;
/**
* The treasury's pallet id, used for deriving its sovereign account ID.
**/
palletId: PalletId & AugmentedConst<ApiType>;
/**
@@ -678,6 +804,45 @@ declare module '@polkadot/api/types/consts' {
**/
[key: string]: Codec;
};
uniques: {
/**
* The basic amount of funds that must be reserved when adding an attribute to an asset.
**/
attributeDepositBase: DepositBalanceOf & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved for an asset class.
**/
classDeposit: DepositBalanceOf & AugmentedConst<ApiType>;
/**
* The additional funds that must be reserved for the number of bytes store in metadata,
* either "normal" metadata or attribute metadata.
**/
depositPerByte: DepositBalanceOf & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved for an asset instance.
**/
instanceDeposit: DepositBalanceOf & AugmentedConst<ApiType>;
/**
* The maximum length of an attribute key.
**/
keyLimit: u32 & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved when adding metadata to your asset.
**/
metadataDepositBase: DepositBalanceOf & AugmentedConst<ApiType>;
/**
* The maximum length of data stored on-chain.
**/
stringLimit: u32 & AugmentedConst<ApiType>;
/**
* The maximum length of an attribute value.
**/
valueLimit: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
vesting: {
/**
* The minimum amount transferred to call `vested_transfer`.
+15 -7
View File
@@ -314,9 +314,9 @@ declare module '@polkadot/api/types/events' {
**/
Delegated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/**
* A proposal has been enacted. \[ref_index, is_ok\]
* A proposal has been enacted. \[ref_index, result\]
**/
Executed: AugmentedEvent<ApiType, [ReferendumIndex, bool]>;
Executed: AugmentedEvent<ApiType, [ReferendumIndex, DispatchResult]>;
/**
* An external proposal has been tabled.
**/
@@ -819,7 +819,7 @@ declare module '@polkadot/api/types/events' {
* the remainder from the maximum amount of reward.
* \[era_index, validator_payout, remainder\]
**/
EraPayout: AugmentedEvent<ApiType, [EraIndex, Balance, Balance]>;
EraPaid: AugmentedEvent<ApiType, [EraIndex, Balance, Balance]>;
/**
* A nominator has been kicked from a validator. \[nominator, stash\]
**/
@@ -830,18 +830,22 @@ declare module '@polkadot/api/types/events' {
**/
OldSlashingReportDiscarded: AugmentedEvent<ApiType, [SessionIndex]>;
/**
* The staker has been rewarded by this amount. \[stash, amount\]
* The stakers' rewards are getting paid. \[era_index, validator_stash\]
**/
Reward: AugmentedEvent<ApiType, [AccountId, Balance]>;
PayoutStarted: AugmentedEvent<ApiType, [EraIndex, AccountId]>;
/**
* The nominator has been rewarded by this amount. \[stash, amount\]
**/
Rewarded: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* One validator (and its nominators) has been slashed by the given amount.
* \[validator, amount\]
**/
Slash: AugmentedEvent<ApiType, [AccountId, Balance]>;
Slashed: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* A new set of stakers was elected.
**/
StakingElection: AugmentedEvent<ApiType, []>;
StakersElected: AugmentedEvent<ApiType, []>;
/**
* The election failed. No new era is planned.
**/
@@ -1172,6 +1176,10 @@ declare module '@polkadot/api/types/events' {
* well as the error. \[index, error\]
**/
BatchInterrupted: AugmentedEvent<ApiType, [u32, DispatchError]>;
/**
* A single item within a Batch of dispatches has completed with no error.
**/
ItemCompleted: AugmentedEvent<ApiType, []>;
/**
* Generic event
**/
+1 -1
View File
@@ -939,7 +939,7 @@ declare module '@polkadot/api/types/storage' {
/**
* The last planned session scheduled by the session pallet.
*
* This is basically in sync with the call to [`SessionManager::new_session`].
* This is basically in sync with the call to [`pallet_session::SessionManager::new_session`].
**/
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<SessionIndex>, []> & QueryableStorageEntry<ApiType, []>;
/**
+26 -26
View File
@@ -1352,8 +1352,9 @@ declare module '@polkadot/api/types/submittable' {
* origin is removed as a runner-up.
* - `origin` is a current member. In this case, the deposit is unreserved and origin is
* removed as a member, consequently not being a candidate for the next round anymore.
* Similar to [`remove_members`], if replacement runners exists, they are immediately
* used. If the prime is renouncing, then no prime will exist until the next round.
* Similar to [`remove_member`](Self::remove_member), if replacement runners exists,
* they are immediately used. If the prime is renouncing, then no prime will exist until
* the next round.
*
* The dispatch origin of this call must be signed, and have one of the above roles.
*
@@ -2556,7 +2557,7 @@ declare module '@polkadot/api/types/submittable' {
* Schedule a named task after a delay.
*
* # <weight>
* Same as [`schedule_named`].
* Same as [`schedule_named`](Self::schedule_named).
* # </weight>
**/
scheduleNamedAfter: AugmentedSubmittable<(id: Bytes | string | Uint8Array, after: BlockNumber | AnyNumber | Uint8Array, maybePeriodic: Option<Period> | null | object | string | Uint8Array, priority: Priority | AnyNumber | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes, BlockNumber, Option<Period>, Priority, Call]>;
@@ -2954,8 +2955,8 @@ declare module '@polkadot/api/types/submittable' {
* The dispatch origin for this call must be _Signed_ by the stash, not the controller.
*
* Use this if there are additional funds in your stash account that you wish to bond.
* Unlike [`bond`] or [`unbond`] this function does not impose any limitation on the amount
* that can be added.
* Unlike [`bond`](Self::bond) or [`unbond`](Self::unbond) this function does not impose any limitation
* on the amount that can be added.
*
* Emits `Bonded`.
*
@@ -3017,7 +3018,6 @@ declare module '@polkadot/api/types/submittable' {
*
* This can be helpful if bond requirements are updated, and we need to remove old users
* who do not satisfy these requirements.
*
**/
chillOther: AugmentedSubmittable<(controller: AccountId | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId]>;
/**
@@ -3093,7 +3093,7 @@ declare module '@polkadot/api/types/submittable' {
* The dispatch origin must be Root.
*
* # <weight>
* Same as [`set_validator_count`].
* Same as [`Self::set_validator_count`].
* # </weight>
**/
increaseValidatorCount: AugmentedSubmittable<(additional: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>]>;
@@ -3185,7 +3185,7 @@ declare module '@polkadot/api/types/submittable' {
* The dispatch origin must be Root.
*
* # <weight>
* Same as [`set_validator_count`].
* Same as [`Self::set_validator_count`].
* # </weight>
**/
scaleValidatorCount: AugmentedSubmittable<(factor: Percent | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Percent]>;
@@ -4413,24 +4413,6 @@ declare module '@polkadot/api/types/submittable' {
* # </weight>
**/
vest: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
/**
* Unlock any vested funds of a `target` account.
*
* The dispatch origin for this call must be _Signed_.
*
* - `target`: The account whose vested funds should be unlocked. Must have funds still
* locked under this pallet.
*
* Emits either `VestingCompleted` or `VestingUpdated`.
*
* # <weight>
* - `O(1)`.
* - DbWeight: 3 Reads, 3 Writes
* - Reads: Vesting Storage, Balances Locks, Target Account
* - Writes: Vesting Storage, Balances Locks, Target Account
* # </weight>
**/
vestOther: AugmentedSubmittable<(target: LookupSource | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [LookupSource]>;
/**
* Create a vested transfer.
*
@@ -4450,6 +4432,24 @@ declare module '@polkadot/api/types/submittable' {
* # </weight>
**/
vestedTransfer: AugmentedSubmittable<(target: LookupSource | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, schedule: VestingInfo | { locked?: any; perBlock?: any; startingBlock?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [LookupSource, VestingInfo]>;
/**
* Unlock any vested funds of a `target` account.
*
* The dispatch origin for this call must be _Signed_.
*
* - `target`: The account whose vested funds should be unlocked. Must have funds still
* locked under this pallet.
*
* Emits either `VestingCompleted` or `VestingUpdated`.
*
* # <weight>
* - `O(1)`.
* - DbWeight: 3 Reads, 3 Writes
* - Reads: Vesting Storage, Balances Locks, Target Account
* - Writes: Vesting Storage, Balances Locks, Target Account
* # </weight>
**/
vestOther: AugmentedSubmittable<(target: LookupSource | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [LookupSource]>;
/**
* Generic tx
**/
+33 -22
View File
@@ -189,12 +189,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
return this._rpcCore.provider.hasSubscriptions || !!this._rpcCore.state.queryStorageAt;
}
protected _injectDecorated (registry: VersionedRegistry<ApiType>, fromEmpty?: boolean, blockHash?: Uint8Array): FullDecoration<ApiType> {
const decoratedMeta = expandMetadata(registry.registry, registry.metadata);
// clear the decoration, we are redoing it here
if (fromEmpty || !registry.decoration) {
registry.decoration = {
protected _createDecorated (registry: VersionedRegistry<ApiType>, fromEmpty?: boolean, blockHash?: Uint8Array | null, decoratedApi?: ApiDecoration<ApiType>): FullDecoration<ApiType> {
if (!decoratedApi) {
decoratedApi = {
consts: {},
errors: {},
events: {},
@@ -202,25 +199,39 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
} as ApiDecoration<ApiType>;
}
if (!registry.decoratedMeta) {
registry.decoratedMeta = expandMetadata(registry.registry, registry.metadata);
}
// adjust the versioned registry
augmentObject('consts', decoratedMeta.consts, registry.decoration.consts, fromEmpty);
augmentObject('errors', decoratedMeta.errors, registry.decoration.errors, fromEmpty);
augmentObject('events', decoratedMeta.events, registry.decoration.events, fromEmpty);
augmentObject('consts', registry.decoratedMeta.consts, decoratedApi.consts, fromEmpty);
augmentObject('errors', registry.decoratedMeta.errors, decoratedApi.errors, fromEmpty);
augmentObject('events', registry.decoratedMeta.events, decoratedApi.events, fromEmpty);
const storage = blockHash
? this._decorateStorageAt(decoratedMeta, this._decorateMethod, blockHash)
: this._decorateStorage(decoratedMeta, this._decorateMethod);
? this._decorateStorageAt(registry.decoratedMeta, this._decorateMethod, blockHash)
: this._decorateStorage(registry.decoratedMeta, this._decorateMethod);
augmentObject('query', storage, registry.decoration.query, fromEmpty);
augmentObject('query', storage, decoratedApi.query, fromEmpty);
return {
decoratedApi: registry.decoration,
decoratedMeta
decoratedApi,
decoratedMeta: registry.decoratedMeta
};
}
protected _injectMetadata (registry: VersionedRegistry<ApiType>, fromEmpty?: boolean): void {
const { decoratedApi, decoratedMeta } = this._injectDecorated(registry, fromEmpty);
// clear the decoration, we are redoing it here
if (fromEmpty || !registry.decoratedApi) {
registry.decoratedApi = {
consts: {},
errors: {},
events: {},
query: {}
} as ApiDecoration<ApiType>;
}
const { decoratedApi, decoratedMeta } = this._createDecorated(registry, fromEmpty, null, registry.decoratedApi);
this._consts = decoratedApi.consts;
this._errors = decoratedApi.errors;
@@ -245,7 +256,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
* backwards compatible endpoint for metadata injection, may be removed in the future (However, it is still useful for testing injection)
*/
public injectMetadata (metadata: Metadata, fromEmpty?: boolean, registry?: Registry): void {
this._injectMetadata({ metadata, registry: registry || this.#registry, specVersion: BN_ZERO }, fromEmpty);
this._injectMetadata({ metadata, registry: registry || this.#registry, specName: this.#registry.createType('Text'), specVersion: BN_ZERO }, fromEmpty);
}
private _decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
@@ -405,7 +416,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
private _decorateStorageEntry<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): QueryableStorageEntry<ApiType> {
// get the storage arguments, with DoubleMap as an array entry, otherwise spread
const getArgs = (args: unknown[]): unknown[] => extractStorageArgs(creator, args);
const getArgs = (args: unknown[]): unknown[] => extractStorageArgs(this.#registry, creator, args);
// Disable this where it occurs for each field we are decorating
/* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
@@ -488,7 +499,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
private _decorateStorageEntryAt<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>, blockHash: Uint8Array): QueryableStorageEntryAt<ApiType> {
// get the storage arguments, with DoubleMap as an array entry, otherwise spread
const getArgs = (args: unknown[]): unknown[] => extractStorageArgs(creator, args);
const getArgs = (args: unknown[]): unknown[] => extractStorageArgs(this.#registry, creator, args);
// Disable this where it occurs for each field we are decorating
/* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
@@ -545,18 +556,18 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return decorateMethod((...args: unknown[]): Observable<Codec> => {
return this.hasSubscriptions
? this._rpcCore.state.subscribeStorage<[Codec]>([extractStorageArgs(creator, args)]).pipe(
? this._rpcCore.state.subscribeStorage<[Codec]>([extractStorageArgs(this.#registry, creator, args)]).pipe(
map(([data]) => data) // extract first/only result from list
)
: this._rpcCore.state.getStorage(extractStorageArgs(creator, args));
: this._rpcCore.state.getStorage(extractStorageArgs(this.#registry, creator, args));
}, {
methodName: creator.method,
overrideNoSub: (...args: unknown[]) => this._rpcCore.state.getStorage(extractStorageArgs(creator, args))
overrideNoSub: (...args: unknown[]) => this._rpcCore.state.getStorage(extractStorageArgs(this.#registry, creator, args))
});
}
private _decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: Arg[], range: [Hash, Hash?]): Observable<[Hash, Codec][]> {
const outputType = unwrapStorageType(decorated.creator.meta.type, decorated.creator.meta.modifier.isOptional);
const outputType = unwrapStorageType(this.#registry, decorated.creator.meta.type, decorated.creator.meta.modifier.isOptional);
return this._rpcCore.state
.queryStorage<[Option<Raw>]>([decorated.key(...args)], ...range)
+10 -7
View File
@@ -114,9 +114,8 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
const u8aHash = u8aToU8a(blockHash);
const registry = await this.getBlockRegistry(u8aHash);
return registry.decoration
? registry.decoration
: this._injectDecorated(registry, true, u8aHash).decoratedApi;
// always create a new decoration for this specific hash
return this._createDecorated(registry, true, u8aHash).decoratedApi;
}
/**
@@ -152,8 +151,12 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
: await firstValueFrom((this._rpcCore.state.getRuntimeVersion as RpcInterfaceMethod).json(header.parentHash))
);
// check for pre-existing registries
const existingViaVersion = this.#registries.find(({ specVersion }) => specVersion.eq(version.specVersion));
// check for pre-existing registries. We also check specName, e.g. it
// could be changed like in Westmint with upgrade from shell -> westmint
const existingViaVersion = this.#registries.find(({ specName, specVersion }) =>
specName.eq(version.specName) &&
specVersion.eq(version.specVersion)
);
if (existingViaVersion) {
existingViaVersion.lastBlockHash = blockHash;
@@ -170,7 +173,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
this._initRegistry(registry, this._runtimeChain as Text, version, metadata);
// add our new registry
const result = { lastBlockHash: blockHash, metadata, registry, specVersion: version.specVersion };
const result = { lastBlockHash: blockHash, metadata, registry, specName: version.specName, specVersion: version.specVersion };
this.#registries.push(result);
@@ -301,7 +304,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
// setup the initial registry, when we have none
if (!this.#registries.length) {
this.#registries.push({ isDefault: true, metadata, registry: this.registry, specVersion: runtimeVersion.specVersion });
this.#registries.push({ isDefault: true, metadata, registry: this.registry, specName: runtimeVersion.specName, specVersion: runtimeVersion.specVersion });
}
// get unique types & validate
+5 -1
View File
@@ -2,15 +2,19 @@
// SPDX-License-Identifier: Apache-2.0
import type { Metadata } from '@polkadot/types/metadata';
import type { DecoratedMeta } from '@polkadot/types/metadata/decorate/types';
import type { Text } from '@polkadot/types/primitive';
import type { Registry } from '@polkadot/types/types';
import type { BN } from '@polkadot/util';
import type { ApiDecoration, ApiTypes } from '../types';
export interface VersionedRegistry<ApiType extends ApiTypes> {
decoration?: ApiDecoration<ApiType> | null;
decoratedApi?: ApiDecoration<ApiType>;
decoratedMeta?: DecoratedMeta;
isDefault?: boolean;
lastBlockHash?: Uint8Array | null;
metadata: Metadata;
registry: Registry;
specName: Text;
specVersion: BN;
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api', version: '5.1.1' };
export const packageInfo = { name: '@polkadot/api', version: '5.3.2' };
+13 -13
View File
@@ -4,7 +4,7 @@
import type { Storage } from '@polkadot/types/metadata/decorate/types';
import { decorateStorage, Metadata, TypeRegistry } from '@polkadot/types';
import metaStatic from '@polkadot/types/metadata/static';
import metaStatic from '@polkadot/types/metadata/static-substrate';
import { extractStorageArgs } from './validate';
@@ -20,79 +20,79 @@ describe('extractStorageArgs', (): void => {
it('validates no-arg plain', (): void => {
expect(
extractStorageArgs(storage.timestamp.now, [])
extractStorageArgs(registry, storage.timestamp.now, [])
).toEqual([storage.timestamp.now]);
});
it('validates no-arg plain (with undefined, undefined)', (): void => {
expect(
extractStorageArgs(storage.timestamp.now, [undefined, undefined])
extractStorageArgs(registry, storage.timestamp.now, [undefined, undefined])
).toEqual([storage.timestamp.now]);
});
it('validates no-arg plain (failing when there are args)', (): void => {
expect(
(): unknown => extractStorageArgs(storage.timestamp.now, [123, 456])
(): unknown => extractStorageArgs(registry, storage.timestamp.now, [123, 456])
).toThrow('timestamp.now() does not take any arguments, 2 found');
});
it('validates map, 1 arg', (): void => {
expect(
extractStorageArgs(storage.staking.payee, ['abc'])
extractStorageArgs(registry, storage.staking.payee, ['abc'])
).toEqual([storage.staking.payee, 'abc']);
});
it('validates map, 1 arg (failing with no args)', (): void => {
expect(
(): any =>
extractStorageArgs(storage.staking.payee, [])
extractStorageArgs(registry, storage.staking.payee, [])
).toThrow('staking.payee(AccountId) is a map, requiring 1 argument, 0 found');
});
it('validates map, 1 arg (failing with no args)', (): void => {
expect(
(): any =>
extractStorageArgs(storage.staking.payee, ['abc', 'def'])
extractStorageArgs(registry, storage.staking.payee, ['abc', 'def'])
).toThrow('staking.payee(AccountId) is a map, requiring 1 argument, 2 found');
});
it('validates doublemap, 2 args', (): void => {
expect(
extractStorageArgs(storage.staking.erasStakers, [1, '0x1234'])
extractStorageArgs(registry, storage.staking.erasStakers, [1, '0x1234'])
).toEqual([storage.staking.erasStakers, [1, '0x1234']]);
});
it('validates doublemap, 2 args (failing with no args)', (): void => {
expect(
(): any =>
extractStorageArgs(storage.staking.erasStakers, [])
extractStorageArgs(registry, storage.staking.erasStakers, [])
).toThrow('staking.erasStakers(EraIndex, AccountId) is a double map, requiring 2 arguments, 0 found');
});
it('validates doublemap, 2 args (failing with 1 arg)', (): void => {
expect(
(): any =>
extractStorageArgs(storage.staking.erasStakers, [123])
extractStorageArgs(registry, storage.staking.erasStakers, [123])
).toThrow('staking.erasStakers(EraIndex, AccountId) is a double map, requiring 2 arguments, 1 found');
});
// Linked maps have been removed
it.skip('validates linked map, no args', (): void => {
expect(
extractStorageArgs(storage.staking.validators, [])
extractStorageArgs(registry, storage.staking.validators, [])
).toEqual([storage.staking.validators]);
});
it.skip('validates linked map, single arg', (): void => {
expect(
extractStorageArgs(storage.staking.validators, [123])
extractStorageArgs(registry, storage.staking.validators, [123])
).toEqual([storage.staking.validators, 123]);
});
it.skip('validates linked map (failing with extra args)', (): void => {
expect(
(): any[] =>
extractStorageArgs(storage.staking.validators, [123, 456])
extractStorageArgs(registry, storage.staking.validators, [123, 456])
).toThrow('staking.validators(AccountId) is a linked map, requiring either 0 arguments (retrieving all) or 1 argument, 2 found');
});
});
+13 -12
View File
@@ -3,26 +3,27 @@
import type { Type } from '@polkadot/types';
import type { StorageEntry } from '@polkadot/types/primitive/types';
import type { Registry } from '@polkadot/types/types';
import { assert, isUndefined } from '@polkadot/util';
function sig ({ method, section }: StorageEntry, args: Type[]): string {
function sig (_: Registry, { method, section }: StorageEntry, args: Type[]): string {
return `${section}.${method}(${args.join(', ')})`;
}
function doDoubleMap (creator: StorageEntry, args: unknown[]): [StorageEntry, [any, any]] {
function doDoubleMap (registry: Registry, creator: StorageEntry, args: unknown[]): [StorageEntry, [any, any]] {
const { key1, key2 } = creator.meta.type.asDoubleMap;
assert(args.length === 2, () => `${sig(creator, [key1, key2])} is a double map, requiring 2 arguments, ${args.length} found`);
assert(args.length === 2, () => `${sig(registry, creator, [key1, key2])} is a double map, requiring 2 arguments, ${args.length} found`);
// pass as tuple
return [creator, args as [any, any]];
}
function doMap (creator: StorageEntry, args: unknown[]): [StorageEntry] | [StorageEntry, any] {
function doMap (registry: Registry, creator: StorageEntry, args: unknown[]): [StorageEntry] | [StorageEntry, any] {
const { key } = creator.meta.type.asMap;
assert(args.length === 1, () => `${sig(creator, [key])} is a map, requiring 1 argument, ${args.length} found`);
assert(args.length === 1, () => `${sig(registry, creator, [key])} is a map, requiring 1 argument, ${args.length} found`);
// expand
return args.length
@@ -30,10 +31,10 @@ function doMap (creator: StorageEntry, args: unknown[]): [StorageEntry] | [Stora
: [creator];
}
function doNMap (creator: StorageEntry, args: unknown[]): [StorageEntry, any[]] {
function doNMap (registry: Registry, creator: StorageEntry, args: unknown[]): [StorageEntry, any[]] {
const { keyVec } = creator.meta.type.asNMap;
assert(args.length === keyVec.length, () => `${sig(creator, keyVec)} is a multi map, requiring ${keyVec.length} arguments, ${args.length} found`);
assert(args.length === keyVec.length, () => `${sig(registry, creator, keyVec)} is a multi map, requiring ${keyVec.length} arguments, ${args.length} found`);
// pass as tuple
return [creator, args];
@@ -41,18 +42,18 @@ function doNMap (creator: StorageEntry, args: unknown[]): [StorageEntry, any[]]
// sets up the arguments in the form of [creator, args] ready to be used in a storage
// call. Additionally, it verifies that the correct number of arguments have been passed
export function extractStorageArgs (creator: StorageEntry, _args: unknown[]): [StorageEntry, any[]] | [StorageEntry] | [StorageEntry, any] {
export function extractStorageArgs (registry: Registry, creator: StorageEntry, _args: unknown[]): [StorageEntry, any[]] | [StorageEntry] | [StorageEntry, any] {
const args = _args.filter((arg) => !isUndefined(arg));
if (creator.meta.type.isDoubleMap) {
return doDoubleMap(creator, args);
return doDoubleMap(registry, creator, args);
} else if (creator.meta.type.isMap) {
return doMap(creator, args);
return doMap(registry, creator, args);
} else if (creator.meta.type.isNMap) {
return doNMap(creator, args);
return doNMap(registry, creator, args);
}
assert(args.length === 0, () => `${sig(creator, [])} does not take any arguments, ${args.length} found`);
assert(args.length === 0, () => `${sig(registry, creator, [])} does not take any arguments, ${args.length} found`);
// no args
return [creator];
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-core",
"version": "5.1.1",
"version": "5.3.2",
"type": "module",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
@@ -19,13 +19,13 @@
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/rpc-provider": "5.1.1",
"@polkadot/types": "5.1.1",
"@polkadot/util": "^7.0.2",
"@babel/runtime": "^7.14.8",
"@polkadot/rpc-provider": "5.3.2",
"@polkadot/types": "5.3.2",
"@polkadot/util": "^7.1.1",
"rxjs": "^7.2.0"
},
"devDependencies": {
"@polkadot/keyring": "^7.0.2"
"@polkadot/keyring": "^7.1.1"
}
}
+8 -22
View File
@@ -11,7 +11,7 @@ import type { RpcInterface, RpcInterfaceMethod } from './types';
import { Observable, publishReplay, refCount } from 'rxjs';
import { createClass, createTypeUnsafe, Option, rpcDefinitions } from '@polkadot/types';
import { rpcDefinitions } from '@polkadot/types';
import { assert, hexToU8a, isFunction, isNull, isUndefined, logger, memoize, u8aToU8a } from '@polkadot/util';
import { drr, refCountDelay } from './util';
@@ -339,7 +339,7 @@ export class RpcCore {
assert(inputs.length >= reqArgCount && inputs.length <= def.params.length, () => `Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`);
return inputs.map((input, index): Codec =>
createTypeUnsafe(registry, def.params[index].type, [input], { blockHash })
registry.createTypeUnsafe(def.params[index].type, [input], { blockHash })
);
}
@@ -366,7 +366,7 @@ export class RpcCore {
: mapped as unknown as Codec[];
}
return createTypeUnsafe(registry, rpc.type, [result], { blockHash });
return registry.createTypeUnsafe(rpc.type, [result], { blockHash });
}
private _formatStorageData (registry: Registry, blockHash: Uint8Array | string | null | undefined, key: StorageKey, value: string | null): Codec {
@@ -432,29 +432,15 @@ export class RpcCore {
: ` entry ${entryIndex}:`;
try {
if (meta.modifier.isOptional) {
let inner = null;
if (!isEmpty) {
inner = createTypeUnsafe(registry, type, [input], { blockHash, isPedantic: true });
}
const option = new Option(registry, createClass(registry, type), inner);
if (blockHash) {
option.createdAtHash = registry.createType('Hash', blockHash);
}
return option;
}
return createTypeUnsafe(registry, type, [
return registry.createTypeUnsafe(type, [
isEmpty
? meta.fallback
? hexToU8a(meta.fallback.toHex())
: undefined
: input
], { blockHash, isPedantic: true });
: meta.modifier.isOptional
? registry.createTypeUnsafe(type, [input], { blockHash, isPedantic: true })
: input
], { blockHash, isOptional: meta.modifier.isOptional, isPedantic: !meta.modifier.isOptional });
} catch (error) {
throw new Error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:${entryNum}: ${(error as Error).message}`);
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-core', version: '5.1.1' };
export const packageInfo = { name: '@polkadot/rpc-core', version: '5.3.2' };
+10 -10
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-provider",
"version": "5.1.1",
"version": "5.3.2",
"type": "module",
"description": "Transport providers for the API",
"main": "index.js",
@@ -19,18 +19,18 @@
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/types": "5.1.1",
"@polkadot/util": "^7.0.2",
"@polkadot/util-crypto": "^7.0.2",
"@polkadot/x-fetch": "^7.0.2",
"@polkadot/x-global": "^7.0.2",
"@polkadot/x-ws": "^7.0.2",
"@babel/runtime": "^7.14.8",
"@polkadot/types": "5.3.2",
"@polkadot/util": "^7.1.1",
"@polkadot/util-crypto": "^7.1.1",
"@polkadot/x-fetch": "^7.1.1",
"@polkadot/x-global": "^7.1.1",
"@polkadot/x-ws": "^7.1.1",
"eventemitter3": "^4.0.7"
},
"devDependencies": {
"@polkadot/keyring": "^7.0.2",
"@polkadot/types": "5.1.1",
"@polkadot/keyring": "^7.1.1",
"@polkadot/types": "5.3.2",
"mock-socket": "^9.0.3",
"nock": "^13.1.1"
}
+1 -1
View File
@@ -15,7 +15,7 @@ import { decorateStorage, Metadata } from '@polkadot/types';
import jsonrpc from '@polkadot/types/interfaces/jsonrpc';
import rpcHeader from '@polkadot/types/json/Header.004.json';
import rpcSignedBlock from '@polkadot/types/json/SignedBlock.004.immortal.json';
import rpcMetadata from '@polkadot/types/metadata/static';
import rpcMetadata from '@polkadot/types/metadata/static-substrate';
import { assert, BN, bnToU8a, logger, u8aToHex } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-provider', version: '5.1.1' };
export const packageInfo = { name: '@polkadot/rpc-provider', version: '5.3.2' };
+8 -8
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/typegen",
"version": "5.1.1",
"version": "5.3.2",
"type": "module",
"description": "Type generation scripts",
"main": "index.js",
@@ -26,19 +26,19 @@
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
"dependencies": {
"@babel/core": "^7.14.6",
"@babel/core": "^7.14.8",
"@babel/register": "^7.14.5",
"@babel/runtime": "^7.14.6",
"@polkadot/api": "5.1.1",
"@polkadot/rpc-provider": "5.1.1",
"@polkadot/types": "5.1.1",
"@polkadot/util": "^7.0.2",
"@babel/runtime": "^7.14.8",
"@polkadot/api": "5.3.2",
"@polkadot/rpc-provider": "5.3.2",
"@polkadot/types": "5.3.2",
"@polkadot/util": "^7.1.1",
"handlebars": "^4.7.7",
"websocket": "^1.0.34",
"yargs": "^17.0.1"
},
"devDependencies": {
"@types/websocket": "^1.0.3",
"@types/websocket": "^1.0.4",
"@types/yargs": "^17.0.2"
}
}
+15 -17
View File
@@ -24,7 +24,6 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
}, {});
const modules = meta.asLatest.modules
.sort(compareName)
.filter((mod) => mod.constants.length > 0)
.map(({ constants, name }) => {
if (!isStrict) {
@@ -32,9 +31,8 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
}
const items = constants
.sort(compareName)
.map(({ docs, name, type }) => {
const returnType = formatType(allDefs, type.toString(), imports);
const returnType = formatType(meta.registry, allDefs, type.toString(), imports);
setImports(allDefs, imports, [returnType]);
@@ -43,31 +41,31 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
name: stringCamelCase(name),
type: returnType
};
});
})
.sort(compareName);
return {
items,
name: stringCamelCase(name)
};
});
const types = [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
];
})
.sort(compareName);
return generateForMetaTemplate({
headerType: 'chain',
imports,
isStrict,
modules,
types
types: [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
]
});
});
}
+10 -12
View File
@@ -19,31 +19,29 @@ function generateForMeta (meta: Metadata, dest: string, isStrict: boolean): void
const imports = createImports({});
const modules = meta.asLatest.modules
.sort(compareName)
.filter((mod) => mod.errors.length > 0)
.map(({ errors, name }) => ({
items: errors
.sort(compareName)
.map(({ docs, name }) => ({
docs,
name: name.toString()
})),
}))
.sort(compareName),
name: stringCamelCase(name)
}));
const types = [
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
];
}))
.sort(compareName);
return generateForMetaTemplate({
headerType: 'chain',
imports,
isStrict,
modules,
types
types: [
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
]
});
});
}
+14 -16
View File
@@ -24,14 +24,13 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
}, {});
const modules = meta.asLatest.modules
.sort(compareName)
.filter((mod) => mod.events.isSome)
.map(({ events, name }) => ({
items: events
.unwrap()
.sort(compareName)
.map(({ args, docs, name }) => {
const types = args.map((type) => formatType(allDefs, type.toString(), imports));
const types = args.map((type) => formatType(meta.registry, allDefs, type.toString(), imports));
setImports(allDefs, imports, types);
@@ -40,27 +39,26 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
name: name.toString(),
type: types.join(', ')
};
}),
}).sort(compareName),
name: stringCamelCase(name)
}));
const types = [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
];
}))
.sort(compareName);
return generateForMetaTemplate({
headerType: 'chain',
imports,
isStrict,
modules,
types
types: [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
]
});
});
}
@@ -62,18 +62,16 @@ export function generateInterfaceTypes (importDefinitions: { [importPath: string
});
});
const types = [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
}))
];
return generateInterfaceTypesTemplate({
headerType: 'defs',
imports,
items: items.sort((a, b) => a.localeCompare(b)),
types
types: [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
}))
]
});
});
}
+25 -23
View File
@@ -18,12 +18,12 @@ import { ModuleTypes } from '../util/imports';
// From a storage entry metadata, we return [args, returnType]
/** @internal */
function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string, string] {
const outputType = unwrapStorageType(storageEntry.type, storageEntry.modifier.isOptional);
const outputType = unwrapStorageType(registry, storageEntry.type, storageEntry.modifier.isOptional);
if (storageEntry.type.isPlain) {
setImports(allDefs, imports, [storageEntry.type.asPlain.toString()]);
return ['', '', formatType(allDefs, outputType, imports)];
return ['', '', formatType(registry, allDefs, outputType, imports)];
} else if (storageEntry.type.isMap) {
const map = storageEntry.type.asMap;
@@ -36,9 +36,9 @@ function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registr
]);
return [
formatType(allDefs, map.key.toString(), imports),
formatType(registry, allDefs, map.key.toString(), imports),
`arg: ${similarTypes.join(' | ')}`,
formatType(allDefs, outputType, imports)
formatType(registry, allDefs, outputType, imports)
];
} else if (storageEntry.type.isDoubleMap) {
const dm = storageEntry.type.asDoubleMap;
@@ -57,9 +57,12 @@ function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registr
const key2Types = similarTypes2.join(' | ');
return [
[formatType(allDefs, dm.key1.toString(), imports), formatType(allDefs, dm.key2.toString(), imports)].join(', '),
[
formatType(registry, allDefs, dm.key1.toString(), imports),
formatType(registry, allDefs, dm.key2.toString(), imports)
].join(', '),
`arg1: ${key1Types}, arg2: ${key2Types}`,
formatType(allDefs, outputType, imports)
formatType(registry, allDefs, outputType, imports)
];
} else if (storageEntry.type.isNMap) {
const nmap = storageEntry.type.asNMap;
@@ -75,9 +78,9 @@ function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registr
const keyTypes = similarTypes.map((t) => t.join(' | '));
return [
nmap.keyVec.map((k) => formatType(allDefs, k.toString(), imports)).join(', '),
nmap.keyVec.map((k) => formatType(registry, allDefs, k.toString(), imports)).join(', '),
keyTypes.map((t, i) => `arg${i + 1}: ${t}`).join(', '),
formatType(allDefs, outputType, imports)
formatType(registry, allDefs, outputType, imports)
];
}
@@ -101,7 +104,6 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
.filter((mod) => !mod.storage.isNone)
.map(({ name, storage }) => {
const items = storage.unwrap().items
.sort(compareName)
.map((storageEntry) => {
const [args, params, returnType] = entrySignature(allDefs, registry, storageEntry, imports);
@@ -113,33 +115,33 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
params,
returnType
};
});
})
.sort(compareName);
return {
items,
name: stringCamelCase(name)
};
});
})
.sort(compareName);
imports.typesTypes.Observable = true;
const types = [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
];
return generateForMetaTemplate({
headerType: 'chain',
imports,
isStrict,
modules,
types
types: [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
}
]
});
});
}
+7 -9
View File
@@ -90,7 +90,7 @@ export function generateRpcTypes (registry: TypeRegistry, importDefinitions: Rec
return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`;
});
type = formatType(allDefs, def.type, imports);
type = formatType(registry, allDefs, def.type, imports);
generic = '';
}
@@ -126,18 +126,16 @@ export function generateRpcTypes (registry: TypeRegistry, importDefinitions: Rec
imports.typesTypes.Observable = true;
const types = [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
}))
];
return generateRpcTypesTemplate({
headerType: 'chain',
imports,
modules,
types
types: [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
}))
]
});
});
}
+31 -28
View File
@@ -2,12 +2,13 @@
// SPDX-License-Identifier: Apache-2.0
import type { TypeDef } from '@polkadot/types/create/types';
import type { Registry } from '@polkadot/types/types';
import type { ModuleTypes } from '../util/imports';
import Handlebars from 'handlebars';
import path from 'path';
import { getTypeDef } from '@polkadot/types/create';
import { getTypeDef, TypeRegistry } from '@polkadot/types/create';
import { TypeDefInfo } from '@polkadot/types/create/types';
import * as defaultDefinitions from '@polkadot/types/interfaces/definitions';
import { assert, isString, stringCamelCase, stringify, stringUpperFirst } from '@polkadot/util';
@@ -28,13 +29,13 @@ export function createGetter (definitions: Record<string, ModuleTypes>, name = '
/** @internal */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function errorUnhandled (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
function errorUnhandled (_: Registry, definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
throw new Error(`Generate: ${def.name || ''}: Unhandled type ${TypeDefInfo[def.info]}`);
}
/** @internal */
function tsExport (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
return exportInterface(def.name, formatType(definitions, def, imports));
function tsExport (registry: Registry, definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
return exportInterface(def.name, formatType(registry, definitions, def, imports));
}
const tsBTreeMap = tsExport;
@@ -47,7 +48,7 @@ const tsPlain = tsExport;
const tsTuple = tsExport;
/** @internal */
function tsEnum (definitions: Record<string, ModuleTypes>, { name: enumName, sub }: TypeDef, imports: TypeImports): string {
function tsEnum (registry: Registry, definitions: Record<string, ModuleTypes>, { name: enumName, sub }: TypeDef, imports: TypeImports): string {
setImports(definitions, imports, ['Enum']);
const keys = (sub as TypeDef[]).map((def, index): string => {
@@ -56,7 +57,7 @@ function tsEnum (definitions: Record<string, ModuleTypes>, { name: enumName, sub
const isComplex = [TypeDefInfo.Struct, TypeDefInfo.Tuple, TypeDefInfo.Vec, TypeDefInfo.VecFixed].includes(info);
const asGetter = type === 'Null' || info === TypeDefInfo.DoNotConstruct
? ''
: createGetter(definitions, `as${getter}`, isComplex ? formatType(definitions, info === TypeDefInfo.Struct ? def : type, imports) : type, imports);
: createGetter(definitions, `as${getter}`, isComplex ? formatType(registry, definitions, info === TypeDefInfo.Struct ? def : type, imports) : type, imports);
const isGetter = info === TypeDefInfo.DoNotConstruct
? ''
: createGetter(definitions, `is${getter}`, 'boolean', imports);
@@ -82,18 +83,18 @@ function tsEnum (definitions: Record<string, ModuleTypes>, { name: enumName, sub
return exportInterface(enumName, 'Enum', keys.join(''));
}
function tsInt (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports, type: 'Int' | 'UInt' = 'Int'): string {
function tsInt (_: Registry, definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports, type: 'Int' | 'UInt' = 'Int'): string {
setImports(definitions, imports, [type]);
return exportInterface(def.name, type);
}
/** @internal */
function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Err' | 'Error', def: TypeDef, imports: TypeImports): string {
function tsResultGetter (registry: Registry, definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Err' | 'Error', def: TypeDef, imports: TypeImports): string {
const { info, type } = def;
const asGetter = type === 'Null'
? ''
: (getter === 'Error' ? ' /** @deprecated Use asErr */\n' : '') + createGetter(definitions, `as${getter}`, info === TypeDefInfo.Tuple ? formatType(definitions, def, imports) : type, imports);
: (getter === 'Error' ? ' /** @deprecated Use asErr */\n' : '') + createGetter(definitions, `as${getter}`, info === TypeDefInfo.Tuple ? formatType(registry, definitions, def, imports) : type, imports);
const isGetter = (getter === 'Error' ? ' /** @deprecated Use isErr */\n' : '') + createGetter(definitions, `is${getter}`, 'boolean', imports);
switch (info) {
@@ -109,28 +110,28 @@ function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName =
}
/** @internal */
function tsResult (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
function tsResult (registry: Registry, definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
const [okDef, errorDef] = (def.sub as TypeDef[]);
const inner = [
tsResultGetter(definitions, def.name, 'Err', errorDef, imports),
tsResultGetter(registry, definitions, def.name, 'Err', errorDef, imports),
// @deprecated, use Err
tsResultGetter(definitions, def.name, 'Error', errorDef, imports),
tsResultGetter(definitions, def.name, 'Ok', okDef, imports)
tsResultGetter(registry, definitions, def.name, 'Error', errorDef, imports),
tsResultGetter(registry, definitions, def.name, 'Ok', okDef, imports)
].join('');
setImports(definitions, imports, [def.type]);
return exportInterface(def.name, formatType(definitions, def, imports), inner);
return exportInterface(def.name, formatType(registry, definitions, def, imports), inner);
}
/** @internal */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function tsSi (definitions: Record<string, ModuleTypes>, { type }: TypeDef, imports: TypeImports): string {
function tsSi (registry: Registry, definitions: Record<string, ModuleTypes>, { type }: TypeDef, imports: TypeImports): string {
throw new Error('Unable to generate string definition from TypeDefInfo.Si');
}
/** @internal */
function tsSet (definitions: Record<string, ModuleTypes>, { name: setName, sub }: TypeDef, imports: TypeImports): string {
function tsSet (_: Registry, definitions: Record<string, ModuleTypes>, { name: setName, sub }: TypeDef, imports: TypeImports): string {
setImports(definitions, imports, ['Set']);
const types = (sub as TypeDef[]).map(({ name }): string => {
@@ -143,11 +144,11 @@ function tsSet (definitions: Record<string, ModuleTypes>, { name: setName, sub }
}
/** @internal */
function tsStruct (definitions: Record<string, ModuleTypes>, { name: structName, sub }: TypeDef, imports: TypeImports): string {
function tsStruct (registry: Registry, definitions: Record<string, ModuleTypes>, { name: structName, sub }: TypeDef, imports: TypeImports): string {
setImports(definitions, imports, ['Struct']);
const keys = (sub as TypeDef[]).map((typedef): string => {
const returnType = formatType(definitions, typedef, imports);
const returnType = formatType(registry, definitions, typedef, imports);
return createGetter(definitions, typedef.name, returnType, imports);
});
@@ -156,12 +157,12 @@ function tsStruct (definitions: Record<string, ModuleTypes>, { name: structName,
}
/** @internal */
function tsUInt (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
return tsInt(definitions, def, imports, 'UInt');
function tsUInt (registry: Registry, definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
return tsInt(registry, definitions, def, imports, 'UInt');
}
/** @internal */
function tsVec (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
function tsVec (registry: Registry, definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
const type = (def.sub as TypeDef).type;
if (def.info === TypeDefInfo.VecFixed && type === 'u8') {
@@ -170,13 +171,13 @@ function tsVec (definitions: Record<string, ModuleTypes>, def: TypeDef, imports:
return exportType(def.name, 'U8aFixed');
}
return exportInterface(def.name, formatType(definitions, def, imports));
return exportInterface(def.name, formatType(registry, definitions, def, imports));
}
// handlers are defined externally to use - this means that when we do a
// `generators[typedef.info](...)` TS will show any unhandled types. Rather
// we are being explicit in having no handlers where we do not support (yet)
const encoders: Record<TypeDefInfo, (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports) => string> = {
const encoders: Record<TypeDefInfo, (registry: Registry, definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports) => string> = {
[TypeDefInfo.BTreeMap]: tsBTreeMap,
[TypeDefInfo.BTreeSet]: tsBTreeSet,
[TypeDefInfo.Compact]: tsCompact,
@@ -199,11 +200,11 @@ const encoders: Record<TypeDefInfo, (definitions: Record<string, ModuleTypes>, d
};
/** @internal */
function generateInterfaces (definitions: Record<string, ModuleTypes>, { types }: { types: Record<string, any> }, imports: Imports): [string, string][] {
function generateInterfaces (registry: Registry, definitions: Record<string, ModuleTypes>, { types }: { types: Record<string, any> }, imports: Imports): [string, string][] {
return Object.entries(types).map(([name, type]): [string, string] => {
const def = getTypeDef(isString(type) ? type : stringify(type), { name });
return [name, encoders[def.info](definitions, def, imports)];
return [name, encoders[def.info](registry, definitions, def, imports)];
});
}
@@ -217,10 +218,10 @@ const templateTypes = readTemplate('tsDef/types');
const generateTsDefTypesTemplate = Handlebars.compile(templateTypes);
/** @internal */
function generateTsDefFor (importDefinitions: { [importPath: string]: Record<string, ModuleTypes> }, defName: string, { types }: { types: Record<string, any> }, outputDir: string): void {
function generateTsDefFor (registry: Registry, importDefinitions: { [importPath: string]: Record<string, ModuleTypes> }, 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 interfaces = generateInterfaces(registry, definitions, { types }, imports);
const items = interfaces.sort((a, b): number => a[0].localeCompare(b[0])).map(([, definition]): string => definition);
const importTypes = [
@@ -242,13 +243,15 @@ function generateTsDefFor (importDefinitions: { [importPath: string]: Record<str
/** @internal */
export function generateTsDef (importDefinitions: { [importPath: string]: Record<string, ModuleTypes> }, outputDir: string, generatingPackage: string): void {
const registry = new TypeRegistry();
writeFile(path.join(outputDir, 'types.ts'), (): string => {
const definitions = importDefinitions[generatingPackage];
Object.entries(definitions).forEach(([defName, obj]): void => {
console.log(`\tExtracting interfaces for ${defName}`);
generateTsDefFor(importDefinitions, defName, obj, outputDir);
generateTsDefFor(registry, importDefinitions, defName, obj, outputDir);
});
return generateTsDefTypesTemplate({
+15 -17
View File
@@ -37,13 +37,11 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
}, {});
const modules = meta.asLatest.modules
.sort(compareName)
.filter(({ calls }) => calls.unwrapOr([]).length !== 0)
.map(({ calls, name }) => {
setImports(allDefs, imports, ['Call', 'Extrinsic', 'SubmittableExtrinsic']);
const items = calls.unwrap()
.sort(compareName)
.map(({ args, docs, name }) => {
const params = args
.map(({ name, type }) => {
@@ -57,36 +55,36 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
.join(', ');
return {
args: args.map(({ type }) => formatType(allDefs, type.toString(), imports)).join(', '),
args: args.map(({ type }) => formatType(registry, allDefs, type.toString(), imports)).join(', '),
docs,
name: stringCamelCase(name),
params
};
});
})
.sort(compareName);
return {
items,
name: stringCamelCase(name)
};
});
const types = [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes', 'SubmittableExtrinsic']
}
];
})
.sort(compareName);
return generateForMetaTemplate({
headerType: 'chain',
imports,
isStrict,
modules,
types
types: [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath,
types: Object.keys(imports.localTypes[packagePath])
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes', 'SubmittableExtrinsic']
}
]
});
});
}
+3 -3
View File
@@ -9,7 +9,7 @@ import fs from 'fs';
import { GenericCall as Call, Metadata, TypeRegistry, Vec } from '@polkadot/types';
import * as definitions from '@polkadot/types/interfaces/definitions';
import { getStorage as getSubstrateStorage } from '@polkadot/types/metadata/decorate/storage/getStorage';
import rpcdata from '@polkadot/types/metadata/static';
import rpcdata from '@polkadot/types/metadata/static-substrate';
import { Text } from '@polkadot/types/primitive';
import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
import { stringCamelCase, stringLowerFirst } from '@polkadot/util';
@@ -211,7 +211,7 @@ function addStorage (metadata: MetadataLatest): string {
? ('`' + func.type.asNMap.keyVec.map((k) => k.toString()).join(', ') + '`')
: '';
const methodName = stringLowerFirst(func.name);
const outputType = unwrapStorageType(func.type, func.modifier.isOptional);
const outputType = unwrapStorageType(metadata.registry, func.type, func.modifier.isOptional);
return {
interface: '`' + `api.query.${sectionName}.${methodName}` + '`',
@@ -234,7 +234,7 @@ function addStorage (metadata: MetadataLatest): string {
? ('`' + meta.type.asDoubleMap.key1.toString() + ', ' + meta.type.asDoubleMap.key2.toString() + '`')
: '';
const methodName = stringLowerFirst(name);
const outputType = unwrapStorageType(meta.type, meta.modifier.isOptional);
const outputType = unwrapStorageType(metadata.registry, meta.type, meta.modifier.isOptional);
return {
interface: '`' + `api.query.substrate.${methodName}` + '`',
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/typegen', version: '5.1.1' };
export const packageInfo = { name: '@polkadot/typegen', version: '5.3.2' };
+8 -5
View File
@@ -10,7 +10,7 @@ import { ClassOfUnsafe, getTypeDef } from '@polkadot/types/create';
import { TypeDefInfo } from '@polkadot/types/create/types';
import { GenericAccountId, GenericLookupSource, GenericVote } from '@polkadot/types/generic';
import { AllConvictions } from '@polkadot/types/interfaces/democracy/definitions';
import { Null } from '@polkadot/types/primitive';
import { bool, Null } from '@polkadot/types/primitive';
import * as primitiveClasses from '@polkadot/types/primitive';
import { isChildClass, stringify } from '@polkadot/util';
@@ -28,7 +28,10 @@ const voteConvictions = arrayToStrType(AllConvictions);
/** @internal */
export function getDerivedTypes (registry: Registry, definitions: Record<string, ModuleTypes>, type: string, primitiveName: string, imports: TypeImports): string[] {
// `primitiveName` represents the actual primitive type our type is mapped to
const isCompact = isCompactEncodable((primitiveClasses as Record<string, any>)[primitiveName] || ClassOfUnsafe(registry, type));
const isCompact = isCompactEncodable(
(primitiveClasses as Record<string, any>)[primitiveName] ||
ClassOfUnsafe(registry, type)
);
const def = getTypeDef(type);
setImports(definitions, imports, ['Option', 'Vec', isCompact ? 'Compact' : '']);
@@ -54,7 +57,7 @@ export function getDerivedTypes (registry: Registry, definitions: Record<string,
});
}
const result = types.map((t) => formatType(definitions, t, imports)).map((t) => `'${t}': ${t};`);
const result = types.map((t) => formatType(registry, definitions, t, imports)).map((t) => `'${t}': ${t};`);
result.unshift(`${type}: ${type};`);
@@ -68,7 +71,7 @@ export function getDerivedTypes (registry: Registry, definitions: Record<string,
export function getSimilarTypes (registry: Registry, definitions: Record<string, ModuleTypes>, _type: string, imports: TypeImports): string[] {
const typeParts = _type.split('::');
const type = typeParts[typeParts.length - 1];
const possibleTypes = [formatType(definitions, type, imports)];
const possibleTypes = [formatType(registry, definitions, type, imports)];
if (type === 'Extrinsic') {
setImports(definitions, imports, ['IExtrinsic']);
@@ -121,7 +124,7 @@ export function getSimilarTypes (registry: Registry, definitions: Record<string,
possibleTypes.push('Address', 'AccountId', 'AccountIndex', 'LookupSource', 'string', 'Uint8Array');
} else if (isChildClass(GenericAccountId, Clazz)) {
possibleTypes.push('string', 'Uint8Array');
} else if (isChildClass(registry.createClass('bool'), Clazz)) {
} else if (isChildClass(bool, Clazz)) {
possibleTypes.push('boolean', 'Uint8Array');
} else if (isChildClass(Null, Clazz)) {
possibleTypes.push('null');
+5 -1
View File
@@ -1,12 +1,16 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { TypeRegistry } from '@polkadot/types';
import { formatType } from './formatting';
describe('formatType', (): void => {
const registry = new TypeRegistry();
it('handles nested Tuples', (): void => {
expect(
formatType({}, '(AccountId, (Balance, u32), u64)', {
formatType(registry, {}, '(AccountId, (Balance, u32), u64)', {
codecTypes: {},
definitions: {},
extrinsicTypes: {},
+121 -187
View File
@@ -1,7 +1,10 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable @typescript-eslint/no-unused-vars */
import type { TypeDef } from '@polkadot/types/create/types';
import type { Registry } from '@polkadot/types/types';
import Handlebars from 'handlebars';
@@ -83,100 +86,138 @@ export function exportType (name = '', base: string): string {
return exportInterface(name, base);
}
/**
* Given the inner `K` & `V`, return a `BTreeMap<K, V>` string
*/
/** @internal */
function formatBTreeMap (key: string, val: string): string {
return `BTreeMap<${key}, ${val}>`;
}
const formatters: Record<TypeDefInfo, (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => string> = {
[TypeDefInfo.Compact]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['Compact']);
/**
* Given the inner `V`, return a `BTreeSet<V>` string
*/
/** @internal */
function formatBTreeSet (val: string): string {
return `BTreeSet<${val}>`;
}
const sub = typeDef.sub as TypeDef;
/**
* Given the inner `T`, return a `Compact<T>` string
*/
/** @internal */
function formatCompact (inner: string): string {
return paramsNotation('Compact', inner);
}
return paramsNotation('Compact', formatType(registry, definitions, sub.lookupName || sub.type, imports, withShortcut));
},
[TypeDefInfo.DoNotConstruct]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['DoNotConstruct']);
/**
* Simple return
*/
/** @internal */
function formatDoNoConstruct (): string {
return 'DoNotConstruct';
}
return 'DoNotConstruct';
},
[TypeDefInfo.Enum]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
if (typeDef.lookupName) {
return typeDef.lookupName;
}
/**
* Given the inner `K` & `V`, return a `BTreeMap<K, V>` string
*/
/** @internal */
function formatHashMap (key: string, val: string): string {
return `HashMap<${key}, ${val}>`;
}
throw new Error(`TypeDefInfo.Enum: Not implemented on ${stringify(typeDef)}`);
},
[TypeDefInfo.Int]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
throw new Error(`TypeDefInfo.Int: Not implemented on ${stringify(typeDef)}`);
},
[TypeDefInfo.UInt]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
throw new Error(`TypeDefInfo.UInt: Not implemented on ${stringify(typeDef)}`);
},
[TypeDefInfo.Null]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['Null']);
/**
* Given the inner `T`, return a `Vec<T>` string
*/
/** @internal */
function formatLinkage (inner: string): string {
return paramsNotation('Linkage', inner);
}
return 'Null';
},
[TypeDefInfo.Option]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['Option']);
/**
* Given the inner `T`, return a `Option<T>` string
*/
/** @internal */
function formatOption (inner: string): string {
return paramsNotation('Option', inner);
}
const sub = (typeDef.sub as TypeDef);
/**
* Given the inner `O` & `E`, return a `Result<O, E>` string
*/
/** @internal */
function formatResult (innerOk: string, innerError: string): string {
return `Result<${innerOk}, ${innerError}>`;
}
return paramsNotation('Option', formatType(registry, definitions, sub.lookupName || sub.type, imports, withShortcut));
},
[TypeDefInfo.Plain]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, [typeDef.type]);
/**
* Given the entries `[string, T][]`, return a `{ name: T; ... }` string
*/
/** @internal */
function formatStruct (inners: [string, string][]): string {
return `{ ${inners.map(([k, t]) => `${k}: ${t};`).join(' ')} } & Struct`;
}
return typeDef.type;
},
[TypeDefInfo.Set]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
throw new Error(`TypeDefInfo.Set: Not implemented on ${stringify(typeDef)}`);
},
[TypeDefInfo.Si]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
return formatType(registry, definitions, registry.lookup.getTypeDef(typeDef.type), imports, withShortcut);
},
[TypeDefInfo.Struct]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['Struct']);
/**
* Given the inners `T[]`, return a `ITuple<...T>` string
*/
/** @internal */
function formatTuple (inners: string[]): string {
return paramsNotation('ITuple', `[${inners.join(', ')}]`);
}
return `{${withShortcut ? ' ' : '\n'}${
((typeDef.sub as TypeDef[]).map(({ lookupName, name, type }, index) => [
name || `unknown${index}`,
formatType(registry, definitions, lookupName || type, imports, withShortcut)
])).map(([k, t]) => `${withShortcut ? '' : ' readonly '}${k}: ${t};`).join(withShortcut ? ' ' : '\n')
}${withShortcut ? ' ' : '\n '}} & Struct`;
},
[TypeDefInfo.Tuple]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['ITuple']);
/**
* Given the inner `T`, return a `Vec<T>` string
*/
/** @internal */
function formatVec (inner: string): string {
return paramsNotation('Vec', inner);
}
// `(a,b)` gets transformed into `ITuple<[a, b]>`
return paramsNotation('ITuple', `[${
((typeDef.sub as TypeDef[]).map(({ lookupName, type }) =>
formatType(registry, definitions, lookupName || type, imports, withShortcut)
)).join(', ')
}]`);
},
[TypeDefInfo.Vec]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['Vec']);
const sub = (typeDef.sub as TypeDef);
return paramsNotation('Vec', formatType(registry, definitions, sub.lookupName || sub.type, imports, withShortcut));
},
[TypeDefInfo.VecFixed]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
const sub = (typeDef.sub as TypeDef);
if (sub.type === 'u8') {
setImports(definitions, imports, ['U8aFixed']);
return 'U8aFixed';
}
setImports(definitions, imports, ['Vec']);
return paramsNotation('Vec', formatType(registry, definitions, sub.lookupName || sub.type, imports, withShortcut));
},
[TypeDefInfo.BTreeMap]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['BTreeMap']);
const [keyDef, valDef] = (typeDef.sub as TypeDef[]);
return `BTreeMap<${formatType(registry, definitions, keyDef.lookupName || keyDef.type, imports, withShortcut)}, ${formatType(registry, definitions, valDef.lookupName || valDef.type, imports, withShortcut)}>`;
},
[TypeDefInfo.BTreeSet]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['BTreeSet']);
const valDef = typeDef.sub as TypeDef;
return `BTreeSet<${formatType(registry, definitions, valDef.lookupName || valDef.type, imports, withShortcut)}>`;
},
[TypeDefInfo.HashMap]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['HashMap']);
const [keyDef, valDef] = (typeDef.sub as TypeDef[]);
return `HashMap<${formatType(registry, definitions, keyDef.lookupName || keyDef.type, imports, withShortcut)}, ${formatType(registry, definitions, valDef.lookupName || valDef.type, imports, withShortcut)}>`;
},
[TypeDefInfo.Linkage]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['Linkage']);
const sub = (typeDef.sub as TypeDef);
return paramsNotation('Linkage', formatType(registry, definitions, sub.lookupName || sub.type, imports, withShortcut));
},
[TypeDefInfo.Result]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
setImports(definitions, imports, ['Result']);
const [okDef, errDef] = (typeDef.sub as TypeDef[]);
return `Result<${formatType(registry, definitions, okDef.lookupName || okDef.type, imports, withShortcut)}, ${formatType(registry, definitions, errDef.lookupName || errDef.type, imports, withShortcut)}>`;
}
};
/**
* Correctly format a given type
*/
/** @internal */
// eslint-disable-next-line @typescript-eslint/ban-types
export function formatType (definitions: Record<string, ModuleTypes>, type: string | String | TypeDef, imports: TypeImports): string {
export function formatType (registry: Registry, definitions: Record<string, ModuleTypes>, type: string | String | TypeDef, imports: TypeImports, withShortcut = false): string {
let typeDef: TypeDef;
if (isString(type)) {
@@ -184,7 +225,7 @@ export function formatType (definitions: Record<string, ModuleTypes>, type: stri
// If type is "unorthodox" (i.e. `{ something: any }` for an Enum input or `[a | b | c, d | e | f]` for a Tuple's similar types),
// we return it as-is
if (/(^{.+:.+})|^\([^,]+\)|^\(.+\)\[\]|^\[.+\]/.exec(_type) && !/\[\w+;\w+\]/.exec(_type)) {
if (withShortcut && /(^{.+:.+})|^\([^,]+\)|^\(.+\)\[\]|^\[.+\]/.exec(_type) && !/\[\w+;\w+\]/.exec(_type)) {
return _type;
}
@@ -195,112 +236,5 @@ export function formatType (definitions: Record<string, ModuleTypes>, type: stri
setImports(definitions, imports, [typeDef.type]);
// FIXME Swap to Record<TypeDefInfo, fn> to check all types
switch (typeDef.info) {
case TypeDefInfo.Compact: {
setImports(definitions, imports, ['Compact']);
return formatCompact(formatType(definitions, (typeDef.sub as TypeDef).type, imports));
}
case TypeDefInfo.DoNotConstruct: {
setImports(definitions, imports, ['DoNotConstruct']);
return formatDoNoConstruct();
}
case TypeDefInfo.Option: {
setImports(definitions, imports, ['Option']);
return formatOption(formatType(definitions, (typeDef.sub as TypeDef).type, imports));
}
case TypeDefInfo.Plain: {
return typeDef.type;
}
case TypeDefInfo.Struct: {
setImports(definitions, imports, ['Struct']);
return formatStruct(
((typeDef.sub as TypeDef[]).map(({ name, type }, index) => [
name || `unknown${index}`,
formatType(definitions, type, imports)
]))
);
}
case TypeDefInfo.Tuple: {
setImports(definitions, imports, ['ITuple']);
// `(a,b)` gets transformed into `ITuple<[a, b]>`
return formatTuple(
((typeDef.sub as TypeDef[]).map(({ type }) => formatType(definitions, type, imports)))
);
}
case TypeDefInfo.Vec: {
setImports(definitions, imports, ['Vec']);
return formatVec(formatType(definitions, (typeDef.sub as TypeDef).type, imports));
}
case TypeDefInfo.VecFixed: {
const type = (typeDef.sub as TypeDef).type;
if (type === 'u8') {
setImports(definitions, imports, ['U8aFixed']);
return 'U8aFixed';
}
setImports(definitions, imports, ['Vec']);
return formatVec(formatType(definitions, type, imports));
}
case TypeDefInfo.BTreeMap: {
setImports(definitions, imports, ['BTreeMap']);
const [keyDef, valDef] = (typeDef.sub as TypeDef[]);
return formatBTreeMap(formatType(definitions, keyDef.type, imports), formatType(definitions, valDef.type, imports));
}
case TypeDefInfo.BTreeSet: {
setImports(definitions, imports, ['BTreeSet']);
const valDef = typeDef.sub as TypeDef;
return formatBTreeSet(formatType(definitions, valDef.type, imports));
}
case TypeDefInfo.HashMap: {
setImports(definitions, imports, ['HashMap']);
const [keyDef, valDef] = (typeDef.sub as TypeDef[]);
return formatHashMap(formatType(definitions, keyDef.type, imports), formatType(definitions, valDef.type, imports));
}
case TypeDefInfo.Linkage: {
const type = (typeDef.sub as TypeDef).type;
setImports(definitions, imports, ['Linkage']);
return formatLinkage(formatType(definitions, type, imports));
}
case TypeDefInfo.Result: {
setImports(definitions, imports, ['Result']);
const [okDef, errorDef] = (typeDef.sub as TypeDef[]);
return formatResult(formatType(definitions, okDef.type, imports), formatType(definitions, errorDef.type, imports));
}
default: {
throw new Error(`Cannot format ${stringify(type)}`);
}
}
return formatters[typeDef.info](registry, typeDef, definitions, imports, withShortcut);
}
+2 -2
View File
@@ -64,10 +64,10 @@ export function setImports (allDefs: Record<string, ModuleTypes>, imports: TypeI
// TypeDef.sub is a `TypeDef | TypeDef[]`
if (Array.isArray(typeDef.sub)) {
typeDef.sub.forEach((subType) => setImports(allDefs, imports, [subType.type]));
typeDef.sub.forEach((subType) => setImports(allDefs, imports, [subType.lookupName || subType.type]));
} else if (typeDef.sub && (typeDef.info !== TypeDefInfo.VecFixed || typeDef.sub.type !== 'u8')) {
// typeDef.sub is a TypeDef in this case
setImports(allDefs, imports, [typeDef.sub.type]);
setImports(allDefs, imports, [typeDef.sub.lookupName || typeDef.sub.type]);
}
} else if (type.includes('[') && type.includes('|')) {
// We split the types (we already dod the check above, so safe-path should not be caught)
+5 -2
View File
@@ -9,5 +9,8 @@ export * from './imports';
export * from './initMeta';
export * from './register';
export const compareName = (a: { name: { toString(): string } }, b: { name: { toString(): string } }): number =>
a.name.toString().localeCompare(b.name.toString());
type Cmp = { name: { toString(): string } };
export function compareName (a: Cmp, b: Cmp): number {
return a.name.toString().localeCompare(b.name.toString());
}
+1 -1
View File
@@ -4,7 +4,7 @@
import type { ExtraTypes } from '../generate/types';
import { Metadata, TypeRegistry } from '@polkadot/types';
import staticData from '@polkadot/types/metadata/static';
import staticData from '@polkadot/types/metadata/static-substrate';
import { registerDefinitions } from './register';
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/types-known",
"version": "5.1.1",
"version": "5.3.2",
"type": "module",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
@@ -19,9 +19,9 @@
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/networks": "^7.0.2",
"@polkadot/types": "5.1.1",
"@polkadot/util": "^7.0.2"
"@babel/runtime": "^7.14.8",
"@polkadot/networks": "^7.1.1",
"@polkadot/types": "5.3.2",
"@polkadot/util": "^7.1.1"
}
}
+1
View File
@@ -14,6 +14,7 @@ import typesModules from './modules';
import typesSpec from './spec';
import upgrades from './upgrades';
export { knownOrigins } from './knownOrigins';
export { packageInfo } from './packageInfo';
// flatten a VersionedType[] into a Record<string, string>
+27
View File
@@ -0,0 +1,27 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
// We want predictive ordering (manually managed)
/* eslint-disable sort-keys */
// FIXME: Need some sort of solution for specifying these
// Since we don't have insight into the origin specification, we can only define what we know about
// in a pure Substrate/Polkadot implementation, any other custom origins won't be handled at all
export const knownOrigins: Record<string, string> = {
//
// (1) Defaults from Substrate
//
Council: 'CollectiveOrigin',
System: 'SystemOrigin',
TechnicalCommittee: 'CollectiveOrigin',
//
// (2) Defaults from Polkadot
//
Xcm: 'XcmOrigin',
XcmPallet: 'XcmOrigin',
//
// (3) Defaults from Acala
//
Authority: 'AuthorityOrigin',
GeneralCouncil: 'CollectiveOrigin'
};
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/types-known', version: '5.1.1' };
export const packageInfo = { name: '@polkadot/types-known', version: '5.3.2' };
+1 -1
View File
@@ -13,7 +13,7 @@ const upgrades: ChainUpgradesRaw = [
[2962294, 2012], [3240000, 2013], [3274408, 2015], [3323565, 2019], [3534175, 2022],
[3860281, 2023], [4143129, 2024], [4401242, 2025], [4841367, 2026], [5961600, 2027],
[6137912, 2028], [6561855, 2029], [7100891, 2030], [7468792, 9010], [7668600, 9030],
[7812476, 9040], [8010981, 9050], [8073833, 9070]
[7812476, 9040], [8010981, 9050], [8073833, 9070], [8555825, 9080]
];
export default upgrades;
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/types",
"version": "5.1.1",
"version": "5.3.2",
"type": "module",
"description": "Implementation of the Parity codec",
"main": "index.js",
@@ -19,13 +19,13 @@
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": {
"@babel/runtime": "^7.14.6",
"@polkadot/util": "^7.0.2",
"@polkadot/util-crypto": "^7.0.2",
"@babel/runtime": "^7.14.8",
"@polkadot/util": "^7.1.1",
"@polkadot/util-crypto": "^7.1.1",
"rxjs": "^7.2.0"
},
"devDependencies": {
"@polkadot/keyring": "^7.0.2",
"@polkadot/keyring": "^7.1.1",
"@types/bn.js": "^4.11.6",
"bn.js": "^4.11.9"
}
+84 -4
View File
@@ -10,7 +10,7 @@ import type { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
import type { AllowedSlots, BabeAuthorityWeight, BabeBlockWeight, BabeEpochConfiguration, BabeEquivocationProof, BabeWeight, EpochAuthorship, MaybeRandomness, MaybeVrf, NextConfigDescriptor, NextConfigDescriptorV1, Randomness, RawBabePreDigest, RawBabePreDigestCompat, RawBabePreDigestPrimary, RawBabePreDigestPrimaryTo159, RawBabePreDigestSecondaryPlain, RawBabePreDigestSecondaryTo159, RawBabePreDigestSecondaryVRF, RawBabePreDigestTo159, SlotNumber, VrfData, VrfOutput, VrfProof } from '@polkadot/types/interfaces/babe';
import type { AccountData, BalanceLock, BalanceLockTo212, BalanceStatus, Reasons, ReserveData, ReserveIdentifier, VestingSchedule, WithdrawReasons } from '@polkadot/types/interfaces/balances';
import type { BeefyCommitment, BeefyId, BeefyNextAuthoritySet, BeefyPayload, BeefySignedCommitment, MmrRootHash, ValidatorSetId } from '@polkadot/types/interfaces/beefy';
import type { BridgedBlockHash, BridgedBlockNumber, BridgedHeader, InitializationData } from '@polkadot/types/interfaces/bridges';
import type { BridgedBlockHash, BridgedBlockNumber, BridgedHeader, CallOrigin, ChainId, DeliveredMessages, DispatchFeePayment, InboundLaneData, InboundRelayer, InitializationData, LaneId, MessageData, MessageKey, MessageNonce, MessagesDeliveryProofOf, MessagesProofOf, OperatingMode, OutboundLaneData, OutboundMessageFee, OutboundPayload, Parameter, RelayerId, UnrewardedRelayer, UnrewardedRelayersState } from '@polkadot/types/interfaces/bridges';
import type { BlockHash } from '@polkadot/types/interfaces/chain';
import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { EthereumAddress, StatementKind } from '@polkadot/types/interfaces/claims';
@@ -25,14 +25,14 @@ import type { ApprovalFlag, DefunctVoter, Renouncing, SetIndex, Vote, VoteIndex,
import type { CreatedBlock, ImportedAux } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthBlock, EthBloom, EthCallRequest, EthFilter, EthFilterAddress, EthFilterChanges, EthFilterTopic, EthFilterTopicEntry, EthFilterTopicInner, EthHeader, EthLog, EthReceipt, EthRichBlock, EthRichHeader, EthStorageProof, EthSubKind, EthSubParams, EthSubResult, EthSyncInfo, EthSyncStatus, EthTransaction, EthTransactionAction, EthTransactionCondition, EthTransactionRequest, EthTransactionSignature, EthTransactionStatus, EthWork, EthereumAccountId, EthereumLookupSource, EthereumSignature } from '@polkadot/types/interfaces/eth';
import type { EvmAccount, EvmLog, EvmVicinity, ExitError, ExitFatal, ExitReason, ExitRevert, ExitSucceed } from '@polkadot/types/interfaces/evm';
import type { AnySignature, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV4, ExtrinsicSignature, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV4, ImmortalEra, MortalEra, MultiSignature, Signature, SignerPayload, Sr25519Signature } from '@polkadot/types/interfaces/extrinsics';
import type { AnySignature, EcdsaSignature, Ed25519Signature, Era, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV4, ExtrinsicSignature, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV4, ImmortalEra, MortalEra, MultiSignature, Signature, SignerPayload, Sr25519Signature } from '@polkadot/types/interfaces/extrinsics';
import type { AssetOptions, Owner, PermissionLatest, PermissionVersions, PermissionsV1 } from '@polkadot/types/interfaces/genericAsset';
import type { ActiveGilt, ActiveGiltsTotal, ActiveIndex, GiltBid } from '@polkadot/types/interfaces/gilt';
import type { AuthorityIndex, AuthorityList, AuthoritySet, AuthoritySetChange, AuthoritySetChanges, AuthorityWeight, DelayKind, DelayKindBest, EncodedFinalityProofs, ForkTreePendingChange, ForkTreePendingChangeNode, GrandpaCommit, GrandpaEquivocation, GrandpaEquivocationProof, GrandpaEquivocationValue, GrandpaJustification, GrandpaPrecommit, GrandpaPrevote, GrandpaSignedPrecommit, JustificationNotification, KeyOwnerProof, NextAuthority, PendingChange, PendingPause, PendingResume, Precommits, Prevotes, ReportedRoundStates, RoundState, SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import type { IdentityFields, IdentityInfo, IdentityInfoAdditional, IdentityJudgement, RegistrarIndex, RegistrarInfo, Registration, RegistrationJudgement } from '@polkadot/types/interfaces/identity';
import type { AuthIndex, AuthoritySignature, Heartbeat, HeartbeatTo244, OpaqueMultiaddr, OpaqueNetworkState, OpaquePeerId } from '@polkadot/types/interfaces/imOnline';
import type { CallIndex, LotteryConfig } from '@polkadot/types/interfaces/lottery';
import type { ErrorMetadataLatest, ErrorMetadataV10, ErrorMetadataV11, ErrorMetadataV12, ErrorMetadataV13, ErrorMetadataV9, EventMetadataLatest, EventMetadataV10, EventMetadataV11, EventMetadataV12, EventMetadataV13, EventMetadataV9, ExtrinsicMetadataLatest, ExtrinsicMetadataV11, ExtrinsicMetadataV12, ExtrinsicMetadataV13, ExtrinsicMetadataV14, FunctionArgumentMetadataLatest, FunctionArgumentMetadataV10, FunctionArgumentMetadataV11, FunctionArgumentMetadataV12, FunctionArgumentMetadataV13, FunctionArgumentMetadataV9, FunctionMetadataLatest, FunctionMetadataV10, FunctionMetadataV11, FunctionMetadataV12, FunctionMetadataV13, FunctionMetadataV9, MetadataAll, MetadataLatest, MetadataV10, MetadataV11, MetadataV12, MetadataV13, MetadataV14, MetadataV9, ModuleConstantMetadataLatest, ModuleConstantMetadataV10, ModuleConstantMetadataV11, ModuleConstantMetadataV12, ModuleConstantMetadataV13, ModuleConstantMetadataV9, ModuleMetadataLatest, ModuleMetadataV10, ModuleMetadataV11, ModuleMetadataV12, ModuleMetadataV13, ModuleMetadataV9, PalletCallMetadataLatest, PalletCallMetadataV14, PalletConstantMetadataLatest, PalletConstantMetadataV14, PalletErrorMetadataLatest, PalletErrorMetadataV14, PalletEventMetadataLatest, PalletEventMetadataV14, PalletMetadataLatest, PalletMetadataV14, PalletStorageMetadataLatest, PalletStorageMetadataV14, PortableRegistry, PortableType, SignedExtensionMetadataLatest, SignedExtensionMetadataV14, StorageEntryMetadataLatest, StorageEntryMetadataV10, StorageEntryMetadataV11, StorageEntryMetadataV12, StorageEntryMetadataV13, StorageEntryMetadataV14, StorageEntryMetadataV9, StorageEntryModifierLatest, StorageEntryModifierV10, StorageEntryModifierV11, StorageEntryModifierV12, StorageEntryModifierV13, StorageEntryModifierV14, StorageEntryModifierV9, StorageEntryTypeLatest, StorageEntryTypeV10, StorageEntryTypeV11, StorageEntryTypeV12, StorageEntryTypeV13, StorageEntryTypeV14, StorageEntryTypeV9, StorageHasher, StorageHasherV10, StorageHasherV11, StorageHasherV12, StorageHasherV13, StorageHasherV14, StorageHasherV9, StorageMetadataLatest, StorageMetadataV10, StorageMetadataV11, StorageMetadataV12, StorageMetadataV13, StorageMetadataV9 } from '@polkadot/types/interfaces/metadata';
import type { ErrorMetadataLatest, ErrorMetadataV10, ErrorMetadataV11, ErrorMetadataV12, ErrorMetadataV13, ErrorMetadataV14, ErrorMetadataV9, EventMetadataLatest, EventMetadataV10, EventMetadataV11, EventMetadataV12, EventMetadataV13, EventMetadataV14, EventMetadataV9, ExtrinsicMetadataLatest, ExtrinsicMetadataV11, ExtrinsicMetadataV12, ExtrinsicMetadataV13, ExtrinsicMetadataV14, FunctionArgumentMetadataLatest, FunctionArgumentMetadataV10, FunctionArgumentMetadataV11, FunctionArgumentMetadataV12, FunctionArgumentMetadataV13, FunctionArgumentMetadataV14, FunctionArgumentMetadataV9, FunctionMetadataLatest, FunctionMetadataV10, FunctionMetadataV11, FunctionMetadataV12, FunctionMetadataV13, FunctionMetadataV14, FunctionMetadataV9, MetadataAll, MetadataLatest, MetadataV10, MetadataV11, MetadataV12, MetadataV13, MetadataV14, MetadataV9, ModuleConstantMetadataLatest, ModuleConstantMetadataV10, ModuleConstantMetadataV11, ModuleConstantMetadataV12, ModuleConstantMetadataV13, ModuleConstantMetadataV9, ModuleMetadataLatest, ModuleMetadataV10, ModuleMetadataV11, ModuleMetadataV12, ModuleMetadataV13, ModuleMetadataV9, PalletCallMetadataLatest, PalletCallMetadataV14, PalletConstantMetadataLatest, PalletConstantMetadataV14, PalletErrorMetadataLatest, PalletErrorMetadataV14, PalletEventMetadataLatest, PalletEventMetadataV14, PalletMetadataLatest, PalletMetadataV14, PalletStorageMetadataLatest, PalletStorageMetadataV14, PortableRegistry, PortableType, SignedExtensionMetadataLatest, SignedExtensionMetadataV14, StorageEntryMetadataLatest, StorageEntryMetadataV10, StorageEntryMetadataV11, StorageEntryMetadataV12, StorageEntryMetadataV13, StorageEntryMetadataV14, StorageEntryMetadataV9, StorageEntryModifierLatest, StorageEntryModifierV10, StorageEntryModifierV11, StorageEntryModifierV12, StorageEntryModifierV13, StorageEntryModifierV14, StorageEntryModifierV9, StorageEntryTypeLatest, StorageEntryTypeV10, StorageEntryTypeV11, StorageEntryTypeV12, StorageEntryTypeV13, StorageEntryTypeV14, StorageEntryTypeV9, StorageHasher, StorageHasherV10, StorageHasherV11, StorageHasherV12, StorageHasherV13, StorageHasherV14, StorageHasherV9, StorageMetadataLatest, StorageMetadataV10, StorageMetadataV11, StorageMetadataV12, StorageMetadataV13, StorageMetadataV9 } from '@polkadot/types/interfaces/metadata';
import type { MmrLeafProof } from '@polkadot/types/interfaces/mmr';
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
import type { DeferredOffenceOf, Kind, OffenceDetails, Offender, OpaqueTimeSlot, ReportIdOf, Reporter } from '@polkadot/types/interfaces/offences';
@@ -48,7 +48,7 @@ import type { Si0Field, Si0LookupTypeId, Si0Path, Si0Type, Si0TypeDef, Si0TypeDe
import type { Period, Priority, SchedulePeriod, SchedulePriority, Scheduled, ScheduledTo254, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { BeefyKey, FullIdentification, IdentificationTuple, Keys, MembershipProof, SessionIndex, SessionKeys1, SessionKeys10, SessionKeys10B, SessionKeys2, SessionKeys3, SessionKeys4, SessionKeys5, SessionKeys6, SessionKeys6B, SessionKeys7, SessionKeys7B, SessionKeys8, SessionKeys8B, SessionKeys9, SessionKeys9B, ValidatorCount } from '@polkadot/types/interfaces/session';
import type { Bid, BidKind, SocietyJudgement, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import type { ActiveEraInfo, CompactAssignments, CompactAssignmentsTo257, CompactAssignmentsTo265, CompactAssignmentsWith16, CompactAssignmentsWith24, CompactScore, CompactScoreCompact, ElectionCompute, ElectionPhase, ElectionResult, ElectionScore, ElectionSize, ElectionStatus, EraIndex, EraPoints, EraRewardPoints, EraRewards, Exposure, ExtendedBalance, Forcing, IndividualExposure, KeyType, MomentOf, Nominations, NominatorIndex, NominatorIndexCompact, OffchainAccuracy, OffchainAccuracyCompact, PhragmenScore, Points, RawSolution, RawSolutionTo265, RawSolutionWith16, RawSolutionWith24, ReadySolution, RewardDestination, RewardPoint, RoundSnapshot, SeatHolder, SignedSubmission, SignedSubmissionOf, SlashJournalEntry, SlashingSpans, SlashingSpansTo204, SolutionOrSnapshotSize, SolutionSupport, SolutionSupports, SpanIndex, SpanRecord, StakingLedger, StakingLedgerTo223, StakingLedgerTo240, SubmissionIndicesOf, Supports, UnappliedSlash, UnappliedSlashOther, UnlockChunk, ValidatorIndex, ValidatorIndexCompact, ValidatorPrefs, ValidatorPrefsTo145, ValidatorPrefsTo196, ValidatorPrefsWithBlocked, ValidatorPrefsWithCommission, VoteWeight, Voter } from '@polkadot/types/interfaces/staking';
import type { ActiveEraInfo, CompactAssignments, CompactAssignmentsTo257, CompactAssignmentsTo265, CompactAssignmentsWith16, CompactAssignmentsWith24, CompactScore, CompactScoreCompact, ElectionCompute, ElectionPhase, ElectionResult, ElectionScore, ElectionSize, ElectionStatus, EraIndex, EraPoints, EraRewardPoints, EraRewards, Exposure, ExtendedBalance, Forcing, IndividualExposure, KeyType, MomentOf, Nominations, NominatorIndex, NominatorIndexCompact, OffchainAccuracy, OffchainAccuracyCompact, PhragmenScore, Points, RawSolution, RawSolutionTo265, RawSolutionWith16, RawSolutionWith24, ReadySolution, RewardDestination, RewardPoint, RoundSnapshot, SeatHolder, SignedSubmission, SignedSubmissionOf, SignedSubmissionTo276, SlashJournalEntry, SlashingSpans, SlashingSpansTo204, SolutionOrSnapshotSize, SolutionSupport, SolutionSupports, SpanIndex, SpanRecord, StakingLedger, StakingLedgerTo223, StakingLedgerTo240, SubmissionIndicesOf, Supports, UnappliedSlash, UnappliedSlashOther, UnlockChunk, ValidatorIndex, ValidatorIndexCompact, ValidatorPrefs, ValidatorPrefsTo145, ValidatorPrefsTo196, ValidatorPrefsWithBlocked, ValidatorPrefsWithCommission, VoteWeight, Voter } from '@polkadot/types/interfaces/staking';
import type { ApiId, BlockTrace, BlockTraceEvent, BlockTraceEventData, BlockTraceSpan, KeyValueOption, ReadProof, RuntimeVersion, RuntimeVersionApi, RuntimeVersionPartial, StorageChangeSet, TraceBlockResponse, TraceError } from '@polkadot/types/interfaces/state';
import type { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
import type { AccountInfo, AccountInfoWithDualRefCount, AccountInfoWithProviders, AccountInfoWithRefCount, AccountInfoWithRefCountU8, AccountInfoWithTripleRefCount, ApplyExtrinsicResult, ArithmeticError, BlockLength, BlockWeights, ChainProperties, ChainType, ConsumedWeight, DigestOf, DispatchClass, DispatchError, DispatchErrorModule, DispatchErrorTo198, DispatchInfo, DispatchInfoTo190, DispatchInfoTo244, DispatchOutcome, DispatchResult, DispatchResultOf, DispatchResultTo198, Event, EventId, EventIndex, EventRecord, Health, InvalidTransaction, Key, LastRuntimeUpgradeInfo, NetworkState, NetworkStatePeerset, NetworkStatePeersetInfo, NodeRole, NotConnectedPeer, Peer, PeerEndpoint, PeerEndpointAddr, PeerInfo, PeerPing, PerDispatchClassU32, PerDispatchClassWeight, PerDispatchClassWeightsPerClass, Phase, RawOrigin, RefCount, RefCountTo259, SyncState, SystemOrigin, TokenError, TransactionValidityError, UnknownTransaction, WeightPerClass } from '@polkadot/types/interfaces/system';
@@ -98,10 +98,12 @@ declare module '@polkadot/types/types/registry' {
'Compact<LeasePeriod>': Compact<LeasePeriod>;
'Compact<LeasePeriodOf>': Compact<LeasePeriodOf>;
'Compact<MemberCount>': Compact<MemberCount>;
'Compact<MessageNonce>': Compact<MessageNonce>;
'Compact<Moment>': Compact<Moment>;
'Compact<MomentOf>': Compact<MomentOf>;
'Compact<NominatorIndex>': Compact<NominatorIndex>;
'Compact<OffchainAccuracy>': Compact<OffchainAccuracy>;
'Compact<OutboundMessageFee>': Compact<OutboundMessageFee>;
'Compact<OverweightIndex>': Compact<OverweightIndex>;
'Compact<PageCounter>': Compact<PageCounter>;
'Compact<ParaId>': Compact<ParaId>;
@@ -274,12 +276,14 @@ declare module '@polkadot/types/types/registry' {
'Option<CallHash>': Option<CallHash>;
'Option<CallHashOf>': Option<CallHashOf>;
'Option<CallIndex>': Option<CallIndex>;
'Option<CallOrigin>': Option<CallOrigin>;
'Option<CandidateCommitments>': Option<CandidateCommitments>;
'Option<CandidateDescriptor>': Option<CandidateDescriptor>;
'Option<CandidateHash>': Option<CandidateHash>;
'Option<CandidateInfo>': Option<CandidateInfo>;
'Option<CandidatePendingAvailability>': Option<CandidatePendingAvailability>;
'Option<CandidateReceipt>': Option<CandidateReceipt>;
'Option<ChainId>': Option<ChainId>;
'Option<ChainProperties>': Option<ChainProperties>;
'Option<ChainType>': Option<ChainType>;
'Option<ChangesTrieConfiguration>': Option<ChangesTrieConfiguration>;
@@ -353,6 +357,7 @@ declare module '@polkadot/types/types/registry' {
'Option<DelayKindBest>': Option<DelayKindBest>;
'Option<Delegations>': Option<Delegations>;
'Option<DeletedContract>': Option<DeletedContract>;
'Option<DeliveredMessages>': Option<DeliveredMessages>;
'Option<DepositBalance>': Option<DepositBalance>;
'Option<DepositBalanceOf>': Option<DepositBalanceOf>;
'Option<DestroyWitness>': Option<DestroyWitness>;
@@ -363,6 +368,7 @@ declare module '@polkadot/types/types/registry' {
'Option<DispatchError>': Option<DispatchError>;
'Option<DispatchErrorModule>': Option<DispatchErrorModule>;
'Option<DispatchErrorTo198>': Option<DispatchErrorTo198>;
'Option<DispatchFeePayment>': Option<DispatchFeePayment>;
'Option<DispatchInfo>': Option<DispatchInfo>;
'Option<DispatchInfoTo190>': Option<DispatchInfoTo190>;
'Option<DispatchInfoTo244>': Option<DispatchInfoTo244>;
@@ -386,6 +392,7 @@ declare module '@polkadot/types/types/registry' {
'Option<EncodedFinalityProofs>': Option<EncodedFinalityProofs>;
'Option<EncodedJustification>': Option<EncodedJustification>;
'Option<EpochAuthorship>': Option<EpochAuthorship>;
'Option<Era>': Option<Era>;
'Option<EraIndex>': Option<EraIndex>;
'Option<EraPoints>': Option<EraPoints>;
'Option<EraRewardPoints>': Option<EraRewardPoints>;
@@ -395,6 +402,7 @@ declare module '@polkadot/types/types/registry' {
'Option<ErrorMetadataV11>': Option<ErrorMetadataV11>;
'Option<ErrorMetadataV12>': Option<ErrorMetadataV12>;
'Option<ErrorMetadataV13>': Option<ErrorMetadataV13>;
'Option<ErrorMetadataV14>': Option<ErrorMetadataV14>;
'Option<ErrorMetadataV9>': Option<ErrorMetadataV9>;
'Option<EthAccount>': Option<EthAccount>;
'Option<EthBlock>': Option<EthBlock>;
@@ -436,6 +444,7 @@ declare module '@polkadot/types/types/registry' {
'Option<EventMetadataV11>': Option<EventMetadataV11>;
'Option<EventMetadataV12>': Option<EventMetadataV12>;
'Option<EventMetadataV13>': Option<EventMetadataV13>;
'Option<EventMetadataV14>': Option<EventMetadataV14>;
'Option<EventMetadataV9>': Option<EventMetadataV9>;
'Option<EventRecord>': Option<EventRecord>;
'Option<EvmAccount>': Option<EvmAccount>;
@@ -483,12 +492,14 @@ declare module '@polkadot/types/types/registry' {
'Option<FunctionArgumentMetadataV11>': Option<FunctionArgumentMetadataV11>;
'Option<FunctionArgumentMetadataV12>': Option<FunctionArgumentMetadataV12>;
'Option<FunctionArgumentMetadataV13>': Option<FunctionArgumentMetadataV13>;
'Option<FunctionArgumentMetadataV14>': Option<FunctionArgumentMetadataV14>;
'Option<FunctionArgumentMetadataV9>': Option<FunctionArgumentMetadataV9>;
'Option<FunctionMetadataLatest>': Option<FunctionMetadataLatest>;
'Option<FunctionMetadataV10>': Option<FunctionMetadataV10>;
'Option<FunctionMetadataV11>': Option<FunctionMetadataV11>;
'Option<FunctionMetadataV12>': Option<FunctionMetadataV12>;
'Option<FunctionMetadataV13>': Option<FunctionMetadataV13>;
'Option<FunctionMetadataV14>': Option<FunctionMetadataV14>;
'Option<FunctionMetadataV9>': Option<FunctionMetadataV9>;
'Option<FundIndex>': Option<FundIndex>;
'Option<FundInfo>': Option<FundInfo>;
@@ -549,6 +560,8 @@ declare module '@polkadot/types/types/registry' {
'Option<InboundDownwardMessage>': Option<InboundDownwardMessage>;
'Option<InboundHrmpMessage>': Option<InboundHrmpMessage>;
'Option<InboundHrmpMessages>': Option<InboundHrmpMessages>;
'Option<InboundLaneData>': Option<InboundLaneData>;
'Option<InboundRelayer>': Option<InboundRelayer>;
'Option<InboundStatus>': Option<InboundStatus>;
'Option<IncludedBlocks>': Option<IncludedBlocks>;
'Option<InclusionFee>': Option<InclusionFee>;
@@ -580,6 +593,7 @@ declare module '@polkadot/types/types/registry' {
'Option<KeyValue>': Option<KeyValue>;
'Option<KeyValueOption>': Option<KeyValueOption>;
'Option<Kind>': Option<Kind>;
'Option<LaneId>': Option<LaneId>;
'Option<LastContribution>': Option<LastContribution>;
'Option<LastRuntimeUpgradeInfo>': Option<LastRuntimeUpgradeInfo>;
'Option<LeasePeriod>': Option<LeasePeriod>;
@@ -595,9 +609,14 @@ declare module '@polkadot/types/types/registry' {
'Option<MaybeVrf>': Option<MaybeVrf>;
'Option<MemberCount>': Option<MemberCount>;
'Option<MembershipProof>': Option<MembershipProof>;
'Option<MessageData>': Option<MessageData>;
'Option<MessageId>': Option<MessageId>;
'Option<MessageIngestionType>': Option<MessageIngestionType>;
'Option<MessageKey>': Option<MessageKey>;
'Option<MessageNonce>': Option<MessageNonce>;
'Option<MessageQueueChain>': Option<MessageQueueChain>;
'Option<MessagesDeliveryProofOf>': Option<MessagesDeliveryProofOf>;
'Option<MessagesProofOf>': Option<MessagesProofOf>;
'Option<MessagingStateSnapshot>': Option<MessagingStateSnapshot>;
'Option<MessagingStateSnapshotEgressEntry>': Option<MessagingStateSnapshotEgressEntry>;
'Option<MetadataAll>': Option<MetadataAll>;
@@ -666,9 +685,13 @@ declare module '@polkadot/types/types/registry' {
'Option<OpenTipFinderTo225>': Option<OpenTipFinderTo225>;
'Option<OpenTipTip>': Option<OpenTipTip>;
'Option<OpenTipTo225>': Option<OpenTipTo225>;
'Option<OperatingMode>': Option<OperatingMode>;
'Option<Origin>': Option<Origin>;
'Option<OriginCaller>': Option<OriginCaller>;
'Option<OutboundHrmpMessage>': Option<OutboundHrmpMessage>;
'Option<OutboundLaneData>': Option<OutboundLaneData>;
'Option<OutboundMessageFee>': Option<OutboundMessageFee>;
'Option<OutboundPayload>': Option<OutboundPayload>;
'Option<OutboundStatus>': Option<OutboundStatus>;
'Option<Outcome>': Option<Outcome>;
'Option<OverweightIndex>': Option<OverweightIndex>;
@@ -698,6 +721,7 @@ declare module '@polkadot/types/types/registry' {
'Option<ParaId>': Option<ParaId>;
'Option<ParaInfo>': Option<ParaInfo>;
'Option<ParaLifecycle>': Option<ParaLifecycle>;
'Option<Parameter>': Option<Parameter>;
'Option<ParaPastCodeMeta>': Option<ParaPastCodeMeta>;
'Option<ParaScheduling>': Option<ParaScheduling>;
'Option<ParathreadClaim>': Option<ParathreadClaim>;
@@ -788,6 +812,7 @@ declare module '@polkadot/types/types/registry' {
'Option<RelayBlockNumber>': Option<RelayBlockNumber>;
'Option<RelayChainBlockNumber>': Option<RelayChainBlockNumber>;
'Option<RelayChainHash>': Option<RelayChainHash>;
'Option<RelayerId>': Option<RelayerId>;
'Option<RelayHash>': Option<RelayHash>;
'Option<Releases>': Option<Releases>;
'Option<Remark>': Option<Remark>;
@@ -871,6 +896,7 @@ declare module '@polkadot/types/types/registry' {
'Option<SignedExtensionMetadataV14>': Option<SignedExtensionMetadataV14>;
'Option<SignedSubmission>': Option<SignedSubmission>;
'Option<SignedSubmissionOf>': Option<SignedSubmissionOf>;
'Option<SignedSubmissionTo276>': Option<SignedSubmissionTo276>;
'Option<SignerPayload>': Option<SignerPayload>;
'Option<SigningContext>': Option<SigningContext>;
'Option<SiLookupTypeId>': Option<SiLookupTypeId>;
@@ -991,6 +1017,8 @@ declare module '@polkadot/types/types/registry' {
'Option<UncleEntryItem>': Option<UncleEntryItem>;
'Option<UnknownTransaction>': Option<UnknownTransaction>;
'Option<UnlockChunk>': Option<UnlockChunk>;
'Option<UnrewardedRelayer>': Option<UnrewardedRelayer>;
'Option<UnrewardedRelayersState>': Option<UnrewardedRelayersState>;
'Option<UpwardMessage>': Option<UpwardMessage>;
'Option<usize>': Option<usize>;
'Option<USize>': Option<USize>;
@@ -1187,12 +1215,14 @@ declare module '@polkadot/types/types/registry' {
'Vec<CallHash>': Vec<CallHash>;
'Vec<CallHashOf>': Vec<CallHashOf>;
'Vec<CallIndex>': Vec<CallIndex>;
'Vec<CallOrigin>': Vec<CallOrigin>;
'Vec<CandidateCommitments>': Vec<CandidateCommitments>;
'Vec<CandidateDescriptor>': Vec<CandidateDescriptor>;
'Vec<CandidateHash>': Vec<CandidateHash>;
'Vec<CandidateInfo>': Vec<CandidateInfo>;
'Vec<CandidatePendingAvailability>': Vec<CandidatePendingAvailability>;
'Vec<CandidateReceipt>': Vec<CandidateReceipt>;
'Vec<ChainId>': Vec<ChainId>;
'Vec<ChainProperties>': Vec<ChainProperties>;
'Vec<ChainType>': Vec<ChainType>;
'Vec<ChangesTrieConfiguration>': Vec<ChangesTrieConfiguration>;
@@ -1266,6 +1296,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<DelayKindBest>': Vec<DelayKindBest>;
'Vec<Delegations>': Vec<Delegations>;
'Vec<DeletedContract>': Vec<DeletedContract>;
'Vec<DeliveredMessages>': Vec<DeliveredMessages>;
'Vec<DepositBalance>': Vec<DepositBalance>;
'Vec<DepositBalanceOf>': Vec<DepositBalanceOf>;
'Vec<DestroyWitness>': Vec<DestroyWitness>;
@@ -1276,6 +1307,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<DispatchError>': Vec<DispatchError>;
'Vec<DispatchErrorModule>': Vec<DispatchErrorModule>;
'Vec<DispatchErrorTo198>': Vec<DispatchErrorTo198>;
'Vec<DispatchFeePayment>': Vec<DispatchFeePayment>;
'Vec<DispatchInfo>': Vec<DispatchInfo>;
'Vec<DispatchInfoTo190>': Vec<DispatchInfoTo190>;
'Vec<DispatchInfoTo244>': Vec<DispatchInfoTo244>;
@@ -1299,6 +1331,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<EncodedFinalityProofs>': Vec<EncodedFinalityProofs>;
'Vec<EncodedJustification>': Vec<EncodedJustification>;
'Vec<EpochAuthorship>': Vec<EpochAuthorship>;
'Vec<Era>': Vec<Era>;
'Vec<EraIndex>': Vec<EraIndex>;
'Vec<EraPoints>': Vec<EraPoints>;
'Vec<EraRewardPoints>': Vec<EraRewardPoints>;
@@ -1308,6 +1341,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<ErrorMetadataV11>': Vec<ErrorMetadataV11>;
'Vec<ErrorMetadataV12>': Vec<ErrorMetadataV12>;
'Vec<ErrorMetadataV13>': Vec<ErrorMetadataV13>;
'Vec<ErrorMetadataV14>': Vec<ErrorMetadataV14>;
'Vec<ErrorMetadataV9>': Vec<ErrorMetadataV9>;
'Vec<EthAccount>': Vec<EthAccount>;
'Vec<EthBlock>': Vec<EthBlock>;
@@ -1349,6 +1383,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<EventMetadataV11>': Vec<EventMetadataV11>;
'Vec<EventMetadataV12>': Vec<EventMetadataV12>;
'Vec<EventMetadataV13>': Vec<EventMetadataV13>;
'Vec<EventMetadataV14>': Vec<EventMetadataV14>;
'Vec<EventMetadataV9>': Vec<EventMetadataV9>;
'Vec<EventRecord>': Vec<EventRecord>;
'Vec<EvmAccount>': Vec<EvmAccount>;
@@ -1396,12 +1431,14 @@ declare module '@polkadot/types/types/registry' {
'Vec<FunctionArgumentMetadataV11>': Vec<FunctionArgumentMetadataV11>;
'Vec<FunctionArgumentMetadataV12>': Vec<FunctionArgumentMetadataV12>;
'Vec<FunctionArgumentMetadataV13>': Vec<FunctionArgumentMetadataV13>;
'Vec<FunctionArgumentMetadataV14>': Vec<FunctionArgumentMetadataV14>;
'Vec<FunctionArgumentMetadataV9>': Vec<FunctionArgumentMetadataV9>;
'Vec<FunctionMetadataLatest>': Vec<FunctionMetadataLatest>;
'Vec<FunctionMetadataV10>': Vec<FunctionMetadataV10>;
'Vec<FunctionMetadataV11>': Vec<FunctionMetadataV11>;
'Vec<FunctionMetadataV12>': Vec<FunctionMetadataV12>;
'Vec<FunctionMetadataV13>': Vec<FunctionMetadataV13>;
'Vec<FunctionMetadataV14>': Vec<FunctionMetadataV14>;
'Vec<FunctionMetadataV9>': Vec<FunctionMetadataV9>;
'Vec<FundIndex>': Vec<FundIndex>;
'Vec<FundInfo>': Vec<FundInfo>;
@@ -1462,6 +1499,8 @@ declare module '@polkadot/types/types/registry' {
'Vec<InboundDownwardMessage>': Vec<InboundDownwardMessage>;
'Vec<InboundHrmpMessage>': Vec<InboundHrmpMessage>;
'Vec<InboundHrmpMessages>': Vec<InboundHrmpMessages>;
'Vec<InboundLaneData>': Vec<InboundLaneData>;
'Vec<InboundRelayer>': Vec<InboundRelayer>;
'Vec<InboundStatus>': Vec<InboundStatus>;
'Vec<IncludedBlocks>': Vec<IncludedBlocks>;
'Vec<InclusionFee>': Vec<InclusionFee>;
@@ -1493,6 +1532,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<KeyValue>': Vec<KeyValue>;
'Vec<KeyValueOption>': Vec<KeyValueOption>;
'Vec<Kind>': Vec<Kind>;
'Vec<LaneId>': Vec<LaneId>;
'Vec<LastContribution>': Vec<LastContribution>;
'Vec<LastRuntimeUpgradeInfo>': Vec<LastRuntimeUpgradeInfo>;
'Vec<LeasePeriod>': Vec<LeasePeriod>;
@@ -1508,9 +1548,14 @@ declare module '@polkadot/types/types/registry' {
'Vec<MaybeVrf>': Vec<MaybeVrf>;
'Vec<MemberCount>': Vec<MemberCount>;
'Vec<MembershipProof>': Vec<MembershipProof>;
'Vec<MessageData>': Vec<MessageData>;
'Vec<MessageId>': Vec<MessageId>;
'Vec<MessageIngestionType>': Vec<MessageIngestionType>;
'Vec<MessageKey>': Vec<MessageKey>;
'Vec<MessageNonce>': Vec<MessageNonce>;
'Vec<MessageQueueChain>': Vec<MessageQueueChain>;
'Vec<MessagesDeliveryProofOf>': Vec<MessagesDeliveryProofOf>;
'Vec<MessagesProofOf>': Vec<MessagesProofOf>;
'Vec<MessagingStateSnapshot>': Vec<MessagingStateSnapshot>;
'Vec<MessagingStateSnapshotEgressEntry>': Vec<MessagingStateSnapshotEgressEntry>;
'Vec<MetadataAll>': Vec<MetadataAll>;
@@ -1579,9 +1624,13 @@ declare module '@polkadot/types/types/registry' {
'Vec<OpenTipFinderTo225>': Vec<OpenTipFinderTo225>;
'Vec<OpenTipTip>': Vec<OpenTipTip>;
'Vec<OpenTipTo225>': Vec<OpenTipTo225>;
'Vec<OperatingMode>': Vec<OperatingMode>;
'Vec<Origin>': Vec<Origin>;
'Vec<OriginCaller>': Vec<OriginCaller>;
'Vec<OutboundHrmpMessage>': Vec<OutboundHrmpMessage>;
'Vec<OutboundLaneData>': Vec<OutboundLaneData>;
'Vec<OutboundMessageFee>': Vec<OutboundMessageFee>;
'Vec<OutboundPayload>': Vec<OutboundPayload>;
'Vec<OutboundStatus>': Vec<OutboundStatus>;
'Vec<Outcome>': Vec<Outcome>;
'Vec<OverweightIndex>': Vec<OverweightIndex>;
@@ -1611,6 +1660,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<ParaId>': Vec<ParaId>;
'Vec<ParaInfo>': Vec<ParaInfo>;
'Vec<ParaLifecycle>': Vec<ParaLifecycle>;
'Vec<Parameter>': Vec<Parameter>;
'Vec<ParaPastCodeMeta>': Vec<ParaPastCodeMeta>;
'Vec<ParaScheduling>': Vec<ParaScheduling>;
'Vec<ParathreadClaim>': Vec<ParathreadClaim>;
@@ -1701,6 +1751,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<RelayBlockNumber>': Vec<RelayBlockNumber>;
'Vec<RelayChainBlockNumber>': Vec<RelayChainBlockNumber>;
'Vec<RelayChainHash>': Vec<RelayChainHash>;
'Vec<RelayerId>': Vec<RelayerId>;
'Vec<RelayHash>': Vec<RelayHash>;
'Vec<Releases>': Vec<Releases>;
'Vec<Remark>': Vec<Remark>;
@@ -1784,6 +1835,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<SignedExtensionMetadataV14>': Vec<SignedExtensionMetadataV14>;
'Vec<SignedSubmission>': Vec<SignedSubmission>;
'Vec<SignedSubmissionOf>': Vec<SignedSubmissionOf>;
'Vec<SignedSubmissionTo276>': Vec<SignedSubmissionTo276>;
'Vec<SignerPayload>': Vec<SignerPayload>;
'Vec<SigningContext>': Vec<SigningContext>;
'Vec<SiLookupTypeId>': Vec<SiLookupTypeId>;
@@ -1904,6 +1956,8 @@ declare module '@polkadot/types/types/registry' {
'Vec<UncleEntryItem>': Vec<UncleEntryItem>;
'Vec<UnknownTransaction>': Vec<UnknownTransaction>;
'Vec<UnlockChunk>': Vec<UnlockChunk>;
'Vec<UnrewardedRelayer>': Vec<UnrewardedRelayer>;
'Vec<UnrewardedRelayersState>': Vec<UnrewardedRelayersState>;
'Vec<UpwardMessage>': Vec<UpwardMessage>;
'Vec<usize>': Vec<usize>;
'Vec<USize>': Vec<USize>;
@@ -2100,12 +2154,14 @@ declare module '@polkadot/types/types/registry' {
CallHash: CallHash;
CallHashOf: CallHashOf;
CallIndex: CallIndex;
CallOrigin: CallOrigin;
CandidateCommitments: CandidateCommitments;
CandidateDescriptor: CandidateDescriptor;
CandidateHash: CandidateHash;
CandidateInfo: CandidateInfo;
CandidatePendingAvailability: CandidatePendingAvailability;
CandidateReceipt: CandidateReceipt;
ChainId: ChainId;
ChainProperties: ChainProperties;
ChainType: ChainType;
ChangesTrieConfiguration: ChangesTrieConfiguration;
@@ -2179,6 +2235,7 @@ declare module '@polkadot/types/types/registry' {
DelayKindBest: DelayKindBest;
Delegations: Delegations;
DeletedContract: DeletedContract;
DeliveredMessages: DeliveredMessages;
DepositBalance: DepositBalance;
DepositBalanceOf: DepositBalanceOf;
DestroyWitness: DestroyWitness;
@@ -2189,6 +2246,7 @@ declare module '@polkadot/types/types/registry' {
DispatchError: DispatchError;
DispatchErrorModule: DispatchErrorModule;
DispatchErrorTo198: DispatchErrorTo198;
DispatchFeePayment: DispatchFeePayment;
DispatchInfo: DispatchInfo;
DispatchInfoTo190: DispatchInfoTo190;
DispatchInfoTo244: DispatchInfoTo244;
@@ -2212,6 +2270,7 @@ declare module '@polkadot/types/types/registry' {
EncodedFinalityProofs: EncodedFinalityProofs;
EncodedJustification: EncodedJustification;
EpochAuthorship: EpochAuthorship;
Era: Era;
EraIndex: EraIndex;
EraPoints: EraPoints;
EraRewardPoints: EraRewardPoints;
@@ -2221,6 +2280,7 @@ declare module '@polkadot/types/types/registry' {
ErrorMetadataV11: ErrorMetadataV11;
ErrorMetadataV12: ErrorMetadataV12;
ErrorMetadataV13: ErrorMetadataV13;
ErrorMetadataV14: ErrorMetadataV14;
ErrorMetadataV9: ErrorMetadataV9;
EthAccount: EthAccount;
EthBlock: EthBlock;
@@ -2262,6 +2322,7 @@ declare module '@polkadot/types/types/registry' {
EventMetadataV11: EventMetadataV11;
EventMetadataV12: EventMetadataV12;
EventMetadataV13: EventMetadataV13;
EventMetadataV14: EventMetadataV14;
EventMetadataV9: EventMetadataV9;
EventRecord: EventRecord;
EvmAccount: EvmAccount;
@@ -2309,12 +2370,14 @@ declare module '@polkadot/types/types/registry' {
FunctionArgumentMetadataV11: FunctionArgumentMetadataV11;
FunctionArgumentMetadataV12: FunctionArgumentMetadataV12;
FunctionArgumentMetadataV13: FunctionArgumentMetadataV13;
FunctionArgumentMetadataV14: FunctionArgumentMetadataV14;
FunctionArgumentMetadataV9: FunctionArgumentMetadataV9;
FunctionMetadataLatest: FunctionMetadataLatest;
FunctionMetadataV10: FunctionMetadataV10;
FunctionMetadataV11: FunctionMetadataV11;
FunctionMetadataV12: FunctionMetadataV12;
FunctionMetadataV13: FunctionMetadataV13;
FunctionMetadataV14: FunctionMetadataV14;
FunctionMetadataV9: FunctionMetadataV9;
FundIndex: FundIndex;
FundInfo: FundInfo;
@@ -2375,6 +2438,8 @@ declare module '@polkadot/types/types/registry' {
InboundDownwardMessage: InboundDownwardMessage;
InboundHrmpMessage: InboundHrmpMessage;
InboundHrmpMessages: InboundHrmpMessages;
InboundLaneData: InboundLaneData;
InboundRelayer: InboundRelayer;
InboundStatus: InboundStatus;
IncludedBlocks: IncludedBlocks;
InclusionFee: InclusionFee;
@@ -2406,6 +2471,7 @@ declare module '@polkadot/types/types/registry' {
KeyValue: KeyValue;
KeyValueOption: KeyValueOption;
Kind: Kind;
LaneId: LaneId;
LastContribution: LastContribution;
LastRuntimeUpgradeInfo: LastRuntimeUpgradeInfo;
LeasePeriod: LeasePeriod;
@@ -2421,9 +2487,14 @@ declare module '@polkadot/types/types/registry' {
MaybeVrf: MaybeVrf;
MemberCount: MemberCount;
MembershipProof: MembershipProof;
MessageData: MessageData;
MessageId: MessageId;
MessageIngestionType: MessageIngestionType;
MessageKey: MessageKey;
MessageNonce: MessageNonce;
MessageQueueChain: MessageQueueChain;
MessagesDeliveryProofOf: MessagesDeliveryProofOf;
MessagesProofOf: MessagesProofOf;
MessagingStateSnapshot: MessagingStateSnapshot;
MessagingStateSnapshotEgressEntry: MessagingStateSnapshotEgressEntry;
MetadataAll: MetadataAll;
@@ -2492,9 +2563,13 @@ declare module '@polkadot/types/types/registry' {
OpenTipFinderTo225: OpenTipFinderTo225;
OpenTipTip: OpenTipTip;
OpenTipTo225: OpenTipTo225;
OperatingMode: OperatingMode;
Origin: Origin;
OriginCaller: OriginCaller;
OutboundHrmpMessage: OutboundHrmpMessage;
OutboundLaneData: OutboundLaneData;
OutboundMessageFee: OutboundMessageFee;
OutboundPayload: OutboundPayload;
OutboundStatus: OutboundStatus;
Outcome: Outcome;
OverweightIndex: OverweightIndex;
@@ -2524,6 +2599,7 @@ declare module '@polkadot/types/types/registry' {
ParaId: ParaId;
ParaInfo: ParaInfo;
ParaLifecycle: ParaLifecycle;
Parameter: Parameter;
ParaPastCodeMeta: ParaPastCodeMeta;
ParaScheduling: ParaScheduling;
ParathreadClaim: ParathreadClaim;
@@ -2614,6 +2690,7 @@ declare module '@polkadot/types/types/registry' {
RelayBlockNumber: RelayBlockNumber;
RelayChainBlockNumber: RelayChainBlockNumber;
RelayChainHash: RelayChainHash;
RelayerId: RelayerId;
RelayHash: RelayHash;
Releases: Releases;
Remark: Remark;
@@ -2697,6 +2774,7 @@ declare module '@polkadot/types/types/registry' {
SignedExtensionMetadataV14: SignedExtensionMetadataV14;
SignedSubmission: SignedSubmission;
SignedSubmissionOf: SignedSubmissionOf;
SignedSubmissionTo276: SignedSubmissionTo276;
SignerPayload: SignerPayload;
SigningContext: SigningContext;
SiLookupTypeId: SiLookupTypeId;
@@ -2817,6 +2895,8 @@ declare module '@polkadot/types/types/registry' {
UncleEntryItem: UncleEntryItem;
UnknownTransaction: UnknownTransaction;
UnlockChunk: UnlockChunk;
UnrewardedRelayer: UnrewardedRelayer;
UnrewardedRelayersState: UnrewardedRelayersState;
UpwardMessage: UpwardMessage;
usize: usize;
USize: USize;
+1 -1
View File
@@ -6,7 +6,7 @@ import type { AnyJson, Codec, Registry } from '../types';
import { compactToU8a, u8aConcat, u8aToHex } from '@polkadot/util';
import { compareArray } from './utils';
import { compareArray } from './utils/compareArray';
/**
* @name AbstractArray
+130 -2
View File
@@ -2,15 +2,52 @@
// SPDX-License-Identifier: Apache-2.0
import { TypeRegistry } from '../create';
import { Text, U32 } from '../primitive';
import { BTreeMap, Struct } from '.';
import { I32, Text, U32 } from '../primitive';
import { Constructor } from '../types';
import { ITuple } from '../types/interfaces';
import { BTreeMap, Enum, Struct, Tuple } from '.';
const registry = new TypeRegistry();
class U32TextTuple extends (Tuple.with([U32, Text]) as unknown as Constructor<ITuple<[U32, Text]>>) {}
// Reason: We purposefully want `text` to be the first key of the struct and take priority during sorting
// eslint-disable-next-line sort-keys
class MockStruct extends Struct.with({ text: Text, int: I32 }) {}
class MockEnum extends Enum.with({
Key1: MockStruct,
Key2: MockStruct,
Key3: U32TextTuple
}) {}
const mockU32TextMap = new Map<Text, U32>();
const mockU32TupleMap = new Map<ITuple<[U32, Text]>, U32>();
const mockU32I32Map = new Map<I32, U32>();
const mockU32StructMap = new Map<MockStruct, U32>();
const mockU32EnumMap = new Map<MockEnum, U32>();
mockU32TextMap.set(new Text(registry, 'bazzing'), new U32(registry, 69));
mockU32TupleMap.set((new U32TextTuple(registry, [2, 'ba'])), new U32(registry, 42));
mockU32TupleMap.set((new U32TextTuple(registry, [2, 'b'])), new U32(registry, 7));
mockU32TupleMap.set((new U32TextTuple(registry, [1, 'baz'])), new U32(registry, 13));
mockU32I32Map.set(new I32(registry, 255), new U32(registry, 69));
mockU32I32Map.set(new I32(registry, -255), new U32(registry, 42));
mockU32I32Map.set(new I32(registry, 1000), new U32(registry, 7));
mockU32I32Map.set(new I32(registry, -1000), new U32(registry, 25));
mockU32I32Map.set(new I32(registry, 0), new U32(registry, 13));
mockU32StructMap.set(new MockStruct(registry, { int: 1, text: 'b' }), new U32(registry, 42));
mockU32StructMap.set(new MockStruct(registry, { int: -1, text: 'b' }), new U32(registry, 7));
mockU32StructMap.set(new MockStruct(registry, { int: -1, text: 'ba' }), new U32(registry, 25));
mockU32StructMap.set(new MockStruct(registry, { int: -2, text: 'baz' }), new U32(registry, 13));
mockU32EnumMap.set(new MockEnum(registry, { Key3: new U32TextTuple(registry, [2, 'ba']) }), new U32(registry, 13));
mockU32EnumMap.set(new MockEnum(registry, { Key3: new U32TextTuple(registry, [2, 'b']) }), new U32(registry, 42));
mockU32EnumMap.set(new MockEnum(registry, { Key2: new MockStruct(registry, { int: -1, text: 'b' }) }), new U32(registry, 7));
mockU32EnumMap.set(new MockEnum(registry, { Key1: new MockStruct(registry, { int: 1, text: 'b' }) }), new U32(registry, 25));
mockU32EnumMap.set(new MockEnum(registry, { Key1: new MockStruct(registry, { int: -1, text: 'b' }) }), new U32(registry, 69));
describe('BTreeMap', (): void => {
it('decodes null', (): void => {
expect(
@@ -54,6 +91,97 @@ describe('BTreeMap', (): void => {
).toEqual(13);
});
it('correctly sorts simple keys', (): void => {
expect(
Array.from(new (BTreeMap.with(I32, U32))(registry, mockU32I32Map).keys()).map((k) => k.toNumber())
).toEqual([-1000, -255, 0, 255, 1000]);
});
it('correctly sorts tuple keys', (): void => {
expect(
Array.from(new (BTreeMap.with(U32TextTuple, U32))(registry, mockU32TupleMap).keys()).map((k) => k.toJSON())
).toEqual([[1, 'baz'], [2, 'b'], [2, 'ba']]);
});
it('correctly sorts struct keys', (): void => {
expect(
Array.from(new (BTreeMap.with(MockStruct, U32))(registry, mockU32StructMap).keys()).map((k) => k.toJSON())
).toEqual([
{ int: -1, text: 'b' },
{ int: 1, text: 'b' },
{ int: -1, text: 'ba' },
{ int: -2, text: 'baz' }
]);
});
it('correctly sorts enum keys', (): void => {
expect(
Array.from(new (BTreeMap.with(MockEnum, U32))(registry, mockU32EnumMap).keys()).map((k) => k.toJSON())
).toEqual([
{ key1: { int: -1, text: 'b' } },
{ key1: { int: 1, text: 'b' } },
{ key2: { int: -1, text: 'b' } },
{ key3: [2, 'b'] },
{ key3: [2, 'ba'] }
]);
});
it('correctly serializes/deserializes to/from json with numeric keys', (): void => {
expect(
new (BTreeMap.with(I32, U32))(
registry,
new (BTreeMap.with(I32, U32))(registry, mockU32I32Map).toJSON()
).toJSON()
).toEqual({ '-1000': 25, '-255': 42, 0: 13, 1000: 7, 255: 69 });
});
it('correctly serializes/deserializes to/from json with text keys', (): void => {
expect(
new (BTreeMap.with(Text, U32))(
registry,
new (BTreeMap.with(Text, U32))(registry, mockU32TextMap).toJSON()
).toJSON()
).toEqual({ bazzing: 69 });
});
it('correctly serializes/deserializes to/from json with tuple keys', (): void => {
expect(
new (BTreeMap.with(U32TextTuple, U32))(
registry,
new (BTreeMap.with(U32TextTuple, U32))(registry, mockU32TupleMap).toJSON()
).toJSON()
).toEqual({ '[1,"baz"]': 13, '[2,"b"]': 7, '[2,"ba"]': 42 });
});
it('correctly serializes/deserializes to/from json with struct keys', (): void => {
expect(
new (BTreeMap.with(MockStruct, U32))(
registry,
new (BTreeMap.with(MockStruct, U32))(registry, mockU32StructMap).toJSON()
).toJSON()
).toEqual({
'{"text":"b","int":-1}': 7,
'{"text":"b","int":1}': 42,
'{"text":"ba","int":-1}': 25,
'{"text":"baz","int":-2}': 13
});
});
it('correctly serializes/deserializes to/from json with enum keys', (): void => {
expect(
new (BTreeMap.with(MockEnum, U32))(
registry,
new (BTreeMap.with(MockEnum, U32))(registry, mockU32EnumMap).toJSON()
).toJSON()
).toEqual({
'{"key1":{"text":"b","int":-1}}': 69,
'{"key1":{"text":"b","int":1}}': 25,
'{"key2":{"text":"b","int":-1}}': 7,
'{"key3":[2,"b"]}': 42,
'{"key3":[2,"ba"]}': 13
});
});
it('generates sane toRawTypes', (): void => {
expect(new (BTreeMap.with(Text, U32))(registry).toRawType()).toBe('BTreeMap<Text,u32>');
expect(new (BTreeMap.with(Text, Text))(registry).toRawType()).toBe('BTreeMap<Text,Text>');
+84 -2
View File
@@ -4,11 +4,24 @@
import type { CodecTo } from '../types';
import { TypeRegistry } from '../create';
import { Text, U32 } from '../primitive';
import { BTreeSet, Struct } from '.';
import { I32, Text, U32 } from '../primitive';
import { Constructor } from '../types';
import { ITuple } from '../types/interfaces';
import { Enum } from './Enum';
import { BTreeSet, Struct, Tuple } from '.';
const registry = new TypeRegistry();
class U32TextTuple extends (Tuple.with([U32, Text]) as unknown as Constructor<ITuple<[U32, Text]>>) {}
// Reason: We purposefully want `text` to be the first key of the struct and take priority during sorting
// eslint-disable-next-line sort-keys
class MockStruct extends Struct.with({ text: Text, int: I32 }) {}
class MockEnum extends Enum.with({
Key1: MockStruct,
Key2: MockStruct,
Key3: U32TextTuple
}) {}
const mockU32Set = new Set<U32>();
mockU32Set.add(new U32(registry, 2));
@@ -21,6 +34,34 @@ const mockU32SetObject = [2, 24, 30, 80];
const mockU32SetHexString = '0x1002000000180000001e00000050000000';
const mockU32SetUint8Array = Uint8Array.from([16, 2, 0, 0, 0, 24, 0, 0, 0, 30, 0, 0, 0, 80, 0, 0, 0]);
const mockI32SetObj = [1000, 0, 255, -255, -1000];
const mockTextSetObj = [
new Text(registry, 'baz'),
new Text(registry, 'b'),
new Text(registry, 'bb'),
new Text(registry, 'ba'),
new Text(registry, 'c')
];
const mockTupleSetObj = [
new U32TextTuple(registry, [2, 'ba']),
new U32TextTuple(registry, [2, 'bb']),
new U32TextTuple(registry, [2, 'b']),
new U32TextTuple(registry, [1, 'baz'])
];
const mockStructSetObj = [
new MockStruct(registry, { int: 1, text: 'b' }),
new MockStruct(registry, { int: -1, text: 'b' }),
new MockStruct(registry, { int: -1, text: 'ba' }),
new MockStruct(registry, { int: -2, text: 'baz' })
];
const mockEnumSetObj = [
new MockEnum(registry, { Key3: new U32TextTuple(registry, [2, 'ba']) }),
new MockEnum(registry, { Key3: new U32TextTuple(registry, [2, 'b']) }),
new MockEnum(registry, { Key2: new MockStruct(registry, { int: -1, text: 'b' }) }),
new MockEnum(registry, { Key1: new MockStruct(registry, { int: 1, text: 'b' }) }),
new MockEnum(registry, { Key1: new MockStruct(registry, { int: -1, text: 'b' }) })
];
describe('BTreeSet', (): void => {
describe('decoding', (): void => {
const testDecode = (type: string, input: any, output: string): void =>
@@ -94,6 +135,47 @@ describe('BTreeSet', (): void => {
).toEqual(17);
});
it('correctly sorts numeric values', (): void => {
expect(
Array.from(new (BTreeSet.with(I32))(registry, mockI32SetObj)).map((k) => k.toNumber())
).toEqual([-1000, -255, 0, 255, 1000]);
});
it('correctly sorts text values', (): void => {
expect(
Array.from(new (BTreeSet.with(Text))(registry, mockTextSetObj)).map((k) => k.toString())
).toEqual(['b', 'ba', 'baz', 'bb', 'c']);
});
it('correctly sorts complex tuple values', (): void => {
expect(
Array.from(new (BTreeSet.with(U32TextTuple))(registry, mockTupleSetObj)).map((k) => k.toJSON())
).toEqual([[1, 'baz'], [2, 'b'], [2, 'ba'], [2, 'bb']]);
});
it('correctly sorts complex struct values', (): void => {
expect(
Array.from(new (BTreeSet.with(MockStruct))(registry, mockStructSetObj)).map((k) => k.toJSON())
).toEqual([
{ int: -1, text: 'b' },
{ int: 1, text: 'b' },
{ int: -1, text: 'ba' },
{ int: -2, text: 'baz' }
]);
});
it('correctly sorts complex enum values', (): void => {
expect(
Array.from(new (BTreeSet.with(MockEnum))(registry, mockEnumSetObj)).map((k) => k.toJSON())
).toEqual([
{ key1: { int: -1, text: 'b' } },
{ key1: { int: 1, text: 'b' } },
{ key2: { int: -1, text: 'b' } },
{ key3: [2, 'b'] },
{ key3: [2, 'ba'] }
]);
});
it('generates sane toRawTypes', (): void => {
expect(new (BTreeSet.with(U32))(registry).toRawType()).toBe('BTreeSet<u32>');
expect(new (BTreeSet.with(Text))(registry).toRawType()).toBe('BTreeSet<Text>');
+2 -2
View File
@@ -6,7 +6,7 @@ import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../t
import { compactFromU8a, compactToU8a, isHex, isU8a, logger, stringify, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
import { compareSet, decodeU8a, typeToConstructor } from './utils';
import { compareSet, decodeU8a, sortSet, typeToConstructor } from './utils';
const l = logger('BTreeSet');
@@ -84,7 +84,7 @@ export class BTreeSet<V extends Codec = Codec> extends Set<V> implements Codec {
readonly #ValClass: Constructor<V>;
constructor (registry: Registry, valType: Constructor<V> | keyof InterfaceTypes, rawValue?: Uint8Array | string | string[] | Set<any>) {
super(decodeSet(registry, valType, rawValue));
super(sortSet(decodeSet(registry, valType, rawValue)));
this.registry = registry;
this.#ValClass = typeToConstructor(registry, valType);
+1 -1
View File
@@ -18,7 +18,7 @@ export class DoNotConstruct implements Codec {
constructor (registry: Registry, typeName = 'DoNotConstruct') {
this.registry = registry;
this.#neverError = new Error(`Cannot construct unknown type ${typeName}`);
this.#neverError = new Error(`DoNotConstruct: Cannot construct unknown type ${typeName}`);
throw this.#neverError;
}
+1 -1
View File
@@ -310,7 +310,7 @@ export class Enum implements Codec {
} else if (this.#isBasic && isString(other)) {
return this.type === other;
} else if (isU8a(other)) {
return !this.toU8a().some((entry, index): boolean => entry !== other[index]);
return !this.toU8a().some((entry, index) => entry !== other[index]);
} else if (isHex(other)) {
return this.toHex() === other;
} else if (other instanceof Enum) {
+12 -3
View File
@@ -6,7 +6,10 @@ import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../t
import { compactFromU8a, compactToU8a, isHex, isObject, isU8a, logger, stringify, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
import { compareMap, decodeU8a, typeToConstructor } from './utils';
import { AbstractArray } from './AbstractArray';
import { Enum } from './Enum';
import { Struct } from './Struct';
import { compareMap, decodeU8a, sortMap, typeToConstructor } from './utils';
const l = logger('Map');
@@ -34,11 +37,15 @@ function decodeMapFromMap<K extends Codec = Codec, V extends Codec = Codec> (reg
const output = new Map<K, V>();
value.forEach((val: any, key: any) => {
const isComplex = KeyClass.prototype instanceof AbstractArray ||
KeyClass.prototype instanceof Struct ||
KeyClass.prototype instanceof Enum;
try {
output.set(
key instanceof KeyClass
? key
: new KeyClass(registry, key),
: new KeyClass(registry, isComplex ? JSON.parse(key) : key),
val instanceof ValClass
? val
: new ValClass(registry, val)
@@ -97,7 +104,9 @@ export class CodecMap<K extends Codec = Codec, V extends Codec = Codec> extends
readonly #type: string;
constructor (registry: Registry, keyType: Constructor<K> | keyof InterfaceTypes, valType: Constructor<V> | keyof InterfaceTypes, rawValue: Uint8Array | string | Map<any, any> | undefined, type: 'BTreeMap' | 'HashMap' = 'HashMap') {
super(decodeMap(registry, keyType, valType, rawValue));
const decoded = decodeMap(registry, keyType, valType, rawValue);
super(type === 'BTreeMap' ? sortMap(decoded) : decoded);
this.registry = registry;
this.#KeyClass = typeToConstructor(registry, keyType);
+1 -1
View File
@@ -7,7 +7,7 @@ import type { CodecTo } from '../types';
import { TypeRegistry } from '../create';
import { Metadata } from '../metadata';
import rpcMetadata from '../metadata/static';
import rpcMetadata from '../metadata/static-substrate';
import { Text, U32, u128 as U128 } from '../primitive';
import { Tuple } from '.';
+1 -1
View File
@@ -9,7 +9,7 @@ import { randomAsU8a } from '@polkadot/util-crypto';
import { createTypeUnsafe, TypeRegistry } from '../create';
import { GenericAccountId as AccountId } from '../generic';
import { Metadata } from '../metadata';
import rpcMetadata from '../metadata/static';
import rpcMetadata from '../metadata/static-substrate';
import { Text } from '../primitive';
import { Tuple, Vec } from '.';
+1
View File
@@ -7,3 +7,4 @@ export { compareSet } from './compareSet';
export { decodeU8a } from './decodeU8a';
export { mapToTypeMap } from './mapToTypeMap';
export { typeToConstructor } from './typeToConstructor';
export { sortAsc, sortSet, sortMap } from './sortValues';
@@ -0,0 +1,77 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { Codec } from '../../types';
import type { Enum } from '../Enum';
import { bnToBn, isBigInt, isBn, isFunction, isNumber, stringify } from '@polkadot/util';
type SortArg = Codec | Codec[] | number[] | BN | bigint | number | Uint8Array;
/** @internal **/
function isArrayLike (arg: SortArg): arg is Uint8Array | Codec[] | number[] {
return arg instanceof Uint8Array || Array.isArray(arg);
}
/** @internal **/
function isCodec (arg: SortArg): arg is Codec {
return isFunction(arg && (arg as Codec).toU8a);
}
/** @internal **/
function isEnum (arg: SortArg): arg is Enum {
return isCodec(arg) && isNumber((arg as Enum).index) && isCodec((arg as Enum).value);
}
/** @internal */
function isNumberLike (arg: SortArg): arg is BN | bigint | number {
return isNumber(arg) || isBn(arg) || isBigInt(arg);
}
/** @internal */
function sortArray (a: Uint8Array | Codec[] | number[], b: Uint8Array | Codec[] | number[]): number {
// Vec, Tuple, Bytes etc.
let sortRes = 0;
const minLen = Math.min(a.length, b.length);
for (let i = 0; i < minLen; ++i) {
sortRes = sortAsc(a[i], b[i]);
if (sortRes !== 0) {
return sortRes;
}
}
return a.length - b.length;
}
/**
* Sort keys/values of BTreeSet/BTreeMap in ascending order for encoding compatibility with Rust's BTreeSet/BTreeMap
* (https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html)
* (https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html)
*/
export function sortAsc<V extends SortArg = Codec> (a: V, b: V): number {
if (isNumberLike(a) && isNumberLike(b)) {
return bnToBn(a).cmp(bnToBn(b));
} else if (a instanceof Map && b instanceof Map) {
return sortAsc(Array.from(a.values()), Array.from(b.values()));
} else if (isEnum(a) && isEnum(b)) {
return sortAsc(a.index, b.index) || sortAsc(a.value, b.value);
} else if (isArrayLike(a) && isArrayLike(b)) {
return sortArray(a, b);
} else if (isCodec(a) && isCodec(b)) {
// Text, Bool etc.
return sortAsc(a.toU8a(true), b.toU8a(true));
}
throw new Error(`Attempting to sort unrecognized values: ${stringify(a)} (typeof ${typeof a}) <-> ${stringify(b)} (typeof ${typeof b})`);
}
export function sortSet<V extends Codec = Codec> (set: Set<V>): Set<V> {
return new Set(Array.from(set).sort(sortAsc));
}
export function sortMap<K extends Codec = Codec, V extends Codec = Codec> (map: Map<K, V>): Map<K, V> {
return new Map(Array.from(map.entries()).sort(([keyA], [keyB]) => sortAsc(keyA, keyB)));
}
+22 -17
View File
@@ -8,6 +8,7 @@ import type { FromReg, TypeDef } from './types';
import { assert, isNumber, isUndefined, stringify } from '@polkadot/util';
import { BTreeMap, BTreeSet, CodecSet, Compact, DoNotConstruct, Enum, HashMap, Int, Option, Result, Struct, Tuple, U8aFixed, UInt, Vec, VecFixed } from '../codec';
import { Bytes, Null } from '../primitive';
import { getTypeDef } from './getTypeDef';
import { TypeDefInfo } from './types';
@@ -130,7 +131,7 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[TypeDefInfo.Null]: (registry: Registry, _: TypeDef): Constructor =>
createClass(registry, 'Null'),
Null,
[TypeDefInfo.Option]: (registry: Registry, value: TypeDef): Constructor =>
Option.with(getSubType(value)),
@@ -159,7 +160,7 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
},
[TypeDefInfo.Si]: (registry: Registry, value: TypeDef): Constructor =>
getTypeClass(registry, registry.lookup.getTypeDef(value.index as number)),
getTypeClass(registry, registry.lookup.getTypeDef(value.type)),
[TypeDefInfo.Struct]: (registry: Registry, value: TypeDef): Constructor =>
Struct.with(getTypeClassMap(value), value.alias),
@@ -175,7 +176,7 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
return (
subType === 'u8'
? createClass(registry, 'Bytes')
? Bytes
: Vec.with(subType)
);
},
@@ -183,34 +184,38 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
[TypeDefInfo.VecFixed]: (registry: Registry, { displayName, length, sub }: TypeDef): Constructor => {
assert(isNumber(length) && !isUndefined(sub), 'Expected length & type information for fixed vector');
const subType = (sub as TypeDef).type as keyof InterfaceTypes;
return (
(sub as TypeDef).type === 'u8'
subType === 'u8'
? U8aFixed.with((length * 8) as U8aBitLength, displayName)
: VecFixed.with((sub as TypeDef).type as keyof InterfaceTypes, length)
: VecFixed.with(subType, length)
);
}
};
// Returns the type Class for construction
export function getTypeClass<T extends Codec = Codec> (registry: Registry, value: TypeDef): Constructor<T> {
let Type = registry.get<T>(value.type);
export function getTypeClass<T extends Codec = Codec> (registry: Registry, typeDef: TypeDef): Constructor<T> {
let Type = registry.get<T>(typeDef.type);
if (Type) {
return Type;
}
const getFn = infoMapping[value.info];
try {
Type = infoMapping[typeDef.info](registry, typeDef) as Constructor<T>;
assert(getFn, () => `Unable to construct class from ${stringify(value)}`);
assert(Type, 'No class created');
Type = getFn(registry, value) as Constructor<T>;
// don't clobber any existing
if (!Type.__fallbackType && typeDef.fallbackType) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore ...this is the only place we we actually assign this...
Type.__fallbackType = typeDef.fallbackType;
}
// don't clobber any existing
if (!Type.__fallbackType && value.fallbackType) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore ...this is the only place we we actually assign this...
Type.__fallbackType = value.fallbackType;
return Type;
} catch (error) {
throw new Error(`Unable to construct class from ${stringify(typeDef)}: ${(error as Error).message}`);
}
return Type;
}
+16 -16
View File
@@ -3,20 +3,16 @@
import type { Bytes } from '../primitive/Bytes';
import type { Codec, Constructor, InterfaceTypes, Registry } from '../types';
import type { FromReg } from './types';
import type { CreateOptions, FromReg } from './types';
import { assert, isHex, isU8a, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { Option } from '../codec/Option';
import { createClass } from './createClass';
interface CreateOptions {
blockHash?: Uint8Array | string | null;
isPedantic?: boolean;
}
// With isPedantic, actually check that the encoding matches that supplied. This
// is much slower, but verifies that we have the correct types defined
function checkInstance<T extends Codec = Codec, K extends string = string> (value: Uint8Array, created: FromReg<T, K>): void {
function checkInstance (created: FromReg<Codec, string>, value: Uint8Array): void {
const u8a = created.toU8a();
const rawType = created.toRawType();
@@ -30,25 +26,29 @@ function checkInstance<T extends Codec = Codec, K extends string = string> (valu
);
}
// Initializes a type with a value. This also checks for fallbacks and in the cases
// where isPedantic is specified (storage decoding), also check the format/structure
function initType<T extends Codec = Codec, K extends string = string> (registry: Registry, Type: Constructor<FromReg<T, K>>, params: unknown[] = [], { blockHash, isPedantic }: CreateOptions = {}): FromReg<T, K> {
const created = new Type(registry, ...params);
const value = params[0];
function checkPedantic (created: FromReg<Codec, string>, [value]: unknown[], isPedantic = false): void {
if (isPedantic) {
if (isU8a(value)) {
checkInstance(value, created);
checkInstance(created, value);
} else if (isHex(value)) {
checkInstance(u8aToU8a(value), created);
checkInstance(created, u8aToU8a(value));
}
}
}
// Initializes a type with a value. This also checks for fallbacks and in the cases
// where isPedantic is specified (storage decoding), also check the format/structure
function initType<T extends Codec = Codec, K extends string = string> (registry: Registry, Type: Constructor<FromReg<T, K>>, params: unknown[] = [], { blockHash, isOptional, isPedantic }: CreateOptions = {}): FromReg<T, K> {
const created = new (isOptional ? Option.with(Type) : Type)(registry, ...params);
checkPedantic(created, params, isPedantic);
if (blockHash) {
created.createdAtHash = createType(registry, 'Hash', blockHash);
}
return created;
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return created as any;
}
// An unsafe version of the `createType` below. It's unsafe because the `type`
@@ -2,12 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
import { encodeTypeDef } from './encodeTypes';
import { TypeRegistry } from './registry';
import { TypeDefInfo } from './types';
describe('encodeTypeDef', (): void => {
const registry = new TypeRegistry();
it('correctly encodes a complex struct', (): void => {
expect(
JSON.parse(encodeTypeDef({
JSON.parse(encodeTypeDef(registry, {
info: TypeDefInfo.Struct,
sub: [
{
@@ -47,7 +50,7 @@ describe('encodeTypeDef', (): void => {
it('correctly encodes a complex struct (named)', (): void => {
expect(
JSON.parse(encodeTypeDef({
JSON.parse(encodeTypeDef(registry, {
info: TypeDefInfo.Struct,
sub: [
{
@@ -88,7 +91,7 @@ describe('encodeTypeDef', (): void => {
it('correctly encodes a complex enum', (): void => {
expect(
JSON.parse(encodeTypeDef({
JSON.parse(encodeTypeDef(registry, {
info: TypeDefInfo.Enum,
sub: [
{
@@ -148,7 +151,7 @@ describe('encodeTypeDef', (): void => {
it('correctly encodes a complex enum (named)', (): void => {
expect(
JSON.parse(encodeTypeDef({
JSON.parse(encodeTypeDef(registry, {
info: TypeDefInfo.Enum,
sub: [
{
+77 -41
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Registry } from '../types/registry';
import type { TypeDef } from './types';
import { assert, isNumber, isUndefined, stringify } from '@polkadot/util';
@@ -19,7 +20,7 @@ export function paramsNotation <T> (outer: string, inner?: T | T[], transform: (
}`;
}
function encodeWithParams (typeDef: TypeDef, outer: string): string {
function encodeWithParams (registry: Registry, typeDef: TypeDef, outer: string): string {
const { info, sub } = typeDef;
switch (info) {
@@ -31,25 +32,26 @@ function encodeWithParams (typeDef: TypeDef, outer: string): string {
case TypeDefInfo.Option:
case TypeDefInfo.Result:
case TypeDefInfo.Vec:
return paramsNotation(outer, sub, (param) => encodeTypeDef(param));
return paramsNotation(outer, sub, (param) => encodeTypeDef(registry, param));
}
throw new Error(`Unable to encode ${stringify(typeDef)} with params`);
}
function encodeDoNotConstruct ({ displayName }: TypeDef): string {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function encodeDoNotConstruct (registry: Registry, { displayName }: TypeDef): string {
return `DoNotConstruct<${displayName || 'Unknown'}>`;
}
function encodeSubTypes (sub: TypeDef[], asEnum?: boolean): string {
function encodeSubTypes (registry: Registry, sub: TypeDef[], asEnum?: boolean, extra?: Record<string, unknown>): string {
const names = sub.map(({ name }) => name);
assert(names.every((n) => !!n), () => `Subtypes does not have consistent names, ${names.join(', ')}`);
const inner = sub.reduce< Record<string, string>>((result, type) => ({
...result,
[type.name as string]: encodeTypeDef(type)
}), {});
[type.name as string]: encodeTypeDef(registry, type)
}), { ...(extra as Record<string, string>) });
return stringify(
asEnum
@@ -58,7 +60,7 @@ function encodeSubTypes (sub: TypeDef[], asEnum?: boolean): string {
);
}
function encodeEnum (typeDef: TypeDef): string {
function encodeEnum (registry: Registry, typeDef: TypeDef): string {
assert(typeDef.sub && Array.isArray(typeDef.sub), 'Unable to encode Enum type');
const sub = typeDef.sub;
@@ -67,28 +69,38 @@ function encodeEnum (typeDef: TypeDef): string {
// TODO We need to take the disciminant into account and auto-add empty entries
return sub.every(({ type }) => type === 'Null')
? stringify({ _enum: sub.map(({ name }, index) => `${name || `Empty${index}`}`) })
: encodeSubTypes(sub, true);
: encodeSubTypes(registry, sub, true);
}
function encodeStruct (typeDef: TypeDef): string {
function encodeStruct (registry: Registry, typeDef: TypeDef): string {
assert(typeDef.sub && Array.isArray(typeDef.sub), 'Unable to encode Struct type');
return encodeSubTypes(typeDef.sub);
return encodeSubTypes(registry, typeDef.sub, false, {
...(
typeDef.alias
? { _alias: [...typeDef.alias.entries()].reduce<Record<string, string>>((all, [k, v]) => ({
...all,
[k]: v
}), {}) }
: {}
)
});
}
function encodeTuple (typeDef: TypeDef): string {
function encodeTuple (registry: Registry, typeDef: TypeDef): string {
assert(typeDef.sub && Array.isArray(typeDef.sub), 'Unable to encode Tuple type');
return `(${typeDef.sub.map((type) => encodeTypeDef(type)).join(', ')})`;
return `(${typeDef.sub.map((type) => encodeTypeDef(registry, type)).join(',')})`;
}
function encodeUInt ({ length }: TypeDef, type: 'Int' | 'UInt'): string {
function encodeUInt (registry: Registry, { length }: TypeDef, type: 'Int' | 'UInt'): string {
assert(isNumber(length), 'Unable to encode VecFixed type');
return `${type}<${length}>`;
}
function encodeVecFixed ({ length, sub }: TypeDef): string {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function encodeVecFixed (registry: Registry, { length, sub }: TypeDef): string {
assert(isNumber(length) && !isUndefined(sub) && !Array.isArray(sub), 'Unable to encode VecFixed type');
return `[${sub.type};${length}]`;
@@ -96,38 +108,62 @@ function encodeVecFixed ({ length, sub }: TypeDef): string {
// We setup a record here to ensure we have comprehensive coverage (any item not covered will result
// in a compile-time error with the missing index)
const encoders: Record<TypeDefInfo, (typeDef: TypeDef) => string> = {
[TypeDefInfo.BTreeMap]: (typeDef: TypeDef): string => encodeWithParams(typeDef, 'BTreeMap'),
[TypeDefInfo.BTreeSet]: (typeDef: TypeDef): string => encodeWithParams(typeDef, 'BTreeSet'),
[TypeDefInfo.Compact]: (typeDef: TypeDef): string => encodeWithParams(typeDef, 'Compact'),
[TypeDefInfo.DoNotConstruct]: (typeDef: TypeDef): string => encodeDoNotConstruct(typeDef),
[TypeDefInfo.Enum]: (typeDef: TypeDef): string => encodeEnum(typeDef),
[TypeDefInfo.HashMap]: (typeDef: TypeDef): string => encodeWithParams(typeDef, 'HashMap'),
[TypeDefInfo.Int]: (typeDef: TypeDef): string => encodeUInt(typeDef, 'Int'),
[TypeDefInfo.Linkage]: (typeDef: TypeDef): string => encodeWithParams(typeDef, 'Linkage'),
const encoders: Record<TypeDefInfo, (registry: Registry, typeDef: TypeDef) => string> = {
[TypeDefInfo.BTreeMap]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, 'BTreeMap'),
[TypeDefInfo.BTreeSet]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, 'BTreeSet'),
[TypeDefInfo.Compact]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, 'Compact'),
[TypeDefInfo.DoNotConstruct]: (registry: Registry, typeDef: TypeDef) =>
encodeDoNotConstruct(registry, typeDef),
[TypeDefInfo.Enum]: (registry: Registry, typeDef: TypeDef) =>
encodeEnum(registry, typeDef),
[TypeDefInfo.HashMap]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, 'HashMap'),
[TypeDefInfo.Int]: (registry: Registry, typeDef: TypeDef) =>
encodeUInt(registry, typeDef, 'Int'),
[TypeDefInfo.Linkage]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, 'Linkage'),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[TypeDefInfo.Null]: (typeDef: TypeDef): string => 'Null',
[TypeDefInfo.Option]: (typeDef: TypeDef): string => encodeWithParams(typeDef, 'Option'),
[TypeDefInfo.Plain]: (typeDef: TypeDef): string => typeDef.displayName || typeDef.type,
[TypeDefInfo.Result]: (typeDef: TypeDef): string => encodeWithParams(typeDef, 'Result'),
[TypeDefInfo.Set]: (typeDef: TypeDef): string => typeDef.type,
[TypeDefInfo.Si]: (typeDef: TypeDef): string => typeDef.type,
[TypeDefInfo.Struct]: (typeDef: TypeDef): string => encodeStruct(typeDef),
[TypeDefInfo.Tuple]: (typeDef: TypeDef): string => encodeTuple(typeDef),
[TypeDefInfo.UInt]: (typeDef: TypeDef): string => encodeUInt(typeDef, 'UInt'),
[TypeDefInfo.Vec]: (typeDef: TypeDef): string => encodeWithParams(typeDef, 'Vec'),
[TypeDefInfo.VecFixed]: (typeDef: TypeDef): string => encodeVecFixed(typeDef)
[TypeDefInfo.Null]: (registry: Registry, typeDef: TypeDef) =>
'Null',
[TypeDefInfo.Option]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, 'Option'),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[TypeDefInfo.Plain]: (registry: Registry, typeDef: TypeDef) =>
typeDef.displayName || typeDef.type,
[TypeDefInfo.Result]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, 'Result'),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[TypeDefInfo.Set]: (registry: Registry, typeDef: TypeDef) =>
typeDef.type,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[TypeDefInfo.Si]: (registry: Registry, typeDef: TypeDef) =>
typeDef.lookupName || typeDef.type,
[TypeDefInfo.Struct]: (registry: Registry, typeDef: TypeDef) =>
encodeStruct(registry, typeDef),
[TypeDefInfo.Tuple]: (registry: Registry, typeDef: TypeDef) =>
encodeTuple(registry, typeDef),
[TypeDefInfo.UInt]: (registry: Registry, typeDef: TypeDef) =>
encodeUInt(registry, typeDef, 'UInt'),
[TypeDefInfo.Vec]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, 'Vec'),
[TypeDefInfo.VecFixed]: (registry: Registry, typeDef: TypeDef) =>
encodeVecFixed(registry, typeDef)
};
function encodeType (typeDef: TypeDef): string {
function encodeType (registry: Registry, typeDef: TypeDef, withLookup = true): string {
const encoder = encoders[typeDef.info];
assert(encoder, () => `Cannot encode type: info=${typeDef.info}, typeDef=${stringify(typeDef)}`);
assert(encoder, () => `Cannot encode type ${stringify(typeDef)}`);
return encoder(typeDef);
return withLookup && typeDef.lookupName
? typeDef.lookupName
: encoder(registry, typeDef);
}
export function encodeTypeDef (typeDef: TypeDef): string {
export function encodeTypeDef (registry: Registry, typeDef: TypeDef): string {
assert(!isUndefined(typeDef.info), () => `Invalid type definition with no instance info, typeDef=${stringify(typeDef)}`);
// In the case of contracts we do have the unfortunate situation where the displayName would
@@ -137,12 +173,12 @@ export function encodeTypeDef (typeDef: TypeDef): string {
return typeDef.displayName;
}
return encodeType(typeDef);
return encodeType(registry, typeDef);
}
export function withTypeString (typeDef: Omit<TypeDef, 'type'>): TypeDef {
export function withTypeString (registry: Registry, typeDef: Omit<TypeDef, 'type'>): TypeDef {
return {
...typeDef,
type: encodeType(typeDef as TypeDef)
type: encodeType(registry, typeDef as TypeDef, false)
};
}
+20 -10
View File
@@ -6,6 +6,7 @@
import type { ExtDef } from '../extrinsic/signedExtensions/types';
import type { ChainProperties, CodecHash, DispatchErrorModule, Hash, MetadataLatest, PortableRegistry, SiLookupTypeId } from '../interfaces/types';
import type { CallFunction, Codec, CodecHasher, Constructor, InterfaceTypes, RegisteredTypes, Registry, RegistryError, RegistryTypes } from '../types';
import type { CreateOptions } from './types';
import { assert, assertReturn, BN_ZERO, formatBalance, isFunction, isString, isU8a, logger, stringCamelCase, stringify, u8aToHex } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
@@ -20,7 +21,7 @@ import * as definitions from '../interfaces/definitions';
import { decorateConstants, decorateExtrinsics } from '../metadata/decorate';
import { Metadata } from '../metadata/Metadata';
import { createClass, getTypeClass } from './createClass';
import { createType } from './createType';
import { createTypeUnsafe } from './createType';
import { getTypeDef } from './getTypeDef';
const l = logger('registry');
@@ -30,11 +31,13 @@ function injectErrors (_: Registry, metadata: Metadata, metadataErrors: Record<s
const modules = metadata.asLatest.modules;
// decorate the errors
modules.forEach((section, _sectionIndex): void => {
const sectionIndex = metadata.version >= 12 ? section.index.toNumber() : _sectionIndex;
const sectionName = stringCamelCase(section.name);
modules.forEach(({ errors, index, name }, _sectionIndex): void => {
const sectionIndex = metadata.version >= 12
? index.toNumber()
: _sectionIndex;
const sectionName = stringCamelCase(name);
section.errors.forEach(({ docs, name }, index): void => {
errors.forEach(({ docs, name }, index): void => {
const eventIndex = new Uint8Array([sectionIndex, index]);
metadataErrors[u8aToHex(eventIndex)] = {
@@ -53,13 +56,13 @@ function injectEvents (registry: Registry, metadata: Metadata, metadataEvents: R
// decorate the events
metadata.asLatest.modules
.filter(({ events }) => events.isSome)
.forEach((section, _sectionIndex): void => {
.forEach(({ events, index, name }, _sectionIndex): void => {
const sectionIndex = metadata.version >= 12
? section.index.toNumber()
? index.toNumber()
: _sectionIndex;
const sectionName = stringCamelCase(section.name);
const sectionName = stringCamelCase(name);
section.events.unwrap().forEach((meta, methodIndex): void => {
events.unwrap().forEach((meta, methodIndex): void => {
const methodName = meta.name.toString();
const typeDef = meta.args.map((arg) => getTypeDef(arg));
let Types: Constructor<Codec>[] | null = null;
@@ -247,7 +250,14 @@ export class TypeRegistry implements Registry {
* @description Creates an instance of a type as registered
*/
public createType <K extends keyof InterfaceTypes> (type: K, ...params: unknown[]): InterfaceTypes[K] {
return createType(this, type, ...params);
return createTypeUnsafe(this, type, params);
}
/**
* @description Creates an instance of a type as registered
*/
public createTypeUnsafe <T extends Codec = Codec, K extends string = string> (type: K, params: unknown[], options?: CreateOptions): T {
return createTypeUnsafe(this, type, params, options);
}
// find a specific call
+11
View File
@@ -34,12 +34,23 @@ export enum TypeDefInfo {
export interface TypeDef {
alias?: Map<string, string>;
displayName?: string;
docs?: string[];
fallbackType?: string;
info: TypeDefInfo;
index?: number;
isFromSi?: boolean;
length?: number;
lookupIndex?: number;
lookupName?: string;
lookupNameRoot?: string;
name?: string;
namespace?: string;
sub?: TypeDef | TypeDef[];
type: string;
}
export interface CreateOptions {
blockHash?: Uint8Array | string | null;
isOptional?: boolean;
isPedantic?: boolean;
}
@@ -3,7 +3,7 @@
import { TypeRegistry } from '../create';
import { Metadata } from '../metadata';
import rpcMetadata from '../metadata/static';
import rpcMetadata from '../metadata/static-substrate';
import { GenericExtrinsic as Extrinsic } from '.';
const registry = new TypeRegistry();
@@ -3,7 +3,7 @@
import { TypeRegistry } from '../create';
import { Metadata } from '../metadata';
import rpcMetadata from '../metadata/static';
import rpcMetadata from '../metadata/static-substrate';
import { GenericSignerPayload as SignerPayload } from '.';
const registry = new TypeRegistry();
@@ -6,7 +6,7 @@ import { BN } from '@polkadot/util';
import { TypeRegistry } from '../../create';
import { decorateExtrinsics, Metadata } from '../../metadata';
import rpcMetadata from '../../metadata/static';
import rpcMetadata from '../../metadata/static-substrate';
import { GenericExtrinsicV4 as Extrinsic } from '.';
const registry = new TypeRegistry();
@@ -6,7 +6,7 @@ import { BN_ZERO } from '@polkadot/util';
import { TypeRegistry } from '../../create';
import { Metadata } from '../../metadata';
import metadataStatic from '../../metadata/static';
import metadataStatic from '../../metadata/static-substrate';
import { GenericExtrinsicSignatureV4 as ExtrinsicSignature } from '.';
const signOptions = {
+1 -1
View File
@@ -7,7 +7,7 @@
import { TypeRegistry } from '../create';
import block00300 from '../json/SignedBlock.003.00.json';
import { Metadata } from '../metadata';
import metadataStatic from '../metadata/static';
import metadataStatic from '../metadata/static-substrate';
import { GenericBlock as Block } from './Block';
const registry = new TypeRegistry();
+1 -1
View File
@@ -3,7 +3,7 @@
import { TypeRegistry } from '../create';
import { Metadata } from '../metadata';
import metadataStatic from '../metadata/static';
import metadataStatic from '../metadata/static-substrate';
import { GenericCall as Call } from '.';
const registry = new TypeRegistry();
+379 -120
View File
@@ -3,29 +3,159 @@
import type { Vec } from '../codec/Vec';
import type { PortableType } from '../interfaces/metadata';
import type { SiField, SiLookupTypeId, SiType, SiTypeDefArray, SiTypeDefCompact, SiTypeDefComposite, SiTypeDefSequence, SiTypeDefTuple, SiTypeDefVariant, SiVariant } from '../interfaces/scaleInfo';
import type { SiField, SiLookupTypeId, SiPath, SiType, SiTypeDefArray, SiTypeDefCompact, SiTypeDefComposite, SiTypeDefSequence, SiTypeDefTuple, SiTypeDefVariant, SiTypeParameter, SiVariant } from '../interfaces/scaleInfo';
import type { Text } from '../primitive/Text';
import type { Type } from '../primitive/Type';
import type { Registry, TypeDef } from '../types';
import { assert, isNumber, isString, stringCamelCase, stringify } from '@polkadot/util';
import { assert, isNumber, isString, stringCamelCase, stringify, stringUpperFirst } from '@polkadot/util';
import { Struct } from '../codec/Struct';
import { withTypeString } from '../create/encodeTypes';
import { getTypeDef } from '../create/getTypeDef';
import { TypeDefInfo } from '../types';
// Alias the primitive enum with out known values
const PRIMITIVE_ALIAS: Record<string, string> = {
Char: 'u32', // Rust char is 4-bytes
Str: 'Text'
};
const INK_PRIMITIVE_ALWAYS = ['AccountId', 'AccountIndex', 'Address', 'Balance'];
// These are types where we have a specific decoding/encoding override + helpers
const PRIMITIVE_PATHS = [
// match {node, polkadot, ...}_runtime
'*_runtime::Call',
'*_runtime::Event',
// these have a specific encoding or logic (for pallets)
'pallet_democracy::vote::Vote',
'pallet_identity::types::Data',
// these are well-known types with additional encoding
'sp_core::crypto::AccountId32',
'sp_runtime::generic::era::Era',
'sp_runtime::multiaddress::MultiAddress',
// shorten some well-known types
'primitive_types::*',
'sp_arithmetic::per_things::*',
// ink!
'ink_env::types::*'
].map((p) => p.split('::'));
// Mappings for types that should be converted to set via BitVec
const SETS = [
'pallet_identity::types::BitFlags'
].map((p) => p.split('::'));
// These we never use these as top-level names, they are wrappers
const WRAPPERS = ['BoundedBTreeMap', 'BoundedVec', 'Box', 'BTreeMap', 'Cow', 'Result', 'Option', 'WeakBoundedVec'];
// These are reserved and/or conflicts with built-in Codec definitions
const RESERVED = ['call', 'entries', 'hash', 'keys', 'new', 'size'];
function matchParts (first: string[], second: (string | Text)[]): boolean {
return first.length === second.length && first.every((a, index) => {
const b = second[index].toString();
return (a === '*') || (a === b) || (
a.includes('*') &&
a.includes('_') &&
b.includes('_') &&
matchParts(a.split('_'), b.split('_'))
);
});
}
// check if the path matches the PRIMITIVE_SP (with wildcards)
function getPrimitivePath (path: SiPath): string | null {
// TODO We need to handle ink! Balance in some way
return path.length && PRIMITIVE_PATHS.some((p) => matchParts(p, path))
? path[path.length - 1].toString()
: null;
}
function removeDuplicateNames (names: [number, (string | null)][]): [number, (string | null)][] {
return names.map(([lookupIndex, name]): [number, string | null] => [
lookupIndex,
(
!name ||
names.some(([oIndex, oName]) =>
name === oName &&
lookupIndex !== oIndex
)
)
? null
: name
]);
}
function extractName (types: PortableType[], id: SiLookupTypeId, { params, path }: SiType): [number, string | null] {
const lookupIndex = id.toNumber();
if (!path.length || WRAPPERS.includes(path[path.length - 1].toString())) {
return [lookupIndex, null];
}
const parts = path
.map((p) => stringUpperFirst(stringCamelCase(p)))
.filter((p, index) =>
(
// Remove ::{pallet, traits, types}::
index !== 1 ||
!['Pallet', 'Traits', 'Types'].includes(p.toString())
) &&
(
// sp_runtime::generic::digest::Digest -> sp_runtime::generic::Digest
// sp_runtime::multiaddress::MultiAddress -> sp_runtime::MultiAddress
index === path.length - 1 ||
p.toLowerCase() !== path[index + 1].toLowerCase()
)
);
let typeName = parts.join('');
if (parts.length === 2 && parts[parts.length - 1] === 'RawOrigin' && params.length === 2 && params[1].type.isSome) {
// Do magic for RawOrigin lookup
const instanceType = types[params[1].type.unwrap().toNumber()];
if (instanceType.type.path.length === 2) {
typeName = `${typeName}${instanceType.type.path[1].toString()}`;
}
}
return [lookupIndex, typeName];
}
function extractNames (registry: Registry, types: PortableType[]): Record<number, string> {
const dedup = removeDuplicateNames(
types.map(({ id, type }) =>
extractName(types, id, type)
)
);
const [names, typesNew] = dedup.reduce<[Record<number, string>, Record<string, string>]>(([names, types], [lookupIndex, name], index) => {
if (name) {
// We set the name for this specific type
names[index] = name;
// we map to the actual lookupIndex
types[name] = registry.createLookupType(lookupIndex);
}
return [names, types];
}, [{}, {}]);
registry.register(typesNew);
return names;
}
export class GenericPortableRegistry extends Struct {
#names: Record<number, string>;
#typeDefs: Record<number, TypeDef> = {};
constructor (registry: Registry, value?: Uint8Array) {
super(registry, {
types: 'Vec<PortableType>'
}, value);
this.#names = extractNames(registry, this.types);
}
/**
@@ -50,20 +180,50 @@ export class GenericPortableRegistry extends Struct {
* @description Lookup the type definition for the index
*/
public getTypeDef (lookupId: SiLookupTypeId | string | number): TypeDef {
const index = this.#getLookupId(lookupId);
const lookupIndex = this.#getLookupId(lookupId);
if (!this.#typeDefs[index]) {
this.#typeDefs[index] = this.#extract(this.getSiType(lookupId), index);
if (!this.#typeDefs[lookupIndex]) {
// we set first since we will get into circular lookups along the way
this.#typeDefs[lookupIndex] = {
info: TypeDefInfo.DoNotConstruct,
lookupIndex,
lookupName: this.#names[lookupIndex],
type: this.registry.createLookupType(lookupIndex)
};
const extracted = this.#extract(this.getSiType(lookupId), lookupIndex);
Object.keys(extracted).forEach((k): void => {
if (k !== 'lookupName' || extracted[k]) {
// these are safe since we are looking through the keys as set
this.#typeDefs[lookupIndex][k as 'info'] = extracted[k as 'info'];
}
});
// don't set lookupName on lower-level, we want to always direct to the type
if (extracted.info === TypeDefInfo.Plain) {
this.#typeDefs[lookupIndex].lookupNameRoot = this.#typeDefs[lookupIndex].lookupName;
delete this.#typeDefs[lookupIndex].lookupName;
}
}
return this.#typeDefs[index];
return this.#typeDefs[lookupIndex];
}
#createSiDef (type: SiLookupTypeId): TypeDef {
return {
info: TypeDefInfo.Si,
type: this.registry.createLookupType(type)
};
#createSiDef (lookupId: SiLookupTypeId): TypeDef {
const typeDef = this.getTypeDef(lookupId);
const lookupIndex = lookupId.toNumber();
// Setup for a lookup on complex types
return [TypeDefInfo.Enum, TypeDefInfo.Struct].includes(typeDef.info) && typeDef.lookupName
? {
docs: typeDef.docs,
info: TypeDefInfo.Si,
lookupIndex,
lookupName: this.#names[lookupIndex],
type: this.registry.createLookupType(lookupId)
}
: typeDef;
}
#getLookupId (lookupId: SiLookupTypeId | string | number): number {
@@ -80,29 +240,20 @@ export class GenericPortableRegistry extends Struct {
#extract (type: SiType, lookupIndex: number): TypeDef {
const path = [...type.path];
// We handle ink! here as well, although we still have a different registry there
const isPrimitivePath = !!path.length && (
(
path.length > 2 &&
path[0].eq('ink_env') &&
path[1].eq('types')
) ||
INK_PRIMITIVE_ALWAYS.includes(path[path.length - 1].toString())
);
let typeDef: TypeDef;
const primType = getPrimitivePath(type.path);
try {
if (isPrimitivePath) {
typeDef = this.#extractPrimitivePath(lookupIndex, type);
if (primType) {
typeDef = this.#extractPrimitivePath(lookupIndex, primType);
} else if (type.def.isArray) {
typeDef = this.#extractArray(lookupIndex, type.def.asArray);
} else if (type.def.isCompact) {
typeDef = this.#extractCompact(lookupIndex, type.def.asCompact);
} else if (type.def.isComposite) {
typeDef = this.#extractComposite(lookupIndex, type.def.asComposite);
typeDef = this.#extractComposite(lookupIndex, type, type.def.asComposite);
} else if (type.def.isHistoricMetaCompat) {
typeDef = getTypeDef(type.def.asHistoricMetaCompat);
typeDef = this.#extractHistoric(lookupIndex, type.def.asHistoricMetaCompat);
} else if (type.def.isPrimitive) {
typeDef = this.#extractPrimitive(lookupIndex, type);
} else if (type.def.isSequence) {
@@ -115,45 +266,60 @@ export class GenericPortableRegistry extends Struct {
throw new Error(`Invalid type at index ${lookupIndex}: No handler for ${type.def.toString()}`);
}
} catch (error) {
throw new Error(`PortableRegistry: Error extracting ${stringify(type)}: ${(error as Error).message}`);
throw new Error(`PortableRegistry: ${lookupIndex}: Error extracting ${stringify(type)}: ${(error as Error).message}`);
}
const displayName = path.pop()?.toString();
return {
...(displayName
? { displayName }
: {}
),
...(path.length > 1
? { namespace: path.map((s) => s.toString()).join('::') }
: {}
),
docs: type.docs.map((d) => d.toString()),
namespace: path.join('::'),
...typeDef
};
}
#extractArray (lookupIndex: number, { len: length, type }: SiTypeDefArray): TypeDef {
assert(!length || length.toNumber() <= 256, 'PortableRegistry: Only support for [Type; <length>], where length <= 256');
assert(!length || length.toNumber() <= 256, () => `PortableRegistry: ${lookupIndex}: Only support for [Type; <length>], where length <= 256`);
return {
return withTypeString(this.registry, {
info: TypeDefInfo.VecFixed,
length: length.toNumber(),
sub: this.#createSiDef(type),
type: this.registry.createLookupType(lookupIndex)
};
sub: this.#createSiDef(type)
});
}
#extractCompact (lookupIndex: number, { type }: SiTypeDefCompact): TypeDef {
return {
#extractCompact (_: number, { type }: SiTypeDefCompact): TypeDef {
return withTypeString(this.registry, {
info: TypeDefInfo.Compact,
sub: this.#createSiDef(type),
type: this.registry.createLookupType(lookupIndex)
};
sub: this.#createSiDef(type)
});
}
#extractComposite (lookupIndex: number, { fields }: SiTypeDefComposite): TypeDef {
return this.#extractFields(lookupIndex, fields);
#extractComposite (lookupIndex: number, { params, path }: SiType, { fields }: SiTypeDefComposite): TypeDef {
if (path.length === 1 && path[0].eq('BTreeMap')) {
return withTypeString(this.registry, {
info: TypeDefInfo.BTreeMap,
sub: params.map(({ type }) => this.#createSiDef(type.unwrap()))
});
}
return SETS.some((p) => matchParts(p, path))
? this.#extractCompositeSet(lookupIndex, params, fields)
: this.#extractFields(lookupIndex, fields);
}
#extractCompositeSet (lookupIndex: number, params: SiTypeParameter[], fields: SiField[]): TypeDef {
assert(params.length === 1 && fields.length === 1, () => `PortableRegistry: ${lookupIndex}: Set handling expects since param and single field`);
return withTypeString(this.registry, {
info: TypeDefInfo.Set,
length: this.registry.createType(this.registry.createLookupType(fields[0].type) as 'u32').bitLength(),
sub: this.getSiType(params[0].type.unwrap()).def.asVariant.variants.map(({ index, name }): TypeDef => ({
// This will be an issue > 2^53 - 1 ... don't have those (yet)
index: index.toNumber(),
info: TypeDefInfo.Plain,
name: name.toString(),
type: 'Null'
}))
});
}
#extractFields (lookupIndex: number, fields: SiField[]): TypeDef {
@@ -163,43 +329,96 @@ export class GenericPortableRegistry extends Struct {
]),
[true, true]);
assert(isTuple || isStruct, 'PortableRegistry: Invalid fields type detected, expected either Tuple or Struct');
assert(isTuple || isStruct, () => `PortableRegistry: ${lookupIndex}: Invalid fields type detected, expected either Tuple (all unnamed) or Struct (all named)`);
if (isTuple) {
if (fields.length === 0) {
return {
info: TypeDefInfo.Null,
type: 'Null'
};
} else if (fields.length === 1) {
return {
...this.#createSiDef(fields[0].type),
...(fields[0].name.isSome
? { name: stringCamelCase(fields[0].name.unwrap()) }
: {}
)
};
}
if (fields.length === 0) {
return {
info: TypeDefInfo.Null,
type: 'Null'
};
} else if (isTuple && fields.length === 1) {
const typeDef = this.#createSiDef(fields[0].type);
return {
...typeDef,
...(
lookupIndex === -1
? {}
: {
lookupIndex,
lookupName: this.#names[lookupIndex],
lookupNameRoot: typeDef.lookupName
}
)
};
}
const sub = fields.map(({ name, type }) => ({
...this.#createSiDef(type),
...(name.isSome
? { name: stringCamelCase(name.unwrap()) }
: {}
)
}));
const [sub, alias] = this.#extractFieldsAlias(fields);
return {
return withTypeString(this.registry, {
info: isTuple // Tuple check first
? TypeDefInfo.Tuple
: TypeDefInfo.Struct,
sub,
type: `(${sub.map(({ type }) => type).join(',')})`
...(
alias.size
? { alias }
: {}
),
...(
lookupIndex === -1
? {}
: {
lookupIndex,
lookupName: this.#names[lookupIndex]
}
),
sub
});
}
#extractFieldsAlias (fields: SiField[]): [TypeDef[], Map<string, string>] {
const alias = new Map<string, string>();
const sub = fields.map(({ docs, name, type }) => {
const typeDef = this.#createSiDef(type);
if (name.isNone) {
return typeDef;
}
let nameField = stringCamelCase(name.unwrap());
let nameOrig: string | null = null;
if (nameField.includes('#')) {
nameOrig = nameField;
nameField = nameOrig.replace(/#/g, '_');
} else if (RESERVED.includes(nameField)) {
nameOrig = nameField;
nameField = `${nameField}_`;
}
if (nameOrig) {
alias.set(nameField, nameOrig);
}
return {
...typeDef,
docs: docs.map((d) => d.toString()),
name: nameField
};
});
return [sub, alias];
}
#extractHistoric (_: number, type: Type): TypeDef {
return {
...getTypeDef(type),
displayName: type.toString(),
isFromSi: true
};
}
#extractPrimitive (lookupIndex: number, type: SiType): TypeDef {
#extractPrimitive (_: number, type: SiType): TypeDef {
const typeStr = type.def.asPrimitive.type.toString();
return {
@@ -208,68 +427,108 @@ export class GenericPortableRegistry extends Struct {
};
}
#extractPrimitivePath (lookupIndex: number, type: SiType): TypeDef {
#extractPrimitivePath (_: number, type: string): TypeDef {
return {
info: TypeDefInfo.Plain,
type: type.path[type.path.length - 1].toString()
type
};
}
#extractSequence (lookupIndex: number, { type }: SiTypeDefSequence): TypeDef {
return {
const sub = this.#createSiDef(type);
if (sub.type === 'u8') {
return {
info: TypeDefInfo.Plain,
type: 'Bytes'
};
}
return withTypeString(this.registry, {
info: TypeDefInfo.Vec,
sub: this.#createSiDef(type),
type: this.registry.createLookupType(lookupIndex)
};
lookupIndex,
lookupName: this.#names[lookupIndex],
sub
});
}
#extractTuple (lookupIndex: number, ids: SiTypeDefTuple): TypeDef {
return ids.length === 1
? this.getTypeDef(ids[0])
: {
info: TypeDefInfo.Tuple,
sub: ids.map((type) => this.#createSiDef(type)),
type: this.registry.createLookupType(lookupIndex)
if (ids.length === 0) {
return {
info: TypeDefInfo.Null,
type: 'Null'
};
} else if (ids.length === 1) {
return this.getTypeDef(ids[0]);
}
const sub = ids.map((type) => this.#createSiDef(type));
return withTypeString(this.registry, {
info: TypeDefInfo.Tuple,
lookupIndex,
lookupName: this.#names[lookupIndex],
sub
});
}
#extractVariant (lookupIndex: number, { params, path }: SiType, { variants }: SiTypeDefVariant): TypeDef {
const specialVariant = path[0].toString();
return specialVariant === 'Option'
? {
if (specialVariant === 'Option') {
return withTypeString(this.registry, {
info: TypeDefInfo.Option,
sub: this.#createSiDef(params[0].type.unwrap()),
type: this.registry.createLookupType(lookupIndex)
}
: specialVariant === 'Result'
? {
info: TypeDefInfo.Result,
sub: params.map((p, index) => ({
name: ['Ok', 'Error'][index],
...this.#createSiDef(p.type.unwrap())
})),
type: this.registry.createLookupType(lookupIndex)
}
: {
info: TypeDefInfo.Enum,
sub: this.#extractVariantSub(lookupIndex, variants),
type: this.registry.createLookupType(lookupIndex)
};
sub: this.#createSiDef(params[0].type.unwrap())
});
} else if (specialVariant === 'Result') {
return withTypeString(this.registry, {
info: TypeDefInfo.Result,
sub: params.map(({ type }) => this.#createSiDef(type.unwrap())).map((def, index) => ({
name: ['Ok', 'Error'][index],
...def
}))
});
} else if (variants.length === 0) {
return {
info: TypeDefInfo.Null,
type: 'Null'
};
}
return this.#extractVariantEnum(lookupIndex, variants);
}
#extractVariantSub (lookupIndex: number, variants: SiVariant[]): TypeDef[] {
return variants.every(({ fields }) => fields.length === 0)
? variants.map(({ index, name }) => ({
index: index.toNumber(),
info: TypeDefInfo.Plain,
name: name.toString(),
type: 'Null'
}))
: variants.map(({ fields, index, name }) => ({
...this.#extractFields(lookupIndex, fields),
index: index.toNumber(),
name: name.toString()
}));
#extractVariantEnum (lookupIndex: number, variants: SiVariant[]): TypeDef {
const sub: (TypeDef & { name: string })[] = [];
// we may get entries out of order, arrange them first before creating with gaps filled
// NOTE: Since we mutate, use a copy of the array as an input
[...variants]
.sort((a, b) => a.index.cmp(b.index))
.forEach(({ fields, index, name }) => {
const desired = index.toNumber();
while (sub.length !== desired) {
sub.push({
index: sub.length,
info: TypeDefInfo.Null,
name: `Unused${sub.length}`,
type: 'Null'
});
}
sub.push({
...this.#extractFields(-1, fields),
index: index.toNumber(),
name: name.toString()
});
});
return withTypeString(this.registry, {
info: TypeDefInfo.Enum,
lookupIndex,
lookupName: this.#names[lookupIndex],
sub
});
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
import type { Codec } from './types';
import * as definitions from './interfaces/definitions';
import metadataStatic from './metadata/static';
import metadataStatic from './metadata/static-substrate';
import { createTypeUnsafe, TypeRegistry } from './create';
import * as exported from './index.types';
import { Metadata } from './metadata';
@@ -12,11 +12,82 @@ export default {
BridgedBlockHash: 'H256',
BridgedBlockNumber: 'BlockNumber',
BridgedHeader: 'Header',
CallOrigin: {
_enum: {
SourceRoot: 'Null',
TargetAccount: '(AccountId, MultiSigner, MultiSignature)',
SourceAccount: 'AccountId'
}
},
ChainId: '[u8; 4]',
DeliveredMessages: {
begin: 'MessageNonce',
end: 'MessageNonce',
// pub type DispatchResultsBitVec = BitVec<Msb0, u8>;
dispatchResults: 'BitVec'
},
DispatchFeePayment: {
_enum: ['AtSourceChain', 'AtTargetChain']
},
InboundLaneData: {
relayers: 'Vec<UnrewardedRelayer>',
lastConfirmedNonce: 'MessageNonce'
},
InboundRelayer: 'AccountId',
InitializationData: {
header: 'Header',
authorityList: 'AuthorityList',
setId: 'SetId',
isHalted: 'bool'
},
LaneId: '[u8; 4]',
MessageData: {
payload: 'Bytes',
fee: 'Balance'
},
MessagesDeliveryProofOf: {
bridgedHeaderHash: 'BlockHash',
storageProof: 'Vec<Bytes>',
lane: 'LaneId'
},
MessageKey: {
laneId: 'LaneId',
nonce: 'MessageNonce'
},
MessageNonce: 'u64',
MessagesProofOf: {
bridgedHeaderHash: 'BridgedBlockHash',
storageProof: 'Vec<Bytes>',
lane: 'LaneId',
noncesStart: 'MessageNonce',
noncesEnd: 'MessageNonce'
},
OperatingMode: {
_enum: ['Normal', 'RejectingOutboundMessages', 'Halted']
},
OutboundLaneData: {
latestGeneratedNonce: 'MessageNonce',
latestReceivedNonce: 'MessageNonce',
oldestUnprunedNonce: 'MessageNonce'
},
OutboundMessageFee: 'Balance',
OutboundPayload: {
specVersion: 'u32',
weight: 'Weight',
origin: 'CallOrigin',
dispatchFeePayment: 'DispatchFeePayment',
call: 'Bytes'
},
Parameter: 'Null',
RelayerId: 'AccountId',
UnrewardedRelayer: {
relayer: 'RelayerId',
messages: 'DeliveredMessages'
},
UnrewardedRelayersState: {
unrewardedRelayer_Entries: 'MessageNonce',
messagesInOldestEntry: 'MessageNonce',
totalMessages: 'MessageNonce'
}
}
} as Definitions;
+118 -2
View File
@@ -1,9 +1,12 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
import type { Struct, bool } from '@polkadot/types';
import type { BitVec, Bytes, Enum, Null, Struct, U8aFixed, Vec, bool, u32, u64 } from '@polkadot/types';
import type { ITuple } from '@polkadot/types/types';
import type { BlockHash } from '@polkadot/types/interfaces/chain';
import type { MultiSignature } from '@polkadot/types/interfaces/extrinsics';
import type { AuthorityList, SetId } from '@polkadot/types/interfaces/grandpa';
import type { BlockNumber, H256, Header } from '@polkadot/types/interfaces/runtime';
import type { AccountId, Balance, BlockNumber, H256, Header, MultiSigner, Weight } from '@polkadot/types/interfaces/runtime';
/** @name BridgedBlockHash */
export interface BridgedBlockHash extends H256 {}
@@ -14,6 +17,40 @@ export interface BridgedBlockNumber extends BlockNumber {}
/** @name BridgedHeader */
export interface BridgedHeader extends Header {}
/** @name CallOrigin */
export interface CallOrigin extends Enum {
readonly isSourceRoot: boolean;
readonly isTargetAccount: boolean;
readonly asTargetAccount: ITuple<[AccountId, MultiSigner, MultiSignature]>;
readonly isSourceAccount: boolean;
readonly asSourceAccount: AccountId;
}
/** @name ChainId */
export interface ChainId extends U8aFixed {}
/** @name DeliveredMessages */
export interface DeliveredMessages extends Struct {
readonly begin: MessageNonce;
readonly end: MessageNonce;
readonly dispatchResults: BitVec;
}
/** @name DispatchFeePayment */
export interface DispatchFeePayment extends Enum {
readonly isAtSourceChain: boolean;
readonly isAtTargetChain: boolean;
}
/** @name InboundLaneData */
export interface InboundLaneData extends Struct {
readonly relayers: Vec<UnrewardedRelayer>;
readonly lastConfirmedNonce: MessageNonce;
}
/** @name InboundRelayer */
export interface InboundRelayer extends AccountId {}
/** @name InitializationData */
export interface InitializationData extends Struct {
readonly header: Header;
@@ -22,4 +59,83 @@ export interface InitializationData extends Struct {
readonly isHalted: bool;
}
/** @name LaneId */
export interface LaneId extends U8aFixed {}
/** @name MessageData */
export interface MessageData extends Struct {
readonly payload: Bytes;
readonly fee: Balance;
}
/** @name MessageKey */
export interface MessageKey extends Struct {
readonly laneId: LaneId;
readonly nonce: MessageNonce;
}
/** @name MessageNonce */
export interface MessageNonce extends u64 {}
/** @name MessagesDeliveryProofOf */
export interface MessagesDeliveryProofOf extends Struct {
readonly bridgedHeaderHash: BlockHash;
readonly storageProof: Vec<Bytes>;
readonly lane: LaneId;
}
/** @name MessagesProofOf */
export interface MessagesProofOf extends Struct {
readonly bridgedHeaderHash: BridgedBlockHash;
readonly storageProof: Vec<Bytes>;
readonly lane: LaneId;
readonly noncesStart: MessageNonce;
readonly noncesEnd: MessageNonce;
}
/** @name OperatingMode */
export interface OperatingMode extends Enum {
readonly isNormal: boolean;
readonly isRejectingOutboundMessages: boolean;
readonly isHalted: boolean;
}
/** @name OutboundLaneData */
export interface OutboundLaneData extends Struct {
readonly latestGeneratedNonce: MessageNonce;
readonly latestReceivedNonce: MessageNonce;
readonly oldestUnprunedNonce: MessageNonce;
}
/** @name OutboundMessageFee */
export interface OutboundMessageFee extends Balance {}
/** @name OutboundPayload */
export interface OutboundPayload extends Struct {
readonly specVersion: u32;
readonly weight: Weight;
readonly origin: CallOrigin;
readonly dispatchFeePayment: DispatchFeePayment;
readonly call: Bytes;
}
/** @name Parameter */
export interface Parameter extends Null {}
/** @name RelayerId */
export interface RelayerId extends AccountId {}
/** @name UnrewardedRelayer */
export interface UnrewardedRelayer extends Struct {
readonly relayer: RelayerId;
readonly messages: DeliveredMessages;
}
/** @name UnrewardedRelayersState */
export interface UnrewardedRelayersState extends Struct {
readonly unrewardedRelayer_Entries: MessageNonce;
readonly messagesInOldestEntry: MessageNonce;
readonly totalMessages: MessageNonce;
}
export type PHANTOM_BRIDGES = 'bridges';
@@ -20,6 +20,7 @@ export default {
ExtrinsicPayloadUnknown: 'GenericExtrinsicPayloadUnknown',
// eras
Era: 'ExtrinsicEra',
ImmortalEra: 'GenericImmortalEra',
MortalEra: 'GenericMortalEra',
@@ -13,6 +13,9 @@ export interface EcdsaSignature extends U8aFixed {}
/** @name Ed25519Signature */
export interface Ed25519Signature extends H512 {}
/** @name Era */
export interface Era extends ExtrinsicEra {}
/** @name Extrinsic */
export interface Extrinsic extends GenericExtrinsic {}
+105 -13
View File
@@ -2,7 +2,7 @@
/* eslint-disable */
import type { Bytes, Enum, GenericPortableRegistry, Option, Struct, Text, Type, Vec, bool, u8 } from '@polkadot/types';
import type { SiLookupTypeId, SiType } from '@polkadot/types/interfaces/scaleInfo';
import type { SiField, SiLookupTypeId, SiType } from '@polkadot/types/interfaces/scaleInfo';
/** @name ErrorMetadataLatest */
export interface ErrorMetadataLatest extends ErrorMetadataV13 {}
@@ -19,6 +19,15 @@ export interface ErrorMetadataV12 extends ErrorMetadataV11 {}
/** @name ErrorMetadataV13 */
export interface ErrorMetadataV13 extends ErrorMetadataV12 {}
/** @name ErrorMetadataV14 */
export interface ErrorMetadataV14 extends Struct {
readonly name: Text;
readonly fields: Vec<SiField>;
readonly index: u8;
readonly docs: Vec<Text>;
readonly args: Vec<Type>;
}
/** @name ErrorMetadataV9 */
export interface ErrorMetadataV9 extends Struct {
readonly name: Text;
@@ -40,6 +49,15 @@ export interface EventMetadataV12 extends EventMetadataV11 {}
/** @name EventMetadataV13 */
export interface EventMetadataV13 extends EventMetadataV12 {}
/** @name EventMetadataV14 */
export interface EventMetadataV14 extends Struct {
readonly name: Text;
readonly fields: Vec<SiField>;
readonly index: u8;
readonly docs: Vec<Text>;
readonly args: Vec<Type>;
}
/** @name EventMetadataV9 */
export interface EventMetadataV9 extends Struct {
readonly name: Text;
@@ -84,6 +102,9 @@ export interface FunctionArgumentMetadataV12 extends FunctionArgumentMetadataV11
/** @name FunctionArgumentMetadataV13 */
export interface FunctionArgumentMetadataV13 extends FunctionArgumentMetadataV12 {}
/** @name FunctionArgumentMetadataV14 */
export interface FunctionArgumentMetadataV14 extends FunctionArgumentMetadataV13 {}
/** @name FunctionArgumentMetadataV9 */
export interface FunctionArgumentMetadataV9 extends Struct {
readonly name: Text;
@@ -105,6 +126,15 @@ export interface FunctionMetadataV12 extends FunctionMetadataV11 {}
/** @name FunctionMetadataV13 */
export interface FunctionMetadataV13 extends FunctionMetadataV12 {}
/** @name FunctionMetadataV14 */
export interface FunctionMetadataV14 extends Struct {
readonly name: Text;
readonly fields: Vec<SiField>;
readonly index: u8;
readonly docs: Vec<Text>;
readonly args: Vec<FunctionArgumentMetadataLatest>;
}
/** @name FunctionMetadataV9 */
export interface FunctionMetadataV9 extends Struct {
readonly name: Text;
@@ -405,9 +435,20 @@ export interface StorageEntryTypeV10 extends Enum {
readonly isPlain: boolean;
readonly asPlain: Type;
readonly isMap: boolean;
readonly asMap: { hasher: StorageHasherV10; key: Type; value: Type; linked: bool; } & Struct;
readonly asMap: {
readonly hasher: StorageHasherV10;
readonly key: Type;
readonly value: Type;
readonly linked: bool;
} & Struct;
readonly isDoubleMap: boolean;
readonly asDoubleMap: { hasher: StorageHasherV10; key1: Type; key2: Type; value: Type; key2Hasher: StorageHasherV10; } & Struct;
readonly asDoubleMap: {
readonly hasher: StorageHasherV10;
readonly key1: Type;
readonly key2: Type;
readonly value: Type;
readonly key2Hasher: StorageHasherV10;
} & Struct;
}
/** @name StorageEntryTypeV11 */
@@ -415,9 +456,20 @@ export interface StorageEntryTypeV11 extends Enum {
readonly isPlain: boolean;
readonly asPlain: Type;
readonly isMap: boolean;
readonly asMap: { hasher: StorageHasherV11; key: Type; value: Type; linked: bool; } & Struct;
readonly asMap: {
readonly hasher: StorageHasherV11;
readonly key: Type;
readonly value: Type;
readonly linked: bool;
} & Struct;
readonly isDoubleMap: boolean;
readonly asDoubleMap: { hasher: StorageHasherV11; key1: Type; key2: Type; value: Type; key2Hasher: StorageHasherV11; } & Struct;
readonly asDoubleMap: {
readonly hasher: StorageHasherV11;
readonly key1: Type;
readonly key2: Type;
readonly value: Type;
readonly key2Hasher: StorageHasherV11;
} & Struct;
}
/** @name StorageEntryTypeV12 */
@@ -428,11 +480,26 @@ export interface StorageEntryTypeV13 extends Enum {
readonly isPlain: boolean;
readonly asPlain: Type;
readonly isMap: boolean;
readonly asMap: { hasher: StorageHasherV13; key: Type; value: Type; linked: bool; } & Struct;
readonly asMap: {
readonly hasher: StorageHasherV13;
readonly key: Type;
readonly value: Type;
readonly linked: bool;
} & Struct;
readonly isDoubleMap: boolean;
readonly asDoubleMap: { hasher: StorageHasherV13; key1: Type; key2: Type; value: Type; key2Hasher: StorageHasherV13; } & Struct;
readonly asDoubleMap: {
readonly hasher: StorageHasherV13;
readonly key1: Type;
readonly key2: Type;
readonly value: Type;
readonly key2Hasher: StorageHasherV13;
} & Struct;
readonly isNMap: boolean;
readonly asNMap: { keyVec: Vec<Type>; hashers: Vec<StorageHasherV13>; value: Type; } & Struct;
readonly asNMap: {
readonly keyVec: Vec<Type>;
readonly hashers: Vec<StorageHasherV13>;
readonly value: Type;
} & Struct;
}
/** @name StorageEntryTypeV14 */
@@ -440,11 +507,25 @@ export interface StorageEntryTypeV14 extends Enum {
readonly isPlain: boolean;
readonly asPlain: SiLookupTypeId;
readonly isMap: boolean;
readonly asMap: { hasher: StorageHasherV14; key: SiLookupTypeId; value: SiLookupTypeId; } & Struct;
readonly asMap: {
readonly hasher: StorageHasherV14;
readonly key: SiLookupTypeId;
readonly value: SiLookupTypeId;
} & Struct;
readonly isDoubleMap: boolean;
readonly asDoubleMap: { hasher: StorageHasherV14; key1: SiLookupTypeId; key2: SiLookupTypeId; value: SiLookupTypeId; key2Hasher: StorageHasherV14; } & Struct;
readonly asDoubleMap: {
readonly hasher: StorageHasherV14;
readonly key1: SiLookupTypeId;
readonly key2: SiLookupTypeId;
readonly value: SiLookupTypeId;
readonly key2Hasher: StorageHasherV14;
} & Struct;
readonly isNMap: boolean;
readonly asNMap: { key: SiLookupTypeId; hashers: Vec<StorageHasherV14>; value: SiLookupTypeId; } & Struct;
readonly asNMap: {
readonly key: SiLookupTypeId;
readonly hashers: Vec<StorageHasherV14>;
readonly value: SiLookupTypeId;
} & Struct;
}
/** @name StorageEntryTypeV9 */
@@ -452,9 +533,20 @@ export interface StorageEntryTypeV9 extends Enum {
readonly isPlain: boolean;
readonly asPlain: Type;
readonly isMap: boolean;
readonly asMap: { hasher: StorageHasherV9; key: Type; value: Type; linked: bool; } & Struct;
readonly asMap: {
readonly hasher: StorageHasherV9;
readonly key: Type;
readonly value: Type;
readonly linked: bool;
} & Struct;
readonly isDoubleMap: boolean;
readonly asDoubleMap: { hasher: StorageHasherV9; key1: Type; key2: Type; value: Type; key2Hasher: StorageHasherV9; } & Struct;
readonly asDoubleMap: {
readonly hasher: StorageHasherV9;
readonly key1: Type;
readonly key2: Type;
readonly value: Type;
readonly key2Hasher: StorageHasherV9;
} & Struct;
}
/** @name StorageHasher */
@@ -6,6 +6,8 @@
import type { DefinitionsTypes } from '../../types';
import { SiVariant } from '../scaleInfo/definitions';
export const v14: DefinitionsTypes = {
// registry
PortableRegistry: 'GenericPortableRegistry',
@@ -14,6 +16,21 @@ export const v14: DefinitionsTypes = {
type: 'SiType'
},
// compatibility with earlier layouts, i.e. don't break previous users
ErrorMetadataV14: {
...SiVariant,
args: 'Vec<Type>'
},
EventMetadataV14: {
...SiVariant,
args: 'Vec<Type>'
},
FunctionArgumentMetadataV14: 'FunctionArgumentMetadataV13',
FunctionMetadataV14: {
...SiVariant,
args: 'Vec<FunctionArgumentMetadataLatest>'
},
// V14
ExtrinsicMetadataV14: {
type: 'SiLookupTypeId',
@@ -8,6 +8,13 @@ import { v0 } from './v0';
// order important in structs... :)
/* eslint-disable sort-keys */
export const SiVariant = {
name: 'Text',
fields: 'Vec<SiField>',
index: 'u8',
docs: 'Vec<Text>'
};
export default {
rpc: {},
types: {
@@ -69,11 +76,6 @@ export default {
name: 'Text',
type: 'Option<SiLookupTypeId>'
},
SiVariant: {
name: 'Text',
fields: 'Vec<SiField>',
index: 'u8',
docs: 'Vec<Text>'
}
SiVariant
}
} as Definitions;
@@ -139,6 +139,13 @@ const phragmen = {
deposit: 'Balance'
},
SignedSubmission: {
_fallback: 'SignedSubmissionTo276',
who: 'AccountId',
deposit: 'Balance',
solution: 'RawSolution',
reward: 'Balance'
},
SignedSubmissionTo276: {
who: 'AccountId',
deposit: 'Balance',
solution: 'RawSolution'
@@ -265,11 +265,19 @@ export interface SignedSubmission extends Struct {
readonly who: AccountId;
readonly deposit: Balance;
readonly solution: RawSolution;
readonly reward: Balance;
}
/** @name SignedSubmissionOf */
export interface SignedSubmissionOf extends SignedSubmission {}
/** @name SignedSubmissionTo276 */
export interface SignedSubmissionTo276 extends Struct {
readonly who: AccountId;
readonly deposit: Balance;
readonly solution: RawSolution;
}
/** @name SlashingSpans */
export interface SlashingSpans extends Struct {
readonly spanIndex: SpanIndex;
@@ -8,7 +8,7 @@ import { TypeRegistry } from '../../create';
import json1 from '../../json/EventRecord.001.json';
import json3 from '../../json/EventRecord.003.json';
import { Metadata } from '../../metadata';
import rpcMetadata from '../../metadata/static';
import rpcMetadata from '../../metadata/static-substrate';
describe('EventRecord', (): void => {
const registry = new TypeRegistry();
+1 -1
View File
@@ -3,7 +3,7 @@
import { TypeRegistry } from '../create';
import { Metadata } from './Metadata';
import substrateData from './static';
import substrateData from './static-substrate';
describe('Metadata', (): void => {
it('allows creation from hex with JSON equivalence', (): void => {
@@ -6,8 +6,8 @@ import type { Constants } from '../types';
import { TypeRegistry } from '../../../create';
import { Metadata } from '../../Metadata';
import rpcMetadata from '../../static';
import rpcMetadataV10 from '../../v10/static';
import rpcMetadata from '../../static-substrate';
import rpcMetadataV10 from '../../v10/substrate-hex';
import { decorateConstants } from '..';
function init (meta: string): [Constants, TypeRegistry] {
@@ -18,7 +18,9 @@ export function decorateErrors (_: Registry, { modules }: MetadataLatest, metaVe
return result;
}
const sectionIndex = metaVersion >= 12 ? index.toNumber() : _sectionIndex;
const sectionIndex = metaVersion >= 12
? index.toNumber()
: _sectionIndex;
result[stringCamelCase(name)] = errors.reduce((newModule: ModuleErrors, meta, errorIndex): ModuleErrors => {
// we don't camelCase the error name
@@ -16,7 +16,9 @@ export function decorateEvents (_: Registry, { modules }: MetadataLatest, metaVe
return modules
.filter(({ events }) => events.isSome)
.reduce((result: Events, { events, index, name }, _sectionIndex): Events => {
const sectionIndex = metaVersion >= 12 ? index.toNumber() : _sectionIndex;
const sectionIndex = metaVersion >= 12
? index.toNumber()
: _sectionIndex;
result[stringCamelCase(name)] = events.unwrap().reduce((newModule: ModuleEvents, meta, eventIndex): ModuleEvents => {
// we don't camelCase the event name
@@ -6,7 +6,7 @@ import { BN } from '@polkadot/util';
import { TypeRegistry } from '../../../create';
import { Metadata } from '../../Metadata';
import metadataStatic from '../../static';
import metadataStatic from '../../static-substrate';
import { decorateExtrinsics } from '..';
const keyring = createTestPairs({ type: 'ed25519' }, false);
@@ -14,7 +14,9 @@ export function decorateExtrinsics (registry: Registry, { modules }: MetadataLat
return modules
.filter(({ calls }) => calls.isSome)
.reduce((result: Extrinsics, { calls, index, name }, _sectionIndex): Extrinsics => {
const sectionIndex = metaVersion >= 12 ? index.toNumber() : _sectionIndex;
const sectionIndex = metaVersion >= 12
? index.toNumber()
: _sectionIndex;
const section = stringCamelCase(name);
result[section] = calls.unwrap().reduce((newModule: ModuleExtrinsics, callMetadata, methodIndex): ModuleExtrinsics => {
@@ -5,7 +5,7 @@ import { u8aToHex } from '@polkadot/util';
import { TypeRegistry } from '../../create';
import { Metadata } from '../Metadata';
import json from '../static';
import json from '../static-substrate';
import { decorateConstants, decorateExtrinsics, decorateStorage } from './';
const registry = new TypeRegistry();
@@ -6,7 +6,7 @@ import { u8aToHex } from '@polkadot/util';
import { TypeRegistry } from '../../../create';
import { Metadata } from '../../';
import rpcMetadata from '../../static';
import rpcMetadata from '../../static-substrate';
import { decorateStorage } from '..';
const keyring = createTestPairs({ type: 'ed25519' });
@@ -1,6 +1,6 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import metadata from './v13/static';
import metadata from './v13/polkadot-hex';
export default metadata;
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import metadata from './v13/substrate-hex';
export default metadata;
+23 -6
View File
@@ -3,24 +3,26 @@
import type { Codec, Registry } from '../../types';
import type { MetadataInterface } from '../types';
import type { Check } from './types';
import { assert, hexToU8a, stringify, u8aToHex } from '@polkadot/util';
import { TypeRegistry } from '../../create';
import { unwrapStorageType } from '../../primitive/StorageKey';
import { Metadata } from '../Metadata';
import { getUniqTypes } from './getUniqTypes';
/** @internal */
export function decodeLatestSubstrate<Modules extends Codec> (registry: Registry, version: number, rpcData: string, staticSubstrate: Record<string, unknown>): void {
it('decodes latest substrate properly', (): void => {
const metadata = new Metadata(registry, rpcData);
export function decodeLatestMeta<Modules extends Codec> (registry: Registry, version: number, { compare, data }: Check): void {
it('decodes metadata properly', (): void => {
const metadata = new Metadata(registry, data);
registry.setMetadata(metadata);
try {
expect(metadata.version).toBe(version);
expect((metadata[`asV${version}` as keyof Metadata] as unknown as MetadataInterface<Modules>).modules.length).not.toBe(0);
expect(metadata.toJSON()).toEqual(staticSubstrate);
expect(metadata.toJSON()).toEqual(compare);
} catch (error) {
console.error(stringify(metadata.toJSON()));
@@ -54,10 +56,10 @@ export function defaultValues (registry: Registry, rpcData: string, withThrow =
metadata.asLatest.modules.filter(({ storage }): boolean => storage.isSome).forEach((mod): void => {
mod.storage.unwrap().items.forEach(({ fallback, modifier, name, type }): void => {
const inner = unwrapStorageType(type, modifier.isOptional);
const inner = unwrapStorageType(registry, type, modifier.isOptional);
const location = `${mod.name.toString()}.${name.toString()}: ${inner}`;
it(`creates default types for ${location}`, (): void => {
it(location, (): void => {
expect((): void => {
try {
const type = registry.createType(inner, hexToU8a(fallback.toHex()));
@@ -82,3 +84,18 @@ export function defaultValues (registry: Registry, rpcData: string, withThrow =
});
});
}
export function testMeta (version: number, matchers: Record<string, Check>, withFallback = true): void {
describe(`MetadataV${version}`, (): void => {
describe.each(Object.keys(matchers))('%s', (type): void => {
const matcher = matchers[type];
const registry = new TypeRegistry();
decodeLatestMeta(registry, version, matcher);
toLatest(registry, version, matcher.data);
defaultValues(registry, matcher.data, true, withFallback);
});
});
}

Some files were not shown because too many files have changed in this diff Show More