Compare commits

..
62 Commits
Author SHA1 Message Date
github-actions[bot] e4a19dcefd [CI Skip] release/stable 9.0.1
skip-checks: true
2022-07-30 04:39:21 +00:00
Jaco 11d5a4edf0 9.0.1 (#5119) 2022-07-30 07:31:39 +03:00
github-actions[bot] 2eb901a954 [CI Skip] bump/beta 8.14.2-14-x
skip-checks: true
2022-07-29 15:36:45 +00:00
Jaco b63164d6ea Bump Substrate, Polkadot & Kusama static metadata (#5118)
* Bump Substrate, Polkadot & Kusama static metadata

* continue-on-error: true
2022-07-29 18:28:34 +03:00
github-actions[bot] c40fa16217 [CI Skip] bump/beta 8.14.2-13-x
skip-checks: true
2022-07-29 10:34:03 +00:00
Jaco afcbe96fd1 Bump common (#5117) 2022-07-29 13:25:00 +03:00
github-actions[bot] 7d53c4b45d [CI Skip] release/beta 8.14.2-12
skip-checks: true
2022-07-29 08:18:14 +00:00
Jaco 62bfcf84dd Ensure call is exposed on rx (#5116)
* Ensure call is exposed on rx

* Adjust to only top-level detection

* .123npm

* Adjust check for contractsApi
2022-07-29 11:10:05 +03:00
github-actions[bot] b2cfac4edd [CI Skip] release/beta 8.14.2-11
skip-checks: true
2022-07-29 07:23:24 +00:00
Jaco 7b2e5ed59f Publish beta to npm (#5115) 2022-07-29 10:12:55 +03:00
github-actions[bot] fdab9818d5 [CI Skip] bump/beta 8.14.2-10-x
skip-checks: true
2022-07-29 06:39:53 +00:00
Jaco 85fc0bff7d Rename alliance derive location (#5114) 2022-07-29 09:31:37 +03:00
github-actions[bot] 7a545de0c2 [CI Skip] bump/beta 8.14.2-9-x
skip-checks: true
2022-07-28 08:55:28 +00:00
Jaco b22b26d021 Support for alliance motion derives (#5113)
* Support for alliance motion derives

* allianceMotion
2022-07-28 11:46:45 +03:00
github-actions[bot] 30f72f915e [CI Skip] bump/beta 8.14.2-8-x
skip-checks: true
2022-07-26 11:06:22 +00:00
Jaco b522bc76af Upgrade blocks (#5111)
* Upgrade blocks

* CHANGELOG
2022-07-26 13:55:59 +03:00
github-actions[bot] fee3c6b1be [CI Skip] bump/beta 8.14.2-7-x
skip-checks: true
2022-07-26 06:42:45 +00:00
Jaco 79bed8eda3 Prototype static init Enum/Set/Struct (#5087)
* Prototype static init Enum/Set/Struct

* Adjust (similar, logic extracted - further local testing)

* Adjust with latest util (no prototype atm)

* Introduce prototype assignment

* Old Enum tests

* Fix toCallsOnly spread

* Adjust

* Use objectSpread in derives (decorated objects only)

* Adjust

* Remove extra map from bag get

* Additional spreads

* Signer spread

* Formatting

* typo

* Adjust spreads for session

* Additional spread

* Adjust spread

* Formatting

* CHANGELOG

* Adjust

* slice

* CHANGELOG
2022-07-26 09:34:59 +03:00
github-actions[bot] 1aae7b59bb [CI Skip] bump/beta 8.14.2-6-x
skip-checks: true
2022-07-26 06:25:24 +00:00
Jaco 2d84bac287 Remove API deprecated interfaces (#5109)
* Remove API deprecated interfaces

* Adjust checkTypes

* CHANGELOG
2022-07-26 09:17:23 +03:00
github-actions[bot] 789957b0af [CI Skip] bump/beta 8.14.2-5-x
skip-checks: true
2022-07-26 06:01:27 +00:00
Jaco d26f289199 Remove deprecated api-contract methods (#5110)
* Remove deprecated api-contract methods

* Remove checkTypes deprecated
2022-07-26 08:53:05 +03:00
github-actions[bot] 1fe06e63e5 [CI Skip] bump/beta 8.14.2-4-x
skip-checks: true
2022-07-26 04:56:00 +00:00
Jaco 3790f48e03 Specific check for storageDepositLimit support (#5108)
* Specific check for storageDepositLimit support

* Adjust asserts
2022-07-26 07:48:21 +03:00
github-actions[bot] fc5aae8a84 [CI Skip] bump/beta 8.14.2-3-x
skip-checks: true
2022-07-25 13:33:46 +00:00
Jaco 0c79e13aba Convert api-contract usage of api.rpc.* to api.call.* (#5107)
* Convert api-contract usage of api.rpc.* to api.call.*

* Cast call (augmentation not available in build)

* Revert tx check assert

* Call mock
2022-07-25 16:22:26 +03:00
github-actions[bot] 6e65bdbb5c [CI Skip] bump/beta 8.14.2-2-x
skip-checks: true
2022-07-25 11:36:02 +00:00
Jaco 95d113e03f Export api.rx.call.* (#5106)
* Export api.rx.call.*

* Adjust
2022-07-25 14:27:48 +03:00
github-actions[bot] a9a92d0bf8 [CI Skip] bump/beta 8.14.2-1-x
skip-checks: true
2022-07-25 11:25:21 +00:00
Jaco c1fb6e8218 CHANGELOG 2022-07-25 14:17:08 +03:00
github-actions[bot] 7cfc1950ae [CI Skip] bump/beta 8.14.2-0-x
skip-checks: true
2022-07-25 06:36:11 +00:00
Jaco fabf9e9160 Adjust augmentation methods (#5104) 2022-07-25 09:27:59 +03:00
github-actions[bot] a2ff40f735 [CI Skip] release/stable 8.14.1
skip-checks: true
2022-07-23 14:56:53 +00:00
Jaco 9c51ea14be 8.14.1 (#5102) 2022-07-23 17:48:54 +03:00
github-actions[bot] e3f912cef5 [CI Skip] bump/beta 8.13.2-13-x
skip-checks: true
2022-07-22 14:41:02 +00:00
Jaco 21808f0283 Auto-extract Meta* interface types based on version list (#5100)
* Auto-extract Meta* interface types based on version list

* Additional dedupe

* s/ALL_VERSIONS/KNOWN_VERSIONS/

* Restore type addition

* Additional <const> specifiers

* Handle contracts similar to metadata
2022-07-22 17:30:12 +03:00
github-actions[bot] 714380575c [CI Skip] bump/beta 8.13.2-12-x
skip-checks: true
2022-07-22 04:17:30 +00:00
Jaco ec76f2cefd Shortcut balance instances check (#5099) 2022-07-22 07:06:55 +03:00
github-actions[bot] 2121a1eea0 [CI Skip] bump/beta 8.13.2-11-x
skip-checks: true
2022-07-21 18:14:01 +00:00
Jaco c0e0346987 Fix for derive.balances.account (instances check) (#5098) 2022-07-21 21:06:02 +03:00
github-actions[bot] 9b5004df9b [CI Skip] bump/beta 8.13.2-10-x
skip-checks: true
2022-07-21 09:14:03 +00:00
Jaco dd7ad37dbf Bump Kusama metadata (#5096) 2022-07-21 12:05:19 +03:00
github-actions[bot] 92d6f6b98f [CI Skip] bump/beta 8.13.2-9-x
skip-checks: true
2022-07-21 06:03:26 +00:00
Jaco fcb317d65b Bump common (#5095) 2022-07-21 08:54:49 +03:00
github-actions[bot] b8d4b034ab [CI Skip] bump/beta 8.13.2-8-x
skip-checks: true
2022-07-21 04:27:26 +00:00
Jaco 60398d9f47 TransactionPaymentCallApi runtime definition (#5094) 2022-07-21 07:18:52 +03:00
github-actions[bot] 7a1525d3e2 [CI Skip] bump/beta 8.13.2-7-x
skip-checks: true
2022-07-20 11:02:12 +00:00
Jaco 1ee461dd59 Adjust CHANGELOG (#5091)
* Adjust CHANGELOG

* Bump deps
2022-07-20 13:51:23 +03:00
github-actions[bot] cfa15f98f7 [CI Skip] bump/beta 8.13.2-6-x
skip-checks: true
2022-07-20 09:21:26 +00:00
Jaco 18671cc650 Apply objectSpread on metadata conversion (as missing) (#5090) 2022-07-20 12:12:53 +03:00
github-actions[bot] a790e8c3ee [CI Skip] bump/beta 8.13.2-5-x
skip-checks: true
2022-07-19 18:39:45 +00:00
Nikos Kontakis bb6e16eac7 Bump substrate connect to 0.7.9 (Add CommonJS Support) (#5088)
* Bump substrate connect to 0.7.9

* Remove comment about ESM-only at bundle
2022-07-19 21:31:52 +03:00
github-actions[bot] 23e191eaf7 [CI Skip] bump/beta 8.13.2-4-x
skip-checks: true
2022-07-19 05:53:58 +00:00
Jaco cec0325820 Bump dev deps (#5084) 2022-07-19 08:44:10 +03:00
github-actions[bot] ffd8d74e3a [CI Skip] bump/beta 8.13.2-3-x
skip-checks: true
2022-07-18 11:19:15 +00:00
Jaco 91a04ad159 Add Codec toPrimitive (#5080) 2022-07-18 14:10:46 +03:00
github-actions[bot] 434f969208 [CI Skip] bump/beta 8.13.2-2-x
skip-checks: true
2022-07-18 07:42:59 +00:00
Jaco 34a5cbed90 Adjust instance check to handle Call paths (#5082) 2022-07-18 10:35:14 +03:00
github-actions[bot] 72469ae6da [CI Skip] bump/beta 8.13.2-1-x
skip-checks: true
2022-07-18 06:22:21 +00:00
Jaco 14f2a9da39 Adjust lazyVariants with internal $type (#5081)
* Adjust lazyVariants with internal $type

* Adjust

* Allow for empty paths

* Allow any $ override

* Adjust

* Small usage fixes, dedupe
2022-07-18 09:12:14 +03:00
github-actions[bot] 12750bc83d [CI Skip] bump/beta 8.13.2-0-x
skip-checks: true
2022-07-16 11:24:15 +00:00
Jaco 9a2b67aa25 Adjust CodecMap toHuman key representation (Bytes, if isAscii) (#5079)
* Adjust CodecMap toHuman key representation (Bytes, if isAscii)

* Use Raw instead of Bytes

* old typo
2022-07-16 14:16:29 +03:00
152 changed files with 1857 additions and 1622 deletions
+1
View File
@@ -17,6 +17,7 @@ jobs:
deno-version: vx.x.x
- name: ${{ matrix.step }}
if: always()
continue-on-error: true
run: |
yarn install --immutable | grep -v 'YN0013'
yarn ${{ matrix.step }}
+39 -1
View File
@@ -1,5 +1,43 @@
# CHANGELOG
## 9.0.1 Jul 30, 2022
- **Breaking change** The decorated field getters on `Struct` were moved to the prototype class for performance reasons. While `struct.<field>` access still behaves in the same way, with the same results, this does mean that the prototype getters are not visible when doing an `Object.keys(struct)` or when doing an object spread.
- **Breaking change** Deprecated interfaces have been removed including `tx.sign(...)` (use `signAsync`), `Result.{is, as}Error` (use `{is, as}Err`) as well as storage `.range(...)` operations.
- **Breaking change** Deprecated interfaces on `api-contract` have been removed. Always ensure you pass an options object to construction and query methods.
- **Breaking change** Contracts access via `api-contract` will now detect the usage of `storageDepositLimit` in params, if not available the contract interfaces will not be decorated.
Changes:
- Decorate `Struct/Enum/Set` field getters on class prototypes
- Convert `api-contract` usage of `api.rpc.*` to `api.call.*`
- Drop support for contract runtimes without `storageDepositLimit` (runtime `contractsApi` only has support for latest)
- Export `api.rx.call.*` for internal usage (derive, contracts)
- Remove old-style param passing as opposed to options in `api-contract`
- Support for alliance/motion collective derives
- Add Kusama 9260 upgrade block
- Add Polkadot 9230 & 9250 upgrade blocks
- Add Westend 9251, 9260 & 9261 upgrade blocks
- Update to latest Substrate, Polkadot & Kusama metadata
## 8.14.1 Jul 23, 2022
Contributed:
- Update `@substrate/connect` with dual ESM/CJS support (Thanks to https://github.com/wirednkod)
Changes:
- `{BTree|Hash}Map.toHuman()` now display `Raw` keys as ascii (if detected)
- Add `toPrimitive()` to all base `Codec` interfaces (string/boolean/number)
- Adjust metadata conversion with `objectSpread` (where missing)
- Support for `TransactionPaymentCallApi` runtime interface
- Check `registry.getModuleInstances` against metadata paths (fallback)
- Update to `@polkadot/util` 10.1.1
- Update to latest Kusama metadata (Substrate & Polkadot are current)
## 8.13.1 Jul 16, 2022
Changes:
@@ -332,7 +370,7 @@ Changes:
- Only explicitly support LSB on `BitVec` types
- Change `toHuman()` on `BitVec` to output default LSB
- Add `bytes{Sent, Recv}` to provider stats
- Clear connection timout on provider `disconnect()`
- Clear connection timeout on provider `disconnect()`
- Add support for `dev_getBlockStats` RPC
+2 -2
View File
@@ -1,4 +1,4 @@
3136 Jaco 8.13.1 (#5078)
3166 Jaco 9.0.1 (#5119)
83 Amaury Martiny StatementKind: Regular and Saft (#2303)
37 Keith Ingram Update contract types and rpc (#4541)
35 Stefanie Doll Updated child storage parameters (#1709)
@@ -7,7 +7,7 @@
15 Jeremías Díaz feat(types): add correct tuple type to storage key (#3054)
11 Ian He HttpProvider support clone() (#3949)
10 Axel Chalon Make Enum/Tuple constructor use value directly if instance (#1954)
6 Nikos Kontakis Bump substrate connect to 0.7.8 (#5058)
7 Nikos Kontakis Bump substrate connect to 0.7.9 (Add CommonJS Support) (#5088)
5 Chevdor Fix metadata package link (#3458)
5 Jake Naviasky Fixing approvalFlagsToBools. (#1250)
4 Alex D Use derive customAccount and customLocks for balance overrides (#3248)
+7 -7
View File
@@ -11,10 +11,10 @@
},
"sideEffects": false,
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"versions": {
"git": "8.13.1",
"npm": "8.13.1"
"git": "9.0.1",
"npm": "9.0.1"
},
"workspaces": [
"packages/*"
@@ -34,10 +34,10 @@
"test:one": "NODE_OPTIONS=--experimental-vm-modules polkadot-dev-run-test --detectOpenHandles --forceExit"
},
"devDependencies": {
"@babel/core": "^7.18.6",
"@babel/register": "^7.18.6",
"@babel/runtime": "^7.18.6",
"@polkadot/dev": "^0.67.79",
"@babel/core": "^7.18.9",
"@babel/register": "^7.18.9",
"@babel/runtime": "^7.18.9",
"@polkadot/dev": "^0.67.86",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^28.1.6",
"copyfiles": "^2.4.1"
+9 -9
View File
@@ -20,18 +20,18 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/api-base": "8.13.1",
"@polkadot/rpc-augment": "8.13.1",
"@polkadot/types": "8.13.1",
"@polkadot/types-augment": "8.13.1",
"@polkadot/types-codec": "8.13.1",
"@polkadot/util": "^10.0.2"
"@babel/runtime": "^7.18.9",
"@polkadot/api-base": "9.0.1",
"@polkadot/rpc-augment": "9.0.1",
"@polkadot/types": "9.0.1",
"@polkadot/types-augment": "9.0.1",
"@polkadot/types-codec": "9.0.1",
"@polkadot/util": "^10.1.2"
},
"devDependencies": {
"@polkadot/types-support": "8.13.1"
"@polkadot/types-support": "9.0.1"
}
}
+4 -9
View File
@@ -945,6 +945,10 @@ declare module '@polkadot/api-base/types/errors' {
MetadataExceedsMaxLen: AugmentedError<ApiType>;
/**
* The amount does not meet the minimum bond to either join or create a pool.
*
* The depositor can never unbond to a value less than
* `Pallet::depositor_min_bond`. The caller does not have nominating
* permissions for the pool. Members can never unbond to a value below `MinJoinBond`.
**/
MinimumBondNotMet: AugmentedError<ApiType>;
/**
@@ -952,10 +956,6 @@ declare module '@polkadot/api-base/types/errors' {
* other members to be permissionlessly unbonded.
**/
NotDestroying: AugmentedError<ApiType>;
/**
* Not enough points. Ty unbonding less.
**/
NotEnoughPointsToUnbond: AugmentedError<ApiType>;
/**
* Either a) the caller cannot make a valid kick or b) the pool is not destroying.
**/
@@ -964,11 +964,6 @@ declare module '@polkadot/api-base/types/errors' {
* The caller does not have nominating permissions for the pool.
**/
NotNominator: AugmentedError<ApiType>;
/**
* The depositor must be the only member in the bonded pool in order to unbond. And the
* depositor must be the only member in the sub pools in order to withdraw unbonded.
**/
NotOnlyPoolMember: AugmentedError<ApiType>;
/**
* The pool is not open to join
**/
+2 -2
View File
@@ -585,12 +585,12 @@ declare module '@polkadot/api-base/types/events' {
* pool.
* - `points` is the number of points that are issued as a result of `balance` being
* dissolved into the corresponding unbonding pool.
*
* - `era` is the era in which the balance will be unbonded.
* In the absence of slashing, these values will match. In the presence of slashing, the
* number of points that are issued in the unbonding pool will be less than the amount
* requested to be unbonded.
**/
Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128], { member: AccountId32, poolId: u32, balance: u128, points: u128 }>;
Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128, era: u32], { member: AccountId32, poolId: u32, balance: u128, points: u128, era: u32 }>;
/**
* The unbond pool at `era` of pool `pool_id` has been slashed to `balance`.
**/
-4
View File
@@ -1532,10 +1532,6 @@ declare module '@polkadot/api-base/types/storage' {
* This is basically in sync with the call to [`pallet_session::SessionManager::new_session`].
**/
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The earliest era for which we have a pending, unapplied slash.
**/
earliestUnappliedSlash: AugmentedQuery<ApiType, () => Observable<Option<u32>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Rewards for the last `HISTORY_DEPTH` eras.
* If reward hasn't been set or has been removed then 0 reward is returned.
+13 -1
View File
@@ -17,9 +17,10 @@ import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { AuthorityList, GrandpaEquivocationProof, SetId } from '@polkadot/types/interfaces/grandpa';
import type { OpaqueMetadata } from '@polkadot/types/interfaces/metadata';
import type { MmrBatchProof, MmrEncodableOpaqueLeaf, MmrError, MmrLeafIndex, MmrProof } from '@polkadot/types/interfaces/mmr';
import type { NpApiError } from '@polkadot/types/interfaces/nompools';
import type { CandidateCommitments, CandidateEvent, CommittedCandidateReceipt, CoreState, GroupRotationInfo, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, ParaId, ParaValidatorIndex, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, SessionInfo, ValidationCode, ValidationCodeHash, ValidatorSignature } from '@polkadot/types/interfaces/parachains';
import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { AccountId, Block, Hash, Header, Index, KeyTypeId, Slot, ValidatorId } from '@polkadot/types/interfaces/runtime';
import type { AccountId, Balance, Block, Hash, Header, Index, KeyTypeId, Slot, ValidatorId } from '@polkadot/types/interfaces/runtime';
import type { SessionIndex } from '@polkadot/types/interfaces/session';
import type { RuntimeVersion } from '@polkadot/types/interfaces/state';
import type { ApplyExtrinsicResult } from '@polkadot/types/interfaces/system';
@@ -206,6 +207,17 @@ declare module '@polkadot/api-base/types/calls' {
**/
[key: string]: DecoratedCallBase<ApiType>;
};
/** 0x17a6bc0d0062aeb3/1 */
nominationPoolsApi: {
/**
* Returns the pending rewards for the given member.
**/
pendingRewards: AugmentedCall<ApiType, (member: AccountId | string | Uint8Array) => Observable<Result<Balance, NpApiError>>>;
/**
* Generic call
**/
[key: string]: DecoratedCallBase<ApiType>;
};
/** 0xf78b278be53f454c/2 */
offchainWorkerApi: {
/**
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-augment', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/api-augment', path: 'auto', type: 'auto', version: '9.0.1' };
@@ -1320,10 +1320,6 @@ declare module '@polkadot/api-base/types/storage' {
* This is basically in sync with the call to [`pallet_session::SessionManager::new_session`].
**/
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The earliest era for which we have a pending, unapplied slash.
**/
earliestUnappliedSlash: AugmentedQuery<ApiType, () => Observable<Option<u32>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Rewards for the last `HISTORY_DEPTH` eras.
* If reward hasn't been set or has been removed then 0 reward is returned.
+8 -4
View File
@@ -17,6 +17,14 @@ declare module '@polkadot/api-base/types/errors' {
* nominated.
**/
AccountNonGrata: AugmentedError<ApiType>;
/**
* The founders/fellows/allies have already been initialized.
**/
AllianceAlreadyInitialized: AugmentedError<ApiType>;
/**
* The Alliance has not been initialized yet, therefore accounts cannot join it.
**/
AllianceNotYetInitialized: AugmentedError<ApiType>;
/**
* Account is already an elevated (fellow) member.
**/
@@ -33,10 +41,6 @@ declare module '@polkadot/api-base/types/errors' {
* Balance is insufficient for the required deposit.
**/
InsufficientFunds: AugmentedError<ApiType>;
/**
* The founders/fellows/allies have already been initialized.
**/
MembersAlreadyInitialized: AugmentedError<ApiType>;
/**
* The announcement is not found.
**/
+2 -2
View File
@@ -755,12 +755,12 @@ declare module '@polkadot/api-base/types/events' {
* pool.
* - `points` is the number of points that are issued as a result of `balance` being
* dissolved into the corresponding unbonding pool.
*
* - `era` is the era in which the balance will be unbonded.
* In the absence of slashing, these values will match. In the presence of slashing, the
* number of points that are issued in the unbonding pool will be less than the amount
* requested to be unbonded.
**/
Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128], { member: AccountId32, poolId: u32, balance: u128, points: u128 }>;
Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128, era: u32], { member: AccountId32, poolId: u32, balance: u128, points: u128, era: u32 }>;
/**
* The unbond pool at `era` of pool `pool_id` has been slashed to `balance`.
**/
@@ -1295,10 +1295,6 @@ declare module '@polkadot/api-base/types/storage' {
* This is basically in sync with the call to [`pallet_session::SessionManager::new_session`].
**/
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The earliest era for which we have a pending, unapplied slash.
**/
earliestUnappliedSlash: AugmentedQuery<ApiType, () => Observable<Option<u32>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Rewards for the last `HISTORY_DEPTH` eras.
* If reward hasn't been set or has been removed then 0 reward is returned.
@@ -17,6 +17,7 @@ import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { AuthorityList, GrandpaEquivocationProof, SetId } from '@polkadot/types/interfaces/grandpa';
import type { OpaqueMetadata } from '@polkadot/types/interfaces/metadata';
import type { MmrBatchProof, MmrEncodableOpaqueLeaf, MmrError, MmrLeafIndex, MmrProof } from '@polkadot/types/interfaces/mmr';
import type { NpApiError } from '@polkadot/types/interfaces/nompools';
import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { AccountId, Balance, Block, Hash, Header, Index, KeyTypeId, Slot } from '@polkadot/types/interfaces/runtime';
import type { RuntimeVersion } from '@polkadot/types/interfaces/state';
@@ -216,6 +217,17 @@ declare module '@polkadot/api-base/types/calls' {
**/
[key: string]: DecoratedCallBase<ApiType>;
};
/** 0x17a6bc0d0062aeb3/1 */
nominationPoolsApi: {
/**
* Returns the pending rewards for the given member.
**/
pendingRewards: AugmentedCall<ApiType, (member: AccountId | string | Uint8Array) => Observable<Result<Balance, NpApiError>>>;
/**
* Generic call
**/
[key: string]: DecoratedCallBase<ApiType>;
};
/** 0xf78b278be53f454c/2 */
offchainWorkerApi: {
/**
+5 -5
View File
@@ -20,13 +20,13 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/rpc-core": "8.13.1",
"@polkadot/types": "8.13.1",
"@polkadot/util": "^10.0.2",
"@babel/runtime": "^7.18.9",
"@polkadot/rpc-core": "9.0.1",
"@polkadot/types": "9.0.1",
"@polkadot/util": "^10.1.2",
"rxjs": "^7.5.6"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-base', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/api-base', path: 'auto', type: 'auto', version: '9.0.1' };
+2 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { DecoratedRpc, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics } from '@polkadot/api-base/types';
import type { DecoratedRpc, QueryableCalls, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics } from '@polkadot/api-base/types';
import type { RpcInterface } from '@polkadot/rpc-core/types';
import type { Metadata } from '@polkadot/types';
import type { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
@@ -10,6 +10,7 @@ import type { Registry, Signer } from '@polkadot/types/types';
// A smaller interface of ApiRx, used in derive and in SubmittableExtrinsic
export interface ApiInterfaceRx {
call: QueryableCalls<'rxjs'>,
consts: QueryableConsts<'rxjs'>;
extrinsicType: number;
genesisHash?: Hash;
-4
View File
@@ -58,10 +58,6 @@ export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunctio
* @deprecated Use api.at(<blockHash>)
*/
keysAt: <K extends AnyTuple = A> (hash: Hash | Uint8Array | string, ...args: DropLast<Parameters<F>>) => PromiseOrObs<ApiType, StorageKey<K>[]>;
/**
* @deprecated The underlying RPC this been marked unsafe and is generally not exposed
*/
range: <T extends Codec | any = ReturnCodec<F>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>;
/**
* @deprecated Use api.at(<blockHash>)
*/
@@ -58,11 +58,6 @@ export interface SubmittableExtrinsic<ApiType extends ApiTypes, R extends ISubmi
send (statusCb: Callback<R>): SubmittableResultSubscription<ApiType, R>;
/**
* @deprecated
*/
sign (account: IKeyringPair, _options?: Partial<SignerOptions>): this;
signAsync (account: AddressOrPair, _options?: Partial<SignerOptions>): PromiseOrObs<ApiType, this>;
signAndSend (account: AddressOrPair, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType, R>;
+10 -10
View File
@@ -20,20 +20,20 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/api": "8.13.1",
"@polkadot/types": "8.13.1",
"@polkadot/types-codec": "8.13.1",
"@polkadot/types-create": "8.13.1",
"@polkadot/util": "^10.0.2",
"@polkadot/util-crypto": "^10.0.2",
"@babel/runtime": "^7.18.9",
"@polkadot/api": "9.0.1",
"@polkadot/types": "9.0.1",
"@polkadot/types-codec": "9.0.1",
"@polkadot/types-create": "9.0.1",
"@polkadot/util": "^10.1.2",
"@polkadot/util-crypto": "^10.1.2",
"rxjs": "^7.5.6"
},
"devDependencies": {
"@polkadot/api-augment": "8.13.1",
"@polkadot/keyring": "^10.0.2"
"@polkadot/api-augment": "9.0.1",
"@polkadot/keyring": "^10.1.2"
}
}
+5 -5
View File
@@ -8,7 +8,11 @@ import { v0ToV1 } from './toV1';
import { v1ToV2 } from './toV2';
import { v2ToV3 } from './toV3';
type Versions = 'V3' | 'V2' | 'V1' | 'V0';
// The versions where an enum is used, aka V0 is missing
// (Order from newest, i.e. we expect more on newest vs oldest)
export const enumVersions = <const> ['V3', 'V2', 'V1'];
type Versions = typeof enumVersions[number] | 'V0';
type Converter = (registry: Registry, vx: any) => ContractMetadataLatest;
@@ -26,10 +30,6 @@ export const v2ToLatest = createConverter(v3ToLatest, v2ToV3);
export const v1ToLatest = createConverter(v2ToLatest, v1ToV2);
export const v0ToLatest = createConverter(v1ToLatest, v0ToV1);
// The versions where an enum is used, aka V0 is missing
// (Order from newest, i.e. we expect more on newest vs oldest)
export const enumVersions = ['V3', 'V2', 'V1'];
export const convertVersions: [Versions, Converter][] = [
['V3', v3ToLatest],
['V2', v2ToLatest],
+1 -1
View File
@@ -23,7 +23,7 @@ interface ArgsEntry <T extends WithArgs> extends NamedEntry {
args: GetArgsType<T>['args'][0][];
}
const ARG_TYPES = {
const ARG_TYPES = <const> {
ContractConstructorSpec: 'ContractMessageParamSpecV2',
ContractEventSpec: 'ContractEventParamSpecV2',
ContractMessageSpec: 'ContractMessageParamSpecV2'
+4 -4
View File
@@ -26,10 +26,10 @@ export abstract class Base<ApiType extends ApiTypes> {
if (!api || !api.isConnected || !api.tx) {
throw new Error('Your API has not been initialized correctly and is not connected to a chain');
} else if (!api.tx.contracts || !Object.keys(api.tx.contracts).length) {
throw new Error('You need to connect to a chain with a runtime that supports contracts');
} else if (!isFunction(api.tx.contracts.instantiateWithCode)) {
throw new Error('You need to connect to a chain with a runtime with a V3 contracts module. The runtime does not expose api.tx.contracts.instantiateWithCode');
} else if (!api.tx.contracts || !isFunction(api.tx.contracts.instantiateWithCode) || api.tx.contracts.instantiateWithCode.meta.args.length !== 6) {
throw new Error('The runtime does not expose api.tx.contracts.instantiateWithCode with storageDepositLimit');
} else if (!api.call.contractsApi || !isFunction(api.call.contractsApi.call)) {
throw new Error('Your runtime does not expose the api.call.contractsApi.call runtime interfaces');
}
}
+7 -11
View File
@@ -57,20 +57,16 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
}
#deploy = (constructorOrId: AbiConstructor | string | number, { gasLimit = BN_ZERO, salt, storageDepositLimit = null, value = BN_ZERO }: BlueprintOptions, params: unknown[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => {
const hasStorageDeposit = this.api.tx.contracts.instantiate.meta.args.length === 6;
const encParams = this.abi.findConstructor(constructorOrId).toU8a(params);
const encSalt = encodeSalt(salt);
const tx = hasStorageDeposit
? this.api.tx.contracts.instantiate(value, gasLimit, storageDepositLimit, this.codeHash, encParams, encSalt)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old style without storage deposit
: this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encParams, encSalt);
return tx.withResultTransform((result: ISubmittableResult) =>
new BlueprintSubmittableResult(result, applyOnEvent(result, ['Instantiated'], ([record]: EventRecord[]) =>
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
))
);
return this.api.tx.contracts
.instantiate(value, gasLimit, storageDepositLimit, this.codeHash, encParams, encSalt)
.withResultTransform((result: ISubmittableResult) =>
new BlueprintSubmittableResult(result, applyOnEvent(result, ['Instantiated'], ([record]: EventRecord[]) =>
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
))
);
};
}
+13 -17
View File
@@ -64,27 +64,23 @@ export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
}
#instantiate = (constructorOrId: AbiConstructor | string | number, { gasLimit = BN_ZERO, salt, storageDepositLimit = null, value = BN_ZERO }: BlueprintOptions, params: unknown[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
const hasStorageDeposit = this.api.tx.contracts.instantiateWithCode.meta.args.length === 6;
const encCode = compactAddLength(this.code);
const encParams = this.abi.findConstructor(constructorOrId).toU8a(params);
const encSalt = encodeSalt(salt);
const tx = hasStorageDeposit
? this.api.tx.contracts.instantiateWithCode(value, gasLimit, storageDepositLimit, encCode, encParams, encSalt)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old style without storage deposit
: this.api.tx.contracts.instantiateWithCode(value, gasLimit, encCode, encParams, encSalt);
return tx.withResultTransform((result: ISubmittableResult) =>
new CodeSubmittableResult(result, ...(applyOnEvent(result, ['CodeStored', 'Instantiated'], (records: EventRecord[]) =>
records.reduce<[Blueprint<ApiType>?, Contract<ApiType>?]>(([blueprint, contract], { event }) =>
this.api.events.contracts.Instantiated.is(event)
? [blueprint, new Contract<ApiType>(this.api, this.abi, (event as unknown as { data: [Codec, AccountId] }).data[1], this._decorateMethod)]
: this.api.events.contracts.CodeStored.is(event)
? [new Blueprint<ApiType>(this.api, this.abi, (event as unknown as { data: [AccountId] }).data[0], this._decorateMethod), contract]
: [blueprint, contract],
[])
) || []))
);
return this.api.tx.contracts
.instantiateWithCode(value, gasLimit, storageDepositLimit, encCode, encParams, encSalt)
.withResultTransform((result: ISubmittableResult) =>
new CodeSubmittableResult(result, ...(applyOnEvent(result, ['CodeStored', 'Instantiated'], (records: EventRecord[]) =>
records.reduce<[Blueprint<ApiType>?, Contract<ApiType>?]>(([blueprint, contract], { event }) =>
this.api.events.contracts.Instantiated.is(event)
? [blueprint, new Contract<ApiType>(this.api, this.abi, (event as unknown as { data: [Codec, AccountId] }).data[1], this._decorateMethod)]
: this.api.events.contracts.CodeStored.is(event)
? [new Blueprint<ApiType>(this.api, this.abi, (event as unknown as { data: [AccountId] }).data[0], this._decorateMethod), contract]
: [blueprint, contract],
[])
) || []))
);
};
}
+41 -66
View File
@@ -13,10 +13,10 @@ import { map } from 'rxjs';
import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base';
import { BN, BN_HUNDRED, BN_ONE, BN_ZERO, bnToBn, isFunction, isUndefined, logger } from '@polkadot/util';
import { BN, BN_HUNDRED, BN_ONE, BN_ZERO, bnToBn, isUndefined, logger } from '@polkadot/util';
import { Abi } from '../Abi';
import { applyOnEvent, extractOptions, isOptions } from '../util';
import { applyOnEvent } from '../util';
import { Base } from './Base';
import { withMeta } from './util';
@@ -26,23 +26,18 @@ export interface ContractConstructor<ApiType extends ApiTypes> {
// As per Rust, 5 * GAS_PER_SEC
const MAX_CALL_GAS = new BN(5_000_000_000_000).isub(BN_ONE);
const ERROR_NO_CALL = 'Your node does not expose the contracts.call RPC. This is most probably due to a runtime configuration.';
const l = logger('Contract');
function createQuery <ApiType extends ApiTypes> (meta: AbiMessage, fn: (origin: string | AccountId | Uint8Array, options: ContractOptions, params: unknown[]) => ContractCallResult<ApiType, ContractCallOutcome>): ContractQuery<ApiType> {
return withMeta(meta, (origin: string | AccountId | Uint8Array, options: bigint | string | number | BN | ContractOptions, ...params: unknown[]): ContractCallResult<ApiType, ContractCallOutcome> =>
isOptions(options)
? fn(origin, options, params)
: fn(origin, ...extractOptions<ContractOptions>(options, params))
return withMeta(meta, (origin: string | AccountId | Uint8Array, options: ContractOptions, ...params: unknown[]): ContractCallResult<ApiType, ContractCallOutcome> =>
fn(origin, options, params)
);
}
function createTx <ApiType extends ApiTypes> (meta: AbiMessage, fn: (options: ContractOptions, params: unknown[]) => SubmittableExtrinsic<ApiType>): ContractTx<ApiType> {
return withMeta(meta, (options: bigint | string | number | BN | ContractOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType> =>
isOptions(options)
? fn(options, params)
: fn(...extractOptions<ContractOptions>(options, params))
return withMeta(meta, (options: ContractOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType> =>
fn(options, params)
);
}
@@ -82,15 +77,7 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
});
}
public get hasRpcContractsCall (): boolean {
return isFunction(this.api.rx.rpc.contracts?.call);
}
public get query (): MapMessageQuery<ApiType> {
if (!this.hasRpcContractsCall) {
throw new Error(ERROR_NO_CALL);
}
return this.#query;
}
@@ -112,64 +99,52 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
};
#exec = (messageOrId: AbiMessage | string | number, { gasLimit = BN_ZERO, storageDepositLimit = null, value = BN_ZERO }: ContractOptions, params: unknown[]): SubmittableExtrinsic<ApiType> => {
const hasStorageDeposit = this.api.tx.contracts.call.meta.args.length === 5;
const gas = this.#getGas(gasLimit);
const encParams = this.abi.findMessage(messageOrId).toU8a(params);
const tx = hasStorageDeposit
? this.api.tx.contracts.call(this.address, value, gas, storageDepositLimit, encParams)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old style without storage deposit
: this.api.tx.contracts.call(this.address, value, gas, encParams);
return tx.withResultTransform((result: ISubmittableResult) =>
// ContractEmitted is the current generation, ContractExecution is the previous generation
new ContractSubmittableResult(result, applyOnEvent(result, ['ContractEmitted', 'ContractExecution'], (records: EventRecord[]) =>
records
.map(({ event: { data: [, data] } }): DecodedEvent | null => {
try {
return this.abi.decodeEvent(data as Bytes);
} catch (error) {
l.error(`Unable to decode contract event: ${(error as Error).message}`);
return this.api.tx.contracts
.call(this.address, value, gas, storageDepositLimit, encParams)
.withResultTransform((result: ISubmittableResult) =>
// ContractEmitted is the current generation, ContractExecution is the previous generation
new ContractSubmittableResult(result, applyOnEvent(result, ['ContractEmitted', 'ContractExecution'], (records: EventRecord[]) =>
records
.map(({ event: { data: [, data] } }): DecodedEvent | null => {
try {
return this.abi.decodeEvent(data as Bytes);
} catch (error) {
l.error(`Unable to decode contract event: ${(error as Error).message}`);
return null;
}
})
.filter((decoded): decoded is DecodedEvent => !!decoded)
))
);
return null;
}
})
.filter((decoded): decoded is DecodedEvent => !!decoded)
))
);
};
#read = (messageOrId: AbiMessage | string | number, { gasLimit = BN_ZERO, storageDepositLimit = null, value = BN_ZERO }: ContractOptions, params: unknown[]): ContractCallSend<ApiType> => {
if (!this.hasRpcContractsCall) {
throw new Error(ERROR_NO_CALL);
}
const message = this.abi.findMessage(messageOrId);
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
send: this._decorateMethod((origin: string | AccountId | Uint8Array) => {
const hasStorageDeposit = this.api.tx.contracts.call.meta.args.length === 5;
const inputData = message.toU8a(params);
const rpc = hasStorageDeposit
? this.api.rx.rpc.contracts.call({ dest: this.address, gasLimit: this.#getGas(gasLimit, true), inputData, origin, storageDepositLimit, value })
: this.api.rx.rpc.contracts.call({ dest: this.address, gasLimit: this.#getGas(gasLimit, true), inputData, origin, value });
const mapFn = ({ debugMessage, gasConsumed, gasRequired, result, storageDeposit }: ContractExecResult): ContractCallOutcome => ({
debugMessage,
gasConsumed,
gasRequired: gasRequired && !gasRequired.isZero()
? gasRequired
: gasConsumed,
output: result.isOk && message.returnType
? this.abi.registry.createTypeUnsafe(message.returnType.lookupName || message.returnType.type, [result.asOk.data.toU8a(true)], { isPedantic: true })
: null,
result,
storageDeposit
});
return rpc.pipe(map(mapFn));
})
send: this._decorateMethod((origin: string | AccountId | Uint8Array) =>
this.api.rx.call.contractsApi
.call<ContractExecResult>(origin, this.address, value, this.#getGas(gasLimit, true), storageDepositLimit, message.toU8a(params))
.pipe(
map(({ debugMessage, gasConsumed, gasRequired, result, storageDeposit }): ContractCallOutcome => ({
debugMessage,
gasConsumed,
gasRequired: gasRequired && !gasRequired.isZero()
? gasRequired
: gasConsumed,
output: result.isOk && message.returnType
? this.abi.registry.createTypeUnsafe(message.returnType.lookupName || message.returnType.type, [result.asOk.data.toU8a(true)], { isPedantic: true })
: null,
result,
storageDeposit
}))
)
)
};
};
}
+14 -3
View File
@@ -6,14 +6,25 @@ import { TypeRegistry } from '@polkadot/types';
const registry = new TypeRegistry();
const instantiateWithCode = (): never => {
throw new Error('mock');
};
instantiateWithCode.meta = { args: new Array(6) };
export const mockApi = {
call: {
contractsApi: {
call: (): never => {
throw new Error('mock');
}
}
},
isConnected: true,
registry,
tx: {
contracts: {
instantiateWithCode: (): never => {
throw new Error('mock');
}
instantiateWithCode
}
}
} as unknown as ApiBase<'promise'>;
-9
View File
@@ -5,7 +5,6 @@ import type { Observable } from 'rxjs';
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes, ObsInnerType } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces';
import type { BN } from '@polkadot/util';
import type { AbiMessage, BlueprintOptions, ContractCallOutcome, ContractOptions } from '../types';
export interface MessageMeta {
@@ -14,26 +13,18 @@ export interface MessageMeta {
export interface BlueprintDeploy<ApiType extends ApiTypes> extends MessageMeta {
(options: BlueprintOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType>;
// @deprecated Use options form (to be dropped in a major update)
(value: bigint | string | number | BN, gasLimit: bigint | string | number | BN, ...params: unknown[]): SubmittableExtrinsic<ApiType>;
}
export interface ContractQuery<ApiType extends ApiTypes> extends MessageMeta {
(origin: AccountId | string | Uint8Array, options: ContractOptions, ...params: unknown[]): ContractCallResult<ApiType, ContractCallOutcome>;
// @deprecated Use options form (to be dropped in a major update)
(origin: AccountId | string | Uint8Array, value: bigint | BN | string | number, gasLimit: bigint | BN | string | number, ...params: unknown[]): ContractCallResult<ApiType, ContractCallOutcome>;
}
export interface ContractTx<ApiType extends ApiTypes> extends MessageMeta {
(options: ContractOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType>;
// @deprecated Use options form (to be dropped in a major update)
(value: bigint | BN | string | number, gasLimit: bigint | BN | string | number, ...params: unknown[]): SubmittableExtrinsic<ApiType>;
}
export interface ContractGeneric<O, T> {
(messageOrId: AbiMessage | string | number, options: O, ...params: unknown[]): T;
// @deprecated Use options form (to be dropped in a major update)
(messageOrId: AbiMessage | string | number, value: bigint | BN | string | number, gasLimit: bigint | BN | string | number, ...params: unknown[]): T;
}
export type ContractCallResult<ApiType extends ApiTypes, T> = ApiType extends 'rxjs'
+4 -11
View File
@@ -4,7 +4,6 @@
import type { SubmittableResult } from '@polkadot/api';
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes } from '@polkadot/api/types';
import type { BN } from '@polkadot/util';
import type { AbiConstructor, AbiMessage, BlueprintOptions } from '../types';
import type { BlueprintDeploy, ContractGeneric } from './types';
@@ -12,8 +11,6 @@ import { Bytes } from '@polkadot/types';
import { compactAddLength, u8aToU8a } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
import { extractOptions, isOptions } from '../util';
export const EMPTY_SALT = new Uint8Array();
export function withMeta <T extends { meta: AbiMessage }> (meta: AbiMessage, creator: Omit<T, 'meta'>): T {
@@ -23,18 +20,14 @@ export function withMeta <T extends { meta: AbiMessage }> (meta: AbiMessage, cre
}
export function createBluePrintTx <ApiType extends ApiTypes, R extends SubmittableResult> (meta: AbiMessage, fn: (options: BlueprintOptions, params: unknown[]) => SubmittableExtrinsic<ApiType, R>): BlueprintDeploy<ApiType> {
return withMeta(meta, (options: bigint | string | number | BN | BlueprintOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType, R> =>
isOptions(options)
? fn(options, params)
: fn(...extractOptions<BlueprintOptions>(options, params))
return withMeta(meta, (options: BlueprintOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType, R> =>
fn(options, params)
);
}
export function createBluePrintWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: unknown[]) => T): ContractGeneric<BlueprintOptions, T> {
return (constructorOrId: AbiConstructor | string | number, options: bigint | string | number | BN | BlueprintOptions, ...params: unknown[]): T =>
isOptions(options)
? fn(constructorOrId, options, params)
: fn(constructorOrId, ...extractOptions<BlueprintOptions>(options, params));
return (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, ...params: unknown[]): T =>
fn(constructorOrId, options, params);
}
export function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()): Uint8Array {
@@ -14,12 +14,8 @@ import abiIncrementer from './test/contracts/ink/v0/incrementer.json' assert { t
async function checkBlueprint (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
const blueprint = new BlueprintPromise(api, abiIncrementer as Record<string, unknown>, '0x1234');
// new style
await blueprint.tx.new({ gasLimit: 456, salt: '0x1234', value: 123 }, 42).signAndSend(pairs.bob);
await blueprint.tx.new({ gasLimit: 456, value: 123 }, 42).signAndSend(pairs.bob);
// old style
await blueprint.tx.new(123, 456, 42).signAndSend(pairs.bob);
}
async function checkContract (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
@@ -27,11 +23,9 @@ async function checkContract (api: ApiPromise, pairs: TestKeyringMap): Promise<v
// queries
await contract.query.get(pairs.alice.address, {});
await contract.query.get(pairs.alice.address, 0, 0);
// execute
await contract.tx.inc({ gasLimit: 1234 }, 123).signAndSend(pairs.eve);
await contract.tx.inc(123, 456, 69).signAndSend(pairs.eve);
}
async function main (): Promise<void> {
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-contract', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/api-contract', path: 'auto', type: 'auto', version: '9.0.1' };
-16
View File
@@ -3,15 +3,9 @@
import type { SubmittableResult } from '@polkadot/api';
import type { EventRecord } from '@polkadot/types/interfaces';
import type { BN } from '@polkadot/util';
import type { BlueprintOptions, ContractOptions } from './types';
import { isBigInt, isBn, isNumber, isString } from '@polkadot/util';
type ContractEvents = 'CodeStored' | 'ContractEmitted' | 'ContractExecution' | 'Instantiated';
type TOptions = BlueprintOptions | ContractOptions;
export function applyOnEvent <T> (result: SubmittableResult, types: ContractEvents[], fn: (records: EventRecord[]) => T): T | undefined {
if (result.isInBlock || result.isFinalized) {
const records = result.filterRecords('contracts', types);
@@ -23,13 +17,3 @@ export function applyOnEvent <T> (result: SubmittableResult, types: ContractEven
return undefined;
}
export function isOptions <T> (options: bigint | string | number | BN | T): options is T {
return !(isBn(options) || isBigInt(options) || isNumber(options) || isString(options));
}
export function extractOptions <T extends TOptions> (value: bigint | string | number | BN, params: unknown[]): [T, unknown[]] {
const gasLimit = params.shift() as BN;
return [{ gasLimit, value } as T, params];
}
+15 -15
View File
@@ -20,25 +20,25 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/api": "8.13.1",
"@polkadot/api-augment": "8.13.1",
"@polkadot/api-base": "8.13.1",
"@polkadot/rpc-core": "8.13.1",
"@polkadot/types": "8.13.1",
"@polkadot/types-codec": "8.13.1",
"@polkadot/util": "^10.0.2",
"@polkadot/util-crypto": "^10.0.2",
"@babel/runtime": "^7.18.9",
"@polkadot/api": "9.0.1",
"@polkadot/api-augment": "9.0.1",
"@polkadot/api-base": "9.0.1",
"@polkadot/rpc-core": "9.0.1",
"@polkadot/types": "9.0.1",
"@polkadot/types-codec": "9.0.1",
"@polkadot/util": "^10.1.2",
"@polkadot/util-crypto": "^10.1.2",
"rxjs": "^7.5.6"
},
"devDependencies": {
"@polkadot/api": "8.13.1",
"@polkadot/api-augment": "8.13.1",
"@polkadot/rpc-augment": "8.13.1",
"@polkadot/rpc-provider": "8.13.1",
"@polkadot/types-support": "8.13.1"
"@polkadot/api": "9.0.1",
"@polkadot/api-augment": "9.0.1",
"@polkadot/rpc-augment": "9.0.1",
"@polkadot/rpc-provider": "9.0.1",
"@polkadot/types-support": "9.0.1"
}
}
+14
View File
@@ -0,0 +1,14 @@
// Copyright 2017-2022 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { hasProposals as collectiveHasProposals, members as collectiveMembers, prime as collectivePrime, proposal as collectiveProposal, proposalCount as collectiveProposalCount, proposalHashes as collectiveProposalHashes, proposals as collectiveProposals } from '../collective';
export const members = collectiveMembers('allianceMotion');
export const hasProposals = collectiveHasProposals('allianceMotion');
export const proposal = collectiveProposal('allianceMotion');
export const proposalCount = collectiveProposalCount('allianceMotion');
export const proposalHashes = collectiveProposalHashes('allianceMotion');
export const proposals = collectiveProposals('allianceMotion');
export const prime = collectivePrime('allianceMotion');
+10 -13
View File
@@ -10,7 +10,7 @@ import type { Bag } from './types';
import { map, of, switchMap } from 'rxjs';
import { BN_ZERO, bnToBn } from '@polkadot/util';
import { BN_ZERO, bnToBn, objectSpread } from '@polkadot/util';
import { memo } from '../util';
@@ -21,20 +21,17 @@ function orderBags (ids: BN[], bags: Option<PalletBagsListListBag>[]): Bag[] {
id,
key: id.toString()
}))
.sort((a, b) => b.id.cmp(a.id))
.map((base, index): Bag => ({
...base,
bagLower: BN_ZERO,
bagUpper: base.id,
index
}));
.sort((a, b) => b.id.cmp(a.id));
const max = sorted.length - 1;
return sorted.map((entry, index) =>
index === max
? entry
// We could probably use a .add(BN_ONE) here
: { ...entry, bagLower: sorted[index + 1].bagUpper }
return sorted.map((entry, index): Bag =>
objectSpread(entry, {
bagLower: index === max
? BN_ZERO
: sorted[index + 1].id,
bagUpper: entry.id,
index
})
);
}
@@ -8,12 +8,14 @@ import type { Bag, BagExpanded } from './types';
import { map, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util';
export function expand (instanceId: string, api: DeriveApi): (bag: Bag) => Observable<BagExpanded> {
return memo(instanceId, (bag: Bag): Observable<BagExpanded> =>
api.derive.bagsList.listNodes(bag.bag).pipe(
map((nodes) => ({ ...bag, nodes }))
map((nodes) => objectSpread({ nodes }, bag))
)
);
}
+7 -7
View File
@@ -9,7 +9,7 @@ import type { DeriveApi, DeriveBalancesAccount, DeriveBalancesAccountData } from
import { combineLatest, map, of, switchMap } from 'rxjs';
import { isFunction } from '@polkadot/util';
import { isFunction, objectSpread } from '@polkadot/util';
import { memo } from '../util';
@@ -40,12 +40,11 @@ function getBalance (api: DeriveApi, [freeBalance, reservedBalance, frozenFee, f
}
function calcBalances (api: DeriveApi, [accountId, [accountNonce, [primary, ...additional]]]: [AccountId, Result]): DeriveBalancesAccount {
return {
return objectSpread({
accountId,
accountNonce,
additional: additional.map((b) => getBalance(api, b)),
...getBalance(api, primary)
};
additional: additional.map((b) => getBalance(api, b))
}, getBalance(api, primary));
}
// old
@@ -150,7 +149,8 @@ function querySystemAccount (api: DeriveApi, accountId: AccountId): Observable<R
* ```
*/
export function account (instanceId: string, api: DeriveApi): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAccount> {
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances');
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName, 'balances');
const nonDefaultBalances = balanceInstances && (balanceInstances.length !== 1 || balanceInstances[0] !== 'balances');
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAccount> =>
api.derive.accounts.accountId(address).pipe(
@@ -158,7 +158,7 @@ export function account (instanceId: string, api: DeriveApi): (address: AccountI
(accountId
? combineLatest([
of(accountId),
balanceInstances
nonDefaultBalances
? queryBalancesAccount(api, accountId, balanceInstances)
: isFunction(api.query.system?.account)
? querySystemAccount(api, accountId)
+7 -10
View File
@@ -9,7 +9,7 @@ import type { DeriveApi, DeriveBalancesAccount, DeriveBalancesAccountData, Deriv
import { combineLatest, map, of, switchMap } from 'rxjs';
import { BN, BN_ZERO, bnMax, bnMin, isFunction } from '@polkadot/util';
import { BN, BN_ZERO, bnMax, bnMin, isFunction, objectSpread } from '@polkadot/util';
import { memo } from '../util';
@@ -57,13 +57,12 @@ function calcLocked (api: DeriveApi, bestNumber: BlockNumber, locks: (PalletBala
function calcShared (api: DeriveApi, bestNumber: BlockNumber, data: DeriveBalancesAccountData, locks: (PalletBalancesBalanceLock | BalanceLockTo212)[]): DeriveBalancesAllAccountData {
const { allLocked, lockedBalance, lockedBreakdown, vestingLocked } = calcLocked(api, bestNumber, locks);
return {
...data,
return objectSpread({}, data, {
availableBalance: api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), data.freeBalance.sub(lockedBalance))),
lockedBalance,
lockedBreakdown,
vestingLocked
};
});
}
function calcVesting (bestNumber: BlockNumber, shared: DeriveBalancesAllAccountData, _vesting: PalletVestingVestingInfo[] | null): DeriveBalancesAllVesting {
@@ -102,16 +101,14 @@ function calcVesting (bestNumber: BlockNumber, shared: DeriveBalancesAllAccountD
function calcBalances (api: DeriveApi, [data, [vesting, allLocks, namedReserves], bestNumber]: Result): DeriveBalancesAll {
const shared = calcShared(api, bestNumber, data, allLocks[0]);
return {
...shared,
...calcVesting(bestNumber, shared, vesting),
return objectSpread(shared, calcVesting(bestNumber, shared, vesting), {
accountId: data.accountId,
accountNonce: data.accountNonce,
additional: allLocks
.filter((_, index) => index !== 0)
.slice(1)
.map((l, index) => calcShared(api, bestNumber, data.additional[index], l)),
namedReserves
};
});
}
// old
@@ -211,7 +208,7 @@ function queryCurrent (api: DeriveApi, accountId: AccountId | string, balanceIns
* ```
*/
export function all (instanceId: string, api: DeriveApi): (address: AccountId | string) => Observable<DeriveBalancesAll> {
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances');
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName, 'balances');
return memo(instanceId, (address: AccountId | string): Observable<DeriveBalancesAll> =>
combineLatest([
+7 -3
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { DeriveCustom } from '@polkadot/api-base/types';
import type { AnyFunction } from '@polkadot/types/types';
import type { AnyFunction, AnyString } from '@polkadot/types/types';
import type { ExactDerive } from './derive';
import type { DeriveApi } from './types';
@@ -22,6 +22,10 @@ export { lazyDeriveSection };
// Enable derive only if some of these modules are available
const checks: Record<string, Avail> = {
allianceMotion: {
instances: ['allianceMotion'],
methods: []
},
bagsList: {
instances: ['voterList', 'bagsList'],
methods: [],
@@ -84,7 +88,7 @@ const checks: Record<string, Avail> = {
}
};
function getModuleInstances (api: DeriveApi, specName: string, moduleName: string): string[] {
function getModuleInstances (api: DeriveApi, specName: AnyString, moduleName: string): string[] {
return api.registry.getModuleInstances(specName, moduleName) || [];
}
@@ -97,7 +101,7 @@ function injectFunctions (instanceId: string, api: DeriveApi, derives: DeriveCus
const result: Record<string, Record<string, AnyFunction>> = {};
const names = Object.keys(derives);
const keys = Object.keys(api.query);
const specName = api.runtimeVersion.specName.toString();
const specName = api.runtimeVersion.specName;
const filterKeys = (q: string) => keys.includes(q);
const filterInstances = (q: string) => getModuleInstances(api, specName, q).some(filterKeys);
@@ -12,7 +12,7 @@ import { isFunction } from '@polkadot/util';
import { memo } from '../util';
export function getInstance (api: DeriveApi, section: string): DeriveApi['query']['council'] {
const instances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), section);
const instances = api.registry.getModuleInstances(api.runtimeVersion.specName, section);
const name = instances && instances.length
? instances[0]
: section;
@@ -58,7 +58,7 @@ export function hasProposals (section: Collective): (instanceId: string, api: De
export function proposals (section: Collective): (instanceId: string, api: DeriveApi) => () => Observable<DeriveCollectiveProposal[]> {
return withSection(section, (query, api) =>
(): Observable<DeriveCollectiveProposal[]> =>
api.derive[section].proposalHashes().pipe(
api.derive[section as 'council'].proposalHashes().pipe(
switchMap((all) => _proposalsFrom(api, query, all))
)
);
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2022 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
export type Collective = 'council' | 'membership' | 'technicalCommittee';
export type Collective = 'allianceMotion' | 'council' | 'membership' | 'technicalCommittee';
@@ -7,6 +7,8 @@ import type { DeriveApi, DeriveOwnContributions } from '../types';
import { combineLatest, EMPTY, map, of, startWith, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util';
import { extractContributed } from './util';
@@ -21,10 +23,8 @@ function _getValues (api: DeriveApi, childKey: string, keys: string[]): Observab
? api.registry.createType('Balance', o.unwrap())
: api.registry.createType('Balance')
)
.reduce((all: DeriveOwnContributions, b, index): DeriveOwnContributions => ({
...all,
[keys[index]]: b
}), {})
.reduce((all: DeriveOwnContributions, b, index): DeriveOwnContributions =>
objectSpread(all, { [keys[index]]: b }), {})
)
);
}
@@ -51,10 +51,9 @@ function _contributions (api: DeriveApi, paraId: string | number | BN, childKey:
_getValues(api, childKey, keys),
_watchOwnChanges(api, paraId, childKey, keys)
]).pipe(
map(([all, latest]) => ({
...all,
...latest
}))
map(([all, latest]) =>
objectSpread({}, all, latest)
)
);
}
@@ -11,7 +11,7 @@ import type { DeriveApi, DeriveDispatch, DeriveProposalImage } from '../types';
import { catchError, combineLatest, map, of, switchMap } from 'rxjs';
import { Enum } from '@polkadot/types';
import { isFunction, stringToHex } from '@polkadot/util';
import { isFunction, objectSpread, stringToHex } from '@polkadot/util';
import { memo } from '../util';
@@ -107,7 +107,7 @@ function queryScheduler (api: DeriveApi): Observable<DeriveDispatch[]> {
]);
}),
map(([infos, images]): DeriveDispatch[] =>
infos.map((info, index) => ({ ...info, image: images[index] }))
infos.map((info, index) => objectSpread({ image: images[index] }, info))
)
);
}
+16 -14
View File
@@ -9,7 +9,7 @@ import type { DeriveApi, DeriveProposal, DeriveProposalImage } from '../types';
import { combineLatest, map, of, switchMap } from 'rxjs';
import { isFunction } from '@polkadot/util';
import { isFunction, objectSpread } from '@polkadot/util';
import { memo } from '../util';
@@ -33,17 +33,17 @@ function parse ([proposals, images, optDepositors]: Result): DeriveProposal[] {
.map(([index, imageHash, proposer], proposalIndex): DeriveProposal => {
const depositors = optDepositors[proposalIndex].unwrap();
return {
...(
isNewDepositors(depositors)
? { balance: depositors[1], seconds: depositors[0] }
: { balance: depositors[0], seconds: depositors[1] }
),
image: images[proposalIndex],
imageHash,
index,
proposer
};
return objectSpread(
{
image: images[proposalIndex],
imageHash,
index,
proposer
},
isNewDepositors(depositors)
? { balance: depositors[1], seconds: depositors[0] }
: { balance: depositors[0], seconds: depositors[1] }
);
});
}
@@ -56,9 +56,11 @@ export function proposals (instanceId: string, api: DeriveApi): () => Observable
? combineLatest([
of(proposals),
api.derive.democracy.preimages(
proposals.map(([, hash]) => hash)),
proposals.map(([, hash]) => hash)
),
api.query.democracy.depositOf.multi(
proposals.map(([index]) => index))
proposals.map(([index]) => index)
)
])
: of<Result>([[], [], []])
),
@@ -6,6 +6,8 @@ import type { DeriveApi, DeriveReferendumExt } from '../types';
import { combineLatest, map, of, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util';
export function referendums (instanceId: string, api: DeriveApi): () => Observable<DeriveReferendumExt[]> {
@@ -20,10 +22,9 @@ export function referendums (instanceId: string, api: DeriveApi): () => Observab
: of([[], []])
),
map(([referendums, votes]) =>
referendums.map((referendum, index): DeriveReferendumExt => ({
...referendum,
...votes[index]
}))
referendums.map((referendum, index): DeriveReferendumExt =>
objectSpread({}, referendum, votes[index])
)
)
)
);
@@ -10,7 +10,7 @@ import type { DeriveApi, DeriveBalancesAccount, DeriveReferendum, DeriveReferend
import { combineLatest, map, of, switchMap } from 'rxjs';
import { isFunction } from '@polkadot/util';
import { isFunction, objectSpread } from '@polkadot/util';
import { memo } from '../util';
import { calcVotes, getStatus } from './util';
@@ -57,11 +57,12 @@ function extractVotes (mapped: [AccountId, PalletDemocracyVoteVoting][], referen
// FIXME We are ignoring split votes
votes.reduce((result: DeriveReferendumVote[], [, vote]): DeriveReferendumVote[] => {
if (vote.isStandard) {
result.push({
accountId,
isDelegating: false,
...vote.asStandard
});
result.push(
objectSpread({
accountId,
isDelegating: false
}, vote.asStandard)
);
}
return result;
+3 -4
View File
@@ -6,7 +6,7 @@ import type { PalletDemocracyReferendumInfo, PalletDemocracyReferendumStatus, Pa
import type { Option } from '@polkadot/types-codec';
import type { DeriveReferendum, DeriveReferendumVote, DeriveReferendumVotes, DeriveReferendumVoteState } from '../types';
import { BN, bnSqrt } from '@polkadot/util';
import { BN, bnSqrt, objectSpread } from '@polkadot/util';
interface ApproxState {
votedAye: BN;
@@ -119,11 +119,10 @@ export function calcVotes (sqrtElectorate: BN, referendum: DeriveReferendum, vot
? calcVotesCurrent(referendum.status.tally, votes)
: calcVotesPrev(votes);
return {
...state,
return objectSpread({}, state, {
isPassing: calcPassing(referendum.status.threshold, sqrtElectorate, state),
votes
};
});
}
export function getStatus (info: Option<PalletDemocracyReferendumInfo | ReferendumInfoTo239>): PalletDemocracyReferendumStatus | ReferendumInfoTo239 | null {
+2 -1
View File
@@ -4,6 +4,7 @@
import type { AnyFunction } from '@polkadot/types/types';
import * as accounts from './accounts';
import * as alliance from './alliance';
import * as bagsList from './bagsList';
import * as balances from './balances';
import * as bounties from './bounties';
@@ -23,7 +24,7 @@ import * as technicalCommittee from './technicalCommittee';
import * as treasury from './treasury';
import * as tx from './tx';
export const derive = { accounts, bagsList, balances, bounties, chain, contracts, council, crowdloan, democracy, elections, imOnline, membership, parachains, session, society, staking, technicalCommittee, treasury, tx };
export const derive = { accounts, alliance, bagsList, balances, bounties, chain, contracts, council, crowdloan, democracy, elections, imOnline, membership, parachains, session, society, staking, technicalCommittee, treasury, tx };
type DeriveSection<Section> = {
[M in keyof Section]: Section[M] extends AnyFunction
+13 -10
View File
@@ -11,6 +11,8 @@ import type { DeriveElectionsInfo } from './types';
import { combineLatest, map, of } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util';
// SeatHolder is current tuple is 2.x-era Substrate
@@ -55,7 +57,7 @@ function getConstants (api: DeriveApi, elections: string | null): Partial<Derive
}
function getModules (api: DeriveApi): [string, string | null] {
const [council] = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'council') || ['council'];
const [council] = api.registry.getModuleInstances(api.runtimeVersion.specName, 'council') || ['council'];
const elections = api.query.phragmenElection
? 'phragmenElection'
: api.query.electionsPhragmen
@@ -107,15 +109,16 @@ export function info (instanceId: string, api: DeriveApi): () => Observable<Deri
? queryAll(api, council, elections)
: queryCouncil(api, council)
).pipe(
map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({
...getConstants(api, elections),
candidateCount: api.registry.createType('u32', candidates.length),
candidates: candidates.map(getCandidate),
members: members.length
? members.map(getAccountTuple).sort(sortAccounts)
: councilMembers.map((a): [AccountId32, Balance] => [a, api.registry.createType('Balance')]),
runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts)
}))
map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo =>
objectSpread({}, getConstants(api, elections), {
candidateCount: api.registry.createType('u32', candidates.length),
candidates: candidates.map(getCandidate),
members: members.length
? members.map(getAccountTuple).sort(sortAccounts)
: councilMembers.map((a): [AccountId32, Balance] => [a, api.registry.createType('Balance')]),
runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts)
})
)
);
});
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-derive', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/api-derive', path: 'auto', type: 'auto', version: '9.0.1' };
+15 -15
View File
@@ -8,6 +8,8 @@ import type { Active, DidUpdate, Heads, ParaInfoResult, PendingSwap, RelayDispat
import { map, of } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util';
import { didUpdateToBool } from './util';
@@ -28,20 +30,18 @@ function parseActive (id: ParaId, active: Active): DeriveParachainActive | null
if (found && found[1].isSome) {
const [collatorId, retriable] = found[1].unwrap();
return {
collatorId,
...(
retriable.isWithRetries
? {
isRetriable: true,
retries: retriable.asWithRetries.toNumber()
}
: {
isRetriable: false,
retries: 0
}
)
};
return objectSpread<DeriveParachainActive>(
{ collatorId },
retriable.isWithRetries
? {
isRetriable: true,
retries: retriable.asWithRetries.toNumber()
}
: {
isRetriable: false,
retries: 0
}
);
}
return null;
@@ -65,7 +65,7 @@ function parse (id: ParaId, [active, retryQueue, selectedThreads, didUpdate, inf
didUpdate: didUpdateToBool(didUpdate, id),
heads,
id,
info: { id, ...info.unwrap() } as DeriveParachainInfo,
info: objectSpread<DeriveParachainInfo>({ id }, info.unwrap()),
pendingSwapId: pendingSwap.unwrapOr(null),
relayDispatchQueue,
retryCollators: parseCollators(id, retryQueue),
@@ -8,6 +8,8 @@ import type { DidUpdate, ParaInfoResult, PendingSwap, RelayDispatchQueueSize } f
import { combineLatest, map, of, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util';
import { didUpdateToBool } from './util';
@@ -23,7 +25,7 @@ function parse ([ids, didUpdate, infos, pendingSwaps, relayDispatchQueueSizes]:
return ids.map((id, index): DeriveParachain => ({
didUpdate: didUpdateToBool(didUpdate, id),
id,
info: { id, ...infos[index].unwrapOr(null) } as DeriveParachainInfo,
info: objectSpread<DeriveParachainInfo>({ id }, infos[index].unwrapOr(null)),
pendingSwapId: pendingSwaps[index].unwrapOr(null),
relayDispatchQueueSize: relayDispatchQueueSizes[index][0].toNumber()
}));
+4 -3
View File
@@ -6,6 +6,8 @@ import type { DeriveApi, DeriveSessionInfo } from '../types';
import { map } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util';
/**
@@ -18,13 +20,12 @@ export function info (instanceId: string, api: DeriveApi): () => Observable<Deri
const sessionLength = api.consts?.babe?.epochDuration || api.registry.createType('u64', 1);
const sessionsPerEra = api.consts?.staking?.sessionsPerEra || api.registry.createType('SessionIndex', 1);
return {
...indexes,
return objectSpread({
eraLength: api.registry.createType('BlockNumber', sessionsPerEra.mul(sessionLength)),
isEpoch: !!api.query.babe,
sessionLength,
sessionsPerEra
};
}, indexes);
})
)
);
+10 -8
View File
@@ -8,6 +8,8 @@ import type { DeriveApi, DeriveSessionInfo, DeriveSessionProgress } from '../typ
import { combineLatest, map, of, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util';
type ResultSlotsNoSession = [u64, u64, u64];
@@ -28,20 +30,20 @@ function createDerive (api: DeriveApi, info: DeriveSessionInfo, [currentSlot, ep
const sessionProgress = currentSlot.sub(epochStartSlot);
const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).imul(info.sessionLength).iadd(sessionProgress);
return {
...info,
return objectSpread({
eraProgress: api.registry.createType('BlockNumber', eraProgress),
sessionProgress: api.registry.createType('BlockNumber', sessionProgress)
};
}, info);
}
function queryAura (api: DeriveApi): Observable<DeriveSessionProgress> {
return api.derive.session.info().pipe(
map((info): DeriveSessionProgress => ({
...info,
eraProgress: api.registry.createType('BlockNumber'),
sessionProgress: api.registry.createType('BlockNumber')
}))
map((info): DeriveSessionProgress =>
objectSpread({
eraProgress: api.registry.createType('BlockNumber'),
sessionProgress: api.registry.createType('BlockNumber')
}, info)
)
);
}
+3 -5
View File
@@ -9,7 +9,7 @@ import type { StakingQueryFlags } from './types';
import { combineLatest, map, switchMap } from 'rxjs';
import { BN, BN_ZERO } from '@polkadot/util';
import { BN, BN_ZERO, objectSpread } from '@polkadot/util';
import { firstMemo, memo } from '../util';
@@ -54,12 +54,10 @@ function redeemableSum (api: DeriveApi, stakingLedger: PalletStakingStakingLedge
}
function parseResult (api: DeriveApi, sessionInfo: DeriveSessionInfo, keys: DeriveStakingKeys, query: DeriveStakingQuery): DeriveStakingAccount {
return {
...keys,
...query,
return objectSpread({}, keys, query, {
redeemable: redeemableSum(api, query.stakingLedger, sessionInfo),
unlocking: calculateUnlocking(api, query.stakingLedger, sessionInfo)
};
});
}
/**
+8 -5
View File
@@ -6,6 +6,8 @@ import type { DeriveApi, DeriveStakingOverview } from '../types';
import { combineLatest, map } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util';
/**
@@ -17,10 +19,11 @@ export function overview (instanceId: string, api: DeriveApi): () => Observable<
api.derive.session.indexes(),
api.derive.staking.validators()
]).pipe(
map(([indexes, { nextElected, validators }]): DeriveStakingOverview => ({
...indexes,
nextElected,
validators
}))
map(([indexes, { nextElected, validators }]): DeriveStakingOverview =>
objectSpread({}, indexes, {
nextElected,
validators
})
)
));
}
@@ -10,7 +10,7 @@ import type { DeriveStakingQuery } from './types';
import { combineLatest, map, of, switchMap } from 'rxjs';
import { BN_BILLION, BN_ZERO } from '@polkadot/util';
import { BN_BILLION, BN_ZERO, objectSpread } from '@polkadot/util';
import { firstMemo, memo } from '../util';
@@ -125,10 +125,11 @@ function filterRewards (eras: EraIndex[], valInfo: [string, DeriveStakingQuery][
return true;
})
.filter(({ validators }) => Object.keys(validators).length !== 0)
.map((reward) => ({
...reward,
nominators: reward.nominating.filter((n) => reward.validators[n.validatorId])
}));
.map((reward) =>
objectSpread({}, reward, {
nominators: reward.nominating.filter((n) => reward.validators[n.validatorId])
})
);
}
export function _stakerRewardsEras (instanceId: string, api: DeriveApi): (eras: EraIndex[], withActive?: boolean) => Observable<ErasResult> {
+18 -18
View File
@@ -20,29 +20,29 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/api-augment": "8.13.1",
"@polkadot/api-base": "8.13.1",
"@polkadot/api-derive": "8.13.1",
"@polkadot/keyring": "^10.0.2",
"@polkadot/rpc-augment": "8.13.1",
"@polkadot/rpc-core": "8.13.1",
"@polkadot/rpc-provider": "8.13.1",
"@polkadot/types": "8.13.1",
"@polkadot/types-augment": "8.13.1",
"@polkadot/types-codec": "8.13.1",
"@polkadot/types-create": "8.13.1",
"@polkadot/types-known": "8.13.1",
"@polkadot/util": "^10.0.2",
"@polkadot/util-crypto": "^10.0.2",
"@babel/runtime": "^7.18.9",
"@polkadot/api-augment": "9.0.1",
"@polkadot/api-base": "9.0.1",
"@polkadot/api-derive": "9.0.1",
"@polkadot/keyring": "^10.1.2",
"@polkadot/rpc-augment": "9.0.1",
"@polkadot/rpc-core": "9.0.1",
"@polkadot/rpc-provider": "9.0.1",
"@polkadot/types": "9.0.1",
"@polkadot/types-augment": "9.0.1",
"@polkadot/types-codec": "9.0.1",
"@polkadot/types-create": "9.0.1",
"@polkadot/types-known": "9.0.1",
"@polkadot/util": "^10.1.2",
"@polkadot/util-crypto": "^10.1.2",
"eventemitter3": "^4.0.7",
"rxjs": "^7.5.6"
},
"devDependencies": {
"@polkadot/api-augment": "8.13.1",
"@polkadot/types-support": "8.13.1"
"@polkadot/api-augment": "9.0.1",
"@polkadot/types-support": "9.0.1"
}
}
+13 -21
View File
@@ -4,7 +4,7 @@
import type { Observable } from 'rxjs';
import type { AugmentedCall, DeriveCustom, QueryableCalls } from '@polkadot/api-base/types';
import type { RpcInterface } from '@polkadot/rpc-core/types';
import type { Option, Raw, StorageKey, Text, u64 } from '@polkadot/types';
import type { StorageKey, Text, u64 } from '@polkadot/types';
import type { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import type { DecoratedMeta } from '@polkadot/types/metadata/decorate/types';
import type { StorageEntry } from '@polkadot/types/primitive/types';
@@ -19,7 +19,7 @@ import { BehaviorSubject, combineLatest, from, map, of, switchMap, tap, toArray
import { getAvailableDerives } from '@polkadot/api-derive';
import { memo, RpcCore } from '@polkadot/rpc-core';
import { WsProvider } from '@polkadot/rpc-provider';
import { expandMetadata, Metadata, typeDefinitions, TypeRegistry, unwrapStorageType } from '@polkadot/types';
import { expandMetadata, Metadata, typeDefinitions, TypeRegistry } from '@polkadot/types';
import { getSpecRuntime } from '@polkadot/types-known';
import { arrayChunk, arrayFlatten, assertReturn, BN, compactStripLength, lazyMethod, lazyMethods, logger, nextTick, objectSpread, stringCamelCase, stringUpperFirst, u8aConcatStrict, u8aToHex } from '@polkadot/util';
import { blake2AsHex } from '@polkadot/util-crypto';
@@ -108,6 +108,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
protected _runtimeVersion?: RuntimeVersion;
protected _rx: ApiInterfaceRx = {
call: {} as QueryableCalls<'rxjs'>,
consts: {} as QueryableConsts<'rxjs'>,
query: {} as QueryableStorage<'rxjs'>,
tx: {} as SubmittableExtrinsics<'rxjs'>
@@ -220,6 +221,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
query: {},
registry,
rx: {
call: {},
query: {}
},
tx: createSubmittable(this._type, this._rx, this._decorateMethod, registry, blockHash)
@@ -236,8 +238,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
}
const runtime = this._decorateCalls(registry, this._decorateMethod, blockHash);
const runtimeRx = this._decorateCalls<'rxjs'>(registry, this._rxDecorateMethod, blockHash);
const storage = this._decorateStorage(registry.decoratedMeta, this._decorateMethod, blockHash);
const storageRx = this._decorateStorage(registry.decoratedMeta, this._rxDecorateMethod, blockHash);
const storageRx = this._decorateStorage<'rxjs'>(registry.decoratedMeta, this._rxDecorateMethod, blockHash);
augmentObject('consts', registry.decoratedMeta.consts, decoratedApi.consts, fromEmpty);
augmentObject('errors', registry.decoratedMeta.errors, decoratedApi.errors, fromEmpty);
@@ -245,6 +248,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
augmentObject('query', storage, decoratedApi.query, fromEmpty);
augmentObject('query', storageRx, decoratedApi.rx.query, fromEmpty);
augmentObject('call', runtime, decoratedApi.call, fromEmpty);
augmentObject('call', runtimeRx, decoratedApi.rx.call, fromEmpty);
decoratedApi.findCall = (callIndex: Uint8Array | string): CallFunction =>
findCall(registry.registry, callIndex);
@@ -274,6 +278,8 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
this._errors = decoratedApi.errors;
this._events = decoratedApi.events;
this._query = decoratedApi.query;
this._rx.call = decoratedApi.rx.call;
this._rx.query = decoratedApi.rx.query;
const tx = this._decorateExtrinsics(decoratedMeta, this._decorateMethod);
@@ -488,7 +494,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
}
// pre-metadata decoration
protected _decorateCalls<ApiType extends ApiTypes> ({ registry, runtimeVersion: { apis, specName } }: VersionedRegistry<ApiType>, decorateMethod: DecorateMethod<ApiType>, blockHash?: Uint8Array | string | null): QueryableCalls<ApiType> {
protected _decorateCalls<ApiType extends ApiTypes> ({ registry, runtimeVersion: { apis, specName } }: VersionedRegistry<any>, decorateMethod: DecorateMethod<ApiType>, blockHash?: Uint8Array | string | null): QueryableCalls<ApiType> {
const result = {} as QueryableCalls<ApiType>;
const named: Record<string, Record<string, DefinitionCallNamed>> = {};
const hashes: Record<HexString, boolean> = {};
@@ -626,7 +632,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const lazySection = (section: string) =>
lazyMethods({}, Object.keys(tx[section]), (method: string) =>
this._decorateExtrinsicEntry(tx[section][method], result)
method.startsWith('$')
? tx[section][method]
: this._decorateExtrinsicEntry(tx[section][method], result)
);
const sections = Object.keys(tx);
@@ -701,9 +709,6 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
decorated.keyPrefix = (...args: unknown[]): string =>
u8aToHex(creator.keyPrefix(...args));
decorated.range = decorateMethod((range: [Hash, Hash?], ...args: unknown[]): Observable<[Hash, Codec][]> =>
this._decorateStorageRange(decorated, args, range));
decorated.size = decorateMethod((...args: unknown[]): Observable<u64> =>
this._rpcCore.state.getStorageSize(getArgs(args)));
@@ -877,19 +882,6 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
});
}
private _decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: unknown[], range: [Hash, Hash?]): Observable<[Hash, Codec][]> {
const outputType = unwrapStorageType(this.#registry, decorated.creator.meta.type, decorated.creator.meta.modifier.isOptional);
return this._rpcCore.state
.queryStorage<[Option<Raw>]>([decorated.key(...args)], ...range)
.pipe(map((result: [Hash, [Option<Raw>]][]): [Hash, Codec][] =>
result.map(([blockHash, [value]]) => [
blockHash,
this.createType<Codec>(outputType, value.isSome ? value.unwrap().toHex() : undefined)
])
));
}
// retrieve a set of values for a specific set of keys - here we chunk the keys into PAGE_SIZE sizes
private _retrieveMulti (keys: [StorageEntry, unknown[]][], blockHash?: Uint8Array): Observable<Codec[]> {
if (!keys.length) {
+2 -2
View File
@@ -194,8 +194,8 @@ export abstract class Getters<ApiType extends ApiTypes> extends Init<ApiType> im
/**
* @description The underlying Rx API interface
*/
public get rx (): Pick<ApiInterfaceRx, 'tx' | 'rpc' | 'query'> {
return assertResult(this._rx as Pick<ApiInterfaceRx, 'tx' | 'rpc' | 'query'>);
public get rx (): Pick<ApiInterfaceRx, 'tx' | 'rpc' | 'query' | 'call'> {
return assertResult(this._rx as Pick<ApiInterfaceRx, 'tx' | 'rpc' | 'query' | 'call'>);
}
/**
+2 -10
View File
@@ -125,7 +125,7 @@ async function query (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
console.log('query types:', bar, bal, bal2, override, oldBal, multia, multib);
}
async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
async function queryExtra (api: ApiPromise): Promise<void> {
// events destructing
await api.query.system.events((records): void => {
records.forEach(({ event, phase }): void => {
@@ -155,14 +155,6 @@ async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise<void
await api.query.assets.account.entries(123);
await api.query.assets.blah.keys();
// check range
await api.query.balances.freeBalance.range<Balance>(['0x1234'], pairs.bob.address);
// 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`).join(', ')}`);
// is
const key = {} as StorageKey;
@@ -313,7 +305,7 @@ async function main (): Promise<void> {
errors(api),
events(api),
query(api, pairs),
queryExtra(api, pairs),
queryExtra(api),
queryMulti(api, pairs),
rpc(api),
types(api),
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/api', path: 'auto', type: 'auto', version: '9.0.1' };
+2 -12
View File
@@ -5,7 +5,7 @@
import type { Observable } from 'rxjs';
import type { Address, ApplyExtrinsicResult, Call, Extrinsic, ExtrinsicEra, ExtrinsicStatus, Hash, Header, Index, RuntimeDispatchInfo, SignerPayload } from '@polkadot/types/interfaces';
import type { Callback, Codec, Constructor, IKeyringPair, ISubmittableResult, SignatureOptions } from '@polkadot/types/types';
import type { Callback, Codec, Constructor, ISubmittableResult, SignatureOptions } from '@polkadot/types/types';
import type { Registry } from '@polkadot/types-codec/types';
import type { ApiInterfaceRx, ApiTypes, PromiseOrObs, SignerResult } from '../types';
import type { AddressOrPair, SignerOptions, SubmittableDryRunResult, SubmittableExtrinsic, SubmittablePaymentResult, SubmittableResultResult, SubmittableResultSubscription } from './types';
@@ -170,17 +170,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, blockHas
}
/**
* @description Sign a transaction, returning the this to allow chaining, i.e. .sign(...).send(). When options, e.g. nonce/blockHash are not specified, it will be inferred. To retrieve eg. nonce use `signAsync` (the preferred interface, this is provided for backwards compatibility)
* @deprecated
*/
public override sign (account: IKeyringPair, partialOptions?: Partial<SignerOptions>): this {
super.sign(account, makeSignOptions(api, optionsOrNonce(partialOptions), {}));
return this;
}
/**
* @description Signs a transaction, returning `this` to allow chaining. E.g.: `sign(...).send()`. Like `.signAndSend` this will retrieve the nonce and blockHash to send the tx with.
* @description Signs a transaction, returning `this` to allow chaining. E.g.: `signAsync(...).send()`. Like `.signAndSend` this will retrieve the nonce and blockHash to send the tx with.
*/
public signAsync (account: AddressOrPair, partialOptions?: Partial<SignerOptions>): PromiseOrObs<ApiType, this> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
+2 -5
View File
@@ -5,7 +5,7 @@ import type { Signer, SignerResult } from '@polkadot/api/types';
import type { KeyringPair } from '@polkadot/keyring/types';
import type { Registry, SignerPayloadJSON, SignerPayloadRaw } from '@polkadot/types/types';
import { hexToU8a, u8aToHex } from '@polkadot/util';
import { hexToU8a, objectSpread, u8aToHex } from '@polkadot/util';
let id = 0;
@@ -31,10 +31,7 @@ export class SingleAccountSigner implements Signer {
setTimeout((): void => {
const signed = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.#keyringPair);
resolve({
id: ++id,
...signed
});
resolve(objectSpread({ id: ++id }, signed));
}, this.#signDelay);
});
}
+1
View File
@@ -104,6 +104,7 @@ export interface ApiDecoration<ApiType extends ApiTypes> {
registry: Registry;
runtimeVersion: RuntimeVersionPartial;
rx: {
call: QueryableCalls<'rxjs'>;
query: QueryableStorage<'rxjs'>;
};
tx: (extrinsic: Call | Extrinsic | Uint8Array | string) => SubmittableExtrinsic<ApiType>;
+10 -23
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2022 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { lazyMethod, logger, objectClear } from '@polkadot/util';
import { lazyMethods, logger, objectClear } from '@polkadot/util';
type Sections <T> = Record<string, Methods<T>>;
@@ -58,11 +58,13 @@ function findMethodExcludes <T> (src: Sections<T>, dst: Sections<T>): string[] {
const srcMethods = Object.keys(src[section]);
const dstMethods = Object.keys(dst[section]);
excludes.push(
...dstMethods
.filter((m) => !srcMethods.includes(m))
.map((m) => `${section}.${m}`)
);
for (let d = 0; d < dstMethods.length; d++) {
const method = dstMethods[d];
if (!srcMethods.includes(method)) {
excludes.push(`${section}.${method}`);
}
}
}
return excludes;
@@ -75,22 +77,6 @@ function extractMethods <T> (src: Sections<T>, dst: Sections<T>): StringsStrings
];
}
function lazySection <T> (src: Methods<T>, dst: Methods<T>): void {
const creator = (m: string) => src[m];
const methods = Object.keys(src);
for (let i = 0; i < methods.length; i++) {
const method = methods[i];
// We use hasOwnproperty here to only check for the existence of the key,
// instead of reading dst[section][method] which will evaluate when already
// set as a lazy value previously
if (!Object.prototype.hasOwnProperty.call(dst, method)) {
lazyMethod(dst, method, creator);
}
}
}
/**
* @description Takes a decorated api section (e.g. api.tx) and augment it with the details. It does not override what is
* already available, but rather just adds new missing items into the result object.
@@ -111,6 +97,7 @@ export function augmentObject <T> (prefix: string | null, src: Sections<T>, dst:
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
const methods = src[section];
// We don't set here with a lazy interface, we decorate based
// on the top-level structure (this bypasses adding lazy onto lazy)
@@ -118,7 +105,7 @@ export function augmentObject <T> (prefix: string | null, src: Sections<T>, dst:
dst[section] = {};
}
lazySection(src[section], dst[section]);
lazyMethods(dst[section], Object.keys(methods), (m: string) => methods[m]);
}
return dst;
+6 -6
View File
@@ -20,13 +20,13 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/rpc-core": "8.13.1",
"@polkadot/types": "8.13.1",
"@polkadot/types-codec": "8.13.1",
"@polkadot/util": "^10.0.2"
"@babel/runtime": "^7.18.9",
"@polkadot/rpc-core": "9.0.1",
"@polkadot/types": "9.0.1",
"@polkadot/types-codec": "9.0.1",
"@polkadot/util": "^10.1.2"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/rpc-augment', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/rpc-augment', path: 'auto', type: 'auto', version: '9.0.1' };
+8 -8
View File
@@ -20,18 +20,18 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/rpc-augment": "8.13.1",
"@polkadot/rpc-provider": "8.13.1",
"@polkadot/types": "8.13.1",
"@polkadot/util": "^10.0.2",
"@babel/runtime": "^7.18.9",
"@polkadot/rpc-augment": "9.0.1",
"@polkadot/rpc-provider": "9.0.1",
"@polkadot/types": "9.0.1",
"@polkadot/util": "^10.1.2",
"rxjs": "^7.5.6"
},
"devDependencies": {
"@polkadot/keyring": "^10.0.2",
"@polkadot/rpc-augment": "8.13.1"
"@polkadot/keyring": "^10.1.2",
"@polkadot/rpc-augment": "9.0.1"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/rpc-core', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/rpc-core', path: 'auto', type: 'auto', version: '9.0.1' };
+12 -12
View File
@@ -20,21 +20,21 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/keyring": "^10.0.2",
"@polkadot/types": "8.13.1",
"@polkadot/types-support": "8.13.1",
"@polkadot/util": "^10.0.2",
"@polkadot/util-crypto": "^10.0.2",
"@polkadot/x-fetch": "^10.0.2",
"@polkadot/x-global": "^10.0.2",
"@polkadot/x-ws": "^10.0.2",
"@substrate/connect": "0.7.8",
"@babel/runtime": "^7.18.9",
"@polkadot/keyring": "^10.1.2",
"@polkadot/types": "9.0.1",
"@polkadot/types-support": "9.0.1",
"@polkadot/util": "^10.1.2",
"@polkadot/util-crypto": "^10.1.2",
"@polkadot/x-fetch": "^10.1.2",
"@polkadot/x-global": "^10.1.2",
"@polkadot/x-ws": "^10.1.2",
"@substrate/connect": "0.7.9",
"eventemitter3": "^4.0.7",
"mock-socket": "^9.1.5",
"nock": "^13.2.8"
"nock": "^13.2.9"
}
}
+1 -3
View File
@@ -4,6 +4,4 @@
export { HttpProvider } from './http';
export { packageInfo } from './packageInfo';
export { WsProvider } from './ws';
// ESM-only, only export top-level when we have dual versions
// export { ScProvider } from './substrate-connect';
export { ScProvider } from './substrate-connect';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/rpc-provider', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/rpc-provider', path: 'auto', type: 'auto', version: '9.0.1' };
+16 -16
View File
@@ -20,7 +20,7 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"bin": {
"polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.cjs",
@@ -30,21 +30,21 @@
"polkadot-types-internal-metadata": "./scripts/polkadot-types-internal-metadata.cjs"
},
"dependencies": {
"@babel/core": "^7.18.6",
"@babel/register": "^7.18.6",
"@babel/runtime": "^7.18.6",
"@polkadot/api": "8.13.1",
"@polkadot/api-augment": "8.13.1",
"@polkadot/rpc-augment": "8.13.1",
"@polkadot/rpc-provider": "8.13.1",
"@polkadot/types": "8.13.1",
"@polkadot/types-augment": "8.13.1",
"@polkadot/types-codec": "8.13.1",
"@polkadot/types-create": "8.13.1",
"@polkadot/types-support": "8.13.1",
"@polkadot/util": "^10.0.2",
"@polkadot/util-crypto": "^10.0.2",
"@polkadot/x-ws": "^10.0.2",
"@babel/core": "^7.18.9",
"@babel/register": "^7.18.9",
"@babel/runtime": "^7.18.9",
"@polkadot/api": "9.0.1",
"@polkadot/api-augment": "9.0.1",
"@polkadot/rpc-augment": "9.0.1",
"@polkadot/rpc-provider": "9.0.1",
"@polkadot/types": "9.0.1",
"@polkadot/types-augment": "9.0.1",
"@polkadot/types-codec": "9.0.1",
"@polkadot/types-create": "9.0.1",
"@polkadot/types-support": "9.0.1",
"@polkadot/util": "^10.1.2",
"@polkadot/util-crypto": "^10.1.2",
"@polkadot/x-ws": "^10.1.2",
"handlebars": "^4.7.7",
"websocket": "^1.0.34",
"yargs": "^17.5.1"
+3 -5
View File
@@ -105,12 +105,12 @@ function tsNull (registry: Registry, definitions: Record<string, ModuleTypes>, {
}
/** @internal */
function tsResultGetter (registry: Registry, definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Err' | 'Error', def: TypeDef, imports: TypeImports): string {
function tsResultGetter (registry: Registry, definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Err', def: TypeDef, imports: TypeImports): string {
const { info, lookupName, type } = def;
const asGetter = type === 'Null'
? ''
: (getter === 'Error' ? ' /** @deprecated Use asErr */\n' : '') + createGetter(definitions, `as${getter}`, lookupName || (info === TypeDefInfo.Tuple ? formatType(registry, definitions, def, imports, false) : type), imports);
const isGetter = (getter === 'Error' ? ' /** @deprecated Use isErr */\n' : '') + createGetter(definitions, `is${getter}`, 'boolean', imports);
: createGetter(definitions, `as${getter}`, lookupName || (info === TypeDefInfo.Tuple ? formatType(registry, definitions, def, imports, false) : type), imports);
const isGetter = createGetter(definitions, `is${getter}`, 'boolean', imports);
switch (info) {
case TypeDefInfo.Option:
@@ -137,8 +137,6 @@ function tsResult (registry: Registry, definitions: Record<string, ModuleTypes>,
const [okDef, errorDef] = (def.sub as TypeDef[]);
const inner = [
tsResultGetter(registry, definitions, def.name, 'Err', errorDef, imports),
// @deprecated, use Err
tsResultGetter(registry, definitions, def.name, 'Error', errorDef, imports),
tsResultGetter(registry, definitions, def.name, 'Ok', okDef, imports)
].join('');
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/typegen', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/typegen', path: 'auto', type: 'auto', version: '9.0.1' };
+5 -5
View File
@@ -20,12 +20,12 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/types": "8.13.1",
"@polkadot/types-codec": "8.13.1",
"@polkadot/util": "^10.0.2"
"@babel/runtime": "^7.18.9",
"@polkadot/types": "9.0.1",
"@polkadot/types-codec": "9.0.1",
"@polkadot/util": "^10.1.2"
}
}
@@ -1571,6 +1571,7 @@ export default {
poolId: 'u32',
balance: 'u128',
points: 'u128',
era: 'u32',
},
Withdrawn: {
member: 'AccountId32',
@@ -4142,7 +4143,7 @@ export default {
* Lookup436: pallet_staking::Releases
**/
PalletStakingReleases: {
_enum: ['V1_0_0Ancient', 'V2_0_0', 'V3_0_0', 'V4_0_0', 'V5_0_0', 'V6_0_0', 'V7_0_0', 'V8_0_0', 'V9_0_0']
_enum: ['V1_0_0Ancient', 'V2_0_0', 'V3_0_0', 'V4_0_0', 'V5_0_0', 'V6_0_0', 'V7_0_0', 'V8_0_0', 'V9_0_0', 'V10_0_0']
},
/**
* Lookup437: pallet_staking::pallet::pallet::Error<T>
@@ -5125,7 +5126,7 @@ export default {
* Lookup638: pallet_alliance::pallet::Error<T, I>
**/
PalletAllianceError: {
_enum: ['MembersAlreadyInitialized', 'AlreadyMember', 'NotMember', 'NotAlly', 'NotFounder', 'UpForKicking', 'NoVotingRights', 'AlreadyElevated', 'AlreadyUnscrupulous', 'AccountNonGrata', 'NotListedAsUnscrupulous', 'TooManyUnscrupulousItems', 'TooLongWebsiteUrl', 'InsufficientFunds', 'WithoutIdentityDisplayAndWebsite', 'WithoutGoodIdentityJudgement', 'MissingProposalHash', 'NotVetoableProposal', 'MissingAnnouncement', 'TooManyMembers', 'TooManyAnnouncements']
_enum: ['AllianceAlreadyInitialized', 'AllianceNotYetInitialized', 'AlreadyMember', 'NotMember', 'NotAlly', 'NotFounder', 'UpForKicking', 'NoVotingRights', 'AlreadyElevated', 'AlreadyUnscrupulous', 'AccountNonGrata', 'NotListedAsUnscrupulous', 'TooManyUnscrupulousItems', 'TooLongWebsiteUrl', 'InsufficientFunds', 'WithoutIdentityDisplayAndWebsite', 'WithoutGoodIdentityJudgement', 'MissingProposalHash', 'NotVetoableProposal', 'MissingAnnouncement', 'TooManyMembers', 'TooManyAnnouncements']
},
/**
* Lookup639: pallet_nomination_pools::PoolMember<T>
@@ -1741,6 +1741,7 @@ declare module '@polkadot/types/lookup' {
readonly poolId: u32;
readonly balance: u128;
readonly points: u128;
readonly era: u32;
} & Struct;
readonly isWithdrawn: boolean;
readonly asWithdrawn: {
@@ -4451,7 +4452,8 @@ declare module '@polkadot/types/lookup' {
readonly isV700: boolean;
readonly isV800: boolean;
readonly isV900: boolean;
readonly type: 'V100Ancient' | 'V200' | 'V300' | 'V400' | 'V500' | 'V600' | 'V700' | 'V800' | 'V900';
readonly isV1000: boolean;
readonly type: 'V100Ancient' | 'V200' | 'V300' | 'V400' | 'V500' | 'V600' | 'V700' | 'V800' | 'V900' | 'V1000';
}
/** @name PalletStakingPalletError (437) */
@@ -5686,7 +5688,8 @@ declare module '@polkadot/types/lookup' {
/** @name PalletAllianceError (638) */
interface PalletAllianceError extends Enum {
readonly isMembersAlreadyInitialized: boolean;
readonly isAllianceAlreadyInitialized: boolean;
readonly isAllianceNotYetInitialized: boolean;
readonly isAlreadyMember: boolean;
readonly isNotMember: boolean;
readonly isNotAlly: boolean;
@@ -5707,7 +5710,7 @@ declare module '@polkadot/types/lookup' {
readonly isMissingAnnouncement: boolean;
readonly isTooManyMembers: boolean;
readonly isTooManyAnnouncements: boolean;
readonly type: 'MembersAlreadyInitialized' | 'AlreadyMember' | 'NotMember' | 'NotAlly' | 'NotFounder' | 'UpForKicking' | 'NoVotingRights' | 'AlreadyElevated' | 'AlreadyUnscrupulous' | 'AccountNonGrata' | 'NotListedAsUnscrupulous' | 'TooManyUnscrupulousItems' | 'TooLongWebsiteUrl' | 'InsufficientFunds' | 'WithoutIdentityDisplayAndWebsite' | 'WithoutGoodIdentityJudgement' | 'MissingProposalHash' | 'NotVetoableProposal' | 'MissingAnnouncement' | 'TooManyMembers' | 'TooManyAnnouncements';
readonly type: 'AllianceAlreadyInitialized' | 'AllianceNotYetInitialized' | 'AlreadyMember' | 'NotMember' | 'NotAlly' | 'NotFounder' | 'UpForKicking' | 'NoVotingRights' | 'AlreadyElevated' | 'AlreadyUnscrupulous' | 'AccountNonGrata' | 'NotListedAsUnscrupulous' | 'TooManyUnscrupulousItems' | 'TooLongWebsiteUrl' | 'InsufficientFunds' | 'WithoutIdentityDisplayAndWebsite' | 'WithoutGoodIdentityJudgement' | 'MissingProposalHash' | 'NotVetoableProposal' | 'MissingAnnouncement' | 'TooManyMembers' | 'TooManyAnnouncements';
}
/** @name PalletNominationPoolsPoolMember (639) */
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/types-augment', path: 'auto', type: 'auto', version: '8.13.1' };
export const packageInfo = { name: '@polkadot/types-augment', path: 'auto', type: 'auto', version: '9.0.1' };
+8 -8
View File
@@ -20,17 +20,17 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.13.1",
"version": "9.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.6",
"@polkadot/util": "^10.0.2",
"@polkadot/x-bigint": "^10.0.2"
"@babel/runtime": "^7.18.9",
"@polkadot/util": "^10.1.2",
"@polkadot/x-bigint": "^10.1.2"
},
"devDependencies": {
"@polkadot/types": "8.13.1",
"@polkadot/types-augment": "8.13.1",
"@polkadot/types-support": "8.13.1",
"@polkadot/util-crypto": "^10.0.2"
"@polkadot/types": "9.0.1",
"@polkadot/types-augment": "9.0.1",
"@polkadot/types-support": "9.0.1",
"@polkadot/util-crypto": "^10.1.2"
}
}
@@ -140,6 +140,19 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
return result;
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): AnyJson {
const result = new Array<AnyJson>(this.length);
for (let i = 0; i < this.length; i++) {
result[i] = this[i] && this[i].toPrimitive();
}
return result;
}
/**
* @description Returns the base runtime type name for this instance
*/
@@ -83,6 +83,13 @@ export abstract class AbstractBase<T extends Codec> implements Codec {
return this.#raw.toJSON();
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): AnyJson {
return this.#raw.toPrimitive();
}
/**
* @description Returns the string representation of the value
*/
+9
View File
@@ -207,6 +207,15 @@ export abstract class AbstractInt extends BN implements INumber {
: this.toNumber();
}
/**
* @description Returns the value in a primitive form, either number when <= 52 bits, or string otherwise
*/
public toPrimitive (): number | string {
return super.bitLength() > MAX_NUMBER_BITS
? this.toString()
: this.toNumber();
}
/**
* @description Returns the base runtime type name for this instance
*/
+7
View File
@@ -171,6 +171,13 @@ export class Compact<T extends INumber> implements ICompact<T> {
return this.#raw.toNumber();
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): string | number {
return this.#raw.toPrimitive();
}
/**
* @description Returns the base runtime type name for this instance
*/
@@ -72,6 +72,10 @@ export class DoNotConstruct implements Codec {
throw this.#neverError;
}
toPrimitive (): AnyJson {
throw this.#neverError;
}
toRawType (): string {
throw this.#neverError;
}
+8 -5
View File
@@ -117,13 +117,16 @@ describe('Enum', (): void => {
it('has correct isXyz/asXyz (Enum.with)', (): void => {
const test = new (Enum.with({ First: Text, Second: U32, Third: U32 }))(registry, { Second: 42 }) as any as { isFirst: boolean; isSecond: boolean; asSecond: U32; isThird: boolean; asThird: never };
const asKeys = Object.keys(test).filter((k) => k.startsWith('as'));
const isKeys = Object.keys(test).filter((k) => k.startsWith('is'));
expect(asKeys).toEqual(['asFirst', 'asSecond', 'asThird']);
expect(isKeys).toEqual(['isFirst', 'isSecond', 'isThird']);
// const asKeys = Object.keys(test).filter((k) => k.startsWith('as'));
// const isKeys = Object.keys(test).filter((k) => k.startsWith('is'));
// expect([isKeys, asKeys]).toEqual([
// ['isFirst', 'isSecond', 'isThird'],
// ['asFirst', 'asSecond', 'asThird']
// ]);
expect([test.isFirst, test.isSecond, test.isThird]).toEqual([false, true, false]);
expect(test.asSecond.toNumber()).toEqual(42);
expect((): never => test.asThird).toThrow(/Cannot convert 'Second' via asThird/);
});
+34 -28
View File
@@ -223,19 +223,6 @@ export class Enum implements IEnum {
}
public static with (Types: Record<string, string | CodecClass> | Record<string, number> | string[]): EnumCodecClass<Enum> {
const keys = Array.isArray(Types)
? Types
: Object.keys(Types);
const asKeys = new Array<string>(keys.length);
const isKeys = new Array<string>(keys.length);
for (let i = 0; i < keys.length; i++) {
const name = stringPascalCase(keys[i]);
asKeys[i] = `as${name}`;
isKeys[i] = `is${name}`;
}
let definition: Definition | undefined;
// eslint-disable-next-line no-return-assign
@@ -243,18 +230,36 @@ export class Enum implements IEnum {
definition = d;
return class extends Enum {
constructor (registry: Registry, value?: unknown, index?: number) {
super(registry, Types, value, index, { definition, setDefinition });
static {
const keys = Array.isArray(Types)
? Types
: Object.keys(Types);
const asKeys = new Array<string>(keys.length);
const isKeys = new Array<string>(keys.length);
objectProperties(this, isKeys, (_, i) => this.type === keys[i]);
objectProperties(this, asKeys, (k, i): Codec => {
if (!this[isKeys[i] as keyof this]) {
throw new Error(`Cannot convert '${this.type}' via ${k}`);
for (let i = 0; i < keys.length; i++) {
const name = stringPascalCase(keys[i]);
asKeys[i] = `as${name}`;
isKeys[i] = `is${name}`;
}
objectProperties(this.prototype, isKeys, (_: string, i: number, self: Enum) =>
self.type === keys[i]
);
objectProperties(this.prototype, asKeys, (k: string, i: number, self: Enum): Codec => {
if (self.type !== keys[i]) {
throw new Error(`Cannot convert '${self.type}' via ${k}`);
}
return this.value;
return self.value;
});
}
constructor (registry: Registry, value?: unknown, index?: number) {
super(registry, Types, value, index, { definition, setDefinition });
}
};
}
@@ -307,14 +312,6 @@ export class Enum implements IEnum {
return this.#raw instanceof Null;
}
/**
* @description Checks if the Enum points to a [[Null]] type
* @deprecated use isNone
*/
public get isNull (): boolean {
return this.isNone;
}
/**
* @description The available keys for this enum
*/
@@ -414,6 +411,15 @@ export class Enum implements IEnum {
return this.index;
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): AnyJson {
return this.#isBasic
? this.type
: { [stringCamelCase(this.type)]: this.#raw.toPrimitive() };
}
/**
* @description Returns a raw struct representation of the enum types
*/
+7
View File
@@ -69,6 +69,13 @@ export class Null implements Codec {
return null;
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): null {
return null;
}
/**
* @description Returns the base runtime type name for this instance
*/
+9
View File
@@ -206,6 +206,15 @@ export class Option<T extends Codec> implements IOption<T> {
: this.#raw.toJSON();
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): AnyJson {
return this.isNone
? null
: this.#raw.toPrimitive();
}
/**
* @description Returns the base runtime type name for this instance
*/
@@ -39,9 +39,7 @@ describe('Result', (): void => {
const result = new Type(registry, { Err: 'error' });
expect(result.isErr).toBe(true);
expect(result.isError).toBe(true);
expect(result.asErr.toString()).toEqual('error');
expect(result.asError.toString()).toEqual('error');
expect(result.toHex()).toEqual('0x01146572726f72');
});
-14
View File
@@ -36,13 +36,6 @@ export class Result<O extends Codec, E extends Codec> extends Enum implements IR
return this.value as E;
}
/**
* @deprecated Use asErr
*/
public get asError (): E {
return this.asErr;
}
/**
* @description Returns the wrapper Ok value (if isOk)
*/
@@ -68,13 +61,6 @@ export class Result<O extends Codec, E extends Codec> extends Enum implements IR
return !this.isOk;
}
/**
* @deprecated Use isErr
*/
public get isError (): boolean {
return this.isErr;
}
/**
* @description Checks if the Result wraps an Ok value
*/
@@ -193,6 +193,19 @@ export class BTreeSet<V extends Codec = Codec> extends Set<V> implements ISet<V>
return `BTreeSet<${this.registry.getClassName(this.#ValClass) || new this.#ValClass(this.registry).toRawType()}>`;
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): AnyJson {
const json: AnyJson = [];
for (const v of this.values()) {
json.push(v.toPrimitive());
}
return json;
}
/**
* @description Returns the string representation of the value
*/
+23 -1
View File
@@ -8,6 +8,7 @@ import { compactFromU8aLim, compactToU8a, isHex, isObject, isU8a, logger, string
import { AbstractArray } from '../abstract/Array';
import { Enum } from '../base/Enum';
import { Raw } from '../native/Raw';
import { Struct } from '../native/Struct';
import { compareMap, decodeU8a, sortMap, typeToConstructor } from '../utils';
@@ -182,7 +183,11 @@ export class CodecMap<K extends Codec = Codec, V extends Codec = Codec> extends
const json: Record<string, AnyJson> = {};
for (const [k, v] of this.entries()) {
json[k.toString()] = v.toHuman(isExtended);
json[
k instanceof Raw && k.isAscii
? k.toUtf8()
: k.toString()
] = v.toHuman(isExtended);
}
return json;
@@ -201,6 +206,23 @@ export class CodecMap<K extends Codec = Codec, V extends Codec = Codec> extends
return json;
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): AnyJson {
const json: Record<string, AnyJson> = {};
for (const [k, v] of this.entries()) {
json[
k instanceof Raw && k.isAscii
? k.toUtf8()
: k.toString()
] = v.toPrimitive();
}
return json;
}
/**
* @description Returns the base runtime type name for this instance
*/
@@ -92,6 +92,15 @@ export class WrapperKeepOpaque<T extends Codec> extends Bytes {
: super.toHuman();
}
/**
* @description Converts the value in a best-fit primitive form
*/
public override toPrimitive (): any {
return this.#decoded
? this.#decoded.toPrimitive()
: super.toPrimitive();
}
/**
* @description Returns the base runtime type name for this instance
*/
+7
View File
@@ -105,6 +105,13 @@ export class bool extends Boolean implements Codec {
return this.valueOf();
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): boolean {
return this.toJSON();
}
/**
* @description Returns the base runtime type name for this instance
*/
+7
View File
@@ -136,6 +136,13 @@ export class CodecDate extends Date implements INumber {
return Math.ceil(this.getTime() / 1000);
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): number {
return this.toNumber();
}
/**
* @description Returns the base runtime type name for this instance
*/
+7
View File
@@ -112,6 +112,13 @@ export class Float extends Number implements IFloat {
return this.valueOf();
}
/**
* @description Converts the value in a best-fit primitive form
*/
public toPrimitive (): number {
return this.toNumber();
}
/**
* @description Returns the base runtime type name for this instance
*/

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