Compare commits

..
33 Commits
Author SHA1 Message Date
Github Actions 63483b9db7 [CI Skip] release/stable 1.23.1
skip-checks: true
2020-07-06 05:45:32 +00:00
Jaco Greeff b26c7f9f0a 1.23.1 (ith version bump) 2020-07-06 07:31:36 +02:00
Github Actions a165c9375c [CI Skip] release/beta 1.23.0-beta.7
skip-checks: true
2020-07-06 05:27:04 +00:00
Jaco Greeff 28631f7180 1.23 (#2411) 2020-07-06 07:15:07 +02:00
Github Actions 6489251b47 [CI Skip] release/beta 1.23.0-beta.6
skip-checks: true
2020-07-03 15:34:13 +00:00
Jaco Greeff 66884febea Add OpaqueCall type (#2408) 2020-07-03 17:22:02 +02:00
Github Actions 8058dc350f [CI Skip] release/beta 1.23.0-beta.5
skip-checks: true
2020-07-03 10:05:48 +00:00
Jaco Greeff 63096cc238 Remove unneeded base extends (#2407)
* Remove unneeded base extends

* CHANGELOG

* Result with value on enum
2020-07-03 11:55:39 +02:00
Github Actions 05600c0cd0 [CI Skip] release/beta 1.23.0-beta.4
skip-checks: true
2020-07-03 09:46:07 +00:00
Jaco Greeff eed5e23e65 Validate number sign in AbstractInt (#2406) 2020-07-03 11:33:30 +02:00
Github Actions cdf5b15673 [CI Skip] release/beta 1.23.0-beta.3
skip-checks: true
2020-07-02 05:27:15 +00:00
Jaco Greeff 1922676bd7 Bump deps (#2404) 2020-07-02 07:14:08 +02:00
Github Actions b6c427e985 [CI Skip] release/beta 1.23.0-beta.2
skip-checks: true
2020-07-01 15:55:54 +00:00
Jaco Greeff 0327aedf8e Update ProxyType for Kusama, Polkadot & Westend (#2403)
* Update ProxyType fro Kusama, Polkadot & Westend

* CHANGELOG
2020-07-01 17:42:22 +02:00
Github Actions d7035cebb1 [CI Skip] release/beta 1.23.0-beta.1
skip-checks: true
2020-07-01 11:51:42 +00:00
Daniel Maricic 8b492021af Fixed typo in README (#2402) 2020-07-01 13:39:07 +02:00
Github Actions 6a01fc7c8c [CI Skip] release/beta 1.23.0-beta.0
skip-checks: true
2020-07-01 05:58:34 +00:00
Jaco Greeff bbc30ec9dc Cross-referencing type failure (#2400)
* Cross-referencing type failure

* typo

* Adjust toRawType() with name from registry

* Rewrite yarn.lock

* Adjustments

* Test adjustments
2020-07-01 07:47:21 +02:00
Github Actions f07c0628bc [CI Skip] release/stable 1.22.1
skip-checks: true
2020-06-30 08:04:08 +00:00
Jaco Greeff 023c7588e5 1.22 (#2399)
* 1.22

* CHANGELOG for OpenTip
2020-06-30 09:52:42 +02:00
Jaco Greeff 7dfc8625cc New OpenTip structure (#2394)
* New OpenTip structure

* Kusama update
2020-06-29 16:20:43 +02:00
Github Actions 8643b5da87 [CI Skip] release/beta 1.22.0-beta.5
skip-checks: true
2020-06-29 07:03:10 +00:00
Jaco Greeff afa0e63ae8 CHANGELOG & Bumps (#2397)
* CHANGELOG & Bumps

* Rewrite yarn.lock
2020-06-29 08:52:12 +02:00
Github Actions 534303ff45 [CI Skip] release/beta 1.22.0-beta.4
skip-checks: true
2020-06-28 14:18:29 +00:00
Jaco Greeff f1ebcddec6 Adjust for vesting via locks (#2396) 2020-06-28 16:08:02 +02:00
Github Actions 657a2006dd [CI Skip] release/beta 1.22.0-beta.3
skip-checks: true
2020-06-24 19:02:00 +00:00
Jaco Greeff 219e928c01 Retried staker rewards for specified eras (#2392) 2020-06-24 20:52:21 +02:00
Github Actions 43183118d5 [CI Skip] release/beta 1.22.0-beta.2
skip-checks: true
2020-06-24 10:43:10 +00:00
Alexander Krupenkin 76e15d465d Add [u8; 33] type width for U8aFixed type (#2391)
ECDSA compressed public key has 33-byte length, this is required for encoding public key as a parameter.
2020-06-24 12:31:55 +02:00
Github Actions 4c0387e1a3 [CI Skip] release/beta 1.22.0-beta.1
skip-checks: true
2020-06-23 20:31:15 +00:00
Jaco Greeff bbbd82eb4a Move indices cache to indices list (#2390) 2020-06-23 22:19:13 +02:00
Github Actions a34a7450aa [CI Skip] release/beta 1.22.0-beta.0
skip-checks: true
2020-06-23 18:38:54 +00:00
Jaco Greeff bf472fdcf4 Optimize accountId -> accountIndex lookups (#2389) 2020-06-23 20:25:58 +02:00
49 changed files with 1876 additions and 1588 deletions
+18
View File
@@ -1,5 +1,23 @@
# CHANGELOG # CHANGELOG
## 1.23.1 Jul 6, 2020
- Small README typo fix (Thanks to https://github.com/woss)
- Add latest Substrate master types
- Adjust `<Codec>.toRawType()` to use registry name as available
- Update `ProxyType` for Kusama, Polkadot & Westend with `IdentityJudgement`
- Validate number format (signed/unsigned) for number types
- Remove core codec dependencies on Base class (with proper TS encapsulation)
## 1.22.1 Jun 30, 2020
- **Important** Substrate changed the treasury tip structure, on older chains supply `OpenTip: 'OpenTipTo225'`
- Allow for `[u8; 33]` in U8aFixed (Thanks to https://github.com/akru)
- Improve derive accountId -> accountIndex lookups (optimize entries queries)
- Vesting balance calculations via `derive.balances.all` has been updated for locks
- Add derive for multi staking rewards with specified eras
- `@polkadot/util` 2.16
## 1.21.1 Jun 23, 2020 ## 1.21.1 Jun 23, 2020
- Fix subscriptions never unsubscribing after the id swap in 1.18.1 (Thanks to https://github.com/dillu24 for testing iterations) - Fix subscriptions never unsubscribing after the id swap in 1.18.1 (Thanks to https://github.com/dillu24 for testing iterations)
+1 -1
View File
@@ -7,7 +7,7 @@
# @polkadot/api # @polkadot/api
This library provides a clean wrapper around all the methods exposed by a Polkadot/Subtrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/). This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/).
If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions. If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions.
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [ "packages": [
"packages/*" "packages/*"
], ],
"version": "1.21.1" "version": "1.23.1"
} }
+7 -7
View File
@@ -24,15 +24,15 @@
"test:watch": "polkadot-dev-run-test --watch" "test:watch": "polkadot-dev-run-test --watch"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.10.3", "@babel/core": "^7.10.4",
"@babel/register": "^7.10.3", "@babel/register": "^7.10.4",
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/dev": "^0.55.12", "@polkadot/dev": "^0.55.20",
"@polkadot/ts": "^0.3.26", "@polkadot/ts": "^0.3.27",
"@polkadot/typegen": "workspace:packages/typegen", "@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^26.0.0", "@types/jest": "^26.0.3",
"@vuepress/plugin-search": "^1.5.2", "@vuepress/plugin-search": "^1.5.2",
"copyfiles": "^2.3.0" "copyfiles": "^2.3.0"
}, },
"version": "1.21.1" "version": "1.23.1"
} }
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api-contract", "name": "@polkadot/api-contract",
"version": "1.21.1", "version": "1.23.1",
"description": "Interfaces for interacting with contracts and contract ABIs", "description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -26,12 +26,12 @@
}, },
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/api": "1.21.1", "@polkadot/api": "1.23.1",
"@polkadot/rpc-core": "1.21.1", "@polkadot/rpc-core": "1.23.1",
"@polkadot/types": "1.21.1", "@polkadot/types": "1.23.1",
"@polkadot/util": "^2.15.1", "@polkadot/util": "^2.17.1",
"bn.js": "^5.1.2", "bn.js": "^5.1.2",
"rxjs": "^6.5.5" "rxjs": "^6.6.0"
} }
} }
+10 -10
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api-derive", "name": "@polkadot/api-derive",
"version": "1.21.1", "version": "1.23.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.", "description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -27,18 +27,18 @@
}, },
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/api": "1.21.1", "@polkadot/api": "1.23.1",
"@polkadot/rpc-core": "1.21.1", "@polkadot/rpc-core": "1.23.1",
"@polkadot/rpc-provider": "1.21.1", "@polkadot/rpc-provider": "1.23.1",
"@polkadot/types": "1.21.1", "@polkadot/types": "1.23.1",
"@polkadot/util": "^2.15.1", "@polkadot/util": "^2.17.1",
"@polkadot/util-crypto": "^2.15.1", "@polkadot/util-crypto": "^2.17.1",
"bn.js": "^5.1.2", "bn.js": "^5.1.2",
"memoizee": "^0.4.14", "memoizee": "^0.4.14",
"rxjs": "^6.5.5" "rxjs": "^6.6.0"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^2.15.1" "@polkadot/keyring": "^2.17.1"
} }
} }
+17 -6
View File
@@ -16,6 +16,8 @@ import { memo } from '../util';
const enumsetSize = ENUMSET_SIZE.toNumber(); const enumsetSize = ENUMSET_SIZE.toNumber();
let indicesCache: AccountIndexes | null = null;
function queryEnumSet (api: ApiInterfaceRx): Observable<AccountIndexes> { function queryEnumSet (api: ApiInterfaceRx): Observable<AccountIndexes> {
return api.query.indices.nextEnumSet<AccountIndex>().pipe( return api.query.indices.nextEnumSet<AccountIndex>().pipe(
// use the nextEnumSet (which is a counter of the number of sets) to construct // use the nextEnumSet (which is a counter of the number of sets) to construct
@@ -72,11 +74,20 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
*/ */
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> { export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
return memo((): Observable<AccountIndexes> => return memo((): Observable<AccountIndexes> =>
(api.query.indices indicesCache
? isFunction(api.query.indices.accounts) ? of(indicesCache)
? queryAccounts(api) : (
: queryEnumSet(api) api.query.indices
: of({} as AccountIndexes) ? isFunction(api.query.indices.accounts)
).pipe(startWith({})) ? queryAccounts(api).pipe(startWith({}))
: queryEnumSet(api).pipe(startWith({}))
: of({} as AccountIndexes)
).pipe(
map((indices): AccountIndexes => {
indicesCache = indices;
return indices;
})
)
); );
} }
+11 -15
View File
@@ -20,15 +20,17 @@ type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll { function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll {
let lockedBalance = api.registry.createType('Balance'); let lockedBalance = api.registry.createType('Balance');
let lockedBreakdown: (BalanceLock | BalanceLockTo212)[] = []; let lockedBreakdown: (BalanceLock | BalanceLockTo212)[] = [];
let vestingLocked = api.registry.createType('Balance');
let allLocked = false; let allLocked = false;
if (Array.isArray(locks)) { if (Array.isArray(locks)) {
// only get the locks that are valid until passed the current block // only get the locks that are valid until passed the current block
lockedBreakdown = (locks as BalanceLockTo212[]).filter(({ until }): boolean => !until || (bestNumber && until.gt(bestNumber))); lockedBreakdown = (locks as BalanceLockTo212[]).filter(({ until }): boolean => !until || (bestNumber && until.gt(bestNumber)));
const notAll = lockedBreakdown.filter(({ amount }): boolean => !amount.isMax()); const notAll = lockedBreakdown.filter(({ amount }) => !amount.isMax());
allLocked = lockedBreakdown.some(({ amount }): boolean => amount.isMax()); allLocked = lockedBreakdown.some(({ amount }) => amount.isMax());
vestingLocked = api.registry.createType('Balance', lockedBreakdown.filter(({ id }) => id.eq('0x76657374696e6720')).reduce((result: BN, { amount }) => result.iadd(amount), new BN(0)));
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699 // get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
if (notAll.length) { if (notAll.length) {
@@ -41,19 +43,11 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
// - perBlock is the unlock amount // - perBlock is the unlock amount
const { locked: vestingTotal, perBlock, startingBlock } = vesting || api.registry.createType('VestingInfo'); const { locked: vestingTotal, perBlock, startingBlock } = vesting || api.registry.createType('VestingInfo');
const isStarted = bestNumber.gt(startingBlock); const isStarted = bestNumber.gt(startingBlock);
const vestedBalance = api.registry.createType('Balance', isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : 0); const vestedNow = isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : new BN(0);
const isVesting = isStarted && vestedBalance.lt(vestingTotal); const vestedBalance = vestedNow.gt(vestingTotal) ? vestingTotal : api.registry.createType('Balance', vestedNow);
const isVesting = isStarted && !vestingLocked.isZero();
// The available balance & vested has an interplay here const vestedClaimable = api.registry.createType('Balance', isVesting ? vestingLocked.sub(vestingTotal.sub(vestedBalance)) : 0);
// " const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), freeBalance.sub(lockedBalance)));
// vesting is a guarantee that the account's balance will never go below a certain amount. so it functions in the opposite way, a bit like a lock that is monotonically decreasing rather than a liquid amount that is monotonically increasing.
// locks function as the same guarantee - that a balance will not be lower than a particular amount.
// because of this you can see that if there is a "vesting lock" that guarantees the balance cannot go below 200, and a "staking lock" that guarantees the balance cannot drop below 300, then we just have two guarantees of which the first is irrelevant.
// i.e. (balance >= 200 && balance >= 300) == (balance >= 300)
// ""
const floating = freeBalance.sub(lockedBalance);
const extraReceived = isVesting ? freeBalance.sub(vestingTotal) : new BN(0);
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), isVesting && floating.gt(vestedBalance) ? vestedBalance.add(extraReceived) : floating));
return { return {
accountId, accountId,
@@ -67,6 +61,8 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
lockedBreakdown, lockedBreakdown,
reservedBalance, reservedBalance,
vestedBalance, vestedBalance,
vestedClaimable,
vestingLocked,
vestingTotal, vestingTotal,
votingBalance votingBalance
}; };
@@ -12,8 +12,8 @@ import { Option, u32 } from '@polkadot/types';
import { memo } from '../util'; import { memo } from '../util';
export function erasHistoric (api: ApiInterfaceRx): (withActive?: boolean) => Observable<EraIndex[]> { export function erasHistoric (api: ApiInterfaceRx): (withActive: boolean) => Observable<EraIndex[]> {
return memo((withActive?: boolean): Observable<EraIndex[]> => return memo((withActive: boolean): Observable<EraIndex[]> =>
api.query.staking?.activeEra api.query.staking?.activeEra
? api.queryMulti<[Option<ActiveEraInfo>, u32]>([ ? api.queryMulti<[Option<ActiveEraInfo>, u32]>([
api.query.staking.activeEra, api.query.staking.activeEra,
@@ -199,14 +199,18 @@ export function stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | st
); );
} }
export function stakerRewardsMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> { export function stakerRewardsMultiEras (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> {
return memo((accountIds: (Uint8Array | string)[], withActive = false): Observable<DeriveStakerReward[][]> => return memo((accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> =>
accountIds.length accountIds.length && eras.length
? api.derive.staking.erasHistoric(withActive).pipe( ? combineLatest(accountIds.map((acc) => api.derive.staking._stakerRewards(acc, eras, false)))
switchMap((eras) =>
combineLatest(accountIds.map((acc) => api.derive.staking._stakerRewards(acc, eras, withActive)))
)
)
: of([]) : of([])
); );
} }
export function stakerRewardsMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> {
return memo((accountIds: (Uint8Array | string)[], withActive = false): Observable<DeriveStakerReward[][]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking.stakerRewardsMultiEras(accountIds, eras))
)
);
}
+2
View File
@@ -31,6 +31,8 @@ export interface DeriveBalancesAll extends DeriveBalancesAccount {
availableBalance: Balance; availableBalance: Balance;
votingBalance: Balance; votingBalance: Balance;
vestedBalance: Balance; vestedBalance: Balance;
vestedClaimable: Balance;
vestingLocked: Balance;
vestingTotal: Balance; vestingTotal: Balance;
} }
+13 -13
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api", "name": "@polkadot/api",
"version": "1.21.1", "version": "1.23.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC", "description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -26,21 +26,21 @@
}, },
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/api-derive": "1.21.1", "@polkadot/api-derive": "1.23.1",
"@polkadot/keyring": "^2.15.1", "@polkadot/keyring": "^2.17.1",
"@polkadot/metadata": "1.21.1", "@polkadot/metadata": "1.23.1",
"@polkadot/rpc-core": "1.21.1", "@polkadot/rpc-core": "1.23.1",
"@polkadot/rpc-provider": "1.21.1", "@polkadot/rpc-provider": "1.23.1",
"@polkadot/types": "1.21.1", "@polkadot/types": "1.23.1",
"@polkadot/types-known": "1.21.1", "@polkadot/types-known": "1.23.1",
"@polkadot/util": "^2.15.1", "@polkadot/util": "^2.17.1",
"@polkadot/util-crypto": "^2.15.1", "@polkadot/util-crypto": "^2.17.1",
"bn.js": "^5.1.2", "bn.js": "^5.1.2",
"eventemitter3": "^4.0.4", "eventemitter3": "^4.0.4",
"rxjs": "^6.5.5" "rxjs": "^6.6.0"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^2.15.1" "@polkadot/keyring": "^2.17.1"
} }
} }
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/metadata", "name": "@polkadot/metadata",
"version": "1.21.1", "version": "1.23.1",
"description": "Helpers to extract information from runtime metadata", "description": "Helpers to extract information from runtime metadata",
"main": "index.js", "main": "index.js",
"publishConfig": { "publishConfig": {
@@ -26,14 +26,14 @@
}, },
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/types": "1.21.1", "@polkadot/types": "1.23.1",
"@polkadot/types-known": "1.21.1", "@polkadot/types-known": "1.23.1",
"@polkadot/util": "^2.15.1", "@polkadot/util": "^2.17.1",
"@polkadot/util-crypto": "^2.15.1", "@polkadot/util-crypto": "^2.17.1",
"bn.js": "^5.1.2" "bn.js": "^5.1.2"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^2.15.1" "@polkadot/keyring": "^2.17.1"
} }
} }
+8 -8
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/rpc-core", "name": "@polkadot/rpc-core",
"version": "1.21.1", "version": "1.23.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface", "description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -26,15 +26,15 @@
}, },
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/metadata": "1.21.1", "@polkadot/metadata": "1.23.1",
"@polkadot/rpc-provider": "1.21.1", "@polkadot/rpc-provider": "1.23.1",
"@polkadot/types": "1.21.1", "@polkadot/types": "1.23.1",
"@polkadot/util": "^2.15.1", "@polkadot/util": "^2.17.1",
"memoizee": "^0.4.14", "memoizee": "^0.4.14",
"rxjs": "^6.5.5" "rxjs": "^6.6.0"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^2.15.1" "@polkadot/keyring": "^2.17.1"
} }
} }
+8 -8
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/rpc-provider", "name": "@polkadot/rpc-provider",
"version": "1.21.1", "version": "1.23.1",
"description": "Transport providers for the API", "description": "Transport providers for the API",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -26,19 +26,19 @@
}, },
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/metadata": "1.21.1", "@polkadot/metadata": "1.23.1",
"@polkadot/types": "1.21.1", "@polkadot/types": "1.23.1",
"@polkadot/util": "^2.15.1", "@polkadot/util": "^2.17.1",
"@polkadot/util-crypto": "^2.15.1", "@polkadot/util-crypto": "^2.17.1",
"bn.js": "^5.1.2", "bn.js": "^5.1.2",
"eventemitter3": "^4.0.4", "eventemitter3": "^4.0.4",
"isomorphic-fetch": "^2.2.1", "isomorphic-fetch": "^2.2.1",
"websocket": "^1.0.31" "websocket": "^1.0.31"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^2.15.1", "@polkadot/keyring": "^2.17.1",
"mock-socket": "^9.0.3", "mock-socket": "^9.0.3",
"nock": "^12.0.3" "nock": "^13.0.2"
} }
} }
+10 -10
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/typegen", "name": "@polkadot/typegen",
"version": "1.21.1", "version": "1.23.1",
"description": "Type generation scripts", "description": "Type generation scripts",
"main": "index.js", "main": "index.js",
"bin": { "bin": {
@@ -33,17 +33,17 @@
}, },
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
"dependencies": { "dependencies": {
"@babel/core": "^7.10.3", "@babel/core": "^7.10.4",
"@babel/register": "^7.10.3", "@babel/register": "^7.10.4",
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/api": "1.21.1", "@polkadot/api": "1.23.1",
"@polkadot/metadata": "1.21.1", "@polkadot/metadata": "1.23.1",
"@polkadot/rpc-provider": "1.21.1", "@polkadot/rpc-provider": "1.23.1",
"@polkadot/types": "1.21.1", "@polkadot/types": "1.23.1",
"@polkadot/util": "^2.15.1", "@polkadot/util": "^2.17.1",
"handlebars": "^4.7.6", "handlebars": "^4.7.6",
"websocket": "^1.0.31", "websocket": "^1.0.31",
"yargs": "^15.3.1" "yargs": "^15.4.0"
}, },
"devDependencies": { "devDependencies": {
"@types/websocket": "^1.0.0", "@types/websocket": "^1.0.0",
+4 -4
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/types-known", "name": "@polkadot/types-known",
"version": "1.21.1", "version": "1.23.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface", "description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -26,9 +26,9 @@
}, },
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/types": "1.21.1", "@polkadot/types": "1.23.1",
"@polkadot/util": "^2.15.1", "@polkadot/util": "^2.17.1",
"bn.js": "^5.1.2" "bn.js": "^5.1.2"
}, },
"devDependencies": { "devDependencies": {
+27 -13
View File
@@ -4,6 +4,15 @@
import { OverrideVersionedType } from '@polkadot/types/types'; import { OverrideVersionedType } from '@polkadot/types/types';
const sharedTypes = {
Address: 'AccountId',
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
ProxyType: {
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement']
}
};
const versioned: OverrideVersionedType[] = [ const versioned: OverrideVersionedType[] = [
{ {
// 1020 is first CC3 // 1020 is first CC3
@@ -16,6 +25,7 @@ const versioned: OverrideVersionedType[] = [
Keys: 'SessionKeys5', Keys: 'SessionKeys5',
LookupSource: 'Address', LookupSource: 'Address',
Multiplier: 'Fixed64', Multiplier: 'Fixed64',
OpenTip: 'OpenTipTo225',
ReferendumInfo: 'ReferendumInfoTo239', ReferendumInfo: 'ReferendumInfoTo239',
SlashingSpans: 'SlashingSpansTo204', SlashingSpans: 'SlashingSpansTo204',
StakingLedger: 'StakingLedgerTo223', StakingLedger: 'StakingLedgerTo223',
@@ -32,6 +42,7 @@ const versioned: OverrideVersionedType[] = [
Keys: 'SessionKeys5', Keys: 'SessionKeys5',
LookupSource: 'Address', LookupSource: 'Address',
Multiplier: 'Fixed64', Multiplier: 'Fixed64',
OpenTip: 'OpenTipTo225',
ReferendumInfo: 'ReferendumInfoTo239', ReferendumInfo: 'ReferendumInfoTo239',
SlashingSpans: 'SlashingSpansTo204', SlashingSpans: 'SlashingSpansTo204',
StakingLedger: 'StakingLedgerTo223', StakingLedger: 'StakingLedgerTo223',
@@ -49,6 +60,7 @@ const versioned: OverrideVersionedType[] = [
Keys: 'SessionKeys5', Keys: 'SessionKeys5',
LookupSource: 'Address', LookupSource: 'Address',
Multiplier: 'Fixed64', Multiplier: 'Fixed64',
OpenTip: 'OpenTipTo225',
ReferendumInfo: 'ReferendumInfoTo239', ReferendumInfo: 'ReferendumInfoTo239',
StakingLedger: 'StakingLedgerTo223', StakingLedger: 'StakingLedgerTo223',
Votes: 'VotesTo230', Votes: 'VotesTo230',
@@ -59,11 +71,10 @@ const versioned: OverrideVersionedType[] = [
minmax: [1046, 1054], minmax: [1046, 1054],
types: { types: {
// Indices optional, not in transaction // Indices optional, not in transaction
Address: 'AccountId', ...sharedTypes,
DispatchInfo: 'DispatchInfoTo244', DispatchInfo: 'DispatchInfoTo244',
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
Multiplier: 'Fixed64', Multiplier: 'Fixed64',
OpenTip: 'OpenTipTo225',
ReferendumInfo: 'ReferendumInfoTo239', ReferendumInfo: 'ReferendumInfoTo239',
StakingLedger: 'StakingLedgerTo240', StakingLedger: 'StakingLedgerTo240',
Weight: 'u32' Weight: 'u32'
@@ -72,11 +83,10 @@ const versioned: OverrideVersionedType[] = [
{ {
minmax: [1055, 1056], minmax: [1055, 1056],
types: { types: {
Address: 'AccountId', ...sharedTypes,
DispatchInfo: 'DispatchInfoTo244', DispatchInfo: 'DispatchInfoTo244',
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
Multiplier: 'Fixed64', Multiplier: 'Fixed64',
OpenTip: 'OpenTipTo225',
StakingLedger: 'StakingLedgerTo240', StakingLedger: 'StakingLedgerTo240',
Weight: 'u32' Weight: 'u32'
} }
@@ -84,18 +94,22 @@ const versioned: OverrideVersionedType[] = [
{ {
minmax: [1057, 1061], minmax: [1057, 1061],
types: { types: {
Address: 'AccountId', ...sharedTypes,
DispatchInfo: 'DispatchInfoTo244', DispatchInfo: 'DispatchInfoTo244',
Keys: 'SessionKeys5', OpenTip: 'OpenTipTo225'
LookupSource: 'AccountId'
} }
}, },
{ {
minmax: [1062, undefined], minmax: [1062, 2012],
types: { types: {
Address: 'AccountId', ...sharedTypes,
Keys: 'SessionKeys5', OpenTip: 'OpenTipTo225'
LookupSource: 'AccountId' }
},
{
minmax: [2013, undefined],
types: {
...sharedTypes
} }
} }
]; ];
+14 -11
View File
@@ -4,25 +4,28 @@
import { OverrideVersionedType } from '@polkadot/types/types'; import { OverrideVersionedType } from '@polkadot/types/types';
const sharedTypes = {
Address: 'AccountId',
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
ProxyType: {
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'SudoBalances', 'IdentityJudgement']
}
};
// these are override types for Polkadot // these are override types for Polkadot
const versioned: OverrideVersionedType[] = [ const versioned: OverrideVersionedType[] = [
{ {
minmax: [0, 3], minmax: [0, 12],
types: { types: {
Address: 'AccountId', ...sharedTypes,
Keys: 'SessionKeys5', OpenTip: 'OpenTipTo225'
LookupSource: 'AccountId'
} }
}, },
{ {
minmax: [4, undefined], minmax: [13, undefined],
types: { types: {
Address: 'AccountId', ...sharedTypes
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
ProxyType: {
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'SudoBalances']
}
} }
} }
]; ];
+16 -14
View File
@@ -4,34 +4,36 @@
import { OverrideVersionedType } from '@polkadot/types/types'; import { OverrideVersionedType } from '@polkadot/types/types';
const sharedTypes = {
Address: 'AccountId',
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
ProxyType: {
_enum: ['Any', 'NonTransfer', 'Staking', 'SudoBalances', 'IdentityJudgement']
}
};
const versioned: OverrideVersionedType[] = [ const versioned: OverrideVersionedType[] = [
{ {
minmax: [1, 2], minmax: [1, 2],
types: { types: {
Address: 'AccountId', ...sharedTypes,
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
Multiplier: 'Fixed64', Multiplier: 'Fixed64',
OpenTip: 'OpenTipTo225',
Weight: 'u32' Weight: 'u32'
} }
}, },
{ {
minmax: [3, 19], minmax: [3, 22],
types: { types: {
Address: 'AccountId', ...sharedTypes,
Keys: 'SessionKeys5', OpenTip: 'OpenTipTo225'
LookupSource: 'AccountId'
} }
}, },
{ {
minmax: [20, undefined], minmax: [23, undefined],
types: { types: {
Address: 'AccountId', ...sharedTypes
Keys: 'SessionKeys5',
LookupSource: 'AccountId',
ProxyType: {
_enum: ['Any', 'NonTransfer', 'Staking', 'SudoBalances']
}
} }
} }
]; ];
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/types", "name": "@polkadot/types",
"version": "1.21.1", "version": "1.23.1",
"description": "Implementation of the Parity codec", "description": "Implementation of the Parity codec",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -26,17 +26,17 @@
}, },
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.10.3", "@babel/runtime": "^7.10.4",
"@polkadot/metadata": "1.21.1", "@polkadot/metadata": "1.23.1",
"@polkadot/util": "^2.15.1", "@polkadot/util": "^2.17.1",
"@polkadot/util-crypto": "^2.15.1", "@polkadot/util-crypto": "^2.17.1",
"@types/bn.js": "^4.11.6", "@types/bn.js": "^4.11.6",
"bn.js": "^5.1.2", "bn.js": "^5.1.2",
"memoizee": "^0.4.14", "memoizee": "^0.4.14",
"rxjs": "^6.5.5" "rxjs": "^6.6.0"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^2.15.1", "@polkadot/keyring": "^2.17.1",
"@types/memoizee": "^0.4.4" "@types/memoizee": "^0.4.4"
} }
} }
+11 -5
View File
@@ -31,7 +31,7 @@ import { AbridgedCandidateReceipt, AttestedCandidate, AuctionIndex, Bidder, Cand
import { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment'; import { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery'; import { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import { RpcMethods } from '@polkadot/types/interfaces/rpc'; import { RpcMethods } from '@polkadot/types/interfaces/rpc';
import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, ExtrinsicsWeight, Fixed128, Fixed64, H160, H256, H512, Hash, Header, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, ModuleId, Moment, Origin, Pays, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, ProxyType, Releases, RuntimeDbWeight, Seal, SealV0, SignedBlock, StorageData, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime'; import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, ExtrinsicsWeight, Fixed128, Fixed64, H160, H256, H512, Hash, Header, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, ModuleId, Moment, OpaqueCall, Origin, Pays, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, ProxyType, Releases, RuntimeDbWeight, Seal, SealV0, SignedBlock, StorageData, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';
import { Period, Priority, SchedulePeriod, SchedulePriority, Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler'; import { Period, Priority, SchedulePeriod, SchedulePriority, Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import { FullIdentification, IdentificationTuple, Keys, MembershipProof, SessionIndex, SessionKeys1, SessionKeys2, SessionKeys3, SessionKeys4, SessionKeys5, SessionKeys6, ValidatorCount } from '@polkadot/types/interfaces/session'; import { FullIdentification, IdentificationTuple, Keys, MembershipProof, SessionIndex, SessionKeys1, SessionKeys2, SessionKeys3, SessionKeys4, SessionKeys5, SessionKeys6, ValidatorCount } from '@polkadot/types/interfaces/session';
import { Bid, BidKind, SocietyJudgement, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society'; import { Bid, BidKind, SocietyJudgement, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
@@ -39,7 +39,7 @@ import { ActiveEraInfo, CompactAssignments, CompactScore, ElectionCompute, Elect
import { ApiId, KeyValueOption, ReadProof, RuntimeVersion, RuntimeVersionApi, StorageChangeSet } from '@polkadot/types/interfaces/state'; import { ApiId, KeyValueOption, ReadProof, RuntimeVersion, RuntimeVersionApi, StorageChangeSet } from '@polkadot/types/interfaces/state';
import { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support'; import { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
import { AccountInfo, ApplyExtrinsicResult, ChainProperties, ChainType, DigestOf, DispatchClass, DispatchError, DispatchErrorModule, DispatchErrorTo198, DispatchInfo, DispatchInfoTo190, DispatchInfoTo244, DispatchOutcome, DispatchResult, DispatchResultOf, DispatchResultTo198, Event, EventId, EventIndex, EventRecord, EventRecordTo76, Health, InvalidTransaction, Key, LastRuntimeUpgradeInfo, NetworkState, NetworkStatePeerset, NetworkStatePeersetInfo, NodeRole, NotConnectedPeer, Peer, PeerEndpoint, PeerEndpointAddr, PeerInfo, PeerPing, Phase, RefCount, TransactionValidityError, UnknownTransaction } from '@polkadot/types/interfaces/system'; import { AccountInfo, ApplyExtrinsicResult, ChainProperties, ChainType, DigestOf, DispatchClass, DispatchError, DispatchErrorModule, DispatchErrorTo198, DispatchInfo, DispatchInfoTo190, DispatchInfoTo244, DispatchOutcome, DispatchResult, DispatchResultOf, DispatchResultTo198, Event, EventId, EventIndex, EventRecord, EventRecordTo76, Health, InvalidTransaction, Key, LastRuntimeUpgradeInfo, NetworkState, NetworkStatePeerset, NetworkStatePeersetInfo, NodeRole, NotConnectedPeer, Peer, PeerEndpoint, PeerEndpointAddr, PeerInfo, PeerPing, Phase, RefCount, TransactionValidityError, UnknownTransaction } from '@polkadot/types/interfaces/system';
import { OpenTip, OpenTipFinder, OpenTipTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury'; import { OpenTip, OpenTipFinderTo225, OpenTipTip, OpenTipTo225, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import { Multiplier } from '@polkadot/types/interfaces/txpayment'; import { Multiplier } from '@polkadot/types/interfaces/txpayment';
import { CallHash, Multisig, Timepoint } from '@polkadot/types/interfaces/utility'; import { CallHash, Multisig, Timepoint } from '@polkadot/types/interfaces/utility';
import { VestingInfo } from '@polkadot/types/interfaces/vesting'; import { VestingInfo } from '@polkadot/types/interfaces/vesting';
@@ -225,6 +225,9 @@ declare module '@polkadot/types/types/registry' {
'Compact<Moment>': Compact<Moment>; 'Compact<Moment>': Compact<Moment>;
'Option<Moment>': Option<Moment>; 'Option<Moment>': Option<Moment>;
'Vec<Moment>': Vec<Moment>; 'Vec<Moment>': Vec<Moment>;
OpaqueCall: OpaqueCall;
'Option<OpaqueCall>': Option<OpaqueCall>;
'Vec<OpaqueCall>': Vec<OpaqueCall>;
Origin: Origin; Origin: Origin;
'Option<Origin>': Option<Origin>; 'Option<Origin>': Option<Origin>;
'Vec<Origin>': Vec<Origin>; 'Vec<Origin>': Vec<Origin>;
@@ -1112,9 +1115,12 @@ declare module '@polkadot/types/types/registry' {
OpenTip: OpenTip; OpenTip: OpenTip;
'Option<OpenTip>': Option<OpenTip>; 'Option<OpenTip>': Option<OpenTip>;
'Vec<OpenTip>': Vec<OpenTip>; 'Vec<OpenTip>': Vec<OpenTip>;
OpenTipFinder: OpenTipFinder; OpenTipTo225: OpenTipTo225;
'Option<OpenTipFinder>': Option<OpenTipFinder>; 'Option<OpenTipTo225>': Option<OpenTipTo225>;
'Vec<OpenTipFinder>': Vec<OpenTipFinder>; 'Vec<OpenTipTo225>': Vec<OpenTipTo225>;
OpenTipFinderTo225: OpenTipFinderTo225;
'Option<OpenTipFinderTo225>': Option<OpenTipFinderTo225>;
'Vec<OpenTipFinderTo225>': Vec<OpenTipFinderTo225>;
OpenTipTip: OpenTipTip; OpenTipTip: OpenTipTip;
'Option<OpenTipTip>': Option<OpenTipTip>; 'Option<OpenTipTip>': Option<OpenTipTip>;
'Vec<OpenTipTip>': Vec<OpenTipTip>; 'Vec<OpenTipTip>': Vec<OpenTipTip>;
+3 -2
View File
@@ -6,7 +6,7 @@ import { H256 } from '../interfaces/runtime';
import { AnyNumber, Codec, Registry } from '../types'; import { AnyNumber, Codec, Registry } from '../types';
import BN from 'bn.js'; import BN from 'bn.js';
import { assert, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isHex, isString, isU8a, u8aToBn } from '@polkadot/util'; import { BN_ZERO, assert, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isHex, isString, isU8a, u8aToBn } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto'; import { blake2AsU8a } from '@polkadot/util-crypto';
import Raw from './Raw'; import Raw from './Raw';
@@ -77,6 +77,7 @@ export default abstract class AbstractInt extends BN implements Codec {
this.#isHexJson = isHexJson; this.#isHexJson = isHexJson;
this.#isSigned = isSigned; this.#isSigned = isSigned;
assert(isSigned || this.gte(BN_ZERO), `${this.toRawType()}: Negative number passed to unsigned type`);
assert(super.bitLength() <= bitLength, `${this.toRawType()}: Input too large. Found input with ${super.bitLength()} bits, expected ${bitLength}`); assert(super.bitLength() <= bitLength, `${this.toRawType()}: Input too large. Found input with ${super.bitLength()} bits, expected ${bitLength}`);
} }
@@ -161,7 +162,7 @@ export default abstract class AbstractInt extends BN implements Codec {
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
*/ */
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
public toHuman (isExpanded?: boolean): any { public toHuman (isExpanded?: boolean): string {
// FIXME we need proper expansion here // FIXME we need proper expansion here
return this instanceof this.registry.createClass('Balance') return this instanceof this.registry.createClass('Balance')
? this.isMax() ? this.isMax()
+1 -1
View File
@@ -171,7 +171,7 @@ export default class BTreeSet<V extends Codec = Codec> extends Set<V> implements
* @description Returns the base runtime type name for this instance * @description Returns the base runtime type name for this instance
*/ */
public toRawType (): string { public toRawType (): string {
return `BTreeSet<${new this.#ValClass(this.registry).toRawType()}>`; return `BTreeSet<${this.registry.getClassName(this.#ValClass) || new this.#ValClass(this.registry).toRawType()}>`;
} }
/** /**
+72 -15
View File
@@ -2,15 +2,17 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import { AnyNumber, Codec, Constructor, ICompact, InterfaceTypes, Registry } from '../types'; import { H256 } from '@polkadot/types/interfaces';
import { AnyJson, AnyNumber, Codec, Constructor, ICompact, InterfaceTypes, Registry } from '../types';
import BN from 'bn.js'; import BN from 'bn.js';
import { compactAddLength, compactFromU8a, compactStripLength, compactToU8a, isBigInt, isBn, isNumber, isString } from '@polkadot/util'; import { compactAddLength, compactFromU8a, compactStripLength, compactToU8a, isBigInt, isBn, isNumber, isString } from '@polkadot/util';
import { DEFAULT_BITLENGTH } from '@polkadot/util/compact/defaults'; import { DEFAULT_BITLENGTH } from '@polkadot/util/compact/defaults';
import { blake2AsU8a } from '@polkadot/util-crypto';
import typeToConstructor from './utils/typeToConstructor'; import typeToConstructor from './utils/typeToConstructor';
import { UIntBitLength } from './AbstractInt'; import { UIntBitLength } from './AbstractInt';
import Base from './Base'; import Raw from './Raw';
export interface CompactEncodable extends Codec { export interface CompactEncodable extends Codec {
bitLength (): number; bitLength (): number;
@@ -26,11 +28,17 @@ export interface CompactEncodable extends Codec {
* used by other types to add length-prefixed encoding, or in the case of wrapped types, taking * used by other types to add length-prefixed encoding, or in the case of wrapped types, taking
* a number and making the compact representation thereof * a number and making the compact representation thereof
*/ */
export default class Compact<T extends CompactEncodable> extends Base<T> implements ICompact<T> { export default class Compact<T extends CompactEncodable> implements ICompact<T> {
public readonly registry: Registry;
readonly #Type: Constructor<T>;
readonly #raw: T;
constructor (registry: Registry, Type: Constructor<T> | keyof InterfaceTypes, value: Compact<T> | AnyNumber = 0) { constructor (registry: Registry, Type: Constructor<T> | keyof InterfaceTypes, value: Compact<T> | AnyNumber = 0) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment this.registry = registry;
// @ts-ignore this.#Type = typeToConstructor(registry, Type);
super(registry, Compact.decodeCompact<T>(registry, typeToConstructor(registry, Type), value)); this.#raw = Compact.decodeCompact<T>(registry, this.#Type, value) as T;
} }
public static with<T extends CompactEncodable> (Type: Constructor<T> | keyof InterfaceTypes): Constructor<Compact<T>> { public static with<T extends CompactEncodable> (Type: Constructor<T> | keyof InterfaceTypes): Constructor<Compact<T>> {
@@ -61,7 +69,7 @@ export default class Compact<T extends CompactEncodable> extends Base<T> impleme
/** @internal */ /** @internal */
public static decodeCompact<T extends CompactEncodable> (registry: Registry, Type: Constructor<T>, value: Compact<T> | AnyNumber): CompactEncodable { public static decodeCompact<T extends CompactEncodable> (registry: Registry, Type: Constructor<T>, value: Compact<T> | AnyNumber): CompactEncodable {
if (value instanceof Compact) { if (value instanceof Compact) {
return new Type(registry, value._raw); return new Type(registry, value.#raw);
} else if (isString(value) || isNumber(value) || isBn(value) || isBigInt(value)) { } else if (isString(value) || isNumber(value) || isBn(value) || isBigInt(value)) {
return new Type(registry, value); return new Type(registry, value);
} }
@@ -71,20 +79,41 @@ export default class Compact<T extends CompactEncodable> extends Base<T> impleme
return new Type(registry, _value); return new Type(registry, _value);
} }
/**
* @description The length of the value when encoded as a Uint8Array
*/
public get encodedLength (): number {
return this.toU8a().length;
}
/**
* @description returns a hash of the contents
*/
public get hash (): H256 {
return new Raw(this.registry, blake2AsU8a(this.toU8a(), 256));
}
/**
* @description Checks if the value is an empty value
*/
public get isEmpty (): boolean {
return this.#raw.isEmpty;
}
/** /**
* @description Returns the number of bits in the value * @description Returns the number of bits in the value
*/ */
public bitLength (): number { public bitLength (): number {
return this._raw.bitLength(); return this.#raw.bitLength();
} }
/** /**
* @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
*/ */
public eq (other?: unknown): boolean { public eq (other?: unknown): boolean {
return this._raw.eq( return this.#raw.eq(
other instanceof Compact other instanceof Compact
? other._raw ? other.#raw
: other : other
); );
} }
@@ -93,21 +122,49 @@ export default class Compact<T extends CompactEncodable> extends Base<T> impleme
* @description Returns the BN representation of the number * @description Returns the BN representation of the number
*/ */
public toBn (): BN { public toBn (): BN {
return this._raw.toBn(); return this.#raw.toBn();
}
/**
* @description Returns a hex string representation of the value. isLe returns a LE (number-only) representation
*/
public toHex (isLe?: boolean): string {
return this.#raw.toHex(isLe);
}
/**
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
*/
public toHuman (isExtended?: boolean): AnyJson {
return this.#raw.toHuman(isExtended);
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
public toJSON (): AnyJson {
return this.#raw.toJSON();
} }
/** /**
* @description Returns the number representation for the value * @description Returns the number representation for the value
*/ */
public toNumber (): number { public toNumber (): number {
return this._raw.toNumber(); return this.#raw.toNumber();
} }
/** /**
* @description Returns the base runtime type name for this instance * @description Returns the base runtime type name for this instance
*/ */
public toRawType (): string { public toRawType (): string {
return `Compact<${this._raw.toRawType()}>`; return `Compact<${this.registry.getClassName(this.#Type) || this.#raw.toRawType()}>`;
}
/**
* @description Returns the string representation of the value
*/
public toString (): string {
return this.#raw.toString();
} }
/** /**
@@ -116,13 +173,13 @@ export default class Compact<T extends CompactEncodable> extends Base<T> impleme
*/ */
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
public toU8a (isBare?: boolean): Uint8Array { public toU8a (isBare?: boolean): Uint8Array {
return Compact.encodeU8a(this._raw.toBn()); return Compact.encodeU8a(this.#raw.toBn());
} }
/** /**
* @description Returns the embedded [[UInt]] or [[Moment]] value * @description Returns the embedded [[UInt]] or [[Moment]] value
*/ */
public unwrap (): T { public unwrap (): T {
return this._raw; return this.#raw;
} }
} }
+51 -31
View File
@@ -2,13 +2,15 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import { H256 } from '@polkadot/types/interfaces';
import { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types'; import { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types';
import { assert, hexToU8a, isHex, isNumber, isObject, isString, isU8a, isUndefined, stringCamelCase, stringUpperFirst, u8aConcat, u8aToHex } from '@polkadot/util'; import { assert, hexToU8a, isHex, isNumber, isObject, isString, isU8a, isUndefined, stringCamelCase, stringUpperFirst, u8aConcat, u8aToHex } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
import Null from '../primitive/Null'; import Null from '../primitive/Null';
import { mapToTypeMap } from './utils'; import { mapToTypeMap } from './utils';
import Base from './Base'; import Raw from './Raw';
import Struct from './Struct'; import Struct from './Struct';
// export interface, this is used in Enum.with, so required as public by TS // export interface, this is used in Enum.with, so required as public by TS
@@ -114,25 +116,29 @@ function decodeEnum (registry: Registry, def: TypesDef, value?: any, index?: num
// TODO: // TODO:
// - As per Enum, actually use TS enum // - As per Enum, actually use TS enum
// - It should rather probably extend Enum instead of copying code // - It should rather probably extend Enum instead of copying code
export default class Enum extends Base<Codec> { export default class Enum implements Codec {
private _def: TypesDef; public readonly registry: Registry;
private _index: number; readonly #def: TypesDef;
private _indexes: number[]; readonly #index: number;
private _isBasic: boolean; readonly #indexes: number[];
readonly #isBasic: boolean;
readonly #raw: Codec;
constructor (registry: Registry, def: Record<string, keyof InterfaceTypes | Constructor> | string[], value?: unknown, index?: number) { constructor (registry: Registry, def: Record<string, keyof InterfaceTypes | Constructor> | string[], value?: unknown, index?: number) {
const defInfo = extractDef(registry, def); const defInfo = extractDef(registry, def);
const decoded = decodeEnum(registry, defInfo.def, value, index); const decoded = decodeEnum(registry, defInfo.def, value, index);
super(registry, decoded.value); this.registry = registry;
this.#def = defInfo.def;
this._def = defInfo.def; this.#isBasic = defInfo.isBasic;
this._isBasic = defInfo.isBasic; this.#indexes = Object.keys(defInfo.def).map((_, index): number => index);
this._indexes = Object.keys(defInfo.def).map((_, index): number => index); this.#index = this.#indexes.indexOf(decoded.index) || 0;
this._index = this._indexes.indexOf(decoded.index) || 0; this.#raw = decoded.value;
} }
public static with (Types: Record<string, keyof InterfaceTypes | Constructor> | string[]): EnumConstructor<Enum> { public static with (Types: Record<string, keyof InterfaceTypes | Constructor> | string[]): EnumConstructor<Enum> {
@@ -140,7 +146,7 @@ export default class Enum extends Base<Codec> {
constructor (registry: Registry, value?: unknown, index?: number) { constructor (registry: Registry, value?: unknown, index?: number) {
super(registry, Types, value, index); super(registry, Types, value, index);
Object.keys(this._def).forEach((_key): void => { Object.keys(this.#def).forEach((_key): void => {
const name = stringUpperFirst(stringCamelCase(_key.replace(' ', '_'))); const name = stringUpperFirst(stringCamelCase(_key.replace(' ', '_')));
const askey = `as${name}`; const askey = `as${name}`;
const iskey = `is${name}`; const iskey = `is${name}`;
@@ -175,21 +181,35 @@ export default class Enum extends Base<Codec> {
* @description The length of the value when encoded as a Uint8Array * @description The length of the value when encoded as a Uint8Array
*/ */
public get encodedLength (): number { public get encodedLength (): number {
return 1 + this._raw.encodedLength; return 1 + this.#raw.encodedLength;
}
/**
* @description returns a hash of the contents
*/
public get hash (): H256 {
return new Raw(this.registry, blake2AsU8a(this.toU8a(), 256));
} }
/** /**
* @description The index of the metadata value * @description The index of the metadata value
*/ */
public get index (): number { public get index (): number {
return this._index; return this.#index;
} }
/** /**
* @description true if this is a basic enum (no values) * @description true if this is a basic enum (no values)
*/ */
public get isBasic (): boolean { public get isBasic (): boolean {
return this._isBasic; return this.#isBasic;
}
/**
* @description Checks if the value is an empty value
*/
public get isEmpty (): boolean {
return this.#raw.isEmpty;
} }
/** /**
@@ -203,35 +223,35 @@ export default class Enum extends Base<Codec> {
* @description Checks if the Enum points to a [[Null]] type (deprecated, use isNone) * @description Checks if the Enum points to a [[Null]] type (deprecated, use isNone)
*/ */
public get isNull (): boolean { public get isNull (): boolean {
return this._raw instanceof Null; return this.#raw instanceof Null;
} }
/** /**
* @description The available keys for this enum * @description The available keys for this enum
*/ */
public get defEntries (): string[] { public get defEntries (): string[] {
return Object.keys(this._def); return Object.keys(this.#def);
} }
/** /**
* @description The available keys for this enum * @description The available keys for this enum
*/ */
public get defKeys (): string[] { public get defKeys (): string[] {
return Object.keys(this._def); return Object.keys(this.#def);
} }
/** /**
* @description The name of the type this enum value represents * @description The name of the type this enum value represents
*/ */
public get type (): string { public get type (): string {
return this.defKeys[this._index]; return this.defKeys[this.#index];
} }
/** /**
* @description The value of the enum * @description The value of the enum
*/ */
public get value (): Codec { public get value (): Codec {
return this._raw; return this.#raw;
} }
/** /**
@@ -241,7 +261,7 @@ export default class Enum extends Base<Codec> {
// cater for the case where we only pass the enum index // cater for the case where we only pass the enum index
if (isNumber(other)) { if (isNumber(other)) {
return this.toNumber() === other; return this.toNumber() === other;
} else if (this._isBasic && isString(other)) { } else if (this.#isBasic && isString(other)) {
return this.type === other; return this.type === other;
} else if (isU8a(other)) { } else if (isU8a(other)) {
return !this.toU8a().some((entry, index): boolean => entry !== other[index]); return !this.toU8a().some((entry, index): boolean => entry !== other[index]);
@@ -268,34 +288,34 @@ export default class Enum extends Base<Codec> {
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
*/ */
public toHuman (isExtended?: boolean): AnyJson { public toHuman (isExtended?: boolean): AnyJson {
return this._isBasic return this.#isBasic
? this.type ? this.type
: { [this.type]: this._raw.toHuman(isExtended) }; : { [this.type]: this.#raw.toHuman(isExtended) };
} }
/** /**
* @description Converts the Object to JSON, typically used for RPC transfers * @description Converts the Object to JSON, typically used for RPC transfers
*/ */
public toJSON (): AnyJson { public toJSON (): AnyJson {
return this._isBasic return this.#isBasic
? this.type ? this.type
: { [this.type]: this._raw.toJSON() }; : { [this.type]: this.#raw.toJSON() };
} }
/** /**
* @description Returns the number representation for the value * @description Returns the number representation for the value
*/ */
public toNumber (): number { public toNumber (): number {
return this._index; return this.#index;
} }
/** /**
* @description Returns a raw struct representation of the enum types * @description Returns a raw struct representation of the enum types
*/ */
protected _toRawStruct (): string[] | Record<string, string> { protected _toRawStruct (): string[] | Record<string, string> {
return this._isBasic return this.#isBasic
? this.defKeys ? this.defKeys
: Struct.typesToMap(this.registry, this._def); : Struct.typesToMap(this.registry, this.#def);
} }
/** /**
@@ -319,11 +339,11 @@ export default class Enum extends Base<Codec> {
* @param isBare true when the value has none of the type-specific prefixes (internal) * @param isBare true when the value has none of the type-specific prefixes (internal)
*/ */
public toU8a (isBare?: boolean): Uint8Array { public toU8a (isBare?: boolean): Uint8Array {
const index = this._indexes[this._index]; const index = this.#indexes[this.#index];
return u8aConcat( return u8aConcat(
new Uint8Array([index]), new Uint8Array([index]),
this._raw.toU8a(isBare) this.#raw.toU8a(isBare)
); );
} }
} }
+1 -1
View File
@@ -180,7 +180,7 @@ export default class CodecMap<K extends Codec = Codec, V extends Codec = Codec>
* @description Returns the base runtime type name for this instance * @description Returns the base runtime type name for this instance
*/ */
public toRawType (): string { public toRawType (): string {
return `${this.#type}<${new this.#KeyClass(this.registry).toRawType()},${new this.#ValClass(this.registry).toRawType()}>`; return `${this.#type}<${this.registry.getClassName(this.#KeyClass) || new this.#KeyClass(this.registry).toRawType()},${this.registry.getClassName(this.#ValClass) || new this.#ValClass(this.registry).toRawType()}>`;
} }
/** /**
+46 -14
View File
@@ -2,13 +2,15 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import { Codec, Constructor, InterfaceTypes, Registry } from '../types'; import { H256 } from '@polkadot/types/interfaces';
import { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types';
import { isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util'; import { isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
import Null from '../primitive/Null'; import Null from '../primitive/Null';
import { typeToConstructor } from './utils'; import { typeToConstructor } from './utils';
import Base from './Base'; import Raw from './Raw';
/** @internal */ /** @internal */
function decodeOptionU8a (registry: Registry, Type: Constructor, value: Uint8Array): Codec { function decodeOptionU8a (registry: Registry, Type: Constructor, value: Uint8Array): Codec {
@@ -48,15 +50,17 @@ function decodeOption (registry: Registry, typeName: Constructor | keyof Interfa
* implements that - decodes, checks for optionality and wraps the required structure * implements that - decodes, checks for optionality and wraps the required structure
* with a value if/as required/found. * with a value if/as required/found.
*/ */
export default class Option<T extends Codec> extends Base<T> { export default class Option<T extends Codec> implements Codec {
public readonly registry: Registry;
readonly #Type: Constructor<T>; readonly #Type: Constructor<T>;
constructor (registry: Registry, typeName: Constructor<T> | keyof InterfaceTypes, value?: unknown) { readonly #raw: T;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
super(registry, decodeOption(registry, typeName, value));
constructor (registry: Registry, typeName: Constructor<T> | keyof InterfaceTypes, value?: unknown) {
this.registry = registry;
this.#Type = typeToConstructor(registry, typeName); this.#Type = typeToConstructor(registry, typeName);
this.#raw = decodeOption(registry, typeName, value) as T;
} }
public static with<O extends Codec> (Type: Constructor<O> | keyof InterfaceTypes): Constructor<Option<O>> { public static with<O extends Codec> (Type: Constructor<O> | keyof InterfaceTypes): Constructor<Option<O>> {
@@ -72,7 +76,14 @@ export default class Option<T extends Codec> extends Base<T> {
*/ */
public get encodedLength (): number { public get encodedLength (): number {
// boolean byte (has value, doesn't have) along with wrapped length // boolean byte (has value, doesn't have) along with wrapped length
return 1 + this._raw.encodedLength; return 1 + this.#raw.encodedLength;
}
/**
* @description returns a hash of the contents
*/
public get hash (): H256 {
return new Raw(this.registry, blake2AsU8a(this.toU8a(), 256));
} }
/** /**
@@ -86,7 +97,7 @@ export default class Option<T extends Codec> extends Base<T> {
* @description Checks if the Option has no value * @description Checks if the Option has no value
*/ */
public get isNone (): boolean { public get isNone (): boolean {
return this._raw instanceof Null; return this.#raw instanceof Null;
} }
/** /**
@@ -100,7 +111,7 @@ export default class Option<T extends Codec> extends Base<T> {
* @description The actual value for the Option * @description The actual value for the Option
*/ */
public get value (): Codec { public get value (): Codec {
return this._raw; return this.#raw;
} }
/** /**
@@ -125,31 +136,52 @@ export default class Option<T extends Codec> extends Base<T> {
: u8aToHex(this.toU8a().subarray(1)); : u8aToHex(this.toU8a().subarray(1));
} }
/**
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
*/
public toHuman (isExtended?: boolean): AnyJson {
return this.#raw.toHuman(isExtended);
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
public toJSON (): AnyJson {
return this.#raw.toJSON();
}
/** /**
* @description Returns the base runtime type name for this instance * @description Returns the base runtime type name for this instance
*/ */
public toRawType (isBare?: boolean): string { public toRawType (isBare?: boolean): string {
const wrapped = new this.#Type(this.registry).toRawType(); const wrapped = this.registry.getClassName(this.#Type) || new this.#Type(this.registry).toRawType();
return isBare return isBare
? wrapped ? wrapped
: `Option<${wrapped}>`; : `Option<${wrapped}>`;
} }
/**
* @description Returns the string representation of the value
*/
public toString (): string {
return this.#raw.toString();
}
/** /**
* @description Encodes the value as a Uint8Array as per the SCALE specifications * @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal) * @param isBare true when the value has none of the type-specific prefixes (internal)
*/ */
public toU8a (isBare?: boolean): Uint8Array { public toU8a (isBare?: boolean): Uint8Array {
if (isBare) { if (isBare) {
return this._raw.toU8a(true); return this.#raw.toU8a(true);
} }
const u8a = new Uint8Array(this.encodedLength); const u8a = new Uint8Array(this.encodedLength);
if (this.isSome) { if (this.isSome) {
u8a.set([1]); u8a.set([1]);
u8a.set(this._raw.toU8a(), 1); u8a.set(this.#raw.toU8a(), 1);
} }
return u8a; return u8a;
@@ -163,7 +195,7 @@ export default class Option<T extends Codec> extends Base<T> {
throw new Error('Option: unwrapping a None value'); throw new Error('Option: unwrapping a None value');
} }
return this._raw; return this.#raw;
} }
/** /**
+1 -1
View File
@@ -58,6 +58,6 @@ describe('Result', (): void => {
}); });
it('returns a proper raw typedef rom a built-in', (): void => { it('returns a proper raw typedef rom a built-in', (): void => {
expect(registry.createType('DispatchResult').toRawType()).toEqual('Result<(),{"_enum":{"Other":"Null","CannotLookup":"Null","BadOrigin":"Null","Module":"{\\"index\\":\\"u8\\",\\"error\\":\\"u8\\"}"}}>'); expect(registry.createType('DispatchResult').toRawType()).toEqual('Result<(),DispatchError>');
}); });
}); });
+1 -1
View File
@@ -50,7 +50,7 @@ export default class Result<O extends Codec, E extends Codec> extends Enum {
* @description Checks if the Result has no value * @description Checks if the Result has no value
*/ */
public get isEmpty (): boolean { public get isEmpty (): boolean {
return this.isOk && this._raw.isEmpty; return this.isOk && this.value.isEmpty;
} }
/** /**
+6 -7
View File
@@ -5,7 +5,6 @@
/* eslint-disable sort-keys */ /* eslint-disable sort-keys */
import { TypeRegistry } from '../create'; import { TypeRegistry } from '../create';
import AccountId from '../generic/AccountId';
import Text from '../primitive/Text'; import Text from '../primitive/Text';
import U32 from '../primitive/U32'; import U32 from '../primitive/U32';
import { CodecTo } from '../types'; import { CodecTo } from '../types';
@@ -221,20 +220,20 @@ describe('Struct', (): void => {
it('generates sane toRawType', (): void => { it('generates sane toRawType', (): void => {
expect( expect(
new Struct(registry, { new Struct(registry, {
accountId: AccountId, accountId: 'AccountId',
balanceCompact: registry.createClass('Compact<Balance>'), balanceCompact: registry.createClass('Compact<Balance>'),
blockNumber: registry.createClass('BlockNumber'), blockNumber: registry.createClass('BlockNumber'),
compactNumber: registry.createClass('Compact<BlockNumber>'), compactNumber: registry.createClass('Compact<BlockNumber>'),
optionNumber: registry.createClass('Option<BlockNumber>'), optionNumber: registry.createClass('Option<BlockNumber>'),
counter: U32, counter: U32,
vector: Vec.with(AccountId) vector: Vec.with('AccountId')
}).toRawType() }).toRawType()
).toEqual(JSON.stringify({ ).toEqual(JSON.stringify({
accountId: 'AccountId', accountId: 'AccountId',
balanceCompact: 'Compact<Balance>', // Override in Uint balanceCompact: 'Compact<Balance>', // Override in Uint
blockNumber: 'u32', blockNumber: 'BlockNumber',
compactNumber: 'Compact<u32>', compactNumber: 'Compact<BlockNumber>',
optionNumber: 'Option<u32>', optionNumber: 'Option<BlockNumber>',
counter: 'u32', counter: 'u32',
vector: 'Vec<AccountId>' vector: 'Vec<AccountId>'
})); }));
@@ -242,7 +241,7 @@ describe('Struct', (): void => {
it('generates sane toRawType (via with)', (): void => { it('generates sane toRawType (via with)', (): void => {
const Type = Struct.with({ const Type = Struct.with({
accountId: AccountId, accountId: 'AccountId',
balance: registry.createClass('Balance') balance: registry.createClass('Balance')
}); });
+3 -3
View File
@@ -267,11 +267,11 @@ export default class Struct<
} }
public static typesToMap (registry: Registry, Types: Record<string, Constructor>): Record<string, string> { public static typesToMap (registry: Registry, Types: Record<string, Constructor>): Record<string, string> {
return Object.entries(Types).reduce((result, [key, Type]): Record<string, string> => { return Object.entries(Types).reduce((result: Record<string, string>, [key, Type]): Record<string, string> => {
result[key] = new Type(registry).toRawType(); result[key] = registry.getClassName(Type) || new Type(registry).toRawType();
return result; return result;
}, {} as Record<string, string>); }, {});
} }
/** /**
+2 -2
View File
@@ -131,14 +131,14 @@ describe('Tuple', (): void => {
it('generates sane value with array types', (): void => { it('generates sane value with array types', (): void => {
expect( expect(
new Tuple(registry, [U128, registry.createClass('BlockNumber')]).toRawType() new Tuple(registry, [U128, registry.createClass('BlockNumber')]).toRawType()
).toEqual('(u128,u32)'); ).toEqual('(u128,BlockNumber)');
}); });
it('generates sane value with object types', (): void => { it('generates sane value with object types', (): void => {
expect( expect(
// eslint-disable-next-line sort-keys // eslint-disable-next-line sort-keys
new Tuple(registry, { number: U128, blockNumber: registry.createClass('BlockNumber') }).toRawType() new Tuple(registry, { number: U128, blockNumber: registry.createClass('BlockNumber') }).toRawType()
).toEqual('(u128,u32)'); ).toEqual('(u128,BlockNumber)');
}); });
}); });
}); });
+3 -1
View File
@@ -101,7 +101,9 @@ export default class Tuple extends AbstractArray<Codec> {
Array.isArray(this._Types) Array.isArray(this._Types)
? this._Types ? this._Types
: Object.values(this._Types) : Object.values(this._Types)
).map((Type): string => new Type(this.registry).toRawType()); ).map((Type) =>
this.registry.getClassName(Type) || new Type(this.registry).toRawType()
);
return `(${types.join(',')})`; return `(${types.join(',')})`;
} }
+3 -2
View File
@@ -8,10 +8,11 @@ import { isString, u8aToU8a } from '@polkadot/util';
import Raw from './Raw'; import Raw from './Raw';
// The 520 here is a weird one - it is explicitly for a [u8; 65] as found as a EcdsaSignature // The 520 here is a weird one - it is explicitly for a [u8; 65] as found as a EcdsaSignature,
// and 264 here is explicity for a [u8; 33] as found as EcdsaPublic key.
// Likewise 160 is for [u8; 20], which is also a H160, i.e. an Ethereum address. Both these are // Likewise 160 is for [u8; 20], which is also a H160, i.e. an Ethereum address. Both these are
// as a result of the Polkadot claims module. (Technically we don't need the 520 in here) // as a result of the Polkadot claims module. (Technically we don't need the 520 in here)
export type BitLength = 8 | 16 | 32 | 64 | 128 | 160 | 256 | 512 | 520 | 1024 | 2048; export type BitLength = 8 | 16 | 32 | 64 | 128 | 160 | 256 | 264 | 512 | 520 | 1024 | 2048;
/** @internal */ /** @internal */
function decodeU8aFixed (value: AnyU8a, bitLength: BitLength): AnyU8a { function decodeU8aFixed (value: AnyU8a, bitLength: BitLength): AnyU8a {
+6
View File
@@ -16,6 +16,12 @@ describe('UInt', (): void => {
).toThrow('u32: Input too large. Found input with 164 bits, expected 32'); ).toThrow('u32: Input too large. Found input with 164 bits, expected 32');
}); });
it('fails on negative numbers', (): void => {
expect(
(): UInt => new UInt(registry, -123, 32)
).toThrow('u32: Negative number passed to unsigned type');
});
it('allows for construction via BigInt', (): void => { it('allows for construction via BigInt', (): void => {
expect( expect(
new UInt(registry, 123456789123456789123456789n, 128).toHuman() new UInt(registry, 123456789123456789123456789n, 128).toHuman()
+1 -1
View File
@@ -92,6 +92,6 @@ export default class Vec<T extends Codec> extends AbstractArray<T> {
* @description Returns the base runtime type name for this instance * @description Returns the base runtime type name for this instance
*/ */
public toRawType (): string { public toRawType (): string {
return `Vec<${new this._Type(this.registry).toRawType()}>`; return `Vec<${this.registry.getClassName(this._Type) || new this._Type(this.registry).toRawType()}>`;
} }
} }
+29 -1
View File
@@ -4,7 +4,7 @@
import { TypeDef, TypeDefInfo } from './types'; import { TypeDef, TypeDefInfo } from './types';
import { getTypeDef } from '.'; import { TypeRegistry, getTypeDef } from '.';
describe('getTypeDef', (): void => { describe('getTypeDef', (): void => {
it('does not allow invalid tuples, end )', (): void => { it('does not allow invalid tuples, end )', (): void => {
@@ -290,4 +290,32 @@ describe('getTypeDef', (): void => {
type: '[[u8;32];3]' type: '[[u8;32];3]'
}); });
}); });
it('creates recursive structures', (): void => {
const registry = new TypeRegistry();
registry.register({
Recursive: {
data: 'Vec<Recursive>'
}
});
const raw = registry.createType('Recursive' as 'u32').toRawType();
expect(
getTypeDef(raw)
).toEqual({
info: TypeDefInfo.Struct,
sub: [{
info: TypeDefInfo.Vec,
name: 'data',
sub: {
info: TypeDefInfo.Plain,
type: 'Recursive'
},
type: 'Vec<Recursive>'
}],
type: '{"data":"Vec<Recursive>"}'
});
});
}); });
+33 -20
View File
@@ -9,10 +9,17 @@ import { assert } from '@polkadot/util';
import sanitize from './sanitize'; import sanitize from './sanitize';
import { typeSplit } from './typeSplit'; import { typeSplit } from './typeSplit';
interface TypeDefOptions {
name?: string;
displayName?: string;
}
const MAX_NESTED = 64;
// decode an enum of either of the following forms // decode an enum of either of the following forms
// { _enum: ['A', 'B', 'C'] } // { _enum: ['A', 'B', 'C'] }
// { _enum: { A: AccountId, B: Balance, C: u32 } } // { _enum: { A: AccountId, B: Balance, C: u32 } }
function _decodeEnum (value: TypeDef, details: string[] | Record<string, string>): TypeDef { function _decodeEnum (value: TypeDef, details: string[] | Record<string, string>, count: number): TypeDef {
value.info = TypeDefInfo.Enum; value.info = TypeDefInfo.Enum;
// not as pretty, but remain compatible with oo7 for both struct and Array types // not as pretty, but remain compatible with oo7 for both struct and Array types
@@ -24,7 +31,7 @@ function _decodeEnum (value: TypeDef, details: string[] | Record<string, string>
})) }))
: Object.entries(details).map(([name, type]): TypeDef => : Object.entries(details).map(([name, type]): TypeDef =>
// eslint-disable-next-line @typescript-eslint/no-use-before-define // eslint-disable-next-line @typescript-eslint/no-use-before-define
getTypeDef(type || 'Null', { name }) getTypeDef(type || 'Null', { name }, count)
); );
return value; return value;
@@ -50,13 +57,13 @@ function _decodeSet (value: TypeDef, details: Record<string, number>): TypeDef {
// decode a struct, set or enum // decode a struct, set or enum
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
function _decodeStruct (value: TypeDef, type: string, _: string): TypeDef { function _decodeStruct (value: TypeDef, type: string, _: string, count: number): TypeDef {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parsed: Record<string, any> = JSON.parse(type); const parsed: Record<string, any> = JSON.parse(type);
const keys = Object.keys(parsed); const keys = Object.keys(parsed);
if (keys.length === 1 && keys[0] === '_enum') { if (keys.length === 1 && keys[0] === '_enum') {
return _decodeEnum(value, parsed[keys[0]]); return _decodeEnum(value, parsed[keys[0]], count);
} else if (keys.length === 1 && keys[0] === '_set') { } else if (keys.length === 1 && keys[0] === '_set') {
return _decodeSet(value, parsed[keys[0]]); return _decodeSet(value, parsed[keys[0]]);
} }
@@ -66,7 +73,7 @@ function _decodeStruct (value: TypeDef, type: string, _: string): TypeDef {
: undefined; : undefined;
value.sub = keys.filter((name) => !['_alias'].includes(name)).map((name): TypeDef => value.sub = keys.filter((name) => !['_alias'].includes(name)).map((name): TypeDef =>
// eslint-disable-next-line @typescript-eslint/no-use-before-define // eslint-disable-next-line @typescript-eslint/no-use-before-define
getTypeDef(parsed[name], { name }) getTypeDef(parsed[name], { name }, count)
); );
return value; return value;
@@ -74,7 +81,7 @@ function _decodeStruct (value: TypeDef, type: string, _: string): TypeDef {
// decode a fixed vector, e.g. [u8;32] // decode a fixed vector, e.g. [u8;32]
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
function _decodeFixedVec (value: TypeDef, type: string, _: string): TypeDef { function _decodeFixedVec (value: TypeDef, type: string, _: string, count: number): TypeDef {
const [vecType, strLength, displayName] = type.substr(1, type.length - 2).split(';'); const [vecType, strLength, displayName] = type.substr(1, type.length - 2).split(';');
const length = parseInt(strLength.trim(), 10); const length = parseInt(strLength.trim(), 10);
@@ -84,18 +91,18 @@ function _decodeFixedVec (value: TypeDef, type: string, _: string): TypeDef {
value.displayName = displayName; value.displayName = displayName;
value.length = length; value.length = length;
// eslint-disable-next-line @typescript-eslint/no-use-before-define // eslint-disable-next-line @typescript-eslint/no-use-before-define
value.sub = getTypeDef(vecType); value.sub = getTypeDef(vecType, {}, count);
return value; return value;
} }
// decode a tuple // decode a tuple
function _decodeTuple (value: TypeDef, _: string, subType: string): TypeDef { function _decodeTuple (value: TypeDef, _: string, subType: string, count: number): TypeDef {
value.sub = subType.length === 0 value.sub = subType.length === 0
? [] ? []
: typeSplit(subType).map((inner): TypeDef => : typeSplit(subType).map((inner): TypeDef =>
// eslint-disable-next-line @typescript-eslint/no-use-before-define // eslint-disable-next-line @typescript-eslint/no-use-before-define
getTypeDef(inner) getTypeDef(inner, {}, count)
); );
return value; return value;
@@ -103,7 +110,7 @@ function _decodeTuple (value: TypeDef, _: string, subType: string): TypeDef {
// decode a Int/UInt<bitLength[, name]> // decode a Int/UInt<bitLength[, name]>
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
function _decodeInt (value: TypeDef, type: string, _: string, clazz: 'Int' | 'UInt' = 'Int'): TypeDef { function _decodeAnyInt (value: TypeDef, type: string, _: string, clazz: 'Int' | 'UInt'): TypeDef {
const [strLength, displayName] = type.substr(clazz.length + 1, type.length - clazz.length - 1 - 1).split(','); const [strLength, displayName] = type.substr(clazz.length + 1, type.length - clazz.length - 1 - 1).split(',');
const length = parseInt(strLength.trim(), 10); const length = parseInt(strLength.trim(), 10);
@@ -116,8 +123,12 @@ function _decodeInt (value: TypeDef, type: string, _: string, clazz: 'Int' | 'UI
return value; return value;
} }
function _decodeInt (value: TypeDef, type: string, subType: string): TypeDef {
return _decodeAnyInt(value, type, subType, 'Int');
}
function _decodeUInt (value: TypeDef, type: string, subType: string): TypeDef { function _decodeUInt (value: TypeDef, type: string, subType: string): TypeDef {
return _decodeInt(value, type, subType, 'UInt'); return _decodeAnyInt(value, type, subType, 'UInt');
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -139,7 +150,7 @@ function hasWrapper (type: string, [start, end]: [string, string, TypeDefInfo, a
return true; return true;
} }
const nestedExtraction: [string, string, TypeDefInfo, (value: TypeDef, type: string, subType: string) => TypeDef][] = [ const nestedExtraction: [string, string, TypeDefInfo, (value: TypeDef, type: string, subType: string, count: number) => TypeDef][] = [
['[', ']', TypeDefInfo.VecFixed, _decodeFixedVec], ['[', ']', TypeDefInfo.VecFixed, _decodeFixedVec],
['{', '}', TypeDefInfo.Struct, _decodeStruct], ['{', '}', TypeDefInfo.Struct, _decodeStruct],
['(', ')', TypeDefInfo.Tuple, _decodeTuple], ['(', ')', TypeDefInfo.Tuple, _decodeTuple],
@@ -164,15 +175,17 @@ function extractSubType (type: string, [start, end]: [string, string, TypeDefInf
return type.substr(start.length, type.length - start.length - end.length); return type.substr(start.length, type.length - start.length - end.length);
} }
interface TypeDefOptions { export function getTypeDef (_type: string, { displayName, name }: TypeDefOptions = {}, count = 0): TypeDef {
name?: string;
displayName?: string;
}
export function getTypeDef (_type: string, { displayName, name }: TypeDefOptions = {}): TypeDef {
// create the type via Type, allowing types to be sanitized // create the type via Type, allowing types to be sanitized
const type = sanitize(_type); const type = sanitize(_type);
const value: TypeDef = { displayName, info: TypeDefInfo.Plain, name, type }; const value: TypeDef = { displayName, info: TypeDefInfo.Plain, name, type };
if (++count === MAX_NESTED) {
console.warn('getTypeDef: Maximum nested limit reached');
return value;
}
const nested = nestedExtraction.find((nested): boolean => const nested = nestedExtraction.find((nested): boolean =>
hasWrapper(type, nested) hasWrapper(type, nested)
); );
@@ -180,7 +193,7 @@ export function getTypeDef (_type: string, { displayName, name }: TypeDefOptions
if (nested) { if (nested) {
value.info = nested[2]; value.info = nested[2];
return nested[3](value, type, extractSubType(type, nested)); return nested[3](value, type, extractSubType(type, nested), count);
} }
const wrapped = wrappedExtraction.find((wrapped): boolean => const wrapped = wrappedExtraction.find((wrapped): boolean =>
@@ -189,7 +202,7 @@ export function getTypeDef (_type: string, { displayName, name }: TypeDefOptions
if (wrapped) { if (wrapped) {
value.info = wrapped[2]; value.info = wrapped[2];
value.sub = getTypeDef(extractSubType(type, wrapped)); value.sub = getTypeDef(extractSubType(type, wrapped), {}, count);
} }
return value; return value;
+29 -1
View File
@@ -76,7 +76,35 @@ describe('TypeRegistry', (): void => {
expect((first as any).next.unwrap().next.isSome).toBe(false); expect((first as any).next.unwrap().next.isSome).toBe(false);
}); });
it('can register cross-referencing types ()', (): void => { it('can register non-embedded recursive types', (): void => {
registry.register({
Operation: {
data: 'OperationData'
},
OperationData: {
ops: 'Vec<Operation>'
},
Rule: {
data: 'RuleData'
},
RuleData: {
ops: 'Vec<Operation>'
}
});
expect(registry.hasDef('Rule')).toBe(true);
expect(registry.hasClass('Rule')).toBe(false);
const Rule = registry.getOrThrow('Rule');
expect(registry.hasClass('Rule')).toBe(true);
const instance = new Rule(registry);
expect(instance.toRawType()).toEqual('{"data":"RuleData"}');
});
it('can register cross-referencing types', (): void => {
registry.register({ registry.register({
A: { A: {
next: 'B' next: 'B'
+8
View File
@@ -225,6 +225,14 @@ export class TypeRegistry implements Registry {
return this.#chainProperties; return this.#chainProperties;
} }
public getClassName (clazz: Constructor): string | undefined {
const entry = [...this.#classes.entries()].find(([, test]) => test === clazz);
return entry
? entry[0]
: undefined;
}
public getDefinition (name: string): string | undefined { public getDefinition (name: string): string | undefined {
return this.#definitions.get(name); return this.#definitions.get(name);
} }
+1 -9
View File
@@ -24,15 +24,7 @@ describe('Block', (): void => {
).toEqual( ).toEqual(
// each of the containing structures have been stringified on their own // each of the containing structures have been stringified on their own
JSON.stringify({ JSON.stringify({
header: JSON.stringify({ header: 'Header',
parentHash: 'H256',
number: 'Compact<u32>',
stateRoot: 'H256',
extrinsicsRoot: 'H256',
digest: JSON.stringify({
logs: 'Vec<{"_enum":{"Other":"Bytes","AuthoritiesChange":"Vec<AccountId>","ChangesTrieRoot":"H256","SealV0":"(u64,H512)","Consensus":"(u32,Bytes)","Seal":"(u32,Bytes)","PreRuntime":"(u32,Bytes)"}}>'
})
}),
extrinsics: 'Vec<Extrinsic>' extrinsics: 'Vec<Extrinsic>'
}) })
); );
@@ -65,6 +65,7 @@ export default {
LookupTarget: 'AccountId', LookupTarget: 'AccountId',
ModuleId: 'LockIdentifier', ModuleId: 'LockIdentifier',
Moment: 'u64', Moment: 'u64',
OpaqueCall: 'Bytes',
Origin: 'DoNotConstruct<Origin>', Origin: 'DoNotConstruct<Origin>',
Pays: { Pays: {
_enum: ['Yes', 'No'] _enum: ['Yes', 'No']
@@ -133,6 +133,9 @@ export interface ModuleId extends LockIdentifier {}
/** @name Moment */ /** @name Moment */
export interface Moment extends u64 {} export interface Moment extends u64 {}
/** @name OpaqueCall */
export interface OpaqueCall extends Bytes {}
/** @name Origin */ /** @name Origin */
export interface Origin extends DoNotConstruct {} export interface Origin extends DoNotConstruct {}
@@ -13,11 +13,20 @@ export default {
OpenTip: { OpenTip: {
reason: 'Hash', reason: 'Hash',
who: 'AccountId', who: 'AccountId',
finder: 'Option<OpenTipFinder>', finder: 'AccountId',
deposit: 'Balance',
closes: 'Option<BlockNumber>',
tips: 'Vec<OpenTipTip>',
findersFee: 'bool'
},
OpenTipTo225: {
reason: 'Hash',
who: 'AccountId',
finder: 'Option<OpenTipFinderTo225>',
closes: 'Option<BlockNumber>', closes: 'Option<BlockNumber>',
tips: 'Vec<OpenTipTip>' tips: 'Vec<OpenTipTip>'
}, },
OpenTipFinder: '(AccountId, Balance)', OpenTipFinderTo225: '(AccountId, Balance)',
OpenTipTip: '(AccountId, Balance)', OpenTipTip: '(AccountId, Balance)',
TreasuryProposal: { TreasuryProposal: {
proposer: 'AccountId', proposer: 'AccountId',
@@ -3,23 +3,35 @@
import { ITuple } from '@polkadot/types/types'; import { ITuple } from '@polkadot/types/types';
import { Option, Struct, Vec } from '@polkadot/types/codec'; import { Option, Struct, Vec } from '@polkadot/types/codec';
import { bool } from '@polkadot/types/primitive';
import { AccountId, Balance, BlockNumber, Hash } from '@polkadot/types/interfaces/runtime'; import { AccountId, Balance, BlockNumber, Hash } from '@polkadot/types/interfaces/runtime';
/** @name OpenTip */ /** @name OpenTip */
export interface OpenTip extends Struct { export interface OpenTip extends Struct {
readonly reason: Hash; readonly reason: Hash;
readonly who: AccountId; readonly who: AccountId;
readonly finder: Option<OpenTipFinder>; readonly finder: AccountId;
readonly deposit: Balance;
readonly closes: Option<BlockNumber>; readonly closes: Option<BlockNumber>;
readonly tips: Vec<OpenTipTip>; readonly tips: Vec<OpenTipTip>;
readonly findersFee: bool;
} }
/** @name OpenTipFinder */ /** @name OpenTipFinderTo225 */
export interface OpenTipFinder extends ITuple<[AccountId, Balance]> {} export interface OpenTipFinderTo225 extends ITuple<[AccountId, Balance]> {}
/** @name OpenTipTip */ /** @name OpenTipTip */
export interface OpenTipTip extends ITuple<[AccountId, Balance]> {} export interface OpenTipTip extends ITuple<[AccountId, Balance]> {}
/** @name OpenTipTo225 */
export interface OpenTipTo225 extends Struct {
readonly reason: Hash;
readonly who: AccountId;
readonly finder: Option<OpenTipFinderTo225>;
readonly closes: Option<BlockNumber>;
readonly tips: Vec<OpenTipTip>;
}
/** @name TreasuryProposal */ /** @name TreasuryProposal */
export interface TreasuryProposal extends Struct { export interface TreasuryProposal extends Struct {
readonly proposer: AccountId; readonly proposer: AccountId;
+4 -4
View File
@@ -67,11 +67,11 @@ export default class Data extends Enum {
} }
get asRaw (): Bytes { get asRaw (): Bytes {
return this._raw as Bytes; return this.value as Bytes;
} }
get asSha256 (): H256 { get asSha256 (): H256 {
return this._raw as H256; return this.value as H256;
} }
get isRaw (): boolean { get isRaw (): boolean {
@@ -97,7 +97,7 @@ export default class Data extends Enum {
return new Uint8Array(1); return new Uint8Array(1);
} else if (this.index === 1) { } else if (this.index === 1) {
// don't add the length, just the data // don't add the length, just the data
const data = this._raw.toU8a(true); const data = this.value.toU8a(true);
const length = Math.min(data.length, 32); const length = Math.min(data.length, 32);
const u8a = new Uint8Array(length + 1); const u8a = new Uint8Array(length + 1);
@@ -111,7 +111,7 @@ export default class Data extends Enum {
const u8a = new Uint8Array(33); const u8a = new Uint8Array(33);
u8a.set([this.index + 32], 0); u8a.set([this.index + 32], 0);
u8a.set(this._raw.toU8a(), 1); u8a.set(this.value.toU8a(), 1);
return u8a; return u8a;
} }
+1
View File
@@ -124,6 +124,7 @@ export interface Registry {
createType <K extends keyof InterfaceTypes> (type: K, ...params: unknown[]): InterfaceTypes[K]; createType <K extends keyof InterfaceTypes> (type: K, ...params: unknown[]): InterfaceTypes[K];
get <T extends Codec = Codec> (name: string, withUnknown?: boolean): Constructor<T> | undefined; get <T extends Codec = Codec> (name: string, withUnknown?: boolean): Constructor<T> | undefined;
getChainProperties (): ChainProperties | undefined; getChainProperties (): ChainProperties | undefined;
getClassName (clazz: Constructor): string | undefined;
getDefinition (name: string): string | undefined; getDefinition (name: string): string | undefined;
getOrThrow <T extends Codec = Codec> (name: string, msg?: string): Constructor<T>; getOrThrow <T extends Codec = Codec> (name: string, msg?: string): Constructor<T>;
getOrUnknown <T extends Codec = Codec> (name: string): Constructor<T>; getOrUnknown <T extends Codec = Codec> (name: string): Constructor<T>;
+1328 -1309
View File
File diff suppressed because it is too large Load Diff