Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
daaf4654a1 | ||
|
|
f8d4fcaf04 | ||
|
|
eb19a39d82 | ||
|
|
7ed958fb2d | ||
|
|
bbe9b94f26 | ||
|
|
6e83e6aaef | ||
|
|
1545bbf7c5 | ||
|
|
5bfc2cd534 | ||
|
|
b22d0a196f | ||
|
|
b174864804 | ||
|
|
e6834d60c5 | ||
|
|
97438bb2e8 | ||
|
|
f630d43a25 | ||
|
|
0187f1ff19 | ||
|
|
d8db866316 | ||
|
|
28aa9e18a7 | ||
|
|
3eaea97b8f | ||
|
|
ea0e5e4547 | ||
|
|
1256317b65 | ||
|
|
e0c3ed1b96 | ||
|
|
9f2c3016d7 | ||
|
|
938ace2342 | ||
|
|
e5d2607dff | ||
|
|
50b8db2263 | ||
|
|
91766a6885 | ||
|
|
4b1a9ab9e1 | ||
|
|
9a14c65336 | ||
|
|
4aa66fd4c6 | ||
|
|
3d9c62d538 | ||
|
|
4156eb44ab | ||
|
|
4b2d33693c | ||
|
|
e8b127e177 | ||
|
|
b052b03f31 | ||
|
|
6727e12468 | ||
|
|
c130285651 | ||
|
|
47fc4a2b3c |
@@ -10,7 +10,7 @@ jobs:
|
||||
matrix:
|
||||
step: ['build:release', 'docs:release']
|
||||
name: ${{ matrix.step }}
|
||||
if: "! contains(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
|
||||
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
@@ -21,16 +21,13 @@ jobs:
|
||||
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
|
||||
GH_PAGES_SRC: build-docs
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_RELEASE_GITHUB_API_TOKEN: ${{ secrets.GH_PAT }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn ${{ matrix.step }}
|
||||
|
||||
dummy:
|
||||
name: Dummy
|
||||
if: "contains(github.event.head_commit.message, '[CI Skip]')"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: dummy
|
||||
|
||||
+101
-80
@@ -1,4 +1,25 @@
|
||||
# 1.15.1 May 23, 2020
|
||||
# CHANGELOG
|
||||
|
||||
## 1.17.1 Jun 2, 2020
|
||||
|
||||
- Fix `ElectionSize` type (Thanks to https://github.com/arjanz)
|
||||
- Allow `BTreeSet` decoding from Array/JSON inputs
|
||||
- Adjust Call-only metadata output to trim documentation to first full line
|
||||
- Safeguard against divide-by-zero for total era points (expired reward eras)
|
||||
- Internal derive optimizations with combining calls
|
||||
- Support for latest Substrate types & metadata
|
||||
- `@polkadot/util` 2.12
|
||||
|
||||
## 1.16.1 May 26, 2020
|
||||
|
||||
- Support for Polkadot CC1 types & signed extensions
|
||||
- Add support for Babe VRF secondary digests (author extraction)
|
||||
- Adjust `Perbill/Permill` `toHuman()` formatting to output percentage
|
||||
- Support for latest Substrate types & metadata
|
||||
- Update to latest TypeScript, eslint & typescript-eslint
|
||||
- `@polkadot/util` 2.11
|
||||
|
||||
## 1.15.1 May 23, 2020
|
||||
|
||||
- Adjust `keyPrefix()` with DoubleMap args (Thanks to https://github.com/KiChjang)
|
||||
- Added `WeightToFeeCoefficient` type (Thanks to https://github.com/danforbes)
|
||||
@@ -10,7 +31,7 @@
|
||||
- Adjust `Multiplier` type to `Fixed128` (as per latest Substrate)
|
||||
- Updated to latest Substrate metadata & add new types
|
||||
|
||||
# 1.14.1 May 14, 2020
|
||||
## 1.14.1 May 14, 2020
|
||||
|
||||
- **Important** `DispatchInfo` changed `paysFee` to an enum, if using an older version use, `DispatchInfo: 'DispatchInfoTo244'`
|
||||
- Align imOnline `Heartbeat` with Substrate (Thanks to https://github.com/arjanz)
|
||||
@@ -27,7 +48,7 @@
|
||||
- Extends types for Polkadot claims
|
||||
- Update `@polkadot/util` to 2.10
|
||||
|
||||
# 1.13.1 May 6, 2020
|
||||
## 1.13.1 May 6, 2020
|
||||
|
||||
- Add support for ECDSA keypairs in extrinsic signers (Thanks to https://github.com/akru)
|
||||
- Rework type generation to use templating for better maintenance (Thanks to https://github.com/xlc)
|
||||
@@ -40,11 +61,11 @@
|
||||
- Update types & metadata as per latest Substrate master
|
||||
- Adjust Centrifuge starting version
|
||||
|
||||
# 1.12.2 Apr 30, 2020
|
||||
## 1.12.2 Apr 30, 2020
|
||||
|
||||
- Update `@polkadot/util` to stable 2.9.1 (sadly missed in the previous version, stable should match to stable)
|
||||
|
||||
# 1.12.1 Apr 29, 2020
|
||||
## 1.12.1 Apr 29, 2020
|
||||
|
||||
- Fix `CompactAssignments` types (Thanks to https://github.com/arjanz)
|
||||
- Provider ayo-connect now allows for interval config (Thanks to https://github.com/jnaviask)
|
||||
@@ -55,11 +76,11 @@
|
||||
- Allow generic types in ApiPromise.combineLatest
|
||||
- Update to latest substrate metadata
|
||||
|
||||
# 1.11.2 Apr 22, 2020
|
||||
## 1.11.2 Apr 22, 2020
|
||||
|
||||
- Small patch to add missing Polkadot master types (will be in next Kusama update)
|
||||
|
||||
# 1.11.1 Apr 21, 2020
|
||||
## 1.11.1 Apr 21, 2020
|
||||
|
||||
- **Important** Substrate master has an updated `Weight` (to `u64`), on older chains apply `Weight: 'u32'` (This does affect event decoding if wrongly set)
|
||||
- Allow user type augmentation to work with different versions of rxjs (Thanks to https://github.com/monitz87)
|
||||
@@ -78,7 +99,7 @@
|
||||
- Enhance API support for non-subscription providers (skip subscription to runtimeVersion)
|
||||
- Adjust types for Kusama 1057 (notably the new `StakingLedger`)
|
||||
|
||||
# 1.10.1 Apr 13, 2020
|
||||
## 1.10.1 Apr 13, 2020
|
||||
|
||||
- **Important** Substrate master has updated staking, on older chains apply `StakingLedger: 'StakingLedgerTo240'`
|
||||
- Add `rpc.system.chainType` to retrieve the chain type (Development. Local, Live & Custom)
|
||||
@@ -91,7 +112,7 @@
|
||||
- Internally all private/protected methods/variables are now `_` prefixed (Aligning with the `private/protected` indicators in the TS definitions)
|
||||
- Update metadata/docs-from-metadata to the latest Substrate
|
||||
|
||||
# 1.9.1 Apr 1, 2020
|
||||
## 1.9.1 Apr 1, 2020
|
||||
|
||||
- **Breaking change** (TypeScript with derives only) The return type names for `api.derive.*` have been adjusted for consistency, all starting with `Derive*` (previously a mixture of `Derived*` and `Derive*`)
|
||||
- **Breaking change** (derives only) Additional cleanups of democracy proposal & referenda derives, including support for new Polkadot/Substrate vote retrievals
|
||||
@@ -106,7 +127,7 @@
|
||||
- Fix encoding for `Vec<u8>`-related types as part of constants
|
||||
- Internal adjustment of interface type locations (no impact on imports via `@polkadot/types/interfaces`)
|
||||
|
||||
# 1.8.1 Mar 22, 2020
|
||||
## 1.8.1 Mar 22, 2020
|
||||
|
||||
- **Breaking change** The format for any custom RPCs have been changed (alongside API-internal changes) to allow for better RPC management. If you are currently using custom RPCs (or planning to do so), look at the [updated documentation](https://polkadot.js.org/api/start/rpc.custom.html)
|
||||
- **Breaking change** Alongside API RPC changes, the `@polkadot/jsonrpc` package has been removed. Since it was never documented and only used internally, this should not have adverse impacts. All RPC definitions itself has now been moved to the relevant modules inside `@polkadot/types/interfaces`
|
||||
@@ -118,7 +139,7 @@
|
||||
- Adjusted referendum derives to cater for bot new/old democracy. Derived `referendumInfo` now includes `status` field, not `info`
|
||||
- Add `initWasm` flag to API options. When set to `false` does not init the WASM portion (leaving it to the user elsewhere)
|
||||
|
||||
# 1.7.1 Mar 17, 2020
|
||||
## 1.7.1 Mar 17, 2020
|
||||
|
||||
- **Important** Current versions of Polkadot/Substrate have dropped support for linked maps on storage entries. If you are using these queries to retrieve all entries, for instance `staking.{nominators,validators}()` and using an upgraded chain, you need to swap to retrieving entries via `.entries()` or `.keys()` for the keys.
|
||||
- Pull in support and types for latest Polkadot/Substrate
|
||||
@@ -128,11 +149,11 @@
|
||||
- Expanded `derive.staking.*` derives, including addition of `derive.staking.own*`
|
||||
- Re-add fixed (with tests) checks for query args, previously disabled in 1.6.2
|
||||
|
||||
# 1.6.2 Mar 12, 2020
|
||||
## 1.6.2 Mar 12, 2020
|
||||
|
||||
- Revert checks for query args, not working on `.at()` queries (proper fix in next version)
|
||||
|
||||
# 1.6.1 Mar 12, 2020
|
||||
## 1.6.1 Mar 12, 2020
|
||||
|
||||
- **Breaking change** `api.rpc.state.queryStorage(...)` now fully decodes the `Vec<StorageChangeSet>` and returns a decoded `[Hash, Codec[]][]` when using this RPC.
|
||||
- `StorageKey` now has an `.args` property, decoded from meta where `twox64_concat` or `blake128_concat` are used on maps
|
||||
@@ -146,7 +167,7 @@
|
||||
- Add runtime validation for map arguments to `api.query.*`
|
||||
- TypeScript interfaces for linked maps now correctly generates as `[Type, Linkage<Next>]`
|
||||
|
||||
# 1.5.1 Mar 06, 2020
|
||||
## 1.5.1 Mar 06, 2020
|
||||
|
||||
- **Important** Substrate master has updated staking, on older chains supply `StakingLedger: 'StakingLedgerTo223'`
|
||||
- **Important** Substrate master has updated collective, on older chains supply `Votes: 'VotesTo230'`
|
||||
@@ -166,11 +187,11 @@
|
||||
- Add additional derives to `api.derive.staking` to handle lazy-payout retrievals
|
||||
- Update `@polkadot/{util, util-crypto, keyring}` to 1.6.1 & `@polkadot/wasm` to 1.2.1
|
||||
|
||||
# 1.4.2 Feb 27, 2020
|
||||
## 1.4.2 Feb 27, 2020
|
||||
|
||||
- Fix `api.tx(<extrinsic>): Submittable` decoration (non-working in 1.4.1, now with proper test)
|
||||
|
||||
# 1.4.1 Feb 26, 2020
|
||||
## 1.4.1 Feb 26, 2020
|
||||
|
||||
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features (specifically `#private`), which is not usable in TS versions < 3.8
|
||||
- **Breaking change** - `api.derive.staking.*` has updated result types and detects support for lazy payouts queries
|
||||
@@ -196,7 +217,7 @@
|
||||
- Cleanup augmentation and generation scripts for type definitions, aligning with api augmentation
|
||||
- Bump to `@polkadot/{util, util-crypto, keyring}` 2.5.1
|
||||
|
||||
# 1.3.1 Feb 18, 2020
|
||||
## 1.3.1 Feb 18, 2020
|
||||
|
||||
- Add `@types/bn.js` as a normal dependency, exposed in `*.d.ts` (Thanks to https://github.com/monitz87)
|
||||
- Type generation scripts (including `polkadot-types-from-{chain,defs}`) has been moved to the `@polkadot/typegen` package
|
||||
@@ -204,7 +225,7 @@
|
||||
- Expose chain properties on registry (and use for API type formatting)
|
||||
- Add `toHuman(isExtended?: boolean)` to all codec types, formatting into a human-readable structure
|
||||
|
||||
# 1.2.1 Feb 16, 2020
|
||||
## 1.2.1 Feb 16, 2020
|
||||
|
||||
- **Important** Update RPC status codes (latest Substrate 2), with the `isInBlock` (`isFinalized` now indicates finality)
|
||||
- Storage `.entries(arg?: any)` now has the correct argument type for DoubleMap (Thanks to https://github.com/monitz87)
|
||||
@@ -222,7 +243,7 @@
|
||||
- Cleanup `codec/Date` tests to make it run properly on all timezones
|
||||
- Add explicit dependencies to all packages and move TypeScript `@types/*` to dev deps
|
||||
|
||||
# 1.1.1 Feb 06, 2020
|
||||
## 1.1.1 Feb 06, 2020
|
||||
|
||||
- **Important** Chains without `balances.account` or `system.account` should supply `"BalanceLock": "BalanceLockTo212"` to their types to use the previous-generation `BalanceLock` (when querying locks)
|
||||
- Add support for `balances.account` in all applicable derives (incl. `vesting` module)
|
||||
@@ -236,7 +257,7 @@
|
||||
- Adjust balances fees derivation with optional transfer and creation fees (removed in Substrate)
|
||||
- Adjust enum `.toJSON()` to return type name as specified
|
||||
|
||||
# 1.0.1 Jan 30, 2020
|
||||
## 1.0.1 Jan 30, 2020
|
||||
|
||||
- **Breaking change** Drop support for Substrate v1 chain in all derives
|
||||
- Return unsub functions from provider .on emitters (Thanks to https://github.com/jak-pan)
|
||||
@@ -255,7 +276,7 @@
|
||||
- Remove support for un-deployed metadata
|
||||
- Remove old known types for Substrate V1
|
||||
|
||||
# 0.100.1 Jan 13, 2020
|
||||
## 0.100.1 Jan 13, 2020
|
||||
|
||||
- **Important** This will the the last API version with Substrate 1.x support. Although you will still be able to use subsequent versions with older chains, dependent libraries such as sr25519 may not be compatible.
|
||||
- Add support for the Substrate identity module
|
||||
@@ -266,7 +287,7 @@
|
||||
- Add support for latest Polkadot/Substrate types
|
||||
- Add `paymentInfo` to submittables to calculate fees
|
||||
|
||||
# 0.99.1 Dec 13, 2019
|
||||
## 0.99.1 Dec 13, 2019
|
||||
|
||||
- **Breaking change** The `Data` and `U8a` type has been renamed and just replaced with the `Raw` type
|
||||
- **Breaking change** The `api.derive.staking.info` has been split into 2 - `staking.query` for non-balance related information (more effective) and `staking.account` that enhances query for all the information previously found `.info`
|
||||
@@ -275,7 +296,7 @@
|
||||
- Add additional derives for both council & treasury
|
||||
- Alignment with latest Polkadot/Substrate master branch types
|
||||
|
||||
# 0.98.1 Dec 04, 2019
|
||||
## 0.98.1 Dec 04, 2019
|
||||
|
||||
- Make the TypeScript generation script mor re-usable (Thanks to https://github.com/xlc)
|
||||
- Add `.entries()` for all map-types, returning storage keys and values
|
||||
@@ -284,7 +305,7 @@
|
||||
- Support for new Substrate democracy with preimages in derive
|
||||
- Alignment of types with Substrate/Polkadot master branches
|
||||
|
||||
# 0.97.1 Nov 29, 2019
|
||||
## 0.97.1 Nov 29, 2019
|
||||
|
||||
- **Breaking change** Add the passing on an explicit `Registry` to all calls to `createType` as well as all codec classes. If you are upgrading form an older version, use the [migration guide](UPGRADING.md) to walk through the changes required.
|
||||
- **Breaking change** The metadata classes have been moved from `@polkadot/types` into `@polkadot/metadata`. If you explicitly create `Metadata` classes, you now would need to do so with the `import Metadata from '@polkadot/metadata';` This is a decorated class, where the previous metadata is now available on `Metadata.metadata`, alongside decorated `consts.*`', `tx.*` and `query.*`.
|
||||
@@ -296,7 +317,7 @@
|
||||
- Support for Metadata V9, which adjusts the hashing methods of storage entries
|
||||
- Support for Metadata V10 (still un-released), which includes prefixed map support
|
||||
|
||||
# 0.96.1 Nov 09, 2019
|
||||
## 0.96.1 Nov 09, 2019
|
||||
|
||||
- Updated types for latest Kusama
|
||||
- Add `filterRecords` (in addition to `findRecord`) on submittable results
|
||||
@@ -306,11 +327,11 @@
|
||||
- Update council derives for the latest Substrate master support (with constants)
|
||||
- Derive cleanups, including sharing of instances between the API and internal to derives
|
||||
|
||||
# 0.95.2 Oct 25, 2019
|
||||
## 0.95.2 Oct 25, 2019
|
||||
|
||||
- Temporary removal of `account_nextIndex` use, will be re-added in a future release
|
||||
|
||||
# 0.95.1 Oct 25, 2019
|
||||
## 0.95.1 Oct 25, 2019
|
||||
|
||||
- Support Extrinsic V4 with additional signature indicator (Latest Polkadot/Substrate/Kusama)
|
||||
- Adjust subscription update checks to avoid duplicated data updates
|
||||
@@ -320,7 +341,7 @@
|
||||
- All latest Polkadot & Substrate types (as per master branches)
|
||||
- **Breaking change** `Call.injectMethods` is moved to `Call.injectMetadata` to align with `Events` (This _should_ not be used externally, however mentioned as breaking here)
|
||||
|
||||
# 0.94.1 Oct 07, 2019
|
||||
## 0.94.1 Oct 07, 2019
|
||||
|
||||
- Add handling of `Result<Ok, Error>` definitions
|
||||
- Adjust API cloning now takes RPC filters from source into account
|
||||
@@ -332,7 +353,7 @@
|
||||
- Add documentation for custom extrinsic formats (advanced chains)
|
||||
- Update to latest substrate master metadata
|
||||
|
||||
# 0.93.1 Sep 26, 2019
|
||||
## 0.93.1 Sep 26, 2019
|
||||
|
||||
- Support for Kusama CC2
|
||||
- In extrinsic submission, use `rpc.account.nextIndex` to retrieve the nonce when available
|
||||
@@ -342,7 +363,7 @@
|
||||
- Support recursive type registration (self-referencing via `Box`) in addition to better sanitation of user-defined-types
|
||||
- Documentation and example updates (thanks mostly to contributions)
|
||||
|
||||
# 0.92.1 Sep 12, 2019
|
||||
## 0.92.1 Sep 12, 2019
|
||||
|
||||
- The API now correctly sets the ss58 prefix as retrieved from the chain properties via `ss58Format`
|
||||
- Bump to `@polkadot/util` 1.4.1, removing use of `ExtError`
|
||||
@@ -350,7 +371,7 @@
|
||||
- Support the latest Polkadot & Substrate master branches (incl. metadata updates)
|
||||
- Getting started documentation has been made available
|
||||
|
||||
# 0.91.1 Sep 09, 2019
|
||||
## 0.91.1 Sep 09, 2019
|
||||
|
||||
- This release was focussed on stability, with a number of cleanups and bug-fixes
|
||||
- Adjustments for Substrate 1.x chain detection (with auto-types) and Substrate 2.x support has been extended with all latest types
|
||||
@@ -364,7 +385,7 @@
|
||||
- **Breaking change** `SignerPayload` is renamed to `SignerPayloadJSON`
|
||||
- **Breaking change** `SignerPayloadJSON`, `SignerPayloadRawBase` and `SignerPayloadRaw` are all moved to `@polkadot/types`
|
||||
|
||||
# 0.90.1 Aug 24, 2019
|
||||
## 0.90.1 Aug 24, 2019
|
||||
|
||||
If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md).
|
||||
|
||||
@@ -382,7 +403,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- The `types/codec/createType` has been moved to `types/codec/create` with the same exports. If you explicitly imported from here (and not doing the suggested `import { createType } from '@polkadot/types`), the reference needs to be updated
|
||||
|
||||
|
||||
# 0.82.0-beta.x Jul 28, 2019
|
||||
## 0.82.0-beta.x Jul 28, 2019
|
||||
|
||||
- Support for substrate 2.x (master) has been extended,
|
||||
- Additional types have been addedd for the modules
|
||||
@@ -401,7 +422,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- The `ContractsAbi` type has been moved from `@polkadot/types` to `import { Abi } from '@polkadot/api-contract`. This paves the way for an enhanced contracts interface, instead of dealing with low-level API calls.
|
||||
|
||||
|
||||
# 0.81.1 Jun 14, 2019
|
||||
## 0.81.1 Jun 14, 2019
|
||||
|
||||
- The dependency on `@polkadot/keyring` has been removed - if you relied on the API to provide this, you would now need to manually add it
|
||||
- `createType` allows for the creation of `[u8; <length>]` types (opening the door for contract support)
|
||||
@@ -421,7 +442,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Add `off` method to `Api` (Base, for both `ApiPromise` & `ApiRx`) to remove an event listener
|
||||
|
||||
|
||||
# 0.80.1 Jun 04, 2019
|
||||
## 0.80.1 Jun 04, 2019
|
||||
|
||||
- Support for mortal transactions
|
||||
- Better DoubleMap storage support
|
||||
@@ -431,7 +452,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Misc. cleanups and fixes
|
||||
|
||||
|
||||
# 0.79.1 May 22, 2019
|
||||
## 0.79.1 May 22, 2019
|
||||
|
||||
- DoubleMap query support
|
||||
- Support latest EventRecord metadata (substrate master)
|
||||
@@ -443,7 +464,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Add `toRawType` on all type classes (breakdown into primitive types)
|
||||
|
||||
|
||||
# 0.78.1 May 08, 2019
|
||||
## 0.78.1 May 08, 2019
|
||||
|
||||
- Fix linked-maps (not working since 0.77.1)
|
||||
- Convert Usize to U32 (as found in WASM environments)
|
||||
@@ -454,13 +475,13 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Metadata updates for substrate (WithdrawReasons, ContractInfo)
|
||||
|
||||
|
||||
# 0.77.1 Apr 25, 2019
|
||||
## 0.77.1 Apr 25, 2019
|
||||
|
||||
- Support Metadata v4, which introduces the use of a custom hasher to hash storage map keys.
|
||||
- Add TreasuryProposal (not the same as democracy, type aliased)
|
||||
|
||||
|
||||
# 0.76.1 Apr 03, 2019
|
||||
## 0.76.1 Apr 03, 2019
|
||||
|
||||
- Caching improvements (duplicate queries, no duplicate subscriptions)
|
||||
- Experimental contract API
|
||||
@@ -468,12 +489,12 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Update @polkadot/util-crypto with smaller footprint
|
||||
|
||||
|
||||
# 0.75.1 Mar 29, 2019
|
||||
## 0.75.1 Mar 29, 2019
|
||||
|
||||
- Start journey to 1.0
|
||||
|
||||
|
||||
# 0.53.1 Mar 29, 2019
|
||||
## 0.53.1 Mar 29, 2019
|
||||
|
||||
- Change spelling to US English as per substrate master (1.0-rc1). Breaking changes as a result:
|
||||
- For extrinsic status results, if you have checked the type returns, i.e. `result.type === 'Finalised'` now check on the status for `result.status.isFinalized` or `result.status.isBroadcast`, ... (the `type` property is now accessible only on `result.status.type`)
|
||||
@@ -484,7 +505,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- All examples have been updated with sr25519 addresses (with the new checksums)
|
||||
|
||||
|
||||
# 0.52.1 Mar 28, 2019
|
||||
## 0.52.1 Mar 28, 2019
|
||||
|
||||
- Support queries to linked mapped storage (found in new staking interfaces)
|
||||
- Add `derive.staking.controllers` to retrieve all active staking controllers
|
||||
@@ -494,42 +515,42 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Check for single instances for api and types as they are loaded (assertSingletonPackage)
|
||||
|
||||
|
||||
# 0.51.1 Mar 25, 2019
|
||||
## 0.51.1 Mar 25, 2019
|
||||
|
||||
- Support metadata V2 as per latest substrate master
|
||||
- Update metadata with new types as per latest substrate master
|
||||
|
||||
|
||||
# 0.50.1 Mar 23, 2019
|
||||
## 0.50.1 Mar 23, 2019
|
||||
|
||||
- Latest util-crypto (usage of WASM with JS fallbacks if not available)
|
||||
- Update upstream @polkadot dependencies (for new crypto)
|
||||
|
||||
|
||||
# 0.49.1 Mar 20, 2019
|
||||
## 0.49.1 Mar 20, 2019
|
||||
|
||||
- Fix large message signing on non-known nodes (default is now hashing, there has been enough time between upgrades)
|
||||
|
||||
|
||||
# 0.48.1 Mar 18, 2019
|
||||
## 0.48.1 Mar 18, 2019
|
||||
|
||||
- Pull in new sr25519 capable keyring for dev nodes
|
||||
- When using dev mode, it assumes that the node is the latest with derived sr25519 keys
|
||||
|
||||
|
||||
# 0.47.1 Mar 14, 2019
|
||||
## 0.47.1 Mar 14, 2019
|
||||
|
||||
- Swap to publishing -beta.x on merge (non-breaking testing)
|
||||
|
||||
|
||||
# 0.46.1 Mar 01, 2019
|
||||
## 0.46.1 Mar 01, 2019
|
||||
|
||||
- Extended type registration to now handle internal types as well. Additionally the built-in Extrinsic type can now we overridden with a custom version.
|
||||
- Where `Extrinsic` and `Method` is used as types, consider importing `{ IMethod, IExtrinsic }` from `@polkadot/types/types`, especially in the cases where this is used from a `SubmittableExtrinsic`
|
||||
- The `typeRegistry` constant is now `getTypeRegistry()` as a function
|
||||
|
||||
|
||||
# 0.45.1 Feb 19, 2019
|
||||
## 0.45.1 Feb 19, 2019
|
||||
|
||||
- Storage with option values now correctly return `Option<Type>` and is indicated as such in the documentation
|
||||
|
||||
@@ -546,7 +567,7 @@ console.log('llo', llo.unwrapOr('not set') /* Option<BlockNumber> */)
|
||||
```
|
||||
|
||||
|
||||
# 0.44.1 Feb 19, 2019
|
||||
## 0.44.1 Feb 19, 2019
|
||||
|
||||
- Split primitives and types into separate folders. This should not affect external use since the exports remain the same, however does have an impact where classes are referenced directly. e.g.
|
||||
|
||||
@@ -564,45 +585,45 @@ import { Method, Signature } from '@polkadot/types';
|
||||
```
|
||||
|
||||
|
||||
# 0.43.1 Feb 14, 2019
|
||||
## 0.43.1 Feb 14, 2019
|
||||
|
||||
- Introduces support for the new keyring with sr25519 support in addition to ed25519. While this does not change the exposed API, it is considered breaking since @polkadot/keyring has interface changes. (Unless needed, don't rush the upgrade)
|
||||
|
||||
|
||||
# 0.42.1 Jan 31, 2019
|
||||
## 0.42.1 Jan 31, 2019
|
||||
|
||||
- Support for substrate hash signing with implVersion >= 18
|
||||
- Changed signatures for Extrinsic signing, this should not have (much) of an impact since it is generally not used directly. SubmittableExtrinsic (as exposed by the API), supports the old-style use.
|
||||
|
||||
|
||||
# 0.41.1 Jan 26, 2019
|
||||
## 0.41.1 Jan 26, 2019
|
||||
|
||||
- Support the V1 metadata specification from Substrate in addition to the currently testnet active V0 version
|
||||
|
||||
|
||||
# 0.40.1 Jan 16, 2019
|
||||
## 0.40.1 Jan 16, 2019
|
||||
|
||||
- The API interfaces now require a WS-compatible provider, e.g. subscription support is a must. Previously the HTTPProvider could be use (although it was very limited in the interactions).
|
||||
|
||||
|
||||
# 0.39.1 Jan 11, 2019
|
||||
## 0.39.1 Jan 11, 2019
|
||||
|
||||
- The Promise API now returns a `Promise<UnsubFunction>` instead of `UnsubFunction` when making subscriptions.
|
||||
|
||||
|
||||
# 0.38.1 Jan 08, 2019
|
||||
## 0.38.1 Jan 08, 2019
|
||||
|
||||
Substrate has been updated with a breaking new transaction format where the Index/Nonce is now encoded as a Compact. This change is being rolled out to both Alexander (Polkadot testnet) as well as Charred Cherry (Substrate testnet) - transactions between old and new are not compatible.
|
||||
|
||||
|
||||
# 0.37.1 Jan 04, 2019
|
||||
## 0.37.1 Jan 04, 2019
|
||||
|
||||
api-observable has been removed. This was only used in /apps and inconsistent with the api/rx and api/promise APIs. Future work will include derives like was included in api-observable into the base.
|
||||
|
||||
Tuples now return single types when only one type is available, i.e. `(AccountId)` would now resolve as `AccountId`. The extra type wrapper adds no benefit to users here.
|
||||
|
||||
|
||||
# 0.36.1 Jan 03, 2019
|
||||
## 0.36.1 Jan 03, 2019
|
||||
|
||||
Api Promise has been updated in the way we deal with subscriptions. Previously a subscription returned `Promise<number>` where the caller was to keep track of the id and use it in subsequent unsubscribes. Now any subscriptions return an unsubscribe/destroy function `(): void`, that is use for removing the subscriptions, e.g.
|
||||
|
||||
@@ -613,51 +634,51 @@ unsubscribe(); // here we destroy the subscription
|
||||
```
|
||||
|
||||
|
||||
# 0.35.1 Dec 20, 2018
|
||||
## 0.35.1 Dec 20, 2018
|
||||
|
||||
Swapped to new metadata structures from Substrate. If the API is not working with your node, update Substrate to latest master branch. (Or 0.9.1 for Charred Cherry). Dropped support for old metadata as found as far back as BBQ Birch.
|
||||
|
||||
|
||||
# 0.34.1 Dec 18, 2018
|
||||
## 0.34.1 Dec 18, 2018
|
||||
|
||||
Changed the send signature (for future expansion of eg. events) to return `result: { status: ExtrinsicStatus }` instead of `status: ExtrinsicStatus`. For most cases where only status `type` checks are used, i.e. `status.type === 'Finalised'` this should not be a breaking change. Deep inspection of the status object however will need to adapt.
|
||||
|
||||
# 0.33.1 Dec 06, 2018
|
||||
## 0.33.1 Dec 06, 2018
|
||||
|
||||
# 0.32.1 Nov 21, 2018
|
||||
## 0.32.1 Nov 21, 2018
|
||||
|
||||
# 0.31.1 Oct 10, 2018
|
||||
## 0.31.1 Oct 10, 2018
|
||||
|
||||
# 0.30.1 Sep 27, 2018
|
||||
## 0.30.1 Sep 27, 2018
|
||||
|
||||
# 0.29.1 Sep 14, 2018
|
||||
## 0.29.1 Sep 14, 2018
|
||||
|
||||
# 0.28.1 Aug 11, 2018
|
||||
## 0.28.1 Aug 11, 2018
|
||||
|
||||
# 0.15.1 Aug 07, 2018
|
||||
## 0.15.1 Aug 07, 2018
|
||||
|
||||
# 0.14.1 Jun 23, 2018
|
||||
## 0.14.1 Jun 23, 2018
|
||||
|
||||
# 0.13.1 May 29, 2018
|
||||
## 0.13.1 May 29, 2018
|
||||
|
||||
# 0.12.1 May 18, 2018
|
||||
## 0.12.1 May 18, 2018
|
||||
|
||||
# 0.11.1 May 16, 2018
|
||||
## 0.11.1 May 16, 2018
|
||||
|
||||
# 0.10.1 May 07, 2018
|
||||
## 0.10.1 May 07, 2018
|
||||
|
||||
# 0.9.1 Apr 24, 2018
|
||||
## 0.9.1 Apr 24, 2018
|
||||
|
||||
# 0.8.1 Mar 15, 2018
|
||||
## 0.8.1 Mar 15, 2018
|
||||
|
||||
# 0.7.1 Jan 25, 2018
|
||||
## 0.7.1 Jan 25, 2018
|
||||
|
||||
# 0.6.1 Dec 03, 2017
|
||||
## 0.6.1 Dec 03, 2017
|
||||
|
||||
# 0.5.1 Nov 28, 2017
|
||||
## 0.5.1 Nov 28, 2017
|
||||
|
||||
# 0.4.1 Nov 19, 2017
|
||||
## 0.4.1 Nov 19, 2017
|
||||
|
||||
# 0.3.1 Nov 19, 2017
|
||||
## 0.3.1 Nov 19, 2017
|
||||
|
||||
# 0.2.1 Nov 18, 2017
|
||||
## 0.2.1 Nov 18, 2017
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiPromise, WsProvider } = require('@polkadot/api');
|
||||
|
||||
+1
-1
@@ -9,5 +9,5 @@
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"version": "1.15.1"
|
||||
"version": "1.17.1"
|
||||
}
|
||||
|
||||
+8
-7
@@ -24,14 +24,15 @@
|
||||
"test:watch": "polkadot-dev-run-test --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.9.6",
|
||||
"@babel/register": "^7.9.0",
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/dev": "^0.53.5",
|
||||
"@polkadot/ts": "^0.3.22",
|
||||
"@babel/core": "^7.10.2",
|
||||
"@babel/register": "^7.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/dev": "^0.55.7",
|
||||
"@polkadot/ts": "^0.3.25",
|
||||
"@polkadot/typegen": "workspace:packages/typegen",
|
||||
"@types/jest": "^25.2.3",
|
||||
"@vuepress/plugin-search": "^1.5.0",
|
||||
"copyfiles": "^2.2.0"
|
||||
}
|
||||
"copyfiles": "^2.3.0"
|
||||
},
|
||||
"version": "1.17.1"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-contract",
|
||||
"version": "1.15.1",
|
||||
"version": "1.17.1",
|
||||
"description": "Interfaces for interacting with contracts and contract ABIs",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,11 +26,11 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/api": "1.15.1",
|
||||
"@polkadot/rpc-core": "1.15.1",
|
||||
"@polkadot/types": "1.15.1",
|
||||
"@polkadot/util": "^2.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/api": "1.17.1",
|
||||
"@polkadot/rpc-core": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"bn.js": "^5.1.2",
|
||||
"rxjs": "^6.5.5"
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ function parseSelector (registry: Registry, fnname: string, input: ContractABIMe
|
||||
return registry.createType('u32', hexToU8a(input));
|
||||
} else if (typeof input === 'string') {
|
||||
try {
|
||||
const array = JSON.parse(input);
|
||||
const array = JSON.parse(input) as unknown[];
|
||||
|
||||
assert(array.length === 4, `${fnname}: Invalid selector length`);
|
||||
|
||||
@@ -108,7 +108,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
|
||||
public createMessage (name: string, message: Partial<ContractABIMessage> & ContractABIMessageBase): ContractABIFn {
|
||||
const args = message.args.map(({ name, type }): ContractABIFnArg => {
|
||||
assert(isObject(type), `Invalid type at index ${type}`);
|
||||
assert(isObject(type), `Invalid type at index ${type.toString()}`);
|
||||
|
||||
return {
|
||||
name: stringCamelCase(name),
|
||||
@@ -183,6 +183,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
public convertMessage ({ args, name, return_type: returnType, ...message }: ContractABIMessagePre): ContractABIMessage {
|
||||
return {
|
||||
...message,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
args: this.convertArgs(args),
|
||||
name: this._stringAt(name),
|
||||
returnType: returnType ? this.convertType(returnType) : null
|
||||
@@ -191,6 +192,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
|
||||
public convertEvent ({ args }: ContractABIEventPre): ContractABIEvent {
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
args: this.convertArgs(args)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,11 +7,11 @@ import { MetaRegistryItem, MetaRegistryJson, MetaTypeDefClikeEnum, MetaType, Met
|
||||
import { assert } from '@polkadot/util';
|
||||
import { displayType, withTypeString } from '@polkadot/types';
|
||||
|
||||
const builtinMap: [(id: any) => boolean, MetaTypeInfo][] = [
|
||||
[(id: any): boolean => typeof id === 'string', MetaTypeInfo.BuiltinPlain],
|
||||
[(id: any): boolean => Array.isArray(id), MetaTypeInfo.BuiltinTuple],
|
||||
[(id: any): boolean => !!(id['array.type']), MetaTypeInfo.BuiltinVecFixed],
|
||||
[(id: any): boolean => !!(id['slice.type']), MetaTypeInfo.BuiltinVec]
|
||||
const builtinMap: [(id: unknown | unknown[] | { 'array.type': unknown } | { 'slice.type': unknown }) => boolean, MetaTypeInfo][] = [
|
||||
[(id: any) => typeof id === 'string', MetaTypeInfo.BuiltinPlain],
|
||||
[(id: any) => Array.isArray(id), MetaTypeInfo.BuiltinTuple],
|
||||
[(id: any) => !!((id as { 'array.type': unknown })['array.type']), MetaTypeInfo.BuiltinVecFixed],
|
||||
[(id: any) => !!((id as { 'slice.type': unknown })['slice.type']), MetaTypeInfo.BuiltinVec]
|
||||
];
|
||||
|
||||
const typeMap: [string, MetaTypeInfo][] = [
|
||||
@@ -25,8 +25,8 @@ function detectedType ({ def, id }: MetaType): MetaTypeInfo {
|
||||
assert(!(def as MetaTypeDefUnion)['union.fields'], 'Invalid union type definition found');
|
||||
|
||||
const lookup = def === 'builtin'
|
||||
? builtinMap.find(([test]): boolean => test(id))
|
||||
: typeMap.find(([test]): boolean => !!(def as any)[test]);
|
||||
? builtinMap.find(([test]) => test(id))
|
||||
: typeMap.find(([test]) => !!(def as unknown as Record<string, unknown>)[test]);
|
||||
|
||||
return lookup
|
||||
? lookup[1]
|
||||
@@ -59,7 +59,7 @@ class MetadataRegistryLookup {
|
||||
}
|
||||
}
|
||||
|
||||
protected _itemAt (index: number, variant: MetaRegistryItem): any {
|
||||
protected _itemAt (index: number, variant: MetaRegistryItem): string | MetaType | TypeDef {
|
||||
assert(this._hasItemAt(index, variant), `MetaRegistry: Invalid ${variant} index ${index} found in metadata`);
|
||||
|
||||
switch (variant) {
|
||||
@@ -72,24 +72,24 @@ class MetadataRegistryLookup {
|
||||
}
|
||||
}
|
||||
|
||||
protected _itemsAt (indices: number[], variant: MetaRegistryItem): any[] {
|
||||
return indices.map((index: number): string => this._itemAt(index, variant));
|
||||
protected _itemsAt (indices: number[], variant: MetaRegistryItem): (string | MetaType | TypeDef)[] {
|
||||
return indices.map((index: number) => this._itemAt(index, variant));
|
||||
}
|
||||
|
||||
protected _stringAt (index: StringIndex): string {
|
||||
return this._itemAt(index, MetaRegistryItem.String);
|
||||
return this._itemAt(index, MetaRegistryItem.String) as string;
|
||||
}
|
||||
|
||||
public stringsAt (indices: StringIndex[]): string[] {
|
||||
return this._itemsAt(indices, MetaRegistryItem.String);
|
||||
return this._itemsAt(indices, MetaRegistryItem.String) as string[];
|
||||
}
|
||||
|
||||
public typeAt (index: TypeIndex): MetaType {
|
||||
return this._itemAt(index, MetaRegistryItem.Type);
|
||||
return this._itemAt(index, MetaRegistryItem.Type) as MetaType;
|
||||
}
|
||||
|
||||
public typesAt (indices: TypeIndex[]): MetaType[] {
|
||||
return this._itemsAt(indices, MetaRegistryItem.Type);
|
||||
return this._itemsAt(indices, MetaRegistryItem.Type) as MetaType[];
|
||||
}
|
||||
|
||||
public hasTypeDefAt (index: TypeIndex): boolean {
|
||||
@@ -98,7 +98,7 @@ class MetadataRegistryLookup {
|
||||
|
||||
public typeDefAt (index: TypeIndex, extra: Pick<TypeDef, never> = {}): TypeDef {
|
||||
return {
|
||||
...this._itemAt(index, MetaRegistryItem.TypeDef),
|
||||
...this._itemAt(index, MetaRegistryItem.TypeDef) as TypeDef,
|
||||
...extra
|
||||
};
|
||||
}
|
||||
@@ -136,7 +136,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
private _typeDefDefFields (metaType: MetaType, typeIndex?: TypeIndex): Pick<TypeDef, never> {
|
||||
private _typeDefDefFields (metaType: MetaType, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
|
||||
let typeDef;
|
||||
|
||||
switch (detectedType(metaType)) {
|
||||
@@ -234,7 +234,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex?: TypeIndex): Pick<TypeDef, never> {
|
||||
private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
|
||||
const { 'slice.type': vecTypeIndex } = id;
|
||||
|
||||
assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`);
|
||||
@@ -250,7 +250,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex?: TypeIndex): Pick<TypeDef, never> {
|
||||
private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
|
||||
const { 'array.len': vecLength, 'array.type': vecTypeIndex } = id;
|
||||
|
||||
assert(!vecLength || vecLength <= 256, 'MetaRegistry: Only support for [Type; <length>], where length <= 256');
|
||||
@@ -301,7 +301,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
public typeDefForOption (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
|
||||
public typeDefForOption (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick<TypeDef, any> {
|
||||
assert(id['custom.params'] && id['custom.params'][0], `Invalid Option type defined at index ${typeIndex}`);
|
||||
|
||||
return {
|
||||
@@ -310,7 +310,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
public typeDefForResult (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
|
||||
public typeDefForResult (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick<TypeDef, any> {
|
||||
assert(id['custom.params'] && id['custom.params'][0] && id['custom.params'][1], `Invalid Result type defined at index ${typeIndex}`);
|
||||
|
||||
return {
|
||||
|
||||
@@ -47,6 +47,7 @@ export default class Blueprint<ApiType extends ApiTypes> extends BaseWithTx<ApiT
|
||||
assert(!!this.abi.constructors[constructorIndex], `Specified constructor index ${constructorIndex} does not exist`);
|
||||
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
signAndSend: this.decorateMethod(
|
||||
(account: IKeyringPair | string | AccountId | Address): BlueprintCreateResultSubscription<ApiType> => {
|
||||
return this._apiContracts
|
||||
|
||||
@@ -19,7 +19,6 @@ import { BaseWithTx } from './util';
|
||||
|
||||
type CodePutCodeResultSubscription<ApiType extends ApiTypes> = Observable<CodePutCodeResult<ApiType>>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
|
||||
export interface CodePutCode<ApiType extends ApiTypes> {
|
||||
signAndSend (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType>;
|
||||
}
|
||||
@@ -46,6 +45,7 @@ export default class Code<ApiType extends ApiTypes> extends BaseWithTx<ApiType>
|
||||
|
||||
public createBlueprint = (maxGas: number | BN): CodePutCode<ApiType> => {
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
signAndSend: this.decorateMethod(
|
||||
(account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType> =>
|
||||
this._apiContracts
|
||||
|
||||
@@ -21,7 +21,6 @@ type ContractCallResultSubscription<ApiType extends ApiTypes, CallType extends C
|
||||
? Observable<ContractCallResult<CallType>>
|
||||
: Promise<ObsInnerType<ContractCallResult<CallType>>>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
|
||||
export interface ContractCall<ApiType extends ApiTypes, CallType extends ContractCallTypes> {
|
||||
send (account: IKeyringPair | string | AccountId | Address): ContractCallResultSubscription<ApiType, CallType>;
|
||||
}
|
||||
@@ -45,6 +44,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
const { def, fn } = this.getMessage(message);
|
||||
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
send: this.decorateMethod(
|
||||
as === 'rpc' && this.hasRpcContractsCall
|
||||
? (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'rpc'> =>
|
||||
|
||||
@@ -46,7 +46,7 @@ export abstract class Base<ApiType extends ApiTypes> implements ContractBase<Api
|
||||
: 0;
|
||||
const def = this.abi.abi.contract.messages[index];
|
||||
|
||||
assert(!!def, `Attempted to access a contract message that does not exist: ${typeof nameOrIndex === 'number' ? `index ${nameOrIndex}` : nameOrIndex}`);
|
||||
assert(!!def, `Attempted to access a contract message that does not exist: ${typeof nameOrIndex === 'number' ? `index ${nameOrIndex}` : (nameOrIndex || 'unknown')}`);
|
||||
|
||||
const fn = this.abi.messages[def.name] || this.abi.messages[stringCamelCase(def.name)];
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface ContractBase<ApiType extends ApiTypes> {
|
||||
|
||||
export interface ContractABITypePre {
|
||||
ty: TypeIndex;
|
||||
// eslint-disable-next-line camelcase
|
||||
display_name: StringIndex[];
|
||||
}
|
||||
|
||||
@@ -56,6 +57,7 @@ export interface ContractABIMessageCommon {
|
||||
|
||||
export interface ContractABIMessagePre extends ContractABIMessageCommon, ContractABIMessageBasePre {
|
||||
name: StringIndex;
|
||||
// eslint-disable-next-line camelcase
|
||||
return_type: ContractABITypePre | null;
|
||||
}
|
||||
|
||||
@@ -187,6 +189,7 @@ export interface InterfaceAbi {
|
||||
}
|
||||
|
||||
export interface InterfaceContractCalls {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
[index: string]: Function;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-derive",
|
||||
"version": "1.15.1",
|
||||
"version": "1.17.1",
|
||||
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -27,18 +27,18 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/api": "1.15.1",
|
||||
"@polkadot/rpc-core": "1.15.1",
|
||||
"@polkadot/rpc-provider": "1.15.1",
|
||||
"@polkadot/types": "1.15.1",
|
||||
"@polkadot/util": "^2.10.1",
|
||||
"@polkadot/util-crypto": "^2.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/api": "1.17.1",
|
||||
"@polkadot/rpc-core": "1.17.1",
|
||||
"@polkadot/rpc-provider": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@polkadot/util-crypto": "^2.12.2",
|
||||
"bn.js": "^5.1.2",
|
||||
"memoizee": "^0.4.14",
|
||||
"rxjs": "^6.5.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.10.1"
|
||||
"@polkadot/keyring": "^2.12.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ export function referendumIds (api: ApiInterfaceRx): () => Observable<BN[]> {
|
||||
]).pipe(
|
||||
map(([first, total]): BN[] =>
|
||||
total.gt(first)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
? [...Array(total.sub(first).toNumber())].map((_, i): BN => first.addn(i))
|
||||
: []
|
||||
)
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-return */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-call */
|
||||
/* eslint-disable @typescript-eslint/restrict-template-expressions */
|
||||
|
||||
import { Observable, from } from 'rxjs';
|
||||
import ApiRx from '@polkadot/api/rx/Api';
|
||||
import MockProvider from '@polkadot/rpc-provider/mock';
|
||||
@@ -33,7 +37,7 @@ describe('derive', (): void => {
|
||||
const api = new ApiRx({ provider: new MockProvider(registry), registry });
|
||||
|
||||
beforeAll((done): void => {
|
||||
api.isReady.subscribe((): void => done());
|
||||
api.isReady.subscribe(() => done());
|
||||
});
|
||||
|
||||
testFunction(api)('accounts', 'idAndIndex', []);
|
||||
|
||||
@@ -76,9 +76,11 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
|
||||
.reduce((sectionAcc, _methodName): DeriveSection<typeof section> => {
|
||||
const methodName = _methodName as keyof typeof section;
|
||||
// Not sure what to do here, casting as any. Though the final types are good
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call
|
||||
const method = (section[methodName] as any)(api);
|
||||
|
||||
// idem
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
|
||||
(sectionAcc as any)[methodName] = method;
|
||||
|
||||
return sectionAcc;
|
||||
|
||||
@@ -38,7 +38,7 @@ function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposur
|
||||
|
||||
export function _eraExposure (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraExposure> {
|
||||
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraExposure> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era}`;
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveEraExposure>(cacheKey);
|
||||
|
||||
@@ -40,7 +40,7 @@ export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive
|
||||
const cached: DeriveEraPoints[] = withActive
|
||||
? []
|
||||
: eras
|
||||
.map((era) => deriveCache.get(`${CACHE_KEY}-${era}`))
|
||||
.map((era) => deriveCache.get<DeriveEraPoints>(`${CACHE_KEY}-${era.toString()}`))
|
||||
.filter((value): value is DeriveEraPoints => !!value);
|
||||
const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era)));
|
||||
|
||||
@@ -50,7 +50,7 @@ export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive
|
||||
map((points): DeriveEraPoints[] => {
|
||||
const query = mapPoints(remaining, points);
|
||||
|
||||
!withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era}`, q));
|
||||
!withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era.toString()}`, q));
|
||||
|
||||
return eras.map((era): DeriveEraPoints =>
|
||||
cached.find((cached) => era.eq(cached.era)) ||
|
||||
|
||||
@@ -26,7 +26,7 @@ function mapPrefs (era: EraIndex, all: [StorageKey, ValidatorPrefs][]): DeriveEr
|
||||
|
||||
export function _eraPrefs (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraPrefs> {
|
||||
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraPrefs> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era}`;
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveEraPrefs>(cacheKey);
|
||||
|
||||
@@ -30,7 +30,7 @@ export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActiv
|
||||
const cached: DeriveEraRewards[] = withActive
|
||||
? []
|
||||
: eras
|
||||
.map((era) => deriveCache.get(`${CACHE_KEY}-${era}`))
|
||||
.map((era) => deriveCache.get<DeriveEraRewards>(`${CACHE_KEY}-${era.toString()}`))
|
||||
.filter((value): value is DeriveEraRewards => !!value);
|
||||
const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era)));
|
||||
|
||||
@@ -42,7 +42,7 @@ export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActiv
|
||||
map((optRewards) => {
|
||||
const query = mapRewards(remaining, optRewards);
|
||||
|
||||
!withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era}`, q));
|
||||
!withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era.toString()}`, q));
|
||||
|
||||
return eras.map((era): DeriveEraRewards =>
|
||||
cached.find((cached) => era.eq(cached.era)) ||
|
||||
|
||||
@@ -32,7 +32,7 @@ function mapSlashes (era: EraIndex, noms: [StorageKey, Option<BalanceOf>][], val
|
||||
|
||||
export function _eraSlashes (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraSlashes> {
|
||||
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraSlashes> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era}`;
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveEraSlashes>(cacheKey);
|
||||
|
||||
@@ -2,34 +2,62 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { EraIndex, Exposure } from '@polkadot/types/interfaces';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveOwnExposure } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
export function ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveOwnExposure[]> => {
|
||||
const CACHE_KEY = 'ownExposure';
|
||||
|
||||
export function _ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveOwnExposure> {
|
||||
return memo((accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveOwnExposure> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveOwnExposure>(cacheKey);
|
||||
|
||||
return cached
|
||||
? of(cached)
|
||||
: api.queryMulti<[Exposure, Exposure]>([
|
||||
[api.query.staking.erasStakersClipped, [era, accountId]],
|
||||
[api.query.staking.erasStakers, [era, accountId]]
|
||||
]).pipe(
|
||||
map(([clipped, exposure]): DeriveOwnExposure => {
|
||||
const value = { clipped, era, exposure };
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> {
|
||||
return memo((accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> =>
|
||||
api.derive.staking._ownExposure(accountId, era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _ownExposures (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveOwnExposure[]> =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => api.derive.staking._ownExposure(accountId, era, withActive))
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function ownExposures (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveOwnExposure[]> => {
|
||||
return api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => combineLatest([
|
||||
of(era),
|
||||
api.query.staking.erasStakersClipped(era, accountId),
|
||||
api.query.staking.erasStakers(era, accountId)
|
||||
]))
|
||||
)
|
||||
: of([])
|
||||
),
|
||||
map((result): DeriveOwnExposure[] =>
|
||||
result.map(([era, clipped, exposure]): DeriveOwnExposure => ({
|
||||
clipped,
|
||||
era,
|
||||
exposure
|
||||
}))
|
||||
api.derive.staking._ownExposures(accountId, eras, withActive)
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -3,34 +3,68 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { BalanceOf, EraIndex, Perbill } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveStakerSlashes } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
const CACHE_KEY = 'ownSlash';
|
||||
|
||||
export function _ownSlash (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveStakerSlashes> {
|
||||
return memo((accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveStakerSlashes> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveStakerSlashes>(cacheKey);
|
||||
|
||||
return cached
|
||||
? of(cached)
|
||||
: api.queryMulti<[Option<BalanceOf>, Option<ITuple<[Perbill, BalanceOf]>>]>([
|
||||
[api.query.staking.nominatorSlashInEra, [era, accountId]],
|
||||
[api.query.staking.validatorSlashInEra, [era, accountId]]
|
||||
]).pipe(
|
||||
map(([optNom, optVal]): DeriveStakerSlashes => {
|
||||
const value = {
|
||||
era,
|
||||
total: optVal.isSome
|
||||
? optVal.unwrap()[1]
|
||||
: optNom.unwrapOrDefault()
|
||||
};
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function ownSlash (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> {
|
||||
return memo((accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> =>
|
||||
api.derive.staking._ownSlash(accountId, era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => api.derive.staking._ownSlash(accountId, era, withActive))
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> => {
|
||||
return api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => combineLatest([
|
||||
of(era),
|
||||
api.query.staking.nominatorSlashInEra(era, accountId),
|
||||
api.query.staking.validatorSlashInEra(era, accountId)
|
||||
]))
|
||||
)
|
||||
: of([])
|
||||
),
|
||||
map((result): DeriveStakerSlashes[] =>
|
||||
result.map(([era, optNom, optVal]): DeriveStakerSlashes => ({
|
||||
era,
|
||||
total: optVal.isSome
|
||||
? optVal.unwrap()[1]
|
||||
: optNom.unwrapOrDefault()
|
||||
}))
|
||||
api.derive.staking._ownSlashes(accountId, eras, withActive)
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -32,18 +32,20 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, e
|
||||
Object.entries(eraValidators).forEach(([validatorId, exposure]): void => {
|
||||
const valPoints = allValPoints[validatorId] || ZERO;
|
||||
const valComm = allValPrefs[validatorId]?.commission.unwrap() || ZERO;
|
||||
const avail = eraReward.mul(valPoints).div(eraPoints);
|
||||
const valCut = valComm.mul(avail).div(COMM_DIV);
|
||||
const expTotal = exposure.total.unwrap();
|
||||
let avail = ZERO;
|
||||
let value: BN | undefined;
|
||||
|
||||
if (!expTotal.isZero() && !valPoints.isZero()) {
|
||||
if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) {
|
||||
avail = eraReward.mul(valPoints).div(eraPoints);
|
||||
|
||||
const valCut = valComm.mul(avail).div(COMM_DIV);
|
||||
let staked: BN;
|
||||
|
||||
if (validatorId === stakerId) {
|
||||
staked = exposure.own.unwrap();
|
||||
} else {
|
||||
const stakerExp = exposure.others.find(({ who }): boolean => who.eq(stakerId));
|
||||
const stakerExp = exposure.others.find(({ who }) => who.eq(stakerId));
|
||||
|
||||
staked = stakerExp
|
||||
? stakerExp.value.unwrap()
|
||||
|
||||
@@ -9,7 +9,7 @@ import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions';
|
||||
import { Struct } from '@polkadot/types';
|
||||
|
||||
// We can ignore the properties, added via Struct.with
|
||||
const _Header: Constructor<Header> = Struct.with(runtimeTypes.types.Header as any) as any;
|
||||
const _Header = Struct.with(runtimeTypes.types.Header as any) as Constructor<Header>;
|
||||
|
||||
/**
|
||||
* @name HeaderExtended
|
||||
|
||||
@@ -32,7 +32,7 @@ function wrapCache (keyStart: string, cache: DeriveCache): DeriveCache {
|
||||
|
||||
return undefined;
|
||||
},
|
||||
set: (partial: string, v: any): void => {
|
||||
set: (partial: string, v: unknown): void => {
|
||||
cache.set(`${keyStart}${partial}`, { v, x: Date.now() });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { DeriveCache } from './types';
|
||||
|
||||
const mapCache: Map<string, any> = new Map();
|
||||
const mapCache = new Map<string, any>();
|
||||
|
||||
const deriveMapCache: DeriveCache = {
|
||||
del: (key: string): void => {
|
||||
@@ -18,7 +18,7 @@ const deriveMapCache: DeriveCache = {
|
||||
}
|
||||
},
|
||||
get: <T = any> (key: string): T | undefined => {
|
||||
return mapCache.get(key);
|
||||
return mapCache.get(key) as T;
|
||||
},
|
||||
set: (key: string, value: any): void => {
|
||||
mapCache.set(key, value);
|
||||
@@ -29,7 +29,7 @@ const deriveNoopCache: DeriveCache = {
|
||||
del: (): void => undefined,
|
||||
forEach: () => undefined,
|
||||
get: (): undefined => undefined,
|
||||
set: (_: string, value: any): any => value
|
||||
set: (_: string, value: unknown): unknown => value
|
||||
};
|
||||
|
||||
export { deriveMapCache, deriveNoopCache };
|
||||
|
||||
+12
-12
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api",
|
||||
"version": "1.15.1",
|
||||
"version": "1.17.1",
|
||||
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,21 +26,21 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/api-derive": "1.15.1",
|
||||
"@polkadot/keyring": "^2.10.1",
|
||||
"@polkadot/metadata": "1.15.1",
|
||||
"@polkadot/rpc-core": "1.15.1",
|
||||
"@polkadot/rpc-provider": "1.15.1",
|
||||
"@polkadot/types": "1.15.1",
|
||||
"@polkadot/types-known": "1.15.1",
|
||||
"@polkadot/util": "^2.10.1",
|
||||
"@polkadot/util-crypto": "^2.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/api-derive": "1.17.1",
|
||||
"@polkadot/keyring": "^2.12.2",
|
||||
"@polkadot/metadata": "1.17.1",
|
||||
"@polkadot/rpc-core": "1.17.1",
|
||||
"@polkadot/rpc-provider": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/types-known": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@polkadot/util-crypto": "^2.12.2",
|
||||
"bn.js": "^5.1.2",
|
||||
"eventemitter3": "^4.0.4",
|
||||
"rxjs": "^6.5.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.10.1"
|
||||
"@polkadot/keyring": "^2.12.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,8 +68,12 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
**/
|
||||
signedClaimHandicap: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* Size of a contract at the time of instantiation. This is a simple way to ensure that
|
||||
* empty contracts eventually gets deleted.
|
||||
* A size offset for an contract. A just created account with untouched storage will have that
|
||||
* much of storage from the perspective of the state rent.
|
||||
*
|
||||
* This is a simple way to ensure that contracts with empty storage eventually get deleted
|
||||
* by making them pay rent. This creates an incentive to remove them early in order to save
|
||||
* rent.
|
||||
**/
|
||||
storageSizeOffset: AugmentedConst<u32>;
|
||||
/**
|
||||
|
||||
@@ -16,7 +16,7 @@ import { AccountId, AccountIndex, Address, Balance, BalanceOf, BlockNumber, Call
|
||||
import { Period, Priority } from '@polkadot/types/interfaces/scheduler';
|
||||
import { Keys } from '@polkadot/types/interfaces/session';
|
||||
import { SocietyJudgement } from '@polkadot/types/interfaces/society';
|
||||
import { CompactAssignments, EraIndex, PhragmenScore, RewardDestination, ValidatorIndex, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
|
||||
import { CompactAssignments, ElectionSize, EraIndex, PhragmenScore, RewardDestination, ValidatorIndex, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
|
||||
import { Key } from '@polkadot/types/interfaces/system';
|
||||
import { Timepoint } from '@polkadot/types/interfaces/utility';
|
||||
import { VestingInfo } from '@polkadot/types/interfaces/vesting';
|
||||
@@ -184,7 +184,24 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* - up to 3 events
|
||||
* # </weight>
|
||||
**/
|
||||
close: AugmentedSubmittable<(proposal: Hash | string | Uint8Array, index: Compact<ProposalIndex> | AnyNumber | Uint8Array, proposalWeightBound: Compact<Weight> | AnyNumber | Uint8Array, lengthBound: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
close: AugmentedSubmittable<(proposalHash: Hash | string | Uint8Array, index: Compact<ProposalIndex> | AnyNumber | Uint8Array, proposalWeightBound: Compact<Weight> | AnyNumber | Uint8Array, lengthBound: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Disapprove a proposal, close, and remove it from the system, regardless of its current state.
|
||||
*
|
||||
* Must be called by the Root origin.
|
||||
*
|
||||
* Parameters:
|
||||
* * `proposal_hash`: The hash of the proposal that should be disapproved.
|
||||
*
|
||||
* # <weight>
|
||||
* Complexity: O(P) where P is the number of max proposals
|
||||
* Base Weight: .49 * P
|
||||
* DB Weight:
|
||||
* * Reads: Proposals
|
||||
* * Writes: Voting, Proposals, ProposalOf
|
||||
* # </weight>
|
||||
**/
|
||||
disapproveProposal: AugmentedSubmittable<(proposalHash: Hash | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Dispatch a proposal from a member using the `Member` origin.
|
||||
*
|
||||
@@ -2363,45 +2380,22 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* minimized (to ensure less variance)
|
||||
*
|
||||
* # <weight>
|
||||
* E: number of edges. m: size of winner committee. n: number of nominators. d: edge degree
|
||||
* (16 for now) v: number of on-chain validator candidates.
|
||||
*
|
||||
* NOTE: given a solution which is reduced, we can enable a new check the ensure `|E| < n +
|
||||
* m`. We don't do this _yet_, but our offchain worker code executes it nonetheless.
|
||||
*
|
||||
* major steps (all done in `check_and_replace_solution`):
|
||||
*
|
||||
* - Storage: O(1) read `ElectionStatus`.
|
||||
* - Storage: O(1) read `PhragmenScore`.
|
||||
* - Storage: O(1) read `ValidatorCount`.
|
||||
* - Storage: O(1) length read from `SnapshotValidators`.
|
||||
*
|
||||
* - Storage: O(v) reads of `AccountId` to fetch `snapshot_validators`.
|
||||
* - Memory: O(m) iterations to map winner index to validator id.
|
||||
* - Storage: O(n) reads `AccountId` to fetch `snapshot_nominators`.
|
||||
* - Memory: O(n + m) reads to map index to `AccountId` for un-compact.
|
||||
*
|
||||
* - Storage: O(e) accountid reads from `Nomination` to read correct nominations.
|
||||
* - Storage: O(e) calls into `slashable_balance_of_vote_weight` to convert ratio to staked.
|
||||
*
|
||||
* - Memory: build_support_map. O(e).
|
||||
* - Memory: evaluate_support: O(E).
|
||||
*
|
||||
* - Storage: O(e) writes to `QueuedElected`.
|
||||
* - Storage: O(1) write to `QueuedScore`
|
||||
*
|
||||
* The weight of this call is 1/10th of the blocks total weight.
|
||||
* See `crate::weight` module.
|
||||
* # </weight>
|
||||
**/
|
||||
submitElectionSolution: AugmentedSubmittable<(winners: Vec<ValidatorIndex> | (ValidatorIndex | AnyNumber | Uint8Array)[], compactAssignments: CompactAssignments | { votes1?: any; votes2?: any; votes3?: any; votes4?: any; votes5?: any; votes6?: any; votes7?: any; votes8?: any; votes9?: any; votes10?: any; votes11?: any; votes12?: any; votes13?: any; votes14?: any; votes15?: any; votes16?: any } | string | Uint8Array, score: PhragmenScore, era: EraIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
submitElectionSolution: AugmentedSubmittable<(winners: Vec<ValidatorIndex> | (ValidatorIndex | AnyNumber | Uint8Array)[], compact: CompactAssignments | { votes1?: any; votes2?: any; votes3?: any; votes4?: any; votes5?: any; votes6?: any; votes7?: any; votes8?: any; votes9?: any; votes10?: any; votes11?: any; votes12?: any; votes13?: any; votes14?: any; votes15?: any; votes16?: any } | string | Uint8Array, score: PhragmenScore, era: EraIndex | AnyNumber | Uint8Array, size: ElectionSize | { validators?: any; nominators?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Unsigned version of `submit_election_solution`.
|
||||
*
|
||||
* Note that this must pass the [`ValidateUnsigned`] check which only allows transactions
|
||||
* from the local node to be included. In other words, only the block author can include a
|
||||
* transaction in the block.
|
||||
*
|
||||
* # <weight>
|
||||
* See `crate::weight` module.
|
||||
* # </weight>
|
||||
**/
|
||||
submitElectionSolutionUnsigned: AugmentedSubmittable<(winners: Vec<ValidatorIndex> | (ValidatorIndex | AnyNumber | Uint8Array)[], compactAssignments: CompactAssignments | { votes1?: any; votes2?: any; votes3?: any; votes4?: any; votes5?: any; votes6?: any; votes7?: any; votes8?: any; votes9?: any; votes10?: any; votes11?: any; votes12?: any; votes13?: any; votes14?: any; votes15?: any; votes16?: any } | string | Uint8Array, score: PhragmenScore, era: EraIndex | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
submitElectionSolutionUnsigned: AugmentedSubmittable<(winners: Vec<ValidatorIndex> | (ValidatorIndex | AnyNumber | Uint8Array)[], compact: CompactAssignments | { votes1?: any; votes2?: any; votes3?: any; votes4?: any; votes5?: any; votes6?: any; votes7?: any; votes8?: any; votes9?: any; votes10?: any; votes11?: any; votes12?: any; votes13?: any; votes14?: any; votes15?: any; votes16?: any } | string | Uint8Array, score: PhragmenScore, era: EraIndex | AnyNumber | Uint8Array, size: ElectionSize | { validators?: any; nominators?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Schedule a portion of the stash to be unlocked ready for transfer out after the bond
|
||||
* period ends. If this leaves an amount actively bonded less than
|
||||
@@ -2691,7 +2685,24 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* - up to 3 events
|
||||
* # </weight>
|
||||
**/
|
||||
close: AugmentedSubmittable<(proposal: Hash | string | Uint8Array, index: Compact<ProposalIndex> | AnyNumber | Uint8Array, proposalWeightBound: Compact<Weight> | AnyNumber | Uint8Array, lengthBound: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
close: AugmentedSubmittable<(proposalHash: Hash | string | Uint8Array, index: Compact<ProposalIndex> | AnyNumber | Uint8Array, proposalWeightBound: Compact<Weight> | AnyNumber | Uint8Array, lengthBound: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Disapprove a proposal, close, and remove it from the system, regardless of its current state.
|
||||
*
|
||||
* Must be called by the Root origin.
|
||||
*
|
||||
* Parameters:
|
||||
* * `proposal_hash`: The hash of the proposal that should be disapproved.
|
||||
*
|
||||
* # <weight>
|
||||
* Complexity: O(P) where P is the number of max proposals
|
||||
* Base Weight: .49 * P
|
||||
* DB Weight:
|
||||
* * Reads: Proposals
|
||||
* * Writes: Voting, Proposals, ProposalOf
|
||||
* # </weight>
|
||||
**/
|
||||
disapproveProposal: AugmentedSubmittable<(proposalHash: Hash | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Dispatch a proposal from a member using the `Member` origin.
|
||||
*
|
||||
@@ -3049,7 +3060,8 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* Register approval for a dispatch to be made from a deterministic composite account if
|
||||
* approved by a total of `threshold - 1` of `other_signatories`.
|
||||
*
|
||||
* If there are enough, then dispatch the call.
|
||||
* If there are enough, then dispatch the call. Calls must each fulfil the `IsCallable`
|
||||
* filter.
|
||||
*
|
||||
* Payment: `MultisigDepositBase` will be reserved if this is the first approval, plus
|
||||
* `threshold` times `MultisigDepositFactor`. It is returned once this dispatch happens or
|
||||
@@ -3101,6 +3113,8 @@ declare module '@polkadot/api/types/submittable' {
|
||||
/**
|
||||
* Send a call through an indexed pseudonym of the sender.
|
||||
*
|
||||
* Calls must each fulfil the `IsCallable` filter.
|
||||
*
|
||||
* The dispatch origin for this call must be _Signed_.
|
||||
*
|
||||
* # <weight>
|
||||
@@ -3112,7 +3126,8 @@ declare module '@polkadot/api/types/submittable' {
|
||||
/**
|
||||
* Send a batch of dispatch calls.
|
||||
*
|
||||
* This will execute until the first one fails and then stop.
|
||||
* This will execute until the first one fails and then stop. Calls must fulfil the
|
||||
* `IsCallable` filter unless the origin is `Root`.
|
||||
*
|
||||
* May be called from any origin.
|
||||
*
|
||||
|
||||
@@ -31,7 +31,7 @@ import Events from './Events';
|
||||
|
||||
interface MetaDecoration {
|
||||
callIndex?: Uint8Array;
|
||||
meta: any;
|
||||
meta: Record<string, unknown>;
|
||||
method: string;
|
||||
section: string;
|
||||
toJSON: () => any;
|
||||
@@ -246,9 +246,9 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.forEach(([_, { method, section }]): void => {
|
||||
delete (this._rpc as any)[section][method];
|
||||
delete (this._rpcCore as any)[section][method];
|
||||
delete (this._rx.rpc as any)[section][method];
|
||||
delete (this._rpc as Record<string, Record<string, unknown>>)[section][method];
|
||||
delete (this._rpcCore as unknown as Record<string, Record<string, unknown>>)[section][method];
|
||||
delete (this._rx.rpc as Record<string, Record<string, unknown>>)[section][method];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -257,11 +257,12 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
const sectionName = _sectionName as keyof DecoratedRpc<ApiType, RpcInterface>;
|
||||
|
||||
// out and section here are horrors to get right from a typing perspective :(
|
||||
(out as any)[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]> => {
|
||||
(out as Record<string, unknown>)[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]> => {
|
||||
// skip subscriptions where we have a non-subscribe interface
|
||||
if (this.hasSubscriptions || !(methodName.startsWith('subscribe') || methodName.startsWith('unsubscribe'))) {
|
||||
(section as any)[methodName] = decorateMethod(method, { methodName });
|
||||
(section as any)[methodName].raw = decorateMethod(method.raw, { methodName });
|
||||
(section as Record<string, unknown>)[methodName] = decorateMethod(method, { methodName }) as unknown;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
(section as Record<string, { raw: unknown }>)[methodName].raw = decorateMethod(method.raw, { methodName }) as unknown;
|
||||
}
|
||||
|
||||
return section;
|
||||
@@ -272,10 +273,12 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
}
|
||||
|
||||
protected _decorateMulti<ApiType extends ApiTypes> (decorateMethod: DecorateMethod<ApiType>): QueryableStorageMulti<ApiType> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return decorateMethod((calls: QueryableStorageMultiArg<ApiType>[]): Observable<Codec[]> =>
|
||||
this._rpcCore.state.subscribeStorage(
|
||||
calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageEntry<ApiType>, ...Arg[]] =>
|
||||
// the input is a QueryableStorageEntry, convert to StorageEntry
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
Array.isArray(arg)
|
||||
? [arg[0].creator, ...arg.slice(1)]
|
||||
: [arg.creator] as any)));
|
||||
@@ -299,7 +302,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
const decorated = (...params: Arg[]): SubmittableExtrinsic<ApiType> =>
|
||||
creator(method(...params));
|
||||
|
||||
return this._decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction<ApiType>;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return this._decorateFunctionMeta(method as any, decorated as any) as unknown as SubmittableExtrinsicFunction<ApiType>;
|
||||
}
|
||||
|
||||
protected _decorateStorage<ApiType extends ApiTypes> (storage: Storage, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> {
|
||||
@@ -319,6 +323,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
const getArgs = (...args: any[]): any[] => extractStorageArgs(creator, args);
|
||||
|
||||
// FIXME We probably want to be able to query the full list with non-subs as well
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const decorated = this.hasSubscriptions && creator.iterKey && creator.meta.type.isMap && creator.meta.type.asMap.linked.isTrue
|
||||
? this._decorateStorageLinked(creator, decorateMethod)
|
||||
: decorateMethod((...args: any[]): Observable<Codec> => (
|
||||
@@ -332,32 +337,41 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
: this._rpcCore.state.getStorage(getArgs(...args))
|
||||
), { methodName: creator.method });
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
decorated.creator = creator;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.at = decorateMethod((hash: Hash, arg1?: Arg, arg2?: Arg): Observable<Codec> =>
|
||||
this._rpcCore.state.getStorage(getArgs(arg1, arg2), hash));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.hash = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<Hash> =>
|
||||
this._rpcCore.state.getStorageHash(getArgs(arg1, arg2)));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
decorated.key = (arg1?: Arg, arg2?: Arg): string =>
|
||||
u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
decorated.keyPrefix = (key1?: Arg): string =>
|
||||
u8aToHex(creator.keyPrefix(key1));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.range = decorateMethod((range: [Hash, Hash?], arg1?: Arg, arg2?: Arg): Observable<[Hash, Codec][]> =>
|
||||
this._decorateStorageRange(decorated, [arg1, arg2], range));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.size = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<u64> =>
|
||||
this._rpcCore.state.getStorageSize(getArgs(arg1, arg2)));
|
||||
|
||||
// .keys() & .entries() only available on map types
|
||||
if (creator.iterKey && (creator.meta.type.isMap || creator.meta.type.isDoubleMap)) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.entries = decorateMethod(
|
||||
memo((doubleMapArg?: Arg): Observable<[StorageKey, Codec][]> =>
|
||||
this._retrieveMapEntries(creator, doubleMapArg)));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.keys = decorateMethod(
|
||||
memo((doubleMapArg?: Arg): Observable<StorageKey[]> =>
|
||||
this._retrieveMapKeys(creator, doubleMapArg)));
|
||||
@@ -366,12 +380,13 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
// only support multi where subs are available
|
||||
if (this.hasSubscriptions) {
|
||||
// When using double map storage function, user need to pass double map key as an array
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.multi = decorateMethod((args: (Arg | Arg[])[]): Observable<Codec[]> =>
|
||||
this._rpcCore.state.subscribeStorage(
|
||||
args.map((arg: Arg[] | Arg): [StorageEntry, Arg | Arg[]] => [creator, arg])));
|
||||
}
|
||||
|
||||
return this._decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageEntry<ApiType>;
|
||||
return this._decorateFunctionMeta(creator as any, decorated) as unknown as QueryableStorageEntry<ApiType>;
|
||||
}
|
||||
|
||||
private _decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: [Arg?, Arg?], range: [Hash, Hash?]): Observable<[Hash, Codec][]> {
|
||||
@@ -388,7 +403,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
}
|
||||
|
||||
private _decorateStorageLinked<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
|
||||
const result: Map<Codec, ITuple<[Codec, Linkage<Codec>]> | null> = new Map();
|
||||
const result = new Map<Codec, ITuple<[Codec, Linkage<Codec>]> | null>();
|
||||
let subject: BehaviorSubject<LinkageResult>;
|
||||
let head: Codec | null = null;
|
||||
const iterKey = creator.iterKey;
|
||||
@@ -451,9 +466,11 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
|
||||
// this handles the case where the head changes effectively, i.e. a new entry
|
||||
// appears at the top of the list, the new getNext gets kicked off
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return decorateMethod((...args: any[]): Observable<LinkageResult | [Codec, Linkage<Codec>]> =>
|
||||
args.length
|
||||
? this._rpcCore.state
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
.subscribeStorage<[[Codec, Linkage<Codec>]]>([[creator, ...args]])
|
||||
.pipe(map(([data]): [Codec, Linkage<Codec>] => data))
|
||||
: this._rpcCore.state
|
||||
|
||||
@@ -62,6 +62,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
// 'connected' event, then the `on('connected')` won't fire anymore. To
|
||||
// cater for this case, we call manually `this._onProviderConnect`.
|
||||
if (this._rpcCore.provider.isConnected()) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
this.#onProviderConnect();
|
||||
}
|
||||
}
|
||||
@@ -107,7 +108,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
// manually build a list of all available methods in this RPC, we are
|
||||
// going to filter on it to align the cloned RPC without making a call
|
||||
Object.keys(source.rpc).forEach((section): void => {
|
||||
Object.keys((source.rpc as any)[section]).forEach((method): void => {
|
||||
Object.keys((source.rpc as Record<string, Record<string, unknown>>)[section]).forEach((method): void => {
|
||||
methods.push(`${section}_${method}`);
|
||||
});
|
||||
});
|
||||
@@ -130,7 +131,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
? of(false)
|
||||
: this._rpcCore.state.getMetadata().pipe(
|
||||
map((metadata: Metadata): boolean => {
|
||||
l.log(`Runtime version updated to ${version.specVersion}`);
|
||||
l.log(`Runtime version updated to spec=${version.specVersion.toString()}, tx=${version.transactionVersion.toString()}`);
|
||||
|
||||
this._runtimeMetadata = metadata;
|
||||
this._runtimeVersion = version;
|
||||
@@ -167,7 +168,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
await this._filterRpc();
|
||||
|
||||
// retrieve metadata, either from chain or as pass-in via options
|
||||
const metadataKey = `${this._genesisHash}-${runtimeVersion.specVersion}`;
|
||||
const metadataKey = `${this._genesisHash?.toHex() || '0x'}-${runtimeVersion.specVersion.toString()}`;
|
||||
const metadata = metadataKey in optMetadata
|
||||
? new Metadata(this.registry, optMetadata[metadataKey])
|
||||
: await this._rpcCore.state.getMetadata().toPromise();
|
||||
@@ -232,7 +233,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
});
|
||||
}, KEEPALIVE_INTERVAL);
|
||||
} catch (_error) {
|
||||
const error = new Error(`FATAL: Unable to initialize the API: ${_error.message}`);
|
||||
const error = new Error(`FATAL: Unable to initialize the API: ${(_error as Error).message}`);
|
||||
|
||||
l.error(error);
|
||||
|
||||
|
||||
@@ -29,8 +29,8 @@ interface PkgJson {
|
||||
let pkgJson: PkgJson = { name: '@polkadot/api', version: '-' };
|
||||
|
||||
import('../package.json')
|
||||
.then((_pkgJson: any): void => {
|
||||
pkgJson = _pkgJson;
|
||||
.then((_pkgJson: unknown): void => {
|
||||
pkgJson = _pkgJson as PkgJson;
|
||||
})
|
||||
.catch((): void => {
|
||||
// ignore
|
||||
|
||||
@@ -87,7 +87,7 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
|
||||
// check range types
|
||||
const entries = await api.query.system.events.range(['0x12345', '0x7890']);
|
||||
|
||||
console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`)}`);
|
||||
console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`).join(', ')}`);
|
||||
}
|
||||
|
||||
async function rpc (api: ApiPromise): Promise<void> {
|
||||
@@ -105,6 +105,7 @@ async function rpc (api: ApiPromise): Promise<void> {
|
||||
await api.rpc.chain.getBlock.raw('0x123456');
|
||||
|
||||
// using raw subs
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
api.rpc.chain.subscribeNewHeads.raw((result: Uint8Array): void => {
|
||||
console.log(result);
|
||||
});
|
||||
@@ -125,7 +126,7 @@ function types (api: ApiPromise): void {
|
||||
|
||||
async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
|
||||
// transfer, also allows for BigInt inputs here
|
||||
const transfer = api.tx.balances.transfer(keyring.bob.address, 123_456_789n);
|
||||
const transfer = api.tx.balances.transfer(keyring.bob.address, 123456789n);
|
||||
|
||||
console.log('transfer as Call', transfer as IMethod);
|
||||
console.log('transfer as Extrinsic', transfer as IExtrinsic);
|
||||
@@ -161,6 +162,7 @@ async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
|
||||
// it allows for query & then using the submittable
|
||||
const second = api.tx.democracy.second(123, 5);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
second.signAndSend('123', (result): void => {
|
||||
console.log(result);
|
||||
});
|
||||
@@ -173,12 +175,15 @@ async function main (): Promise<void> {
|
||||
const api = await ApiPromise.create();
|
||||
const keyring = testKeyring();
|
||||
|
||||
consts(api);
|
||||
derive(api);
|
||||
query(api, keyring);
|
||||
rpc(api);
|
||||
types(api);
|
||||
tx(api, keyring);
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
Promise.all([
|
||||
consts(api),
|
||||
derive(api),
|
||||
query(api, keyring),
|
||||
rpc(api),
|
||||
types(api),
|
||||
tx(api, keyring)
|
||||
]);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
|
||||
@@ -39,7 +39,7 @@ describe('ApiPromise', (): void => {
|
||||
|
||||
const signer = new SingleAccountSigner(registry, aliceEd);
|
||||
const api = await ApiPromise.create({ provider, registry, signer });
|
||||
const transfer = api.tx.balances.transfer(keyring.getPair('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e').address, 321_564_789_876_512_345n);
|
||||
const transfer = api.tx.balances.transfer(keyring.getPair('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e').address, 321564789876512345n);
|
||||
|
||||
return { api, transfer: await transfer.signAsync(aliceEd.address, {}) };
|
||||
}
|
||||
@@ -57,8 +57,10 @@ describe('ApiPromise', (): void => {
|
||||
const metadata: any = {};
|
||||
const key = `${genesisHash}-${specVersion}`;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
metadata[key] = rpcData;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const api = await ApiPromise.create({ metadata, provider, registry } as ApiOptions);
|
||||
|
||||
expect(api.genesisHash).toBeDefined();
|
||||
|
||||
@@ -25,6 +25,7 @@ function extractArgs (args: any[], needsCallback: boolean): [any[], Callback<Cod
|
||||
// If the last arg is a function, we pop it, put it into callback.
|
||||
// actualArgs will then hold the actual arguments to be passed to `method`
|
||||
if (args.length && isFunction(args[args.length - 1])) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
callback = actualArgs.pop();
|
||||
}
|
||||
|
||||
@@ -38,6 +39,7 @@ function extractArgs (args: any[], needsCallback: boolean): [any[], Callback<Cod
|
||||
function promiseTracker (resolve: (value: () => void) => void, reject: (value: Error) => void): Tracker {
|
||||
let isCompleted = false;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
const complete = (fn: Function, value: any): void => {
|
||||
if (!isCompleted) {
|
||||
isCompleted = true;
|
||||
@@ -68,24 +70,22 @@ export function decorateMethod<Method extends AnyFunction> (method: Method, opti
|
||||
const [actualArgs, callback] = extractArgs(args, !!needsCallback);
|
||||
|
||||
if (!callback) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
return method(...actualArgs).pipe(first()).toPromise() as Promise<ObsInnerType<ReturnType<Method>>>;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject): void => {
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
const subscription = method(...actualArgs)
|
||||
.pipe(
|
||||
// if we find an error (invalid params, etc), reject the promise
|
||||
catchError((error): Observable<never> =>
|
||||
tracker.reject(error)
|
||||
),
|
||||
// upon the first result, resolve with the unsub function
|
||||
tap((): void =>
|
||||
tracker.resolve((): void => subscription.unsubscribe())
|
||||
)
|
||||
)
|
||||
.subscribe(callback);
|
||||
}) as any; // ???
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
const subscription: { unsubscribe: () => void } = method(...actualArgs).pipe(
|
||||
// if we find an error (invalid params, etc), reject the promise
|
||||
catchError((error): Observable<never> => tracker.reject(error)),
|
||||
// upon the first result, resolve with the unsub function
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return
|
||||
tap(() => tracker.resolve(() => subscription.unsubscribe()))
|
||||
).subscribe(callback);
|
||||
}) as UnsubscribePromise;
|
||||
} as StorageEntryPromiseOverloads;
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ export default class Combinator<T extends any[] = any[]> {
|
||||
this.#fns.push(fn);
|
||||
|
||||
// Not quite 100% how to have a variable number at the front here
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/ban-types
|
||||
return (fn as Function)(...args, this._createCallback(index));
|
||||
});
|
||||
}
|
||||
@@ -54,7 +55,7 @@ export default class Combinator<T extends any[] = any[]> {
|
||||
}
|
||||
|
||||
protected _createCallback (index: number): (value: any) => void {
|
||||
return (value: any): void => {
|
||||
return (value: unknown): void => {
|
||||
this.#fired[index] = true;
|
||||
this.#results[index] = value;
|
||||
|
||||
@@ -68,6 +69,7 @@ export default class Combinator<T extends any[] = any[]> {
|
||||
}
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
this.#callback(this.#results as T);
|
||||
} catch (error) {
|
||||
// swallow, we don't want the handler to trip us up
|
||||
|
||||
@@ -41,6 +41,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
const [allOptions] = this.#makeSignAndSendOptions(options);
|
||||
const address = isKeyringPair(account) ? account.address : account.toString();
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
|
||||
return decorateMethod(
|
||||
(): Observable<RuntimeDispatchInfo> =>
|
||||
api.derive.tx.signingInfo(address, allOptions.nonce, allOptions.era).pipe(
|
||||
@@ -70,6 +71,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
//
|
||||
// also supports signing through external signers
|
||||
public signAsync (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): SubmittableThis<ApiType, this> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
|
||||
return decorateMethod(
|
||||
(): Observable<this> =>
|
||||
this.#observeSign(account, optionsOrNonce).pipe(mapTo(this))
|
||||
@@ -90,6 +92,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
const [options, statusCb] = this.#makeSignAndSendOptions(optionsOrStatus, optionalStatusCb);
|
||||
const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
|
||||
return decorateMethod(
|
||||
(): Observable<Codec> => (
|
||||
this.#observeSign(account, options).pipe(
|
||||
@@ -112,6 +115,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
public send (statusCb?: Callback<ISubmittableResult>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> {
|
||||
const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
|
||||
return decorateMethod(
|
||||
isSubscription
|
||||
? this.#observeSubscribe
|
||||
|
||||
@@ -22,6 +22,6 @@ export default function createSubmittable<ApiType extends ApiTypes> (apiType: Ap
|
||||
Submittable = createClass<ApiType>({ api, apiType, decorateMethod });
|
||||
}
|
||||
|
||||
return new Submittable(api.registry, extrinsic);
|
||||
return new Submittable(api.registry, extrinsic) as SubmittableExtrinsic<ApiType>;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, Address, Extrinsic, ExtrinsicStatus, EventRecord, Hash, RuntimeDispatchInfo } from '@polkadot/types/interfaces';
|
||||
import { AnyNumber, AnyU8a, Callback, Codec, IExtrinsicEra, IKeyringPair, SignatureOptions, Signer, ISubmittableResult } from '@polkadot/types/types';
|
||||
import { AnyNumber, AnyU8a, Callback, Codec, IExtrinsicEra, IKeyringPair, Signer, ISubmittableResult } from '@polkadot/types/types';
|
||||
import { ApiTypes } from '../types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
@@ -50,9 +50,9 @@ export interface SubmittableExtrinsic<ApiType extends ApiTypes> extends Extrinsi
|
||||
|
||||
send(statusCb: Callback<ISubmittableResult>): SubmittableResultSubscription<ApiType>;
|
||||
|
||||
sign(account: IKeyringPair, _options?: Partial<SignatureOptions>): this;
|
||||
sign(account: IKeyringPair, _options?: Partial<SignerOptions>): this;
|
||||
|
||||
signAsync(account: AddressOrPair, _options?: Partial<SignatureOptions>): SubmittableThis<ApiType, this>;
|
||||
signAsync(account: AddressOrPair, _options?: Partial<SignerOptions>): SubmittableThis<ApiType, this>;
|
||||
|
||||
signAndSend(account: AddressOrPair, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType>;
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ describe('augmentObject', (): void => {
|
||||
});
|
||||
|
||||
afterEach((): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
spy.mockClear();
|
||||
});
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ function extractMethods (src: Record<string, Record<string, any>>, dst: Record<s
|
||||
* already available, but rather just adds new missing ites into the result object.
|
||||
* @internal
|
||||
*/
|
||||
export default function augmentObject (prefix: string, src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>, fromEmpty = false): Record<string, Record<string, any>> {
|
||||
export default function augmentObject (prefix: string, src: Record<string, Record<string, unknown>>, dst: Record<string, Record<string, unknown>>, fromEmpty = false): Record<string, Record<string, any>> {
|
||||
if (fromEmpty) {
|
||||
Object.keys(dst).forEach((key): void => {
|
||||
delete dst[key];
|
||||
@@ -88,12 +88,12 @@ export default function augmentObject (prefix: string, src: Record<string, Recor
|
||||
|
||||
return Object
|
||||
.keys(src)
|
||||
.reduce((newSection, sectionName): Record<string, Record<string, any>> => {
|
||||
.reduce((newSection, sectionName): Record<string, Record<string, unknown>> => {
|
||||
const section = src[sectionName];
|
||||
|
||||
newSection[sectionName] = Object
|
||||
.keys(section)
|
||||
.reduce((result, methodName): Record<string, any> => {
|
||||
.reduce((result, methodName): Record<string, unknown> => {
|
||||
// TODO When it does match, check the actual details and warn when there are differences
|
||||
if (!result[methodName]) {
|
||||
result[methodName] = section[methodName];
|
||||
|
||||
@@ -14,17 +14,14 @@ export type DeriveAllSections<ApiType extends ApiTypes, AllSections extends AnyD
|
||||
|
||||
// A technically unsafe version of Object.keys(obj) that assumes that
|
||||
// obj only has known properties of T
|
||||
function keys<T extends object> (obj: T): (keyof T)[] {
|
||||
return Object.keys(obj) as (keyof T)[];
|
||||
function keys<T extends Record<string, unknown>> (obj: T): (keyof T)[] {
|
||||
return Object.keys(obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a methods decorator which keeps all type information.
|
||||
*/
|
||||
function decorateMethods<ApiType extends ApiTypes, Section extends Record<string, AnyFunction>> (
|
||||
section: Section,
|
||||
decorateMethod: DecorateMethod<ApiType>
|
||||
): DeriveSection<ApiType, Section> {
|
||||
function decorateMethods<ApiType extends ApiTypes, Section extends Record<string, AnyFunction>> (section: Section, decorateMethod: DecorateMethod<ApiType>): DeriveSection<ApiType, Section> {
|
||||
return keys(section).reduce(
|
||||
<MethodName extends keyof Section>(
|
||||
acc: DeriveSection<ApiType, Section>,
|
||||
@@ -32,7 +29,8 @@ function decorateMethods<ApiType extends ApiTypes, Section extends Record<string
|
||||
): DeriveSection<ApiType, Section> => {
|
||||
const method = section[methodName];
|
||||
|
||||
acc[methodName] = decorateMethod(method);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
acc[methodName] = decorateMethod(method) as MethodResult<ApiType, Section[MethodName]>;
|
||||
|
||||
return acc;
|
||||
},
|
||||
|
||||
@@ -18,7 +18,7 @@ export default function filterEvents (extHash: H256, { block: { extrinsics, head
|
||||
if (index === -1) {
|
||||
// only warn on filtering with isInBlock (finalization finalizes after)
|
||||
if (status.isInBlock) {
|
||||
l.warn(`block ${header.hash}: Unable to find extrinsic ${myHash} inside ${allHashes}`);
|
||||
l.warn(`block ${header.hash.toHex()}: Unable to find extrinsic ${myHash} inside ${allHashes.join(', ')}`);
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
@@ -35,8 +35,7 @@ describe('extractStorageArgs', (): void => {
|
||||
|
||||
it('validates no-arg plain (failing when there are args)', (): void => {
|
||||
expect(
|
||||
(): any[] =>
|
||||
extractStorageArgs(storage.timestamp.now, [123, 456])
|
||||
(): unknown => extractStorageArgs(storage.timestamp.now, [123, 456])
|
||||
).toThrow('timestamp.now() does not take any arguments, 2 found');
|
||||
});
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ function doMap (creator: StorageEntry, args: any[]): [StorageEntry] | [StorageEn
|
||||
|
||||
// sets up the arguments in the form of [creator, args] ready to be used in a storage
|
||||
// call. Additionally, it verifies that the correct number of arguments have been passed
|
||||
export function extractStorageArgs (creator: StorageEntry, _args: any[]): any[] {
|
||||
export function extractStorageArgs (creator: StorageEntry, _args: any[]): [StorageEntry, [any, any]] | [StorageEntry] | [StorageEntry, any] {
|
||||
const args = _args.filter((arg) => !isUndefined(arg));
|
||||
|
||||
if (creator.meta.type.isDoubleMap) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { EventRecord } from '@polkadot/types/interfaces';
|
||||
import { SubmittableResult } from '../../src';
|
||||
|
||||
// log all events for the transfers, calling done() when finalized
|
||||
export const logEvents = (done: () => {}): (r: SubmittableResult) => void =>
|
||||
export const logEvents = (done: () => Record<string, unknown>): (r: SubmittableResult) => void =>
|
||||
({ events, status }: SubmittableResult): void => {
|
||||
console.log('Transaction status:', status.type);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/metadata",
|
||||
"version": "1.15.1",
|
||||
"version": "1.17.1",
|
||||
"description": "Helpers to extract information from runtime metadata",
|
||||
"main": "index.js",
|
||||
"publishConfig": {
|
||||
@@ -26,14 +26,14 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/types": "1.15.1",
|
||||
"@polkadot/types-known": "1.15.1",
|
||||
"@polkadot/util": "^2.10.1",
|
||||
"@polkadot/util-crypto": "^2.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/types-known": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@polkadot/util-crypto": "^2.12.2",
|
||||
"bn.js": "^5.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.10.1"
|
||||
"@polkadot/keyring": "^2.12.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ describe('createFunction', (): void => {
|
||||
it('should create timestamp.now correctly', (): void => {
|
||||
expect(
|
||||
createFunction(registry, {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
meta: { type: {} } as any,
|
||||
method: 'Now',
|
||||
prefix: 'Timestamp',
|
||||
@@ -29,6 +30,7 @@ describe('createFunction', (): void => {
|
||||
createFunction(
|
||||
registry,
|
||||
{
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
meta: { type: {} } as any,
|
||||
method: 'authorityCount',
|
||||
prefix: 'Substrate',
|
||||
@@ -50,6 +52,7 @@ describe('createFunction', (): void => {
|
||||
createFunction(
|
||||
registry,
|
||||
{
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
meta: { type: {} } as any,
|
||||
method: 'authorityCount',
|
||||
prefix: 'Substrate',
|
||||
@@ -74,6 +77,7 @@ describe('createFunction', (): void => {
|
||||
|
||||
beforeAll((): void => {
|
||||
storageFn = createFunction(registry, {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
meta: {
|
||||
name: 'metaName',
|
||||
type: {
|
||||
@@ -119,6 +123,7 @@ describe('createFunction', (): void => {
|
||||
|
||||
it('allows creates double map function with a Null type key', (): void => {
|
||||
const storageFn = createFunction(registry, {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
meta: {
|
||||
type: {
|
||||
asDoubleMap: {
|
||||
@@ -144,6 +149,7 @@ describe('createFunction', (): void => {
|
||||
|
||||
it('allows creating of known DoubleMap keys (with Bytes)', (): void => {
|
||||
const storageFn = createFunction(registry, {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
meta: {
|
||||
type: {
|
||||
asDoubleMap: {
|
||||
|
||||
@@ -73,10 +73,7 @@ function createKeyDoubleMap (registry: Registry, itemFn: CreateItemFn, stringKey
|
||||
const { meta: { name, type } } = itemFn;
|
||||
|
||||
// since we are passing an almost-unknown through, trust, but verify
|
||||
assert(
|
||||
Array.isArray(args) && !isUndefined(args[0]) && !isNull(args[0]) && !isUndefined(args[1]) && !isNull(args[1]),
|
||||
`${name} is a DoubleMap and requires two arguments`
|
||||
);
|
||||
assert(Array.isArray(args) && !isUndefined(args[0]) && !isNull(args[0]) && !isUndefined(args[1]) && !isNull(args[1]), `${(name || 'unknown').toString()} is a DoubleMap and requires two arguments`);
|
||||
|
||||
// if this fails, we have bigger issues
|
||||
assert(!isUndefined(hasher2), '2 hashing functions should be defined for DoubleMaps');
|
||||
@@ -110,7 +107,7 @@ function createKey (registry: Registry, itemFn: CreateItemFn, stringKey: string,
|
||||
if (type.isMap) {
|
||||
const map = type.asMap;
|
||||
|
||||
assert(!isUndefined(arg) && !isNull(arg), `${name} is a Map and requires one argument`);
|
||||
assert(!isUndefined(arg) && !isNull(arg), `${name.toString()} is a Map and requires one argument`);
|
||||
|
||||
param = createTypeUnsafe(registry, map.key.toString(), [arg]).toU8a();
|
||||
}
|
||||
@@ -134,7 +131,7 @@ function expandWithMeta ({ meta, method, prefix, section }: CreateItemFn, storag
|
||||
// explicitly add the actual method in the toJSON, this gets used to determine caching and without it
|
||||
// instances (e.g. collective) will not work since it is only matched on param meta
|
||||
storageFn.toJSON = (): any => ({
|
||||
...(meta.toJSON() as any),
|
||||
...(meta.toJSON() as Record<string, unknown>),
|
||||
storage: { method, prefix, section }
|
||||
});
|
||||
|
||||
|
||||
@@ -14,11 +14,11 @@ export type HasherFunction = (data: HasherInput) => Uint8Array;
|
||||
const DEFAULT_FN = (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128);
|
||||
|
||||
const HASHERS: Record<keyof typeof AllHashers, HasherFunction> = {
|
||||
Blake2_128: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase
|
||||
Blake2_128: (data: HasherInput): Uint8Array => // eslint-disable-line camelcase
|
||||
blake2AsU8a(data, 128),
|
||||
Blake2_128Concat: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase
|
||||
Blake2_128Concat: (data: HasherInput): Uint8Array => // eslint-disable-line camelcase
|
||||
u8aConcat(blake2AsU8a(data, 128), u8aToU8a(data)),
|
||||
Blake2_256: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase
|
||||
Blake2_256: (data: HasherInput): Uint8Array => // eslint-disable-line camelcase
|
||||
blake2AsU8a(data, 256),
|
||||
Identity: (data: HasherInput): Uint8Array =>
|
||||
u8aToU8a(data),
|
||||
|
||||
@@ -14,7 +14,7 @@ export default function getStorage (registry: Registry, metaVersion: number): St
|
||||
substrate: Object
|
||||
.entries(substrate)
|
||||
.reduce((storage: Record<string, StorageEntry>, [key, fn]): Record<string, StorageEntry> => {
|
||||
(storage as any)[key] = fn(registry, metaVersion);
|
||||
(storage as Record<string, unknown>)[key] = fn(registry, metaVersion);
|
||||
|
||||
return storage;
|
||||
}, {})
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { AnyNumber, Registry } from '@polkadot/types/types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
@@ -11,7 +11,7 @@ import U32 from '@polkadot/types/primitive/U32';
|
||||
export const MAGIC_NUMBER = 0x6174656d; // `meta`, reversed for Little Endian encoding
|
||||
|
||||
export default class MagicNumber extends U32 {
|
||||
constructor (registry: Registry, value?: any) {
|
||||
constructor (registry: Registry, value?: AnyNumber) {
|
||||
super(registry, value);
|
||||
|
||||
if (!this.isEmpty) {
|
||||
|
||||
@@ -33,13 +33,13 @@ type MetaAsX = 'asV0' | 'asV1' | 'asV2' | 'asV3' | 'asV4' | 'asV5' | 'asV6' | 'a
|
||||
* The versioned runtime metadata as a decoded structure
|
||||
*/
|
||||
export default class MetadataVersioned extends Struct {
|
||||
readonly #converted: Map<number, MetaMapped> = new Map();
|
||||
readonly #converted = new Map<number, MetaMapped>();
|
||||
|
||||
constructor (registry: Registry, value?: any) {
|
||||
constructor (registry: Registry, value?: unknown) {
|
||||
super(registry, {
|
||||
magicNumber: MagicNumber,
|
||||
metadata: 'MetadataAll'
|
||||
}, value);
|
||||
}, value as Map<unknown, unknown>);
|
||||
|
||||
registry.setMetadata(this);
|
||||
}
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
type Types = string | Types[];
|
||||
|
||||
/** @internal */
|
||||
export default function flattenUniq (list: any[]): any[] {
|
||||
const flat = list.reduce((result, entry): any[] => {
|
||||
export default function flattenUniq (list: Types[]): string[] {
|
||||
const flat = list.reduce((result: string[], entry): string[] => {
|
||||
return result.concat(
|
||||
Array.isArray(entry)
|
||||
? flattenUniq(entry)
|
||||
@@ -13,6 +15,6 @@ export default function flattenUniq (list: any[]): any[] {
|
||||
}, []);
|
||||
|
||||
return [...new Set(flat)]
|
||||
.filter((value: any): any => value)
|
||||
.filter((value: string) => value)
|
||||
.sort();
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import getUniqTypes from './getUniqTypes';
|
||||
import Metadata from '../Metadata';
|
||||
|
||||
/** @internal */
|
||||
export function decodeLatestSubstrate<Modules extends Codec> (registry: Registry, version: number, rpcData: string, staticSubstrate: object): void {
|
||||
export function decodeLatestSubstrate<Modules extends Codec> (registry: Registry, version: number, rpcData: string, staticSubstrate: Record<string, unknown>): void {
|
||||
it('decodes latest substrate properly', (): void => {
|
||||
const metadata = new Metadata(registry, rpcData);
|
||||
|
||||
@@ -49,14 +49,14 @@ export function defaultValues (registry: Registry, rpcData: string, withThrow =
|
||||
metadata.asLatest.modules.filter(({ storage }): boolean => storage.isSome).forEach((mod): void => {
|
||||
mod.storage.unwrap().items.forEach(({ fallback, name, type }): void => {
|
||||
const inner = unwrapStorageType(type);
|
||||
const location = `${mod.name}.${name}: ${inner}`;
|
||||
const location = `${mod.name.toString()}.${name.toString()}: ${inner}`;
|
||||
|
||||
it(`creates default types for ${location}`, (): void => {
|
||||
expect((): void => {
|
||||
try {
|
||||
registry.createType(inner, fallback);
|
||||
} catch (error) {
|
||||
const message = `${location}:: ${error.message}`;
|
||||
const message = `${location}:: ${(error as Error).message}`;
|
||||
|
||||
if (withThrow) {
|
||||
throw new Error(message);
|
||||
|
||||
@@ -12,6 +12,15 @@ interface ModuleMetadataTrimmed {
|
||||
calls: Option<Vec<FunctionMetadataLatest>>;
|
||||
}
|
||||
|
||||
function trimDocs (documentation: Vec<Text>): string[] {
|
||||
const strings = documentation.map((doc) => doc.toString().trim());
|
||||
const firstEmpty = strings.findIndex((doc) => !doc.length);
|
||||
|
||||
return firstEmpty === -1
|
||||
? strings
|
||||
: strings.slice(0, firstEmpty);
|
||||
}
|
||||
|
||||
function mapCalls (registry: Registry, _calls: Option<Vec<FunctionMetadataLatest>>): Option<Vec<FunctionMetadataLatest>> {
|
||||
const calls = _calls.unwrapOr(null);
|
||||
|
||||
@@ -21,12 +30,12 @@ function mapCalls (registry: Registry, _calls: Option<Vec<FunctionMetadataLatest
|
||||
? calls.map(({ args, documentation, name }) =>
|
||||
registry.createType('FunctionMetadataLatest', {
|
||||
args,
|
||||
documentation: documentation.map((doc) => doc.toString().trim()),
|
||||
documentation: trimDocs(documentation),
|
||||
name
|
||||
})
|
||||
)
|
||||
: null
|
||||
);
|
||||
) as Option<Vec<FunctionMetadataLatest>>;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
|
||||
@@ -8,9 +8,11 @@ import { getTypeDef } from '@polkadot/types/create';
|
||||
|
||||
import flattenUniq from './flattenUniq';
|
||||
|
||||
type Extracted = string | Extracted[];
|
||||
|
||||
/** @internal */
|
||||
function extractTypes (types: string[]): any[] {
|
||||
return types.map((type): any => {
|
||||
function extractTypes (types: string[]): Extracted[] {
|
||||
return types.map((type): Extracted => {
|
||||
const decoded = getTypeDef(type);
|
||||
|
||||
switch (decoded.info) {
|
||||
@@ -38,12 +40,10 @@ function extractTypes (types: string[]): any[] {
|
||||
|
||||
/** @internal */
|
||||
export default function validateTypes (registry: Registry, types: string[], throwError: boolean): void {
|
||||
const missing = flattenUniq(extractTypes(types)).filter((type): boolean =>
|
||||
!registry.hasType(type)
|
||||
);
|
||||
const missing = flattenUniq(extractTypes(types)).filter((type) => !registry.hasType(type));
|
||||
|
||||
if (missing.length !== 0) {
|
||||
const message = `Unknown types found, no types for ${missing}`;
|
||||
const message = `Unknown types found, no types for ${missing.join(', ')}`;
|
||||
|
||||
if (throwError) {
|
||||
throw new Error(message);
|
||||
|
||||
@@ -565,7 +565,8 @@
|
||||
"documentation": [
|
||||
" Send a batch of dispatch calls.",
|
||||
"",
|
||||
" This will execute until the first one fails and then stop.",
|
||||
" This will execute until the first one fails and then stop. Calls must fulfil the",
|
||||
" `IsCallable` filter unless the origin is `Root`.",
|
||||
"",
|
||||
" May be called from any origin.",
|
||||
"",
|
||||
@@ -599,6 +600,8 @@
|
||||
"documentation": [
|
||||
" Send a call through an indexed pseudonym of the sender.",
|
||||
"",
|
||||
" Calls must each fulfil the `IsCallable` filter.",
|
||||
"",
|
||||
" The dispatch origin for this call must be _Signed_.",
|
||||
"",
|
||||
" # <weight>",
|
||||
@@ -631,7 +634,8 @@
|
||||
" Register approval for a dispatch to be made from a deterministic composite account if",
|
||||
" approved by a total of `threshold - 1` of `other_signatories`.",
|
||||
"",
|
||||
" If there are enough, then dispatch the call.",
|
||||
" If there are enough, then dispatch the call. Calls must each fulfil the `IsCallable`",
|
||||
" filter.",
|
||||
"",
|
||||
" Payment: `MultisigDepositBase` will be reserved if this is the first approval, plus",
|
||||
" `threshold` times `MultisigDepositFactor`. It is returned once this dispatch happens or",
|
||||
@@ -863,6 +867,15 @@
|
||||
" A multisig operation has been cancelled. First param is the account that is",
|
||||
" cancelling, third is the multisig account, fourth is hash of the call."
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Uncallable",
|
||||
"args": [
|
||||
"u32"
|
||||
],
|
||||
"documentation": [
|
||||
" A call with a `false` IsCallable filter was attempted."
|
||||
]
|
||||
}
|
||||
],
|
||||
"constants": [],
|
||||
@@ -938,6 +951,12 @@
|
||||
"documentation": [
|
||||
" A timepoint was given, yet no multisig operation is underway."
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Uncallable",
|
||||
"documentation": [
|
||||
" A call with a `false` IsCallable filter was attempted."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -3015,7 +3034,7 @@
|
||||
"type": "Vec<ValidatorIndex>"
|
||||
},
|
||||
{
|
||||
"name": "compact_assignments",
|
||||
"name": "compact",
|
||||
"type": "CompactAssignments"
|
||||
},
|
||||
{
|
||||
@@ -3025,6 +3044,10 @@
|
||||
{
|
||||
"name": "era",
|
||||
"type": "EraIndex"
|
||||
},
|
||||
{
|
||||
"name": "size",
|
||||
"type": "ElectionSize"
|
||||
}
|
||||
],
|
||||
"documentation": [
|
||||
@@ -3073,34 +3096,7 @@
|
||||
" minimized (to ensure less variance)",
|
||||
"",
|
||||
" # <weight>",
|
||||
" E: number of edges. m: size of winner committee. n: number of nominators. d: edge degree",
|
||||
" (16 for now) v: number of on-chain validator candidates.",
|
||||
"",
|
||||
" NOTE: given a solution which is reduced, we can enable a new check the ensure `|E| < n +",
|
||||
" m`. We don't do this _yet_, but our offchain worker code executes it nonetheless.",
|
||||
"",
|
||||
" major steps (all done in `check_and_replace_solution`):",
|
||||
"",
|
||||
" - Storage: O(1) read `ElectionStatus`.",
|
||||
" - Storage: O(1) read `PhragmenScore`.",
|
||||
" - Storage: O(1) read `ValidatorCount`.",
|
||||
" - Storage: O(1) length read from `SnapshotValidators`.",
|
||||
"",
|
||||
" - Storage: O(v) reads of `AccountId` to fetch `snapshot_validators`.",
|
||||
" - Memory: O(m) iterations to map winner index to validator id.",
|
||||
" - Storage: O(n) reads `AccountId` to fetch `snapshot_nominators`.",
|
||||
" - Memory: O(n + m) reads to map index to `AccountId` for un-compact.",
|
||||
"",
|
||||
" - Storage: O(e) accountid reads from `Nomination` to read correct nominations.",
|
||||
" - Storage: O(e) calls into `slashable_balance_of_vote_weight` to convert ratio to staked.",
|
||||
"",
|
||||
" - Memory: build_support_map. O(e).",
|
||||
" - Memory: evaluate_support: O(E).",
|
||||
"",
|
||||
" - Storage: O(e) writes to `QueuedElected`.",
|
||||
" - Storage: O(1) write to `QueuedScore`",
|
||||
"",
|
||||
" The weight of this call is 1/10th of the blocks total weight.",
|
||||
" See `crate::weight` module.",
|
||||
" # </weight>"
|
||||
]
|
||||
},
|
||||
@@ -3112,7 +3108,7 @@
|
||||
"type": "Vec<ValidatorIndex>"
|
||||
},
|
||||
{
|
||||
"name": "compact_assignments",
|
||||
"name": "compact",
|
||||
"type": "CompactAssignments"
|
||||
},
|
||||
{
|
||||
@@ -3122,6 +3118,10 @@
|
||||
{
|
||||
"name": "era",
|
||||
"type": "EraIndex"
|
||||
},
|
||||
{
|
||||
"name": "size",
|
||||
"type": "ElectionSize"
|
||||
}
|
||||
],
|
||||
"documentation": [
|
||||
@@ -3129,7 +3129,11 @@
|
||||
"",
|
||||
" Note that this must pass the [`ValidateUnsigned`] check which only allows transactions",
|
||||
" from the local node to be included. In other words, only the block author can include a",
|
||||
" transaction in the block."
|
||||
" transaction in the block.",
|
||||
"",
|
||||
" # <weight>",
|
||||
" See `crate::weight` module.",
|
||||
" # </weight>"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -3185,6 +3189,15 @@
|
||||
" A new set of stakers was elected with the given computation method."
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "SolutionStored",
|
||||
"args": [
|
||||
"ElectionCompute"
|
||||
],
|
||||
"documentation": [
|
||||
" A new solution for the upcoming election has been stored."
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Bonded",
|
||||
"args": [
|
||||
@@ -3404,6 +3417,12 @@
|
||||
" The claimed score does not match with the one computed from the data."
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "PhragmenBogusElectionSize",
|
||||
"documentation": [
|
||||
" The election size is invalid."
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "CallNotAllowed",
|
||||
"documentation": [
|
||||
@@ -5402,7 +5421,7 @@
|
||||
"name": "close",
|
||||
"args": [
|
||||
{
|
||||
"name": "proposal",
|
||||
"name": "proposal_hash",
|
||||
"type": "Hash"
|
||||
},
|
||||
{
|
||||
@@ -5447,6 +5466,31 @@
|
||||
" - up to 3 events",
|
||||
" # </weight>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "disapprove_proposal",
|
||||
"args": [
|
||||
{
|
||||
"name": "proposal_hash",
|
||||
"type": "Hash"
|
||||
}
|
||||
],
|
||||
"documentation": [
|
||||
" Disapprove a proposal, close, and remove it from the system, regardless of its current state.",
|
||||
"",
|
||||
" Must be called by the Root origin.",
|
||||
"",
|
||||
" Parameters:",
|
||||
" * `proposal_hash`: The hash of the proposal that should be disapproved.",
|
||||
"",
|
||||
" # <weight>",
|
||||
" Complexity: O(P) where P is the number of max proposals",
|
||||
" Base Weight: .49 * P",
|
||||
" DB Weight:",
|
||||
" * Reads: Proposals",
|
||||
" * Writes: Voting, Proposals, ProposalOf",
|
||||
" # </weight>"
|
||||
]
|
||||
}
|
||||
],
|
||||
"events": [
|
||||
@@ -5825,7 +5869,7 @@
|
||||
"name": "close",
|
||||
"args": [
|
||||
{
|
||||
"name": "proposal",
|
||||
"name": "proposal_hash",
|
||||
"type": "Hash"
|
||||
},
|
||||
{
|
||||
@@ -5870,6 +5914,31 @@
|
||||
" - up to 3 events",
|
||||
" # </weight>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "disapprove_proposal",
|
||||
"args": [
|
||||
{
|
||||
"name": "proposal_hash",
|
||||
"type": "Hash"
|
||||
}
|
||||
],
|
||||
"documentation": [
|
||||
" Disapprove a proposal, close, and remove it from the system, regardless of its current state.",
|
||||
"",
|
||||
" Must be called by the Root origin.",
|
||||
"",
|
||||
" Parameters:",
|
||||
" * `proposal_hash`: The hash of the proposal that should be disapproved.",
|
||||
"",
|
||||
" # <weight>",
|
||||
" Complexity: O(P) where P is the number of max proposals",
|
||||
" Base Weight: .49 * P",
|
||||
" DB Weight:",
|
||||
" * Reads: Proposals",
|
||||
" * Writes: Voting, Proposals, ProposalOf",
|
||||
" # </weight>"
|
||||
]
|
||||
}
|
||||
],
|
||||
"events": [
|
||||
@@ -7759,8 +7828,12 @@
|
||||
"type": "u32",
|
||||
"value": "0x08000000",
|
||||
"documentation": [
|
||||
" Size of a contract at the time of instantiation. This is a simple way to ensure that",
|
||||
" empty contracts eventually gets deleted."
|
||||
" A size offset for an contract. A just created account with untouched storage will have that",
|
||||
" much of storage from the perspective of the state rent.",
|
||||
"",
|
||||
" This is a simple way to ensure that contracts with empty storage eventually get deleted",
|
||||
" by making them pay rent. This creates an incentive to remove them early in order to save",
|
||||
" rent."
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/rpc-core",
|
||||
"version": "1.15.1",
|
||||
"version": "1.17.1",
|
||||
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,15 +26,15 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/metadata": "1.15.1",
|
||||
"@polkadot/rpc-provider": "1.15.1",
|
||||
"@polkadot/types": "1.15.1",
|
||||
"@polkadot/util": "^2.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/metadata": "1.17.1",
|
||||
"@polkadot/rpc-provider": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"memoizee": "^0.4.14",
|
||||
"rxjs": "^6.5.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.10.1"
|
||||
"@polkadot/keyring": "^2.12.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +84,7 @@ describe('Cached Observables', (): void => {
|
||||
|
||||
it('creates different observables for different methods but same arguments', (): void => {
|
||||
// params do not match here
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
const observable1 = (rpc.chain as any).subscribeNewHeads([123]);
|
||||
const observable2 = rpc.state.subscribeStorage([123]);
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ describe('Api', (): void => {
|
||||
}
|
||||
});
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
expect(isFunction((rpc as any).testing.foo)).toBe(true);
|
||||
expect(rpc.sections.includes('testing')).toBe(true);
|
||||
expect(rpc.mapping.get('testing_foo')).toEqual({
|
||||
|
||||
@@ -63,7 +63,7 @@ function logErrorMessage (method: string, { params, type }: DefinitionRpc, error
|
||||
export default class Rpc implements RpcInterface {
|
||||
readonly #storageCache = new Map<string, string | null>();
|
||||
|
||||
public readonly mapping: Map<string, DefinitionRpcExt> = new Map();
|
||||
public readonly mapping = new Map<string, DefinitionRpcExt>();
|
||||
|
||||
public readonly provider: ProviderInterface;
|
||||
|
||||
@@ -134,7 +134,7 @@ export default class Rpc implements RpcInterface {
|
||||
|
||||
// decorate the sections with base and user methods
|
||||
this.sections.forEach((sectionName): void => {
|
||||
(this as any)[sectionName as Section] = {
|
||||
(this as Record<string, unknown>)[sectionName as Section] = {
|
||||
...this._createInterface(sectionName, jsonrpc[sectionName as 'babe'] || {}),
|
||||
...this._createInterface(sectionName, userRpc[sectionName] || {})
|
||||
};
|
||||
@@ -156,7 +156,7 @@ export default class Rpc implements RpcInterface {
|
||||
// `<S extends keyof RpcInterface, M extends keyof RpcInterface[S]>`
|
||||
// Not doing so, because it makes this class a little bit less readable,
|
||||
// and leaving it as-is doesn't harm much
|
||||
(exposed as any)[method] = isSubscription
|
||||
(exposed as Record<string, unknown>)[method] = isSubscription
|
||||
? this._createMethodSubscribe(section, method, def as DefinitionRpcSub)
|
||||
: this._createMethodSend(section, method, def);
|
||||
|
||||
@@ -333,7 +333,7 @@ export default class Rpc implements RpcInterface {
|
||||
try {
|
||||
return this._formatStorageData(key, result);
|
||||
} catch (error) {
|
||||
console.error(`Unable to decode storage ${key.section}.${key.method}:`, error.message);
|
||||
console.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:`, (error as Error).message);
|
||||
|
||||
throw error;
|
||||
}
|
||||
@@ -341,10 +341,10 @@ export default class Rpc implements RpcInterface {
|
||||
const keys = params[0] as Vec<StorageKey>;
|
||||
|
||||
return keys
|
||||
? this._formatStorageSet(keys, result.changes)
|
||||
? this._formatStorageSet(keys, (result as { changes: [string, string | null][] }).changes)
|
||||
: this.registry.createType('StorageChangeSet', result);
|
||||
} else if (rpc.type === 'Vec<StorageChangeSet>') {
|
||||
const mapped = result.map(({ block, changes }: { block: string; changes: [string, string | null][] }): [Hash, Codec[]] => [
|
||||
const mapped = (result as { block: string; changes: [string, string | null][] }[]).map(({ block, changes }): [Hash, Codec[]] => [
|
||||
this.registry.createType('Hash', block),
|
||||
this._formatStorageSet(params[0] as Vec<StorageKey>, changes)
|
||||
]);
|
||||
@@ -352,7 +352,7 @@ export default class Rpc implements RpcInterface {
|
||||
// we only query at a specific block, not a range - flatten
|
||||
return method === 'queryStorageAt'
|
||||
? mapped[0][1]
|
||||
: mapped;
|
||||
: mapped as unknown as Codec[];
|
||||
}
|
||||
|
||||
return createTypeUnsafe(this.registry, rpc.type, [result]);
|
||||
@@ -404,7 +404,7 @@ export default class Rpc implements RpcInterface {
|
||||
try {
|
||||
results.push(this._formatStorageSetEntry(key, changes, withCache));
|
||||
} catch (error) {
|
||||
console.error(`Unable to decode storage ${key.section}.${key.method}:`, error.message);
|
||||
console.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:`, (error as Error).message);
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ describe('methodSend', (): void => {
|
||||
};
|
||||
|
||||
provider = {
|
||||
send: jest.fn((method, params): Promise<any> => {
|
||||
send: jest.fn((method, params: any[]): Promise<any> => {
|
||||
return Promise.resolve(params[0]);
|
||||
})
|
||||
};
|
||||
@@ -41,8 +41,10 @@ describe('methodSend', (): void => {
|
||||
|
||||
it('checks for mismatched parameters', (done): void => {
|
||||
// private method
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
const method = (rpc as any)._createMethodSend('test', 'bleh', methods.bleh);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
method(1).subscribe(
|
||||
(): void => undefined,
|
||||
(error: Error): void => {
|
||||
@@ -53,10 +55,13 @@ describe('methodSend', (): void => {
|
||||
|
||||
it('calls the provider with the correct parameters', (done): void => {
|
||||
// private method
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
const method = (rpc as any)._createMethodSend('test', 'blah', methods.blah);
|
||||
|
||||
// Args are length-prefixed, because it's a Bytes
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
method(new Uint8Array([2 << 2, 0x12, 0x34])).subscribe((): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
expect(provider.send).toHaveBeenCalledWith('test_blah', ['0x1234']);
|
||||
done();
|
||||
});
|
||||
|
||||
@@ -18,7 +18,9 @@ describe('replay', (): void => {
|
||||
|
||||
it('subscribes via the rpc section', (done): void => {
|
||||
// we don't honor types or number of params here
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
(rpc.chain as any).getBlockHash = jest.fn((): Observable<number> => of(1));
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
(rpc.chain as any).getBlockHash(123, false).subscribe((): void => {
|
||||
expect(
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
@@ -32,6 +34,7 @@ describe('replay', (): void => {
|
||||
it('returns the observable value', (done): void => {
|
||||
rpc.system.chain().subscribe((value: any): void => {
|
||||
if (value) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
expect(value.toString()).toEqual('mockChain'); // Defined in MockProvider
|
||||
done();
|
||||
}
|
||||
@@ -40,9 +43,9 @@ describe('replay', (): void => {
|
||||
|
||||
it('replay(1) works as expected', (done): void => {
|
||||
const observable = rpc.system.chain();
|
||||
let a: string | undefined;
|
||||
let a: any | undefined;
|
||||
|
||||
observable.subscribe((value: any): void => { a = value; });
|
||||
observable.subscribe((value?: unknown): void => { a = value; });
|
||||
|
||||
setTimeout((): void => {
|
||||
// Subscribe again to the same observable, it should fire value immediately
|
||||
|
||||
@@ -18,7 +18,7 @@ interface Options {
|
||||
|
||||
const l = logger('drr');
|
||||
|
||||
const CMP = (a: any, b: any): boolean =>
|
||||
const CMP = (a: unknown, b: unknown): boolean =>
|
||||
JSON.stringify({ t: a }) === JSON.stringify({ t: b });
|
||||
|
||||
const ERR = (error: Error): Observable<never> => {
|
||||
@@ -40,7 +40,7 @@ export const drr = ({ skipChange = false, skipTimeout = false }: Options = {}):
|
||||
catchError(ERR),
|
||||
skipChange
|
||||
? tap(NOOP)
|
||||
: distinctUntilChanged(CMP),
|
||||
: distinctUntilChanged<T>(CMP),
|
||||
publishReplay(1),
|
||||
skipTimeout
|
||||
? refCount()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/rpc-provider",
|
||||
"version": "1.15.1",
|
||||
"version": "1.17.1",
|
||||
"description": "Transport providers for the API",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,18 +26,18 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/metadata": "1.15.1",
|
||||
"@polkadot/types": "1.15.1",
|
||||
"@polkadot/util": "^2.10.1",
|
||||
"@polkadot/util-crypto": "^2.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/metadata": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@polkadot/util-crypto": "^2.12.2",
|
||||
"bn.js": "^5.1.2",
|
||||
"eventemitter3": "^4.0.4",
|
||||
"isomorphic-fetch": "^2.2.1",
|
||||
"websocket": "^1.0.31"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.10.1",
|
||||
"@polkadot/keyring": "^2.12.2",
|
||||
"mock-socket": "^9.0.3",
|
||||
"nock": "^12.0.3"
|
||||
}
|
||||
|
||||
@@ -17,12 +17,12 @@ describe('encodeObject', (): void => {
|
||||
|
||||
it('encodes a valid JsonRPC object', (): void => {
|
||||
expect(
|
||||
coder.encodeObject('method', 'params')
|
||||
coder.encodeObject('method', ['a', 'b'])
|
||||
).toEqual({
|
||||
id: 1,
|
||||
jsonrpc: '2.0',
|
||||
method: 'method',
|
||||
params: 'params'
|
||||
params: ['a', 'b']
|
||||
});
|
||||
expect(coder.getId()).toEqual(1);
|
||||
});
|
||||
|
||||
@@ -24,7 +24,7 @@ function formatErrorData (data?: string | number): string {
|
||||
export default class RpcCoder {
|
||||
#id = 0;
|
||||
|
||||
public decodeResponse (response: JsonRpcResponse): any {
|
||||
public decodeResponse (response: JsonRpcResponse): unknown {
|
||||
assert(response, 'Empty response object received');
|
||||
assert(response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object');
|
||||
|
||||
@@ -51,7 +51,7 @@ export default class RpcCoder {
|
||||
);
|
||||
}
|
||||
|
||||
public encodeObject (method: string, params: any | any[]): JsonRpcRequest {
|
||||
public encodeObject (method: string, params: unknown[]): JsonRpcRequest {
|
||||
return {
|
||||
id: ++this.#id,
|
||||
jsonrpc: '2.0',
|
||||
|
||||
@@ -32,13 +32,13 @@ describe('Http', (): void => {
|
||||
return http.subscribe('', '', [], (cb): void => {
|
||||
expect(cb).toEqual(expect.anything());
|
||||
}).catch((error): void => {
|
||||
expect(error.message).toMatch(/does not have subscriptions/);
|
||||
expect((error as Error).message).toMatch(/does not have subscriptions/);
|
||||
});
|
||||
});
|
||||
|
||||
it('does not (yet) support unsubscribe', (): Promise<boolean | void> => {
|
||||
return http.unsubscribe('', '', 0).catch((error): void => {
|
||||
expect(error.message).toMatch(/does not have subscriptions/);
|
||||
expect((error as Error).message).toMatch(/does not have subscriptions/);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -109,6 +109,7 @@ export default class HttpProvider implements ProviderInterface {
|
||||
|
||||
assert(response.ok, `[${response.status}]: ${response.statusText}`);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const result = await response.json();
|
||||
|
||||
return this.#coder.decodeResponse(result);
|
||||
|
||||
@@ -10,14 +10,17 @@ describe('http/polyfill', (): void => {
|
||||
let origFetch: any;
|
||||
|
||||
beforeEach((): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
origFetch = global.fetch;
|
||||
});
|
||||
|
||||
afterEach((): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
global.fetch = origFetch;
|
||||
});
|
||||
|
||||
it('polyfills with no exceptions (without fetch)', (): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
(global as any).fetch = undefined;
|
||||
require('./polyfill');
|
||||
|
||||
@@ -25,6 +28,7 @@ describe('http/polyfill', (): void => {
|
||||
});
|
||||
|
||||
it('polyfills with no exceptions (with fetch)', (): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
(global as any).fetch = (): boolean => true;
|
||||
require('./polyfill');
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ describe('send', (): void => {
|
||||
});
|
||||
|
||||
it('passes the body through correctly', (): Promise<void> => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
mock = mockHttp([{
|
||||
method: 'test_body',
|
||||
reply: {
|
||||
@@ -31,6 +32,7 @@ describe('send', (): void => {
|
||||
return http
|
||||
.send('test_body', ['param'])
|
||||
.then((): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
expect((mock.body as any).test_body).toEqual({
|
||||
id: 1,
|
||||
jsonrpc: '2.0',
|
||||
@@ -41,6 +43,7 @@ describe('send', (): void => {
|
||||
});
|
||||
|
||||
it('throws error when !response.ok', (): Promise<any> => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
mock = mockHttp([{
|
||||
code: 500,
|
||||
method: 'test_error'
|
||||
@@ -49,7 +52,7 @@ describe('send', (): void => {
|
||||
return http
|
||||
.send('test_error', [])
|
||||
.catch((error): void => {
|
||||
expect(error.message).toMatch(/\[500\]: Internal Server/);
|
||||
expect((error as Error).message).toMatch(/\[500\]: Internal Server/);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
/* eslint-disable @typescript-eslint/camelcase */
|
||||
/* eslint-disable camelcase */
|
||||
|
||||
import { Header } from '@polkadot/types/interfaces';
|
||||
import { Codec, Registry } from '@polkadot/types/types';
|
||||
@@ -22,14 +22,15 @@ import { randomAsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
const INTERVAL = 1000;
|
||||
const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply(
|
||||
[], Object.values(jsonrpc).map((section): string[] =>
|
||||
[],
|
||||
Object.values(jsonrpc).map((section): string[] =>
|
||||
Object
|
||||
.values(section)
|
||||
.filter(({ isSubscription }) => isSubscription)
|
||||
.map(({ jsonrpc }) => jsonrpc)
|
||||
.concat('chain_subscribeNewHead')
|
||||
)
|
||||
);
|
||||
) as string[];
|
||||
|
||||
const keyring = testKeyring({ type: 'ed25519' });
|
||||
const l = logger('api-mock');
|
||||
@@ -50,12 +51,14 @@ export default class Mock implements ProviderInterface {
|
||||
|
||||
private prevNumber = new BN(-1);
|
||||
|
||||
private requests: Record<string, (...params: any[]) => any> = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
private requests: Record<string, (...params: any[]) => unknown> = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-unsafe-member-access
|
||||
chain_getBlock: (hash: string): any => this.registry.createType('SignedBlock', rpcSignedBlock.result).toJSON(),
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
chain_getBlockHash: (blockNumber: number): string => '0x1234',
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
chain_getFinalizedHead: () => this.registry.createType('Header', rpcHeader.result).hash,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
chain_getHeader: () => this.registry.createType('Header', rpcHeader.result).toJSON(),
|
||||
state_getKeys: (): string[] => [],
|
||||
state_getKeysPaged: (): string[] => [],
|
||||
@@ -112,7 +115,7 @@ export default class Mock implements ProviderInterface {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
public async send (method: string, params: any[]): Promise<any> {
|
||||
public async send (method: string, params: any[]): Promise<unknown> {
|
||||
if (!this.requests[method]) {
|
||||
throw new Error(`provider.send: Invalid method '${method}'`);
|
||||
}
|
||||
@@ -121,11 +124,11 @@ export default class Mock implements ProviderInterface {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
public async subscribe (type: string, method: string, ...params: any[]): Promise<number> {
|
||||
public async subscribe (type: string, method: string, ...params: unknown[]): Promise<number> {
|
||||
l.debug((): any => ['subscribe', method, params]);
|
||||
|
||||
if (this.subscriptions[method]) {
|
||||
const callback: MockStateSubscriptionCallback = params.pop();
|
||||
const callback = params.pop() as MockStateSubscriptionCallback;
|
||||
const id = ++this.subscriptionId;
|
||||
|
||||
this.subscriptions[method].callbacks[id] = callback;
|
||||
|
||||
@@ -18,7 +18,7 @@ describe('send', (): void => {
|
||||
return mock
|
||||
.send('something_invalid', [])
|
||||
.catch((error): void => {
|
||||
expect(error.message).toMatch(/Invalid method/);
|
||||
expect((error as Error).message).toMatch(/Invalid method/);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ describe('subscribe', (): void => {
|
||||
return mock
|
||||
.subscribe('test', 'test_notFound')
|
||||
.catch((error): void => {
|
||||
expect(error.message).toMatch(/Invalid method 'test_notFound'/);
|
||||
expect((error as Error).message).toMatch(/Invalid method 'test_notFound'/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,7 +41,7 @@ describe('subscribe', (): void => {
|
||||
});
|
||||
|
||||
it('calls back with new headers', (done): Promise<number> => {
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any): void => {
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: { number: number }): void => {
|
||||
if (header.number === 4) {
|
||||
done();
|
||||
}
|
||||
@@ -51,7 +51,7 @@ describe('subscribe', (): void => {
|
||||
it('handles errors withing callbacks gracefully', (done): Promise<number> => {
|
||||
let hasThrown = false;
|
||||
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any): void => {
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: { number: number }): void => {
|
||||
if (!hasThrown) {
|
||||
hasThrown = true;
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { Server } from 'mock-socket';
|
||||
import { Constructor } from '@polkadot/types/types';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
export interface Global extends NodeJS.Global {
|
||||
WebSocket: Constructor<WebSocket>;
|
||||
fetch: any;
|
||||
@@ -14,7 +15,7 @@ export interface Mock {
|
||||
body: Record<string, any>;
|
||||
requests: number;
|
||||
server: Server;
|
||||
done: () => {};
|
||||
done: () => Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type MockStateSubscriptionCallback = (error: Error | null, value: any) => void;
|
||||
|
||||
@@ -25,7 +25,7 @@ describe('unsubscribe', (): void => {
|
||||
return mock
|
||||
.unsubscribe('chain_newHead', 'chain_subscribeNewHead', 5)
|
||||
.catch((error): boolean => {
|
||||
expect(error.message).toMatch(/Unable to find/);
|
||||
expect((error as Error).message).toMatch(/Unable to find/);
|
||||
|
||||
return false;
|
||||
});
|
||||
@@ -41,7 +41,7 @@ describe('unsubscribe', (): void => {
|
||||
mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id)
|
||||
)
|
||||
.catch((error): boolean => {
|
||||
expect(error.message).toMatch(/Unable to find/);
|
||||
expect((error as Error).message).toMatch(/Unable to find/);
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ export interface JsonRpcObject {
|
||||
|
||||
export interface JsonRpcRequest extends JsonRpcObject {
|
||||
method: string;
|
||||
params: any[];
|
||||
params: unknown[];
|
||||
}
|
||||
|
||||
export interface JsonRpcResponseBaseError {
|
||||
@@ -20,14 +20,14 @@ export interface JsonRpcResponseBaseError {
|
||||
|
||||
interface JsonRpcResponseSingle {
|
||||
error?: JsonRpcResponseBaseError;
|
||||
result?: any;
|
||||
result?: unknown;
|
||||
}
|
||||
|
||||
interface JsonRpcResponseSubscription {
|
||||
method?: string;
|
||||
params: {
|
||||
error?: JsonRpcResponseBaseError;
|
||||
result: any;
|
||||
result: unknown;
|
||||
subscription: number;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
/* eslint-disable @typescript-eslint/camelcase */
|
||||
/* eslint-disable camelcase */
|
||||
|
||||
import { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types';
|
||||
|
||||
@@ -108,6 +108,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
this.#websocket = null;
|
||||
|
||||
if (autoConnectMs > 0) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
this.connect();
|
||||
}
|
||||
}
|
||||
@@ -247,9 +248,9 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* ```
|
||||
*/
|
||||
public async subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise<number> {
|
||||
const id = await this.send(method, params, { callback, type });
|
||||
const id = await this.send(method, params, { callback, type }) as Promise<number>;
|
||||
|
||||
return id as number;
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -270,9 +271,9 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
delete this.#subscriptions[subscription];
|
||||
|
||||
const result = await this.send(method, [id]);
|
||||
const result = await this.send(method, [id]) as Promise<boolean>;
|
||||
|
||||
return result as boolean;
|
||||
return result;
|
||||
}
|
||||
|
||||
#emit = (type: ProviderInterfaceEmitted, ...args: any[]): void => {
|
||||
@@ -289,6 +290,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
if (this.#autoConnectMs > 0) {
|
||||
setTimeout((): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
this.connect();
|
||||
}, this.#autoConnectMs);
|
||||
}
|
||||
@@ -300,9 +302,10 @@ export default class WsProvider implements WSProviderInterface {
|
||||
}
|
||||
|
||||
#onSocketMessage = (message: MessageEvent): void => {
|
||||
l.debug((): any => ['received', message.data]);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
l.debug(() => ['received', message.data]);
|
||||
|
||||
const response: JsonRpcResponse = JSON.parse(message.data as string);
|
||||
const response = JSON.parse(message.data as string) as JsonRpcResponse;
|
||||
|
||||
return isUndefined(response.method)
|
||||
? this.#onSocketMessageResult(response)
|
||||
@@ -320,7 +323,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
try {
|
||||
const { method, params, subscription } = handler;
|
||||
const result = this.#coder.decodeResponse(response);
|
||||
const result = this.#coder.decodeResponse(response) as string;
|
||||
|
||||
// first send the result - in case of subs, we may have an update
|
||||
// immediately if we have some queued results already
|
||||
@@ -348,7 +351,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
}
|
||||
|
||||
#onSocketMessageSubscribe = (response: JsonRpcResponse): void => {
|
||||
const method = ALIASSES[response.method as string] || response.method;
|
||||
const method = ALIASSES[response.method as string] || response.method || 'invalid';
|
||||
const subId = `${method}::${response.params.subscription}`;
|
||||
const handler = this.#subscriptions[subId];
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ describe('getWebScoket', (): void => {
|
||||
});
|
||||
|
||||
it('polyfills with no exceptions (with WebSocket)', async (): Promise<void> => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
(global as any).WebSocket = undefined;
|
||||
|
||||
const WS = await getWSClass();
|
||||
@@ -29,6 +30,7 @@ describe('getWebScoket', (): void => {
|
||||
});
|
||||
|
||||
it('polyfills with no exceptions (without WebSocket)', async (): Promise<void> => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
(global as any).WebSocket = (): boolean => true;
|
||||
|
||||
const WS = await getWSClass();
|
||||
|
||||
@@ -33,6 +33,7 @@ describe('onOpen', (): void => {
|
||||
}], 0);
|
||||
const sendPromise = ws.send('test_queue', []);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
ws.connect();
|
||||
|
||||
return sendPromise.then((result): void => {
|
||||
|
||||
@@ -50,7 +50,7 @@ describe('send', (): void => {
|
||||
return createWs()
|
||||
.send('test_encoding', [{ error: 'send error' }])
|
||||
.catch((error): void => {
|
||||
expect(error.message).toEqual('send error');
|
||||
expect((error as Error).message).toEqual('send error');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -67,6 +67,7 @@ describe('send', (): void => {
|
||||
.send('test_body', ['param'])
|
||||
.then((): void => {
|
||||
expect(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
(mock.body as any).test_body
|
||||
).toEqual('{"id":1,"jsonrpc":"2.0","method":"test_body","params":["param"]}');
|
||||
});
|
||||
@@ -84,7 +85,7 @@ describe('send', (): void => {
|
||||
return createWs()
|
||||
.send('test_error', [])
|
||||
.catch((error): void => {
|
||||
expect(error.message).toMatch(/666: error/);
|
||||
expect((error as Error).message).toMatch(/666: error/);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
/* eslint-disable */
|
||||
|
||||
import nock from 'nock';
|
||||
|
||||
const TEST_HTTP_URL = 'http://localhost:9944';
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Server } from 'mock-socket';
|
||||
const TEST_WS_URL = 'ws://localhost:9955';
|
||||
|
||||
interface Scope {
|
||||
body: { [index: string]: {} };
|
||||
body: { [index: string]: Record<string, any> };
|
||||
requests: number;
|
||||
server: Server;
|
||||
done: any;
|
||||
@@ -24,7 +24,7 @@ interface ErrorDef {
|
||||
interface ReplyDef {
|
||||
id: number;
|
||||
reply: {
|
||||
result: any;
|
||||
result: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ function createReply ({ id, reply: { result } }: ReplyDef): any {
|
||||
}
|
||||
|
||||
// scope definition returned
|
||||
function mockWs (requests: { method: string }[], wsUrl: string = TEST_WS_URL): Scope {
|
||||
function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TEST_WS_URL): Scope {
|
||||
const server = new Server(wsUrl);
|
||||
|
||||
let requestCount = 0;
|
||||
@@ -68,11 +68,13 @@ function mockWs (requests: { method: string }[], wsUrl: string = TEST_WS_URL): S
|
||||
server.on('connection', (socket): void => {
|
||||
// FIXME This whole any mess is a mess
|
||||
socket.on('message', (body: any): void => {
|
||||
const request = requests[requestCount];
|
||||
const response = (request as any).error
|
||||
? createError(request as any)
|
||||
: createReply(request as any);
|
||||
const request: any = requests[requestCount];
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
|
||||
const response: any = request.error
|
||||
? createError(request)
|
||||
: createReply(request);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
|
||||
scope.body[request.method] = body;
|
||||
requestCount++;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/typegen",
|
||||
"version": "1.15.1",
|
||||
"version": "1.17.1",
|
||||
"description": "Type generation scripts",
|
||||
"main": "index.js",
|
||||
"bin": {
|
||||
@@ -33,14 +33,14 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.9.6",
|
||||
"@babel/register": "^7.9.0",
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/api": "1.15.1",
|
||||
"@polkadot/metadata": "1.15.1",
|
||||
"@polkadot/rpc-provider": "1.15.1",
|
||||
"@polkadot/types": "1.15.1",
|
||||
"@polkadot/util": "^2.10.1",
|
||||
"@babel/core": "^7.10.2",
|
||||
"@babel/register": "^7.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/api": "1.17.1",
|
||||
"@polkadot/metadata": "1.17.1",
|
||||
"@polkadot/rpc-provider": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"handlebars": "^4.7.6",
|
||||
"websocket": "^1.0.31",
|
||||
"yargs": "^15.3.1"
|
||||
|
||||
@@ -19,7 +19,7 @@ async function run (ws: string): Promise<void> {
|
||||
]);
|
||||
|
||||
// output the chain info, for easy re-use
|
||||
console.error(`// Generated via 'yarn run chain:info ${ws}'\n\nexport default {\n chain: '${chain.toString()}',\n genesisHash: '${api.genesisHash.toHex()}',\n specVersion: ${api.runtimeVersion.specVersion.toNumber()},\n ss58Format: ${props.ss58Format.unwrapOr(42)},\n tokenDecimals: ${props.tokenDecimals.unwrapOr(0)},\n tokenSymbol: '${props.tokenSymbol.unwrapOr('UNIT')}',\n metaCalls: '${Buffer.from(api.runtimeMetadata.asCallsOnly.toU8a()).toString('base64')}'\n};`);
|
||||
console.error(`// Generated via 'yarn run chain:info ${ws}'\n\nexport default {\n chain: '${chain.toString()}',\n genesisHash: '${api.genesisHash.toHex()}',\n specVersion: ${api.runtimeVersion.specVersion.toNumber()},\n ss58Format: ${props.ss58Format.unwrapOr(42).toString()},\n tokenDecimals: ${props.tokenDecimals.unwrapOr(0).toString()},\n tokenSymbol: '${props.tokenSymbol.unwrapOr('UNIT').toString()}',\n metaCalls: '${Buffer.from(api.runtimeMetadata.asCallsOnly.toU8a()).toString('base64')}'\n};`);
|
||||
|
||||
// show any missing types
|
||||
api.runtimeMetadata.getUniqTypes(false);
|
||||
|
||||
@@ -12,13 +12,14 @@ import generateQuery from './generate/query';
|
||||
import generateTx from './generate/tx';
|
||||
import { HEADER, writeFile } from './util';
|
||||
|
||||
let websocket: any = null;
|
||||
let websocket: WebSocket;
|
||||
|
||||
function generate (metaHex: string, pkg: string | undefined, output: string, isStrict?: boolean): void {
|
||||
console.log(`Generating from metadata, ${formatNumber((metaHex.length - 2) / 2)} bytes`);
|
||||
|
||||
const extraTypes = pkg
|
||||
? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) }
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) as Record<string, any> }
|
||||
: {};
|
||||
|
||||
generateConst(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict);
|
||||
@@ -38,7 +39,7 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
function onSocketClose (event: any): void {
|
||||
function onSocketClose (event: { code: number; reason: string }): void {
|
||||
console.error(`disconnected, code: '${event.code}' reason: '${event.reason}'`);
|
||||
|
||||
process.exit(1);
|
||||
@@ -89,6 +90,7 @@ export default function main (): void {
|
||||
websocket.onopen = onSocketOpen;
|
||||
|
||||
websocket.onmessage = (message: any): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
generate(JSON.parse(message.data).result, pkg, output, isStrict);
|
||||
};
|
||||
})
|
||||
@@ -96,6 +98,7 @@ export default function main (): void {
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-member-access
|
||||
generate(require(path.join(process.cwd(), endpoint)).result, pkg, output, isStrict);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,10 +24,10 @@ export default function main (): void {
|
||||
}).argv;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const userDefs = require(path.join(process.cwd(), input, 'definitions.ts'));
|
||||
const userDefs = require(path.join(process.cwd(), input, 'definitions.ts')) as Record<string, any>;
|
||||
const userKeys = Object.keys(userDefs);
|
||||
const filteredBase = Object
|
||||
.entries(substrateDefs)
|
||||
.entries(substrateDefs as Record<string, unknown>)
|
||||
.filter(([key]) => {
|
||||
if (userKeys.includes(key)) {
|
||||
console.warn(`Override found for ${key} in user types, ignoring in @polkadot/types`);
|
||||
@@ -37,7 +37,7 @@ export default function main (): void {
|
||||
|
||||
return true;
|
||||
})
|
||||
.reduce((defs: any, [key, value]) => {
|
||||
.reduce((defs: Record<string, any>, [key, value]) => {
|
||||
defs[key] = value;
|
||||
|
||||
return defs;
|
||||
|
||||
@@ -18,7 +18,7 @@ const generateForMetaTemplate = Handlebars.compile(template);
|
||||
/** @internal */
|
||||
function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>>, isStrict: boolean): void {
|
||||
writeFile(dest, (): string => {
|
||||
const allTypes: Record<string, Record<string, { types: Record<string, any> }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
|
||||
const allTypes: Record<string, Record<string, { types: Record<string, unknown> }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
|
||||
const imports = createImports(allTypes);
|
||||
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
|
||||
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as defaultDefinitions from '@polkadot/types/interfaces/definitions';
|
||||
import * as defaultPrimitives from '@polkadot/types/primitive';
|
||||
|
||||
import { createImports, getDerivedTypes, readTemplate, setImports, writeFile } from '../util';
|
||||
import { ModuleTypes } from '../util/imports';
|
||||
|
||||
const primitiveClasses = {
|
||||
...defaultPrimitives,
|
||||
@@ -19,9 +20,9 @@ const template = readTemplate('interfaceRegistry');
|
||||
const generateInterfaceTypesTemplate = Handlebars.compile(template);
|
||||
|
||||
/** @internal */
|
||||
export function generateInterfaceTypes (importDefinitions: { [importPath: string]: object }, dest: string): void {
|
||||
export function generateInterfaceTypes (importDefinitions: { [importPath: string]: Record<string, ModuleTypes> }, dest: string): void {
|
||||
writeFile(dest, (): string => {
|
||||
Object.entries(importDefinitions).reduce((acc, def) => Object.assign(acc, def), {} as object);
|
||||
Object.entries(importDefinitions).reduce((acc, def) => Object.assign(acc, def), {});
|
||||
|
||||
const imports = createImports(importDefinitions);
|
||||
const definitions = imports.definitions;
|
||||
@@ -46,7 +47,8 @@ export function generateInterfaceTypes (importDefinitions: { [importPath: string
|
||||
|
||||
uniqueTypes.forEach((type) => {
|
||||
existingTypes[type] = true;
|
||||
items.push(...getDerivedTypes(definitions, type, types[type], imports));
|
||||
|
||||
items.push(...getDerivedTypes(definitions, type, types[type] as string, imports));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -15,10 +15,11 @@ import { TypeRegistry } from '@polkadot/types/create';
|
||||
import { stringCamelCase } from '@polkadot/util';
|
||||
|
||||
import { TypeImports, createImports, compareName, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
|
||||
import { ModuleTypes } from '../util/imports';
|
||||
|
||||
// From a storage entry metadata, we return [args, returnType]
|
||||
/** @internal */
|
||||
function entrySignature (allDefs: object, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] {
|
||||
function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] {
|
||||
const format = (type: string): string => formatType(allDefs, type, imports);
|
||||
const outputType = unwrapStorageType(storageEntry.type, storageEntry.modifier.isOptional);
|
||||
|
||||
@@ -59,7 +60,7 @@ function entrySignature (allDefs: object, registry: Registry, storageEntry: Stor
|
||||
];
|
||||
}
|
||||
|
||||
throw new Error(`entryArgs: Cannot parse args of entry ${storageEntry.name}`);
|
||||
throw new Error(`entryArgs: Cannot parse args of entry ${storageEntry.name.toString()}`);
|
||||
}
|
||||
|
||||
const template = readTemplate('query');
|
||||
|
||||
@@ -60,7 +60,8 @@ export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.t
|
||||
|
||||
if (args === undefined) {
|
||||
setImports(allDefs, imports, [def.type]);
|
||||
args = def.params.map((param: any) => {
|
||||
|
||||
args = def.params.map((param) => {
|
||||
const similarTypes = getSimilarTypes(definitions, registry, param.type, imports);
|
||||
|
||||
setImports(allDefs, imports, [param.type, ...similarTypes]);
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
|
||||
import { TypeDef, TypeDefInfo } from '@polkadot/types/create/types';
|
||||
import { ModuleTypes } from '../util/imports';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
import path from 'path';
|
||||
import { getTypeDef } from '@polkadot/types/create';
|
||||
import * as defaultDefinitions from '@polkadot/types/interfaces/definitions';
|
||||
import { isString, stringCamelCase, stringUpperFirst } from '@polkadot/util';
|
||||
import { isString, stringCamelCase, stringUpperFirst, assert } from '@polkadot/util';
|
||||
|
||||
import { TypeImports, createImports, exportInterface, exportType, readTemplate, formatType, setImports, writeFile } from '../util';
|
||||
|
||||
@@ -19,7 +19,7 @@ interface Imports extends TypeImports {
|
||||
|
||||
// helper to generate a `readonly <Name>: <Type>;` getter
|
||||
/** @internal */
|
||||
export function createGetter (definitions: object, name = '', type: string, imports: TypeImports): string {
|
||||
export function createGetter (definitions: Record<string, ModuleTypes>, name = '', type: string, imports: TypeImports): string {
|
||||
setImports(definitions, imports, [type]);
|
||||
|
||||
return ` readonly ${name}: ${type};\n`;
|
||||
@@ -27,12 +27,12 @@ export function createGetter (definitions: object, name = '', type: string, impo
|
||||
|
||||
/** @internal */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function errorUnhandled (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
throw new Error(`Generate: ${name}: Unhandled type ${TypeDefInfo[def.info]}`);
|
||||
function errorUnhandled (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
throw new Error(`Generate: ${def.name || ''}: Unhandled type ${TypeDefInfo[def.info]}`);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsExport (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
function tsExport (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
return exportInterface(def.name, formatType(definitions, def, imports));
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ const tsPlain = tsExport;
|
||||
const tsTuple = tsExport;
|
||||
|
||||
/** @internal */
|
||||
function tsEnum (definitions: object, { name: enumName, sub }: TypeDef, imports: TypeImports): string {
|
||||
function tsEnum (definitions: Record<string, ModuleTypes>, { name: enumName, sub }: TypeDef, imports: TypeImports): string {
|
||||
setImports(definitions, imports, ['Enum']);
|
||||
|
||||
const keys = (sub as TypeDef[]).map(({ info, name = '', type }): string => {
|
||||
@@ -64,21 +64,21 @@ function tsEnum (definitions: object, { name: enumName, sub }: TypeDef, imports:
|
||||
return `${isGetter}${asGetter}`;
|
||||
|
||||
default:
|
||||
throw new Error(`Enum: ${enumName}: Unhandled type ${TypeDefInfo[info]}`);
|
||||
throw new Error(`Enum: ${enumName || 'undefined'}: Unhandled type ${TypeDefInfo[info]}`);
|
||||
}
|
||||
});
|
||||
|
||||
return exportInterface(enumName, 'Enum', keys.join(''));
|
||||
}
|
||||
|
||||
function tsInt (definitions: object, def: TypeDef, imports: TypeImports, type: 'Int' | 'UInt' = 'Int'): string {
|
||||
function tsInt (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports, type: 'Int' | 'UInt' = 'Int'): string {
|
||||
setImports(definitions, imports, [type]);
|
||||
|
||||
return exportInterface(def.name, type);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsResultGetter (definitions: object, resultName = '', getter: 'Ok' | 'Error', def: TypeDef, imports: TypeImports): string {
|
||||
function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Error', def: TypeDef, imports: TypeImports): string {
|
||||
const { info, type } = def;
|
||||
const asGetter = type === 'Null'
|
||||
? ''
|
||||
@@ -97,7 +97,7 @@ function tsResultGetter (definitions: object, resultName = '', getter: 'Ok' | 'E
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsResult (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
function tsResult (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
const [okDef, errorDef] = (def.sub as TypeDef[]);
|
||||
const inner = [
|
||||
tsResultGetter(definitions, def.name, 'Error', errorDef, imports),
|
||||
@@ -110,18 +110,20 @@ function tsResult (definitions: object, def: TypeDef, imports: TypeImports): str
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsSet (definitions: object, { name: setName, sub }: TypeDef, imports: TypeImports): string {
|
||||
function tsSet (definitions: Record<string, ModuleTypes>, { name: setName, sub }: TypeDef, imports: TypeImports): string {
|
||||
setImports(definitions, imports, ['Set']);
|
||||
|
||||
const types = (sub as TypeDef[]).map(({ name }): string =>
|
||||
createGetter(definitions, `is${name}`, 'boolean', imports)
|
||||
);
|
||||
const types = (sub as TypeDef[]).map(({ name }): string => {
|
||||
assert(!!name, 'Invalid TypeDef found, no name specified');
|
||||
|
||||
return createGetter(definitions, `is${name}`, 'boolean', imports);
|
||||
});
|
||||
|
||||
return exportInterface(setName, 'Set', types.join(''));
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsStruct (definitions: object, { name: structName, sub }: TypeDef, imports: TypeImports): string {
|
||||
function tsStruct (definitions: Record<string, ModuleTypes>, { name: structName, sub }: TypeDef, imports: TypeImports): string {
|
||||
setImports(definitions, imports, ['Struct']);
|
||||
|
||||
const keys = (sub as TypeDef[]).map((typedef): string => {
|
||||
@@ -134,12 +136,12 @@ function tsStruct (definitions: object, { name: structName, sub }: TypeDef, impo
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsUInt (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
function tsUInt (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
return tsInt(definitions, def, imports, 'UInt');
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsVec (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
function tsVec (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
const type = (def.sub as TypeDef).type;
|
||||
|
||||
if (def.info === TypeDefInfo.VecFixed && type === 'u8') {
|
||||
@@ -152,7 +154,7 @@ function tsVec (definitions: object, def: TypeDef, imports: TypeImports): string
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function generateInterfaces (definitions: object, { types }: { types: Record<string, any> }, imports: Imports): [string, string][] {
|
||||
function generateInterfaces (definitions: Record<string, ModuleTypes>, { types }: { types: Record<string, any> }, imports: Imports): [string, string][] {
|
||||
// handlers are defined externally to use - this means that when we do a
|
||||
// `generators[typedef.info](...)` TS will show any unhandled types. Rather
|
||||
// we are being explicit in having no handlers where we do not support (yet)
|
||||
@@ -194,7 +196,7 @@ const templateTypes = readTemplate('tsDef/types');
|
||||
const generateTsDefTypesTemplate = Handlebars.compile(templateTypes);
|
||||
|
||||
/** @internal */
|
||||
function generateTsDefFor (importDefinitions: { [importPath: string]: object }, defName: string, { types }: { types: Record<string, any> }, outputDir: string): void {
|
||||
function generateTsDefFor (importDefinitions: { [importPath: string]: Record<string, ModuleTypes> }, defName: string, { types }: { types: Record<string, any> }, outputDir: string): void {
|
||||
const imports = { ...createImports(importDefinitions, { types }), interfaces: [] } as Imports;
|
||||
const definitions = imports.definitions;
|
||||
const interfaces = generateInterfaces(definitions, { types }, imports);
|
||||
@@ -218,7 +220,7 @@ function generateTsDefFor (importDefinitions: { [importPath: string]: object },
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function generateTsDef (importDefinitions: { [importPath: string]: object }, outputDir: string, generatingPackage: string): void {
|
||||
export function generateTsDef (importDefinitions: { [importPath: string]: Record<string, ModuleTypes> }, outputDir: string, generatingPackage: string): void {
|
||||
writeFile(path.join(outputDir, 'types.ts'), (): string => {
|
||||
const definitions = importDefinitions[generatingPackage];
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user