Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d493e1a03 | ||
|
|
e5437ef9e9 | ||
|
|
b56bed39e1 | ||
|
|
e789f91850 | ||
|
|
a236eb9453 | ||
|
|
7ef01b8534 | ||
|
|
0e58545a9d | ||
|
|
c474123777 | ||
|
|
93edfcf560 | ||
|
|
e5a67d82fa | ||
|
|
194f6aece1 | ||
|
|
3b4fef8f6e | ||
|
|
6c7323ee3a | ||
|
|
a97b50decb | ||
|
|
52accf6444 | ||
|
|
5b8eb231cc | ||
|
|
5ea62367d3 | ||
|
|
49a034a1a0 | ||
|
|
62a476cb4c | ||
|
|
b283673812 | ||
|
|
b6a075fefb | ||
|
|
afa844ae01 | ||
|
|
353ef59a1c | ||
|
|
6228999e6f | ||
|
|
56db42fedf | ||
|
|
df44693e5d | ||
|
|
cfa25f8dda | ||
|
|
bc8934f3c3 | ||
|
|
bc67c72e9b | ||
|
|
22d85e745a | ||
|
|
60ba2952f7 | ||
|
|
bb10d2813f | ||
|
|
80b581f0df | ||
|
|
ef37c421ac | ||
|
|
6e1e8e622b | ||
|
|
ec38a1510f | ||
|
|
e550ca5a71 | ||
|
|
80241f732f | ||
|
|
84fc0be12e | ||
|
|
e1f14e8a83 | ||
|
|
1155724604 | ||
|
|
3bb9541943 | ||
|
|
25288f664a | ||
|
|
879c5d7b44 | ||
|
|
cdaec1953c | ||
|
|
f4bf7a9c52 | ||
|
|
7b46c6aa15 | ||
|
|
d28f4ccfa0 | ||
|
|
e5b05dc700 | ||
|
|
bf9831753e | ||
|
|
5e1670dbae | ||
|
|
0d0a230c86 | ||
|
|
9989b69b46 | ||
|
|
66693253ef | ||
|
|
cbffc37dcf | ||
|
|
74ee42ed66 | ||
|
|
f642e2399f | ||
|
|
8cefb055db | ||
|
|
1f31756019 | ||
|
|
4d6a1da6d5 | ||
|
|
d62e720627 |
+2
-1
@@ -42,4 +42,5 @@
|
||||
|
||||
6.4.2
|
||||
6.5.2
|
||||
6.7.2
|
||||
6.7.2
|
||||
6.9.2
|
||||
@@ -1,5 +1,50 @@
|
||||
# CHANGELOG
|
||||
|
||||
## 6.9.2 Nov 22, 2021
|
||||
|
||||
Upgrade priority: Medium. Pulls in `@polkadot/util-crypto` fix for TS projects.
|
||||
|
||||
Changes:
|
||||
|
||||
- Update `@polkadot/util-crypto` with TS compilation work-around
|
||||
|
||||
|
||||
## 6.9.1 Nov 21, 2021
|
||||
|
||||
Upgrade priority: Medium. Recommended for metadata v14 parachains. For TS users, the package now support TypeScript 4.5.2 and allows extraction of user types from metadata v14.
|
||||
|
||||
Contributed:
|
||||
|
||||
- Lookup TS generation for all metadata v14 chains (Thanks to https://github.com/savudani8)
|
||||
- Update `BeefySignedCommitment` type (Thanks to https://github.com/czl1378)
|
||||
|
||||
Changes:
|
||||
|
||||
- Adjust runtime `*::{Call, Event}` matching for metadata v14
|
||||
- Adjust derive decoration with (optional) known methods
|
||||
- Expose `*{Call, Event, Error}` TS types for metadata v14
|
||||
- Align Option `.toJSON` output with Substrate input
|
||||
- Optimize Enum, Struct, Option & Number decoding paths
|
||||
- Ajust PascalCase conversions with function from util
|
||||
- Prepare pre-v13 types for optional injection
|
||||
- Adjustments for TS 4.5.2 support (flatten type infers)
|
||||
|
||||
|
||||
## 6.8.1 Nov 11, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for chains with non-MultiSignature variants where `paymentInfo` is required.
|
||||
|
||||
Changes:
|
||||
|
||||
- Adjust `paymentInfo` signatures to cater for non-MultiSignature variants
|
||||
- Remove `::generic::` from names & namespaces under metadata v14
|
||||
- Add Polkadot 9122 upgrade block
|
||||
- Cleanup Polkadot/Kusama/Westend/Rococo known types (>= v14 metadata)
|
||||
- Internal `decorateMethod{Promise, Rx}` renamed to `to{Promise, Rx}Method`
|
||||
- Add RPC provider-level LRU for historic requests
|
||||
- Add optional known runtime version param to internal `rx.queryAt`
|
||||
|
||||
|
||||
## 6.7.2 Nov 9, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for chains on metadata v14 with non-default `Address` implementations.
|
||||
|
||||
+6
-6
@@ -11,7 +11,7 @@
|
||||
},
|
||||
"sideEffects": false,
|
||||
"type": "commonjs",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
@@ -33,14 +33,14 @@
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.16.0",
|
||||
"@babel/register": "^7.16.0",
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/dev": "^0.63.27",
|
||||
"@polkadot/ts": "^0.4.13",
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/dev": "^0.63.29",
|
||||
"@polkadot/ts": "^0.4.14",
|
||||
"@polkadot/typegen": "workspace:packages/typegen",
|
||||
"@types/jest": "^27.0.2",
|
||||
"@types/jest": "^27.0.3",
|
||||
"copyfiles": "^2.4.1"
|
||||
},
|
||||
"resolutions": {
|
||||
"typescript": "^4.4.4"
|
||||
"typescript": "^4.5.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,13 +20,13 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/api": "6.7.2",
|
||||
"@polkadot/types": "6.7.2",
|
||||
"@polkadot/util": "^7.8.2",
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/api": "6.9.2",
|
||||
"@polkadot/types": "6.9.2",
|
||||
"@polkadot/util": "^7.9.2",
|
||||
"rxjs": "^7.4.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ export abstract class Base<ApiType extends ApiTypes> {
|
||||
this.api = api;
|
||||
this._decorateMethod = decorateMethod;
|
||||
|
||||
assert(!!(api && api.isConnected && api.tx && api.tx.contracts && Object.keys(api.tx.contracts).length), 'Your API has not been initialized correctly and it not decorated with the runtime interfaces for contracts as retrieved from the on-chain runtime');
|
||||
assert(!!(api && api.isConnected && api.tx), 'Your API has not been initialized correctly and is not connected to a chain');
|
||||
assert(!!(api.tx.contracts && Object.keys(api.tx.contracts).length), 'You need to connect to a chain with a runtime that supports contracts');
|
||||
assert(isFunction(api.tx.contracts.instantiateWithCode), 'You need to connect to a chain with a runtime with a V3 contracts module. The runtime does not expose api.tx.contracts.instantiateWithCode');
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { AnyJson } from '@polkadot/types/types';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import { decorateMethodPromise } from '@polkadot/api';
|
||||
import { toPromiseMethod } from '@polkadot/api';
|
||||
|
||||
import v0contractFlipper from '../../test/contracts/ink/v0/flipper.contract.json';
|
||||
import v0abiFlipper from '../../test/contracts/ink/v0/flipper.json';
|
||||
@@ -19,19 +19,19 @@ const v0wasmFlipper = fs.readFileSync(path.join(__dirname, '../../test/contracts
|
||||
describe('Code', (): void => {
|
||||
it('can construct with an individual ABI/WASM combo', (): void => {
|
||||
expect(
|
||||
() => new Code(mockApi, v0abiFlipper as AnyJson, v0wasmFlipper, decorateMethodPromise)
|
||||
() => new Code(mockApi, v0abiFlipper as AnyJson, v0wasmFlipper, toPromiseMethod)
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('can construct with an .contract ABI (v0)', (): void => {
|
||||
expect(
|
||||
() => new Code(mockApi, v0contractFlipper as AnyJson, null, decorateMethodPromise)
|
||||
() => new Code(mockApi, v0contractFlipper as AnyJson, null, toPromiseMethod)
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it.only('can construct with an .contract ABI (v1)', (): void => {
|
||||
expect(
|
||||
() => new Code(mockApi, v1contractFlipper as AnyJson, null, decorateMethodPromise)
|
||||
() => new Code(mockApi, v1contractFlipper as AnyJson, null, toPromiseMethod)
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/api-contract', version: '6.7.2' };
|
||||
export const packageInfo = { name: '@polkadot/api-contract', version: '6.9.2' };
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
import type { Hash } from '@polkadot/types/interfaces';
|
||||
import type { AnyJson } from '@polkadot/types/types';
|
||||
|
||||
import { ApiPromise, decorateMethodPromise } from '@polkadot/api';
|
||||
import { ApiPromise, toPromiseMethod } from '@polkadot/api';
|
||||
|
||||
import { Abi } from '../Abi';
|
||||
import { Blueprint as BaseBlueprint } from '../base';
|
||||
|
||||
export class Blueprint extends BaseBlueprint<'promise'> {
|
||||
constructor (api: ApiPromise, abi: AnyJson | Abi, codeHash: string | Hash) {
|
||||
super(api, abi, codeHash, decorateMethodPromise);
|
||||
super(api, abi, codeHash, toPromiseMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
import type { ApiPromise } from '@polkadot/api';
|
||||
import type { AnyJson } from '@polkadot/types/types';
|
||||
|
||||
import { decorateMethodPromise } from '@polkadot/api';
|
||||
import { toPromiseMethod } from '@polkadot/api';
|
||||
|
||||
import { Abi } from '../Abi';
|
||||
import { Code as BaseCode } from '../base';
|
||||
|
||||
export class Code extends BaseCode<'promise'> {
|
||||
constructor (api: ApiPromise, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined) {
|
||||
super(api, abi, wasm, decorateMethodPromise);
|
||||
super(api, abi, wasm, toPromiseMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
import type { AccountId } from '@polkadot/types/interfaces';
|
||||
import type { AnyJson } from '@polkadot/types/types';
|
||||
|
||||
import { ApiPromise, decorateMethodPromise } from '@polkadot/api';
|
||||
import { ApiPromise, toPromiseMethod } from '@polkadot/api';
|
||||
|
||||
import { Abi } from '../Abi';
|
||||
import { Contract as BaseContract } from '../base';
|
||||
|
||||
export class Contract extends BaseContract<'promise'> {
|
||||
constructor (api: ApiPromise, abi: AnyJson | Abi, address: string | AccountId) {
|
||||
super(api, abi, address, decorateMethodPromise);
|
||||
super(api, abi, address, toPromiseMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
import type { Hash } from '@polkadot/types/interfaces';
|
||||
import type { AnyJson } from '@polkadot/types/types';
|
||||
|
||||
import { ApiRx, decorateMethodRx } from '@polkadot/api';
|
||||
import { ApiRx, toRxMethod } from '@polkadot/api';
|
||||
|
||||
import { Abi } from '../Abi';
|
||||
import { Blueprint as BaseBlueprint } from '../base';
|
||||
|
||||
export class Blueprint extends BaseBlueprint<'rxjs'> {
|
||||
constructor (api: ApiRx, abi: AnyJson | Abi, codeHash: string | Hash) {
|
||||
super(api, abi, codeHash, decorateMethodRx);
|
||||
super(api, abi, codeHash, toRxMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
import type { ApiRx } from '@polkadot/api';
|
||||
import type { AnyJson } from '@polkadot/types/types';
|
||||
|
||||
import { decorateMethodRx } from '@polkadot/api';
|
||||
import { toRxMethod } from '@polkadot/api';
|
||||
|
||||
import { Abi } from '../Abi';
|
||||
import { Code as BaseCode } from '../base';
|
||||
|
||||
export class Code extends BaseCode<'rxjs'> {
|
||||
constructor (api: ApiRx, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined) {
|
||||
super(api, abi, wasm, decorateMethodRx);
|
||||
super(api, abi, wasm, toRxMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
import type { AccountId } from '@polkadot/types/interfaces';
|
||||
import type { AnyJson } from '@polkadot/types/types';
|
||||
|
||||
import { ApiRx, decorateMethodRx } from '@polkadot/api';
|
||||
import { ApiRx, toRxMethod } from '@polkadot/api';
|
||||
|
||||
import { Abi } from '../Abi';
|
||||
import { Contract as BaseContract } from '../base';
|
||||
|
||||
export class Contract extends BaseContract<'rxjs'> {
|
||||
constructor (api: ApiRx, abi: AnyJson | Abi, address: string | AccountId) {
|
||||
super(api, abi, address, decorateMethodRx);
|
||||
super(api, abi, address, toRxMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,19 +20,19 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/api": "6.7.2",
|
||||
"@polkadot/rpc-core": "6.7.2",
|
||||
"@polkadot/types": "6.7.2",
|
||||
"@polkadot/util": "^7.8.2",
|
||||
"@polkadot/util-crypto": "^7.8.2",
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/api": "6.9.2",
|
||||
"@polkadot/rpc-core": "6.9.2",
|
||||
"@polkadot/types": "6.9.2",
|
||||
"@polkadot/util": "^7.9.2",
|
||||
"@polkadot/util-crypto": "^7.9.2",
|
||||
"rxjs": "^7.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^7.8.2",
|
||||
"@polkadot/rpc-provider": "6.7.2"
|
||||
"@polkadot/keyring": "^7.9.2",
|
||||
"@polkadot/rpc-provider": "6.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ export * from './type';
|
||||
|
||||
interface Avail {
|
||||
instances: string[];
|
||||
methods: string[];
|
||||
withDetect?: boolean;
|
||||
}
|
||||
|
||||
@@ -54,19 +55,61 @@ export type ExactDerive = DeriveAllSections<typeof derive>;
|
||||
|
||||
// Enable derive only if some of these modules are available
|
||||
const checks: Record<string, Avail> = {
|
||||
contracts: { instances: ['contracts'] },
|
||||
council: { instances: ['council'], withDetect: true },
|
||||
crowdloan: { instances: ['crowdloan'] },
|
||||
democracy: { instances: ['democracy'] },
|
||||
elections: { instances: ['phragmenElection', 'electionsPhragmen', 'elections', 'council'], withDetect: true },
|
||||
imOnline: { instances: ['imOnline'] },
|
||||
membership: { instances: ['membership'] },
|
||||
parachains: { instances: ['parachains', 'registrar'] },
|
||||
session: { instances: ['session'] },
|
||||
society: { instances: ['society'] },
|
||||
staking: { instances: ['staking'] },
|
||||
technicalCommittee: { instances: ['technicalCommittee'], withDetect: true },
|
||||
treasury: { instances: ['treasury'] }
|
||||
contracts: {
|
||||
instances: ['contracts'],
|
||||
methods: []
|
||||
},
|
||||
council: {
|
||||
instances: ['council'],
|
||||
methods: [],
|
||||
withDetect: true
|
||||
},
|
||||
crowdloan: {
|
||||
instances: ['crowdloan'],
|
||||
methods: []
|
||||
},
|
||||
democracy: {
|
||||
instances: ['democracy'],
|
||||
methods: []
|
||||
},
|
||||
elections: {
|
||||
instances: ['phragmenElection', 'electionsPhragmen', 'elections', 'council'],
|
||||
methods: [],
|
||||
withDetect: true
|
||||
},
|
||||
imOnline: {
|
||||
instances: ['imOnline'],
|
||||
methods: []
|
||||
},
|
||||
membership: {
|
||||
instances: ['membership'],
|
||||
methods: []
|
||||
},
|
||||
parachains: {
|
||||
instances: ['parachains', 'registrar'],
|
||||
methods: []
|
||||
},
|
||||
session: {
|
||||
instances: ['session'],
|
||||
methods: []
|
||||
},
|
||||
society: {
|
||||
instances: ['society'],
|
||||
methods: []
|
||||
},
|
||||
staking: {
|
||||
instances: ['staking'],
|
||||
methods: ['erasRewardPoints']
|
||||
},
|
||||
technicalCommittee: {
|
||||
instances: ['technicalCommittee'],
|
||||
methods: [],
|
||||
withDetect: true
|
||||
},
|
||||
treasury: {
|
||||
instances: ['treasury'],
|
||||
methods: []
|
||||
}
|
||||
};
|
||||
|
||||
function getModuleInstances (api: ApiInterfaceRx, specName: string, moduleName: string): string[] {
|
||||
@@ -88,12 +131,27 @@ function injectFunctions (instanceId: string, api: ApiInterfaceRx, derives: Deri
|
||||
const filterInstances = (q: string) =>
|
||||
getModuleInstances(api, specName, q).some(filterQueryKeys);
|
||||
|
||||
const filterMethods = (instances: string[]) =>
|
||||
(m: string) =>
|
||||
instances.some((q) =>
|
||||
queryKeys.includes(q) &&
|
||||
!!api.query[q][m]
|
||||
);
|
||||
|
||||
const isIncluded = (s: string) => (
|
||||
!checks[s] ||
|
||||
checks[s].instances.some(filterQueryKeys) ||
|
||||
(
|
||||
checks[s].withDetect &&
|
||||
checks[s].instances.some(filterInstances)
|
||||
(
|
||||
checks[s].instances.some(filterQueryKeys) &&
|
||||
(
|
||||
!checks[s].methods.length ||
|
||||
checks[s].methods.every(filterMethods(checks[s].instances))
|
||||
)
|
||||
) ||
|
||||
(
|
||||
checks[s].withDetect &&
|
||||
checks[s].instances.some(filterInstances)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/api-derive', version: '6.7.2' };
|
||||
export const packageInfo = { name: '@polkadot/api-derive', version: '6.9.2' };
|
||||
|
||||
+10
-10
@@ -20,18 +20,18 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/api-derive": "6.7.2",
|
||||
"@polkadot/keyring": "^7.8.2",
|
||||
"@polkadot/rpc-core": "6.7.2",
|
||||
"@polkadot/rpc-provider": "6.7.2",
|
||||
"@polkadot/types": "6.7.2",
|
||||
"@polkadot/types-known": "6.7.2",
|
||||
"@polkadot/util": "^7.8.2",
|
||||
"@polkadot/util-crypto": "^7.8.2",
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/api-derive": "6.9.2",
|
||||
"@polkadot/keyring": "^7.9.2",
|
||||
"@polkadot/rpc-core": "6.9.2",
|
||||
"@polkadot/rpc-provider": "6.9.2",
|
||||
"@polkadot/types": "6.9.2",
|
||||
"@polkadot/types-known": "6.9.2",
|
||||
"@polkadot/util": "^7.9.2",
|
||||
"@polkadot/util-crypto": "^7.9.2",
|
||||
"eventemitter3": "^4.0.7",
|
||||
"rxjs": "^7.4.0"
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { ApiTypes } from '@polkadot/api/types';
|
||||
import type { BTreeMap, Bytes, Data, Null, Option, U8aFixed, Vec, WrapperOpaque, bool, u128, u32, u64, u8 } from '@polkadot/types';
|
||||
import type { AccountId32, Call, H256, Perbill, Percent } from '@polkadot/types/interfaces/runtime';
|
||||
import type { FrameSupportWeightsPerDispatchClassU64, FrameSystemAccountInfo, FrameSystemEventRecord, FrameSystemLastRuntimeUpgradeInfo, FrameSystemPhase, NodeRuntimeSessionKeys, PalletAssetsApproval, PalletAssetsAssetBalance, PalletAssetsAssetDetails, PalletAssetsAssetMetadata, PalletAuthorshipUncleEntryItem, PalletBagsListListBag, PalletBagsListListNode, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesReleases, PalletBalancesReserveData, PalletBountiesBounty, PalletCollectiveVotes, PalletContractsStorageDeletedContract, PalletContractsStorageRawContractInfo, PalletContractsWasmPrefabWasmModule, PalletDemocracyPreimageStatus, PalletDemocracyReferendumInfo, PalletDemocracyReleases, PalletDemocracyVoteThreshold, PalletDemocracyVoteVoting, PalletElectionProviderMultiPhasePhase, PalletElectionProviderMultiPhaseReadySolution, PalletElectionProviderMultiPhaseRoundSnapshot, PalletElectionProviderMultiPhaseSignedSignedSubmission, PalletElectionProviderMultiPhaseSolutionOrSnapshotSize, PalletElectionsPhragmenSeatHolder, PalletElectionsPhragmenVoter, PalletGiltActiveGilt, PalletGiltActiveGiltsTotal, PalletGiltGiltBid, PalletGrandpaStoredPendingChange, PalletGrandpaStoredState, PalletIdentityRegistrarInfo, PalletIdentityRegistration, PalletImOnlineBoundedOpaqueNetworkState, PalletImOnlineSr25519AppSr25519Public, PalletLotteryLotteryConfig, PalletMultisigMultisig, PalletProxyAnnouncement, PalletProxyProxyDefinition, PalletRecoveryActiveRecovery, PalletRecoveryRecoveryConfig, PalletSchedulerReleases, PalletSchedulerScheduledV2, PalletSocietyBid, PalletSocietyBidKind, PalletSocietyVote, PalletSocietyVouchingStatus, PalletStakingActiveEraInfo, PalletStakingEraRewardPoints, PalletStakingExposure, PalletStakingForcing, PalletStakingNominations, PalletStakingReleases, PalletStakingRewardDestination, PalletStakingSlashingSlashingSpans, PalletStakingSlashingSpanRecord, PalletStakingStakingLedger, PalletStakingUnappliedSlash, PalletStakingValidatorPrefs, PalletTipsOpenTip, PalletTransactionPaymentReleases, PalletTransactionStorageTransactionInfo, PalletTreasuryProposal, PalletUniquesClassDetails, PalletUniquesClassMetadata, PalletUniquesInstanceDetails, PalletUniquesInstanceMetadata, PalletVestingReleases, PalletVestingVestingInfo, SpAuthorityDiscoveryAppPublic, SpConsensusBabeAppPublic, SpConsensusBabeBabeEpochConfiguration, SpConsensusBabeDigestsNextConfigDescriptor, SpCoreCryptoKeyTypeId, SpRuntimeGenericDigest, SpStakingOffenceOffenceDetails } from '@polkadot/types/lookup';
|
||||
import type { FrameSupportWeightsPerDispatchClassU64, FrameSystemAccountInfo, FrameSystemEventRecord, FrameSystemLastRuntimeUpgradeInfo, FrameSystemPhase, NodeRuntimeSessionKeys, PalletAssetsApproval, PalletAssetsAssetBalance, PalletAssetsAssetDetails, PalletAssetsAssetMetadata, PalletAuthorshipUncleEntryItem, PalletBagsListListBag, PalletBagsListListNode, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesReleases, PalletBalancesReserveData, PalletBountiesBounty, PalletCollectiveVotes, PalletContractsStorageDeletedContract, PalletContractsStorageRawContractInfo, PalletContractsWasmPrefabWasmModule, PalletDemocracyPreimageStatus, PalletDemocracyReferendumInfo, PalletDemocracyReleases, PalletDemocracyVoteThreshold, PalletDemocracyVoteVoting, PalletElectionProviderMultiPhasePhase, PalletElectionProviderMultiPhaseReadySolution, PalletElectionProviderMultiPhaseRoundSnapshot, PalletElectionProviderMultiPhaseSignedSignedSubmission, PalletElectionProviderMultiPhaseSolutionOrSnapshotSize, PalletElectionsPhragmenSeatHolder, PalletElectionsPhragmenVoter, PalletGiltActiveGilt, PalletGiltActiveGiltsTotal, PalletGiltGiltBid, PalletGrandpaStoredPendingChange, PalletGrandpaStoredState, PalletIdentityRegistrarInfo, PalletIdentityRegistration, PalletImOnlineBoundedOpaqueNetworkState, PalletImOnlineSr25519AppSr25519Public, PalletLotteryLotteryConfig, PalletMultisigMultisig, PalletProxyAnnouncement, PalletProxyProxyDefinition, PalletRecoveryActiveRecovery, PalletRecoveryRecoveryConfig, PalletSchedulerReleases, PalletSchedulerScheduledV2, PalletSocietyBid, PalletSocietyBidKind, PalletSocietyVote, PalletSocietyVouchingStatus, PalletStakingActiveEraInfo, PalletStakingEraRewardPoints, PalletStakingExposure, PalletStakingForcing, PalletStakingNominations, PalletStakingReleases, PalletStakingRewardDestination, PalletStakingSlashingSlashingSpans, PalletStakingSlashingSpanRecord, PalletStakingStakingLedger, PalletStakingUnappliedSlash, PalletStakingValidatorPrefs, PalletTipsOpenTip, PalletTransactionPaymentReleases, PalletTransactionStorageTransactionInfo, PalletTreasuryProposal, PalletUniquesClassDetails, PalletUniquesClassMetadata, PalletUniquesInstanceDetails, PalletUniquesInstanceMetadata, PalletVestingReleases, PalletVestingVestingInfo, SpAuthorityDiscoveryAppPublic, SpConsensusBabeAppPublic, SpConsensusBabeBabeEpochConfiguration, SpConsensusBabeDigestsNextConfigDescriptor, SpCoreCryptoKeyTypeId, SpRuntimeDigest, SpStakingOffenceOffenceDetails } from '@polkadot/types/lookup';
|
||||
import type { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
|
||||
|
||||
declare module '@polkadot/api/types/storage' {
|
||||
@@ -1163,7 +1163,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* Digest of the current block, also part of the block header.
|
||||
**/
|
||||
digest: AugmentedQuery<ApiType, () => Observable<SpRuntimeGenericDigest>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
digest: AugmentedQuery<ApiType, () => Observable<SpRuntimeDigest>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The number of events in the `Events<T>` list.
|
||||
**/
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
|
||||
import type { Bytes, Compact, Data, Option, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types';
|
||||
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
|
||||
import type { AccountId32, Call, H256, MultiAddress, Perbill, Percent, Perquintill } from '@polkadot/types/interfaces/runtime';
|
||||
import type { NodeRuntimeOriginCaller, NodeRuntimeProxyType, NodeRuntimeSessionKeys, PalletAssetsDestroyWitness, PalletDemocracyConviction, PalletDemocracyVoteAccountVote, PalletElectionProviderMultiPhaseRawSolution, PalletElectionProviderMultiPhaseSolutionOrSnapshotSize, PalletElectionsPhragmenRenouncing, PalletIdentityBitFlags, PalletIdentityIdentityInfo, PalletIdentityJudgement, PalletImOnlineHeartbeat, PalletImOnlineSr25519AppSr25519Signature, PalletMultisigTimepoint, PalletSocietyJudgement, PalletStakingRewardDestination, PalletStakingValidatorPrefs, PalletUniquesDestroyWitness, PalletVestingVestingInfo, SpConsensusBabeDigestsNextConfigDescriptor, SpConsensusSlotsEquivocationProof, SpCoreChangesTrieChangesTrieConfiguration, SpFinalityGrandpaEquivocationProof, SpNposElectionsSupport, SpRuntimeGenericHeader, SpSessionMembershipProof, SpTransactionStorageProofTransactionStorageProof } from '@polkadot/types/lookup';
|
||||
import type { NodeRuntimeOriginCaller, NodeRuntimeProxyType, NodeRuntimeSessionKeys, PalletAssetsDestroyWitness, PalletDemocracyConviction, PalletDemocracyVoteAccountVote, PalletElectionProviderMultiPhaseRawSolution, PalletElectionProviderMultiPhaseSolutionOrSnapshotSize, PalletElectionsPhragmenRenouncing, PalletIdentityBitFlags, PalletIdentityIdentityInfo, PalletIdentityJudgement, PalletImOnlineHeartbeat, PalletImOnlineSr25519AppSr25519Signature, PalletMultisigTimepoint, PalletSocietyJudgement, PalletStakingRewardDestination, PalletStakingValidatorPrefs, PalletUniquesDestroyWitness, PalletVestingVestingInfo, SpConsensusBabeDigestsNextConfigDescriptor, SpConsensusSlotsEquivocationProof, SpCoreChangesTrieChangesTrieConfiguration, SpFinalityGrandpaEquivocationProof, SpNposElectionsSupport, SpRuntimeHeader, SpSessionMembershipProof, SpTransactionStorageProofTransactionStorageProof } from '@polkadot/types/lookup';
|
||||
import type { AnyNumber, ITuple } from '@polkadot/types/types';
|
||||
|
||||
declare module '@polkadot/api/types/submittable' {
|
||||
@@ -425,7 +425,7 @@ declare module '@polkadot/api/types/submittable' {
|
||||
/**
|
||||
* Provide a set of uncles.
|
||||
**/
|
||||
setUncles: AugmentedSubmittable<(newUncles: Vec<SpRuntimeGenericHeader> | (SpRuntimeGenericHeader | { parentHash?: any; number?: any; stateRoot?: any; extrinsicsRoot?: any; digest?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Vec<SpRuntimeGenericHeader>]>;
|
||||
setUncles: AugmentedSubmittable<(newUncles: Vec<SpRuntimeHeader> | (SpRuntimeHeader | { parentHash?: any; number?: any; stateRoot?: any; extrinsicsRoot?: any; digest?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Vec<SpRuntimeHeader>]>;
|
||||
/**
|
||||
* Generic tx
|
||||
**/
|
||||
|
||||
@@ -146,8 +146,8 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
|
||||
|
||||
this.#instanceId = `${++instanceCounter}`;
|
||||
this.#registry = options.source?.registry || options.registry || new TypeRegistry();
|
||||
this._rx.queryAt = (blockHash: Uint8Array | string) =>
|
||||
from(this.at(blockHash)).pipe(map((a) => a.rx.query));
|
||||
this._rx.queryAt = (blockHash: Uint8Array | string, knownVersion?: RuntimeVersion) =>
|
||||
from(this.at(blockHash, knownVersion)).pipe(map((a) => a.rx.query));
|
||||
this._rx.registry = this.#registry;
|
||||
|
||||
const thisProvider = options.source
|
||||
|
||||
@@ -5,6 +5,6 @@ export { Keyring } from '@polkadot/keyring';
|
||||
export { WsProvider, HttpProvider } from '@polkadot/rpc-provider';
|
||||
|
||||
export { packageInfo } from './packageInfo';
|
||||
export { ApiPromise, decorateMethod as decorateMethodPromise } from './promise';
|
||||
export * from './promise';
|
||||
export { SubmittableResult } from './submittable';
|
||||
export { ApiRx, decorateMethod as decorateMethodRx } from './rx';
|
||||
export * from './rx';
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/api', version: '6.7.2' };
|
||||
export const packageInfo = { name: '@polkadot/api', version: '6.9.2' };
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
// Copyright 2017-2021 @polkadot/api authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiOptions, UnsubscribePromise } from '../types';
|
||||
|
||||
import { objectSpread } from '@polkadot/util';
|
||||
|
||||
import { ApiBase } from '../base';
|
||||
import { Combinator, CombinatorCallback, CombinatorFunction } from './Combinator';
|
||||
import { promiseTracker, toPromiseMethod } from './decorateMethod';
|
||||
|
||||
/**
|
||||
* # @polkadot/api/promise
|
||||
*
|
||||
* ## Overview
|
||||
*
|
||||
* @name ApiPromise
|
||||
* @description
|
||||
* ApiPromise is a standard JavaScript wrapper around the RPC and interfaces on the Polkadot network. As a full Promise-based, all interface calls return Promises, including the static `.create(...)`. Subscription calls utilise `(value) => {}` callbacks to pass through the latest values.
|
||||
*
|
||||
* The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of the subscription-based features of Polkadot (and Substrate) clients.
|
||||
*
|
||||
* @see [[ApiRx]]
|
||||
*
|
||||
* ## Usage
|
||||
*
|
||||
* Making rpc calls -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import ApiPromise from '@polkadot/api/promise';
|
||||
*
|
||||
* // initialise via static create
|
||||
* const api = await ApiPromise.create();
|
||||
*
|
||||
* // make a subscription to the network head
|
||||
* api.rpc.chain.subscribeNewHeads((header) => {
|
||||
* console.log(`Chain is at #${header.number}`);
|
||||
* });
|
||||
* ```
|
||||
* <BR>
|
||||
*
|
||||
* Subscribing to chain state -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { ApiPromise, WsProvider } from '@polkadot/api';
|
||||
*
|
||||
* // initialise a provider with a specific endpoint
|
||||
* const provider = new WsProvider('wss://example.com:9944')
|
||||
*
|
||||
* // initialise via isReady & new with specific provider
|
||||
* const api = await new ApiPromise({ provider }).isReady;
|
||||
*
|
||||
* // retrieve the block target time
|
||||
* const blockPeriod = await api.query.timestamp.blockPeriod().toNumber();
|
||||
* let last = 0;
|
||||
*
|
||||
* // subscribe to the current block timestamp, updates automatically (callback provided)
|
||||
* api.query.timestamp.now((timestamp) => {
|
||||
* const elapsed = last
|
||||
* ? `, ${timestamp.toNumber() - last}s since last`
|
||||
* : '';
|
||||
*
|
||||
* last = timestamp.toNumber();
|
||||
* console.log(`timestamp ${timestamp}${elapsed} (${blockPeriod}s target)`);
|
||||
* });
|
||||
* ```
|
||||
* <BR>
|
||||
*
|
||||
* Submitting a transaction -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import ApiPromise from '@polkadot/api/promise';
|
||||
*
|
||||
* ApiPromise.create().then((api) => {
|
||||
* const [nonce] = await api.query.system.account(keyring.alice.address);
|
||||
*
|
||||
* api.tx.balances
|
||||
* // create transfer
|
||||
* transfer(keyring.bob.address, 12345)
|
||||
* // sign the transcation
|
||||
* .sign(keyring.alice, { nonce })
|
||||
* // send the transaction (optional status callback)
|
||||
* .send((status) => {
|
||||
* console.log(`current status ${status.type}`);
|
||||
* })
|
||||
* // retrieve the submitted extrinsic hash
|
||||
* .then((hash) => {
|
||||
* console.log(`submitted with hash ${hash}`);
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export class ApiPromise extends ApiBase<'promise'> {
|
||||
#isReadyPromise: Promise<ApiPromise>;
|
||||
#isReadyOrErrorPromise: Promise<ApiPromise>;
|
||||
|
||||
/**
|
||||
* @description Creates an instance of the ApiPromise class
|
||||
* @param options Options to create an instance. This can be either [[ApiOptions]] or
|
||||
* an [[WsProvider]].
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import Api from '@polkadot/api/promise';
|
||||
*
|
||||
* new Api().isReady.then((api) => {
|
||||
* api.rpc.subscribeNewHeads((header) => {
|
||||
* console.log(`new block #${header.number.toNumber()}`);
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
constructor (options?: ApiOptions) {
|
||||
super(options, 'promise', toPromiseMethod);
|
||||
|
||||
this.#isReadyPromise = new Promise((resolve): void => {
|
||||
super.once('ready', () => resolve(this));
|
||||
});
|
||||
|
||||
this.#isReadyOrErrorPromise = new Promise((resolve, reject): void => {
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
super.once('ready', () => tracker.resolve(this));
|
||||
super.once('error', (error: Error) => tracker.reject(error));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.
|
||||
* @param options options that is passed to the class contructor. Can be either [[ApiOptions]] or a
|
||||
* provider (see the constructor arguments)
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import Api from '@polkadot/api/promise';
|
||||
*
|
||||
* Api.create().then(async (api) => {
|
||||
* const timestamp = await api.query.timestamp.now();
|
||||
*
|
||||
* console.log(`lastest block timestamp ${timestamp}`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
public static create (options?: ApiOptions): Promise<ApiPromise> {
|
||||
const instance = new ApiPromise(options);
|
||||
|
||||
if (options && options.throwOnConnect) {
|
||||
return instance.isReadyOrError;
|
||||
}
|
||||
|
||||
// Swallow any rejections on isReadyOrError
|
||||
// (in Node 15.x this creates issues, when not being looked at)
|
||||
instance.isReadyOrError.catch(() => {
|
||||
// ignore
|
||||
});
|
||||
|
||||
return instance.isReady;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Promise that resolves the first time we are connected and loaded
|
||||
*/
|
||||
public get isReady (): Promise<ApiPromise> {
|
||||
return this.#isReadyPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Promise that resolves if we can connect, or reject if there is an error
|
||||
*/
|
||||
public get isReadyOrError (): Promise<ApiPromise> {
|
||||
return this.#isReadyOrErrorPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a clone of this ApiPromise instance (new underlying provider connection)
|
||||
*/
|
||||
public clone (): ApiPromise {
|
||||
return new ApiPromise(
|
||||
objectSpread({}, this._options, { source: this })
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates a combinator that can be used to combine the latest results from multiple subscriptions
|
||||
* @param fns An array of function to combine, each in the form of `(cb: (value: void)) => void`
|
||||
* @param callback A callback that will return an Array of all the values this combinator has been applied to
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7';
|
||||
*
|
||||
* // combines values from balance & nonce as it updates
|
||||
* api.combineLatest([
|
||||
* api.rpc.chain.subscribeNewHeads,
|
||||
* (cb) => api.query.system.account(address, cb)
|
||||
* ], ([head, [balance, nonce]]) => {
|
||||
* console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
public async combineLatest <T extends any[] = any[]> (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback<T>): UnsubscribePromise {
|
||||
const combinator = new Combinator(fns, callback);
|
||||
|
||||
return (): void => {
|
||||
combinator.unsubscribe();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Copyright 2017-2021 @polkadot/api authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Observable } from 'rxjs';
|
||||
import type { Callback, Codec } from '@polkadot/types/types';
|
||||
import type { DecorateFn, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise, VoidFn } from '../types';
|
||||
|
||||
import { catchError, EMPTY, Subscription, tap } from 'rxjs';
|
||||
|
||||
import { assert, isFunction } from '@polkadot/util';
|
||||
|
||||
interface Tracker<T> {
|
||||
reject: (value: Error) => Observable<never>;
|
||||
resolve: (value: T) => void;
|
||||
}
|
||||
|
||||
// a Promise completion tracker, wrapping an isComplete variable that ensures the promise only resolves once
|
||||
export function promiseTracker<T> (resolve: (value: T) => void, reject: (value: Error) => void): Tracker<T> {
|
||||
let isCompleted = false;
|
||||
|
||||
return {
|
||||
reject: (error: Error): Observable<never> => {
|
||||
if (!isCompleted) {
|
||||
isCompleted = true;
|
||||
|
||||
reject(error);
|
||||
}
|
||||
|
||||
return EMPTY;
|
||||
},
|
||||
resolve: (value: T): void => {
|
||||
if (!isCompleted) {
|
||||
isCompleted = true;
|
||||
|
||||
resolve(value);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// extract the arguments and callback params from a value array possibly containing a callback
|
||||
function extractArgs (args: unknown[], needsCallback: boolean): [unknown[], Callback<Codec> | undefined] {
|
||||
let callback: Callback<Codec> | undefined;
|
||||
const actualArgs = args.slice();
|
||||
|
||||
// If the last arg is a function, we pop it, put it into callback.
|
||||
// actualArgs will then hold the actual arguments to be passed to `method`
|
||||
if (args.length && isFunction(args[args.length - 1])) {
|
||||
callback = actualArgs.pop() as Callback<Codec>;
|
||||
}
|
||||
|
||||
// When we need a subscription, ensure that a valid callback is actually passed
|
||||
assert(!needsCallback || isFunction(callback), 'Expected a callback to be passed with subscriptions');
|
||||
|
||||
return [actualArgs, callback];
|
||||
}
|
||||
|
||||
// Decorate a call for a single-shot result - retrieve and then immediate unsubscribe
|
||||
function decorateCall<M extends DecorateFn<ObsInnerType<ReturnType<M>>>> (method: M, args: unknown[]): Promise<ObsInnerType<ReturnType<M>>> {
|
||||
return new Promise((resolve, reject): void => {
|
||||
// single result tracker - either reject with Error or resolve with Codec result
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
// encoding errors reject immediately, any result unsubscribes and resolves
|
||||
const subscription: Subscription = method(...args)
|
||||
.pipe(
|
||||
catchError((error: Error) => tracker.reject(error))
|
||||
)
|
||||
.subscribe((result): void => {
|
||||
tracker.resolve(result);
|
||||
setTimeout(() => subscription.unsubscribe(), 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Decorate a subscription where we have a result callback specified
|
||||
function decorateSubscribe<M extends DecorateFn<ObsInnerType<ReturnType<M>>>> (method: M, args: unknown[], resultCb: Callback<Codec>): UnsubscribePromise {
|
||||
return new Promise<VoidFn>((resolve, reject): void => {
|
||||
// either reject with error or resolve with unsubscribe callback
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
// errors reject immediately, the first result resolves with an unsubscribe promise, all results via callback
|
||||
const subscription: Subscription = method(...args)
|
||||
.pipe(
|
||||
catchError((error: Error) => tracker.reject(error)),
|
||||
tap(() => tracker.resolve(() => subscription.unsubscribe()))
|
||||
)
|
||||
.subscribe((result): void => {
|
||||
// queue result (back of queue to clear current)
|
||||
setTimeout(() => resultCb(result) as void, 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent
|
||||
*/
|
||||
export function toPromiseMethod<M extends DecorateFn<ObsInnerType<ReturnType<M>>>> (method: M, options?: DecorateMethodOptions): StorageEntryPromiseOverloads {
|
||||
const needsCallback = !!(options && options.methodName && options.methodName.includes('subscribe'));
|
||||
|
||||
return function (...args: unknown[]): Promise<ObsInnerType<ReturnType<M>>> | UnsubscribePromise {
|
||||
const [actualArgs, resultCb] = extractArgs(args, needsCallback);
|
||||
|
||||
return resultCb
|
||||
? decorateSubscribe(method, actualArgs, resultCb)
|
||||
: decorateCall((options?.overrideNoSub as M) || method, actualArgs);
|
||||
} as StorageEntryPromiseOverloads;
|
||||
}
|
||||
@@ -1,312 +1,5 @@
|
||||
// Copyright 2017-2021 @polkadot/api authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Observable } from 'rxjs';
|
||||
import type { Callback, Codec } from '@polkadot/types/types';
|
||||
import type { ApiOptions, DecorateFn, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise, VoidFn } from '../types';
|
||||
|
||||
import { catchError, EMPTY, Subscription, tap } from 'rxjs';
|
||||
|
||||
import { assert, isFunction, objectSpread } from '@polkadot/util';
|
||||
|
||||
import { ApiBase } from '../base';
|
||||
import { Combinator, CombinatorCallback, CombinatorFunction } from './Combinator';
|
||||
|
||||
interface Tracker<T> {
|
||||
reject: (value: Error) => Observable<never>;
|
||||
resolve: (value: T) => void;
|
||||
}
|
||||
|
||||
// extract the arguments and callback params from a value array possibly containing a callback
|
||||
function extractArgs (args: unknown[], needsCallback: boolean): [unknown[], Callback<Codec> | undefined] {
|
||||
let callback: Callback<Codec> | undefined;
|
||||
const actualArgs = args.slice();
|
||||
|
||||
// If the last arg is a function, we pop it, put it into callback.
|
||||
// actualArgs will then hold the actual arguments to be passed to `method`
|
||||
if (args.length && isFunction(args[args.length - 1])) {
|
||||
callback = actualArgs.pop() as Callback<Codec>;
|
||||
}
|
||||
|
||||
// When we need a subscription, ensure that a valid callback is actually passed
|
||||
assert(!needsCallback || isFunction(callback), 'Expected a callback to be passed with subscriptions');
|
||||
|
||||
return [actualArgs, callback];
|
||||
}
|
||||
|
||||
// a Promise completion tracker, wrapping an isComplete variable that ensures the promise only resolves once
|
||||
function promiseTracker<T> (resolve: (value: T) => void, reject: (value: Error) => void): Tracker<T> {
|
||||
let isCompleted = false;
|
||||
|
||||
return {
|
||||
reject: (error: Error): Observable<never> => {
|
||||
if (!isCompleted) {
|
||||
isCompleted = true;
|
||||
|
||||
reject(error);
|
||||
}
|
||||
|
||||
return EMPTY;
|
||||
},
|
||||
resolve: (value: T): void => {
|
||||
if (!isCompleted) {
|
||||
isCompleted = true;
|
||||
|
||||
resolve(value);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Decorate a call for a single-shot result - retrieve and then immediate unsubscribe
|
||||
function decorateCall<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>>> (method: Method, actualArgs: unknown[]): Promise<ObsInnerType<ReturnType<Method>>> {
|
||||
return new Promise((resolve, reject): void => {
|
||||
// single result tracker - either reject with Error or resolve with Codec result
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
// encoding errors reject immediately, any result unsubscribes and resolves
|
||||
const subscription: Subscription = method(...actualArgs).pipe(
|
||||
catchError((error: Error) => tracker.reject(error))
|
||||
).subscribe((result): void => {
|
||||
tracker.resolve(result);
|
||||
setTimeout(() => subscription.unsubscribe(), 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Decorate a subscription where we have a result callback specified
|
||||
function decorateSubscribe<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>>> (method: Method, actualArgs: unknown[], resultCb: Callback<Codec>): UnsubscribePromise {
|
||||
return new Promise<VoidFn>((resolve, reject): void => {
|
||||
// either reject with error or resolve with unsubscribe callback
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
// errors reject immediately, the first result resolves with an unsubscribe promise, all results via callback
|
||||
const subscription: Subscription = method(...actualArgs).pipe(
|
||||
catchError((error: Error) => tracker.reject(error)),
|
||||
tap(() => tracker.resolve(() => subscription.unsubscribe()))
|
||||
).subscribe((result): void => {
|
||||
// queue result (back of queue to clear current)
|
||||
setTimeout(() => resultCb(result) as void, 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent
|
||||
*/
|
||||
export function decorateMethod<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>>> (method: Method, options?: DecorateMethodOptions): StorageEntryPromiseOverloads {
|
||||
const needsCallback = options && options.methodName && options.methodName.includes('subscribe');
|
||||
|
||||
return function (...args: unknown[]): Promise<ObsInnerType<ReturnType<Method>>> | UnsubscribePromise {
|
||||
const [actualArgs, resultCb] = extractArgs(args, !!needsCallback);
|
||||
|
||||
return resultCb
|
||||
? decorateSubscribe(method, actualArgs, resultCb)
|
||||
: decorateCall((options?.overrideNoSub as Method) || method, actualArgs);
|
||||
} as StorageEntryPromiseOverloads;
|
||||
}
|
||||
|
||||
/**
|
||||
* # @polkadot/api/promise
|
||||
*
|
||||
* ## Overview
|
||||
*
|
||||
* @name ApiPromise
|
||||
* @description
|
||||
* ApiPromise is a standard JavaScript wrapper around the RPC and interfaces on the Polkadot network. As a full Promise-based, all interface calls return Promises, including the static `.create(...)`. Subscription calls utilise `(value) => {}` callbacks to pass through the latest values.
|
||||
*
|
||||
* The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of the subscription-based features of Polkadot (and Substrate) clients.
|
||||
*
|
||||
* @see [[ApiRx]]
|
||||
*
|
||||
* ## Usage
|
||||
*
|
||||
* Making rpc calls -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import ApiPromise from '@polkadot/api/promise';
|
||||
*
|
||||
* // initialise via static create
|
||||
* const api = await ApiPromise.create();
|
||||
*
|
||||
* // make a subscription to the network head
|
||||
* api.rpc.chain.subscribeNewHeads((header) => {
|
||||
* console.log(`Chain is at #${header.number}`);
|
||||
* });
|
||||
* ```
|
||||
* <BR>
|
||||
*
|
||||
* Subscribing to chain state -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { ApiPromise, WsProvider } from '@polkadot/api';
|
||||
*
|
||||
* // initialise a provider with a specific endpoint
|
||||
* const provider = new WsProvider('wss://example.com:9944')
|
||||
*
|
||||
* // initialise via isReady & new with specific provider
|
||||
* const api = await new ApiPromise({ provider }).isReady;
|
||||
*
|
||||
* // retrieve the block target time
|
||||
* const blockPeriod = await api.query.timestamp.blockPeriod().toNumber();
|
||||
* let last = 0;
|
||||
*
|
||||
* // subscribe to the current block timestamp, updates automatically (callback provided)
|
||||
* api.query.timestamp.now((timestamp) => {
|
||||
* const elapsed = last
|
||||
* ? `, ${timestamp.toNumber() - last}s since last`
|
||||
* : '';
|
||||
*
|
||||
* last = timestamp.toNumber();
|
||||
* console.log(`timestamp ${timestamp}${elapsed} (${blockPeriod}s target)`);
|
||||
* });
|
||||
* ```
|
||||
* <BR>
|
||||
*
|
||||
* Submitting a transaction -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import ApiPromise from '@polkadot/api/promise';
|
||||
*
|
||||
* ApiPromise.create().then((api) => {
|
||||
* const [nonce] = await api.query.system.account(keyring.alice.address);
|
||||
*
|
||||
* api.tx.balances
|
||||
* // create transfer
|
||||
* transfer(keyring.bob.address, 12345)
|
||||
* // sign the transcation
|
||||
* .sign(keyring.alice, { nonce })
|
||||
* // send the transaction (optional status callback)
|
||||
* .send((status) => {
|
||||
* console.log(`current status ${status.type}`);
|
||||
* })
|
||||
* // retrieve the submitted extrinsic hash
|
||||
* .then((hash) => {
|
||||
* console.log(`submitted with hash ${hash}`);
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export class ApiPromise extends ApiBase<'promise'> {
|
||||
#isReadyPromise: Promise<ApiPromise>;
|
||||
#isReadyOrErrorPromise: Promise<ApiPromise>;
|
||||
|
||||
/**
|
||||
* @description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.
|
||||
* @param options options that is passed to the class contructor. Can be either [[ApiOptions]] or a
|
||||
* provider (see the constructor arguments)
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import Api from '@polkadot/api/promise';
|
||||
*
|
||||
* Api.create().then(async (api) => {
|
||||
* const timestamp = await api.query.timestamp.now();
|
||||
*
|
||||
* console.log(`lastest block timestamp ${timestamp}`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
public static create (options?: ApiOptions): Promise<ApiPromise> {
|
||||
const instance = new ApiPromise(options);
|
||||
|
||||
if (options && options.throwOnConnect) {
|
||||
return instance.isReadyOrError;
|
||||
}
|
||||
|
||||
// Swallow any rejections on isReadyOrError
|
||||
// (in Node 15.x this creates issues, when not being looked at)
|
||||
instance.isReadyOrError.catch(() => {
|
||||
// ignore
|
||||
});
|
||||
|
||||
return instance.isReady;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates an instance of the ApiPromise class
|
||||
* @param options Options to create an instance. This can be either [[ApiOptions]] or
|
||||
* an [[WsProvider]].
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import Api from '@polkadot/api/promise';
|
||||
*
|
||||
* new Api().isReady.then((api) => {
|
||||
* api.rpc.subscribeNewHeads((header) => {
|
||||
* console.log(`new block #${header.number.toNumber()}`);
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
constructor (options?: ApiOptions) {
|
||||
super(options, 'promise', decorateMethod);
|
||||
|
||||
this.#isReadyPromise = new Promise((resolve): void => {
|
||||
super.once('ready', () => resolve(this));
|
||||
});
|
||||
|
||||
this.#isReadyOrErrorPromise = new Promise((resolve, reject): void => {
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
super.once('ready', () => tracker.resolve(this));
|
||||
super.once('error', (error: Error) => tracker.reject(error));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Promise that resolves the first time we are connected and loaded
|
||||
*/
|
||||
public get isReady (): Promise<ApiPromise> {
|
||||
return this.#isReadyPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Promise that resolves if we can connect, or reject if there is an error
|
||||
*/
|
||||
public get isReadyOrError (): Promise<ApiPromise> {
|
||||
return this.#isReadyOrErrorPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a clone of this ApiPromise instance (new underlying provider connection)
|
||||
*/
|
||||
public clone (): ApiPromise {
|
||||
return new ApiPromise(
|
||||
objectSpread({}, this._options, { source: this })
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates a combinator that can be used to combine the latest results from multiple subscriptions
|
||||
* @param fns An array of function to combine, each in the form of `(cb: (value: void)) => void`
|
||||
* @param callback A callback that will return an Array of all the values this combinator has been applied to
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7';
|
||||
*
|
||||
* // combines values from balance & nonce as it updates
|
||||
* api.combineLatest([
|
||||
* api.rpc.chain.subscribeNewHeads,
|
||||
* (cb) => api.query.system.account(address, cb)
|
||||
* ], ([head, [balance, nonce]]) => {
|
||||
* console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
public async combineLatest <T extends any[] = any[]> (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback<T>): UnsubscribePromise {
|
||||
const combinator = new Combinator(fns, callback);
|
||||
|
||||
return (): void => {
|
||||
combinator.unsubscribe();
|
||||
};
|
||||
}
|
||||
}
|
||||
export { ApiPromise } from './Api';
|
||||
export { toPromiseMethod } from './decorateMethod';
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// Copyright 2017-2021 @polkadot/api authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiOptions } from '../types';
|
||||
|
||||
import { from, Observable } from 'rxjs';
|
||||
|
||||
import { objectSpread } from '@polkadot/util';
|
||||
|
||||
import { ApiBase } from '../base';
|
||||
import { toRxMethod } from './decorateMethod';
|
||||
|
||||
/**
|
||||
* # @polkadot/api/rx
|
||||
*
|
||||
* ## Overview
|
||||
*
|
||||
* @name ApiRx
|
||||
*
|
||||
* @description
|
||||
* ApiRx is a powerful RxJS Observable wrapper around the RPC and interfaces on the Polkadot network. As a full Observable API, all interface calls return RxJS Observables, including the static `.create(...)`. In the same fashion and subscription-based methods return long-running Observables that update with the latest values.
|
||||
*
|
||||
* The API is well suited to real-time applications where the latest state is needed, unlocking the subscription-based features of Polkadot (and Substrate) clients. Some familiarity with RxJS is a requirement to use the API, however just understanding `.subscribe` and `.pipe` on Observables will unlock full-scale use thereof.
|
||||
*
|
||||
* @see [[ApiPromise]]
|
||||
*
|
||||
* ## Usage
|
||||
*
|
||||
* Making rpc calls -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import ApiRx from '@polkadot/api/rx';
|
||||
*
|
||||
* // initialize via Promise & static create
|
||||
* const api = await ApiRx.create().toPromise();
|
||||
*
|
||||
* // make a call to retrieve the current network head
|
||||
* api.rpc.chain.subscribeNewHeads().subscribe((header) => {
|
||||
* console.log(`Chain is at #${header.number}`);
|
||||
* });
|
||||
* ```
|
||||
* <BR>
|
||||
*
|
||||
* Subscribing to chain state -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { combineLatest, pairwise, switchMap } from 'rxjs';
|
||||
* import { ApiRx, WsProvider } from '@polkadot/api';
|
||||
*
|
||||
*
|
||||
* // initialize a provider with a specific endpoint
|
||||
* const provider = new WsProvider('wss://example.com:9944')
|
||||
*
|
||||
* // initialize via isReady & new with specific provider
|
||||
* new ApiRx({ provider })
|
||||
* .isReady
|
||||
* .pipe(
|
||||
* switchMap((api) =>
|
||||
* combineLatest([
|
||||
* api.query.timestamp.blockPeriod(),
|
||||
* api.query.timestamp.now().pipe(pairwise())
|
||||
* ])
|
||||
* )
|
||||
* )
|
||||
* .subscribe(([blockPeriod, timestamp]) => {
|
||||
* const elapsed = timestamp[1].toNumber() - timestamp[0].toNumber();
|
||||
* console.log(`timestamp ${timestamp[1]} \nelapsed ${elapsed} \n(${blockPeriod}s target)`);
|
||||
* });
|
||||
* ```
|
||||
* <BR>
|
||||
*
|
||||
* Submitting a transaction -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { first, switchMap } from 'rxjs';
|
||||
* import ApiRx from '@polkadot/api/rx';
|
||||
*
|
||||
* // import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
|
||||
* import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
* const keyring = testingPairs();
|
||||
*
|
||||
* // get api via Promise
|
||||
* const api = await ApiRx.create().toPromise();
|
||||
*
|
||||
* // retrieve nonce for the account
|
||||
* api.query.system
|
||||
* .account(keyring.alice.address)
|
||||
* .pipe(
|
||||
* first(),
|
||||
* // pipe nonce into transfer
|
||||
* switchMap(([nonce]) =>
|
||||
* api.tx.balances
|
||||
* // create transfer
|
||||
* .transfer(keyring.bob.address, 12345)
|
||||
* // sign the transaction
|
||||
* .sign(keyring.alice, { nonce })
|
||||
* // send the transaction
|
||||
* .send()
|
||||
* )
|
||||
* )
|
||||
* // subscribe to overall result
|
||||
* .subscribe(({ status }) => {
|
||||
* if (status.isInBlock) {
|
||||
* console.log('Completed at block hash', status.asFinalized.toHex());
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export class ApiRx extends ApiBase<'rxjs'> {
|
||||
#isReadyRx: Observable<ApiRx>;
|
||||
|
||||
/**
|
||||
* @description Create an instance of the ApiRx class
|
||||
* @param options Options to create an instance. Can be either [[ApiOptions]] or [[WsProvider]]
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { switchMap } from 'rxjs';
|
||||
* import Api from '@polkadot/api/rx';
|
||||
*
|
||||
* new Api().isReady
|
||||
* .pipe(
|
||||
* switchMap((api) =>
|
||||
* api.rpc.chain.subscribeNewHeads()
|
||||
* ))
|
||||
* .subscribe((header) => {
|
||||
* console.log(`new block #${header.number.toNumber()}`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
constructor (options?: ApiOptions) {
|
||||
super(options, 'rxjs', toRxMethod);
|
||||
|
||||
this.#isReadyRx = from<Promise<ApiRx>>(
|
||||
// You can create an observable from an event, however my mind groks this form better
|
||||
new Promise((resolve): void => {
|
||||
super.on('ready', () => resolve(this));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance.
|
||||
* @param options options that is passed to the class constructor. Can be either [[ApiOptions]] or [[WsProvider]]
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { switchMap } from 'rxjs';
|
||||
* import Api from '@polkadot/api/rx';
|
||||
*
|
||||
* Api.create()
|
||||
* .pipe(
|
||||
* switchMap((api) =>
|
||||
* api.rpc.chain.subscribeNewHeads()
|
||||
* ))
|
||||
* .subscribe((header) => {
|
||||
* console.log(`new block #${header.number.toNumber()}`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
public static create (options?: ApiOptions): Observable<ApiRx> {
|
||||
return new ApiRx(options).isReady;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Observable that returns the first time we are connected and loaded
|
||||
*/
|
||||
public get isReady (): Observable<ApiRx> {
|
||||
return this.#isReadyRx;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a clone of this ApiRx instance (new underlying provider connection)
|
||||
*/
|
||||
public clone (): ApiRx {
|
||||
return new ApiRx(
|
||||
objectSpread({}, this._options, { source: this })
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2017-2021 @polkadot/api authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec } from '@polkadot/types/types';
|
||||
import type { DecorateFn } from '../types';
|
||||
|
||||
export function toRxMethod <M extends DecorateFn<Codec>> (method: M): M {
|
||||
return method;
|
||||
}
|
||||
@@ -1,189 +1,5 @@
|
||||
// Copyright 2017-2021 @polkadot/api authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec } from '@polkadot/types/types';
|
||||
import type { ApiOptions, DecorateFn } from '../types';
|
||||
|
||||
import { from, Observable } from 'rxjs';
|
||||
|
||||
import { objectSpread } from '@polkadot/util';
|
||||
|
||||
import { ApiBase } from '../base';
|
||||
|
||||
export function decorateMethod <Method extends DecorateFn<Codec>> (method: Method): Method {
|
||||
return method;
|
||||
}
|
||||
|
||||
/**
|
||||
* # @polkadot/api/rx
|
||||
*
|
||||
* ## Overview
|
||||
*
|
||||
* @name ApiRx
|
||||
*
|
||||
* @description
|
||||
* ApiRx is a powerful RxJS Observable wrapper around the RPC and interfaces on the Polkadot network. As a full Observable API, all interface calls return RxJS Observables, including the static `.create(...)`. In the same fashion and subscription-based methods return long-running Observables that update with the latest values.
|
||||
*
|
||||
* The API is well suited to real-time applications where the latest state is needed, unlocking the subscription-based features of Polkadot (and Substrate) clients. Some familiarity with RxJS is a requirement to use the API, however just understanding `.subscribe` and `.pipe` on Observables will unlock full-scale use thereof.
|
||||
*
|
||||
* @see [[ApiPromise]]
|
||||
*
|
||||
* ## Usage
|
||||
*
|
||||
* Making rpc calls -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import ApiRx from '@polkadot/api/rx';
|
||||
*
|
||||
* // initialize via Promise & static create
|
||||
* const api = await ApiRx.create().toPromise();
|
||||
*
|
||||
* // make a call to retrieve the current network head
|
||||
* api.rpc.chain.subscribeNewHeads().subscribe((header) => {
|
||||
* console.log(`Chain is at #${header.number}`);
|
||||
* });
|
||||
* ```
|
||||
* <BR>
|
||||
*
|
||||
* Subscribing to chain state -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { combineLatest, pairwise, switchMap } from 'rxjs';
|
||||
* import { ApiRx, WsProvider } from '@polkadot/api';
|
||||
*
|
||||
*
|
||||
* // initialize a provider with a specific endpoint
|
||||
* const provider = new WsProvider('wss://example.com:9944')
|
||||
*
|
||||
* // initialize via isReady & new with specific provider
|
||||
* new ApiRx({ provider })
|
||||
* .isReady
|
||||
* .pipe(
|
||||
* switchMap((api) =>
|
||||
* combineLatest([
|
||||
* api.query.timestamp.blockPeriod(),
|
||||
* api.query.timestamp.now().pipe(pairwise())
|
||||
* ])
|
||||
* )
|
||||
* )
|
||||
* .subscribe(([blockPeriod, timestamp]) => {
|
||||
* const elapsed = timestamp[1].toNumber() - timestamp[0].toNumber();
|
||||
* console.log(`timestamp ${timestamp[1]} \nelapsed ${elapsed} \n(${blockPeriod}s target)`);
|
||||
* });
|
||||
* ```
|
||||
* <BR>
|
||||
*
|
||||
* Submitting a transaction -
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { first, switchMap } from 'rxjs';
|
||||
* import ApiRx from '@polkadot/api/rx';
|
||||
*
|
||||
* // import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
|
||||
* import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
* const keyring = testingPairs();
|
||||
*
|
||||
* // get api via Promise
|
||||
* const api = await ApiRx.create().toPromise();
|
||||
*
|
||||
* // retrieve nonce for the account
|
||||
* api.query.system
|
||||
* .account(keyring.alice.address)
|
||||
* .pipe(
|
||||
* first(),
|
||||
* // pipe nonce into transfer
|
||||
* switchMap(([nonce]) =>
|
||||
* api.tx.balances
|
||||
* // create transfer
|
||||
* .transfer(keyring.bob.address, 12345)
|
||||
* // sign the transaction
|
||||
* .sign(keyring.alice, { nonce })
|
||||
* // send the transaction
|
||||
* .send()
|
||||
* )
|
||||
* )
|
||||
* // subscribe to overall result
|
||||
* .subscribe(({ status }) => {
|
||||
* if (status.isInBlock) {
|
||||
* console.log('Completed at block hash', status.asFinalized.toHex());
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export class ApiRx extends ApiBase<'rxjs'> {
|
||||
#isReadyRx: Observable<ApiRx>;
|
||||
|
||||
/**
|
||||
* @description Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance.
|
||||
* @param options options that is passed to the class constructor. Can be either [[ApiOptions]] or [[WsProvider]]
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { switchMap } from 'rxjs';
|
||||
* import Api from '@polkadot/api/rx';
|
||||
*
|
||||
* Api.create()
|
||||
* .pipe(
|
||||
* switchMap((api) =>
|
||||
* api.rpc.chain.subscribeNewHeads()
|
||||
* ))
|
||||
* .subscribe((header) => {
|
||||
* console.log(`new block #${header.number.toNumber()}`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
public static create (options?: ApiOptions): Observable<ApiRx> {
|
||||
return new ApiRx(options).isReady;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Create an instance of the ApiRx class
|
||||
* @param options Options to create an instance. Can be either [[ApiOptions]] or [[WsProvider]]
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { switchMap } from 'rxjs';
|
||||
* import Api from '@polkadot/api/rx';
|
||||
*
|
||||
* new Api().isReady
|
||||
* .pipe(
|
||||
* switchMap((api) =>
|
||||
* api.rpc.chain.subscribeNewHeads()
|
||||
* ))
|
||||
* .subscribe((header) => {
|
||||
* console.log(`new block #${header.number.toNumber()}`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
constructor (options?: ApiOptions) {
|
||||
super(options, 'rxjs', decorateMethod);
|
||||
|
||||
this.#isReadyRx = from<Promise<ApiRx>>(
|
||||
// You can create an observable from an event, however my mind groks this form better
|
||||
new Promise((resolve): void => {
|
||||
super.on('ready', () => resolve(this));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Observable that returns the first time we are connected and loaded
|
||||
*/
|
||||
public get isReady (): Observable<ApiRx> {
|
||||
return this.#isReadyRx;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a clone of this ApiRx instance (new underlying provider connection)
|
||||
*/
|
||||
public clone (): ApiRx {
|
||||
return new ApiRx(
|
||||
objectSpread({}, this._options, { source: this })
|
||||
);
|
||||
}
|
||||
}
|
||||
export { ApiRx } from './Api';
|
||||
export { toRxMethod } from './decorateMethod';
|
||||
|
||||
@@ -95,7 +95,7 @@ export interface ApiInterfaceRx {
|
||||
runtimeMetadata: Metadata;
|
||||
runtimeVersion: RuntimeVersion;
|
||||
query: QueryableStorage<'rxjs'>;
|
||||
queryAt: (blockHash: Uint8Array | string) => Observable<QueryableStorage<'rxjs'>>;
|
||||
queryAt: (blockHash: Uint8Array | string, knownVersion?: RuntimeVersion) => Observable<QueryableStorage<'rxjs'>>;
|
||||
queryMulti: QueryableStorageMulti<'rxjs'>;
|
||||
rpc: DecoratedRpc<'rxjs', RpcInterface>;
|
||||
tx: SubmittableExtrinsics<'rxjs'>;
|
||||
|
||||
@@ -20,16 +20,16 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/rpc-provider": "6.7.2",
|
||||
"@polkadot/types": "6.7.2",
|
||||
"@polkadot/util": "^7.8.2",
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/rpc-provider": "6.9.2",
|
||||
"@polkadot/types": "6.9.2",
|
||||
"@polkadot/util": "^7.9.2",
|
||||
"rxjs": "^7.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^7.8.2"
|
||||
"@polkadot/keyring": "^7.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,7 +204,7 @@ export class RpcCore {
|
||||
? await this.#getBlockRegistry(u8aToU8a(blockHash))
|
||||
: { registry: this.#registryDefault };
|
||||
const params = this._formatInputs(registry, null, def, values);
|
||||
const result = await this.provider.send<AnyJson>(rpcName, params.map((p) => p.toJSON()));
|
||||
const result = await this.provider.send<AnyJson>(rpcName, params.map((p) => p.toJSON()), !!blockHash);
|
||||
|
||||
return this._formatResult(isScale, registry, blockHash, method, def, params, result);
|
||||
};
|
||||
|
||||
@@ -62,7 +62,7 @@ describe('methodSend', (): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
method(new Uint8Array([2 << 2, 0x12, 0x34])).subscribe((): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
expect(provider.send).toHaveBeenCalledWith('test_blah', ['0x1234']);
|
||||
expect(provider.send).toHaveBeenCalledWith('test_blah', ['0x1234'], false);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/rpc-core', version: '6.7.2' };
|
||||
export const packageInfo = { name: '@polkadot/rpc-core', version: '6.9.2' };
|
||||
|
||||
@@ -20,22 +20,22 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/types": "6.7.2",
|
||||
"@polkadot/util": "^7.8.2",
|
||||
"@polkadot/util-crypto": "^7.8.2",
|
||||
"@polkadot/x-fetch": "^7.8.2",
|
||||
"@polkadot/x-global": "^7.8.2",
|
||||
"@polkadot/x-ws": "^7.8.2",
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/types": "6.9.2",
|
||||
"@polkadot/util": "^7.9.2",
|
||||
"@polkadot/util-crypto": "^7.9.2",
|
||||
"@polkadot/x-fetch": "^7.9.2",
|
||||
"@polkadot/x-global": "^7.9.2",
|
||||
"@polkadot/x-ws": "^7.9.2",
|
||||
"eventemitter3": "^4.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^7.8.2",
|
||||
"@polkadot/types": "6.7.2",
|
||||
"mock-socket": "^9.0.7",
|
||||
"nock": "^13.1.4"
|
||||
"@polkadot/keyring": "^7.9.2",
|
||||
"@polkadot/types": "6.9.2",
|
||||
"mock-socket": "^9.0.8",
|
||||
"nock": "^13.2.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { fetch } from '@polkadot/x-fetch';
|
||||
|
||||
import { RpcCoder } from '../coder';
|
||||
import defaults from '../defaults';
|
||||
import { LRUCache } from '../lru';
|
||||
|
||||
const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
|
||||
|
||||
@@ -34,6 +35,8 @@ const l = logger('api-http');
|
||||
* @see [[WsProvider]]
|
||||
*/
|
||||
export class HttpProvider implements ProviderInterface {
|
||||
readonly #callCache = new LRUCache();
|
||||
|
||||
readonly #coder: RpcCoder;
|
||||
|
||||
readonly #endpoint: string;
|
||||
@@ -103,8 +106,24 @@ export class HttpProvider implements ProviderInterface {
|
||||
/**
|
||||
* @summary Send HTTP POST Request with Body to configured HTTP Endpoint.
|
||||
*/
|
||||
public async send <T> (method: string, params: unknown[]): Promise<T> {
|
||||
public async send <T> (method: string, params: unknown[], isCacheable?: boolean): Promise<T> {
|
||||
const body = this.#coder.encodeJson(method, params);
|
||||
let resultPromise: Promise<T> | null = isCacheable
|
||||
? this.#callCache.get(body) as Promise<T>
|
||||
: null;
|
||||
|
||||
if (!resultPromise) {
|
||||
resultPromise = this.#send(body);
|
||||
|
||||
if (isCacheable) {
|
||||
this.#callCache.set(body, resultPromise);
|
||||
}
|
||||
}
|
||||
|
||||
return resultPromise;
|
||||
}
|
||||
|
||||
async #send <T> (body: string): Promise<T> {
|
||||
const response = await fetch(this.#endpoint, {
|
||||
body,
|
||||
headers: {
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { LRUCache } from './lru';
|
||||
|
||||
describe('LRUCache', (): void => {
|
||||
it('allows getting of items below capacity', (): void => {
|
||||
const keys = ['1', '2', '3', '4'];
|
||||
const lru = new LRUCache(4);
|
||||
|
||||
keys.forEach((k) => lru.set(k, `${k}${k}${k}`));
|
||||
|
||||
expect(lru.keys().join(', ')).toEqual(keys.reverse().join(', '));
|
||||
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
|
||||
|
||||
keys.forEach((k) => expect(lru.get(k)).toEqual(`${k}${k}${k}`));
|
||||
});
|
||||
|
||||
it('drops items when at capacity', (): void => {
|
||||
const keys = ['1', '2', '3', '4', '5', '6'];
|
||||
const lru = new LRUCache(4);
|
||||
|
||||
keys.forEach((k) => lru.set(k, `${k}${k}${k}`));
|
||||
|
||||
expect(lru.keys().join(', ')).toEqual(keys.slice(2).reverse().join(', '));
|
||||
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
|
||||
|
||||
keys.slice(2).forEach((k) => expect(lru.get(k)).toEqual(`${k}${k}${k}`));
|
||||
});
|
||||
|
||||
it('adjusts the order as they are used', (): void => {
|
||||
const keys = ['1', '2', '3', '4', '5'];
|
||||
const lru = new LRUCache(4);
|
||||
|
||||
keys.forEach((k) => lru.set(k, `${k}${k}${k}`));
|
||||
|
||||
expect(lru.entries()).toEqual([['5', '555'], ['4', '444'], ['3', '333'], ['2', '222']]);
|
||||
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
|
||||
|
||||
lru.get('3');
|
||||
|
||||
expect(lru.entries()).toEqual([['3', '333'], ['5', '555'], ['4', '444'], ['2', '222']]);
|
||||
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
|
||||
|
||||
lru.set('4', '4433');
|
||||
|
||||
expect(lru.entries()).toEqual([['4', '4433'], ['3', '333'], ['5', '555'], ['2', '222']]);
|
||||
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
|
||||
|
||||
lru.set('6', '666');
|
||||
|
||||
expect(lru.entries()).toEqual([['6', '666'], ['4', '4433'], ['3', '333'], ['5', '555']]);
|
||||
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
const DEFAULT_CAPACITY = 2048;
|
||||
|
||||
class LRUNode {
|
||||
public readonly key: string;
|
||||
|
||||
public next: LRUNode;
|
||||
public prev: LRUNode;
|
||||
|
||||
constructor (key: string) {
|
||||
this.key = key;
|
||||
this.next = this.prev = this;
|
||||
}
|
||||
}
|
||||
|
||||
// https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
|
||||
export class LRUCache {
|
||||
readonly capacity: number;
|
||||
readonly #data: Map<string, unknown> = new Map();
|
||||
readonly #refs: Map<string, LRUNode> = new Map();
|
||||
|
||||
#length = 0;
|
||||
#head: LRUNode;
|
||||
#tail: LRUNode;
|
||||
|
||||
constructor (capacity = DEFAULT_CAPACITY) {
|
||||
this.capacity = capacity;
|
||||
this.#head = this.#tail = new LRUNode('<empty>');
|
||||
}
|
||||
|
||||
get length (): number {
|
||||
return this.#length;
|
||||
}
|
||||
|
||||
get lengthData (): number {
|
||||
return this.#data.size;
|
||||
}
|
||||
|
||||
get lengthRefs (): number {
|
||||
return this.#refs.size;
|
||||
}
|
||||
|
||||
entries (): [string, unknown][] {
|
||||
const keys = this.keys();
|
||||
const entries = new Array<[string, unknown]>(keys.length);
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
|
||||
entries[i] = [key, this.#data.get(key)];
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
keys (): string[] {
|
||||
const keys: string[] = [];
|
||||
|
||||
if (this.#length) {
|
||||
let curr = this.#head;
|
||||
|
||||
while (curr !== this.#tail) {
|
||||
keys.push(curr.key);
|
||||
curr = curr.next;
|
||||
}
|
||||
|
||||
keys.push(curr.key);
|
||||
}
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
get <T> (key: string): T | null {
|
||||
const data = this.#data.get(key);
|
||||
|
||||
if (data) {
|
||||
this.#toHead(key);
|
||||
|
||||
return data as T;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
set <T> (key: string, value: T): void {
|
||||
if (this.#data.has(key)) {
|
||||
this.#toHead(key);
|
||||
} else {
|
||||
const node = new LRUNode(key);
|
||||
|
||||
this.#refs.set(node.key, node);
|
||||
|
||||
if (this.length === 0) {
|
||||
this.#head = this.#tail = node;
|
||||
} else {
|
||||
this.#head.prev = node;
|
||||
node.next = this.#head;
|
||||
this.#head = node;
|
||||
}
|
||||
|
||||
if (this.#length === this.capacity) {
|
||||
this.#data.delete(this.#tail.key);
|
||||
this.#refs.delete(this.#tail.key);
|
||||
|
||||
this.#tail = this.#tail.prev;
|
||||
} else {
|
||||
this.#length += 1;
|
||||
}
|
||||
}
|
||||
|
||||
this.#data.set(key, value);
|
||||
}
|
||||
|
||||
#toHead (key: string): void {
|
||||
const ref = this.#refs.get(key);
|
||||
|
||||
if (ref && ref !== this.#head) {
|
||||
ref.prev.next = ref.next;
|
||||
ref.next.prev = ref.prev;
|
||||
ref.next = this.#head;
|
||||
|
||||
this.#head.prev = ref;
|
||||
this.#head = ref;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/rpc-provider', version: '6.7.2' };
|
||||
export const packageInfo = { name: '@polkadot/rpc-provider', version: '6.9.2' };
|
||||
|
||||
@@ -49,7 +49,7 @@ export interface ProviderInterface {
|
||||
connect (): Promise<void>;
|
||||
disconnect (): Promise<void>;
|
||||
on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void;
|
||||
send <T = any> (method: string, params: unknown[]): Promise<T>;
|
||||
send <T = any> (method: string, params: unknown[], isCacheable?: boolean): Promise<T>;
|
||||
subscribe (type: string, method: string, params: unknown[], cb: ProviderInterfaceCallback): Promise<number | string>;
|
||||
unsubscribe (type: string, method: string, id: number | string): Promise<boolean>;
|
||||
}
|
||||
|
||||
@@ -7,12 +7,13 @@ import type { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, Pro
|
||||
|
||||
import EventEmitter from 'eventemitter3';
|
||||
|
||||
import { assert, isChildClass, isNull, isUndefined, logger } from '@polkadot/util';
|
||||
import { assert, isChildClass, isNull, isUndefined, logger, objectSpread } from '@polkadot/util';
|
||||
import { xglobal } from '@polkadot/x-global';
|
||||
import { WebSocket } from '@polkadot/x-ws';
|
||||
|
||||
import { RpcCoder } from '../coder';
|
||||
import defaults from '../defaults';
|
||||
import { LRUCache } from '../lru';
|
||||
import { getWSErrorString } from './errors';
|
||||
|
||||
interface SubscriptionHandler {
|
||||
@@ -75,6 +76,8 @@ function eraseRecord<T> (record: Record<string, T>, cb?: (item: T) => void): voi
|
||||
* @see [[HttpProvider]]
|
||||
*/
|
||||
export class WsProvider implements ProviderInterface {
|
||||
readonly #callCache = new LRUCache();
|
||||
|
||||
readonly #coder: RpcCoder;
|
||||
|
||||
readonly #endpoints: string[];
|
||||
@@ -260,12 +263,28 @@ export class WsProvider implements ProviderInterface {
|
||||
* @param params Encoded parameters as applicable for the method
|
||||
* @param subscription Subscription details (internally used)
|
||||
*/
|
||||
public send <T = any> (method: string, params: unknown[], subscription?: SubscriptionHandler): Promise<T> {
|
||||
public send <T = any> (method: string, params: unknown[], isCacheable?: boolean, subscription?: SubscriptionHandler): Promise<T> {
|
||||
const body = this.#coder.encodeJson(method, params);
|
||||
let resultPromise: Promise<T> | null = isCacheable
|
||||
? this.#callCache.get(body) as Promise<T>
|
||||
: null;
|
||||
|
||||
if (!resultPromise) {
|
||||
resultPromise = this.#send(body, method, params, subscription);
|
||||
|
||||
if (isCacheable) {
|
||||
this.#callCache.set(body, resultPromise);
|
||||
}
|
||||
}
|
||||
|
||||
return resultPromise;
|
||||
}
|
||||
|
||||
async #send <T> (json: string, method: string, params: unknown[], subscription?: SubscriptionHandler): Promise<T> {
|
||||
return new Promise<T>((resolve, reject): void => {
|
||||
try {
|
||||
assert(this.isConnected && !isNull(this.#websocket), 'WebSocket is not connected');
|
||||
|
||||
const json = this.#coder.encodeJson(method, params);
|
||||
const id = this.#coder.getId();
|
||||
|
||||
const callback = (error?: Error | null, result?: T): void => {
|
||||
@@ -309,7 +328,7 @@ export class WsProvider implements ProviderInterface {
|
||||
* ```
|
||||
*/
|
||||
public subscribe (type: string, method: string, params: unknown[], callback: ProviderInterfaceCallback): Promise<number | string> {
|
||||
return this.send<number | string>(method, params, { callback, type });
|
||||
return this.send<number | string>(method, params, false, { callback, type });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -410,11 +429,10 @@ export class WsProvider implements ProviderInterface {
|
||||
if (subscription) {
|
||||
const subId = `${subscription.type}::${result}`;
|
||||
|
||||
this.#subscriptions[subId] = {
|
||||
...subscription,
|
||||
this.#subscriptions[subId] = objectSpread({}, subscription, {
|
||||
method,
|
||||
params
|
||||
};
|
||||
});
|
||||
|
||||
// if we have a result waiting for this subscription already
|
||||
if (this.#waitingForId[subId]) {
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"main": "index.js",
|
||||
"bin": {
|
||||
"polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.cjs",
|
||||
@@ -32,18 +32,18 @@
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.16.0",
|
||||
"@babel/register": "^7.16.0",
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/api": "6.7.2",
|
||||
"@polkadot/rpc-provider": "6.7.2",
|
||||
"@polkadot/types": "6.7.2",
|
||||
"@polkadot/types-support": "6.7.2",
|
||||
"@polkadot/util": "^7.8.2",
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/api": "6.9.2",
|
||||
"@polkadot/rpc-provider": "6.9.2",
|
||||
"@polkadot/types": "6.9.2",
|
||||
"@polkadot/types-support": "6.9.2",
|
||||
"@polkadot/util": "^7.9.2",
|
||||
"handlebars": "^4.7.7",
|
||||
"websocket": "^1.0.34",
|
||||
"yargs": "^17.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/websocket": "^1.0.4",
|
||||
"@types/yargs": "^17.0.5"
|
||||
"@types/yargs": "^17.0.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import path from 'path';
|
||||
import yargs from 'yargs';
|
||||
|
||||
import { Definitions } from '@polkadot/types/types';
|
||||
import { formatNumber } from '@polkadot/util';
|
||||
import { WebSocket } from '@polkadot/x-ws';
|
||||
|
||||
@@ -18,12 +19,24 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS
|
||||
? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) as Record<string, any> }
|
||||
: {};
|
||||
|
||||
generateDefaultConsts(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict);
|
||||
let customLookupDefinitions;
|
||||
|
||||
try {
|
||||
customLookupDefinitions = {
|
||||
rpc: {},
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires
|
||||
types: require(path.join(process.cwd(), output, 'lookup.ts')).default
|
||||
} as Definitions;
|
||||
} catch (error) {
|
||||
console.log('No custom definitions found.');
|
||||
}
|
||||
|
||||
generateDefaultConsts(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
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);
|
||||
generateDefaultEvents(path.join(process.cwd(), output, 'augment-api-events.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
generateDefaultQuery(path.join(process.cwd(), output, 'augment-api-query.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
generateDefaultRpc(path.join(process.cwd(), output, 'augment-api-rpc.ts'), extraTypes);
|
||||
generateDefaultTx(path.join(process.cwd(), output, 'augment-api-tx.ts'), metaHex, extraTypes, isStrict);
|
||||
generateDefaultTx(path.join(process.cwd(), output, 'augment-api-tx.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
|
||||
|
||||
writeFile(path.join(process.cwd(), output, 'augment-api.ts'), (): string =>
|
||||
[
|
||||
|
||||
@@ -8,11 +8,16 @@ import * as substrateDefs from '@polkadot/types/interfaces/definitions';
|
||||
|
||||
import { generateInterfaceTypes } from './generate/interfaceRegistry';
|
||||
import { generateTsDef } from './generate/tsDef';
|
||||
import { generateDefaultLookup } from './generate';
|
||||
|
||||
type ArgV = { input: string; package: string };
|
||||
type ArgV = { input: string; package: string; endpoint?: string; };
|
||||
|
||||
export function main (): void {
|
||||
const { input, package: pkg } = yargs.strict().options({
|
||||
const { endpoint, input, package: pkg } = yargs.strict().options({
|
||||
endpoint: {
|
||||
description: 'The endpoint to connect to (e.g. wss://kusama-rpc.polkadot.io) or relative path to a file containing the JSON output of an RPC state_getMetadata call',
|
||||
type: 'string'
|
||||
},
|
||||
input: {
|
||||
description: 'The directory to use for the user definitions',
|
||||
required: true,
|
||||
@@ -25,6 +30,13 @@ export function main (): void {
|
||||
}
|
||||
}).argv as ArgV;
|
||||
|
||||
if (endpoint) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const metaHex = (require(path.join(process.cwd(), endpoint)) as Record<string, string>).result;
|
||||
|
||||
generateDefaultLookup(path.join(process.cwd(), input), metaHex);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const userDefs = require(path.join(process.cwd(), input, 'definitions.ts')) as Record<string, any>;
|
||||
const userKeys = Object.keys(userDefs);
|
||||
|
||||
@@ -8,6 +8,7 @@ import Handlebars from 'handlebars';
|
||||
|
||||
import lookupDefinitions from '@polkadot/types/augment/lookup/definitions';
|
||||
import * as defaultDefs from '@polkadot/types/interfaces/definitions';
|
||||
import { Definitions } from '@polkadot/types/types';
|
||||
import { stringCamelCase } from '@polkadot/util';
|
||||
|
||||
import { compareName, createImports, formatType, initMeta, readTemplate, setImports, writeFile } from '../util';
|
||||
@@ -16,10 +17,15 @@ const template = readTemplate('consts');
|
||||
const generateForMetaTemplate = Handlebars.compile(template);
|
||||
|
||||
/** @internal */
|
||||
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
|
||||
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
|
||||
writeFile(dest, (): string => {
|
||||
const allTypes = {
|
||||
'@polkadot/types/augment': { lookup: lookupDefinitions },
|
||||
'@polkadot/types/augment': {
|
||||
lookup: {
|
||||
...lookupDefinitions,
|
||||
...customLookupDefinitions
|
||||
}
|
||||
},
|
||||
'@polkadot/types/interfaces': defaultDefs,
|
||||
...extraTypes
|
||||
};
|
||||
@@ -79,8 +85,8 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
|
||||
|
||||
// Call `generateForMeta()` with current static metadata
|
||||
/** @internal */
|
||||
export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
|
||||
export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
const { metadata } = initMeta(data, extraTypes);
|
||||
|
||||
return generateForMeta(metadata, dest, extraTypes, isStrict);
|
||||
return generateForMeta(metadata, dest, extraTypes, isStrict, customLookupDefinitions);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import Handlebars from 'handlebars';
|
||||
|
||||
import lookupDefinitions from '@polkadot/types/augment/lookup/definitions';
|
||||
import * as defaultDefs from '@polkadot/types/interfaces/definitions';
|
||||
import { Definitions } from '@polkadot/types/types';
|
||||
import { stringCamelCase } from '@polkadot/util';
|
||||
|
||||
import { compareName, createImports, formatType, initMeta, readTemplate, setImports, writeFile } from '../util';
|
||||
@@ -16,10 +17,15 @@ const template = readTemplate('events');
|
||||
const generateForMetaTemplate = Handlebars.compile(template);
|
||||
|
||||
/** @internal */
|
||||
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
|
||||
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
|
||||
writeFile(dest, (): string => {
|
||||
const allTypes = {
|
||||
'@polkadot/types/augment': { lookup: lookupDefinitions },
|
||||
'@polkadot/types/augment': {
|
||||
lookup: {
|
||||
...lookupDefinitions,
|
||||
...customLookupDefinitions
|
||||
}
|
||||
},
|
||||
'@polkadot/types/interfaces': defaultDefs,
|
||||
...extraTypes
|
||||
};
|
||||
@@ -71,8 +77,8 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
|
||||
|
||||
// Call `generateForMeta()` with current static metadata
|
||||
/** @internal */
|
||||
export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
|
||||
export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
const { metadata } = initMeta(data, extraTypes);
|
||||
|
||||
return generateForMeta(metadata, dest, extraTypes, isStrict);
|
||||
return generateForMeta(metadata, dest, extraTypes, isStrict, customLookupDefinitions);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ import { isString, stringify } from '@polkadot/util';
|
||||
import { createImports, exportType, initMeta, readTemplate, writeFile } from '../util';
|
||||
import { typeEncoders } from './tsDef';
|
||||
|
||||
const MAP_ENUMS = ['Call', 'Event', 'Error', 'RawEvent'];
|
||||
const WITH_TYPEDEF = false;
|
||||
|
||||
const generateLookupDefsTmpl = Handlebars.compile(readTemplate('lookup/defs'));
|
||||
@@ -131,33 +130,7 @@ function expandDefToString ({ lookupNameRoot, type }: TypeDef, indent: number):
|
||||
}
|
||||
|
||||
function getFilteredTypes (lookup: PortableRegistry, exclude: string[] = []): [PortableType, TypeDef][] {
|
||||
const named = lookup.types.filter(({ id, type: { path } }) => {
|
||||
const typeDef = lookup.getTypeDef(id);
|
||||
|
||||
return (
|
||||
// We actually only want those with lookupName set
|
||||
!!typeDef.lookupName &&
|
||||
!(
|
||||
path.length === 2 &&
|
||||
(
|
||||
(
|
||||
// Ensure that we match {node, kusama, *}_runtime
|
||||
path[0].toString().split('_')[1] === 'runtime' &&
|
||||
!['Call', 'Event'].includes(path[1].toString())
|
||||
) ||
|
||||
path[0].toString().startsWith('pallet_')
|
||||
) &&
|
||||
// Ensure we strip generics, e.g. Event<T>
|
||||
MAP_ENUMS.includes(path[1].toString().split('<')[0])
|
||||
) &&
|
||||
!(
|
||||
path.length >= 3 &&
|
||||
path[path.length - 2].toString() === 'pallet' &&
|
||||
// As above, cater for generics
|
||||
MAP_ENUMS.includes(path[path.length - 1].toString().split('<')[0])
|
||||
)
|
||||
);
|
||||
});
|
||||
const named = lookup.types.filter(({ id }) => !!lookup.getTypeDef(id).lookupName);
|
||||
const names = named.map(({ id }) => lookup.getName(id));
|
||||
|
||||
return named
|
||||
@@ -261,7 +234,7 @@ export function generateDefaultLookup (destDir = 'packages/types/src/augment/loo
|
||||
generateLookup(
|
||||
destDir,
|
||||
staticData
|
||||
? [[undefined, staticData]]
|
||||
? [['lookup', staticData]]
|
||||
: [
|
||||
['substrate', staticSubstrate],
|
||||
['polkadot', staticPolkadot],
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { StorageEntryMetadataLatest } from '@polkadot/types/interfaces';
|
||||
import type { Metadata, PortableRegistry } from '@polkadot/types/metadata';
|
||||
import type { Registry } from '@polkadot/types/types';
|
||||
import type { Definitions, Registry } from '@polkadot/types/types';
|
||||
import type { ExtraTypes } from './types';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
@@ -66,10 +66,15 @@ const template = readTemplate('query');
|
||||
const generateForMetaTemplate = Handlebars.compile(template);
|
||||
|
||||
/** @internal */
|
||||
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
|
||||
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
|
||||
writeFile(dest, (): string => {
|
||||
const allTypes: ExtraTypes = {
|
||||
'@polkadot/types/augment': { lookup: lookupDefinitions },
|
||||
'@polkadot/types/augment': {
|
||||
lookup: {
|
||||
...lookupDefinitions,
|
||||
...customLookupDefinitions
|
||||
}
|
||||
},
|
||||
'@polkadot/types/interfaces': defaultDefs,
|
||||
...extraTypes
|
||||
};
|
||||
@@ -129,8 +134,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?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
|
||||
export function generateDefaultQuery (dest = 'packages/api/src/augment/query.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
const { metadata, registry } = initMeta(data, extraTypes);
|
||||
|
||||
return generateForMeta(registry, metadata, dest, extraTypes, isStrict);
|
||||
return generateForMeta(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import path from 'path';
|
||||
import { getTypeDef, TypeRegistry } from '@polkadot/types/create';
|
||||
import { TypeDefInfo } from '@polkadot/types/create/types';
|
||||
import * as defaultDefinitions from '@polkadot/types/interfaces/definitions';
|
||||
import { assert, isString, stringCamelCase, stringify, stringUpperFirst } from '@polkadot/util';
|
||||
import { assert, isString, stringify, stringPascalCase } from '@polkadot/util';
|
||||
|
||||
import { createImports, exportInterface, exportType, formatType, readTemplate, setImports, TypeImports, writeFile } from '../util';
|
||||
|
||||
@@ -56,7 +56,7 @@ function tsEnum (registry: Registry, definitions: Record<string, ModuleTypes>, {
|
||||
.filter(({ name }) => !!name && !name.startsWith('__Unused'))
|
||||
.map((def, index): string => {
|
||||
const { info, lookupName, name = `unknown${index}`, type } = def;
|
||||
const getter = stringUpperFirst(stringCamelCase(name.replace(' ', '_')));
|
||||
const getter = stringPascalCase(name.replace(' ', '_'));
|
||||
const isComplex = [TypeDefInfo.Option, TypeDefInfo.Result, TypeDefInfo.Struct, TypeDefInfo.Tuple, TypeDefInfo.Vec, TypeDefInfo.VecFixed].includes(info);
|
||||
const asGetter = type === 'Null' || info === TypeDefInfo.DoNotConstruct
|
||||
? ''
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Metadata } from '@polkadot/types/metadata/Metadata';
|
||||
import type { Registry } from '@polkadot/types/types';
|
||||
import type { Definitions, Registry } from '@polkadot/types/types';
|
||||
import type { ExtraTypes } from './types';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
@@ -29,10 +29,15 @@ const template = readTemplate('tx');
|
||||
const generateForMetaTemplate = Handlebars.compile(template);
|
||||
|
||||
/** @internal */
|
||||
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
|
||||
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
|
||||
writeFile(dest, (): string => {
|
||||
const allTypes: ExtraTypes = {
|
||||
'@polkadot/types/augment': { lookup: lookupDefinitions },
|
||||
'@polkadot/types/augment': {
|
||||
lookup: {
|
||||
...lookupDefinitions,
|
||||
...customLookupDefinitions
|
||||
}
|
||||
},
|
||||
'@polkadot/types/interfaces': defaultDefs,
|
||||
...extraTypes
|
||||
};
|
||||
@@ -114,8 +119,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?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
|
||||
export function generateDefaultTx (dest = 'packages/api/src/augment/tx.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
|
||||
const { metadata, registry } = initMeta(data, extraTypes);
|
||||
|
||||
return generateForMeta(registry, metadata, dest, extraTypes, isStrict);
|
||||
return generateForMeta(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions);
|
||||
}
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/typegen', version: '6.7.2' };
|
||||
export const packageInfo = { name: '@polkadot/typegen', version: '6.9.2' };
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
/* eslint-disable sort-keys */
|
||||
|
||||
import type { DefinitionsTypes } from '../../types';
|
||||
|
||||
export default {
|
||||
{{#each defs}}
|
||||
{{> docs}}
|
||||
@@ -11,5 +9,5 @@ export default {
|
||||
{{{this}}}
|
||||
{{/each}}
|
||||
{{/each}}
|
||||
} as DefinitionsTypes;
|
||||
};
|
||||
{{> footer }}
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
/* eslint-disable sort-keys */
|
||||
|
||||
import type { Definitions } from '../../types';
|
||||
|
||||
export default {
|
||||
rpc: {},
|
||||
types: {
|
||||
@@ -14,5 +12,5 @@ export default {
|
||||
{{/each}}
|
||||
{{/each}}
|
||||
}
|
||||
} as Definitions;
|
||||
};
|
||||
{{> footer }}
|
||||
|
||||
@@ -20,12 +20,12 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/networks": "^7.8.2",
|
||||
"@polkadot/types": "6.7.2",
|
||||
"@polkadot/util": "^7.8.2"
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/networks": "^7.9.2",
|
||||
"@polkadot/types": "6.9.2",
|
||||
"@polkadot/util": "^7.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/types-known', version: '6.7.2' };
|
||||
export const packageInfo = { name: '@polkadot/types-known', version: '6.9.2' };
|
||||
|
||||
@@ -185,7 +185,7 @@ const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
// metadata v14
|
||||
minmax: [9106, undefined],
|
||||
types: objectSpread({}, sharedTypes)
|
||||
types: {}
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
// metadata v14
|
||||
minmax: [9110, undefined],
|
||||
types: objectSpread({}, sharedTypes)
|
||||
types: {}
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
// metadata v14
|
||||
minmax: [9106, undefined],
|
||||
types: objectSpread({}, sharedTypes)
|
||||
types: {}
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
// metadata V14
|
||||
minmax: [500, undefined],
|
||||
types: objectSpread({}, sharedTypes)
|
||||
types: {}
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
// metadata v14
|
||||
minmax: [9106, undefined],
|
||||
types: objectSpread({}, sharedTypes)
|
||||
types: {}
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ const upgrades: ChainUpgradesRaw = [
|
||||
[528470, 13], [687751, 14], [746085, 15], [787923, 16], [799302, 17],
|
||||
[1205128, 18], [1603423, 23], [1733218, 24], [2005673, 25], [2436698, 26],
|
||||
[3613564, 27], [3899547, 28], [4345767, 29], [4876134, 30], [5661442, 9050],
|
||||
[6321619, 9080], [6713249, 9090], [7217907, 9100], [7229126, 9110]
|
||||
[6321619, 9080], [6713249, 9090], [7217907, 9100], [7229126, 9110], [7560558, 9122]
|
||||
];
|
||||
|
||||
export default upgrades;
|
||||
|
||||
@@ -20,10 +20,10 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/util": "^7.8.2"
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/util": "^7.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/types-support', version: '6.7.2' };
|
||||
export const packageInfo = { name: '@polkadot/types-support', version: '6.9.2' };
|
||||
|
||||
@@ -20,17 +20,17 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "6.7.2",
|
||||
"version": "6.9.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.16.0",
|
||||
"@polkadot/util": "^7.8.2",
|
||||
"@polkadot/util-crypto": "^7.8.2",
|
||||
"@babel/runtime": "^7.16.3",
|
||||
"@polkadot/util": "^7.9.2",
|
||||
"@polkadot/util-crypto": "^7.9.2",
|
||||
"rxjs": "^7.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^7.8.2",
|
||||
"@polkadot/types-support": "6.7.2",
|
||||
"@polkadot/keyring": "^7.9.2",
|
||||
"@polkadot/types-support": "6.9.2",
|
||||
"@types/bn.js": "^4.11.6",
|
||||
"bn.js": "^4.12.0"
|
||||
}
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
|
||||
/* eslint-disable sort-keys */
|
||||
|
||||
import type { DefinitionsTypes } from '../../types';
|
||||
|
||||
export default {
|
||||
/**
|
||||
* Lookup74: kusama_runtime::ProxyType
|
||||
@@ -12,6 +10,29 @@ export default {
|
||||
KusamaRuntimeProxyType: {
|
||||
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement', 'CancelProxy', 'Auction']
|
||||
},
|
||||
/**
|
||||
* Lookup107: pallet_xcm::pallet::Event<T>
|
||||
**/
|
||||
PalletXcmEvent: {
|
||||
_enum: {
|
||||
Attempted: 'XcmV2TraitsOutcome',
|
||||
Sent: '(XcmV1MultiLocation,XcmV1MultiLocation,XcmV2Xcm)',
|
||||
UnexpectedResponse: '(XcmV1MultiLocation,u64)',
|
||||
ResponseReady: '(u64,XcmV2Response)',
|
||||
Notified: '(u64,u8,u8)',
|
||||
NotifyOverweight: '(u64,u8,u8,u64,u64)',
|
||||
NotifyDispatchError: '(u64,u8,u8)',
|
||||
NotifyDecodeFailed: '(u64,u8,u8)',
|
||||
InvalidResponder: '(XcmV1MultiLocation,u64,Option<XcmV1MultiLocation>)',
|
||||
InvalidResponderVersion: '(XcmV1MultiLocation,u64)',
|
||||
ResponseTaken: 'u64',
|
||||
AssetsTrapped: '(H256,XcmV1MultiLocation,XcmVersionedMultiAssets)',
|
||||
VersionChangeNotified: '(XcmV1MultiLocation,u32)',
|
||||
SupportedVersionChanged: '(XcmV1MultiLocation,u32)',
|
||||
NotifyTargetSendFail: '(XcmV1MultiLocation,u64,XcmV2TraitsError)',
|
||||
NotifyTargetMigrationFail: '(XcmVersionedMultiLocation,u64)'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup108: xcm::v1::multilocation::MultiLocation
|
||||
**/
|
||||
@@ -573,6 +594,60 @@ export default {
|
||||
votes23: 'Vec<(Compact<u32>,[(Compact<u16>,Compact<PerU16>);22],Compact<u16>)>',
|
||||
votes24: 'Vec<(Compact<u32>,[(Compact<u16>,Compact<PerU16>);23],Compact<u16>)>'
|
||||
},
|
||||
/**
|
||||
* Lookup511: pallet_xcm::pallet::Call<T>
|
||||
**/
|
||||
PalletXcmCall: {
|
||||
_enum: {
|
||||
send: {
|
||||
dest: 'XcmVersionedMultiLocation',
|
||||
message: 'XcmVersionedXcm',
|
||||
},
|
||||
teleport_assets: {
|
||||
dest: 'XcmVersionedMultiLocation',
|
||||
beneficiary: 'XcmVersionedMultiLocation',
|
||||
assets: 'XcmVersionedMultiAssets',
|
||||
feeAssetItem: 'u32',
|
||||
},
|
||||
reserve_transfer_assets: {
|
||||
dest: 'XcmVersionedMultiLocation',
|
||||
beneficiary: 'XcmVersionedMultiLocation',
|
||||
assets: 'XcmVersionedMultiAssets',
|
||||
feeAssetItem: 'u32',
|
||||
},
|
||||
execute: {
|
||||
message: 'XcmVersionedXcm',
|
||||
maxWeight: 'u64',
|
||||
},
|
||||
force_xcm_version: {
|
||||
location: 'XcmV1MultiLocation',
|
||||
xcmVersion: 'u32',
|
||||
},
|
||||
force_default_xcm_version: {
|
||||
maybeXcmVersion: 'Option<u32>',
|
||||
},
|
||||
force_subscribe_version_notify: {
|
||||
location: 'XcmVersionedMultiLocation',
|
||||
},
|
||||
force_unsubscribe_version_notify: {
|
||||
location: 'XcmVersionedMultiLocation',
|
||||
},
|
||||
limited_reserve_transfer_assets: {
|
||||
dest: 'XcmVersionedMultiLocation',
|
||||
beneficiary: 'XcmVersionedMultiLocation',
|
||||
assets: 'XcmVersionedMultiAssets',
|
||||
feeAssetItem: 'u32',
|
||||
weightLimit: 'XcmV2WeightLimit',
|
||||
},
|
||||
limited_teleport_assets: {
|
||||
dest: 'XcmVersionedMultiLocation',
|
||||
beneficiary: 'XcmVersionedMultiLocation',
|
||||
assets: 'XcmVersionedMultiAssets',
|
||||
feeAssetItem: 'u32',
|
||||
weightLimit: 'XcmV2WeightLimit'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup512: xcm::VersionedXcm<Call>
|
||||
**/
|
||||
@@ -842,8 +917,14 @@ export default {
|
||||
MigrateAndNotifyOldTargets: 'Null'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup700: pallet_xcm::pallet::Error<T>
|
||||
**/
|
||||
PalletXcmError: {
|
||||
_enum: ['Unreachable', 'SendFailure', 'Filtered', 'UnweighableMessage', 'DestinationNotInvertible', 'Empty', 'CannotReanchor', 'TooManyAssets', 'InvalidOrigin', 'BadVersion', 'BadLocation', 'NoSubscription', 'AlreadySubscribed']
|
||||
},
|
||||
/**
|
||||
* Lookup711: kusama_runtime::Runtime
|
||||
**/
|
||||
KusamaRuntimeRuntime: 'Null'
|
||||
} as DefinitionsTypes;
|
||||
};
|
||||
|
||||
@@ -3,15 +3,31 @@
|
||||
|
||||
/* eslint-disable sort-keys */
|
||||
|
||||
import type { DefinitionsTypes } from '../../types';
|
||||
|
||||
export default {
|
||||
/**
|
||||
* Lookup65: polkadot_runtime_common::claims::pallet::Event<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonClaimsPalletEvent: {
|
||||
_enum: {
|
||||
Claimed: '(AccountId32,EthereumAddress,u128)'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup72: polkadot_runtime::ProxyType
|
||||
**/
|
||||
PolkadotRuntimeProxyType: {
|
||||
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', '__Unused4', 'IdentityJudgement', 'CancelProxy', 'Auction']
|
||||
},
|
||||
/**
|
||||
* Lookup82: polkadot_runtime_parachains::inclusion::pallet::Event<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsInclusionPalletEvent: {
|
||||
_enum: {
|
||||
CandidateBacked: '(PolkadotPrimitivesV1CandidateReceipt,Bytes,u32,u32)',
|
||||
CandidateIncluded: '(PolkadotPrimitivesV1CandidateReceipt,Bytes,u32,u32)',
|
||||
CandidateTimedOut: '(PolkadotPrimitivesV1CandidateReceipt,Bytes,u32)'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup83: polkadot_primitives::v1::CandidateReceipt<primitive_types::H256>
|
||||
**/
|
||||
@@ -41,6 +57,32 @@ export default {
|
||||
* Lookup87: polkadot_primitives::v0::collator_app::Signature
|
||||
**/
|
||||
PolkadotPrimitivesV0CollatorAppSignature: 'SpCoreSr25519Signature',
|
||||
/**
|
||||
* Lookup94: polkadot_runtime_parachains::paras::pallet::Event
|
||||
**/
|
||||
PolkadotRuntimeParachainsParasPalletEvent: {
|
||||
_enum: {
|
||||
CurrentCodeUpdated: 'u32',
|
||||
CurrentHeadUpdated: 'u32',
|
||||
CodeUpgradeScheduled: 'u32',
|
||||
NewHeadNoted: 'u32',
|
||||
ActionQueued: '(u32,u32)'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup95: polkadot_runtime_parachains::ump::pallet::Event
|
||||
**/
|
||||
PolkadotRuntimeParachainsUmpPalletEvent: {
|
||||
_enum: {
|
||||
InvalidFormat: '[u8;32]',
|
||||
UnsupportedVersion: '[u8;32]',
|
||||
ExecutedUpward: '([u8;32],XcmV2TraitsOutcome)',
|
||||
WeightExhausted: '([u8;32],u64,u64)',
|
||||
UpwardMessagesReceived: '(u32,u32,u32)',
|
||||
OverweightEnqueued: '(u32,[u8;32],u64,u64)',
|
||||
OverweightServiced: '(u64,u64)'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup96: xcm::v2::traits::Outcome
|
||||
**/
|
||||
@@ -84,6 +126,17 @@ export default {
|
||||
WeightNotComputable: 'Null'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup98: polkadot_runtime_parachains::hrmp::pallet::Event<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsHrmpPalletEvent: {
|
||||
_enum: {
|
||||
OpenChannelRequested: '(u32,u32,u32,u32)',
|
||||
OpenChannelCanceled: '(u32,PolkadotParachainPrimitivesHrmpChannelId)',
|
||||
OpenChannelAccepted: '(u32,u32)',
|
||||
ChannelClosed: '(u32,PolkadotParachainPrimitivesHrmpChannelId)'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup99: polkadot_parachain::primitives::HrmpChannelId
|
||||
**/
|
||||
@@ -91,6 +144,56 @@ export default {
|
||||
sender: 'u32',
|
||||
recipient: 'u32'
|
||||
},
|
||||
/**
|
||||
* Lookup100: polkadot_runtime_common::paras_registrar::pallet::Event<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonParasRegistrarPalletEvent: {
|
||||
_enum: {
|
||||
Registered: '(u32,AccountId32)',
|
||||
Deregistered: 'u32',
|
||||
Reserved: '(u32,AccountId32)'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup101: polkadot_runtime_common::slots::pallet::Event<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonSlotsPalletEvent: {
|
||||
_enum: {
|
||||
NewLeasePeriod: 'u32',
|
||||
Leased: '(u32,AccountId32,u32,u32,u128,u128)'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup102: polkadot_runtime_common::auctions::pallet::Event<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonAuctionsPalletEvent: {
|
||||
_enum: {
|
||||
AuctionStarted: '(u32,u32,u32)',
|
||||
AuctionClosed: 'u32',
|
||||
Reserved: '(AccountId32,u128,u128)',
|
||||
Unreserved: '(AccountId32,u128)',
|
||||
ReserveConfiscated: '(u32,AccountId32,u128)',
|
||||
BidAccepted: '(AccountId32,u32,u128,u32,u32)',
|
||||
WinningOffset: '(u32,u32)'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup103: polkadot_runtime_common::crowdloan::pallet::Event<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonCrowdloanPalletEvent: {
|
||||
_enum: {
|
||||
Created: 'u32',
|
||||
Contributed: '(AccountId32,u32,u128)',
|
||||
Withdrew: '(AccountId32,u32,u128)',
|
||||
PartiallyRefunded: 'u32',
|
||||
AllRefunded: 'u32',
|
||||
Dissolved: 'u32',
|
||||
HandleBidResult: '(u32,Result<Null, SpRuntimeDispatchError>)',
|
||||
Edited: 'u32',
|
||||
MemoUpdated: '(AccountId32,u32,Bytes)',
|
||||
AddedToNewRaise: 'u32'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup162: polkadot_runtime::SessionKeys
|
||||
**/
|
||||
@@ -110,6 +213,39 @@ export default {
|
||||
* Lookup164: polkadot_primitives::v1::assignment_app::Public
|
||||
**/
|
||||
PolkadotPrimitivesV1AssignmentAppPublic: 'SpCoreSr25519Public',
|
||||
/**
|
||||
* Lookup195: polkadot_runtime_common::claims::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonClaimsPalletCall: {
|
||||
_enum: {
|
||||
claim: {
|
||||
dest: 'AccountId32',
|
||||
ethereumSignature: 'PolkadotRuntimeCommonClaimsEcdsaSignature',
|
||||
},
|
||||
mint_claim: {
|
||||
who: 'EthereumAddress',
|
||||
value: 'u128',
|
||||
vestingSchedule: 'Option<(u128,u128,u32)>',
|
||||
statement: 'Option<PolkadotRuntimeCommonClaimsStatementKind>',
|
||||
},
|
||||
claim_attest: {
|
||||
dest: 'AccountId32',
|
||||
ethereumSignature: 'PolkadotRuntimeCommonClaimsEcdsaSignature',
|
||||
statement: 'Bytes',
|
||||
},
|
||||
attest: {
|
||||
statement: 'Bytes',
|
||||
},
|
||||
move_claim: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
old: 'EthereumAddress',
|
||||
new_: 'EthereumAddress',
|
||||
maybePreclaim: 'Option<AccountId32>'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup196: polkadot_runtime_common::claims::EcdsaSignature
|
||||
**/
|
||||
@@ -207,6 +343,277 @@ export default {
|
||||
votes15: 'Vec<(Compact<u32>,[(Compact<u16>,Compact<PerU16>);14],Compact<u16>)>',
|
||||
votes16: 'Vec<(Compact<u32>,[(Compact<u16>,Compact<PerU16>);15],Compact<u16>)>'
|
||||
},
|
||||
/**
|
||||
* Lookup319: polkadot_runtime_parachains::configuration::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsConfigurationPalletCall: {
|
||||
_enum: {
|
||||
set_validation_upgrade_frequency: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_validation_upgrade_delay: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_code_retention_period: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_max_code_size: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_max_pov_size: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_max_head_data_size: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_parathread_cores: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_parathread_retries: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_group_rotation_frequency: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_chain_availability_period: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_thread_availability_period: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_scheduling_lookahead: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_max_validators_per_core: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'Option<u32>',
|
||||
},
|
||||
set_max_validators: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'Option<u32>',
|
||||
},
|
||||
set_dispute_period: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_dispute_post_conclusion_acceptance_period: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_dispute_max_spam_slots: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_dispute_conclusion_by_time_out_period: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_no_show_slots: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_n_delay_tranches: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_zeroth_delay_tranche_width: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_needed_approvals: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_relay_vrf_modulo_samples: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_max_upward_queue_count: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_max_upward_queue_size: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_max_downward_message_size: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_ump_service_total_weight: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u64',
|
||||
},
|
||||
set_max_upward_message_size: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_max_upward_message_num_per_candidate: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_hrmp_open_request_ttl: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_hrmp_sender_deposit: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u128',
|
||||
},
|
||||
set_hrmp_recipient_deposit: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u128',
|
||||
},
|
||||
set_hrmp_channel_max_capacity: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_hrmp_channel_max_total_size: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_hrmp_max_parachain_inbound_channels: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_hrmp_max_parathread_inbound_channels: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_hrmp_channel_max_message_size: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_hrmp_max_parachain_outbound_channels: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_hrmp_max_parathread_outbound_channels: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_hrmp_max_message_num_per_candidate: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u32',
|
||||
},
|
||||
set_ump_max_individual_weight: {
|
||||
_alias: {
|
||||
new_: 'new',
|
||||
},
|
||||
new_: 'u64'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup320: polkadot_runtime_parachains::shared::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsSharedPalletCall: 'Null',
|
||||
/**
|
||||
* Lookup321: polkadot_runtime_parachains::inclusion::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsInclusionPalletCall: 'Null',
|
||||
/**
|
||||
* Lookup322: polkadot_runtime_parachains::paras_inherent::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsParasInherentPalletCall: {
|
||||
_enum: {
|
||||
enter: {
|
||||
data: 'PolkadotPrimitivesV1InherentData'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup323: polkadot_primitives::v1::InherentData<sp_runtime::generic::header::Header<Number, sp_runtime::traits::BlakeTwo256>>
|
||||
**/
|
||||
@@ -214,7 +621,7 @@ export default {
|
||||
bitfields: 'Vec<PolkadotPrimitivesV1SignedUncheckedSigned>',
|
||||
backedCandidates: 'Vec<PolkadotPrimitivesV1BackedCandidate>',
|
||||
disputes: 'Vec<PolkadotPrimitivesV1DisputeStatementSet>',
|
||||
parentHeader: 'SpRuntimeGenericHeader'
|
||||
parentHeader: 'SpRuntimeHeader'
|
||||
},
|
||||
/**
|
||||
* Lookup325: polkadot_primitives::v1::signed::UncheckedSigned<polkadot_primitives::v1::AvailabilityBitfield, polkadot_primitives::v1::AvailabilityBitfield>
|
||||
@@ -309,6 +716,198 @@ export default {
|
||||
PolkadotPrimitivesV1InvalidDisputeStatementKind: {
|
||||
_enum: ['Explicit']
|
||||
},
|
||||
/**
|
||||
* Lookup349: polkadot_runtime_parachains::paras::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsParasPalletCall: {
|
||||
_enum: {
|
||||
force_set_current_code: {
|
||||
para: 'u32',
|
||||
newCode: 'Bytes',
|
||||
},
|
||||
force_set_current_head: {
|
||||
para: 'u32',
|
||||
newHead: 'Bytes',
|
||||
},
|
||||
force_schedule_code_upgrade: {
|
||||
para: 'u32',
|
||||
newCode: 'Bytes',
|
||||
relayParentNumber: 'u32',
|
||||
},
|
||||
force_note_new_head: {
|
||||
para: 'u32',
|
||||
newHead: 'Bytes',
|
||||
},
|
||||
force_queue_action: {
|
||||
para: 'u32'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup350: polkadot_runtime_parachains::initializer::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsInitializerPalletCall: {
|
||||
_enum: {
|
||||
force_approve: {
|
||||
upTo: 'u32'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup351: polkadot_runtime_parachains::dmp::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsDmpPalletCall: 'Null',
|
||||
/**
|
||||
* Lookup352: polkadot_runtime_parachains::ump::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsUmpPalletCall: {
|
||||
_enum: {
|
||||
service_overweight: {
|
||||
index: 'u64',
|
||||
weightLimit: 'u64'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup353: polkadot_runtime_parachains::hrmp::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsHrmpPalletCall: {
|
||||
_enum: {
|
||||
hrmp_init_open_channel: {
|
||||
recipient: 'u32',
|
||||
proposedMaxCapacity: 'u32',
|
||||
proposedMaxMessageSize: 'u32',
|
||||
},
|
||||
hrmp_accept_open_channel: {
|
||||
sender: 'u32',
|
||||
},
|
||||
hrmp_close_channel: {
|
||||
channelId: 'PolkadotParachainPrimitivesHrmpChannelId',
|
||||
},
|
||||
force_clean_hrmp: {
|
||||
para: 'u32',
|
||||
},
|
||||
force_process_hrmp_open: 'Null',
|
||||
force_process_hrmp_close: 'Null',
|
||||
hrmp_cancel_open_request: {
|
||||
channelId: 'PolkadotParachainPrimitivesHrmpChannelId'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup354: polkadot_runtime_common::paras_registrar::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonParasRegistrarPalletCall: {
|
||||
_enum: {
|
||||
register: {
|
||||
id: 'u32',
|
||||
genesisHead: 'Bytes',
|
||||
validationCode: 'Bytes',
|
||||
},
|
||||
force_register: {
|
||||
who: 'AccountId32',
|
||||
deposit: 'u128',
|
||||
id: 'u32',
|
||||
genesisHead: 'Bytes',
|
||||
validationCode: 'Bytes',
|
||||
},
|
||||
deregister: {
|
||||
id: 'u32',
|
||||
},
|
||||
swap: {
|
||||
id: 'u32',
|
||||
other: 'u32',
|
||||
},
|
||||
force_remove_lock: {
|
||||
para: 'u32',
|
||||
},
|
||||
reserve: 'Null'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup355: polkadot_runtime_common::slots::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonSlotsPalletCall: {
|
||||
_enum: {
|
||||
force_lease: {
|
||||
para: 'u32',
|
||||
leaser: 'AccountId32',
|
||||
amount: 'u128',
|
||||
periodBegin: 'u32',
|
||||
periodCount: 'u32',
|
||||
},
|
||||
clear_all_leases: {
|
||||
para: 'u32',
|
||||
},
|
||||
trigger_onboard: {
|
||||
para: 'u32'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup356: polkadot_runtime_common::auctions::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonAuctionsPalletCall: {
|
||||
_enum: {
|
||||
new_auction: {
|
||||
duration: 'Compact<u32>',
|
||||
leasePeriodIndex: 'Compact<u32>',
|
||||
},
|
||||
bid: {
|
||||
para: 'Compact<u32>',
|
||||
auctionIndex: 'Compact<u32>',
|
||||
firstSlot: 'Compact<u32>',
|
||||
lastSlot: 'Compact<u32>',
|
||||
amount: 'Compact<u128>',
|
||||
},
|
||||
cancel_auction: 'Null'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup358: polkadot_runtime_common::crowdloan::pallet::Call<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonCrowdloanPalletCall: {
|
||||
_enum: {
|
||||
create: {
|
||||
index: 'Compact<u32>',
|
||||
cap: 'Compact<u128>',
|
||||
firstPeriod: 'Compact<u32>',
|
||||
lastPeriod: 'Compact<u32>',
|
||||
end: 'Compact<u32>',
|
||||
verifier: 'Option<SpRuntimeMultiSigner>',
|
||||
},
|
||||
contribute: {
|
||||
index: 'Compact<u32>',
|
||||
value: 'Compact<u128>',
|
||||
signature: 'Option<SpRuntimeMultiSignature>',
|
||||
},
|
||||
withdraw: {
|
||||
who: 'AccountId32',
|
||||
index: 'Compact<u32>',
|
||||
},
|
||||
refund: {
|
||||
index: 'Compact<u32>',
|
||||
},
|
||||
dissolve: {
|
||||
index: 'Compact<u32>',
|
||||
},
|
||||
edit: {
|
||||
index: 'Compact<u32>',
|
||||
cap: 'Compact<u128>',
|
||||
firstPeriod: 'Compact<u32>',
|
||||
lastPeriod: 'Compact<u32>',
|
||||
end: 'Compact<u32>',
|
||||
verifier: 'Option<SpRuntimeMultiSigner>',
|
||||
},
|
||||
add_memo: {
|
||||
index: 'u32',
|
||||
memo: 'Bytes',
|
||||
},
|
||||
poke: {
|
||||
index: 'u32'
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup360: sp_runtime::MultiSigner
|
||||
**/
|
||||
@@ -323,6 +922,12 @@ export default {
|
||||
* Lookup361: sp_core::ecdsa::Public
|
||||
**/
|
||||
SpCoreEcdsaPublic: '[u8;33]',
|
||||
/**
|
||||
* Lookup464: polkadot_runtime_common::claims::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonClaimsPalletError: {
|
||||
_enum: ['InvalidEthereumSignature', 'SignerHasNoClaim', 'SenderHasNoClaim', 'PotUnderflow', 'InvalidStatement', 'VestedBalanceExists']
|
||||
},
|
||||
/**
|
||||
* Lookup514: polkadot_runtime_parachains::configuration::HostConfiguration<BlockNumber>
|
||||
**/
|
||||
@@ -368,6 +973,12 @@ export default {
|
||||
relayVrfModuloSamples: 'u32',
|
||||
umpMaxIndividualWeight: 'u64'
|
||||
},
|
||||
/**
|
||||
* Lookup515: polkadot_runtime_parachains::configuration::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsConfigurationPalletError: {
|
||||
_enum: ['InvalidNewValue']
|
||||
},
|
||||
/**
|
||||
* Lookup518: polkadot_runtime_parachains::inclusion::AvailabilityBitfieldRecord<N>
|
||||
**/
|
||||
@@ -391,6 +1002,12 @@ export default {
|
||||
backedInNumber: 'u32',
|
||||
backingGroup: 'u32'
|
||||
},
|
||||
/**
|
||||
* Lookup520: polkadot_runtime_parachains::inclusion::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsInclusionPalletError: {
|
||||
_enum: ['WrongBitfieldSize', 'BitfieldDuplicateOrUnordered', 'ValidatorIndexOutOfBounds', 'InvalidBitfieldSignature', 'UnscheduledCandidate', 'CandidateScheduledBeforeParaFree', 'WrongCollator', 'ScheduledOutOfOrder', 'HeadDataTooLarge', 'PrematureCodeUpgrade', 'NewCodeTooLarge', 'CandidateNotInParentContext', 'InvalidGroupIndex', 'InsufficientBacking', 'InvalidBacking', 'NotCollatorSigned', 'ValidationDataHashMismatch', 'IncorrectDownwardMessageHandling', 'InvalidUpwardMessages', 'HrmpWatermarkMishandling', 'InvalidOutboundHrmp', 'InvalidValidationCodeHash', 'ParaHeadMismatch']
|
||||
},
|
||||
/**
|
||||
* Lookup521: polkadot_primitives::v1::ScrapedOnChainVotes<primitive_types::H256>
|
||||
**/
|
||||
@@ -399,6 +1016,12 @@ export default {
|
||||
backingValidatorsPerCandidate: 'Vec<(PolkadotPrimitivesV1CandidateReceipt,Vec<(u32,PolkadotPrimitivesV0ValidityAttestation)>)>',
|
||||
disputes: 'Vec<PolkadotPrimitivesV1DisputeStatementSet>'
|
||||
},
|
||||
/**
|
||||
* Lookup526: polkadot_runtime_parachains::paras_inherent::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsParasInherentPalletError: {
|
||||
_enum: ['TooManyInclusionInherents', 'InvalidParentHeader', 'CandidateConcludedInvalid']
|
||||
},
|
||||
/**
|
||||
* Lookup528: polkadot_runtime_parachains::scheduler::ParathreadClaimQueue
|
||||
**/
|
||||
@@ -491,6 +1114,12 @@ export default {
|
||||
validationCode: 'Bytes',
|
||||
parachain: 'bool'
|
||||
},
|
||||
/**
|
||||
* Lookup549: polkadot_runtime_parachains::paras::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsParasPalletError: {
|
||||
_enum: ['NotRegistered', 'CannotOnboard', 'CannotOffboard', 'CannotUpgrade', 'CannotDowngrade']
|
||||
},
|
||||
/**
|
||||
* Lookup551: polkadot_runtime_parachains::initializer::BufferedSessionChange
|
||||
**/
|
||||
@@ -506,6 +1135,12 @@ export default {
|
||||
sentAt: 'u32',
|
||||
msg: 'Bytes'
|
||||
},
|
||||
/**
|
||||
* Lookup555: polkadot_runtime_parachains::ump::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsUmpPalletError: {
|
||||
_enum: ['UnknownMessageIndex', 'WeightOverLimit']
|
||||
},
|
||||
/**
|
||||
* Lookup556: polkadot_runtime_parachains::hrmp::HrmpOpenChannelRequest
|
||||
**/
|
||||
@@ -537,6 +1172,12 @@ export default {
|
||||
sentAt: 'u32',
|
||||
data: 'Bytes'
|
||||
},
|
||||
/**
|
||||
* Lookup564: polkadot_runtime_parachains::hrmp::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeParachainsHrmpPalletError: {
|
||||
_enum: ['OpenHrmpChannelToSelf', 'OpenHrmpChannelInvalidRecipient', 'OpenHrmpChannelZeroCapacity', 'OpenHrmpChannelCapacityExceedsLimit', 'OpenHrmpChannelZeroMessageSize', 'OpenHrmpChannelMessageSizeExceedsLimit', 'OpenHrmpChannelAlreadyExists', 'OpenHrmpChannelAlreadyRequested', 'OpenHrmpChannelLimitExceeded', 'AcceptHrmpChannelDoesntExist', 'AcceptHrmpChannelAlreadyConfirmed', 'AcceptHrmpChannelLimitExceeded', 'CloseHrmpChannelUnauthorized', 'CloseHrmpChannelDoesntExist', 'CloseHrmpChannelAlreadyUnderway', 'CancelHrmpOpenChannelUnauthorized', 'OpenHrmpChannelDoesntExist', 'OpenHrmpChannelAlreadyConfirmed']
|
||||
},
|
||||
/**
|
||||
* Lookup566: polkadot_primitives::v1::SessionInfo
|
||||
**/
|
||||
@@ -560,6 +1201,24 @@ export default {
|
||||
deposit: 'u128',
|
||||
locked: 'bool'
|
||||
},
|
||||
/**
|
||||
* Lookup569: polkadot_runtime_common::paras_registrar::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonParasRegistrarPalletError: {
|
||||
_enum: ['NotRegistered', 'AlreadyRegistered', 'NotOwner', 'CodeTooLarge', 'HeadDataTooLarge', 'NotParachain', 'NotParathread', 'CannotDeregister', 'CannotDowngrade', 'CannotUpgrade', 'ParaLocked', 'NotReserved']
|
||||
},
|
||||
/**
|
||||
* Lookup572: polkadot_runtime_common::slots::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonSlotsPalletError: {
|
||||
_enum: ['ParaNotOnboarding', 'LeaseError']
|
||||
},
|
||||
/**
|
||||
* Lookup577: polkadot_runtime_common::auctions::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonAuctionsPalletError: {
|
||||
_enum: ['AuctionInProgress', 'LeasePeriodInPast', 'ParaNotRegistered', 'NotCurrentAuction', 'NotAuction', 'AuctionEnded', 'AlreadyLeasedOut']
|
||||
},
|
||||
/**
|
||||
* Lookup578: polkadot_runtime_common::crowdloan::FundInfo<sp_core::crypto::AccountId32, Balance, BlockNumber, LeasePeriod>
|
||||
**/
|
||||
@@ -585,6 +1244,12 @@ export default {
|
||||
Ending: 'u32'
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Lookup580: polkadot_runtime_common::crowdloan::pallet::Error<T>
|
||||
**/
|
||||
PolkadotRuntimeCommonCrowdloanPalletError: {
|
||||
_enum: ['FirstPeriodInPast', 'FirstPeriodTooFarInFuture', 'LastPeriodBeforeFirstPeriod', 'LastPeriodTooFarInFuture', 'CannotEndInPast', 'EndTooFarInFuture', 'Overflow', 'ContributionTooSmall', 'InvalidParaId', 'CapExceeded', 'ContributionPeriodOver', 'InvalidOrigin', 'NotParachain', 'LeaseActive', 'BidOrLeaseActive', 'FundNotEnded', 'NoContributions', 'NotReadyToDissolve', 'InvalidSignature', 'MemoTooLarge', 'AlreadyInNewRaise', 'VrfDelayInProgress', 'NoLeasePeriod']
|
||||
},
|
||||
/**
|
||||
* Lookup591: polkadot_runtime_common::claims::PrevalidateAttests<T>
|
||||
**/
|
||||
@@ -593,4 +1258,4 @@ export default {
|
||||
* Lookup592: polkadot_runtime::Runtime
|
||||
**/
|
||||
PolkadotRuntimeRuntime: 'Null'
|
||||
} as DefinitionsTypes;
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,7 @@
|
||||
/* eslint-disable */
|
||||
|
||||
import type { Bytes, Compact, Enum, Null, Option, Struct, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types';
|
||||
import type { PerU16 } from '@polkadot/types/interfaces/runtime';
|
||||
import type { H256, PerU16 } from '@polkadot/types/interfaces/runtime';
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
|
||||
declare module '@polkadot/types/lookup' {
|
||||
@@ -18,6 +18,42 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly isAuction: boolean;
|
||||
}
|
||||
|
||||
/** @name PalletXcmEvent (107) */
|
||||
export interface PalletXcmEvent extends Enum {
|
||||
readonly isAttempted: boolean;
|
||||
readonly asAttempted: XcmV2TraitsOutcome;
|
||||
readonly isSent: boolean;
|
||||
readonly asSent: ITuple<[XcmV1MultiLocation, XcmV1MultiLocation, XcmV2Xcm]>;
|
||||
readonly isUnexpectedResponse: boolean;
|
||||
readonly asUnexpectedResponse: ITuple<[XcmV1MultiLocation, u64]>;
|
||||
readonly isResponseReady: boolean;
|
||||
readonly asResponseReady: ITuple<[u64, XcmV2Response]>;
|
||||
readonly isNotified: boolean;
|
||||
readonly asNotified: ITuple<[u64, u8, u8]>;
|
||||
readonly isNotifyOverweight: boolean;
|
||||
readonly asNotifyOverweight: ITuple<[u64, u8, u8, u64, u64]>;
|
||||
readonly isNotifyDispatchError: boolean;
|
||||
readonly asNotifyDispatchError: ITuple<[u64, u8, u8]>;
|
||||
readonly isNotifyDecodeFailed: boolean;
|
||||
readonly asNotifyDecodeFailed: ITuple<[u64, u8, u8]>;
|
||||
readonly isInvalidResponder: boolean;
|
||||
readonly asInvalidResponder: ITuple<[XcmV1MultiLocation, u64, Option<XcmV1MultiLocation>]>;
|
||||
readonly isInvalidResponderVersion: boolean;
|
||||
readonly asInvalidResponderVersion: ITuple<[XcmV1MultiLocation, u64]>;
|
||||
readonly isResponseTaken: boolean;
|
||||
readonly asResponseTaken: u64;
|
||||
readonly isAssetsTrapped: boolean;
|
||||
readonly asAssetsTrapped: ITuple<[H256, XcmV1MultiLocation, XcmVersionedMultiAssets]>;
|
||||
readonly isVersionChangeNotified: boolean;
|
||||
readonly asVersionChangeNotified: ITuple<[XcmV1MultiLocation, u32]>;
|
||||
readonly isSupportedVersionChanged: boolean;
|
||||
readonly asSupportedVersionChanged: ITuple<[XcmV1MultiLocation, u32]>;
|
||||
readonly isNotifyTargetSendFail: boolean;
|
||||
readonly asNotifyTargetSendFail: ITuple<[XcmV1MultiLocation, u64, XcmV2TraitsError]>;
|
||||
readonly isNotifyTargetMigrationFail: boolean;
|
||||
readonly asNotifyTargetMigrationFail: ITuple<[XcmVersionedMultiLocation, u64]>;
|
||||
}
|
||||
|
||||
/** @name XcmV1MultiLocation (108) */
|
||||
export interface XcmV1MultiLocation extends Struct {
|
||||
readonly parents: u8;
|
||||
@@ -519,6 +555,67 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly votes24: Vec<ITuple<[Compact<u32>, Vec<ITuple<[Compact<u16>, Compact<PerU16>]>>, Compact<u16>]>>;
|
||||
}
|
||||
|
||||
/** @name PalletXcmCall (511) */
|
||||
export interface PalletXcmCall extends Enum {
|
||||
readonly isSend: boolean;
|
||||
readonly asSend: {
|
||||
readonly dest: XcmVersionedMultiLocation;
|
||||
readonly message: XcmVersionedXcm;
|
||||
} & Struct;
|
||||
readonly isTeleportAssets: boolean;
|
||||
readonly asTeleportAssets: {
|
||||
readonly dest: XcmVersionedMultiLocation;
|
||||
readonly beneficiary: XcmVersionedMultiLocation;
|
||||
readonly assets: XcmVersionedMultiAssets;
|
||||
readonly feeAssetItem: u32;
|
||||
} & Struct;
|
||||
readonly isReserveTransferAssets: boolean;
|
||||
readonly asReserveTransferAssets: {
|
||||
readonly dest: XcmVersionedMultiLocation;
|
||||
readonly beneficiary: XcmVersionedMultiLocation;
|
||||
readonly assets: XcmVersionedMultiAssets;
|
||||
readonly feeAssetItem: u32;
|
||||
} & Struct;
|
||||
readonly isExecute: boolean;
|
||||
readonly asExecute: {
|
||||
readonly message: XcmVersionedXcm;
|
||||
readonly maxWeight: u64;
|
||||
} & Struct;
|
||||
readonly isForceXcmVersion: boolean;
|
||||
readonly asForceXcmVersion: {
|
||||
readonly location: XcmV1MultiLocation;
|
||||
readonly xcmVersion: u32;
|
||||
} & Struct;
|
||||
readonly isForceDefaultXcmVersion: boolean;
|
||||
readonly asForceDefaultXcmVersion: {
|
||||
readonly maybeXcmVersion: Option<u32>;
|
||||
} & Struct;
|
||||
readonly isForceSubscribeVersionNotify: boolean;
|
||||
readonly asForceSubscribeVersionNotify: {
|
||||
readonly location: XcmVersionedMultiLocation;
|
||||
} & Struct;
|
||||
readonly isForceUnsubscribeVersionNotify: boolean;
|
||||
readonly asForceUnsubscribeVersionNotify: {
|
||||
readonly location: XcmVersionedMultiLocation;
|
||||
} & Struct;
|
||||
readonly isLimitedReserveTransferAssets: boolean;
|
||||
readonly asLimitedReserveTransferAssets: {
|
||||
readonly dest: XcmVersionedMultiLocation;
|
||||
readonly beneficiary: XcmVersionedMultiLocation;
|
||||
readonly assets: XcmVersionedMultiAssets;
|
||||
readonly feeAssetItem: u32;
|
||||
readonly weightLimit: XcmV2WeightLimit;
|
||||
} & Struct;
|
||||
readonly isLimitedTeleportAssets: boolean;
|
||||
readonly asLimitedTeleportAssets: {
|
||||
readonly dest: XcmVersionedMultiLocation;
|
||||
readonly beneficiary: XcmVersionedMultiLocation;
|
||||
readonly assets: XcmVersionedMultiAssets;
|
||||
readonly feeAssetItem: u32;
|
||||
readonly weightLimit: XcmV2WeightLimit;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name XcmVersionedXcm (512) */
|
||||
export interface XcmVersionedXcm extends Enum {
|
||||
readonly isV0: boolean;
|
||||
@@ -808,6 +905,23 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly isMigrateAndNotifyOldTargets: boolean;
|
||||
}
|
||||
|
||||
/** @name PalletXcmError (700) */
|
||||
export interface PalletXcmError extends Enum {
|
||||
readonly isUnreachable: boolean;
|
||||
readonly isSendFailure: boolean;
|
||||
readonly isFiltered: boolean;
|
||||
readonly isUnweighableMessage: boolean;
|
||||
readonly isDestinationNotInvertible: boolean;
|
||||
readonly isEmpty: boolean;
|
||||
readonly isCannotReanchor: boolean;
|
||||
readonly isTooManyAssets: boolean;
|
||||
readonly isInvalidOrigin: boolean;
|
||||
readonly isBadVersion: boolean;
|
||||
readonly isBadLocation: boolean;
|
||||
readonly isNoSubscription: boolean;
|
||||
readonly isAlreadySubscribed: boolean;
|
||||
}
|
||||
|
||||
/** @name KusamaRuntimeRuntime (711) */
|
||||
export type KusamaRuntimeRuntime = Null;
|
||||
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
|
||||
/* eslint-disable */
|
||||
|
||||
import type { BitVec, Bytes, Compact, Enum, Null, Option, Struct, U8aFixed, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types';
|
||||
import type { BitVec, Bytes, Compact, Enum, Null, Option, Result, Struct, U8aFixed, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types';
|
||||
import type { EthereumAddress } from '@polkadot/types/interfaces/eth';
|
||||
import type { AccountId32, H256, PerU16 } from '@polkadot/types/interfaces/runtime';
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
|
||||
declare module '@polkadot/types/lookup' {
|
||||
|
||||
/** @name PolkadotRuntimeCommonClaimsPalletEvent (65) */
|
||||
export interface PolkadotRuntimeCommonClaimsPalletEvent extends Enum {
|
||||
readonly isClaimed: boolean;
|
||||
readonly asClaimed: ITuple<[AccountId32, EthereumAddress, u128]>;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeProxyType (72) */
|
||||
export interface PolkadotRuntimeProxyType extends Enum {
|
||||
readonly isAny: boolean;
|
||||
@@ -18,6 +25,16 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly isAuction: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsInclusionPalletEvent (82) */
|
||||
export interface PolkadotRuntimeParachainsInclusionPalletEvent extends Enum {
|
||||
readonly isCandidateBacked: boolean;
|
||||
readonly asCandidateBacked: ITuple<[PolkadotPrimitivesV1CandidateReceipt, Bytes, u32, u32]>;
|
||||
readonly isCandidateIncluded: boolean;
|
||||
readonly asCandidateIncluded: ITuple<[PolkadotPrimitivesV1CandidateReceipt, Bytes, u32, u32]>;
|
||||
readonly isCandidateTimedOut: boolean;
|
||||
readonly asCandidateTimedOut: ITuple<[PolkadotPrimitivesV1CandidateReceipt, Bytes, u32]>;
|
||||
}
|
||||
|
||||
/** @name PolkadotPrimitivesV1CandidateReceipt (83) */
|
||||
export interface PolkadotPrimitivesV1CandidateReceipt extends Struct {
|
||||
readonly descriptor: PolkadotPrimitivesV1CandidateDescriptor;
|
||||
@@ -43,6 +60,38 @@ declare module '@polkadot/types/lookup' {
|
||||
/** @name PolkadotPrimitivesV0CollatorAppSignature (87) */
|
||||
export interface PolkadotPrimitivesV0CollatorAppSignature extends SpCoreSr25519Signature {}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsParasPalletEvent (94) */
|
||||
export interface PolkadotRuntimeParachainsParasPalletEvent extends Enum {
|
||||
readonly isCurrentCodeUpdated: boolean;
|
||||
readonly asCurrentCodeUpdated: u32;
|
||||
readonly isCurrentHeadUpdated: boolean;
|
||||
readonly asCurrentHeadUpdated: u32;
|
||||
readonly isCodeUpgradeScheduled: boolean;
|
||||
readonly asCodeUpgradeScheduled: u32;
|
||||
readonly isNewHeadNoted: boolean;
|
||||
readonly asNewHeadNoted: u32;
|
||||
readonly isActionQueued: boolean;
|
||||
readonly asActionQueued: ITuple<[u32, u32]>;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsUmpPalletEvent (95) */
|
||||
export interface PolkadotRuntimeParachainsUmpPalletEvent extends Enum {
|
||||
readonly isInvalidFormat: boolean;
|
||||
readonly asInvalidFormat: U8aFixed;
|
||||
readonly isUnsupportedVersion: boolean;
|
||||
readonly asUnsupportedVersion: U8aFixed;
|
||||
readonly isExecutedUpward: boolean;
|
||||
readonly asExecutedUpward: ITuple<[U8aFixed, XcmV2TraitsOutcome]>;
|
||||
readonly isWeightExhausted: boolean;
|
||||
readonly asWeightExhausted: ITuple<[U8aFixed, u64, u64]>;
|
||||
readonly isUpwardMessagesReceived: boolean;
|
||||
readonly asUpwardMessagesReceived: ITuple<[u32, u32, u32]>;
|
||||
readonly isOverweightEnqueued: boolean;
|
||||
readonly asOverweightEnqueued: ITuple<[u32, U8aFixed, u64, u64]>;
|
||||
readonly isOverweightServiced: boolean;
|
||||
readonly asOverweightServiced: ITuple<[u64, u64]>;
|
||||
}
|
||||
|
||||
/** @name XcmV2TraitsOutcome (96) */
|
||||
export interface XcmV2TraitsOutcome extends Enum {
|
||||
readonly isComplete: boolean;
|
||||
@@ -85,12 +134,84 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly isWeightNotComputable: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsHrmpPalletEvent (98) */
|
||||
export interface PolkadotRuntimeParachainsHrmpPalletEvent extends Enum {
|
||||
readonly isOpenChannelRequested: boolean;
|
||||
readonly asOpenChannelRequested: ITuple<[u32, u32, u32, u32]>;
|
||||
readonly isOpenChannelCanceled: boolean;
|
||||
readonly asOpenChannelCanceled: ITuple<[u32, PolkadotParachainPrimitivesHrmpChannelId]>;
|
||||
readonly isOpenChannelAccepted: boolean;
|
||||
readonly asOpenChannelAccepted: ITuple<[u32, u32]>;
|
||||
readonly isChannelClosed: boolean;
|
||||
readonly asChannelClosed: ITuple<[u32, PolkadotParachainPrimitivesHrmpChannelId]>;
|
||||
}
|
||||
|
||||
/** @name PolkadotParachainPrimitivesHrmpChannelId (99) */
|
||||
export interface PolkadotParachainPrimitivesHrmpChannelId extends Struct {
|
||||
readonly sender: u32;
|
||||
readonly recipient: u32;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonParasRegistrarPalletEvent (100) */
|
||||
export interface PolkadotRuntimeCommonParasRegistrarPalletEvent extends Enum {
|
||||
readonly isRegistered: boolean;
|
||||
readonly asRegistered: ITuple<[u32, AccountId32]>;
|
||||
readonly isDeregistered: boolean;
|
||||
readonly asDeregistered: u32;
|
||||
readonly isReserved: boolean;
|
||||
readonly asReserved: ITuple<[u32, AccountId32]>;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonSlotsPalletEvent (101) */
|
||||
export interface PolkadotRuntimeCommonSlotsPalletEvent extends Enum {
|
||||
readonly isNewLeasePeriod: boolean;
|
||||
readonly asNewLeasePeriod: u32;
|
||||
readonly isLeased: boolean;
|
||||
readonly asLeased: ITuple<[u32, AccountId32, u32, u32, u128, u128]>;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonAuctionsPalletEvent (102) */
|
||||
export interface PolkadotRuntimeCommonAuctionsPalletEvent extends Enum {
|
||||
readonly isAuctionStarted: boolean;
|
||||
readonly asAuctionStarted: ITuple<[u32, u32, u32]>;
|
||||
readonly isAuctionClosed: boolean;
|
||||
readonly asAuctionClosed: u32;
|
||||
readonly isReserved: boolean;
|
||||
readonly asReserved: ITuple<[AccountId32, u128, u128]>;
|
||||
readonly isUnreserved: boolean;
|
||||
readonly asUnreserved: ITuple<[AccountId32, u128]>;
|
||||
readonly isReserveConfiscated: boolean;
|
||||
readonly asReserveConfiscated: ITuple<[u32, AccountId32, u128]>;
|
||||
readonly isBidAccepted: boolean;
|
||||
readonly asBidAccepted: ITuple<[AccountId32, u32, u128, u32, u32]>;
|
||||
readonly isWinningOffset: boolean;
|
||||
readonly asWinningOffset: ITuple<[u32, u32]>;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonCrowdloanPalletEvent (103) */
|
||||
export interface PolkadotRuntimeCommonCrowdloanPalletEvent extends Enum {
|
||||
readonly isCreated: boolean;
|
||||
readonly asCreated: u32;
|
||||
readonly isContributed: boolean;
|
||||
readonly asContributed: ITuple<[AccountId32, u32, u128]>;
|
||||
readonly isWithdrew: boolean;
|
||||
readonly asWithdrew: ITuple<[AccountId32, u32, u128]>;
|
||||
readonly isPartiallyRefunded: boolean;
|
||||
readonly asPartiallyRefunded: u32;
|
||||
readonly isAllRefunded: boolean;
|
||||
readonly asAllRefunded: u32;
|
||||
readonly isDissolved: boolean;
|
||||
readonly asDissolved: u32;
|
||||
readonly isHandleBidResult: boolean;
|
||||
readonly asHandleBidResult: ITuple<[u32, Result<Null, SpRuntimeDispatchError>]>;
|
||||
readonly isEdited: boolean;
|
||||
readonly asEdited: u32;
|
||||
readonly isMemoUpdated: boolean;
|
||||
readonly asMemoUpdated: ITuple<[AccountId32, u32, Bytes]>;
|
||||
readonly isAddedToNewRaise: boolean;
|
||||
readonly asAddedToNewRaise: u32;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeSessionKeys (162) */
|
||||
export interface PolkadotRuntimeSessionKeys extends Struct {
|
||||
readonly grandpa: SpFinalityGrandpaAppPublic;
|
||||
@@ -107,6 +228,38 @@ declare module '@polkadot/types/lookup' {
|
||||
/** @name PolkadotPrimitivesV1AssignmentAppPublic (164) */
|
||||
export interface PolkadotPrimitivesV1AssignmentAppPublic extends SpCoreSr25519Public {}
|
||||
|
||||
/** @name PolkadotRuntimeCommonClaimsPalletCall (195) */
|
||||
export interface PolkadotRuntimeCommonClaimsPalletCall extends Enum {
|
||||
readonly isClaim: boolean;
|
||||
readonly asClaim: {
|
||||
readonly dest: AccountId32;
|
||||
readonly ethereumSignature: PolkadotRuntimeCommonClaimsEcdsaSignature;
|
||||
} & Struct;
|
||||
readonly isMintClaim: boolean;
|
||||
readonly asMintClaim: {
|
||||
readonly who: EthereumAddress;
|
||||
readonly value: u128;
|
||||
readonly vestingSchedule: Option<ITuple<[u128, u128, u32]>>;
|
||||
readonly statement: Option<PolkadotRuntimeCommonClaimsStatementKind>;
|
||||
} & Struct;
|
||||
readonly isClaimAttest: boolean;
|
||||
readonly asClaimAttest: {
|
||||
readonly dest: AccountId32;
|
||||
readonly ethereumSignature: PolkadotRuntimeCommonClaimsEcdsaSignature;
|
||||
readonly statement: Bytes;
|
||||
} & Struct;
|
||||
readonly isAttest: boolean;
|
||||
readonly asAttest: {
|
||||
readonly statement: Bytes;
|
||||
} & Struct;
|
||||
readonly isMoveClaim: boolean;
|
||||
readonly asMoveClaim: {
|
||||
readonly old: EthereumAddress;
|
||||
readonly new_: EthereumAddress;
|
||||
readonly maybePreclaim: Option<AccountId32>;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonClaimsEcdsaSignature (196) */
|
||||
export interface PolkadotRuntimeCommonClaimsEcdsaSignature extends U8aFixed {}
|
||||
|
||||
@@ -155,12 +308,194 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly votes16: Vec<ITuple<[Compact<u32>, Vec<ITuple<[Compact<u16>, Compact<PerU16>]>>, Compact<u16>]>>;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsConfigurationPalletCall (319) */
|
||||
export interface PolkadotRuntimeParachainsConfigurationPalletCall extends Enum {
|
||||
readonly isSetValidationUpgradeFrequency: boolean;
|
||||
readonly asSetValidationUpgradeFrequency: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetValidationUpgradeDelay: boolean;
|
||||
readonly asSetValidationUpgradeDelay: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetCodeRetentionPeriod: boolean;
|
||||
readonly asSetCodeRetentionPeriod: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetMaxCodeSize: boolean;
|
||||
readonly asSetMaxCodeSize: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetMaxPovSize: boolean;
|
||||
readonly asSetMaxPovSize: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetMaxHeadDataSize: boolean;
|
||||
readonly asSetMaxHeadDataSize: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetParathreadCores: boolean;
|
||||
readonly asSetParathreadCores: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetParathreadRetries: boolean;
|
||||
readonly asSetParathreadRetries: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetGroupRotationFrequency: boolean;
|
||||
readonly asSetGroupRotationFrequency: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetChainAvailabilityPeriod: boolean;
|
||||
readonly asSetChainAvailabilityPeriod: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetThreadAvailabilityPeriod: boolean;
|
||||
readonly asSetThreadAvailabilityPeriod: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetSchedulingLookahead: boolean;
|
||||
readonly asSetSchedulingLookahead: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetMaxValidatorsPerCore: boolean;
|
||||
readonly asSetMaxValidatorsPerCore: {
|
||||
readonly new_: Option<u32>;
|
||||
} & Struct;
|
||||
readonly isSetMaxValidators: boolean;
|
||||
readonly asSetMaxValidators: {
|
||||
readonly new_: Option<u32>;
|
||||
} & Struct;
|
||||
readonly isSetDisputePeriod: boolean;
|
||||
readonly asSetDisputePeriod: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetDisputePostConclusionAcceptancePeriod: boolean;
|
||||
readonly asSetDisputePostConclusionAcceptancePeriod: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetDisputeMaxSpamSlots: boolean;
|
||||
readonly asSetDisputeMaxSpamSlots: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetDisputeConclusionByTimeOutPeriod: boolean;
|
||||
readonly asSetDisputeConclusionByTimeOutPeriod: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetNoShowSlots: boolean;
|
||||
readonly asSetNoShowSlots: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetNDelayTranches: boolean;
|
||||
readonly asSetNDelayTranches: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetZerothDelayTrancheWidth: boolean;
|
||||
readonly asSetZerothDelayTrancheWidth: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetNeededApprovals: boolean;
|
||||
readonly asSetNeededApprovals: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetRelayVrfModuloSamples: boolean;
|
||||
readonly asSetRelayVrfModuloSamples: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetMaxUpwardQueueCount: boolean;
|
||||
readonly asSetMaxUpwardQueueCount: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetMaxUpwardQueueSize: boolean;
|
||||
readonly asSetMaxUpwardQueueSize: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetMaxDownwardMessageSize: boolean;
|
||||
readonly asSetMaxDownwardMessageSize: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetUmpServiceTotalWeight: boolean;
|
||||
readonly asSetUmpServiceTotalWeight: {
|
||||
readonly new_: u64;
|
||||
} & Struct;
|
||||
readonly isSetMaxUpwardMessageSize: boolean;
|
||||
readonly asSetMaxUpwardMessageSize: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetMaxUpwardMessageNumPerCandidate: boolean;
|
||||
readonly asSetMaxUpwardMessageNumPerCandidate: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetHrmpOpenRequestTtl: boolean;
|
||||
readonly asSetHrmpOpenRequestTtl: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetHrmpSenderDeposit: boolean;
|
||||
readonly asSetHrmpSenderDeposit: {
|
||||
readonly new_: u128;
|
||||
} & Struct;
|
||||
readonly isSetHrmpRecipientDeposit: boolean;
|
||||
readonly asSetHrmpRecipientDeposit: {
|
||||
readonly new_: u128;
|
||||
} & Struct;
|
||||
readonly isSetHrmpChannelMaxCapacity: boolean;
|
||||
readonly asSetHrmpChannelMaxCapacity: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetHrmpChannelMaxTotalSize: boolean;
|
||||
readonly asSetHrmpChannelMaxTotalSize: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetHrmpMaxParachainInboundChannels: boolean;
|
||||
readonly asSetHrmpMaxParachainInboundChannels: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetHrmpMaxParathreadInboundChannels: boolean;
|
||||
readonly asSetHrmpMaxParathreadInboundChannels: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetHrmpChannelMaxMessageSize: boolean;
|
||||
readonly asSetHrmpChannelMaxMessageSize: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetHrmpMaxParachainOutboundChannels: boolean;
|
||||
readonly asSetHrmpMaxParachainOutboundChannels: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetHrmpMaxParathreadOutboundChannels: boolean;
|
||||
readonly asSetHrmpMaxParathreadOutboundChannels: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetHrmpMaxMessageNumPerCandidate: boolean;
|
||||
readonly asSetHrmpMaxMessageNumPerCandidate: {
|
||||
readonly new_: u32;
|
||||
} & Struct;
|
||||
readonly isSetUmpMaxIndividualWeight: boolean;
|
||||
readonly asSetUmpMaxIndividualWeight: {
|
||||
readonly new_: u64;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsSharedPalletCall (320) */
|
||||
export type PolkadotRuntimeParachainsSharedPalletCall = Null;
|
||||
|
||||
/** @name PolkadotRuntimeParachainsInclusionPalletCall (321) */
|
||||
export type PolkadotRuntimeParachainsInclusionPalletCall = Null;
|
||||
|
||||
/** @name PolkadotRuntimeParachainsParasInherentPalletCall (322) */
|
||||
export interface PolkadotRuntimeParachainsParasInherentPalletCall extends Enum {
|
||||
readonly isEnter: boolean;
|
||||
readonly asEnter: {
|
||||
readonly data: PolkadotPrimitivesV1InherentData;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name PolkadotPrimitivesV1InherentData (323) */
|
||||
export interface PolkadotPrimitivesV1InherentData extends Struct {
|
||||
readonly bitfields: Vec<PolkadotPrimitivesV1SignedUncheckedSigned>;
|
||||
readonly backedCandidates: Vec<PolkadotPrimitivesV1BackedCandidate>;
|
||||
readonly disputes: Vec<PolkadotPrimitivesV1DisputeStatementSet>;
|
||||
readonly parentHeader: SpRuntimeGenericHeader;
|
||||
readonly parentHeader: SpRuntimeHeader;
|
||||
}
|
||||
|
||||
/** @name PolkadotPrimitivesV1SignedUncheckedSigned (325) */
|
||||
@@ -243,6 +578,203 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly isExplicit: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsParasPalletCall (349) */
|
||||
export interface PolkadotRuntimeParachainsParasPalletCall extends Enum {
|
||||
readonly isForceSetCurrentCode: boolean;
|
||||
readonly asForceSetCurrentCode: {
|
||||
readonly para: u32;
|
||||
readonly newCode: Bytes;
|
||||
} & Struct;
|
||||
readonly isForceSetCurrentHead: boolean;
|
||||
readonly asForceSetCurrentHead: {
|
||||
readonly para: u32;
|
||||
readonly newHead: Bytes;
|
||||
} & Struct;
|
||||
readonly isForceScheduleCodeUpgrade: boolean;
|
||||
readonly asForceScheduleCodeUpgrade: {
|
||||
readonly para: u32;
|
||||
readonly newCode: Bytes;
|
||||
readonly relayParentNumber: u32;
|
||||
} & Struct;
|
||||
readonly isForceNoteNewHead: boolean;
|
||||
readonly asForceNoteNewHead: {
|
||||
readonly para: u32;
|
||||
readonly newHead: Bytes;
|
||||
} & Struct;
|
||||
readonly isForceQueueAction: boolean;
|
||||
readonly asForceQueueAction: {
|
||||
readonly para: u32;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsInitializerPalletCall (350) */
|
||||
export interface PolkadotRuntimeParachainsInitializerPalletCall extends Enum {
|
||||
readonly isForceApprove: boolean;
|
||||
readonly asForceApprove: {
|
||||
readonly upTo: u32;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsDmpPalletCall (351) */
|
||||
export type PolkadotRuntimeParachainsDmpPalletCall = Null;
|
||||
|
||||
/** @name PolkadotRuntimeParachainsUmpPalletCall (352) */
|
||||
export interface PolkadotRuntimeParachainsUmpPalletCall extends Enum {
|
||||
readonly isServiceOverweight: boolean;
|
||||
readonly asServiceOverweight: {
|
||||
readonly index: u64;
|
||||
readonly weightLimit: u64;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsHrmpPalletCall (353) */
|
||||
export interface PolkadotRuntimeParachainsHrmpPalletCall extends Enum {
|
||||
readonly isHrmpInitOpenChannel: boolean;
|
||||
readonly asHrmpInitOpenChannel: {
|
||||
readonly recipient: u32;
|
||||
readonly proposedMaxCapacity: u32;
|
||||
readonly proposedMaxMessageSize: u32;
|
||||
} & Struct;
|
||||
readonly isHrmpAcceptOpenChannel: boolean;
|
||||
readonly asHrmpAcceptOpenChannel: {
|
||||
readonly sender: u32;
|
||||
} & Struct;
|
||||
readonly isHrmpCloseChannel: boolean;
|
||||
readonly asHrmpCloseChannel: {
|
||||
readonly channelId: PolkadotParachainPrimitivesHrmpChannelId;
|
||||
} & Struct;
|
||||
readonly isForceCleanHrmp: boolean;
|
||||
readonly asForceCleanHrmp: {
|
||||
readonly para: u32;
|
||||
} & Struct;
|
||||
readonly isForceProcessHrmpOpen: boolean;
|
||||
readonly isForceProcessHrmpClose: boolean;
|
||||
readonly isHrmpCancelOpenRequest: boolean;
|
||||
readonly asHrmpCancelOpenRequest: {
|
||||
readonly channelId: PolkadotParachainPrimitivesHrmpChannelId;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonParasRegistrarPalletCall (354) */
|
||||
export interface PolkadotRuntimeCommonParasRegistrarPalletCall extends Enum {
|
||||
readonly isRegister: boolean;
|
||||
readonly asRegister: {
|
||||
readonly id: u32;
|
||||
readonly genesisHead: Bytes;
|
||||
readonly validationCode: Bytes;
|
||||
} & Struct;
|
||||
readonly isForceRegister: boolean;
|
||||
readonly asForceRegister: {
|
||||
readonly who: AccountId32;
|
||||
readonly deposit: u128;
|
||||
readonly id: u32;
|
||||
readonly genesisHead: Bytes;
|
||||
readonly validationCode: Bytes;
|
||||
} & Struct;
|
||||
readonly isDeregister: boolean;
|
||||
readonly asDeregister: {
|
||||
readonly id: u32;
|
||||
} & Struct;
|
||||
readonly isSwap: boolean;
|
||||
readonly asSwap: {
|
||||
readonly id: u32;
|
||||
readonly other: u32;
|
||||
} & Struct;
|
||||
readonly isForceRemoveLock: boolean;
|
||||
readonly asForceRemoveLock: {
|
||||
readonly para: u32;
|
||||
} & Struct;
|
||||
readonly isReserve: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonSlotsPalletCall (355) */
|
||||
export interface PolkadotRuntimeCommonSlotsPalletCall extends Enum {
|
||||
readonly isForceLease: boolean;
|
||||
readonly asForceLease: {
|
||||
readonly para: u32;
|
||||
readonly leaser: AccountId32;
|
||||
readonly amount: u128;
|
||||
readonly periodBegin: u32;
|
||||
readonly periodCount: u32;
|
||||
} & Struct;
|
||||
readonly isClearAllLeases: boolean;
|
||||
readonly asClearAllLeases: {
|
||||
readonly para: u32;
|
||||
} & Struct;
|
||||
readonly isTriggerOnboard: boolean;
|
||||
readonly asTriggerOnboard: {
|
||||
readonly para: u32;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonAuctionsPalletCall (356) */
|
||||
export interface PolkadotRuntimeCommonAuctionsPalletCall extends Enum {
|
||||
readonly isNewAuction: boolean;
|
||||
readonly asNewAuction: {
|
||||
readonly duration: Compact<u32>;
|
||||
readonly leasePeriodIndex: Compact<u32>;
|
||||
} & Struct;
|
||||
readonly isBid: boolean;
|
||||
readonly asBid: {
|
||||
readonly para: Compact<u32>;
|
||||
readonly auctionIndex: Compact<u32>;
|
||||
readonly firstSlot: Compact<u32>;
|
||||
readonly lastSlot: Compact<u32>;
|
||||
readonly amount: Compact<u128>;
|
||||
} & Struct;
|
||||
readonly isCancelAuction: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonCrowdloanPalletCall (358) */
|
||||
export interface PolkadotRuntimeCommonCrowdloanPalletCall extends Enum {
|
||||
readonly isCreate: boolean;
|
||||
readonly asCreate: {
|
||||
readonly index: Compact<u32>;
|
||||
readonly cap: Compact<u128>;
|
||||
readonly firstPeriod: Compact<u32>;
|
||||
readonly lastPeriod: Compact<u32>;
|
||||
readonly end: Compact<u32>;
|
||||
readonly verifier: Option<SpRuntimeMultiSigner>;
|
||||
} & Struct;
|
||||
readonly isContribute: boolean;
|
||||
readonly asContribute: {
|
||||
readonly index: Compact<u32>;
|
||||
readonly value: Compact<u128>;
|
||||
readonly signature: Option<SpRuntimeMultiSignature>;
|
||||
} & Struct;
|
||||
readonly isWithdraw: boolean;
|
||||
readonly asWithdraw: {
|
||||
readonly who: AccountId32;
|
||||
readonly index: Compact<u32>;
|
||||
} & Struct;
|
||||
readonly isRefund: boolean;
|
||||
readonly asRefund: {
|
||||
readonly index: Compact<u32>;
|
||||
} & Struct;
|
||||
readonly isDissolve: boolean;
|
||||
readonly asDissolve: {
|
||||
readonly index: Compact<u32>;
|
||||
} & Struct;
|
||||
readonly isEdit: boolean;
|
||||
readonly asEdit: {
|
||||
readonly index: Compact<u32>;
|
||||
readonly cap: Compact<u128>;
|
||||
readonly firstPeriod: Compact<u32>;
|
||||
readonly lastPeriod: Compact<u32>;
|
||||
readonly end: Compact<u32>;
|
||||
readonly verifier: Option<SpRuntimeMultiSigner>;
|
||||
} & Struct;
|
||||
readonly isAddMemo: boolean;
|
||||
readonly asAddMemo: {
|
||||
readonly index: u32;
|
||||
readonly memo: Bytes;
|
||||
} & Struct;
|
||||
readonly isPoke: boolean;
|
||||
readonly asPoke: {
|
||||
readonly index: u32;
|
||||
} & Struct;
|
||||
}
|
||||
|
||||
/** @name SpRuntimeMultiSigner (360) */
|
||||
export interface SpRuntimeMultiSigner extends Enum {
|
||||
readonly isEd25519: boolean;
|
||||
@@ -256,6 +788,16 @@ declare module '@polkadot/types/lookup' {
|
||||
/** @name SpCoreEcdsaPublic (361) */
|
||||
export interface SpCoreEcdsaPublic extends U8aFixed {}
|
||||
|
||||
/** @name PolkadotRuntimeCommonClaimsPalletError (464) */
|
||||
export interface PolkadotRuntimeCommonClaimsPalletError extends Enum {
|
||||
readonly isInvalidEthereumSignature: boolean;
|
||||
readonly isSignerHasNoClaim: boolean;
|
||||
readonly isSenderHasNoClaim: boolean;
|
||||
readonly isPotUnderflow: boolean;
|
||||
readonly isInvalidStatement: boolean;
|
||||
readonly isVestedBalanceExists: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsConfigurationHostConfiguration (514) */
|
||||
export interface PolkadotRuntimeParachainsConfigurationHostConfiguration extends Struct {
|
||||
readonly maxCodeSize: u32;
|
||||
@@ -300,6 +842,11 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly umpMaxIndividualWeight: u64;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsConfigurationPalletError (515) */
|
||||
export interface PolkadotRuntimeParachainsConfigurationPalletError extends Enum {
|
||||
readonly isInvalidNewValue: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsInclusionAvailabilityBitfieldRecord (518) */
|
||||
export interface PolkadotRuntimeParachainsInclusionAvailabilityBitfieldRecord extends Struct {
|
||||
readonly bitfield: BitVec;
|
||||
@@ -318,6 +865,33 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly backingGroup: u32;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsInclusionPalletError (520) */
|
||||
export interface PolkadotRuntimeParachainsInclusionPalletError extends Enum {
|
||||
readonly isWrongBitfieldSize: boolean;
|
||||
readonly isBitfieldDuplicateOrUnordered: boolean;
|
||||
readonly isValidatorIndexOutOfBounds: boolean;
|
||||
readonly isInvalidBitfieldSignature: boolean;
|
||||
readonly isUnscheduledCandidate: boolean;
|
||||
readonly isCandidateScheduledBeforeParaFree: boolean;
|
||||
readonly isWrongCollator: boolean;
|
||||
readonly isScheduledOutOfOrder: boolean;
|
||||
readonly isHeadDataTooLarge: boolean;
|
||||
readonly isPrematureCodeUpgrade: boolean;
|
||||
readonly isNewCodeTooLarge: boolean;
|
||||
readonly isCandidateNotInParentContext: boolean;
|
||||
readonly isInvalidGroupIndex: boolean;
|
||||
readonly isInsufficientBacking: boolean;
|
||||
readonly isInvalidBacking: boolean;
|
||||
readonly isNotCollatorSigned: boolean;
|
||||
readonly isValidationDataHashMismatch: boolean;
|
||||
readonly isIncorrectDownwardMessageHandling: boolean;
|
||||
readonly isInvalidUpwardMessages: boolean;
|
||||
readonly isHrmpWatermarkMishandling: boolean;
|
||||
readonly isInvalidOutboundHrmp: boolean;
|
||||
readonly isInvalidValidationCodeHash: boolean;
|
||||
readonly isParaHeadMismatch: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotPrimitivesV1ScrapedOnChainVotes (521) */
|
||||
export interface PolkadotPrimitivesV1ScrapedOnChainVotes extends Struct {
|
||||
readonly session: u32;
|
||||
@@ -325,6 +899,13 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly disputes: Vec<PolkadotPrimitivesV1DisputeStatementSet>;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsParasInherentPalletError (526) */
|
||||
export interface PolkadotRuntimeParachainsParasInherentPalletError extends Enum {
|
||||
readonly isTooManyInclusionInherents: boolean;
|
||||
readonly isInvalidParentHeader: boolean;
|
||||
readonly isCandidateConcludedInvalid: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsSchedulerParathreadClaimQueue (528) */
|
||||
export interface PolkadotRuntimeParachainsSchedulerParathreadClaimQueue extends Struct {
|
||||
readonly queue: Vec<PolkadotRuntimeParachainsSchedulerQueuedParathread>;
|
||||
@@ -409,6 +990,15 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly parachain: bool;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsParasPalletError (549) */
|
||||
export interface PolkadotRuntimeParachainsParasPalletError extends Enum {
|
||||
readonly isNotRegistered: boolean;
|
||||
readonly isCannotOnboard: boolean;
|
||||
readonly isCannotOffboard: boolean;
|
||||
readonly isCannotUpgrade: boolean;
|
||||
readonly isCannotDowngrade: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsInitializerBufferedSessionChange (551) */
|
||||
export interface PolkadotRuntimeParachainsInitializerBufferedSessionChange extends Struct {
|
||||
readonly validators: Vec<PolkadotPrimitivesV0ValidatorAppPublic>;
|
||||
@@ -422,6 +1012,12 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly msg: Bytes;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsUmpPalletError (555) */
|
||||
export interface PolkadotRuntimeParachainsUmpPalletError extends Enum {
|
||||
readonly isUnknownMessageIndex: boolean;
|
||||
readonly isWeightOverLimit: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsHrmpHrmpOpenChannelRequest (556) */
|
||||
export interface PolkadotRuntimeParachainsHrmpHrmpOpenChannelRequest extends Struct {
|
||||
readonly confirmed: bool;
|
||||
@@ -450,6 +1046,28 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly data: Bytes;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeParachainsHrmpPalletError (564) */
|
||||
export interface PolkadotRuntimeParachainsHrmpPalletError extends Enum {
|
||||
readonly isOpenHrmpChannelToSelf: boolean;
|
||||
readonly isOpenHrmpChannelInvalidRecipient: boolean;
|
||||
readonly isOpenHrmpChannelZeroCapacity: boolean;
|
||||
readonly isOpenHrmpChannelCapacityExceedsLimit: boolean;
|
||||
readonly isOpenHrmpChannelZeroMessageSize: boolean;
|
||||
readonly isOpenHrmpChannelMessageSizeExceedsLimit: boolean;
|
||||
readonly isOpenHrmpChannelAlreadyExists: boolean;
|
||||
readonly isOpenHrmpChannelAlreadyRequested: boolean;
|
||||
readonly isOpenHrmpChannelLimitExceeded: boolean;
|
||||
readonly isAcceptHrmpChannelDoesntExist: boolean;
|
||||
readonly isAcceptHrmpChannelAlreadyConfirmed: boolean;
|
||||
readonly isAcceptHrmpChannelLimitExceeded: boolean;
|
||||
readonly isCloseHrmpChannelUnauthorized: boolean;
|
||||
readonly isCloseHrmpChannelDoesntExist: boolean;
|
||||
readonly isCloseHrmpChannelAlreadyUnderway: boolean;
|
||||
readonly isCancelHrmpOpenChannelUnauthorized: boolean;
|
||||
readonly isOpenHrmpChannelDoesntExist: boolean;
|
||||
readonly isOpenHrmpChannelAlreadyConfirmed: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotPrimitivesV1SessionInfo (566) */
|
||||
export interface PolkadotPrimitivesV1SessionInfo extends Struct {
|
||||
readonly validators: Vec<PolkadotPrimitivesV0ValidatorAppPublic>;
|
||||
@@ -471,6 +1089,39 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly locked: bool;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonParasRegistrarPalletError (569) */
|
||||
export interface PolkadotRuntimeCommonParasRegistrarPalletError extends Enum {
|
||||
readonly isNotRegistered: boolean;
|
||||
readonly isAlreadyRegistered: boolean;
|
||||
readonly isNotOwner: boolean;
|
||||
readonly isCodeTooLarge: boolean;
|
||||
readonly isHeadDataTooLarge: boolean;
|
||||
readonly isNotParachain: boolean;
|
||||
readonly isNotParathread: boolean;
|
||||
readonly isCannotDeregister: boolean;
|
||||
readonly isCannotDowngrade: boolean;
|
||||
readonly isCannotUpgrade: boolean;
|
||||
readonly isParaLocked: boolean;
|
||||
readonly isNotReserved: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonSlotsPalletError (572) */
|
||||
export interface PolkadotRuntimeCommonSlotsPalletError extends Enum {
|
||||
readonly isParaNotOnboarding: boolean;
|
||||
readonly isLeaseError: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonAuctionsPalletError (577) */
|
||||
export interface PolkadotRuntimeCommonAuctionsPalletError extends Enum {
|
||||
readonly isAuctionInProgress: boolean;
|
||||
readonly isLeasePeriodInPast: boolean;
|
||||
readonly isParaNotRegistered: boolean;
|
||||
readonly isNotCurrentAuction: boolean;
|
||||
readonly isNotAuction: boolean;
|
||||
readonly isAuctionEnded: boolean;
|
||||
readonly isAlreadyLeasedOut: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonCrowdloanFundInfo (578) */
|
||||
export interface PolkadotRuntimeCommonCrowdloanFundInfo extends Struct {
|
||||
readonly depositor: AccountId32;
|
||||
@@ -494,6 +1145,33 @@ declare module '@polkadot/types/lookup' {
|
||||
readonly asEnding: u32;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonCrowdloanPalletError (580) */
|
||||
export interface PolkadotRuntimeCommonCrowdloanPalletError extends Enum {
|
||||
readonly isFirstPeriodInPast: boolean;
|
||||
readonly isFirstPeriodTooFarInFuture: boolean;
|
||||
readonly isLastPeriodBeforeFirstPeriod: boolean;
|
||||
readonly isLastPeriodTooFarInFuture: boolean;
|
||||
readonly isCannotEndInPast: boolean;
|
||||
readonly isEndTooFarInFuture: boolean;
|
||||
readonly isOverflow: boolean;
|
||||
readonly isContributionTooSmall: boolean;
|
||||
readonly isInvalidParaId: boolean;
|
||||
readonly isCapExceeded: boolean;
|
||||
readonly isContributionPeriodOver: boolean;
|
||||
readonly isInvalidOrigin: boolean;
|
||||
readonly isNotParachain: boolean;
|
||||
readonly isLeaseActive: boolean;
|
||||
readonly isBidOrLeaseActive: boolean;
|
||||
readonly isFundNotEnded: boolean;
|
||||
readonly isNoContributions: boolean;
|
||||
readonly isNotReadyToDissolve: boolean;
|
||||
readonly isInvalidSignature: boolean;
|
||||
readonly isMemoTooLarge: boolean;
|
||||
readonly isAlreadyInNewRaise: boolean;
|
||||
readonly isVrfDelayInProgress: boolean;
|
||||
readonly isNoLeasePeriod: boolean;
|
||||
}
|
||||
|
||||
/** @name PolkadotRuntimeCommonClaimsPrevalidateAttests (591) */
|
||||
export type PolkadotRuntimeCommonClaimsPrevalidateAttests = Null;
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -81,8 +81,9 @@ assert(hh[0].bitLength() && ms[0].strings && ms[1].values && ms[2].keys, 'All ok
|
||||
const tt1 = registry.createType('(u32, Compact<u64>, u128 , Something)');
|
||||
// unwraps into a u32
|
||||
const tt2 = registry.createType('(((u32)))');
|
||||
// TEST: Adding a single param makes this go over the recursion limit in 4.4.4
|
||||
// lots and lots of params (indicates recursion limit)
|
||||
const tt4 = registry.createType('(u8,u16,u32,u64,u128,u256,u8,u16,u32,u64,u128,u256,u8,u16,u32,u64,u128,u256)');
|
||||
const tt4 = registry.createType('(u8,u16,u32,u64,u128,u256,u8,u16,u32,u64,u128,u256,u8,u16,u32,u64,u128,u256,u8)');
|
||||
// empty
|
||||
const tt5 = registry.createType('()');
|
||||
// nested tuples
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyNumber, INumber, Registry } from '../types';
|
||||
import type { UIntBitLength } from './types';
|
||||
|
||||
import { assert, BN, BN_BILLION, BN_HUNDRED, BN_MILLION, BN_QUINTILL, BN_ZERO, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isBn, isHex, isU8a, stringify, u8aToBn } from '@polkadot/util';
|
||||
import { assert, BN, BN_BILLION, BN_HUNDRED, BN_MILLION, BN_QUINTILL, BN_ZERO, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isBn, isHex, isU8a, u8aToBn } from '@polkadot/util';
|
||||
|
||||
export const DEFAULT_UINT_BITS = 64;
|
||||
|
||||
@@ -28,20 +28,8 @@ function toPercentage (value: BN, divisor: BN): string {
|
||||
|
||||
/** @internal */
|
||||
function decodeAbstractInt (value: AnyNumber, bitLength: UIntBitLength, isNegative: boolean): string {
|
||||
// This function returns a string, which will be passed in the BN
|
||||
// constructor. It would be ideal to actually return a BN, but there's a
|
||||
// bug: https://github.com/indutny/bn.js/issues/206.
|
||||
if (isU8a(value)) {
|
||||
if (!value.length) {
|
||||
return '0';
|
||||
}
|
||||
|
||||
try {
|
||||
// NOTE When passing u8a in (typically from decoded data), it is always Little Endian
|
||||
return u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative }).toString();
|
||||
} catch (error) {
|
||||
throw new Error(`AbstractInt: failed on ${stringify(value)}:: ${(error as Error).message}`);
|
||||
}
|
||||
return u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative }).toString();
|
||||
} else if (isBn(value)) {
|
||||
return value.toString();
|
||||
} else if (isHex(value, -1, true)) {
|
||||
@@ -68,7 +56,15 @@ export abstract class AbstractInt extends BN implements INumber {
|
||||
readonly #isSigned: boolean;
|
||||
|
||||
constructor (registry: Registry, value: AnyNumber = 0, bitLength: UIntBitLength = DEFAULT_UINT_BITS, isSigned = false) {
|
||||
super(decodeAbstractInt(value, bitLength, isSigned));
|
||||
// Construct via a string, which will be passed in the BN constructor.
|
||||
// It would be ideal to actually return a BN, but there is an issue:
|
||||
// https://github.com/indutny/bn.js/issues/206
|
||||
super(
|
||||
// shortcut isU8a as used in SCALE decoding
|
||||
isU8a(value)
|
||||
? u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative: isSigned }).toString()
|
||||
: decodeAbstractInt(value, bitLength, isSigned)
|
||||
);
|
||||
|
||||
this.registry = registry;
|
||||
this.#bitLength = bitLength;
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { AnyJson, Codec, Constructor, ISet, Registry } from '../types';
|
||||
|
||||
import { compactFromU8a, compactToU8a, isHex, isU8a, logger, stringify, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { compareSet, decodeU8a, sortSet, typeToConstructor } from './utils';
|
||||
import { compareSet, decodeU8aVec, sortSet, typeToConstructor } from './utils';
|
||||
|
||||
const l = logger('BTreeSet');
|
||||
|
||||
@@ -15,7 +15,7 @@ const l = logger('BTreeSet');
|
||||
function decodeSetFromU8a<V extends Codec> (registry: Registry, ValClass: Constructor<V>, u8a: Uint8Array): [Set<V>, number] {
|
||||
const output = new Set<V>();
|
||||
const [offset, length] = compactFromU8a(u8a);
|
||||
const [values, decodedLength] = decodeU8a<V>(registry, u8a.subarray(offset), new Array(length.toNumber()).fill(ValClass));
|
||||
const [values, decodedLength] = decodeU8aVec(registry, u8a, offset, ValClass, length.toNumber());
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
output.add(values[i]);
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces';
|
||||
import type { AnyJson, Codec, Constructor, IEnum, Registry } from '../types';
|
||||
|
||||
import { assert, hexToU8a, isHex, isNumber, isObject, isString, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, stringUpperFirst, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
import { assert, isHex, isNumber, isObject, isString, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, stringPascalCase, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Null } from '../primitive/Null';
|
||||
import { mapToTypeMap, typesToMap } from './utils';
|
||||
@@ -40,40 +40,37 @@ function isRustEnum (def: Record<string, string | Constructor> | Record<string,
|
||||
}
|
||||
|
||||
function extractDef (registry: Registry, _def: Record<string, string | Constructor> | Record<string, number> | string[]): { def: TypesDef; isBasic: boolean; isIndexed: boolean } {
|
||||
if (Array.isArray(_def)) {
|
||||
return {
|
||||
def: _def.reduce((def: TypesDef, key, index): TypesDef => {
|
||||
def[key] = { Type: Null, index };
|
||||
|
||||
return def;
|
||||
}, {}),
|
||||
isBasic: true,
|
||||
isIndexed: false
|
||||
};
|
||||
}
|
||||
|
||||
const def: TypesDef = {};
|
||||
let isBasic: boolean;
|
||||
let isIndexed: boolean;
|
||||
let def: TypesDef;
|
||||
|
||||
if (isRustEnum(_def)) {
|
||||
def = Object
|
||||
.entries(mapToTypeMap(registry, _def))
|
||||
.reduce((def: TypesDef, [key, Type], index): TypesDef => {
|
||||
def[key] = { Type, index };
|
||||
if (Array.isArray(_def)) {
|
||||
for (let i = 0; i < _def.length; i++) {
|
||||
def[_def[i]] = { Type: Null, index: i };
|
||||
}
|
||||
|
||||
isBasic = true;
|
||||
isIndexed = false;
|
||||
} else if (isRustEnum(_def)) {
|
||||
const entries = Object.entries(mapToTypeMap(registry, _def));
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const [key, Type] = entries[i];
|
||||
|
||||
def[key] = { Type, index: i };
|
||||
}
|
||||
|
||||
return def;
|
||||
}, {});
|
||||
isBasic = !Object.values(def).some(({ Type }) => Type !== Null);
|
||||
isIndexed = false;
|
||||
} else {
|
||||
def = Object
|
||||
.entries(_def)
|
||||
.reduce((def: TypesDef, [key, index]): TypesDef => {
|
||||
def[key] = { Type: Null, index };
|
||||
const entries = Object.entries(_def);
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const [key, index] = entries[i];
|
||||
|
||||
def[key] = { Type: Null, index };
|
||||
}
|
||||
|
||||
return def;
|
||||
}, {});
|
||||
isBasic = true;
|
||||
isIndexed = true;
|
||||
}
|
||||
@@ -114,23 +111,24 @@ function decodeFromJSON (registry: Registry, def: TypesDef, key: string, value?:
|
||||
}
|
||||
}
|
||||
|
||||
function decodeFromString (registry: Registry, def: TypesDef, value: string): Decoded {
|
||||
return isHex(value)
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
? decodeFromValue(registry, def, hexToU8a(value))
|
||||
: decodeFromJSON(registry, def, value);
|
||||
}
|
||||
function decodeEnum (registry: Registry, def: TypesDef, value?: unknown, index?: number): Decoded {
|
||||
// NOTE We check the index path first, before looking at values - this allows treating
|
||||
// the optional indexes before anything else, more-specific > less-specific
|
||||
if (isNumber(index)) {
|
||||
return createFromValue(registry, def, index, value);
|
||||
} else if (isU8a(value) || isHex(value)) {
|
||||
const u8a = u8aToU8a(value);
|
||||
|
||||
function decodeFromValue (registry: Registry, def: TypesDef, value?: unknown): Decoded {
|
||||
if (isU8a(value)) {
|
||||
// nested, we don't want to match isObject below
|
||||
if (value.length) {
|
||||
return createFromValue(registry, def, value[0], value.subarray(1));
|
||||
if (u8a.length) {
|
||||
return createFromValue(registry, def, u8a[0], u8a.subarray(1));
|
||||
}
|
||||
} else if (value instanceof Enum) {
|
||||
return createFromValue(registry, def, value.index, value.value);
|
||||
} else if (isNumber(value)) {
|
||||
return createFromValue(registry, def, value);
|
||||
} else if (isString(value)) {
|
||||
return decodeFromString(registry, def, value.toString());
|
||||
return decodeFromJSON(registry, def, value.toString());
|
||||
} else if (isObject(value)) {
|
||||
const key = Object.keys(value)[0];
|
||||
|
||||
@@ -141,19 +139,6 @@ function decodeFromValue (registry: Registry, def: TypesDef, value?: unknown): D
|
||||
return createFromValue(registry, def, Object.values(def)[0].index);
|
||||
}
|
||||
|
||||
function decodeEnum (registry: Registry, def: TypesDef, value?: unknown, index?: number): Decoded {
|
||||
// NOTE We check the index path first, before looking at values - this allows treating
|
||||
// the optional indexes before anything else, more-specific > less-specific
|
||||
if (isNumber(index)) {
|
||||
return createFromValue(registry, def, index, value);
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
} else if (value instanceof Enum) {
|
||||
return createFromValue(registry, def, value.index, value.value);
|
||||
}
|
||||
|
||||
return decodeFromValue(registry, def, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Enum
|
||||
* @description
|
||||
@@ -179,15 +164,19 @@ export class Enum implements IEnum {
|
||||
|
||||
readonly #raw: Codec;
|
||||
|
||||
constructor (registry: Registry, def: Record<string, string | Constructor> | Record<string, number> | string[], value?: unknown, index?: number) {
|
||||
const defInfo = extractDef(registry, def);
|
||||
const decoded = decodeEnum(registry, defInfo.def, value, index);
|
||||
constructor (registry: Registry, Types: Record<string, string | Constructor> | Record<string, number> | string[], value?: unknown, index?: number) {
|
||||
const { def, isBasic, isIndexed } = extractDef(registry, Types);
|
||||
|
||||
// shortcut isU8a as used in SCALE decoding
|
||||
const decoded = isU8a(value) && value.length && !isNumber(index)
|
||||
? createFromValue(registry, def, value[0], value.subarray(1))
|
||||
: decodeEnum(registry, def, value, index);
|
||||
|
||||
this.registry = registry;
|
||||
this.#def = defInfo.def;
|
||||
this.#isBasic = defInfo.isBasic;
|
||||
this.#isIndexed = defInfo.isIndexed;
|
||||
this.#indexes = Object.values(defInfo.def).map(({ index }) => index);
|
||||
this.#def = def;
|
||||
this.#isBasic = isBasic;
|
||||
this.#isIndexed = isIndexed;
|
||||
this.#indexes = Object.values(def).map(({ index }) => index);
|
||||
this.#entryIndex = this.#indexes.indexOf(decoded.index) || 0;
|
||||
this.#raw = decoded.value;
|
||||
|
||||
@@ -204,7 +193,7 @@ export class Enum implements IEnum {
|
||||
const isKeys = new Array<string>(keys.length);
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const name = stringUpperFirst(stringCamelCase(keys[i].replace(' ', '_')));
|
||||
const name = stringPascalCase(keys[i].replace(' ', '_'));
|
||||
|
||||
asKeys[i] = `as${name}`;
|
||||
isKeys[i] = `is${name}`;
|
||||
|
||||
@@ -102,6 +102,24 @@ describe('Option', (): void => {
|
||||
).toEqual(new Uint8Array([0]));
|
||||
});
|
||||
|
||||
it('converts toJSON() as null without', (): void => {
|
||||
expect(
|
||||
new Option(registry, Text).toJSON()
|
||||
).toEqual(null);
|
||||
});
|
||||
|
||||
it('converts toJSON() as non-null with Bytes', (): void => {
|
||||
expect(
|
||||
new Option(registry, Bytes, 'abcde').toJSON()
|
||||
).toEqual('0x6162636465');
|
||||
});
|
||||
|
||||
it('converts toJSON() as non-null with Text', (): void => {
|
||||
expect(
|
||||
new Option(registry, Text, 'abcde').toJSON()
|
||||
).toEqual('abcde');
|
||||
});
|
||||
|
||||
describe('utils', (): void => {
|
||||
const test = new Option(registry, Text, '1234');
|
||||
|
||||
|
||||
@@ -5,22 +5,20 @@ import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces';
|
||||
import type { AnyJson, Codec, Constructor, IOption, Registry } from '../types';
|
||||
|
||||
import { assert, isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util';
|
||||
import { assert, isCodec, isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { Null } from '../primitive/Null';
|
||||
import { typeToConstructor } from './utils';
|
||||
|
||||
/** @internal */
|
||||
function decodeOption (registry: Registry, typeName: Constructor | string, value?: unknown): Codec {
|
||||
if (isNull(value) || isUndefined(value) || value instanceof Null || value === '0x') {
|
||||
return new Null(registry);
|
||||
function decodeOption (registry: Registry, Type: Constructor, value?: unknown): Codec {
|
||||
// In the case of an option, unwrap the inner
|
||||
if (value instanceof Option) {
|
||||
value = value.value;
|
||||
}
|
||||
|
||||
const Type = typeToConstructor(registry, typeName);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
if (value instanceof Option) {
|
||||
return decodeOption(registry, Type, value.value);
|
||||
if (isNull(value) || isUndefined(value) || value instanceof Null || value === '0x') {
|
||||
return new Null(registry);
|
||||
} else if (value instanceof Type) {
|
||||
// don't re-create, use as it (which also caters for derived types)
|
||||
return value;
|
||||
@@ -55,12 +53,19 @@ export class Option<T extends Codec> implements IOption<T> {
|
||||
readonly #raw: T;
|
||||
|
||||
constructor (registry: Registry, typeName: Constructor<T> | string, value?: unknown) {
|
||||
this.registry = registry;
|
||||
this.#Type = typeToConstructor(registry, typeName);
|
||||
this.#raw = decodeOption(registry, typeName, value) as T;
|
||||
const Type = typeToConstructor(registry, typeName);
|
||||
const decoded = isU8a(value) && value.length && !isCodec(value)
|
||||
? value[0] === 0
|
||||
? new Null(registry)
|
||||
: new Type(registry, value.subarray(1))
|
||||
: decodeOption(registry, Type, value);
|
||||
|
||||
if (this.#raw.initialU8aLength) {
|
||||
this.#initialU8aLength = 1 + this.#raw.initialU8aLength;
|
||||
this.registry = registry;
|
||||
this.#Type = Type;
|
||||
this.#raw = decoded as T;
|
||||
|
||||
if (decoded.initialU8aLength) {
|
||||
this.#initialU8aLength = 1 + decoded.initialU8aLength;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,7 +160,9 @@ export class Option<T extends Codec> implements IOption<T> {
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): AnyJson {
|
||||
return this.#raw.toJSON();
|
||||
return this.isNone
|
||||
? null
|
||||
: this.#raw.toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { Constructor, ISet, Registry } from '../types';
|
||||
|
||||
import { assert, BN, bnToBn, bnToU8a, isBn, isNumber, isString, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, stringUpperFirst, u8aToBn, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
import { assert, BN, bnToBn, bnToU8a, isBn, isNumber, isString, isU8a, isUndefined, objectProperties, stringify, stringPascalCase, u8aToBn, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { compareArray } from './utils';
|
||||
|
||||
@@ -108,7 +108,7 @@ export class CodecSet extends Set<string> implements ISet<string> {
|
||||
const isKeys = new Array<string>(keys.length);
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
isKeys[i] = `is${stringUpperFirst(stringCamelCase(keys[i]))}`;
|
||||
isKeys[i] = `is${stringPascalCase(keys[i])}`;
|
||||
}
|
||||
|
||||
return class extends CodecSet {
|
||||
|
||||
@@ -5,14 +5,14 @@ import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyJson, BareOpts, Codec, Constructor, ConstructorDef, IStruct, Registry } from '../types';
|
||||
|
||||
import { assert, hexToU8a, isBoolean, isFunction, isHex, isObject, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
import { assert, isBoolean, isFunction, isHex, isObject, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { compareMap, decodeU8a, mapToTypeMap, typesToMap } from './utils';
|
||||
|
||||
type TypesDef<T = Codec> = Record<string, string | Constructor<T>>;
|
||||
|
||||
/** @internal */
|
||||
function decodeStructFromObject (registry: Registry, Types: ConstructorDef, value: any, jsonMap: Map<string, string>): Iterable<[string, Codec]> {
|
||||
function decodeStructFromObject (registry: Registry, Types: ConstructorDef, value: any, jsonMap: Map<string, string>): [Iterable<[string, Codec]>, number] {
|
||||
let jsonObj: Record<string, unknown> | undefined;
|
||||
const inputKeys = Object.keys(Types);
|
||||
const typeofArray = Array.isArray(value);
|
||||
@@ -71,40 +71,7 @@ function decodeStructFromObject (registry: Registry, Types: ConstructorDef, valu
|
||||
}
|
||||
}
|
||||
|
||||
return raw;
|
||||
}
|
||||
|
||||
function decodeZip (k: string, v: Codec): [string, Codec] {
|
||||
return [k, v];
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode input to pass into constructor.
|
||||
*
|
||||
* @param Types - Types definition.
|
||||
* @param value - Value to decode, one of:
|
||||
* - null
|
||||
* - undefined
|
||||
* - hex
|
||||
* - Uint8Array
|
||||
* - object with `{ key1: value1, key2: value2 }`, assuming `key1` and `key2`
|
||||
* are also keys in `Types`
|
||||
* - array with `[value1, value2]` assuming the array has the same length as
|
||||
* `Object.keys(Types)`
|
||||
* @param jsonMap
|
||||
* @internal
|
||||
*/
|
||||
function decodeStruct (registry: Registry, Types: ConstructorDef, value: unknown, jsonMap: Map<string, string>): [Iterable<[string, Codec]>, number] {
|
||||
if (isU8a(value)) {
|
||||
return decodeU8a(registry, value, Types, decodeZip);
|
||||
} else if (value instanceof Struct) {
|
||||
return [value as Iterable<[string, Codec]>, 0];
|
||||
} else if (isHex(value)) {
|
||||
return decodeStruct(registry, Types, hexToU8a(value), jsonMap);
|
||||
}
|
||||
|
||||
// We assume from here that value is a JS object (Array, Map, Object)
|
||||
return [decodeStructFromObject(registry, Types, value || {}, jsonMap), 0];
|
||||
return [raw, 0];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,16 +101,22 @@ export class Struct<
|
||||
|
||||
readonly #Types: ConstructorDef;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
constructor (registry: Registry, Types: S, value?: V | Map<unknown, unknown> | unknown[] | HexString | null, jsonMap = new Map<string, string>()) {
|
||||
const [decoded, decodedLength] = decodeStruct(registry, mapToTypeMap(registry, Types), value, jsonMap);
|
||||
const typeMap = mapToTypeMap(registry, Types);
|
||||
const [decoded, decodedLength] = isU8a(value)
|
||||
? decodeU8a<Codec, [string, Codec]>(registry, value, typeMap, true)
|
||||
: isHex(value)
|
||||
? decodeU8a<Codec, [string, Codec]>(registry, u8aToU8a(value), typeMap, true)
|
||||
: value instanceof Struct
|
||||
? [value as Iterable<[string, Codec]>, 0]
|
||||
: decodeStructFromObject(registry, typeMap, value || {}, jsonMap);
|
||||
|
||||
super(decoded);
|
||||
|
||||
this.registry = registry;
|
||||
this.initialU8aLength = decodedLength;
|
||||
this.#jsonMap = jsonMap;
|
||||
this.#Types = mapToTypeMap(registry, Types);
|
||||
this.#Types = typeMap;
|
||||
}
|
||||
|
||||
public static with<S extends TypesDef> (Types: S, jsonMap?: Map<string, string>): Constructor<Struct<S>> {
|
||||
|
||||
@@ -21,14 +21,14 @@ type TupleTypes = TupleType[] | {
|
||||
};
|
||||
|
||||
/** @internal */
|
||||
function decodeTuple (registry: Registry, _Types: TupleConstructors, value?: AnyTupleValue): [Codec[], number] {
|
||||
function decodeTuple (registry: Registry, Classes: TupleConstructors, value?: AnyTupleValue): [Codec[], number] {
|
||||
if (isU8a(value) || isHex(value)) {
|
||||
return decodeU8a(registry, u8aToU8a(value), _Types);
|
||||
return decodeU8a(registry, u8aToU8a(value), Classes);
|
||||
}
|
||||
|
||||
const Types: Constructor[] = Array.isArray(_Types)
|
||||
? _Types
|
||||
: Object.values(_Types);
|
||||
const Types: Constructor[] = Array.isArray(Classes)
|
||||
? Classes
|
||||
: Object.values(Classes);
|
||||
|
||||
return [
|
||||
Types.map((Type, index): Codec => {
|
||||
@@ -58,16 +58,18 @@ export class Tuple extends AbstractArray<Codec> implements ITuple<Codec[]> {
|
||||
#Types: TupleConstructors;
|
||||
|
||||
constructor (registry: Registry, Types: TupleTypes | TupleType, value?: AnyTupleValue) {
|
||||
const Clazzes = Array.isArray(Types)
|
||||
const Classes = Array.isArray(Types)
|
||||
? Types.map((t) => typeToConstructor(registry, t))
|
||||
: isFunction(Types) || isString(Types)
|
||||
? [typeToConstructor(registry, Types)]
|
||||
: mapToTypeMap(registry, Types);
|
||||
const [values, decodedLength] = decodeTuple(registry, Clazzes, value);
|
||||
const [values, decodedLength] = isU8a(value)
|
||||
? decodeU8a(registry, value, Classes)
|
||||
: decodeTuple(registry, Classes, value);
|
||||
|
||||
super(registry, values, decodedLength);
|
||||
|
||||
this.#Types = Clazzes;
|
||||
this.#Types = Classes;
|
||||
}
|
||||
|
||||
public static with (Types: TupleTypes | TupleType): Constructor<Tuple> {
|
||||
|
||||
@@ -4,25 +4,22 @@
|
||||
import type { AnyU8a, Constructor, Registry } from '../types';
|
||||
import type { U8aBitLength } from './types';
|
||||
|
||||
import { assert, isU8a, u8aToU8a } from '@polkadot/util';
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Raw } from './Raw';
|
||||
|
||||
/** @internal */
|
||||
function decodeU8aFixed (value: AnyU8a, bitLength: U8aBitLength): [AnyU8a, number] {
|
||||
if (isU8a(value)) {
|
||||
const byteLength = bitLength / 8;
|
||||
const u8a = u8aToU8a(value);
|
||||
const byteLength = bitLength / 8;
|
||||
|
||||
if (!value || !value.length) {
|
||||
return [new Uint8Array(byteLength), 0];
|
||||
}
|
||||
|
||||
assert(value.length >= byteLength, () => `Expected at least ${byteLength} bytes (${bitLength} bits), found ${value.length} bytes`);
|
||||
|
||||
return [value.subarray(0, byteLength), byteLength];
|
||||
if (!u8a.length) {
|
||||
return [new Uint8Array(byteLength), 0];
|
||||
}
|
||||
|
||||
return decodeU8aFixed(u8aToU8a(value), bitLength);
|
||||
assert(u8a.length >= byteLength, () => `Expected at least ${byteLength} bytes (${bitLength} bits), found ${u8a.length} bytes`);
|
||||
|
||||
return [u8a.subarray(0, byteLength), byteLength];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,6 +11,12 @@ import { UInt } from '.';
|
||||
describe('UInt', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
it('decodes an empty Uint8array correctly', (): void => {
|
||||
expect(
|
||||
new UInt(registry, new Uint8Array()).toNumber()
|
||||
).toEqual(0);
|
||||
});
|
||||
|
||||
it('still has the BN interfaces', (): void => {
|
||||
expect([
|
||||
new UInt(registry, 32).mul(BN_TWO).toNumber(),
|
||||
@@ -26,6 +32,12 @@ describe('UInt', (): void => {
|
||||
expect(test instanceof BN).toBe(true);
|
||||
});
|
||||
|
||||
// e.g. headers
|
||||
it('decodes hex that are not multiples of 2', (): void => {
|
||||
expect(new UInt(registry, '0x123').toNumber()).toEqual(0x123);
|
||||
expect(new UInt(registry, '0x0123').toNumber()).toEqual(0x123);
|
||||
});
|
||||
|
||||
it('fails on a number that is too large for the bits specified', (): void => {
|
||||
expect(
|
||||
(): UInt => new UInt(registry, '12345678901234567890123456789012345678901234567890', 32)
|
||||
|
||||
@@ -4,15 +4,15 @@
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Codec, Constructor, Registry } from '../types';
|
||||
|
||||
import { assert, u8aConcat } from '@polkadot/util';
|
||||
import { assert, isU8a, u8aConcat } from '@polkadot/util';
|
||||
|
||||
import { AbstractArray } from './AbstractArray';
|
||||
import { typeToConstructor } from './utils';
|
||||
import { decodeU8aVec, typeToConstructor } from './utils';
|
||||
import { decodeVec } from './Vec';
|
||||
|
||||
/** @internal */
|
||||
function decodeVecFixed<T extends Codec> (registry: Registry, Type: Constructor<T>, length: number, value: Uint8Array | HexString | unknown[]): [T[], number] {
|
||||
const [values,, decodedLengthNoOffset] = decodeVec(registry, Type, value, length);
|
||||
function decodeVecFixed<T extends Codec> (registry: Registry, value: Uint8Array | HexString | unknown[], Type: Constructor<T>, length: number): [T[], number, number] {
|
||||
const [values, decodedLength, decodedLengthNoOffset] = decodeVec(registry, Type, value, length);
|
||||
|
||||
while (values.length < length) {
|
||||
values.push(new Type(registry));
|
||||
@@ -20,7 +20,7 @@ function decodeVecFixed<T extends Codec> (registry: Registry, Type: Constructor<
|
||||
|
||||
assert(values.length === length, () => `Expected a length of exactly ${length} entries`);
|
||||
|
||||
return [values, decodedLengthNoOffset];
|
||||
return [values, decodedLength, decodedLengthNoOffset];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,9 +33,11 @@ export class VecFixed<T extends Codec> extends AbstractArray<T> {
|
||||
|
||||
constructor (registry: Registry, Type: Constructor<T> | string, length: number, value: Uint8Array | HexString | unknown[] = [] as unknown[]) {
|
||||
const Clazz = typeToConstructor<T>(registry, Type);
|
||||
const [values, decodedLength] = decodeVecFixed(registry, Clazz, length, value);
|
||||
const [values,, decodedLengthNoOffset] = isU8a(value)
|
||||
? decodeU8aVec(registry, value, 0, Clazz, length)
|
||||
: decodeVecFixed(registry, value, Clazz, length);
|
||||
|
||||
super(registry, values, decodedLength);
|
||||
super(registry, values, decodedLengthNoOffset);
|
||||
|
||||
this.#Type = Clazz;
|
||||
}
|
||||
|
||||
@@ -5,15 +5,15 @@ import type { Codec, Constructor, Registry } from '../../types';
|
||||
|
||||
import { u8aToHex } from '@polkadot/util';
|
||||
|
||||
function formatFailure (error: Error, type: string, u8a: Uint8Array, key?: string): string {
|
||||
function formatFailure (error: Error, type: string | null, u8a: Uint8Array, key?: string): string {
|
||||
return `decodeU8a: failed at ${u8aToHex(u8a)}…${key ? ` on ${key}` : ''}${type ? `: ${type}` : ''}:: ${error.message}`;
|
||||
}
|
||||
|
||||
function getRawType (registry: Registry, Type: Constructor): string {
|
||||
function getRawType (registry: Registry, Type: Constructor): string | null {
|
||||
try {
|
||||
return new Type(registry).toRawType();
|
||||
} catch {
|
||||
return '';
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ function getRawType (registry: Registry, Type: Constructor): string {
|
||||
* @param result - The result array (will be returned with values pushed)
|
||||
* @param types - The array of Constructor to decode the U8a against.
|
||||
*/
|
||||
export function decodeU8a <T extends Codec = Codec, E = T> (registry: Registry, u8a: Uint8Array, types: Constructor[] | { [index: string]: Constructor }, zip?: (key: string, value: T) => E): [E[], number] {
|
||||
export function decodeU8a <T extends Codec = Codec, E = T> (registry: Registry, u8a: Uint8Array, types: Constructor[] | { [index: string]: Constructor }, withZip?: boolean): [E[], number] {
|
||||
const [Types, keys]: [Constructor[], string[]] = Array.isArray(types)
|
||||
? [types, []]
|
||||
: [Object.values(types), Object.keys(types)];
|
||||
@@ -38,8 +38,8 @@ export function decodeU8a <T extends Codec = Codec, E = T> (registry: Registry,
|
||||
const value = new Types[i](registry, u8a.subarray(offset));
|
||||
|
||||
offset += value.initialU8aLength || value.encodedLength;
|
||||
result[i] = zip
|
||||
? zip(keys[i], value as T)
|
||||
result[i] = withZip
|
||||
? [keys[i], value] as unknown as E
|
||||
: value as unknown as E;
|
||||
} catch (error) {
|
||||
throw new Error(formatFailure(
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { ExtDef } from '../extrinsic/signedExtensions/types';
|
||||
import type { ChainProperties, CodecHash, DispatchErrorModule, Hash, MetadataLatest, SiField, SiLookupTypeId, SiVariant } from '../interfaces/types';
|
||||
import type { CallFunction, Codec, CodecHasher, Constructor, DetectCodec, DetectConstructor, RegisteredTypes, Registry, RegistryError, RegistryTypes } from '../types';
|
||||
import type { CallFunction, Codec, CodecHasher, Constructor, Definitions, DetectCodec, DetectConstructor, RegisteredTypes, Registry, RegistryError, RegistryTypes } from '../types';
|
||||
import type { CreateOptions, TypeDef } from './types';
|
||||
|
||||
import { assert, assertReturn, BN_ZERO, formatBalance, isFunction, isString, isU8a, lazyMethod, logger, objectSpread, stringCamelCase, stringify } from '@polkadot/util';
|
||||
@@ -158,7 +158,7 @@ export class TypeRegistry implements Registry {
|
||||
|
||||
readonly #knownDefaults: RegistryTypes;
|
||||
|
||||
readonly #knownDefinitions: Record<string, { types: RegistryTypes }>;
|
||||
readonly #knownDefinitions: Record<string, Definitions>;
|
||||
|
||||
#knownTypes: RegisteredTypes = {};
|
||||
|
||||
@@ -170,7 +170,7 @@ export class TypeRegistry implements Registry {
|
||||
|
||||
constructor (createdAtHash?: Hash | Uint8Array | string) {
|
||||
this.#knownDefaults = objectSpread({ Json, Metadata, PortableRegistry, Raw }, baseTypes);
|
||||
this.#knownDefinitions = definitions as unknown as Record<string, { types: RegistryTypes }>;
|
||||
this.#knownDefinitions = definitions;
|
||||
|
||||
this.init();
|
||||
|
||||
@@ -192,7 +192,7 @@ export class TypeRegistry implements Registry {
|
||||
const allKnown = Object.values(this.#knownDefinitions);
|
||||
|
||||
for (let i = 0; i < allKnown.length; i++) {
|
||||
this.register(allKnown[i].types);
|
||||
this.register(allKnown[i].types as unknown as RegistryTypes);
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
@@ -68,8 +68,8 @@ describe('ExtrinsicSignatureV4', (): void => {
|
||||
'00' + // MultiAddress
|
||||
'd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' +
|
||||
'01' +
|
||||
'4242424242424242424242424242424242424242424242424242424242424242' +
|
||||
'4242424242424242424242424242424242424242424242424242424242424242' +
|
||||
'0101010101010101010101010101010101010101010101010101010101010101' +
|
||||
'0101010101010101010101010101010101010101010101010101010101010101' +
|
||||
'00a50100'
|
||||
);
|
||||
});
|
||||
@@ -92,13 +92,39 @@ describe('ExtrinsicSignatureV4', (): void => {
|
||||
).toHex()
|
||||
).toEqual(
|
||||
'0x' +
|
||||
// Address = AccountId
|
||||
// '00' +
|
||||
// Address = AccountId, no prefix
|
||||
'd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' +
|
||||
// This is a prefix-less signature, anySignture as opposed to Multi above
|
||||
// '01' +
|
||||
'4242424242424242424242424242424242424242424242424242424242424242' +
|
||||
'4242424242424242424242424242424242424242424242424242424242424242' +
|
||||
'0101010101010101010101010101010101010101010101010101010101010101' +
|
||||
'0101010101010101010101010101010101010101010101010101010101010101' +
|
||||
'00a50100'
|
||||
);
|
||||
});
|
||||
|
||||
it('fake signs with non-enum signature', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
const metadata = new Metadata(registry, metadataStatic);
|
||||
|
||||
registry.setMetadata(metadata);
|
||||
registry.register({
|
||||
Address: 'AccountId',
|
||||
ExtrinsicSignature: '[u8;65]'
|
||||
});
|
||||
|
||||
expect(
|
||||
new ExtrinsicSignature(registry).signFake(
|
||||
registry.createType('Call'),
|
||||
pairs.alice.address,
|
||||
signOptions
|
||||
).toHex()
|
||||
).toEqual(
|
||||
'0x' +
|
||||
// Address = AccountId, no prefix
|
||||
'd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' +
|
||||
// 65 bytes here
|
||||
'01' +
|
||||
'0101010101010101010101010101010101010101010101010101010101010101' +
|
||||
'0101010101010101010101010101010101010101010101010101010101010101' +
|
||||
'00a50100'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -7,16 +7,15 @@ import type { Address, Balance, Call, Index } from '../../interfaces/runtime';
|
||||
import type { ExtrinsicPayloadValue, IExtrinsicSignature, IKeyringPair, Registry, SignatureOptions } from '../../types';
|
||||
import type { ExtrinsicSignatureOptions } from '../types';
|
||||
|
||||
import { assert, isU8a, isUndefined, objectProperties, objectSpread, stringify, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
import { assert, isU8a, isUndefined, objectProperties, objectSpread, stringify, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { Compact } from '../../codec/Compact';
|
||||
import { Enum } from '../../codec/Enum';
|
||||
import { Struct } from '../../codec/Struct';
|
||||
import { EMPTY_U8A, IMMORTAL_ERA } from '../constants';
|
||||
import { GenericExtrinsicPayloadV4 } from './ExtrinsicPayload';
|
||||
|
||||
const FAKE_NONE = new Uint8Array();
|
||||
const FAKE_SOME = new Uint8Array([1]);
|
||||
// Ensure we have enough data for all types of signatures
|
||||
const FAKE_SIGNATURE = new Uint8Array(256).fill(1);
|
||||
|
||||
function toAddress (registry: Registry, address: Address | Uint8Array | string): Address {
|
||||
return registry.createType('Address', isU8a(address) ? u8aToHex(address) : address);
|
||||
@@ -28,7 +27,6 @@ function toAddress (registry: Registry, address: Address | Uint8Array | string):
|
||||
* A container for the [[Signature]] associated with a specific [[Extrinsic]]
|
||||
*/
|
||||
export class GenericExtrinsicSignatureV4 extends Struct implements IExtrinsicSignature {
|
||||
#fakePrefix: Uint8Array;
|
||||
#signKeys: string[];
|
||||
|
||||
constructor (registry: Registry, value?: GenericExtrinsicSignatureV4 | Uint8Array, { isSigned }: ExtrinsicSignatureOptions = {}) {
|
||||
@@ -44,9 +42,6 @@ export class GenericExtrinsicSignatureV4 extends Struct implements IExtrinsicSig
|
||||
GenericExtrinsicSignatureV4.decodeExtrinsicSignature(value, isSigned)
|
||||
);
|
||||
|
||||
this.#fakePrefix = registry.createType('ExtrinsicSignature') instanceof Enum
|
||||
? FAKE_SOME
|
||||
: FAKE_NONE;
|
||||
this.#signKeys = Object.keys(signTypes);
|
||||
|
||||
objectProperties(this, this.#signKeys, (k) => this.get(k));
|
||||
@@ -188,7 +183,7 @@ export class GenericExtrinsicSignatureV4 extends Struct implements IExtrinsicSig
|
||||
|
||||
const signer = toAddress(this.registry, address);
|
||||
const payload = this.createPayload(method, options);
|
||||
const signature = this.registry.createType('ExtrinsicSignature', u8aConcat(this.#fakePrefix, new Uint8Array(64).fill(0x42)));
|
||||
const signature = this.registry.createType('ExtrinsicSignature', FAKE_SIGNATURE);
|
||||
|
||||
return this._injectSignature(signer, signature, payload);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export default {
|
||||
BeefyId: '[u8; 33]',
|
||||
BeefySignedCommitment: {
|
||||
commitment: 'BeefyCommitment',
|
||||
signatures: 'Vec<Option<Signature>>'
|
||||
signatures: 'Vec<Option<EcdsaSignature>>'
|
||||
},
|
||||
BeefyNextAuthoritySet: {
|
||||
id: 'u64',
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
/* eslint-disable */
|
||||
|
||||
import type { Option, Struct, U8aFixed, Vec, u32, u64 } from '@polkadot/types';
|
||||
import type { Signature } from '@polkadot/types/interfaces/extrinsics';
|
||||
import type { EcdsaSignature } from '@polkadot/types/interfaces/extrinsics';
|
||||
import type { BlockNumber, H256 } from '@polkadot/types/interfaces/runtime';
|
||||
|
||||
/** @name BeefyCommitment */
|
||||
@@ -28,7 +28,7 @@ export interface BeefyPayload extends MmrRootHash {}
|
||||
/** @name BeefySignedCommitment */
|
||||
export interface BeefySignedCommitment extends Struct {
|
||||
readonly commitment: BeefyCommitment;
|
||||
readonly signatures: Vec<Option<Signature>>;
|
||||
readonly signatures: Vec<Option<EcdsaSignature>>;
|
||||
}
|
||||
|
||||
/** @name MmrRootHash */
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// technically runtime can go below, but since it is the base, do it first
|
||||
export { default as runtime } from './runtime/definitions';
|
||||
export * from './essentials';
|
||||
|
||||
// substrate types
|
||||
export { default as assets } from './assets/definitions';
|
||||
@@ -53,15 +52,11 @@ export { default as poll } from './poll/definitions';
|
||||
export { default as purchase } from './purchase/definitions';
|
||||
export { default as xcm } from './xcm/definitions';
|
||||
|
||||
// scale-info & contracts
|
||||
export { default as contractsAbi } from './contractsAbi/definitions';
|
||||
export { default as scaleInfo } from './scaleInfo/definitions';
|
||||
|
||||
// other useful types
|
||||
export { default as contractsAbi } from './contractsAbi/definitions';
|
||||
export { default as eth } from './eth/definitions';
|
||||
|
||||
// pull in metadata & rpc last, assuming that is uses info from above
|
||||
export { default as metadata } from './metadata/definitions';
|
||||
// pull in rpc last, assuming that is uses info from above
|
||||
export { default as rpc } from './rpc/definitions';
|
||||
|
||||
// rpc-only definitions
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { default as metadata } from './metadata/definitions';
|
||||
export { default as runtime } from './runtime/definitions';
|
||||
export { default as scaleInfo } from './scaleInfo/definitions';
|
||||
@@ -5,29 +5,26 @@ import type { DefinitionRpcExt, DefinitionRpcSub } from '../types';
|
||||
|
||||
import { objectSpread } from '@polkadot/util';
|
||||
|
||||
import * as definitions from './definitions';
|
||||
import * as defs from './definitions';
|
||||
|
||||
const jsonrpc: Record<string, Record<string, DefinitionRpcExt>> = {};
|
||||
|
||||
Object
|
||||
.keys(definitions)
|
||||
.filter((key) => Object.keys(definitions[key as 'babe'].rpc || {}).length !== 0)
|
||||
.forEach((_section): void => {
|
||||
jsonrpc[_section] = {};
|
||||
Object.keys(defs).forEach((s) =>
|
||||
Object.entries(defs[s as 'babe'].rpc || {}).forEach(([method, def]): void => {
|
||||
// allow for section overrides
|
||||
const section = def.aliasSection || s;
|
||||
|
||||
Object
|
||||
.entries(definitions[_section as 'babe'].rpc)
|
||||
.forEach(([method, def]): void => {
|
||||
const isSubscription = !!(def as DefinitionRpcSub).pubsub;
|
||||
const section = def.aliasSection || _section;
|
||||
if (!jsonrpc[section]) {
|
||||
jsonrpc[section] = {};
|
||||
}
|
||||
|
||||
// allow for section overrides
|
||||
if (!jsonrpc[section]) {
|
||||
jsonrpc[section] = {};
|
||||
}
|
||||
|
||||
jsonrpc[section][method] = objectSpread({}, def, { isSubscription, jsonrpc: `${section}_${method}`, method, section });
|
||||
});
|
||||
});
|
||||
jsonrpc[section][method] = objectSpread({}, def, {
|
||||
isSubscription: !!(def as DefinitionRpcSub).pubsub,
|
||||
jsonrpc: `${section}_${method}`,
|
||||
method,
|
||||
section
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
export default jsonrpc;
|
||||
|
||||
@@ -31,7 +31,6 @@ export * from './grandpa/types';
|
||||
export * from './identity/types';
|
||||
export * from './imOnline/types';
|
||||
export * from './lottery/types';
|
||||
export * from './metadata/types';
|
||||
export * from './mmr/types';
|
||||
export * from './offchain/types';
|
||||
export * from './offences/types';
|
||||
@@ -42,8 +41,6 @@ export * from './proxy/types';
|
||||
export * from './purchase/types';
|
||||
export * from './recovery/types';
|
||||
export * from './rpc/types';
|
||||
export * from './runtime/types';
|
||||
export * from './scaleInfo/types';
|
||||
export * from './scheduler/types';
|
||||
export * from './session/types';
|
||||
export * from './society/types';
|
||||
@@ -58,3 +55,6 @@ export * from './uniques/types';
|
||||
export * from './utility/types';
|
||||
export * from './vesting/types';
|
||||
export * from './xcm/types';
|
||||
export * from './metadata/types';
|
||||
export * from './runtime/types';
|
||||
export * from './scaleInfo/types';
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { SiField, SiLookupTypeId, SiPath, SiType, SiTypeDefArray, SiTypeDef
|
||||
import type { Text, Type } from '../../primitive';
|
||||
import type { Registry, TypeDef } from '../../types';
|
||||
|
||||
import { assert, isNumber, isString, objectSpread, stringCamelCase, stringify, stringUpperFirst } from '@polkadot/util';
|
||||
import { assert, isNumber, isString, objectSpread, stringCamelCase, stringify, stringPascalCase } from '@polkadot/util';
|
||||
|
||||
import { Struct } from '../../codec/Struct';
|
||||
import { withTypeString } from '../../create/encodeTypes';
|
||||
@@ -26,9 +26,13 @@ const PRIMITIVE_ALIAS: Record<string, string> = {
|
||||
|
||||
// These are types where we have a specific decoding/encoding override + helpers
|
||||
const PATHS_ALIAS = splitNamespace([
|
||||
// match {node, polkadot, ...}_runtime
|
||||
'*_runtime::Call',
|
||||
'*_runtime::Event',
|
||||
// These come in different forms
|
||||
// - node_runtime::Call
|
||||
// - polkadot_runtime::Call
|
||||
// - node_template_runtime::Call
|
||||
// - interbtc_runtime_parachain::Call
|
||||
'*_runtime_*::Call',
|
||||
'*_runtime_*::Event',
|
||||
// these have a specific encoding or logic (for pallets)
|
||||
'pallet_democracy::vote::Vote',
|
||||
'pallet_identity::types::Data',
|
||||
@@ -57,6 +61,9 @@ const WRAPPERS = ['BoundedBTreeMap', 'BoundedVec', 'Box', 'BTreeMap', 'Cow', 'Re
|
||||
// These are reserved and/or conflicts with built-in Codec or JS definitions
|
||||
const RESERVED = ['entries', 'hash', 'keys', 'new', 'size'];
|
||||
|
||||
// Remove these from all paths at index 1
|
||||
const PATH_RM_INDEX_1 = ['generic', 'misc', 'pallet', 'traits', 'types'];
|
||||
|
||||
function splitNamespace (values: string[]): string[][] {
|
||||
return values.map((v) => v.split('::'));
|
||||
}
|
||||
@@ -78,16 +85,24 @@ function matchParts (first: string[], second: (string | Text)[]): boolean {
|
||||
}
|
||||
|
||||
if (a.includes('*') && a.includes('_') && b.includes('_')) {
|
||||
const suba = a.split('_');
|
||||
const subb = b.split('_');
|
||||
let suba = a.split('_');
|
||||
let subb = b.split('_');
|
||||
|
||||
// match initial *'s to multiples if we have a match for the other
|
||||
if (suba[0] === '*') {
|
||||
// the first parts where the length is greater is always a match
|
||||
while (suba.length < subb.length) {
|
||||
subb.shift();
|
||||
const indexOf = subb.indexOf(suba[1]);
|
||||
|
||||
if (indexOf !== -1) {
|
||||
suba = suba.slice(1);
|
||||
subb = subb.slice(indexOf);
|
||||
}
|
||||
}
|
||||
|
||||
// check for * matches at the end, adjust accordingly
|
||||
if ((suba.length === 2) && (suba[1] === '*') && (suba[0] === subb[0])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return matchParts(suba, subb);
|
||||
}
|
||||
|
||||
@@ -103,17 +118,34 @@ function getAliasPath (path: SiPath): string | null {
|
||||
: null;
|
||||
}
|
||||
|
||||
function hasNoDupes (input: [number, string, SiTypeParameter[]][]): boolean {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const [ai, an] = input[i];
|
||||
|
||||
for (let j = 0; j < input.length; j++) {
|
||||
const [bi, bn] = input[j];
|
||||
|
||||
// if the indexes are not the same and the names match, we have a dupe
|
||||
if (ai !== bi && an === bn) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function removeDuplicateNames (lookup: PortableRegistry, names: [number, string | null, SiTypeParameter[]][]): [number, string, SiTypeParameter[]][] {
|
||||
const rewrite: Record<number, string> = {};
|
||||
|
||||
return names
|
||||
.map(([lookupIndex, name, params]): [number, string | null, SiTypeParameter[]] => {
|
||||
.map(([lookupIndex, name, params]): [number, string, SiTypeParameter[]] | null => {
|
||||
if (!name) {
|
||||
return [lookupIndex, null, params];
|
||||
return null;
|
||||
}
|
||||
|
||||
// those where the name is matching
|
||||
const allSame = names.filter(([, oName]) => name === oName);
|
||||
// those where the name is matching (since name is filtered, these all do have names)
|
||||
const allSame = names.filter(([, oName]) => name === oName) as [number, string, SiTypeParameter[]][];
|
||||
|
||||
// are there among matching names
|
||||
const anyDiff = allSame.some(([oIndex,, oParams]) =>
|
||||
@@ -146,43 +178,38 @@ function removeDuplicateNames (lookup: PortableRegistry, names: [number, string
|
||||
}
|
||||
|
||||
// see if using the param type helps
|
||||
const adjusted = allSame.map(([oIndex, oName, oParams]): [number, string | null, SiTypeParameter[]] => {
|
||||
const adjusted = new Array<[number, string, SiTypeParameter[]]>(allSame.length);
|
||||
|
||||
for (let i = 0; i < allSame.length; i++) {
|
||||
const [oIndex, oName, oParams] = allSame[i];
|
||||
const { def, path } = lookup.getSiType(oParams[paramIdx].type.unwrap());
|
||||
|
||||
if (!def.isPrimitive && !path.length) {
|
||||
return [oIndex, null, params];
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
adjusted[i] = [
|
||||
oIndex,
|
||||
def.isPrimitive
|
||||
? `${oName as string}${def.asPrimitive.toString()}`
|
||||
: `${oName as string}${path[path.length - 1].toString()}`,
|
||||
? `${oName}${def.asPrimitive.toString()}`
|
||||
: `${oName}${path[path.length - 1].toString()}`,
|
||||
params
|
||||
];
|
||||
});
|
||||
|
||||
// any dupes remaining?
|
||||
const noDupes = adjusted.every(([i, n]) =>
|
||||
!!n &&
|
||||
!adjusted.some(([ai, an]) =>
|
||||
i !== ai &&
|
||||
n === an
|
||||
)
|
||||
);
|
||||
|
||||
if (noDupes) {
|
||||
// we filtered above for null names
|
||||
adjusted.forEach(([index, name]): void => {
|
||||
rewrite[index] = name as string;
|
||||
});
|
||||
}
|
||||
|
||||
return noDupes
|
||||
? [lookupIndex, name, params]
|
||||
: [lookupIndex, null, params];
|
||||
if (hasNoDupes(adjusted)) {
|
||||
for (let i = 0; i < adjusted.length; i++) {
|
||||
const [index, name] = adjusted[i];
|
||||
|
||||
rewrite[index] = name;
|
||||
}
|
||||
|
||||
return [lookupIndex, name, params];
|
||||
}
|
||||
|
||||
return null;
|
||||
})
|
||||
.filter((n): n is [number, string, SiTypeParameter[]] => !!n[1])
|
||||
.filter((n): n is [number, string, SiTypeParameter[]] => !!n)
|
||||
.map(([lookupIndex, name, params]) => [
|
||||
lookupIndex,
|
||||
rewrite[lookupIndex] || name,
|
||||
@@ -190,32 +217,33 @@ function removeDuplicateNames (lookup: PortableRegistry, names: [number, string
|
||||
]);
|
||||
}
|
||||
|
||||
function extractName (types: PortableType[], { id, type: { params, path } }: PortableType): [number, string | null, SiTypeParameter[]] {
|
||||
const lookupIndex = id.toNumber();
|
||||
|
||||
function extractName (types: PortableType[], { id, type: { params, path } }: PortableType): [number, string, SiTypeParameter[]] | null {
|
||||
// if we have no path or determined as a wrapper, we just skip it
|
||||
if (!path.length || WRAPPERS.includes(path[path.length - 1].toString())) {
|
||||
return [lookupIndex, null, []];
|
||||
return null;
|
||||
}
|
||||
|
||||
const parts = path
|
||||
.map((p) => stringUpperFirst(stringCamelCase(p)))
|
||||
.filter((p, index) =>
|
||||
(
|
||||
// Remove ::{misc, pallet, traits, types}::
|
||||
.map((p) => stringPascalCase(p))
|
||||
.filter((p, index) => {
|
||||
const lower = p.toLowerCase();
|
||||
|
||||
return (
|
||||
// Remove ::{generic, misc, pallet, traits, types}::
|
||||
index !== 1 ||
|
||||
!['Misc', 'Pallet', 'Traits', 'Types'].includes(p.toString())
|
||||
!PATH_RM_INDEX_1.includes(lower)
|
||||
) &&
|
||||
(
|
||||
// sp_runtime::generic::digest::Digest -> sp_runtime::generic::Digest
|
||||
// sp_runtime::multiaddress::MultiAddress -> sp_runtime::MultiAddress
|
||||
index === path.length - 1 ||
|
||||
p.toLowerCase() !== path[index + 1].toLowerCase()
|
||||
)
|
||||
);
|
||||
lower !== path[index + 1].toLowerCase()
|
||||
);
|
||||
});
|
||||
let typeName = parts.join('');
|
||||
|
||||
if (parts.length === 2 && parts[parts.length - 1] === 'RawOrigin' && params.length === 2 && params[1].type.isSome) {
|
||||
// Do magic for RawOrigin lookup
|
||||
// do magic for RawOrigin lookup, e.g. pallet_collective::RawOrigin
|
||||
if (parts.length === 2 && parts[1] === 'RawOrigin' && params.length === 2 && params[1].type.isSome) {
|
||||
const instanceType = types[params[1].type.unwrap().toNumber()];
|
||||
|
||||
if (instanceType.type.path.length === 2) {
|
||||
@@ -223,14 +251,63 @@ function extractName (types: PortableType[], { id, type: { params, path } }: Por
|
||||
}
|
||||
}
|
||||
|
||||
return [lookupIndex, typeName, params];
|
||||
return [id.toNumber(), typeName, params];
|
||||
}
|
||||
|
||||
function extractNames (lookup: PortableRegistry, types: PortableType[]): [Record<number, string>, Record<string, SiTypeParameter[]>] {
|
||||
const dedup = removeDuplicateNames(lookup, types.map((t) =>
|
||||
extractName(types, t)
|
||||
));
|
||||
function registerTypes (lookup: PortableRegistry, lookups: Record<string, string>, names: Record<number, string>, params: Record<string, SiTypeParameter[]>): void {
|
||||
// Register the types we extracted
|
||||
lookup.registry.register(lookups);
|
||||
|
||||
// Try and extract the AccountId/Address/Signature type from UncheckedExtrinsic
|
||||
if (params.SpRuntimeUncheckedExtrinsic) {
|
||||
// Address, Call, Signature, Extra
|
||||
const [addrParam,, sigParam] = params.SpRuntimeUncheckedExtrinsic;
|
||||
const siAddress = lookup.getSiType(addrParam.type.unwrap());
|
||||
const siSignature = lookup.getSiType(sigParam.type.unwrap());
|
||||
const nsSignature = createNamespace(siSignature);
|
||||
let nsAccountId = createNamespace(siAddress);
|
||||
const isMultiAddress = nsAccountId === 'sp_runtime::multiaddress::MultiAddress';
|
||||
|
||||
// With multiaddress, we check the first type param again
|
||||
if (isMultiAddress) {
|
||||
// AccountId, AccountIndex
|
||||
const [idParam] = siAddress.params;
|
||||
|
||||
nsAccountId = createNamespace(lookup.getSiType(idParam.type.unwrap()));
|
||||
}
|
||||
|
||||
lookup.registry.register({
|
||||
AccountId: ['sp_core::crypto::AccountId32'].includes(nsAccountId)
|
||||
? 'AccountId32'
|
||||
: ['account::AccountId20', 'primitive_types::H160'].includes(nsAccountId)
|
||||
? 'AccountId20'
|
||||
: 'AccountId32', // other, default to AccountId32
|
||||
Address: isMultiAddress
|
||||
? 'MultiAddress'
|
||||
: 'AccountId',
|
||||
ExtrinsicSignature: ['sp_runtime::MultiSignature'].includes(nsSignature)
|
||||
? 'MultiSignature'
|
||||
: names[sigParam.type.unwrap().toNumber()] || 'MultiSignature'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function extractTypeInfo (lookup: PortableRegistry, portable: PortableType[]): [Record<number, PortableType>, Record<string, string>, Record<number, string>, Record<string, SiTypeParameter[]>] {
|
||||
const nameInfo: [number, string, SiTypeParameter[]][] = [];
|
||||
const types: Record<number, PortableType> = {};
|
||||
|
||||
for (let i = 0; i < portable.length; i++) {
|
||||
const type = portable[i];
|
||||
const extracted = extractName(portable, portable[i]);
|
||||
|
||||
if (extracted) {
|
||||
nameInfo.push(extracted);
|
||||
}
|
||||
|
||||
types[type.id.toNumber()] = type;
|
||||
}
|
||||
|
||||
const dedup = removeDuplicateNames(lookup, nameInfo);
|
||||
const lookups: Record<string, string> = {};
|
||||
const names: Record<number, string> = {};
|
||||
const params: Record<string, SiTypeParameter[]> = {};
|
||||
@@ -243,23 +320,7 @@ function extractNames (lookup: PortableRegistry, types: PortableType[]): [Record
|
||||
params[name] = p;
|
||||
}
|
||||
|
||||
lookup.registry.register(lookups);
|
||||
|
||||
return [names, params];
|
||||
}
|
||||
|
||||
// types have an id, which means they are to be named by
|
||||
// the specified id - ensure we have a mapping lookup for these
|
||||
function extractTypeMap (types: PortableType[]): Record<number, PortableType> {
|
||||
const result: Record<number, PortableType> = {};
|
||||
|
||||
for (let i = 0; i < types.length; i++) {
|
||||
const p = types[i];
|
||||
|
||||
result[p.id.toNumber()] = p;
|
||||
}
|
||||
|
||||
return result;
|
||||
return [types, lookups, names, params];
|
||||
}
|
||||
|
||||
export class PortableRegistry extends Struct {
|
||||
@@ -274,43 +335,12 @@ export class PortableRegistry extends Struct {
|
||||
types: 'Vec<PortableType>'
|
||||
}, value);
|
||||
|
||||
const [names, params] = extractNames(this, this.types);
|
||||
const [types, lookups, names, params] = extractTypeInfo(this, this.types);
|
||||
|
||||
this.#names = names;
|
||||
this.#types = extractTypeMap(this.types);
|
||||
this.#types = types;
|
||||
|
||||
// Try and extract the AccountId/Address/Signature type from UncheckedExtrinsic
|
||||
if (params.SpRuntimeGenericUncheckedExtrinsic) {
|
||||
// Address, Call, Signature, Extra
|
||||
const [addrParam,, sigParam] = params.SpRuntimeGenericUncheckedExtrinsic;
|
||||
const siAddress = this.getSiType(addrParam.type.unwrap());
|
||||
const siSignature = this.getSiType(sigParam.type.unwrap());
|
||||
const nsSignature = createNamespace(siSignature);
|
||||
let nsAccountId = createNamespace(siAddress);
|
||||
const isMultiAddress = nsAccountId === 'sp_runtime::multiaddress::MultiAddress';
|
||||
|
||||
// With multiaddress, we check the first type param again
|
||||
if (isMultiAddress) {
|
||||
// AccountId, AccountIndex
|
||||
const [idParam] = siAddress.params;
|
||||
|
||||
nsAccountId = createNamespace(this.getSiType(idParam.type.unwrap()));
|
||||
}
|
||||
|
||||
this.registry.register({
|
||||
AccountId: ['sp_core::crypto::AccountId32'].includes(nsAccountId)
|
||||
? 'AccountId32'
|
||||
: ['account::AccountId20', 'primitive_types::H160'].includes(nsAccountId)
|
||||
? 'AccountId20'
|
||||
: 'AccountId32', // other, default to AccountId32
|
||||
Address: isMultiAddress
|
||||
? 'MultiAddress'
|
||||
: 'AccountId',
|
||||
ExtrinsicSignature: ['sp_runtime::MultiSignature'].includes(nsSignature)
|
||||
? 'MultiSignature'
|
||||
: names[sigParam.type.unwrap().toNumber()] || 'MultiSignature'
|
||||
});
|
||||
}
|
||||
registerTypes(this, lookups, names, params);
|
||||
|
||||
// console.timeEnd('PortableRegistry')
|
||||
}
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/types', version: '6.7.2' };
|
||||
export const packageInfo = { name: '@polkadot/types', version: '6.9.2' };
|
||||
|
||||
@@ -17,6 +17,9 @@ export class Null implements Codec {
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
// Added for compatibility reasons, e.g. see Option
|
||||
public readonly initialU8aLength = 0;
|
||||
|
||||
constructor (registry: Registry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ export function unwrapStorageType (registry: Registry, type: StorageEntryTypeLat
|
||||
const outputType = getSiName(registry.lookup, unwrapStorageSi(type));
|
||||
|
||||
return isOptional
|
||||
? `Option<${outputType}>` as keyof InterfaceTypes
|
||||
? `Option<${outputType}>` as unknown as keyof InterfaceTypes
|
||||
: outputType as keyof InterfaceTypes;
|
||||
}
|
||||
|
||||
|
||||
@@ -62,13 +62,6 @@ export type __WrapTwo = keyof __MapWrapTwo<Codec, Codec>;
|
||||
|
||||
export type __Wrap = __WrapOne | __WrapTwo;
|
||||
|
||||
export type __ToStruct<K extends Record<string, unknown>> =
|
||||
K['_enum'] extends true
|
||||
? Enum
|
||||
: K['_set'] extends true
|
||||
? CodecSet
|
||||
: Struct;
|
||||
|
||||
export type __ToTuple<O extends Codec[]> =
|
||||
O[0] extends Codec
|
||||
? O[1] extends Codec
|
||||
@@ -76,15 +69,6 @@ export type __ToTuple<O extends Codec[]> =
|
||||
: O[0]
|
||||
: Null;
|
||||
|
||||
export type __CodecFirst<K> =
|
||||
K extends keyof InterfaceTypes
|
||||
? InterfaceTypes[K]
|
||||
: K extends unknown[]
|
||||
? __ToTuple<__Codecs<K>>
|
||||
: K extends Record<string, unknown>
|
||||
? __ToStruct<K>
|
||||
: Codec;
|
||||
|
||||
export type __CodecsNext<K, C extends Codec[]> =
|
||||
K extends __WrapOne
|
||||
? C extends [Codec, ...infer X]
|
||||
@@ -94,7 +78,22 @@ export type __CodecsNext<K, C extends Codec[]> =
|
||||
? C extends [Codec, Codec, ...infer X]
|
||||
? [__MapWrapTwo<C[0], C[1]>[K], ...X]
|
||||
: Codec
|
||||
: [__CodecFirst<K>, ...C];
|
||||
: [
|
||||
// __CodecFirst<K>
|
||||
K extends keyof InterfaceTypes
|
||||
? InterfaceTypes[K]
|
||||
: K extends unknown[]
|
||||
? __ToTuple<__Codecs<K>>
|
||||
: K extends Record<string, unknown>
|
||||
// __ToStruct<K extends Record<string, unknown>>
|
||||
? K['_enum'] extends true
|
||||
? Enum
|
||||
: K['_set'] extends true
|
||||
? CodecSet
|
||||
: Struct
|
||||
: Codec,
|
||||
...C
|
||||
];
|
||||
|
||||
export type __Codecs<T extends unknown[]> =
|
||||
T extends [infer K, ...infer N]
|
||||
@@ -123,25 +122,18 @@ export type __TokenizeStruct<T extends [__Value[], string], V extends __Value[],
|
||||
export type __TokenizeTuple<T extends [__Value[], string], V extends __Value[], I extends string> =
|
||||
__Tokenize<T[1], __CombineInner<V, I, T[0]>>;
|
||||
|
||||
export type __TokenizeWrapped<K extends string, V extends __Value[], I extends string, R extends string> =
|
||||
K extends `${infer X}${R}`
|
||||
? X extends '['
|
||||
? __Tokenize<R, [...__Combine<V, I>, '[']>
|
||||
: __Tokenize<R, __Combine<V, `${I}${X}`>>
|
||||
: never;
|
||||
|
||||
export type __TokenizeKnown<K extends string, V extends __Value[], I extends string, R extends string> =
|
||||
K extends `${infer X}${',' | '>'}${R}`
|
||||
? __Tokenize<R, __Combine<V, `${I}${X}`>>
|
||||
: never;
|
||||
|
||||
// NOTE For recursion limits, it is more optimal to use __Sanitize with conjunction with __Tokenize
|
||||
// below, even while we do more matching (Number of characters iterated through is the most problematic)
|
||||
export type __Tokenize<K extends string, V extends __Value[] = [], I extends string = ''> =
|
||||
K extends '' | '>' | ')' | '}'
|
||||
? [__Combine<V, I>, '']
|
||||
: K extends `${__Wrap}${infer R}`
|
||||
? __TokenizeWrapped<K, V, I, R>
|
||||
// __TokenizeWrapped<K extends string, V extends __Value[], I extends string, R extends string>
|
||||
? K extends `${infer X}${R}`
|
||||
? X extends '['
|
||||
? __Tokenize<R, [...__Combine<V, I>, '[']>
|
||||
: __Tokenize<R, __Combine<V, `${I}${X}`>>
|
||||
: never
|
||||
: K extends `${',' | '>'}${infer R}`
|
||||
? __Tokenize<R, __Combine<V, I>>
|
||||
: K extends `${')' | '}'}${infer R}`
|
||||
@@ -151,7 +143,10 @@ export type __Tokenize<K extends string, V extends __Value[] = [], I extends str
|
||||
: K extends `{${infer R}`
|
||||
? __TokenizeStruct<__Tokenize<R>, V, I, R>
|
||||
: K extends `${keyof InterfaceTypes}${',' | '>'}${infer R}`
|
||||
? __TokenizeKnown<K, V, I, R>
|
||||
// __TokenizeKnown<K extends string, V extends __Value[], I extends string, R extends string>
|
||||
? K extends `${infer X}${',' | '>'}${R}`
|
||||
? __Tokenize<R, __Combine<V, `${I}${X}`>>
|
||||
: never
|
||||
: K extends `${infer C}${infer R}`
|
||||
? __Tokenize<R, V, `${I}${C}`>
|
||||
: [__Combine<V, I>, ''];
|
||||
|
||||
Reference in New Issue
Block a user