Compare commits

..
44 Commits
Author SHA1 Message Date
Github Actions aa7e30070f [CI Skip] release/stable 3.9.1
skip-checks: true
2021-02-14 17:46:51 +00:00
Jaco Greeff 64b5855f65 3.8 (#3174) 2021-02-14 18:39:44 +01:00
Github Actions d7ff9e706e [CI Skip] release/beta 3.8.2-5
skip-checks: true
2021-02-14 08:53:37 +00:00
Jaco Greeff 15ba6f6261 Adjust Result for Rust-compatible Err (w/ deprecation of is/asError) (#3172)
* Adjust Result for Rust-compatible Err (w/ deprecation of is/asError)

* Jsdoc comments

* test updates
2021-02-14 09:43:37 +01:00
Github Actions 8c88a880c6 [CI Skip] release/beta 3.8.2-4
skip-checks: true
2021-02-11 17:27:04 +00:00
Jaco Greeff 74566cce7b Update Rococo types (drop v0) (#3167) 2021-02-11 18:17:05 +01:00
Github Actions 16f6deed5e [CI Skip] release/beta 3.8.2-3
skip-checks: true
2021-02-10 12:14:16 +00:00
Jaco Greeff 40edc131fe Allow geneic args for keys/entries (#3165) 2021-02-10 13:04:23 +01:00
Github Actions 3e014b38e6 [CI Skip] release/beta 3.8.2-2
skip-checks: true
2021-02-10 08:49:29 +00:00
Jaco Greeff b4cfdbffab Fix council derives for seatholders (#3163)
* Fix council derives for setholders

* Fix vote retreival
2021-02-10 09:41:47 +01:00
Github Actions cbfb6f8f59 [CI Skip] release/beta 3.8.2-1
skip-checks: true
2021-02-09 19:00:05 +00:00
Jaco Greeff b5bc15ab8b Last Kusama upgrade block (#3160) 2021-02-09 19:50:24 +01:00
Github Actions 0b343fc0f8 [CI Skip] release/beta 3.8.2-0
skip-checks: true
2021-02-08 15:55:08 +00:00
Jaco Greeff e7f9693873 Add ParaLifecycle type (#3159) 2021-02-08 16:47:02 +01:00
Github Actions a0a5c3185d [CI Skip] release/stable 3.8.1
skip-checks: true
2021-02-07 13:05:43 +00:00
Jaco Greeff 151d4693a9 3.8 (#3158) 2021-02-07 13:56:10 +01:00
Github Actions cdb27d8ec2 [CI Skip] release/beta 3.7.4-8
skip-checks: true
2021-02-07 12:14:25 +00:00
Jaco Greeff 055e4d1261 Bump to common stable (#3157) 2021-02-07 13:06:46 +01:00
Github Actions bf753255ab [CI Skip] release/beta 3.7.4-7
skip-checks: true
2021-02-07 08:59:19 +00:00
Jaco Greeff e2230ef454 Bump common (#3155)
* Bump common

* Adjust (some) tests

* Adjust tests
2021-02-07 09:49:48 +01:00
Github Actions 0f5b01b856 [CI Skip] release/beta 3.7.4-6
skip-checks: true
2021-02-06 13:45:59 +00:00
Jaco Greeff 82787c96c6 Single put_code/deploy (new & backwards compat.) (#3143)
* Single put_code/deploy (new & backwards compat.)

* new-style

* old-style deploy?

* notice

* Cleanups

* linting

* grrr... Mac case-sensistivity

* Add createContract on BluePrint

* Adjust contracts check

* Adjust

* Adjust tests
2021-02-06 14:36:42 +01:00
Github Actions f89028d5fe [CI Skip] release/beta 3.7.4-5
skip-checks: true
2021-02-06 12:09:28 +00:00
Jaco Greeff ba24a2e917 Bump latest Substrate meta (#3154) 2021-02-06 13:00:26 +01:00
Github Actions b549bbf46b [CI Skip] release/beta 3.7.4-4
skip-checks: true
2021-02-06 07:58:57 +00:00
Jaco Greeff 1e87f58f36 Allow extensions on typesBundle (#3142)
* Allow extensions on typesBundle

* User extension take precedence
2021-02-06 08:49:11 +01:00
Github Actions f643426067 [CI Skip] release/beta 3.7.4-3
skip-checks: true
2021-02-05 21:12:04 +00:00
Jaco Greeff 94d26c76ec Check for autoConnectMs on reconnect (#3151)
* Check for autoConnectMs on reconnect

* Update packages/rpc-provider/src/ws/index.ts
2021-02-05 22:03:31 +01:00
Github Actions 8fe262a712 [CI Skip] release/beta 3.7.4-2
skip-checks: true
2021-02-05 15:55:13 +00:00
Jake Naviasky 122ee968cb Add eth filter RPC endpoints and FilterChanges type. (#3150) 2021-02-05 16:45:31 +01:00
Github Actions d2ff350db9 [CI Skip] release/beta 3.7.4-1
skip-checks: true
2021-02-05 07:34:46 +00:00
Nantian 9100aabbac fix signedExtensions type (#3148) 2021-02-05 08:25:17 +01:00
Github Actions 1e73f69253 [CI Skip] release/beta 3.7.4-0
skip-checks: true
2021-02-04 16:16:08 +00:00
Jaco Greeff 7153cb4158 Extend ProxyType with CancelProxy (#3147) 2021-02-04 17:05:56 +01:00
Github Actions 999dc6f8a5 [CI Skip] release/stable 3.7.3
skip-checks: true
2021-02-02 16:37:56 +00:00
Jaco Greeff 724574afe7 3.7.3 (w/ Polkadot 27 upgrade blocks) (#3139) 2021-02-02 17:29:43 +01:00
Github Actions 0352a30b6b [CI Skip] release/beta 3.7.3-1
skip-checks: true
2021-02-02 10:14:04 +00:00
Jaco Greeff 41b4cd5c55 Adjust known-types to use @polkadot/networks (#3138) 2021-02-02 11:06:52 +01:00
Github Actions 89f16f3123 [CI Skip] release/beta 3.7.3-0
skip-checks: true
2021-02-02 09:22:19 +00:00
Jaco Greeff 261a4eede3 Add 26 checkpoint for Polkadot (#3137) 2021-02-02 10:15:17 +01:00
Github Actions f623b382f7 [CI Skip] release/stable 3.7.2
skip-checks: true
2021-02-02 07:50:56 +00:00
Jaco Greeff 51537c619a Adjust Keys fro 28 (#3135)
* Adjust Keys fro 28

* 3.7.2
2021-02-02 08:41:24 +01:00
Github Actions 3df943572f [CI Skip] release/beta 3.7.2-0
skip-checks: true
2021-02-01 20:22:53 +00:00
Jaco Greeff aa10804f6f Westend upgrade block for 48 (#3134) 2021-02-01 21:13:58 +01:00
74 changed files with 1952 additions and 1357 deletions
+2
View File
@@ -13,3 +13,5 @@
3.6.2 3.6.2
3.6.3 3.6.3
3.6.4 3.6.4
3.7.2
3.7.3
+50
View File
@@ -1,5 +1,55 @@
# CHANGELOG # CHANGELOG
## 3.9.1 Feb 14, 2021
Upgrade priority: Low.
- **Important** The `Result<T, E>` has been updated in the generation and the base types to follow the Rust version 100%. This means `{as, is}Error` is now available as `{as, is}Err` on the `Result` type. The older versions can still be used, but the `*Error` interfaces are now marked as deprecated.
Changes:
- Adjust `Result<T, E>` interface to be 100% compatible with the Rust version
- Add the `2028` upgrade to the known upgrades (optimizing certain `.at` queries)
- Adjust council derives to cater for latest Substrate & Polkadot
- Adjust Rococo know type definitions to cater for the latest update
- Update types for latest Polkadot/Substrate
- Add generic arguments for TypeScript users to `.entries/.keys` to deal with the key typings
## 3.8.1 Feb 7, 2021
Upgrade priority: Low. Recommended for users of the latest Substrate master, especially using contracts.
- **Important** The `api-contract` `Code` now supports deploying the code and a contract in on operation. This aligns with the latest Substrate where code cannot be uploaded with a contract. The `createBlueprint` is therefore deprecated, use `code.tx.<constructor>(...)` to deploy code. (Compatible with both old and new versions of Substrate)
Contributed:
- Add support for latest Frontier RPCs (Thanks to https://github.com/jnaviask)
- Fix user-supplied signed extensions type signature (Thanks to https://github.com/ntduan)
Changes:
- Expand `api-contract` to allow for `Code` to deploy contract alongside code. `createBlueprint` is now deprecated, replaced by `createContract` or the preferred `code.tx.<constructor>`, which uploads and deploys the code in one operation. This aligns with the current Substrate master contracts implementation.
- Allow for signed extensions to be supplied inside type bundles
- Ensure that the auto-connect state is checked on auto-connections (respecting disconnect)
- Added `CancelProxy` to `ProxyTypes on Polkadot, Kusama & Westend
- Updated to latest Substrate metadata
## 3.7.3 Feb 2, 2021
Changes:
- Added Polkadot upgrade block for runtime 27 (known checkpoint optimization)
## 3.7.2 Feb 2, 2021
Changes:
- Adjusted the `Keys` type for the 28 runtime on Kusama, Polkadot & Westend
## 3.7.1 Feb 1, 2021 ## 3.7.1 Feb 1, 2021
Upgrade priority: Low. However recommended for current Substrate master, Polkadot and Rococo users and those wishing to support the upcoming Polkadot 28 runtime with the new `MultiAddress`. Upgrade priority: Low. However recommended for current Substrate master, Polkadot and Rococo users and those wishing to support the upcoming Polkadot 28 runtime with the new `MultiAddress`.
+5 -5
View File
@@ -25,14 +25,14 @@
"test:watch": "polkadot-dev-run-test --watch" "test:watch": "polkadot-dev-run-test --watch"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.12.10", "@babel/core": "^7.12.13",
"@babel/register": "^7.12.10", "@babel/register": "^7.12.13",
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/dev": "^0.61.24", "@polkadot/dev": "^0.61.25",
"@polkadot/ts": "^0.3.59", "@polkadot/ts": "^0.3.59",
"@polkadot/typegen": "workspace:packages/typegen", "@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^26.0.20", "@types/jest": "^26.0.20",
"copyfiles": "^2.4.1" "copyfiles": "^2.4.1"
}, },
"version": "3.7.1" "version": "3.9.1"
} }
+6 -6
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api-contract", "name": "@polkadot/api-contract",
"version": "3.7.1", "version": "3.9.1",
"description": "Interfaces for interacting with contracts and contract ABIs", "description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": false,
@@ -12,11 +12,11 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/api": "3.7.1", "@polkadot/api": "3.9.1",
"@polkadot/types": "3.7.1", "@polkadot/types": "3.9.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.6.2",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^5.6.2",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
} }
} }
+1 -1
View File
@@ -26,6 +26,6 @@ export abstract class Base<ApiType extends ApiTypes> {
this.registry = this.abi.registry; this.registry = this.abi.registry;
this._decorateMethod = decorateMethod; this._decorateMethod = decorateMethod;
assert(this.api.rx.tx.contracts && this.api.rx.tx.contracts.putCode, 'You need to connect to a node with the contracts module, the metadata does not enable api.tx.contracts on this instance'); assert(api.rx.tx.contracts?.instantiate, 'You need to connect to a node with the contracts module, the metadata does not enable api.tx.contracts on this instance');
} }
} }
+7 -34
View File
@@ -6,44 +6,17 @@ import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import type { AccountId, EventRecord, Hash } from '@polkadot/types/interfaces'; import type { AccountId, EventRecord, Hash } from '@polkadot/types/interfaces';
import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types'; import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types'; import type { AbiConstructor, BlueprintOptions } from '../types';
import type { BlueprintDeploy, ContractGeneric, MapConstructorExec } from './types'; import type { ContractGeneric, MapConstructorExec } from './types';
import BN from 'bn.js';
import { SubmittableResult } from '@polkadot/api'; import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base'; import { ApiBase } from '@polkadot/api/base';
import { Bytes } from '@polkadot/types'; import { isUndefined, stringCamelCase } from '@polkadot/util';
import { compactAddLength, isUndefined, stringCamelCase, u8aToU8a } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
import { Abi } from '../Abi'; import { Abi } from '../Abi';
import { applyOnEvent, extractOptions, isOptions } from '../util'; import { applyOnEvent } from '../util';
import { Base } from './Base'; import { Base } from './Base';
import { Contract } from './Contract'; import { Contract } from './Contract';
import { createBluePrintTx, createBluePrintWithId, EMPTY_SALT, encodeSalt } from './util';
const EMPTY_SALT = new Uint8Array();
function createTx <ApiType extends ApiTypes> (fn: (options: BlueprintOptions, params: CodecArg[]) => SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>>): BlueprintDeploy<ApiType> {
return (options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> =>
isOptions(options)
? fn(options, params)
: fn(...extractOptions(options, params));
}
function createWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]) => T): ContractGeneric<BlueprintOptions, T> {
return (constructorOrId: AbiConstructor | string | number, options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): T =>
isOptions(options)
? fn(constructorOrId, options, params)
: fn(constructorOrId, ...extractOptions(options, params));
}
function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()) {
return salt instanceof Bytes
? salt
: salt && salt.length
? compactAddLength(u8aToU8a(salt))
: EMPTY_SALT;
}
export class BlueprintSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult { export class BlueprintSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly contract?: Contract<ApiType>; public readonly contract?: Contract<ApiType>;
@@ -73,13 +46,13 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
super(api, abi, decorateMethod); super(api, abi, decorateMethod);
this.codeHash = this.registry.createType('Hash', codeHash); this.codeHash = this.registry.createType('Hash', codeHash);
this.createContract = createWithId(this.#deploy); this.createContract = createBluePrintWithId(this.#deploy);
this.abi.constructors.forEach((c): void => { this.abi.constructors.forEach((c): void => {
const messageName = stringCamelCase(c.identifier); const messageName = stringCamelCase(c.identifier);
if (isUndefined(this.#tx[messageName])) { if (isUndefined(this.#tx[messageName])) {
this.#tx[messageName] = createTx((o, p) => this.#deploy(c, o, p)); this.#tx[messageName] = createBluePrintTx((o, p) => this.#deploy(c, o, p));
} }
}); });
} }
@@ -99,7 +72,7 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
: this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encoded); : this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encoded);
return tx.withResultTransform((result: ISubmittableResult) => return tx.withResultTransform((result: ISubmittableResult) =>
new BlueprintSubmittableResult(result, applyOnEvent(result, 'Instantiated', ([record]: EventRecord[]) => new BlueprintSubmittableResult(result, applyOnEvent(result, ['Instantiated'], ([record]: EventRecord[]) =>
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod) new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
)) ))
); );
+74 -4
View File
@@ -4,30 +4,39 @@
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types'; import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes, DecorateMethod } from '@polkadot/api/types'; import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import type { EventRecord, Hash } from '@polkadot/types/interfaces'; import type { EventRecord, Hash } from '@polkadot/types/interfaces';
import type { AnyJson, ISubmittableResult } from '@polkadot/types/types'; import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types';
import type { MapConstructorExec } from './types';
import { SubmittableResult } from '@polkadot/api'; import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base'; import { ApiBase } from '@polkadot/api/base';
import { assert, compactAddLength, isWasm, u8aToU8a } from '@polkadot/util'; import { assert, compactAddLength, isFunction, isUndefined, isWasm, stringCamelCase, u8aToU8a } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
import { Abi } from '../Abi'; import { Abi } from '../Abi';
import { applyOnEvent } from '../util'; import { applyOnEvent } from '../util';
import { Base } from './Base'; import { Base } from './Base';
import { Blueprint } from './Blueprint'; import { Blueprint } from './Blueprint';
import { Contract } from './Contract';
import { createBluePrintTx, EMPTY_SALT, encodeSalt } from './util';
export class CodeSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult { export class CodeSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly blueprint?: Blueprint<ApiType>; public readonly blueprint?: Blueprint<ApiType>;
public readonly contract?: Contract<ApiType>;
constructor (result: ISubmittableResult, blueprint?: Blueprint<ApiType>) { constructor (result: ISubmittableResult, blueprint?: Blueprint<ApiType>, contract?: Contract<ApiType>) {
super(result); super(result);
this.blueprint = blueprint; this.blueprint = blueprint;
this.contract = contract;
} }
} }
export class Code<ApiType extends ApiTypes> extends Base<ApiType> { export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
public readonly code: Uint8Array; public readonly code: Uint8Array;
readonly #tx: MapConstructorExec<ApiType> = {};
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined, decorateMethod: DecorateMethod<ApiType>) { constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined, decorateMethod: DecorateMethod<ApiType>) {
super(api, abi, decorateMethod); super(api, abi, decorateMethod);
@@ -36,18 +45,79 @@ export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
: u8aToU8a(wasm); : u8aToU8a(wasm);
assert(isWasm(this.code), 'No WASM code provided'); assert(isWasm(this.code), 'No WASM code provided');
this.abi.constructors.forEach((c): void => {
const messageName = stringCamelCase(c.identifier);
if (isUndefined(this.#tx[messageName])) {
this.#tx[messageName] = createBluePrintTx((o, p) => this.#instantiate(c, o, p));
}
});
} }
/** /**
* @description Deploy the code bundle, creating a Blueprint. * @description Deploy the code bundle, creating a Blueprint.
* @deprecated Use the `code.tx.<constructor>(...) format to put code and deploy
*/ */
public createBlueprint (): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> { public createBlueprint (): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> {
return this.api.tx.contracts return this.api.tx.contracts
.putCode(compactAddLength(this.code)) .putCode(compactAddLength(this.code))
.withResultTransform((result: ISubmittableResult) => .withResultTransform((result: ISubmittableResult) =>
new CodeSubmittableResult(result, applyOnEvent(result, 'CodeStored', ([record]: EventRecord[]) => new CodeSubmittableResult(result, applyOnEvent(result, ['CodeStored'], ([record]: EventRecord[]) =>
new Blueprint<ApiType>(this.api, this.abi, record.event.data[0] as Hash, this._decorateMethod) new Blueprint<ApiType>(this.api, this.abi, record.event.data[0] as Hash, this._decorateMethod)
)) ))
); );
} }
/**
* @description Deploy the code bundle and the contract, creating a Blueprint.
* @deprecated Use the `code.tx.<constructor>(...) format to put code and deploy
*/
public createContract (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> {
return this.#instantiate(constructorOrId, options, params);
}
public get tx (): MapConstructorExec<ApiType> {
return this.#tx;
}
#instantiate = (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
return isFunction(this.api.tx.contracts.instantiateWithCode)
? this.#instantiateSingle(constructorOrId, options, params)
: this.#instantiateBatch(constructorOrId, options, params);
}
#instantiateSingle = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
return this.api.tx.contracts
.instantiateWithCode(value, gasLimit, compactAddLength(this.code), this.abi.findConstructor(constructorOrId).toU8a(params), encodeSalt(salt))
.withResultTransform(this.#transformEvents);
}
#instantiateBatch = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
const encodedSalt = encodeSalt(salt);
const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5;
const encoded = this.abi.findConstructor(constructorOrId).toU8a(params, withSalt ? EMPTY_SALT : encodedSalt);
const codeHash = blake2AsU8a(this.code);
return this.api.tx.utility.batch([
this.api.tx.contracts.putCode(compactAddLength(this.code)),
withSalt
? this.api.tx.contracts.instantiate(value, gasLimit, codeHash, encoded, encodedSalt)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old style with salt included in the params itself
: this.api.tx.contracts.instantiate(value, gasLimit, codeHash, encoded)
]).withResultTransform(this.#transformEvents);
}
#transformEvents = (result: ISubmittableResult): CodeSubmittableResult<ApiType> => {
return new CodeSubmittableResult(result, ...(applyOnEvent(result, ['CodeStored', 'Instantiated'], (records: EventRecord[]) =>
records.reduce(([blueprint, contract], { event }): [Blueprint<ApiType>?, Contract<ApiType>?] =>
this.api.events.contracts.Instantiated.is(event)
? [blueprint, new Contract<ApiType>(this.api, this.abi, event.data[1], this._decorateMethod)]
: this.api.events.contracts.CodeStored.is(event)
? [new Blueprint<ApiType>(this.api, this.abi, event.data[0], this._decorateMethod), contract]
: [blueprint, contract],
[] as [Blueprint<ApiType>?, Contract<ApiType>?])
) || []));
}
} }
+1 -1
View File
@@ -156,7 +156,7 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
return this.api.tx.contracts return this.api.tx.contracts
.call(this.address, value, this.#getGas(gasLimit), this.abi.findMessage(messageOrId).toU8a(params)) .call(this.address, value, this.#getGas(gasLimit), this.abi.findMessage(messageOrId).toU8a(params))
.withResultTransform((result: ISubmittableResult) => .withResultTransform((result: ISubmittableResult) =>
new ContractSubmittableResult(result, applyOnEvent(result, 'ContractExecution', (records: EventRecord[]) => new ContractSubmittableResult(result, applyOnEvent(result, ['ContractExecution'], (records: EventRecord[]) =>
records records
.map(({ event: { data: [, data] } }): DecodedEvent | null => { .map(({ event: { data: [, data] } }): DecodedEvent | null => {
try { try {
+3
View File
@@ -11,6 +11,9 @@ export const mockApi = {
rx: { rx: {
tx: { tx: {
contracts: { contracts: {
instantiate: (): never => {
throw new Error('mock');
},
putCode: (): never => { putCode: (): never => {
throw new Error('mock'); throw new Error('mock');
} }
+41
View File
@@ -0,0 +1,41 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { SubmittableResult } from '@polkadot/api';
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes } from '@polkadot/api/types';
import type { CodecArg } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types';
import type { BlueprintDeploy, ContractGeneric } from './types';
import BN from 'bn.js';
import { Bytes } from '@polkadot/types';
import { compactAddLength, u8aToU8a } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
import { extractOptions, isOptions } from '../util';
export const EMPTY_SALT = new Uint8Array();
export function createBluePrintTx <ApiType extends ApiTypes, R extends SubmittableResult> (fn: (options: BlueprintOptions, params: CodecArg[]) => SubmittableExtrinsic<ApiType, R>): BlueprintDeploy<ApiType> {
return (options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, R> =>
isOptions(options)
? fn(options, params)
: fn(...extractOptions(options, params));
}
export function createBluePrintWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]) => T): ContractGeneric<BlueprintOptions, T> {
return (constructorOrId: AbiConstructor | string | number, options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): T =>
isOptions(options)
? fn(constructorOrId, options, params)
: fn(constructorOrId, ...extractOptions(options, params));
}
export function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()): Uint8Array {
return salt instanceof Bytes
? salt
: salt && salt.length
? compactAddLength(u8aToU8a(salt))
: EMPTY_SALT;
}
+2 -2
View File
@@ -20,9 +20,9 @@ export function formatData (registry: Registry, data: Raw, { type }: TypeDef): C
return createTypeUnsafe(registry, type, [data], { isPedantic: true }); return createTypeUnsafe(registry, type, [data], { isPedantic: true });
} }
export function applyOnEvent <T> (result: SubmittableResult, type: ContractEvents, fn: (records: EventRecord[]) => T): T | undefined { export function applyOnEvent <T> (result: SubmittableResult, types: ContractEvents[], fn: (records: EventRecord[]) => T): T | undefined {
if (result.isInBlock || result.isFinalized) { if (result.isInBlock || result.isFinalized) {
const records = result.filterRecords('contracts', type); const records = result.filterRecords('contracts', types);
if (records.length) { if (records.length) {
return fn(records); return fn(records);
+10 -10
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api-derive", "name": "@polkadot/api-derive",
"version": "3.7.1", "version": "3.9.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.", "description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": false,
@@ -12,17 +12,17 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/api": "3.7.1", "@polkadot/api": "3.9.1",
"@polkadot/rpc-core": "3.7.1", "@polkadot/rpc-core": "3.9.1",
"@polkadot/types": "3.7.1", "@polkadot/types": "3.9.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.6.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.6.2",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^5.6.2",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1", "@polkadot/keyring": "^5.6.2",
"@polkadot/rpc-provider": "3.7.1" "@polkadot/rpc-provider": "3.9.1"
} }
} }
+4 -4
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { DeriveBounties, DeriveCollectiveProposal } from '@polkadot/api-derive/types'; import type { DeriveBounties, DeriveCollectiveProposal } from '@polkadot/api-derive/types';
import type { Bytes, Option, StorageKey } from '@polkadot/types'; import type { Bytes, Option } from '@polkadot/types';
import type { Bounty, BountyIndex, ProposalIndex } from '@polkadot/types/interfaces'; import type { Bounty, BountyIndex, ProposalIndex } from '@polkadot/types/interfaces';
import { memo } from '@polkadot/api-derive/util'; import { memo } from '@polkadot/api-derive/util';
@@ -32,7 +32,7 @@ function parseResult ([maybeBounties, maybeDescriptions, ids, bountyProposals]:
} }
export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveBounties> { export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveBounties> {
const bountyBase = api.query.bounties ? api.query.bounties : api.query.treasury; const bountyBase = api.query.bounties || api.query.treasury;
return memo(instanceId, (): Observable<DeriveBounties> => return memo(instanceId, (): Observable<DeriveBounties> =>
combineLatest([ combineLatest([
@@ -41,12 +41,12 @@ export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observ
]).pipe( ]).pipe(
switchMap(() => switchMap(() =>
combineLatest([ combineLatest([
bountyBase.bounties.keys(), bountyBase.bounties.keys<[BountyIndex]>(),
api.derive.council ? api.derive.council.proposals() : of([]) api.derive.council ? api.derive.council.proposals() : of([])
]) ])
), ),
switchMap(([keys, proposals]): Observable<Result> => { switchMap(([keys, proposals]): Observable<Result> => {
const ids = (keys as StorageKey<[BountyIndex]>[]).map(({ args: [id] }) => id); const ids = keys.map(({ args: [id] }) => id);
return combineLatest([ return combineLatest([
bountyBase.bounties.multi<Option<Bounty>>(ids), bountyBase.bounties.multi<Option<Bounty>>(ids),
+19 -9
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { Vec } from '@polkadot/types'; import type { Vec } from '@polkadot/types';
import type { AccountId, Balance } from '@polkadot/types/interfaces'; import type { AccountId, Balance, Voter } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types'; import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveCouncilVote, DeriveCouncilVotes } from '../types'; import type { DeriveCouncilVote, DeriveCouncilVotes } from '../types';
@@ -13,18 +13,25 @@ import { map } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
// Voter is current tuple is 2.x-era
type VoteEntry = Voter | ITuple<[Balance, Vec<AccountId>]>;
function isVoter (value: VoteEntry): value is Voter {
return !Array.isArray(value);
}
function retrieveStakeOf (api: ApiInterfaceRx): Observable<[AccountId, Balance][]> { function retrieveStakeOf (api: ApiInterfaceRx): Observable<[AccountId, Balance][]> {
return (api.query.electionsPhragmen || api.query.elections).stakeOf.entries<Balance>().pipe( return (api.query.electionsPhragmen || api.query.elections).stakeOf.entries<Balance, [AccountId]>().pipe(
map((entries) => map((entries) =>
entries.map(([key, stake]) => [key.args[0] as AccountId, stake]) entries.map(([{ args: [accountId] }, stake]) => [accountId, stake])
) )
); );
} }
function retrieveVoteOf (api: ApiInterfaceRx): Observable<[AccountId, AccountId[]][]> { function retrieveVoteOf (api: ApiInterfaceRx): Observable<[AccountId, AccountId[]][]> {
return (api.query.electionsPhragmen || api.query.elections).votesOf.entries<Vec<AccountId>>().pipe( return (api.query.electionsPhragmen || api.query.elections).votesOf.entries<Vec<AccountId>, [AccountId]>().pipe(
map((entries) => map((entries) =>
entries.map(([key, votes]) => [key.args[0] as AccountId, votes]) entries.map(([{ args: [accountId] }, votes]) => [accountId, votes])
) )
); );
} }
@@ -56,11 +63,14 @@ function retrievePrev (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> { function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
const elections = (api.query.electionsPhragmen || api.query.elections); const elections = (api.query.electionsPhragmen || api.query.elections);
return elections.voting.entries<ITuple<[Balance, Vec<AccountId>]>>().pipe( return elections.voting.entries<VoteEntry, [AccountId]>().pipe(
map((entries): DeriveCouncilVotes => map((entries): DeriveCouncilVotes =>
entries.map(([key, [stake, votes]]): [AccountId, DeriveCouncilVote] => entries.map(([{ args: [accountId] }, value]): [AccountId, DeriveCouncilVote] => [
[key.args[0] as AccountId, { stake, votes }] accountId,
) isVoter(value)
? { stake: value.stake, votes: value.votes }
: { stake: value[0], votes: value[1] }
])
) )
); );
} }
@@ -51,7 +51,7 @@ function schedulerEntries (api: ApiInterfaceRx): Observable<[BlockNumber[], Opti
api.query.scheduler.agenda.keys() api.query.scheduler.agenda.keys()
), ),
switchMap((keys) => { switchMap((keys) => {
const blockNumbers = keys.map((key) => key.args[0]); const blockNumbers = keys.map(({ args: [blockNumber] }) => blockNumber);
return combineLatest([ return combineLatest([
of(blockNumbers), of(blockNumbers),
@@ -67,9 +67,9 @@ function extractVotes (mapped: [AccountId, Voting][], referendumId: BN): DeriveR
} }
function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> { function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> {
return api.query.democracy.votingOf.entries<Voting>().pipe( return api.query.democracy.votingOf.entries<Voting, [AccountId]>().pipe(
map((allVoting): DeriveReferendumVote[] => { map((allVoting): DeriveReferendumVote[] => {
const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0], voting]); const mapped = allVoting.map(([{ args: [accountId] }, voting]): [AccountId, Voting] => [accountId, voting]);
const votes = extractVotes(mapped, referendumId); const votes = extractVotes(mapped, referendumId);
const delegations = mapped const delegations = mapped
.filter(([, voting]) => voting.isDelegating) .filter(([, voting]) => voting.isDelegating)
+18 -5
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { u32, Vec } from '@polkadot/types'; import type { u32, Vec } from '@polkadot/types';
import type { AccountId, Balance, BlockNumber } from '@polkadot/types/interfaces'; import type { AccountId, Balance, BlockNumber, SeatHolder } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types'; import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveElectionsInfo } from './types'; import type { DeriveElectionsInfo } from './types';
@@ -12,14 +12,27 @@ import { map } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
function sortAccounts ([, balanceA]: ITuple<[AccountId, Balance]>, [, balanceB]: ITuple<[AccountId, Balance]>): number { // SeatHolder is current tuple is 2.x-era Substrate
type Member = SeatHolder | ITuple<[AccountId, Balance]>;
function isSeatHolder (value: Member): value is SeatHolder {
return !Array.isArray(value);
}
function getAccountTuple (value: Member): [AccountId, Balance] {
return isSeatHolder(value)
? [value.who, value.stake]
: value;
}
function sortAccounts ([, balanceA]: [AccountId, Balance], [, balanceB]: [AccountId, Balance]): number {
return balanceB.cmp(balanceA); return balanceB.cmp(balanceA);
} }
function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> { function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections'; const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
return api.queryMulti<[Vec<AccountId>, Vec<AccountId>, Vec<ITuple<[AccountId, Balance]>>, Vec<ITuple<[AccountId, Balance]>>]>([ return api.queryMulti<[Vec<AccountId>, Vec<AccountId>, Vec<Member>, Vec<Member>]>([
api.query.council.members, api.query.council.members,
api.query[section].candidates, api.query[section].candidates,
api.query[section].members, api.query[section].members,
@@ -32,9 +45,9 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
desiredRunnersUp: api.consts[section].desiredRunnersUp as u32, desiredRunnersUp: api.consts[section].desiredRunnersUp as u32,
desiredSeats: api.consts[section].desiredMembers as u32, desiredSeats: api.consts[section].desiredMembers as u32,
members: members.length members: members.length
? members.sort(sortAccounts) ? members.map(getAccountTuple).sort(sortAccounts)
: councilMembers.map((accountId): [AccountId, Balance] => [accountId, api.registry.createType('Balance')]), : councilMembers.map((accountId): [AccountId, Balance] => [accountId, api.registry.createType('Balance')]),
runnersUp: runnersUp.sort(sortAccounts), runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts),
termDuration: api.consts[section].termDuration as BlockNumber, termDuration: api.consts[section].termDuration as BlockNumber,
votingBond: api.consts[section].votingBond as Balance votingBond: api.consts[section].votingBond as Balance
})) }))
@@ -10,7 +10,7 @@ import type { DeriveStakingQuery } from './types';
import BN from 'bn.js'; import BN from 'bn.js';
import { isFunction } from '@polkadot/util'; import { BN_BILLION, BN_ZERO, isFunction } from '@polkadot/util';
import { combineLatest, of } from '@polkadot/x-rxjs'; import { combineLatest, of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators'; import { map, switchMap } from '@polkadot/x-rxjs/operators';
@@ -18,29 +18,27 @@ import { memo } from '../util';
type ErasResult = [{ unwrapOr: (value: BN) => BN }, DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]]; type ErasResult = [{ unwrapOr: (value: BN) => BN }, DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]];
const ZERO = new BN(0);
const MIN_ONE = new BN(-1); const MIN_ONE = new BN(-1);
const COMM_DIV = new BN(1_000_000_000);
function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] { function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] {
return exposures.map(({ era, isEmpty, isValidator, nominating, validators: eraValidators }): DeriveStakerReward => { return exposures.map(({ era, isEmpty, isValidator, nominating, validators: eraValidators }): DeriveStakerReward => {
const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: ZERO, validators: {} }; const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: BN_ZERO, validators: {} };
const { eraReward } = erasRewards.find((r) => r.era.eq(era)) || { eraReward: api.registry.createType('Balance') }; const { eraReward } = erasRewards.find((r) => r.era.eq(era)) || { eraReward: api.registry.createType('Balance') };
const { validators: allValPrefs } = erasPrefs.find((p) => p.era.eq(era)) || { validators: {} as DeriveEraValPrefs }; const { validators: allValPrefs } = erasPrefs.find((p) => p.era.eq(era)) || { validators: {} as DeriveEraValPrefs };
const validators: Record<string, DeriveStakerRewardValidator> = {}; const validators: Record<string, DeriveStakerRewardValidator> = {};
const stakerId = stashId.toString(); const stakerId = stashId.toString();
Object.entries(eraValidators).forEach(([validatorId, exposure]): void => { Object.entries(eraValidators).forEach(([validatorId, exposure]): void => {
const valPoints = allValPoints[validatorId] || ZERO; const valPoints = allValPoints[validatorId] || BN_ZERO;
const valComm = allValPrefs[validatorId]?.commission.unwrap() || ZERO; const valComm = allValPrefs[validatorId]?.commission.unwrap() || BN_ZERO;
const expTotal = exposure.total.unwrap(); const expTotal = exposure.total.unwrap();
let avail = ZERO; let avail = BN_ZERO;
let value: BN | undefined; let value: BN | undefined;
if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) { if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) {
avail = eraReward.mul(valPoints).div(eraPoints); avail = eraReward.mul(valPoints).div(eraPoints);
const valCut = valComm.mul(avail).div(COMM_DIV); const valCut = valComm.mul(avail).div(BN_BILLION);
let staked: BN; let staked: BN;
if (validatorId === stakerId) { if (validatorId === stakerId) {
@@ -50,10 +48,10 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, e
staked = stakerExp staked = stakerExp
? stakerExp.value.unwrap() ? stakerExp.value.unwrap()
: ZERO; : BN_ZERO;
} }
value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : ZERO); value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : BN_ZERO);
} }
validators[validatorId] = { validators[validatorId] = {
@@ -181,7 +179,7 @@ export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accou
return withActive return withActive
? of(rewards) ? of(rewards)
: filterRewards(api, eras, { migrateEra: erasResult[0].unwrapOr(ZERO), rewards, stakingLedger }); : filterRewards(api, eras, { migrateEra: erasResult[0].unwrapOr(BN_ZERO), rewards, stakingLedger });
}) })
) )
); );
+1 -1
View File
@@ -15,7 +15,7 @@ import { memo } from '../util';
export function stashes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> { export function stashes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo(instanceId, (): Observable<AccountId[]> => return memo(instanceId, (): Observable<AccountId[]> =>
api.query.staking.validators.keys().pipe( api.query.staking.validators.keys().pipe(
map((keys) => keys.map((key) => key.args[0]).filter((a) => a)) map((keys) => keys.map(({ args: [validatorId] }) => validatorId).filter((a) => a))
) )
); );
} }
@@ -18,7 +18,7 @@ export function nextElected (instanceId: string, api: ApiInterfaceRx): () => Obs
// only populate for next era in the last session, so track both here - entries are not // only populate for next era in the last session, so track both here - entries are not
// subscriptions, so we need a trigger - currentIndex acts as that trigger to refresh // subscriptions, so we need a trigger - currentIndex acts as that trigger to refresh
switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)), switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)),
map((keys) => keys.map((key) => key.args[1])) map((keys) => keys.map(({ args: [, accountId] }) => accountId))
) )
: api.query.staking.currentElected<AccountId[]>() : api.query.staking.currentElected<AccountId[]>()
); );
+12 -12
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api", "name": "@polkadot/api",
"version": "3.7.1", "version": "3.9.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC", "description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js", "main": "index.js",
"sideEffects": [ "sideEffects": [
@@ -15,17 +15,17 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/api-derive": "3.7.1", "@polkadot/api-derive": "3.9.1",
"@polkadot/keyring": "^5.5.1", "@polkadot/keyring": "^5.6.2",
"@polkadot/metadata": "3.7.1", "@polkadot/metadata": "3.9.1",
"@polkadot/rpc-core": "3.7.1", "@polkadot/rpc-core": "3.9.1",
"@polkadot/rpc-provider": "3.7.1", "@polkadot/rpc-provider": "3.9.1",
"@polkadot/types": "3.7.1", "@polkadot/types": "3.9.1",
"@polkadot/types-known": "3.7.1", "@polkadot/types-known": "3.9.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.6.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.6.2",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^5.6.2",
"bn.js": "^4.11.9", "bn.js": "^4.11.9",
"eventemitter3": "^4.0.7" "eventemitter3": "^4.0.7"
} }
+6 -1
View File
@@ -184,7 +184,8 @@ declare module '@polkadot/api/types/errors' {
**/ **/
CodeNotFound: AugmentedError<ApiType>; CodeNotFound: AugmentedError<ApiType>;
/** /**
* The code supplied to `put_code` exceeds the limit specified in the current schedule. * The code supplied to `instantiate_with_code` exceeds the limit specified in the
* current schedule.
**/ **/
CodeTooLarge: AugmentedError<ApiType>; CodeTooLarge: AugmentedError<ApiType>;
/** /**
@@ -210,6 +211,10 @@ declare module '@polkadot/api/types/errors' {
* Trying again during another block is the only way to resolve this issue. * Trying again during another block is the only way to resolve this issue.
**/ **/
DeletionQueueFull: AugmentedError<ApiType>; DeletionQueueFull: AugmentedError<ApiType>;
/**
* A contract with the same AccountId already exists.
**/
DuplicateContract: AugmentedError<ApiType>;
/** /**
* The topics passed to `seal_deposit_events` contains at least one duplicate. * The topics passed to `seal_deposit_events` contains at least one duplicate.
**/ **/
+45 -19
View File
@@ -160,45 +160,71 @@ declare module '@polkadot/api/types/events' {
contracts: { contracts: {
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
/** /**
* Code with the specified hash has been stored. * A code with the specified hash was removed.
* \[code_hash\] * \[code_hash\]
*
* This happens when the last contract that uses this code hash was removed or evicted.
**/
CodeRemoved: AugmentedEvent<ApiType, [Hash]>;
/**
* Code with the specified hash has been stored. \[code_hash\]
**/ **/
CodeStored: AugmentedEvent<ApiType, [Hash]>; CodeStored: AugmentedEvent<ApiType, [Hash]>;
/** /**
* An event deposited upon execution of a contract from the account. * A custom event emitted by the contract.
* \[account, data\] * \[contract, data\]
**/
ContractExecution: AugmentedEvent<ApiType, [AccountId, Bytes]>;
/**
* Contract has been evicted and is now in tombstone state.
* \[contract, tombstone\]
* *
* # Params * # Params
* *
* - `contract`: `AccountId`: The account ID of the evicted contract. * - `contract`: The contract that emitted the event.
* - `tombstone`: `bool`: True if the evicted contract left behind a tombstone. * - `data`: Data supplied by the contract. Metadata generated during contract
* compilation is needed to decode it.
**/ **/
Evicted: AugmentedEvent<ApiType, [AccountId, bool]>; ContractEmitted: AugmentedEvent<ApiType, [AccountId, Bytes]>;
/** /**
* Contract deployed by address at the specified address. \[owner, contract\] * Contract has been evicted and is now in tombstone state. \[contract\]
**/
Evicted: AugmentedEvent<ApiType, [AccountId]>;
/**
* Contract deployed by address at the specified address. \[deployer, contract\]
**/ **/
Instantiated: AugmentedEvent<ApiType, [AccountId, AccountId]>; Instantiated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/** /**
* Restoration for a contract has been successful. * Restoration of a contract has been successful.
* \[donor, dest, code_hash, rent_allowance\] * \[restorer, dest, code_hash, rent_allowance\]
* *
* # Params * # Params
* *
* - `donor`: `AccountId`: Account ID of the restoring contract * - `restorer`: Account ID of the restoring contract.
* - `dest`: `AccountId`: Account ID of the restored contract * - `dest`: Account ID of the restored contract.
* - `code_hash`: `Hash`: Code hash of the restored contract * - `code_hash`: Code hash of the restored contract.
* - `rent_allowance: `Balance`: Rent allowance of the restored contract * - `rent_allowance`: Rent allowance of the restored contract.
**/ **/
Restored: AugmentedEvent<ApiType, [AccountId, AccountId, Hash, Balance]>; Restored: AugmentedEvent<ApiType, [AccountId, AccountId, Hash, Balance]>;
/** /**
* Triggered when the current \[schedule\] is updated. * Triggered when the current schedule is updated.
* \[version\]
*
* # Params
*
* - `version`: The version of the newly set schedule.
**/ **/
ScheduleUpdated: AugmentedEvent<ApiType, [u32]>; ScheduleUpdated: AugmentedEvent<ApiType, [u32]>;
/**
* Contract has been terminated without leaving a tombstone.
* \[contract, beneficiary\]
*
* # Params
*
* - `contract`: The contract that was terminated.
* - `beneficiary`: The account that received the contracts remaining balance.
*
* # Note
*
* The only way for a contract to be removed without a tombstone and emitting
* this event is by calling `seal_terminate`.
**/
Terminated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
}; };
council: { council: {
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
+5 -5
View File
@@ -19,7 +19,7 @@ import type { CallIndex, LotteryConfig } from '@polkadot/types/interfaces/lotter
import type { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences'; import type { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy'; import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy';
import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery'; import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, ValidatorId } from '@polkadot/types/interfaces/runtime'; import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, Slot, ValidatorId } from '@polkadot/types/interfaces/runtime';
import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler'; import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session'; import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society'; import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
@@ -78,7 +78,7 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Current slot number. * Current slot number.
**/ **/
currentSlot: AugmentedQuery<ApiType, () => Observable<u64>, []> & QueryableStorageEntry<ApiType, []>; currentSlot: AugmentedQuery<ApiType, () => Observable<Slot>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Current epoch index. * Current epoch index.
**/ **/
@@ -87,7 +87,7 @@ declare module '@polkadot/api/types/storage' {
* The slot at which the first epoch actually started. This is 0 * The slot at which the first epoch actually started. This is 0
* until the first block of the chain. * until the first block of the chain.
**/ **/
genesisSlot: AugmentedQuery<ApiType, () => Observable<u64>, []> & QueryableStorageEntry<ApiType, []>; genesisSlot: AugmentedQuery<ApiType, () => Observable<Slot>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Temporary value (cleared at block finalization) which is `Some` * Temporary value (cleared at block finalization) which is `Some`
* if per-block initialization has already been called for current block. * if per-block initialization has already been called for current block.
@@ -148,7 +148,7 @@ declare module '@polkadot/api/types/storage' {
/** /**
* The balance of an account. * The balance of an account.
* *
* NOTE: This is only used in the case that this module is used to store balances. * NOTE: This is only used in the case that this pallet is used to store balances.
**/ **/
account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>; account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
/** /**
@@ -421,7 +421,7 @@ declare module '@polkadot/api/types/storage' {
imOnline: { imOnline: {
[key: string]: QueryableStorageEntry<ApiType>; [key: string]: QueryableStorageEntry<ApiType>;
/** /**
* For each session index, we keep a mapping of `T::ValidatorId` to the * For each session index, we keep a mapping of `ValidatorId<T>` to the
* number of blocks authored by the given authority. * number of blocks authored by the given authority.
**/ **/
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>, [SessionIndex, ValidatorId]> & QueryableStorageEntry<ApiType, [SessionIndex, ValidatorId]>; authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>, [SessionIndex, ValidatorId]> & QueryableStorageEntry<ApiType, [SessionIndex, ValidatorId]>;
+25 -1
View File
@@ -11,7 +11,7 @@ import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus'; import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts'; import type { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
import type { CreatedBlock } from '@polkadot/types/interfaces/engine'; import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthCallRequest, EthFilter, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth'; import type { EthAccount, EthCallRequest, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics'; import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa'; import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { StorageKind } from '@polkadot/types/interfaces/offchain'; import type { StorageKind } from '@polkadot/types/interfaces/offchain';
@@ -188,6 +188,14 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Returns the code at given address at given time (block number). * Returns the code at given address at given time (block number).
**/ **/
getCode: AugmentedRpc<(address: H160 | string | Uint8Array, number?: BlockNumber | AnyNumber | Uint8Array) => Observable<Bytes>>; getCode: AugmentedRpc<(address: H160 | string | Uint8Array, number?: BlockNumber | AnyNumber | Uint8Array) => Observable<Bytes>>;
/**
* Returns filter changes since last poll.
**/
getFilterChanges: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<EthFilterChanges>>;
/**
* Returns all logs matching given filter (in a range 'from' - 'to').
**/
getFilterLogs: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<Vec<EthLog>>>;
/** /**
* Returns logs matching given filter object. * Returns logs matching given filter object.
**/ **/
@@ -248,6 +256,18 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Returns true if client is actively mining new blocks. * Returns true if client is actively mining new blocks.
**/ **/
mining: AugmentedRpc<() => Observable<bool>>; mining: AugmentedRpc<() => Observable<bool>>;
/**
* Returns id of new block filter.
**/
newBlockFilter: AugmentedRpc<() => Observable<U256>>;
/**
* Returns id of new filter.
**/
newFilter: AugmentedRpc<(filter: EthFilter | { fromBlock?: any; toBlock?: any; blockHash?: any; address?: any; topics?: any } | string | Uint8Array) => Observable<U256>>;
/**
* Returns id of new block filter.
**/
newPendingTransactionFilter: AugmentedRpc<() => Observable<U256>>;
/** /**
* Returns protocol version encoded as a string (quotes are necessary). * Returns protocol version encoded as a string (quotes are necessary).
**/ **/
@@ -276,6 +296,10 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Returns an object with data about the sync status or false. * Returns an object with data about the sync status or false.
**/ **/
syncing: AugmentedRpc<() => Observable<EthSyncStatus>>; syncing: AugmentedRpc<() => Observable<EthSyncStatus>>;
/**
* Uninstalls filter.
**/
uninstallFilter: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<bool>>;
}; };
grandpa: { grandpa: {
/** /**
+27 -16
View File
@@ -396,7 +396,7 @@ declare module '@polkadot/api/types/submittable' {
* *
* 99% of the time you want [`transfer`] instead. * 99% of the time you want [`transfer`] instead.
* *
* [`transfer`]: struct.Module.html#method.transfer * [`transfer`]: struct.Pallet.html#method.transfer
* # <weight> * # <weight>
* - Cheaper than transfer because account cannot be killed. * - Cheaper than transfer because account cannot be killed.
* - Base Weight: 51.4 µs * - Base Weight: 51.4 µs
@@ -552,26 +552,37 @@ declare module '@polkadot/api/types/submittable' {
**/ **/
claimSurcharge: AugmentedSubmittable<(dest: AccountId | string | Uint8Array, auxSender: Option<AccountId> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId, Option<AccountId>]>; claimSurcharge: AugmentedSubmittable<(dest: AccountId | string | Uint8Array, auxSender: Option<AccountId> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId, Option<AccountId>]>;
/** /**
* Instantiates a new contract from the `code_hash` generated by `put_code`, * Instantiates a contract from a previously deployed wasm binary.
* optionally transferring some balance.
* *
* The supplied `salt` is used for contract address deriviation. See `fn contract_address`. * This function is identical to [`Self::instantiate_with_code`] but without the
* * code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary
* Instantiation is executed as follows: * must be supplied.
*
* - The destination address is computed based on the sender, code_hash and the salt.
* - The smart-contract account is created at the computed address.
* - The `ctor_code` is executed in the context of the newly-created account. Buffer returned
* after the execution is saved as the `code` of the account. That code will be invoked
* upon any call received by this account.
* - The contract is initialized.
**/ **/
instantiate: AugmentedSubmittable<(endowment: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, codeHash: CodeHash | string | Uint8Array, data: Bytes | string | Uint8Array, salt: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>, Compact<Gas>, CodeHash, Bytes, Bytes]>; instantiate: AugmentedSubmittable<(endowment: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, codeHash: CodeHash | string | Uint8Array, data: Bytes | string | Uint8Array, salt: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>, Compact<Gas>, CodeHash, Bytes, Bytes]>;
/** /**
* Stores the given binary Wasm code into the chain's storage and returns its `codehash`. * Instantiates a new contract from the supplied `code` optionally transferring
* You can instantiate contracts only with stored code. * some balance.
*
* This is the only function that can deploy new code to the chain.
*
* # Parameters
*
* * `endowment`: The balance to transfer from the `origin` to the newly created contract.
* * `gas_limit`: The gas limit enforced when executing the constructor.
* * `code`: The contract code to deploy in raw bytes.
* * `data`: The input data to pass to the contract constructor.
* * `salt`: Used for the address derivation. See [`Self::contract_address`].
*
* Instantiation is executed as follows:
*
* - The supplied `code` is instrumented, deployed, and a `code_hash` is created for that code.
* - If the `code_hash` already exists on the chain the underlying `code` will be shared.
* - The destination address is computed based on the sender, code_hash and the salt.
* - The smart-contract account is created at the computed address.
* - The `endowment` is transferred to the new account.
* - The `deploy` function is executed in the context of the newly-created account.
**/ **/
putCode: AugmentedSubmittable<(code: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes]>; instantiateWithCode: AugmentedSubmittable<(endowment: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, code: Bytes | string | Uint8Array, data: Bytes | string | Uint8Array, salt: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>, Compact<Gas>, Bytes, Bytes, Bytes]>;
/** /**
* Updates the schedule for metering contracts. * Updates the schedule for metering contracts.
* *
+5 -2
View File
@@ -13,7 +13,7 @@ import BN from 'bn.js';
import { Metadata } from '@polkadot/metadata'; import { Metadata } from '@polkadot/metadata';
import { TypeRegistry } from '@polkadot/types/create'; import { TypeRegistry } from '@polkadot/types/create';
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic'; import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic';
import { getSpecAlias, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known'; import { getSpecAlias, getSpecExtensions, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
import { assert, BN_ZERO, logger, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util'; import { assert, BN_ZERO, logger, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto'; import { cryptoWaitReady } from '@polkadot/util-crypto';
import { of } from '@polkadot/x-rxjs'; import { of } from '@polkadot/x-rxjs';
@@ -91,7 +91,10 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName); registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName);
} }
registry.setMetadata(metadata, undefined, this._options.signedExtensions); registry.setMetadata(metadata, undefined, {
...getSpecExtensions(registry, chain, version.specName),
...(this._options.signedExtensions || {})
});
return registry; return registry;
} }
+3 -3
View File
@@ -66,14 +66,14 @@ export class SubmittableResult implements ISubmittableResult {
/** /**
* @description Filters EventRecords for the specified method & section (there could be multiple) * @description Filters EventRecords for the specified method & section (there could be multiple)
*/ */
public filterRecords (section: string, method: string): EventRecord[] { public filterRecords (section: string, method: string | string[]): EventRecord[] {
return filterAndApply(this.events, section, [method], recordIdentity); return filterAndApply(this.events, section, Array.isArray(method) ? method : [method], recordIdentity);
} }
/** /**
* @description Finds an EventRecord for the specified method & section * @description Finds an EventRecord for the specified method & section
*/ */
public findRecord (section: string, method: string): EventRecord | undefined { public findRecord (section: string, method: string | string[]): EventRecord | undefined {
return this.filterRecords(section, method)[0]; return this.filterRecords(section, method)[0];
} }
+1 -1
View File
@@ -60,7 +60,7 @@ export interface ApiOptions extends RegisteredTypes {
/** /**
* @description Any chain-specific signed extensions that are now well-known * @description Any chain-specific signed extensions that are now well-known
*/ */
signedExtensions?: Record<string, ExtDef>; signedExtensions?: ExtDef;
/** /**
* @description An external signer which will be used to sign extrinsic when account passed in is not KeyringPair * @description An external signer which will be used to sign extrinsic when account passed in is not KeyringPair
*/ */
+7 -7
View File
@@ -35,19 +35,19 @@ export type QueryableStorageEntry<ApiType extends ApiTypes, A extends AnyTuple =
// eslint-disable-next-line no-use-before-define // eslint-disable-next-line no-use-before-define
: AugmentedQuery<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloads; : AugmentedQuery<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloads;
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple> { export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> {
at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>; at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>;
creator: StorageEntry; creator: StorageEntry;
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>; entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>; entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>; entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>; hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>;
is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>; is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>;
key: (...args: Parameters<F>) => string; key: (...args: Parameters<F>) => string;
keyPrefix: () => string; keyPrefix: () => string;
keys: (arg?: any) => PromiseOrObs<ApiType, StorageKey<A>[]>; keys: <K extends AnyTuple = A> (arg?: any) => PromiseOrObs<ApiType, StorageKey<K>[]>;
keysAt: (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey<A>[]>; keysAt: <K extends AnyTuple = A> (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey<K>[]>;
keysPaged: (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey<A>[]>; keysPaged: <K extends AnyTuple = A> (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey<K>[]>;
// @deprecated The underlying RPC this been marked unsafe and is generally not exposed // @deprecated The underlying RPC this been marked unsafe and is generally not exposed
range: <T extends Codec | any = ObsInnerType<ReturnType<F>>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>; range: <T extends Codec | any = ObsInnerType<ReturnType<F>>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>;
size: (...args: Parameters<F>) => PromiseOrObs<ApiType, u64>; size: (...args: Parameters<F>) => PromiseOrObs<ApiType, u64>;
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/metadata", "name": "@polkadot/metadata",
"version": "3.7.1", "version": "3.9.1",
"description": "Helpers to extract information from runtime metadata", "description": "Helpers to extract information from runtime metadata",
"main": "index.js", "main": "index.js",
"sideEffects": [ "sideEffects": [
@@ -15,14 +15,14 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/types": "3.7.1", "@polkadot/types": "3.9.1",
"@polkadot/types-known": "3.7.1", "@polkadot/types-known": "3.9.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.6.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.6.2",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1" "@polkadot/keyring": "^5.6.2"
} }
} }
+123 -53
View File
@@ -474,7 +474,7 @@
{ {
"name": "Version", "name": "Version",
"type": "RuntimeVersion", "type": "RuntimeVersion",
"value": "0x106e6f6465387375627374726174652d6e6f64650a000000050100000000000030df6acb689907609b0300000037e397fc7c91f5e40100000040fe3ad401f8959a04000000d2bc9897eed08f1502000000f78b278be53f454c02000000ed99c5acb25eedf502000000cbca25e39f14238702000000687ad44ad37f03c201000000bc9d89904f5b923f0100000068b66ba122c93fa70100000037c8bb1350a9a2a801000000ab3c0572291feb8b0100000002000000", "value": "0x106e6f6465387375627374726174652d6e6f64650a000000080100000000000034df6acb689907609b0300000037e397fc7c91f5e40100000040fe3ad401f8959a04000000d2bc9897eed08f1502000000f78b278be53f454c02000000ed99c5acb25eedf502000000cbca25e39f14238702000000687ad44ad37f03c201000000bc9d89904f5b923f0100000068b66ba122c93fa70100000037c8bb1350a9a2a80100000091d5df18b0d2cf5801000000ab3c0572291feb8b0100000002000000",
"documentation": [ "documentation": [
" Get the chain's current version." " Get the chain's current version."
] ]
@@ -671,7 +671,7 @@
"name": "GenesisSlot", "name": "GenesisSlot",
"modifier": "Default", "modifier": "Default",
"type": { "type": {
"Plain": "u64" "Plain": "Slot"
}, },
"fallback": "0x0000000000000000", "fallback": "0x0000000000000000",
"documentation": [ "documentation": [
@@ -683,7 +683,7 @@
"name": "CurrentSlot", "name": "CurrentSlot",
"modifier": "Default", "modifier": "Default",
"type": { "type": {
"Plain": "u64" "Plain": "Slot"
}, },
"fallback": "0x0000000000000000", "fallback": "0x0000000000000000",
"documentation": [ "documentation": [
@@ -1331,7 +1331,7 @@
"documentation": [ "documentation": [
" The balance of an account.", " The balance of an account.",
"", "",
" NOTE: This is only used in the case that this module is used to store balances." " NOTE: This is only used in the case that this pallet is used to store balances."
] ]
}, },
{ {
@@ -1489,7 +1489,7 @@
"", "",
" 99% of the time you want [`transfer`] instead.", " 99% of the time you want [`transfer`] instead.",
"", "",
" [`transfer`]: struct.Module.html#method.transfer", " [`transfer`]: struct.Pallet.html#method.transfer",
" # <weight>", " # <weight>",
" - Cheaper than transfer because account cannot be killed.", " - Cheaper than transfer because account cannot be killed.",
" - Base Weight: 51.4 µs", " - Base Weight: 51.4 µs",
@@ -6842,7 +6842,7 @@
"type": { "type": {
"Plain": "Schedule" "Plain": "Schedule"
}, },
"fallback": "0x000000000004000000000200000001000080000000100000000010000000010000200000000000080019060000016302005498030053100000941c0000a40d0000f11800005e2a00007000000044790100dcf102007907000080060000690700001a06000013190000f92800007f0700007d9ea70811080000a3070000770a00003308000023080000a5070000a3070000050a00003c0a000077090000b50900008f090000240a00007f09000041090000f9090000ec090000120a0000b70900003f0900003b200000cc1c000017200000471d0000e3090000c409000087090000080a00002e0a0000310a00003e0a0000380a00009c33260000000000a8fa2500000000005620250000000000848b4f00000000000e4a250000000000003f2500000000001066250000000000c0905400000000008c4e2500000000006c4b250000000000b49d490000000000466b12000000000090786500000000000f01000000000000b01b4300000000000003000000000000989e591f00000000c07d7c220000000040eca60900000000a4b55a0000000000701683000000000022b8c80700000000aa0900000000000076e85f0000000000bab5971100000000cf02000000000000f81bbb0800000000dedb070200000000dc050000000000007271d10900000000f49adb08000000007e070e08000000004a02000000000000260300000000000008f83e1b0000000051020000000000003103000000000000d70a000000000000d49522000000000068100000000000007c09250000000000240d000000000000b6e22000000000001f0600000000000006a22000000000001c06000000000000", "fallback": "0x0000000000040000000002000000010000800000001000000000100000000100002000000000000800150600004c6b02004c8103009e1800000b1d0000160d0000651800006d2b00008a000000f5700100fdf602008e070000440600006e070000030600004f180000b528000091070000b60da70827080000590800006a0a0000ef070000560800004a0800008e080000f509000061090000dd090000a10a00009c090000e409000091090000650900001e0a0000120a0000ae09000099090000060a00006b2000000b1d000051200000221d000094090000ad090000b6090000160a0000660a0000fd090000260a0000440a0000d41a2a0000000000a0c729000000000092122900000000001ab5580000000000ba1c290000000000e000290000000000b0ef280000000000ee325c0000000000dec1280000000000ca07290000000000c07d4e00000000009c77140000000000303a7200000000000b01000000000000f0ab450000000000ff0200000000000060a21c270000000030078d31000000002635af09000000000ae164000000000038b18e0000000000b6b1cc0700000000890900000000000040036c00000000008ad6e21100000000de020000000000006e67cc080000000078f6110200000000e605000000000000acb1b50a00000000b24419090000000092579f08000000004702000000000000240300000000000016eaeb220000000055020000000000003503000000000000db0a000000000000f4802600000000006a100000000000006a9a280000000000220d0000000000004e9c2400000000001c0600000000000026832400000000001b06000000000000",
"documentation": [ "documentation": [
" Current cost schedule for contracts." " Current cost schedule for contracts."
] ]
@@ -6939,19 +6939,6 @@
" The schedule must have a greater version than the stored schedule." " The schedule must have a greater version than the stored schedule."
] ]
}, },
{
"name": "put_code",
"args": [
{
"name": "code",
"type": "Bytes"
}
],
"documentation": [
" Stores the given binary Wasm code into the chain's storage and returns its `codehash`.",
" You can instantiate contracts only with stored code."
]
},
{ {
"name": "call", "name": "call",
"args": [ "args": [
@@ -6982,6 +6969,54 @@
" a regular account will be created and any value will be transferred." " a regular account will be created and any value will be transferred."
] ]
}, },
{
"name": "instantiate_with_code",
"args": [
{
"name": "endowment",
"type": "Compact<BalanceOf>"
},
{
"name": "gas_limit",
"type": "Compact<Gas>"
},
{
"name": "code",
"type": "Bytes"
},
{
"name": "data",
"type": "Bytes"
},
{
"name": "salt",
"type": "Bytes"
}
],
"documentation": [
" Instantiates a new contract from the supplied `code` optionally transferring",
" some balance.",
"",
" This is the only function that can deploy new code to the chain.",
"",
" # Parameters",
"",
" * `endowment`: The balance to transfer from the `origin` to the newly created contract.",
" * `gas_limit`: The gas limit enforced when executing the constructor.",
" * `code`: The contract code to deploy in raw bytes.",
" * `data`: The input data to pass to the contract constructor.",
" * `salt`: Used for the address derivation. See [`Self::contract_address`].",
"",
" Instantiation is executed as follows:",
"",
" - The supplied `code` is instrumented, deployed, and a `code_hash` is created for that code.",
" - If the `code_hash` already exists on the chain the underlying `code` will be shared.",
" - The destination address is computed based on the sender, code_hash and the salt.",
" - The smart-contract account is created at the computed address.",
" - The `endowment` is transferred to the new account.",
" - The `deploy` function is executed in the context of the newly-created account."
]
},
{ {
"name": "instantiate", "name": "instantiate",
"args": [ "args": [
@@ -7007,19 +7042,11 @@
} }
], ],
"documentation": [ "documentation": [
" Instantiates a new contract from the `code_hash` generated by `put_code`,", " Instantiates a contract from a previously deployed wasm binary.",
" optionally transferring some balance.",
"", "",
" The supplied `salt` is used for contract address deriviation. See `fn contract_address`.", " This function is identical to [`Self::instantiate_with_code`] but without the",
"", " code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary",
" Instantiation is executed as follows:", " must be supplied."
"",
" - The destination address is computed based on the sender, code_hash and the salt.",
" - The smart-contract account is created at the computed address.",
" - The `ctor_code` is executed in the context of the newly-created account. Buffer returned",
" after the execution is saved as the `code` of the account. That code will be invoked",
" upon any call received by this account.",
" - The contract is initialized."
] ]
}, },
{ {
@@ -7055,23 +7082,37 @@
"AccountId" "AccountId"
], ],
"documentation": [ "documentation": [
" Contract deployed by address at the specified address. \\[owner, contract\\]" " Contract deployed by address at the specified address. \\[deployer, contract\\]"
] ]
}, },
{ {
"name": "Evicted", "name": "Evicted",
"args": [ "args": [
"AccountId", "AccountId"
"bool"
], ],
"documentation": [ "documentation": [
" Contract has been evicted and is now in tombstone state.", " Contract has been evicted and is now in tombstone state. \\[contract\\]"
" \\[contract, tombstone\\]", ]
},
{
"name": "Terminated",
"args": [
"AccountId",
"AccountId"
],
"documentation": [
" Contract has been terminated without leaving a tombstone.",
" \\[contract, beneficiary\\]",
"", "",
" # Params", " # Params",
"", "",
" - `contract`: `AccountId`: The account ID of the evicted contract.", " - `contract`: The contract that was terminated.",
" - `tombstone`: `bool`: True if the evicted contract left behind a tombstone." " - `beneficiary`: The account that received the contracts remaining balance.",
"",
" # Note",
"",
" The only way for a contract to be removed without a tombstone and emitting",
" this event is by calling `seal_terminate`."
] ]
}, },
{ {
@@ -7083,15 +7124,15 @@
"Balance" "Balance"
], ],
"documentation": [ "documentation": [
" Restoration for a contract has been successful.", " Restoration of a contract has been successful.",
" \\[donor, dest, code_hash, rent_allowance\\]", " \\[restorer, dest, code_hash, rent_allowance\\]",
"", "",
" # Params", " # Params",
"", "",
" - `donor`: `AccountId`: Account ID of the restoring contract", " - `restorer`: Account ID of the restoring contract.",
" - `dest`: `AccountId`: Account ID of the restored contract", " - `dest`: Account ID of the restored contract.",
" - `code_hash`: `Hash`: Code hash of the restored contract", " - `code_hash`: Code hash of the restored contract.",
" - `rent_allowance: `Balance`: Rent allowance of the restored contract" " - `rent_allowance`: Rent allowance of the restored contract."
] ]
}, },
{ {
@@ -7100,8 +7141,7 @@
"Hash" "Hash"
], ],
"documentation": [ "documentation": [
" Code with the specified hash has been stored.", " Code with the specified hash has been stored. \\[code_hash\\]"
" \\[code_hash\\]"
] ]
}, },
{ {
@@ -7110,18 +7150,41 @@
"u32" "u32"
], ],
"documentation": [ "documentation": [
" Triggered when the current \\[schedule\\] is updated." " Triggered when the current schedule is updated.",
" \\[version\\]",
"",
" # Params",
"",
" - `version`: The version of the newly set schedule."
] ]
}, },
{ {
"name": "ContractExecution", "name": "ContractEmitted",
"args": [ "args": [
"AccountId", "AccountId",
"Bytes" "Bytes"
], ],
"documentation": [ "documentation": [
" An event deposited upon execution of a contract from the account.", " A custom event emitted by the contract.",
" \\[account, data\\]" " \\[contract, data\\]",
"",
" # Params",
"",
" - `contract`: The contract that emitted the event.",
" - `data`: Data supplied by the contract. Metadata generated during contract",
" compilation is needed to decode it."
]
},
{
"name": "CodeRemoved",
"args": [
"Hash"
],
"documentation": [
" A code with the specified hash was removed.",
" \\[code_hash\\]",
"",
" This happens when the last contract that uses this code hash was removed or evicted."
] ]
} }
], ],
@@ -7224,7 +7287,7 @@
{ {
"name": "DeletionQueueDepth", "name": "DeletionQueueDepth",
"type": "u32", "type": "u32",
"value": "0x11010000", "value": "0xf2000000",
"documentation": [ "documentation": [
" The maximum number of tries that can be queued for deletion." " The maximum number of tries that can be queued for deletion."
] ]
@@ -7328,7 +7391,8 @@
{ {
"name": "CodeTooLarge", "name": "CodeTooLarge",
"documentation": [ "documentation": [
" The code supplied to `put_code` exceeds the limit specified in the current schedule." " The code supplied to `instantiate_with_code` exceeds the limit specified in the",
" current schedule."
] ]
}, },
{ {
@@ -7428,6 +7492,12 @@
" This can either happen when the accumulated storage in bytes is too large or", " This can either happen when the accumulated storage in bytes is too large or",
" when number of storage items is too large." " when number of storage items is too large."
] ]
},
{
"name": "DuplicateContract",
"documentation": [
" A contract with the same AccountId already exists."
]
} }
], ],
"index": 17 "index": 17
@@ -7648,7 +7718,7 @@
}, },
"fallback": "0x00000000", "fallback": "0x00000000",
"documentation": [ "documentation": [
" For each session index, we keep a mapping of `T::ValidatorId` to the", " For each session index, we keep a mapping of `ValidatorId<T>` to the",
" number of blocks authored by the given authority." " number of blocks authored by the given authority."
] ]
} }
File diff suppressed because one or more lines are too long
+8 -8
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/rpc-core", "name": "@polkadot/rpc-core",
"version": "3.7.1", "version": "3.9.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface", "description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": false,
@@ -12,14 +12,14 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/metadata": "3.7.1", "@polkadot/metadata": "3.9.1",
"@polkadot/rpc-provider": "3.7.1", "@polkadot/rpc-provider": "3.9.1",
"@polkadot/types": "3.7.1", "@polkadot/types": "3.9.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.6.2",
"@polkadot/x-rxjs": "^5.5.1" "@polkadot/x-rxjs": "^5.6.2"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1" "@polkadot/keyring": "^5.6.2"
} }
} }
+10 -10
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/rpc-provider", "name": "@polkadot/rpc-provider",
"version": "3.7.1", "version": "3.9.1",
"description": "Transport providers for the API", "description": "Transport providers for the API",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": false,
@@ -12,19 +12,19 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/types": "3.7.1", "@polkadot/types": "3.9.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.6.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.6.2",
"@polkadot/x-fetch": "^5.5.1", "@polkadot/x-fetch": "^5.6.2",
"@polkadot/x-global": "^5.5.1", "@polkadot/x-global": "^5.6.2",
"@polkadot/x-ws": "^5.5.1", "@polkadot/x-ws": "^5.6.2",
"bn.js": "^4.11.9", "bn.js": "^4.11.9",
"eventemitter3": "^4.0.7" "eventemitter3": "^4.0.7"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1", "@polkadot/keyring": "^5.6.2",
"@polkadot/metadata": "3.7.1", "@polkadot/metadata": "3.9.1",
"mock-socket": "^9.0.3", "mock-socket": "^9.0.3",
"nock": "^13.0.7" "nock": "^13.0.7"
} }
+3 -1
View File
@@ -189,6 +189,7 @@ export class WsProvider implements ProviderInterface {
* @description Connect, never throwing an error, but rather forcing a retry * @description Connect, never throwing an error, but rather forcing a retry
*/ */
public async connectWithRetry (): Promise<void> { public async connectWithRetry (): Promise<void> {
if (this.#autoConnectMs > 0) {
try { try {
await this.connect(); await this.connect();
} catch (error) { } catch (error) {
@@ -196,7 +197,8 @@ export class WsProvider implements ProviderInterface {
this.connectWithRetry().catch((): void => { this.connectWithRetry().catch((): void => {
// does not throw // does not throw
}); });
}, this.#autoConnectMs || RETRY_DELAY); }, this.#autoConnectMs);
}
} }
} }
+10 -10
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/typegen", "name": "@polkadot/typegen",
"version": "3.7.1", "version": "3.9.1",
"description": "Type generation scripts", "description": "Type generation scripts",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": false,
@@ -19,20 +19,20 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
"dependencies": { "dependencies": {
"@babel/core": "^7.12.10", "@babel/core": "^7.12.13",
"@babel/register": "^7.12.10", "@babel/register": "^7.12.13",
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/api": "3.7.1", "@polkadot/api": "3.9.1",
"@polkadot/metadata": "3.7.1", "@polkadot/metadata": "3.9.1",
"@polkadot/rpc-provider": "3.7.1", "@polkadot/rpc-provider": "3.9.1",
"@polkadot/types": "3.7.1", "@polkadot/types": "3.9.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.6.2",
"handlebars": "^4.7.6", "handlebars": "^4.7.6",
"websocket": "^1.0.33", "websocket": "^1.0.33",
"yargs": "^16.2.0" "yargs": "^16.2.0"
}, },
"devDependencies": { "devDependencies": {
"@types/websocket": "^1.0.1", "@types/websocket": "^1.0.1",
"@types/yargs": "^15.0.13" "@types/yargs": "^16.0.0"
} }
} }
+5 -3
View File
@@ -87,12 +87,12 @@ function tsInt (definitions: Record<string, ModuleTypes>, def: TypeDef, imports:
} }
/** @internal */ /** @internal */
function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Error', def: TypeDef, imports: TypeImports): string { function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Err' | 'Error', def: TypeDef, imports: TypeImports): string {
const { info, type } = def; const { info, type } = def;
const asGetter = type === 'Null' const asGetter = type === 'Null'
? '' ? ''
: createGetter(definitions, `as${getter}`, info === TypeDefInfo.Tuple ? formatType(definitions, def, imports) : type, imports); : (getter === 'Error' ? ' /** @deprecated Use asErr */\n' : '') + createGetter(definitions, `as${getter}`, info === TypeDefInfo.Tuple ? formatType(definitions, def, imports) : type, imports);
const isGetter = createGetter(definitions, `is${getter}`, 'boolean', imports); const isGetter = (getter === 'Error' ? ' /** @deprecated Use isErr */\n' : '') + createGetter(definitions, `is${getter}`, 'boolean', imports);
switch (info) { switch (info) {
case TypeDefInfo.Plain: case TypeDefInfo.Plain:
@@ -110,6 +110,8 @@ function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName =
function tsResult (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string { function tsResult (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
const [okDef, errorDef] = (def.sub as TypeDef[]); const [okDef, errorDef] = (def.sub as TypeDef[]);
const inner = [ const inner = [
tsResultGetter(definitions, def.name, 'Err', errorDef, imports),
// @deprecated, use Err
tsResultGetter(definitions, def.name, 'Error', errorDef, imports), tsResultGetter(definitions, def.name, 'Error', errorDef, imports),
tsResultGetter(definitions, def.name, 'Ok', okDef, imports) tsResultGetter(definitions, def.name, 'Ok', okDef, imports)
].join(''); ].join('');
+5 -4
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/types-known", "name": "@polkadot/types-known",
"version": "3.7.1", "version": "3.9.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface", "description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": false,
@@ -12,9 +12,10 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/types": "3.7.1", "@polkadot/networks": "^5.6.2",
"@polkadot/util": "^5.5.1", "@polkadot/types": "3.9.1",
"@polkadot/util": "^5.6.2",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
+14
View File
@@ -3,6 +3,7 @@
import type BN from 'bn.js'; import type BN from 'bn.js';
import type { Text } from '@polkadot/types'; import type { Text } from '@polkadot/types';
import type { ExtDef } from '@polkadot/types/extrinsic/signedExtensions/types';
import type { Hash } from '@polkadot/types/interfaces'; import type { Hash } from '@polkadot/types/interfaces';
import type { ChainUpgradeVersion, DefinitionRpc, DefinitionRpcSub, OverrideModuleType, OverrideVersionedType, Registry, RegistryTypes } from '@polkadot/types/types'; import type { ChainUpgradeVersion, DefinitionRpc, DefinitionRpcSub, OverrideModuleType, OverrideVersionedType, Registry, RegistryTypes } from '@polkadot/types/types';
@@ -37,6 +38,19 @@ export function getModuleTypes ({ knownTypes }: Registry, section: string): Over
}; };
} }
/**
* @description Based on the chain and runtimeVersion, get the applicable signed extensions (ready for registration)
*/
export function getSpecExtensions ({ knownTypes }: Registry, chainName: Text | string, specName: Text | string): ExtDef {
const _chainName = chainName.toString();
const _specName = specName.toString();
return {
...(knownTypes.typesBundle?.spec?.[_specName]?.signedExtensions || {}),
...(knownTypes.typesBundle?.chain?.[_chainName]?.signedExtensions || {})
};
}
/** /**
* @description Based on the chain and runtimeVersion, get the applicable types (ready for registration) * @description Based on the chain and runtimeVersion, get the applicable types (ready for registration)
*/ */
+10 -5
View File
@@ -8,23 +8,28 @@ import type { OverrideVersionedType } from '@polkadot/types/types';
const sharedTypes = { const sharedTypes = {
AccountInfo: 'AccountInfoWithProviders', AccountInfo: 'AccountInfoWithProviders',
Address: 'MultiAddress', Address: 'MultiAddress',
Keys: 'SessionKeys5', Keys: 'SessionKeys6',
LookupSource: 'MultiAddress', LookupSource: 'MultiAddress',
ProxyType: { ProxyType: {
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement'] _enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement', 'CancelProxy']
} },
ValidatorPrefs: 'ValidatorPrefsWithBlocked'
}; };
const addrIndicesTypes = { const addrIndicesTypes = {
AccountInfo: 'AccountInfoWithRefCount', AccountInfo: 'AccountInfoWithRefCount',
Address: 'LookupSource', Address: 'LookupSource',
LookupSource: 'IndicesLookupSource' Keys: 'SessionKeys5',
LookupSource: 'IndicesLookupSource',
ValidatorPrefs: 'ValidatorPrefsWithCommission'
}; };
const addrAccountIdTypes = { const addrAccountIdTypes = {
AccountInfo: 'AccountInfoWithRefCount', AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId', Address: 'AccountId',
LookupSource: 'AccountId' Keys: 'SessionKeys5',
LookupSource: 'AccountId',
ValidatorPrefs: 'ValidatorPrefsWithCommission'
}; };
const versioned: OverrideVersionedType[] = [ const versioned: OverrideVersionedType[] = [
+7 -5
View File
@@ -8,18 +8,20 @@ import type { OverrideVersionedType } from '@polkadot/types/types';
const sharedTypes = { const sharedTypes = {
AccountInfo: 'AccountInfoWithProviders', AccountInfo: 'AccountInfoWithProviders',
Address: 'MultiAddress', Address: 'MultiAddress',
Keys: 'SessionKeys5', Keys: 'SessionKeys6',
LookupSource: 'MultiAddress', LookupSource: 'MultiAddress',
ProxyType: { ProxyType: {
// was: SudoBalances _enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'DeprecatedSudoBalances', 'IdentityJudgement', 'CancelProxy']
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'Unused', 'IdentityJudgement'] },
} ValidatorPrefs: 'ValidatorPrefsWithBlocked'
}; };
const addrAccountIdTypes = { const addrAccountIdTypes = {
AccountInfo: 'AccountInfoWithRefCount', AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId', Address: 'AccountId',
LookupSource: 'AccountId' Keys: 'SessionKeys5',
LookupSource: 'AccountId',
ValidatorPrefs: 'ValidatorPrefsWithCommission'
}; };
// these are override types for Polkadot // these are override types for Polkadot
+2 -26
View File
@@ -18,39 +18,15 @@ const sharedTypes = {
const versioned: OverrideVersionedType[] = [ const versioned: OverrideVersionedType[] = [
{ {
minmax: [0, 9], minmax: [0, 200],
types: { types: {
...sharedTypes, ...sharedTypes,
AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId',
CompactAssignments: 'CompactAssignmentsTo257',
LookupSource: 'AccountId',
RefCount: 'RefCountTo259',
RewardDestination: 'RewardDestinationTo257',
Keys: 'SessionKeys5'
}
},
{
minmax: [10, 12],
types: {
...sharedTypes,
AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId',
Keys: 'SessionKeys5',
LookupSource: 'AccountId'
}
},
{
minmax: [13, 201],
types: {
...sharedTypes,
AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId', Address: 'AccountId',
LookupSource: 'AccountId' LookupSource: 'AccountId'
} }
}, },
{ {
minmax: [202, undefined], minmax: [201, undefined],
types: { types: {
...sharedTypes ...sharedTypes
} }
+8 -5
View File
@@ -8,18 +8,21 @@ import type { OverrideVersionedType } from '@polkadot/types/types';
const sharedTypes = { const sharedTypes = {
AccountInfo: 'AccountInfoWithProviders', AccountInfo: 'AccountInfoWithProviders',
Address: 'MultiAddress', Address: 'MultiAddress',
Keys: 'SessionKeys5', Keys: 'SessionKeys6',
LookupSource: 'MultiAddress', LookupSource: 'MultiAddress',
ProxyType: { ProxyType: {
// was: SudoBalances _enum: ['Any', 'NonTransfer', 'Staking', 'SudoBalances', 'IdentityJudgement', 'CancelProxy'
_enum: ['Any', 'NonTransfer', 'Staking', 'Unused', 'IdentityJudgement'] ]
} },
ValidatorPrefs: 'ValidatorPrefsWithBlocked'
}; };
const addrAccountIdTypes = { const addrAccountIdTypes = {
AccountInfo: 'AccountInfoWithRefCount', AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId', Address: 'AccountId',
LookupSource: 'AccountId' LookupSource: 'AccountId',
Keys: 'SessionKeys5',
ValidatorPrefs: 'ValidatorPrefsWithCommission'
}; };
const versioned: OverrideVersionedType[] = [ const versioned: OverrideVersionedType[] = [
@@ -1,10 +1,62 @@
// Copyright 2017-2021 @polkadot/types-known authors & contributors // Copyright 2017-2021 @polkadot/types-known authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import { assert, u8aEq } from '@polkadot/util';
import all from '.'; import all from '.';
interface TestDef {
genesisHash: string;
network: string;
versions: [number, [number, number]][];
}
const TESTS: TestDef[] = [
{
genesisHash: '0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe',
network: 'kusama',
versions: [
[0, [0, 1020]],
[17, [901442, 1045]]
]
},
{
genesisHash: '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3',
network: 'polkadot',
versions: [
[0, [0, 0]],
[19, [2436698, 26]]
]
},
{
genesisHash: '0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e',
network: 'westend',
versions: [
[0, [214356, 4]],
[23, [4207800, 48]]
]
}
];
describe('upgrades', (): void => { describe('upgrades', (): void => {
it('is valid', (): void => { TESTS.forEach(({ genesisHash, network, versions }): void => {
expect(all).toBeDefined(); describe(network, (): void => {
const chain = all.find((n) => n.network === network);
assert(chain, `Unable to find the entry for ${network}`);
it('has a valid genesisHash', (): void => {
expect(u8aEq(chain.genesisHash, genesisHash)).toBe(true);
});
versions.forEach(([index, [blockNumber, specVersion]]): void => {
it(`has a valid entry at index ${index}`, (): void => {
const version = chain.versions[index];
expect(version.blockNumber.eqn(blockNumber)).toBe(true);
expect(version.specVersion.eqn(specVersion)).toBe(true);
});
});
});
}); });
}); });
+16 -8
View File
@@ -6,14 +6,22 @@ import type { ChainUpgradesRaw } from './types';
import BN from 'bn.js'; import BN from 'bn.js';
import networks from '@polkadot/networks';
import { assert, hexToU8a } from '@polkadot/util'; import { assert, hexToU8a } from '@polkadot/util';
import kusama from './kusama'; import kusama from './kusama';
import polkadot from './polkadot'; import polkadot from './polkadot';
import westend from './westend'; import westend from './westend';
// testnets are not available in the networks map
const NET_EXTRA: Record<string, { genesisHash: string[] }> = {
westend: {
genesisHash: ['0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e']
}
};
/** @internal */ /** @internal */
function checkOrder (network: string, versions: [number, number][]): [number, number][] { function checkOrder (network: string, versions: ChainUpgradesRaw): [number, number][] {
const ooo = versions.filter((curr, index): boolean => { const ooo = versions.filter((curr, index): boolean => {
const prev = versions[index - 1]; const prev = versions[index - 1];
@@ -28,9 +36,13 @@ function checkOrder (network: string, versions: [number, number][]): [number, nu
} }
/** @internal */ /** @internal */
function rawToFinal (network: string, { genesisHash, versions }: ChainUpgradesRaw): ChainUpgrades { function mapRaw ([network, versions]: [string, ChainUpgradesRaw]): ChainUpgrades {
const chain = networks.find((n) => n.network === network) || NET_EXTRA[network];
assert(chain, `Unable to find info for chain ${network}`);
return { return {
genesisHash: hexToU8a(genesisHash), genesisHash: hexToU8a(chain.genesisHash[0]),
network, network,
versions: checkOrder(network, versions).map(([blockNumber, specVersion]) => ({ versions: checkOrder(network, versions).map(([blockNumber, specVersion]) => ({
blockNumber: new BN(blockNumber), blockNumber: new BN(blockNumber),
@@ -40,10 +52,6 @@ function rawToFinal (network: string, { genesisHash, versions }: ChainUpgradesRa
} }
// Type overrides for specific spec types & versions as given in runtimeVersion // Type overrides for specific spec types & versions as given in runtimeVersion
const upgrades: ChainUpgrades[] = [ const upgrades = Object.entries({ kusama, polkadot, westend }).map(mapRaw);
rawToFinal('kusama', kusama),
rawToFinal('polkadot', polkadot),
rawToFinal('westend', westend)
];
export default upgrades; export default upgrades;
+4 -6
View File
@@ -3,9 +3,7 @@
import type { ChainUpgradesRaw } from './types'; import type { ChainUpgradesRaw } from './types';
const upgrades: ChainUpgradesRaw = { const upgrades: ChainUpgradesRaw = [
genesisHash: '0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe',
versions: [
[0, 1020], [26669, 1021], [38245, 1022], [54248, 1023], [59659, 1024], [0, 1020], [26669, 1021], [38245, 1022], [54248, 1023], [59659, 1024],
[67651, 1025], [82191, 1027], [83238, 1028], [101503, 1029], [203466, 1030], [67651, 1025], [82191, 1027], [83238, 1028], [101503, 1029], [203466, 1030],
[295787, 1031], [461692, 1032], [504329, 1033], [569327, 1038], [587687, 1039], [295787, 1031], [461692, 1032], [504329, 1033], [569327, 1038], [587687, 1039],
@@ -13,8 +11,8 @@ const upgrades: ChainUpgradesRaw = {
[1472960, 1052], [1475648, 1053], [1491596, 1054], [1574408, 1055], [2064961, 1058], [1472960, 1052], [1475648, 1053], [1491596, 1054], [1574408, 1055], [2064961, 1058],
[2201991, 1062], [2671528, 2005], [2704202, 2007], [2728002, 2008], [2832534, 2011], [2201991, 1062], [2671528, 2005], [2704202, 2007], [2728002, 2008], [2832534, 2011],
[2962294, 2012], [3240000, 2013], [3274408, 2015], [3323565, 2019], [3534175, 2022], [2962294, 2012], [3240000, 2013], [3274408, 2015], [3323565, 2019], [3534175, 2022],
[3860281, 2023], [4143129, 2024], [4401242, 2025], [4841367, 2026], [5961600, 2027] [3860281, 2023], [4143129, 2024], [4401242, 2025], [4841367, 2026], [5961600, 2027],
] [6137912, 2028]
}; ];
export default upgrades; export default upgrades;
@@ -3,14 +3,12 @@
import type { ChainUpgradesRaw } from './types'; import type { ChainUpgradesRaw } from './types';
const upgrades: ChainUpgradesRaw = { const upgrades: ChainUpgradesRaw = [
genesisHash: '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3',
versions: [
[0, 0], [29231, 1], [188836, 5], [199405, 6], [214264, 7], [0, 0], [29231, 1], [188836, 5], [199405, 6], [214264, 7],
[244358, 8], [303079, 9], [314201, 10], [342400, 11], [443963, 12], [244358, 8], [303079, 9], [314201, 10], [342400, 11], [443963, 12],
[528470, 13], [687751, 14], [746085, 15], [787923, 16], [799302, 17], [528470, 13], [687751, 14], [746085, 15], [787923, 16], [799302, 17],
[1205128, 18], [1603423, 23], [1733218, 24], [2005673, 25] [1205128, 18], [1603423, 23], [1733218, 24], [2005673, 25], [2436698, 26],
] [3613564, 27]
}; ];
export default upgrades; export default upgrades;
+1 -4
View File
@@ -1,7 +1,4 @@
// Copyright 2017-2021 @polkadot/types-known authors & contributors // Copyright 2017-2021 @polkadot/types-known authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export interface ChainUpgradesRaw { export type ChainUpgradesRaw = [number, number][];
genesisHash: string;
versions: [number, number][];
}
+3 -6
View File
@@ -3,15 +3,12 @@
import type { ChainUpgradesRaw } from './types'; import type { ChainUpgradesRaw } from './types';
const upgrades: ChainUpgradesRaw = { const upgrades: ChainUpgradesRaw = [
genesisHash: '0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e',
versions: [
[214356, 4], [392764, 7], [409740, 8], [809976, 20], [877581, 24], [214356, 4], [392764, 7], [409740, 8], [809976, 20], [877581, 24],
[879238, 25], [889472, 26], [902937, 27], [932751, 28], [991142, 29], [879238, 25], [889472, 26], [902937, 27], [932751, 28], [991142, 29],
[1030162, 31], [1119657, 32], [1199282, 33], [1342534, 34], [1392263, 35], [1030162, 31], [1119657, 32], [1199282, 33], [1342534, 34], [1392263, 35],
[1431703, 36], [1433369, 37], [1490972, 41], [2087397, 43], [2316688, 44], [1431703, 36], [1433369, 37], [1490972, 41], [2087397, 43], [2316688, 44],
[2549864, 45], [3925782, 46], [3925843, 47] [2549864, 45], [3925782, 46], [3925843, 47], [4207800, 48]
] ];
};
export default upgrades; export default upgrades;
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/types", "name": "@polkadot/types",
"version": "3.7.1", "version": "3.9.1",
"description": "Implementation of the Parity codec", "description": "Implementation of the Parity codec",
"main": "index.js", "main": "index.js",
"sideEffects": [ "sideEffects": [
@@ -15,15 +15,15 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.12.13",
"@polkadot/metadata": "3.7.1", "@polkadot/metadata": "3.9.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.6.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.6.2",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^5.6.2",
"@types/bn.js": "^4.11.6", "@types/bn.js": "^4.11.6",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1" "@polkadot/keyring": "^5.6.2"
} }
} }
+8 -2
View File
@@ -20,7 +20,7 @@ import type { DeployData, FundIndex, FundInfo, LastContribution } from '@polkado
import type { AccountVote, AccountVoteSplit, AccountVoteStandard, Conviction, Delegations, PreimageStatus, PreimageStatusAvailable, PriorLock, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, ReferendumInfoFinished, ReferendumInfoTo239, ReferendumStatus, Tally, Voting, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces/democracy'; import type { AccountVote, AccountVoteSplit, AccountVoteStandard, Conviction, Delegations, PreimageStatus, PreimageStatusAvailable, PriorLock, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, ReferendumInfoFinished, ReferendumInfoTo239, ReferendumStatus, Tally, Voting, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces/democracy';
import type { ApprovalFlag, DefunctVoter, Renouncing, SetIndex, Vote, VoteIndex, VoteThreshold, VoterInfo } from '@polkadot/types/interfaces/elections'; import type { ApprovalFlag, DefunctVoter, Renouncing, SetIndex, Vote, VoteIndex, VoteThreshold, VoterInfo } from '@polkadot/types/interfaces/elections';
import type { CreatedBlock, ImportedAux } from '@polkadot/types/interfaces/engine'; import type { CreatedBlock, ImportedAux } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthBlock, EthBloom, EthCallRequest, EthFilter, EthFilterAddress, EthFilterTopic, EthFilterTopicEntry, EthFilterTopicInner, EthHeader, EthLog, EthReceipt, EthRichBlock, EthRichHeader, EthStorageProof, EthSubKind, EthSubParams, EthSubResult, EthSyncInfo, EthSyncStatus, EthTransaction, EthTransactionAction, EthTransactionCondition, EthTransactionRequest, EthTransactionStatus, EthWork, EthereumAccountId, EthereumLookupSource, EthereumSignature } from '@polkadot/types/interfaces/eth'; import type { EthAccount, EthBlock, EthBloom, EthCallRequest, EthFilter, EthFilterAddress, EthFilterChanges, EthFilterTopic, EthFilterTopicEntry, EthFilterTopicInner, EthHeader, EthLog, EthReceipt, EthRichBlock, EthRichHeader, EthStorageProof, EthSubKind, EthSubParams, EthSubResult, EthSyncInfo, EthSyncStatus, EthTransaction, EthTransactionAction, EthTransactionCondition, EthTransactionRequest, EthTransactionStatus, EthWork, EthereumAccountId, EthereumLookupSource, EthereumSignature } from '@polkadot/types/interfaces/eth';
import type { EvmAccount, EvmLog, EvmVicinity, ExitError, ExitFatal, ExitReason, ExitRevert, ExitSucceed } from '@polkadot/types/interfaces/evm'; import type { EvmAccount, EvmLog, EvmVicinity, ExitError, ExitFatal, ExitReason, ExitRevert, ExitSucceed } from '@polkadot/types/interfaces/evm';
import type { AnySignature, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV4, ExtrinsicSignature, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV4, ImmortalEra, MortalEra, MultiSignature, Signature, SignerPayload, Sr25519Signature } from '@polkadot/types/interfaces/extrinsics'; import type { AnySignature, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV4, ExtrinsicSignature, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV4, ImmortalEra, MortalEra, MultiSignature, Signature, SignerPayload, Sr25519Signature } from '@polkadot/types/interfaces/extrinsics';
import type { AssetOptions, Owner, PermissionLatest, PermissionVersions, PermissionsV1 } from '@polkadot/types/interfaces/genericAsset'; import type { AssetOptions, Owner, PermissionLatest, PermissionVersions, PermissionsV1 } from '@polkadot/types/interfaces/genericAsset';
@@ -31,7 +31,7 @@ import type { CallIndex, LotteryConfig } from '@polkadot/types/interfaces/lotter
import type { DoubleMapTypeLatest, DoubleMapTypeV10, DoubleMapTypeV11, DoubleMapTypeV12, DoubleMapTypeV9, ErrorMetadataLatest, ErrorMetadataV10, ErrorMetadataV11, ErrorMetadataV12, ErrorMetadataV9, EventMetadataLatest, EventMetadataV10, EventMetadataV11, EventMetadataV12, EventMetadataV9, ExtrinsicMetadataLatest, ExtrinsicMetadataV11, ExtrinsicMetadataV12, FunctionArgumentMetadataLatest, FunctionArgumentMetadataV10, FunctionArgumentMetadataV11, FunctionArgumentMetadataV12, FunctionArgumentMetadataV9, FunctionMetadataLatest, FunctionMetadataV10, FunctionMetadataV11, FunctionMetadataV12, FunctionMetadataV9, MapTypeLatest, MapTypeV10, MapTypeV11, MapTypeV12, MapTypeV9, MetadataAll, MetadataLatest, MetadataV10, MetadataV11, MetadataV12, MetadataV9, ModuleConstantMetadataLatest, ModuleConstantMetadataV10, ModuleConstantMetadataV11, ModuleConstantMetadataV12, ModuleConstantMetadataV9, ModuleMetadataLatest, ModuleMetadataV10, ModuleMetadataV11, ModuleMetadataV12, ModuleMetadataV9, StorageEntryMetadataLatest, StorageEntryMetadataV10, StorageEntryMetadataV11, StorageEntryMetadataV12, StorageEntryMetadataV9, StorageEntryModifierLatest, StorageEntryModifierV10, StorageEntryModifierV11, StorageEntryModifierV12, StorageEntryModifierV9, StorageEntryTypeLatest, StorageEntryTypeV10, StorageEntryTypeV11, StorageEntryTypeV12, StorageEntryTypeV9, StorageHasher, StorageHasherV10, StorageHasherV11, StorageHasherV12, StorageHasherV9, StorageMetadataLatest, StorageMetadataV10, StorageMetadataV11, StorageMetadataV12, StorageMetadataV9 } from '@polkadot/types/interfaces/metadata'; import type { DoubleMapTypeLatest, DoubleMapTypeV10, DoubleMapTypeV11, DoubleMapTypeV12, DoubleMapTypeV9, ErrorMetadataLatest, ErrorMetadataV10, ErrorMetadataV11, ErrorMetadataV12, ErrorMetadataV9, EventMetadataLatest, EventMetadataV10, EventMetadataV11, EventMetadataV12, EventMetadataV9, ExtrinsicMetadataLatest, ExtrinsicMetadataV11, ExtrinsicMetadataV12, FunctionArgumentMetadataLatest, FunctionArgumentMetadataV10, FunctionArgumentMetadataV11, FunctionArgumentMetadataV12, FunctionArgumentMetadataV9, FunctionMetadataLatest, FunctionMetadataV10, FunctionMetadataV11, FunctionMetadataV12, FunctionMetadataV9, MapTypeLatest, MapTypeV10, MapTypeV11, MapTypeV12, MapTypeV9, MetadataAll, MetadataLatest, MetadataV10, MetadataV11, MetadataV12, MetadataV9, ModuleConstantMetadataLatest, ModuleConstantMetadataV10, ModuleConstantMetadataV11, ModuleConstantMetadataV12, ModuleConstantMetadataV9, ModuleMetadataLatest, ModuleMetadataV10, ModuleMetadataV11, ModuleMetadataV12, ModuleMetadataV9, StorageEntryMetadataLatest, StorageEntryMetadataV10, StorageEntryMetadataV11, StorageEntryMetadataV12, StorageEntryMetadataV9, StorageEntryModifierLatest, StorageEntryModifierV10, StorageEntryModifierV11, StorageEntryModifierV12, StorageEntryModifierV9, StorageEntryTypeLatest, StorageEntryTypeV10, StorageEntryTypeV11, StorageEntryTypeV12, StorageEntryTypeV9, StorageHasher, StorageHasherV10, StorageHasherV11, StorageHasherV12, StorageHasherV9, StorageMetadataLatest, StorageMetadataV10, StorageMetadataV11, StorageMetadataV12, StorageMetadataV9 } from '@polkadot/types/interfaces/metadata';
import type { StorageKind } from '@polkadot/types/interfaces/offchain'; import type { StorageKind } from '@polkadot/types/interfaces/offchain';
import type { DeferredOffenceOf, Kind, OffenceDetails, Offender, OpaqueTimeSlot, ReportIdOf, Reporter } from '@polkadot/types/interfaces/offences'; import type { DeferredOffenceOf, Kind, OffenceDetails, Offender, OpaqueTimeSlot, ReportIdOf, Reporter } from '@polkadot/types/interfaces/offences';
import type { AbridgedCandidateReceipt, AbridgedHostConfiguration, AbridgedHrmpChannel, AbstractFungible, AbstractNonFungible, AccountId32Junction, AccountIndex64Junction, AccountKey20Junction, AssetInstance, AssignmentId, AssignmentKind, AttestedCandidate, AuctionIndex, AuthorityDiscoveryId, AvailabilityBitfield, AvailabilityBitfieldRecord, BackedCandidate, Balances, Bidder, BufferedSessionChange, CandidateCommitments, CandidateDescriptor, CandidateHash, CandidatePendingAvailability, CandidateReceipt, CollatorId, CollatorSignature, CommittedCandidateReceipt, ConcreteFungible, ConcreteNonFungible, CoreAssignment, CoreIndex, CoreOccupied, DepositAsset, DepositReserveAsset, DoubleVoteReport, DownwardMessage, ExchangeAsset, GlobalValidationSchedule, GroupIndex, HeadData, HostConfiguration, HrmpChannel, HrmpChannelId, HrmpOpenChannelRequest, InboundDownwardMessage, InboundHrmpMessage, InboundHrmpMessages, IncomingParachain, IncomingParachainDeploy, IncomingParachainFixed, InitiateReserveWithdraw, InitiateTeleport, Junction, LeasePeriod, LeasePeriodOf, LocalValidationData, MessageIngestionType, MessagingStateSnapshot, MessagingStateSnapshotEgressEntry, MultiAsset, MultiLocation, NetworkId, NewBidder, NewBidderOption, Order, OriginKind, OutboundHrmpMessage, ParaGenesisArgs, ParaId, ParaInfo, ParaPastCodeMeta, ParaScheduling, ParaValidatorIndex, ParachainDispatchOrigin, ParachainProposal, ParathreadClaim, ParathreadClaimQueue, ParathreadEntry, PersistedValidationData, QueryHolding, QueuedParathread, RegisteredParachainInfo, RelayChainBlockNumber, RelayTo, RelayedFrom, Remark, ReserveAssetDeposit, Retriable, Scheduling, SessionInfo, SessionInfoValidatorGroup, SignedAvailabilityBitfield, SignedAvailabilityBitfields, SigningContext, SlotRange, Statement, SubId, SystemInherentData, TeleportAsset, Transact, TransientValidationData, UpwardMessage, ValidationCode, ValidationData, ValidationDataType, ValidationFunctionParams, ValidatorSignature, ValidityAttestation, VecInboundHrmpMessage, VersionedMultiAsset, VersionedMultiLocation, VersionedXcm, WinnersData, WinnersDataTuple, WinningData, WinningDataEntry, WithdrawAsset, Xcm, XcmError, XcmResult } from '@polkadot/types/interfaces/parachains'; import type { AbridgedCandidateReceipt, AbridgedHostConfiguration, AbridgedHrmpChannel, AbstractFungible, AbstractNonFungible, AccountId32Junction, AccountIndex64Junction, AccountKey20Junction, AssetInstance, AssignmentId, AssignmentKind, AttestedCandidate, AuctionIndex, AuthorityDiscoveryId, AvailabilityBitfield, AvailabilityBitfieldRecord, BackedCandidate, Balances, Bidder, BufferedSessionChange, CandidateCommitments, CandidateDescriptor, CandidateHash, CandidatePendingAvailability, CandidateReceipt, CollatorId, CollatorSignature, CommittedCandidateReceipt, ConcreteFungible, ConcreteNonFungible, CoreAssignment, CoreIndex, CoreOccupied, DepositAsset, DepositReserveAsset, DoubleVoteReport, DownwardMessage, ExchangeAsset, GlobalValidationSchedule, GroupIndex, HeadData, HostConfiguration, HrmpChannel, HrmpChannelId, HrmpOpenChannelRequest, InboundDownwardMessage, InboundHrmpMessage, InboundHrmpMessages, IncomingParachain, IncomingParachainDeploy, IncomingParachainFixed, InitiateReserveWithdraw, InitiateTeleport, Junction, LeasePeriod, LeasePeriodOf, LocalValidationData, MessageIngestionType, MessagingStateSnapshot, MessagingStateSnapshotEgressEntry, MultiAsset, MultiLocation, NetworkId, NewBidder, NewBidderOption, Order, OriginKind, OutboundHrmpMessage, ParaGenesisArgs, ParaId, ParaInfo, ParaLifecycle, ParaPastCodeMeta, ParaScheduling, ParaValidatorIndex, ParachainDispatchOrigin, ParachainProposal, ParathreadClaim, ParathreadClaimQueue, ParathreadEntry, PersistedValidationData, QueryHolding, QueuedParathread, RegisteredParachainInfo, RelayChainBlockNumber, RelayTo, RelayedFrom, Remark, ReserveAssetDeposit, Retriable, Scheduling, SessionInfo, SessionInfoValidatorGroup, SignedAvailabilityBitfield, SignedAvailabilityBitfields, SigningContext, SlotRange, Statement, SubId, SystemInherentData, TeleportAsset, Transact, TransientValidationData, UpwardMessage, ValidationCode, ValidationData, ValidationDataType, ValidationFunctionParams, ValidatorSignature, ValidityAttestation, VecInboundHrmpMessage, VersionedMultiAsset, VersionedMultiLocation, VersionedXcm, WinnersData, WinnersDataTuple, WinningData, WinningDataEntry, WithdrawAsset, Xcm, XcmError, XcmResult } from '@polkadot/types/interfaces/parachains';
import type { FeeDetails, InclusionFee, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment'; import type { FeeDetails, InclusionFee, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { Approvals } from '@polkadot/types/interfaces/poll'; import type { Approvals } from '@polkadot/types/interfaces/poll';
import type { ProxyAnnouncement, ProxyDefinition, ProxyType } from '@polkadot/types/interfaces/proxy'; import type { ProxyAnnouncement, ProxyDefinition, ProxyType } from '@polkadot/types/interfaces/proxy';
@@ -340,6 +340,7 @@ declare module '@polkadot/types/types/registry' {
'Option<EthereumSignature>': Option<EthereumSignature>; 'Option<EthereumSignature>': Option<EthereumSignature>;
'Option<EthFilter>': Option<EthFilter>; 'Option<EthFilter>': Option<EthFilter>;
'Option<EthFilterAddress>': Option<EthFilterAddress>; 'Option<EthFilterAddress>': Option<EthFilterAddress>;
'Option<EthFilterChanges>': Option<EthFilterChanges>;
'Option<EthFilterTopic>': Option<EthFilterTopic>; 'Option<EthFilterTopic>': Option<EthFilterTopic>;
'Option<EthFilterTopicEntry>': Option<EthFilterTopicEntry>; 'Option<EthFilterTopicEntry>': Option<EthFilterTopicEntry>;
'Option<EthFilterTopicInner>': Option<EthFilterTopicInner>; 'Option<EthFilterTopicInner>': Option<EthFilterTopicInner>;
@@ -577,6 +578,7 @@ declare module '@polkadot/types/types/registry' {
'Option<ParaGenesisArgs>': Option<ParaGenesisArgs>; 'Option<ParaGenesisArgs>': Option<ParaGenesisArgs>;
'Option<ParaId>': Option<ParaId>; 'Option<ParaId>': Option<ParaId>;
'Option<ParaInfo>': Option<ParaInfo>; 'Option<ParaInfo>': Option<ParaInfo>;
'Option<ParaLifecycle>': Option<ParaLifecycle>;
'Option<ParaPastCodeMeta>': Option<ParaPastCodeMeta>; 'Option<ParaPastCodeMeta>': Option<ParaPastCodeMeta>;
'Option<ParaScheduling>': Option<ParaScheduling>; 'Option<ParaScheduling>': Option<ParaScheduling>;
'Option<ParathreadClaim>': Option<ParathreadClaim>; 'Option<ParathreadClaim>': Option<ParathreadClaim>;
@@ -1062,6 +1064,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<EthereumSignature>': Vec<EthereumSignature>; 'Vec<EthereumSignature>': Vec<EthereumSignature>;
'Vec<EthFilter>': Vec<EthFilter>; 'Vec<EthFilter>': Vec<EthFilter>;
'Vec<EthFilterAddress>': Vec<EthFilterAddress>; 'Vec<EthFilterAddress>': Vec<EthFilterAddress>;
'Vec<EthFilterChanges>': Vec<EthFilterChanges>;
'Vec<EthFilterTopic>': Vec<EthFilterTopic>; 'Vec<EthFilterTopic>': Vec<EthFilterTopic>;
'Vec<EthFilterTopicEntry>': Vec<EthFilterTopicEntry>; 'Vec<EthFilterTopicEntry>': Vec<EthFilterTopicEntry>;
'Vec<EthFilterTopicInner>': Vec<EthFilterTopicInner>; 'Vec<EthFilterTopicInner>': Vec<EthFilterTopicInner>;
@@ -1299,6 +1302,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<ParaGenesisArgs>': Vec<ParaGenesisArgs>; 'Vec<ParaGenesisArgs>': Vec<ParaGenesisArgs>;
'Vec<ParaId>': Vec<ParaId>; 'Vec<ParaId>': Vec<ParaId>;
'Vec<ParaInfo>': Vec<ParaInfo>; 'Vec<ParaInfo>': Vec<ParaInfo>;
'Vec<ParaLifecycle>': Vec<ParaLifecycle>;
'Vec<ParaPastCodeMeta>': Vec<ParaPastCodeMeta>; 'Vec<ParaPastCodeMeta>': Vec<ParaPastCodeMeta>;
'Vec<ParaScheduling>': Vec<ParaScheduling>; 'Vec<ParaScheduling>': Vec<ParaScheduling>;
'Vec<ParathreadClaim>': Vec<ParathreadClaim>; 'Vec<ParathreadClaim>': Vec<ParathreadClaim>;
@@ -1784,6 +1788,7 @@ declare module '@polkadot/types/types/registry' {
EthereumSignature: EthereumSignature; EthereumSignature: EthereumSignature;
EthFilter: EthFilter; EthFilter: EthFilter;
EthFilterAddress: EthFilterAddress; EthFilterAddress: EthFilterAddress;
EthFilterChanges: EthFilterChanges;
EthFilterTopic: EthFilterTopic; EthFilterTopic: EthFilterTopic;
EthFilterTopicEntry: EthFilterTopicEntry; EthFilterTopicEntry: EthFilterTopicEntry;
EthFilterTopicInner: EthFilterTopicInner; EthFilterTopicInner: EthFilterTopicInner;
@@ -2021,6 +2026,7 @@ declare module '@polkadot/types/types/registry' {
ParaGenesisArgs: ParaGenesisArgs; ParaGenesisArgs: ParaGenesisArgs;
ParaId: ParaId; ParaId: ParaId;
ParaInfo: ParaInfo; ParaInfo: ParaInfo;
ParaLifecycle: ParaLifecycle;
ParaPastCodeMeta: ParaPastCodeMeta; ParaPastCodeMeta: ParaPastCodeMeta;
ParaScheduling: ParaScheduling; ParaScheduling: ParaScheduling;
ParathreadClaim: ParathreadClaim; ParathreadClaim: ParathreadClaim;
+5 -5
View File
@@ -7,7 +7,7 @@ import type { UIntBitLength } from './types';
import BN from 'bn.js'; import BN from 'bn.js';
import { assert, BN_ZERO, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isHex, isString, isU8a, u8aToBn } from '@polkadot/util'; import { assert, BN_BILLION, BN_HUNDRED, BN_MILLION, BN_QUINTILL, BN_ZERO, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isHex, isString, isU8a, u8aToBn } from '@polkadot/util';
export const DEFAULT_UINT_BITS = 64; export const DEFAULT_UINT_BITS = 64;
@@ -17,10 +17,10 @@ const MAX_NUMBER_BITS = 52;
const MUL_P = new BN(1_00_00); const MUL_P = new BN(1_00_00);
const FORMATTERS: [string, BN][] = [ const FORMATTERS: [string, BN][] = [
['Perquintill', new BN(1_000_000_000_000)], ['Perquintill', BN_QUINTILL],
['Perbill', new BN(1_000_000_000)], ['Perbill', BN_BILLION],
['Permill', new BN(1_000_000)], ['Permill', BN_MILLION],
['Percent', new BN(100)] ['Percent', BN_HUNDRED]
]; ];
function toPercentage (value: BN, divisor: BN): string { function toPercentage (value: BN, divisor: BN): string {
+9 -5
View File
@@ -9,7 +9,7 @@ import { Result } from '.';
describe('Result', (): void => { describe('Result', (): void => {
const registry = new TypeRegistry(); const registry = new TypeRegistry();
const Type = Result.with({ Error: Text, Ok: u32 }); const Type = Result.with({ Err: Text, Ok: u32 });
it('has a sane toRawType representation', (): void => { it('has a sane toRawType representation', (): void => {
expect(new Type(registry).toRawType()).toEqual('Result<u32,Text>'); expect(new Type(registry).toRawType()).toEqual('Result<u32,Text>');
@@ -29,17 +29,21 @@ describe('Result', (): void => {
it('decodes from a u8a (error)', (): void => { it('decodes from a u8a (error)', (): void => {
const result = new Type(registry, new Uint8Array([1, 4 << 2, 100, 101, 102, 103])); const result = new Type(registry, new Uint8Array([1, 4 << 2, 100, 101, 102, 103]));
expect(result.isError); expect(result.isErr);
expect(result.asError.toU8a()).toEqual(new Uint8Array([4 << 2, 100, 101, 102, 103])); expect(result.asErr.toU8a()).toEqual(new Uint8Array([4 << 2, 100, 101, 102, 103]));
expect(result.toHex()).toEqual('0x011064656667'); expect(result.toHex()).toEqual('0x011064656667');
expect(result.toJSON()).toEqual({ expect(result.toJSON()).toEqual({
Error: hexToString('0x64656667') Err: hexToString('0x64656667')
}); });
}); });
it('decodes from a JSON representation', (): void => { it('decodes from a JSON representation', (): void => {
const result = new Type(registry, { Error: 'error' }); const result = new Type(registry, { Err: 'error' });
expect(result.isErr).toBe(true);
expect(result.isError).toBe(true);
expect(result.asErr.toString()).toEqual('error');
expect(result.asError.toString()).toEqual('error');
expect(result.toHex()).toEqual('0x01146572726f72'); expect(result.toHex()).toEqual('0x01146572726f72');
}); });
+26 -12
View File
@@ -13,34 +13,41 @@ import { Enum } from './Enum';
* A Result maps to the Rust Result type, that can either wrap a success or error value * A Result maps to the Rust Result type, that can either wrap a success or error value
*/ */
export class Result<O extends Codec, E extends Codec> extends Enum { export class Result<O extends Codec, E extends Codec> extends Enum {
constructor (registry: Registry, Ok: Constructor<O> | keyof InterfaceTypes, Error: Constructor<E> | keyof InterfaceTypes, value?: unknown) { constructor (registry: Registry, Ok: Constructor<O> | keyof InterfaceTypes, Err: Constructor<E> | keyof InterfaceTypes, value?: unknown) {
// NOTE This is order-dependent, Ok (with index 0) needs to be first // NOTE This is order-dependent, Ok (with index 0) needs to be first
// eslint-disable-next-line sort-keys // eslint-disable-next-line sort-keys
super(registry, { Ok, Error }, value); super(registry, { Ok, Err }, value);
} }
public static with<O extends Codec, E extends Codec> (Types: { Ok: Constructor<O> | keyof InterfaceTypes; Error: Constructor<E> | keyof InterfaceTypes }): Constructor<Result<O, E>> { public static with<O extends Codec, E extends Codec> (Types: { Ok: Constructor<O> | keyof InterfaceTypes; Err: Constructor<E> | keyof InterfaceTypes }): Constructor<Result<O, E>> {
return class extends Result<O, E> { return class extends Result<O, E> {
constructor (registry: Registry, value?: unknown) { constructor (registry: Registry, value?: unknown) {
super(registry, Types.Ok, Types.Error, value); super(registry, Types.Ok, Types.Err, value);
} }
}; };
} }
/** /**
* @description Returns the wrapper Error value (if isError) * @description Returns the wrapper Err value (if isErr)
*/ */
public get asError (): E { public get asErr (): E {
assert(this.isError, 'Cannot extract Error value from Ok result, check isError first'); assert(this.isErr, 'Cannot extract Err value from Ok result, check isErr first');
return this.value as E; return this.value as E;
} }
/**
* @deprecated Use asErr
*/
public get asError (): E {
return this.asErr;
}
/** /**
* @description Returns the wrapper Ok value (if isOk) * @description Returns the wrapper Ok value (if isOk)
*/ */
public get asOk (): O { public get asOk (): O {
assert(this.isOk, 'Cannot extract Ok value from Error result, check isOk first'); assert(this.isOk, 'Cannot extract Ok value from Err result, check isOk first');
return this.value as O; return this.value as O;
} }
@@ -53,10 +60,17 @@ export class Result<O extends Codec, E extends Codec> extends Enum {
} }
/** /**
* @description Checks if the Result wraps an Error value * @description Checks if the Result wraps an Err value
*/
public get isErr (): boolean {
return !this.isOk;
}
/**
* @deprecated Use isErr
*/ */
public get isError (): boolean { public get isError (): boolean {
return !this.isOk; return this.isErr;
} }
/** /**
@@ -70,8 +84,8 @@ export class Result<O extends Codec, E extends Codec> extends Enum {
* @description Returns the base runtime type name for this instance * @description Returns the base runtime type name for this instance
*/ */
public toRawType (): string { public toRawType (): string {
const Types = this._toRawStruct() as { Ok: unknown; Error: unknown }; const Types = this._toRawStruct() as { Ok: unknown; Err: unknown };
return `Result<${Types.Ok as string},${Types.Error as string}>`; return `Result<${Types.Ok as string},${Types.Err as string}>`;
} }
} }
+2 -2
View File
@@ -117,10 +117,10 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
registry.getOrUnknown(value.type), registry.getOrUnknown(value.type),
[TypeDefInfo.Result]: (registry: Registry, value: TypeDef): Constructor => { [TypeDefInfo.Result]: (registry: Registry, value: TypeDef): Constructor => {
const [Ok, Error] = getTypeClassArray(value); const [Ok, Err] = getTypeClassArray(value);
// eslint-disable-next-line @typescript-eslint/no-use-before-define // eslint-disable-next-line @typescript-eslint/no-use-before-define
return Result.with({ Error, Ok }); return Result.with({ Err, Ok });
}, },
[TypeDefInfo.Set]: (registry: Registry, value: TypeDef): Constructor => { [TypeDefInfo.Set]: (registry: Registry, value: TypeDef): Constructor => {
+1 -1
View File
@@ -66,7 +66,7 @@ describe('createType', (): void => {
it('allows creation of a Result', (): void => { it('allows creation of a Result', (): void => {
expect( expect(
createTypeUnsafe(registry, 'Result<u32,Text>', ['0x011064656667']).toJSON() createTypeUnsafe(registry, 'Result<u32,Text>', ['0x011064656667']).toJSON()
).toEqual({ Error: 'defg' }); ).toEqual({ Err: 'defg' });
}); });
it('allows creation of a Set', (): void => { it('allows creation of a Set', (): void => {
+3 -3
View File
@@ -134,7 +134,7 @@ export class TypeRegistry implements Registry {
#signedExtensions: string[] = defaultExtensions; #signedExtensions: string[] = defaultExtensions;
#userExtensions?: Record<string, ExtDef>; #userExtensions?: ExtDef;
constructor () { constructor () {
this.#knownDefaults = { Json, Metadata, Raw, ...baseTypes }; this.#knownDefaults = { Json, Metadata, Raw, ...baseTypes };
@@ -377,7 +377,7 @@ export class TypeRegistry implements Registry {
} }
// sets the metadata // sets the metadata
public setMetadata (metadata: Metadata, signedExtensions?: string[], userExtensions?: Record<string, ExtDef>): void { public setMetadata (metadata: Metadata, signedExtensions?: string[], userExtensions?: ExtDef): void {
injectExtrinsics(this, metadata, this.#metadataCalls); injectExtrinsics(this, metadata, this.#metadataCalls);
injectErrors(this, metadata, this.#metadataErrors); injectErrors(this, metadata, this.#metadataErrors);
injectEvents(this, metadata, this.#metadataEvents); injectEvents(this, metadata, this.#metadataEvents);
@@ -399,7 +399,7 @@ export class TypeRegistry implements Registry {
} }
// sets the available signed extensions // sets the available signed extensions
setSignedExtensions (signedExtensions: string[] = defaultExtensions, userExtensions?: Record<string, ExtDef>): void { setSignedExtensions (signedExtensions: string[] = defaultExtensions, userExtensions?: ExtDef): void {
this.#signedExtensions = signedExtensions; this.#signedExtensions = signedExtensions;
this.#userExtensions = userExtensions; this.#userExtensions = userExtensions;
@@ -28,8 +28,8 @@ describe('EthereumLookupSource', (): void => {
); );
testDecode( testDecode(
'AccountIndex (mixed prefixes)', 'AccountIndex (mixed prefixes)',
registry.createType('EthereumLookupSource', '2jpAFn'), registry.createType('EthereumLookupSource', '118r'),
// NOTE Expected address here is encoded with prefix 42, input above with 68 // NOTE Expected address here is encoded with prefix 42, input above with 1
'25GUyv' '25GUyv'
); );
testDecode( testDecode(
@@ -98,7 +98,7 @@ describe('EthereumLookupSource', (): void => {
it('equals on AccountIndex', (): void => { it('equals on AccountIndex', (): void => {
// see the test below - these are equivalent (with different prefix encoding) // see the test below - these are equivalent (with different prefix encoding)
expect(registry.createType('EthereumLookupSource', '2jpAFn').eq('25GUyv')).toBe(true); expect(registry.createType('EthereumLookupSource', '118r').eq('25GUyv')).toBe(true);
}); });
}); });
}); });
@@ -1,7 +1,9 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export const emptyCheck = { import type { ExtInfo } from './types';
export const emptyCheck: ExtInfo = {
extrinsic: {}, extrinsic: {},
payload: {} payload: {}
}; };
@@ -3,17 +3,14 @@
import type { ExtDef, ExtInfo, ExtTypes } from './types'; import type { ExtDef, ExtInfo, ExtTypes } from './types';
import polkadotExtensions from './polkadot'; import { polkadot } from './polkadot';
import substrateExtensions from './substrate'; import { substrate } from './substrate';
// A mapping of the known signed extensions to the extra fields that they contain. Unlike in the actual extensions, // A mapping of the known signed extensions to the extra fields that they contain. Unlike in the actual extensions,
// we define the extra fields not as a Tuple, but rather as a struct so they can be named. These will be expanded // we define the extra fields not as a Tuple, but rather as a struct so they can be named. These will be expanded
// into the various fields when added to the payload (we only support V4 onwards with these, V3 and earlier are // into the various fields when added to the payload (we only support V4 onwards with these, V3 and earlier are
// deemed fixed and non-changeable) // deemed fixed and non-changeable)
const allExtensions: ExtDef = { const allExtensions: ExtDef = { ...substrate, ...polkadot };
...substrateExtensions,
...polkadotExtensions
};
// the v4 signed extensions (the order is important here, as applied by default) // the v4 signed extensions (the order is important here, as applied by default)
const defaultExtensions: Array<keyof typeof allExtensions> = [ const defaultExtensions: Array<keyof typeof allExtensions> = [
@@ -26,15 +23,16 @@ const defaultExtensions: Array<keyof typeof allExtensions> = [
'CheckBlockGasLimit' 'CheckBlockGasLimit'
]; ];
function findUnknownExtensions (extensions: string[], userExtensions: Record<string, ExtDef> = {}): string[] { function findUnknownExtensions (extensions: string[], userExtensions: ExtDef = {}): string[] {
const names = [...Object.keys(allExtensions), ...Object.keys(userExtensions)]; const names = [...Object.keys(allExtensions), ...Object.keys(userExtensions)];
return extensions.filter((key) => !names.includes(key)); return extensions.filter((key) => !names.includes(key));
} }
function expandExtensionTypes (extensions: string[], type: keyof ExtInfo, userExtensions: Record<string, ExtDef> = {}): ExtTypes { function expandExtensionTypes (extensions: string[], type: keyof ExtInfo, userExtensions: ExtDef = {}): ExtTypes {
return extensions return extensions
.map((key) => allExtensions[key] || userExtensions[key]) // Always allow user extensions first - these should provide overrides
.map((key) => userExtensions[key] || allExtensions[key])
.filter((info): info is ExtInfo => !!info) .filter((info): info is ExtInfo => !!info)
.reduce((result, info): ExtTypes => ({ ...result, ...info[type] }), {}); .reduce((result, info): ExtTypes => ({ ...result, ...info[type] }), {});
} }
@@ -5,11 +5,11 @@ import type { ExtDef } from './types';
import { emptyCheck } from './emptyCheck'; import { emptyCheck } from './emptyCheck';
export default { export const polkadot: ExtDef = {
LimitParathreadCommits: emptyCheck, LimitParathreadCommits: emptyCheck,
OnlyStakingAndClaims: emptyCheck, OnlyStakingAndClaims: emptyCheck,
PrevalidateAttests: emptyCheck, PrevalidateAttests: emptyCheck,
RestrictFunctionality: emptyCheck, RestrictFunctionality: emptyCheck,
TransactionCallFilter: emptyCheck, TransactionCallFilter: emptyCheck,
ValidateDoubleVoteReports: emptyCheck ValidateDoubleVoteReports: emptyCheck
} as ExtDef; };
@@ -1,11 +1,11 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { ExtDef } from './types'; import type { ExtDef, ExtInfo } from './types';
import { emptyCheck } from './emptyCheck'; import { emptyCheck } from './emptyCheck';
const CheckMortality = { const CheckMortality: ExtInfo = {
extrinsic: { extrinsic: {
era: 'ExtrinsicEra' era: 'ExtrinsicEra'
}, },
@@ -14,7 +14,7 @@ const CheckMortality = {
} }
}; };
export default { export const substrate: ExtDef = {
ChargeTransactionPayment: { ChargeTransactionPayment: {
extrinsic: { extrinsic: {
tip: 'Compact<Balance>' tip: 'Compact<Balance>'
@@ -57,4 +57,4 @@ export default {
CheckWeight: emptyCheck, CheckWeight: emptyCheck,
LockStakingStatus: emptyCheck, LockStakingStatus: emptyCheck,
ValidateEquivocationReport: emptyCheck ValidateEquivocationReport: emptyCheck
} as ExtDef; };
+10 -10
View File
@@ -90,7 +90,7 @@ describe('AccountId', (): void => {
])); ]));
it('decodes to a non-empty value', (): void => { it('decodes to a non-empty value', (): void => {
expect(registry.createType('AccountId', '7qT1BvpawNbqb3BZaBTMFMMAKrpJKLPf1LmEHR1JyarWJdMX').isEmpty).toBe(false); expect(registry.createType('AccountId', 'FVU8T5yaAssHAUwo3PnKso7fqNthEqJZGCZgJZSR9cKjWAf').isEmpty).toBe(false);
}); });
}); });
@@ -98,7 +98,7 @@ describe('AccountId', (): void => {
it('has the correct entries', (): void => { it('has the correct entries', (): void => {
registry.setChainProperties( registry.setChainProperties(
registry.createType('ChainProperties', { registry.createType('ChainProperties', {
ss58Format: 68 ss58Format: 2
}) })
); );
@@ -106,14 +106,14 @@ describe('AccountId', (): void => {
const list = registry.createType('Vec<AccountId>', data).map((accountId) => accountId.toString()); const list = registry.createType('Vec<AccountId>', data).map((accountId) => accountId.toString());
expect(list).toEqual([ expect(list).toEqual([
'7qVJujLF3EDbZt5WfQXWvueFedMS4Vfk2Hb4GyR8jwksTLup', 'FXmrFbdg2VdG1NttGTx1S6Czbv2SQ7PaD2PfryGBWWgt52i',
'7pHyqeYaJjJPgxQgCXoS2EZMhBhtpm6BLCqQ4jJZTQB2kMhw', 'ELSnAoxwXaRP5i4RPjs6m1K3AGVCfXpt8GjTcrgtxvrAuZv',
'7pYLWV6PTUmLTMQfHmmuBwBNLkhcKhRAnkM36CSJtjat9ACb', 'EaoT1Mn6H3N9Ui3WdiLGTdKgjGChbrpLfnNV5zSLJLhZvgj',
'7qT1BvpawNbqb3BZaBTMFMMAKrpJKLPf1LmEHR1JyarWJdMX', 'FVU8T5yaAssHAUwo3PnKso7fqNthEqJZGCZgJZSR9cKjWAf',
'7rADc9JW5EUGFPWLjPMipH4c3bJ2GyAUedmqQHiaGucWVrsT', 'GCgYfZti2kHwWoixFJ9toWZPZrcesc8CZDAoBGhiUNKvTQM',
'7oK5KRH6jt4p8auipnru9ptqeuRwbLMHA2tgCViZzhmW4Lox', 'DMYFwYVNgLqpiD73eoLEMLnzszXyEnvhxL1bPGhSGXKV8kS',
'7ndAVsHvonnzTg4AvRhpraNCKj9g4CGQXKoLrgkTZ91Na6PE', 'CfdSPZKSb529oMZ9HeFw6p9fhiGS6i45FEgFaJazhmBzsxZ',
'7oL7VfXgLA8L3pJJwi11v3sBYc1b5R3tLrweHwzMNxgEpjxP' 'DNaSBo4xxQMjwbhAZwSzaK8taaBTKVXtnNygqYUpXS4FMwN'
]); ]);
}); });
}); });
@@ -44,7 +44,7 @@ describe('AccountIndex', (): void => {
}); });
it('compares numbers', (): void => { it('compares numbers', (): void => {
expect(registry.createType('AccountIndex', '2jpAFn').eq(256 * 1)).toBe(true); expect(registry.createType('AccountIndex', '118r').eq(256 * 1)).toBe(true);
}); });
describe('calcLength', (): void => { describe('calcLength', (): void => {
@@ -23,7 +23,7 @@ describe('LookupSource', (): void => {
it('equals on AccountIndex', (): void => { it('equals on AccountIndex', (): void => {
// see the test below - these are equivalent (with different prefix encoding) // see the test below - these are equivalent (with different prefix encoding)
expect(registry.createType('IndicesLookupSource', '2jpAFn').eq('25GUyv')).toBe(true); expect(registry.createType('IndicesLookupSource', '118r').eq('25GUyv')).toBe(true);
}); });
}); });
@@ -40,8 +40,8 @@ describe('LookupSource', (): void => {
); );
testDecode( testDecode(
'AccountIndex (mixed prefixes)', 'AccountIndex (mixed prefixes)',
registry.createType('IndicesLookupSource', '2jpAFn'), registry.createType('IndicesLookupSource', '118r'),
// NOTE Expected adress here is encoded with prefix 42, input above with 68 // NOTE Expected adress here is encoded with prefix 42, input above with 1
'25GUyv' '25GUyv'
); );
testDecode( testDecode(
@@ -83,7 +83,7 @@ describe('LookupSource', (): void => {
'Mwz15xP2' 'Mwz15xP2'
); );
// FIXME The specification allows for 8 byte addresses, however since AccountIndex is u32 internally // FIXME The specification allows for 8 byte addresses, however since AccountIndex is u32 internally
// (and defined that way in thd efault Substrate),this does not actually work since it is 8 bytes, // (and defined that way in the default Substrate),this does not actually work since it is 8 bytes,
// instead of 4 bytes max u32 length // instead of 4 bytes max u32 length
// testDecode( // testDecode(
// 'Uint8Array (with prefix 8 bytes)', // 'Uint8Array (with prefix 8 bytes)',
@@ -73,6 +73,13 @@ const types: DefinitionsTypes = {
Null: 'Null' Null: 'Null'
} }
}, },
EthFilterChanges: {
_enum: {
Logs: 'Vec<EthLog>',
Hashes: 'Vec<H256>',
Empty: 'Null'
}
},
EthFilterTopic: { EthFilterTopic: {
_enum: { _enum: {
Single: 'EthFilterTopicInner', Single: 'EthFilterTopicInner',
+38
View File
@@ -131,6 +131,20 @@ export const rpc: DefinitionsRpc = {
], ],
type: 'Bytes' type: 'Bytes'
}, },
getFilterChanges: {
description: 'Returns filter changes since last poll.',
params: [
{ name: 'index', type: 'U256' }
],
type: 'EthFilterChanges'
},
getFilterLogs: {
description: 'Returns all logs matching given filter (in a range \'from\' - \'to\').',
params: [
{ name: 'index', type: 'U256' }
],
type: 'Vec<EthLog>'
},
getLogs: { getLogs: {
description: 'Returns logs matching given filter object.', description: 'Returns logs matching given filter object.',
params: [ params: [
@@ -239,6 +253,23 @@ export const rpc: DefinitionsRpc = {
params: [], params: [],
type: 'bool' type: 'bool'
}, },
newBlockFilter: {
description: 'Returns id of new block filter.',
params: [],
type: 'U256'
},
newFilter: {
description: 'Returns id of new filter.',
params: [
{ name: 'filter', type: 'EthFilter' }
],
type: 'U256'
},
newPendingTransactionFilter: {
description: 'Returns id of new block filter.',
params: [],
type: 'U256'
},
protocolVersion: { protocolVersion: {
description: 'Returns protocol version encoded as a string (quotes are necessary).', description: 'Returns protocol version encoded as a string (quotes are necessary).',
params: [], params: [],
@@ -292,5 +323,12 @@ export const rpc: DefinitionsRpc = {
description: 'Returns an object with data about the sync status or false.', description: 'Returns an object with data about the sync status or false.',
params: [], params: [],
type: 'EthSyncStatus' type: 'EthSyncStatus'
},
uninstallFilter: {
description: 'Uninstalls filter.',
params: [
{ name: 'index', type: 'U256' }
],
type: 'bool'
} }
}; };
@@ -80,6 +80,15 @@ export interface EthFilterAddress extends Enum {
readonly isNull: boolean; readonly isNull: boolean;
} }
/** @name EthFilterChanges */
export interface EthFilterChanges extends Enum {
readonly isLogs: boolean;
readonly asLogs: Vec<EthLog>;
readonly isHashes: boolean;
readonly asHashes: Vec<H256>;
readonly isEmpty: boolean;
}
/** @name EthFilterTopic */ /** @name EthFilterTopic */
export interface EthFilterTopic extends Enum { export interface EthFilterTopic extends Enum {
readonly isSingle: boolean; readonly isSingle: boolean;
@@ -225,6 +225,9 @@ export default {
ParaInfo: { ParaInfo: {
scheduling: 'Scheduling' scheduling: 'Scheduling'
}, },
ParaLifecycle: {
_enum: ['Onboarding', 'Parathread', 'Parachain', 'UpgradingToParachain', 'DowngradingToParathread', 'OutgoingParathread', 'OutgoingParachain']
},
ParaPastCodeMeta: { ParaPastCodeMeta: {
upgradeTimes: 'Vec<BlockNumber>', upgradeTimes: 'Vec<BlockNumber>',
lastPruned: 'Option<BlockNumber>' lastPruned: 'Option<BlockNumber>'
@@ -569,6 +569,17 @@ export interface ParaInfo extends Struct {
readonly scheduling: Scheduling; readonly scheduling: Scheduling;
} }
/** @name ParaLifecycle */
export interface ParaLifecycle extends Enum {
readonly isOnboarding: boolean;
readonly isParathread: boolean;
readonly isParachain: boolean;
readonly isUpgradingToParachain: boolean;
readonly isDowngradingToParathread: boolean;
readonly isOutgoingParathread: boolean;
readonly isOutgoingParachain: boolean;
}
/** @name ParaPastCodeMeta */ /** @name ParaPastCodeMeta */
export interface ParaPastCodeMeta extends Struct { export interface ParaPastCodeMeta extends Struct {
readonly upgradeTimes: Vec<BlockNumber>; readonly upgradeTimes: Vec<BlockNumber>;
@@ -26,7 +26,11 @@ export interface AccountInfoWithRefCount extends Struct {
/** @name ApplyExtrinsicResult */ /** @name ApplyExtrinsicResult */
export interface ApplyExtrinsicResult extends Result<DispatchOutcome, TransactionValidityError> { export interface ApplyExtrinsicResult extends Result<DispatchOutcome, TransactionValidityError> {
readonly isErr: boolean;
readonly asErr: TransactionValidityError;
/** @deprecated Use isErr */
readonly isError: boolean; readonly isError: boolean;
/** @deprecated Use asErr */
readonly asError: TransactionValidityError; readonly asError: TransactionValidityError;
readonly isOk: boolean; readonly isOk: boolean;
readonly asOk: DispatchOutcome; readonly asOk: DispatchOutcome;
@@ -112,7 +116,11 @@ export interface DispatchInfoTo244 extends Struct {
/** @name DispatchOutcome */ /** @name DispatchOutcome */
export interface DispatchOutcome extends Result<ITuple<[]>, DispatchError> { export interface DispatchOutcome extends Result<ITuple<[]>, DispatchError> {
readonly isErr: boolean;
readonly asErr: DispatchError;
/** @deprecated Use isErr */
readonly isError: boolean; readonly isError: boolean;
/** @deprecated Use asErr */
readonly asError: DispatchError; readonly asError: DispatchError;
readonly isOk: boolean; readonly isOk: boolean;
readonly asOk: ITuple<[]>; readonly asOk: ITuple<[]>;
@@ -120,7 +128,11 @@ export interface DispatchOutcome extends Result<ITuple<[]>, DispatchError> {
/** @name DispatchResult */ /** @name DispatchResult */
export interface DispatchResult extends Result<ITuple<[]>, DispatchError> { export interface DispatchResult extends Result<ITuple<[]>, DispatchError> {
readonly isErr: boolean;
readonly asErr: DispatchError;
/** @deprecated Use isErr */
readonly isError: boolean; readonly isError: boolean;
/** @deprecated Use asErr */
readonly asError: DispatchError; readonly asError: DispatchError;
readonly isOk: boolean; readonly isOk: boolean;
readonly asOk: ITuple<[]>; readonly asOk: ITuple<[]>;
@@ -131,7 +143,11 @@ export interface DispatchResultOf extends DispatchResult {}
/** @name DispatchResultTo198 */ /** @name DispatchResultTo198 */
export interface DispatchResultTo198 extends Result<ITuple<[]>, Text> { export interface DispatchResultTo198 extends Result<ITuple<[]>, Text> {
readonly isErr: boolean;
readonly asErr: Text;
/** @deprecated Use isErr */
readonly isError: boolean; readonly isError: boolean;
/** @deprecated Use asErr */
readonly asError: Text; readonly asError: Text;
readonly isOk: boolean; readonly isOk: boolean;
readonly asOk: ITuple<[]>; readonly asOk: ITuple<[]>;
+3 -2
View File
@@ -49,6 +49,7 @@ export interface OverrideBundleDefinition {
derives?: DeriveCustom; derives?: DeriveCustom;
instances?: Record<string, string[]>; instances?: Record<string, string[]>;
rpc?: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>; rpc?: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>;
signedExtensions?: ExtDef;
types?: OverrideVersionedType[]; types?: OverrideVersionedType[];
} }
@@ -116,6 +117,6 @@ export interface Registry {
register (arg1: string | Constructor | RegistryTypes, arg2?: Constructor): void; register (arg1: string | Constructor | RegistryTypes, arg2?: Constructor): void;
setChainProperties (properties?: ChainProperties): void; setChainProperties (properties?: ChainProperties): void;
setHasher (hasher?: (data: Uint8Array) => Uint8Array): void; setHasher (hasher?: (data: Uint8Array) => Uint8Array): void;
setMetadata (metadata: Metadata, signedExtensions?: string[], userExtensions?: Record<string, ExtDef>): void; setMetadata (metadata: Metadata, signedExtensions?: string[], userExtensions?: ExtDef): void;
setSignedExtensions (signedExtensions?: string[], userExtensions?: Record<string, ExtDef>): void; setSignedExtensions (signedExtensions?: string[], userExtensions?: ExtDef): void;
} }
+1059 -927
View File
File diff suppressed because it is too large Load Diff