Compare commits

..
4 Commits
Author SHA1 Message Date
github-actions[bot] ac07123e54 [CI Skip] release/stable 10.9.1
skip-checks: true
2023-06-12 04:41:46 +00:00
Jaco a9865bb60a 10.9.1 (#5672)
* 10.9.1

* Bump static metadata
2023-06-12 07:31:48 +03:00
github-actions[bot] 62741a10dd [CI Skip] bump/beta 10.8.2-0-x
skip-checks: true
2023-06-11 07:08:56 +00:00
Jaco c277b3d865 Adjust object index typings (#5671)
* Adjust object index typings

* CHANGELOG

* Remove dot-notation overrides

* Align overrides

* Ordering

* Revert lint formatting changes

* Bump common
2023-06-11 09:58:20 +03:00
108 changed files with 784 additions and 673 deletions
+8
View File
@@ -1,5 +1,13 @@
# CHANGELOG
## 10.9.1 Jun 12, 2023
Changes:
- Adjust object index access for stricter tsconfig settings
- Update to latest Polkadot, Kusama & Substrate metadata
## 10.8.1 Jun 5, 2023
Contributed:
+1 -1
View File
@@ -1,4 +1,4 @@
3473 Jaco 10.8.1 (#5669)
3475 Jaco 10.9.1 (#5672)
83 Amaury Martiny StatementKind: Regular and Saft (#2303)
37 Keith Ingram Update contract types and rpc (#4541)
35 Stefanie Doll Updated child storage parameters (#1709)
+7
View File
@@ -4,6 +4,13 @@
import baseConfig from '@polkadot/dev/config/eslint';
export default [
{
ignores: [
// see the tsconfig.eslint.json for explanation
'packages/api-augment/src/kusama/*.ts',
'packages/api-augment/src/polkadot/*.ts'
]
},
...baseConfig,
{
rules: {
+4 -4
View File
@@ -14,10 +14,10 @@
},
"sideEffects": false,
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"versions": {
"git": "10.8.1",
"npm": "10.8.1"
"git": "10.9.1",
"npm": "10.9.1"
},
"workspaces": [
"packages/*"
@@ -40,7 +40,7 @@
"test:one": "polkadot-dev-run-test --env node"
},
"devDependencies": {
"@polkadot/dev": "^0.75.16",
"@polkadot/dev": "^0.75.19",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/node": "^20.2.5"
},
+7 -7
View File
@@ -18,15 +18,15 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/api-base": "10.8.1",
"@polkadot/rpc-augment": "10.8.1",
"@polkadot/types": "10.8.1",
"@polkadot/types-augment": "10.8.1",
"@polkadot/types-codec": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/api-base": "10.9.1",
"@polkadot/rpc-augment": "10.9.1",
"@polkadot/types": "10.9.1",
"@polkadot/types-augment": "10.9.1",
"@polkadot/types-codec": "10.9.1",
"@polkadot/util": "^12.3.1",
"tslib": "^2.5.3"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-augment', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/api-augment', path: 'auto', type: 'auto', version: '10.9.1' };
+4 -4
View File
@@ -18,12 +18,12 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/rpc-core": "10.8.1",
"@polkadot/types": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/rpc-core": "10.9.1",
"@polkadot/types": "10.9.1",
"@polkadot/util": "^12.3.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.3"
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-base', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/api-base', path: 'auto', type: 'auto', version: '10.9.1' };
+10 -9
View File
@@ -18,20 +18,21 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/api": "10.8.1",
"@polkadot/types": "10.8.1",
"@polkadot/types-codec": "10.8.1",
"@polkadot/types-create": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/util-crypto": "^12.2.2",
"@polkadot/api": "10.9.1",
"@polkadot/api-augment": "10.9.1",
"@polkadot/types": "10.9.1",
"@polkadot/types-codec": "10.9.1",
"@polkadot/types-create": "10.9.1",
"@polkadot/util": "^12.3.1",
"@polkadot/util-crypto": "^12.3.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.3"
},
"devDependencies": {
"@polkadot/api-augment": "10.8.1",
"@polkadot/keyring": "^12.2.2"
"@polkadot/api-augment": "10.9.1",
"@polkadot/keyring": "^12.3.1"
}
}
+3 -3
View File
@@ -101,7 +101,7 @@ describe('Abi', (): void => {
JSON.parse(fs.readFileSync(cmpFile, 'utf-8'))
);
} catch (error) {
if (process.env.GITHUB_REPOSITORY) {
if (process.env['GITHUB_REPOSITORY']) {
console.error(registryJson);
throw error;
@@ -114,8 +114,8 @@ describe('Abi', (): void => {
});
it('has the correct hash for the source', (): void => {
const abi = new Abi(abis.ink_v0_flipperBundle);
const bundle = abis.ink_v0_flipperBundle as unknown as JSONAbi;
const abi = new Abi(abis['ink_v0_flipperBundle']);
const bundle = abis['ink_v0_flipperBundle'] as unknown as JSONAbi;
// manual
expect(bundle.source.hash).toEqual(blake2AsHex(bundle.source.wasm));
+9 -3
View File
@@ -12,6 +12,12 @@ import { assertReturn, compactAddLength, compactStripLength, isBn, isNumber, isO
import { convertVersions, enumVersions } from './toLatest.js';
interface AbiJson {
version?: string;
[key: string]: unknown;
}
const l = logger('Abi');
const PRIMITIVE_ALWAYS = ['AccountId', 'AccountIndex', 'Address', 'Balance'];
@@ -26,12 +32,12 @@ function findMessage <T extends AbiMessage> (list: T[], messageOrId: T | string
return assertReturn(message, () => `Attempted to call an invalid contract interface, ${stringify(messageOrId)}`);
}
function getLatestMeta (registry: Registry, json: Record<string, unknown>): ContractMetadataLatest {
function getLatestMeta (registry: Registry, json: AbiJson): ContractMetadataLatest {
// this is for V1, V2, V3
const vx = enumVersions.find((v) => isObject(json[v]));
// this was added in V4
const jsonVersion = json.version as string;
const jsonVersion = json.version;
if (!vx && jsonVersion && !enumVersions.find((v) => v === `V${jsonVersion}`)) {
throw new Error(`Unable to handle version ${jsonVersion}`);
@@ -56,7 +62,7 @@ function getLatestMeta (registry: Registry, json: Record<string, unknown>): Cont
function parseJson (json: Record<string, unknown>, chainProperties?: ChainProperties): [Record<string, unknown>, Registry, ContractMetadataLatest, ContractProjectInfo] {
const registry = new TypeRegistry();
const info = registry.createType('ContractProjectInfo', json) as unknown as ContractProjectInfo;
const latest = getLatestMeta(registry, json);
const latest = getLatestMeta(registry, json as unknown as AbiJson);
const lookup = registry.createType('PortableRegistry', { types: latest.types }, true);
// attach the lookup to the registry - now the types are known
@@ -10,7 +10,7 @@ import { v0ToLatest, v1ToLatest, v2ToLatest, v3ToLatest, v4ToLatest } from './to
describe('v0ToLatest', (): void => {
const registry = new TypeRegistry();
const contract = registry.createType('ContractMetadata', { V0: abis.ink_v0_erc20 });
const contract = registry.createType('ContractMetadata', { V0: abis['ink_v0_erc20'] });
const latest = v0ToLatest(registry, contract.asV0);
it('has the correct constructors', (): void => {
@@ -52,7 +52,7 @@ describe('v0ToLatest', (): void => {
describe('v1ToLatest', (): void => {
const registry = new TypeRegistry();
const contract = registry.createType('ContractMetadata', { V1: abis.ink_v1_flipper.V1 });
const contract = registry.createType('ContractMetadata', { V1: abis['ink_v1_flipper']['V1'] });
const latest = v1ToLatest(registry, contract.asV1);
it('has the correct constructors', (): void => {
@@ -68,7 +68,7 @@ describe('v1ToLatest', (): void => {
});
it('has the correct messages with namespaced method name', (): void => {
const contract = registry.createType('ContractMetadata', { V1: abis.ink_v1_psp22.V1 });
const contract = registry.createType('ContractMetadata', { V1: abis['ink_v1_psp22']['V1'] });
const latest = v1ToLatest(registry, contract.asV1);
expect(
@@ -87,7 +87,7 @@ describe('v1ToLatest', (): void => {
describe('v2ToLatest', (): void => {
const registry = new TypeRegistry();
const contract = registry.createType('ContractMetadata', { V2: abis.ink_v2_flipper.V2 });
const contract = registry.createType('ContractMetadata', { V2: abis['ink_v2_flipper']['V2'] });
const latest = v2ToLatest(registry, contract.asV2);
it('has the correct constructor flag', (): void => {
@@ -99,7 +99,7 @@ describe('v2ToLatest', (): void => {
describe('v3ToLatest', (): void => {
const registry = new TypeRegistry();
const contract = registry.createType('ContractMetadata', { V3: abis.ink_v3_flipper.V3 });
const contract = registry.createType('ContractMetadata', { V3: abis['ink_v3_flipper']['V3'] });
const latest = v3ToLatest(registry, contract.asV3);
it('has the correct constructor flags', (): void => {
@@ -112,7 +112,7 @@ describe('v3ToLatest', (): void => {
});
it('has the correct messages', (): void => {
const contract = registry.createType('ContractMetadata', { V3: abis.ink_v3_traitErc20.V3 });
const contract = registry.createType('ContractMetadata', { V3: abis['ink_v3_traitErc20']['V3'] });
const latest = v3ToLatest(registry, contract.asV3);
expect(
@@ -125,7 +125,7 @@ describe('v3ToLatest', (): void => {
describe('v4ToLatest', (): void => {
const registry = new TypeRegistry();
const contract = registry.createType('ContractMetadata', { V4: abis.ink_v4_flipperContract });
const contract = registry.createType('ContractMetadata', { V4: abis['ink_v4_flipperContract'] });
const latest = v4ToLatest(registry, contract.asV4);
it('has the correct constructor flags', (): void => {
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2023 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import '@polkadot/api-augment';
+1 -1
View File
@@ -97,7 +97,7 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
: convertWeight(
this.api.consts.system.blockWeights
? (this.api.consts.system.blockWeights as unknown as { maxBlock: WeightV2 }).maxBlock
: this.api.consts.system.maximumBlockWeight as Weight
: this.api.consts.system['maximumBlockWeight'] as Weight
).v1Weight.muln(64).div(BN_HUNDRED)
);
};
@@ -5,7 +5,7 @@
import '@polkadot/api-augment';
import type { TestKeyringMap } from '@polkadot/keyring/testingPairs';
import type { TestKeyringMapSubstrate } from '@polkadot/keyring/testingPairs';
import { ApiPromise } from '@polkadot/api';
import { BlueprintPromise, ContractPromise } from '@polkadot/api-contract';
@@ -13,21 +13,21 @@ import { createTestPairs } from '@polkadot/keyring/testingPairs';
import abiIncrementer from './test/contracts/ink/v0/incrementer.json' assert { type: 'json' };
async function checkBlueprint (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
async function checkBlueprint (api: ApiPromise, pairs: TestKeyringMapSubstrate): Promise<void> {
const blueprint = new BlueprintPromise(api, abiIncrementer as Record<string, unknown>, '0x1234');
await blueprint.tx.new({ gasLimit: 456, salt: '0x1234', value: 123 }, 42).signAndSend(pairs.bob);
await blueprint.tx.new({ gasLimit: 456, value: 123 }, 42).signAndSend(pairs.bob);
await blueprint.tx['new']({ gasLimit: 456, salt: '0x1234', value: 123 }, 42).signAndSend(pairs.bob);
await blueprint.tx['new']({ gasLimit: 456, value: 123 }, 42).signAndSend(pairs.bob);
}
async function checkContract (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
async function checkContract (api: ApiPromise, pairs: TestKeyringMapSubstrate): Promise<void> {
const contract = new ContractPromise(api, abiIncrementer as Record<string, unknown>, '0x1234');
// queries
await contract.query.get(pairs.alice.address, {});
await contract.query['get'](pairs.alice.address, {});
// execute
await contract.tx.inc({ gasLimit: 1234 }, 123).signAndSend(pairs.eve);
await contract.tx['inc']({ gasLimit: 1234 }, 123).signAndSend(pairs.eve);
}
async function main (): Promise<void> {
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-contract', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/api-contract', path: 'auto', type: 'auto', version: '10.9.1' };
@@ -7,10 +7,14 @@ import user from './user/index.js';
const all: Record<string, Record<string, unknown>> = {};
Object.entries({ ink, solang, user }).forEach(([type, abis]) =>
Object.entries(abis).forEach(([name, abi]): void => {
all[`${type}_${name}`] = abi;
})
);
Object
.entries({ ink, solang, user })
.forEach(([type, abis]) =>
Object
.entries(abis)
.forEach(([name, abi]): void => {
all[`${type}_${name}`] = abi;
})
);
export default all;
@@ -14,6 +14,7 @@
],
"references": [
{ "path": "../api/tsconfig.build.json" },
{ "path": "../api-augment/tsconfig.build.json" },
{ "path": "../types/tsconfig.build.json" },
{ "path": "../types-codec/tsconfig.build.json" },
{ "path": "../types-create/tsconfig.build.json" }
+14 -14
View File
@@ -18,25 +18,25 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/api": "10.8.1",
"@polkadot/api-augment": "10.8.1",
"@polkadot/api-base": "10.8.1",
"@polkadot/rpc-core": "10.8.1",
"@polkadot/types": "10.8.1",
"@polkadot/types-codec": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/util-crypto": "^12.2.2",
"@polkadot/api": "10.9.1",
"@polkadot/api-augment": "10.9.1",
"@polkadot/api-base": "10.9.1",
"@polkadot/rpc-core": "10.9.1",
"@polkadot/types": "10.9.1",
"@polkadot/types-codec": "10.9.1",
"@polkadot/util": "^12.3.1",
"@polkadot/util-crypto": "^12.3.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.3"
},
"devDependencies": {
"@polkadot/api": "10.8.1",
"@polkadot/api-augment": "10.8.1",
"@polkadot/rpc-augment": "10.8.1",
"@polkadot/rpc-provider": "10.8.1",
"@polkadot/types-support": "10.8.1"
"@polkadot/api": "10.9.1",
"@polkadot/api-augment": "10.9.1",
"@polkadot/rpc-augment": "10.9.1",
"@polkadot/rpc-provider": "10.9.1",
"@polkadot/types-support": "10.9.1"
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ export function _flags (instanceId: string, api: DeriveApi): () => Observable<Fl
return memo(instanceId, (): Observable<FlagsIntermediate> => {
const results: unknown[] = [undefined, [], [], [], undefined];
const calls = [
(api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections)?.members,
(api.query.elections || api.query['phragmenElection'] || api.query['electionsPhragmen'])?.members,
api.query.council?.members,
api.query.technicalCommittee?.members,
api.query.society?.members,
+3 -3
View File
@@ -15,13 +15,13 @@ import { memo } from '../util/index.js';
function retrieveNick (api: DeriveApi, accountId?: AccountId): Observable<string | undefined> {
return ((
accountId && api.query.nicks?.nameOf
? api.query.nicks.nameOf(accountId)
accountId && api.query['nicks']?.['nameOf']
? api.query['nicks']['nameOf'](accountId)
: of(undefined)
) as Observable<Option<ITuple<[Bytes, Balance]>> | undefined>).pipe(
map((nameOf): string | undefined =>
nameOf?.isSome
? u8aToString(nameOf.unwrap()[0]).substring(0, (api.consts.nicks.maxLength as u32).toNumber())
? u8aToString(nameOf.unwrap()[0]).substring(0, (api.consts['nicks']['maxLength'] as u32).toNumber())
: undefined
)
);
+5 -7
View File
@@ -1,16 +1,14 @@
// Copyright 2017-2023 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { QueryableStorage } from '@polkadot/api-base/types';
import type { DeriveApi } from '../types.js';
export function getQueryInterface (api: DeriveApi): QueryableStorage<'rxjs'>['voterBagsList'] {
export function getQueryInterface (api: DeriveApi): DeriveApi['query']['voterList'] {
return (
// latest substrate (latest always first)
api.query.voterBagsList ||
// latest substrate & polkadot
api.query.voterList ||
// previous substrate
api.query.bagsList ||
// latest polkadot
api.query.voterList
api.query['voterBagsList'] ||
api.query['bagsList']
);
}
+8 -8
View File
@@ -50,9 +50,9 @@ function calcBalances (api: DeriveApi, [accountId, [accountNonce, [primary, ...a
// old
function queryBalancesFree (api: DeriveApi, accountId: AccountId): Observable<Result> {
return combineLatest([
api.query.balances.freeBalance<Balance>(accountId),
api.query.balances.reservedBalance<Balance>(accountId),
api.query.system.accountNonce<Index>(accountId)
api.query.balances['freeBalance']<Balance>(accountId),
api.query.balances['reservedBalance']<Balance>(accountId),
api.query.system['accountNonce']<Index>(accountId)
]).pipe(
map(([freeBalance, reservedBalance, accountNonce]): Result => [
accountNonce,
@@ -71,8 +71,8 @@ function queryNonceOnly (api: DeriveApi, accountId: AccountId): Observable<Resul
? api.query.system.account(accountId).pipe(
map(({ nonce }) => fill(nonce))
)
: isFunction(api.query.system.accountNonce)
? api.query.system.accountNonce<Index>(accountId).pipe(
: isFunction(api.query.system['accountNonce'])
? api.query.system['accountNonce']<Index>(accountId).pipe(
map((nonce) => fill(nonce))
)
: of(fill(api.registry.createType('Index')));
@@ -80,7 +80,7 @@ function queryNonceOnly (api: DeriveApi, accountId: AccountId): Observable<Resul
function queryBalancesAccount (api: DeriveApi, accountId: AccountId, modules: string[] = ['balances']): Observable<Result> {
const balances = modules
.map((m): QueryableStorageEntry<'rxjs'> => (api.derive as DeriveCustomAccount)[m]?.customAccount || api.query[m]?.account)
.map((m): QueryableStorageEntry<'rxjs'> => (api.derive as DeriveCustomAccount)[m]?.customAccount || api.query[m as 'balances']?.account)
.filter((q) => isFunction(q));
const extract = (nonce: Index, data: AccountData[]): Result => [
@@ -98,7 +98,7 @@ function queryBalancesAccount (api: DeriveApi, accountId: AccountId, modules: st
map(([{ nonce }, ...balances]) => extract(nonce, balances as unknown as AccountData[]))
)
: combineLatest([
api.query.system.accountNonce<Index>(accountId),
api.query.system['accountNonce']<Index>(accountId),
...balances.map((c) => c(accountId))
]).pipe(
map(([nonce, ...balances]) => extract(nonce, balances as unknown as AccountData[]))
@@ -164,7 +164,7 @@ export function account (instanceId: string, api: DeriveApi): (address: AccountI
? querySystemAccount(api, accountId)
: isFunction(api.query.balances?.account)
? queryBalancesAccount(api, accountId)
: isFunction(api.query.balances?.freeBalance)
: isFunction(api.query.balances?.['freeBalance'])
? queryBalancesFree(api, accountId)
: queryNonceOnly(api, accountId)
])
+1 -1
View File
@@ -116,7 +116,7 @@ function calcBalances (api: DeriveApi, result: Result): DeriveBalancesAll {
function queryOld (api: DeriveApi, accountId: AccountId | string): Observable<ResultBalance> {
return combineLatest([
api.query.balances.locks(accountId),
api.query.balances.vesting<Option<VestingSchedule>>(accountId)
api.query.balances['vesting']<Option<VestingSchedule>>(accountId)
]).pipe(
map(([locks, optVesting]): ResultBalance => {
let vestingNew = null;
+4 -4
View File
@@ -42,11 +42,11 @@ function getAuthorDetailsWithAt (header: Header, queryAt: QueryableStorage<'rxjs
if (loggedAuthor) {
// use the author mapping pallet, if available (ie: moonbeam, moonriver), to map session (nimbus) key to author (collator/validator) key
if (queryAt.authorMapping?.mappingWithDeposit) {
if (queryAt['authorMapping']?.['mappingWithDeposit']) {
return combineLatest([
of(header),
validators,
queryAt.authorMapping.mappingWithDeposit<OptionMapping>(loggedAuthor).pipe(
queryAt['authorMapping']['mappingWithDeposit']<OptionMapping>(loggedAuthor).pipe(
map((o) =>
o.unwrapOr({ account: null }).account
)
@@ -55,13 +55,13 @@ function getAuthorDetailsWithAt (header: Header, queryAt: QueryableStorage<'rxjs
}
// fall back to session and parachain staking pallets, if available (ie: manta, calamari), to map session (nimbus) key to author (collator) key
if (queryAt.parachainStaking?.selectedCandidates && queryAt.session?.nextKeys) {
if (queryAt['parachainStaking']?.['selectedCandidates'] && queryAt.session?.nextKeys) {
const loggedHex = loggedAuthor.toHex();
return combineLatest([
of(header),
validators,
queryAt.parachainStaking.selectedCandidates<Vec<AccountId>>().pipe(
queryAt['parachainStaking']['selectedCandidates']<Vec<AccountId>>().pipe(
mergeMap((selectedCandidates) =>
combineLatest([
of(selectedCandidates),
+10 -10
View File
@@ -15,18 +15,18 @@ type ResultV2 = [BN, BN, BN, BN, BN, BN, BN, BN, BN, BN];
function queryConstants (api: DeriveApi): Observable<ResultV2> {
return of([
// deprecated
api.consts.contracts.callBaseFee || api.registry.createType('Balance'),
api.consts.contracts.contractFee || api.registry.createType('Balance'),
api.consts.contracts.creationFee || api.registry.createType('Balance'),
api.consts.contracts.transactionBaseFee || api.registry.createType('Balance'),
api.consts.contracts.transactionByteFee || api.registry.createType('Balance'),
api.consts.contracts.transferFee || api.registry.createType('Balance'),
api.consts.contracts['callBaseFee'] || api.registry.createType('Balance'),
api.consts.contracts['contractFee'] || api.registry.createType('Balance'),
api.consts.contracts['creationFee'] || api.registry.createType('Balance'),
api.consts.contracts['transactionBaseFee'] || api.registry.createType('Balance'),
api.consts.contracts['transactionByteFee'] || api.registry.createType('Balance'),
api.consts.contracts['transferFee'] || api.registry.createType('Balance'),
// current
api.consts.contracts.rentByteFee,
api.consts.contracts.rentDepositOffset,
api.consts.contracts.surchargeReward,
api.consts.contracts.tombstoneDeposit
api.consts.contracts['rentByteFee'] || api.registry.createType('Balance'),
api.consts.contracts['rentDepositOffset'] || api.registry.createType('Balance'),
api.consts.contracts['surchargeReward'] || api.registry.createType('Balance'),
api.consts.contracts['tombstoneDeposit'] || api.registry.createType('Balance')
]) as unknown as Observable<ResultV2>;
}
+7 -7
View File
@@ -21,22 +21,22 @@ function isVoter (value: VoteEntry): value is PalletElectionsPhragmenVoter {
}
function retrieveStakeOf (elections: QueryableModuleStorage<'rxjs'>): Observable<[AccountId, Balance][]> {
return elections.stakeOf.entries<Balance, [AccountId]>().pipe(
return elections['stakeOf'].entries<Balance, [AccountId]>().pipe(
map((entries) =>
entries.map(([{ args: [accountId] }, stake]) => [accountId, stake])
)
);
}
function retrieveVoteOf (elections: QueryableModuleStorage<'rxjs'>): Observable<[AccountId, AccountId[]][]> {
return elections.votesOf.entries<Vec<AccountId>, [AccountId]>().pipe(
function retrieveVoteOf (elections: DeriveApi['query']['elections']): Observable<[AccountId, AccountId[]][]> {
return elections['votesOf'].entries<Vec<AccountId>, [AccountId]>().pipe(
map((entries) =>
entries.map(([{ args: [accountId] }, votes]) => [accountId, votes])
)
);
}
function retrievePrev (api: DeriveApi, elections: QueryableModuleStorage<'rxjs'>): Observable<DeriveCouncilVotes> {
function retrievePrev (api: DeriveApi, elections: DeriveApi['query']['elections']): Observable<DeriveCouncilVotes> {
return combineLatest([
retrieveStakeOf(elections),
retrieveVoteOf(elections)
@@ -63,7 +63,7 @@ function retrievePrev (api: DeriveApi, elections: QueryableModuleStorage<'rxjs'>
);
}
function retrieveCurrent (elections: QueryableModuleStorage<'rxjs'>): Observable<DeriveCouncilVotes> {
function retrieveCurrent (elections: DeriveApi['query']['elections']): Observable<DeriveCouncilVotes> {
return elections.voting.entries<VoteEntry, [AccountId]>().pipe(
map((entries): DeriveCouncilVotes =>
entries.map(([{ args: [accountId] }, value]): [AccountId, DeriveCouncilVote] => [
@@ -77,11 +77,11 @@ function retrieveCurrent (elections: QueryableModuleStorage<'rxjs'>): Observable
}
export function votes (instanceId: string, api: DeriveApi): () => Observable<DeriveCouncilVotes> {
const elections = api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections;
const elections = api.query.elections || api.query['phragmenElection'] || api.query['electionsPhragmen'];
return memo(instanceId, (): Observable<DeriveCouncilVotes> =>
elections
? elections.stakeOf
? elections['stakeOf']
? retrievePrev(api, elections)
: retrieveCurrent(elections)
: of([])
@@ -35,7 +35,7 @@ function createChildKey (info: AllInfo): string {
export function childKey (instanceId: string, api: DeriveApi): (paraId: string | number | BN) => Observable<string | null> {
return memo(instanceId, (paraId: string | number | BN): Observable<string | null> =>
api.query.crowdloan.funds<Option<PolkadotRuntimeCommonCrowdloanFundInfo>>(paraId).pipe(
api.query['crowdloan']['funds']<Option<PolkadotRuntimeCommonCrowdloanFundInfo>>(paraId).pipe(
map((optInfo) =>
optInfo.isSome
? createChildKey(optInfo.unwrap())
@@ -53,7 +53,7 @@ function isBounded (call: FrameSupportPreimagesBounded | FrameSupportScheduleMay
}
function queryQueue (api: DeriveApi): Observable<DeriveDispatch[]> {
return api.query.democracy.dispatchQueue<Vec<ITuple<[BlockNumber, Hash, ReferendumIndex]>>>().pipe(
return api.query.democracy['dispatchQueue']<Vec<ITuple<[BlockNumber, Hash, ReferendumIndex]>>>().pipe(
switchMap((dispatches) =>
combineLatest([
of(dispatches),
@@ -142,7 +142,7 @@ export function dispatchQueue (instanceId: string, api: DeriveApi): () => Observ
return memo(instanceId, (): Observable<DeriveDispatch[]> =>
isFunction(api.query.scheduler?.agenda)
? queryScheduler(api)
: api.query.democracy.dispatchQueue
: api.query.democracy['dispatchQueue']
? queryQueue(api)
: of([])
);
@@ -20,7 +20,7 @@ type PreimageInfo = [Bytes, AccountId, Balance, BlockNumber];
type OldPreimage = ITuple<PreimageInfo>;
function isDemocracyPreimage (api: DeriveApi, imageOpt: Option<OldPreimage> | Option<PreimageStatus>): imageOpt is Option<PreimageStatus> {
return !!imageOpt && !api.query.democracy.dispatchQueue;
return !!imageOpt && !api.query.democracy['dispatchQueue'];
}
function constructProposal (api: DeriveApi, [bytes, proposer, balance, at]: PreimageInfo): DeriveProposalImage {
@@ -79,7 +79,7 @@ function parseImage (api: DeriveApi, [proposalHash, status, bytes]: [HexString,
function getDemocracyImages (api: DeriveApi, bounded: (Hash | Uint8Array | string | FrameSupportPreimagesBounded)[]): Observable<(DeriveProposalImage | undefined)[]> {
const hashes = bounded.map((b) => getImageHashBounded(b));
return api.query.democracy.preimages.multi<Option<PreimageStatus>>(hashes).pipe(
return api.query.democracy['preimages'].multi<Option<PreimageStatus>>(hashes).pipe(
map((images): (DeriveProposalImage | undefined)[] =>
images.map((imageOpt) => parseDemocracy(api, imageOpt))
)
@@ -127,7 +127,7 @@ function getImages (api: DeriveApi, bounded: (FrameSupportPreimagesBounded | Uin
export function preimages (instanceId: string, api: DeriveApi): (hashes: (Hash | Uint8Array | string | FrameSupportPreimagesBounded)[]) => Observable<(DeriveProposalImage | undefined)[]> {
return memo(instanceId, (hashes: (Hash | Uint8Array | string | FrameSupportPreimagesBounded)[]): Observable<(DeriveProposalImage | undefined)[]> =>
hashes.length
? isFunction(api.query.democracy.preimages)
? isFunction(api.query.democracy['preimages'])
? getDemocracyImages(api, hashes)
: isFunction(api.query.preimage.preimageFor)
? getImages(api, hashes)
@@ -23,7 +23,6 @@ type Result = [Proposals, (DeriveProposalImage | undefined)[], Depositors[]];
function isNewDepositors (depositors: ITuple<[Vec<AccountId>, Balance]> | ITuple<[Balance, Vec<AccountId>]>): depositors is ITuple<[Vec<AccountId>, Balance]> {
// Detect balance...
// eslint-disable-next-line @typescript-eslint/unbound-method
return isFunction((depositors[1] as Balance).mul);
}
@@ -20,12 +20,12 @@ type VotingDirect = PalletDemocracyVoteVoting['asDirect'];
type VotingDirectVote = VotingDirect['votes'][0];
function votesPrev (api: DeriveApi, referendumId: BN): Observable<DeriveReferendumVote[]> {
return api.query.democracy.votersFor<Vec<AccountId>>(referendumId).pipe(
return api.query.democracy['votersFor']<Vec<AccountId>>(referendumId).pipe(
switchMap((votersFor): Observable<[Vec<AccountId>, Vote[], DeriveBalancesAccount[]]> =>
combineLatest([
of(votersFor),
votersFor.length
? api.query.democracy.voteOf.multi<Vote>(
? api.query.democracy['voteOf'].multi<Vote>(
votersFor.map((accountId): [BN | number, AccountId] =>
[referendumId, accountId]
)
+12 -10
View File
@@ -47,20 +47,22 @@ function sortAccounts ([, balanceA]: [AccountId32, Balance], [, balanceB]: [Acco
function getConstants (api: DeriveApi, elections: string | null): Partial<DeriveElectionsInfo> {
return elections
? {
candidacyBond: api.consts[elections].candidacyBond as Balance,
desiredRunnersUp: api.consts[elections].desiredRunnersUp as u32,
desiredSeats: api.consts[elections].desiredMembers as u32,
termDuration: api.consts[elections].termDuration as BlockNumber,
votingBond: api.consts[elections].votingBond as Balance
candidacyBond: api.consts[elections as 'elections'].candidacyBond as Balance,
desiredRunnersUp: api.consts[elections as 'elections'].desiredRunnersUp as u32,
desiredSeats: api.consts[elections as 'elections'].desiredMembers as u32,
termDuration: api.consts[elections as 'elections'].termDuration as BlockNumber,
votingBond: api.consts[elections as 'elections']['votingBond'] as Balance,
votingBondBase: api.consts[elections as 'elections'].votingBondBase as Balance,
votingBondFactor: api.consts[elections as 'elections'].votingBondFactor as Balance
}
: {};
}
function getModules (api: DeriveApi): [string, string | null] {
const [council] = api.registry.getModuleInstances(api.runtimeVersion.specName, 'council') || ['council'];
const elections = api.query.phragmenElection
const elections = api.query['phragmenElection']
? 'phragmenElection'
: api.query.electionsPhragmen
: api.query['electionsPhragmen']
? 'electionsPhragmen'
: api.query.elections
? 'elections'
@@ -72,9 +74,9 @@ function getModules (api: DeriveApi): [string, string | null] {
function queryAll (api: DeriveApi, council: string, elections: string): Observable<[AccountId32[], Candidate[], Member[], Member[]]> {
return api.queryMulti<[Vec<AccountId32>, Vec<Candidate>, Vec<Member>, Vec<Member>]>([
api.query[council as 'council'].members,
api.query[elections as 'phragmenElection'].candidates,
api.query[elections as 'phragmenElection'].members,
api.query[elections as 'phragmenElection'].runnersUp
api.query[elections as 'elections'].candidates,
api.query[elections as 'elections'].members,
api.query[elections as 'elections'].runnersUp
]);
}
@@ -17,4 +17,6 @@ export interface DeriveElectionsInfo {
voteCount?: VoteIndex;
voterCount?: SetIndex;
votingBond?: Balance;
votingBondBase?: Balance;
votingBondFactor?: Balance;
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-derive', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/api-derive', path: 'auto', type: 'auto', version: '10.9.1' };
+9 -9
View File
@@ -75,16 +75,16 @@ function parse (id: ParaId, [active, retryQueue, selectedThreads, didUpdate, inf
export function info (instanceId: string, api: DeriveApi): (id: ParaId | number) => Observable<DeriveParachainFull | null> {
return memo(instanceId, (id: ParaId | number): Observable<DeriveParachainFull | null> =>
api.query.registrar && api.query.parachains
api.query['registrar'] && api.query['parachains']
? api.queryMulti<Result>([
api.query.registrar.active,
api.query.registrar.retryQueue,
api.query.registrar.selectedThreads,
api.query.parachains.didUpdate,
[api.query.registrar.paras, id],
[api.query.registrar.pendingSwap, id],
[api.query.parachains.heads, id],
[api.query.parachains.relayDispatchQueue, id]
api.query['registrar']['active'],
api.query['registrar']['retryQueue'],
api.query['registrar']['selectedThreads'],
api.query['parachains']['didUpdate'],
[api.query['registrar']['paras'], id],
[api.query['registrar']['pendingSwap'], id],
[api.query['parachains']['heads'], id],
[api.query['parachains']['relayDispatchQueue'], id]
])
.pipe(
map((result: Result): DeriveParachainFull | null =>
@@ -16,12 +16,12 @@ import { didUpdateToBool } from './util.js';
type Result = [
ParaId[],
DidUpdate,
RelayDispatchQueueSize[],
ParaInfoResult[],
PendingSwap[],
RelayDispatchQueueSize[]
PendingSwap[]
];
function parse ([ids, didUpdate, infos, pendingSwaps, relayDispatchQueueSizes]: Result): DeriveParachain[] {
function parse ([ids, didUpdate, relayDispatchQueueSizes, infos, pendingSwaps]: Result): DeriveParachain[] {
return ids.map((id, index): DeriveParachain => ({
didUpdate: didUpdateToBool(didUpdate, id),
id,
@@ -33,15 +33,15 @@ function parse ([ids, didUpdate, infos, pendingSwaps, relayDispatchQueueSizes]:
export function overview (instanceId: string, api: DeriveApi): () => Observable<DeriveParachain[]> {
return memo(instanceId, (): Observable<DeriveParachain[]> =>
api.query.registrar?.parachains && api.query.parachains
? api.query.registrar.parachains<ParaId[]>().pipe(
api.query['registrar']?.['parachains'] && api.query['parachains']
? api.query['registrar']['parachains']<ParaId[]>().pipe(
switchMap((paraIds) =>
combineLatest([
of(paraIds),
api.query.parachains.didUpdate<DidUpdate>(),
api.query.registrar.paras.multi<ParaInfoResult>(paraIds),
api.query.registrar.pendingSwap.multi<PendingSwap>(paraIds),
api.query.parachains.relayDispatchQueueSize.multi<RelayDispatchQueueSize>(paraIds)
api.query['parachains']['didUpdate']<DidUpdate>(),
api.query['parachains']['relayDispatchQueueSize'].multi<RelayDispatchQueueSize>(paraIds),
api.query['registrar']['paras'].multi<ParaInfoResult>(paraIds),
api.query['registrar']['pendingSwap'].multi<PendingSwap>(paraIds)
])
),
map(parse)
@@ -19,7 +19,7 @@ export function erasHistoric (instanceId: string, api: DeriveApi): (withActive?:
api.query.staking.activeEra(),
api.consts.staking.historyDepth
? of(api.consts.staking.historyDepth)
: api.query.staking.historyDepth<u32>()
: api.query.staking['historyDepth']<u32>()
]).pipe(
map(([activeEraOpt, historyDepth]): EraIndex[] => {
const result: EraIndex[] = [];
+2 -2
View File
@@ -38,8 +38,8 @@ export function keysMulti (instanceId: string, api: DeriveApi): (stashIds: (Uint
switchMap((queuedKeys) =>
combineLatest([
of(queuedKeys),
api.consts.session?.dedupKeyPrefix
? api.query.session.nextKeys.multi(stashIds.map((s) => [api.consts.session.dedupKeyPrefix, s]))
api.consts['session']?.['dedupKeyPrefix']
? api.query.session.nextKeys.multi(stashIds.map((s) => [api.consts['session']['dedupKeyPrefix'], s]))
: combineLatest(stashIds.map((s) => api.query.session.nextKeys(s)))
])
),
@@ -18,7 +18,7 @@ export function nextElected (instanceId: string, api: DeriveApi): () => Observab
switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)),
map((keys) => keys.map(({ args: [, accountId] }) => accountId))
)
: api.query.staking.currentElected<AccountId[]>()
: api.query.staking['currentElected']<AccountId[]>()
);
}
@@ -3,7 +3,7 @@
import type { ApiPromise } from '@polkadot/api';
import type { Bounty, BountyIndex } from '@polkadot/types/interfaces';
import type { Codec, Constructor, InterfaceTypes, Registry } from '@polkadot/types/types';
import type { Codec, CodecClass, InterfaceTypes, Registry } from '@polkadot/types/types';
import { Option, StorageKey } from '@polkadot/types';
@@ -29,7 +29,7 @@ export class BountyFactory {
this.#registry.createType('Bounty');
public optionOf = <T extends Codec>(value: T): Option<T> => {
const typeName = this.#registry.getClassName(value.constructor as Constructor<T>);
const typeName = this.#registry.getClassName(value.constructor as CodecClass<T>);
return new Option<T>(this.#registry, typeName as keyof InterfaceTypes, value);
};
+17 -17
View File
@@ -18,29 +18,29 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/api-augment": "10.8.1",
"@polkadot/api-base": "10.8.1",
"@polkadot/api-derive": "10.8.1",
"@polkadot/keyring": "^12.2.2",
"@polkadot/rpc-augment": "10.8.1",
"@polkadot/rpc-core": "10.8.1",
"@polkadot/rpc-provider": "10.8.1",
"@polkadot/types": "10.8.1",
"@polkadot/types-augment": "10.8.1",
"@polkadot/types-codec": "10.8.1",
"@polkadot/types-create": "10.8.1",
"@polkadot/types-known": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/util-crypto": "^12.2.2",
"@polkadot/api-augment": "10.9.1",
"@polkadot/api-base": "10.9.1",
"@polkadot/api-derive": "10.9.1",
"@polkadot/keyring": "^12.3.1",
"@polkadot/rpc-augment": "10.9.1",
"@polkadot/rpc-core": "10.9.1",
"@polkadot/rpc-provider": "10.9.1",
"@polkadot/types": "10.9.1",
"@polkadot/types-augment": "10.9.1",
"@polkadot/types-codec": "10.9.1",
"@polkadot/types-create": "10.9.1",
"@polkadot/types-known": "10.9.1",
"@polkadot/util": "^12.3.1",
"@polkadot/util-crypto": "^12.3.1",
"eventemitter3": "^5.0.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.3"
},
"devDependencies": {
"@polkadot/api-augment": "10.8.1",
"@polkadot/types-support": "10.8.1"
"@polkadot/api-augment": "10.9.1",
"@polkadot/types-support": "10.9.1"
}
}
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2023 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import '@polkadot/api-augment';
+4 -1
View File
@@ -404,7 +404,10 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const decorateFn = (section: string, method: string): unknown => {
const source = rpc[section as 'chain'][method as 'getHeader'];
const fn = decorateMethod(source, { methodName: method }) as Record<string, unknown>;
const fn = decorateMethod(source, { methodName: method }) as {
meta: unknown;
raw: unknown;
};
fn.meta = source.meta;
fn.raw = decorateMethod(source.raw, { methodName: method }) as unknown;
+16 -16
View File
@@ -6,7 +6,7 @@
import '@polkadot/api-augment';
import type { HeaderExtended } from '@polkadot/api-derive/types';
import type { TestKeyringMap } from '@polkadot/keyring/testingPairs';
import type { TestKeyringMapSubstrate } from '@polkadot/keyring/testingPairs';
import type { StorageKey } from '@polkadot/types';
import type { AccountId, Balance, DispatchErrorModule, Event, Header, Index } from '@polkadot/types/interfaces';
import type { FrameSystemAccountInfo } from '@polkadot/types/lookup';
@@ -35,7 +35,7 @@ async function calls (api: ApiPromise): Promise<void> {
function consts (api: ApiPromise): void {
// constants has actual value & metadata
console.log(
api.consts.foo.bar,
api.consts['notIn']['augmentation'],
api.consts.balances.existentialDeposit.toNumber(),
api.consts.balances.existentialDeposit.meta.docs.map((s) => s.toString()).join(''),
api.consts.system.blockWeights.maxBlock.refTime.toNumber()
@@ -59,10 +59,10 @@ function errors (api: ApiPromise): void {
console.log(api.errors.vesting.AmountLow.is(someError));
// non-existing error, existing module
console.log(api.errors.vesting.Something.is(someError));
console.log(api.errors.vesting['NonAugmented'].is(someError));
// something random
console.log(api.errors.something.Random.is(someError));
console.log(api.errors['thisIsNot']['Augmented'].is(someError));
}
function events (api: ApiPromise): void {
@@ -97,20 +97,20 @@ function events (api: ApiPromise): void {
}
// something random, just codec[]
if (api.events.something.Random.is(event)) {
if (api.events['not']['Augmented'].is(event)) {
const [a, b] = event.data;
console.log(a.toHuman(), b.toHuman());
}
}
async function query (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
async function query (api: ApiPromise, pairs: TestKeyringMapSubstrate): Promise<void> {
const intentions = await api.query.staking.bonded();
console.log('intentions:', intentions);
// api.query.*.* is well-typed
const bar = await api.query.foo.bar(); // bar is Codec (unknown module)
const bar = await api.query['notIn']['augmentation'](); // bar is Codec (unknown module)
const bal = await api.query.balances.totalIssuance(); // bal is Balance
const bal2 = await api.query.balances.totalIssuance('WRONG_ARG'); // bal2 is Codec (wrong args)
const override = await api.query.balances.totalIssuance<Header>(); // override is still available
@@ -119,7 +119,7 @@ async function query (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
const oldBal = await api.query.balances.totalIssuance.at('abcd');
// For older queries we can cast with `<Balance>` (newer chain have multi typed)
const multia = await api.query.balances.freeBalance.multi<Balance>([pairs.alice.address, pairs.bob.address]);
const multia = await api.query.balances['freeBalance'].multi<Balance>([pairs.alice.address, pairs.bob.address]);
const multib = await api.query.system.account.multi([pairs.alice.address, pairs.bob.address]);
await api.query.system.account(pairs.alice.address);
@@ -157,7 +157,7 @@ async function queryExtra (api: ApiPromise): Promise<void> {
await api.query.assets.approvals.keys(123, 'blah');
await api.query.assets.account.keys(123);
await api.query.assets.account.entries(123);
await api.query.assets.blah.keys();
await api.query.assets['notAugmented'].keys();
// is
const key = {} as StorageKey;
@@ -170,7 +170,7 @@ async function queryExtra (api: ApiPromise): Promise<void> {
}
}
async function queryMulti (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
async function queryMulti (api: ApiPromise, pairs: TestKeyringMapSubstrate): Promise<void> {
// check multi for unsub
const multiUnsub = await api.queryMulti([
[api.query.staking.validators],
@@ -185,7 +185,7 @@ async function queryMulti (api: ApiPromise, pairs: TestKeyringMap): Promise<void
const multiRes = await api.queryMulti([
[api.query.system.account, pairs.eve.address],
// older chains only
[api.query.system.accountNonce, pairs.eve.address]
[api.query.system['accountNonce'], pairs.eve.address]
]);
console.log(multiRes);
@@ -241,7 +241,7 @@ function types (api: ApiPromise): void {
console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe, u32.toNumber(), f32.toNumber(), api.createType('AccountData'), raw.subarray(0, 10));
}
async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
async function tx (api: ApiPromise, pairs: TestKeyringMapSubstrate): Promise<void> {
// transfer, also allows for bigint inputs here
const transfer = api.tx.balances.transfer(pairs.bob.address, BigInt(123456789));
@@ -251,7 +251,7 @@ async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
console.log('hash:', (await transfer.signAndSend(pairs.alice)).toHex());
// passing options, but waiting for hash
const nonce = await api.query.system.accountNonce<Index>(pairs.alice.address);
const nonce = await api.query.system['accountNonce']<Index>(pairs.alice.address);
(await api.tx.balances
.transfer(pairs.bob.address, 12345)
@@ -264,7 +264,7 @@ async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
.signAndSend(pairs.alice, ({ status }: SubmittableResult) => console.log(status.type));
// with options and the callback
const nonce2 = await api.query.system.accountNonce(pairs.alice.address);
const nonce2 = await api.query.system['accountNonce'](pairs.alice.address);
const unsub2 = await api.tx.balances
.transfer(pairs.bob.address, 12345)
.signAndSend(pairs.alice, { nonce: nonce2 }, ({ status }: SubmittableResult): void => {
@@ -280,7 +280,7 @@ async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
await second.signAndSend('123', (result) => console.log(result));
// it handles enum inputs correctly
await api.tx.democracy.proxyVote(123, { Split: { nay: 456, yay: 123 } }).signAndSend(pairs.alice);
await api.tx.democracy['proxyVote'](123, { Split: { nay: 456, yay: 123 } }).signAndSend(pairs.alice);
// is
if (api.tx.balances.transfer.is(second)) {
@@ -295,7 +295,7 @@ async function at (api: ApiPromise): Promise<void> {
const apiAt = await api.at('0x1234');
// get old balances
console.log(await apiAt.query.balances.freeBalance('0x1234'));
console.log(await apiAt.query.balances['freeBalance']('0x1234'));
// get some constants
console.log(apiAt.consts.balances.existentialDeposit);
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/api', path: 'auto', type: 'auto', version: '10.9.1' };
+2 -2
View File
@@ -5,7 +5,7 @@
import type { Observable } from 'rxjs';
import type { Address, ApplyExtrinsicResult, Call, Extrinsic, ExtrinsicEra, ExtrinsicStatus, Hash, Header, Index, RuntimeDispatchInfo, SignerPayload } from '@polkadot/types/interfaces';
import type { Callback, Codec, Constructor, ISubmittableResult, SignatureOptions } from '@polkadot/types/types';
import type { Callback, Codec, CodecClass, ISubmittableResult, SignatureOptions } from '@polkadot/types/types';
import type { Registry } from '@polkadot/types-codec/types';
import type { ApiBase } from '../base/index.js';
import type { ApiInterfaceRx, ApiTypes, PromiseOrObs, SignerResult } from '../types/index.js';
@@ -83,7 +83,7 @@ function optionsOrNonce (partialOptions: Partial<SignerOptions> = {}): Partial<S
: partialOptions;
}
export function createClass <ApiType extends ApiTypes> ({ api, apiType, blockHash, decorateMethod }: SubmittableOptions<ApiType>): Constructor<SubmittableExtrinsic<ApiType>> {
export function createClass <ApiType extends ApiTypes> ({ api, apiType, blockHash, decorateMethod }: SubmittableOptions<ApiType>): CodecClass<SubmittableExtrinsic<ApiType>> {
// an instance of the base extrinsic for us to extend
const ExtrinsicBase = api.registry.createClass('Extrinsic');
+13 -13
View File
@@ -18,55 +18,55 @@ describe('extractStorageArgs', (): void => {
it('validates no-arg plain', (): void => {
expect(
extractStorageArgs(registry, storage.timestamp.now, [])
).toEqual([storage.timestamp.now, []]);
extractStorageArgs(registry, storage['timestamp']['now'], [])
).toEqual([storage['timestamp']['now'], []]);
});
it('validates no-arg plain (with undefined, undefined)', (): void => {
expect(
extractStorageArgs(registry, storage.timestamp.now, [undefined, undefined])
).toEqual([storage.timestamp.now, []]);
extractStorageArgs(registry, storage['timestamp']['now'], [undefined, undefined])
).toEqual([storage['timestamp']['now'], []]);
});
it('validates no-arg plain (failing when there are args)', (): void => {
expect(
() => extractStorageArgs(registry, storage.timestamp.now, [123, 456])
() => extractStorageArgs(registry, storage['timestamp']['now'], [123, 456])
).toThrow('timestamp.now() does not take any arguments, 2 found');
});
it('validates map, 1 arg', (): void => {
expect(
extractStorageArgs(registry, storage.staking.payee, ['abc'])
).toEqual([storage.staking.payee, ['abc']]);
extractStorageArgs(registry, storage['staking']['payee'], ['abc'])
).toEqual([storage['staking']['payee'], ['abc']]);
});
it('validates map, 1 arg (failing with no args)', (): void => {
expect(
() => extractStorageArgs(registry, storage.staking.payee, [])
() => extractStorageArgs(registry, storage['staking']['payee'], [])
).toThrow('staking.payee(AccountId32) is a map, requiring 1 arguments, 0 found');
});
it('validates map, 1 arg (failing with more args)', (): void => {
expect(
() => extractStorageArgs(registry, storage.staking.payee, ['abc', 'def'])
() => extractStorageArgs(registry, storage['staking']['payee'], ['abc', 'def'])
).toThrow('staking.payee(AccountId32) is a map, requiring 1 arguments, 2 found');
});
it('validates doublemap, 2 args', (): void => {
expect(
extractStorageArgs(registry, storage.staking.erasStakers, [1, '0x1234'])
).toEqual([storage.staking.erasStakers, [1, '0x1234']]);
extractStorageArgs(registry, storage['staking']['erasStakers'], [1, '0x1234'])
).toEqual([storage['staking']['erasStakers'], [1, '0x1234']]);
});
it('validates doublemap, 2 args (failing with no args)', (): void => {
expect(
() => extractStorageArgs(registry, storage.staking.erasStakers, [])
() => extractStorageArgs(registry, storage['staking']['erasStakers'], [])
).toThrow('staking.erasStakers(u32, AccountId32) is a map, requiring 2 arguments, 0 found');
});
it('validates doublemap, 2 args (failing with 1 arg)', (): void => {
expect(
() => extractStorageArgs(registry, storage.staking.erasStakers, [123])
() => extractStorageArgs(registry, storage['staking']['erasStakers'], [123])
).toThrow('staking.erasStakers(u32, AccountId32) is a map, requiring 2 arguments, 1 found');
});
});
+1
View File
@@ -12,6 +12,7 @@
"**/test/**/*"
],
"references": [
{ "path": "../api-augment/tsconfig.build.json" },
{ "path": "../api-base/tsconfig.build.json" },
{ "path": "../api-derive/tsconfig.build.json" },
{ "path": "../rpc-augment/tsconfig.build.json" },
+5 -5
View File
@@ -18,13 +18,13 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/rpc-core": "10.8.1",
"@polkadot/types": "10.8.1",
"@polkadot/types-codec": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/rpc-core": "10.9.1",
"@polkadot/types": "10.9.1",
"@polkadot/types-codec": "10.9.1",
"@polkadot/util": "^12.3.1",
"tslib": "^2.5.3"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/rpc-augment', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/rpc-augment', path: 'auto', type: 'auto', version: '10.9.1' };
+7 -7
View File
@@ -18,18 +18,18 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/rpc-augment": "10.8.1",
"@polkadot/rpc-provider": "10.8.1",
"@polkadot/types": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/rpc-augment": "10.9.1",
"@polkadot/rpc-provider": "10.9.1",
"@polkadot/types": "10.9.1",
"@polkadot/util": "^12.3.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.3"
},
"devDependencies": {
"@polkadot/keyring": "^12.2.2",
"@polkadot/rpc-augment": "10.8.1"
"@polkadot/keyring": "^12.3.1",
"@polkadot/rpc-augment": "10.9.1"
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ describe('Api', (): void => {
}
});
expect(isFunction((rpc as unknown as Record<string, Record<string, boolean>>).testing.foo)).toBe(true);
expect(isFunction((rpc as unknown as { testing: { foo: boolean } }).testing.foo)).toBe(true);
expect(rpc.sections.includes('testing')).toBe(true);
expect(rpc.mapping.get('testing_foo')).toEqual({
description: 'foo',
+1 -1
View File
@@ -13,7 +13,7 @@ import { RpcCore } from './index.js';
describe('methodSend', (): void => {
const registry = new TypeRegistry();
let rpc: RpcCore;
let methods: Record<string, DefinitionRpc>;
let methods: { blah: DefinitionRpc; bleh: DefinitionRpc };
let provider: ProviderInterface;
beforeEach((): void => {
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/rpc-core', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/rpc-core', path: 'auto', type: 'auto', version: '10.9.1' };
+9 -9
View File
@@ -18,17 +18,17 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/keyring": "^12.2.2",
"@polkadot/types": "10.8.1",
"@polkadot/types-support": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/util-crypto": "^12.2.2",
"@polkadot/x-fetch": "^12.2.2",
"@polkadot/x-global": "^12.2.2",
"@polkadot/x-ws": "^12.2.2",
"@polkadot/keyring": "^12.3.1",
"@polkadot/types": "10.9.1",
"@polkadot/types-support": "10.9.1",
"@polkadot/util": "^12.3.1",
"@polkadot/util-crypto": "^12.3.1",
"@polkadot/x-fetch": "^12.3.1",
"@polkadot/x-global": "^12.3.1",
"@polkadot/x-ws": "^12.3.1",
"eventemitter3": "^5.0.1",
"mock-socket": "^9.2.1",
"nock": "^13.3.1",
+1 -1
View File
@@ -36,7 +36,7 @@ describe.skip('send', (): void => {
return http
.send('test_body', ['param'])
.then((): void => {
expect(mock.body.test_body).toEqual({
expect(mock.body['test_body']).toEqual({
id: 1,
jsonrpc: '2.0',
method: 'test_body',
+2 -2
View File
@@ -202,11 +202,11 @@ export class MockProvider implements ProviderInterface {
// increment the balances and nonce for each account
keyring.getPairs().forEach(({ publicKey }, index): void => {
this.setStateBn(query.system.account(publicKey), newHead.number.toBn().addn(index));
this.setStateBn(query['system']['account'](publicKey), newHead.number.toBn().addn(index));
});
// set the timestamp for the current block
this.setStateBn(query.timestamp.now(), Math.floor(Date.now() / 1000));
this.setStateBn(query['timestamp']['now'](), Math.floor(Date.now() / 1000));
this.updateSubs('chain_subscribeNewHead', newHead);
// We emit connected/disconnected at intervals
+11 -2
View File
@@ -17,10 +17,19 @@ export interface Mock {
export type MockStateSubscriptionCallback = (error: Error | null, value: any) => void;
export type MockStateSubscriptions = Record<string, {
export interface MockStateSubscription {
callbacks: Record<number, MockStateSubscriptionCallback>;
lastValue: any;
}>;
}
export interface MockStateSubscriptions {
// known
chain_subscribeNewHead: MockStateSubscription;
state_subscribeStorage: MockStateSubscription;
// others
[key: string]: MockStateSubscription;
}
export type MockStateDb = Record<string, Uint8Array>;
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/rpc-provider', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/rpc-provider', path: 'auto', type: 'auto', version: '10.9.1' };
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Constructor } from '@polkadot/util/types';
import type { Class } from '@polkadot/util/types';
import type { EndpointStats, JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '../types.js';
import { EventEmitter } from 'eventemitter3';
@@ -209,7 +209,7 @@ export class WsProvider implements ProviderInterface {
this.#endpointIndex = this.selectEndpointIndex(this.#endpoints);
// the as here is Deno-specific - not available on the globalThis
this.#websocket = typeof xglobal.WebSocket !== 'undefined' && isChildClass(xglobal.WebSocket as unknown as Constructor<WebSocket>, WebSocket)
this.#websocket = typeof xglobal.WebSocket !== 'undefined' && isChildClass(xglobal.WebSocket as unknown as Class<WebSocket>, WebSocket)
? new WebSocket(this.endpoint)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - WS may be an instance of ws, which supports options
+13 -13
View File
@@ -18,7 +18,7 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"bin": {
"polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.mjs",
@@ -28,18 +28,18 @@
"polkadot-types-internal-metadata": "./scripts/polkadot-types-internal-metadata.mjs"
},
"dependencies": {
"@polkadot/api": "10.8.1",
"@polkadot/api-augment": "10.8.1",
"@polkadot/rpc-augment": "10.8.1",
"@polkadot/rpc-provider": "10.8.1",
"@polkadot/types": "10.8.1",
"@polkadot/types-augment": "10.8.1",
"@polkadot/types-codec": "10.8.1",
"@polkadot/types-create": "10.8.1",
"@polkadot/types-support": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/util-crypto": "^12.2.2",
"@polkadot/x-ws": "^12.2.2",
"@polkadot/api": "10.9.1",
"@polkadot/api-augment": "10.9.1",
"@polkadot/rpc-augment": "10.9.1",
"@polkadot/rpc-provider": "10.9.1",
"@polkadot/types": "10.9.1",
"@polkadot/types-augment": "10.9.1",
"@polkadot/types-codec": "10.9.1",
"@polkadot/types-create": "10.9.1",
"@polkadot/types-support": "10.9.1",
"@polkadot/util": "^12.3.1",
"@polkadot/util-crypto": "^12.3.1",
"@polkadot/x-ws": "^12.3.1",
"handlebars": "^4.7.7",
"tslib": "^2.5.3",
"yargs": "^17.7.2"
+11 -4
View File
@@ -19,6 +19,13 @@ import { isString, stringify } from '@polkadot/util';
import { createImports, exportInterface, initMeta, readTemplate, writeFile } from '../util/index.js';
import { typeEncoders } from './tsDef.js';
// Record<string, >
interface ParsedDef {
_set: Record<string, number>;
[key: string]: string | Record<string, string> | Record<string, number>;
}
const WITH_TYPEDEF = false;
const generateLookupDefsTmpl = Handlebars.compile(readTemplate('lookup/defs'));
@@ -67,9 +74,9 @@ function expandSet (parsed: Record<string, number>): string[] {
);
}
function expandObject (parsed: Record<string, string | Record<string, string>>): string[] {
function expandObject (parsed: ParsedDef): string[] {
if (parsed._set) {
return expandSet(parsed._set as unknown as Record<string, number>);
return expandSet(parsed._set);
}
return formatObject(
@@ -78,7 +85,7 @@ function expandObject (parsed: Record<string, string | Record<string, string>>):
? expandType(v)
: Array.isArray(v)
? [`[${(v as string[]).map((e) => `'${e}'`).join(', ')}]`]
: expandObject(v);
: expandObject(v as ParsedDef);
inner.forEach((l, index): void => {
all.push(`${
@@ -98,7 +105,7 @@ function expandType (encoded: string): string[] {
return [`'${encoded}'`];
}
return expandObject(JSON.parse(encoded) as Record<string, string | Record<string, string>>);
return expandObject(JSON.parse(encoded) as ParsedDef);
}
function expandDefToString ({ lookupNameRoot, type }: TypeDef, indent: number): string {
+1 -1
View File
@@ -114,7 +114,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
})
.sort(compareName);
imports.typesTypes.Observable = true;
imports.typesTypes['Observable'] = true;
return generateForMetaTemplate({
headerType: 'chain',
+1 -1
View File
@@ -126,7 +126,7 @@ export function generateRpcTypes (registry: TypeRegistry, importDefinitions: Rec
};
}).concat(...Object.values(additional)).sort((a, b) => a.name.localeCompare(b.name));
imports.typesTypes.Observable = true;
imports.typesTypes['Observable'] = true;
return generateRpcTypesTemplate({
headerType: 'chain',
+1 -1
View File
@@ -141,7 +141,7 @@ export function generateCallTypes (registry: Registry, meta: Metadata, dest: str
}).filter(({ items }) => items.length).sort((a, b) => a.name.localeCompare(b.name));
if (modules.length) {
imports.typesTypes.Observable = true;
imports.typesTypes['Observable'] = true;
}
return generateCallsTypesTemplate({
+4 -1
View File
@@ -1,4 +1,7 @@
// Copyright 2017-2023 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
export type ExtraTypes = Record<string, Record<string, { runtime?: Record<string, any>, types: Record<string, any> }>>;
export type ExtraTypes = Record<string, Record<string, {
runtime?: Record<string, any>;
types: Record<string, any>;
}>>;
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/typegen', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/typegen', path: 'auto', type: 'auto', version: '10.9.1' };
+4 -4
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Constructor, Registry } from '@polkadot/types/types';
import type { CodecClass, Registry } from '@polkadot/types/types';
import type { UInt } from '@polkadot/types-codec';
import type { TypeDef } from '@polkadot/types-create/types';
import type { ModuleTypes, TypeImports } from './imports.js';
@@ -69,7 +69,7 @@ export function getSimilarTypes (registry: Registry, definitions: Record<string,
}
}
} else if (isChildClass(Enum, Clazz)) {
const { defKeys, isBasic } = new (Clazz as Constructor)(registry) as Enum;
const { defKeys, isBasic } = new (Clazz as CodecClass)(registry) as Enum;
const keys = defKeys.filter((v) => !v.startsWith('__Unused'));
if (isBasic) {
@@ -80,7 +80,7 @@ export function getSimilarTypes (registry: Registry, definitions: Record<string,
}
possibleTypes.push('Uint8Array');
} else if (isChildClass(AbstractInt as unknown as Constructor<UInt>, Clazz) || isChildClass(Compact, Clazz)) {
} else if (isChildClass(AbstractInt as unknown as CodecClass<UInt>, Clazz) || isChildClass(Compact, Clazz)) {
possibleTypes.push('AnyNumber', 'Uint8Array');
} else if (isChildClass(GenericLookupSource, Clazz)) {
possibleTypes.push('Address', 'AccountId', 'AccountIndex', 'LookupSource', 'string', 'Uint8Array');
@@ -93,7 +93,7 @@ export function getSimilarTypes (registry: Registry, definitions: Record<string,
} else if (isChildClass(Null, Clazz)) {
possibleTypes.push('null');
} else if (isChildClass(Struct, Clazz)) {
const s = new (Clazz as Constructor)(registry) as Struct;
const s = new (Clazz as CodecClass)(registry) as Struct;
const obj = s.defKeys.map((key): string => `${key}?: any`).join('; ');
possibleTypes.push(`{ ${obj} }`, 'string', 'Uint8Array');
+4 -4
View File
@@ -18,12 +18,12 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/types": "10.8.1",
"@polkadot/types-codec": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/types": "10.9.1",
"@polkadot/types-codec": "10.9.1",
"@polkadot/util": "^12.3.1",
"tslib": "^2.5.3"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/types-augment', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/types-augment', path: 'auto', type: 'auto', version: '10.9.1' };
+7 -7
View File
@@ -18,17 +18,17 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/util": "^12.2.2",
"@polkadot/x-bigint": "^12.2.2",
"@polkadot/util": "^12.3.1",
"@polkadot/x-bigint": "^12.3.1",
"tslib": "^2.5.3"
},
"devDependencies": {
"@polkadot/types": "10.8.1",
"@polkadot/types-augment": "10.8.1",
"@polkadot/types-support": "10.8.1",
"@polkadot/util-crypto": "^12.2.2"
"@polkadot/types": "10.9.1",
"@polkadot/types-augment": "10.9.1",
"@polkadot/types-support": "10.9.1",
"@polkadot/util-crypto": "^12.3.1"
}
}
+2 -2
View File
@@ -379,8 +379,8 @@ describe('Enum', (): void => {
const type = new Enum(registry, { A: Text, B: U32, C: U32 }).toRawType();
const value = registry.createType(type, { B: 123 });
expect((value as unknown as Record<string, unknown>).isB).toEqual(true);
expect((value as unknown as Record<string, U32>).asB.toNumber()).toEqual(123);
expect((value as unknown as { isB: boolean }).isB).toEqual(true);
expect((value as unknown as { asB: U32 }).asB.toNumber()).toEqual(123);
});
});
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/types-codec', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/types-codec', path: 'auto', type: 'auto', version: '10.9.1' };
+1 -1
View File
@@ -45,7 +45,7 @@ ${formatFixed(micro).padStart(NUM_PAD + PRE_PAD + 1)} μs/op`;
}
export function perf (name: string, count: number, inputs: unknown[][], exec: ExecFn): void {
const test = process.env.GITHUB_REPOSITORY
const test = process.env['GITHUB_REPOSITORY']
? it.skip
: it;
+2 -4
View File
@@ -117,15 +117,13 @@ export interface Codec {
toU8a (isBare?: BareOpts): Uint8Array;
}
export interface CodecClass<T = Codec> {
export interface CodecClass<T = Codec, A extends unknown[] = any[]> {
/**
* @description An internal fallback type (previous generation) if encoding fails
*/
readonly __fallbackType?: string;
// NOTE: We need the any[] here, unknown[] does not work as expected
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new(registry: Registry, ...args: any[]): T;
new(registry: Registry, ...args: A): T;
}
export interface CodecObject<T extends ToString> extends Codec {
+4 -4
View File
@@ -18,14 +18,14 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/types-codec": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/types-codec": "10.9.1",
"@polkadot/util": "^12.3.1",
"tslib": "^2.5.3"
},
"devDependencies": {
"@polkadot/types": "10.8.1"
"@polkadot/types": "10.9.1"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/types-create', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/types-create', path: 'auto', type: 'auto', version: '10.9.1' };
+22 -6
View File
@@ -15,6 +15,22 @@ interface TypeDefOptions {
displayName?: string;
}
interface SetDetails {
_bitLength: number;
index: number;
[key: string]: number;
}
interface ParsedDef {
_alias: string;
_enum?: string[];
_fallback?: string;
_set?: SetDetails;
[key: string]: unknown;
}
const KNOWN_INTERNALS = ['_alias', '_fallback'];
function getTypeString (typeOrObj: any): string {
@@ -71,7 +87,7 @@ function _decodeEnum (value: TypeDef, details: string[] | Record<string, string>
// decode a set of the form
// { _set: { A: 0b0001, B: 0b0010, C: 0b0100 } }
function _decodeSet (value: TypeDef, details: Record<string, number>, fallbackType: string | undefined): TypeDef {
function _decodeSet (value: TypeDef, details: SetDetails, fallbackType: string | undefined): TypeDef {
value.info = TypeDefInfo.Set;
value.fallbackType = fallbackType;
value.length = details._bitLength;
@@ -90,13 +106,13 @@ function _decodeSet (value: TypeDef, details: Record<string, number>, fallbackTy
// decode a struct, set or enum
function _decodeStruct (value: TypeDef, type: string, _: string, count: number): TypeDef {
const parsed = JSON.parse(type) as Record<string, unknown> & { _alias: string, _fallback?: string };
const parsed = JSON.parse(type) as ParsedDef;
const keys = Object.keys(parsed);
if (keys.includes('_enum')) {
return _decodeEnum(value, parsed._enum as string[], count, parsed._fallback);
} else if (keys.includes('_set')) {
return _decodeSet(value, parsed._set as Record<string, number>, parsed._fallback);
if (parsed._enum) {
return _decodeEnum(value, parsed._enum, count, parsed._fallback);
} else if (parsed._set) {
return _decodeSet(value, parsed._set, parsed._fallback);
}
value.alias = parsed._alias
+7 -7
View File
@@ -18,17 +18,17 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/networks": "^12.2.2",
"@polkadot/types": "10.8.1",
"@polkadot/types-codec": "10.8.1",
"@polkadot/types-create": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/networks": "^12.3.1",
"@polkadot/types": "10.9.1",
"@polkadot/types-codec": "10.9.1",
"@polkadot/types-create": "10.9.1",
"@polkadot/util": "^12.3.1",
"tslib": "^2.5.3"
},
"devDependencies": {
"@polkadot/api": "10.8.1"
"@polkadot/api": "10.9.1"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/types-known', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/types-known', path: 'auto', type: 'auto', version: '10.9.1' };
+2 -2
View File
@@ -18,10 +18,10 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/util": "^12.2.2",
"@polkadot/util": "^12.3.1",
"tslib": "^2.5.3"
}
}
File diff suppressed because one or more lines are too long
@@ -31600,25 +31600,25 @@
{
"name": "amount1_desired",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
"name": "amount2_desired",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
"name": "amount1_min",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
"name": "amount2_min",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
@@ -31651,19 +31651,19 @@
{
"name": "lp_token_burn",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
"name": "amount1_min_receive",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
"name": "amount2_min_receive",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
@@ -31690,13 +31690,13 @@
{
"name": "amount_in",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
"name": "amount_out_min",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
@@ -31729,13 +31729,13 @@
{
"name": "amount_out",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
"name": "amount_in_max",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": []
},
{
@@ -34064,7 +34064,7 @@
{
"name": "amount1_provided",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": [
"The amount of the first asset that was added to the pool."
]
@@ -34072,7 +34072,7 @@
{
"name": "amount2_provided",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": [
"The amount of the second asset that was added to the pool."
]
@@ -34088,7 +34088,7 @@
{
"name": "lp_token_minted",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": [
"The amount of lp tokens that were minted of that id."
]
@@ -34129,7 +34129,7 @@
{
"name": "amount1",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": [
"The amount of the first asset that was removed from the pool."
]
@@ -34137,7 +34137,7 @@
{
"name": "amount2",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": [
"The amount of the second asset that was removed from the pool."
]
@@ -34153,7 +34153,7 @@
{
"name": "lp_token_burned",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": [
"The amount of lp tokens that were burned of that id."
]
@@ -34203,7 +34203,7 @@
{
"name": "amount_in",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": [
"The amount of the first asset that was swapped."
]
@@ -34211,7 +34211,7 @@
{
"name": "amount_out",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": [
"The amount of the second asset that was received."
]
@@ -34253,7 +34253,7 @@
{
"name": "amount",
"type": 6,
"typeName": "AssetBalanceOf<T>",
"typeName": "T::AssetBalance",
"docs": [
"The amount of the asset that was transferred."
]
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/types-support', path: 'auto', type: 'auto', version: '10.8.1' };
export const packageInfo = { name: '@polkadot/types-support', path: 'auto', type: 'auto', version: '10.9.1' };
+9 -9
View File
@@ -18,20 +18,20 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "10.8.1",
"version": "10.9.1",
"main": "index.js",
"dependencies": {
"@polkadot/keyring": "^12.2.2",
"@polkadot/types-augment": "10.8.1",
"@polkadot/types-codec": "10.8.1",
"@polkadot/types-create": "10.8.1",
"@polkadot/util": "^12.2.2",
"@polkadot/util-crypto": "^12.2.2",
"@polkadot/keyring": "^12.3.1",
"@polkadot/types-augment": "10.9.1",
"@polkadot/types-codec": "10.9.1",
"@polkadot/types-create": "10.9.1",
"@polkadot/util": "^12.3.1",
"@polkadot/util-crypto": "^12.3.1",
"rxjs": "^7.8.1",
"tslib": "^2.5.3"
},
"devDependencies": {
"@polkadot/keyring": "^12.2.2",
"@polkadot/types-support": "10.8.1"
"@polkadot/keyring": "^12.3.1",
"@polkadot/types-support": "10.9.1"
}
}
+1 -1
View File
@@ -155,7 +155,7 @@ function injectExtrinsics (registry: TypeRegistry, { lookup, pallets }: Metadata
function extractProperties (registry: TypeRegistry, metadata: Metadata): ChainProperties | undefined {
const original = registry.getChainProperties();
const constants = decorateConstants(registry, metadata.asLatest, metadata.version);
const ss58Format = constants.system && (constants.system.sS58Prefix || constants.system.ss58Prefix);
const ss58Format = constants['system'] && (constants['system']['sS58Prefix'] || constants['system']['ss58Prefix']);
if (!ss58Format) {
return original;
@@ -37,7 +37,7 @@ describe('ExtrinsicV4', (): void => {
expect(
new Extrinsic(
registry,
tx.balances.transferAllowDeath(keyring.bob.publicKey, 6969n)
tx['balances']['transferAllowDeath'](keyring.bob.publicKey, 6969n)
).toHex()
).toEqual(
'0x' +
@@ -52,7 +52,7 @@ describe('ExtrinsicV4', (): void => {
expect(
new Extrinsic(
registry,
tx.balances.transferAllowDeath(keyring.bob.publicKey, 6969n)
tx['balances']['transferAllowDeath'](keyring.bob.publicKey, 6969n)
).sign(keyring.alice, {
blockHash: '0xec7afaf1cca720ce88c1d1b689d81f0583cc15a97d621cf046dd9abf605ef22f',
genesisHash: '0xdcd1346701ca8396496e52aa2785b1748deb6db09551b72159dcb3e08991025b',
@@ -20,7 +20,7 @@ describe('ExtrinsicPayload', (): void => {
it('has a sane inspect', (): void => {
// we don't expect this to fail, however it is actually a good
// reference for the ordering in base Substrate
expect(new ExtrinsicPayload(registry, { method: tx.timestamp.set(0).toHex() } as never).inspect()).toEqual({
expect(new ExtrinsicPayload(registry, { method: tx['timestamp']['set'](0).toHex() } as never).inspect()).toEqual({
inner: [
{ name: 'method', outer: [new Uint8Array([3, 0, 0])] },
{ inner: undefined, name: 'era', outer: [new Uint8Array([0]), new Uint8Array([0])] },
+2 -2
View File
@@ -88,8 +88,8 @@ function decodeCallViaU8a (registry: Registry, value: Uint8Array, _meta?: Functi
function decodeCall (registry: Registry, value: unknown | DecodedMethod | Uint8Array | string = new Uint8Array(), _meta?: FunctionMetadataLatest): DecodedMethod {
if (isU8a(value) || isHex(value)) {
return decodeCallViaU8a(registry, u8aToU8a(value), _meta);
} else if (isObject(value) && value.callIndex && value.args) {
return decodeCallViaObject(registry, value as DecodedMethod, _meta);
} else if (isObject<DecodedMethod>(value) && value.callIndex && value.args) {
return decodeCallViaObject(registry, value, _meta);
}
throw new Error(`Call: Cannot decode value '${value as string}' of type ${typeof value}`);
@@ -5,6 +5,7 @@ import type { AnyJson } from '@polkadot/types-codec/types';
import type { HexString } from '@polkadot/util/types';
import type { MetadataAll, MetadataLatest, MetadataV9, MetadataV10, MetadataV11, MetadataV12, MetadataV13, MetadataV14, MetadataV15 } from '../interfaces/metadata/index.js';
import type { Registry } from '../types/index.js';
import type { MetaVersionAll, MetaVersionAsX } from './versions.js';
import { Struct } from '@polkadot/types-codec';
@@ -17,23 +18,10 @@ import { toV14 } from './v13/toV14.js';
import { toV15 } from './v14/toV15.js';
import { toLatest } from './v15/toLatest.js';
import { MagicNumber } from './MagicNumber.js';
import { LATEST_VERSION, TO_CALLS_VERSION } from './versions.js';
// Use these to generate all the Meta* types below via template keys
// NOTE: Keep from latest -> earliest, see the LATEST_VERSION 0 index
const KNOWN_VERSIONS = [15, 14, 13, 12, 11, 10, 9] as const;
const LATEST_VERSION = KNOWN_VERSIONS[0];
// This is part of migration. The toCallsOnly would be usede for esxtensions,
// i.e. they need to be updated. To ensure that they are passed a known version
// we actually set this to a known-working version
//
// NOTE: This would only work on compatible types, i.e. v14 & v15 comply
const TO_CALLS_VERSION = 14; // LATEST_VERSION;
type MetaAll = typeof KNOWN_VERSIONS[number];
type MetaAsX = `asV${MetaAll}`;
type MetaMapped = MetadataAll[MetaAsX];
type MetaVersions = Exclude<MetaAll, 9> | 'latest';
type MetaMapped = MetadataAll[MetaVersionAsX];
type MetaVersions = Exclude<MetaVersionAll, 9> | 'latest';
/**
* @name MetadataVersioned
@@ -64,15 +52,15 @@ export class MetadataVersioned extends Struct {
#getVersion = <T extends MetaMapped, F extends MetaMapped>(version: MetaVersions, fromPrev: (registry: Registry, input: F, metaVersion: number) => T): T => {
if (version !== 'latest' && this.#assertVersion(version)) {
const asCurr: MetaAsX = `asV${version}`;
const asCurr: MetaVersionAsX = `asV${version}`;
return this.#metadata()[asCurr] as T;
}
if (!this.#converted.has(version)) {
const asPrev: MetaAsX = version === 'latest'
const asPrev: MetaVersionAsX = version === 'latest'
? `asV${LATEST_VERSION}`
: `asV${(version - 1) as MetaAll}`;
: `asV${(version - 1) as MetaVersionAll}`;
this.#converted.set(version, fromPrev(this.registry, this[asPrev] as F, this.version));
}
@@ -165,8 +153,8 @@ export class MetadataVersioned extends Struct {
/**
* @description the metadata version this structure represents
*/
public get version (): number {
return this.#metadata().index;
public get version (): MetaVersionAll {
return this.#metadata().index as MetaVersionAll;
}
public getUniqTypes (throwError: boolean): string[] {
@@ -27,10 +27,19 @@ interface Extract extends ExtractBase {
interface TypeInfo {
lookups: Record<string, LookupString>;
names: Record<number, string>;
params: Record<string, SiTypeParameter[]>;
params: TypeInfoParams;
types: Record<number, PortableType>;
}
interface TypeInfoParams {
// known param definitions
FrameSystemEventRecord: [event: SiTypeParameter, topic: SiTypeParameter]
SpRuntimeUncheckedExtrinsic: [address: SiTypeParameter, call: SiTypeParameter, signature: SiTypeParameter, extra: SiTypeParameter];
// other type definitions
[key: string]: SiTypeParameter[];
}
// Just a placeholder for a type.unrwapOr()
const TYPE_UNWRAP = { toNumber: () => -1 };
@@ -398,7 +407,7 @@ function removeDupeNames (lookup: PortableRegistry, portable: PortableType[], na
}
/** @internal Detect on-chain types (AccountId/Signature) as set as the default */
function registerTypes (lookup: PortableRegistry, lookups: Record<string, string>, names: Record<number, string>, params: Record<string, SiTypeParameter[]>): void {
function registerTypes (lookup: PortableRegistry, lookups: Record<string, string>, names: Record<number, string>, params: TypeInfoParams): void {
// Register the types we extracted
lookup.registry.register(lookups);
@@ -439,7 +448,7 @@ function registerTypes (lookup: PortableRegistry, lookups: Record<string, string
* @internal Extracts aliases based on what we know the runtime config looks like in a
* Substrate chain. Specifically we want to have access to the Call and Event params
**/
function extractAliases (params: Record<string, SiTypeParameter[]>, isContract?: boolean): Record<number, string> {
function extractAliases (params: TypeInfoParams, isContract?: boolean): Record<number, string> {
const hasParams = Object.keys(params).some((k) => !k.startsWith('Pallet'));
const alias: Record<number, string> = {};
@@ -483,7 +492,7 @@ function extractTypeInfo (lookup: PortableRegistry, portable: PortableType[]): T
const lookups: Record<string, LookupString> = {};
const names: Record<number, string> = {};
const params: Record<string, SiTypeParameter[]> = {};
const params = {} as TypeInfoParams;
const dedup = removeDupeNames(lookup, portable, nameInfo);
for (let i = 0, count = dedup.length; i < count; i++) {
@@ -501,7 +510,7 @@ export class PortableRegistry extends Struct implements ILookup {
#alias: Record<number, string>;
#lookups: Record<string, LookupString>;
#names: Record<number, string>;
#params: Record<string, SiTypeParameter[]>;
#params: TypeInfoParams;
#typeDefs: Record<number, TypeDef> = {};
#types: Record<number, PortableType>;
@@ -14,7 +14,7 @@ import { TypeRegistry } from '../../../create/index.js';
import { Metadata } from '../../Metadata.js';
import { decorateConstants } from '../index.js';
function init (meta: HexString): [Constants, TypeRegistry] {
function init (meta: HexString): [consts: Constants, registry: TypeRegistry] {
const registry = new TypeRegistry();
const metadata = new Metadata(registry, meta);
@@ -27,9 +27,9 @@ describe('decorateConstants', (): void => {
it('should return constants with the correct type and value', (): void => {
const [consts] = init(rpcMetadata);
expect((consts.democracy.cooloffPeriod as unknown as BlockNumber).bitLength()).toBe(32);
expect((consts['democracy']['cooloffPeriod'] as unknown as BlockNumber).bitLength()).toBe(32);
// 3 second blocks, 28 days
expect((consts.democracy.cooloffPeriod as unknown as BlockNumber).toNumber()).toEqual(28 * 24 * 60 * (60 / 3));
expect((consts['democracy']['cooloffPeriod'] as unknown as BlockNumber).toNumber()).toEqual(28 * 24 * 60 * (60 / 3));
});
// removed from session
@@ -38,7 +38,7 @@ describe('decorateConstants', (): void => {
// 0x34 removes as the length prefix removed
expect(
consts.session.dedupKeyPrefix.toHex()
consts['session']['dedupKeyPrefix'].toHex()
).toEqual('0x3a73657373696f6e3a6b657973');
});
});
@@ -22,11 +22,12 @@ export function decorateConstants (registry: Registry, { pallets }: MetadataLate
{},
constants,
(constant: PalletConstantMetadataLatest): ConstantCodec => {
const codec = registry.createTypeUnsafe(registry.createLookupType(constant.type), [hexToU8a(constant.value.toHex())]);
const codec = registry.createTypeUnsafe<ConstantCodec>(registry.createLookupType(constant.type), [hexToU8a(constant.value.toHex())]);
(codec as unknown as Record<string, unknown>).meta = constant;
// We are casting here since we are assigning to a read-only property
(codec as { meta: PalletConstantMetadataLatest }).meta = constant;
return codec as ConstantCodec;
return codec;
},
objectNameToCamel
)
@@ -18,13 +18,13 @@ const errors = decorateErrors(registry, metadata.asLatest, metadata.version);
describe('decorateErrors', (): void => {
it('should return known errors', (): void => {
expect(errors.balances.InsufficientBalance).toBeDefined();
expect(errors.system.FailedToExtractRuntimeVersion).toBeDefined();
expect(errors['balances']['InsufficientBalance']).toBeDefined();
expect(errors['system']['FailedToExtractRuntimeVersion']).toBeDefined();
});
it('has the correct metadata for known errors', (): void => {
expect(
errors.proxy.NotProxy.meta.toJSON()
errors['proxy']['NotProxy'].meta.toJSON()
).toEqual({
args: [],
docs: ['Sender is not a proxy of the account to be proxied.'],
@@ -36,7 +36,7 @@ describe('decorateErrors', (): void => {
it('should check against a specific error', (): void => {
expect(
errors.system.InvalidSpecName.is(
errors['system']['InvalidSpecName'].is(
registry.createType('DispatchErrorModule', {
error: 0,
index: 0
@@ -18,13 +18,13 @@ const events = decorateEvents(registry, metadata.asLatest, metadata.version);
describe('decorateEvents', (): void => {
it('should return known errors', (): void => {
expect(events.balances.Transfer).toBeDefined();
expect(events.system.CodeUpdated).toBeDefined();
expect(events['balances']['Transfer']).toBeDefined();
expect(events['system']['CodeUpdated']).toBeDefined();
});
it('has the correct metadata for known errors', (): void => {
expect(
events.staking.Rewarded.meta.toJSON()
events['staking']['Rewarded'].meta.toJSON()
).toEqual({
args: ['AccountId32', 'u128'],
docs: [
@@ -41,7 +41,7 @@ describe('decorateEvents', (): void => {
it('should check against a specific error', (): void => {
expect(
events.system.ExtrinsicSuccess.is(registry.createType('Event', { index: [0, 0] }))
events['system']['ExtrinsicSuccess'].is(registry.createType('Event', { index: [0, 0] }))
).toBe(true);
});
});
@@ -24,7 +24,7 @@ describe('extrinsics', (): void => {
it('encodes an actual transfer (actual data)', (): void => {
expect(
registry.createType('Extrinsic',
extrinsics.balances.transfer(keyring.bob.publicKey, 6969)
extrinsics['balances']['transfer'](keyring.bob.publicKey, 6969)
).sign(keyring.alice, {
blockHash: '0xec7afaf1cca720ce88c1d1b689d81f0583cc15a97d621cf046dd9abf605ef22f',
genesisHash: '0xdcd1346701ca8396496e52aa2785b1748deb6db09551b72159dcb3e08991025b',
@@ -57,16 +57,16 @@ describe('extrinsics', (): void => {
describe('decorateExtrinsics', (): void => {
it('should throw if an incorrect number of args is supplied', (): void => {
expect(() => extrinsics.balances.setBalance()).toThrow(/expects 3 arguments/);
expect(() => extrinsics['balances']['setBalance']()).toThrow(/expects 3 arguments/);
});
it('should return a value if the storage function does not expect an argument', (): void => {
expect(() => extrinsics.balances.setBalance('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF', 2, 3)).not.toThrow();
expect(() => extrinsics['balances']['setBalance']('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF', 2, 3)).not.toThrow();
});
it('should return properly-encoded transactions', (): void => {
expect(
registry.createType('Extrinsic', extrinsics.timestamp.set(32)).toU8a()
registry.createType('Extrinsic', extrinsics['timestamp']['set'](32)).toU8a()
).toEqual(
new Uint8Array([
// length (encoded)
@@ -82,9 +82,9 @@ describe('decorateExtrinsics', (): void => {
});
it('has working .is', (): void => {
const tx = extrinsics.balances.setBalance('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF', 2, 3);
const tx = extrinsics['balances']['setBalance']('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF', 2, 3);
expect(extrinsics.balances.setBalance.is(tx)).toBe(true);
expect(extrinsics.balances.transfer.is(tx)).toBe(false);
expect(extrinsics['balances']['setBalance'].is(tx)).toBe(true);
expect(extrinsics['balances']['transfer'].is(tx)).toBe(false);
});
});
@@ -22,7 +22,7 @@ describe('Decorated', () => {
expect(
u8aToHex(
query.system.account('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')
query['system']['account']('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')
)
).toEqual(
'0x410126aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d'
@@ -33,7 +33,7 @@ describe('Decorated', () => {
const tx = decorateExtrinsics(registry, metadata.asLatest, metadata.version);
expect(
registry.createType('Extrinsic', tx.timestamp.set(63)).toU8a()
registry.createType('Extrinsic', tx['timestamp']['set'](63)).toU8a()
).toEqual(
new Uint8Array([
// length (encoded)
@@ -51,7 +51,7 @@ describe('Decorated', () => {
it('should return constants with the correct type and value', (): void => {
const consts = decorateConstants(registry, metadata.asLatest, metadata.version);
expect(consts.democracy.cooloffPeriod).toBeInstanceOf(u32); // BlockNumber
expect(consts.democracy.cooloffPeriod.toHex()).toEqual('0x000c4e00');
expect(consts['democracy']['cooloffPeriod']).toBeInstanceOf(u32); // BlockNumber
expect(consts['democracy']['cooloffPeriod'].toHex()).toEqual('0x000c4e00');
});
});
@@ -19,13 +19,13 @@ describe('getSorage', (): void => {
const storage = getStorage(registry);
it('should return well known keys', (): void => {
expect(typeof storage.substrate).toBe('object');
expect(typeof storage['substrate']).toBe('object');
expect(storage.substrate.code()).toEqual(compactAddLength(u8aToU8a(':code')));
expect(storage['substrate']['code']()).toEqual(compactAddLength(u8aToU8a(':code')));
expect(storage.substrate.changesTrieConfig).toBeTruthy();
expect(storage.substrate.childStorageKeyPrefix).toBeTruthy();
expect(storage.substrate.extrinsicIndex).toBeTruthy();
expect(storage.substrate.heapPages).toBeTruthy();
expect(storage['substrate']['changesTrieConfig']).toBeTruthy();
expect(storage['substrate']['childStorageKeyPrefix']).toBeTruthy();
expect(storage['substrate']['extrinsicIndex']).toBeTruthy();
expect(storage['substrate']['heapPages']).toBeTruthy();
});
});
@@ -23,28 +23,28 @@ describe('decorateStorage', (): void => {
const query = decorateStorage(registry, metadata.asLatest, metadata.version);
it('should throw if the storage function expects an argument', (): void => {
expect(() => query.balances.account()).toThrow('Call to balances.account needs 1 arguments, found []');
expect(() => query['balances']['account']()).toThrow('Call to balances.account needs 1 arguments, found []');
});
it('should throw if the storage function expects multiple arguments', (): void => {
expect(() => query.staking.erasStakers([1])).toThrow('Call to staking.erasStakers needs 2 arguments, found [1]');
expect(() => query['staking']['erasStakers']([1])).toThrow('Call to staking.erasStakers needs 2 arguments, found [1]');
});
it('should throw if the storage function expects tuple arguments', (): void => {
expect(() => query.staking.erasStakers(1)).toThrow('Call to staking.erasStakers needs 2 arguments, found [1]');
expect(() => query['staking']['erasStakers'](1)).toThrow('Call to staking.erasStakers needs 2 arguments, found [1]');
});
it('should return a value if the storage function does not expect an argument', (): void => {
expect(() => query.timestamp.now()).not.toThrow();
expect(() => query['timestamp']['now']()).not.toThrow();
});
it('should return a value if the storage function has the correct arguments', (): void => {
expect(() => query.staking.erasStakers(1, keyring.alice.address)).not.toThrow();
expect(() => query['staking']['erasStakers'](1, keyring.alice.address)).not.toThrow();
});
it('should return the correct length-prefixed storage key', (): void => {
expect(
u8aToHex(query.system.account(keyring.alice.address))
u8aToHex(query['system']['account'](keyring.alice.address))
).toEqual(
'0x' +
'4101' + // length
@@ -56,7 +56,7 @@ describe('decorateStorage', (): void => {
it('should decorate the palletVersion entry', (): void => {
expect(
u8aToHex(query.system.palletVersion())
u8aToHex(query['system']['palletVersion']())
).toEqual(
'0x' +
'80' + // length

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