Compare commits

...
81 Commits
Author SHA1 Message Date
Github Actions 67ae9627af [CI Skip] release/stable 3.6.1
skip-checks: true
2021-01-24 13:00:12 +00:00
Jaco Greeff 29f7e12df6 3.6 (#3101) 2021-01-24 13:52:53 +01:00
Github Actions a4bb2c8268 [CI Skip] release/beta 3.5.2-16
skip-checks: true
2021-01-24 11:40:20 +00:00
Jaco Greeff 6521c5f533 Bump common (#3100) 2021-01-24 12:33:04 +01:00
Github Actions 6925c18821 [CI Skip] release/beta 3.5.2-15
skip-checks: true
2021-01-24 10:31:50 +00:00
Jaco Greeff 9269d94677 Bump common (#3099)
* Bump common

* Undefined value

* Test for undefined
2021-01-24 11:23:23 +01:00
Github Actions d438814ad6 [CI Skip] release/beta 3.5.2-14
skip-checks: true
2021-01-23 15:56:13 +00:00
Jaco Greeff bc205a350b Fix ChainProperties JSON decoding 2021-01-23 16:47:22 +01:00
Github Actions 6bf6fddd28 [CI Skip] release/beta 3.5.2-13
skip-checks: true
2021-01-23 13:53:50 +00:00
Jaco Greeff 23f8eb9713 Return locks for extended balance instances (#3097) 2021-01-23 14:45:17 +01:00
Github Actions 8ab3097328 [CI Skip] release/beta 3.5.2-12
skip-checks: true
2021-01-23 12:44:02 +00:00
Jaco Greeff 644d0e6c2e Change registry.chainToekn to registry.chainTokens (#3096) 2021-01-23 13:36:30 +01:00
Github Actions 6a69fdfbbf [CI Skip] release/beta 3.5.2-11
skip-checks: true
2021-01-23 11:24:22 +00:00
Jaco Greeff 16e9a64941 Allow multiples in system.properties (decimals, tokens) (#3093)
* Allow multiples in syste.propertis (decimals, tokens)

* registry.chain{Decimals, Token} returns array values

* Bump common

* AbstractInt format with first decimal/token

* Adjust ss58Format consistency

* u8 decimals/format

* cleanups

* More slight weidness

* Adjust all t u32

* Cleanup properties format from Codec
2021-01-23 12:16:10 +01:00
Github Actions f3cbc070ea [CI Skip] release/beta 3.5.2-10
skip-checks: true
2021-01-22 23:07:31 +00:00
Jaco Greeff df22526229 Bump deps (#3095) 2021-01-22 23:58:53 +01:00
Github Actions 3739bdaa89 [CI Skip] release/beta 3.5.2-9
skip-checks: true
2021-01-22 21:31:40 +00:00
Jaco Greeff 1f55f38bd2 Introduce instances, apply to balance derives (multi-result) (#3094)
* Introducce instances, apply to balance derives (multi-result)

* Nonce extraction

* Optimize
2021-01-22 22:24:10 +01:00
Github Actions c9deb0d88f [CI Skip] release/beta 3.5.2-8
skip-checks: true
2021-01-22 16:29:02 +00:00
Jaco Greeff eecfb39463 Bump common (#3092) 2021-01-22 17:21:33 +01:00
Github Actions 51bb27da42 [CI Skip] release/beta 3.5.2-7
skip-checks: true
2021-01-22 08:21:12 +00:00
Jaco Greeff 9c0d296e87 typegen dedup (#3089) 2021-01-22 09:12:29 +01:00
Github Actions 0793e0bf8c [CI Skip] release/beta 3.5.2-6
skip-checks: true
2021-01-21 21:45:15 +00:00
Jaco Greeff e9ad88d50e Register all types for error generation (#3088)
* Register all types for error generation

* type for ExtraTypes
2021-01-21 22:37:37 +01:00
Github Actions fbe24c04b8 [CI Skip] release/beta 3.5.2-5
skip-checks: true
2021-01-21 10:08:55 +00:00
Jaco Greeff 8a7d4d3be3 Bump metadata (#3085)
* Bump metadata

* linting
2021-01-21 11:01:31 +01:00
Github Actions 61c9a3bb93 [CI Skip] release/beta 3.5.2-4
skip-checks: true
2021-01-21 08:39:46 +00:00
Jaco Greeff 3721a11f34 Add errors/events Md interface endpoints (#3084) 2021-01-21 09:31:40 +01:00
Github Actions 21039dec1f [CI Skip] release/beta 3.5.2-3
skip-checks: true
2021-01-19 21:54:16 +00:00
Jaco Greeff 1393f565d8 Paras validator index alias (#3079) 2021-01-19 22:46:49 +01:00
Jaco Greeff 1530e55f9d Disallow primitive singular registration (#3077) 2021-01-19 22:46:29 +01:00
Github Actions c982505f73 [CI Skip] release/beta 3.5.2-2
skip-checks: true
2021-01-19 21:15:33 +00:00
Jaco Greeff ec8c0d3e8b Move x-rxjs into common (#3078)
* Moe x-rxjs into common

* yarn

* jest config

* Pull in new pubslished x-rxjs
2021-01-19 22:08:03 +01:00
Github Actions 8cb0269676 [CI Skip] release/beta 3.5.2-1
skip-checks: true
2021-01-19 12:27:07 +00:00
Jaco Greeff 27f460cfe3 Add payment_queryFeeDetails (#3076) 2021-01-19 13:18:23 +01:00
Jaco Greeff e98e8d6a0d Type capability detection (#3075)
* Type capability detection

* re-add Observable export

* Remove unused exports

* Decorate capabilities

* log capabilities

* Detect capabilities for historic

* Re-add logging

* Log

* Rework ValidatorPrefs types
2021-01-19 13:15:18 +01:00
Github Actions 2f94662837 [CI Skip] release/beta 3.5.2-0
skip-checks: true
2021-01-19 10:49:10 +00:00
Jaco Greeff d46d6a9acd Add ValidatorPrefs w/ blocked flag (#3073) 2021-01-19 11:41:23 +01:00
Github Actions 093d2cfa7c [CI Skip] release/stable 3.5.1
skip-checks: true
2021-01-18 11:37:28 +00:00
Jaco Greeff 35b31a21dc 3.5 (#3071) 2021-01-18 12:29:58 +01:00
Github Actions 8b9741a722 [CI Skip] release/beta 3.4.2-18
skip-checks: true
2021-01-18 08:42:18 +00:00
Ewa Kowalska d5cfa9b0e9 Handle no council for bounties proposals (#3062)
* Handle no council for bounties proposals

* Fix code climate

* Handle no council present with api derive
2021-01-18 09:33:20 +01:00
Github Actions 129d1214fe [CI Skip] release/beta 3.4.2-17
skip-checks: true
2021-01-17 15:11:37 +00:00
Jaco Greeff abb3375c3a Bump common (& Substrate node references) (#3069) 2021-01-17 16:04:26 +01:00
Github Actions 4cfa06b43f [CI Skip] release/beta 3.4.2-16
skip-checks: true
2021-01-17 13:30:25 +00:00
Jaco Greeff 8fa80ac0f6 Adjust node-template for MultiAddress (>= 100) (#3068)
* Adjust node-template for MultiAddress (>= 100)

* Bump deps
2021-01-17 14:22:09 +01:00
Github Actions 2d011c68df [CI Skip] release/beta 3.4.2-15
skip-checks: true
2021-01-17 12:48:44 +00:00
Jaco Greeff 640ef4bdab Adjust Rococo types (#3067) 2021-01-17 13:39:29 +01:00
Github Actions cdd20c0b99 [CI Skip] release/beta 3.4.2-14
skip-checks: true
2021-01-15 21:41:55 +00:00
Jaco Greeff 3a12123bf9 Remove recursion on decodeU8a (#3063)
* Remove recursion on decodeU8a

* Remove skipped tests

* Remove extra allocation
2021-01-15 22:34:30 +01:00
Github Actions 5657d5395b [CI Skip] release/beta 3.4.2-13
skip-checks: true
2021-01-15 15:14:00 +00:00
Jeremías Díaz 66b1108c5c feat(types): add correct tuple type to storage key (#3054)
* feat(types): add correct tuple type to storage key

* refactor(types): remove unneeded type assertions
2021-01-15 16:06:23 +01:00
Github Actions 7bf7e207c2 [CI Skip] release/beta 3.4.2-12
skip-checks: true
2021-01-15 13:38:01 +00:00
Jaco Greeff 01098395ec Add crowdloan types (#3060)
* Add crowdloan types

* Update
2021-01-15 14:28:57 +01:00
Github Actions 3e21dfdc03 [CI Skip] release/beta 3.4.2-11
skip-checks: true
2021-01-15 12:56:17 +00:00
Jaco Greeff a400fb2362 Sort registry (#3061) 2021-01-15 13:49:12 +01:00
Github Actions 44172aa359 [CI Skip] release/beta 3.4.2-10
skip-checks: true
2021-01-15 11:32:08 +00:00
Jaco Greeff 82cab2827a Add lottery types (#3059) 2021-01-15 12:23:19 +01:00
Github Actions a198eb1515 [CI Skip] release/beta 3.4.2-9
skip-checks: true
2021-01-15 10:57:12 +00:00
Jaco Greeff 6e67cd6c97 Bump common (#3058) 2021-01-15 11:48:25 +01:00
Github Actions e51e89df56 [CI Skip] release/beta 3.4.2-8
skip-checks: true
2021-01-13 23:12:15 +00:00
Jaco Greeff e46fd07d39 align aura/babe without staking 2021-01-14 00:03:28 +01:00
Jaco Greeff b2cf9aed83 Info changes for no staking (but with babe) 2021-01-14 00:01:42 +01:00
Jaco Greeff c632030437 Fix derive session.info with no staking 2021-01-13 23:59:59 +01:00
Github Actions 9dc683d289 [CI Skip] release/beta 3.4.2-7
skip-checks: true
2021-01-13 22:53:45 +00:00
Jaco Greeff 6cef6190b1 Optional staking in session progress calcs (#3051)
* Optional staking in session progress calcs

* No extra pipe
2021-01-13 23:46:15 +01:00
Github Actions 75dd443d79 [CI Skip] release/beta 3.4.2-6
skip-checks: true
2021-01-13 12:14:07 +00:00
Jaco Greeff 13dacb591d Updata parachain types (#3050) 2021-01-13 13:07:07 +01:00
Jaco Greeff 429bf5456e Add tests for toBigInt usage (#3049)
* Add tests for toBigInt usage

* Update packages/types/src/codec/UInt.spec.ts
2021-01-13 13:00:10 +01:00
Github Actions 527c0f5015 [CI Skip] release/beta 3.4.2-5
skip-checks: true
2021-01-13 10:19:11 +00:00
Jaco Greeff 527ab27bee Westend 46, 47 blocks (#3044) 2021-01-13 11:09:33 +01:00
Github Actions 7991403022 [CI Skip] release/beta 3.4.2-4
skip-checks: true
2021-01-13 08:07:59 +00:00
Ian He 61d2e6c5e5 toBigInt() uses primitive type bigint (#3047) 2021-01-13 09:01:11 +01:00
Github Actions e005a3fc0c [CI Skip] release/beta 3.4.2-3
skip-checks: true
2021-01-12 13:54:07 +00:00
Jaco Greeff 2dfb0fb59a Dedupe parachain types (#3043)
* Updata parachain types

* Remove duplication

* hrmp update
2021-01-12 14:46:57 +01:00
Github Actions 70c011e7e2 [CI Skip] release/beta 3.4.2-2
skip-checks: true
2021-01-12 13:23:32 +00:00
Jaco Greeff 8134322626 Updata parachain types (#3042) 2021-01-12 14:14:54 +01:00
Github Actions 60152749bb [CI Skip] release/beta 3.4.2-1
skip-checks: true
2021-01-11 23:27:12 +00:00
Jaco Greeff b257e120d4 Update parachain types (#3041) 2021-01-12 00:20:20 +01:00
Github Actions 6dc75acd21 [CI Skip] release/beta 3.4.2-0
skip-checks: true
2021-01-11 15:44:17 +00:00
Jaco Greeff a04400170c Set Rococo Keys to 6 (#3040) 2021-01-11 16:36:32 +01:00
108 changed files with 4874 additions and 3698 deletions
+44
View File
@@ -1,5 +1,49 @@
# CHANGELOG
## 3.6.1 Jan 24, 2020
Upgrade priority: Medium if not already on at least 3.3.1. The next upgrade of Kusama/Polkadot requires it.
- **Breaking change** To support chains with multiple tokens, such as bridges, the `ChainProperties` type now returns an array of tokens and decimals (instead of singular values) in the `token{Decimals, Symbol}` getters. Additionally, this means that the `registry` interfaces has been changes, to `registry.chainDecimals: number[]` and `registry.chainTokens: string[]`. Where used the `[0]` index will return the first value if only interested in a single, for a straight conversion.
Changes:
- Allow for the detection of on-chain capabilities as available (e.g. `AccountData`, `ValidatorPrefs`)
- Cater for multiple tokens and decimals in the chain the chain `system.properties` (as per the chain specification)
- Add a `instances: { [key]: [module1, module2] }` definition in teh bundle types, allowing for multiple instances (e.g. Balances)
- Adjust the `api-derive` for balances to retrieve values via `instances` as well as across multiple modules
- Ensure all types are registered for all metadata typegen steps
- Add `rpc.payment.queryFeeDetails` RPC endpoint
- Update types & metadata to latest Substrate
- Move the `@polkadot/x-rxjs` package into the common repo
- Allow doc generation for errors/events (markdown outputs)
## 3.5.1 Jan 18, 2020
Upgrade priority: Low. Recommended for parachain developers.
- **Important** The default for Substrate on the Address types are `MultiAddress`. It is recommended that chains add explicit definitions for `Address` and `LookupSource` in their types, instead of relying on the API-defaults. A future update will swap the API defaults to align with Substrate.
- **Important** Like the above changes in Substrate, the `AccountInfo` structure has also changed. It is recommended that chain developers explicitly add `AccountInfo: 'AccountInfoWithRefCount'` for the version with `refCount` on and `AccountInfoWithProviders` for the latest Substrate version. As per the above, the API defaults will be changed to align with Substrate.
Contributed:
- Apply correct TypeScript type for `toBigInt()` (Thanks to https://github.com/ianhe8x)
- Expand type definitions for storage key tuples (Thanks to https://github.com/monitz87)
- Adjust bounty derive to cater for non-council chains (Thanks to https://github.com/ekowalsk)
Changes:
- Remove recursion in vector/struct U8a stream decoding
- Availability of staking made optional in session length calcs (era does require it)
- Updates to parachain types, ensuring it has coverage for all the latest
- Update all Rococo types to the latest (session keys, session reports, parachain indexes)
- Update known upgrade checkpoints fo WestEnd
- Add types of the lottery module in Substrate
- Add and extend types for the crowdloan module in Polkadot
- Adjust node-template to default to `MultiAddress` on specVersion >= 100
## 3.4.1 Jan 11, 2020
Upgrade priority: Low. Fixes for parachain types, `.entries()` (with no values) and `event.is(...)` checks, users of these interfaces will have benefit.
+2 -4
View File
@@ -13,8 +13,7 @@ module.exports = Object.assign({}, config, {
'@polkadot/typegen(.*)$': '<rootDir>/packages/typegen/src/$1',
'@polkadot/types-known(.*)$': '<rootDir>/packages/types-known/src/$1',
// eslint-disable-next-line sort-keys
'@polkadot/types(.*)$': '<rootDir>/packages/types/src/$1',
'@polkadot/x-rxjs(.*)$': '<rootDir>/packages/x-rxjs/src/$1'
'@polkadot/types(.*)$': '<rootDir>/packages/types/src/$1'
},
modulePathIgnorePatterns: [
'<rootDir>/packages/api/build',
@@ -25,8 +24,7 @@ module.exports = Object.assign({}, config, {
'<rootDir>/packages/rpc-provider/build',
'<rootDir>/packages/typegen/build',
'<rootDir>/packages/types/build',
'<rootDir>/packages/types-known/build',
'<rootDir>/packages/x-rxjs/build'
'<rootDir>/packages/types-known/build'
],
resolver: '@polkadot/dev/config/jest-resolver.cjs'
});
+1 -1
View File
@@ -34,5 +34,5 @@
"@types/jest": "^26.0.20",
"copyfiles": "^2.4.1"
},
"version": "3.4.1"
"version": "3.6.1"
}
+5 -6
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/api-contract",
"version": "3.4.1",
"version": "3.6.1",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
"module": "index.mjs",
"sideEffects": false,
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
@@ -14,10 +13,10 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@polkadot/api": "3.4.1",
"@polkadot/types": "3.4.1",
"@polkadot/util": "^5.2.3",
"@polkadot/x-rxjs": "3.4.1",
"@polkadot/api": "3.6.1",
"@polkadot/types": "3.6.1",
"@polkadot/util": "^5.4.2",
"@polkadot/x-rxjs": "^5.4.2",
"bn.js": "^4.11.9"
}
}
+9 -10
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/api-derive",
"version": "3.4.1",
"version": "3.6.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"module": "index.mjs",
"sideEffects": false,
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
@@ -14,16 +13,16 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@polkadot/api": "3.4.1",
"@polkadot/rpc-core": "3.4.1",
"@polkadot/types": "3.4.1",
"@polkadot/util": "^5.2.3",
"@polkadot/util-crypto": "^5.2.3",
"@polkadot/x-rxjs": "3.4.1",
"@polkadot/api": "3.6.1",
"@polkadot/rpc-core": "3.6.1",
"@polkadot/types": "3.6.1",
"@polkadot/util": "^5.4.2",
"@polkadot/util-crypto": "^5.4.2",
"@polkadot/x-rxjs": "^5.4.2",
"bn.js": "^4.11.9"
},
"devDependencies": {
"@polkadot/keyring": "^5.2.3",
"@polkadot/rpc-provider": "3.4.1"
"@polkadot/keyring": "^5.4.2",
"@polkadot/rpc-provider": "3.6.1"
}
}
+1 -2
View File
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountIndex } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import type { AccountIndexes } from '../types';
@@ -18,7 +17,7 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
map((entries): AccountIndexes =>
entries.reduce((indexes: AccountIndexes, [key, idOpt]): AccountIndexes => {
if (idOpt.isSome) {
indexes[idOpt.unwrap()[0].toString()] = key.args[0] as AccountIndex;
indexes[idOpt.unwrap()[0].toString()] = key.args[0];
}
return indexes;
+52 -25
View File
@@ -1,24 +1,24 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
import type { AccountData, AccountId, AccountIndex, AccountInfo, Address, Balance, Index } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveBalancesAccount } from '../types';
import type { DeriveBalancesAccount, DeriveBalancesAccountData } from '../types';
import { isFunction } from '@polkadot/util';
import { assert, isFunction } from '@polkadot/util';
import { combineLatest, of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { memo } from '../util';
type Result = [Balance, Balance, Balance, Balance, Index];
type BalanceResult = [Balance, Balance, Balance, Balance];
function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBalance, frozenFee, frozenMisc, accountNonce]]: [AccountId, Result]): DeriveBalancesAccount {
type Result = [Index, BalanceResult[]];
function getBalance (api: ApiInterfaceRx, [freeBalance, reservedBalance, frozenFee, frozenMisc]: BalanceResult): DeriveBalancesAccountData {
return {
accountId,
accountNonce,
freeBalance,
frozenFee,
frozenMisc,
@@ -27,6 +27,19 @@ function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBa
};
}
function calcBalances (api: ApiInterfaceRx, [accountId, [accountNonce, balances]]: [AccountId, Result]): DeriveBalancesAccount {
const primary = balances[0];
assert(primary, 'No balances retrieved for account');
return {
accountId,
accountNonce,
additional: balances.filter((_, index) => index !== 0).map((b) => getBalance(api, b)),
...getBalance(api, primary)
};
}
// old
function queryBalancesFree (api: ApiInterfaceRx, accountId: AccountId): Observable<Result> {
return api.queryMulti<[Balance, Balance, Index]>([
@@ -34,21 +47,25 @@ function queryBalancesFree (api: ApiInterfaceRx, accountId: AccountId): Observab
[api.query.balances.reservedBalance, accountId],
[api.query.system.accountNonce, accountId]
]).pipe(
map(([freeBalance, reservedBalance, accountNonce]): Result =>
[freeBalance, reservedBalance, api.registry.createType('Balance'), api.registry.createType('Balance'), accountNonce]
)
map(([freeBalance, reservedBalance, accountNonce]): Result => [
accountNonce,
[[freeBalance, reservedBalance, api.registry.createType('Balance'), api.registry.createType('Balance')]]
])
);
}
function queryBalancesAccount (api: ApiInterfaceRx, accountId: AccountId): Observable<Result> {
return api.queryMulti<[AccountData, Index]>([
[api.query.balances.account, accountId],
[api.query.system.accountNonce, accountId]
]).pipe(
map(([{ feeFrozen, free, miscFrozen, reserved }, accountNonce]): Result =>
[free, reserved, feeFrozen, miscFrozen, accountNonce]
function queryBalancesAccount (api: ApiInterfaceRx, accountId: AccountId, modules: string[] = ['balances']): Observable<Result> {
const balances = modules.map((m): QueryableStorageMultiArg<'rxjs'> => [api.query[m].account, accountId]);
const extract = (data: AccountData[]) =>
data.map(({ feeFrozen, free, miscFrozen, reserved }): BalanceResult => [free, reserved, feeFrozen, miscFrozen]);
return isFunction(api.query.system.account)
? api.queryMulti<[AccountInfo, ...(AccountData[])]>([[api.query.system.account, accountId], ...balances]).pipe(
map(([{ nonce }, ...balances]): Result => [nonce, extract(balances)])
)
);
: api.queryMulti<[Index, ...(AccountData[])]>([[api.query.system.accountNonce, accountId], ...balances]).pipe(
map(([nonce, ...balances]): Result => [nonce, extract(balances)])
);
}
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Result> {
@@ -60,7 +77,7 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
: (infoOrTuple as [Index, AccountData])[1];
const accountNonce = (infoOrTuple as AccountInfo).nonce || (infoOrTuple as [Index, AccountData])[0];
return [free, reserved, feeFrozen, miscFrozen, accountNonce];
return [accountNonce, [[free, reserved, feeFrozen, miscFrozen]]];
})
);
}
@@ -81,19 +98,29 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
* ```
*/
export function account (instanceId: string, api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAccount> {
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances');
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAccount> =>
api.derive.accounts.accountId(address).pipe(
switchMap((accountId): Observable<[AccountId, Result]> =>
(accountId
? combineLatest([
of(accountId),
isFunction(api.query.system.account)
? queryCurrent(api, accountId)
: isFunction(api.query.balances.account)
? queryBalancesAccount(api, accountId)
: queryBalancesFree(api, accountId)
balanceInstances
? queryBalancesAccount(api, accountId, balanceInstances)
: isFunction(api.query.system.account)
? queryCurrent(api, accountId)
: isFunction(api.query.balances.account)
? queryBalancesAccount(api, accountId)
: queryBalancesFree(api, accountId)
])
: of([
api.registry.createType('AccountId'),
[
api.registry.createType('Index'),
[[api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance')]]
]
])
: of([api.registry.createType('AccountId'), [api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Index')]])
)
),
map((result): DeriveBalancesAccount => calcBalances(api, result))
+54 -36
View File
@@ -1,21 +1,23 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
import type { Option, Vec } from '@polkadot/types';
import type { AccountId, AccountIndex, Address, Balance, BalanceLock, BalanceLockTo212, BlockNumber, VestingInfo, VestingSchedule } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveBalancesAccount, DeriveBalancesAll } from '../types';
import type { DeriveBalancesAccount, DeriveBalancesAccountData, DeriveBalancesAll, DeriveBalancesAllAccountData } from '../types';
import BN from 'bn.js';
import { bnMax, isFunction } from '@polkadot/util';
import { bnMax } from '@polkadot/util';
import { combineLatest, of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { memo } from '../util';
type ResultBalance = [VestingInfo | null, (BalanceLock | BalanceLockTo212)[]];
type BalanceLocksEntry = Vec<BalanceLock | BalanceLockTo212>;
type BalanceLocks = BalanceLocksEntry[];
type ResultBalance = [VestingInfo | null, ((BalanceLock | BalanceLockTo212)[])[]];
type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
interface AllLocked {
@@ -50,8 +52,21 @@ function calcLocked (api: ApiInterfaceRx, bestNumber: BlockNumber, locks: (Balan
return { allLocked, lockedBalance, lockedBreakdown, vestingLocked };
}
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll {
function calcShared (api: ApiInterfaceRx, bestNumber: BlockNumber, data: DeriveBalancesAccountData, locks: (BalanceLock | BalanceLockTo212)[]): DeriveBalancesAllAccountData {
const { allLocked, lockedBalance, lockedBreakdown, vestingLocked } = calcLocked(api, bestNumber, locks);
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), data.freeBalance.sub(lockedBalance)));
return {
...data,
availableBalance,
lockedBalance,
lockedBreakdown,
vestingLocked
};
}
function calcBalances (api: ApiInterfaceRx, [data, bestNumber, [vesting, allLocks]]: Result): DeriveBalancesAll {
const shared = calcShared(api, bestNumber, data, allLocks[0]);
// Calculate the vesting balances,
// - offset = balance locked at startingBlock
// - perBlock is the unlock amount
@@ -59,29 +74,21 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
const isStarted = bestNumber.gt(startingBlock);
const vestedNow = isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : new BN(0);
const vestedBalance = vestedNow.gt(vestingTotal) ? vestingTotal : api.registry.createType('Balance', vestedNow);
const isVesting = isStarted && !vestingLocked.isZero();
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)));
const isVesting = isStarted && !shared.vestingLocked.isZero();
const vestedClaimable = api.registry.createType('Balance', isVesting ? shared.vestingLocked.sub(vestingTotal.sub(vestedBalance)) : 0);
const vestingEndBlock = api.registry.createType('BlockNumber', isVesting ? vestingTotal.div(perBlock).add(startingBlock) : 0);
return {
accountId,
accountNonce,
availableBalance,
freeBalance,
frozenFee,
frozenMisc,
...shared,
accountId: data.accountId,
accountNonce: data.accountNonce,
additional: allLocks.filter((_, index) => index !== 0).map((l, index) => calcShared(api, bestNumber, data.additional[index], l)),
isVesting,
lockedBalance,
lockedBreakdown,
reservedBalance,
vestedBalance,
vestedClaimable,
vestingEndBlock,
vestingLocked,
vestingPerBlock: perBlock,
vestingTotal,
votingBalance
vestingTotal
};
}
@@ -100,28 +107,37 @@ function queryOld (api: ApiInterfaceRx, accountId: AccountId): Observable<Result
vestingNew = api.registry.createType('VestingInfo', { locked, perBlock, startingBlock });
}
return [vestingNew, locks];
return [vestingNew, [locks]];
})
);
}
// current (balances vesting)
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<ResultBalance> {
// current (balances, vesting)
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId, balanceInstances: string[] = ['balances']): Observable<ResultBalance> {
const lockCalls = balanceInstances.map((m) => api.query[m].locks);
const lockEmpty = lockCalls.map((c) => !c);
const lockQueries = lockCalls.filter((c) => c).map((c): QueryableStorageMultiArg<'rxjs'> => [c, accountId]);
return (
api.query.vesting?.vesting
? api.queryMulti<[Vec<BalanceLock>, Option<VestingInfo>]>([
[api.query.balances.locks, accountId],
[api.query.vesting.vesting, accountId]
? api.queryMulti<[Option<VestingInfo>, ...BalanceLocks]>([
[api.query.vesting.vesting, accountId],
...lockQueries
])
: api.query.balances.locks(accountId).pipe(
map((locks): [Vec<BalanceLock>, Option<VestingInfo>] =>
[locks, api.registry.createType('Option<VestingInfo>')]
// TODO We need to check module instances here as well, not only the balances module
: lockQueries.length
? api.queryMulti<[...(Vec<BalanceLock>)[]]>(lockQueries).pipe(
map((locks): [Option<VestingInfo>, ...BalanceLocks] =>
[api.registry.createType('Option<VestingInfo>'), ...locks]
)
)
)
: of([api.registry.createType('Option<VestingInfo>')] as [Option<VestingInfo>])
).pipe(
map(([locks, optVesting]): ResultBalance =>
[optVesting.unwrapOr(null), locks]
)
map(([optVesting, ...locks]): ResultBalance => {
let offset = -1;
return [optVesting.unwrapOr(null), lockEmpty.map((e) => e ? api.registry.createType('Vec<BalanceLock>') : locks[++offset])];
})
);
}
@@ -141,6 +157,8 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
* ```
*/
export function all (instanceId: string, api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAll> {
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances');
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAll> =>
api.derive.balances.account(address).pipe(
switchMap((account): Observable<Result> =>
@@ -148,11 +166,11 @@ export function all (instanceId: string, api: ApiInterfaceRx): (address: Account
? combineLatest([
of(account),
api.derive.chain.bestNumber(),
isFunction(api.query.system.account) || isFunction(api.query.balances.account)
? queryCurrent(api, account.accountId)
api.query.system?.account || api.query.balances?.account
? queryCurrent(api, account.accountId, balanceInstances)
: queryOld(api, account.accountId)
])
: of([account, api.registry.createType('BlockNumber'), [null, api.registry.createType('Vec<BalanceLock>')]])
: of([account, api.registry.createType('BlockNumber'), [null, []]])
)
),
map((result): DeriveBalancesAll => calcBalances(api, result))
@@ -59,7 +59,7 @@ describe('bounties derive', () => {
bountyDescriptions: {
multi: () => of([
optionOf(bytes('make polkadot even better')),
optionOf(bytes('this will be totally ignored'))
optionOf(bytes('some other bounty'))
])
}
}
@@ -117,6 +117,28 @@ describe('bounties derive', () => {
expect(result[1].proposals).toHaveLength(0);
});
it('when no council, returns bounties without motions', async () => {
const mockApi = {
...defaultMockApi,
query: {
...defaultMockApi.query,
council: null
}
} as unknown as ApiInterfaceRx;
const result = await bounties('', mockApi)().toPromise();
expect(result).toHaveLength(2);
expect(result[0].bounty.proposer.toString()).toEqual(DEFAULT_PROPOSER);
expect(result[0].description).toEqual('make polkadot even better');
expect(result[0].index.eq(0)).toBe(true);
expect(result[0].proposals).toHaveLength(0);
expect(result[1].bounty.proposer.toString()).toEqual(DEFAULT_PROPOSER);
expect(result[1].description).toEqual('some other bounty');
expect(result[1].index.eq(1)).toBe(true);
expect(result[1].proposals).toHaveLength(0);
});
it('combines bounties with motions', async () => {
const mockApi = {
...defaultMockApi,
+4 -4
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { DeriveBounties, DeriveCollectiveProposal } from '@polkadot/api-derive/types';
import type { Bytes, Option } from '@polkadot/types';
import type { Bytes, Option, StorageKey } from '@polkadot/types';
import type { Bounty, BountyIndex, ProposalIndex } from '@polkadot/types/interfaces';
import { memo } from '@polkadot/api-derive/util';
@@ -37,16 +37,16 @@ export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observ
return memo(instanceId, (): Observable<DeriveBounties> =>
combineLatest([
bountyBase.bountyCount<BountyIndex>(),
api.query.council.proposalCount<ProposalIndex>()
api.query.council ? api.query.council.proposalCount<ProposalIndex>() : of(0)
]).pipe(
switchMap(() =>
combineLatest([
bountyBase.bounties.keys(),
api.derive.council.proposals()
api.derive.council ? api.derive.council.proposals() : of([])
])
),
switchMap(([keys, proposals]): Observable<Result> => {
const ids = keys.map(({ args: [id] }) => id as BountyIndex);
const ids = (keys as StorageKey<[BountyIndex]>[]).map(({ args: [id] }) => id);
return combineLatest([
bountyBase.bounties.multi<Option<Bounty>>(ids),
@@ -51,7 +51,7 @@ function schedulerEntries (api: ApiInterfaceRx): Observable<[BlockNumber[], Opti
api.query.scheduler.agenda.keys()
),
switchMap((keys) => {
const blockNumbers = keys.map((key) => key.args[0] as BlockNumber);
const blockNumbers = keys.map((key) => key.args[0]);
return combineLatest([
of(blockNumbers),
@@ -69,7 +69,7 @@ function extractVotes (mapped: [AccountId, Voting][], referendumId: BN): DeriveR
function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> {
return api.query.democracy.votingOf.entries<Voting>().pipe(
map((allVoting): DeriveReferendumVote[] => {
const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0] as AccountId, voting]);
const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0], voting]);
const votes = extractVotes(mapped, referendumId);
const delegations = mapped
.filter(([, voting]) => voting.isDelegating)
+3 -1
View File
@@ -35,6 +35,7 @@ function queryAura (api: ApiInterfaceRx): Observable<DeriveSessionInfo> {
[
false,
api.registry.createType('u64', 1),
// we may have aura without staking (permissioned)
api.consts.staking?.sessionsPerEra || api.registry.createType('SessionIndex', 1)
],
indexes
@@ -50,7 +51,8 @@ function queryBabe (api: ApiInterfaceRx): Observable<DeriveSessionInfo> {
[
true,
api.consts.babe.epochDuration,
api.consts.staking.sessionsPerEra
// we may have babe without staking (permissioned)
api.consts.staking?.sessionsPerEra || api.registry.createType('SessionIndex', 1)
],
indexes
])
+16 -8
View File
@@ -12,6 +12,7 @@ import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { memo } from '../util';
type ResultSlotsNoSession = [u64, u64, u64];
type ResultSlots = [u64, u64, u64, Option<SessionIndex>];
type ResultSlotsFlat = [u64, u64, u64, SessionIndex];
@@ -39,19 +40,26 @@ function queryAura (api: ApiInterfaceRx): Observable<DeriveSessionProgress> {
function queryBabe (api: ApiInterfaceRx): Observable<[DeriveSessionInfo, ResultSlotsFlat]> {
return api.derive.session.info().pipe(
switchMap((info): Observable<[DeriveSessionInfo, ResultSlots]> =>
switchMap((info): Observable<[DeriveSessionInfo, ResultSlots | ResultSlotsNoSession]> =>
combineLatest([
of(info),
api.queryMulti<ResultSlots>([
api.query.babe.currentSlot,
api.query.babe.epochIndex,
api.query.babe.genesisSlot,
[api.query.staking.erasStartSessionIndex, info.activeEra]
])
// we may have no staking, but have babe (permissioned)
api.query.staking
? api.queryMulti<ResultSlots>([
api.query.babe.currentSlot,
api.query.babe.epochIndex,
api.query.babe.genesisSlot,
[api.query.staking.erasStartSessionIndex, info.activeEra]
])
: api.queryMulti<ResultSlotsNoSession>([
api.query.babe.currentSlot,
api.query.babe.epochIndex,
api.query.babe.genesisSlot
])
])
),
map(([info, [currentSlot, epochIndex, genesisSlot, optStartIndex]]): [DeriveSessionInfo, ResultSlotsFlat] => [
info, [currentSlot, epochIndex, genesisSlot, optStartIndex.unwrapOr(api.registry.createType('SessionIndex', 1))]
info, [currentSlot, epochIndex, genesisSlot, optStartIndex && optStartIndex.isSome ? optStartIndex.unwrap() : api.registry.createType('SessionIndex', 1)]
])
);
}
+1 -1
View File
@@ -15,7 +15,7 @@ import { memo } from '../util';
export function stashes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo(instanceId, (): Observable<AccountId[]> =>
api.query.staking.validators.keys().pipe(
map((keys) => keys.map((key) => key.args[0] as AccountId).filter((a) => a))
map((keys) => keys.map((key) => key.args[0]).filter((a) => a))
)
);
}
@@ -18,7 +18,7 @@ export function nextElected (instanceId: string, api: ApiInterfaceRx): () => Obs
// only populate for next era in the last session, so track both here - entries are not
// subscriptions, so we need a trigger - currentIndex acts as that trigger to refresh
switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)),
map((keys) => keys.map((key) => key.args[1] as AccountId))
map((keys) => keys.map((key) => key.args[1]))
)
: api.query.staking.currentElected<AccountId[]>()
);
+15 -8
View File
@@ -13,9 +13,7 @@ export * from './parachains/types';
export * from './session/types';
export * from './staking/types';
export interface DeriveBalancesAccount {
accountId: AccountId;
accountNonce: Index;
export interface DeriveBalancesAccountData {
freeBalance: Balance;
frozenFee: Balance;
frozenMisc: Balance;
@@ -23,16 +21,25 @@ export interface DeriveBalancesAccount {
votingBalance: Balance;
}
export interface DeriveBalancesAll extends DeriveBalancesAccount {
isVesting: boolean;
export interface DeriveBalancesAccount extends DeriveBalancesAccountData {
accountId: AccountId;
accountNonce: Index;
additional: DeriveBalancesAccountData[];
}
export interface DeriveBalancesAllAccountData extends DeriveBalancesAccountData {
availableBalance: Balance;
lockedBalance: Balance;
lockedBreakdown: (BalanceLock | BalanceLockTo212)[];
availableBalance: Balance;
votingBalance: Balance;
vestingLocked: Balance;
}
export interface DeriveBalancesAll extends DeriveBalancesAccount, DeriveBalancesAllAccountData {
additional: DeriveBalancesAllAccountData[];
isVesting: boolean;
vestedBalance: Balance;
vestedClaimable: Balance;
vestingEndBlock: BlockNumber;
vestingLocked: Balance;
vestingPerBlock: Balance;
vestingTotal: Balance;
}
+11 -12
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/api",
"version": "3.4.1",
"version": "3.6.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
"module": "index.mjs",
"sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
@@ -17,16 +16,16 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@polkadot/api-derive": "3.4.1",
"@polkadot/keyring": "^5.2.3",
"@polkadot/metadata": "3.4.1",
"@polkadot/rpc-core": "3.4.1",
"@polkadot/rpc-provider": "3.4.1",
"@polkadot/types": "3.4.1",
"@polkadot/types-known": "3.4.1",
"@polkadot/util": "^5.2.3",
"@polkadot/util-crypto": "^5.2.3",
"@polkadot/x-rxjs": "3.4.1",
"@polkadot/api-derive": "3.6.1",
"@polkadot/keyring": "^5.4.2",
"@polkadot/metadata": "3.6.1",
"@polkadot/rpc-core": "3.6.1",
"@polkadot/rpc-provider": "3.6.1",
"@polkadot/types": "3.6.1",
"@polkadot/types-known": "3.6.1",
"@polkadot/util": "^5.4.2",
"@polkadot/util-crypto": "^5.4.2",
"@polkadot/x-rxjs": "^5.4.2",
"bn.js": "^4.11.9",
"eventemitter3": "^4.0.7"
}
+66 -25
View File
@@ -3,11 +3,12 @@
import type { Vec, u16, u32, u64, u8 } from '@polkadot/types';
import type { Codec } from '@polkadot/types/types';
import type { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Perbill, Percent, Permill, RuntimeDbWeight } from '@polkadot/types/interfaces/runtime';
import type { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Perbill, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
import type { SessionIndex } from '@polkadot/types/interfaces/session';
import type { EraIndex } from '@polkadot/types/interfaces/staking';
import type { RuntimeVersion } from '@polkadot/types/interfaces/state';
import type { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
import type { BlockWeights } from '@polkadot/types/interfaces/system';
import type { BlockLength, BlockWeights } from '@polkadot/types/interfaces/system';
import type { ApiTypes } from '@polkadot/api/types';
declare module '@polkadot/api/types/consts' {
@@ -17,6 +18,9 @@ declare module '@polkadot/api/types/consts' {
/**
* The number of **slots** that an epoch takes. We couple sessions to
* epochs, i.e. we start a new session once the new epoch begins.
* NOTE: Currently it is not possible to change the epoch duration
* after the chain has started. Attempting to do so will brick block
* production.
**/
epochDuration: u64 & AugmentedConst<ApiType>;
/**
@@ -49,6 +53,10 @@ declare module '@polkadot/api/types/consts' {
* The delay period for which a bounty beneficiary need to wait before claim the payout.
**/
bountyDepositPayoutDelay: BlockNumber & AugmentedConst<ApiType>;
/**
* Bounty duration in blocks.
**/
bountyUpdatePeriod: BlockNumber & AugmentedConst<ApiType>;
/**
* Minimum value for a bounty.
**/
@@ -64,6 +72,40 @@ declare module '@polkadot/api/types/consts' {
};
contracts: {
[key: string]: Codec;
/**
* The maximum number of tries that can be queued for deletion.
**/
deletionQueueDepth: u32 & AugmentedConst<ApiType>;
/**
* The maximum amount of weight that can be consumed per block for lazy trie removal.
**/
deletionWeightLimit: Weight & AugmentedConst<ApiType>;
/**
* The balance every contract needs to deposit to stay alive indefinitely.
*
* This is different from the [`Self::TombstoneDeposit`] because this only needs to be
* deposited while the contract is alive. Costs for additional storage are added to
* this base cost.
*
* This is a simple way to ensure that contracts with empty storage eventually get deleted by
* making them pay rent. This creates an incentive to remove them early in order to save rent.
**/
depositPerContract: BalanceOf & AugmentedConst<ApiType>;
/**
* The balance a contract needs to deposit per storage byte to stay alive indefinitely.
*
* Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day,
* then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent.
* But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000,
* then it would pay 500 BU/day.
**/
depositPerStorageByte: BalanceOf & AugmentedConst<ApiType>;
/**
* The balance a contract needs to deposit per storage item to stay alive indefinitely.
*
* It works the same as [`Self::DepositPerStorageByte`] but for storage items.
**/
depositPerStorageItem: BalanceOf & AugmentedConst<ApiType>;
/**
* The maximum nesting level of a call/instantiate stack. A reasonable default
* value is 100.
@@ -74,19 +116,13 @@ declare module '@polkadot/api/types/consts' {
**/
maxValueSize: u32 & AugmentedConst<ApiType>;
/**
* Price of a byte of storage per one block interval. Should be greater than 0.
**/
rentByteFee: BalanceOf & AugmentedConst<ApiType>;
/**
* The amount of funds a contract should deposit in order to offset
* the cost of one byte.
* The fraction of the deposit that should be used as rent per block.
*
* Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day,
* then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent.
* But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000,
* then it would pay 500 BU/day.
* When a contract hasn't enough balance deposited to stay alive indefinitely it needs
* to pay per block for the storage it consumes that is not covered by the deposit.
* This determines how high this rent payment is per block as a fraction of the deposit.
**/
rentDepositOffset: BalanceOf & AugmentedConst<ApiType>;
rentFraction: Perbill & AugmentedConst<ApiType>;
/**
* Number of block delay an extrinsic claim surcharge has.
*
@@ -94,15 +130,6 @@ declare module '@polkadot/api/types/consts' {
* for current_block - delay
**/
signedClaimHandicap: BlockNumber & AugmentedConst<ApiType>;
/**
* A size offset for an contract. A just created account with untouched storage will have that
* much of storage from the perspective of the state rent.
*
* This is a simple way to ensure that contracts with empty storage eventually get deleted
* by making them pay rent. This creates an incentive to remove them early in order to save
* rent.
**/
storageSizeOffset: u32 & AugmentedConst<ApiType>;
/**
* Reward that is received by the party whose touch has led
* to removal of a contract.
@@ -159,7 +186,8 @@ declare module '@polkadot/api/types/consts' {
desiredRunnersUp: u32 & AugmentedConst<ApiType>;
moduleId: LockIdentifier & AugmentedConst<ApiType>;
termDuration: BlockNumber & AugmentedConst<ApiType>;
votingBond: BalanceOf & AugmentedConst<ApiType>;
votingBondBase: BalanceOf & AugmentedConst<ApiType>;
votingBondFactor: BalanceOf & AugmentedConst<ApiType>;
};
identity: {
[key: string]: Codec;
@@ -199,6 +227,11 @@ declare module '@polkadot/api/types/consts' {
**/
deposit: BalanceOf & AugmentedConst<ApiType>;
};
lottery: {
[key: string]: Codec;
maxCalls: u32 & AugmentedConst<ApiType>;
moduleId: ModuleId & AugmentedConst<ApiType>;
};
multisig: {
[key: string]: Codec;
/**
@@ -343,11 +376,15 @@ declare module '@polkadot/api/types/consts' {
system: {
[key: string]: Codec;
/**
* The maximum number of blocks to allow in mortal eras.
* Maximum number of block number to block hash mappings to keep (oldest pruned first).
**/
blockHashCount: BlockNumber & AugmentedConst<ApiType>;
/**
* The weight configuration (limits & base values) for each class of extrinsics and block.
* The maximum length of a block (in bytes).
**/
blockLength: BlockLength & AugmentedConst<ApiType>;
/**
* Block & extrinsics weights: base values and limits.
**/
blockWeights: BlockWeights & AugmentedConst<ApiType>;
/**
@@ -362,6 +399,10 @@ declare module '@polkadot/api/types/consts' {
* an identifier of the chain.
**/
ss58Prefix: u8 & AugmentedConst<ApiType>;
/**
* Get the chain's current version.
**/
version: RuntimeVersion & AugmentedConst<ApiType>;
};
timestamp: {
[key: string]: Codec;
+61 -5
View File
@@ -11,6 +11,14 @@ declare module '@polkadot/api/types/errors' {
* Transfer amount should be non-zero.
**/
AmountZero: AugmentedError<ApiType>;
/**
* Invalid metadata given.
**/
BadMetadata: AugmentedError<ApiType>;
/**
* Some internal state is broken.
**/
BadState: AugmentedError<ApiType>;
/**
* Invalid witness data given.
**/
@@ -179,6 +187,13 @@ declare module '@polkadot/api/types/errors' {
* The code supplied to `put_code` exceeds the limit specified in the current schedule.
**/
CodeTooLarge: AugmentedError<ApiType>;
/**
* A contract could not be evicted because it has enough balance to pay rent.
*
* This can be returned from [`Module::claim_surcharge`] because the target
* contract has enough balance to pay for its rent.
**/
ContractNotEvictable: AugmentedError<ApiType>;
/**
* Contract trapped during execution.
**/
@@ -187,6 +202,14 @@ declare module '@polkadot/api/types/errors' {
* Input passed to a contract API function failed to decode as expected type.
**/
DecodingFailed: AugmentedError<ApiType>;
/**
* Removal of a contract failed because the deletion queue is full.
*
* This can happen when either calling [`Module::claim_surcharge`] or `seal_terminate`.
* The queue is filled by deleting contracts and emptied by a fixed amount each block.
* Trying again during another block is the only way to resolve this issue.
**/
DeletionQueueFull: AugmentedError<ApiType>;
/**
* The topics passed to `seal_deposit_events` contains at least one duplicate.
**/
@@ -229,6 +252,12 @@ declare module '@polkadot/api/types/errors' {
* its contructor. No contracts are allowed to exist below that threshold.
**/
NewContractNotFunded: AugmentedError<ApiType>;
/**
* The chain does not provide a chain extension. Calling the chain extension results
* in this error. Note that this usually shouldn't happen as deploying such contracts
* is rejected.
**/
NoChainExtension: AugmentedError<ApiType>;
/**
* The contract that was called is either no contract at all (a plain account)
* or is a tombstone.
@@ -256,6 +285,13 @@ declare module '@polkadot/api/types/errors' {
* of a tombstone.
**/
ReentranceDenied: AugmentedError<ApiType>;
/**
* A storage modification exhausted the 32bit type that holds the storage size.
*
* This can either happen when the accumulated storage in bytes is too large or
* when number of storage items is too large.
**/
StorageExhausted: AugmentedError<ApiType>;
/**
* The amount of topics passed to `seal_deposit_events` exceeds the limit.
**/
@@ -468,10 +504,6 @@ declare module '@polkadot/api/types/errors' {
* Candidate does not have enough funds.
**/
InsufficientCandidateFunds: AugmentedError<ApiType>;
/**
* The provided count of number of candidates is incorrect.
**/
InvalidCandidateCount: AugmentedError<ApiType>;
/**
* The renouncing origin presented a wrong `Renouncing` parameter.
**/
@@ -484,6 +516,10 @@ declare module '@polkadot/api/types/errors' {
* The provided count of number of votes is incorrect.
**/
InvalidVoteCount: AugmentedError<ApiType>;
/**
* The provided count of number of candidates is incorrect.
**/
InvalidWitnessData: AugmentedError<ApiType>;
/**
* Cannot vote with stake less than minimum balance.
**/
@@ -515,7 +551,7 @@ declare module '@polkadot/api/types/errors' {
/**
* Runner cannot re-submit candidacy.
**/
RunnerSubmit: AugmentedError<ApiType>;
RunnerUpSubmit: AugmentedError<ApiType>;
/**
* Cannot vote more than candidates.
**/
@@ -752,6 +788,10 @@ declare module '@polkadot/api/types/errors' {
* This user has already vouched for this recovery
**/
AlreadyVouched: AugmentedError<ApiType>;
/**
* Some internal state is broken.
**/
BadState: AugmentedError<ApiType>;
/**
* The friend must wait until the delay period to vouch for this recovery
**/
@@ -830,6 +870,10 @@ declare module '@polkadot/api/types/errors' {
* Invalid ownership proof.
**/
InvalidProof: AugmentedError<ApiType>;
/**
* Key setting account is not live, so it's impossible to associate keys.
**/
NoAccount: AugmentedError<ApiType>;
/**
* No associated validator ID for account.
**/
@@ -928,6 +972,14 @@ declare module '@polkadot/api/types/errors' {
* Controller is already paired.
**/
AlreadyPaired: AugmentedError<ApiType>;
/**
* Internal state has become somehow corrupted and the operation cannot continue.
**/
BadState: AugmentedError<ApiType>;
/**
* A nomination target was supplied that was blocked or otherwise not a validator.
**/
BadTarget: AugmentedError<ApiType>;
/**
* The call is not allowed at the given time due to restrictions of election period.
**/
@@ -1043,6 +1095,10 @@ declare module '@polkadot/api/types/errors' {
* The snapshot data of the current window is missing.
**/
SnapshotUnavailable: AugmentedError<ApiType>;
/**
* Too many nomination targets supplied.
**/
TooManyTargets: AugmentedError<ApiType>;
};
sudo: {
[key: string]: AugmentedError<ApiType>;
+46 -12
View File
@@ -1,7 +1,7 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { Bytes, Option, Vec, bool, u16, u32 } from '@polkadot/types';
import type { Bytes, Option, Vec, bool, u16, u32, u8 } from '@polkadot/types';
import type { ITuple } from '@polkadot/types/types';
import type { TAssetBalance } from '@polkadot/types/interfaces/assets';
import type { BalanceStatus } from '@polkadot/types/interfaces/balances';
@@ -11,6 +11,7 @@ import type { PropIndex, ReferendumIndex } from '@polkadot/types/interfaces/demo
import type { VoteThreshold } from '@polkadot/types/interfaces/elections';
import type { AuthorityList } from '@polkadot/types/interfaces/grandpa';
import type { RegistrarIndex } from '@polkadot/types/interfaces/identity';
import type { CallIndex } from '@polkadot/types/interfaces/lottery';
import type { Kind, OpaqueTimeSlot } from '@polkadot/types/interfaces/offences';
import type { ProxyType } from '@polkadot/types/interfaces/proxy';
import type { AccountId, AccountIndex, AssetId, Balance, BlockNumber, CallHash, Hash, PhantomData } from '@polkadot/types/interfaces/runtime';
@@ -26,6 +27,14 @@ declare module '@polkadot/api/types/events' {
export interface AugmentedEvents<ApiType> {
assets: {
[key: string]: AugmentedEvent<ApiType>;
/**
* Some asset `asset_id` was frozen. \[asset_id\]
**/
AssetFrozen: AugmentedEvent<ApiType, [AssetId]>;
/**
* Some asset `asset_id` was thawed. \[asset_id\]
**/
AssetThawed: AugmentedEvent<ApiType, [AssetId]>;
/**
* Some assets were destroyed. \[asset_id, owner, balance\]
**/
@@ -58,6 +67,10 @@ declare module '@polkadot/api/types/events' {
* The maximum amount of zombies allowed has changed. \[asset_id, max_zombies\]
**/
MaxZombiesChanged: AugmentedEvent<ApiType, [AssetId, u32]>;
/**
* New metadata has been set for an asset. \[asset_id, name, symbol, decimals\]
**/
MetadataSet: AugmentedEvent<ApiType, [AssetId, Bytes, Bytes, u8]>;
/**
* The owner changed \[asset_id, owner\]
**/
@@ -309,7 +322,10 @@ declare module '@polkadot/api/types/events' {
elections: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A candidate was slashed due to failing to obtain a seat as member or runner-up
* A \[candidate\] was slashed by \[amount\] due to failing to obtain a seat as member or
* runner-up.
*
* Note that old members and runners-up are also candidates.
**/
CandidateSlashed: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
@@ -326,10 +342,6 @@ declare module '@polkadot/api/types/events' {
* `EmptyTerm`.
**/
MemberKicked: AugmentedEvent<ApiType, [AccountId]>;
/**
* A \[member\] has renounced their candidacy.
**/
MemberRenounced: AugmentedEvent<ApiType, [AccountId]>;
/**
* A new term with \[new_members\]. This indicates that enough candidates existed to run the
* election, not that enough have has been elected. The inner value must be examined for
@@ -338,14 +350,13 @@ declare module '@polkadot/api/types/events' {
**/
NewTerm: AugmentedEvent<ApiType, [Vec<ITuple<[AccountId, Balance]>>]>;
/**
* A seat holder (member or runner-up) was slashed due to failing to retaining their position.
* Someone has renounced their candidacy.
**/
Renounced: AugmentedEvent<ApiType, [AccountId]>;
/**
* A \[seat holder\] was slashed by \[amount\] by being forcefully removed from the set.
**/
SeatHolderSlashed: AugmentedEvent<ApiType, [AccountId, Balance]>;
/**
* A voter was reported with the the report being successful or not.
* \[voter, reporter, success\]
**/
VoterReported: AugmentedEvent<ApiType, [AccountId, AccountId, bool]>;
};
grandpa: {
[key: string]: AugmentedEvent<ApiType>;
@@ -437,6 +448,25 @@ declare module '@polkadot/api/types/events' {
**/
IndexFrozen: AugmentedEvent<ApiType, [AccountIndex, AccountId]>;
};
lottery: {
[key: string]: AugmentedEvent<ApiType>;
/**
* A new set of calls have been set!
**/
CallsUpdated: AugmentedEvent<ApiType, []>;
/**
* A lottery has been started!
**/
LotteryStarted: AugmentedEvent<ApiType, []>;
/**
* A ticket has been bought!
**/
TicketBought: AugmentedEvent<ApiType, [AccountId, CallIndex]>;
/**
* A winner has been chosen!
**/
Winner: AugmentedEvent<ApiType, [AccountId, Balance]>;
};
multisig: {
[key: string]: AugmentedEvent<ApiType>;
/**
@@ -622,6 +652,10 @@ declare module '@polkadot/api/types/events' {
* \[era_index, validator_payout, remainder\]
**/
EraPayout: AugmentedEvent<ApiType, [EraIndex, Balance, Balance]>;
/**
* A nominator has been kicked from a validator. \[nominator, stash\]
**/
Kicked: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/**
* An old slashing report from a prior era was discarded because it could
* not be processed. \[session_index\]
+71 -13
View File
@@ -3,18 +3,19 @@
import type { Bytes, Data, Option, U8aFixed, Vec, bool, u32, u64 } from '@polkadot/types';
import type { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
import type { AssetBalance, AssetDetails } from '@polkadot/types/interfaces/assets';
import type { AssetBalance, AssetDetails, AssetMetadata } from '@polkadot/types/interfaces/assets';
import type { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
import type { BabeAuthorityWeight, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
import type { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
import type { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { CodeHash, ContractInfo, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
import type { CodeHash, ContractInfo, DeletedContract, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
import type { PreimageStatus, PropIndex, Proposal, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy';
import type { VoteThreshold } from '@polkadot/types/interfaces/elections';
import type { SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import type { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity';
import type { AuthIndex } from '@polkadot/types/interfaces/imOnline';
import type { CallIndex, LotteryConfig } from '@polkadot/types/interfaces/lottery';
import type { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy';
import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
@@ -22,7 +23,7 @@ import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber,
import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import type { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import type { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, RewardDestination, SeatHolder, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs, Voter } from '@polkadot/types/interfaces/staking';
import type { AccountInfo, ConsumedWeight, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system';
import type { Bounty, BountyIndex, OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import type { Multiplier } from '@polkadot/types/interfaces/txpayment';
@@ -42,6 +43,10 @@ declare module '@polkadot/api/types/storage' {
* Details of an asset.
**/
asset: AugmentedQuery<ApiType, (arg: AssetId | AnyNumber | Uint8Array) => Observable<Option<AssetDetails>>, [AssetId]> & QueryableStorageEntry<ApiType, [AssetId]>;
/**
* Metadata of an asset.
**/
metadata: AugmentedQuery<ApiType, (arg: AssetId | AnyNumber | Uint8Array) => Observable<AssetMetadata>, [AssetId]> & QueryableStorageEntry<ApiType, [AssetId]>;
};
authorship: {
[key: string]: QueryableStorageEntry<ApiType>;
@@ -96,6 +101,10 @@ declare module '@polkadot/api/types/storage' {
* execution context should always yield zero.
**/
lateness: AugmentedQuery<ApiType, () => Observable<BlockNumber>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Next epoch authorities.
**/
nextAuthorities: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AuthorityId, BabeAuthorityWeight]>>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Next epoch configuration, if changed.
**/
@@ -197,6 +206,13 @@ declare module '@polkadot/api/types/storage' {
* Current cost schedule for contracts.
**/
currentSchedule: AugmentedQuery<ApiType, () => Observable<Schedule>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Evicted contracts that await child trie deletion.
*
* Child trie deletion is a heavy operation depending on the amount of storage items
* stored in said trie. Therefore this operation is performed lazily in `on_initialize`.
**/
deletionQueue: AugmentedQuery<ApiType, () => Observable<Vec<DeletedContract>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* A mapping from an original code hash to the original code, untouched by instrumentation.
**/
@@ -310,28 +326,37 @@ declare module '@polkadot/api/types/storage' {
elections: {
[key: string]: QueryableStorageEntry<ApiType>;
/**
* The present candidate list. Sorted based on account-id. A current member or runner-up
* can never enter this vector and is always implicitly assumed to be a candidate.
* The present candidate list. A current member or runner-up can never enter this vector
* and is always implicitly assumed to be a candidate.
*
* Second element is the deposit.
*
* Invariant: Always sorted based on account id.
**/
candidates: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>, []> & QueryableStorageEntry<ApiType, []>;
candidates: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The total number of vote rounds that have happened, excluding the upcoming one.
**/
electionRounds: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The current elected membership. Sorted based on account id.
* The current elected members.
*
* Invariant: Always sorted based on account id.
**/
members: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>, []> & QueryableStorageEntry<ApiType, []>;
members: AugmentedQuery<ApiType, () => Observable<Vec<SeatHolder>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The current runners_up. Sorted based on low to high merit (worse to best).
* The current reserved runners-up.
*
* Invariant: Always sorted based on rank (worse to best). Upon removal of a member, the
* last (i.e. _best_) runner-up will be replaced.
**/
runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>, []> & QueryableStorageEntry<ApiType, []>;
runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<SeatHolder>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Votes and locked stake of a particular voter.
*
* TWOX-NOTE: SAFE as `AccountId` is a crypto hash
* TWOX-NOTE: SAFE as `AccountId` is a crypto hash.
**/
voting: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
voting: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voter>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
};
grandpa: {
[key: string]: QueryableStorageEntry<ApiType>;
@@ -426,6 +451,34 @@ declare module '@polkadot/api/types/storage' {
**/
accounts: AugmentedQuery<ApiType, (arg: AccountIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[AccountId, BalanceOf, bool]>>>, [AccountIndex]> & QueryableStorageEntry<ApiType, [AccountIndex]>;
};
lottery: {
[key: string]: QueryableStorageEntry<ApiType>;
/**
* The calls stored in this pallet to be used in an active lottery if configured
* by `Config::ValidateCall`.
**/
callIndices: AugmentedQuery<ApiType, () => Observable<Vec<CallIndex>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The configuration for the current lottery.
**/
lottery: AugmentedQuery<ApiType, () => Observable<Option<LotteryConfig>>, []> & QueryableStorageEntry<ApiType, []>;
lotteryIndex: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Users who have purchased a ticket. (Lottery Index, Tickets Purchased)
**/
participants: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[u32, Vec<CallIndex>]>>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
/**
* Each ticket's owner.
*
* May have residual storage from previous lotteries. Use `TicketsCount` to see which ones
* are actually valid ticket mappings.
**/
tickets: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<AccountId>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
/**
* Total number of tickets sold.
**/
ticketsCount: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
};
mmr: {
[key: string]: QueryableStorageEntry<ApiType>;
/**
@@ -817,7 +870,7 @@ declare module '@polkadot/api/types/storage' {
* True if network has been upgraded to this version.
* Storage version of the pallet.
*
* This is set to v3.0.0 for new networks.
* This is set to v5.0.0 for new networks.
**/
storageVersion: AugmentedQuery<ApiType, () => Observable<Releases>, []> & QueryableStorageEntry<ApiType, []>;
/**
@@ -912,6 +965,11 @@ declare module '@polkadot/api/types/storage' {
* Hash of the previous block.
**/
parentHash: AugmentedQuery<ApiType, () => Observable<Hash>, []> & QueryableStorageEntry<ApiType, []>;
/**
* True if we have upgraded so that AccountInfo contains two types of `RefCount`. False
* (default) if not.
**/
upgradedToDualRefCount: AugmentedQuery<ApiType, () => Observable<bool>, []> & QueryableStorageEntry<ApiType, []>;
/**
* True if we have upgraded so that `type RefCount` is `u32`. False (default) if not.
**/
+5 -1
View File
@@ -15,7 +15,7 @@ import type { EthAccount, EthCallRequest, EthFilter, EthLog, EthReceipt, EthRich
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
import type { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { RpcMethods } from '@polkadot/types/interfaces/rpc';
import type { AccountId, BlockNumber, H160, H256, H64, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import type { ReadProof, RuntimeVersion } from '@polkadot/types/interfaces/state';
@@ -316,6 +316,10 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
localStorageSet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
};
payment: {
/**
* Query the detailed fee of a given encoded extrinsic
**/
queryFeeDetails: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<FeeDetails>>;
/**
* Retrieves the fee information for an encoded extrinsic
**/
+190 -130
View File
@@ -1,14 +1,14 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { Bytes, Compact, Data, Option, U8aFixed, Vec, bool, u16, u32, u64 } from '@polkadot/types';
import type { Bytes, Compact, Data, Option, U8aFixed, Vec, bool, u16, u32, u64, u8 } from '@polkadot/types';
import type { AnyNumber, ITuple } from '@polkadot/types/types';
import type { TAssetBalance } from '@polkadot/types/interfaces/assets';
import type { BabeEquivocationProof } from '@polkadot/types/interfaces/babe';
import type { MemberCount, ProposalIndex } from '@polkadot/types/interfaces/collective';
import type { CodeHash, Gas, Schedule } from '@polkadot/types/interfaces/contracts';
import type { AccountVote, Conviction, PropIndex, Proposal, ReferendumIndex } from '@polkadot/types/interfaces/democracy';
import type { DefunctVoter, Renouncing } from '@polkadot/types/interfaces/elections';
import type { Renouncing } from '@polkadot/types/interfaces/elections';
import type { Extrinsic, Signature } from '@polkadot/types/interfaces/extrinsics';
import type { GrandpaEquivocationProof, KeyOwnerProof } from '@polkadot/types/interfaces/grandpa';
import type { IdentityFields, IdentityInfo, IdentityJudgement, RegistrarIndex } from '@polkadot/types/interfaces/identity';
@@ -158,6 +158,18 @@ declare module '@polkadot/api/types/submittable' {
* Weight: `O(1)`
**/
freeze: AugmentedSubmittable<(id: Compact<AssetId> | AnyNumber | Uint8Array, who: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<AssetId>, LookupSource]>;
/**
* Disallow further unprivileged transfers for the asset class.
*
* Origin must be Signed and the sender should be the Freezer of the asset `id`.
*
* - `id`: The identifier of the asset to be frozen.
*
* Emits `Frozen`.
*
* Weight: `O(1)`
**/
freezeAsset: AugmentedSubmittable<(id: Compact<AssetId> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<AssetId>]>;
/**
* Mint assets of a particular class.
*
@@ -173,7 +185,46 @@ declare module '@polkadot/api/types/submittable' {
* Modes: Pre-existing balance of `beneficiary`; Account pre-existence of `beneficiary`.
**/
mint: AugmentedSubmittable<(id: Compact<AssetId> | AnyNumber | Uint8Array, beneficiary: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, amount: Compact<TAssetBalance> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<AssetId>, LookupSource, Compact<TAssetBalance>]>;
/**
* Set the maximum number of zombie accounts for an asset.
*
* Origin must be Signed and the sender should be the Owner of the asset `id`.
*
* Funds of sender are reserved according to the formula:
* `AssetDepositBase + AssetDepositPerZombie * max_zombies` taking into account
* any already reserved funds.
*
* - `id`: The identifier of the asset to update zombie count.
* - `max_zombies`: The new number of zombies allowed for this asset.
*
* Emits `MaxZombiesChanged`.
*
* Weight: `O(1)`
**/
setMaxZombies: AugmentedSubmittable<(id: Compact<AssetId> | AnyNumber | Uint8Array, maxZombies: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<AssetId>, Compact<u32>]>;
/**
* Set the metadata for an asset.
*
* NOTE: There is no `unset_metadata` call. Simply pass an empty name, symbol,
* and 0 decimals to this function to remove the metadata of an asset and
* return your deposit.
*
* Origin must be Signed and the sender should be the Owner of the asset `id`.
*
* Funds of sender are reserved according to the formula:
* `MetadataDepositBase + MetadataDepositPerByte * (name.len + symbol.len)` taking into
* account any already reserved funds.
*
* - `id`: The identifier of the asset to update.
* - `name`: The user friendly name of this asset. Limited in length by `StringLimit`.
* - `symbol`: The exchange symbol for this asset. Limited in length by `StringLimit`.
* - `decimals`: The number of decimals this asset uses to represent one unit.
*
* Emits `MaxZombiesChanged`.
*
* Weight: `O(1)`
**/
setMetadata: AugmentedSubmittable<(id: Compact<AssetId> | AnyNumber | Uint8Array, name: Bytes | string | Uint8Array, symbol: Bytes | string | Uint8Array, decimals: u8 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<AssetId>, Bytes, Bytes, u8]>;
/**
* Change the Issuer, Admin and Freezer of an asset.
*
@@ -202,6 +253,18 @@ declare module '@polkadot/api/types/submittable' {
* Weight: `O(1)`
**/
thaw: AugmentedSubmittable<(id: Compact<AssetId> | AnyNumber | Uint8Array, who: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<AssetId>, LookupSource]>;
/**
* Allow unprivileged transfers for the asset again.
*
* Origin must be Signed and the sender should be the Admin of the asset `id`.
*
* - `id`: The identifier of the asset to be frozen.
*
* Emits `Thawed`.
*
* Weight: `O(1)`
**/
thawAsset: AugmentedSubmittable<(id: Compact<AssetId> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<AssetId>]>;
/**
* Move some assets from the sender account to another.
*
@@ -477,11 +540,15 @@ declare module '@polkadot/api/types/submittable' {
**/
call: AugmentedSubmittable<(dest: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, value: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, data: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [LookupSource, Compact<BalanceOf>, Compact<Gas>, Bytes]>;
/**
* Allows block producers to claim a small reward for evicting a contract. If a block producer
* fails to do so, a regular users will be allowed to claim the reward.
* Allows block producers to claim a small reward for evicting a contract. If a block
* producer fails to do so, a regular users will be allowed to claim the reward.
*
* If contract is not evicted as a result of this call, no actions are taken and
* the sender is not eligible for the reward.
* In case of a successful eviction no fees are charged from the sender. However, the
* reward is capped by the total amount of rent that was payed by the contract while
* it was alive.
*
* If contract is not evicted as a result of this call, [`Error::ContractNotEvictable`]
* is returned and the sender is not eligible for the reward.
**/
claimSurcharge: AugmentedSubmittable<(dest: AccountId | string | Uint8Array, auxSender: Option<AccountId> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId, Option<AccountId>]>;
/**
@@ -986,6 +1053,19 @@ declare module '@polkadot/api/types/submittable' {
};
elections: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
/**
* Clean all voters who are defunct (i.e. they do not serve any purpose at all). The
* deposit of the removed voters are returned.
*
* This is an root function to be used only for cleaning the state.
*
* The dispatch origin of this call must be root.
*
* # <weight>
* The total number of voters and those that are defunct must be provided as witness data.
* # </weight>
**/
cleanDefunctVoters: AugmentedSubmittable<(numVoters: u32 | AnyNumber | Uint8Array, numDefunct: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32]>;
/**
* Remove a particular member from the set. This is effective immediately and the bond of
* the outgoing member is slashed.
@@ -993,125 +1073,59 @@ declare module '@polkadot/api/types/submittable' {
* If a runner-up is available, then the best runner-up will be removed and replaces the
* outgoing member. Otherwise, a new phragmen election is started.
*
* The dispatch origin of this call must be root.
*
* Note that this does not affect the designated block number of the next election.
*
* # <weight>
* If we have a replacement:
* - Base weight: 50.93 µs
* - State reads:
* - RunnersUp.len()
* - Members, RunnersUp (remove_and_replace_member)
* - State writes:
* - Members, RunnersUp (remove_and_replace_member)
* Else, since this is a root call and will go into phragmen, we assume full block for now.
* If we have a replacement, we use a small weight. Else, since this is a root call and
* will go into phragmen, we assume full block for now.
* # </weight>
**/
removeMember: AugmentedSubmittable<(who: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, hasReplacement: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [LookupSource, bool]>;
/**
* Remove `origin` as a voter. This removes the lock and returns the bond.
* Remove `origin` as a voter.
*
* # <weight>
* Base weight: 36.8 µs
* All state access is from do_remove_voter.
* State reads:
* - Voting
* - [AccountData(who)]
* State writes:
* - Voting
* - Locks
* - [AccountData(who)]
* # </weight>
* This removes the lock and returns the deposit.
*
* The dispatch origin of this call must be signed and be a voter.
**/
removeVoter: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
/**
* Renounce one's intention to be a candidate for the next election round. 3 potential
* outcomes exist:
* - `origin` is a candidate and not elected in any set. In this case, the bond is
*
* - `origin` is a candidate and not elected in any set. In this case, the deposit is
* unreserved, returned and origin is removed as a candidate.
* - `origin` is a current runner-up. In this case, the bond is unreserved, returned and
* - `origin` is a current runner-up. In this case, the deposit is unreserved, returned and
* origin is removed as a runner-up.
* - `origin` is a current member. In this case, the bond is unreserved and origin is
* - `origin` is a current member. In this case, the deposit is unreserved and origin is
* removed as a member, consequently not being a candidate for the next round anymore.
* Similar to [`remove_voter`], if replacement runners exists, they are immediately used.
* <weight>
* If a candidate is renouncing:
* Base weight: 17.28 µs
* Complexity of candidate_count: 0.235 µs
* State reads:
* - Candidates
* - [AccountBalance(who) (unreserve)]
* State writes:
* - Candidates
* - [AccountBalance(who) (unreserve)]
* If member is renouncing:
* Base weight: 46.25 µs
* State reads:
* - Members, RunnersUp (remove_and_replace_member),
* - [AccountData(who) (unreserve)]
* State writes:
* - Members, RunnersUp (remove_and_replace_member),
* - [AccountData(who) (unreserve)]
* If runner is renouncing:
* Base weight: 46.25 µs
* State reads:
* - RunnersUp (remove_and_replace_member),
* - [AccountData(who) (unreserve)]
* State writes:
* - RunnersUp (remove_and_replace_member),
* - [AccountData(who) (unreserve)]
* </weight>
* Similar to [`remove_members`], if replacement runners exists, they are immediately used.
* If the prime is renouncing, then no prime will exist until the next round.
*
* The dispatch origin of this call must be signed, and have one of the above roles.
*
* # <weight>
* The type of renouncing must be provided as witness data.
* # </weight>
**/
renounceCandidacy: AugmentedSubmittable<(renouncing: Renouncing | { Member: any } | { RunnerUp: any } | { Candidate: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Renouncing]>;
/**
* Report `target` for being an defunct voter. In case of a valid report, the reporter is
* rewarded by the bond amount of `target`. Otherwise, the reporter itself is removed and
* their bond is slashed.
* Submit oneself for candidacy. A fixed amount of deposit is recorded.
*
* A defunct voter is defined to be:
* - a voter whose current submitted votes are all invalid. i.e. all of them are no
* longer a candidate nor an active member or a runner-up.
* All candidates are wiped at the end of the term. They either become a member/runner-up,
* or leave the system while their deposit is slashed.
*
* The dispatch origin of this call must be signed.
*
* The origin must provide the number of current candidates and votes of the reported target
* for the purpose of accurate weight calculation.
* ### Warning
*
* Even if a candidate ends up being a member, they must call [`Call::renounce_candidacy`]
* to get their deposit back. Losing the spot in an election will always lead to a slash.
*
* # <weight>
* No Base weight based on min square analysis.
* Complexity of candidate_count: 1.755 µs
* Complexity of vote_count: 18.51 µs
* State reads:
* - Voting(reporter)
* - Candidate.len()
* - Voting(Target)
* - Candidates, Members, RunnersUp (is_defunct_voter)
* State writes:
* - Lock(reporter || target)
* - [AccountBalance(reporter)] + AccountBalance(target)
* - Voting(reporter || target)
* Note: the db access is worse with respect to db, which is when the report is correct.
* # </weight>
**/
reportDefunctVoter: AugmentedSubmittable<(defunct: DefunctVoter | { who?: any; voteCount?: any; candidateCount?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [DefunctVoter]>;
/**
* Submit oneself for candidacy.
*
* A candidate will either:
* - Lose at the end of the term and forfeit their deposit.
* - Win and become a member. Members will eventually get their stash back.
* - Become a runner-up. Runners-ups are reserved members in case one gets forcefully
* removed.
*
* # <weight>
* Base weight = 33.33 µs
* Complexity of candidate_count: 0.375 µs
* State reads:
* - Candidates
* - Members
* - RunnersUp
* - [AccountBalance(who)]
* State writes:
* - [AccountBalance(who)]
* - Candidates
* The number of current candidates must be provided as witness data.
* # </weight>
**/
submitCandidacy: AugmentedSubmittable<(candidateCount: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>]>;
@@ -1119,28 +1133,25 @@ declare module '@polkadot/api/types/submittable' {
* Vote for a set of candidates for the upcoming round of election. This can be called to
* set the initial votes, or update already existing votes.
*
* Upon initial voting, `value` units of `who`'s balance is locked and a bond amount is
* reserved.
* Upon initial voting, `value` units of `who`'s balance is locked and a deposit amount is
* reserved. The deposit is based on the number of votes and can be updated over time.
*
* The `votes` should:
* - not be empty.
* - be less than the number of possible candidates. Note that all current members and
* runners-up are also automatically candidates for the next round.
*
* It is the responsibility of the caller to not place all of their balance into the lock
* and keep some for further transactions.
* If `value` is more than `who`'s total balance, then the maximum of the two is used.
*
* The dispatch origin of this call must be signed.
*
* ### Warning
*
* It is the responsibility of the caller to **NOT** place all of their balance into the
* lock and keep some for further operations.
*
* # <weight>
* Base weight: 47.93 µs
* State reads:
* - Candidates.len() + Members.len() + RunnersUp.len()
* - Voting (is_voter)
* - Lock
* - [AccountBalance(who) (unreserve + total_balance)]
* State writes:
* - Voting
* - Lock
* - [AccountBalance(who) (unreserve -- only when creating a new voter)]
* We assume the maximum weight among all 3 cases: vote_equal, vote_more and vote_less.
* # </weight>
**/
vote: AugmentedSubmittable<(votes: Vec<AccountId> | (AccountId | string | Uint8Array)[], value: Compact<BalanceOf> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Vec<AccountId>, Compact<BalanceOf>]>;
@@ -1568,6 +1579,52 @@ declare module '@polkadot/api/types/submittable' {
**/
transfer: AugmentedSubmittable<(updated: AccountId | string | Uint8Array, index: AccountIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId, AccountIndex]>;
};
lottery: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
/**
* Buy a ticket to enter the lottery.
*
* This extrinsic acts as a passthrough function for `call`. In all
* situations where `call` alone would succeed, this extrinsic should
* succeed.
*
* If `call` is successful, then we will attempt to purchase a ticket,
* which may fail silently. To detect success of a ticket purchase, you
* should listen for the `TicketBought` event.
*
* This extrinsic must be called by a signed origin.
**/
buyTicket: AugmentedSubmittable<(call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Call]>;
/**
* Set calls in storage which can be used to purchase a lottery ticket.
*
* This function only matters if you use the `ValidateCall` implementation
* provided by this pallet, which uses storage to determine the valid calls.
*
* This extrinsic must be called by the Manager origin.
**/
setCalls: AugmentedSubmittable<(calls: Vec<Call> | (Call | { callIndex?: any; args?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Vec<Call>]>;
/**
* Start a lottery using the provided configuration.
*
* This extrinsic must be called by the `ManagerOrigin`.
*
* Parameters:
*
* * `price`: The cost of a single ticket.
* * `length`: How long the lottery should run for starting at the current block.
* * `delay`: How long after the lottery end we should wait before picking a winner.
* * `repeat`: If the lottery should repeat when completed.
**/
startLottery: AugmentedSubmittable<(price: BalanceOf | AnyNumber | Uint8Array, length: BlockNumber | AnyNumber | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array, repeat: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [BalanceOf, BlockNumber, BlockNumber, bool]>;
/**
* If a lottery is repeating, you can use this to stop the repeat.
* The lottery will continue to run to completion.
*
* This extrinsic must be called by the `ManagerOrigin`.
**/
stopRepeat: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
};
multisig: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
/**
@@ -2676,6 +2733,22 @@ declare module '@polkadot/api/types/submittable' {
* # </weight>
**/
increaseValidatorCount: AugmentedSubmittable<(additional: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>]>;
/**
* Remove the given nominations from the calling validator.
*
* Effects will be felt at the beginning of the next era.
*
* The dispatch origin for this call must be _Signed_ by the controller, not the stash.
* And, it can be only called when [`EraElectionStatus`] is `Closed`. The controller
* account should represent a validator.
*
* - `who`: A list of nominator stash accounts who are nominating this validator which
* should no longer be nominating this validator.
*
* Note: Making this call only makes sense if you first set the validator preferences to
* block any further nominations.
**/
kick: AugmentedSubmittable<(who: Vec<LookupSource> | (LookupSource | Address | AccountId | AccountIndex | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Vec<LookupSource>]>;
/**
* Declare the desire to nominate `targets` for the origin controller.
*
@@ -2730,9 +2803,9 @@ declare module '@polkadot/api/types/submittable' {
**/
payoutStakers: AugmentedSubmittable<(validatorStash: AccountId | string | Uint8Array, era: EraIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId, EraIndex]>;
/**
* Remove all data structure concerning a staker/stash once its balance is zero.
* Remove all data structure concerning a staker/stash once its balance is at the minimum.
* This is essentially equivalent to `withdraw_unbonded` except it can be called by anyone
* and the target `stash` must have no funds left.
* and the target `stash` must have no funds left beyond the ED.
*
* This can be called from any origin.
*
@@ -3167,19 +3240,6 @@ declare module '@polkadot/api/types/submittable' {
* # </weight>
**/
setStorage: AugmentedSubmittable<(items: Vec<KeyValue> | (KeyValue)[]) => SubmittableExtrinsic<ApiType>, [Vec<KeyValue>]>;
/**
* Kill the sending account, assuming there are no references outstanding and the composite
* data is equal to its default value.
*
* # <weight>
* - `O(1)`
* - 1 storage read and deletion.
* --------------------
* Base Weight: 8.626 µs
* No DB Read or Write operations because caller is already in overlay
* # </weight>
**/
suicide: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
};
technicalCommittee: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
+24 -2
View File
@@ -14,12 +14,13 @@ import { Metadata } from '@polkadot/metadata';
import { TypeRegistry } from '@polkadot/types/create';
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic';
import { getSpecAlias, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
import { assert, BN_ZERO, logger, u8aEq, u8aToU8a } from '@polkadot/util';
import { assert, BN_ZERO, logger, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import { of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { Decorate } from './Decorate';
import { detectedCapabilities } from './util';
const KEEPALIVE_INTERVAL = 15000;
const DEFAULT_BLOCKNUMBER = { unwrap: () => BN_ZERO };
@@ -135,6 +136,11 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
// nothing has been found, construct new
const metadata = await this._rpcCore.state.getMetadata(header.parentHash).toPromise();
const registry = this._initRegistry(new TypeRegistry(), this._runtimeChain as Text, version, metadata);
// For now, since this is new we ignore the capability lookups (this could be useful once proven)
// this._detectCapabilities(registry, blockHash);
// add our new registry
const result = { isDefault: false, lastBlockHash, metadata, metadataConsts: null, registry, specVersion: version.specVersion };
this.#registries.push(result);
@@ -180,6 +186,19 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
return [source.genesisHash, source.runtimeMetadata];
}
private _detectCapabilities (registry?: Registry, blockHash?: string | Uint8Array): void {
detectedCapabilities(this._rx, blockHash)
.toPromise()
.then((types): void => {
if (Object.keys(types).length) {
(registry || this.registry).register(types as Record<string, string>);
l.log(`Capabilities detected${blockHash ? ` (${u8aToHex(u8aToU8a(blockHash))})` : ''}: ${JSON.stringify(types)}`);
}
})
.catch(l.error);
}
// subscribe to metadata updates, inject the types on changes
private _subscribeUpdates (): void {
if (this.#updateSub || !this.hasSubscriptions) {
@@ -212,6 +231,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
// clear the registry types to ensure that we override correctly
this._initRegistry(thisRegistry.registry.init(), this._runtimeChain as Text, version, metadata);
this.injectMetadata(metadata, false, thisRegistry.registry);
this._detectCapabilities(thisRegistry.registry);
return true;
})
@@ -277,9 +297,11 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
this._rx.extrinsicType = this._extrinsicType;
this._rx.genesisHash = this._genesisHash;
this._rx.runtimeVersion = this._runtimeVersion;
this._rx.runtimeVersion = this._runtimeVersion as RuntimeVersion; // must be set here
// inject metadata and adjust the types as detected
this.injectMetadata(metadata, true);
this._detectCapabilities();
// derive is last, since it uses the decorated rx
this._rx.derive = this._decorateDeriveRx(this._rxDecorateMethod);
+74
View File
@@ -0,0 +1,74 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { bool } from '@polkadot/types';
import type { Releases } from '@polkadot/types/interfaces';
import type { InterfaceTypes } from '@polkadot/types/types';
import { combineLatest, Observable, of } from '@polkadot/x-rxjs';
import { map, take } from '@polkadot/x-rxjs/operators';
// the order and types needs to map with the all array setup below
type Extracted = [bool | null, bool | null, Releases | null];
type DetectedKeys = keyof Pick<InterfaceTypes, 'AccountInfo' | 'ValidatorPrefs'>;
type DetectedValues = keyof InterfaceTypes;
interface DetectedTypes extends Record<DetectedKeys, DetectedValues> {
AccountInfo: 'AccountInfoWithRefCount' | 'AccountInfoWithProviders',
ValidatorPrefs: 'ValidatorPrefsWithBlocked' | 'ValidatorPrefsWithCommission';
}
function mapCapabilities ([systemRefcount32, systemRefcountDual, stakingVersion]: Extracted): Partial<DetectedTypes> {
const types: Partial<DetectedTypes> = {};
// AccountInfo
if (systemRefcountDual && systemRefcountDual.isTrue) {
types.AccountInfo = 'AccountInfoWithProviders';
} else if (systemRefcount32 && systemRefcount32.isTrue) {
types.AccountInfo = 'AccountInfoWithRefCount';
}
// ValidatorPrefs
if (stakingVersion) {
if (stakingVersion.index >= 4) { // v1 = index 0, V5 = index 4
types.ValidatorPrefs = 'ValidatorPrefsWithBlocked';
} else {
types.ValidatorPrefs = 'ValidatorPrefsWithCommission';
}
}
return types;
}
/**
* @description Query the chain for the specific capabilities
*/
export function detectedCapabilities (api: ApiInterfaceRx, blockHash?: Uint8Array | string | undefined): Observable<Partial<DetectedTypes>> {
const all = [
api.query.system?.upgradedToU32RefCount,
api.query.system?.upgradedToDualRefCount,
api.query.staking?.storageVersion
];
const included = all.map((c) => !!c);
const filtered = all.filter((_, index) => included[index]);
return (
filtered.length
? blockHash
? combineLatest(filtered.map((c) => c.at(blockHash)))
: api.queryMulti(filtered)
: of([])
).pipe(
map((results): Partial<DetectedTypes> => {
let offset = -1;
return mapCapabilities(
included.map((isIncluded) => isIncluded ? results[++offset] : null) as Extracted
);
}),
take(1)
);
}
+1 -1
View File
@@ -81,7 +81,7 @@ export interface ApiInterfaceRx {
hasSubscriptions: boolean;
registry: Registry;
runtimeMetadata: Metadata;
runtimeVersion?: RuntimeVersion;
runtimeVersion: RuntimeVersion;
query: QueryableStorage<'rxjs'>;
queryMulti: QueryableStorageMulti<'rxjs'>;
rpc: DecoratedRpc<'rxjs', RpcInterface>;
+6 -6
View File
@@ -38,16 +38,16 @@ export type QueryableStorageEntry<ApiType extends ApiTypes, A extends AnyTuple =
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple> {
at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>;
creator: StorageEntry;
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, T][]>;
entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, T][]>;
entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey, T][]>;
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>;
entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>;
entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>;
hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>;
is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>;
key: (...args: Parameters<F>) => string;
keyPrefix: () => string;
keys: (arg?: any) => PromiseOrObs<ApiType, StorageKey[]>;
keysAt: (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey[]>;
keysPaged: (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey[]>;
keys: (arg?: any) => PromiseOrObs<ApiType, StorageKey<A>[]>;
keysAt: (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey<A>[]>;
keysPaged: (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey<A>[]>;
// @deprecated The underlying RPC this been marked unsafe and is generally not exposed
range: <T extends Codec | any = ObsInnerType<ReturnType<F>>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>;
size: (...args: Parameters<F>) => PromiseOrObs<ApiType, u64>;
+6 -7
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/metadata",
"version": "3.4.1",
"version": "3.6.1",
"description": "Helpers to extract information from runtime metadata",
"main": "index.js",
"module": "index.mjs",
"sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
@@ -17,13 +16,13 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@polkadot/types": "3.4.1",
"@polkadot/types-known": "3.4.1",
"@polkadot/util": "^5.2.3",
"@polkadot/util-crypto": "^5.2.3",
"@polkadot/types": "3.6.1",
"@polkadot/types-known": "3.6.1",
"@polkadot/util": "^5.4.2",
"@polkadot/util-crypto": "^5.4.2",
"bn.js": "^4.11.9"
},
"devDependencies": {
"@polkadot/keyring": "^5.2.3"
"@polkadot/keyring": "^5.4.2"
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+7 -8
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/rpc-core",
"version": "3.4.1",
"version": "3.6.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
"module": "index.mjs",
"sideEffects": false,
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
@@ -14,13 +13,13 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@polkadot/metadata": "3.4.1",
"@polkadot/rpc-provider": "3.4.1",
"@polkadot/types": "3.4.1",
"@polkadot/util": "^5.2.3",
"@polkadot/x-rxjs": "3.4.1"
"@polkadot/metadata": "3.6.1",
"@polkadot/rpc-provider": "3.6.1",
"@polkadot/types": "3.6.1",
"@polkadot/util": "^5.4.2",
"@polkadot/x-rxjs": "^5.4.2"
},
"devDependencies": {
"@polkadot/keyring": "^5.2.3"
"@polkadot/keyring": "^5.4.2"
}
}
+9 -10
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/rpc-provider",
"version": "3.4.1",
"version": "3.6.1",
"description": "Transport providers for the API",
"main": "index.js",
"module": "index.mjs",
"sideEffects": false,
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
@@ -14,18 +13,18 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@polkadot/types": "3.4.1",
"@polkadot/util": "^5.2.3",
"@polkadot/util-crypto": "^5.2.3",
"@polkadot/x-fetch": "^5.2.3",
"@polkadot/x-ws": "^5.2.3",
"@polkadot/types": "3.6.1",
"@polkadot/util": "^5.4.2",
"@polkadot/util-crypto": "^5.4.2",
"@polkadot/x-fetch": "^5.4.2",
"@polkadot/x-ws": "^5.4.2",
"bn.js": "^4.11.9",
"eventemitter3": "^4.0.7"
},
"devDependencies": {
"@polkadot/keyring": "^5.2.3",
"@polkadot/metadata": "3.4.1",
"@polkadot/keyring": "^5.4.2",
"@polkadot/metadata": "3.6.1",
"mock-socket": "^9.0.3",
"nock": "^13.0.5"
"nock": "^13.0.6"
}
}
+6 -7
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/typegen",
"version": "3.4.1",
"version": "3.6.1",
"description": "Type generation scripts",
"main": "index.js",
"module": "index.mjs",
"sideEffects": false,
"bin": {
"polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.js",
@@ -23,11 +22,11 @@
"@babel/core": "^7.12.10",
"@babel/register": "^7.12.10",
"@babel/runtime": "^7.12.5",
"@polkadot/api": "3.4.1",
"@polkadot/metadata": "3.4.1",
"@polkadot/rpc-provider": "3.4.1",
"@polkadot/types": "3.4.1",
"@polkadot/util": "^5.2.3",
"@polkadot/api": "3.6.1",
"@polkadot/metadata": "3.6.1",
"@polkadot/rpc-provider": "3.6.1",
"@polkadot/types": "3.6.1",
"@polkadot/util": "^5.4.2",
"handlebars": "^4.7.6",
"websocket": "^1.0.33",
"yargs": "^16.2.0"
+1 -1
View File
@@ -19,7 +19,7 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS
: {};
generateDefaultConsts(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict);
generateDefaultErrors(path.join(process.cwd(), output, 'augment-api-errors.ts'), metaHex, isStrict);
generateDefaultErrors(path.join(process.cwd(), output, 'augment-api-errors.ts'), metaHex, extraTypes, isStrict);
generateDefaultEvents(path.join(process.cwd(), output, 'augment-api-events.ts'), metaHex, extraTypes, isStrict);
generateDefaultQuery(path.join(process.cwd(), output, 'augment-api-query.ts'), metaHex, extraTypes, isStrict);
generateDefaultRpc(path.join(process.cwd(), output, 'augment-api-rpc.ts'), extraTypes);
+8 -14
View File
@@ -1,23 +1,23 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Metadata } from '@polkadot/metadata/Metadata';
import type { ExtraTypes } from './types';
import Handlebars from 'handlebars';
import { Metadata } from '@polkadot/metadata/Metadata';
import staticData from '@polkadot/metadata/static';
import { TypeRegistry } from '@polkadot/types/create';
import * as defaultDefs from '@polkadot/types/interfaces/definitions';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, formatType, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
import { compareName, createImports, formatType, initMeta, readTemplate, setImports, writeFile } from '../util';
const template = readTemplate('consts');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>>, isStrict: boolean): void {
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
writeFile(dest, (): string => {
const allTypes: Record<string, Record<string, { types: Record<string, unknown> }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const allTypes = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const imports = createImports(allTypes);
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
@@ -74,14 +74,8 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<strin
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data = staticData, extraTypes: Record<string, Record<string, { types: Record<string, any> }>> = {}, isStrict = false): void {
const registry = new TypeRegistry();
registerDefinitions(registry, extraTypes);
const metadata = new Metadata(registry, data);
registry.setMetadata(metadata);
export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
const { metadata } = initMeta(data, extraTypes);
return generateForMeta(metadata, dest, extraTypes, isStrict);
}
+6 -9
View File
@@ -1,14 +1,14 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Metadata } from '@polkadot/metadata/Metadata';
import type { ExtraTypes } from './types';
import Handlebars from 'handlebars';
import { Metadata } from '@polkadot/metadata/Metadata';
import staticData from '@polkadot/metadata/static';
import { TypeRegistry } from '@polkadot/types/create';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, readTemplate, writeFile } from '../util';
import { compareName, createImports, initMeta, readTemplate, writeFile } from '../util';
const template = readTemplate('errors');
const generateForMetaTemplate = Handlebars.compile(template);
@@ -50,11 +50,8 @@ function generateForMeta (meta: Metadata, dest: string, isStrict: boolean): void
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultErrors (dest = 'packages/api/src/augment/errors.ts', data = staticData, isStrict = false): void {
const registry = new TypeRegistry();
const metadata = new Metadata(registry, data);
registry.setMetadata(metadata);
export function generateDefaultErrors (dest = 'packages/api/src/augment/errors.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
const { metadata } = initMeta(data, extraTypes);
return generateForMeta(metadata, dest, isStrict);
}
+8 -14
View File
@@ -1,23 +1,23 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Metadata } from '@polkadot/metadata/Metadata';
import type { ExtraTypes } from './types';
import Handlebars from 'handlebars';
import { Metadata } from '@polkadot/metadata/Metadata';
import staticData from '@polkadot/metadata/static';
import { TypeRegistry } from '@polkadot/types/create';
import * as defaultDefs from '@polkadot/types/interfaces/definitions';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, formatType, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
import { compareName, createImports, formatType, initMeta, readTemplate, setImports, writeFile } from '../util';
const template = readTemplate('events');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>>, isStrict: boolean): void {
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
writeFile(dest, (): string => {
const allTypes: Record<string, Record<string, { types: Record<string, unknown> }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const allTypes = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const imports = createImports(allTypes);
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
@@ -67,14 +67,8 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<strin
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data = staticData, extraTypes: Record<string, Record<string, { types: Record<string, any> }>> = {}, isStrict = false): void {
const registry = new TypeRegistry();
registerDefinitions(registry, extraTypes);
const metadata = new Metadata(registry, data);
registry.setMetadata(metadata);
export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
const { metadata } = initMeta(data, extraTypes);
return generateForMeta(metadata, dest, extraTypes, isStrict);
}
@@ -72,7 +72,7 @@ export function generateInterfaceTypes (importDefinitions: { [importPath: string
return generateInterfaceTypesTemplate({
headerType: 'defs',
imports,
items,
items: items.sort((a, b) => a.localeCompare(b)),
types
});
});
+7 -14
View File
@@ -1,19 +1,18 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Metadata } from '@polkadot/metadata/Metadata';
import type { StorageEntryMetadataLatest } from '@polkadot/types/interfaces/metadata';
import type { Registry } from '@polkadot/types/types';
import type { ExtraTypes } from './types';
import Handlebars from 'handlebars';
import { Metadata } from '@polkadot/metadata/Metadata';
import staticData from '@polkadot/metadata/static';
import { TypeRegistry } from '@polkadot/types/create';
import * as defaultDefs from '@polkadot/types/interfaces/definitions';
import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, TypeImports, writeFile } from '../util';
import { compareName, createImports, formatType, getSimilarTypes, initMeta, readTemplate, setImports, TypeImports, writeFile } from '../util';
import { ModuleTypes } from '../util/imports';
// From a storage entry metadata, we return [args, returnType]
@@ -67,9 +66,9 @@ const template = readTemplate('query');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>>, isStrict: boolean): void {
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
writeFile(dest, (): string => {
const allTypes: Record<string, Record<string, { types: Record<string, any> }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const allTypes: ExtraTypes = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const imports = createImports(allTypes);
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
@@ -130,14 +129,8 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultQuery (dest = 'packages/api/src/augment/query.ts', data = staticData, extraTypes: Record<string, Record<string, { types: Record<string, any> }>> = {}, isStrict = false): void {
const registry = new TypeRegistry();
registerDefinitions(registry, extraTypes);
const metadata = new Metadata(registry, data);
registry.setMetadata(metadata);
export function generateDefaultQuery (dest = 'packages/api/src/augment/query.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
const { metadata, registry } = initMeta(data, extraTypes);
return generateForMeta(registry, metadata, dest, extraTypes, isStrict);
}
+7 -8
View File
@@ -1,14 +1,15 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { TypeRegistry } from '@polkadot/types/create';
import type { Definitions } from '@polkadot/types/types';
import type { ExtraTypes } from './types';
import Handlebars from 'handlebars';
import { TypeRegistry } from '@polkadot/types/create';
import * as defaultDefinitions from '@polkadot/types/interfaces/definitions';
import { createImports, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
import { createImports, formatType, getSimilarTypes, initMeta, readTemplate, setImports, writeFile } from '../util';
interface ItemDef {
args: string;
@@ -29,9 +30,9 @@ const template = readTemplate('rpc');
const generateRpcTypesTemplate = Handlebars.compile(template);
/** @internal */
export function generateRpcTypes (registry: TypeRegistry, importDefinitions: Record<string, Definitions>, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>> = {}): void {
export function generateRpcTypes (registry: TypeRegistry, importDefinitions: Record<string, Definitions>, dest: string, extraTypes: ExtraTypes = {}): void {
writeFile(dest, (): string => {
const allTypes: Record<string, Record<string, { types: Record<string, any> }>> = { '@polkadot/types/interfaces': importDefinitions, ...extraTypes };
const allTypes: ExtraTypes = { '@polkadot/types/interfaces': importDefinitions, ...extraTypes };
const imports = createImports(allTypes);
const definitions = imports.definitions as Record<string, Definitions>;
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
@@ -141,10 +142,8 @@ export function generateRpcTypes (registry: TypeRegistry, importDefinitions: Rec
});
}
export function generateDefaultRpc (dest = 'packages/api/src/augment/rpc.ts', extraTypes: Record<string, Record<string, { types: Record<string, any> }>> = {}): void {
const registry = new TypeRegistry();
registerDefinitions(registry, extraTypes);
export function generateDefaultRpc (dest = 'packages/api/src/augment/rpc.ts', extraTypes: ExtraTypes = {}): void {
const { registry } = initMeta(undefined, extraTypes);
generateRpcTypes(
registry,
+7 -14
View File
@@ -1,18 +1,17 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Metadata } from '@polkadot/metadata/Metadata';
import type { Registry } from '@polkadot/types/types';
import type { ExtraTypes } from './types';
import Handlebars from 'handlebars';
import { Metadata } from '@polkadot/metadata/Metadata';
import staticData from '@polkadot/metadata/static';
import { TypeRegistry } from '@polkadot/types/create';
import * as defaultDefs from '@polkadot/types/interfaces/definitions';
import { Text } from '@polkadot/types/primitive';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
import { compareName, createImports, formatType, getSimilarTypes, initMeta, readTemplate, setImports, writeFile } from '../util';
const MAPPED_NAMES: Record<string, string> = {
new: 'updated'
@@ -28,9 +27,9 @@ const template = readTemplate('tx');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>>, isStrict: boolean): void {
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
writeFile(dest, (): string => {
const allTypes: Record<string, Record<string, { types: Record<string, any> }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const allTypes: ExtraTypes = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const imports = createImports(allTypes);
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
@@ -93,14 +92,8 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultTx (dest = 'packages/api/src/augment/tx.ts', data = staticData, extraTypes: Record<string, Record<string, { types: Record<string, any> }>> = {}, isStrict = false): void {
const registry = new TypeRegistry();
registerDefinitions(registry, extraTypes);
const metadata = new Metadata(registry, data);
registry.setMetadata(metadata);
export function generateDefaultTx (dest = 'packages/api/src/augment/tx.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
const { metadata, registry } = initMeta(data, extraTypes);
return generateForMeta(registry, metadata, dest, extraTypes, isStrict);
}
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
export type ExtraTypes = Record<string, Record<string, { types: Record<string, any> }>>;
+2
View File
@@ -275,6 +275,7 @@ function addEvents (metadata: MetadataLatest): string {
const args = func.args.map((type): string => '`' + type.toString() + '`').join(', ');
return {
interface: '`' + `api.events.${stringCamelCase(meta.name)}.${methodName}.is` + '`',
name: `${methodName}(${args})`,
...(func.documentation.length && { summary: func.documentation })
};
@@ -296,6 +297,7 @@ function addErrors (metadata: MetadataLatest): string {
items: moduleMetadata.errors
.sort(sortByName)
.map((error) => ({
interface: '`' + `api.errors.${stringCamelCase(moduleMetadata.name)}.${error.name.toString()}.is` + '`',
name: error.name.toString(),
...(error.documentation.length && { summary: error.documentation })
})),
+1
View File
@@ -6,6 +6,7 @@ export * from './docs';
export * from './file';
export * from './formatting';
export * from './imports';
export * from './initMeta';
export * from './register';
export const compareName = (a: { name: { toString(): string } }, b: { name: { toString(): string } }): number =>
+27
View File
@@ -0,0 +1,27 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ExtraTypes } from '../generate/types';
import { Metadata } from '@polkadot/metadata/Metadata';
import staticData from '@polkadot/metadata/static';
import { TypeRegistry } from '@polkadot/types/create';
import { registerDefinitions } from './register';
interface Result {
metadata: Metadata;
registry: TypeRegistry;
}
export function initMeta (data = staticData, extraTypes: ExtraTypes = {}): Result {
const registry = new TypeRegistry();
registerDefinitions(registry, extraTypes);
const metadata = new Metadata(registry, data);
registry.setMetadata(metadata);
return { metadata, registry };
}
+3 -4
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/types-known",
"version": "3.4.1",
"version": "3.6.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
"module": "index.mjs",
"sideEffects": false,
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
@@ -14,8 +13,8 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@polkadot/types": "3.4.1",
"@polkadot/util": "^5.2.3",
"@polkadot/types": "3.6.1",
"@polkadot/util": "^5.4.2",
"bn.js": "^4.11.9"
},
"devDependencies": {
+9
View File
@@ -36,15 +36,24 @@ const typesModules: Record<string, OverrideModuleType> = {
identity: {
Judgement: 'IdentityJudgement'
},
inclusion: {
ValidatorIndex: 'ParaValidatorIndex'
},
parachains: {
Id: 'ParaId'
},
parasScheduler: {
ValidatorIndex: 'ParaValidatorIndex'
},
proposeParachain: {
Proposal: 'ParachainProposal'
},
proxy: {
Announcement: 'ProxyAnnouncement'
},
scheduler: {
ValidatorIndex: 'ParaValidatorIndex'
},
society: {
Judgement: 'SocietyJudgement',
Vote: 'SocietyVote'
@@ -7,11 +7,18 @@ import type { OverrideVersionedType } from '@polkadot/types/types';
const versioned: OverrideVersionedType[] = [
{
minmax: [0, undefined],
minmax: [0, 99],
types: {
Address: 'AccountId',
LookupSource: 'AccountId'
}
},
{
minmax: [100, undefined],
types: {
Address: 'MultiAddress',
LookupSource: 'MultiAddress'
}
}
];
+9 -1
View File
@@ -16,12 +16,20 @@ const versioned: OverrideVersionedType[] = [
}
},
{
minmax: [260, undefined],
minmax: [260, 260],
types: {
AccountInfo: 'AccountInfoWithRefCount',
Address: 'MultiAddress',
LookupSource: 'MultiAddress'
}
},
{
minmax: [261, undefined],
types: {
AccountInfo: 'AccountInfoWithProviders',
Address: 'MultiAddress',
LookupSource: 'MultiAddress'
}
}
];
+13 -4
View File
@@ -11,8 +11,9 @@ import type { OverrideVersionedType } from '@polkadot/types/types';
const sharedTypes = {
AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId',
Keys: 'SessionKeys5',
LookupSource: 'AccountId'
FullIdentification: '()', // No staking, only session (as per config)
LookupSource: 'AccountId',
Keys: 'SessionKeys6'
};
const versioned: OverrideVersionedType[] = [
@@ -22,11 +23,19 @@ const versioned: OverrideVersionedType[] = [
...sharedTypes,
CompactAssignments: 'CompactAssignmentsTo257',
RefCount: 'RefCountTo259',
RewardDestination: 'RewardDestinationTo257'
RewardDestination: 'RewardDestinationTo257',
Keys: 'SessionKeys5'
}
},
{
minmax: [10, undefined],
minmax: [10, 12],
types: {
...sharedTypes,
Keys: 'SessionKeys5'
}
},
{
minmax: [13, undefined],
types: {
...sharedTypes
}
+1 -1
View File
@@ -10,7 +10,7 @@ const upgrades: ChainUpgradesRaw = {
[879238, 25], [889472, 26], [902937, 27], [932751, 28], [991142, 29],
[1030162, 31], [1119657, 32], [1199282, 33], [1342534, 34], [1392263, 35],
[1431703, 36], [1433369, 37], [1490972, 41], [2087397, 43], [2316688, 44],
[2549864, 45]
[2549864, 45], [3925782, 46], [3925843, 47]
]
};
+6 -7
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/types",
"version": "3.4.1",
"version": "3.6.1",
"description": "Implementation of the Parity codec",
"main": "index.js",
"module": "index.mjs",
"sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
@@ -17,14 +16,14 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@polkadot/metadata": "3.4.1",
"@polkadot/util": "^5.2.3",
"@polkadot/util-crypto": "^5.2.3",
"@polkadot/x-rxjs": "3.4.1",
"@polkadot/metadata": "3.6.1",
"@polkadot/util": "^5.4.2",
"@polkadot/util-crypto": "^5.4.2",
"@polkadot/x-rxjs": "^5.4.2",
"@types/bn.js": "^4.11.6",
"bn.js": "^4.11.9"
},
"devDependencies": {
"@polkadot/keyring": "^5.2.3"
"@polkadot/keyring": "^5.4.2"
}
}
File diff suppressed because it is too large Load Diff
+4 -2
View File
@@ -146,7 +146,7 @@ export abstract class AbstractInt extends BN implements Codec {
/**
* @description Returns a BigInt representation of the number
*/
public toBigInt (): BigInt {
public toBigInt (): bigint {
return BigInt(this.toString());
}
@@ -179,7 +179,9 @@ export abstract class AbstractInt extends BN implements Codec {
if (rawType === 'Balance') {
return this.isMax()
? 'everything'
: formatBalance(this, { decimals: this.registry.chainDecimals, withSi: true, withUnit: this.registry.chainToken });
// FIXME In the case of multiples we need some way of detecting which instance this belongs
// to. as it stands we will always format (incorrectly) against the first token defined
: formatBalance(this, { decimals: this.registry.chainDecimals[0], withSi: true, withUnit: this.registry.chainTokens[0] });
}
const [, divisor] = FORMATTERS.find(([type]) => type === rawType) || [];
+2 -4
View File
@@ -4,7 +4,7 @@
import type { H256 } from '../interfaces/runtime';
import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types';
import { compactFromU8a, compactToU8a, hexToU8a, isHex, isU8a, logger, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
import { compactFromU8a, compactToU8a, isHex, isU8a, logger, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
import { compareSet, decodeU8a, typeToConstructor } from './utils';
@@ -67,9 +67,7 @@ function decodeSet<V extends Codec = Codec> (registry: Registry, valType: Constr
const ValClass = typeToConstructor(registry, valType);
if (isHex(value)) {
return decodeSet(registry, ValClass, hexToU8a(value));
} else if (isU8a(value)) {
if (isHex(value) || isU8a(value)) {
return decodeSetFromU8a<V>(registry, ValClass, u8aToU8a(value));
} else if (Array.isArray(value) || value instanceof Set) {
return decodeSetFromSet<V>(registry, ValClass, value);
+3 -1
View File
@@ -73,7 +73,9 @@ describe('Compact', (): void => {
});
it('has a valid toBigInt interface', (): void => {
expect(new (Compact.with('u128'))(registry, 12345678987654321n).toBigInt() === 12345678987654321n).toBe(true);
expect(
(new (Compact.with('u128'))(registry, 12345678987654321n).toBigInt() + 1n) === 12345678987654322n
).toBe(true);
});
});
});
+1 -1
View File
@@ -95,7 +95,7 @@ export class Compact<T extends CompactEncodable> implements ICompact<T> {
/**
* @description Returns a BigInt representation of the number
*/
public toBigInt (): BigInt {
public toBigInt (): bigint {
return BigInt(this.toString());
}
+6
View File
@@ -59,6 +59,12 @@ describe('Date', (): void => {
new CodecDate(registry, 3).toHex(true)
).toEqual('0x0300000000000000');
});
it('encodes correctly to BigInt', (): void => {
expect(
new CodecDate(registry, 41).toBigInt() + 1n
).toEqual(42n);
});
});
describe('utils', (): void => {
+1 -1
View File
@@ -83,7 +83,7 @@ export class CodecDate extends Date implements Codec {
/**
* @description Returns a BigInt representation of the number
*/
public toBigInt (): BigInt {
public toBigInt (): bigint {
return BigInt(this.toNumber());
}
+8 -2
View File
@@ -4,7 +4,7 @@
import type { H256 } from '../interfaces/runtime';
import type { AnyJson, Codec, Registry } from '../types';
import { isUndefined } from '@polkadot/util';
import { isFunction, isUndefined } from '@polkadot/util';
import { compareMap } from './utils';
@@ -79,7 +79,13 @@ export class Json extends Map<string, any> implements Codec {
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
*/
public toHuman (): Record<string, AnyJson> {
return this.toJSON();
return [...this.entries()].reduce((json: Record<string, AnyJson>, [key, value]): Record<string, AnyJson> => {
json[key] = isFunction((value as Codec).toHuman)
? (value as Codec).toHuman()
: value as AnyJson;
return json;
}, {});
}
/**
+2 -4
View File
@@ -4,7 +4,7 @@
import type { H256 } from '../interfaces/runtime';
import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types';
import { compactFromU8a, compactToU8a, hexToU8a, isHex, isObject, isU8a, logger, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
import { compactFromU8a, compactToU8a, isHex, isObject, isU8a, logger, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
import { compareMap, decodeU8a, typeToConstructor } from './utils';
@@ -74,9 +74,7 @@ function decodeMap<K extends Codec = Codec, V extends Codec = Codec> (registry:
if (!value) {
return new Map<K, V>();
} else if (isHex(value)) {
return decodeMap(registry, KeyClass, ValClass, hexToU8a(value));
} else if (isU8a(value)) {
} else if (isU8a(value) || isHex(value)) {
return decodeMapFromU8a<K, V>(registry, KeyClass, ValClass, u8aToU8a(value));
} else if (value instanceof Map) {
return decodeMapFromMap<K, V>(registry, KeyClass, ValClass, value);
+3 -12
View File
@@ -4,16 +4,7 @@
import type { H256 } from '../interfaces/runtime';
import type { AnyJson, AnyU8a, IU8a, Registry } from '../types';
import { assert, isAscii, isU8a, isUndefined, isUtf8, u8aToHex, u8aToString, u8aToU8a } from '@polkadot/util';
/** @internal */
function decodeU8a (value?: any): Uint8Array {
if (isU8a(value)) {
return value;
}
return u8aToU8a(value);
}
import { assert, isAscii, isUndefined, isUtf8, u8aToHex, u8aToString, u8aToU8a } from '@polkadot/util';
/**
* @name Raw
@@ -28,7 +19,7 @@ export class Raw extends Uint8Array implements IU8a {
public readonly registry: Registry;
constructor (registry: Registry, value?: AnyU8a) {
super(decodeU8a(value));
super(u8aToU8a(value));
this.registry = registry;
}
@@ -92,7 +83,7 @@ export class Raw extends Uint8Array implements IU8a {
!this.some((value, index) => value !== other[index]);
}
return this.eq(decodeU8a(other));
return this.eq(u8aToU8a(other as any));
}
/**
+3 -5
View File
@@ -3,7 +3,7 @@
import type { AnyNumber, AnyString, AnyU8a, Codec, Constructor, InterfaceTypes, Registry } from '../types';
import { hexToU8a, isHex, isU8a, u8aConcat } from '@polkadot/util';
import { isHex, isU8a, u8aConcat, u8aToU8a } from '@polkadot/util';
import { AbstractArray } from './AbstractArray';
import { decodeU8a, mapToTypeMap, typeToConstructor } from './utils';
@@ -20,10 +20,8 @@ type TupleTypes = (Constructor | keyof InterfaceTypes)[] | {
/** @internal */
function decodeTuple (registry: Registry, _Types: TupleConstructors, value?: AnyTuple): Codec[] {
if (isU8a(value)) {
return decodeU8a(registry, value, _Types);
} else if (isHex(value)) {
return decodeTuple(registry, _Types, hexToU8a(value));
if (isU8a(value) || isHex(value)) {
return decodeU8a(registry, u8aToU8a(value), _Types);
}
const Types: Constructor[] = Array.isArray(_Types)
+6
View File
@@ -45,6 +45,12 @@ describe('UInt', (): void => {
).toEqual(4567);
});
it('has a working toBigInt', (): void => {
expect(
new UInt(registry, 4567).toBigInt() + BigInt(1)
).toEqual(BigInt(4568));
});
it('converts to Little Endian from the provided value', (): void => {
expect(
new UInt(registry, 1234567).toU8a()
+8 -8
View File
@@ -3,8 +3,6 @@
import type { Codec, Constructor, Registry } from '../../types';
import { arrayFlatten } from '@polkadot/util';
/**
* Given an u8a, and an array of Type constructors, decode the u8a against the
* types, and return an array of decoded values.
@@ -16,13 +14,15 @@ export function decodeU8a (registry: Registry, u8a: Uint8Array, _types: Construc
const types = Array.isArray(_types)
? _types
: Object.values(_types);
const result: Codec[] = [];
let offset = 0;
if (!types.length) {
return [];
for (let i = 0; i < types.length; i++) {
const value = new types[i](registry, u8a.subarray(offset));
result.push(value);
offset += value.encodedLength;
}
const Type = types[0];
const value = new Type(registry, u8a);
return arrayFlatten([[value], decodeU8a(registry, u8a.subarray(value.encodedLength), types.slice(1))]);
return result;
}
+32 -14
View File
@@ -104,10 +104,9 @@ function extractProperties (registry: Registry, metadata: Metadata): ChainProper
return original;
}
return registry.createType('ChainProperties', {
...(original || {}),
ss58Format
});
const { tokenDecimals, tokenSymbol } = original || {};
return registry.createType('ChainProperties', { ss58Format, tokenDecimals, tokenSymbol });
}
export class TypeRegistry implements Registry {
@@ -160,10 +159,16 @@ export class TypeRegistry implements Registry {
return this;
}
public get chainDecimals (): number {
return this.#chainProperties?.tokenDecimals.isSome
? this.#chainProperties.tokenDecimals.unwrap().toNumber()
: 12;
public get chainDecimals (): number[] {
if (this.#chainProperties?.tokenDecimals.isSome) {
const allDecimals = this.#chainProperties.tokenDecimals.unwrap();
if (allDecimals.length) {
return allDecimals.map((b) => b.toNumber());
}
}
return [12];
}
public get chainSS58 (): number | undefined {
@@ -172,10 +177,16 @@ export class TypeRegistry implements Registry {
: undefined;
}
public get chainToken (): string {
return this.#chainProperties?.tokenSymbol.isSome
? this.#chainProperties.tokenSymbol.unwrap().toString()
: formatBalance.getDefaults().unit;
public get chainTokens (): string[] {
if (this.#chainProperties?.tokenSymbol.isSome) {
const allTokens = this.#chainProperties.tokenSymbol.unwrap();
if (allTokens.length) {
return allTokens.map((s) => s.toString());
}
}
return [formatBalance.getDefaults().unit];
}
public get knownTypes (): RegisteredTypes {
@@ -268,8 +279,12 @@ export class TypeRegistry implements Registry {
: undefined;
}
public getDefinition (name: string): string | undefined {
return this.#definitions.get(name);
public getDefinition (typeName: string): string | undefined {
return this.#definitions.get(typeName);
}
public getModuleInstances (specName: string, moduleName: string): string[] | undefined {
return this.#knownTypes?.typesBundle?.spec?.[specName]?.instances?.[moduleName];
}
public getOrThrow <T extends Codec = Codec> (name: string, msg?: string): Constructor<T> {
@@ -316,6 +331,7 @@ export class TypeRegistry implements Registry {
this.#classes.set(arg1.name, arg1);
} else if (isString(arg1)) {
assert(isFunction(arg2), `Expected class definition passed to '${arg1}' registration`);
assert(arg1 !== arg2.toString(), `Unable to register circular ${arg1} === ${arg1}`);
this.#classes.set(arg1, arg2);
} else {
@@ -333,6 +349,8 @@ export class TypeRegistry implements Registry {
? type
: JSON.stringify(type);
assert(name !== def, `Unable to register circular ${name} === ${def}`);
// we already have this type, remove the classes registered for it
if (this.#classes.has(name)) {
this.#classes.delete(name);
@@ -0,0 +1,83 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { TypeRegistry } from '../create';
describe('ChainProperties', (): void => {
const registry = new TypeRegistry();
it('decodes from a null value (setting defaults)', (): void => {
expect(
[...registry.createType('ChainProperties', null).keys()]
).toEqual(['ss58Format', 'tokenDecimals', 'tokenSymbol']);
});
it('decodes from an actual JSON', (): void => {
const { ss58Format, tokenDecimals, tokenSymbol } = registry.createType('ChainProperties', JSON.parse('{"ss58Format":2,"tokenDecimals":12,"tokenSymbol":"KSM"}'));
expect(ss58Format.unwrap().eq(2)).toBe(true);
expect(tokenDecimals.unwrap().eq([12])).toBe(true);
expect(tokenSymbol.unwrap().eq(['KSM'])).toBe(true);
});
it('decodes from an actual object (multiple tokens)', (): void => {
const { ss58Format, tokenDecimals, tokenSymbol } = registry.createType('ChainProperties', {
ss58Format: undefined,
tokenDecimals: [10, 12],
tokenSymbol: ['pDOT', 'pKSM']
});
expect(ss58Format.isNone).toBe(true);
expect(tokenDecimals.unwrap().eq([10, 12])).toBe(true);
expect(tokenSymbol.unwrap().eq(['pDOT', 'pKSM'])).toBe(true);
});
it('decodes from an object, flagged for non-existent ss58Format', (): void => {
const { ss58Format, tokenDecimals, tokenSymbol } = registry.createType('ChainProperties', { tokenSymbol: 'DEV' });
expect(ss58Format.isNone).toBe(true);
expect(tokenDecimals.isNone).toBe(true);
expect(tokenSymbol.isSome).toBe(true);
});
it('decodes from a ChainProperties object', (): void => {
const original = registry.createType('ChainProperties', {
ss58Format: 2,
tokenDecimals: 15,
tokenSymbol: 'KSM'
});
const { ss58Format, tokenDecimals, tokenSymbol } = registry.createType('ChainProperties', original);
expect(ss58Format.unwrap().eq(2)).toBe(true);
expect(tokenDecimals.unwrap().eq([15])).toBe(true);
expect(tokenSymbol.unwrap().eq(['KSM'])).toBe(true);
});
it('has a sane toHuman', (): void => {
expect(
registry.createType('ChainProperties', {
ss58Format: 42,
tokenDecimals: registry.createType('u32', 9),
tokenSymbol: ['Unit', 'Aux1']
}).toHuman()
).toEqual({
ss58Format: '42',
tokenDecimals: ['9'],
tokenSymbol: ['Unit', 'Aux1']
});
});
it('has a sane toHuman', (): void => {
expect(
registry.createType('ChainProperties', {
ss58Format: 2,
tokenDecimals: [registry.createType('u32', 12), 8],
tokenSymbol: ['KSM', 'BTC']
}).toHuman()
).toEqual({
ss58Format: '2',
tokenDecimals: ['12', '8'],
tokenSymbol: ['KSM', 'BTC']
});
});
});
@@ -0,0 +1,84 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Codec, Registry } from '../types';
import { isFunction, isNull, isUndefined } from '@polkadot/util';
import { Json } from '../codec/Json';
import { Option } from '../codec/Option';
import { Vec } from '../codec/Vec';
import { Text } from '../primitive/Text';
import { u32 } from '../primitive/U32';
function createValue (registry: Registry, type: string, value: unknown, asArray = true): Option<Codec> {
// We detect codec here as well - when found, generally this is constructed from itself
if (value && isFunction((value as Option<Codec>).unwrapOrDefault)) {
return value as Option<Codec>;
}
return registry.createType(
type as 'Option<u32>',
asArray
? isNull(value) || isUndefined(value)
? null
: Array.isArray(value)
? value
: [value]
: value
);
}
function decodeValue (registry: Registry, key: string, value: unknown): unknown {
return key === 'ss58Format'
? createValue(registry, 'Option<u32>', value, false)
: key === 'tokenDecimals'
? createValue(registry, 'Option<Vec<u32>>' as 'Vec<u32>', value)
: key === 'tokenSymbol'
? createValue(registry, 'Option<Vec<Text>>' as 'Vec<Text>', value)
: value;
}
function decode (registry: Registry, value?: Map<string, unknown> | Record<string, unknown> | null): Record<string, unknown> {
return (
// allow decoding from a map as well (ourselves)
value && isFunction((value as Map<string, unknown>).entries)
? [...(value as Map<string, unknown>).entries()]
: Object.entries(value || {})
).reduce((all: Record<string, unknown>, [key, value]) => {
all[key] = decodeValue(registry, key, value);
return all;
}, {
ss58Format: registry.createType('Option<u32>'),
tokenDecimals: registry.createType('Option<Vec<u32>>' as 'Vec<u32>'),
tokenSymbol: registry.createType('Option<Vec<Text>>' as 'Vec<Text>')
});
}
export class GenericChainProperties extends Json {
constructor (registry: Registry, value?: Map<string, unknown> | Record<string, unknown> | null) {
super(registry, decode(registry, value));
}
/**
* @description The chain ss58Format
*/
public get ss58Format (): Option<u32> {
return this.get('ss58Format') as Option<u32>;
}
/**
* @description The decimals for each of the tokens
*/
public get tokenDecimals (): Option<Vec<u32>> {
return this.get('tokenDecimals') as Option<Vec<u32>>;
}
/**
* @description The symbols for the tokens
*/
public get tokenSymbol (): Option<Vec<Text>> {
return this.get('tokenSymbol') as Option<Vec<Text>>;
}
}
+1
View File
@@ -7,6 +7,7 @@ export { GenericAccountId } from './AccountId';
export { GenericAccountIndex } from './AccountIndex';
export { GenericBlock } from './Block';
export { GenericCall } from './Call';
export { GenericChainProperties } from './ChainProperties';
export { GenericConsensusEngineId } from './ConsensusEngineId';
export { GenericEvent, GenericEventData } from './Event';
export { GenericLookupSource } from './LookupSource';
@@ -26,6 +26,12 @@ export default {
zombies: 'u32',
accounts: 'u32'
},
AssetMetadata: {
deposit: 'TAssetDepositBalance',
name: 'Vec<u8>',
symbol: 'Vec<u8>',
decimals: 'u8'
},
TAssetBalance: 'u64',
TAssetDepositBalance: 'BalanceOf'
}
@@ -1,7 +1,7 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
import type { Struct, bool, u32, u64 } from '@polkadot/types';
import type { Bytes, Struct, bool, u32, u64, u8 } from '@polkadot/types';
import type { AccountId, BalanceOf } from '@polkadot/types/interfaces/runtime';
/** @name AssetBalance */
@@ -25,6 +25,14 @@ export interface AssetDetails extends Struct {
readonly accounts: u32;
}
/** @name AssetMetadata */
export interface AssetMetadata extends Struct {
readonly deposit: TAssetDepositBalance;
readonly name: Bytes;
readonly symbol: Bytes;
readonly decimals: u8;
}
/** @name TAssetBalance */
export interface TAssetBalance extends u64 {}
@@ -0,0 +1,38 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
// order important in structs... :)
/* eslint-disable sort-keys */
import type { Definitions } from '../../types';
export default {
rpc: {},
types: {
FundIndex: 'u32',
LastContribution: {
_enum: {
Never: 'Null',
PreEnding: 'AuctionIndex',
Ending: 'BlockNumber'
}
},
DeployData: {
codeHash: 'Hash',
codeSize: 'u32',
initialHeadData: 'HeadData'
},
FundInfo: {
parachain: 'Option<ParaId>',
owner: 'AccountId',
deposit: 'Balance',
raised: 'Balance',
end: 'BlockNumber',
cap: 'Balance',
lastContribution: 'LastContribution',
firstSlot: 'BlockNumber',
lastSlot: 'BlockNumber',
deployData: 'Option<DeployData>'
}
}
} as Definitions;
@@ -0,0 +1,4 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
export * from './types';
@@ -0,0 +1,41 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
import type { Enum, Option, Struct, u32 } from '@polkadot/types';
import type { AuctionIndex, HeadData, ParaId } from '@polkadot/types/interfaces/parachains';
import type { AccountId, Balance, BlockNumber, Hash } from '@polkadot/types/interfaces/runtime';
/** @name DeployData */
export interface DeployData extends Struct {
readonly codeHash: Hash;
readonly codeSize: u32;
readonly initialHeadData: HeadData;
}
/** @name FundIndex */
export interface FundIndex extends u32 {}
/** @name FundInfo */
export interface FundInfo extends Struct {
readonly parachain: Option<ParaId>;
readonly owner: AccountId;
readonly deposit: Balance;
readonly raised: Balance;
readonly end: BlockNumber;
readonly cap: Balance;
readonly lastContribution: LastContribution;
readonly firstSlot: BlockNumber;
readonly lastSlot: BlockNumber;
readonly deployData: Option<DeployData>;
}
/** @name LastContribution */
export interface LastContribution extends Enum {
readonly isNever: boolean;
readonly isPreEnding: boolean;
readonly asPreEnding: AuctionIndex;
readonly isEnding: boolean;
readonly asEnding: BlockNumber;
}
export type PHANTOM_CROWDLOAN = 'crowdloan';
@@ -22,6 +22,7 @@ export { default as genericAsset } from './genericAsset/definitions';
export { default as grandpa } from './grandpa/definitions';
export { default as identity } from './identity/definitions';
export { default as imOnline } from './imOnline/definitions';
export { default as lottery } from './lottery/definitions';
export { default as offences } from './offences/definitions';
export { default as proxy } from './proxy/definitions';
export { default as recovery } from './recovery/definitions';
@@ -40,6 +41,7 @@ export { default as vesting } from './vesting/definitions';
// polkadot-specific types
export { default as attestations } from './attestations/definitions';
export { default as claims } from './claims/definitions';
export { default as crowdloan } from './crowdloan/definitions';
export { default as parachains } from './parachains/definitions';
export { default as poll } from './poll/definitions';
export { default as purchase } from './purchase/definitions';
@@ -0,0 +1,21 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
// order important in structs... :)
/* eslint-disable sort-keys */
import type { Definitions } from '../../types';
export default {
rpc: {},
types: {
CallIndex: '(u8, u8)',
LotteryConfig: {
price: 'Balance',
start: 'BlockNumber',
length: 'BlockNumber',
delay: 'BlockNumber',
repeat: 'bool'
}
}
} as Definitions;
@@ -0,0 +1,4 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
export * from './types';
@@ -0,0 +1,20 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
import type { Struct, bool, u8 } from '@polkadot/types';
import type { ITuple } from '@polkadot/types/types';
import type { Balance, BlockNumber } from '@polkadot/types/interfaces/runtime';
/** @name CallIndex */
export interface CallIndex extends ITuple<[u8, u8]> {}
/** @name LotteryConfig */
export interface LotteryConfig extends Struct {
readonly price: Balance;
readonly start: BlockNumber;
readonly length: BlockNumber;
readonly delay: BlockNumber;
readonly repeat: bool;
}
export type PHANTOM_LOTTERY = 'lottery';
@@ -6,15 +6,17 @@
import type { Definitions } from '../../types';
const SLOT_RANGE_COUNT = 10;
import hrmpTypes from './hrmp';
import slotTypes from './slots';
// proposeParachain
const proposeTypes = {
ParachainProposal: {
proposer: 'AccountId',
validationFunction: 'ValidationCode',
initialHeadState: 'HeadData',
validationCode: 'ValidationCode',
genesisHead: 'HeadData',
validators: 'Vec<ValidatorId>',
name: 'Vec<u8>',
name: 'Bytes',
balance: 'Balance'
},
RegisteredParachainInfo: {
@@ -27,6 +29,8 @@ export default {
rpc: {},
types: {
...proposeTypes,
...hrmpTypes,
...slotTypes,
AbridgedCandidateReceipt: {
parachainIndex: 'ParaId',
relayParent: 'Hash',
@@ -36,6 +40,25 @@ export default {
povBlockHash: 'Hash',
commitments: 'CandidateCommitments'
},
AbridgedHostConfiguration: {
maxCodeSize: 'u32',
maxHeadDataSize: 'u32',
maxUpwardQueueCount: 'u32',
maxUpwardQueueSize: 'u32',
maxUpwardMessageSize: 'u32',
maxUpwardMessageNumPerCandidate: 'u32',
hrmpMaxMessageNumPerCandidate: 'u32',
validationUpgradeFrequency: 'BlockNumber',
validationUpgradeDelay: 'BlockNumber'
},
AbridgedHrmpChannel: {
maxCapacity: 'u32',
maxTotalSize: 'u32',
maxMessageSize: 'u32',
msgCount: 'u32',
totalSize: 'u32',
mqcHead: 'Option<Hash>'
},
AssignmentId: 'AccountId',
AssignmentKind: {
_enum: {
@@ -49,7 +72,6 @@ export default {
validatorIndices: 'BitVec'
},
AuthorityDiscoveryId: 'AccountId',
AuctionIndex: 'u32',
AvailabilityBitfield: 'BitVec',
AvailabilityBitfieldRecord: {
bitfield: 'AvailabilityBitfield',
@@ -60,12 +82,6 @@ export default {
validityVotes: 'Vec<ValidityAttestation>',
validatorIndices: 'BitVec'
},
Bidder: {
_enum: {
New: 'NewBidder',
Existing: 'ParaId'
}
},
BufferedSessionChange: {
applyAt: 'BlockNumber',
validators: 'Vec<ValidatorId>',
@@ -83,11 +99,11 @@ export default {
CandidateDescriptor: {
paraId: 'ParaId',
relayParent: 'Hash',
collatorId: 'Hash',
collatorId: 'CollatorId',
persistedValidationDataHash: 'Hash',
povHash: 'Hash',
erasureRoot: 'Hash',
signature: 'Signature'
signature: 'CollatorSignature'
},
CandidateHash: 'Hash',
CandidatePendingAvailability: {
@@ -103,7 +119,7 @@ export default {
descriptor: 'CandidateDescriptor',
commitmentsHash: 'Hash'
},
CollatorId: '[u8; 32]',
CollatorId: 'H256',
CollatorSignature: 'Signature',
CommittedCandidateReceipt: {
descriptor: 'CandidateDescriptor',
@@ -138,12 +154,29 @@ export default {
},
HeadData: 'Bytes',
HostConfiguration: {
validationUpgradeFrequency: 'BlockNumber',
validationUpgradeDelay: 'BlockNumber',
acceptancePeriod: 'BlockNumber',
maxCodeSize: 'u32',
maxHeadDataSize: 'u32',
maxUpwardQueueCount: 'u32',
maxUpwardQueueSize: 'u32',
maxUpwardMessageSize: 'u32',
maxUpwardMessageNumPerCandidate: 'u32',
hrmpMaxMessageNumPerCandidate: 'u32',
validationUpgradeFrequency: 'BlockNumber',
validationUpgradeDelay: 'BlockNumber',
maxPovSize: 'u32',
maxDownwardMessageSize: 'u32',
preferredDispatchableUpwardMessagesStepWeight: 'Weight',
hrmpMaxParachainOutboundChannels: 'u32',
hrmpMaxParathreadOutboundChannels: 'u32',
hrmpOpenRequestTtl: 'u32',
hrmpSenderDeposit: 'Balance',
hrmpRecipientDeposit: 'Balance',
hrmpChannelMaxCapacity: 'u32',
hrmpChannelMaxTotalSize: 'u32',
hrmpMaxParachainInboundChannels: 'u32',
hrmpMaxParathreadInboundChannels: 'u32',
hrmpChannelMaxMessageSize: 'u32',
acceptancePeriod: 'BlockNumber',
parathreadCores: 'u32',
parathreadRetries: 'u32',
groupRotationFrequency: 'BlockNumber',
@@ -156,46 +189,7 @@ export default {
nDelayTranches: 'u32',
zerothDelayTrancheWidth: 'u32',
neededApprovals: 'u32',
relayVrfModuloSamples: 'u32',
maxUpwardQueueCount: 'u32',
maxUpwardQueueSize: 'u32',
maxDownwardMessageSize: 'u32',
preferredDispatchableUpwardMessagesStepWeight: 'Weight',
maxUpwardMessageSize: 'u32',
maxUpwardMessageNumPerCandidate: 'u32',
hrmpOpenRequestTtl: 'u32',
hrmpSenderDeposit: 'Balance',
hrmpRecipientDeposit: 'Balance',
hrmpChannelMaxCapacity: 'u32',
hrmpChannelMaxTotalSize: 'u32',
hrmpMaxParachainInboundChannels: 'u32',
hrmpMaxParathreadInboundChannels: 'u32',
hrmpChannelMaxMessageSize: 'u32',
hrmpMaxParachainOutboundChannels: 'u32',
hrmpMaxParathreadOutboundChannels: 'u32',
hrmpMaxMessageNumPerCandidate: 'u32'
},
HrmpChannel: {
senderDeposit: 'Balance',
recipientDeposit: 'Balance',
maxCapacity: 'u32',
maxTotalSize: 'u32',
maxMessageSize: 'u32',
msgCount: 'u32',
totalSize: 'u32',
mqcHead: 'Option<Hash>'
},
HrmpChannelId: {
sender: 'u32',
receiver: 'u32'
},
HrmpOpenChannelRequest: {
confirmed: 'bool',
age: 'SessionIndex',
senderDeposit: 'Balance',
maxMessageSize: 'u32',
maxCapacity: 'u32',
maxTotalSize: 'u32'
relayVrfModuloSamples: 'u32'
},
InboundDownwardMessage: {
pubSentAt: 'BlockNumber',
@@ -206,24 +200,6 @@ export default {
data: 'Bytes'
},
InboundHrmpMessages: 'Vec<InboundHrmpMessage>',
IncomingParachain: {
_enum: {
Unset: 'NewBidder',
Fixed: 'IncomingParachainFixed',
Deploy: 'IncomingParachainDeploy'
}
},
IncomingParachainFixed: {
codeHash: 'Hash',
codeSize: 'u32',
initialHeadData: 'HeadData'
},
IncomingParachainDeploy: {
code: 'ValidationCode',
initialHeadData: 'HeadData'
},
LeasePeriod: 'BlockNumber',
LeasePeriodOf: 'LeasePeriod',
LocalValidationData: {
parentHead: 'HeadData',
balance: 'Balance',
@@ -233,10 +209,6 @@ export default {
downwardMessages: 'Vec<InboundDownwardMessage>',
horizontalMessages: 'BTreeMap<ParaId, InboundHrmpMessages>'
},
NewBidder: {
who: 'AccountId',
sub: 'SubId'
},
OutboundHrmpMessage: {
recipient: 'u32',
data: 'Bytes'
@@ -269,9 +241,11 @@ export default {
claim: 'ParathreadClaim',
retries: 'u32'
},
ParaValidatorIndex: 'u32',
PersistedValidationData: {
parentHead: 'HeadData',
blockNumber: 'BlockNumber',
relayStorageRoot: 'Hash',
hrmpMqcHeads: 'Vec<(u32, Hash)>',
dmqMqcHead: 'Hash',
maxPovSize: 'u32'
@@ -295,7 +269,7 @@ export default {
validators: 'Vec<ValidatorId>',
discoveryKeys: 'Vec<AuthorityDiscoveryId>',
assignmentKeys: 'Vec<AssignmentId>',
validatorGroups: 'Vec<ValidatorGroup>',
validatorGroups: 'Vec<SessionInfoValidatorGroup>',
nCores: 'u32',
zerothDelayTrancheWidth: 'u32',
relayVrfModuloSamples: 'u32',
@@ -303,19 +277,17 @@ export default {
noShowSlots: 'u32',
neededApprovals: 'u32'
},
SessionInfoValidatorGroup: 'Vec<ParaValidatorIndex>',
SignedAvailabilityBitfield: {
payload: 'BitVec',
validatorIndex: 'u32',
signature: 'Signature'
validatorIndex: 'ParaValidatorIndex',
signature: 'ValidatorSignature'
},
SignedAvailabilityBitfields: 'Vec<SignedAvailabilityBitfield>',
SigningContext: {
sessionIndex: 'SessionIndex',
parentHash: 'Hash'
},
SlotRange: {
_enum: ['ZeroZero', 'ZeroOne', 'ZeroTwo', 'ZeroThree', 'OneOne', 'OneTwo', 'OneThree', 'TwoTwo', 'TwoThree', 'ThreeThree']
},
Statement: {
_enum: {
Never: 'Null', // starts at 1
@@ -324,7 +296,6 @@ export default {
Invalid: 'Hash'
}
},
SubId: 'u32',
TransientValidationData: {
maxCodeSize: 'u32',
maxHeadDataSize: 'u32',
@@ -343,7 +314,10 @@ export default {
persisted: 'PersistedValidationData',
transient: 'TransientValidationData'
},
ValidatorGroup: 'Vec<ValidatorIndex>',
ValidationDataType: {
validationData: 'ValidationData',
relayChainState: 'Vec<Bytes>'
},
ValidatorSignature: 'Signature',
ValidityAttestation: {
_enum: {
@@ -357,8 +331,6 @@ export default {
V0: 'Xcm'
}
},
WinningData: `[WinningDataEntry; ${SLOT_RANGE_COUNT}]`,
WinningDataEntry: 'Option<Bidder>',
WithdrawAsset: {
assets: 'Vec<MultiAsset>',
effects: 'Vec<Order>'
@@ -0,0 +1,30 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
// order important in structs... :)
/* eslint-disable sort-keys */
export default {
HrmpChannel: {
maxCapacity: 'u32',
maxTotalSize: 'u32',
maxMessageSize: 'u32',
msgCount: 'u32',
totalSize: 'u32',
mqcHead: 'Option<Hash>',
senderDeposit: 'Balance',
recipientDeposit: 'Balance'
},
HrmpChannelId: {
sender: 'u32',
receiver: 'u32'
},
HrmpOpenChannelRequest: {
confirmed: 'bool',
age: 'SessionIndex',
senderDeposit: 'Balance',
maxMessageSize: 'u32',
maxCapacity: 'u32',
maxTotalSize: 'u32'
}
};
@@ -0,0 +1,48 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
// order important in structs... :)
/* eslint-disable sort-keys */
const SLOT_RANGE_COUNT = 10;
export default {
AuctionIndex: 'u32',
Bidder: {
_enum: {
New: 'NewBidder',
Existing: 'ParaId'
}
},
IncomingParachain: {
_enum: {
Unset: 'NewBidder',
Fixed: 'IncomingParachainFixed',
Deploy: 'IncomingParachainDeploy'
}
},
IncomingParachainDeploy: {
code: 'ValidationCode',
initialHeadData: 'HeadData'
},
IncomingParachainFixed: {
codeHash: 'Hash',
codeSize: 'u32',
initialHeadData: 'HeadData'
},
LeasePeriod: 'BlockNumber',
LeasePeriodOf: 'BlockNumber',
NewBidder: {
who: 'AccountId',
sub: 'SubId'
},
NewBidderOption: 'Option<NewBidder>',
SlotRange: {
_enum: ['ZeroZero', 'ZeroOne', 'ZeroTwo', 'ZeroThree', 'OneOne', 'OneTwo', 'OneThree', 'TwoTwo', 'TwoThree', 'ThreeThree']
},
SubId: 'u32',
WinningData: `[WinningDataEntry; ${SLOT_RANGE_COUNT}]`,
WinningDataEntry: 'Option<Bidder>',
WinnersData: 'Vec<WinnersDataTuple>',
WinnersDataTuple: '(NewBidderOption, ParaId, BalanceOf, SlotRange)'
};
@@ -4,9 +4,8 @@
import type { BTreeMap, BitVec, Bytes, Compact, Enum, Option, Struct, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types';
import type { ITuple } from '@polkadot/types/types';
import type { Signature } from '@polkadot/types/interfaces/extrinsics';
import type { AccountId, Balance, BlockNumber, Hash, ValidatorId, Weight } from '@polkadot/types/interfaces/runtime';
import type { AccountId, Balance, BalanceOf, BlockNumber, H256, Hash, ValidatorId, Weight } from '@polkadot/types/interfaces/runtime';
import type { MembershipProof, SessionIndex } from '@polkadot/types/interfaces/session';
import type { ValidatorIndex } from '@polkadot/types/interfaces/staking';
/** @name AbridgedCandidateReceipt */
export interface AbridgedCandidateReceipt extends Struct {
@@ -19,6 +18,29 @@ export interface AbridgedCandidateReceipt extends Struct {
readonly commitments: CandidateCommitments;
}
/** @name AbridgedHostConfiguration */
export interface AbridgedHostConfiguration extends Struct {
readonly maxCodeSize: u32;
readonly maxHeadDataSize: u32;
readonly maxUpwardQueueCount: u32;
readonly maxUpwardQueueSize: u32;
readonly maxUpwardMessageSize: u32;
readonly maxUpwardMessageNumPerCandidate: u32;
readonly hrmpMaxMessageNumPerCandidate: u32;
readonly validationUpgradeFrequency: BlockNumber;
readonly validationUpgradeDelay: BlockNumber;
}
/** @name AbridgedHrmpChannel */
export interface AbridgedHrmpChannel extends Struct {
readonly maxCapacity: u32;
readonly maxTotalSize: u32;
readonly maxMessageSize: u32;
readonly msgCount: u32;
readonly totalSize: u32;
readonly mqcHead: Option<Hash>;
}
/** @name AbstractFungible */
export interface AbstractFungible extends Struct {
readonly id: Bytes;
@@ -149,11 +171,11 @@ export interface CandidateCommitments extends Struct {
export interface CandidateDescriptor extends Struct {
readonly paraId: ParaId;
readonly relayParent: Hash;
readonly collatorId: Hash;
readonly collatorId: CollatorId;
readonly persistedValidationDataHash: Hash;
readonly povHash: Hash;
readonly erasureRoot: Hash;
readonly signature: Signature;
readonly signature: CollatorSignature;
}
/** @name CandidateHash */
@@ -177,7 +199,7 @@ export interface CandidateReceipt extends Struct {
}
/** @name CollatorId */
export interface CollatorId extends U8aFixed {}
export interface CollatorId extends H256 {}
/** @name CollatorSignature */
export interface CollatorSignature extends Signature {}
@@ -264,12 +286,29 @@ export interface HeadData extends Bytes {}
/** @name HostConfiguration */
export interface HostConfiguration extends Struct {
readonly validationUpgradeFrequency: BlockNumber;
readonly validationUpgradeDelay: BlockNumber;
readonly acceptancePeriod: BlockNumber;
readonly maxCodeSize: u32;
readonly maxHeadDataSize: u32;
readonly maxUpwardQueueCount: u32;
readonly maxUpwardQueueSize: u32;
readonly maxUpwardMessageSize: u32;
readonly maxUpwardMessageNumPerCandidate: u32;
readonly hrmpMaxMessageNumPerCandidate: u32;
readonly validationUpgradeFrequency: BlockNumber;
readonly validationUpgradeDelay: BlockNumber;
readonly maxPovSize: u32;
readonly maxDownwardMessageSize: u32;
readonly preferredDispatchableUpwardMessagesStepWeight: Weight;
readonly hrmpMaxParachainOutboundChannels: u32;
readonly hrmpMaxParathreadOutboundChannels: u32;
readonly hrmpOpenRequestTtl: u32;
readonly hrmpSenderDeposit: Balance;
readonly hrmpRecipientDeposit: Balance;
readonly hrmpChannelMaxCapacity: u32;
readonly hrmpChannelMaxTotalSize: u32;
readonly hrmpMaxParachainInboundChannels: u32;
readonly hrmpMaxParathreadInboundChannels: u32;
readonly hrmpChannelMaxMessageSize: u32;
readonly acceptancePeriod: BlockNumber;
readonly parathreadCores: u32;
readonly parathreadRetries: u32;
readonly groupRotationFrequency: BlockNumber;
@@ -283,35 +322,18 @@ export interface HostConfiguration extends Struct {
readonly zerothDelayTrancheWidth: u32;
readonly neededApprovals: u32;
readonly relayVrfModuloSamples: u32;
readonly maxUpwardQueueCount: u32;
readonly maxUpwardQueueSize: u32;
readonly maxDownwardMessageSize: u32;
readonly preferredDispatchableUpwardMessagesStepWeight: Weight;
readonly maxUpwardMessageSize: u32;
readonly maxUpwardMessageNumPerCandidate: u32;
readonly hrmpOpenRequestTtl: u32;
readonly hrmpSenderDeposit: Balance;
readonly hrmpRecipientDeposit: Balance;
readonly hrmpChannelMaxCapacity: u32;
readonly hrmpChannelMaxTotalSize: u32;
readonly hrmpMaxParachainInboundChannels: u32;
readonly hrmpMaxParathreadInboundChannels: u32;
readonly hrmpChannelMaxMessageSize: u32;
readonly hrmpMaxParachainOutboundChannels: u32;
readonly hrmpMaxParathreadOutboundChannels: u32;
readonly hrmpMaxMessageNumPerCandidate: u32;
}
/** @name HrmpChannel */
export interface HrmpChannel extends Struct {
readonly senderDeposit: Balance;
readonly recipientDeposit: Balance;
readonly maxCapacity: u32;
readonly maxTotalSize: u32;
readonly maxMessageSize: u32;
readonly msgCount: u32;
readonly totalSize: u32;
readonly mqcHead: Option<Hash>;
readonly senderDeposit: Balance;
readonly recipientDeposit: Balance;
}
/** @name HrmpChannelId */
@@ -406,7 +428,7 @@ export interface Junction extends Enum {
export interface LeasePeriod extends BlockNumber {}
/** @name LeasePeriodOf */
export interface LeasePeriodOf extends LeasePeriod {}
export interface LeasePeriodOf extends BlockNumber {}
/** @name LocalValidationData */
export interface LocalValidationData extends Struct {
@@ -473,6 +495,9 @@ export interface NewBidder extends Struct {
readonly sub: SubId;
}
/** @name NewBidderOption */
export interface NewBidderOption extends Option<NewBidder> {}
/** @name Order */
export interface Order extends Enum {
readonly isNull: boolean;
@@ -513,8 +538,8 @@ export interface ParachainDispatchOrigin extends Enum {
/** @name ParachainProposal */
export interface ParachainProposal extends Struct {
readonly proposer: AccountId;
readonly validationFunction: ValidationCode;
readonly initialHeadState: HeadData;
readonly validationCode: ValidationCode;
readonly genesisHead: HeadData;
readonly validators: Vec<ValidatorId>;
readonly name: Bytes;
readonly balance: Balance;
@@ -562,10 +587,14 @@ export interface ParathreadEntry extends Struct {
readonly retries: u32;
}
/** @name ParaValidatorIndex */
export interface ParaValidatorIndex extends u32 {}
/** @name PersistedValidationData */
export interface PersistedValidationData extends Struct {
readonly parentHead: HeadData;
readonly blockNumber: BlockNumber;
readonly relayStorageRoot: Hash;
readonly hrmpMqcHeads: Vec<ITuple<[u32, Hash]>>;
readonly dmqMqcHead: Hash;
readonly maxPovSize: u32;
@@ -632,7 +661,7 @@ export interface SessionInfo extends Struct {
readonly validators: Vec<ValidatorId>;
readonly discoveryKeys: Vec<AuthorityDiscoveryId>;
readonly assignmentKeys: Vec<AssignmentId>;
readonly validatorGroups: Vec<ValidatorGroup>;
readonly validatorGroups: Vec<SessionInfoValidatorGroup>;
readonly nCores: u32;
readonly zerothDelayTrancheWidth: u32;
readonly relayVrfModuloSamples: u32;
@@ -641,11 +670,14 @@ export interface SessionInfo extends Struct {
readonly neededApprovals: u32;
}
/** @name SessionInfoValidatorGroup */
export interface SessionInfoValidatorGroup extends Vec<ParaValidatorIndex> {}
/** @name SignedAvailabilityBitfield */
export interface SignedAvailabilityBitfield extends Struct {
readonly payload: BitVec;
readonly validatorIndex: u32;
readonly signature: Signature;
readonly validatorIndex: ParaValidatorIndex;
readonly signature: ValidatorSignature;
}
/** @name SignedAvailabilityBitfields */
@@ -718,6 +750,12 @@ export interface ValidationData extends Struct {
readonly transient: TransientValidationData;
}
/** @name ValidationDataType */
export interface ValidationDataType extends Struct {
readonly validationData: ValidationData;
readonly relayChainState: Vec<Bytes>;
}
/** @name ValidationFunctionParams */
export interface ValidationFunctionParams extends Struct {
readonly maxCodeSize: u32;
@@ -725,9 +763,6 @@ export interface ValidationFunctionParams extends Struct {
readonly codeUpgradeAllowed: Option<RelayChainBlockNumber>;
}
/** @name ValidatorGroup */
export interface ValidatorGroup extends Vec<ValidatorIndex> {}
/** @name ValidatorSignature */
export interface ValidatorSignature extends Signature {}
@@ -758,6 +793,12 @@ export interface VersionedXcm extends Enum {
readonly asV0: Xcm;
}
/** @name WinnersData */
export interface WinnersData extends Vec<WinnersDataTuple> {}
/** @name WinnersDataTuple */
export interface WinnersDataTuple extends ITuple<[NewBidderOption, ParaId, BalanceOf, SlotRange]> {}
/** @name WinningData */
export interface WinningData extends Vec<WinningDataEntry> {}
@@ -6,26 +6,43 @@
import type { Definitions } from '../../types';
const QUERY_PARAMS = [
{
name: 'extrinsic',
type: 'Bytes'
},
{
name: 'at',
type: 'BlockHash',
isHistoric: true,
isOptional: true
}
];
export default {
rpc: {
queryInfo: {
description: 'Retrieves the fee information for an encoded extrinsic',
params: [
{
name: 'extrinsic',
type: 'Bytes'
},
{
name: 'at',
type: 'BlockHash',
isHistoric: true,
isOptional: true
}
],
params: QUERY_PARAMS,
type: 'RuntimeDispatchInfo'
},
queryFeeDetails: {
description: 'Query the detailed fee of a given encoded extrinsic',
params: QUERY_PARAMS,
type: 'FeeDetails'
}
},
types: {
FeeDetails: {
inclusionFee: 'Option<InclusionFee>'
// skipped in serde
// tip: 'Balance'
},
InclusionFee: {
baseFee: 'Balance',
lenFee: 'Balance',
adjustedWeightFee: 'Balance'
},
RuntimeDispatchInfo: {
weight: 'Weight',
class: 'DispatchClass',
+13 -1
View File
@@ -1,10 +1,22 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
import type { Struct } from '@polkadot/types';
import type { Option, Struct } from '@polkadot/types';
import type { Balance, Weight } from '@polkadot/types/interfaces/runtime';
import type { DispatchClass } from '@polkadot/types/interfaces/system';
/** @name FeeDetails */
export interface FeeDetails extends Struct {
readonly inclusionFee: Option<InclusionFee>;
}
/** @name InclusionFee */
export interface InclusionFee extends Struct {
readonly baseFee: Balance;
readonly lenFee: Balance;
readonly adjustedWeightFee: Balance;
}
/** @name RuntimeDispatchInfo */
export interface RuntimeDispatchInfo extends Struct {
readonly weight: Weight;
@@ -86,7 +86,7 @@ export default {
LookupTarget: 'AccountId',
ModuleId: 'LockIdentifier',
MultiAddress: 'GenericMultiAddress',
Moment: 'u64',
Moment: 'UInt<64, Moment>',
OpaqueCall: 'Bytes',
Origin: 'DoNotConstruct<Origin>',
OriginCaller: {
@@ -120,6 +120,7 @@ export default {
StorageData: 'Bytes',
TransactionPriority: 'u64',
ValidatorId: 'AccountId',
ValidatorIdOf: 'ValidatorId',
Weight: 'u64',
WeightMultiplier: 'Fixed64',
@@ -166,7 +166,7 @@ export interface LookupTarget extends AccountId {}
export interface ModuleId extends LockIdentifier {}
/** @name Moment */
export interface Moment extends u64 {}
export interface Moment extends UInt {}
/** @name MultiAddress */
export interface MultiAddress extends GenericMultiAddress {}
@@ -267,6 +267,9 @@ export interface U32F32 extends UInt {}
/** @name ValidatorId */
export interface ValidatorId extends AccountId {}
/** @name ValidatorIdOf */
export interface ValidatorIdOf extends ValidatorId {}
/** @name Weight */
export interface Weight extends u64 {}
@@ -14,72 +14,86 @@ const deprecated = {
}
};
const phragmen = {
CompactAssignments: {
votes1: 'Vec<(NominatorIndexCompact, ValidatorIndexCompact)>',
votes2: 'Vec<(NominatorIndexCompact, CompactScoreCompact, ValidatorIndexCompact)>',
votes3: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 2], ValidatorIndexCompact)>',
votes4: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 3], ValidatorIndexCompact)>',
votes5: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 4], ValidatorIndexCompact)>',
votes6: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 5], ValidatorIndexCompact)>',
votes7: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 6], ValidatorIndexCompact)>',
votes8: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 7], ValidatorIndexCompact)>',
votes9: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 8], ValidatorIndexCompact)>',
votes10: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 9], ValidatorIndexCompact)>',
votes11: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 10], ValidatorIndexCompact)>',
votes12: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 11], ValidatorIndexCompact)>',
votes13: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 12], ValidatorIndexCompact)>',
votes14: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 13], ValidatorIndexCompact)>',
votes15: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 14], ValidatorIndexCompact)>',
votes16: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 15], ValidatorIndexCompact)>'
},
CompactAssignmentsTo257: {
votes1: 'Vec<(NominatorIndex, [CompactScore; 0], ValidatorIndex)>',
votes2: 'Vec<(NominatorIndex, [CompactScore; 1], ValidatorIndex)>',
votes3: 'Vec<(NominatorIndex, [CompactScore; 2], ValidatorIndex)>',
votes4: 'Vec<(NominatorIndex, [CompactScore; 3], ValidatorIndex)>',
votes5: 'Vec<(NominatorIndex, [CompactScore; 4], ValidatorIndex)>',
votes6: 'Vec<(NominatorIndex, [CompactScore; 5], ValidatorIndex)>',
votes7: 'Vec<(NominatorIndex, [CompactScore; 6], ValidatorIndex)>',
votes8: 'Vec<(NominatorIndex, [CompactScore; 7], ValidatorIndex)>',
votes9: 'Vec<(NominatorIndex, [CompactScore; 8], ValidatorIndex)>',
votes10: 'Vec<(NominatorIndex, [CompactScore; 9], ValidatorIndex)>',
votes11: 'Vec<(NominatorIndex, [CompactScore; 10], ValidatorIndex)>',
votes12: 'Vec<(NominatorIndex, [CompactScore; 11], ValidatorIndex)>',
votes13: 'Vec<(NominatorIndex, [CompactScore; 12], ValidatorIndex)>',
votes14: 'Vec<(NominatorIndex, [CompactScore; 13], ValidatorIndex)>',
votes15: 'Vec<(NominatorIndex, [CompactScore; 14], ValidatorIndex)>',
votes16: 'Vec<(NominatorIndex, [CompactScore; 15], ValidatorIndex)>'
},
CompactScore: '(ValidatorIndex, OffchainAccuracy)',
CompactScoreCompact: '(ValidatorIndexCompact, OffchainAccuracyCompact)',
ElectionCompute: {
_enum: ['OnChain', 'Signed', 'Authority']
},
ElectionResult: {
compute: 'ElectionCompute',
slotStake: 'Balance',
electedStashes: 'Vec<AccountId>',
exposures: 'Vec<(AccountId, Exposure)>'
},
ElectionScore: '[u128; 3]',
ElectionSize: {
validators: 'Compact<ValidatorIndex>',
nominators: 'Compact<NominatorIndex>'
},
ElectionStatus: {
_enum: {
Close: 'Null',
Open: 'BlockNumber'
}
},
SeatHolder: {
who: 'AccountId',
stake: 'Balance',
deposit: 'Balance'
},
Voter: {
votes: 'Vec<AccountId>',
stake: 'Balance',
deposit: 'Balance'
}
};
export default {
rpc: {},
types: {
...deprecated,
...phragmen,
ActiveEraInfo: {
index: 'EraIndex',
start: 'Option<Moment>'
},
CompactAssignments: {
votes1: 'Vec<(NominatorIndexCompact, ValidatorIndexCompact)>',
votes2: 'Vec<(NominatorIndexCompact, CompactScoreCompact, ValidatorIndexCompact)>',
votes3: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 2], ValidatorIndexCompact)>',
votes4: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 3], ValidatorIndexCompact)>',
votes5: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 4], ValidatorIndexCompact)>',
votes6: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 5], ValidatorIndexCompact)>',
votes7: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 6], ValidatorIndexCompact)>',
votes8: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 7], ValidatorIndexCompact)>',
votes9: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 8], ValidatorIndexCompact)>',
votes10: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 9], ValidatorIndexCompact)>',
votes11: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 10], ValidatorIndexCompact)>',
votes12: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 11], ValidatorIndexCompact)>',
votes13: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 12], ValidatorIndexCompact)>',
votes14: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 13], ValidatorIndexCompact)>',
votes15: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 14], ValidatorIndexCompact)>',
votes16: 'Vec<(NominatorIndexCompact, [CompactScoreCompact; 15], ValidatorIndexCompact)>'
},
CompactAssignmentsTo257: {
votes1: 'Vec<(NominatorIndex, [CompactScore; 0], ValidatorIndex)>',
votes2: 'Vec<(NominatorIndex, [CompactScore; 1], ValidatorIndex)>',
votes3: 'Vec<(NominatorIndex, [CompactScore; 2], ValidatorIndex)>',
votes4: 'Vec<(NominatorIndex, [CompactScore; 3], ValidatorIndex)>',
votes5: 'Vec<(NominatorIndex, [CompactScore; 4], ValidatorIndex)>',
votes6: 'Vec<(NominatorIndex, [CompactScore; 5], ValidatorIndex)>',
votes7: 'Vec<(NominatorIndex, [CompactScore; 6], ValidatorIndex)>',
votes8: 'Vec<(NominatorIndex, [CompactScore; 7], ValidatorIndex)>',
votes9: 'Vec<(NominatorIndex, [CompactScore; 8], ValidatorIndex)>',
votes10: 'Vec<(NominatorIndex, [CompactScore; 9], ValidatorIndex)>',
votes11: 'Vec<(NominatorIndex, [CompactScore; 10], ValidatorIndex)>',
votes12: 'Vec<(NominatorIndex, [CompactScore; 11], ValidatorIndex)>',
votes13: 'Vec<(NominatorIndex, [CompactScore; 12], ValidatorIndex)>',
votes14: 'Vec<(NominatorIndex, [CompactScore; 13], ValidatorIndex)>',
votes15: 'Vec<(NominatorIndex, [CompactScore; 14], ValidatorIndex)>',
votes16: 'Vec<(NominatorIndex, [CompactScore; 15], ValidatorIndex)>'
},
CompactScore: '(ValidatorIndex, OffchainAccuracy)',
CompactScoreCompact: '(ValidatorIndexCompact, OffchainAccuracyCompact)',
ElectionCompute: {
_enum: ['OnChain', 'Signed', 'Authority']
},
ElectionResult: {
compute: 'ElectionCompute',
slotStake: 'Balance',
electedStashes: 'Vec<AccountId>',
exposures: 'Vec<(AccountId, Exposure)>'
},
ElectionScore: '[u128; 3]',
ElectionSize: {
validators: 'Compact<ValidatorIndex>',
nominators: 'Compact<NominatorIndex>'
},
ElectionStatus: {
_enum: {
Close: 'Null',
Open: 'BlockNumber'
}
},
EraIndex: 'u32',
EraRewardPoints: {
total: 'RewardPoint',
@@ -190,9 +204,14 @@ export default {
},
ValidatorIndex: 'u16',
ValidatorIndexCompact: 'Compact<ValidatorIndex>',
ValidatorPrefs: {
ValidatorPrefs: 'ValidatorPrefsWithCommission',
ValidatorPrefsWithCommission: {
commission: 'Compact<Perbill>'
},
ValidatorPrefsWithBlocked: {
commission: 'Compact<Perbill>',
blocked: 'bool'
},
ValidatorPrefsTo196: {
validatorPayment: 'Compact<Balance>'
},
+26 -3
View File
@@ -180,6 +180,13 @@ export interface RewardDestinationTo257 extends Enum {
/** @name RewardPoint */
export interface RewardPoint extends u32 {}
/** @name SeatHolder */
export interface SeatHolder extends Struct {
readonly who: AccountId;
readonly stake: Balance;
readonly deposit: Balance;
}
/** @name SlashingSpans */
export interface SlashingSpans extends Struct {
readonly spanIndex: SpanIndex;
@@ -262,9 +269,7 @@ export interface ValidatorIndex extends u16 {}
export interface ValidatorIndexCompact extends Compact<ValidatorIndex> {}
/** @name ValidatorPrefs */
export interface ValidatorPrefs extends Struct {
readonly commission: Compact<Perbill>;
}
export interface ValidatorPrefs extends ValidatorPrefsWithCommission {}
/** @name ValidatorPrefsTo145 */
export interface ValidatorPrefsTo145 extends Struct {
@@ -277,4 +282,22 @@ export interface ValidatorPrefsTo196 extends Struct {
readonly validatorPayment: Compact<Balance>;
}
/** @name ValidatorPrefsWithBlocked */
export interface ValidatorPrefsWithBlocked extends Struct {
readonly commission: Compact<Perbill>;
readonly blocked: bool;
}
/** @name ValidatorPrefsWithCommission */
export interface ValidatorPrefsWithCommission extends Struct {
readonly commission: Compact<Perbill>;
}
/** @name Voter */
export interface Voter extends Struct {
readonly votes: Vec<AccountId>;
readonly stake: Balance;
readonly deposit: Balance;
}
export type PHANTOM_STAKING = 'staking';
@@ -1,34 +0,0 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { TypeRegistry } from '../../create';
describe('ChainProperties', (): void => {
const registry = new TypeRegistry();
it('decodes from a null value', (): void => {
expect(
[...registry.createType('ChainProperties', null).entries()]
).toEqual([]);
});
it('decodes from an actual object', (): void => {
const { ss58Format, tokenDecimals, tokenSymbol } = registry.createType('ChainProperties', {
ss58Format: 2,
tokenDecimals: 15,
tokenSymbol: 'KSM'
});
expect(ss58Format.unwrap().eq(2)).toBe(true);
expect(tokenDecimals.unwrap().eq(15)).toBe(true);
expect(tokenSymbol.unwrap().eq('KSM')).toBe(true);
});
it('decodes from an object, flagged for non-existent ss58Format', (): void => {
const { ss58Format, tokenDecimals, tokenSymbol } = registry.createType('ChainProperties', { tokenSymbol: 'DEV' });
expect(ss58Format.isNone).toBe(true);
expect(tokenDecimals.isNone).toBe(true);
expect(tokenSymbol.isSome).toBe(true);
});
});
@@ -146,16 +146,15 @@ export default {
data: 'AccountData'
},
ApplyExtrinsicResult: 'Result<DispatchOutcome, TransactionValidityError>',
BlockLength: {
max: 'PerDispatchClassU32'
},
BlockWeights: {
baseBlock: 'Weight',
maxBlock: 'Weight',
perClass: 'PerDispatchClass'
},
ChainProperties: {
ss58Format: 'Option<u8>',
tokenDecimals: 'Option<u32>',
tokenSymbol: 'Option<Text>'
},
ChainProperties: 'GenericChainProperties',
ChainType: {
_enum: {
Development: 'Null',
@@ -301,6 +300,11 @@ export default {
operational: 'WeightPerClass',
mandatory: 'WeightPerClass'
},
PerDispatchClassU32: {
normal: 'u32',
operational: 'u32',
mandatory: 'u32'
},
Phase: {
_enum: {
ApplyExtrinsic: 'u32',
+14 -6
View File
@@ -1,7 +1,7 @@
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
/* eslint-disable */
import type { Bytes, Compact, Enum, GenericEvent, HashMap, Option, Result, Struct, Text, U8aFixed, Vec, bool, i32, u32, u64, u8 } from '@polkadot/types';
import type { Bytes, Compact, Enum, GenericChainProperties, GenericEvent, HashMap, Option, Result, Struct, Text, U8aFixed, Vec, bool, i32, u32, u64, u8 } from '@polkadot/types';
import type { ITuple } from '@polkadot/types/types';
import type { AccountData } from '@polkadot/types/interfaces/balances';
import type { AccountId, BlockNumber, Digest, Hash, Index, Pays, Weight } from '@polkadot/types/interfaces/runtime';
@@ -32,6 +32,11 @@ export interface ApplyExtrinsicResult extends Result<DispatchOutcome, Transactio
readonly asOk: DispatchOutcome;
}
/** @name BlockLength */
export interface BlockLength extends Struct {
readonly max: PerDispatchClassU32;
}
/** @name BlockWeights */
export interface BlockWeights extends Struct {
readonly baseBlock: Weight;
@@ -40,11 +45,7 @@ export interface BlockWeights extends Struct {
}
/** @name ChainProperties */
export interface ChainProperties extends Struct {
readonly ss58Format: Option<u8>;
readonly tokenDecimals: Option<u32>;
readonly tokenSymbol: Option<Text>;
}
export interface ChainProperties extends GenericChainProperties {}
/** @name ChainType */
export interface ChainType extends Enum {
@@ -266,6 +267,13 @@ export interface PerDispatchClass extends Struct {
readonly mandatory: WeightPerClass;
}
/** @name PerDispatchClassU32 */
export interface PerDispatchClassU32 extends Struct {
readonly normal: u32;
readonly operational: u32;
readonly mandatory: u32;
}
/** @name Phase */
export interface Phase extends Enum {
readonly isApplyExtrinsic: boolean;
+2
View File
@@ -19,6 +19,7 @@ export * from './genericAsset/types';
export * from './grandpa/types';
export * from './identity/types';
export * from './imOnline/types';
export * from './lottery/types';
export * from './offences/types';
export * from './proxy/types';
export * from './recovery/types';
@@ -35,6 +36,7 @@ export * from './utility/types';
export * from './vesting/types';
export * from './attestations/types';
export * from './claims/types';
export * from './crowdloan/types';
export * from './parachains/types';
export * from './poll/types';
export * from './purchase/types';
@@ -0,0 +1,32 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { hexToU8a } from '@polkadot/util';
import { TypeRegistry } from '../create';
import { BitVec } from './';
// form Inclusion BitVec<lsb0, u8>
const TESTS = ['0x00', '0x0817', '0x0837', '0x087b', '0x0c33'];
const registry = new TypeRegistry();
describe('BitVec', (): void => {
TESTS.forEach((test): void => {
describe(test, (): void => {
const input = hexToU8a(test);
it('has the right encodedLength', (): void => {
expect(
new BitVec(registry, input).encodedLength
).toEqual((test.length - 2) / 2);
});
// FIXME These do not align at all
it.skip('re-encodes to the same input value', (): void => {
expect(
new BitVec(registry, input).toU8a()
).toEqual(input);
});
});
});
});
+1
View File
@@ -13,4 +13,5 @@ export * from './extrinsic';
export * from './interfaces';
export * from './registry';
// used inside augmented definitions
export type { Observable } from '@polkadot/x-rxjs';
+1 -1
View File
@@ -8,7 +8,7 @@ import type { Hash } from '../interfaces/runtime';
import type { AnyTuple, ArgsDef, Codec } from './codec';
export interface ICompact<T> extends Codec {
toBigInt (): BigInt;
toBigInt (): bigint;
toBn (): BN;
toNumber (): number;
unwrap (): T;
+5 -3
View File
@@ -47,6 +47,7 @@ export type DeriveCustom = Record<string, Record<string, (instanceId: string, ap
export interface OverrideBundleDefinition {
alias?: Record<string, OverrideModuleType>;
derives?: DeriveCustom;
instances?: Record<string, string[]>;
rpc?: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>;
types?: OverrideVersionedType[];
}
@@ -81,9 +82,9 @@ export interface RegisteredTypes {
}
export interface Registry {
readonly chainDecimals: number;
readonly chainDecimals: number[];
readonly chainSS58: number | undefined;
readonly chainToken: string;
readonly chainTokens: string[];
readonly knownTypes: RegisteredTypes;
readonly signedExtensions: string[];
@@ -98,7 +99,8 @@ export interface Registry {
get <T extends Codec = Codec> (name: string, withUnknown?: boolean): Constructor<T> | undefined;
getChainProperties (): ChainProperties | undefined;
getClassName (clazz: Constructor): string | undefined;
getDefinition (name: string): string | undefined;
getDefinition (typeName: string): string | undefined;
getModuleInstances (specName: string, moduleName: string): string[] | undefined;
getOrThrow <T extends Codec = Codec> (name: string, msg?: string): Constructor<T>;
getOrUnknown <T extends Codec = Codec> (name: string): Constructor<T>;
setKnownTypes (types: RegisteredTypes): void;
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-5
View File
@@ -1,5 +0,0 @@
# @polkadot/x-rxjs
This is a small wrapper around rjx to make it friendly to both Node.js (from .mjs as well as .cjs) as well as bundlers using both esm and cjs modules.
This need wil disappear, once rxjs supports export maps.
-18
View File
@@ -1,18 +0,0 @@
{
"name": "@polkadot/x-rxjs",
"version": "3.4.1",
"description": "A pass-through interface for RxJs (allowing node + mjs usage)",
"main": "index.js",
"sideEffects": false,
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/x-rxjs#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"rxjs": "^6.6.3"
}
}

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