Compare commits

...
85 Commits
Author SHA1 Message Date
github-actions[bot] 0a9158befc [CI Skip] release/stable 8.10.1
skip-checks: true
2022-06-26 06:56:57 +00:00
Jaco 9c4e984f7b 8.10.1 (#4986) 2022-06-26 09:49:34 +03:00
github-actions[bot] c1187f4c7a [CI Skip] bump/beta 8.9.2-24-x
skip-checks: true
2022-06-25 09:30:24 +00:00
Jaco e279d50224 Metadata bump (#4985) 2022-06-25 12:22:09 +03:00
github-actions[bot] f28908d28e [CI Skip] release/beta 8.9.2-23
skip-checks: true
2022-06-25 06:50:38 +00:00
Jaco 570cf5fea4 Bump dev (#4984) 2022-06-25 09:43:05 +03:00
github-actions[bot] 7bf5bb7a3b [CI Skip] bump/beta 8.9.2-22-x
skip-checks: true
2022-06-25 05:52:37 +00:00
Jaco 756502771e Bump util to 9.6.2 (#4983) 2022-06-25 08:42:41 +03:00
github-actions[bot] 977eb3f9ec [CI Skip] bump/beta 8.9.2-21-x
skip-checks: true
2022-06-24 04:30:32 +00:00
Jaco 909b3429f2 Update CHANGELOG (#4980)
* Update CHANGELOG

* Additional
2022-06-24 07:21:37 +03:00
github-actions[bot] 116b817696 [CI Skip] bump/beta 8.9.2-20-x
skip-checks: true
2022-06-23 17:31:39 +00:00
Alan Sapede c295d699e7 Adds Eth feeHistory & maxPriorityFeePerGas rpc (#4956)
* Adds Eth feeHistory & maxPriorityFeePerGas

* linted

* Fixes rpc method ordering
2022-06-23 20:22:05 +03:00
github-actions[bot] c8ab0e6959 [CI Skip] bump/beta 8.9.2-19-x
skip-checks: true
2022-06-23 17:11:08 +00:00
Jaco cf52676025 Bump dev (w/ deno build fix) (#4979) 2022-06-23 20:02:51 +03:00
github-actions[bot] 935b176740 [CI Skip] bump/beta 8.9.2-18-x
skip-checks: true
2022-06-23 11:23:19 +00:00
Jaco af9c4e0e4b Bump dev 2022-06-23 14:15:35 +03:00
github-actions[bot] 17eccc0b7b [CI Skip] release/beta 8.9.2-17
skip-checks: true
2022-06-23 09:05:32 +00:00
Jaco 1ba2413c86 Bump deps (#4978) 2022-06-23 11:57:28 +03:00
github-actions[bot] ff69198b1a [CI Skip] release/beta 8.9.2-16
skip-checks: true
2022-06-23 07:10:22 +00:00
Jaco 7b368a3f2d Dev bump (w/ publish) (#4977) 2022-06-23 10:01:03 +03:00
github-actions[bot] 58020291ea [CI Skip] release/beta 8.9.2-15
skip-checks: true
2022-06-23 06:35:43 +00:00
Jaco fb1e428615 Westend 9250 upgrade block (#4976) 2022-06-23 09:25:18 +03:00
github-actions[bot] 2164f80a3c [CI Skip] release/beta 8.9.2-14
skip-checks: true
2022-06-23 06:18:45 +00:00
Jaco 59903dfba3 Bump dev (Only publish betas with explicit indicator) (#4975) 2022-06-23 09:08:57 +03:00
github-actions[bot] 97ded7d284 [CI Skip] release/beta 8.9.2-13
skip-checks: true
2022-06-23 04:02:23 +00:00
Jaco 772ab6e7d1 Bump dev (w/ deno augmentation) (#4974)
* Bump dev (w/ deno augmentation)

* Build deno
2022-06-23 06:54:02 +03:00
github-actions[bot] f7a3907519 [CI Skip] release/beta 8.9.2-12
skip-checks: true
2022-06-23 03:46:07 +00:00
Jaco 891790b2b6 Fix f32/f64 primtive typegen (#4973) 2022-06-23 06:37:02 +03:00
github-actions[bot] fac008f453 [CI Skip] release/beta 8.9.2-11
skip-checks: true
2022-06-22 12:09:06 +00:00
Jaco 32fd91a221 Bump dependencies (#4972) 2022-06-22 15:01:15 +03:00
github-actions[bot] 472ab9acac [CI Skip] release/beta 8.9.2-10
skip-checks: true
2022-06-22 10:12:36 +00:00
Jaco 393f528e89 Support for F32 & F64 (#4958)
* Support for F32 & F64

* Additional

* Adjust

* Expand

* Empty creation

* Empty creation #2 (no params)

* Comment around toJSON()

* createdAtHash

* Float tests

* Comments

* typo

* Expand class description

* Add floats to InterfaceTypes

* Jiggle names

* CHANGELOG
2022-06-22 13:02:41 +03:00
github-actions[bot] 4a9d5fd3c1 [CI Skip] release/beta 8.9.2-9
skip-checks: true
2022-06-22 09:16:52 +00:00
Jaco 8e8bcd5f68 Trigger bundles 2022-06-22 12:07:50 +03:00
Jaco bd300791b5 Bump deps (w/ CI performance skips) (#4971)
* Bump deps (w/ CI performance skips)

* Bump common
2022-06-22 12:05:14 +03:00
github-actions[bot] cd2b3be962 [CI Skip] release/beta 8.9.2-8
skip-checks: true
2022-06-22 07:08:24 +00:00
Jaco 87df83a2b9 Bump deps (#4970) 2022-06-22 09:59:50 +03:00
github-actions[bot] 697688eea5 [CI Skip] release/beta 8.9.2-7
skip-checks: true
2022-06-21 13:09:11 +00:00
Jaco 9bbe095a5d Bump dev (w/ stable deno publish) (#4968)
* Bump dev (w/ stable deno publish)

* Bump dev
2022-06-21 16:01:18 +03:00
github-actions[bot] 51a6e50b09 [CI Skip] release/beta 8.9.2-6
skip-checks: true
2022-06-21 04:56:01 +00:00
Jaco d496ab2d1e Bump TS to 4.7.4 (#4967) 2022-06-21 07:47:59 +03:00
github-actions[bot] 3acca845f7 [CI Skip] release/beta 8.9.2-5
skip-checks: true
2022-06-20 17:45:34 +00:00
Jaco 3a8b1c5683 Adjust assert usage (#4966)
* Adjust assert usage

* Adjust assert

* Apply suggestions from code review
2022-06-20 20:37:17 +03:00
github-actions[bot] 94c5c025a9 [CI Skip] release/beta 8.9.2-4
skip-checks: true
2022-06-20 11:26:54 +00:00
Jaco a7c54d704b AbstractBigInt extensible (also via wrapper) (#4965)
* AbstractBigInt extensible (also via wrapper)

* Add missing package
2022-06-20 14:17:24 +03:00
github-actions[bot] 4640939908 [CI Skip] release/beta 8.9.2-3
skip-checks: true
2022-06-20 10:43:37 +00:00
Jaco 6d07803003 Use static get [Symbol.species] () for Array & Uint8Array types (#4964) 2022-06-20 13:33:24 +03:00
github-actions[bot] 13f7e853e8 [CI Skip] release/beta 8.9.2-2
skip-checks: true
2022-06-20 08:45:34 +00:00
Jaco fbd0e4212f Change Date.now to performance.now (#4963)
* Change Date.now to performance.now

* Additional logs
2022-06-20 11:35:50 +03:00
github-actions[bot] ebb9f5c63b [CI Skip] release/beta 8.9.2-1
skip-checks: true
2022-06-20 07:55:16 +00:00
Nikos Kontakis bffb72f29f Bump substrate connect to 0.7.7 (#4962) 2022-06-20 10:45:02 +03:00
github-actions[bot] 68272615e7 [CI Skip] release/beta 8.9.2-0
skip-checks: true
2022-06-20 05:32:32 +00:00
Jaco 190959dbd4 Beefy payload adjustment (#4961) 2022-06-20 08:24:50 +03:00
github-actions[bot] dbb427be5c [CI Skip] release/stable 8.9.1
skip-checks: true
2022-06-19 05:06:55 +00:00
Jaco 9a18016701 8.9.1 (#4957) 2022-06-19 07:57:41 +03:00
github-actions[bot] bcda5caa39 [CI Skip] release/beta 8.8.3-14
skip-checks: true
2022-06-18 19:33:04 +00:00
Jaco b88cad4b87 Bump Substrate metadata (#4955) 2022-06-18 22:25:42 +03:00
github-actions[bot] c86807c0b8 [CI Skip] release/beta 8.8.3-13
skip-checks: true
2022-06-18 12:42:41 +00:00
Jaco 771f3bc6fd Bump util (#4953) 2022-06-18 15:34:57 +03:00
github-actions[bot] 58a18e1da5 [CI Skip] release/beta 8.8.3-12
skip-checks: true
2022-06-18 10:52:53 +00:00
Jaco b42669f864 Adjust type asserts (#4952) 2022-06-18 13:45:04 +03:00
github-actions[bot] 0d2e938674 [CI Skip] release/beta 8.8.3-11
skip-checks: true
2022-06-18 09:10:54 +00:00
Jaco 98b3b10bd9 Add a hash alias for engine CreatedBlock (#4950) 2022-06-18 12:03:27 +03:00
github-actions[bot] 34a1e0cbe2 [CI Skip] release/beta 8.8.3-10
skip-checks: true
2022-06-18 07:13:01 +00:00
Jaco 44512c1d5f Add Kusama 9230 upgrade block (#4951) 2022-06-18 10:05:39 +03:00
github-actions[bot] 0440ce606a [CI Skip] release/beta 8.8.3-9
skip-checks: true
2022-06-17 15:03:36 +00:00
Jaco c05cb79005 Adjust PortableRegistry objectSpread (#4947) 2022-06-17 17:56:02 +03:00
github-actions[bot] ce39264b77 [CI Skip] release/beta 8.8.3-8
skip-checks: true
2022-06-17 14:28:29 +00:00
Jaco 7c5f82404f Adjust PortableRegistry name extraction (#4946)
* Adjust PortableRegistry name extraction

* Adjust count

* Adjust

* Adjust .every check

* Adjust ink! test outcomes
2022-06-17 17:20:26 +03:00
github-actions[bot] 7da9c5c20b [CI Skip] release/beta 8.8.3-7
skip-checks: true
2022-06-17 08:49:42 +00:00
Jaco ccd3b62632 Use switch internal to decodeFixedVec (#4945) 2022-06-17 11:40:45 +03:00
github-actions[bot] fdf6ec9530 [CI Skip] release/beta 8.8.3-6
skip-checks: true
2022-06-17 08:37:08 +00:00
Jaco 51b583d9ea Adjustments for getTypeDef (#4944)
* Adjustments for getTypeDef

* Cleanup unneeded +

* Adjust sanitize replacers

* Ordering

* Adjust sanitize
2022-06-17 11:29:01 +03:00
github-actions[bot] 6149b6ca76 [CI Skip] release/beta 8.8.3-5
skip-checks: true
2022-06-17 07:46:57 +00:00
Jaco 083e0478c3 Rename Base -> AbstractBase (#4943) 2022-06-17 10:36:44 +03:00
github-actions[bot] ee584f62a7 [CI Skip] release/beta 8.8.3-4
skip-checks: true
2022-06-17 06:56:34 +00:00
Jaco 530909d773 Dedupe internal Codec property access (#4941)
* Dedupe internal Codec property access

* Remove getter override

* OptionBool fixes

* Adjust isBasic

* Remove isBasic check

* Re-add isBasic

* Remove static decodeCompact
2022-06-17 09:46:57 +03:00
github-actions[bot] d0c55a31b8 [CI Skip] release/beta 8.8.3-3
skip-checks: true
2022-06-17 05:38:45 +00:00
Jaco eafd4923fe Bump @polkadot/util (#4942) 2022-06-17 08:29:30 +03:00
github-actions[bot] 264bcaf4ac [CI Skip] release/beta 8.8.3-2
skip-checks: true
2022-06-16 09:32:08 +00:00
Pierre Krieger a25c057ae7 Update substrate/connect to 0.7.6 (#4940) 2022-06-16 12:22:20 +03:00
github-actions[bot] 29927129a1 [CI Skip] release/beta 8.8.3-1
skip-checks: true
2022-06-15 14:59:39 +00:00
Jaco 4385320554 Shortcuts for Compact/Number instantiation (#4939)
* Shortcuts for Compact/Number instantiation

* Move/combine isHex/isString
2022-06-15 17:51:39 +03:00
github-actions[bot] 58eadc4e0f [CI Skip] release/beta 8.8.3-0
skip-checks: true
2022-06-15 08:31:14 +00:00
Jaco 89e4cba131 Adjust PortableRegistry name extraction (#4938)
* Adjust PortableRegistry name extraction

* Adjust contract tests

* Adjust

* Adjust
2022-06-15 11:23:38 +03:00
188 changed files with 15380 additions and 13694 deletions
+1
View File
@@ -0,0 +1 @@
8.10.1
+1
View File
@@ -2,6 +2,7 @@ _book/
build/ build/
build-cjs/ build-cjs/
build-esm/ build-esm/
build-deno/
build-docs/ build-docs/
coverage/ coverage/
docs/.vuepress/dist/ docs/.vuepress/dist/
+38 -1
View File
@@ -1,10 +1,47 @@
# CHANGELOG # CHANGELOG
## 8.10.1 Jun 26, 2022
Contributed:
- Bump `@substrate/connect` to 0.7.7 (Thanks to https://github.com/wirednkod)
- Support `feeHistory` & `maxPriorityFeePerGas` eth RPCs (Thanks to https://github.com/crystalin)
Changes:
- Align `BeefyPayload` with Substrate master
- Use `static get [Symbol.species] ()` for `Array` & `Uint8Array` types
- Add support for (optional, non-runtime recommended) `f32` & `f64` types
- Add future-use `AbstrateBigInt` wrapper extension
- Update Codec-internal performance tests
- Add Westend 9250 upgrade block
- Update to latest Substrate, Polkadot & Kusama metadata
## 8.9.1 Jun 19, 2022
Contributed:
- Update `@substrate/connect` to 0.7.6 (Thanks to https://github.com/tomaka)
Changes:
- Deupe all internal type property getters
- Adjust `@polkadot/types-codec` asserts
- Rename `Base` type to `AbstractBase` (reflecting usage)
- Alias `blockHash` on `rpc.engine.createBlock` return
- Instantiate `Compact/UInt/Int` with `number` when passed
- Adjust name extraction in `PortableRegistry` (maintainability)
- Adjust string type path extraction (maintainability)
- Add Kusama 9230 upgrade block
- Update to latest Substrate metadata
## 8.8.2 Jun 14, 2022 ## 8.8.2 Jun 14, 2022
Changes: Changes:
- Aling historic `DispatchErrorModule` with `U8` variant - Align historic `DispatchErrorModule` with `U8` variant
- Extend lookup type name generation when conflicts arrise - Extend lookup type name generation when conflicts arrise
- Update to latest Substrate metadata - Update to latest Substrate metadata
+4 -2
View File
@@ -1,4 +1,4 @@
3023 Jaco 8.8.2 (#4937) 3063 Jaco 8.10.1 (#4986)
83 Amaury Martiny StatementKind: Regular and Saft (#2303) 83 Amaury Martiny StatementKind: Regular and Saft (#2303)
37 Keith Ingram Update contract types and rpc (#4541) 37 Keith Ingram Update contract types and rpc (#4541)
35 Stefanie Doll Updated child storage parameters (#1709) 35 Stefanie Doll Updated child storage parameters (#1709)
@@ -9,12 +9,12 @@
10 Axel Chalon Make Enum/Tuple constructor use value directly if instance (#1954) 10 Axel Chalon Make Enum/Tuple constructor use value directly if instance (#1954)
5 Chevdor Fix metadata package link (#3458) 5 Chevdor Fix metadata package link (#3458)
5 Jake Naviasky Fixing approvalFlagsToBools. (#1250) 5 Jake Naviasky Fixing approvalFlagsToBools. (#1250)
5 Nikos Kontakis Bump substrate connect to 0.7.7 (#4962)
4 Alex D Use derive customAccount and customLocks for balance overrides (#3248) 4 Alex D Use derive customAccount and customLocks for balance overrides (#3248)
4 Alex Wang fix issue that creates duplicate providers (#983) 4 Alex Wang fix issue that creates duplicate providers (#983)
4 Alexander Popiak Add asset id in signing (#4009) 4 Alexander Popiak Add asset id in signing (#4009)
4 Joshy Orndorff spelling; efect -> effect (#2295) 4 Joshy Orndorff spelling; efect -> effect (#2295)
4 Nantian fix bigint type (#3869) 4 Nantian fix bigint type (#3869)
4 Nikos Kontakis Update substrate connect to 0.7.5 (#4835)
4 Scott Twiname Add support for historical BlockNumber rpc methods (#4574) 4 Scott Twiname Add support for historical BlockNumber rpc methods (#4574)
4 Thibaut Sardan no subscription for http (#3127) 4 Thibaut Sardan no subscription for http (#3127)
3 André Silva add support for ValidationCodeHash (#3640) 3 André Silva add support for ValidationCodeHash (#3640)
@@ -43,6 +43,7 @@
2 Wei Tang Use /usr/bin/env bash instead of /bin/bash (#2053) 2 Wei Tang Use /usr/bin/env bash instead of /bin/bash (#2053)
2 Zannis Kalampoukis fix: Typegen handles structs and vectors of structs without erroring (#4743) 2 Zannis Kalampoukis fix: Typegen handles structs and vectors of structs without erroring (#4743)
2 扩散性百万甜面包 Typo, deocrateMethod -> decorateMethod (#1594) 2 扩散性百万甜面包 Typo, deocrateMethod -> decorateMethod (#1594)
1 Alan Sapede Adds Eth feeHistory & maxPriorityFeePerGas rpc (#4956)
1 Andreea Eftene Add storage deposit support (#4304) 1 Andreea Eftene Add storage deposit support (#4304)
1 Brad Larson [NEW] Support for custom headers with providers (#2423) 1 Brad Larson [NEW] Support for custom headers with providers (#2423)
1 chriswmercer little readme tweak (#279) 1 chriswmercer little readme tweak (#279)
@@ -86,6 +87,7 @@
1 Oleksandr Mykhailenko Add more complex namespaced contracts & test cases for them (#4472) 1 Oleksandr Mykhailenko Add more complex namespaced contracts & test cases for them (#4472)
1 Paul M Fox Basic BTreeMaps codec support (#1474) 1 Paul M Fox Basic BTreeMaps codec support (#1474)
1 philipstanislaus Update types for centrifuge chain v1.2.0 (#2424) 1 philipstanislaus Update types for centrifuge chain v1.2.0 (#2424)
1 Pierre Krieger Update substrate/connect to 0.7.6 (#4940)
1 qiuhao update DeriveCustom type (#2581) 1 qiuhao update DeriveCustom type (#2581)
1 r0t0r-r0t0r Fix memory leak on raw rpc call (#4505) 1 r0t0r-r0t0r Fix memory leak on raw rpc call (#4505)
1 Raphael Flechtner fix: typegen disconnect ws on success (#4901) 1 Raphael Flechtner fix: typegen disconnect ws on success (#4901)
+4 -4
View File
@@ -11,7 +11,7 @@
}, },
"sideEffects": false, "sideEffects": false,
"type": "commonjs", "type": "commonjs",
"version": "8.8.2", "version": "8.10.1",
"workspaces": [ "workspaces": [
"packages/*" "packages/*"
], ],
@@ -34,12 +34,12 @@
"@babel/core": "^7.18.5", "@babel/core": "^7.18.5",
"@babel/register": "^7.17.7", "@babel/register": "^7.17.7",
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/dev": "^0.67.3", "@polkadot/dev": "^0.67.43",
"@polkadot/typegen": "workspace:packages/typegen", "@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^28.1.1", "@types/jest": "^28.1.3",
"copyfiles": "^2.4.1" "copyfiles": "^2.4.1"
}, },
"resolutions": { "resolutions": {
"typescript": "^4.7.3" "typescript": "^4.7.4"
} }
} }
+8 -8
View File
@@ -20,18 +20,18 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/api-base": "8.8.2", "@polkadot/api-base": "8.10.1",
"@polkadot/rpc-augment": "8.8.2", "@polkadot/rpc-augment": "8.10.1",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/types-augment": "8.8.2", "@polkadot/types-augment": "8.10.1",
"@polkadot/types-codec": "8.8.2", "@polkadot/types-codec": "8.10.1",
"@polkadot/util": "^9.4.1" "@polkadot/util": "^9.6.2"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/types-support": "8.8.2" "@polkadot/types-support": "8.10.1"
} }
} }
+10 -9
View File
@@ -895,10 +895,6 @@ declare module '@polkadot/api-base/types/errors' {
* pool at a time. * pool at a time.
**/ **/
AccountBelongsToOtherPool: AugmentedError<ApiType>; AccountBelongsToOtherPool: AugmentedError<ApiType>;
/**
* The member is already unbonding in this era.
**/
AlreadyUnbonding: AugmentedError<ApiType>;
/** /**
* The pools state cannot be changed. * The pools state cannot be changed.
**/ **/
@@ -911,7 +907,7 @@ declare module '@polkadot/api-base/types/errors' {
* Some error occurred that should never happen. This should be reported to the * Some error occurred that should never happen. This should be reported to the
* maintainers. * maintainers.
**/ **/
DefensiveError: AugmentedError<ApiType>; Defensive: AugmentedError<ApiType>;
/** /**
* The caller does not have adequate permissions. * The caller does not have adequate permissions.
**/ **/
@@ -921,10 +917,6 @@ declare module '@polkadot/api-base/types/errors' {
* anymore to, for example, collect rewards). * anymore to, for example, collect rewards).
**/ **/
FullyUnbonding: AugmentedError<ApiType>; FullyUnbonding: AugmentedError<ApiType>;
/**
* The pool has insufficient balance to bond as a nominator.
**/
InsufficientBond: AugmentedError<ApiType>;
/** /**
* Too many members in the pool or system. * Too many members in the pool or system.
**/ **/
@@ -1855,6 +1847,10 @@ declare module '@polkadot/api-base/types/errors' {
* Not a member. * Not a member.
**/ **/
NotMember: AugmentedError<ApiType>; NotMember: AugmentedError<ApiType>;
/**
* Too many members.
**/
TooManyMembers: AugmentedError<ApiType>;
/** /**
* Generic error * Generic error
**/ **/
@@ -1891,6 +1887,11 @@ declare module '@polkadot/api-base/types/errors' {
[key: string]: AugmentedError<ApiType>; [key: string]: AugmentedError<ApiType>;
}; };
treasury: { treasury: {
/**
* The spend origin is valid but the amount it is allowed to spend is lower than the
* amount to be spent.
**/
InsufficientPermission: AugmentedError<ApiType>;
/** /**
* Proposer's balance is too low. * Proposer's balance is too low.
**/ **/
+44 -2
View File
@@ -293,6 +293,10 @@ declare module '@polkadot/api-base/types/events' {
* A proposal preimage was removed and used (the deposit was returned). * A proposal preimage was removed and used (the deposit was returned).
**/ **/
PreimageUsed: AugmentedEvent<ApiType, [proposalHash: H256, provider: AccountId32, deposit: u128], { proposalHash: H256, provider: AccountId32, deposit: u128 }>; PreimageUsed: AugmentedEvent<ApiType, [proposalHash: H256, provider: AccountId32, deposit: u128], { proposalHash: H256, provider: AccountId32, deposit: u128 }>;
/**
* A proposal got canceled.
**/
ProposalCanceled: AugmentedEvent<ApiType, [propIndex: u32], { propIndex: u32 }>;
/** /**
* A motion has been proposed by a public account. * A motion has been proposed by a public account.
**/ **/
@@ -554,6 +558,10 @@ declare module '@polkadot/api-base/types/events' {
* A payout has been made to a member. * A payout has been made to a member.
**/ **/
PaidOut: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, payout: u128], { member: AccountId32, poolId: u32, payout: u128 }>; PaidOut: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, payout: u128], { member: AccountId32, poolId: u32, payout: u128 }>;
/**
* The active balance of pool `pool_id` has been slashed to `balance`.
**/
PoolSlashed: AugmentedEvent<ApiType, [poolId: u32, balance: u128], { poolId: u32, balance: u128 }>;
/** /**
* The roles of a pool have been updated to the given new roles. Note that the depositor * The roles of a pool have been updated to the given new roles. Note that the depositor
* can never change. * can never change.
@@ -565,12 +573,31 @@ declare module '@polkadot/api-base/types/events' {
StateChanged: AugmentedEvent<ApiType, [poolId: u32, newState: PalletNominationPoolsPoolState], { poolId: u32, newState: PalletNominationPoolsPoolState }>; StateChanged: AugmentedEvent<ApiType, [poolId: u32, newState: PalletNominationPoolsPoolState], { poolId: u32, newState: PalletNominationPoolsPoolState }>;
/** /**
* A member has unbonded from their pool. * A member has unbonded from their pool.
*
* - `balance` is the corresponding balance of the number of points that has been
* requested to be unbonded (the argument of the `unbond` transaction) from the bonded
* pool.
* - `points` is the number of points that are issued as a result of `balance` being
* dissolved into the corresponding unbonding pool.
*
* In the absence of slashing, these values will match. In the presence of slashing, the
* number of points that are issued in the unbonding pool will be less than the amount
* requested to be unbonded.
**/ **/
Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, amount: u128], { member: AccountId32, poolId: u32, amount: u128 }>; Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128], { member: AccountId32, poolId: u32, balance: u128, points: u128 }>;
/**
* The unbond pool at `era` of pool `pool_id` has been slashed to `balance`.
**/
UnbondingPoolSlashed: AugmentedEvent<ApiType, [poolId: u32, era: u32, balance: u128], { poolId: u32, era: u32, balance: u128 }>;
/** /**
* A member has withdrawn from their pool. * A member has withdrawn from their pool.
*
* The given number of `points` have been dissolved in return of `balance`.
*
* Similar to `Unbonded` event, in the absence of slashing, the ratio of point to balance
* will be 1.
**/ **/
Withdrawn: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, amount: u128], { member: AccountId32, poolId: u32, amount: u128 }>; Withdrawn: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128], { member: AccountId32, poolId: u32, balance: u128, points: u128 }>;
/** /**
* Generic event * Generic event
**/ **/
@@ -1112,6 +1139,17 @@ declare module '@polkadot/api-base/types/events' {
**/ **/
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
}; };
transactionPayment: {
/**
* A transaction fee `actual_fee`, of which `tip` was added to the minimum inclusion fee,
* has been paid by `who`.
**/
TransactionFeePaid: AugmentedEvent<ApiType, [who: AccountId32, actualFee: u128, tip: u128], { who: AccountId32, actualFee: u128, tip: u128 }>;
/**
* Generic event
**/
[key: string]: AugmentedEvent<ApiType>;
};
treasury: { treasury: {
/** /**
* Some funds have been allocated. * Some funds have been allocated.
@@ -1137,6 +1175,10 @@ declare module '@polkadot/api-base/types/events' {
* Spending has finished; this is the amount that rolls over until next spend. * Spending has finished; this is the amount that rolls over until next spend.
**/ **/
Rollover: AugmentedEvent<ApiType, [rolloverBalance: u128], { rolloverBalance: u128 }>; Rollover: AugmentedEvent<ApiType, [rolloverBalance: u128], { rolloverBalance: u128 }>;
/**
* A new spend proposal has been approved.
**/
SpendApproved: AugmentedEvent<ApiType, [proposalIndex: u32, amount: u128, beneficiary: AccountId32], { proposalIndex: u32, amount: u128, beneficiary: AccountId32 }>;
/** /**
* We have ended a spend period and will now allocate funds. * We have ended a spend period and will now allocate funds.
**/ **/
+3
View File
@@ -849,6 +849,9 @@ declare module '@polkadot/api-base/types/storage' {
* *
* This is the amount that the depositor must put as their initial stake in the pool, as an * This is the amount that the depositor must put as their initial stake in the pool, as an
* indication of "skin in the game". * indication of "skin in the game".
*
* This is the value that will always exist in the staking ledger of the pool bonded account
* while all other accounts leave.
**/ **/
minCreateBond: AugmentedQuery<ApiType, () => Observable<u128>, []> & QueryableStorageEntry<ApiType, []>; minCreateBond: AugmentedQuery<ApiType, () => Observable<u128>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
+54 -7
View File
@@ -1452,12 +1452,17 @@ declare module '@polkadot/api-base/types/submittable' {
}; };
grandpa: { grandpa: {
/** /**
* Note that the current authority set of the GRANDPA finality gadget has * Note that the current authority set of the GRANDPA finality gadget has stalled.
* stalled. This will trigger a forced authority set change at the beginning *
* of the next session, to be enacted `delay` blocks after that. The delay * This will trigger a forced authority set change at the beginning of the next session, to
* should be high enough to safely assume that the block signalling the * be enacted `delay` blocks after that. The `delay` should be high enough to safely assume
* forced change will not be re-orged (e.g. 1000 blocks). The GRANDPA voters * that the block signalling the forced change will not be re-orged e.g. 1000 blocks.
* will start the new authority set using the given finalized block as base. * The block production rate (which may be slowed down because of finality lagging) should
* be taken into account when choosing the `delay`. The GRANDPA voters based on the new
* authority will start voting on top of `best_finalized_block_number` for new finalized
* blocks. `best_finalized_block_number` should be the highest of the latest finalized
* block of all validators of the new authority set.
*
* Only callable by root. * Only callable by root.
**/ **/
noteStalled: AugmentedSubmittable<(delay: u32 | AnyNumber | Uint8Array, bestFinalizedBlockNumber: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32]>; noteStalled: AugmentedSubmittable<(delay: u32 | AnyNumber | Uint8Array, bestFinalizedBlockNumber: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32]>;
@@ -2117,6 +2122,16 @@ declare module '@polkadot/api-base/types/submittable' {
* accumulated rewards, see [`BondExtra`]. * accumulated rewards, see [`BondExtra`].
**/ **/
bondExtra: AugmentedSubmittable<(extra: PalletNominationPoolsBondExtra | { FreeBalance: any } | { Rewards: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletNominationPoolsBondExtra]>; bondExtra: AugmentedSubmittable<(extra: PalletNominationPoolsBondExtra | { FreeBalance: any } | { Rewards: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletNominationPoolsBondExtra]>;
/**
* Chill on behalf of the pool.
*
* The dispatch origin of this call must be signed by the pool nominator or the pool
* root role, same as [`Pallet::nominate`].
*
* This directly forward the call to the staking pallet, on behalf of the pool bonded
* account.
**/
chill: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
/** /**
* A bonded member can use this to claim their payout based on the rewards that the pool * A bonded member can use this to claim their payout based on the rewards that the pool
* has accumulated since their last claimed payout (OR since joining if this is there first * has accumulated since their last claimed payout (OR since joining if this is there first
@@ -2159,6 +2174,15 @@ declare module '@polkadot/api-base/types/submittable' {
* * Only a pool with [`PoolState::Open`] can be joined * * Only a pool with [`PoolState::Open`] can be joined
**/ **/
join: AugmentedSubmittable<(amount: Compact<u128> | AnyNumber | Uint8Array, poolId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u128>, u32]>; join: AugmentedSubmittable<(amount: Compact<u128> | AnyNumber | Uint8Array, poolId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u128>, u32]>;
/**
* Nominate on behalf of the pool.
*
* The dispatch origin of this call must be signed by the pool nominator or the pool
* root role.
*
* This directly forward the call to the staking pallet, on behalf of the pool bonded
* account.
**/
nominate: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, validators: Vec<AccountId32> | (AccountId32 | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [u32, Vec<AccountId32>]>; nominate: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, validators: Vec<AccountId32> | (AccountId32 | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [u32, Vec<AccountId32>]>;
/** /**
* Call `withdraw_unbonded` for the pools account. This call can be made by any account. * Call `withdraw_unbonded` for the pools account. This call can be made by any account.
@@ -2182,12 +2206,24 @@ declare module '@polkadot/api-base/types/submittable' {
* * `max_members_per_pool` - Set [`MaxPoolMembersPerPool`]. * * `max_members_per_pool` - Set [`MaxPoolMembersPerPool`].
**/ **/
setConfigs: AugmentedSubmittable<(minJoinBond: PalletNominationPoolsConfigOpU128 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array, minCreateBond: PalletNominationPoolsConfigOpU128 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array, maxPools: PalletNominationPoolsConfigOpU32 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array, maxMembers: PalletNominationPoolsConfigOpU32 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array, maxMembersPerPool: PalletNominationPoolsConfigOpU32 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletNominationPoolsConfigOpU128, PalletNominationPoolsConfigOpU128, PalletNominationPoolsConfigOpU32, PalletNominationPoolsConfigOpU32, PalletNominationPoolsConfigOpU32]>; setConfigs: AugmentedSubmittable<(minJoinBond: PalletNominationPoolsConfigOpU128 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array, minCreateBond: PalletNominationPoolsConfigOpU128 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array, maxPools: PalletNominationPoolsConfigOpU32 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array, maxMembers: PalletNominationPoolsConfigOpU32 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array, maxMembersPerPool: PalletNominationPoolsConfigOpU32 | { Noop: any } | { Set: any } | { Remove: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletNominationPoolsConfigOpU128, PalletNominationPoolsConfigOpU128, PalletNominationPoolsConfigOpU32, PalletNominationPoolsConfigOpU32, PalletNominationPoolsConfigOpU32]>;
/**
* Set a new metadata for the pool.
*
* The dispatch origin of this call must be signed by the state toggler, or the root role
* of the pool.
**/
setMetadata: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, metadata: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, Bytes]>; setMetadata: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, metadata: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, Bytes]>;
/**
* Set a new state for the pool.
*
* The dispatch origin of this call must be signed by the state toggler, or the root role
* of the pool.
**/
setState: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, state: PalletNominationPoolsPoolState | 'Open' | 'Blocked' | 'Destroying' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletNominationPoolsPoolState]>; setState: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, state: PalletNominationPoolsPoolState | 'Open' | 'Blocked' | 'Destroying' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletNominationPoolsPoolState]>;
/** /**
* Unbond up to `unbonding_points` of the `member_account`'s funds from the pool. It * Unbond up to `unbonding_points` of the `member_account`'s funds from the pool. It
* implicitly collects the rewards one last time, since not doing so would mean some * implicitly collects the rewards one last time, since not doing so would mean some
* rewards would go forfeited. * rewards would be forfeited.
* *
* Under certain conditions, this call can be dispatched permissionlessly (i.e. by any * Under certain conditions, this call can be dispatched permissionlessly (i.e. by any
* account). * account).
@@ -4209,6 +4245,17 @@ declare module '@polkadot/api-base/types/submittable' {
* exist altogether, thus there is no way it would have been approved in the first place. * exist altogether, thus there is no way it would have been approved in the first place.
**/ **/
removeApproval: AugmentedSubmittable<(proposalId: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>]>; removeApproval: AugmentedSubmittable<(proposalId: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>]>;
/**
* Propose and approve a spend of treasury funds.
*
* - `origin`: Must be `SpendOrigin` with the `Success` value being at least `amount`.
* - `amount`: The amount to be transferred from the treasury to the `beneficiary`.
* - `beneficiary`: The destination account for the transfer.
*
* NOTE: For record-keeping purposes, the proposer is deemed to be equivalent to the
* beneficiary.
**/
spend: AugmentedSubmittable<(amount: Compact<u128> | AnyNumber | Uint8Array, beneficiary: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u128>, MultiAddress]>;
/** /**
* Generic tx * Generic tx
**/ **/
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/api-augment authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-augment', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/api-augment', path: 'auto', type: 'auto', version: '8.10.1' };
@@ -1557,6 +1557,10 @@ declare module '@polkadot/api-base/types/errors' {
* Not a member. * Not a member.
**/ **/
NotMember: AugmentedError<ApiType>; NotMember: AugmentedError<ApiType>;
/**
* Too many members.
**/
TooManyMembers: AugmentedError<ApiType>;
/** /**
* Generic error * Generic error
**/ **/
@@ -1593,6 +1597,11 @@ declare module '@polkadot/api-base/types/errors' {
[key: string]: AugmentedError<ApiType>; [key: string]: AugmentedError<ApiType>;
}; };
treasury: { treasury: {
/**
* The spend origin is valid but the amount it is allowed to spend is lower than the
* amount to be spent.
**/
InsufficientPermission: AugmentedError<ApiType>;
/** /**
* Proposer's balance is too low. * Proposer's balance is too low.
**/ **/
@@ -293,6 +293,10 @@ declare module '@polkadot/api-base/types/events' {
* A proposal preimage was removed and used (the deposit was returned). * A proposal preimage was removed and used (the deposit was returned).
**/ **/
PreimageUsed: AugmentedEvent<ApiType, [proposalHash: H256, provider: AccountId32, deposit: u128], { proposalHash: H256, provider: AccountId32, deposit: u128 }>; PreimageUsed: AugmentedEvent<ApiType, [proposalHash: H256, provider: AccountId32, deposit: u128], { proposalHash: H256, provider: AccountId32, deposit: u128 }>;
/**
* A proposal got canceled.
**/
ProposalCanceled: AugmentedEvent<ApiType, [propIndex: u32], { propIndex: u32 }>;
/** /**
* A motion has been proposed by a public account. * A motion has been proposed by a public account.
**/ **/
@@ -942,6 +946,17 @@ declare module '@polkadot/api-base/types/events' {
**/ **/
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
}; };
transactionPayment: {
/**
* A transaction fee `actual_fee`, of which `tip` was added to the minimum inclusion fee,
* has been paid by `who`.
**/
TransactionFeePaid: AugmentedEvent<ApiType, [who: AccountId32, actualFee: u128, tip: u128], { who: AccountId32, actualFee: u128, tip: u128 }>;
/**
* Generic event
**/
[key: string]: AugmentedEvent<ApiType>;
};
treasury: { treasury: {
/** /**
* Some funds have been allocated. * Some funds have been allocated.
@@ -967,6 +982,10 @@ declare module '@polkadot/api-base/types/events' {
* Spending has finished; this is the amount that rolls over until next spend. * Spending has finished; this is the amount that rolls over until next spend.
**/ **/
Rollover: AugmentedEvent<ApiType, [rolloverBalance: u128], { rolloverBalance: u128 }>; Rollover: AugmentedEvent<ApiType, [rolloverBalance: u128], { rolloverBalance: u128 }>;
/**
* A new spend proposal has been approved.
**/
SpendApproved: AugmentedEvent<ApiType, [proposalIndex: u32, amount: u128, beneficiary: AccountId32], { proposalIndex: u32, amount: u128, beneficiary: AccountId32 }>;
/** /**
* We have ended a spend period and will now allocate funds. * We have ended a spend period and will now allocate funds.
**/ **/
+22 -6
View File
@@ -1401,12 +1401,17 @@ declare module '@polkadot/api-base/types/submittable' {
}; };
grandpa: { grandpa: {
/** /**
* Note that the current authority set of the GRANDPA finality gadget has * Note that the current authority set of the GRANDPA finality gadget has stalled.
* stalled. This will trigger a forced authority set change at the beginning *
* of the next session, to be enacted `delay` blocks after that. The delay * This will trigger a forced authority set change at the beginning of the next session, to
* should be high enough to safely assume that the block signalling the * be enacted `delay` blocks after that. The `delay` should be high enough to safely assume
* forced change will not be re-orged (e.g. 1000 blocks). The GRANDPA voters * that the block signalling the forced change will not be re-orged e.g. 1000 blocks.
* will start the new authority set using the given finalized block as base. * The block production rate (which may be slowed down because of finality lagging) should
* be taken into account when choosing the `delay`. The GRANDPA voters based on the new
* authority will start voting on top of `best_finalized_block_number` for new finalized
* blocks. `best_finalized_block_number` should be the highest of the latest finalized
* block of all validators of the new authority set.
*
* Only callable by root. * Only callable by root.
**/ **/
noteStalled: AugmentedSubmittable<(delay: u32 | AnyNumber | Uint8Array, bestFinalizedBlockNumber: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32]>; noteStalled: AugmentedSubmittable<(delay: u32 | AnyNumber | Uint8Array, bestFinalizedBlockNumber: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32]>;
@@ -3562,6 +3567,17 @@ declare module '@polkadot/api-base/types/submittable' {
* exist altogether, thus there is no way it would have been approved in the first place. * exist altogether, thus there is no way it would have been approved in the first place.
**/ **/
removeApproval: AugmentedSubmittable<(proposalId: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>]>; removeApproval: AugmentedSubmittable<(proposalId: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>]>;
/**
* Propose and approve a spend of treasury funds.
*
* - `origin`: Must be `SpendOrigin` with the `Success` value being at least `amount`.
* - `amount`: The amount to be transferred from the treasury to the `beneficiary`.
* - `beneficiary`: The destination account for the transfer.
*
* NOTE: For record-keeping purposes, the proposer is deemed to be equivalent to the
* beneficiary.
**/
spend: AugmentedSubmittable<(amount: Compact<u128> | AnyNumber | Uint8Array, beneficiary: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u128>, MultiAddress]>;
/** /**
* Generic tx * Generic tx
**/ **/
@@ -1333,6 +1333,17 @@ declare module '@polkadot/api-base/types/events' {
**/ **/
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
}; };
transactionPayment: {
/**
* A transaction fee `actual_fee`, of which `tip` was added to the minimum inclusion fee,
* has been paid by `who`.
**/
TransactionFeePaid: AugmentedEvent<ApiType, [who: AccountId32, actualFee: u128, tip: u128], { who: AccountId32, actualFee: u128, tip: u128 }>;
/**
* Generic event
**/
[key: string]: AugmentedEvent<ApiType>;
};
transactionStorage: { transactionStorage: {
/** /**
* Storage proof was successfully checked. * Storage proof was successfully checked.
@@ -1701,14 +1701,6 @@ declare module '@polkadot/api-base/types/storage' {
* Storage fee per transaction. * Storage fee per transaction.
**/ **/
entryFee: AugmentedQuery<ApiType, () => Observable<Option<u128>>, []> & QueryableStorageEntry<ApiType, []>; entryFee: AugmentedQuery<ApiType, () => Observable<Option<u128>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Maximum number of indexed transactions in the block.
**/
maxBlockTransactions: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Maximum data set in a single transaction in bytes.
**/
maxTransactionSize: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Was the proof checked in this block? * Was the proof checked in this block?
**/ **/
+4 -4
View File
@@ -20,13 +20,13 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/rpc-core": "8.8.2", "@polkadot/rpc-core": "8.10.1",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/util": "^9.4.1", "@polkadot/util": "^9.6.2",
"rxjs": "^7.5.5" "rxjs": "^7.5.5"
} }
} }
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-base', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/api-base', path: 'auto', type: 'auto', version: '8.10.1' };
+9 -9
View File
@@ -20,20 +20,20 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/api": "8.8.2", "@polkadot/api": "8.10.1",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/types-codec": "8.8.2", "@polkadot/types-codec": "8.10.1",
"@polkadot/types-create": "8.8.2", "@polkadot/types-create": "8.10.1",
"@polkadot/util": "^9.4.1", "@polkadot/util": "^9.6.2",
"@polkadot/util-crypto": "^9.4.1", "@polkadot/util-crypto": "^9.6.2",
"rxjs": "^7.5.5" "rxjs": "^7.5.5"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/api-augment": "8.8.2", "@polkadot/api-augment": "8.10.1",
"@polkadot/keyring": "^9.4.1" "@polkadot/keyring": "^9.6.2"
} }
} }
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-contract', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/api-contract', path: 'auto', type: 'auto', version: '8.10.1' };
@@ -160,6 +160,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 10, "lookupIndex": 10,
"lookupName": "InkStorageCollectionsStashEntry",
"type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"(AccountId,AccountId)\"}}", "type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"(AccountId,AccountId)\"}}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::stash::Entry", "namespace": "ink_storage::collections::stash::Entry",
@@ -180,6 +180,7 @@
{ {
"info": "Struct", "info": "Struct",
"lookupIndex": 10, "lookupIndex": 10,
"lookupName": "InkStorageCollectionsHashmapValueEntryEntry",
"type": "{\"value\":\"u32\",\"keyIndex\":\"u32\"}", "type": "{\"value\":\"u32\",\"keyIndex\":\"u32\"}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::hashmap::ValueEntry", "namespace": "ink_storage::collections::hashmap::ValueEntry",
@@ -205,6 +206,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 11, "lookupIndex": 11,
"lookupName": "InkStorageCollectionsStashEntry",
"type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"(AccountId,AccountId)\"}}", "type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"(AccountId,AccountId)\"}}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::stash::Entry", "namespace": "ink_storage::collections::stash::Entry",
@@ -275,6 +277,7 @@
{ {
"info": "Struct", "info": "Struct",
"lookupIndex": 13, "lookupIndex": 13,
"lookupName": "InkStorageCollectionsHashmapValueEntryOption",
"type": "{\"value\":\"bool\",\"keyIndex\":\"u32\"}", "type": "{\"value\":\"bool\",\"keyIndex\":\"u32\"}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::hashmap::ValueEntry", "namespace": "ink_storage::collections::hashmap::ValueEntry",
@@ -226,6 +226,7 @@
{ {
"info": "Struct", "info": "Struct",
"lookupIndex": 12, "lookupIndex": 12,
"lookupName": "InkStorageCollectionsHashmapValueEntry",
"type": "{\"value\":\"u32\",\"keyIndex\":\"u32\"}", "type": "{\"value\":\"u32\",\"keyIndex\":\"u32\"}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::hashmap::ValueEntry", "namespace": "ink_storage::collections::hashmap::ValueEntry",
@@ -251,7 +252,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 13, "lookupIndex": 13,
"type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"MultisigPlainMultisigPlainTransaction\"}}", "type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"MultisigPlainTransaction\"}}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::stash::Entry", "namespace": "ink_storage::collections::stash::Entry",
"sub": [ "sub": [
@@ -268,7 +269,7 @@
"docs": [], "docs": [],
"info": "Si", "info": "Si",
"lookupIndex": 14, "lookupIndex": 14,
"lookupName": "MultisigPlainMultisigPlainTransaction", "lookupName": "MultisigPlainTransaction",
"type": "Lookup14", "type": "Lookup14",
"index": 1, "index": 1,
"name": "Occupied" "name": "Occupied"
@@ -278,7 +279,7 @@
{ {
"info": "Struct", "info": "Struct",
"lookupIndex": 14, "lookupIndex": 14,
"lookupName": "MultisigPlainMultisigPlainTransaction", "lookupName": "MultisigPlainTransaction",
"type": "{\"callee\":\"AccountId\",\"selector\":\"[u8;4]\",\"input\":\"Bytes\",\"transferredValue\":\"u128\",\"gasLimit\":\"u64\"}", "type": "{\"callee\":\"AccountId\",\"selector\":\"[u8;4]\",\"input\":\"Bytes\",\"transferredValue\":\"u128\",\"gasLimit\":\"u64\"}",
"docs": [], "docs": [],
"namespace": "multisig_plain::multisig_plain::Transaction", "namespace": "multisig_plain::multisig_plain::Transaction",
@@ -373,6 +374,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 19, "lookupIndex": 19,
"lookupName": "InkStorageCollectionsStashEntry",
"type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"AccountId\"}}", "type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"AccountId\"}}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::stash::Entry", "namespace": "ink_storage::collections::stash::Entry",
@@ -416,7 +418,7 @@
{ {
"info": "Tuple", "info": "Tuple",
"lookupIndex": 21, "lookupIndex": 21,
"type": "(u32,MultisigPlainMultisigPlainConfirmationStatus)", "type": "(u32,MultisigPlainConfirmationStatus)",
"docs": [], "docs": [],
"namespace": "", "namespace": "",
"sub": [ "sub": [
@@ -431,7 +433,7 @@
"docs": [], "docs": [],
"info": "Si", "info": "Si",
"lookupIndex": 22, "lookupIndex": 22,
"lookupName": "MultisigPlainMultisigPlainConfirmationStatus", "lookupName": "MultisigPlainConfirmationStatus",
"type": "Lookup22" "type": "Lookup22"
} }
] ]
@@ -439,7 +441,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 22, "lookupIndex": 22,
"lookupName": "MultisigPlainMultisigPlainConfirmationStatus", "lookupName": "MultisigPlainConfirmationStatus",
"type": "{\"_enum\":{\"Confirmed\":\"Null\",\"ConfirmationsNeeded\":\"u32\"}}", "type": "{\"_enum\":{\"Confirmed\":\"Null\",\"ConfirmationsNeeded\":\"u32\"}}",
"docs": [], "docs": [],
"namespace": "multisig_plain::multisig_plain::ConfirmationStatus", "namespace": "multisig_plain::multisig_plain::ConfirmationStatus",
@@ -310,6 +310,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 15, "lookupIndex": 15,
"lookupName": "InkStorageCollectionsStashEntry",
"type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"(u32,AccountId)\"}}", "type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"(u32,AccountId)\"}}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::stash::Entry", "namespace": "ink_storage::collections::stash::Entry",
@@ -380,6 +381,7 @@
{ {
"info": "Struct", "info": "Struct",
"lookupIndex": 17, "lookupIndex": 17,
"lookupName": "InkStorageCollectionsHashmapValueEntry",
"type": "{\"value\":\"Null\",\"keyIndex\":\"u32\"}", "type": "{\"value\":\"Null\",\"keyIndex\":\"u32\"}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::hashmap::ValueEntry", "namespace": "ink_storage::collections::hashmap::ValueEntry",
@@ -83,6 +83,7 @@
{ {
"info": "Struct", "info": "Struct",
"lookupIndex": 6, "lookupIndex": 6,
"lookupName": "InkStorageLazyMapping",
"type": "{\"offsetKey\":\"InkPrimitivesKey\"}", "type": "{\"offsetKey\":\"InkPrimitivesKey\"}",
"docs": [], "docs": [],
"namespace": "ink_storage::lazy::mapping::Mapping", "namespace": "ink_storage::lazy::mapping::Mapping",
@@ -83,6 +83,7 @@
{ {
"info": "Struct", "info": "Struct",
"lookupIndex": 6, "lookupIndex": 6,
"lookupName": "InkStorageLazyMapping",
"type": "{\"offsetKey\":\"InkPrimitivesKey\"}", "type": "{\"offsetKey\":\"InkPrimitivesKey\"}",
"docs": [], "docs": [],
"namespace": "ink_storage::lazy::mapping::Mapping", "namespace": "ink_storage::lazy::mapping::Mapping",
@@ -23,8 +23,8 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 4, "lookupIndex": 4,
"lookupName": "EnumExampleEnumExampleVariant", "lookupName": "EnumExampleVariant",
"type": "{\"_enum\":{\"None\":\"Null\",\"Weekday\":\"EnumExampleEnumExampleWeekday\",\"TupleMaybeSigned\":\"EnumExampleEnumExampleTupleMaybeSigned\",\"NamedMaybeSigned\":\"EnumExampleEnumExampleNamedMaybeSigned\",\"Color\":\"EnumExampleEnumExampleColor\"}}", "type": "{\"_enum\":{\"None\":\"Null\",\"Weekday\":\"EnumExampleWeekday\",\"TupleMaybeSigned\":\"EnumExampleTupleMaybeSigned\",\"NamedMaybeSigned\":\"EnumExampleNamedMaybeSigned\",\"Color\":\"EnumExampleColor\"}}",
"docs": [], "docs": [],
"namespace": "enum_example::enum_example::Variant", "namespace": "enum_example::enum_example::Variant",
"sub": [ "sub": [
@@ -38,7 +38,7 @@
"docs": [], "docs": [],
"info": "Si", "info": "Si",
"lookupIndex": 5, "lookupIndex": 5,
"lookupName": "EnumExampleEnumExampleWeekday", "lookupName": "EnumExampleWeekday",
"type": "Lookup5", "type": "Lookup5",
"index": 1, "index": 1,
"name": "Weekday" "name": "Weekday"
@@ -47,7 +47,7 @@
"docs": [], "docs": [],
"info": "Si", "info": "Si",
"lookupIndex": 6, "lookupIndex": 6,
"lookupName": "EnumExampleEnumExampleTupleMaybeSigned", "lookupName": "EnumExampleTupleMaybeSigned",
"type": "Lookup6", "type": "Lookup6",
"index": 2, "index": 2,
"name": "TupleMaybeSigned" "name": "TupleMaybeSigned"
@@ -56,7 +56,7 @@
"docs": [], "docs": [],
"info": "Si", "info": "Si",
"lookupIndex": 7, "lookupIndex": 7,
"lookupName": "EnumExampleEnumExampleNamedMaybeSigned", "lookupName": "EnumExampleNamedMaybeSigned",
"type": "Lookup7", "type": "Lookup7",
"index": 3, "index": 3,
"name": "NamedMaybeSigned" "name": "NamedMaybeSigned"
@@ -65,7 +65,7 @@
"docs": [], "docs": [],
"info": "Si", "info": "Si",
"lookupIndex": 8, "lookupIndex": 8,
"lookupName": "EnumExampleEnumExampleColor", "lookupName": "EnumExampleColor",
"type": "Lookup8", "type": "Lookup8",
"index": 4, "index": 4,
"name": "Color" "name": "Color"
@@ -75,7 +75,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 5, "lookupIndex": 5,
"lookupName": "EnumExampleEnumExampleWeekday", "lookupName": "EnumExampleWeekday",
"type": "{\"_enum\":[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]}", "type": "{\"_enum\":[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]}",
"docs": [], "docs": [],
"namespace": "enum_example::enum_example::Weekday", "namespace": "enum_example::enum_example::Weekday",
@@ -127,7 +127,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 6, "lookupIndex": 6,
"lookupName": "EnumExampleEnumExampleTupleMaybeSigned", "lookupName": "EnumExampleTupleMaybeSigned",
"type": "{\"_enum\":{\"Signed\":\"i32\",\"Unsigned\":\"u32\"}}", "type": "{\"_enum\":{\"Signed\":\"i32\",\"Unsigned\":\"u32\"}}",
"docs": [], "docs": [],
"namespace": "enum_example::enum_example::TupleMaybeSigned", "namespace": "enum_example::enum_example::TupleMaybeSigned",
@@ -155,7 +155,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 7, "lookupIndex": 7,
"lookupName": "EnumExampleEnumExampleNamedMaybeSigned", "lookupName": "EnumExampleNamedMaybeSigned",
"type": "{\"_enum\":{\"Signed\":\"{\\\"value\\\":\\\"i32\\\"}\",\"Unsigned\":\"{\\\"value\\\":\\\"u32\\\"}\"}}", "type": "{\"_enum\":{\"Signed\":\"{\\\"value\\\":\\\"i32\\\"}\",\"Unsigned\":\"{\\\"value\\\":\\\"u32\\\"}\"}}",
"docs": [], "docs": [],
"namespace": "enum_example::enum_example::NamedMaybeSigned", "namespace": "enum_example::enum_example::NamedMaybeSigned",
@@ -197,7 +197,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 8, "lookupIndex": 8,
"lookupName": "EnumExampleEnumExampleColor", "lookupName": "EnumExampleColor",
"type": "{\"_enum\":{\"Red\":\"Null\",\"Blue\":\"Null\",\"Green\":\"Null\",\"Yellow\":\"Null\",\"Rgb\":\"{\\\"r\\\":\\\"u8\\\",\\\"g\\\":\\\"u8\\\",\\\"b\\\":\\\"u8\\\"}\",\"Rgba\":\"{\\\"r\\\":\\\"u8\\\",\\\"g\\\":\\\"u8\\\",\\\"b\\\":\\\"u8\\\",\\\"a\\\":\\\"u8\\\"}\"}}", "type": "{\"_enum\":{\"Red\":\"Null\",\"Blue\":\"Null\",\"Green\":\"Null\",\"Yellow\":\"Null\",\"Rgb\":\"{\\\"r\\\":\\\"u8\\\",\\\"g\\\":\\\"u8\\\",\\\"b\\\":\\\"u8\\\"}\",\"Rgba\":\"{\\\"r\\\":\\\"u8\\\",\\\"g\\\":\\\"u8\\\",\\\"b\\\":\\\"u8\\\",\\\"a\\\":\\\"u8\\\"}\"}}",
"docs": [], "docs": [],
"namespace": "enum_example::enum_example::Color", "namespace": "enum_example::enum_example::Color",
@@ -160,6 +160,7 @@
{ {
"info": "Enum", "info": "Enum",
"lookupIndex": 10, "lookupIndex": 10,
"lookupName": "InkStorageCollectionsStashEntry",
"type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"(AccountId,AccountId)\"}}", "type": "{\"_enum\":{\"Vacant\":\"InkStorageCollectionsStashVacantEntry\",\"Occupied\":\"(AccountId,AccountId)\"}}",
"docs": [], "docs": [],
"namespace": "ink_storage::collections::stash::Entry", "namespace": "ink_storage::collections::stash::Entry",
+14 -14
View File
@@ -20,25 +20,25 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/api": "8.8.2", "@polkadot/api": "8.10.1",
"@polkadot/api-augment": "8.8.2", "@polkadot/api-augment": "8.10.1",
"@polkadot/api-base": "8.8.2", "@polkadot/api-base": "8.10.1",
"@polkadot/rpc-core": "8.8.2", "@polkadot/rpc-core": "8.10.1",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/types-codec": "8.8.2", "@polkadot/types-codec": "8.10.1",
"@polkadot/util": "^9.4.1", "@polkadot/util": "^9.6.2",
"@polkadot/util-crypto": "^9.4.1", "@polkadot/util-crypto": "^9.6.2",
"rxjs": "^7.5.5" "rxjs": "^7.5.5"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/api": "8.8.2", "@polkadot/api": "8.10.1",
"@polkadot/api-augment": "8.8.2", "@polkadot/api-augment": "8.10.1",
"@polkadot/rpc-augment": "8.8.2", "@polkadot/rpc-augment": "8.10.1",
"@polkadot/rpc-provider": "8.8.2", "@polkadot/rpc-provider": "8.10.1",
"@polkadot/types-support": "8.8.2" "@polkadot/types-support": "8.10.1"
} }
} }
@@ -10,6 +10,7 @@ import type { DeriveApi, DeriveDispatch, DeriveProposalImage } from '../types';
import { catchError, combineLatest, map, of, switchMap } from 'rxjs'; import { catchError, combineLatest, map, of, switchMap } from 'rxjs';
import { Enum } from '@polkadot/types';
import { isFunction, stringToHex } from '@polkadot/util'; import { isFunction, stringToHex } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -24,7 +25,7 @@ interface SchedulerInfo {
function isMaybeHashed (call: FrameSupportScheduleMaybeHashed | Call): call is FrameSupportScheduleMaybeHashed { function isMaybeHashed (call: FrameSupportScheduleMaybeHashed | Call): call is FrameSupportScheduleMaybeHashed {
// check for enum // check for enum
return (call as FrameSupportScheduleMaybeHashed).isBasic === false; return call instanceof Enum;
} }
function queryQueue (api: DeriveApi): Observable<DeriveDispatch[]> { function queryQueue (api: DeriveApi): Observable<DeriveDispatch[]> {
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-derive', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/api-derive', path: 'auto', type: 'auto', version: '8.10.1' };
+17 -17
View File
@@ -20,29 +20,29 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/api-augment": "8.8.2", "@polkadot/api-augment": "8.10.1",
"@polkadot/api-base": "8.8.2", "@polkadot/api-base": "8.10.1",
"@polkadot/api-derive": "8.8.2", "@polkadot/api-derive": "8.10.1",
"@polkadot/keyring": "^9.4.1", "@polkadot/keyring": "^9.6.2",
"@polkadot/rpc-augment": "8.8.2", "@polkadot/rpc-augment": "8.10.1",
"@polkadot/rpc-core": "8.8.2", "@polkadot/rpc-core": "8.10.1",
"@polkadot/rpc-provider": "8.8.2", "@polkadot/rpc-provider": "8.10.1",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/types-augment": "8.8.2", "@polkadot/types-augment": "8.10.1",
"@polkadot/types-codec": "8.8.2", "@polkadot/types-codec": "8.10.1",
"@polkadot/types-create": "8.8.2", "@polkadot/types-create": "8.10.1",
"@polkadot/types-known": "8.8.2", "@polkadot/types-known": "8.10.1",
"@polkadot/util": "^9.4.1", "@polkadot/util": "^9.6.2",
"@polkadot/util-crypto": "^9.4.1", "@polkadot/util-crypto": "^9.6.2",
"eventemitter3": "^4.0.7", "eventemitter3": "^4.0.7",
"rxjs": "^7.5.5" "rxjs": "^7.5.5"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/api-augment": "8.8.2", "@polkadot/api-augment": "8.10.1",
"@polkadot/types-support": "8.8.2" "@polkadot/types-support": "8.10.1"
} }
} }
+3 -1
View File
@@ -213,12 +213,14 @@ function types (api: ApiPromise): void {
const balance = registry.createType('Balance', 2); const balance = registry.createType('Balance', 2);
const gas = registry.createType('Gas', 2); const gas = registry.createType('Gas', 2);
const compact = registry.createType('Compact<u32>', 2); const compact = registry.createType('Compact<u32>', 2);
const f32 = registry.createType('f32');
const u32 = registry.createType('u32');
// const random = registry.createType('RandomType', 2); // This one should deliberately show a TS error // const random = registry.createType('RandomType', 2); // This one should deliberately show a TS error
const gasUnsafe = createTypeUnsafe(registry, 'Gas', [2]); const gasUnsafe = createTypeUnsafe(registry, 'Gas', [2]);
const overriddenUnsafe = createTypeUnsafe<Header>(registry, 'Gas', [2]); const overriddenUnsafe = createTypeUnsafe<Header>(registry, 'Gas', [2]);
console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe, api.createType('AccountData')); console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe, u32.toNumber(), f32.toNumber(), api.createType('AccountData'));
} }
async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> { async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/api', path: 'auto', type: 'auto', version: '8.10.1' };
+5 -5
View File
@@ -20,13 +20,13 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/rpc-core": "8.8.2", "@polkadot/rpc-core": "8.10.1",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/types-codec": "8.8.2", "@polkadot/types-codec": "8.10.1",
"@polkadot/util": "^9.4.1" "@polkadot/util": "^9.6.2"
} }
} }
+10 -2
View File
@@ -3,7 +3,7 @@
import type { AugmentedRpc } from '@polkadot/rpc-core/types'; import type { AugmentedRpc } from '@polkadot/rpc-core/types';
import type { Metadata, StorageKey } from '@polkadot/types'; import type { Metadata, StorageKey } from '@polkadot/types';
import type { Bytes, HashMap, Json, Null, Option, Text, U256, U64, Vec, bool, u32, u64 } from '@polkadot/types-codec'; import type { Bytes, HashMap, Json, Null, Option, Text, U256, U64, Vec, bool, f64, u32, u64 } from '@polkadot/types-codec';
import type { AnyNumber, Codec } from '@polkadot/types-codec/types'; import type { AnyNumber, Codec } from '@polkadot/types-codec/types';
import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author'; import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
import type { EpochAuthorship } from '@polkadot/types/interfaces/babe'; import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';
@@ -14,7 +14,7 @@ import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { CodeUploadRequest, CodeUploadResult, ContractCallRequest, ContractExecResult, ContractInstantiateResult, InstantiateRequest } from '@polkadot/types/interfaces/contracts'; import type { CodeUploadRequest, CodeUploadResult, ContractCallRequest, ContractExecResult, ContractInstantiateResult, InstantiateRequest } from '@polkadot/types/interfaces/contracts';
import type { BlockStats } from '@polkadot/types/interfaces/dev'; import type { BlockStats } from '@polkadot/types/interfaces/dev';
import type { CreatedBlock } from '@polkadot/types/interfaces/engine'; import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthCallRequest, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth'; import type { EthAccount, EthCallRequest, EthFeeHistory, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics'; import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa'; import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { MmrLeafBatchProof, MmrLeafProof } from '@polkadot/types/interfaces/mmr'; import type { MmrLeafBatchProof, MmrLeafProof } from '@polkadot/types/interfaces/mmr';
@@ -197,6 +197,10 @@ declare module '@polkadot/rpc-core/types/jsonrpc' {
* Estimate gas needed for execution of given contract. * Estimate gas needed for execution of given contract.
**/ **/
estimateGas: AugmentedRpc<(request: EthCallRequest | { from?: any; to?: any; gasPrice?: any; gas?: any; value?: any; data?: any; nonce?: any } | string | Uint8Array, number?: BlockNumber | AnyNumber | Uint8Array) => Observable<U256>>; estimateGas: AugmentedRpc<(request: EthCallRequest | { from?: any; to?: any; gasPrice?: any; gas?: any; value?: any; data?: any; nonce?: any } | string | Uint8Array, number?: BlockNumber | AnyNumber | Uint8Array) => Observable<U256>>;
/**
* Returns fee history for given block count & reward percentiles
**/
feeHistory: AugmentedRpc<(blockCount: U256 | AnyNumber | Uint8Array, newestBlock: BlockNumber | AnyNumber | Uint8Array, rewardPercentiles: Option<Vec<f64>> | null | object | string | Uint8Array) => Observable<EthFeeHistory>>;
/** /**
* Returns current gas price. * Returns current gas price.
**/ **/
@@ -289,6 +293,10 @@ declare module '@polkadot/rpc-core/types/jsonrpc' {
* Returns the number of hashes per second that the node is mining with. * Returns the number of hashes per second that the node is mining with.
**/ **/
hashrate: AugmentedRpc<() => Observable<U256>>; hashrate: AugmentedRpc<() => Observable<U256>>;
/**
* Returns max priority fee per gas
**/
maxPriorityFeePerGas: AugmentedRpc<() => Observable<U256>>;
/** /**
* Returns true if client is actively mining new blocks. * Returns true if client is actively mining new blocks.
**/ **/
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/rpc-augment authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/rpc-augment', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/rpc-augment', path: 'auto', type: 'auto', version: '8.10.1' };
+7 -7
View File
@@ -20,18 +20,18 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/rpc-augment": "8.8.2", "@polkadot/rpc-augment": "8.10.1",
"@polkadot/rpc-provider": "8.8.2", "@polkadot/rpc-provider": "8.10.1",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/util": "^9.4.1", "@polkadot/util": "^9.6.2",
"rxjs": "^7.5.5" "rxjs": "^7.5.5"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^9.4.1", "@polkadot/keyring": "^9.6.2",
"@polkadot/rpc-augment": "8.8.2" "@polkadot/rpc-augment": "8.10.1"
} }
} }
+7 -3
View File
@@ -12,7 +12,7 @@ import type { RpcInterfaceMethod } from './types';
import { Observable, publishReplay, refCount } from 'rxjs'; import { Observable, publishReplay, refCount } from 'rxjs';
import { rpcDefinitions } from '@polkadot/types'; import { rpcDefinitions } from '@polkadot/types';
import { assert, hexToU8a, isFunction, isNull, isUndefined, lazyMethod, logger, memoize, objectSpread, u8aConcat, u8aToU8a } from '@polkadot/util'; import { hexToU8a, isFunction, isNull, isUndefined, lazyMethod, logger, memoize, objectSpread, u8aConcat, u8aToU8a } from '@polkadot/util';
import { drr, refCountDelay } from './util'; import { drr, refCountDelay } from './util';
@@ -106,7 +106,9 @@ export class RpcCore {
*/ */
constructor (instanceId: string, registry: Registry, provider: ProviderInterface, userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>> = {}) { constructor (instanceId: string, registry: Registry, provider: ProviderInterface, userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>> = {}) {
// eslint-disable-next-line @typescript-eslint/unbound-method // eslint-disable-next-line @typescript-eslint/unbound-method
assert(provider && isFunction(provider.send), 'Expected Provider to API create'); if (!provider || !isFunction(provider.send)) {
throw new Error('Expected Provider to API create');
}
this.#instanceId = instanceId; this.#instanceId = instanceId;
this.#registryDefault = registry; this.#registryDefault = registry;
@@ -360,7 +362,9 @@ export class RpcCore {
? '' ? ''
: ` (${def.params.length - reqArgCount} optional)`; : ` (${def.params.length - reqArgCount} optional)`;
assert(inputs.length >= reqArgCount && inputs.length <= def.params.length, () => `Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`); if (inputs.length < reqArgCount || inputs.length > def.params.length) {
throw new Error(`Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`);
}
return inputs.map((input, index): Codec => return inputs.map((input, index): Codec =>
registry.createTypeUnsafe(def.params[index].type, [input], { blockHash }) registry.createTypeUnsafe(def.params[index].type, [input], { blockHash })
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/rpc-core', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/rpc-core', path: 'auto', type: 'auto', version: '8.10.1' };
+11 -11
View File
@@ -20,21 +20,21 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/keyring": "^9.4.1", "@polkadot/keyring": "^9.6.2",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/types-support": "8.8.2", "@polkadot/types-support": "8.10.1",
"@polkadot/util": "^9.4.1", "@polkadot/util": "^9.6.2",
"@polkadot/util-crypto": "^9.4.1", "@polkadot/util-crypto": "^9.6.2",
"@polkadot/x-fetch": "^9.4.1", "@polkadot/x-fetch": "^9.6.2",
"@polkadot/x-global": "^9.4.1", "@polkadot/x-global": "^9.6.2",
"@polkadot/x-ws": "^9.4.1", "@polkadot/x-ws": "^9.6.2",
"@substrate/connect": "0.7.5", "@substrate/connect": "0.7.7",
"eventemitter3": "^4.0.7", "eventemitter3": "^4.0.7",
"mock-socket": "^9.1.5", "mock-socket": "^9.1.5",
"nock": "^13.2.6" "nock": "^13.2.7"
} }
} }
+18 -4
View File
@@ -3,7 +3,7 @@
import type { JsonRpcRequest, JsonRpcResponse, JsonRpcResponseBaseError } from '../types'; import type { JsonRpcRequest, JsonRpcResponse, JsonRpcResponseBaseError } from '../types';
import { assert, isNumber, isString, isUndefined, stringify } from '@polkadot/util'; import { isNumber, isString, isUndefined, stringify } from '@polkadot/util';
import RpcError from './error'; import RpcError from './error';
@@ -36,15 +36,29 @@ export class RpcCoder {
#id = 0; #id = 0;
public decodeResponse (response?: JsonRpcResponse): unknown { public decodeResponse (response?: JsonRpcResponse): unknown {
assert(response && response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object'); if (!response || response.jsonrpc !== '2.0') {
throw new Error('Invalid jsonrpc field in decoded object');
}
const isSubscription = !isUndefined(response.params) && !isUndefined(response.method); const isSubscription = !isUndefined(response.params) && !isUndefined(response.method);
assert(isNumber(response.id) || (isSubscription && (isNumber(response.params.subscription) || isString(response.params.subscription))), 'Invalid id field in decoded object'); if (
!isNumber(response.id) &&
(
!isSubscription || (
!isNumber(response.params.subscription) &&
!isString(response.params.subscription)
)
)
) {
throw new Error('Invalid id field in decoded object');
}
checkError(response.error); checkError(response.error);
assert(!isUndefined(response.result) || isSubscription, 'No result found in jsonrpc response'); if (response.result === undefined && !isSubscription) {
throw new Error('No result found in jsonrpc response');
}
if (isSubscription) { if (isSubscription) {
checkError(response.params.error); checkError(response.params.error);
+7 -3
View File
@@ -3,7 +3,7 @@
import type { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '../types'; import type { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '../types';
import { assert, logger } from '@polkadot/util'; import { logger } from '@polkadot/util';
import { fetch } from '@polkadot/x-fetch'; import { fetch } from '@polkadot/x-fetch';
import { RpcCoder } from '../coder'; import { RpcCoder } from '../coder';
@@ -49,7 +49,9 @@ export class HttpProvider implements ProviderInterface {
* @param {string} endpoint The endpoint url starting with http:// * @param {string} endpoint The endpoint url starting with http://
*/ */
constructor (endpoint: string = defaults.HTTP_URL, headers: Record<string, string> = {}) { constructor (endpoint: string = defaults.HTTP_URL, headers: Record<string, string> = {}) {
assert(/^(https|http):\/\//.test(endpoint), () => `Endpoint should start with 'http://', received '${endpoint}'`); if (!/^(https|http):\/\//.test(endpoint)) {
throw new Error(`Endpoint should start with 'http://' or 'https://', received '${endpoint}'`);
}
this.#coder = new RpcCoder(); this.#coder = new RpcCoder();
this.#endpoint = endpoint; this.#endpoint = endpoint;
@@ -156,7 +158,9 @@ export class HttpProvider implements ProviderInterface {
method: 'POST' method: 'POST'
}); });
assert(response.ok, () => `[${response.status}]: ${response.statusText}`); if (!response.ok) {
throw new Error(`[${response.status}]: ${response.statusText}`);
}
const result = await response.text(); const result = await response.text();
+10 -4
View File
@@ -16,7 +16,7 @@ import jsonrpc from '@polkadot/types/interfaces/jsonrpc';
import rpcHeader from '@polkadot/types-support/json/Header.004.json'; import rpcHeader from '@polkadot/types-support/json/Header.004.json';
import rpcSignedBlock from '@polkadot/types-support/json/SignedBlock.004.immortal.json'; import rpcSignedBlock from '@polkadot/types-support/json/SignedBlock.004.immortal.json';
import rpcMetadata from '@polkadot/types-support/metadata/static-substrate'; import rpcMetadata from '@polkadot/types-support/metadata/static-substrate';
import { assert, BN, bnToU8a, logger, u8aToHex } from '@polkadot/util'; import { BN, bnToU8a, logger, u8aToHex } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto'; import { randomAsU8a } from '@polkadot/util-crypto';
const INTERVAL = 1000; const INTERVAL = 1000;
@@ -130,7 +130,9 @@ export class MockProvider implements ProviderInterface {
public async send <T = any> (method: string, params: unknown[]): Promise<T> { public async send <T = any> (method: string, params: unknown[]): Promise<T> {
l.debug(() => ['send', method, params]); l.debug(() => ['send', method, params]);
assert(this.requests[method], () => `provider.send: Invalid method '${method}'`); if (!this.requests[method]) {
throw new Error(`provider.send: Invalid method '${method}'`);
}
return this.requests[method](this.db, params) as T; return this.requests[method](this.db, params) as T;
} }
@@ -139,7 +141,9 @@ export class MockProvider implements ProviderInterface {
public async subscribe (type: string, method: string, ...params: unknown[]): Promise<number> { public async subscribe (type: string, method: string, ...params: unknown[]): Promise<number> {
l.debug(() => ['subscribe', method, params]); l.debug(() => ['subscribe', method, params]);
assert(this.subscriptions[method], () => `provider.subscribe: Invalid method '${method}'`); if (!this.subscriptions[method]) {
throw new Error(`provider.subscribe: Invalid method '${method}'`);
}
const callback = params.pop() as MockStateSubscriptionCallback; const callback = params.pop() as MockStateSubscriptionCallback;
const id = ++this.subscriptionId; const id = ++this.subscriptionId;
@@ -160,7 +164,9 @@ export class MockProvider implements ProviderInterface {
l.debug(() => ['unsubscribe', id, sub]); l.debug(() => ['unsubscribe', id, sub]);
assert(sub, () => `Unable to find subscription for ${id}`); if (!sub) {
throw new Error(`Unable to find subscription for ${id}`);
}
delete this.subscriptionMap[id]; delete this.subscriptionMap[id];
delete this.subscriptions[sub].callbacks[id]; delete this.subscriptions[sub].callbacks[id];
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/rpc-provider', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/rpc-provider', path: 'auto', type: 'auto', version: '8.10.1' };
@@ -1,8 +1,6 @@
// Copyright 2017-2022 @polkadot/rpc-provider authors & contributors // Copyright 2017-2022 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import { assert } from '@polkadot/util';
export interface SmoldotHealth { export interface SmoldotHealth {
isSyncing: boolean isSyncing: boolean
peers: number peers: number
@@ -63,10 +61,9 @@ export function healthChecker (): HealthChecker {
return checker.responsePassThrough(jsonRpcResponse); return checker.responsePassThrough(jsonRpcResponse);
}, },
sendJsonRpc: (request) => { sendJsonRpc: (request) => {
assert( if (!sendJsonRpc) {
sendJsonRpc, throw new Error('setSendJsonRpc must be called before sending requests');
'setSendJsonRpc must be called before sending requests' }
);
if (checker === null) { if (checker === null) {
sendJsonRpc(request); sendJsonRpc(request);
@@ -78,14 +75,12 @@ export function healthChecker (): HealthChecker {
sendJsonRpc = cb; sendJsonRpc = cb;
}, },
start: (healthCallback) => { start: (healthCallback) => {
assert( if (checker !== null) {
checker === null, throw new Error("Can't start the health checker multiple times in parallel");
"Can't start the health checker multiple times in parallel" } else if (!sendJsonRpc) {
); throw new Error('setSendJsonRpc must be called before starting the health checks');
assert( }
sendJsonRpc,
'setSendJsonRpc must be called before starting the health checks'
);
checker = new InnerChecker(healthCallback, sendJsonRpc); checker = new InnerChecker(healthCallback, sendJsonRpc);
checker.update(true); checker.update(true);
}, },
@@ -216,7 +211,9 @@ class InnerChecker {
const id: string = parsedResponse.id; const id: string = parsedResponse.id;
// Need to remove the `extern:` prefix. // Need to remove the `extern:` prefix.
assert(id.startsWith('extern:'), 'State inconsistency in health checker'); if (!id.startsWith('extern:')) {
throw new Error('State inconsistency in health checker');
}
const newId = JSON.parse(id.slice('extern:'.length)) as string; const newId = JSON.parse(id.slice('extern:'.length)) as string;
@@ -283,10 +280,9 @@ class InnerChecker {
}; };
startSubscription = (): void => { startSubscription = (): void => {
assert( if (this.#currentSubunsubRequestId || this.#currentSubscriptionId) {
!this.#currentSubunsubRequestId && !this.#currentSubscriptionId, throw new Error('Internal error in health checker');
'Internal error in health checker' }
);
this.#currentSubunsubRequestId = 'health-checker:'.concat( this.#currentSubunsubRequestId = 'health-checker:'.concat(
this.#nextRequestId.toString() this.#nextRequestId.toString()
@@ -303,10 +299,9 @@ class InnerChecker {
}; };
endSubscription = (): void => { endSubscription = (): void => {
assert( if (this.#currentSubunsubRequestId || !this.#currentSubscriptionId) {
!this.#currentSubunsubRequestId && this.#currentSubscriptionId, throw new Error('Internal error in health checker');
'Internal error in health checker' }
);
this.#currentSubunsubRequestId = 'health-checker:'.concat( this.#currentSubunsubRequestId = 'health-checker:'.concat(
this.#nextRequestId.toString() this.#nextRequestId.toString()
@@ -7,7 +7,7 @@ import type { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, Pro
import { Chain, createScClient, ScClient, WellKnownChain } from '@substrate/connect'; import { Chain, createScClient, ScClient, WellKnownChain } from '@substrate/connect';
import EventEmitter from 'eventemitter3'; import EventEmitter from 'eventemitter3';
import { assert, isError } from '@polkadot/util'; import { isError } from '@polkadot/util';
import { RpcCoder } from '../coder'; import { RpcCoder } from '../coder';
import { healthChecker } from './Health'; import { healthChecker } from './Health';
@@ -71,7 +71,9 @@ export class ScProvider implements ProviderInterface {
// Config details can be found in @substrate/connect repo following the link: // Config details can be found in @substrate/connect repo following the link:
// https://github.com/paritytech/substrate-connect/blob/main/packages/connect/src/connector/index.ts // https://github.com/paritytech/substrate-connect/blob/main/packages/connect/src/connector/index.ts
async connect (config?: ScConfig): Promise<void> { async connect (config?: ScConfig): Promise<void> {
assert(!this.isConnected, 'Already connected!'); if (this.isConnected) {
throw new Error('Already connected!');
}
// it could happen that after emitting `disconnected` due to the fact taht // it could happen that after emitting `disconnected` due to the fact taht
// smoldot is syncing, the consumer tries to reconnect after a certain amount // smoldot is syncing, the consumer tries to reconnect after a certain amount
@@ -91,7 +93,10 @@ export class ScProvider implements ProviderInterface {
? scClients.get(this.#sharedSandbox) ? scClients.get(this.#sharedSandbox)
: createScClient(config); : createScClient(config);
assert(client, 'Unkown ScProvider!'); if (!client) {
throw new Error('Unkown ScProvider!');
}
scClients.set(this, client); scClients.set(this, client);
const hc = healthChecker(); const hc = healthChecker();
@@ -156,7 +161,9 @@ export class ScProvider implements ProviderInterface {
const stale = staleSubscriptions.pop(); const stale = staleSubscriptions.pop();
assert(stale, 'Unable to get stale subscription'); if (!stale) {
throw new Error('Unable to get stale subscription');
}
const { id, unsubscribeMethod } = stale; const { id, unsubscribeMethod } = stale;
@@ -264,7 +271,9 @@ export class ScProvider implements ProviderInterface {
} }
public async send<T = any> (method: string, params: unknown[]): Promise<T> { public async send<T = any> (method: string, params: unknown[]): Promise<T> {
assert(this.isConnected && this.#chain, 'Provider is not connected'); if (!this.isConnected || !this.#chain) {
throw new Error('Provider is not connected');
}
const chain = await this.#chain; const chain = await this.#chain;
const [id, json] = this.#coder.encodeJson(method, params); const [id, json] = this.#coder.encodeJson(method, params);
@@ -302,10 +311,9 @@ export class ScProvider implements ProviderInterface {
params: any[], params: any[],
callback: ProviderInterfaceCallback callback: ProviderInterfaceCallback
): Promise<number | string> { ): Promise<number | string> {
assert( if (!subscriptionUnsubscriptionMethods.has(method)) {
subscriptionUnsubscriptionMethods.has(method), throw new Error(`Unsupported subscribe method: ${method}`);
`Unsupported subscribe method: ${method}` }
);
const id = await this.send<number | string>(method, params); const id = await this.send<number | string>(method, params);
const subscriptionId = `${type}::${id}`; const subscriptionId = `${type}::${id}`;
@@ -320,7 +328,9 @@ export class ScProvider implements ProviderInterface {
const unsubscribeMethod = subscriptionUnsubscriptionMethods.get(method); const unsubscribeMethod = subscriptionUnsubscriptionMethods.get(method);
assert(unsubscribeMethod, 'Invalid unsubscribe method found'); if (!unsubscribeMethod) {
throw new Error('Invalid unsubscribe method found');
}
this.#subscriptions.set(subscriptionId, [cb, { id, unsubscribeMethod }]); this.#subscriptions.set(subscriptionId, [cb, { id, unsubscribeMethod }]);
@@ -332,10 +342,9 @@ export class ScProvider implements ProviderInterface {
method: string, method: string,
id: number | string id: number | string
): Promise<boolean> { ): Promise<boolean> {
assert( if (!this.isConnected) {
this.isConnected, throw new Error('Provider is not connected');
'Provider is not connected' }
);
const subscriptionId = `${type}::${id}`; const subscriptionId = `${type}::${id}`;
+13 -5
View File
@@ -7,7 +7,7 @@ import type { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, Pro
import EventEmitter from 'eventemitter3'; import EventEmitter from 'eventemitter3';
import { assert, isChildClass, isNull, isUndefined, logger, objectSpread } from '@polkadot/util'; import { isChildClass, isNull, isUndefined, logger, objectSpread } from '@polkadot/util';
import { xglobal } from '@polkadot/x-global'; import { xglobal } from '@polkadot/x-global';
import { WebSocket } from '@polkadot/x-ws'; import { WebSocket } from '@polkadot/x-ws';
@@ -122,10 +122,14 @@ export class WsProvider implements ProviderInterface {
? endpoint ? endpoint
: [endpoint]; : [endpoint];
assert(endpoints.length !== 0, 'WsProvider requires at least one Endpoint'); if (endpoints.length === 0) {
throw new Error('WsProvider requires at least one Endpoint');
}
endpoints.forEach((endpoint) => { endpoints.forEach((endpoint) => {
assert(/^(wss|ws):\/\//.test(endpoint), () => `Endpoint should start with 'ws://', received '${endpoint}'`); if (!/^(wss|ws):\/\//.test(endpoint)) {
throw new Error(`Endpoint should start with 'ws://', received '${endpoint}'`);
}
}); });
this.#eventemitter = new EventEmitter(); this.#eventemitter = new EventEmitter();
@@ -319,7 +323,9 @@ export class WsProvider implements ProviderInterface {
async #send <T> (id: number, body: string, method: string, params: unknown[], subscription?: SubscriptionHandler): Promise<T> { async #send <T> (id: number, body: string, method: string, params: unknown[], subscription?: SubscriptionHandler): Promise<T> {
return new Promise<T>((resolve, reject): void => { return new Promise<T>((resolve, reject): void => {
try { try {
assert(this.isConnected && !isNull(this.#websocket), 'WebSocket is not connected'); if (!this.isConnected || this.#websocket === null) {
throw new Error('WebSocket is not connected');
}
const callback = (error?: Error | null, result?: T): void => { const callback = (error?: Error | null, result?: T): void => {
error error
@@ -531,7 +537,9 @@ export class WsProvider implements ProviderInterface {
}; };
#onSocketOpen = (): boolean => { #onSocketOpen = (): boolean => {
assert(!isNull(this.#websocket), 'WebSocket cannot be null in onOpen'); if (this.#websocket === null) {
throw new Error('WebSocket cannot be null in onOpen');
}
l.debug(() => ['connected to', this.#endpoints[this.#endpointIndex]]); l.debug(() => ['connected to', this.#endpoints[this.#endpointIndex]]);
+12 -12
View File
@@ -20,7 +20,7 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"bin": { "bin": {
"polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.cjs", "polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.cjs",
@@ -33,17 +33,17 @@
"@babel/core": "^7.18.5", "@babel/core": "^7.18.5",
"@babel/register": "^7.17.7", "@babel/register": "^7.17.7",
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/api": "8.8.2", "@polkadot/api": "8.10.1",
"@polkadot/api-augment": "8.8.2", "@polkadot/api-augment": "8.10.1",
"@polkadot/rpc-augment": "8.8.2", "@polkadot/rpc-augment": "8.10.1",
"@polkadot/rpc-provider": "8.8.2", "@polkadot/rpc-provider": "8.10.1",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/types-augment": "8.8.2", "@polkadot/types-augment": "8.10.1",
"@polkadot/types-codec": "8.8.2", "@polkadot/types-codec": "8.10.1",
"@polkadot/types-create": "8.8.2", "@polkadot/types-create": "8.10.1",
"@polkadot/types-support": "8.8.2", "@polkadot/types-support": "8.10.1",
"@polkadot/util": "^9.4.1", "@polkadot/util": "^9.6.2",
"@polkadot/x-ws": "^9.4.1", "@polkadot/x-ws": "^9.6.2",
"handlebars": "^4.7.7", "handlebars": "^4.7.7",
"websocket": "^1.0.34", "websocket": "^1.0.34",
"yargs": "^17.5.1" "yargs": "^17.5.1"
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/typegen', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/typegen', path: 'auto', type: 'auto', version: '8.10.1' };
+3 -3
View File
@@ -4,8 +4,6 @@
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { assert } from '@polkadot/util';
import { packageInfo } from '../packageInfo'; import { packageInfo } from '../packageInfo';
export function writeFile (dest: string, generator: () => string, noLog?: boolean): void { export function writeFile (dest: string, generator: () => string, noLog?: boolean): void {
@@ -35,7 +33,9 @@ export function readTemplate (template: string): string {
.map((p) => path.join(rootDir, p, `${template}.hbs`)) .map((p) => path.join(rootDir, p, `${template}.hbs`))
.find((p) => fs.existsSync(p)); .find((p) => fs.existsSync(p));
assert(file, `Unable to locate ${template}.hbs from ${rootDir}`); if (!file) {
throw new Error(`Unable to locate ${template}.hbs from ${rootDir}`);
}
return fs.readFileSync(file).toString(); return fs.readFileSync(file).toString();
} }
+2 -2
View File
@@ -3,7 +3,7 @@
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-unused-vars */
import type { Registry } from '@polkadot/types/types'; import type { AnyString, Registry } from '@polkadot/types/types';
import type { TypeDef } from '@polkadot/types-create/types'; import type { TypeDef } from '@polkadot/types-create/types';
import Handlebars from 'handlebars'; import Handlebars from 'handlebars';
@@ -270,7 +270,7 @@ const formatters: Record<TypeDefInfo, (registry: Registry, typeDef: TypeDef, def
*/ */
/** @internal */ /** @internal */
// eslint-disable-next-line @typescript-eslint/ban-types // eslint-disable-next-line @typescript-eslint/ban-types
export function formatType (registry: Registry, definitions: Record<string, ModuleTypes>, type: string | String | TypeDef, imports: TypeImports, withShortcut = false): string { export function formatType (registry: Registry, definitions: Record<string, ModuleTypes>, type: AnyString | TypeDef, imports: TypeImports, withShortcut = false): string {
let typeDef: TypeDef; let typeDef: TypeDef;
if (isString(type)) { if (isString(type)) {
+4 -4
View File
@@ -20,12 +20,12 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/types-codec": "8.8.2", "@polkadot/types-codec": "8.10.1",
"@polkadot/util": "^9.4.1" "@polkadot/util": "^9.6.2"
} }
} }
+5 -5
View File
@@ -5,13 +5,13 @@
export default { export default {
/** /**
* Lookup79: kusama_runtime::ProxyType * Lookup80: kusama_runtime::ProxyType
**/ **/
KusamaRuntimeProxyType: { KusamaRuntimeProxyType: {
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement', 'CancelProxy', 'Auction', 'Society'] _enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement', 'CancelProxy', 'Auction', 'Society']
}, },
/** /**
* Lookup258: kusama_runtime::SessionKeys * Lookup261: kusama_runtime::SessionKeys
**/ **/
KusamaRuntimeSessionKeys: { KusamaRuntimeSessionKeys: {
grandpa: 'SpFinalityGrandpaAppPublic', grandpa: 'SpFinalityGrandpaAppPublic',
@@ -22,7 +22,7 @@ export default {
authorityDiscovery: 'SpAuthorityDiscoveryAppPublic' authorityDiscovery: 'SpAuthorityDiscoveryAppPublic'
}, },
/** /**
* Lookup332: kusama_runtime::OriginCaller * Lookup335: kusama_runtime::OriginCaller
**/ **/
KusamaRuntimeOriginCaller: { KusamaRuntimeOriginCaller: {
_enum: { _enum: {
@@ -129,7 +129,7 @@ export default {
} }
}, },
/** /**
* Lookup398: kusama_runtime::NposCompactSolution24 * Lookup401: kusama_runtime::NposCompactSolution24
**/ **/
KusamaRuntimeNposCompactSolution24: { KusamaRuntimeNposCompactSolution24: {
votes1: 'Vec<(Compact<u32>,Compact<u16>)>', votes1: 'Vec<(Compact<u32>,Compact<u16>)>',
@@ -158,7 +158,7 @@ export default {
votes24: 'Vec<(Compact<u32>,[(Compact<u16>,Compact<PerU16>);23],Compact<u16>)>' votes24: 'Vec<(Compact<u32>,[(Compact<u16>,Compact<PerU16>);23],Compact<u16>)>'
}, },
/** /**
* Lookup774: kusama_runtime::Runtime * Lookup779: kusama_runtime::Runtime
**/ **/
KusamaRuntimeRuntime: 'Null' KusamaRuntimeRuntime: 'Null'
}; };
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -6,7 +6,7 @@ declare module '@polkadot/types/lookup' {
import type { ITuple } from '@polkadot/types-codec/types'; import type { ITuple } from '@polkadot/types-codec/types';
import type { PerU16 } from '@polkadot/types/interfaces/runtime'; import type { PerU16 } from '@polkadot/types/interfaces/runtime';
/** @name KusamaRuntimeProxyType (79) */ /** @name KusamaRuntimeProxyType (80) */
export interface KusamaRuntimeProxyType extends Enum { export interface KusamaRuntimeProxyType extends Enum {
readonly isAny: boolean; readonly isAny: boolean;
readonly isNonTransfer: boolean; readonly isNonTransfer: boolean;
@@ -19,7 +19,7 @@ declare module '@polkadot/types/lookup' {
readonly type: 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | 'IdentityJudgement' | 'CancelProxy' | 'Auction' | 'Society'; readonly type: 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | 'IdentityJudgement' | 'CancelProxy' | 'Auction' | 'Society';
} }
/** @name KusamaRuntimeSessionKeys (258) */ /** @name KusamaRuntimeSessionKeys (261) */
export interface KusamaRuntimeSessionKeys extends Struct { export interface KusamaRuntimeSessionKeys extends Struct {
readonly grandpa: SpFinalityGrandpaAppPublic; readonly grandpa: SpFinalityGrandpaAppPublic;
readonly babe: SpConsensusBabeAppPublic; readonly babe: SpConsensusBabeAppPublic;
@@ -29,7 +29,7 @@ declare module '@polkadot/types/lookup' {
readonly authorityDiscovery: SpAuthorityDiscoveryAppPublic; readonly authorityDiscovery: SpAuthorityDiscoveryAppPublic;
} }
/** @name KusamaRuntimeOriginCaller (332) */ /** @name KusamaRuntimeOriginCaller (335) */
export interface KusamaRuntimeOriginCaller extends Enum { export interface KusamaRuntimeOriginCaller extends Enum {
readonly isSystem: boolean; readonly isSystem: boolean;
readonly asSystem: FrameSupportDispatchRawOrigin; readonly asSystem: FrameSupportDispatchRawOrigin;
@@ -45,7 +45,7 @@ declare module '@polkadot/types/lookup' {
readonly type: 'System' | 'Void' | 'Council' | 'TechnicalCommittee' | 'ParachainsOrigin' | 'XcmPallet'; readonly type: 'System' | 'Void' | 'Council' | 'TechnicalCommittee' | 'ParachainsOrigin' | 'XcmPallet';
} }
/** @name KusamaRuntimeNposCompactSolution24 (398) */ /** @name KusamaRuntimeNposCompactSolution24 (401) */
export interface KusamaRuntimeNposCompactSolution24 extends Struct { export interface KusamaRuntimeNposCompactSolution24 extends Struct {
readonly votes1: Vec<ITuple<[Compact<u32>, Compact<u16>]>>; readonly votes1: Vec<ITuple<[Compact<u32>, Compact<u16>]>>;
readonly votes2: Vec<ITuple<[Compact<u32>, ITuple<[Compact<u16>, Compact<PerU16>]>, Compact<u16>]>>; readonly votes2: Vec<ITuple<[Compact<u32>, ITuple<[Compact<u16>, Compact<PerU16>]>, Compact<u16>]>>;
@@ -73,7 +73,7 @@ declare module '@polkadot/types/lookup' {
readonly votes24: Vec<ITuple<[Compact<u32>, Vec<ITuple<[Compact<u16>, Compact<PerU16>]>>, Compact<u16>]>>; readonly votes24: Vec<ITuple<[Compact<u32>, Vec<ITuple<[Compact<u16>, Compact<PerU16>]>>, Compact<u16>]>>;
} }
/** @name KusamaRuntimeRuntime (774) */ /** @name KusamaRuntimeRuntime (779) */
export type KusamaRuntimeRuntime = Null; export type KusamaRuntimeRuntime = Null;
} // declare module } // declare module
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/types-augment authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/types-augment', path: 'auto', type: 'auto', version: '8.8.2' }; export const packageInfo = { name: '@polkadot/types-augment', path: 'auto', type: 'auto', version: '8.10.1' };
@@ -2,7 +2,7 @@
/* eslint-disable */ /* eslint-disable */
import type { Data, StorageKey } from '@polkadot/types'; import type { Data, StorageKey } from '@polkadot/types';
import type { BitVec, Bool, Bytes, I128, I16, I256, I32, I64, I8, Json, Null, OptionBool, Raw, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types-codec'; import type { BitVec, Bool, Bytes, F32, F64, I128, I16, I256, I32, I64, I8, Json, Null, OptionBool, Raw, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, f32, f64, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types-codec';
import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets'; import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';
import type { BlockAttestations, IncludedBlocks, MoreAttestations } from '@polkadot/types/interfaces/attestations'; import type { BlockAttestations, IncludedBlocks, MoreAttestations } from '@polkadot/types/interfaces/attestations';
import type { RawAuraPreDigest } from '@polkadot/types/interfaces/aura'; import type { RawAuraPreDigest } from '@polkadot/types/interfaces/aura';
@@ -10,7 +10,7 @@ import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interface
import type { UncleEntryItem } from '@polkadot/types/interfaces/authorship'; 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 { 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 { 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 { BeefyCommitment, BeefyId, BeefyNextAuthoritySet, BeefyPayload, BeefyPayloadId, BeefySignedCommitment, MmrRootHash, ValidatorSetId } from '@polkadot/types/interfaces/beefy';
import type { BridgeMessageId, 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 { BridgeMessageId, 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 { BlockHash } from '@polkadot/types/interfaces/chain';
import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate'; import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
@@ -25,7 +25,7 @@ import type { AccountVote, AccountVoteSplit, AccountVoteStandard, Conviction, De
import type { BlockStats } from '@polkadot/types/interfaces/dev'; import type { BlockStats } from '@polkadot/types/interfaces/dev';
import type { ApprovalFlag, DefunctVoter, Renouncing, SetIndex, Vote, VoteIndex, VoteThreshold, VoterInfo } from '@polkadot/types/interfaces/elections'; import type { ApprovalFlag, DefunctVoter, Renouncing, SetIndex, Vote, VoteIndex, VoteThreshold, VoterInfo } from '@polkadot/types/interfaces/elections';
import type { CreatedBlock, ImportedAux } from '@polkadot/types/interfaces/engine'; import type { CreatedBlock, ImportedAux } from '@polkadot/types/interfaces/engine';
import type { BlockV0, BlockV1, BlockV2, EIP1559Transaction, EIP2930Transaction, EthAccessList, EthAccessListItem, EthAccount, EthAddress, 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, EthereumAddress, EthereumLookupSource, EthereumSignature, LegacyTransaction, TransactionV0, TransactionV1, TransactionV2 } from '@polkadot/types/interfaces/eth'; import type { BlockV0, BlockV1, BlockV2, EIP1559Transaction, EIP2930Transaction, EthAccessList, EthAccessListItem, EthAccount, EthAddress, EthBlock, EthBloom, EthCallRequest, EthFeeHistory, 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, EthereumAddress, EthereumLookupSource, EthereumSignature, LegacyTransaction, TransactionV0, TransactionV1, TransactionV2 } from '@polkadot/types/interfaces/eth';
import type { EvmAccount, EvmLog, EvmVicinity, ExitError, ExitFatal, ExitReason, ExitRevert, ExitSucceed } from '@polkadot/types/interfaces/evm'; import type { EvmAccount, EvmLog, EvmVicinity, ExitError, ExitFatal, ExitReason, ExitRevert, ExitSucceed } from '@polkadot/types/interfaces/evm';
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 { 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 { AssetOptions, Owner, PermissionLatest, PermissionVersions, PermissionsV1 } from '@polkadot/types/interfaces/genericAsset';
@@ -141,6 +141,7 @@ declare module '@polkadot/types/types/registry' {
BeefyKey: BeefyKey; BeefyKey: BeefyKey;
BeefyNextAuthoritySet: BeefyNextAuthoritySet; BeefyNextAuthoritySet: BeefyNextAuthoritySet;
BeefyPayload: BeefyPayload; BeefyPayload: BeefyPayload;
BeefyPayloadId: BeefyPayloadId;
BeefySignedCommitment: BeefySignedCommitment; BeefySignedCommitment: BeefySignedCommitment;
Bid: Bid; Bid: Bid;
Bidder: Bidder; Bidder: Bidder;
@@ -360,6 +361,7 @@ declare module '@polkadot/types/types/registry' {
EthereumAddress: EthereumAddress; EthereumAddress: EthereumAddress;
EthereumLookupSource: EthereumLookupSource; EthereumLookupSource: EthereumLookupSource;
EthereumSignature: EthereumSignature; EthereumSignature: EthereumSignature;
EthFeeHistory: EthFeeHistory;
EthFilter: EthFilter; EthFilter: EthFilter;
EthFilterAddress: EthFilterAddress; EthFilterAddress: EthFilterAddress;
EthFilterChanges: EthFilterChanges; EthFilterChanges: EthFilterChanges;
@@ -424,6 +426,10 @@ declare module '@polkadot/types/types/registry' {
ExtrinsicsWeight: ExtrinsicsWeight; ExtrinsicsWeight: ExtrinsicsWeight;
ExtrinsicUnknown: ExtrinsicUnknown; ExtrinsicUnknown: ExtrinsicUnknown;
ExtrinsicV4: ExtrinsicV4; ExtrinsicV4: ExtrinsicV4;
f32: f32;
F32: F32;
f64: f64;
F64: F64;
FeeDetails: FeeDetails; FeeDetails: FeeDetails;
Fixed128: Fixed128; Fixed128: Fixed128;
Fixed64: Fixed64; Fixed64: Fixed64;
File diff suppressed because one or more lines are too long
+7 -6
View File
@@ -20,16 +20,17 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.8.2", "version": "8.10.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@polkadot/util": "^9.4.1" "@polkadot/util": "^9.6.2",
"@polkadot/x-bigint": "^9.6.2"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/types": "8.8.2", "@polkadot/types": "8.10.1",
"@polkadot/types-augment": "8.8.2", "@polkadot/types-augment": "8.10.1",
"@polkadot/types-support": "8.8.2", "@polkadot/types-support": "8.10.1",
"@polkadot/util-crypto": "^9.4.1" "@polkadot/util-crypto": "^9.6.2"
} }
} }
@@ -20,6 +20,14 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
public createdAtHash?: IU8a; public createdAtHash?: IU8a;
/**
* @description This ensures that operators such as clice, filter, map, etc. return
* new Array instances (without this we need to apply overrides)
*/
static get [Symbol.species] (): typeof Array {
return Array;
}
protected constructor (registry: Registry, length: number) { protected constructor (registry: Registry, length: number) {
super(length); super(length);
@@ -73,14 +81,14 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
inspect (): Inspect { public inspect (): Inspect {
return { return {
inner: this.inspectInner(), inner: this.inspectInner(),
outer: [compactToU8a(this.length)] outer: [compactToU8a(this.length)]
}; };
} }
inspectInner (): Inspect[] { public inspectInner (): Inspect[] {
const inner = new Array<Inspect>(this.length); const inner = new Array<Inspect>(this.length);
for (let i = 0; i < this.length; i++) { for (let i = 0; i < this.length; i++) {
@@ -169,43 +177,4 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
return encoded; return encoded;
} }
// Below are methods that we override. When we do a `new Vec(...).map()`,
// we want it to return an Array. We only override the methods that return a
// new instance.
/**
* @description Concatenates two arrays
*/
public override concat (other: T[]): T[] {
return this.toArray().concat(other instanceof AbstractArray ? other.toArray() : other);
}
/**
* @description Filters the array with the callback
*/
public override filter (callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: unknown): T[] {
return this.toArray().filter(callbackfn, thisArg);
}
/**
* @description Maps the array with the callback
*/
public override map<U> (callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: unknown): U[] {
return this.toArray().map(callbackfn, thisArg);
}
/**
* @description Checks if the array includes a specific value
*/
public override includes (check: unknown): boolean {
return this.some((value: T) => value.eq(check));
}
/**
* @description Returns a slice of an array
*/
public override slice (start?: number, end?: number): T[] {
return this.toArray().slice(start, end);
}
} }
@@ -8,19 +8,19 @@ import type { AnyJson, BareOpts, Codec, Inspect, IU8a, Registry } from '../types
* @name Base * @name Base
* @description A type extends the Base class, when it holds a value * @description A type extends the Base class, when it holds a value
*/ */
export abstract class Base<T extends Codec> implements Codec { export abstract class AbstractBase<T extends Codec> implements Codec {
readonly #registry: Registry;
public createdAtHash?: IU8a; public createdAtHash?: IU8a;
readonly initialU8aLength?: number; public readonly initialU8aLength?: number;
public readonly registry: Registry;
readonly #raw: T; readonly #raw: T;
protected constructor (registry: Registry, value: T, initialU8aLength?: number) { protected constructor (registry: Registry, value: T, initialU8aLength?: number) {
this.#registry = registry;
this.#raw = value; this.#raw = value;
this.initialU8aLength = initialU8aLength; this.initialU8aLength = initialU8aLength;
this.registry = registry;
} }
/** /**
@@ -48,10 +48,6 @@ export abstract class Base<T extends Codec> implements Codec {
return this.#raw.isEmpty; return this.#raw.isEmpty;
} }
public get registry (): Registry {
return this.#registry;
}
/** /**
* @description Compares the value of the input to see if there is a match * @description Compares the value of the input to see if there is a match
*/ */
@@ -62,7 +58,7 @@ export abstract class Base<T extends Codec> implements Codec {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
inspect (): Inspect { public inspect (): Inspect {
return this.#raw.inspect(); return this.#raw.inspect();
} }
@@ -0,0 +1,16 @@
// Copyright 2017-2022 @polkadot/types-codec authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { BigInt } from '@polkadot/x-bigint';
// @ts-expect-error not extensible, we make it extensible here
export abstract class AbstractBigInt extends BigInt {
// @ts-expect-error super() not required, the self magic does that
constructor (value: string | number | bigint | boolean) {
const self = Object(BigInt(value)) as typeof AbstractBigInt;
Object.setPrototypeOf(self, AbstractBigInt.prototype);
return self;
}
}
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types'; import type { HexString } from '@polkadot/util/types';
import type { AnyNumber, Inspect, INumber, IU8a, Registry, UIntBitLength } from '../types'; import type { AnyNumber, Inspect, INumber, IU8a, Registry, UIntBitLength } from '../types';
import { assert, BN, BN_BILLION, BN_HUNDRED, BN_MILLION, BN_QUINTILL, BN_ZERO, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isBn, isHex, isNumber, isString, isU8a, u8aToBn } from '@polkadot/util'; import { BN, BN_BILLION, BN_HUNDRED, BN_MILLION, BN_QUINTILL, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isBn, isHex, isNumber, isString, isU8a, u8aToBn, u8aToNumber } from '@polkadot/util';
export const DEFAULT_UINT_BITS = 64; export const DEFAULT_UINT_BITS = 64;
@@ -25,15 +25,25 @@ function toPercentage (value: BN, divisor: BN): string {
} }
/** @internal */ /** @internal */
function decodeAbstractInt (value: Exclude<AnyNumber, Uint8Array>, isNegative: boolean): string { function decodeAbstractInt (value: Exclude<AnyNumber, Uint8Array>, isNegative: boolean): string | number {
if (isBn(value)) { if (isNumber(value)) {
return value.toString(); if (!Number.isInteger(value) || value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER) {
} else if (isHex(value, -1, true)) { throw new Error('Number needs to be an integer <= Number.MAX_SAFE_INTEGER, i.e. 2 ^ 53 - 1');
return hexToBn(value, { isLe: false, isNegative }).toString(); }
} else if (isNumber(value)) {
assert(value <= Number.MAX_SAFE_INTEGER && value >= Number.MIN_SAFE_INTEGER && Number.isInteger(value), 'Number needs to be an integer <= Number.MAX_SAFE_INTEGER, i.e. 2 ^ 53 - 1'); return value;
} else if (isString(value)) { } else if (isString(value)) {
assert(!(value.includes('.') || value.includes(',') || value.includes('e')), 'String should not contain decimal points or scientific notation'); if (isHex(value, -1, true)) {
return hexToBn(value, { isLe: false, isNegative }).toString();
}
if (value.includes('.') || value.includes(',') || value.includes('e')) {
throw new Error('String should not contain decimal points or scientific notation');
}
return value;
} else if (isBn(value)) {
return value.toString();
} }
return bnToBn(value).toString(); return bnToBn(value).toString();
@@ -49,33 +59,38 @@ export abstract class AbstractInt extends BN implements INumber {
public createdAtHash?: IU8a; public createdAtHash?: IU8a;
readonly encodedLength: number; public readonly encodedLength: number;
public readonly isUnsigned: boolean;
readonly #bitLength: UIntBitLength; readonly #bitLength: UIntBitLength;
readonly #isSigned: boolean;
constructor (registry: Registry, value: AnyNumber = 0, bitLength: UIntBitLength = DEFAULT_UINT_BITS, isSigned = false) { constructor (registry: Registry, value: AnyNumber = 0, bitLength: UIntBitLength = DEFAULT_UINT_BITS, isSigned = false) {
// Construct via a string, which will be passed in the BN constructor. // Construct via a string/number, which will be passed in the BN constructor.
// It would be ideal to actually return a BN, but there is an issue: // It would be ideal to actually return a BN, but there is an issue:
// https://github.com/indutny/bn.js/issues/206 // https://github.com/indutny/bn.js/issues/206
super( super(
// shortcut isU8a as used in SCALE decoding // shortcut isU8a as used in SCALE decoding
isU8a(value) isU8a(value)
? u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative: isSigned }).toString() ? bitLength <= 48
? u8aToNumber(value.subarray(0, bitLength / 8), { isNegative: isSigned })
: u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative: isSigned }).toString()
: decodeAbstractInt(value, isSigned) : decodeAbstractInt(value, isSigned)
); );
this.registry = registry; this.registry = registry;
this.#bitLength = bitLength; this.#bitLength = bitLength;
this.encodedLength = this.#bitLength / 8; this.encodedLength = this.#bitLength / 8;
this.#isSigned = isSigned; this.isUnsigned = !isSigned;
const isPositive = this.gte(BN_ZERO); const isNegative = this.isNeg();
const maxBits = bitLength - (isSigned && isPositive ? 1 : 0); const maxBits = bitLength - (isSigned && !isNegative ? 1 : 0);
assert(isSigned || isPositive, () => `${this.toRawType()}: Negative number passed to unsigned type`); if (isNegative && !isSigned) {
assert(super.bitLength() <= maxBits, () => `${this.toRawType()}: Input too large. Found input with ${super.bitLength()} bits, expected ${maxBits}`); throw new Error(`${this.toRawType()}: Negative number passed to unsigned type`);
} else if (super.bitLength() > maxBits) {
throw new Error(`${this.toRawType()}: Input too large. Found input with ${super.bitLength()} bits, expected ${maxBits}`);
}
} }
/** /**
@@ -92,13 +107,6 @@ export abstract class AbstractInt extends BN implements INumber {
return this.isZero(); return this.isZero();
} }
/**
* @description Checks if the value is an unsigned type
*/
public get isUnsigned (): boolean {
return !this.#isSigned;
}
/** /**
* @description Returns the number of bits in the value * @description Returns the number of bits in the value
*/ */
@@ -115,7 +123,7 @@ export abstract class AbstractInt extends BN implements INumber {
// number and BN inputs (no `.eqn` needed) - numbers will be converted // number and BN inputs (no `.eqn` needed) - numbers will be converted
return super.eq( return super.eq(
isHex(other) isHex(other)
? hexToBn(other.toString(), { isLe: false, isNegative: this.#isSigned }) ? hexToBn(other.toString(), { isLe: false, isNegative: !this.isUnsigned })
: bnToBn(other as string) : bnToBn(other as string)
); );
} }
@@ -123,7 +131,7 @@ export abstract class AbstractInt extends BN implements INumber {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
inspect (): Inspect { public inspect (): Inspect {
return { return {
outer: [this.toU8a()] outer: [this.toU8a()]
}; };
+3 -2
View File
@@ -1,5 +1,6 @@
// Copyright 2017-2022 @polkadot/types-codec authors & contributors // Copyright 2017-2022 @polkadot/types-codec authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { AbstractArray } from './AbstractArray'; export { AbstractArray } from './Array';
export { AbstractInt } from './AbstractInt'; export { AbstractBase } from './Base';
export { AbstractInt } from './Int';
@@ -5,6 +5,10 @@ import { TypeRegistry } from '@polkadot/types';
import { CodecDate, Compact, U32 } from '@polkadot/types-codec'; import { CodecDate, Compact, U32 } from '@polkadot/types-codec';
import { BN } from '@polkadot/util'; import { BN } from '@polkadot/util';
import { perf } from '../test/performance';
const CompactU32 = Compact.with(U32);
describe('Compact', (): void => { describe('Compact', (): void => {
const registry = new TypeRegistry(); const registry = new TypeRegistry();
@@ -88,4 +92,6 @@ describe('Compact', (): void => {
}); });
}); });
}); });
perf('Compact', 75_000, [[new Uint8Array([63 << 2])]], (v: Uint8Array) => new CompactU32(registry, v));
}); });
+23 -18
View File
@@ -5,7 +5,7 @@ import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types'; import type { HexString } from '@polkadot/util/types';
import type { AnyJson, AnyNumber, CodecClass, ICompact, Inspect, INumber, IU8a, Registry } from '../types'; import type { AnyJson, AnyNumber, CodecClass, ICompact, Inspect, INumber, IU8a, Registry } from '../types';
import { compactFromU8a, compactToU8a, isU8a } from '@polkadot/util'; import { compactFromU8a, compactFromU8aLim, compactToU8a, isU8a } from '@polkadot/util';
import { typeToConstructor } from '../utils'; import { typeToConstructor } from '../utils';
@@ -18,6 +18,26 @@ function noopSetDefinition <T> (d: CodecClass<T>): CodecClass<T> {
return d; return d;
} }
function decodeCompact<T extends INumber> (registry: Registry, Type: CodecClass<T>, value: Compact<T> | AnyNumber): [T, number] {
if (isU8a(value)) {
const [decodedLength, bn] = (value[0] & 0b11) < 0b11
? compactFromU8aLim(value)
: compactFromU8a(value);
return [new Type(registry, bn), decodedLength];
} else if (value instanceof Compact) {
const raw = value.unwrap();
return raw instanceof Type
? [raw, 0]
: [new Type(registry, raw), 0];
} else if (value instanceof Type) {
return [value, 0];
}
return [new Type(registry, value), 0];
}
/** /**
* @name Compact * @name Compact
* @description * @description
@@ -41,7 +61,7 @@ export class Compact<T extends INumber> implements ICompact<T> {
this.registry = registry; this.registry = registry;
this.#Type = definition || setDefinition(typeToConstructor(registry, Type)); this.#Type = definition || setDefinition(typeToConstructor(registry, Type));
const [raw, decodedLength] = Compact.decodeCompact<T>(registry, this.#Type, value); const [raw, decodedLength] = decodeCompact<T>(registry, this.#Type, value);
this.initialU8aLength = decodedLength; this.initialU8aLength = decodedLength;
this.#raw = raw; this.#raw = raw;
@@ -61,21 +81,6 @@ export class Compact<T extends INumber> implements ICompact<T> {
}; };
} }
/** @internal */
public static decodeCompact<T extends INumber> (registry: Registry, Type: CodecClass<T>, value: Compact<T> | AnyNumber): [T, number] {
if (isU8a(value)) {
const [decodedLength, bn] = compactFromU8a(value);
return [new Type(registry, bn), decodedLength];
} else if (value instanceof Compact) {
return [new Type(registry, value.#raw), 0];
} else if (value instanceof Type) {
return [value, 0];
}
return [new Type(registry, value), 0];
}
/** /**
* @description The length of the value when encoded as a Uint8Array * @description The length of the value when encoded as a Uint8Array
*/ */
@@ -118,7 +123,7 @@ export class Compact<T extends INumber> implements ICompact<T> {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
inspect (): Inspect { public inspect (): Inspect {
return { return {
outer: [this.toU8a()] outer: [this.toU8a()]
}; };
@@ -56,7 +56,7 @@ export class DoNotConstruct implements Codec {
throw this.#neverError; throw this.#neverError;
} }
inspect (): Inspect { public inspect (): Inspect {
throw this.#neverError; throw this.#neverError;
} }
@@ -7,6 +7,10 @@ import { TypeRegistry } from '@polkadot/types';
import { Enum, Null, Text, U32 } from '@polkadot/types-codec'; import { Enum, Null, Text, U32 } from '@polkadot/types-codec';
import { u8aToHex } from '@polkadot/util'; import { u8aToHex } from '@polkadot/util';
import { perf } from '../test/performance';
const PEnum = Enum.with({ a: U32, b: U32 });
describe('Enum', (): void => { describe('Enum', (): void => {
const registry = new TypeRegistry(); const registry = new TypeRegistry();
@@ -449,4 +453,6 @@ describe('Enum', (): void => {
); );
}); });
}); });
perf('Enum', 20_000, [[new Uint8Array([0, 31, 32, 33, 34])]], (v: Uint8Array) => new PEnum(registry, v));
}); });
+43 -16
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types'; import type { HexString } from '@polkadot/util/types';
import type { AnyJson, Codec, CodecClass, IEnum, Inspect, IU8a, Registry } from '../types'; import type { AnyJson, Codec, CodecClass, IEnum, Inspect, IU8a, Registry } from '../types';
import { assert, isCodec, isHex, isNumber, isObject, isString, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, stringPascalCase, u8aConcatStrict, u8aToHex, u8aToU8a } from '@polkadot/util'; import { isHex, isNumber, isObject, isString, isU8a, objectProperties, stringCamelCase, stringify, stringPascalCase, u8aConcatStrict, u8aToHex, u8aToU8a } from '@polkadot/util';
import { mapToTypeMap, typesToMap } from '../utils'; import { mapToTypeMap, typesToMap } from '../utils';
import { Null } from './Null'; import { Null } from './Null';
@@ -45,7 +45,9 @@ function isRustEnum (def: Record<string, string | CodecClass> | Record<string, n
const defValues = Object.values(def); const defValues = Object.values(def);
if (defValues.some((v) => isNumber(v))) { if (defValues.some((v) => isNumber(v))) {
assert(defValues.every((v) => isNumber(v) && v >= 0 && v <= 255), 'Invalid number-indexed enum definition'); if (!defValues.every((v) => isNumber(v) && v >= 0 && v <= 255)) {
throw new Error('Invalid number-indexed enum definition');
}
return false; return false;
} }
@@ -94,16 +96,37 @@ function extractDef (registry: Registry, _def: Record<string, string | CodecClas
}; };
} }
function createFromValue (registry: Registry, def: TypesDef, index = 0, value?: unknown): Decoded { function getEntryType (def: TypesDef, checkIdx: number): CodecClass {
const entry = Object.values(def).find((e) => e.index === index); const values = Object.values(def);
assert(!isUndefined(entry), () => `Unable to create Enum via index ${index}, in ${Object.keys(def).join(', ')}`); for (let i = 0; i < values.length; i++) {
const { Type, index } = values[i];
if (index === checkIdx) {
return Type;
}
}
throw new Error(`Unable to create Enum via index ${checkIdx}, in ${Object.keys(def).join(', ')}`);
}
function createFromU8a (registry: Registry, def: TypesDef, index: number, value: Uint8Array): Decoded {
const Type = getEntryType(def, index);
return { return {
index, index,
value: isCodec(value) && value instanceof entry.Type value: new Type(registry, value)
};
}
function createFromValue (registry: Registry, def: TypesDef, index = 0, value?: unknown): Decoded {
const Type = getEntryType(def, index);
return {
index,
value: value instanceof Type
? value ? value
: new entry.Type(registry, value) : new Type(registry, value)
}; };
} }
@@ -114,7 +137,9 @@ function decodeFromJSON (registry: Registry, def: TypesDef, key: string, value?:
const keyLower = key.toLowerCase(); const keyLower = key.toLowerCase();
const index = keys.indexOf(keyLower); const index = keys.indexOf(keyLower);
assert(index !== -1, () => `Cannot map Enum JSON, unable to find '${key}' in ${keys.join(', ')}`); if (index === -1) {
throw new Error(`Cannot map Enum JSON, unable to find '${key}' in ${keys.join(', ')}`);
}
try { try {
return createFromValue(registry, def, Object.values(def)[index].index, value); return createFromValue(registry, def, Object.values(def)[index].index, value);
@@ -133,7 +158,7 @@ function decodeEnum (registry: Registry, def: TypesDef, value?: unknown, index?:
// nested, we don't want to match isObject below // nested, we don't want to match isObject below
if (u8a.length) { if (u8a.length) {
return createFromValue(registry, def, u8a[0], u8a.subarray(1)); return createFromU8a(registry, def, u8a[0], u8a.subarray(1));
} }
} else if (value instanceof Enum) { } else if (value instanceof Enum) {
return createFromValue(registry, def, value.index, value.value); return createFromValue(registry, def, value.index, value.value);
@@ -181,7 +206,7 @@ export class Enum implements IEnum {
// shortcut isU8a as used in SCALE decoding // shortcut isU8a as used in SCALE decoding
const decoded = isU8a(value) && value.length && !isNumber(index) const decoded = isU8a(value) && value.length && !isNumber(index)
? createFromValue(registry, def, value[0], value.subarray(1)) ? createFromU8a(registry, def, value[0], value.subarray(1))
: decodeEnum(registry, def, value, index); : decodeEnum(registry, def, value, index);
this.registry = registry; this.registry = registry;
@@ -189,7 +214,7 @@ export class Enum implements IEnum {
this.#isBasic = isBasic; this.#isBasic = isBasic;
this.#isIndexed = isIndexed; this.#isIndexed = isIndexed;
this.#indexes = Object.values(def).map(({ index }) => index); this.#indexes = Object.values(def).map(({ index }) => index);
this.#entryIndex = this.#indexes.indexOf(decoded.index) || 0; this.#entryIndex = this.#indexes.indexOf(decoded.index);
this.#raw = decoded.value; this.#raw = decoded.value;
if (this.#raw.initialU8aLength) { if (this.#raw.initialU8aLength) {
@@ -205,7 +230,7 @@ export class Enum implements IEnum {
const isKeys = new Array<string>(keys.length); const isKeys = new Array<string>(keys.length);
for (let i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
const name = stringPascalCase(keys[i].replace(' ', '_')); const name = stringPascalCase(keys[i]);
asKeys[i] = `as${name}`; asKeys[i] = `as${name}`;
isKeys[i] = `is${name}`; isKeys[i] = `is${name}`;
@@ -223,7 +248,9 @@ export class Enum implements IEnum {
objectProperties(this, isKeys, (_, i) => this.type === keys[i]); objectProperties(this, isKeys, (_, i) => this.type === keys[i]);
objectProperties(this, asKeys, (k, i): Codec => { objectProperties(this, asKeys, (k, i): Codec => {
assert(this[isKeys[i] as keyof this], () => `Cannot convert '${this.type}' via ${k}`); if (!this[isKeys[i] as keyof this]) {
throw new Error(`Cannot convert '${this.type}' via ${k}`);
}
return this.value; return this.value;
}); });
@@ -329,7 +356,7 @@ export class Enum implements IEnum {
return this.type === other; return this.type === other;
} else if (isHex(other)) { } else if (isHex(other)) {
return this.toHex() === other; return this.toHex() === other;
} else if (isCodec(other) && other instanceof Enum) { } else if (other instanceof Enum) {
return this.index === other.index && this.value.eq(other.value); return this.index === other.index && this.value.eq(other.value);
} else if (isObject(other)) { } else if (isObject(other)) {
return this.value.eq(other[this.type]); return this.value.eq(other[this.type]);
@@ -342,8 +369,8 @@ export class Enum implements IEnum {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
inspect (): Inspect { public inspect (): Inspect {
if (this.isBasic) { if (this.#isBasic) {
return { outer: [new Uint8Array([this.index])] }; return { outer: [new Uint8Array([this.index])] };
} }
+1 -1
View File
@@ -3,7 +3,7 @@
import type { AnyNumber, CodecClass, Registry, UIntBitLength } from '../types'; import type { AnyNumber, CodecClass, Registry, UIntBitLength } from '../types';
import { AbstractInt } from '../abstract/AbstractInt'; import { AbstractInt } from '../abstract/Int';
/** /**
* @name Int * @name Int
+5 -15
View File
@@ -12,6 +12,10 @@ import { isNull } from '@polkadot/util';
* Implements a type that does not contain anything (apart from `null`) * Implements a type that does not contain anything (apart from `null`)
*/ */
export class Null implements Codec { export class Null implements Codec {
public readonly encodedLength = 0;
public readonly isEmpty = true;
public readonly registry: Registry; public readonly registry: Registry;
public createdAtHash?: IU8a; public createdAtHash?: IU8a;
@@ -23,13 +27,6 @@ export class Null implements Codec {
this.registry = registry; this.registry = registry;
} }
/**
* @description The length of the value when encoded as a Uint8Array
*/
public get encodedLength (): number {
return 0;
}
/** /**
* @description returns a hash of the contents * @description returns a hash of the contents
*/ */
@@ -37,13 +34,6 @@ export class Null implements Codec {
throw new Error('.hash is not implemented on Null'); throw new Error('.hash is not implemented on Null');
} }
/**
* @description Checks if the value is an empty value (always true)
*/
public get isEmpty (): boolean {
return true;
}
/** /**
* @description Compares the value of the input to see if there is a match * @description Compares the value of the input to see if there is a match
*/ */
@@ -54,7 +44,7 @@ export class Null implements Codec {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
inspect (): Inspect { public inspect (): Inspect {
return {}; return {};
} }
+8 -13
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types'; import type { HexString } from '@polkadot/util/types';
import type { AnyJson, Codec, CodecClass, Inspect, IOption, IU8a, Registry } from '../types'; import type { AnyJson, Codec, CodecClass, Inspect, IOption, IU8a, Registry } from '../types';
import { assert, isCodec, isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util'; import { isCodec, isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util';
import { typeToConstructor } from '../utils'; import { typeToConstructor } from '../utils';
import { Null } from './Null'; import { Null } from './Null';
@@ -70,9 +70,9 @@ export class Option<T extends Codec> implements IOption<T> {
public createdAtHash?: IU8a; public createdAtHash?: IU8a;
readonly #Type: CodecClass<T>; public initialU8aLength?: number;
readonly #initialU8aLength?: number; readonly #Type: CodecClass<T>;
readonly #raw: T; readonly #raw: T;
@@ -89,7 +89,7 @@ export class Option<T extends Codec> implements IOption<T> {
this.#raw = decoded as T; this.#raw = decoded as T;
if (decoded && decoded.initialU8aLength) { if (decoded && decoded.initialU8aLength) {
this.#initialU8aLength = 1 + decoded.initialU8aLength; this.initialU8aLength = 1 + decoded.initialU8aLength;
} }
} }
@@ -117,13 +117,6 @@ export class Option<T extends Codec> implements IOption<T> {
return 1 + this.#raw.encodedLength; return 1 + this.#raw.encodedLength;
} }
/**
* @description The length of the initial encoded value (Only available when constructed from a Uint8Array)
*/
public get initialU8aLength (): number | undefined {
return this.#initialU8aLength;
}
/** /**
* @description returns a hash of the contents * @description returns a hash of the contents
*/ */
@@ -173,7 +166,7 @@ export class Option<T extends Codec> implements IOption<T> {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
inspect (): Inspect { public inspect (): Inspect {
if (this.isNone) { if (this.isNone) {
return { outer: [new Uint8Array([0])] }; return { outer: [new Uint8Array([0])] };
} }
@@ -254,7 +247,9 @@ export class Option<T extends Codec> implements IOption<T> {
* @description Returns the value that the Option represents (if available), throws if null * @description Returns the value that the Option represents (if available), throws if null
*/ */
public unwrap (): T { public unwrap (): T {
assert(this.isSome, 'Option: unwrapping a None value'); if (this.isNone) {
throw new Error('Option: unwrapping a None value');
}
return this.#raw; return this.#raw;
} }
+6 -4
View File
@@ -3,8 +3,6 @@
import type { Codec, CodecClass, IResult, Registry } from '../types'; import type { Codec, CodecClass, IResult, Registry } from '../types';
import { assert } from '@polkadot/util';
import { Enum } from './Enum'; import { Enum } from './Enum';
/** /**
@@ -31,7 +29,9 @@ export class Result<O extends Codec, E extends Codec> extends Enum implements IR
* @description Returns the wrapper Err value (if isErr) * @description Returns the wrapper Err value (if isErr)
*/ */
public get asErr (): E { public get asErr (): E {
assert(this.isErr, 'Cannot extract Err value from Ok result, check isErr first'); if (!this.isErr) {
throw new Error('Cannot extract Err value from Ok result, check isErr first');
}
return this.value as E; return this.value as E;
} }
@@ -47,7 +47,9 @@ export class Result<O extends Codec, E extends Codec> extends Enum implements IR
* @description Returns the wrapper Ok value (if isOk) * @description Returns the wrapper Ok value (if isOk)
*/ */
public get asOk (): O { public get asOk (): O {
assert(this.isOk, 'Cannot extract Ok value from Err result, check isOk first'); if (!this.isOk) {
throw new Error('Cannot extract Ok value from Err result, check isOk first');
}
return this.value as O; return this.value as O;
} }
+8 -8
View File
@@ -5,7 +5,7 @@ import type { AnyTupleValue, Codec, CodecClass, Inspect, ITuple, Registry } from
import { isFunction, isHex, isString, isU8a, stringify, u8aConcatStrict, u8aToU8a } from '@polkadot/util'; import { isFunction, isHex, isString, isU8a, stringify, u8aConcatStrict, u8aToU8a } from '@polkadot/util';
import { AbstractArray } from '../abstract/AbstractArray'; import { AbstractArray } from '../abstract/Array';
import { decodeU8a, mapToTypeMap, typeToConstructor } from '../utils'; import { decodeU8a, mapToTypeMap, typeToConstructor } from '../utils';
type TupleType = (CodecClass | string); type TupleType = (CodecClass | string);
@@ -26,7 +26,7 @@ function noopSetDefinition (d: Definition): Definition {
} }
/** @internal */ /** @internal */
function decodeTuple (registry: Registry, result: Codec[], Classes: Definition, value?: Exclude<AnyTupleValue, Uint8Array>): [Codec[], number] { function decodeTuple (registry: Registry, result: Codec[], value: Exclude<AnyTupleValue, Uint8Array> | undefined, Classes: Definition): [Codec[], number] {
if (isU8a(value) || isHex(value)) { if (isU8a(value) || isHex(value)) {
return decodeU8a(registry, result, u8aToU8a(value), Classes); return decodeU8a(registry, result, u8aToU8a(value), Classes);
} }
@@ -70,11 +70,11 @@ export class Tuple extends AbstractArray<Codec> implements ITuple<Codec[]> {
super(registry, Classes[0].length); super(registry, Classes[0].length);
const [, decodedLength] = isU8a(value) this.initialU8aLength = (
? decodeU8a(registry, this, value, Classes, false) isU8a(value)
: decodeTuple(registry, this, Classes, value); ? decodeU8a(registry, this, value, Classes)
: decodeTuple(registry, this, value, Classes)
this.initialU8aLength = decodedLength; )[1];
this.#Types = Classes; this.#Types = Classes;
} }
@@ -117,7 +117,7 @@ export class Tuple extends AbstractArray<Codec> implements ITuple<Codec[]> {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
override inspect (): Inspect { public override inspect (): Inspect {
return { return {
inner: this.inspectInner() inner: this.inspectInner()
}; };
@@ -5,6 +5,8 @@ import { TypeRegistry } from '@polkadot/types';
import { UInt } from '@polkadot/types-codec'; import { UInt } from '@polkadot/types-codec';
import { BN, BN_TWO, isBn } from '@polkadot/util'; import { BN, BN_TWO, isBn } from '@polkadot/util';
import { perf } from '../test/performance';
describe('UInt', (): void => { describe('UInt', (): void => {
const registry = new TypeRegistry(); const registry = new TypeRegistry();
@@ -180,4 +182,6 @@ describe('UInt', (): void => {
expect(registry.createType('Balance', '123456789012345').toHuman()).toEqual('123.4567 Unit'); expect(registry.createType('Balance', '123456789012345').toHuman()).toEqual('123.4567 Unit');
}); });
}); });
perf('UInt', 75_000, [[new Uint8Array([31, 32, 33, 34])]], (v: Uint8Array) => new UInt(registry, v));
}); });
+1 -1
View File
@@ -3,7 +3,7 @@
import type { AnyNumber, CodecClass, Registry, UIntBitLength } from '../types'; import type { AnyNumber, CodecClass, Registry, UIntBitLength } from '../types';
import { AbstractInt } from '../abstract/AbstractInt'; import { AbstractInt } from '../abstract/Int';
/** /**
* @name UInt * @name UInt
+6 -1
View File
@@ -5,12 +5,15 @@ import type { PropIndex } from '@polkadot/types/interfaces/democracy';
import type { Codec, CodecTo, ITuple } from '@polkadot/types-codec/types'; import type { Codec, CodecTo, ITuple } from '@polkadot/types-codec/types';
import { createTypeUnsafe, GenericAccountId as AccountId, Metadata, TypeRegistry } from '@polkadot/types'; import { createTypeUnsafe, GenericAccountId as AccountId, Metadata, TypeRegistry } from '@polkadot/types';
import { Text, Vec } from '@polkadot/types-codec'; import { Text, u32, Vec } from '@polkadot/types-codec';
import rpcMetadata from '@polkadot/types-support/metadata/static-substrate'; import rpcMetadata from '@polkadot/types-support/metadata/static-substrate';
import { decodeAddress, randomAsU8a } from '@polkadot/util-crypto'; import { decodeAddress, randomAsU8a } from '@polkadot/util-crypto';
import { perf } from '../test/performance';
const registry = new TypeRegistry(); const registry = new TypeRegistry();
const metadata = new Metadata(registry, rpcMetadata); const metadata = new Metadata(registry, rpcMetadata);
const VecU32 = Vec.with(u32);
registry.setMetadata(metadata); registry.setMetadata(metadata);
@@ -190,4 +193,6 @@ describe('Vec', (): void => {
}); });
}); });
}); });
perf('Vec<U32>', 40_000, [[new Uint8Array([3 << 2, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34])]], (v: Uint8Array) => new VecU32(registry, v));
}); });
+10 -8
View File
@@ -4,9 +4,9 @@
import type { HexString } from '@polkadot/util/types'; import type { HexString } from '@polkadot/util/types';
import type { Codec, CodecClass, Registry } from '../types'; import type { Codec, CodecClass, Registry } from '../types';
import { assert, compactFromU8aLim, isU8a, logger, u8aToU8a } from '@polkadot/util'; import { compactFromU8aLim, isU8a, logger, u8aToU8a } from '@polkadot/util';
import { AbstractArray } from '../abstract/AbstractArray'; import { AbstractArray } from '../abstract/Array';
import { decodeU8aVec, typeToConstructor } from '../utils'; import { decodeU8aVec, typeToConstructor } from '../utils';
const MAX_LENGTH = 64 * 1024; const MAX_LENGTH = 64 * 1024;
@@ -30,7 +30,9 @@ function decodeVecLength (value: Uint8Array | HexString | unknown[]): [Uint8Arra
const u8a = u8aToU8a(value); const u8a = u8aToU8a(value);
const [startAt, length] = compactFromU8aLim(u8a); const [startAt, length] = compactFromU8aLim(u8a);
assert(length <= MAX_LENGTH, () => `Vec length ${length.toString()} exceeds ${MAX_LENGTH}`); if (length > MAX_LENGTH) {
throw new Error(`Vec length ${length.toString()} exceeds ${MAX_LENGTH}`);
}
return [u8a, length, startAt]; return [u8a, length, startAt];
} }
@@ -78,11 +80,11 @@ export class Vec<T extends Codec> extends AbstractArray<T> {
this.#Type = definition || setDefinition(typeToConstructor<T>(registry, Type)); this.#Type = definition || setDefinition(typeToConstructor<T>(registry, Type));
const [decodedLength] = isU8a(decodeFrom) this.initialU8aLength = (
? decodeU8aVec(registry, this, decodeFrom, startAt, this.#Type) isU8a(decodeFrom)
: decodeVec(registry, this, decodeFrom, startAt, this.#Type); ? decodeU8aVec(registry, this, decodeFrom, startAt, this.#Type)
: decodeVec(registry, this, decodeFrom, startAt, this.#Type)
this.initialU8aLength = decodedLength; )[0];
} }
public static with<O extends Codec> (Type: CodecClass<O> | string): CodecClass<Vec<O>> { public static with<O extends Codec> (Type: CodecClass<O> | string): CodecClass<Vec<O>> {
+1 -1
View File
@@ -3,7 +3,7 @@
import type { Codec } from '../types'; import type { Codec } from '../types';
import { AbstractArray } from '../abstract/AbstractArray'; import { AbstractArray } from '../abstract/Array';
/** /**
* @name VecAny * @name VecAny
+7 -7
View File
@@ -6,7 +6,7 @@ import type { Codec, CodecClass, Inspect, Registry } from '../types';
import { isU8a, u8aConcatStrict } from '@polkadot/util'; import { isU8a, u8aConcatStrict } from '@polkadot/util';
import { AbstractArray } from '../abstract/AbstractArray'; import { AbstractArray } from '../abstract/Array';
import { decodeU8aVec, typeToConstructor } from '../utils'; import { decodeU8aVec, typeToConstructor } from '../utils';
import { decodeVec } from './Vec'; import { decodeVec } from './Vec';
@@ -34,11 +34,11 @@ export class VecFixed<T extends Codec> extends AbstractArray<T> {
this.#Type = definition || setDefinition(typeToConstructor<T>(registry, Type)); this.#Type = definition || setDefinition(typeToConstructor<T>(registry, Type));
const [, decodedLengthNoOffset] = isU8a(value) this.initialU8aLength = (
? decodeU8aVec(registry, this, value, 0, this.#Type) isU8a(value)
: decodeVec(registry, this, value, 0, this.#Type); ? decodeU8aVec(registry, this, value, 0, this.#Type)
: decodeVec(registry, this, value, 0, this.#Type)
this.initialU8aLength = decodedLengthNoOffset; )[1];
} }
public static with<O extends Codec> (Type: CodecClass<O> | string, length: number): CodecClass<VecFixed<O>> { public static with<O extends Codec> (Type: CodecClass<O> | string, length: number): CodecClass<VecFixed<O>> {
@@ -78,7 +78,7 @@ export class VecFixed<T extends Codec> extends AbstractArray<T> {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
override inspect (): Inspect { public override inspect (): Inspect {
return { return {
inner: this.inspectInner() inner: this.inspectInner()
}; };
-1
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2022 @polkadot/types-codec authors & contributors // Copyright 2017-2022 @polkadot/types-codec authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { Base } from './Base';
export { Compact } from './Compact'; export { Compact } from './Compact';
export { DoNotConstruct } from './DoNotConstruct'; export { DoNotConstruct } from './DoNotConstruct';
export { Enum } from './Enum'; export { Enum } from './Enum';
@@ -140,7 +140,7 @@ export class BTreeSet<V extends Codec = Codec> extends Set<V> implements ISet<V>
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
inspect (): Inspect { public inspect (): Inspect {
const inner = new Array<Inspect>(); const inner = new Array<Inspect>();
for (const v of this.values()) { for (const v of this.values()) {
+5 -3
View File
@@ -3,7 +3,7 @@
import type { AnyU8a, Inspect, Registry } from '../types'; import type { AnyU8a, Inspect, Registry } from '../types';
import { assert, compactFromU8aLim, compactToU8a, isString, u8aConcatStrict, u8aToU8a } from '@polkadot/util'; import { compactFromU8aLim, compactToU8a, isString, u8aConcatStrict, u8aToU8a } from '@polkadot/util';
import { Raw } from '../native/Raw'; import { Raw } from '../native/Raw';
@@ -17,7 +17,9 @@ function decodeBitVecU8a (value?: Uint8Array): [number, Uint8Array] {
const [offset, length] = compactFromU8aLim(value); const [offset, length] = compactFromU8aLim(value);
const total = offset + Math.ceil(length / 8); const total = offset + Math.ceil(length / 8);
assert(total <= value.length, () => `BitVec: required length less than remainder, expected at least ${total}, found ${value.length}`); if (total > value.length) {
throw new Error(`BitVec: required length less than remainder, expected at least ${total}, found ${value.length}`);
}
return [length, value.subarray(offset, total)]; return [length, value.subarray(offset, total)];
} }
@@ -65,7 +67,7 @@ export class BitVec extends Raw {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
override inspect (): Inspect { public override inspect (): Inspect {
return { return {
outer: [compactToU8a(this.#decodedLength), super.toU8a()] outer: [compactToU8a(this.#decodedLength), super.toU8a()]
}; };
+8 -5
View File
@@ -3,7 +3,7 @@
import type { AnyU8a, Inspect, Registry } from '../types'; import type { AnyU8a, Inspect, Registry } from '../types';
import { assert, compactAddLength, compactFromU8aLim, compactToU8a, isCodec, isString, isU8a, u8aToU8a } from '@polkadot/util'; import { compactAddLength, compactFromU8aLim, compactToU8a, isString, isU8a, u8aToU8a } from '@polkadot/util';
import { Raw } from '../native/Raw'; import { Raw } from '../native/Raw';
@@ -20,8 +20,11 @@ function decodeBytesU8a (value: Uint8Array): [Uint8Array, number] {
const [offset, length] = compactFromU8aLim(value); const [offset, length] = compactFromU8aLim(value);
const total = offset + length; const total = offset + length;
assert(length <= MAX_LENGTH, () => `Bytes length ${length.toString()} exceeds ${MAX_LENGTH}`); if (length > MAX_LENGTH) {
assert(total <= value.length, () => `Bytes: required length less than remainder, expected at least ${total}, found ${value.length}`); throw new Error(`Bytes length ${length.toString()} exceeds ${MAX_LENGTH}`);
} else if (total > value.length) {
throw new Error(`Bytes: required length less than remainder, expected at least ${total}, found ${value.length}`);
}
return [value.subarray(offset, total), total]; return [value.subarray(offset, total), total];
} }
@@ -35,7 +38,7 @@ function decodeBytesU8a (value: Uint8Array): [Uint8Array, number] {
*/ */
export class Bytes extends Raw { export class Bytes extends Raw {
constructor (registry: Registry, value?: AnyU8a) { constructor (registry: Registry, value?: AnyU8a) {
const [u8a, decodedLength] = isU8a(value) && !(isCodec(value) && value instanceof Raw) const [u8a, decodedLength] = isU8a(value) && !(value instanceof Raw)
? decodeBytesU8a(value) ? decodeBytesU8a(value)
: Array.isArray(value) || isString(value) : Array.isArray(value) || isString(value)
? [u8aToU8a(value), 0] ? [u8aToU8a(value), 0]
@@ -54,7 +57,7 @@ export class Bytes extends Raw {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
override inspect (isBare?: boolean): Inspect { public override inspect (isBare?: boolean): Inspect {
const clength = compactToU8a(this.length); const clength = compactToU8a(this.length);
return { return {
+2 -2
View File
@@ -6,7 +6,7 @@ import type { AnyJson, Codec, CodecClass, IMap, Inspect, IU8a, Registry } from '
import { compactFromU8aLim, compactToU8a, isHex, isObject, isU8a, logger, stringify, u8aConcatStrict, u8aToHex, u8aToU8a } from '@polkadot/util'; import { compactFromU8aLim, compactToU8a, isHex, isObject, isU8a, logger, stringify, u8aConcatStrict, u8aToHex, u8aToU8a } from '@polkadot/util';
import { AbstractArray } from '../abstract/AbstractArray'; import { AbstractArray } from '../abstract/Array';
import { Enum } from '../base/Enum'; import { Enum } from '../base/Enum';
import { Struct } from '../native/Struct'; import { Struct } from '../native/Struct';
import { compareMap, decodeU8a, sortMap, typeToConstructor } from '../utils'; import { compareMap, decodeU8a, sortMap, typeToConstructor } from '../utils';
@@ -154,7 +154,7 @@ export class CodecMap<K extends Codec = Codec, V extends Codec = Codec> extends
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
inspect (): Inspect { public inspect (): Inspect {
const inner = new Array<Inspect>(); const inner = new Array<Inspect>();
for (const [k, v] of this.entries()) { for (const [k, v] of this.entries()) {
@@ -32,6 +32,8 @@ export class OptionBool extends Option<Bool> {
? decodeU8a(registry, u8aToU8a(value)) ? decodeU8a(registry, u8aToU8a(value))
: value : value
); );
this.initialU8aLength = 1;
} }
/** /**
@@ -41,13 +43,6 @@ export class OptionBool extends Option<Bool> {
return 1; return 1;
} }
/**
* @description The length of the initial encoded value (Only available when constructed from a Uint8Array)
*/
public override get initialU8aLength (): number {
return 1;
}
/** /**
* @description Checks if the value is an empty value (always false) * @description Checks if the value is an empty value (always false)
*/ */
@@ -69,7 +64,7 @@ export class OptionBool extends Option<Bool> {
/** /**
* @description Returns a breakdown of the hex encoding for this Codec * @description Returns a breakdown of the hex encoding for this Codec
*/ */
override inspect (): Inspect { public override inspect (): Inspect {
return { outer: [this.toU8a()] }; return { outer: [this.toU8a()] };
} }
@@ -3,7 +3,7 @@
import type { AnyU8a, CodecClass, Registry, U8aBitLength } from '../types'; import type { AnyU8a, CodecClass, Registry, U8aBitLength } from '../types';
import { assert, isU8a, u8aToU8a } from '@polkadot/util'; import { isU8a, u8aToU8a } from '@polkadot/util';
import { Raw } from '../native/Raw'; import { Raw } from '../native/Raw';
@@ -16,7 +16,9 @@ function decodeU8aFixed (value: AnyU8a, bitLength: U8aBitLength): [AnyU8a, numbe
return [new Uint8Array(byteLength), 0]; return [new Uint8Array(byteLength), 0];
} }
assert(isU8a(value) ? u8a.length >= byteLength : u8a.length === byteLength, () => `Expected input with ${byteLength} bytes (${bitLength} bits), found ${u8a.length} bytes`); if (isU8a(value) ? u8a.length < byteLength : u8a.length !== byteLength) {
throw new Error(`Expected input with ${byteLength} bytes (${bitLength} bits), found ${u8a.length} bytes`);
}
return [u8a.subarray(0, byteLength), byteLength]; return [u8a.subarray(0, byteLength), byteLength];
} }

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