Compare commits

..
209 Commits
Author SHA1 Message Date
Github Actions f6490217ec [CI Skip] 1.1.1
skip-checks: true
2020-02-06 15:12:35 +00:00
Jaco Greeff 601cc62d70 1.1 (#1815) 2020-02-06 16:05:04 +01:00
Github Actions 201480be56 [CI Skip] 1.1.0-beta.22
skip-checks: true
2020-02-06 14:17:09 +00:00
Jaco Greeff 519823bc0e Add resolver for jest (#1813) 2020-02-06 15:09:36 +01:00
Github Actions 0b134c1eb8 [CI Skip] 1.1.0-beta.21
skip-checks: true
2020-02-06 13:16:34 +00:00
Jaco Greeff e6e96aa9c9 Make indices module optional (#1812)
* Make indices optional

* Updtae contracts with optional creation

* Flatten contract fees
2020-02-06 14:09:29 +01:00
Github Actions 84d0d8594e [CI Skip] 1.1.0-beta.20
skip-checks: true
2020-02-06 09:54:57 +00:00
Jaco Greeff 6be25966d8 Enum .toJSON() to return type name as specified (#1811)
* Enum `.toJSON()` to return type name as specified

* Fix text compares
2020-02-06 10:48:33 +01:00
Github Actions a5eb11e5f3 [CI Skip] 1.1.0-beta.19
skip-checks: true
2020-02-05 15:22:43 +00:00
Jaco Greeff 19f87aac4d Council memebrs with no election info (#1810) 2020-02-05 16:15:36 +01:00
Github Actions b217a59310 [CI Skip] 1.1.0-beta.18
skip-checks: true
2020-02-05 14:23:56 +00:00
Jaco Greeff 2de7a3c130 Add .keyPrefix for storage keys (#1809)
* Add .keyPrefix for storage keys

* Fix hex length
2020-02-05 15:15:49 +01:00
Github Actions deecf4853e [CI Skip] 1.1.0-beta.17
skip-checks: true
2020-02-04 15:19:57 +00:00
Jaco Greeff 8889e69341 Bump common (#1807)
* Bump common

* yarn.lock
2020-02-04 16:12:18 +01:00
Github Actions 14194a363e [CI Skip] 1.1.0-beta.16
skip-checks: true
2020-02-04 11:23:05 +00:00
Jaco Greeff 9c50e81ab9 Cleanup sanitize boxes (#1805)
* Cleanup sanitize boxes

* yarn.lock

* Add space before box as allowed
2020-02-04 12:16:18 +01:00
Jaco Greeff 6505e73355 Adjust submittable augmentation (#1806)
* Adjust submittable augmentation

* Add missing extends
2020-02-04 12:15:42 +01:00
Github Actions cefeb37ae6 [CI Skip] 1.1.0-beta.15
skip-checks: true
2020-02-03 16:32:53 +00:00
Jaco Greeff 9e29e89baf Update known extensions (with Polkadot) (#1800)
* Update known extensions (with Polkadot)

* Split definitions for signed extensions
2020-02-03 17:25:33 +01:00
Github Actions b82c90679d [CI Skip] 1.1.0-beta.14
skip-checks: true
2020-02-03 12:49:36 +00:00
Jaco Greeff eeb8d20e58 Bump common (detection) (#1799) 2020-02-03 13:42:49 +01:00
Github Actions b891edbd37 [CI Skip] 1.1.0-beta.13
skip-checks: true
2020-02-03 11:03:16 +00:00
Jaco Greeff 2ee3afcd61 Expand enum & struct defnitions, generator strict mode (#1798) 2020-02-03 11:56:06 +01:00
Github Actions 328630fb17 [CI Skip] 1.1.0-beta.12
skip-checks: true
2020-02-03 09:27:36 +00:00
Jaco Greeff 325080cf71 Cleanup some generation duplication (#1797)
* Cleanup some generation duplicaton

* Override for Metadata import

* Import order in generators
2020-02-03 10:20:33 +01:00
Github Actions 549a536328 [CI Skip] 1.1.0-beta.11
skip-checks: true
2020-02-02 19:26:52 +00:00
Jaco Greeff 23f41a0bab Exclude all augment from cc 2020-02-02 20:19:41 +01:00
Jaco Greeff 5e0c0ba91a Align jsonrpc augmentation with others (#1796) 2020-02-02 20:16:41 +01:00
Github Actions 812a077e63 [CI Skip] 1.1.0-beta.10
skip-checks: true
2020-02-02 18:54:18 +00:00
Jaco Greeff 6ba28c8ad2 Expand simple enums in type generation (#1795) 2020-02-02 19:47:19 +01:00
Github Actions 6cd0074ce4 [CI Skip] 1.1.0-beta.9
skip-checks: true
2020-02-02 18:24:56 +00:00
Jaco Greeff b3d592357f Override for Vote type (not a struct, not caught) (#1794)
* Override for Vote type (not a struct, not caught)

* Generate simple Vote object (first, Struct to be done)

* Comment for hex type (string)

* Expand conviction (like we should on enum)

* Cool, use conviction def for input

* aye is required

* Remove FIXMEs
2020-02-02 19:17:33 +01:00
Github Actions f499946f1f [CI Skip] 1.1.0-beta.8
skip-checks: true
2020-02-02 08:19:04 +00:00
Jaco Greeff 56e28bed7f Rename frozenFee (#1792) 2020-02-02 09:11:49 +01:00
Github Actions c76fb20a83 [CI Skip] 1.1.0-beta.7
skip-checks: true
2020-02-02 07:57:22 +00:00
Jaco Greeff 9d4b0ea56a Update Substrate with vesting (#1790)
* Update Substrate with vesting

* Update balances & vesting queries with compat)

* Split base account queries

* Linting, simpler referendum voters

* Fix (some) tests
2020-02-02 08:50:37 +01:00
Github Actions f9d569ddd1 [CI Skip] 1.1.0-beta.6
skip-checks: true
2020-02-01 20:27:44 +00:00
Jaco Greeff 7221a3637c Add UInt .isMax() (#1791)
* Add UInt .isMax()

* Filter lockedBlance by max
2020-02-01 21:20:48 +01:00
Github Actions 438c830366 [CI Skip] 1.1.0-beta.5
skip-checks: true
2020-02-01 17:47:00 +00:00
Jaco Greeff 3d0fd5a6a8 Warn on unknown extensions (once per registry) (#1788) 2020-02-01 18:40:45 +01:00
Github Actions de57876c7f [CI Skip] 1.1.0-beta.4
skip-checks: true
2020-02-01 13:24:47 +00:00
Jaco Greeff b24a1ff350 SignedExtension injection into payload (#1778)
* Make a start ... V11 definitions

* V11 conversion

* Fix ErrorMetadataV11

* Extension point for signed extensions

* Add V11 to mapped

* Expand toLatest comments

* Make a start at signer extension defs

* exports

* Extract extension definitions

* Add extension registration

* Remove old override

* Get definition on extrinsic creation

* Add missing V4 base

* Optional extrinsic

* Pull extrinsic version from metadata (if available)

* asLatest.extrinsic should now be available

* Don't export non-types for Extrinsic

* Setup registry with default extensions

* Async test really runs async

* Trace test failures (V1 orig, V4 now)

* CHANGELOG

* Add extension data to actual signature

* Cleanups

* Return cleanups

* Mark all type deocde static internal

* Apply extensions fully to payload

* Cleanup duplication

* ExtrinsicSignature* via createType
2020-02-01 14:17:17 +01:00
Github Actions 5f8c623179 [CI Skip] 1.1.0-beta.3
skip-checks: true
2020-02-01 11:07:19 +00:00
Jaco Greeff 00026a173f Keep original doc-line formats (#1787) 2020-02-01 11:59:47 +01:00
Github Actions 8da895efd4 [CI Skip] 1.1.0-beta.2
skip-checks: true
2020-02-01 10:23:48 +00:00
Jaco Greeff 89d029eca3 Expand bool & Enum generation (#1785)
* Expand bool & Enum generation

* Swap consts to Augmented (align with others)
2020-02-01 11:16:27 +01:00
Github Actions ac2a7eea67 [CI Skip] 1.1.0-beta.1
skip-checks: true
2020-01-31 21:42:23 +00:00
Jaco Greeff 4f0e573adf Cleanup to tx generation (#1784) 2020-01-31 22:34:24 +01:00
Github Actions 8417eff2b3 [CI Skip] 1.1.0-beta.0
skip-checks: true
2020-01-31 14:41:36 +00:00
Jaco Greeff 4aa5693906 Extend type generation (#1783)
* Cleanup type overrides

* Generate (with catch-all removal)

* Progress

* Re-gen tx types

* Remove unneeded option check

* Linting updates

* Update CHANGELOG (cleanups as per comments)
2020-01-31 15:34:06 +01:00
Jaco Greeff 982665c337 Update CHANGELOG with missing change (#1782) 2020-01-30 17:22:56 +01:00
Github Actions 6dce57b394 [CI Skip] 1.0.1
skip-checks: true
2020-01-30 16:06:14 +00:00
Jaco Greeff ca7edf1593 1.0 (#1781)
* 1.0

* signAsync typing

* Merge master
2020-01-30 16:59:04 +01:00
Jakub Pánik 59e069f091 Added unsubscribe return function to wsProvider.on() (#1780)
* Added unsubscribe return function to wsProvider.on()

* Updated mocks, added noop to http provider
2020-01-30 16:48:11 +01:00
Github Actions 65ff5c8f30 [CI Skip] 1.0.0-beta.44
skip-checks: true
2020-01-30 14:58:02 +00:00
Jaco Greeff 1c327c60d9 Metadata V11 (#1774)
* Make a start ... V11 definitions

* V11 conversion

* Fix ErrorMetadataV11

* Extension point for signed extensions

* Add V11 to mapped

* Expand toLatest comments
2020-01-30 15:49:37 +01:00
Github Actions de9f033d99 [CI Skip] 1.0.0-beta.43
skip-checks: true
2020-01-30 11:16:33 +00:00
Jaco Greeff 9c913fb482 Cleanup generated doc (only top-level docs) (#1777)
* Cleanup generated doc (only top-level docs)

* Single-line name
2020-01-30 12:09:16 +01:00
Github Actions e19e530c1c [CI Skip] 1.0.0-beta.42
skip-checks: true
2020-01-29 21:28:15 +00:00
Jaco Greeff aa91e0b8b5 Small gen doc updates (#1773) 2020-01-29 22:20:54 +01:00
Github Actions 9a6ba2fe0f [CI Skip] 1.0.0-beta.41
skip-checks: true
2020-01-29 17:33:29 +00:00
Jaco Greeff de853d9cc0 Add EVM types (#1771)
* Add EVM types

* Add findError for metadata
2020-01-29 18:26:06 +01:00
Github Actions 07063134b8 [CI Skip] 1.0.0-beta.40
skip-checks: true
2020-01-29 16:56:40 +00:00
Jaco Greeff 20b8cd762d Add sidebar doc link to TS user gen (#1770) 2020-01-29 17:49:40 +01:00
Github Actions bd3338c3df [CI Skip] 1.0.0-beta.39
skip-checks: true
2020-01-29 16:44:42 +00:00
Jaco Greeff 4c328964d5 Allow chain to use user-defined types (#1769)
* Allow chain to use user-defined types

* --package docs on chain extract
2020-01-29 17:37:19 +01:00
Github Actions 70e5e2b60a [CI Skip] 1.0.0-beta.38
skip-checks: true
2020-01-29 14:59:20 +00:00
Jaco Greeff 4329c0a411 Add polkadot-types-from-{chain,defs} (#1766)
* Add polkadot-types-from-{chain,defs}

* Generate scripts working

* User types generation docs

* Rebuild with new comment line
2020-01-29 15:51:23 +01:00
Github Actions 0713afa0e0 [CI Skip] 1.0.0-beta.37
skip-checks: true
2020-01-29 09:43:41 +00:00
Jaco Greeff 8b518a909b Bump deps (#1765) 2020-01-29 10:36:04 +01:00
Github Actions 794f1fe398 [CI Skip] 1.0.0-beta.36
skip-checks: true
2020-01-28 22:07:54 +00:00
Lae 51423e20b5 Make sure awaiting on an api object won't stuck forever on error (#1763)
* Make sure awaiting on an api object won't stuck forever when error occurs.

* Fix lint issues.
2020-01-28 23:01:07 +01:00
Github Actions d4b27ba670 [CI Skip] 1.0.0-beta.35
skip-checks: true
2020-01-28 21:52:49 +00:00
Jaco Greeff 8ca194a3d2 Cleanup society types (#1764)
* Cleanup society types

* Update types
2020-01-28 22:47:07 +01:00
Github Actions 5fd2c70924 [CI Skip] 1.0.0-beta.34
skip-checks: true
2020-01-28 21:03:11 +00:00
Jaco Greeff d36ee7de2f Add society hasDefender (#1762) 2020-01-28 21:55:55 +01:00
Github Actions 3683f9e5ff [CI Skip] 1.0.0-beta.33
skip-checks: true
2020-01-28 18:22:37 +00:00
Jaco Greeff 18c302d2cf Allow author extract from empty (#1761) 2020-01-28 19:16:08 +01:00
Github Actions 1686f8b357 [CI Skip] 1.0.0-beta.32
skip-checks: true
2020-01-28 17:58:51 +00:00
Jaco Greeff 15158b763c Bump common (#1760) 2020-01-28 18:51:17 +01:00
Github Actions f5f338a9ae [CI Skip] 1.0.0-beta.31
skip-checks: true
2020-01-28 17:17:15 +00:00
Jaco Greeff 458dec53dc Session validators availability detection (#1759) 2020-01-28 18:10:06 +01:00
Github Actions ab05045686 [CI Skip] 1.0.0-beta.30
skip-checks: true
2020-01-28 16:47:39 +00:00
Jaco Greeff b2c84eb461 Bump deps (#1758)
* Bump deps

* api detect
2020-01-28 17:40:57 +01:00
Github Actions 1ee1d70d55 [CI Skip] 1.0.0-beta.29
skip-checks: true
2020-01-28 15:25:22 +00:00
Jaco Greeff 7de647ec0b Cleanup module-specific type-overrides (#1756) 2020-01-28 16:18:40 +01:00
Github Actions cedbd8fa06 [CI Skip] 1.0.0-beta.28
skip-checks: true
2020-01-28 14:40:38 +00:00
Jaco Greeff cba34b4b65 Fill signAsync with expanded chain options (#1753)
* Fill signAsync with expanded chain options

* Use mapTo

* Fill test with defined storage value

* Remove .only
2020-01-28 15:33:44 +01:00
Github Actions 1a99d67c77 [CI Skip] 1.0.0-beta.27
skip-checks: true
2020-01-28 10:13:45 +00:00
Jaco Greeff 2a5c5ce3fe Only include derives with parent query (#1755)
* Only include derives with parent query

* Update CHANGELOG
2020-01-28 11:07:02 +01:00
Github Actions e4ca0a1c64 [CI Skip] 1.0.0-beta.26
skip-checks: true
2020-01-28 08:59:33 +00:00
Jaco Greeff e6018f2f75 Add society-specific Vote type (#1754)
* Add society-specific Vote type

* Cnvert storage types via toLatest
2020-01-28 09:52:40 +01:00
Github Actions a9b4f8d841 [CI Skip] 1.0.0-beta.25
skip-checks: true
2020-01-27 18:42:41 +00:00
Amaury Martiny 7fe68857a0 Init api when provider is already connected (#1752)
* Init api when provider is already connected

* Spacing
2020-01-27 19:35:38 +01:00
Github Actions 4f63fc77a3 [CI Skip] 1.0.0-beta.24
skip-checks: true
2020-01-27 16:20:13 +00:00
Jaco Greeff 6e2ad7789e Expose .entries() for DoubleMaps (#1750)
* Expose .entries() for DoubleMaps

* DoubleMap vs Map test

* Fix decoration

* Remove prefixed map

* Allow SoubleMap entries() with arguments

* DoubleMap with & without params

* Remove debug log

* Update CHANGELOG

* ... and working... finally.

* Cleanup debug logs
2020-01-27 17:13:53 +01:00
Github Actions edb856c94f [CI Skip] 1.0.0-beta.23
skip-checks: true
2020-01-27 14:12:40 +00:00
Jaco Greeff 2f215fe2de Cleanup entries() (#1751) 2020-01-27 15:07:00 +01:00
Github Actions ffa1279c64 [CI Skip] 1.0.0-beta.22
skip-checks: true
2020-01-27 11:56:57 +00:00
Jaco Greeff 83aca87dac Skip types.ts for typedoc (#1749) 2020-01-27 12:50:36 +01:00
Github Actions bf782f6f65 [CI Skip] 1.0.0-beta.21
skip-checks: true
2020-01-27 11:43:36 +00:00
Jaco Greeff 7adad82786 Remove v11 metadata (#1748)
* Remove v11 metadata

* Linting
2020-01-27 12:37:01 +01:00
Github Actions 693cf855f0 [CI Skip] 1.0.0-beta.20
skip-checks: true
2020-01-27 08:45:51 +00:00
Jaco Greeff 854a520517 Mark some function @internal (no doc extraction) (#1746) 2020-01-27 09:38:02 +01:00
Github Actions 6e6fc98cd1 [CI Skip] 1.0.0-beta.19
skip-checks: true
2020-01-26 09:36:27 +00:00
Jaco Greeff 3db15e73a5 Bump deps (#1745)
* Bump deps

* Fix test expectation

* Mark doc internal
2020-01-26 10:27:44 +01:00
Github Actions 215b659a9a [CI Skip] 1.0.0-beta.18
skip-checks: true
2020-01-23 17:12:43 +00:00
Jaco Greeff 7ef945d15b Make invalid V9 metadata parse (won't work, but parses) (#1743)
* Make invalid V9 metadata parse (won't work, but parses)

* Add invalid to V4 (simpler, no code)
2020-01-23 18:06:25 +01:00
Github Actions 73ec345fcc [CI Skip] 1.0.0-beta.17
skip-checks: true
2020-01-22 14:59:54 +00:00
Jaco Greeff c1c537a3b5 Type aliases on a per-module basis (#1740)
* Type aliasses on a per-module basis

* Remove test interface

* Update wrapper

* Move known types to types
2020-01-22 15:51:23 +01:00
Github Actions dc64076c79 [CI Skip] 1.0.0-beta.16
skip-checks: true
2020-01-22 14:22:49 +00:00
Jaco Greeff da8ff51615 Remove unmaintained & outdated E2E (#1739) 2020-01-22 15:14:57 +01:00
Github Actions 60b1bc87a4 [CI Skip] 1.0.0-beta.15
skip-checks: true
2020-01-22 09:41:19 +00:00
Jaco Greeff 7ed1857589 Update SlashingSpans (#1738)
* Update SlashingSpans

* Digest 0toX -> ToX
2020-01-22 10:33:05 +01:00
Github Actions 4c0e60f3d6 [CI Skip] 1.0.0-beta.14
skip-checks: true
2020-01-21 13:52:44 +00:00
Jaco Greeff 20ed3bb5fe Allow passing of signer via sign options (#1734)
* Allow passing of signer via sign options

* Pass signer via api.sign
2020-01-21 14:45:53 +01:00
Jaco Greeff be3f9c8fe8 Remove outdated derive + combineLatest comment (#1733)
As per https://github.com/polkadot-js/api/pull/1732/files#r368599021
2020-01-21 14:45:07 +01:00
Github Actions e850955e55 [CI Skip] 1.0.0-beta.13
skip-checks: true
2020-01-20 13:05:49 +00:00
Jaco Greeff eb5ee9860b Multi query adjustments (#1732) 2020-01-20 13:58:07 +01:00
Github Actions f31bbdde02 [CI Skip] 1.0.0-beta.12
skip-checks: true
2020-01-19 21:55:43 +00:00
Jaco Greeff f67c435378 Trigger build 2020-01-19 22:49:09 +01:00
Jaco Greeff bf9a60a202 Update .123trigger 2020-01-19 22:46:50 +01:00
Jaco Greeff 9c3c07fa9b Derives for society (#1727)
* Deries for society

* Candidates

* Add overview

* Candidate types

* WIP, stash before merge

* Linting

* Readability

* Typo

* Split option maps
2020-01-19 21:56:39 +01:00
Github Actions 11786ca102 [CI Skip] 1.0.0-beta.11
skip-checks: true
2020-01-19 20:14:25 +00:00
Nikolay Volf ffaea83e3e Fix typo (#1730) 2020-01-19 21:05:58 +01:00
Github Actions 954540b944 [CI Skip] 1.0.0-beta.10
skip-checks: true
2020-01-19 10:29:05 +00:00
Jaco Greeff 204cf6769d Bump mtadata (latest Substrate) (#1728) 2020-01-19 11:20:33 +01:00
Github Actions f319bc4c50 [CI Skip] 1.0.0-beta.9
skip-checks: true
2020-01-19 09:24:49 +00:00
Jaco Greeff 7b9a11ac25 Don't map empty tuples to Null (#1725)
* Don't map empty tuples to Null

* Remove unused var

* Regen with tuple Result

* Generated types lint fixes
2020-01-19 10:17:20 +01:00
Github Actions 5d2feca2d4 [CI Skip] 1.0.0-beta.8
skip-checks: true
2020-01-16 13:54:01 +00:00
Jaco Greeff dd97e9daee Add registry error lookup (#1723) 2020-01-16 14:46:21 +01:00
Github Actions be258a1f7c [CI Skip] 1.0.0-beta.7
skip-checks: true
2020-01-15 09:05:23 +00:00
Jaco Greeff 72e9474f6f imOnline Heartbeat struct (#1721) 2020-01-15 09:56:58 +01:00
Github Actions d1f63a7864 [CI Skip] 1.0.0-beta.6
skip-checks: true
2020-01-14 18:15:57 +00:00
Jaco Greeff 07ca18502b Society/Recovery types (#1719)
* Society/Recovery types

* camelCase (linting)
2020-01-14 19:08:40 +01:00
Github Actions cddbe411f7 [CI Skip] 1.0.0-beta.5
skip-checks: true
2020-01-14 15:03:44 +00:00
Jaco Greeff ffa60d1cfa Drop V1 support in derive (#1718)
* Drop V1 support in derive

* Re-do staking with multi

* Re-bump deps

* Adjusts tests (no alice_session)

* CC
2020-01-14 15:55:25 +01:00
Github Actions 88193b6a75 [CI Skip] 1.0.0-beta.4
skip-checks: true
2020-01-14 13:15:58 +00:00
Stefanie Doll cc4a4607f1 Updated child storage parameters (#1709)
* Added child_definition and child_type to chicl dtorage RPC methods

* reset comments in test file

* reverse docs re-built

* Fix linting on child storage tests
2020-01-14 14:07:41 +01:00
Github Actions 6c25d0ab0d [CI Skip] 1.0.0-beta.3
skip-checks: true
2020-01-13 21:26:52 +00:00
Amaury Martiny fbbbcd2612 Enum toJSON returns toString for a basic enum (#1697)
* Update kusama static from 1032 to 1033

* Test 1032 and 1033

* Got exact metadata from kusama

* First pass: enum TOJSON and fix some tests

* Build interfaces

* Fix import

* Use camelCase for enum toJSON

* Build interface

* Fix lint

* Fix tests

* Generate static json
2020-01-13 22:18:51 +01:00
Github Actions dd57b1a007 [CI Skip] 1.0.0-beta.2
skip-checks: true
2020-01-13 17:03:58 +00:00
Jaco Greeff 47d0e68f7d Remove old known keys (#1715)
* Remove old known keys

* Don't import removed

* Update storage keys
2020-01-13 17:55:21 +01:00
Github Actions 7b6397215d [CI Skip] 1.0.0-beta.1
skip-checks: true
2020-01-13 16:39:56 +00:00
Jaco Greeff 5739b69757 Bump to 1.0 beta (#1717)
* Bump to 1.0 beta bump

* Bump common to 2.0 beta
2020-01-13 17:31:33 +01:00
Github Actions 2ca79f2f70 [CI Skip] 0.100.1
skip-checks: true
2020-01-13 15:19:07 +00:00
Jaco Greeff 8fb64f77cd 0.100 (#1716) 2020-01-13 16:11:56 +01:00
Github Actions d1f86ce78e [CI Skip] 0.100.0-beta.30
skip-checks: true
2020-01-13 14:24:03 +00:00
Keith IngramandJaco Greeff 64ff226535 Fix api.derive.collective (#1711)
* fix api.derive.collective

* imports

* Update proposals.ts

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-01-13 15:17:04 +01:00
Github Actions e762746ff0 [CI Skip] 0.100.0-beta.29
skip-checks: true
2020-01-13 11:03:54 +00:00
Xiliang Chen ce5c8f7443 fix AssetOptions def (#1714) 2020-01-13 11:55:51 +01:00
Github Actions fc4cbb608c [CI Skip] 0.100.0-beta.28
skip-checks: true
2020-01-12 13:50:01 +00:00
Jaco Greeff 7ac3043f83 Extract sub identities (via accounts derive) (#1713)
* Extract sub identities

* Cleanups
2020-01-12 14:42:42 +01:00
Github Actions 44b56fb0cb [CI Skip] 0.100.0-beta.27
skip-checks: true
2020-01-10 15:06:03 +00:00
Jaco Greeff 758ce567e5 Failsafe on proposal decode (fallback ro preimage only) (#1710) 2020-01-10 15:58:56 +01:00
Github Actions cb5308b476 [CI Skip] 0.100.0-beta.26
skip-checks: true
2020-01-10 13:55:10 +00:00
Amaury Martiny a9211690be Remove v9->v10 hack (#1694)
* Remove v9->v10 hack

* Update static

* Update JSON
2020-01-10 14:47:06 +01:00
Github Actions a7db14a261 [CI Skip] 0.100.0-beta.25
skip-checks: true
2020-01-10 13:03:45 +00:00
Jaco Greeff 3a1f284fa8 Treasury OpenTip (#1708) 2020-01-10 13:56:05 +01:00
Github Actions a0b6c42629 [CI Skip] 0.100.0-beta.24
skip-checks: true
2020-01-10 11:10:20 +00:00
Jaco Greeff f77ae4d99f Add percent type (#1707) 2020-01-10 12:02:35 +01:00
Github Actions 5fa9af8fd3 [CI Skip] 0.100.0-beta.23
skip-checks: true
2020-01-10 10:32:55 +00:00
Jaco Greeff 1ff029dc11 Update IdentityInfo with twitter field (#1706)
* Update IdentityInfo with twitter field

* Rebuild

* Update test with twitter
2020-01-10 11:25:10 +01:00
Github Actions 4c8c9fbb07 [CI Skip] 0.100.0-beta.22
skip-checks: true
2020-01-09 13:47:13 +00:00
Jaco Greeff 7057cf365b Add paymentInfo to submittables (#1582)
* Add paymentInfo to submittables

* Cleanup paymentInfo call

* Use 0x42...42 dummy sigs

* Re-add paymentInfo to submittable

* Add correct signFake interfaces

* CHANGELOG
2020-01-09 14:40:25 +01:00
Github Actions d1bc48e936 [CI Skip] 0.100.0-beta.21
skip-checks: true
2020-01-09 11:07:18 +00:00
Jaco Greeff 2dee50f019 Bump deps (#1704) 2020-01-09 11:59:21 +01:00
Github Actions fa76378702 [CI Skip] 0.100.0-beta.20
skip-checks: true
2020-01-08 08:29:06 +00:00
Jaco Greeff e855da1f13 Make a start at the Polkadot launch types (#1700)
* Make a start at the Polkadot launch types

* Add missing old DispatchInfo
2020-01-08 09:21:23 +01:00
Github Actions adffde368c [CI Skip] 0.100.0-beta.19
skip-checks: true
2020-01-07 09:01:45 +00:00
Jaco Greeff 5278138cc3 Make submittable signAsync Observable-aware (#1698)
* Make submittable signAsync Observable-aware

* rxjs test for signAsync

* Cleanup tests, pass signer in .create

* Simplify Observable creation
2020-01-07 09:54:04 +01:00
Github Actions 98249a282e [CI Skip] 0.100.0-beta.18
skip-checks: true
2020-01-06 13:20:39 +00:00
Jaco Greeff b7eeb992cd Bump deps (#1699) 2020-01-06 14:12:49 +01:00
Github Actions 01daf32646 [CI Skip] 0.100.0-beta.17
skip-checks: true
2020-01-03 16:45:58 +00:00
Amaury Martiny 51a866fd35 Update kusama static from 1032 to 1033 (#1696)
* Update kusama static from 1032 to 1033

* Update comment

* Rename variables

* Test 1032 and 1033

* Got exact metadata from kusama
2020-01-03 17:38:32 +01:00
Github Actions 53401e29ea [CI Skip] 0.100.0-beta.16
skip-checks: true
2020-01-03 11:13:30 +00:00
Amaury Martiny 774f41e6db Only apply hack if exactly metadata from kusama 1032 (#1695) 2020-01-03 12:05:27 +01:00
Github Actions 1ca3b295a4 [CI Skip] 0.100.0-beta.15
skip-checks: true
2020-01-02 17:11:51 +00:00
Keith IngramandAmaury Martiny 82828d8e09 Add metadata v10/11, blake2_128concat hasher (#1691)
* v11, blake2_128concat

* MetadataAll

* Add storage hasher v4 and v10

* Make lint pass

* Add correct interfaces

* Fix lint

* Update metadata definitions

* Update v10 metadata

* Update packages/types/src/interfaces/utility/definitions.ts

* Update v11

* Add HACK

* Skip v9 tests (part of HACK)

* Correct function names

Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com>
2020-01-02 18:04:42 +01:00
Github Actions 131055c1d5 [CI Skip] 0.100.0-beta.14
skip-checks: true
2019-12-20 10:04:22 +00:00
Jaco Greeff bd2e690261 Update DispatchError for Kusama (#1686) 2019-12-20 10:57:37 +01:00
Github Actions 1a2ca8ea38 [CI Skip] 0.100.0-beta.13
skip-checks: true
2019-12-19 14:44:19 +00:00
Jaco Greeff 0c98593aee Update DispatchError as enum (#1682)
* Update DispatchError as enum

* Add DispatchResult

* Update tests for DispatchResult

* Rebuild
2019-12-19 15:37:36 +01:00
Github Actions 416e2fbc96 [CI Skip] 0.100.0-beta.12
skip-checks: true
2019-12-19 13:14:08 +00:00
Jaco Greeff c04fb9073e Don't query proposal via multi (#1683) 2019-12-19 14:07:23 +01:00
Github Actions 4f85ceb2c3 [CI Skip] 0.100.0-beta.11
skip-checks: true
2019-12-19 10:09:06 +00:00
Jaco Greeff 9196ce85a0 Expand identity derive fields (incl. all) (#1680) 2019-12-19 11:00:47 +01:00
Github Actions 26734bf8bf [CI Skip] 0.100.0-beta.10
skip-checks: true
2019-12-18 15:30:04 +00:00
satellitex 53959d482d Add BTreeSet<V> Codec (#1639)
* add BTreeSet Codec

* Add following BTreeMap

* fix linting

* fix linting

* add validate Types and encode Types

* type def info is incremented.

* fix compareSet
2019-12-18 16:22:54 +01:00
Github Actions 0a0f110c42 [CI Skip] 0.100.0-beta.9
skip-checks: true
2019-12-17 16:28:01 +00:00
Keith Ingram 47f1350652 Additional rpcContractCall guard (#1677)
* additional rpc guard

* isFunction

* isFunction
2019-12-17 17:21:19 +01:00
Github Actions 3c3b7290c2 [CI Skip] 0.100.0-beta.8
skip-checks: true
2019-12-17 14:40:40 +00:00
Jaco Greeff 006c686c18 Fix linked maps with optional entries (#1676)
* Fix linked maps with optional entries

* Revert entries() change for linked maps
2019-12-17 15:33:45 +01:00
Github Actions 44d4a07005 [CI Skip] 0.100.0-beta.7
skip-checks: true
2019-12-16 11:41:13 +00:00
Github Actions 6e61be960c [CI Skip] 0.100.0-beta.6
skip-checks: true
2019-12-16 11:02:37 +00:00
Jaco Greeff bd57359dc5 Cleanuop preimage check (#1674) 2019-12-16 11:56:42 +01:00
Github Actions 10bc6b4060 [CI Skip] 0.100.0-beta.5
skip-checks: true
2019-12-16 09:49:08 +00:00
Jaco Greeff 9e681c0666 Update .123trigger 2019-12-16 10:42:04 +01:00
Github Actions e969382fd0 [CI Skip] 0.100.0-beta.4
skip-checks: true
2019-12-16 09:36:41 +00:00
Jaco Greeff 1949a13810 Update .123trigger 2019-12-16 10:30:18 +01:00
Github Actions 362262c4e1 [CI Skip] 0.100.0-beta.3
skip-checks: true
2019-12-15 20:44:20 +00:00
Keith Ingram ddd5eab7f5 collective proposals (#1671) 2019-12-15 15:37:27 -05:00
Github Actions 1da6193f34 [CI Skip] 0.100.0-beta.2
skip-checks: true
2019-12-15 11:22:45 +00:00
Jaco Greeff c4e553ad80 Add identity names to derive.accounts.info (#1673) 2019-12-15 12:16:17 +01:00
Github Actions 0b83a61600 [CI Skip] 0.100.0-beta.1
skip-checks: true
2019-12-15 09:04:04 +00:00
Jaco Greeff 382f7d75c8 Data has custom encodedLength 2019-12-15 09:56:30 +01:00
Github Actions 88e4518f64 [CI Skip] 0.100.0-beta.0
skip-checks: true
2019-12-15 07:50:37 +00:00
Jaco Greeff b1a657d68a Custom encoding for identity Data (#1672)
* Custom encoding for identity Data

* Custom encoding for IdentityFields

* Allow empty U8a input to Data

* IdentityField tests
2019-12-15 08:43:22 +01:00
Jaco Greeff 067f17b28b Enum with single-entry encoding (#1670)
* Enum with single-entry encoding

* Expand test with breakdown
2019-12-13 11:19:38 +01:00
648 changed files with 33217 additions and 12420 deletions
+1 -1
View File
@@ -1 +1 @@
14
17
+1 -1
View File
@@ -4,6 +4,6 @@ exclude_patterns:
- "**/*.test.js"
- "**/*.test.ts"
- "docs/**/*.js"
- "packages/api/src/query.types.ts"
- "packages/api/src/types/augment/"
- "packages/types/src/interfaces/"
- "packages/types/src/scripts/"
+45 -2
View File
@@ -1,3 +1,46 @@
# 1.1.1
- Add support for `balances.account` in all applicable derives (incl. `vesting` module)
- Inject and use SignedExtensions by name from V11 metadata (V4 extrinsics only)
- Add typings for `api.tx.*.*` - the `polkadot-types-from-chain` now also generates these
- Remove additional V1-only derives `(staking.recentlyOffline`, `balances.nominatorsFor`)
- Add `.isMax()` on int values, an opposite of `isZero()` (e.g. `u128`, as well as derived, e.g. `Balances`)
- Add `.keyPrefix()` to all `api.query.*` complementing the `.key()` call, both returning a hex string
- Council derives now takes bootstrapping (member, no elections) into account
- Account derives now allow for an optional indices module (not required)
- Adjust balances fees derivation with optional transfer and creation fees (removed in Substrate)
- Adjust enum `.toJSON()` to return type name as specified
# 1.0.1
- **Breaking change** Drop support for Substrate v1 chain in all derives
- Return unsub functions from provider .on emitters (Thanks to https://github.com/jak-pan)
- `ApiPromise.isReady` now rejects on unrecoverable errors (Thanks to https://github.com/laec)
- Add `polkadot-types-from-chain` & `polkadot-types-from-defs` TypeScript generators to `@polkadot/types`
- Only decorate derives where relevant parent `api.query.*` is available
- Support `.entries(arg?: any)` lookups on DoubleMaps (in addition to previously supported maps)
- Allow v9 metadata to parse even in cases where it was wrongly deployed pre-v10
- Allow type-aliases on a per-module basis (e.g. `Judgement` in identity as well as society)
- Allow passing `{ signer }` to both `api.tx.*` and `api.sign` (in addition to `api.setSigner`)
- Add derives for the society module
- Don't map empty tuples, e.. `()` to `Null`, rather keep them empty
- Add lookups to the metadata errors via `findMetaError`
- Update metadata and types for the latest Substrate & Polkadot versions
- Support metadata V11 as per latest Substrate
- Remove support for un-deployed metadata
- Remove old known types for Substrate V1
# 0.100.1
- **Important** This will the the last API version with Substrate 1.x support. Although you will still be able to use subsequent versions with older chans, dependent libraries such as sr25519 may not be compatible.
- Add support for the Substrate identity module
- Remove the `codec/Data` type, to remove a conflict with Substrate. This type is now named `Raw`
- Fix for linked maps using `Option`
- Add support for `BTreeSet` (Thanks to https://github.com/satellitex)
- Add support for Metadata v10
- Add support for latest Polkadot/Substrate types
- Add `paymentInfo` to submittables to calculate fees
# 0.99.1
- **Breaking change** The `Data` and `U8a` type has been renamed and just replaced with the `Raw` type
@@ -9,9 +52,9 @@
# 0.98.1
- Make the TypeScript generation script mor re-usable (Thanks to @xlc)
- Make the TypeScript generation script mor re-usable (Thanks to https://github.com/xlc)
- Add `.entries()` for all map-types, returning storage keys and values
- Add `.signAsync` to submittable extrinsics (Thanks to @c410-f3r)
- Add `.signAsync` to submittable extrinsics (Thanks to https://github.com/c410-f3r)
- Cleanup circular references between internal dependencies
- Support for new Substrate democracy with preimages in derive
- Alignment of types with Substrate/Polkadot master branches
+1
View File
@@ -45,6 +45,7 @@ module.exports = {
['start/types.extend.md', 'Extending types'],
['start/extrinsic.extend.md', 'Extending extrinsics'],
['start/typescript.md', 'TypeScript interfaces'],
['start/typescript.user.md', 'TypeScript user generated'],
['start/FAQ.md', 'FAQ']
]
},
+1
View File
@@ -17,6 +17,7 @@
- [Type basics](start/types.basics.md)
- [Type extension](start/types.extend.md)
- [TypeScript interfaces](start/typescript.md)
- [TypeScript user generated](start/typescript.user.md)
## Packages
+2 -7
View File
@@ -46,11 +46,6 @@ As of this writing, there are still some gray areas to type detection, specifica
- `.at` & `.multi` on `api.query` does not (yet) have a `<TypeOverride>` interface. This means `as <TypeOverride>` casts are presently needed for these results
- `api.queryMulti` does not (yet) allow you to provide a hint to the types returned, this ties to the previous point
In addition to expanding the type coverage, we wish to make the actual generation script for the types from `@polkadot/types/interfaces` available in 2 ways -
## Adding user types
- allowing you to point to a folder of types and auto-generate the TypeScript typings from those. (Which is akin to what we do internally). This would allow a reduction in type classes explicitly written and injected.
- once the metadata itself supports full type definitions, the script can be used to generate interface definitions specifically tailored for a chain
## And that's a wrap
This brings us to the end of our overview and jump through the API. While the documentation is still very much and ever evolving item, we can encourage you to try out what you have learned with some [examples](../examples). As we [indicated right at the start of this journey](README.md#help-us-help-others), if there are areas for improvement, let us know.
In addition to the generated and available interfaces, there is also the ability to [create TypeScript interfaces from your own definitions and well as your on-chain modules](typescript.user.md).
+26
View File
@@ -0,0 +1,26 @@
# TypeScript user generated
In the previous section we looked at the TypeScript definitions that are available and is generated from both the chain and definitions. Here we will expand upon the use of the infrastructure created to define types as part of the `@polkadot/types` library and see how to use them to generate your onw defintions and chain types.
## Definitions
A large part of the type definitions are defined not as classes, but rather as structures from which type definitions are extracted and that can be used as-is to let the API know how to decode a type. By now you should be familiar with [type extensions](types.extend.md), but effectively the [types library does exactly the same](https://github.com/polkadot-js/api/tree/master/packages/types/src/interfaces).
To create TypeScript-aware definitions and keep your files in a single place, you can follow the same approach. Assuming you have a package named `@MeInc/stuff` where you have the definitions in an `stuff/interfaces` folder. Each sub-folder would indicate a runtime module, e.g.
- `stuff/interfaces/<module>/definitions.ts` for each module (`types.ts` & `index.ts` will be generated)
- `stuff/interfaces/defnitions.ts` importing all sub-definitions`
With this structure setup, you can generate TypeScript defintions.
In the root of your project (with the `@polkadot/api`), you can run `yarn polkadot-types-from-defs --input ./stuff/interfaces --package @MeInc/stuff/interfaces` which will create `types.ts` and `index.ts` files with the generated types. You can use these in exactly the same way as you would use your types from `@polkadot/types/interfaces`.
## Chain modules
In the same way as the type library provides defaults from a substrate-base chain, you can also, directly from chain from metadata, generate a complete `api.{consts,query}.*` defintion for your specific chain. The command will create 2 files, `{consts, query}.types.ts` which you can either use to augment the TypeScript defintions, or replace those in `@polkadot/api/*` with your versions (copy, TypeScript replacement or browser/node aliassing).
In the root of your project, you can run `yarn polkadot-types-from-chain --endpoint wss://<url> --output ./stuff` and it will create the required output. (Here you can specify an optional `--package @MeInc/stuff` to read definitions for the targetted output folder with the specified package name.)
## And that's a wrap
This brings us to the end of our overview and jump through the API. While the documentation is still very much and ever evolving item, we can encourage you to try out what you have learned with some [examples](../examples). As we [indicated right at the start of this journey](README.md#help-us-help-others), if there are areas for improvement, let us know.
+2 -1
View File
@@ -31,5 +31,6 @@ module.exports = Object.assign({}, config, {
ws_local_polkadot_alex: 'ws://127.0.0.1:9949/',
ws_substrate_1: 'wss://substrate-rpc.parity.io/',
ws_polkadot_alex: 'wss://poc3-rpc.polkadot.io/'
}
},
resolver: './jest.resolver.js'
});
+15
View File
@@ -0,0 +1,15 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path');
module.exports = function resolver (file, config) {
if (file.includes('package.json')) {
console.error(file, config);
return path.join(config.basedir.replace('/src', '/'), file);
}
return config.defaultResolver(file, config);
};
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "0.99.1"
"version": "1.1.1"
}
+7 -10
View File
@@ -1,5 +1,5 @@
{
"version": "0.99.1",
"version": "1.1.1",
"private": true,
"engines": {
"yarn": "^1.10.1"
@@ -9,7 +9,7 @@
],
"resolutions": {
"babel-core": "^7.0.0-bridge.0",
"typescript": "^3.7.3"
"typescript": "^3.7.5"
},
"scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts",
@@ -22,17 +22,14 @@
"postinstall": "polkadot-dev-yarn-only",
"test": "jest --coverage --runInBand --testPathIgnorePatterns e2e",
"test:all": "jest",
"test:e2e": "jest packages/api/test/e2e",
"test:e2e-docker": "TEST_DOCKER=1 jest packages/api/test/e2e",
"test:e2e-remote": "TEST_REMOTE=1 jest packages/api/test/e2e",
"test:one": "jest",
"test:watch": "jest --coverage --watch"
},
"devDependencies": {
"@babel/core": "^7.7.5",
"@babel/register": "^7.7.4",
"@babel/runtime": "^7.7.6",
"@polkadot/dev": "^0.32.0-beta.18",
"@polkadot/ts": "^0.1.88"
"@babel/core": "^7.8.3",
"@babel/register": "^7.8.3",
"@babel/runtime": "^7.8.3",
"@polkadot/dev": "^0.33.3",
"@polkadot/ts": "^0.2.1"
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-contract",
"version": "0.99.1",
"version": "1.1.1",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
"keywords": [
@@ -26,7 +26,7 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.7.6",
"@polkadot/types": "^0.99.1"
"@babel/runtime": "^7.8.3",
"@polkadot/types": "^1.1.1"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/types authors & contributors
// Copyright 2017-2020 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+2 -2
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -41,7 +41,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
return {
send: this.decorateMethod(
as === 'rpc'
as === 'rpc' && this.hasRpcContractsCall
? (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'rpc'> => {
return this.rpcContractsCall(
createType(this.registry, 'ContractCallRequest', {
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// Copyright 2017-2020 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+10 -10
View File
@@ -1,13 +1,13 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// Copyright 2017-2020 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiTypes, DecorateMethod, DecoratedRpc, SubmittableModuleExtrinsics } from '@polkadot/api/types';
import { ApiObject, ContractABIMessage, ContractABIPre, ContractBase, ContractMessage } from '../types';
import { RpcInterface } from '@polkadot/rpc-core/jsonrpc.types';
import { RpcInterface } from '@polkadot/rpc-core/types';
import { Registry } from '@polkadot/types/types';
import { ApiObject, ContractABIMessage, ContractABIPre, ContractBase, ContractMessage } from '../types';
import { assert, stringCamelCase } from '@polkadot/util';
import { assert, isFunction, stringCamelCase } from '@polkadot/util';
import Abi from '../Abi';
export abstract class Base<ApiType extends ApiTypes> implements ContractBase<ApiType> {
@@ -66,13 +66,13 @@ export abstract class BaseWithTx<ApiType extends ApiTypes> extends Base<ApiType>
}
export abstract class BaseWithTxAndRpcCall<ApiType extends ApiTypes> extends BaseWithTx<ApiType> {
public get hasRpcContractsCall (): boolean {
return isFunction(this.api.rx.rpc.contracts?.call);
}
protected get rpcContractsCall (): DecoratedRpc<'rxjs', RpcInterface>['contracts']['call'] {
assert(this.hasRpcContractsCall, 'You need to connect to a node with the contracts.call RPC method.');
return this.api.rx.rpc.contracts.call;
}
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>) {
super(api, abi, decorateMethod);
assert(this.api.rx.rpc.contracts && this.api.rx.tx.contracts.call, 'You need to connect to a node with the contracts module, the metadata does not enable api.rpc.contracts.call on this instance');
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-contract authors & contributors
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/rpc-core authors & contributors
// Copyright 2017-2020 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,49 +1,49 @@
[
{
"info": 7,
"info": 8,
"type": "{\"value\": {\"cell\": {\"cell\": ([u8;32])}}}",
"name": "Flipper",
"namespace": "flipper::normal",
"sub": [
{
"info": 7,
"info": 8,
"type": "{\"cell\": {\"cell\": ([u8;32])}}",
"name": "value",
"namespace": "ink_core::storage::value",
"params": [
{
"info": 5,
"info": 6,
"type": "bool"
}
],
"sub": [
{
"info": 7,
"info": 8,
"type": "{\"cell\": ([u8;32])}",
"name": "cell",
"namespace": "ink_core::storage::cell::sync_cell",
"params": [
{
"info": 5,
"info": 6,
"type": "bool"
}
],
"sub": [
{
"info": 8,
"info": 9,
"type": "([u8;32])",
"name": "cell",
"namespace": "ink_core::storage::key",
"sub": [
{
"info": 10,
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"sub": {
"info": 5,
"info": 6,
"type": "u8"
},
"index": 0
@@ -57,44 +57,44 @@
]
},
{
"info": 7,
"info": 8,
"type": "{\"cell\": {\"cell\": ([u8;32])}}",
"name": "Value",
"namespace": "ink_core::storage::value",
"params": [
{
"info": 5,
"info": 6,
"type": "bool"
}
],
"sub": [
{
"info": 7,
"info": 8,
"type": "{\"cell\": ([u8;32])}",
"name": "cell",
"namespace": "ink_core::storage::cell::sync_cell",
"params": [
{
"info": 5,
"info": 6,
"type": "bool"
}
],
"sub": [
{
"info": 8,
"info": 9,
"type": "([u8;32])",
"name": "cell",
"namespace": "ink_core::storage::key",
"sub": [
{
"info": 10,
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"sub": {
"info": 5,
"info": 6,
"type": "u8"
},
"index": 0
@@ -106,36 +106,36 @@
]
},
{
"info": 5,
"info": 6,
"type": "bool"
},
{
"info": 7,
"info": 8,
"type": "{\"cell\": ([u8;32])}",
"name": "SyncCell",
"namespace": "ink_core::storage::cell::sync_cell",
"params": [
{
"info": 5,
"info": 6,
"type": "bool"
}
],
"sub": [
{
"info": 8,
"info": 9,
"type": "([u8;32])",
"name": "cell",
"namespace": "ink_core::storage::key",
"sub": [
{
"info": 10,
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"sub": {
"info": 5,
"info": 6,
"type": "u8"
},
"index": 0
@@ -145,20 +145,20 @@
]
},
{
"info": 8,
"info": 9,
"type": "([u8;32])",
"name": "Key",
"namespace": "ink_core::storage::key",
"sub": [
{
"info": 10,
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"sub": {
"info": 5,
"info": 6,
"type": "u8"
},
"index": 0
@@ -166,19 +166,19 @@
]
},
{
"info": 10,
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"sub": {
"info": 5,
"info": 6,
"type": "u8"
}
},
{
"info": 5,
"info": 6,
"type": "u8"
}
]
@@ -1,29 +1,29 @@
[
{
"info": 9,
"info": 10,
"type": "{ \"value\": \"{ \"cell\": \"{ \"cell\": \"([u8;32])\"} }<u32>\"} }<u32>\"} }",
"sub": [
{
"info": 9,
"info": 10,
"type": "{ \"cell\": \"{ \"cell\": \"([u8;32])\"} }<u32>\"} }",
"sub": [
{
"info": 9,
"info": 10,
"type": "{ \"cell\": \"([u8;32])\"} }",
"sub": [
{
"info": 10,
"info": 11,
"type": "([u8;32])",
"sub": [
{
"info": 12,
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"sub": {
"info": 6,
"info": 7,
"type": "u8"
},
"index": 0
@@ -37,7 +37,7 @@
"namespace": "ink_core::storage::cell::sync_cell",
"params": [
{
"info": 6,
"info": 7,
"type": "u32"
}
]
@@ -47,7 +47,7 @@
"namespace": "ink_core::storage::value",
"params": [
{
"info": 6,
"info": 7,
"type": "u32"
}
]
@@ -57,26 +57,26 @@
"namespace": "incrementer::normal"
},
{
"info": 9,
"info": 10,
"type": "{ \"cell\": \"{ \"cell\": \"([u8;32])\"} }<u32>\"} }",
"sub": [
{
"info": 9,
"info": 10,
"type": "{ \"cell\": \"([u8;32])\"} }",
"sub": [
{
"info": 10,
"info": 11,
"type": "([u8;32])",
"sub": [
{
"info": 12,
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"sub": {
"info": 6,
"info": 7,
"type": "u8"
},
"index": 0
@@ -90,7 +90,7 @@
"namespace": "ink_core::storage::cell::sync_cell",
"params": [
{
"info": 6,
"info": 7,
"type": "u32"
}
]
@@ -100,32 +100,32 @@
"namespace": "ink_core::storage::value",
"params": [
{
"info": 6,
"info": 7,
"type": "u32"
}
]
},
{
"info": 6,
"info": 7,
"type": "u32"
},
{
"info": 9,
"info": 10,
"type": "{ \"cell\": \"([u8;32])\"} }",
"sub": [
{
"info": 10,
"info": 11,
"type": "([u8;32])",
"sub": [
{
"info": 12,
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"sub": {
"info": 6,
"info": 7,
"type": "u8"
},
"index": 0
@@ -139,24 +139,24 @@
"namespace": "ink_core::storage::cell::sync_cell",
"params": [
{
"info": 6,
"info": 7,
"type": "u32"
}
]
},
{
"info": 10,
"info": 11,
"type": "([u8;32])",
"sub": [
{
"info": 12,
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"sub": {
"info": 6,
"info": 7,
"type": "u8"
},
"index": 0
@@ -166,23 +166,23 @@
"namespace": "ink_core::storage::key"
},
{
"info": 12,
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"sub": {
"info": 6,
"info": 7,
"type": "u8"
}
},
{
"info": 6,
"info": 7,
"type": "u8"
},
{
"info": 6,
"info": 7,
"type": "bool"
}
]
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "0.99.1",
"version": "1.1.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"keywords": [
@@ -27,11 +27,11 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.7.6",
"@polkadot/api": "^0.99.1",
"@polkadot/types": "^0.99.1"
"@babel/runtime": "^7.8.3",
"@polkadot/api": "^1.1.1",
"@polkadot/types": "^1.1.1"
},
"devDependencies": {
"@polkadot/keyring": "^1.7.1"
"@polkadot/keyring": "^2.2.1"
}
}
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,10 +1,10 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, AccountIndex } from '@polkadot/types/interfaces';
import { Observable } from 'rxjs';
import { Observable, of } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { ENUMSET_SIZE } from '@polkadot/types/primitive/Generic/AccountIndex';
@@ -26,18 +26,18 @@ import { memo } from '../util';
* ```
*/
export function indexToId (api: ApiInterfaceRx): (accountIndex: AccountIndex | string) => Observable<AccountId | undefined> {
const querySection = api.query.indices || api.query.balances;
return memo((_accountIndex: AccountIndex | string): Observable<AccountId | undefined> => {
const accountIndex = _accountIndex instanceof ClassOf(api.registry, 'AccountIndex')
? _accountIndex
: createType(api.registry, 'AccountIndex', _accountIndex);
return querySection.enumSet<Vec<AccountId>>(accountIndex.div(ENUMSET_SIZE)).pipe(
startWith([]),
map((accounts): AccountId | undefined =>
(accounts || [])[accountIndex.mod(ENUMSET_SIZE).toNumber()]
return api.query.indices.enumSet
? api.query.indices.enumSet<Vec<AccountId>>(accountIndex.div(ENUMSET_SIZE)).pipe(
startWith([]),
map((accounts): AccountId | undefined =>
(accounts || [])[accountIndex.mod(ENUMSET_SIZE).toNumber()]
)
)
);
: of(undefined);
});
}
+14 -10
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -6,7 +6,7 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, AccountIndex } from '@polkadot/types/interfaces';
import { AccountIndexes } from '../types';
import { Observable } from 'rxjs';
import { Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ENUMSET_SIZE } from '@polkadot/types/primitive/Generic/AccountIndex';
import { Vec, createType } from '@polkadot/types';
@@ -32,14 +32,18 @@ const enumsetSize = ENUMSET_SIZE.toNumber();
*/
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
return memo((): Observable<AccountIndexes> =>
api.query.indices.nextEnumSet<AccountIndex>().pipe(
// use the nextEnumSet (which is a counter of the number of sets) to construct
// a range of values to query [0, 1, 2, ...]. Retrieve the full enum set for the
// specific index - each query can return up to ENUMSET_SIZE (64) records, each
// containing an AccountId
switchMap((next: AccountIndex): Observable<Vec<AccountId>[]> =>
api.query.indices.enumSet.multi<Vec<AccountId>>([...Array(next.toNumber() + 1).keys()])
),
(api.query.indices.nextEnumSet
? api.query.indices.nextEnumSet<AccountIndex>().pipe(
// use the nextEnumSet (which is a counter of the number of sets) to construct
// a range of values to query [0, 1, 2, ...]. Retrieve the full enum set for the
// specific index - each query can return up to ENUMSET_SIZE (64) records, each
// containing an AccountId
switchMap((next: AccountIndex): Observable<Vec<AccountId>[]> =>
api.query.indices.enumSet.multi<Vec<AccountId>>([...Array(next.toNumber() + 1).keys()])
)
)
: of([] as AccountId[][])
).pipe(
map((all: AccountId[][]): AccountIndexes =>
all.reduce((result: AccountIndexes, list, outerIndex): AccountIndexes => {
(list || []).forEach((accountId, innerIndex): void => {
+80 -8
View File
@@ -1,22 +1,30 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, AccountIndex, Address, Balance } from '@polkadot/types/interfaces';
import { AccountId, AccountIndex, Address, Balance, Registration } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveAccountInfo } from '../types';
import { DeriveAccountInfo, DeriveAccountRegistration } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Bytes, Option, u32 } from '@polkadot/types';
import { Bytes, Data, Option, u32 } from '@polkadot/types';
import { u8aToString } from '@polkadot/util';
import { memo } from '../util';
function dataAsString (data: Data): string | undefined {
return data.isRaw
? u8aToString(data.asRaw.toU8a(true))
: data.isSha256
? data.asSha256.toHex()
: undefined;
}
function retrieveNick (api: ApiInterfaceRx, accountId?: AccountId): Observable<string | undefined> {
return ((
accountId && api.query.nicks
accountId && api.query.nicks?.nameOf
? api.query.nicks.nameOf<Option<ITuple<[Bytes, Balance]>>>(accountId)
: of(undefined)
) as Observable<Option<ITuple<[Bytes, Balance]>> | undefined>).pipe(
@@ -28,6 +36,69 @@ function retrieveNick (api: ApiInterfaceRx, accountId?: AccountId): Observable<s
);
}
function extractIdentity (identityOfOpt?: Option<Registration>, superOf?: [AccountId, Data]): DeriveAccountRegistration {
if (!identityOfOpt?.isSome) {
return { judgements: [] };
}
const { info, judgements } = identityOfOpt.unwrap();
const topDisplay = dataAsString(info.display);
return {
display: superOf
? dataAsString(superOf[1]) || topDisplay
: topDisplay,
displayParent: superOf
? topDisplay
: undefined,
email: dataAsString(info.email),
image: dataAsString(info.image),
legal: dataAsString(info.legal),
parent: superOf
? superOf[0]
: undefined,
pgp: info.pgpFingerprint.isSome
? info.pgpFingerprint.unwrap().toHex()
: undefined,
riot: dataAsString(info.riot),
twitter: dataAsString(info.twitter),
web: dataAsString(info.web),
judgements
};
}
function retrieveIdentity (api: ApiInterfaceRx, accountId?: AccountId): Observable<DeriveAccountRegistration> {
return ((
accountId && api.query.identity?.identityOf
? api.queryMulti([
[api.query.identity.identityOf, accountId],
[api.query.identity.superOf, accountId]
])
: of([undefined, undefined])
) as Observable<[Option<Registration> | undefined, Option<ITuple<[AccountId, Data]>> | undefined]>).pipe(
switchMap(([identityOfOpt, superOfOpt]): Observable<[Option<Registration> | undefined, [AccountId, Data] | undefined]> => {
if (identityOfOpt?.isSome) {
// this identity has something set
return of([identityOfOpt, undefined]);
} else if (superOfOpt?.isSome) {
const superOf = superOfOpt.unwrap();
// we have a super
return combineLatest([
api.query.identity.identityOf<Option<Registration>>(superOf[0]),
of(superOf)
]);
}
// nothing of value returned
return of([undefined, undefined]);
}),
map(([identityOfOpt, superOf]): DeriveAccountRegistration =>
extractIdentity(identityOfOpt, superOf)
)
);
}
/**
* @name info
* @description Returns aux. info with regards to an account, current that includes the accountId, accountIndex and nickname
@@ -35,14 +106,15 @@ function retrieveNick (api: ApiInterfaceRx, accountId?: AccountId): Observable<s
export function info (api: ApiInterfaceRx): (address?: AccountIndex | AccountId | Address | string | null) => Observable<DeriveAccountInfo> {
return memo((address?: AccountIndex | AccountId | Address | string | null): Observable<DeriveAccountInfo> =>
api.derive.accounts.idAndIndex(address).pipe(
switchMap(([accountId, accountIndex]): Observable<[DeriveAccountInfo, string?]> =>
switchMap(([accountId, accountIndex]): Observable<[Partial<DeriveAccountInfo>, DeriveAccountRegistration, string?]> =>
combineLatest([
of({ accountId, accountIndex }),
retrieveIdentity(api, accountId),
retrieveNick(api, accountId)
])
),
map(([{ accountId, accountIndex }, nickname]): DeriveAccountInfo => ({
accountId, accountIndex, nickname
map(([{ accountId, accountIndex }, identity, nickname]): DeriveAccountInfo => ({
accountId, accountIndex, identity, nickname
}))
));
}
@@ -0,0 +1,84 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, AccountData, AccountIndex, Address, Balance, Index } from '@polkadot/types/interfaces';
import { DerivedBalancesAccount } from '../types';
import { combineLatest, of, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { createType } from '@polkadot/types';
import { memo } from '../util';
type Result = [Balance, Balance, Balance, Balance, Index];
function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBalance, frozenFee, frozenMisc, accountNonce]]: [AccountId, Result]): DerivedBalancesAccount {
return {
accountId,
accountNonce,
freeBalance,
frozenFee,
frozenMisc,
reservedBalance,
votingBalance: createType(api.registry, 'Balance', freeBalance.add(reservedBalance))
};
}
// old
function queryOld (api: ApiInterfaceRx, accountId: AccountId): Observable<Result> {
return api.queryMulti<[Balance, Balance, Index]>([
[api.query.balances.freeBalance, accountId],
[api.query.balances.reservedBalance, accountId],
[api.query.system.accountNonce, accountId]
]).pipe(
map(([freeBalance, reservedBalance, accountNonce]): Result =>
[freeBalance, reservedBalance, createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), accountNonce]
)
);
}
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Result> {
return api.queryMulti<[AccountData, Index]>([
[api.query.balances.account, accountId],
[api.query.system.accountNonce, accountId]
]).pipe(
map(([{ free, reserved, miscFrozen, feeFrozen }, accountNonce]): Result =>
[free, reserved, feeFrozen, miscFrozen, accountNonce]
)
);
}
/**
* @name account
* @param {( AccountIndex | AccountId | Address | string )} address - An accounts Id in different formats.
* @returns An object containing the results of various balance queries
* @example
* <BR>
*
* ```javascript
* const ALICE = 'F7Hs';
*
* api.derive.balances.all(ALICE, ({ accountId, lockedBalance }) => {
* console.log(`The account ${accountId} has a locked balance ${lockedBalance} units.`);
* });
* ```
*/
export function account (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DerivedBalancesAccount> {
return memo((address: AccountIndex | AccountId | Address | string): Observable<DerivedBalancesAccount> =>
api.derive.accounts.info(address).pipe(
switchMap(({ accountId }): Observable<[AccountId, Result]> =>
(accountId
? combineLatest([
of(accountId),
api.query.balances.account
? queryCurrent(api, accountId)
: queryOld(api, accountId)
])
: of([createType(api.registry, 'AccountId'), [createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), createType(api.registry, 'Index')]])
)
),
map((result): DerivedBalancesAccount => calcBalances(api, result))
));
}
+67 -35
View File
@@ -1,9 +1,9 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, AccountIndex, Address, Balance, BalanceLock, BlockNumber, Index, VestingSchedule } from '@polkadot/types/interfaces';
import { DerivedBalances } from '../types';
import { AccountId, AccountIndex, Address, Balance, BalanceLock, BalanceLockTo212, BlockNumber, VestingInfo, VestingSchedule } from '@polkadot/types/interfaces';
import { DerivedBalancesAccount, DerivedBalancesAll } from '../types';
import BN from 'bn.js';
import { combineLatest, of, Observable } from 'rxjs';
@@ -14,29 +14,32 @@ import { bnMax } from '@polkadot/util';
import { memo } from '../util';
type ResultBalance = [Balance, Balance, BalanceLock[], Option<VestingSchedule>];
type Result = [AccountId, BlockNumber, ResultBalance, Index];
type ResultBalance = [VestingInfo | null, (BalanceLock | BalanceLockTo212)[]];
type Result = [DerivedBalancesAccount, BlockNumber, ResultBalance];
function calcBalances (api: ApiInterfaceRx, [accountId, bestNumber, [freeBalance, reservedBalance, locks, vesting], accountNonce]: Result): DerivedBalances {
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DerivedBalancesAll {
let lockedBalance = createType(api.registry, 'Balance');
let lockedBreakdown: BalanceLock[] = [];
let lockedBreakdown: (BalanceLock | BalanceLockTo212)[] = [];
if (Array.isArray(locks)) {
// only get the locks that are valid until passed the current block
lockedBreakdown = locks.filter(({ until }): boolean => bestNumber && until.gt(bestNumber));
lockedBreakdown = (locks as BalanceLockTo212[]).filter(({ until }): boolean => !until || (bestNumber && until.gt(bestNumber)));
const notAll = lockedBreakdown.filter(({ amount }): boolean => !amount.isMax());
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
if (lockedBreakdown.length) {
lockedBalance = createType(api.registry, 'Balance', bnMax(...lockedBreakdown.map(({ amount }): Balance => amount)));
if (notAll.length) {
lockedBalance = createType(api.registry, 'Balance', bnMax(...notAll.map(({ amount }): Balance => amount)));
}
}
// Calculate the vesting balances,
// - offset = balance locked at genesis,
// - offset = balance locked at startingBlock
// - perBlock is the unlock amount
const { offset: vestingTotal, perBlock } = vesting.unwrapOr(createType(api.registry, 'VestingSchedule'));
const vestedBalance = createType(api.registry, 'Balance', perBlock.mul(bestNumber));
const isVesting = vestedBalance.lt(vestingTotal);
const { locked: vestingTotal, perBlock, startingBlock } = vesting || createType(api.registry, 'VestingInfo');
const isStarted = bestNumber.gt(startingBlock);
const vestedBalance = createType(api.registry, 'Balance', isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : 0);
const isVesting = isStarted && vestedBalance.lt(vestingTotal);
// The available balance & vested has an interplay here
// "
@@ -54,23 +57,56 @@ function calcBalances (api: ApiInterfaceRx, [accountId, bestNumber, [freeBalance
accountNonce,
availableBalance,
freeBalance,
frozenFee,
frozenMisc,
isVesting,
lockedBalance,
lockedBreakdown,
reservedBalance,
vestedBalance,
vestingTotal,
votingBalance: createType(api.registry, 'Balance', freeBalance.add(reservedBalance))
votingBalance
};
}
function queryBalances (api: ApiInterfaceRx, accountId: AccountId): Observable<ResultBalance> {
return api.queryMulti<[Balance, Balance, Vec<BalanceLock>, Option<VestingSchedule>]>([
[api.query.balances.freeBalance, accountId],
[api.query.balances.reservedBalance, accountId],
// old
function queryOld (api: ApiInterfaceRx, accountId: AccountId): Observable<ResultBalance> {
return api.queryMulti<[Vec<BalanceLock>, Option<VestingSchedule>]>([
[api.query.balances.locks, accountId],
[api.query.balances.vesting, accountId]
]);
]).pipe(
map(([locks, optVesting]): ResultBalance => {
let vestingNew = null;
if (optVesting.isSome) {
const { offset: locked, perBlock, startingBlock } = optVesting.unwrap();
vestingNew = createType(api.registry, 'VestingInfo', { locked, perBlock, startingBlock });
}
return [vestingNew, locks];
})
);
}
// current (balances vesting)
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<ResultBalance> {
return (
api.query.vesting.vesting
? api.queryMulti<[Vec<BalanceLock>, Option<VestingInfo>]>([
[api.query.balances.locks, accountId],
[api.query.vesting.vesting, accountId]
])
: api.query.balances.locks(accountId).pipe(
map((locks): [Vec<BalanceLock>, Option<VestingInfo>] =>
[locks, createType(api.registry, 'Option<VestingInfo>')]
)
)
).pipe(
map(([locks, optVesting]): ResultBalance =>
[optVesting.unwrapOr(null), locks]
)
);
}
/**
@@ -88,25 +124,21 @@ function queryBalances (api: ApiInterfaceRx, accountId: AccountId): Observable<R
* });
* ```
*/
export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DerivedBalances> {
return memo((address: AccountIndex | AccountId | Address | string): Observable<DerivedBalances> =>
api.derive.accounts.info(address).pipe(
switchMap(({ accountId }): Observable<Result> =>
(accountId
export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DerivedBalancesAll> {
return memo((address: AccountIndex | AccountId | Address | string): Observable<DerivedBalancesAll> =>
api.derive.balances.account(address).pipe(
switchMap((account): Observable<Result> =>
(!account.accountId.isEmpty
? combineLatest([
of(accountId),
of(account),
api.derive.chain.bestNumber(),
queryBalances(api, accountId),
// FIXME This is having issues with Kusama, only use accountNonce atm
// api.rpc.account && api.rpc.account.nextIndex
// ? api.rpc.account.nextIndex(accountId)
// // otherwise we end up with this: type 'Codec | Index' is not assignable to type 'Index'.
// : api.query.system.accountNonce<Index>(accountId)
api.query.system.accountNonce<Index>(accountId)
api.query.balances.account
? queryCurrent(api, account.accountId)
: queryOld(api, account.accountId)
])
: of([createType(api.registry, 'AccountId'), createType(api.registry, 'BlockNumber'), [createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), createType(api.registry, 'Vec<BalanceLock>'), createType(api.registry, 'Option<VestingSchedule>', null)], createType(api.registry, 'Index')])
: of([account, createType(api.registry, 'BlockNumber'), [null, createType(api.registry, 'Vec<BalanceLock>')]])
)
),
map((result): DerivedBalances => calcBalances(api, result))
map((result): DerivedBalancesAll => calcBalances(api, result))
));
}
+11 -26
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -8,33 +8,22 @@ import { DerivedFees } from '../types';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { createType } from '@polkadot/types';
import { memo } from '../util';
type Result = [Balance, Balance, Balance, Balance, Balance];
function queryV2 (api: ApiInterfaceRx): Observable<Result> {
const paymentBase = api.consts.transactionPayment || api.consts.balances;
function query (api: ApiInterfaceRx): Observable<Result> {
return of([
// get values from api.const for substrate versions post spec_version: 101
// https://github.com/paritytech/substrate/pull/2883/files#diff-5e5e1c3aec9ddfde0a9054d062ab3db9R131
api.consts.balances.creationFee,
api.consts.balances.existentialDeposit,
api.consts.balances.transferFee,
paymentBase.transactionBaseFee as Balance,
paymentBase.transactionByteFee as Balance
]);
}
// deprecated - remove
(api.consts.balances.creationFee as Balance) || createType(api.registry, 'Balance'),
(api.consts.balances.transferFee as Balance) || createType(api.registry, 'Balance'),
function queryV1 (api: ApiInterfaceRx): Observable<Result> {
return api.queryMulti<Result>([
// Support older versions and get values from storage
api.query.balances.creationFee,
api.query.balances.existentialDeposit,
api.query.balances.transferFee,
api.query.balances.transactionBaseFee,
api.query.balances.transactionByteFee
// current
api.consts.balances.existentialDeposit,
api.consts.transactionPayment.transactionBaseFee,
api.consts.transactionPayment.transactionByteFee
]);
}
@@ -52,13 +41,9 @@ function queryV1 (api: ApiInterfaceRx): Observable<Result> {
* ```
*/
export function fees (api: ApiInterfaceRx): () => Observable<DerivedFees> {
const query = api.consts.balances
? queryV2
: queryV1;
return memo((): Observable<DerivedFees> =>
query(api).pipe(
map(([creationFee, existentialDeposit, transferFee, transactionBaseFee, transactionByteFee]): DerivedFees => ({
map(([creationFee, transferFee, existentialDeposit, transactionBaseFee, transactionByteFee]): DerivedFees => ({
creationFee,
existentialDeposit,
transactionBaseFee,
+2 -2
View File
@@ -1,12 +1,12 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { all } from './all';
export * from './account';
export * from './fees';
export * from './votingBalances';
export * from './votingBalancesNominatorsFor';
const votingBalance = all;
@@ -1,22 +1,22 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
import { DerivedBalances } from '../types';
import { DerivedBalancesAccount } from '../types';
import { combineLatest, Observable, of } from 'rxjs';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
export function votingBalances (api: ApiInterfaceRx): (addresses?: (AccountId | AccountIndex | Address | string)[]) => Observable<DerivedBalances[]> {
return memo((addresses?: (AccountId | AccountIndex | Address | string)[]): Observable<DerivedBalances[]> =>
export function votingBalances (api: ApiInterfaceRx): (addresses?: (AccountId | AccountIndex | Address | string)[]) => Observable<DerivedBalancesAccount[]> {
return memo((addresses?: (AccountId | AccountIndex | Address | string)[]): Observable<DerivedBalancesAccount[]> =>
!addresses || !addresses.length
? of([] as DerivedBalances[])
? of([] as DerivedBalancesAccount[])
: combineLatest(
addresses.map((accountId): Observable<DerivedBalances> =>
api.derive.balances.all(accountId))
addresses.map((accountId): Observable<DerivedBalancesAccount> =>
api.derive.balances.account(accountId))
)
);
}
@@ -1,27 +0,0 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
import { DerivedBalances } from '../types';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Vec } from '@polkadot/types';
import { memo } from '../util';
export function votingBalancesNominatorsFor (api: ApiInterfaceRx): (address: AccountId | AccountIndex | Address | string) => Observable<DerivedBalances[]> {
return memo((address: AccountId | AccountIndex | Address | string): Observable<DerivedBalances[]> =>
api.derive.accounts.info(address).pipe(
switchMap(({ accountId }): Observable<AccountId[]> =>
accountId
? api.query.staking.nominatorsFor<Vec<AccountId>>(accountId)
: of([] as AccountId[])
),
switchMap((accounts): Observable<DerivedBalances[]> =>
api.derive.balances.votingBalances(accounts)
)
));
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,10 +1,10 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Observable, combineLatest } from 'rxjs';
import { Observable, combineLatest, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { HeaderExtended } from '../type';
@@ -27,9 +27,11 @@ export function subscribeNewHeads (api: ApiInterfaceRx): () => Observable<Header
return memo((): Observable<HeaderExtended> =>
combineLatest([
api.rpc.chain.subscribeNewHeads(),
api.derive.staking.validators()
api.query.session
? api.query.session.validators()
: of([])
]).pipe(
map(([header, { validators }]): HeaderExtended =>
map(([header, validators]): HeaderExtended =>
new HeaderExtended(api.registry, header, validators)
)
));
@@ -0,0 +1,5 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './proposals';
@@ -0,0 +1,43 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Hash, Proposal, Votes } from '@polkadot/types/interfaces';
import { DerivedCollectiveProposal } from '../types';
import { combineLatest, Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types';
type Result = [Hash[], Option<Proposal>[], Option<Votes>[]];
export function proposals (api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DerivedCollectiveProposal[]> {
return (): Observable<DerivedCollectiveProposal[]> =>
api.query[section]
? api.query[section].proposals().pipe(
switchMap((hashes: Hash[]): Observable<Result> =>
hashes.length
? combineLatest([
of(hashes),
api.query[section].proposalOf.multi<Option<Proposal>>(hashes),
api.query[section].voting.multi<Option<Votes>>(hashes)
])
: of([[], [], []])
),
map(([hashes, proposals, votes]: Result): DerivedCollectiveProposal[] =>
proposals
.map((proposalOpt, index): DerivedCollectiveProposal | null =>
proposalOpt.isSome
? {
hash: hashes[index],
proposal: proposalOpt.unwrap(),
votes: votes[index].unwrapOr(null)
}
: null
)
.filter((proposal): boolean => !!proposal) as DerivedCollectiveProposal[]
)
)
: of([] as DerivedCollectiveProposal[]);
}
+21 -35
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -8,42 +8,27 @@ import { DerivedContractFees } from '../types';
import BN from 'bn.js';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { createType } from '@polkadot/types';
import { memo } from '../util';
type ResultV2 = [BN, BN, BN, BN, BN, BN, BN, BN, BN, BN];
const ZERO = new BN(0);
// parse the result
function parseResult ([callBaseFee, contractFee, createBaseFee, creationFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee, transferFee]: ResultV2): DerivedContractFees {
return {
callBaseFee,
contractFee,
createBaseFee,
creationFee,
rentByteFee,
rentDepositOffset,
tombstoneDeposit,
transactionBaseFee,
transactionByteFee,
transferFee
};
}
type ResultV2 = [BN, BN, BN, BN, BN, BN, BN, BN, BN];
// query via constants (current applicable path)
function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
return of([
// deprecated
api.consts.contracts.creationFee || createType(api.registry, 'Balance'),
api.consts.contracts.transferFee || createType(api.registry, 'Balance'),
// current
api.consts.contracts.callBaseFee,
api.consts.contracts.contractFee,
api.consts.contracts.createBaseFee,
api.consts.contracts.creationFee,
api.consts.contracts.rentByteFee,
api.consts.contracts.rentDepositOffset,
api.consts.contracts.tombstoneDeposit,
api.consts.contracts.transactionBaseFee,
api.consts.contracts.transactionByteFee,
api.consts.contracts.transferFee
api.consts.contracts.transactionByteFee
]) as unknown as Observable<ResultV2>;
}
@@ -62,17 +47,18 @@ function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
*/
export function fees (api: ApiInterfaceRx): () => Observable<DerivedContractFees> {
return memo((): Observable<DerivedContractFees> => {
return (
api.consts.contracts
? queryConstants(api)
: of([ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO])
).pipe(
map(([callBaseFee, contractFee, createBaseFee, creationFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee, transferFee]): DerivedContractFees =>
// We've done this on purpose, i.e. so we can just copy the name/order from the parse above and see gaps
parseResult([
callBaseFee, contractFee, createBaseFee, creationFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee, transferFee
])
)
return queryConstants(api).pipe(
map(([creationFee, transferFee, callBaseFee, contractFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee]): DerivedContractFees => ({
callBaseFee,
contractFee,
creationFee,
rentByteFee,
rentDepositOffset,
tombstoneDeposit,
transactionBaseFee,
transactionByteFee,
transferFee
}))
);
});
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+6 -40
View File
@@ -1,48 +1,14 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Hash, Proposal, Votes } from '@polkadot/types/interfaces';
import { DerivedCouncilProposals } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types';
import { DerivedCollectiveProposals } from '../types';
import { Observable } from 'rxjs';
import { proposals as collectiveProposals } from '../collective';
import { memo } from '../util';
function retrieveProposals (api: ApiInterfaceRx, hashes: Hash[]): Observable<DerivedCouncilProposals> {
return combineLatest([
api.query.council.proposalOf.multi<Option<Proposal>>(hashes),
api.query.council.voting.multi<Option<Votes>>(hashes)
]).pipe(
map(([proposals, votes]: [Option<Proposal>[], Option<Votes>[]]): DerivedCouncilProposals => {
const result: DerivedCouncilProposals = [];
proposals.forEach((proposalOpt, index): void => {
if (proposalOpt.isSome) {
result.push({
hash: hashes[index],
proposal: proposalOpt.unwrap(),
votes: votes[index].unwrapOr(null)
});
}
});
return result;
})
);
}
export function proposals (api: ApiInterfaceRx): () => Observable<DerivedCouncilProposals> {
return memo((): Observable<DerivedCouncilProposals> =>
api.query.council
? api.query.council.proposals().pipe(
switchMap((proposals: Hash[]): Observable<DerivedCouncilProposals> =>
retrieveProposals(api, proposals)
)
)
: of([] as DerivedCouncilProposals)
);
export function proposals (api: ApiInterfaceRx): () => Observable<DerivedCollectiveProposals> {
return memo(collectiveProposals(api, 'council'));
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+27 -19
View File
@@ -1,8 +1,8 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, Balance, BlockNumber, Hash, PropIndex } from '@polkadot/types/interfaces';
import { AccountId, Balance, BlockNumber, Hash, PropIndex, Proposal } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveProposal } from '../types';
@@ -27,11 +27,21 @@ interface Result {
function parse (api: ApiInterfaceRx, { depositors, proposals, preimages }: Result): DeriveProposal[] {
return proposals
.filter(([, , proposer], index): boolean =>
!!(preimages[index]?.isSome) && !!(depositors[index]?.isSome) && !proposer.isEmpty
!!(depositors[index]?.isSome) && !proposer.isEmpty
)
.map(([propIndex, hash, proposer], index): DeriveProposal => {
const preimage = preimages[index].unwrapOr(null);
const depositor = depositors[index].unwrap();
let proposal: undefined | Proposal;
// we could end up in a situation where the proposal is non-decodable, e.g. after an upgrade
if (preimage) {
try {
proposal = createType(api.registry, 'Proposal', preimage[0].toU8a(true));
} catch (error) {
console.error(error);
}
}
return {
balance: depositor[0],
@@ -44,9 +54,7 @@ function parse (api: ApiInterfaceRx, { depositors, proposals, preimages }: Resul
proposer: preimage[1]
}
: undefined,
proposal: preimage
? createType(api.registry, 'Proposal', preimage[0].toU8a(true))
: undefined,
proposal,
proposer,
seconds: depositor[1]
};
@@ -56,20 +64,20 @@ function parse (api: ApiInterfaceRx, { depositors, proposals, preimages }: Resul
export function proposals (api: ApiInterfaceRx): () => Observable<DeriveProposal[]> {
return memo((): Observable<DeriveProposal[]> =>
api.query.democracy?.publicProps
? api.query.democracy
.publicProps<Proposals>()
.pipe(
switchMap((proposals) =>
combineLatest([
of(proposals),
api.query.democracy.preimages.multi<PreImage>(proposals.map(([, hash]): Hash => hash)),
api.query.democracy.depositOf.multi<Depositors>(proposals.map(([index]): PropIndex => index))
])
),
map(([proposals, preimages, depositors]): DeriveProposal[] =>
parse(api, { depositors, proposals, preimages })
)
? api.query.democracy.publicProps<Proposals>().pipe(
switchMap((proposals) =>
combineLatest([
of(proposals),
api.query.democracy.preimages.multi<PreImage>(
proposals.map(([, hash]): Hash => hash)),
api.query.democracy.depositOf.multi<Depositors>(
proposals.map(([index]): PropIndex => index))
])
),
map(([proposals, preimages, depositors]): DeriveProposal[] =>
parse(api, { depositors, proposals, preimages })
)
)
: of([] as DeriveProposal[])
);
}
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -9,7 +9,7 @@ import BN from 'bn.js';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, Vec } from '@polkadot/types';
import { Option } from '@polkadot/types';
import { memo } from '../util';
import { retrieveInfo } from './referendumInfo';
@@ -17,9 +17,9 @@ import { retrieveInfo } from './referendumInfo';
export function referendumInfos (api: ApiInterfaceRx): (ids?: (BN | number)[]) => Observable<DerivedReferendum[]> {
return memo((ids: (BN | number)[] = []): Observable<DerivedReferendum[]> =>
(
!ids || !ids.length
!ids?.length
? of([] as Option<ReferendumInfo>[])
: api.query.democracy.referendumInfoOf.multi(ids) as Observable<Vec<Option<ReferendumInfo>>>
: api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo>>(ids)
).pipe(
switchMap((infos): Observable<(DerivedReferendum | null)[]> =>
combineLatest(
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -10,16 +10,16 @@ import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Vec, createType } from '@polkadot/types';
import { DerivedBalances, DerivedReferendumVote } from '../types';
import { DerivedBalancesAccount, DerivedReferendumVote } from '../types';
import { memo } from '../util';
export function referendumVotesFor (api: ApiInterfaceRx): (referendumId: BN | number) => Observable<DerivedReferendumVote[]> {
return memo((referendumId: BN | number): Observable<DerivedReferendumVote[]> =>
api.query.democracy.votersFor<Vec<AccountId>>(referendumId).pipe(
switchMap((votersFor): Observable<[Vec<AccountId>, Vote[], DerivedBalances[]]> =>
switchMap((votersFor): Observable<[Vec<AccountId>, Vote[], DerivedBalancesAccount[]]> =>
combineLatest([
of(votersFor),
api.derive.democracy.votes(referendumId as BN, votersFor),
api.derive.democracy.votes(referendumId, votersFor),
api.derive.balances.votingBalances(votersFor)
])
),
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -14,10 +14,9 @@ import { memo } from '../util';
export function referendums (api: ApiInterfaceRx): () => Observable<DerivedReferendum[]> {
return memo((): Observable<DerivedReferendum[]> =>
// V2 vs V1 (and early V2)
api.query.democracy?.lowestUnbaked || api.query.democracy?.nextTally
api.query.democracy?.lowestUnbaked
? api.queryMulti<[ReferendumIndex, ReferendumIndex]>([
api.query.democracy.lowestUnbaked || api.query.democracy.nextTally,
api.query.democracy.lowestUnbaked,
api.query.democracy.referendumCount
]).pipe(
switchMap(([earliest, referendumCount]): Observable<DerivedReferendum[]> =>
+4 -4
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -10,12 +10,12 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
export function votes (api: ApiInterfaceRx): (referendumId: BN, accountIds?: AccountId[]) => Observable<Vote[]> {
return memo((referendumId: BN, accountIds: AccountId[] = []): Observable<Vote[]> =>
export function votes (api: ApiInterfaceRx): (referendumId: BN | number, accountIds?: AccountId[]) => Observable<Vote[]> {
return memo((referendumId: BN | number, accountIds: AccountId[] = []): Observable<Vote[]> =>
!accountIds || !accountIds.length
? of([] as Vote[])
: api.query.democracy.voteOf.multi<Vote>(
accountIds.map((accountId): [BN, AccountId] =>
accountIds.map((accountId): [BN | number, AccountId] =>
[referendumId, accountId]
)
)
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+20 -28
View File
@@ -1,11 +1,11 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, Balance, BlockNumber } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { Observable, combineLatest } from 'rxjs';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { createType, Vec, u32 } from '@polkadot/types';
@@ -13,39 +13,31 @@ import { createType, Vec, u32 } from '@polkadot/types';
import { DerivedElectionsInfo } from '../types';
import { memo } from '../util';
function deriveElections (api: ApiInterfaceRx, candidates: AccountId[], members: [AccountId, Balance][], runnersUp: [AccountId, Balance][], candidacyBond: Balance, desiredSeats: u32, termDuration: BlockNumber, votingBond: Balance): DerivedElectionsInfo {
return {
candidates,
candidateCount: createType(api.registry, 'u32', candidates.length),
candidacyBond,
desiredSeats,
members: members.sort((a, b): number => b[1].cmp(a[1])),
runnersUp: runnersUp.sort((a, b): number => b[1].cmp(a[1])),
termDuration,
votingBond
};
function sortAccounts ([, balanceA]: ITuple<[AccountId, Balance]>, [, balanceB]: ITuple<[AccountId, Balance]>): number {
return balanceB.cmp(balanceA);
}
function queryElections (api: ApiInterfaceRx): Observable<DerivedElectionsInfo> {
const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
// NOTE We have an issue where candidates can return `null` for an empty array, hence
// we are not using multi queries here, so empty array is empty (instead of space-filled)
return combineLatest([
api.query[section].candidates<Vec<AccountId>>(),
api.query[section].members<Vec<ITuple<[AccountId, Balance]>>>(),
api.query[section].runnersUp<Vec<ITuple<[AccountId, Balance]>>>()
return api.queryMulti<[Vec<AccountId>, Vec<AccountId>, Vec<ITuple<[AccountId, Balance]>>, Vec<ITuple<[AccountId, Balance]>>]>([
api.query.council.members,
api.query[section].candidates,
api.query[section].members,
api.query[section].runnersUp
]).pipe(
map(([candidates, members, runnersUp]): DerivedElectionsInfo => deriveElections(
api,
map(([councilMembers, candidates, members, runnersUp]): DerivedElectionsInfo => ({
candidates,
members,
runnersUp,
api.consts[section].candidacyBond as Balance,
api.consts[section].desiredMembers as u32,
api.consts[section].termDuration as BlockNumber,
api.consts[section].votingBond as Balance
))
candidateCount: createType(api.registry, 'u32', candidates.length),
candidacyBond: api.consts[section].candidacyBond as Balance,
desiredSeats: api.consts[section].desiredMembers as u32,
members: members.length
? members.sort(sortAccounts)
: councilMembers.map((accountId): [AccountId, Balance] => [accountId, createType(api.registry, 'Balance')]),
runnersUp: runnersUp.sort(sortAccounts),
termDuration: api.consts[section].termDuration as BlockNumber,
votingBond: api.consts[section].votingBond as Balance
}))
);
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -17,13 +17,15 @@ import { memo } from '../util';
*/
export function receivedHeartbeats (api: ApiInterfaceRx): () => Observable<DerivedHeartbeats> {
return memo((): Observable<DerivedHeartbeats> =>
api.query.imOnline?.receivedHeartbeats && api.query.imOnline.authoredBlocks
api.query.imOnline?.receivedHeartbeats
? api.derive.staking.overview().pipe(
switchMap(({ currentIndex, validators }): Observable<[AccountId[], Option<Bytes>[], u32[]]> =>
combineLatest([
of(validators),
api.query.imOnline.receivedHeartbeats.multi<Option<Bytes>>(validators.map((_address, index): [SessionIndex, number] => [currentIndex, index])),
api.query.imOnline.authoredBlocks.multi<u32>(validators.map((address): [SessionIndex, AccountId] => [currentIndex, address]))
api.query.imOnline.receivedHeartbeats.multi<Option<Bytes>>(
validators.map((_address, index): [SessionIndex, number] => [currentIndex, index])),
api.query.imOnline.authoredBlocks.multi<u32>(
validators.map((address): [SessionIndex, AccountId] => [currentIndex, address]))
])
),
map(([validators, heartbeats, numBlocks]): DerivedHeartbeats =>
+1 -3
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -45,7 +45,6 @@ describe('derive', (): void => {
testFunction(api)('balances', 'fees', []);
testFunction(api)('balances', 'votingBalance', []);
testFunction(api)('balances', 'votingBalances', []);
testFunction(api)('balances', 'votingBalancesNominatorsFor', []);
testFunction(api)('chain', 'bestNumber', []);
testFunction(api)('chain', 'bestNumberFinalized', []);
@@ -62,7 +61,6 @@ describe('derive', (): void => {
testFunction(api)('session', 'sessionProgress', []);
testFunction(api)('staking', 'account', []);
testFunction(api)('staking', 'recentlyOffline', []);
testFunction(api)('staking', 'controllers', []);
});
+28 -4
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -16,11 +16,15 @@ import * as democracy from './democracy';
import * as elections from './elections';
import * as imOnline from './imOnline';
import * as session from './session';
import * as society from './society';
import * as staking from './staking';
import * as technicalCommittee from './technicalCommittee';
import * as treasury from './treasury';
export * from './type';
export const derive = { accounts, balances, chain, contracts, council, democracy, elections, imOnline, session, society, staking, technicalCommittee, treasury };
type DeriveSection<Section> = {
[Method in keyof Section]: Section[Method] extends AnyFunction
? ReturnType<Section[Method]> // ReturnType<Section[Method]> will be the inner function, i.e. without (api) argument
@@ -32,13 +36,35 @@ type DeriveAllSections<AllSections> = {
export type DeriveCustom = Record<string, Record<string, (api: ApiInterfaceRx) => (...args: any[]) => Observable<any>>>;
export type ExactDerive = DeriveAllSections<typeof derive>;
// Enable derive only if some of these modules are available
const deriveAvail: Record<string, string[]> = {
contracts: ['contracts'],
council: ['council'],
democracy: ['democracy'],
elections: ['electionsPhragmen', 'elections'],
imOnline: ['imOnline'],
session: ['session'],
society: ['society'],
staking: ['staking'],
technicalCommittee: ['technicalCommittee'],
treasury: ['treasury']
};
/**
* Returns an object that will inject `api` into all the functions inside
* `allSections`, and keep the object architecture of `allSections`.
*/
/** @internal */
function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSections): DeriveAllSections<AllSections> {
const queryKeys = Object.keys(api.query);
return Object
.keys(allSections)
.filter((sectionName): boolean =>
!deriveAvail[sectionName] || deriveAvail[sectionName].some((query): boolean => queryKeys.includes(query))
)
.reduce((deriveAcc, sectionName): DeriveAllSections<AllSections> => {
const section = allSections[sectionName as keyof AllSections];
@@ -58,11 +84,9 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
}, {} as DeriveAllSections<AllSections>);
}
export const derive = { accounts, balances, chain, contracts, council, democracy, elections, imOnline, session, staking, treasury };
export type ExactDerive = DeriveAllSections<typeof derive>;
// FIXME The return type of this function should be {...ExactDerive, ...DeriveCustom}
// For now we just drop the custom derive typings
/** @internal */
export default function decorateDerive (api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
return {
...injectFunctions(api, derive),
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+6 -53
View File
@@ -1,51 +1,21 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BlockNumber, SessionIndex } from '@polkadot/types/interfaces';
import { SessionIndex } from '@polkadot/types/interfaces';
import { DerivedSessionInfo, DeriveSessionIndexes } from '../types';
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, u64, createType } from '@polkadot/types';
import { u64, createType } from '@polkadot/types';
import { memo } from '../util';
type ResultV1Session = [Option<BlockNumber>, BlockNumber, BlockNumber, SessionIndex];
type ResultV1 = [BlockNumber, DeriveSessionIndexes, ResultV1Session];
type ResultSlots = [u64, u64, u64, SessionIndex];
type ResultType = [boolean, u64, SessionIndex];
type Result = [ResultType, DeriveSessionIndexes, ResultSlots];
// internal helper to just split the logic - take all inputs, do the calculations and combine
function createDerivedV1 (api: ApiInterfaceRx, [bestNumber, { currentIndex, validatorCount }, [_lastLengthChange, sessionLength, lastEraLengthChange, sessionsPerEra]]: ResultV1): DerivedSessionInfo {
const lastLengthChange = _lastLengthChange?.unwrapOr(null) || createType(api.registry, 'BlockNumber');
const sessionProgress = bestNumber
.sub(lastLengthChange)
.add(sessionLength)
.mod(sessionLength);
const currentEra = currentIndex
.sub(lastEraLengthChange)
.mod(sessionsPerEra);
const eraProgress = currentEra
.mul(sessionLength)
.add(sessionProgress);
return {
currentEra: createType(api.registry, 'EraIndex', currentEra),
currentIndex,
eraLength: createType(api.registry, 'BlockNumber', sessionLength.mul(sessionsPerEra)),
eraProgress: createType(api.registry, 'BlockNumber', eraProgress),
isEpoch: false,
sessionLength,
sessionsPerEra,
sessionProgress: createType(api.registry, 'BlockNumber', sessionProgress),
validatorCount
};
}
function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, sessionsPerEra], { currentIndex, currentEra, validatorCount }, [currentSlot, epochIndex, epochOrGenesisStartSlot, currentEraStartSessionIndex]]: Result): DerivedSessionInfo {
const epochStartSlot = epochIndex.mul(epochDuration).add(epochOrGenesisStartSlot);
const sessionProgress = currentSlot.sub(epochStartSlot);
@@ -64,21 +34,6 @@ function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, ses
};
}
function infoV1 (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
return combineLatest([
api.derive.chain.bestNumber(),
api.derive.session.indexes(),
api.queryMulti<ResultV1Session>([
api.query.session.lastLengthChange,
api.query.session.sessionLength,
api.query.staking.lastEraLengthChange,
api.query.staking.sessionsPerEra
])
]).pipe(
map((result): DerivedSessionInfo => createDerivedV1(api, result))
);
}
function infoLatestAura (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
return api.derive.session.indexes().pipe(
map((indexes): DerivedSessionInfo =>
@@ -115,11 +70,9 @@ function infoLatestBabe (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
* @description Retrieves all the session and era info and calculates specific values on it as the length of the session and eras
*/
export function info (api: ApiInterfaceRx): () => Observable<DerivedSessionInfo> {
const query = api.consts.timestamp || api.consts.babe || api.consts.aura
? api.consts.babe
? infoLatestBabe // 2.x with Babe
: infoLatestAura // 2.x with Aura (not all info there)
: infoV1;
const query = api.consts.babe
? infoLatestBabe // 2.x with Babe
: infoLatestAura; // 2.x with Aura (not all info there)
return memo((): Observable<DerivedSessionInfo> =>
query(api));
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -0,0 +1,42 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, BalanceOf, Bid, BidKind } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveSocietyCandidate } from '../types';
import { combineLatest, of, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option, Vec } from '@polkadot/types';
import { memo } from '../util';
type ResultSuspend = Option<ITuple<[BalanceOf, BidKind]>>;
type Result = [Bid[], ResultSuspend[]]
/**
* @description Get the candidate info for a society
*/
export function candidates (api: ApiInterfaceRx): () => Observable<DeriveSocietyCandidate[]> {
return memo((): Observable<DeriveSocietyCandidate[]> =>
api.query.society.candidates<Vec<Bid>>().pipe(
switchMap((candidates: Vec<Bid>): Observable<Result> =>
combineLatest([
of(candidates),
api.query.society.suspendedCandidates.multi<ResultSuspend>(
candidates.map(({ who }): AccountId => who))
])
),
map(([candidates, suspended]: Result): DeriveSocietyCandidate[] =>
candidates.map(({ who, kind, value }, index) => ({
accountId: who,
isSuspended: suspended[index].isSome,
kind,
value
}))
)
)
);
}
+8
View File
@@ -0,0 +1,8 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './candidates';
export * from './info';
export * from './member';
export * from './members';
+41
View File
@@ -0,0 +1,41 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, BalanceOf, Bid } from '@polkadot/types/interfaces';
import { DeriveSociety } from '../types';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Option, Vec, u32 } from '@polkadot/types';
import { memo } from '../util';
type Result = [Vec<Bid>, Option<AccountId>, Option<AccountId>, Option<AccountId>, u32, BalanceOf]
/**
* @description Get the overall info for a society
*/
export function info (api: ApiInterfaceRx): () => Observable<DeriveSociety> {
return memo((): Observable<DeriveSociety> =>
api.queryMulti<Result>([
api.query.society.bids,
api.query.society.defender,
api.query.society.founder,
api.query.society.head,
api.query.society.maxMembers,
api.query.society.pot
]).pipe(
map(([bids, defender, founder, head, maxMembers, pot]: Result): DeriveSociety => ({
bids,
defender: defender.unwrapOr(undefined),
hasDefender: (defender.isSome && head.isSome && !head.eq(defender)) || false,
head: head.unwrapOr(undefined),
founder: founder.unwrapOr(undefined),
maxMembers,
pot
}))
)
);
}
+40
View File
@@ -0,0 +1,40 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, Balance, BlockNumber, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveSocietyMember } from '../types';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { bool, Option, Vec } from '@polkadot/types';
import { memo } from '../util';
type Result = [Vec<ITuple<[BlockNumber, Balance]>>, StrikeCount, Option<SocietyVote>, bool, Option<VouchingStatus>];
/**
* @description Get the member info for a society
*/
export function member (api: ApiInterfaceRx): (accountId: AccountId) => Observable<DeriveSocietyMember> {
return memo((accountId: AccountId): Observable<DeriveSocietyMember> =>
api.queryMulti<Result>([
[api.query.society.payouts, accountId],
[api.query.society.strikes, accountId],
[api.query.society.defenderVotes, accountId],
[api.query.society.suspendedMembers, accountId],
[api.query.society.vouching, accountId]
]).pipe(
map(([payouts, strikes, defenderVote, suspended, vouching]: Result): DeriveSocietyMember => ({
accountId,
payouts,
isSuspended: suspended.isTrue,
strikes,
vote: defenderVote.unwrapOr(undefined),
vouching: vouching.unwrapOr(undefined)
}))
)
);
}
@@ -0,0 +1,27 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId } from '@polkadot/types/interfaces';
import { DeriveSocietyMember } from '../types';
import { combineLatest, Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { memo } from '../util';
/**
* @description Get the member info for a society
*/
export function members (api: ApiInterfaceRx): () => Observable<DeriveSocietyMember[]> {
return memo((): Observable<DeriveSocietyMember[]> =>
api.query.society.members<AccountId[]>().pipe(
switchMap((members): Observable<DeriveSocietyMember[]> =>
combineLatest(members.map((accountId): Observable<DeriveSocietyMember> =>
api.derive.society.member(accountId)
))
)
)
);
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -2
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -7,5 +7,4 @@ export * from './controllers';
export * from './electedInfo';
export * from './overview';
export * from './query';
export * from './recentlyOffline';
export * from './validators';
+10 -28
View File
@@ -1,29 +1,25 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, Exposure, Keys, RewardDestination, ValidatorPrefs } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { AccountId, Exposure, Keys, Nominations, RewardDestination, ValidatorPrefs } from '@polkadot/types/interfaces';
import { DerivedStakingStash } from '../types';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Option, Vec } from '@polkadot/types';
import { Option } from '@polkadot/types';
import { memo } from '../util';
// NOTE Unused ATM, preparing for V2-only
type Result = [Option<AccountId>, Nominations, RewardDestination, Exposure, ValidatorPrefs, Option<Keys>];
type Result = [Option<AccountId>, [Vec<AccountId>], RewardDestination, Exposure, ValidatorPrefs, Option<Keys>?];
type ResultV1 = [Option<AccountId>, ITuple<[Vec<AccountId>]>, RewardDestination, Exposure, ValidatorPrefs];
type ResultV2 = [Option<AccountId>, ITuple<[Vec<AccountId>]>, RewardDestination, Exposure, ValidatorPrefs, Option<Keys>];
function parse (stashId: AccountId, [_controllerId, [nominators], rewardDestination, stakers, validatorPrefs, _nextKeys]: Result): DerivedStakingStash {
function parse (stashId: AccountId, [_controllerId, nominators, rewardDestination, stakers, validatorPrefs, _nextKeys]: Result): DerivedStakingStash {
return {
controllerId: _controllerId.unwrapOr(undefined),
nextKeys: _nextKeys?.unwrapOr(undefined),
nominators,
nextKeys: _nextKeys.unwrapOr(undefined),
nominators: nominators.targets,
nominateAt: nominators.submittedIn,
rewardDestination,
stakers,
stashId,
@@ -31,18 +27,8 @@ function parse (stashId: AccountId, [_controllerId, [nominators], rewardDestinat
};
}
function retrieveV1 (api: ApiInterfaceRx, stashId: AccountId): Observable<Result> {
return api.queryMulti<ResultV1>([
[api.query.staking.bonded, stashId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.stakers, stashId],
[api.query.staking.validators, stashId]
]);
}
function retrieveV2 (api: ApiInterfaceRx, stashId: AccountId): Observable<Result> {
return api.queryMulti<ResultV2>([
function query (api: ApiInterfaceRx, stashId: AccountId): Observable<Result> {
return api.queryMulti<Result>([
[api.query.staking.bonded, stashId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
@@ -53,10 +39,6 @@ function retrieveV2 (api: ApiInterfaceRx, stashId: AccountId): Observable<Result
}
export function infoStash (api: ApiInterfaceRx): (stashId: AccountId) => Observable<DerivedStakingStash> {
const query = api.consts.session
? retrieveV2
: retrieveV1;
return memo((stashId: AccountId): Observable<DerivedStakingStash> =>
query(api, stashId).pipe(
map((result): DerivedStakingStash => parse(stashId, result))
+2 -6
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -8,7 +8,6 @@ import { DerivedStakingOverview } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { createType } from '@polkadot/types';
import { memo } from '../util';
@@ -24,10 +23,7 @@ export function overview (api: ApiInterfaceRx): () => Observable<DerivedStakingO
switchMap(([{ currentEra, currentIndex, validatorCount }, { currentElected, validators }]) =>
combineLatest([
of({ currentElected, currentEra, currentIndex, validators, validatorCount }),
// this will change on a per block basis, keep it innermost (and it needs eraIndex)
api.query.staking?.currentEraPointsEarned
? api.query.staking.currentEraPointsEarned<EraPoints>(currentEra)
: of(createType(api.registry, 'EraPoints'))
api.query.staking.currentEraPointsEarned<EraPoints>(currentEra)
])
),
map(([{ currentElected, currentEra, currentIndex, validators, validatorCount }, eraPoints]): DerivedStakingOverview => ({
+38 -119
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -13,142 +13,61 @@ import { createType, Option, Vec } from '@polkadot/types';
import { memo } from '../util';
interface ParseInput {
accountId: AccountId;
controllerId: AccountId;
nominators: AccountId[];
rewardDestination: RewardDestination;
queuedKeys?: [AccountId, Keys][];
stakers: Exposure;
stakingLedger: Option<StakingLedger>;
stashId: AccountId;
validatorPrefs: ValidatorPrefs;
nextKeys?: Option<Keys>;
nextKeyFor?: Option<AccountId>;
}
type MultiResultV2 = [Option<AccountId>, Option<ITuple<[Nominations]>>, RewardDestination, Exposure, [ValidatorPrefs], Option<Keys>, Option<StakingLedger>];
function unwrapSessionIds (stashId: AccountId, queuedKeys: Option<AccountId> | [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
// for 2.x we have a Vec<(ValidatorId,Keys)> of the keys
if (Array.isArray(queuedKeys)) {
const sessionIds = (queuedKeys.find(([currentId]): boolean =>
currentId.eq(stashId)
) || [undefined, [] as AccountId[]])[1];
const nextSessionIds = nextKeys.unwrapOr([] as AccountId[]);
return {
nextSessionIds,
sessionIds
};
}
// substrate 1.x
const nextSessionIds = queuedKeys.isSome
? [queuedKeys.unwrap()]
: [];
function unwrapSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
const sessionIds = (queuedKeys.find(([currentId]): boolean =>
currentId.eq(stashId)
) || [undefined, [] as AccountId[]])[1];
const nextSessionIds = nextKeys.unwrapOr([] as AccountId[]);
return {
nextSessionIds,
sessionIds: nextSessionIds
sessionIds
};
}
function parseResult (api: ApiInterfaceRx, { accountId, controllerId, stashId, nextKeyFor, queuedKeys, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs, nextKeys }: ParseInput): DerivedStakingQuery {
const _stakingLedger = stakingLedger.unwrapOr(undefined);
const _nextKeyFor = nextKeyFor || createType(api.registry, 'Option<AccountId>', null);
const _nextKeys = nextKeys || createType(api.registry, 'Option<Keys>', null);
return {
accountId,
controllerId,
nominators,
rewardDestination,
stakers,
stakingLedger: _stakingLedger,
stashId,
validatorPrefs,
...unwrapSessionIds(stashId, queuedKeys || _nextKeyFor, _nextKeys)
};
}
type MultiResultV1 = [Option<AccountId>, Option<StakingLedger>, [Vec<AccountId>], RewardDestination, Exposure, ITuple<[ValidatorPrefs]>];
function retrieveInfoV1 (api: ApiInterfaceRx, accountId: AccountId, stashId: AccountId, controllerId: AccountId): Observable<DerivedStakingQuery> {
return (
api.queryMulti([
[api.query.session.nextKeyFor, controllerId],
[api.query.staking.ledger, controllerId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.stakers, stashId],
[api.query.staking.validators, stashId]
]) as Observable<MultiResultV1>
).pipe(map(([nextKeyFor, stakingLedger, [nominators], rewardDestination, stakers, [validatorPrefs]]: MultiResultV1): DerivedStakingQuery =>
parseResult(api, {
accountId, controllerId, stashId, nextKeyFor, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs
})
));
}
type MultiResultV2 = [[Vec<AccountId>] | Option<ITuple<[Nominations]>>, RewardDestination, Exposure, [ValidatorPrefs], Option<Keys>, Option<StakingLedger>];
function retrieveInfoV2 (api: ApiInterfaceRx, accountId: AccountId, stashId: AccountId, controllerId: AccountId): Observable<DerivedStakingQuery> {
function retrieve (api: ApiInterfaceRx, stashId: AccountId): Observable<[Vec<ITuple<[AccountId, Keys]>>, MultiResultV2]> {
return combineLatest([
api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>(),
api.queryMulti([
[api.query.staking.bonded, stashId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.stakers, stashId],
[api.query.staking.validators, stashId],
[api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]],
[api.query.staking.ledger, controllerId]
[api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]]
]) as Observable<MultiResultV2>
]).pipe(map(([queuedKeys, [_nominators, rewardDestination, stakers, [validatorPrefs], nextKeys, stakingLedger]]: [[AccountId, Keys][], MultiResultV2]): DerivedStakingQuery => {
// if we have staking.storageVersion it indicates the new structure, unwrap as needed
// FIXME We really want to be pulling all the new (valuable) info along
const nominators: AccountId[] = api.query.staking.storageVersion
? (_nominators as Option<ITuple<[Nominations]>>).isSome
? (_nominators as Option<ITuple<[Nominations]>>).unwrap()[0].targets
: []
: (_nominators as [Vec<AccountId>])[0];
return parseResult(api, {
accountId, controllerId, stashId, queuedKeys, stakingLedger, nominators, rewardDestination, stakers, validatorPrefs, nextKeys
});
}));
}
function retrieveV1 (api: ApiInterfaceRx, accountId: AccountId): Observable<DerivedStakingQuery> {
// depending on where we come from, this may be a controller or stash
return combineLatest([
api.query.staking.bonded<Option<AccountId>>(accountId),
api.query.staking.ledger<Option<StakingLedger>>(accountId)
]).pipe(switchMap(([bonded, stakingLedger]): Observable<DerivedStakingQuery> =>
stakingLedger.isSome
? retrieveInfoV1(api, accountId, stakingLedger.unwrap().stash, accountId)
: bonded.isSome
? retrieveInfoV1(api, accountId, accountId, bonded.unwrap())
: of({ accountId: accountId, nextSessionIds: [], sessionIds: [] })
));
}
function retrieveV2 (api: ApiInterfaceRx, stashId: AccountId): Observable<DerivedStakingQuery> {
return api.query.staking
.bonded<Option<AccountId>>(stashId)
.pipe(switchMap((controllerId): Observable<DerivedStakingQuery> =>
controllerId.isSome
? retrieveInfoV2(api, stashId, stashId, controllerId.unwrap())
: of({ accountId: stashId, nextSessionIds: [], sessionIds: [] })
));
]);
}
/**
* @description From a stash, retrieve the controllerId and fill in all the relevant staking details
* @description From a stash, retrieve the controllerId and all relevant details
*/
export function query (api: ApiInterfaceRx): (_accountId: Uint8Array | string) => Observable<DerivedStakingQuery> {
const retrieve = api.consts.session
? retrieveV2
: retrieveV1;
export function query (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DerivedStakingQuery> {
return memo((accountId: Uint8Array | string): Observable<DerivedStakingQuery> => {
const stashId = createType(api.registry, 'AccountId', accountId);
return memo((accountId: Uint8Array | string): Observable<DerivedStakingQuery> =>
retrieve(api, createType(api.registry, 'AccountId', accountId)));
return retrieve(api, stashId).pipe(
switchMap(([queuedKeys, [controllerIdOpt, nominatorsOpt, rewardDestination, stakers, [validatorPrefs], nextKeys]]): Observable<DerivedStakingQuery> => {
const controllerId = controllerIdOpt.unwrapOr(null);
return controllerId
? api.query.staking.ledger(controllerId).pipe(
map((stakingLedgerOpt): DerivedStakingQuery => ({
accountId: stashId,
controllerId,
nominators: nominatorsOpt.unwrapOr([{ targets: [] }])[0].targets,
rewardDestination,
stakers,
stakingLedger: stakingLedgerOpt.unwrapOr(undefined),
stashId,
validatorPrefs,
...unwrapSessionIds(stashId, queuedKeys, nextKeys)
}))
)
: of({ accountId: stashId, nextSessionIds: [], sessionIds: [] });
})
);
});
}
@@ -1,49 +0,0 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, BlockNumber } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DerivedRecentlyOffline } from '../types';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { Vec, u32 } from '@polkadot/types';
import { memo } from '../util';
type OfflineResult = Vec<ITuple<[AccountId, BlockNumber, u32]>>;
function expandDerived (recentlyOffline: OfflineResult): DerivedRecentlyOffline {
return recentlyOffline.reduce((result: DerivedRecentlyOffline, [accountId, blockNumber, count]): DerivedRecentlyOffline => {
const key = accountId.toString();
if (!result[key]) {
result[key] = [];
}
result[key].push({
blockNumber,
count
});
return result;
}, {});
}
/**
* @description Retrieve a keyed record of accounts recently reported to be offline
*/
export function recentlyOffline (api: ApiInterfaceRx): () => Observable<DerivedRecentlyOffline> {
return memo((): Observable<DerivedRecentlyOffline> =>
(
// TODO recentlyOffline has been dropped for 2.x and replaced, figure out the
// replacement as actually use and implement it
api.query.staking.recentlyOffline
? api.query.staking.recentlyOffline<OfflineResult>()
: of([] as unknown as OfflineResult)
).pipe(
map(expandDerived)
));
}
+13 -14
View File
@@ -1,14 +1,12 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId } from '@polkadot/types/interfaces';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { DeriveStakingValidators } from '../types';
import { Observable, of } from 'rxjs';
import { Observable, combineLatest, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { Vec } from '@polkadot/types';
import { memo } from '../util';
@@ -17,16 +15,17 @@ import { memo } from '../util';
*/
export function validators (api: ApiInterfaceRx): () => Observable<DeriveStakingValidators> {
return memo((): Observable<DeriveStakingValidators> =>
(
// Sadly the node-template is (for some obscure reason) not comprehensive, so while the derive works
// in all actual real-world deployed chains, it does create some confusion for limited template chains
api.query.session && api.query.staking
? api.queryMulti<[Vec<AccountId>, Vec<AccountId>]>([
api.query.session.validators,
api.query.staking.currentElected
])
: of([[], []] as [AccountId[], AccountId[]])
).pipe(
// Sadly the node-template is (for some obscure reason) not comprehensive, so while the derive works
// in all actual real-world deployed chains, it does create some confusion for limited template chains
// NOTE: Not doing multi queries here, since we have validators as a single in the derived newHead
combineLatest([
api.query.session
? api.query.session.validators()
: of([]),
api.query.staking
? api.query.staking.currentElected()
: of([])
]).pipe(
map(([validators, currentElected]): DeriveStakingValidators => ({
currentElected, validators
}))
@@ -0,0 +1,5 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './proposals';
@@ -0,0 +1,14 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { DerivedCollectiveProposals } from '../types';
import { Observable } from 'rxjs';
import { proposals as collectiveProposals } from '../collective';
import { memo } from '../util';
export function proposals (api: ApiInterfaceRx): () => Observable<DerivedCollectiveProposals> {
return memo(collectiveProposals(api, 'technicalCommittee'));
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

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