Compare commits

...
256 Commits
Author SHA1 Message Date
Github Actions dbfc15ba88 [CI Skip] 1.4.1
skip-checks: true
2020-02-26 11:00:07 +00:00
Jaco Greeff 2d40d370f9 1.4 (#1949) 2020-02-26 11:52:37 +01:00
Github Actions 0728e40bfb [CI Skip] 1.4.0-beta.52
skip-checks: true
2020-02-26 10:32:30 +00:00
Keith Ingram 1a50298ffe Split parachains.derive calls (#1948)
* api.derive.registrar.parachains

* remove api parse

* suggestions

* some

* parachains: overview/info

* rm all

* rm all

* refine
2020-02-26 11:26:04 +01:00
Github Actions 68f2cb5bb2 [CI Skip] 1.4.0-beta.51
skip-checks: true
2020-02-26 10:23:37 +00:00
Jaco Greeff 8598002801 Swap to registry.createType (#1947) 2020-02-26 11:17:11 +01:00
Github Actions 333ff8528b [CI Skip] 1.4.0-beta.50
skip-checks: true
2020-02-25 16:08:21 +00:00
Jaco Greeff c17f93a3ec Update docs for system.account (#1944) 2020-02-25 17:01:41 +01:00
Github Actions 67841a9212 [CI Skip] 1.4.0-beta.49
skip-checks: true
2020-02-25 15:59:45 +00:00
Jaco Greeff 6be6b027cb More private field -> #field adjustments (#1945)
* More private field -> #field adjustments

* Work-around for set.add failures

* Remove FIXME, it is done
2020-02-25 16:53:04 +01:00
Github Actions 6943c9b36d [CI Skip] 1.4.0-beta.48
skip-checks: true
2020-02-25 14:17:45 +00:00
Jaco Greeff 253e48f7bb Return all additional identity fields (#1943) 2020-02-25 15:10:47 +01:00
Github Actions eeaf6118a5 [CI Skip] 1.4.0-beta.47
skip-checks: true
2020-02-25 13:22:44 +00:00
Jaco Greeff c3c77ffe43 Add Option.unwrapOrDefault (#1942)
* Add Option.unwrapOrDefault

* linting

* metadata createType(registry, ...) -> registry.createType(...)

* Linting

* Cleanup tests
2020-02-25 14:15:25 +01:00
Github Actions 71e82aece8 [CI Skip] 1.4.0-beta.46
skip-checks: true
2020-02-25 09:14:49 +00:00
Jaco Greeff a7132b4e9c Fix HEADER(...) in fromChain typegen (#1941) 2020-02-25 10:08:31 +01:00
Github Actions 8acb65931e [CI Skip] 1.4.0-beta.45
skip-checks: true
2020-02-25 08:50:07 +00:00
Jaco Greeff dcf053633b CHANGELOG & small strict adjustments (#1940) 2020-02-25 09:44:13 +01:00
Github Actions 015ade79e6 [CI Skip] 1.4.0-beta.44
skip-checks: true
2020-02-25 08:29:18 +00:00
Jaco Greeff a4f56d3d38 Remove deprecated types (up to metadata V5) (#1939) 2020-02-25 09:22:38 +01:00
Github Actions 73d10a55f1 [CI Skip] 1.4.0-beta.43
skip-checks: true
2020-02-25 07:47:12 +00:00
Jeremías Díaz 2d0ce2ddff Make Strict Mode Strict Again (#1938)
* fix: don't format "unorthodox" query input types

Also add support for tuples in `getSimilarTypes`

* fix: refactor type ignore logic into `formatType`

Had to use a regexp solution because types like `([AccountId | string | Uint8Array, Data | { none: any } | { raw: any } | { blakeTwo256: any } | { sha256: any } | { keccak256: any } | { shaThree256: any } | string | Uint8Array])[]` were not being ignored with the current logic, so they were passed to `getTypeDef` and causing delimiter errors.

* refactor: remove superfluous "FirstKeyType" param

* fix: ignore tuples with structs when formatting

* feat: eliminate all index signatures with --strict

* docs: fix doc generation
2020-02-25 08:40:07 +01:00
Github Actions 775697f51e [CI Skip] 1.4.0-beta.42
skip-checks: true
2020-02-24 21:48:03 +00:00
Jaco Greeff 9690777acb Update .123trigger 2020-02-24 22:41:22 +01:00
Jaco Greeff e7d38a5e59 Update CHANGELOG (#1936) 2020-02-24 22:34:54 +01:00
Jeremías Díaz c6355fb147 fix: don't format "unorthodox" query input types (#1934)
* fix: don't format "unorthodox" query input types

Also add support for tuples in `getSimilarTypes`

* fix: refactor type ignore logic into `formatType`

Had to use a regexp solution because types like `([AccountId | string | Uint8Array, Data | { none: any } | { raw: any } | { blakeTwo256: any } | { sha256: any } | { keccak256: any } | { shaThree256: any } | string | Uint8Array])[]` were not being ignored with the current logic, so they were passed to `getTypeDef` and causing delimiter errors.

* refactor: remove superfluous "FirstKeyType" param
2020-02-24 22:31:18 +01:00
Github Actions d85d9ca930 [CI Skip] 1.4.0-beta.41
skip-checks: true
2020-02-24 19:10:00 +00:00
Jaco Greeff af643401b8 Remove metadata index hack... and add another one (#1935)
* Remove metadata index hack

* Parse v9 and V10 upon failure
2020-02-24 20:03:35 +01:00
Github Actions fcea797c8a [CI Skip] 1.4.0-beta.40
skip-checks: true
2020-02-24 15:59:31 +00:00
Jaco Greeff cbc14cc291 Add new staking types, support derives (#1828)
* Add new staking types

* StakingLedgerTo213 - StakingLedgerTo223

* StakingLedgerTo223 in polkadot (dev)

* Add derive activeEra

* Map Ponts -> RewardPoints

* StakingLedger override CHANGELOG

* Cleanups

* Apparent CC dupes (don't see it, but cleanup useul)

* Cleanup result formatting for indexes

* Map nextElected -> validators

* Fix StakingLedger to current

* Merge CHANGELOG

* Mention derive staking updates

* Mark derive changes as breaking
2020-02-24 16:52:48 +01:00
Jaco Greeff 64aa4dcc1c More metadata clarifications (#1933) 2020-02-24 16:52:00 +01:00
Github Actions 429ea4ca99 [CI Skip] 1.4.0-beta.39
skip-checks: true
2020-02-24 14:08:24 +00:00
Jaco Greeff 86ce696808 Update CHANGELOG (#1932)
* Update CHANGELOG

* typos
2020-02-24 15:01:47 +01:00
Github Actions 57ca9a9c32 [CI Skip] 1.4.0-beta.38
skip-checks: true
2020-02-24 12:35:08 +00:00
Jaco Greeff 70a26e33a7 Docs for createType (#1931) 2020-02-24 13:28:08 +01:00
Github Actions c487094aa7 [CI Skip] 1.4.0-beta.37
skip-checks: true
2020-02-24 08:37:14 +00:00
Jaco Greeff bab79b6473 CHANGELOG 3.8 breaking change (#1930) 2020-02-24 09:30:56 +01:00
Github Actions 586e838788 [CI Skip] 1.4.0-beta.36
skip-checks: true
2020-02-23 14:02:59 +00:00
Jaco Greeff 51cb64ade7 Cleanup api.createType d.ts, add createType to registry (#1929)
* Cleanup api.createType d.ts, add createType to registry

* CHANGELOG
2020-02-23 14:57:30 +01:00
Github Actions d09dcb8282 [CI Skip] 1.4.0-beta.35
skip-checks: true
2020-02-23 12:50:23 +00:00
Jaco Greeff 869f9b7af9 InterfaceTypes -> keyof InterfaceRegistry (#1928)
* InterfaceTypes -> keyof InterfaceRegistry

* Renames
2020-02-23 13:43:37 +01:00
Github Actions a938cb545a [CI Skip] 1.4.0-beta.34
skip-checks: true
2020-02-23 11:54:54 +00:00
Jaco Greeff 553b3df0b2 Augment naming 2020-02-23 12:48:01 +01:00
Jaco Greeff 1fd157364b Use allDefs in augment-types 2020-02-23 12:42:05 +01:00
Github Actions fa7ae72c59 [CI Skip] 1.4.0-beta.33
skip-checks: true
2020-02-23 11:33:12 +00:00
Jaco Greeff 443706a6e0 Extract full interfaceRegistry (#1927)
* Extract full interfaceRegistry

* Move augment to top-level in api & types

* Type augment output

* Update with new augmented paths

* Update RPC path
2020-02-23 12:26:10 +01:00
Github Actions ba462aae8b [CI Skip] 1.4.0-beta.32
skip-checks: true
2020-02-23 10:55:21 +00:00
Jaco Greeff a35da085d6 Augment user type registry (#1926)
* Augment user type registry

* Augment InterfaceRegistry

* Addition api.createType test

* Import '@polkadot/types/interfaceAugment'

* Skip CC on generated

* Move augmentation to full path imports

* Output to augment-*
2020-02-23 11:48:40 +01:00
Github Actions 3d8d2e4988 [CI Skip] 1.4.0-beta.31
skip-checks: true
2020-02-23 09:29:30 +00:00
Jaco Greeff 6c5ef6ecd6 Generation scripts register user types (#1925)
* Generation scripts register user types

* Create augment.ts output

* Remove stray package
2020-02-23 10:22:55 +01:00
Github Actions 3bae45a331 [CI Skip] 1.4.0-beta.30
skip-checks: true
2020-02-22 16:08:46 +00:00
Jaco Greeff 196a0891b8 Use isChildClass & isBigInt from @polkadot/util (#1924)
* Use isChildClass & isBigInt from @polkadot/util

* Allow never

* Bumps

* Common 2.5.1

* Fix overrides

* Remove gh-pages script (in dev)
2020-02-22 17:02:03 +01:00
Github Actions 2a16b04420 [CI Skip] 1.4.0-beta.29
skip-checks: true
2020-02-22 14:00:27 +00:00
Jaco Greeff 790deca695 Update docs for isInBlock (rather late than never) (#1923)
* Update docs for isInBlock (rather late than never)

* Only warn on isInBlock filtering
2020-02-22 14:53:46 +01:00
Github Actions 4ec87dc51c [CI Skip] 1.4.0-beta.28
skip-checks: true
2020-02-22 13:03:37 +00:00
Jaco Greeff 51686f0cd4 Don't clobber global space in WS provider (#1922)
* Don't clbber global space in WS provider

* Re-use getWSClass
2020-02-22 13:56:37 +01:00
Github Actions deddc6dc79 [CI Skip] 1.4.0-beta.27
skip-checks: true
2020-02-22 10:37:34 +00:00
Jaco Greeff 3bf4c3fac5 Adjust class privates via #, where applicable (#1921)
* Adjust class priates via #, where applicable

* Remove stray log

* Cleanup rpc-provider

* Small adjustments

* No private access in tests

* Submittable privates

* Use derive for nonce derivation

* Tweak observers

* Alphabetical privates
2020-02-22 11:29:50 +01:00
Github Actions ccf32a6289 [CI Skip] 1.4.0-beta.26
skip-checks: true
2020-02-21 16:32:43 +00:00
Jaco Greeff 4540495a44 BigInt support (& some TS typing cleanups) (#1919)
* Some TS typing cleanups

* docs building again

* yarn.lock rewrite

* tweaks

* BigInt support

* Checktypes with BigInt

* AccountIndex support for BigInt

* Fix ApiPromise signAsync
2020-02-21 17:26:05 +01:00
Github Actions 429b797b23 [CI Skip] 1.4.0-beta.25
skip-checks: true
2020-02-21 13:20:47 +00:00
Jaco Greeff a3d5ef790c Move StorageData to interface (#1918)
* Move StorageDate to interface

* Move extrinsics interfaces

* Update interface imports
2020-02-21 14:13:23 +01:00
Github Actions b548277c05 [CI Skip] 1.4.0-beta.24
skip-checks: true
2020-02-21 12:40:24 +00:00
Jaco Greeff 2de9317b30 Cleanup CompactAssignments (alignment) (#1917)
* Cleanup CompactAssignments (alignment)

* Remove CompactAssignment

* Add CompactScore
2020-02-21 13:33:21 +01:00
Github Actions 877aa33efa [CI Skip] 1.4.0-beta.23
skip-checks: true
2020-02-21 12:24:23 +00:00
Jaco Greeff 8a9e523b84 Small type usage updates (#1916) 2020-02-21 13:17:40 +01:00
Github Actions 19743d6634 [CI Skip] 1.4.0-beta.22
skip-checks: true
2020-02-21 11:44:20 +00:00
Jaco Greeff 85ec141b56 Lazy reaping types & updates (#1914)
* Lazy reaping types & updates

* system.account queries

* AccountInfo -> ContractAccountInfo tests
2020-02-21 12:37:17 +01:00
Github Actions cb175b4bde [CI Skip] 1.4.0-beta.21
skip-checks: true
2020-02-21 11:19:43 +00:00
Jaco Greeff 8672a2e30e Move length to TypeDef (regularly used), IdentityFields to interface (#1913)
* Move length to TypeDef (regularly used), IdentityFields to interface

* Update api-contracts tests
2020-02-21 12:12:18 +01:00
Github Actions 17936f849b [CI Skip] 1.4.0-beta.20
skip-checks: true
2020-02-21 09:02:17 +00:00
Jaco Greeff 3b9f348223 Cleanup IdentityFields (re-use Set) (#1912)
* Cleanup IdentityFields

* Small cleanups

* Re-add commented IdentityFields
2020-02-21 09:55:18 +01:00
Github Actions b5ff0434d9 [CI Skip] 1.4.0-beta.19
skip-checks: true
2020-02-21 08:40:26 +00:00
Jaco Greeff 877a339353 Extrinsic toHuman aligns with .method (#1911) 2020-02-21 09:33:34 +01:00
Github Actions 716f473887 [CI Skip] 1.4.0-beta.18
skip-checks: true
2020-02-20 20:42:44 +00:00
Jaco Greeff 1c1bfb295d VecFixed now take sub, align ext with UInt (#1909)
* Allow nested definitions for fixed arrays

* Comment nested test

* Don't import U8aFixed + u8
2020-02-20 21:36:12 +01:00
Github Actions dd0a31803f [CI Skip] 1.4.0-beta.17
skip-checks: true
2020-02-20 15:35:25 +00:00
Jaco Greeff e04e5577ed Types for offchain phragmen (#1908) 2020-02-20 16:27:48 +01:00
Github Actions 09617aad2e [CI Skip] 1.4.0-beta.16
skip-checks: true
2020-02-20 12:33:42 +00:00
Jaco Greeff 3d8a57a7d5 Bump dev (#1907) 2020-02-20 13:27:22 +01:00
Github Actions feff458cbf [CI Skip] 1.4.0-beta.15
skip-checks: true
2020-02-20 12:10:28 +00:00
Jaco Greeff 543b4846f9 Fixed64 to an interface (#1906)
* Fixed64 to an interface

* Cleanups, re-use creation

* Fix Int export from codec

* Fix Int export
2020-02-20 13:03:29 +01:00
Github Actions 09ab373b54 [CI Skip] 1.4.0-beta.14
skip-checks: true
2020-02-20 11:58:08 +00:00
Jaco Greeff bec6dba14a Move primitive/Extrinsic -> extrinsic (#1905)
* Move primitive/Extrinsic -> extrinsic

* mv primitive/Generic -> generic

* Update registry with BitVec

* ove BitVec back to primitive

* Remove unused import

* Rebuild interfaces
2020-02-20 12:51:06 +01:00
Github Actions e80bea6680 [CI Skip] 1.4.0-beta.13
skip-checks: true
2020-02-20 09:20:54 +00:00
Jaco Greeff 9119e791d1 Add V4 extrinsic test (#1904)
* Add V4 extinsic test

* Update test with toHuman

* Remove unused import
2020-02-20 10:14:21 +01:00
Github Actions 46b99ae83d [CI Skip] 1.4.0-beta.12
skip-checks: true
2020-02-20 07:28:44 +00:00
Jaco Greeff 92129746dc Move inter-package deps to fixed (as per release) (#1903) 2020-02-20 08:21:17 +01:00
Github Actions 4a8a36d284 [CI Skip] 1.4.0-beta.11
skip-checks: true
2020-02-20 07:07:16 +00:00
Jaco Greeff 2b8ce1b3b7 Check AbstractInt bitLength on construction (#1902)
* Check AbstractInt bitLength on construction

* Language cleanups
2020-02-20 08:00:41 +01:00
Github Actions 0e1e0c0d37 [CI Skip] 1.4.0-beta.10
skip-checks: true
2020-02-19 19:05:23 +00:00
Jaco Greeff 427f821430 Fix 11 Jan 2019 issue (#1900)
* Fix 11 Jan 2019 issue

* Update SignedBlock tests
2020-02-19 19:57:59 +01:00
Github Actions 07307f8374 [CI Skip] 1.4.0-beta.9
skip-checks: true
2020-02-19 14:52:02 +00:00
Jaco Greeff cc5b5c81c9 Subscribe to runtime updates (#1896)
* Subscribe to runtime updates

* console.log -> l.log

* Add l.warn to api augment

* Expand logs with added & removed

* Re-do everything when genesis has changed

* augmentObject complexity

* Dedup [string[], strings[]]

* Update CHANGELOG
2020-02-19 15:45:03 +01:00
Jakub Pánik efbc017940 All heads subscription (#1899)
* [CI Skip]  1.4.0-beta.8

skip-checks: true

* Added support for all heads subscription
2020-02-19 15:30:24 +01:00
Github Actions 849972f7b0 [CI Skip] 1.4.0-beta.8
skip-checks: true
2020-02-19 05:54:02 +00:00
Axel Chalon 01758229eb Add manual seal RPCs (#1894)
* Add manual seal RPCs

* yarn build:interfaces
2020-02-19 06:48:00 +01:00
Github Actions add9b59402 [CI Skip] 1.4.0-beta.7
skip-checks: true
2020-02-18 20:36:58 +00:00
Jaco Greeff c8af75088a Add injectMetadata to api (with decoration) (#1892)
* Add injectMetadata to api (with decoration)

* warn function

* OCD

* OCD #2

* toHuman entry expansion

* CHANGELOG for injectMetadata
2020-02-18 21:30:43 +01:00
Github Actions d4b45921fd [CI Skip] 1.4.0-beta.6
skip-checks: true
2020-02-18 20:14:31 +00:00
Jaco Greeff 30f5baa906 ExtrinsicEra & Vote toHuman (#1893) 2020-02-18 21:08:18 +01:00
Github Actions 7150bdcbea [CI Skip] 1.4.0-beta.5
skip-checks: true
2020-02-18 15:46:08 +00:00
Jaco Greeff d041c0abb2 Support arbitrary UInt<bitLength> definitions (#1891)
* Support arbitrar UInt

* CHANGELOG

* Fix generation

* Move UInt
2020-02-18 16:39:18 +01:00
Github Actions 524e694b90 [CI Skip] 1.4.0-beta.4
skip-checks: true
2020-02-18 15:04:32 +00:00
Jaco Greeff bdd1e4c917 Move H160, H256 & H512 to interfaces (#1890)
* Move H160, H256 & H512 to interfaces

* Test for Hash -> H256

* Replace IHash & Codec.hash with H256

* [u8; n] extends U8aFixed

* Update formatting.ts
2020-02-18 15:56:50 +01:00
Github Actions 7233d7c754 [CI Skip] 1.4.0-beta.3
skip-checks: true
2020-02-18 14:00:33 +00:00
Jaco Greeff aee09c48b9 Use static with for derived H*, U* & I* primitives (#1889)
* Usestatic with for derived H*, U* & I* primitives

* Add with override tests

* Fix linting
2020-02-18 14:53:43 +01:00
Github Actions 7edbc58129 [CI Skip] 1.4.0-beta.2
skip-checks: true
2020-02-18 12:41:52 +00:00
Jaco Greeff ad2939cc4f Rework Unconstructable type (#1888)
* Rework Unconstructable type

* hasType updates

* Unknown -> Unconstructable (as it was)

* Remove commented test

* class name

* getOrThrow tests

* typo.

* getOrUnknown
2020-02-18 13:35:42 +01:00
Github Actions e984c74ca6 [CI Skip] 1.4.0-beta.1
skip-checks: true
2020-02-18 12:26:54 +00:00
Jaco Greeff a5c8e3c4e1 Convert DigestItem to definition (#1886)
* Convert DigestItem to definition

* Remove GenericDigestItem export

* Update CHANGELOG.md
2020-02-18 13:20:29 +01:00
Github Actions 1e5191d695 [CI Skip] 1.4.0-beta.0
skip-checks: true
2020-02-18 09:12:00 +00:00
Jaco Greeff b46093e5d3 Add .toHuman on SubmittableResult (#1885) 2020-02-18 10:05:48 +01:00
Github Actions 64f0d7b2a6 [CI Skip] 1.3.1
skip-checks: true
2020-02-18 08:40:23 +00:00
Jaco Greeff 4a1e504ca2 1.3 (#1883)
* 1.3

* Pair create update

* CHANGELOG update
2020-02-18 09:34:35 +01:00
Github Actions ebf3f4491e [CI Skip] 1.3.0-beta.11
skip-checks: true
2020-02-17 14:23:11 +00:00
Jaco Greeff 849f519efe Add GH actions yarn cache (#1881) 2020-02-17 15:16:09 +01:00
Github Actions accc2b4f7d [CI Skip] 1.3.0-beta.10
skip-checks: true
2020-02-17 13:15:05 +00:00
Jaco Greeff 01abc030f9 Cleanup stray accountNonce reference (#1880)
* Cleanup stray accountNonce reference

* Comment for system.account upgrades
2020-02-17 14:08:13 +01:00
Github Actions e041946de5 [CI Skip] 1.3.0-beta.9
skip-checks: true
2020-02-17 11:50:02 +00:00
Jaco Greeff 502e54ce5c Bump common (#1879)
* Bump common

* Add documentation to extended call

* TODO for toHuman event

* CHANGELOG
2020-02-17 12:43:03 +01:00
Github Actions 12986f0cda [CI Skip] 1.3.0-beta.8
skip-checks: true
2020-02-17 10:50:00 +00:00
Jaco Greeff 83d780220c Add toHuman with base formatting (#1878)
* Add toHuman with base formatting

* Balance formatting

* Externalize Enum decode
2020-02-17 11:43:08 +01:00
Github Actions ec7848ae92 [CI Skip] 1.3.0-beta.7
skip-checks: true
2020-02-17 07:53:42 +00:00
Jaco Greeff 2b5be7eaab Remove unexported staking.infostash derive (duplicated as .query) (#1877) 2020-02-17 08:46:59 +01:00
Github Actions 21f4e3107a [CI Skip] 1.3.0-beta.6
skip-checks: true
2020-02-17 07:16:52 +00:00
Jaco Greeff 8a152ea4c0 Split generation scripts into @polkadot/typegen (#1875)
* Split generation scripts into @polkadot/typegen

* Remove moved files

* CC overrides

* interfaces typo

* Cleanup imports

* Some import combinations

* Updates

* Generation updates

* Cleanups, split js wrapper & ts logic

* Rename jiggle 1

* Rename jiggle 2

* Style cleanups

* Expose enry function for scripts

* Typo

* Update script copy & include locations

* CC exclude location

* Minor adjustments

* argv parsing into main
2020-02-17 08:09:59 +01:00
Github Actions fd7b38e781 [CI Skip] 1.3.0-beta.5
skip-checks: true
2020-02-17 06:16:35 +00:00
Jeremías Díaz 5df22835f6 fix: make bn.js into a regular dependency (#1876)
Since `AbstractInt` is exposing `toBn(): BN` which uses `bn.js` types,
projects using polkadot are forced to install `@types/bn.js` on their own,
otherwise they get compilation errors
2020-02-17 07:09:30 +01:00
Github Actions 6a828eb11a [CI Skip] 1.3.0-beta.4
skip-checks: true
2020-02-16 16:48:32 +00:00
Jaco Greeff ad2b1abdc9 Move @polakdot/jsonrpc -> packages/jsonrpc (#1874)
* Move @polakdot/jsonrpc -> packages/jsonrpc

* Update links
2020-02-16 17:41:45 +01:00
Github Actions d3dc2cb00a [CI Skip] 1.3.0-beta.3
skip-checks: true
2020-02-16 12:58:16 +00:00
Jaco Greeff 921e55a82e Move types/codec/create -> types/create (#1871)
* Move types/codec/create -> types/create

* Update imports after move

* Cleanups

* Cleanup code circular deps

* Re-add dropped interfaces

* Drop duplicated code

* Fix imports

* Remove whacky comment
2020-02-16 13:51:37 +01:00
Github Actions fde076152a [CI Skip] 1.3.0-beta.2
skip-checks: true
2020-02-16 12:20:24 +00:00
Jaco Greeff 6e535b0502 Don't make types depend on api (dev deps) (#1869)
* Don't make types depend on api (dev deps)

* Naming cleanups

* Remove skipped tests

* Splt types/types into chunks

* Re-add setChainProperties (properties?: ChainProperties): void;
2020-02-16 13:13:56 +01:00
Github Actions 1ddad84d7e [CI Skip] 1.3.0-beta.1
skip-checks: true
2020-02-16 10:16:34 +00:00
Jaco Greeff 1e975c68ee Make chain properties available on registry (#1868)
* Make chain properties available on registry

* Use registry chainSS58 to format address

* CHANGELOG

* CHANGELOG typo

* Fix tests vis setChainProperties

* Cleanup tests via chain property set

* Remove global ss58 format set
2020-02-16 11:09:48 +01:00
Github Actions 5c962cf093 [CI Skip] 1.3.0-beta.0
skip-checks: true
2020-02-16 09:27:50 +00:00
Jaco Greeff 07f55af202 Documentation of ready rejections (#1870) 2020-02-16 10:21:19 +01:00
Github Actions 6c8dd4be3b [CI Skip] 1.2.1
skip-checks: true
2020-02-16 07:28:13 +00:00
Jaco Greeff a339491d07 1.2 (#1867) 2020-02-16 08:21:50 +01:00
Github Actions ea87472354 [CI Skip] 1.2.0-beta.30
skip-checks: true
2020-02-16 07:01:44 +00:00
Jaco Greeff 0ed156e5d9 FAQ entry for system.account (#1866) 2020-02-16 07:54:46 +01:00
Github Actions 59590540d8 [CI Skip] 1.2.0-beta.29
skip-checks: true
2020-02-16 06:41:42 +00:00
Jaco Greeff c465252e69 Make Metadata <-> hex encoding work (#1862)
* Make Metadata <-> hex encoding work

* Cleanup encoded, only toString exposes santized

* toHex is actual original toHex, remove override

* Update CHANGELOG

* CHANGELOG for .entries argument typing

* Update CHANGELOG.md

* Manual check type for DoubleMap

* Comment around super.toString usage

* Runtime version
2020-02-16 07:34:45 +01:00
Github Actions 0822d4d8c6 [CI Skip] 1.2.0-beta.28
skip-checks: true
2020-02-15 16:58:04 +00:00
Jeremías Díaz 2c3eee4c67 fix: make entries accept args for double maps (#1864) 2020-02-15 17:51:01 +01:00
Github Actions b069710008 [CI Skip] 1.2.0-beta.27
skip-checks: true
2020-02-15 12:10:44 +00:00
Jaco Greeff 9a7e0bf82d Bump deps (#1861)
* Bump deps

* Bump common
2020-02-15 13:03:34 +01:00
Github Actions 4f520f5de6 [CI Skip] 1.2.0-beta.26
skip-checks: true
2020-02-15 08:56:55 +00:00
Jaco Greeff 79ee2ede3d Cleanup date test with locale offset (#1860)
* Cleanup date test with locale offset

* CHANGELOG

* Add dates to CHANGELOG
2020-02-15 09:49:39 +01:00
Github Actions f6b02e1de1 [CI Skip] 1.2.0-beta.25
skip-checks: true
2020-02-15 08:23:22 +00:00
Jaco Greeff c11b0dffc5 Adjust CHANGELOG with all latest changes (#1859) 2020-02-15 09:17:07 +01:00
Github Actions 0935c39906 [CI Skip] 1.2.0-beta.24
skip-checks: true
2020-02-15 07:59:29 +00:00
Keith IngramandJaco Greeff ee622f3d2b Add api.derive.registrar.parachains (#1856)
* api.derive.registrar.parachains

* remove api parse

* suggestions

* some

* Update packages/api-derive/src/parachains/all.ts

* Update packages/api-derive/src/index.ts

* Update packages/api-derive/src/index.ts

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-02-15 08:52:40 +01:00
Github Actions ae350aae6f [CI Skip] 1.2.0-beta.23
skip-checks: true
2020-02-15 07:41:46 +00:00
Axel Chalon 26c59f6d6e Format documentation strings properly & refactor MetadataMd (#1858)
* Format docs strings properly

* Refactor MetadataMd
2020-02-15 08:35:15 +01:00
Github Actions 51c6262327 [CI Skip] 1.2.0-beta.22
skip-checks: true
2020-02-14 15:21:11 +00:00
Jaco Greeff 07ed405610 Bump common (& add @types/bn.js) (#1855) 2020-02-14 16:14:18 +01:00
Github Actions cd5d7b10c3 [CI Skip] 1.2.0-beta.21
skip-checks: true
2020-02-14 14:47:36 +00:00
Jaco Greeff 8e5b43bf62 Add isInBlock, isRetracted (...) to status enum (#1852) 2020-02-14 15:40:56 +01:00
Github Actions 49f3e36c46 [CI Skip] 1.2.0-beta.20
skip-checks: true
2020-02-14 13:54:07 +00:00
Jaco Greeff 7e25145fbf Format known storage (align with others) (#1851) 2020-02-14 14:46:42 +01:00
Github Actions b5bc2ccfaf [CI Skip] 1.2.0-beta.19
skip-checks: true
2020-02-14 13:28:31 +00:00
Jaco Greeff 0e7c508d7f Split private statics from Call (#1849) 2020-02-14 14:21:38 +01:00
Github Actions 4e1c377ceb [CI Skip] 1.2.0-beta.18
skip-checks: true
2020-02-14 12:59:42 +00:00
Jaco Greeff 5c4920db6f Remove balances.freeBalance & system.accountNonce refs (#1847)
* Remove freeBalance references

* Cleanup placeholders

* Add substrate templates to .gitignore

* Swap all use of system.accountNonce

* typo
2020-02-14 13:52:45 +01:00
Github Actions 679e31668e [CI Skip] 1.2.0-beta.17
skip-checks: true
2020-02-14 09:21:48 +00:00
Jaco Greeff 00e567b662 Bump metadata (#1844)
* Bump metadata

* Copy error

* Bump dev

* Fix linting

* Adjust some tests

* FIXME for formatting
2020-02-14 10:15:11 +01:00
Github Actions 503193d6c2 [CI Skip] 1.2.0-beta.16
skip-checks: true
2020-02-14 07:18:45 +00:00
Jaco Greeff 5e82c97c8a Bump dev (#1843)
* Bump dev

* Bumps
2020-02-14 08:12:57 +01:00
Github Actions 8c12c227b4 [CI Skip] 1.2.0-beta.15
skip-checks: true
2020-02-13 23:11:05 +00:00
Jaco Greeff d72456fb26 Bump dev (#1842) 2020-02-14 00:04:43 +01:00
Github Actions ca6d78e7ec [CI Skip] 1.2.0-beta.14
skip-checks: true
2020-02-13 22:08:12 +00:00
Axel Chalon 8210c708ac Add errors to documentation (#1841)
* Add errors to docs

* Fix broken anchor links (camel-case links but lowercase anchors)
2020-02-13 23:01:05 +01:00
Github Actions 41764562e1 [CI Skip] 1.2.0-beta.13
skip-checks: true
2020-02-13 21:32:08 +00:00
Axel Chalon 66c8e5b4e8 Add author_{hasKey, hasSessionKeys} RPCs (#1837)
* Add author_{hasKey, hasSessionKeys} RPCs

* yarn docs

* Revert "yarn docs"

This reverts commit c23624e1d844fcd8821ccf4bd73f0175a3a10526.
2020-02-13 22:24:11 +01:00
Github Actions ca7fe86089 [CI Skip] 1.2.0-beta.12
skip-checks: true
2020-02-13 14:47:22 +00:00
Jaco Greeff cf2fbfce26 Bump dev (#1839) 2020-02-13 15:39:40 +01:00
Github Actions d69113ca5a [CI Skip] 1.2.0-beta.11
skip-checks: true
2020-02-12 17:07:57 +00:00
Jaco Greeff d7eb40caf5 Additional explicit packages (#1836)
* Additional explicit packages

* Package name
2020-02-12 17:59:54 +01:00
Github Actions 2eda438eac [CI Skip] 1.2.0-beta.10
skip-checks: true
2020-02-12 15:41:07 +00:00
Jaco Greeff beddc3e0a5 Explicit deps & bumps (#1835)
* Explicit deps & bumps

* Update CHANGELOG.md
2020-02-12 16:33:57 +01:00
Github Actions ac1ae34e37 [CI Skip] 1.2.0-beta.9
skip-checks: true
2020-02-11 20:35:54 +00:00
Jaco Greeff 52953f248b Adjust composite version (#1833) 2020-02-11 21:28:29 +01:00
Github Actions e027f865aa [CI Skip] 1.2.0-beta.8
skip-checks: true
2020-02-11 13:23:21 +00:00
Jaco Greeff d4e3e546dc Cleanup sanitize with groupings (#1832)
* Cleanup sanitize with groupings

* Small additional cleanups
2020-02-11 14:16:01 +01:00
Github Actions 6cb5476c80 [CI Skip] 1.2.0-beta.7
skip-checks: true
2020-02-11 09:43:56 +00:00
Jaco Greeff 52ffa175a9 Versioned polkadot overrides (#1831) 2020-02-11 10:36:01 +01:00
Github Actions ba2cd0cff5 [CI Skip] 1.2.0-beta.6
skip-checks: true
2020-02-10 20:33:01 +00:00
Keith Ingram fefcc2e0dc update parachains types (#1830) 2020-02-10 15:25:14 -05:00
Github Actions c8fbed2a12 [CI Skip] 1.2.0-beta.5
skip-checks: true
2020-02-10 17:52:41 +00:00
Jaco Greeff 6581d779c7 Alias Address -> AccountId for polkadot/kusama (#1825)
* Swap Address -> LookupSource (correct aliasses)

* Adjust overrides with explicit LookupSource

* Map Lookup{Source,Target}

* Adjust overrides

* Comment Address -> AccountId (for now)

* Fix typo in comments

* Map Address -> AccountId

* CHANGELOG
2020-02-10 18:44:12 +01:00
Github Actions cab5b8bff7 [CI Skip] 1.2.0-beta.4
skip-checks: true
2020-02-08 14:03:31 +00:00
Jaco Greeff 480c0abda8 Add BitVec type (#1822)
* Add BitVec type

* Update comments

* Fixup decoding check

* Fix linting
2020-02-08 14:56:08 +01:00
Github Actions 866c5769bb [CI Skip] 1.2.0-beta.3
skip-checks: true
2020-02-08 13:53:08 +00:00
Jaco Greeff d8141198e1 Provide mapping for LookupSource & LookupTarget (#1823)
* Provide mapping for LookupSource & LookupTarget

* Type overrides for Kusama-next

* Fix LookupSource for Kusama-next

* Fixup tests with lookup
2020-02-08 14:46:08 +01:00
Github Actions a6a1a52d61 [CI Skip] 1.2.0-beta.2
skip-checks: true
2020-02-08 12:19:01 +00:00
Jaco Greeff b6534d2958 Polkadot V11 metadata (#1821) 2020-02-08 13:11:33 +01:00
Github Actions 3645cde156 [CI Skip] 1.2.0-beta.1
skip-checks: true
2020-02-07 14:50:37 +00:00
Jaco Greeff 2ac3640900 Update AccountIndex derive (#1820) 2020-02-07 15:43:21 +01:00
Github Actions e379e7fabd [CI Skip] 1.2.0-beta.0
skip-checks: true
2020-02-07 13:42:08 +00:00
Jaco Greeff 69dae84a42 Update .123trigger (#1819) 2020-02-07 14:34:57 +01:00
Jaco Greeff fe52484547 Query nonce/data from system.account (as available) (#1814)
* Query nonce/data from sustem.account (as available)

* Detect new nonce query, retrieve

* Call system.account for nonce & balance

* Update CHANGELOG
2020-02-07 14:20:34 +01:00
Jaco Greeff faa12a68f7 Move internal decoding to top-level-functions (#1818)
* Move internal decoding to top-level-functions

* Cleanup imports
2020-02-07 14:12:30 +01:00
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
492 changed files with 23860 additions and 13512 deletions
+1 -1
View File
@@ -1 +1 @@
17
19
+4 -2
View File
@@ -4,6 +4,8 @@ exclude_patterns:
- "**/*.test.js"
- "**/*.test.ts"
- "docs/**/*.js"
- "packages/api/src/query.types.ts"
- "packages/api/src/augment/"
- "packages/typegen/scripts"
- "packages/typegen/src"
- "packages/types/src/interfaces/"
- "packages/types/src/scripts/"
- "packages/types/src/augment/"
+40
View File
@@ -14,6 +14,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: lint
run: |
yarn install --frozen-lockfile
@@ -31,6 +41,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: test
run: |
yarn install --frozen-lockfile
@@ -48,6 +68,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: build
run: |
yarn install --frozen-lockfile
@@ -65,6 +95,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: build
run: |
yarn install --frozen-lockfile
+22 -2
View File
@@ -20,6 +20,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: build
env:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
@@ -29,7 +39,7 @@ jobs:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
yarn install --frozen-lockfile
yarn polkadot-dev-ghact-build
yarn polkadot-ci-ghact-build
build_docs:
name: Build Docs
@@ -44,6 +54,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: build
env:
GH_PAT: ${{ secrets.GH_PAT }}
@@ -52,7 +72,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
yarn install --frozen-lockfile
yarn polkadot-dev-ghact-docs
yarn polkadot-ci-ghact-docs
dummy:
name: Dummy
+1
View File
@@ -3,6 +3,7 @@ build/
build-docs/
coverage/
docs/.vuepress/dist/
docs/substrate/*.md
node_modules/
tmp/
.DS_Store
+159 -52
View File
@@ -1,24 +1,91 @@
# 1.0.1
# 1.4.1 Feb 26, 2020
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features (specifically `#private`), which is not usable in TS versions < 3.8
- **Breaking change** - `api.derive.staking.*` has updated result types and detects support for lazy payouts queries
- Rework type generation for `api.{query, tx}` to properly handle complex type inputs (Thanks to https://github.com/monitz87)
- Rework metadata `--strict` mode to effectively decorate chain metadata (Thanks to https://github.com/monitz87)
- Add `api.rpc.chain.subscribeAllHeads` (not just best) (Thanks to https://github.com/jak-pan)
- Add `api.rpc.engine.*` for manual seal support
- Add `api.injectMetadata(metadata)` to initialize API with a specific metadata version
- The api now checks for runtime upgrades, augmenting the interfaces with new metadata when found
- Support types & interfaces required for lazy reaping, lazy payouts & offchain phragmen
- `Option` types now has an `.unwrapOrDefault` as an complement to `.unwrap` & `.unwrapOr`
- Support JS `BigInt` inputs in any derived `UInt` and `Int` object, e.g. `api.tx.balances.transfer(..., 9876543210123456789n)`
- `UInt` & `Int` now does source bitLength checks upon construction
- Registry now exposes `.createType(<type>, ...args)` as an additional helper (like the API)
- Expand `.toHuman` on `ExtrinsicEra`, `SubmittableResult` & `Vote`
- Move `DigestItem`, `Fixed64`, `H160`, `H256` & `H512` to interfaces in `@polkadot/types/interfaces`
- Align construction of unknown types in `registry.get` consistently warn on detection, throw on use
- Support for arbitrary UInt types via `UInt<bitLength>` type definitions
- Expose static `.with` on `UInt`, `Int` & `U8aFixed` classes with optional type name override
- Remove [11 Jan 2019](https://github.com/polkadot-js/api/issues/574) extrinsic length hack
- Use ES `#field` on private class fields as applicable
- Move `types/primitive/{extrinsics, generic}` to `types/{extrinsics, generic}`
- Cleanup augmentation and generation scripts for type definitions, aligning with api augmentation
- Bump to `@polkadot/{util, util-crypto, keyring}` 2.5.1
# 1.3.1 Feb 18, 2020
- Add `@types/bn.js` as a normal dependency, exposed in `*.d.ts` (Thanks to https://github.com/monitz87)
- Type generation scripts (including `polkadot-types-from-{chain,defs}`) has been moved to the `@polkadot/typegen` package
- The `@polkadot/types/codec/create` has been moved to `@polkadot/types/create`, imports from `@polkadot/types` are unaffected
- Expose chain properties on registry (and use for API type formatting)
- Add `toHuman(isExtended?: boolean)` to all codec types, formatting into a human-readable structure
# 1.2.1 Feb 16, 2020
- **Important** Update RPC status codes (latest Substrate 2), with the `isInBlock` (`isFinalized` now indicates finality)
- Storage `.entries(arg?: any)` now has the correct argument type for DoubleMap (Thanks to https://github.com/monitz87)
- Swap Kusama and Polkadot aliases for `Address` to `AccountId` (future update)
- Add `LookupSource` and `LookupTarget` types instead of mapping these directly for aliasing
- Add `BitVec` type primitive
- Add support for `system.account` for balance & nonce queries in derives as well as Submittables (Substrate composites)
- Add `rpc.author.hasKey` and `rpc.author.hasSessionKeys` RPCs
- Add derives for the parachains interfaces
- Applied the latest types for Polkadot parachains
- `registry.findMetaError` now can take in a `DispatchErrorModule` object for error lookups (from `asModule` in `DispatchError`)
- Metadata now correctly serializes to the original input data via `toHex()` & `toU8a()`
- Metadata documentation generation rework, including the output of errors from metadata
- Update all examples and comments to use latest `system.account` queries (instead of `system.accountNonce` and `balances.freeBalance`/`balances.reservedBalance`)
- Cleanup `codec/Date` tests to make it run properly on all timezones
- Add explicit dependencies to all packages and move TypeScript `@types/*` to dev deps
# 1.1.1 Feb 06, 2020
- **Important** Chains without `balances.account` or `system.account` should supply `"BalanceLock": "BalanceLockTo212"` to their types to use the previous-generation `BalanceLock` (when querying locks)
- Add support for `balances.account` in all applicable derives (incl. `vesting` module)
- 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 Jan 30, 2020
- **Breaking change** Drop support for Substrate v1 chain in all derives
- Return unsub functions from provider .on emitters (Thanks to https://github.com/jak-pan)
- `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)
- Remove un-deployed support for v11 metadata (this was decided against on Substrate)
- Allow v9 metadata to parse even in cases where it was wrongly deployed pre-v10
- Allow type-aliasses on a per-module basis (e.g. `Judgement` in identity as well as society)
- 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 empy tuples, e.. `()` to `Null`, rather keep them empty
- Add lookups to the metadata erros via `findMetaError`
- Update metadata and types for the lastest Substrate & Polkadot versions
- Support metadata V11 as per lastest Substrate
- Don't map empty tuples, e.g. `()` 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
# 0.100.1 Jan 13, 2020
- **Important** This will the the last API version with Substrate 1.x support. Although you will still be able to use subsequent versions with older chans, dependent libraries such as sr25519 may not be compatible.
- **Important** This will the the last API version with Substrate 1.x support. Although you will still be able to use subsequent versions with older chains, dependent libraries such as sr25519 may not be compatible.
- Add support for the Substrate identity module
- Remove the `codec/Data` type, to remove a conflict with Substrate. This type is now named `Raw`
- Fix for linked maps using `Option`
@@ -27,16 +94,16 @@
- Add support for latest Polkadot/Substrate types
- Add `paymentInfo` to submittables to calculate fees
# 0.99.1
# 0.99.1 Dec 13, 2019
- **Breaking change** The `Data` and `U8a` type has been renamed and just replaced with the `Raw` type
- **Breaking change** The `api.derive.staking.info` has been split into 2 - `staking.query` for non-balance related information (more effective) and `staking.account` that enhances query for all the information previously found `.info`
- Cleanup `DoubleMap` hashing to always hash over the full value (in the case of `Vec<T>`, this includes the length)
- Update democracy derives to take care of nextTally and lowestU*nbaked
- Update democracy derives to take care of nextTally and lowestUnbaked
- Add additional derives for both council & treasury
- Alignment with latest Polkadot/Substrate master branch types
# 0.98.1
# 0.98.1 Dec 04, 2019
- Make the TypeScript generation script mor re-usable (Thanks to https://github.com/xlc)
- Add `.entries()` for all map-types, returning storage keys and values
@@ -45,7 +112,7 @@
- Support for new Substrate democracy with preimages in derive
- Alignment of types with Substrate/Polkadot master branches
# 0.97.1
# 0.97.1 Nov 29, 2019
- **Breaking change** Add the passing on an explicit `Registry` to all calls to `createType` as well as all codec classes. If you are upgrading form an older version, use the [migration guide](UPGRADING.md) to walk through the changes required.
- **Breaking change** The metadata classes have been moved from `@polkadot/types` into `@polkadot/metadata`. If you explicitly create `Metadata` classes, you now would need to do so with the `import Metadata from '@polkadot/metadata';` This is a decorated class, where the previous metadata is now available on `Metadata.metadata`, alongside decorated `consts.*`', `tx.*` and `query.*`.
@@ -57,7 +124,7 @@
- Support for Metadata V9, which adjusts the hashing methods of storage entries
- Support for Metadata V10 (still un-released), which includes prefixed map support
# 0.96.1
# 0.96.1 Nov 09, 2019
- Updated types for latest Kusama
- Add `filterRecords` (in addition to `findRecord`) on submittable results
@@ -67,11 +134,11 @@
- Update council derives for the latest Substrate master support (with constants)
- Derive cleanups, including sharing of instances between the API and internal to derives
# 0.95.2
# 0.95.2 Oct 25, 2019
- Temporary removal of `account_nextIndex` use, will be re-added in a future release
# 0.95.1
# 0.95.1 Oct 25, 2019
- Support Extrinsic V4 with additional signature indicator (Latest Polkadot/Substrate/Kusama)
- Adjust subscription update checks to avoid duplicated data updates
@@ -81,19 +148,19 @@
- All latest Polkadot & Substrate types (as per master branches)
- **Breaking change** `Call.injectMethods` is moved to `Call.injectMetadata` to align with `Events` (This _should_ not be used externally, however mentioned as breaking here)
# 0.94.1
# 0.94.1 Oct 07, 2019
- Add handling of `Result<Ok, Error>` definitions
- Adjust API cloning now takes RPC filters from source into account
- Simplification of isPedantic checks and less overhead on StorageData types
- Cleanups and fixes around RPC and derive type definitions
- Fix `derive.imOnline.receivedHeatbeats` to query via indexes
- Fix `derive.imOnline.receivedHeartbeats` to query via indexes
- Adjustment of `api.derive.elections.{approvalsOf|approvalsOfAt}` to allow ss58 address input
- Cleanup `Enum` `.eq` handling to be more exhaustive
- Add documentation for custom extrinsic formats (advanced chains)
- Update to latest substrate master metadata
# 0.93.1
# 0.93.1 Sep 26, 2019
- Support for Kusama CC2
- In extrinsic submission, use `rpc.account.nextIndex` to retrieve the nonce when available
@@ -103,7 +170,7 @@
- Support recursive type registration (self-referencing via `Box`) in addition to better sanitation of user-defined-types
- Documentation and example updates (thanks mostly to contributions)
# 0.92.1
# 0.92.1 Sep 12, 2019
- The API now correctly sets the ss58 prefix as retrieved from the chain properties via `ss58Format`
- Bump to `@polkadot/util` 1.4.1, removing use of `ExtError`
@@ -111,7 +178,7 @@
- Support the latest Polkadot & Substrate master branches (incl. metadata updates)
- Getting started documentation has been made available
# 0.91.1
# 0.91.1 Sep 09, 2019
- This release was focussed on stability, with a number of cleanups and bug-fixes
- Adjustments for Substrate 1.x chain detection (with auto-types) and Substrate 2.x support has been extended with all latest types
@@ -121,11 +188,11 @@
- Redeemed balance calculation if `api.derive` now returns the correct values again (bug fix)
- added the `yarn chain:info [--ws URL]` utility to extract a calls-only metadata version
- Missing types are now logged via a `console.warn`, not via `.error`
- `Extrinsic`, `ExtrinsicPayload` & `SignerPayload` is registered in the type registry and can be overriden now
- `Extrinsic`, `ExtrinsicPayload` & `SignerPayload` is registered in the type registry and can be overridden now
- **Breaking change** `SignerPayload` is renamed to `SignerPayloadJSON`
- **Breaking change** `SignerPayloadJSON`, `SignerPayloadRawBase` and `SignerPayloadRaw` are all moved to `@polkadot/types`
# 0.90.1
# 0.90.1 Aug 24, 2019
If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md).
@@ -143,11 +210,11 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- The `types/codec/createType` has been moved to `types/codec/create` with the same exports. If you explicitly imported from here (and not doing the suggested `import { createType } from '@polkadot/types`), the reference needs to be updated
# 0.82.0-beta.x
# 0.82.0-beta.x Jul 28, 2019
- Support for substrate 2.x (master) has been extended,
- Additional types have been addedd for the modules
- `api.derive.contract` is now `api.derive.contracts` to align with the substrate 2.x rename. (Feture detection is used so it supports both 1.x and 2.x chains)
- `api.derive.contract` is now `api.derive.contracts` to align with the substrate 2.x rename. (Feature detection is used so it supports both 1.x and 2.x chains)
- Addition of `api.derive.elections`
- Support latest substrate 2 v6 metadata with module constants using `api.consts`.
@@ -162,7 +229,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- The `ContractsAbi` type has been moved from `@polkadot/types` to `import { Abi } from '@polkadot/api-contract`. This paves the way for an enhanced contracts interface, instead of dealing with low-level API calls.
# 0.81.1
# 0.81.1 Jun 14, 2019
- The dependency on `@polkadot/keyring` has been removed - if you relied on the API to provide this, you would now need to manually add it
- `createType` allows for the creation of `[u8; <length>]` types (opening the door for contract support)
@@ -182,7 +249,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Add `off` method to `Api` (Base, for both `ApiPromise` & `ApiRx`) to remove an event listener
# 0.80.1
# 0.80.1 Jun 04, 2019
- Support for mortal transactions
- Better DoubleMap storage support
@@ -192,7 +259,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Misc. cleanups and fixes
# 0.79.1
# 0.79.1 May 22, 2019
- DoubleMap query support
- Support latest EventRecord metadata (substrate master)
@@ -204,7 +271,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Add `toRawType` on all type classes (breakdown into primitive types)
# 0.78.1
# 0.78.1 May 08, 2019
- Fix linked-maps (not working since 0.77.1)
- Convert Usize to U32 (as found in WASM environments)
@@ -215,13 +282,13 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Metadata updates for substrate (WithdrawReasons, ContractInfo)
# 0.77.1
# 0.77.1 Apr 25, 2019
- Support Metadata v4, which introduces the use of a custom hasher to hash storage map keys.
- Add TreasuryProposal (not the same as democracy, type aliased)
# 0.76.1
# 0.76.1 Apr 03, 2019
- Caching improvements (duplicate queries, no duplicate subscriptions)
- Experimental contract API
@@ -229,12 +296,12 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Update @polkadot/util-crypto with smaller footprint
# 0.75.1
# 0.75.1 Mar 29, 2019
- Start journey to 1.0
# 0.53.1
# 0.53.1 Mar 29, 2019
- Change spelling to US English as per substrate master (1.0-rc1). Breaking changes as a result:
- For extrinsic status results, if you have checked the type returns, i.e. `result.type === 'Finalised'` now check on the status for `result.status.isFinalized` or `result.status.isBroadcast`, ... (the `type` property is now accessible only on `result.status.type`)
@@ -245,7 +312,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- All examples have been updated with sr25519 addresses (with the new checksums)
# 0.52.1
# 0.52.1 Mar 28, 2019
- Support queries to linked mapped storage (found in new staking interfaces)
- Add `derive.staking.controllers` to retrieve all active staking controllers
@@ -255,42 +322,42 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Check for single instances for api and types as they are loaded (assertSingletonPackage)
# 0.51.1
# 0.51.1 Mar 25, 2019
- Support metadata V2 as per latest substrate master
- Update metadata with new types as per latest substrate master
# 0.50.1
# 0.50.1 Mar 23, 2019
- Latest util-crypto (usage of WASM with JS fallbacks if not available)
- Update upstream @polkadot dependencies (for new crypto)
# 0.49.1
# 0.49.1 Mar 20, 2019
- Fix large message signing on non-known nodes (default is now hashing, there has been enough time between upgrades)
# 0.48.1
# 0.48.1 Mar 18, 2019
- Pull in new sr25519 capable keyring for dev nodes
- When using dev mode, it assumes that the node is the latest with derived sr25519 keys
# 0.47.1
# 0.47.1 Mar 14, 2019
- Swap to publishing -beta.x on merge (non-breaking testing)
# 0.46.1
# 0.46.1 Mar 01, 2019
- Extended type registration to now handle internal types as well. Additionally the built-in Extrinsic type can now we overridden with a custom version.
- Where `Extrinsic` and `Method` is used as types, consider importing `{ IMethod, IExtrinsic }` from `@polkadot/types/types`, especially in the cases where this is used from a `SubmittableExtrinsic`
- The `typeRegistry` constant is now `getTypeRegistry()` as a function
# 0.45.1
# 0.45.1 Feb 19, 2019
- Storage with option values now correctly return `Option<Type>` and is indicated as such in the documentation
@@ -307,7 +374,7 @@ console.log('llo', llo.unwrapOr('not set') /* Option<BlockNumber> */)
```
# 0.44.1
# 0.44.1 Feb 19, 2019
- Split primitives and types into separate folders. This should not affect external use since the exports remain the same, however does have an impact where classes are referenced directly. e.g.
@@ -325,45 +392,45 @@ import { Method, Signature } from '@polkadot/types';
```
# 0.43.1
# 0.43.1 Feb 14, 2019
- Introduces support for the new keyring with sr25519 support in addition to ed25519. While this does not change the exposed API, it is considered breaking since @polkadot/keyring has interface changes. (Unless needed, don't rush the upgrade)
# 0.42.1
# 0.42.1 Jan 31, 2019
- Support for substrate hash signing with implVersion >= 18
- Changed signatures for Extrinsic signing, this should not have (much) of an impact since it is generally not used directly. SubmittableExtrinsic (as exposed by the API), supports the old-style use.
# 0.41.1
# 0.41.1 Jan 26, 2019
- Support the V1 metadata specification from Substrate in addition to the currently testnet active V0 version
# 0.40.1
# 0.40.1 Jan 16, 2019
- The API interfaces now require a WS-compatible provider, e.g. subscription support is a must. Previously the HTTPProvider could be use (although it was very limited in the interactions).
# 0.39.1
# 0.39.1 Jan 11, 2019
- The Promise API now returns a `Promise<UnsubFunction>` instead of `UnsubFunction` when making subscriptions.
# 0.38.1
# 0.38.1 Jan 08, 2019
Substrate has been updated with a breaking new transaction format where the Index/Nonce is now encoded as a Compact. This change is being rolled out to both Alexander (Polkadot testnet) as well as Charred Cherry (Substrate testnet) - transactions between old and new are not compatible.
# 0.37.1
# 0.37.1 Jan 04, 2019
api-observable has been removed. This was only used in /apps and inconsistent with the api/rx and api/promise APIs. Future work will include derives like was included in api-observable into the base.
Tuples now return single types when only one type is available, i.e. `(AccountId)` would now resolve as `AccountId`. The extra type wrapper adds no benefit to users here.
# 0.36.1
# 0.36.1 Jan 03, 2019
Api Promise has been updated in the way we deal with subscriptions. Previously a subscription returned `Promise<number>` where the caller was to keep track of the id and use it in subsequent unsubscribes. Now any subscriptions return an unsubscribe/destroy function `(): void`, that is use for removing the subscriptions, e.g.
@@ -374,11 +441,51 @@ unsubscribe(); // here we destroy the subscription
```
# 0.35.1
# 0.35.1 Dec 20, 2018
Swapped to new metadata structures from Substrate. If the API is not working with your node, update Substrate to latest master branch. (Or 0.9.1 for Charred Cherry). Dropped support for old metadata as found as far back as BBQ Birch.
# 0.34.1
# 0.34.1 Dec 18, 2018
Changed the send signature (for future expansion of eg. events) to return `result: { status: ExtrinsicStatus }` instead of `status: ExtrinsicStatus`. For most cases where only status `type` checks are used, i.e. `status.type === 'Finalised'` this should not be a breaking change. Deep inspection of the status object however will need to adapt.
# 0.33.1 Dec 06, 2018
# 0.32.1 Nov 21, 2018
# 0.31.1 Oct 10, 2018
# 0.30.1 Sep 27, 2018
# 0.29.1 Sep 14, 2018
# 0.28.1 Aug 11, 2018
# 0.15.1 Aug 07, 2018
# 0.14.1 Jun 23, 2018
# 0.13.1 May 29, 2018
# 0.12.1 May 18, 2018
# 0.11.1 May 16, 2018
# 0.10.1 May 07, 2018
# 0.9.1 Apr 24, 2018
# 0.8.1 Mar 15, 2018
# 0.7.1 Jan 25, 2018
# 0.6.1 Dec 03, 2017
# 0.5.1 Nov 28, 2017
# 0.4.1 Nov 19, 2017
# 0.3.1 Nov 19, 2017
# 0.2.1 Nov 18, 2017
+1 -1
View File
@@ -27,7 +27,7 @@ The API is split up into a number of internal packages -
Type definitions for interfaces as exposed by Polkadot & Substrate clients -
- [@polkadot/jsonrpc](packages/type-jsonrpc/) Definitions for JSONRPC endpoints
- [@polkadot/jsonrpc](packages/jsonrpc/) Definitions for JSONRPC endpoints
- [@polkadot/types](packages/types/) Codecs for all Polkadot and Substrate primitives
## development
+1 -3
View File
@@ -1,3 +1 @@
module.exports = {
extends: '@polkadot/dev/config/babel'
};
module.exports = require('@polkadot/dev/config/babel');
+10 -9
View File
@@ -2,7 +2,7 @@
function copy_folder () {
SRC="packages/$1/build"
DST="../apps/node_modules/@polkadot/$2"
DST="../apps/node_modules/@polkadot/$1"
echo "** Copying $SRC to $DST"
@@ -12,11 +12,12 @@ function copy_folder () {
yarn polkadot-dev-build-ts
copy_folder "api" "api"
copy_folder "api-contract" "api-contract"
copy_folder "api-derive" "api-derive"
copy_folder "metadata" "metadata"
copy_folder "rpc-core" "rpc-core"
copy_folder "rpc-provider" "rpc-provider"
copy_folder "type-jsonrpc" "jsonrpc"
copy_folder "types" "types"
copy_folder "api"
copy_folder "api-contract"
copy_folder "api-derive"
copy_folder "metadata"
copy_folder "rpc-core"
copy_folder "rpc-provider"
copy_folder "jsonrpc"
copy_folder "types"
copy_folder "typegen"
+4 -1
View File
@@ -43,6 +43,7 @@ module.exports = {
['start/api.tx.wrap.md', 'Complex transactions'],
['start/types.basics.md', 'Type basics'],
['start/types.extend.md', 'Extending types'],
['start/types.create.md', 'Creating types'],
['start/extrinsic.extend.md', 'Extending extrinsics'],
['start/typescript.md', 'TypeScript interfaces'],
['start/typescript.user.md', 'TypeScript user generated'],
@@ -68,6 +69,7 @@ module.exports = {
},
{
title: 'Substrate defaults',
path: '/substrate/',
collapsable: false,
sidebarDepth: 0,
children: [
@@ -75,7 +77,8 @@ module.exports = {
['substrate/constants.md', 'Constants'],
['substrate/storage.md', 'State storage'],
['substrate/extrinsics.md', 'Extrinsics'],
['substrate/events.md', 'System events']
['substrate/events.md', 'System events'],
['substrate/errors.md', 'Errors']
]
},
['/api/', '@polkadot/api'],
@@ -13,21 +13,23 @@ async function main () {
// Retrieve the initial balance. Since the call has no callback, it is simply a promise
// that resolves to the current on-chain value
let previous = await api.query.balances.freeBalance(Alice);
let { nonce: previousNonce, data: { free: previousFree } } = await api.query.system.account(Alice);
console.log(`${Alice} has a balance of ${previous}`);
console.log(`${Alice} has a balance of ${previousFree}, nonce ${previousNonce}`);
console.log(`You may leave this example running and start example 06 or transfer any value to ${Alice}`);
// Here we subscribe to any balance changes and update the on-screen value
api.query.balances.freeBalance(Alice, (current) => {
api.query.system.account(Alice, ({ nonce: currentNonce, data: { free: currentFree } }) => {
// Calculate the delta
const change = current.sub(previous);
const change = currentFree.sub(previousFree);
// Only display positive value changes (Since we are pulling `previous` above already,
// the initial balance change will also be zero)
if (!change.isZero()) {
previous = current;
console.log(`New balance change of: ${change}`);
console.log(`New balance change of ${change}, nonce ${currentNonce}`);
previousFree = currentFree;
previousNonce = currentNonce;
}
});
}
@@ -15,8 +15,8 @@ async function main () {
console.log('Tracking balances for:', [ALICE, BOB]);
// Subscribe and listen to several balance changes
api.query.balances.freeBalance.multi([ALICE, BOB], (balances) => {
console.log('Change detected, new balances: ', balances);
api.query.system.account.multi([ALICE, BOB], (balances) => {
console.log('Change detected, new balances: ', balances.map(({ data: { free } }) => free));
});
}
@@ -12,8 +12,8 @@ async function main () {
const api = await ApiPromise.create();
// Make our basic chain state/storage queries, all in one go
const [accountNonce, now, validators] = await Promise.all([
api.query.system.accountNonce(ALICE),
const [{ nonce: accountNonce }, now, validators] = await Promise.all([
api.query.system.account(ALICE),
api.query.timestamp.now(),
api.query.session.validators()
]);
@@ -25,14 +25,15 @@ async function main () {
// Retrieve the balances for all validators
const validatorBalances = await Promise.all(
validators.map(authorityId =>
api.query.balances.freeBalance(authorityId)
api.query.system.account(authorityId)
)
);
// Print out the authorityIds and balances of all validators
console.log('validators', validators.map((authorityId, index) => ({
address: authorityId.toString(),
balance: validatorBalances[index].toString()
balance: validatorBalances[index].data.free.toHuman(),
nonce: validatorBalances[index].nonce.toHuman()
})));
}
}
@@ -19,14 +19,14 @@ async function main () {
// Retrieve the balance at the preceding block for Alice. For at queries
// the format is always `.at(<blockhash>, ...params)`
const balance = await api.query.balances.freeBalance.at(parentHash, ALICE);
const balance = await api.query.system.account.at(parentHash, ALICE);
console.log(`Alice's balance at ${parentHash.toHex()} was ${balance}`);
console.log(`Alice's balance at ${parentHash.toHex()} was ${balance.data.free}`);
// Now perform a multi query, returning multiple balances at once
const balances = await api.query.balances.freeBalance.multi([ALICE, BOB]);
const balances = await api.query.system.account.multi([ALICE, BOB]);
console.log(`Current balances for Alice and Bob are ${balances[0]} and ${balances[1]}`);
console.log(`Current balances for Alice and Bob are ${balances[0].data.free} and ${balances[1].data.free}`);
}
main().catch(console.error).finally(() => process.exit());
@@ -19,7 +19,7 @@ async function main () {
const alice = keyring.addFromUri('//Alice');
// Get nonce for account
const nonce = await api.query.system.accountNonce(alice.address);
const { nonce } = await api.query.system.account(alice.address);
// Get current block
const signedBlock = await api.rpc.chain.getBlock();
@@ -24,7 +24,7 @@ async function main () {
const keyring = testKeyring.default();
// Get the nonce for the admin key
const nonce = await api.query.system.accountNonce(ALICE);
const { nonce } = await api.query.system.account(ALICE);
// Find the actual keypair in the keyring
const alicePair = keyring.getPair(ALICE);
@@ -40,13 +40,15 @@ async function main () {
.signAndSend(alicePair, { nonce }, ({ events = [], status }) => {
console.log('Transaction status:', status.type);
if (status.isFinalized) {
console.log('Completed at block hash', status.asFinalized.toHex());
if (status.isInBlock) {
console.log('Included at block hash', status.asInBlock.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
} else if (status.isFinalized) {
console.log('Finalized block hash', status.asFinalized.toHex());
process.exit(0);
}
@@ -39,15 +39,15 @@ async function main () {
.signAndSend(adminPair, ({ events = [], status }) => {
console.log('Proposal status:', status.type);
if (status.isFinalized) {
if (status.isInBlock) {
console.error('You have just upgraded your chain');
console.log('Completed at block hash', status.asFinalized.toHex());
console.log('Included at block hash', status.asInBlock.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
console.log(JSON.stringify(events.toHuman(), null, 2));
} else if (status.isFinalized) {
console.log('Finalized block hash', status.asFinalized.toHex());
process.exit(0);
}
@@ -14,7 +14,7 @@ async function main () {
// Here we subscribe to any balance changes and update the on-screen value.
// We're using RxJs pairwise() operator to get the previous and current values as an array.
api.query.balances.freeBalance(Alice)
api.query.system.account(Alice)
.pipe(
// since pairwise only starts emitting values on the second emission, we prepend an
// initial value with the startWith() operator to be able to also receive the first value
@@ -25,12 +25,13 @@ async function main () {
if (balance[0] === 'first') {
// Now we know that if the previous value emitted as balance[0] is `first`,
// then balance[1] is the initial value of Alice account.
console.log(`Alice ${Alice} has a balance of ${balance[1]}`);
console.log(`Alice ${Alice} has a balance of ${balance[1].data.free}`);
console.log('You may leave this example running and start the "Make a transfer" example or transfer any value to Alice address');
return;
}
const change = balance[1].sub(balance[0]);
const change = balance[1].data.free.sub(balance[0].date.free);
// Only display value changes
if (!change.isZero()) {
console.log(`New balance change of: ${change}`);
+6 -5
View File
@@ -22,13 +22,13 @@ function main () {
// In the next step, we're checking if the node has active validators.
// If it does, we're making another call to the api to get the balances for all validators
const balances = (validators && validators.length > 0)
? combineLatest(validators.map(authorityId => api.query.balances.freeBalance(authorityId).pipe(first())))
? combineLatest(validators.map(authorityId => api.query.system.account(authorityId).pipe(first())))
: of(null);
// We're combining the results together with the emitted value 'validators',
// which we're turning back into an observable using of()
return combineLatest(
api.query.system.accountNonce(Alice).pipe(first()),
api.query.system.account(Alice).pipe(first()),
api.query.timestamp.blockPeriod().pipe(first()),
of(validators),
balances
@@ -36,15 +36,16 @@ function main () {
})
)
// Then we're subscribing to the emitted results
.subscribe(([accountNonce, blockPeriod, validators, validatorBalances]) => {
console.log(`accountNonce(${Alice}) ${accountNonce}`);
.subscribe(([{ nonce }, blockPeriod, validators, validatorBalances]) => {
console.log(`accountNonce(${Alice}) ${nonce}`);
console.log(`blockPeriod ${blockPeriod.toNumber()} seconds`);
if (validatorBalances) {
// And lastly we print out the authorityIds and balances of all validators
console.log('validators', validators.map((authorityId, index) => ({
address: authorityId.toString(),
balance: validatorBalances[index].toString()
balance: validatorBalances[index].data.free.toString(),
nonce: validatorBalances[index].data.toString()
})));
}
});
+7 -2
View File
@@ -25,9 +25,14 @@ async function main () {
.signAndSend(alice)
// Subscribe to the status updates of the transfer
.subscribe(({ status }) => {
if (status.isFinalized) {
console.log(`Successful transfer of 12345 from Alice to Bob with hash ${status.asFinalized.toHex()}`);
if (status.isInBlock) {
console.log(`Successful transfer of 12345 from Alice to Bob at block ${status.asInBlock.toHex()}`);
} else if (status.isFinalized) {
console.log('Finalized block hash', status.asFinalized.toHex());
subscription.unsubscribe();
process.exit(0);
} else {
console.log(`Status of transfer: ${status.type}`);
}
+6 -2
View File
@@ -44,13 +44,17 @@ async function main () {
console.log('Transfer status:', status.type);
// Log system events once the transfer is finalised
if (status.isFinalized) {
console.log('Completed at block hash', status.asFinalized.toHex());
if (status.isInBlock) {
console.log('Included at block hash', status.asInBlock.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
} else if (status.isFinalized) {
console.log('Finalized block hash', status.asFinalized.toHex());
process.exit(0);
}
});
}
+5 -5
View File
@@ -40,16 +40,16 @@ async function main () {
// Log transfer events
console.log('Proposal status:', status.type);
if (status.isFinalized) {
if (status.isInBlock) {
console.error('You have just upgraded your chain');
console.log('Completed at block hash', status.asFinalized.toHex());
console.log('Included at block hash', status.asInBlock.toHex());
console.log('Events:');
// Log system events once the chain update is finalised
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
console.log(JSON.stringify(events.toHuman(), null, 2));
} else if (status.isFinalized) {
console.log('Finalized block hash', status.asFinalized.toHex());
process.exit(0);
}
+8
View File
@@ -33,3 +33,11 @@ Tuples, as defined in the Polkadot/Substrate types appear as `(TypeA, TypeB)`. F
Polkadot/Substrate supports both immortal and mortal transactions. For immortal, this means that the transaction has an infinite lifetime, for mortals, the transactions expire after a defined period. By default the API sends mortal transactions when no explicit extrinsic era has been specified. This means that all transaction has a limited lifetime and will expire if not included in the period set.
The length for this transaction validity is set to 50 blocks, which translates to 5 minutes assuming a default of 6 second blocktimes. (10 blocks per minute in this default configuration).
## My chain does not support system.account queries
The API always tracks the latest Substrate master in terms of examples. This means that nonce & balance queries are done via the `api.query.system.account(<account>)` which returns a struct `{ nonce: Index, data: AccountData }` where the `data` is struct containing the free and reserved balances. As with all `api.query.*` endpoints, this is decorated based on what the chain you connect to support, via the metadata exchange.
It is possible that you are connecting to an older chain that has not been upgraded yet. For these chains, this storage entry won't be available (yet). To query the nonce on older chains, you can do a query to `api.query.system.accountNonce(<account>)` and balances can be retrieved via `api.query.balances.freeBalance(<account>)`.
Likewise, if your chain has been upgraded recently and you are still using the old `system.accountNonce` or `balances.freeBalance` queries in your code (which is now not available in the chain metadata), you need to update it to query the new location.
+6 -10
View File
@@ -16,24 +16,20 @@ const ADDR = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFabHE';
// Retrieve the last timestamp
const now = await api.query.timestamp.now();
// Retrieve the account nonce via the system module
const nonce = await api.query.system.accountNonce(ADDR);
// Retrieve the account balance & nonce via the system module
const { nonce, data: balance } = await api.query.system.account(ADDR);
// Retrieve the account balance via the balances module
const balance = await api.query.balances.freeBalance(ADDR);
console.log(`${now}: balance of ${balance} and a nonce of ${nonce}`);
console.log(`${now}: balance of ${balance.free} and a nonce of ${nonce}`);
```
There have been some additions in the code above comparing with retrieving runtime constants. In these cases, since we are making a query to the actual chain, we use the `await` syntax to retrieve the information. Since the API is Promise-based, this means we can also rewrite the above to follow a Promise pattern,
```js
...
// Retrieve last block timestamp, account nonce & balance
const [now, nonce, balance] = await Promise.all([
// Retrieve last block timestamp, account nonce & balances
const [now, { nonce, data: balances }] = await Promise.all([
api.query.timestamp.now(),
api.query.system.accountNonce(ADDR),
api.query.balances.freeBalance(ADDR)
api.query.system.account(ADDR)
]);
```
+10 -11
View File
@@ -10,14 +10,14 @@ Where possible, the use of multi queries are encouraged since it tracks a number
...
// Subscribe to balance changes for 2 accounts, ADDR1 & ADDR2 (already defined)
const unsub = await api.query.balances.freeBalance.multi([ADDR1, ADDR2], (balances) => {
const [balance1, balance2] = balances;
const unsub = await api.query.system.account.multi([ADDR1, ADDR2], (balances) => {
const [{ data: balance1 }, { data: balance2 }] = balances;
console.log(`The balances are ${balance1} and ${balance2}`);
console.log(`The balances are ${balance1.free} and ${balance2.free}`);
});
```
A couple of items to note in the example above: we don't call `freeBalance` directly, but rather `freeBalance.multi`. We pass the addresses we want to query as an array, and the length thereof would depend on the number of addresses we want to query. As an extended example, we can track the balances of a list of validators,
A couple of items to note in the example above: we don't call `account` directly, but rather `account.multi`. We pass the addresses we want to query as an array, and the length thereof would depend on the number of addresses we want to query. As an extended example, we can track the balances of a list of validators,
```js
...
@@ -26,8 +26,8 @@ A couple of items to note in the example above: we don't call `freeBalance` dire
const validators = await api.query.session.validators();
// Subscribe to the balances for these accounts
const unsub = await api.query.balances.freeBalance.multi(validators, (balances) => {
console.log(`The balances are: ${balances}`);
const unsub = await api.query.balances.account.multi(validators, (balances) => {
console.log(`The nonce and free balances are: ${balances.map(([nonce, { free }]) => [nonce, free])}`);
});
```
@@ -43,17 +43,16 @@ The previous `.multi` examples assumes that we do queries for the same types, i.
// Subscribe to the timestamp, our index and balance
const unsub = await api.queryMulti([
api.query.timestamp.now,
[api.query.system.accountNonce, ADDR],
[api.query.balances.freeBalance, ADDR]
], ([now, nonce, balance]) => {
console.log(`${now}: balance of ${balance} and a nonce of ${nonce}`);
[api.query.system.account, ADDR]
], ([now, { nonce, data: balance }]) => {
console.log(`${now}: balance of ${balance.free} and a nonce of ${nonce}`);
});
```
The above example certainly does not quite look as ergonomic and clean, but the API needs to understand (a) which are all the calls we need to make and (b) the calls and their params (if required). So breaking it down -
- `api.query.timestamp.now` - the timestamp is passed naked without any params. Also note that we do not call it while passing, but rather only provides a reference to the function, i.e. we do not have the expected `()` at the end. (This could also be of the form `[api.query.timestamp.now]`, aligning with subsequent entries)
- `[api.query.system.accountNonce, ADDR]` - the nonce query is passed as an array containing the function (once again naked), followed by the parameters that apply.
- `[api.query.system.account, ADDR]` - the nonce & balance query is passed as an array containing the function (once again naked), followed by the parameters that apply.
## Rounding out queries
+8 -8
View File
@@ -13,13 +13,13 @@ Quite often is is useful (taking pruning into account, more on this later) to re
const lastHdr = await api.rpc.chain.getHeader();
// Retrieve the balance at both the current and the parent hashes
const [balanceNow, balancePrev] = await Promise.all([
api.query.balances.freeBalance.at(lastHdr.hash, ADDR),
api.query.balances.freeBalance.at(lastHdr.parentHash, ADDR)
const [{ data: balanceNow }, { data: balancePrev }] = await Promise.all([
api.query.system.account.at(lastHdr.hash, ADDR),
api.query.system.account.at(lastHdr.parentHash, ADDR)
]);
// Display the difference
console.log(`The delta was ${balanceNow.sub(balancePrev)}`);
console.log(`The delta was ${balanceNow.free.sub(balancePrev.free)}`);
```
In the above example, we introduce the `.at(<hash>[, ...params])` query. For all `.at` queries, the first parameter is always the block hash at which we want to make the query, in our example we use both the last retrieved block and the parent thereof. The params are optional as per the type of query made, for instance to retrieve the timestamp for a previous block, it would be -
@@ -44,8 +44,8 @@ In addition to using `api.query` to make actual on-chain queries, it can also be
// Retrieve the hash & size of the entry as stored on-chain
const [entryHash, entrySize] = await Promise.all([
api.query.balances.freeBalance.hash(ADDR),
api.query.balances.freeBalance.size(ADDR)
api.query.system.account.hash(ADDR),
api.query.system.account.size(ADDR)
]);
// Output the info
@@ -60,11 +60,11 @@ It has been explained that the `api.query` interfaces are decorated from the met
```js
// Extract the info
const { meta, method, section } = api.query.balances.freeBalance;
const { meta, method, section } = api.query.system.account;
// Display some info on a specific entry
console.log(`${section}.${method}: ${meta.documentation.join(' ')}`);
console.log(`query key: ${api.query.balances.freeBalance.key(ADDR)}`);
console.log(`query key: ${api.query.system.account.key(ADDR)}`);
```
The `section` & `method` is an indication of where it is exposed on the API. In addition the `meta` holds an array with the metadata documentation for the entry.
+2 -2
View File
@@ -25,8 +25,8 @@ If we had a query with parameters, i.e. where we wish to perform a query for a s
...
// Subscribe to balance changes for our account
const unsub = await api.query.balances.freeBalance(ADDR, (balance) => {
console.log(`Your account balance is ${balance}`);
const unsub = await api.query.system.account(ADDR, ({ nonce, data: balance }) => {
console.log(`free balance is ${balance.freee} with ${balance.reserved} reserved and a nonce of ${nonce}`);
});
```
+1 -1
View File
@@ -28,7 +28,7 @@ The result for this call (we will deal with subscriptions in a short while), is
Despite the single-line format of `signAndSend`, there is a lot happening under the hood (and all of this can be manually provided) -
- Based on the sender, the API will retrieve the `system.accountNonce` to determine the next nonce to use
- Based on the sender, the API will query `system.account` (or `system.accountNonce` on older chains) to determine the next nonce to use
- The API will retrieve the current block hash and use it to create a mortal transaction, i.e. the transaction will only be valid for a limited number of blocks (by default this is 5 mins at 6s block times)
- It will construct a payload and sign this, this includes the `genesisHash`, the `blockHash` for the start of the mortal era as well as the current chain `specVersion`
- The transaction is submitted to the node
+5 -3
View File
@@ -18,8 +18,10 @@ const unsub = await api.tx.balances
.signAndSend(alice, (result) => {
console.log(`Current status is ${result.status}`);
if (result.status.isFinalized) {
console.log(`Transaction included at blockHash ${result.status.asFinalized}`);
if (result.status.isInBlock) {
console.log(`Transaction included at blockHash ${result.status.asInBlock}`);
} else if (result.status.isFinalized) {
console.log(`Transaction finalized at blockHash ${result.status.asFinalized}`);
unsub();
}
});
@@ -27,7 +29,7 @@ const unsub = await api.tx.balances
As per all previous subscriptions, the transaction subscription returns in `unsub()` and the actual method has a subscription callback. The `result` object has 2 parts, `events` (to to covered in the next section) and the `status` enum.
When the `status` enum is in `Finalized` state (checked via `isFinalized`), the underlying value contains the block hash of the block where the transaction has been included. This does not mean the block is finalized, but rather applies to the transaction state, as no further updates will be received for this subscription.
When the `status` enum is in `Finalized` state (checked via `isFinalized`), the underlying value contains the block hash of the block where the transaction has been finalized. `Finalized` will follow `InBlock`, which is the block where the transaction has been included. `InBlock` does not mean the block is finalized, but rather applies to the transaction state, where `Finalized` means that the transaction cannot be forked off the chain.
## Transaction events
+5 -3
View File
@@ -6,14 +6,16 @@ To unpack this, we will start with the Metadata and explain what it actually pro
## Metadata
When the API connects to a node, one of the first things it does is to retrieve the metadata. The metadata, effectively provides data in the form of `api.<type>.<module>.<section>` that fits into one of the following categories -
When the API connects to a node, one of the first things it does is to retrieve the metadata and decorate the API based on the metadata information. The metadata effectively provides data in the form of `api.<type>.<module>.<section>` that fits into one of the following categories -
- [consts](../substrate/constants.md) - All runtime constants, e.g. `api.consts.balances.creationFee`. These are not functions, rather accessing the endpoint immediately yields the result as defined.
- [query](../substrate/storage.md) - All chain state, e.g. `api.query.balances.freeBalance(<accountId>)`.
- [consts](../substrate/constants.md) - All runtime constants, e.g. `api.consts.balances.existentialDeposit`. These are not functions, rather accessing the endpoint immediately yields the result as defined.
- [query](../substrate/storage.md) - All chain state, e.g. `api.query.system.account(<accountId>)`.
- [tx](../substrate/extrinsics.md) - All extrinsics, e.g. `api.tx.balances.transfer(<accountId>, <value>)`.
Additionally the metadata also provides information on [events](../substrate/events.md), these are query-able via the `api.query.system.events()` interface and also appear on transactions... both these cases are detailed later.
None of the information contained within the `api.{consts, query, tx}.<module>.<method>` endpoints are hard coded in the API. Rather everything is fully decorated by what the metadata exposes and is therefore completely dynamic. This means that when you connect to different chains, the metadata and API decoration will change and the API interfaces will reflect what is available on the chain you are connected to.
## Types
The metadata defines the calls with all the type names used in the various interfaces. At the moment (this is undergoing investigations and could improve in future versions of metadata), this also means that the types between the API and the node need to be aligned. For instance, by default Substrate defines a `BlockNumber` type as a `u32` and the API follows the Substrate defaults - if a chain has a different definitions, the API needs to be aware of this so it can actually decode (and encode) the type.
+6
View File
@@ -68,6 +68,12 @@ await api.isReady;
console.log(api.genesisHash.toHex());
```
## Failures
In all cases the API will handle reconnections automatically. This means that when you connect and the endpoint is not (yet) ready, the promise will not resolve immediately, but rather when connected. The same applies to when connection is lost, the API will manage re-connections.
In cases where the API does not support the chain being connected to, such as it using an unknown metadata version, the ready promise will fail to resolve and instead reject.
## Advanced creation
There are more advanced cases where you would prefer to use the longer version, for instance: if you want to explicitly listen to events emitted, you probably want to attach to the API even before connecting to the chain. All API instances implement an `EventEmitter` interface, with `on` handlers, which emit `connected`, `disconnected`, `ready` and `error` events, allowing you to listen to events on the transport layer.
+3 -1
View File
@@ -27,7 +27,7 @@ For example:
```js
const { metadata } = await api.rpc.state.getMetadata();
const modules = metadata.asV3.modules;
const modules = metadata.asLatest.modules;
// This will not work, because `name` is an instance of `Text`, not a string
// const system = modules.find(m => m.name === 'system');
@@ -79,6 +79,8 @@ const [count, accountId] = tuple;
console.log(`${accountId} has ${count.toNumber()} values`);
```
When making a call that expect a `Tuple` input, pass it as an array, so to pass the example above into a call, it would be `.call([123, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'])`
## Extending types
For customized chains, the need exists to register types so the API is aware of how to decode values for those types. The next section will provide a [walk-through for the definition of custom types](types.extend.md) allowing the definition or re-definition of any type the API is aware of.
+54
View File
@@ -0,0 +1,54 @@
# Type creation
Circling back to metadata. There are two important things to remember when using the API to make queries or send transactions.
1. The functionality available, e.g. exposed on `api.query.*` is not hard-coded in the API, rather this is decorated from the chain metadata. So the metadata lets the API know which endpoints are available and what the type for those endpoints are.
2. When you supply a value to the API, internally it will convert that value to the correct type as expected by the chain, i.e. as determined by the metadata. This means that a function such as `balances.transfer(address: Address, value: Balance)` can take at least the following inputs, which are all converted to the correct types -
- `address` can be an `Address`, an `AccountId`, an `Uint8Array` publicKey, a hex publicKey or an ss58 formatted address;
- `value` can be a `Balance`, a value encoded in hex, a `BN` object, a base-10 string, a JS `number`, a JS `BigInt` or even a SCALE-encoded `Uint8Array`
In cases where a value is returned such as storage queries, the response from the chain is always encoded into the correct `Codec` type. This means that while the node may return an encoded block (with encoded extrinsics) via `api.rpc.chain.getBlock()`, this is decoded into a proper `SignedBlock` by the API. Outputting this value via `.toJSON()` will yield an encoding for RPC, so if you are not using TypeScript (which adds code helpers on decoded objects), a representation via `.toHuman()` will be more representative of the actual object fields, re-formatted for human consumption.
## Why create types
With the conversions done in the API, there are limited reasons to create types "manually". However, just because there are not thousands of reasons, does not mean it is not valid. For instance, you may retrieve an `Option` and for the sake of sanity would like to use `.unwrapOr()` on it, returning a `Codec` default value where the value `.isNone`.
```js
// type import for TypeScript
import type { Balance } from '@polkadot/types/interfaces';
...
// unwrap out option into a zero Balance whn not found
const balance: Balance = balanceOpt.unwrapOr(api.createType('Balance'));
```
In the example above, we introduced the `api.createType(<typeName>, [<value>])`. The same format is also exposed by the `TypeRegistry` (more on this in a short while) as well as `createType(...)` from the actual `@polkadot/types` package. All doing exactly the same.
## Choosing how to create
In most cases, you would always want to use the `api.createType` helper. What this does is call the underlying `@polkadot/types` `createType`, passing through the registry that is attached to the API. Registry? Yes, registry.
The registry contains a listing of all internal types and their classes that have been registered. So upon creation of an API instance, a `registry` object is attached to the API and this is passed through to all created types. This allows the type definitions to not pollute the global namespace, but rather be contained and able to reference one another.
As mentioned, the `createType` functions all do exactly the same, and it 99.99% of the cases you would be recommended to just forget about everything and use `api.createType` if and when required. In some cases, you may just have a type object and from that want to create another type instance. For that you can access the `registry` on the type object and call `createType` on it. (If this type object was created from an API instance, the registry on the type and on the API will point to the same instance.)
Basically, this means that we have equivalency in creation for all the items below, all creating on the same registry (containing all injected types), and all wrapping the same value -
```js
import { createType } from '@polkadot/types';
// via API (recommended)
api.createType('Balance', 123);
// via registry (`.registry` is on all API and Codec objects)
api.registry.createType('Balance', 123n);
// via the low-level approach
createType(api.registry, 'Balance', '123');
```
## Extending extrinsics
On customized chains, it is possible to [extend the format of the extrinsics and extrinsic payload for the chain](extrinsic.extend.md), next up we will look at this advanced use-case.
+2 -2
View File
@@ -137,6 +137,6 @@ const api = await ApiPromise.create({
`Balance` would be defined as an `u128` at the end. Effectively based on the flow it is first registered as a `u32`, then overridden as a `u64` and finally overridden once more as a `u128` by the chain types.
## Extending extrinsics
## Type creation
On customized chains, it is possible to [extend the format of the extrinsics and extrinsic payload as customized on the chain](extrinsic.extend.md), next up we will look at this advanced use-case.
While the API always converts all the inputs into the underlying type required by the operation, in some cases you may want to [cret an instance of a type](types.create.md) yourself.
+2 -10
View File
@@ -30,22 +30,14 @@ For any interface injected by metadata, the types are not available by default (
However, to make this sane from a developer perspective the injected methods are generic, effectively making the following possible -
```js
import { Balance, Index } from '@polkadot/types/interfaces';
import { AccountData, Index } from '@polkadot/types/interfaces';
...
const nonce = await api.query.system.accountNonce<Index>(ADDR);
const balance = await api.query.balances.freeBalance<Balance>(ADDR);
const { nonce, data: balances } = await api.query.system.account<[Index, AccountData]>(ADDR);
```
In both these case we can instruct the TypeScript compiler that the type we are expecting in `Index` and `Balance` respectively, not just pure `Codec`. This means that functions like `.toNumber()` is available on both these types - as opposed to just the [general type defaults](types.basics.md#everything-is-a-type) with `.toHex()` and friends.
## Future work
As of this writing, there are still some gray areas to type detection, specifically around the following interfaces -
- `.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
## Adding user types
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).
+2 -2
View File
@@ -6,14 +6,14 @@ In the previous section we looked at the TypeScript definitions that are availab
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.
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`.
In the root of your project (with the `@polkadot/typegen` package installed), 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
-225
View File
@@ -1,225 +0,0 @@
## Constants
The following sections contain the module constants, also known as parameter types. These can only be changed as part of a runtime upgrade. On the api, these are exposed via `api.consts.<module>.<method>`.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[babe](#babe)**
- **[balances](#balances)**
- **[contracts](#contracts)**
- **[democracy](#democracy)**
- **[elections](#elections)**
- **[finalityTracker](#finalityTracker)**
- **[session](#session)**
- **[staking](#staking)**
- **[timestamp](#timestamp)**
- **[treasury](#treasury)**
___
### babe
▸ **epochDuration**: `u64`
- **summary**: The number of **slots** that an epoch takes. We couple sessions to epochs, i.e. we start a new session once the new epoch begins.
▸ **expectedBlockTime**: `Moment`
- **summary**: The expected average block time at which BABE should be creating blocks. Since BABE is probabilistic it is not trivial to figure out what the expected average block time should be based on the slot duration and the security parameter `c` (where `1 - c` represents the probability of a slot being empty).
___
### balances
▸ **creationFee**: `Balance`
- **summary**: The fee required to create an account.
▸ **existentialDeposit**: `Balance`
- **summary**: The minimum amount required to keep an account open.
▸ **transactionBaseFee**: `Balance`
- **summary**: The fee to be paid for making a transaction; the base.
▸ **transactionByteFee**: `Balance`
- **summary**: The fee to be paid for making a transaction; the per-byte portion.
▸ **transferFee**: `Balance`
- **summary**: The fee required to make a transfer.
___
### contracts
▸ **blockGasLimit**: `Gas`
- **summary**: The maximum amount of gas that could be expended per block. A reasonable default value is 10_000_000.
▸ **callBaseFee**: `Gas`
- **summary**: The base fee charged for calling into a contract. A reasonable default value is 135.
▸ **contractFee**: `BalanceOf`
- **summary**: The fee required to instantiate a contract instance. A reasonable default value is 21.
▸ **creationFee**: `BalanceOf`
- **summary**: The fee required to create an account.
▸ **instantiateBaseFee**: `Gas`
- **summary**: The base fee charged for instantiating a contract. A reasonable default value is 175.
▸ **maxDepth**: `u32`
- **summary**: The maximum nesting level of a call/instantiate stack. A reasonable default value is 100.
▸ **maxValueSize**: `u32`
- **summary**: The maximum size of a storage value in bytes. A reasonable default is 16 KiB.
▸ **rentByteFee**: `BalanceOf`
- **summary**: Price of a byte of storage per one block interval. Should be greater than 0.
▸ **rentDepositOffset**: `BalanceOf`
- **summary**: The amount of funds a contract should deposit in order to offset the cost of one byte. Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day, then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent. But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000, then it would pay 500 BU/day.
▸ **signedClaimHandicap**: `BlockNumber`
- **summary**: Number of block delay an extrinsic claim surcharge has. When claim surcharge is called by an extrinsic the rent is checked for current_block - delay
▸ **storageSizeOffset**: `u32`
- **summary**: Size of a contract at the time of instantiaion. This is a simple way to ensure that empty contracts eventually gets deleted.
▸ **surchargeReward**: `BalanceOf`
- **summary**: Reward that is received by the party whose touch has led to removal of a contract.
▸ **tombstoneDeposit**: `BalanceOf`
- **summary**: The minimum amount required to generate a tombstone.
▸ **transactionBaseFee**: `BalanceOf`
- **summary**: The fee to be paid for making a transaction; the base.
▸ **transactionByteFee**: `BalanceOf`
- **summary**: The fee to be paid for making a transaction; the per-byte portion.
▸ **transferFee**: `BalanceOf`
- **summary**: The fee required to make a transfer.
___
### democracy
▸ **cooloffPeriod**: `BlockNumber`
- **summary**: Period in blocks where an external proposal may not be re-submitted after being vetoed.
▸ **emergencyVotingPeriod**: `BlockNumber`
- **summary**: Minimum voting period allowed for an emergency referendum.
▸ **enactmentPeriod**: `BlockNumber`
- **summary**: The minimum period of locking and the period between a proposal being approved and enacted. It should generally be a little more than the unstake period to ensure that voting stakers have an opportunity to remove themselves from the system in the case where they are on the losing side of a vote.
▸ **launchPeriod**: `BlockNumber`
- **summary**: How often (in blocks) new public referenda are launched.
▸ **minimumDeposit**: `BalanceOf`
- **summary**: The minimum amount to be used as a deposit for a public referendum proposal.
▸ **votingPeriod**: `BlockNumber`
- **summary**: How often (in blocks) to check for new votes.
___
### elections
▸ **approvalSetSize**: `u32`
- **summary**: The chunk size of the approval vector.
▸ **candidacyBond**: `BalanceOf`
- **summary**: How much should be locked up in order to submit one's candidacy. A reasonable default value is 9.
▸ **carryCount**: `u32`
- **summary**: How many runners-up should have their approvals persist until the next vote. A reasonable default value is 2.
▸ **decayRatio**: `u32`
- **summary**: Decay factor of weight when being accumulated. It should typically be set to __at least__ `membership_size -1` to keep the collective secure. When set to `N`, it indicates `(1/N)^t` of staked is decayed at weight increment step `t`. 0 will result in no weight being added at all (normal approval voting). A reasonable default value is 24.
▸ **inactiveGracePeriod**: `VoteIndex`
- **summary**: How many vote indices need to go by after a target voter's last vote before they can be reaped if their approvals are moot. A reasonable default value is 1.
▸ **minimumVotingLock**: `BalanceOf`
- **summary**: Minimum about that can be used as the locked value for voting.
▸ **presentSlashPerVoter**: `BalanceOf`
- **summary**: The punishment, per voter, if you provide an invalid presentation. A reasonable default value is 1.
▸ **voterSetSize**: `u32`
- **summary**: The chunk size of the voter vector.
▸ **votingBond**: `BalanceOf`
- **summary**: How much should be locked up in order to be able to submit votes.
▸ **votingFee**: `BalanceOf`
- **summary**: The amount of fee paid upon each vote submission, unless if they submit a _hole_ index and replace it.
▸ **votingPeriod**: `BlockNumber`
- **summary**: How often (in blocks) to check for new votes. A reasonable default value is 1000.
___
### finalityTracker
▸ **reportLatency**: `BlockNumber`
- **summary**: The delay after which point things become suspicious. Default is 1000.
▸ **windowSize**: `BlockNumber`
- **summary**: The number of recent samples to keep from this chain. Default is 101.
___
### session
▸ **dedupKeyPrefix**: `Bytes`
- **summary**: Used as first key for `NextKeys` and `KeyOwner` to put all the data into the same branch of the trie.
___
### staking
▸ **bondingDuration**: `EraIndex`
- **summary**: Number of eras that staked funds must remain bonded for.
▸ **sessionsPerEra**: `SessionIndex`
- **summary**: Number of sessions per era.
___
### timestamp
▸ **minimumPeriod**: `Moment`
- **summary**: The minimum period between blocks. Beware that this is different to the *expected* period that the block production apparatus provides. Your chosen consensus system will generally work with this to determine a sensible block time. e.g. For Aura, it will be double this period on default settings.
___
### treasury
▸ **burn**: `Permill`
- **summary**: Percentage of spare funds (if any) that are burnt per spend period.
▸ **proposalBond**: `Permill`
- **summary**: Fraction of a proposal's value that should be bonded in order to place the proposal. An accepted proposal gets these back. A rejected proposal does not.
▸ **proposalBondMinimum**: `BalanceOf`
- **summary**: Minimum amount of funds that should be placed in a deposit for making a proposal.
▸ **spendPeriod**: `BlockNumber`
- **summary**: Period between successive spends.
-298
View File
@@ -1,298 +0,0 @@
## Events
Events are emitted for certain operations on the runtime. The following sections describe the events that are part of the default Substrate runtime.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[balances](#balances)**
- **[contracts](#contracts)**
- **[council](#council)**
- **[democracy](#democracy)**
- **[elections](#elections)**
- **[grandpa](#grandpa)**
- **[imOnline](#imOnline)**
- **[indices](#indices)**
- **[offences](#offences)**
- **[session](#session)**
- **[staking](#staking)**
- **[sudo](#sudo)**
- **[system](#system)**
- **[technicalCommittee](#technicalCommittee)**
- **[technicalMembership](#technicalMembership)**
- **[treasury](#treasury)**
- **[utility](#utility)**
___
### balances
▸ **NewAccount**(`AccountId`, `Balance`)
- **summary**: A new account was created.
▸ **ReapedAccount**(`AccountId`)
- **summary**: An account was reaped.
▸ **Transfer**(`AccountId`, `AccountId`, `Balance`, `Balance`)
- **summary**: Transfer succeeded (from, to, value, fees).
___
### contracts
▸ **CodeStored**(`Hash`)
- **summary**: Code with the specified hash has been stored.
▸ **Contract**(`AccountId`, `Bytes`)
- **summary**: An event from contract of account.
▸ **Dispatched**(`AccountId`, `bool`)
- **summary**: A call was dispatched from the given account. The bool signals whether it was successful execution or not.
▸ **Instantiated**(`AccountId`, `AccountId`)
- **summary**: Contract deployed by address at the specified address.
▸ **ScheduleUpdated**(`u32`)
- **summary**: Triggered when the current schedule is updated.
▸ **Transfer**(`AccountId`, `AccountId`, `Balance`)
- **summary**: Transfer happened `from` to `to` with given `value` as part of a `call` or `instantiate`.
___
### council
▸ **Approved**(`Hash`)
- **summary**: A motion was approved by the required threshold.
▸ **Disapproved**(`Hash`)
- **summary**: A motion was not approved by the required threshold.
▸ **Executed**(`Hash`, `bool`)
- **summary**: A motion was executed; `bool` is true if returned without error.
▸ **MemberExecuted**(`Hash`, `bool`)
- **summary**: A single member did some action; `bool` is true if returned without error.
▸ **Proposed**(`AccountId`, `ProposalIndex`, `Hash`, `MemberCount`)
- **summary**: A motion (given hash) has been proposed (by given account) with a threshold (given `MemberCount`).
▸ **Voted**(`AccountId`, `Hash`, `bool`, `MemberCount`, `MemberCount`)
- **summary**: A motion (given hash) has been voted on by given account, leaving a tally (yes votes and no votes given respectively as `MemberCount`).
___
### democracy
▸ **Cancelled**(`ReferendumIndex`)
▸ **Delegated**(`AccountId`, `AccountId`)
▸ **Executed**(`ReferendumIndex`, `bool`)
▸ **ExternalTabled**()
▸ **NotPassed**(`ReferendumIndex`)
▸ **Passed**(`ReferendumIndex`)
▸ **Proposed**(`PropIndex`, `Balance`)
▸ **Started**(`ReferendumIndex`, `VoteThreshold`)
▸ **Tabled**(`PropIndex`, `Balance`, `Vec<AccountId>`)
▸ **Undelegated**(`AccountId`)
▸ **Vetoed**(`AccountId`, `Hash`, `BlockNumber`)
___
### elections
▸ **BadReaperSlashed**(`AccountId`)
- **summary**: slashed reaper
▸ **TallyFinalized**(`Vec<AccountId>`, `Vec<AccountId>`)
- **summary**: A tally (for approval votes of seat(s)) has ended (with one or more new members).
▸ **TallyStarted**(`u32`)
- **summary**: A tally (for approval votes of seat(s)) has started.
▸ **VoterReaped**(`AccountId`, `AccountId`)
- **summary**: reaped voter, reaper
___
### grandpa
▸ **NewAuthorities**(`Vec<(AuthorityId,AuthorityWeight)>`)
- **summary**: New authority set has been applied.
▸ **Paused**()
- **summary**: Current authority set has been paused.
▸ **Resumed**()
- **summary**: Current authority set has been resumed.
___
### imOnline
▸ **HeartbeatReceived**(`AuthorityId`)
- **summary**: A new heartbeat was received from `AuthorityId`
___
### indices
▸ **NewAccountIndex**(`AccountId`, `AccountIndex`)
- **summary**: A new account index was assigned. This event is not triggered when an existing index is reassigned to another `AccountId`.
___
### offences
▸ **Offence**(`Kind`, `OpaqueTimeSlot`)
- **summary**: There is an offence reported of the given `kind` happened at the `session_index` and (kind-specific) time slot. This event is not deposited for duplicate slashes.
___
### session
▸ **NewSession**(`SessionIndex`)
- **summary**: New session has happened. Note that the argument is the session index, not the block number as the type might suggest.
___
### staking
▸ **OldSlashingReportDiscarded**(`SessionIndex`)
- **summary**: An old slashing report from a prior era was discarded because it could not be processed.
▸ **Reward**(`Balance`)
- **summary**: All validators have been rewarded by the given balance.
▸ **Slash**(`AccountId`, `Balance`)
- **summary**: One validator (and its nominators) has been slashed by the given amount.
___
### sudo
▸ **KeyChanged**(`AccountId`)
- **summary**: The sudoer just switched identity; the old key is supplied.
▸ **Sudid**(`bool`)
- **summary**: A sudo just took place.
▸ **SudoAsDone**(`bool`)
- **summary**: A sudo just took place.
___
### system
▸ **ExtrinsicFailed**(`DispatchError`)
- **summary**: An extrinsic failed.
▸ **ExtrinsicSuccess**()
- **summary**: An extrinsic completed successfully.
___
### technicalCommittee
▸ **Approved**(`Hash`)
- **summary**: A motion was approved by the required threshold.
▸ **Disapproved**(`Hash`)
- **summary**: A motion was not approved by the required threshold.
▸ **Executed**(`Hash`, `bool`)
- **summary**: A motion was executed; `bool` is true if returned without error.
▸ **MemberExecuted**(`Hash`, `bool`)
- **summary**: A single member did some action; `bool` is true if returned without error.
▸ **Proposed**(`AccountId`, `ProposalIndex`, `Hash`, `MemberCount`)
- **summary**: A motion (given hash) has been proposed (by given account) with a threshold (given `MemberCount`).
▸ **Voted**(`AccountId`, `Hash`, `bool`, `MemberCount`, `MemberCount`)
- **summary**: A motion (given hash) has been voted on by given account, leaving a tally (yes votes and no votes given respectively as `MemberCount`).
___
### technicalMembership
▸ **Dummy**(`PhantomData`)
- **summary**: Phantom member, never used.
▸ **MemberAdded**()
- **summary**: The given member was added; see the transaction for who.
▸ **MemberRemoved**()
- **summary**: The given member was removed; see the transaction for who.
▸ **MembersReset**()
- **summary**: The membership was reset; see the transaction for who the new set is.
▸ **MembersSwapped**()
- **summary**: Two members were swapped; see the transaction for who.
___
### treasury
▸ **Awarded**(`ProposalIndex`, `Balance`, `AccountId`)
- **summary**: Some funds have been allocated.
▸ **Burnt**(`Balance`)
- **summary**: Some of our funds have been burnt.
▸ **Proposed**(`ProposalIndex`)
- **summary**: New proposal.
▸ **Rollover**(`Balance`)
- **summary**: Spending has finished; this is the amount that rolls over until next spend.
▸ **Spending**(`Balance`)
- **summary**: We have ended a spend period and will now allocate funds.
___
### utility
▸ **BatchExecuted**(`Vec<DispatchResult>`)
-370
View File
@@ -1,370 +0,0 @@
## Extrinsics
The following sections contain Extrinsics methods are part of the default Substrate runtime. On the api, these are exposed via `api.tx.<module>.<method>`.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[authorship](#authorship)**
- **[balances](#balances)**
- **[contracts](#contracts)**
- **[council](#council)**
- **[democracy](#democracy)**
- **[elections](#elections)**
- **[finalityTracker](#finalityTracker)**
- **[grandpa](#grandpa)**
- **[imOnline](#imOnline)**
- **[session](#session)**
- **[staking](#staking)**
- **[sudo](#sudo)**
- **[system](#system)**
- **[technicalCommittee](#technicalCommittee)**
- **[technicalMembership](#technicalMembership)**
- **[timestamp](#timestamp)**
- **[treasury](#treasury)**
- **[utility](#utility)**
___
### authorship
▸ **setUncles**(new_uncles: `Vec<Header>`)
- **summary**: Provide a set of uncles.
___
### balances
▸ **forceTransfer**(source: `Address`, dest: `Address`, value: `Compact<Balance>`)
- **summary**: Exactly as `transfer`, except the origin must be root and the source account may be specified.
▸ **setBalance**(who: `Address`, new_free: `Compact<Balance>`, new_reserved: `Compact<Balance>`)
- **summary**: Set the balances of a given account. This will alter `FreeBalance` and `ReservedBalance` in storage. it will also decrease the total issuance of the system (`TotalIssuance`). If the new free or reserved balance is below the existential deposit, it will reset the account nonce (`system::AccountNonce`). The dispatch origin for this call is `root`. # <weight> - Independent of the arguments. - Contains a limited number of reads and writes. # </weight>
▸ **transfer**(dest: `Address`, value: `Compact<Balance>`)
- **summary**: Transfer some liquid free balance to another account. `transfer` will set the `FreeBalance` of the sender and receiver. It will decrease the total issuance of the system by the `TransferFee`. If the sender's account is below the existential deposit as a result of the transfer, the account will be reaped. The dispatch origin for this call must be `Signed` by the transactor. # <weight> - Dependent on arguments but not critical, given proper implementations for input config types. See related functions below. - It contains a limited number of reads and writes internally and no complex computation. Related functions: - `ensure_can_withdraw` is always called internally but has a bounded complexity. - Transferring balances to accounts that did not exist before will cause `T::OnNewAccount::on_new_account` to be called. - Removing enough funds from an account will trigger `T::DustRemoval::on_unbalanced` and `T::OnFreeBalanceZero::on_free_balance_zero`. # </weight>
___
### contracts
▸ **call**(dest: `Address`, value: `Compact<BalanceOf>`, gas_limit: `Compact<Gas>`, data: `Bytes`)
- **summary**: Makes a call to an account, optionally transferring some balance. * If the account is a smart-contract account, the associated code will be executed and any value will be transferred. * If the account is a regular account, any value will be transferred. * If no account exists and the call value is not less than `existential_deposit`, a regular account will be created and any value will be transferred.
▸ **claimSurcharge**(dest: `AccountId`, aux_sender: `Option<AccountId>`)
- **summary**: Allows block producers to claim a small reward for evicting a contract. If a block producer fails to do so, a regular users will be allowed to claim the reward. If contract is not evicted as a result of this call, no actions are taken and the sender is not eligible for the reward.
▸ **instantiate**(endowment: `Compact<BalanceOf>`, gas_limit: `Compact<Gas>`, code_hash: `CodeHash`, data: `Bytes`)
- **summary**: Instantiates a new contract from the `codehash` generated by `put_code`, optionally transferring some balance. Instantiation is executed as follows: - The destination address is computed based on the sender and hash of the code. - The smart-contract account is created at the computed address. - The `ctor_code` is executed in the context of the newly-created account. Buffer returned after the execution is saved as the `code` of the account. That code will be invoked upon any call received by this account. - The contract is initialized.
▸ **putCode**(gas_limit: `Compact<Gas>`, code: `Bytes`)
- **summary**: Stores the given binary Wasm code into the chain's storage and returns its `codehash`. You can instantiate contracts only with stored code.
▸ **updateSchedule**(schedule: `Schedule`)
- **summary**: Updates the schedule for metering contracts. The schedule must have a greater version than the stored schedule.
___
### council
▸ **execute**(proposal: `Proposal`)
- **summary**: Dispatch a proposal from a member using the `Member` origin. Origin must be a member of the collective.
▸ **propose**(threshold: `Compact<MemberCount>`, proposal: `Proposal`)
- **summary**: # <weight> - Bounded storage reads and writes. - Argument `threshold` has bearing on weight. # </weight>
▸ **setMembers**(new_members: `Vec<AccountId>`)
- **summary**: Set the collective's membership manually to `new_members`. Be nice to the chain and provide it pre-sorted. Requires root origin.
▸ **vote**(proposal: `Hash`, index: `Compact<ProposalIndex>`, approve: `bool`)
- **summary**: # <weight> - Bounded storage read and writes. - Will be slightly heavier if the proposal is approved / disapproved after the vote. # </weight>
___
### democracy
▸ **cancelQueued**(when: `Compact<BlockNumber>`, which: `Compact<u32>`, what: `Compact<ReferendumIndex>`)
- **summary**: Cancel a proposal queued for enactment.
▸ **cancelReferendum**(ref_index: `Compact<ReferendumIndex>`)
- **summary**: Remove a referendum.
▸ **delegate**(to: `AccountId`, conviction: `Conviction`)
- **summary**: Delegate vote. # <weight> - One extra DB entry. # </weight>
▸ **emergencyCancel**(ref_index: `ReferendumIndex`)
- **summary**: Schedule an emergency cancellation of a referendum. Cannot happen twice to the same referendum.
▸ **externalPropose**(proposal: `Proposal`)
- **summary**: Schedule a referendum to be tabled once it is legal to schedule an external referendum.
▸ **externalProposeDefault**(proposal: `Proposal`)
- **summary**: Schedule a negative-turnout-bias referendum to be tabled next once it is legal to schedule an external referendum. Unlike `external_propose`, blacklisting has no effect on this and it may replace a pre-scheduled `external_propose` call.
▸ **externalProposeMajority**(proposal: `Proposal`)
- **summary**: Schedule a majority-carries referendum to be tabled next once it is legal to schedule an external referendum. Unlike `external_propose`, blacklisting has no effect on this and it may replace a pre-scheduled `external_propose` call.
▸ **fastTrack**(proposal_hash: `Hash`, voting_period: `BlockNumber`, delay: `BlockNumber`)
- **summary**: Schedule the currently externally-proposed majority-carries referendum to be tabled immediately. If there is no externally-proposed referendum currently, or if there is one but it is not a majority-carries referendum then it fails. - `proposal_hash`: The hash of the current external proposal. - `voting_period`: The period that is allowed for voting on this proposal. - `delay`: The number of block after voting has ended in approval and this should be enacted. Increased to `EmergencyVotingPeriod` if too low.
▸ **propose**(proposal: `Proposal`, value: `Compact<BalanceOf>`)
- **summary**: Propose a sensitive action to be taken. # <weight> - O(1). - Two DB changes, one DB entry. # </weight>
▸ **proxyVote**(ref_index: `Compact<ReferendumIndex>`, vote: `Vote`)
- **summary**: Vote in a referendum on behalf of a stash. If `vote.is_aye()`, the vote is to enact the proposal; otherwise it is a vote to keep the status quo. # <weight> - O(1). - One DB change, one DB entry. # </weight>
▸ **removeProxy**(proxy: `AccountId`)
- **summary**: Clear the proxy. Called by the stash. # <weight> - One DB clear. # </weight>
▸ **resignProxy**()
- **summary**: Clear the proxy. Called by the proxy. # <weight> - One DB clear. # </weight>
▸ **second**(proposal: `Compact<PropIndex>`)
- **summary**: Propose a sensitive action to be taken. # <weight> - O(1). - One DB entry. # </weight>
▸ **setProxy**(proxy: `AccountId`)
- **summary**: Specify a proxy. Called by the stash. # <weight> - One extra DB entry. # </weight>
▸ **undelegate**()
- **summary**: Undelegate vote. # <weight> - O(1). # </weight>
▸ **vetoExternal**(proposal_hash: `Hash`)
- **summary**: Veto and blacklist the external proposal hash.
▸ **vote**(ref_index: `Compact<ReferendumIndex>`, vote: `Vote`)
- **summary**: Vote in a referendum. If `vote.is_aye()`, the vote is to enact the proposal; otherwise it is a vote to keep the status quo. # <weight> - O(1). - One DB change, one DB entry. # </weight>
___
### elections
▸ **presentWinner**(candidate: `Address`, total: `Compact<BalanceOf>`, index: `Compact<VoteIndex>`)
- **summary**: Claim that `candidate` is one of the top `carry_count + desired_seats` candidates. Only works iff the presentation period is active. `candidate` should have at least collected some non-zero `total` votes and `origin` must have enough funds to pay for a potential slash. # <weight> - O(voters) compute. - One DB change. # </weight>
▸ **proxySetApprovals**(votes: `Vec<bool>`, index: `Compact<VoteIndex>`, hint: `SetIndex`, value: `Compact<BalanceOf>`)
- **summary**: Set candidate approvals from a proxy. Approval slots stay valid as long as candidates in those slots are registered. # <weight> - Same as `set_approvals` with one additional storage read. # </weight>
▸ **reapInactiveVoter**(reporter_index: `Compact<u32>`, who: `Address`, who_index: `Compact<u32>`, assumed_vote_index: `Compact<VoteIndex>`)
- **summary**: Remove a voter. For it not to be a bond-consuming no-op, all approved candidate indices must now be either unregistered or registered to a candidate that registered the slot after the voter gave their last approval set. Both indices must be provided as explained in [`voter_at`] function. May be called by anyone. Returns the voter deposit to `signed`. # <weight> - O(1). - Two fewer DB entries, one DB change. # </weight>
▸ **removeMember**(who: `Address`)
- **summary**: Remove a particular member from the set. This is effective immediately. Note: A tally should happen instantly (if not already in a presentation period) to fill the seat if removal means that the desired members are not met.
▸ **retractVoter**(index: `Compact<u32>`)
- **summary**: Remove a voter. All votes are cancelled and the voter deposit is returned. The index must be provided as explained in [`voter_at`] function. Also removes the lock on the balance of the voter. See [`do_set_approvals()`]. # <weight> - O(1). - Two fewer DB entries, one DB change. # </weight>
▸ **setApprovals**(votes: `Vec<bool>`, index: `Compact<VoteIndex>`, hint: `SetIndex`, value: `Compact<BalanceOf>`)
- **summary**: Set candidate approvals. Approval slots stay valid as long as candidates in those slots are registered. Locks `value` from the balance of `origin` indefinitely. Only [`retract_voter`] or [`reap_inactive_voter`] can unlock the balance. `hint` argument is interpreted differently based on: - if `origin` is setting approvals for the first time: The index will be checked for being a valid _hole_ in the voter list. - if the hint is correctly pointing to a hole, no fee is deducted from `origin`. - Otherwise, the call will succeed but the index is ignored and simply a push to the last chunk with free space happens. If the new push causes a new chunk to be created, a fee indicated by [`VotingFee`] is deducted. - if `origin` is already a voter: the index __must__ be valid and point to the correct position of the `origin` in the current voters list. Note that any trailing `false` votes in `votes` is ignored; In approval voting, not voting for a candidate and voting false, are equal. # <weight> - O(1). - Two extra DB entries, one DB change. - Argument `votes` is limited in length to number of candidates. # </weight>
▸ **setDesiredSeats**(count: `Compact<u32>`)
- **summary**: Set the desired member count; if lower than the current count, then seats will not be up election when they expire. If more, then a new vote will be started if one is not already in progress.
▸ **setPresentationDuration**(count: `Compact<BlockNumber>`)
- **summary**: Set the presentation duration. If there is currently a vote being presented for, will invoke `finalize_vote`.
▸ **setTermDuration**(count: `Compact<BlockNumber>`)
- **summary**: Set the presentation duration. If there is current a vote being presented for, will invoke `finalize_vote`.
▸ **submitCandidacy**(slot: `Compact<u32>`)
- **summary**: Submit oneself for candidacy. Account must have enough transferrable funds in it to pay the bond. NOTE: if `origin` has already assigned approvals via [`set_approvals`], it will NOT have any usable funds to pass candidacy bond and must first retract. Note that setting approvals will lock the entire balance of the voter until retraction or being reported. # <weight> - Independent of input. - Three DB changes. # </weight>
___
### finalityTracker
▸ **finalHint**(hint: `Compact<BlockNumber>`)
- **summary**: Hint that the author of this block thinks the best finalized block is the given number.
___
### grandpa
▸ **reportMisbehavior**(_report: `Bytes`)
- **summary**: Report some misbehavior.
___
### imOnline
▸ **heartbeat**(heartbeat: `Heartbeat`, signature: `Signature`)
___
### session
▸ **setKeys**(keys: `Keys`, proof: `Bytes`)
- **summary**: Sets the session key(s) of the function caller to `key`. Allows an account to set its session key prior to becoming a validator. This doesn't take effect until the next session. The dispatch origin of this function must be signed. # <weight> - O(log n) in number of accounts. - One extra DB entry. # </weight>
___
### staking
▸ **bond**(controller: `Address`, value: `Compact<BalanceOf>`, payee: `RewardDestination`)
- **summary**: Take the origin account as a stash and lock up `value` of its balance. `controller` will be the account that controls it. `value` must be more than the `minimum_balance` specified by `T::Currency`. The dispatch origin for this call must be _Signed_ by the stash account. # <weight> - Independent of the arguments. Moderate complexity. - O(1). - Three extra DB entries. NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned unless the `origin` falls below _existential deposit_ and gets removed as dust. # </weight>
▸ **bondExtra**(max_additional: `Compact<BalanceOf>`)
- **summary**: Add some extra amount that have appeared in the stash `free_balance` into the balance up for staking. Use this if there are additional funds in your stash account that you wish to bond. Unlike [`bond`] or [`unbond`] this function does not impose any limitation on the amount that can be added. The dispatch origin for this call must be _Signed_ by the stash, not the controller. # <weight> - Independent of the arguments. Insignificant complexity. - O(1). - One DB entry. # </weight>
▸ **chill**()
- **summary**: Declare no desire to either validate or nominate. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. # <weight> - Independent of the arguments. Insignificant complexity. - Contains one read. - Writes are limited to the `origin` account key. # </weight>
▸ **forceNewEra**()
- **summary**: Force there to be a new era at the end of the next session. After this, it will be reset to normal (non-forced) behaviour. # <weight> - No arguments. # </weight>
▸ **forceNoEras**()
- **summary**: Force there to be no new eras indefinitely. # <weight> - No arguments. # </weight>
▸ **nominate**(targets: `Vec<Address>`)
- **summary**: Declare the desire to nominate `targets` for the origin controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. # <weight> - The transaction's complexity is proportional to the size of `targets`, which is capped at `MAX_NOMINATIONS`. - Both the reads and writes follow a similar pattern. # </weight>
▸ **setController**(controller: `Address`)
- **summary**: (Re-)set the controller of a stash. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the stash, not the controller. # <weight> - Independent of the arguments. Insignificant complexity. - Contains a limited number of reads. - Writes are limited to the `origin` account key. # </weight>
▸ **setInvulnerables**(validators: `Vec<AccountId>`)
- **summary**: Set the validators who cannot be slashed (if any).
▸ **setPayee**(payee: `RewardDestination`)
- **summary**: (Re-)set the payment target for a controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. # <weight> - Independent of the arguments. Insignificant complexity. - Contains a limited number of reads. - Writes are limited to the `origin` account key. # </weight>
▸ **setValidatorCount**(new: `Compact<u32>`)
- **summary**: The ideal number of validators.
▸ **unbond**(value: `Compact<BalanceOf>`)
- **summary**: Schedule a portion of the stash to be unlocked ready for transfer out after the bond period ends. If this leaves an amount actively bonded less than T::Currency::minimum_balance(), then it is increased to the full amount. Once the unlock period is done, you can call `withdraw_unbonded` to actually move the funds out of management ready for transfer. No more than a limited number of unlocking chunks (see `MAX_UNLOCKING_CHUNKS`) can co-exists at the same time. In that case, [`Call::withdraw_unbonded`] need to be called first to remove some of the chunks (if possible). The dispatch origin for this call must be _Signed_ by the controller, not the stash. See also [`Call::withdraw_unbonded`]. # <weight> - Independent of the arguments. Limited but potentially exploitable complexity. - Contains a limited number of reads. - Each call (requires the remainder of the bonded balance to be above `minimum_balance`) will cause a new entry to be inserted into a vector (`Ledger.unlocking`) kept in storage. The only way to clean the aforementioned storage item is also user-controlled via `withdraw_unbonded`. - One DB entry. </weight>
▸ **validate**(prefs: `ValidatorPrefs`)
- **summary**: Declare the desire to validate for the origin controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash. # <weight> - Independent of the arguments. Insignificant complexity. - Contains a limited number of reads. - Writes are limited to the `origin` account key. # </weight>
▸ **withdrawUnbonded**()
- **summary**: Remove any unlocked chunks from the `unlocking` queue from our management. This essentially frees up that balance to be used by the stash account to do whatever it wants. The dispatch origin for this call must be _Signed_ by the controller, not the stash. See also [`Call::unbond`]. # <weight> - Could be dependent on the `origin` argument and how much `unlocking` chunks exist. It implies `consolidate_unlocked` which loops over `Ledger.unlocking`, which is indirectly user-controlled. See [`unbond`] for more detail. - Contains a limited number of reads, yet the size of which could be large based on `ledger`. - Writes are limited to the `origin` account key. # </weight>
___
### sudo
▸ **setKey**(new: `Address`)
- **summary**: Authenticates the current sudo key and sets the given AccountId (`new`) as the new sudo key. The dispatch origin for this call must be _Signed_. # <weight> - O(1). - Limited storage reads. - One DB change. # </weight>
▸ **sudo**(proposal: `Proposal`)
- **summary**: Authenticates the sudo key and dispatches a function call with `Root` origin. The dispatch origin for this call must be _Signed_. # <weight> - O(1). - Limited storage reads. - One DB write (event). - Unknown weight of derivative `proposal` execution. # </weight>
▸ **sudoAs**(who: `Address`, proposal: `Proposal`)
- **summary**: Authenticates the sudo key and dispatches a function call with `Signed` origin from a given account. The dispatch origin for this call must be _Signed_. # <weight> - O(1). - Limited storage reads. - One DB write (event). - Unknown weight of derivative `proposal` execution. # </weight>
___
### system
▸ **fillBlock**()
- **summary**: A big dispatch that will disallow any other transaction to be included.
▸ **killPrefix**(prefix: `Key`)
- **summary**: Kill all storage items with a key that starts with the given prefix.
▸ **killStorage**(keys: `Vec<Key>`)
- **summary**: Kill some items from storage.
▸ **remark**(_remark: `Bytes`)
- **summary**: Make some on-chain remark.
▸ **setCode**(new: `Bytes`)
- **summary**: Set the new code.
▸ **setHeapPages**(pages: `u64`)
- **summary**: Set the number of pages in the WebAssembly environment's heap.
▸ **setStorage**(items: `Vec<KeyValue>`)
- **summary**: Set some items of storage.
___
### technicalCommittee
▸ **execute**(proposal: `Proposal`)
- **summary**: Dispatch a proposal from a member using the `Member` origin. Origin must be a member of the collective.
▸ **propose**(threshold: `Compact<MemberCount>`, proposal: `Proposal`)
- **summary**: # <weight> - Bounded storage reads and writes. - Argument `threshold` has bearing on weight. # </weight>
▸ **setMembers**(new_members: `Vec<AccountId>`)
- **summary**: Set the collective's membership manually to `new_members`. Be nice to the chain and provide it pre-sorted. Requires root origin.
▸ **vote**(proposal: `Hash`, index: `Compact<ProposalIndex>`, approve: `bool`)
- **summary**: # <weight> - Bounded storage read and writes. - Will be slightly heavier if the proposal is approved / disapproved after the vote. # </weight>
___
### technicalMembership
▸ **addMember**(who: `AccountId`)
- **summary**: Add a member `who` to the set. May only be called from `AddOrigin` or root.
▸ **removeMember**(who: `AccountId`)
- **summary**: Remove a member `who` from the set. May only be called from `RemoveOrigin` or root.
▸ **resetMembers**(members: `Vec<AccountId>`)
- **summary**: Change the membership to a new set, disregarding the existing membership. Be nice and pass `members` pre-sorted. May only be called from `ResetOrigin` or root.
▸ **swapMember**(remove: `AccountId`, add: `AccountId`)
- **summary**: Swap out one member `remove` for another `add`. May only be called from `SwapOrigin` or root.
___
### timestamp
▸ **set**(now: `Compact<Moment>`)
- **summary**: Set the current time. This call should be invoked exactly once per block. It will panic at the finalization phase, if this call hasn't been invoked by that time. The timestamp should be greater than the previous one by the amount specified by `MinimumPeriod`. The dispatch origin for this call must be `Inherent`.
___
### treasury
▸ **approveProposal**(proposal_id: `Compact<ProposalIndex>`)
- **summary**: Approve a proposal. At a later time, the proposal will be allocated to the beneficiary and the original deposit will be returned. # <weight> - O(1). - Limited storage reads. - One DB change. # </weight>
▸ **proposeSpend**(value: `Compact<BalanceOf>`, beneficiary: `Address`)
- **summary**: Put forward a suggestion for spending. A deposit proportional to the value is reserved and slashed if the proposal is rejected. It is returned once the proposal is awarded. # <weight> - O(1). - Limited storage reads. - One DB change, one extra DB entry. # </weight>
▸ **rejectProposal**(proposal_id: `Compact<ProposalIndex>`)
- **summary**: Reject a proposed spend. The original deposit will be slashed. # <weight> - O(1). - Limited storage reads. - One DB clear. # </weight>
___
### utility
▸ **batch**(calls: `Vec<Call>`)
- **summary**: Send a batch of dispatch calls (only root).
-175
View File
@@ -1,175 +0,0 @@
## JSON-RPC
The following sections contain RPC methods that are Remote Calls available by default and allow you to interact with the actual node, query, and submit.
- **[account](#account)**
- **[author](#author)**
- **[chain](#chain)**
- **[contracts](#contracts)**
- **[rpc](#rpc)**
- **[state](#state)**
- **[system](#system)**
___
### account
_(Optional) Methods that retrieves account-specific information_
▸ **nextIndex**(accountId: `AccountId`): `Index`
- **summary**: Retrieves the next accountIndex as available on the node
___
### author
_Authoring of network items_
▸ **insertKey**(keyType: `Text`, suri: `Text`, publicKey: `Bytes`): `Bytes`
- **summary**: Insert a key into the keystore.
▸ **pendingExtrinsics**(): `Vec<Extrinsic>`
- **summary**: Returns all pending extrinsics, potentially grouped by sender
▸ **removeExtrinsic**(bytesOrHash: `Vec<ExtrinsicOrHash>`): `Vec<Hash>`
- **summary**: Remove given extrinsic from the pool and temporarily ban it to prevent reimporting
▸ **rotateKeys**(): `Bytes`
- **summary**: Generate new session keys and returns the corresponding public keys
▸ **submitAndWatchExtrinsic**(extrinsic: `Extrinsic`): `ExtrinsicStatus`
- **summary**: Submit and subscribe to watch an extrinsic until unsubscribed
▸ **submitExtrinsic**(extrinsic: `Extrinsic`): `Hash`
- **summary**: Submit a fully formatted extrinsic for block inclusion
___
### chain
_Retrieval of chain data_
▸ **getBlock**(hash?: `Hash`): `SignedBlock`
- **summary**: Get header and body of a relay chain block
▸ **getBlockHash**(blockNumber?: `BlockNumber`): `Hash`
- **summary**: Get the block hash for a specific block
▸ **getFinalizedHead**(): `Hash`
- **summary**: Get hash of the last finalized block in the canon chain
▸ **getHeader**(hash?: `Hash`): `Header`
- **summary**: Retrieves the header for a specific block
▸ **subscribeFinalizedHeads**(): `Header`
- **summary**: Retrieves the best finalized header via subscription
▸ **subscribeNewHeads**(): `Header`
- **summary**: Retrieves the best header via subscription
___
### contracts
_(Optional) Methods that performs actions on contracts_
▸ **call**(callRequest: `ContractCallRequest`, at?: `Hash`): `ContractExecResult`
- **summary**: Executes a call to a contract
___
### rpc
_Retrieves information about the RPC endpoints_
▸ **methods**(): `RpcMethods`
- **summary**: Retrieves the list of RPC methods that are exposed by the node
___
### state
_Query of state_
▸ **call**(method: `Text`, data: `Bytes`, block?: `Hash`): `Bytes`
- **summary**: Perform a call to a builtin on the chain
▸ **getChildKeys**(childStorageKey: `StorageKey`, key: `StorageKey`, block?: `Hash`): `Vec<StorageKey>`
- **summary**: Retrieves the keys with prefix of a specific child storage
▸ **getChildStorage**(childStorageKey: `StorageKey`, key: `StorageKey`, block?: `Hash`): `StorageData`
- **summary**: Retrieves the child storage for a key
▸ **getChildStorageHash**(childStorageKey: `StorageKey`, key: `StorageKey`, block?: `Hash`): `Hash`
- **summary**: Retrieves the child storage hash
▸ **getChildStorageSize**(childStorageKey: `StorageKey`, key: `StorageKey`, block?: `Hash`): `u64`
- **summary**: Retrieves the child storage size
▸ **getKeys**(key: `StorageKey`, block?: `Hash`): `Vec<StorageKey>`
- **summary**: Retrieves the keys with a certain prefix
▸ **getMetadata**(block?: `Hash`): `Metadata`
- **summary**: Returns the runtime metadata
▸ **getRuntimeVersion**(hash?: `Hash`): `RuntimeVersion`
- **summary**: Get the runtime version
▸ **getStorage**(key: `StorageKey`, block?: `Hash`): `StorageData`
- **summary**: Retrieves the storage for a key
▸ **getStorageHash**(key: `StorageKey`, block?: `Hash`): `Hash`
- **summary**: Retrieves the storage hash
▸ **getStorageSize**(key: `StorageKey`, block?: `Hash`): `u64`
- **summary**: Retrieves the storage size
▸ **queryStorage**(keys: `Vec<StorageKey>`, startBlock: `Hash`, block?: `Hash`): `Vec<StorageChangeSet>`
- **summary**: Query historical storage entries (by key) starting from a start block
▸ **subscribeRuntimeVersion**(): `RuntimeVersion`
- **summary**: Retrieves the runtime version via subscription
▸ **subscribeStorage**(keys: `Vec<StorageKey>`): `StorageChangeSet`
- **summary**: Subscribes to storage changes for the provided keys
___
### system
_Calls to retrieve system info_
▸ **chain**(): `Text`
- **summary**: Retrieves the chain
▸ **health**(): `Health`
- **summary**: Return health status of the node
▸ **name**(): `Text`
- **summary**: Retrieves the node name
▸ **networkState**(): `NetworkState`
- **summary**: Returns current state of the network
▸ **peers**(): `Vec<PeerInfo>`
- **summary**: Returns the currently connected peers
▸ **properties**(): `ChainProperties`
- **summary**: Get a custom set of properties as a JSON object, defined in the chain spec
▸ **version**(): `Text`
- **summary**: Retrieves the version of the node
+26
View File
@@ -0,0 +1,26 @@
{
"name": "substrate",
"description": "These are keys that are always available to the runtime implementation",
"items": [
{
"name": "changesTrieConfig(): `u32`",
"summary": "Changes trie configuration is stored under this key."
},
{
"name": "childStorageKeyPrefix(): `u32`",
"summary": "Prefix of child storage keys."
},
{
"name": "code(): `Bytes`",
"summary": "Wasm code of the runtime."
},
{
"name": "extrinsicIndex(): `u32`",
"summary": "Current extrinsic index (u32) is stored under this key."
},
{
"name": "heapPages(): `u64`",
"summary": "Number of wasm linear memory pages required for execution of the runtime."
}
]
}
-23
View File
@@ -1,23 +0,0 @@
---
### substrate
_These are keys that are always available to the runtime implementation_
▸ **changesTrieConfig**(): `u32`
- **summary**: Changes trie configuration is stored under this key.
▸ **childStorageKeyPrefix**(): `u32`
- **summary**: Prefix of child storage keys.
▸ **code**(): `Bytes`
- **summary**: Wasm code of the runtime.
▸ **extrinsicIndex**(): `u32`
- **summary**: Current extrinsic index (u32) is stored under this key.
▸ **heapPages**(): `u64`
- **summary**: Number of wasm linear memory pages required for execution of the runtime.
---
-545
View File
@@ -1,545 +0,0 @@
## Storage
The following sections contain Storage methods are part of the default Substrate runtime. On the api, these are exposed via `api.query.<module>.<method>`.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[authorship](#authorship)**
- **[babe](#babe)**
- **[balances](#balances)**
- **[contracts](#contracts)**
- **[council](#council)**
- **[democracy](#democracy)**
- **[elections](#elections)**
- **[grandpa](#grandpa)**
- **[imOnline](#imOnline)**
- **[indices](#indices)**
- **[offences](#offences)**
- **[session](#session)**
- **[staking](#staking)**
- **[sudo](#sudo)**
- **[system](#system)**
- **[technicalCommittee](#technicalCommittee)**
- **[technicalMembership](#technicalMembership)**
- **[timestamp](#timestamp)**
- **[treasury](#treasury)**
- **[substrate](#substrate)**
___
### authorship
▸ **author**(): `Option<AccountId>`
- **summary**: Author of current block.
▸ **didSetUncles**(): `bool`
- **summary**: Whether uncles were already set in this block.
▸ **uncles**(): `Vec<UncleEntryItem>`
- **summary**: Uncles
___
### babe
▸ **authorities**(): `Vec<(AuthorityId,BabeAuthorityWeight)>`
- **summary**: Current epoch authorities.
▸ **currentSlot**(): `u64`
- **summary**: Current slot number.
▸ **epochIndex**(): `u64`
- **summary**: Current epoch index.
▸ **genesisSlot**(): `u64`
- **summary**: The slot at which the first epoch actually started. This is 0 until the first block of the chain.
▸ **initialized**(): `Option<MaybeVrf>`
- **summary**: Temporary value (cleared at block finalization) which is `Some` if per-block initialization has already been called for current block.
▸ **nextRandomness**(): `[u8;32]`
- **summary**: Next epoch randomness.
▸ **randomness**(): `[u8;32]`
- **summary**: The epoch randomness for the *current* epoch. # Security This MUST NOT be used for gambling, as it can be influenced by a malicious validator in the short term. It MAY be used in many cryptographic protocols, however, so long as one remembers that this (like everything else on-chain) it is public. For example, it can be used where a number is needed that cannot have been chosen by an adversary, for purposes such as public-coin zero-knowledge proofs.
▸ **segmentIndex**(): `u32`
- **summary**: Randomness under construction. We make a tradeoff between storage accesses and list length. We store the under-construction randomness in segments of up to `UNDER_CONSTRUCTION_SEGMENT_LENGTH`. Once a segment reaches this length, we begin the next one. We reset all segments and return to `0` at the beginning of every epoch.
▸ **underConstruction**(`u32`): `Vec<[u8;32]>`
___
### balances
▸ **freeBalance**(`AccountId`): `Balance`
- **summary**: The 'free' balance of a given account. This is the only balance that matters in terms of most operations on tokens. It alone is used to determine the balance when in the contract execution environment. When this balance falls below the value of `ExistentialDeposit`, then the 'current account' is deleted: specifically `FreeBalance`. Further, the `OnFreeBalanceZero` callback is invoked, giving a chance to external modules to clean up data associated with the deleted account. `system::AccountNonce` is also deleted if `ReservedBalance` is also zero (it also gets collapsed to zero if it ever becomes less than `ExistentialDeposit`.
▸ **locks**(`AccountId`): `Vec<BalanceLock>`
- **summary**: Any liquidity locks on some account balances.
▸ **reservedBalance**(`AccountId`): `Balance`
- **summary**: The amount of the balance of a given account that is externally reserved; this can still get slashed, but gets slashed last of all. This balance is a 'reserve' balance that other subsystems use in order to set aside tokens that are still 'owned' by the account holder, but which are suspendable. When this balance falls below the value of `ExistentialDeposit`, then this 'reserve account' is deleted: specifically, `ReservedBalance`. `system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets collapsed to zero if it ever becomes less than `ExistentialDeposit`.)
▸ **totalIssuance**(): `Balance`
- **summary**: The total units issued in the system.
▸ **vesting**(`AccountId`): `Option<VestingSchedule>`
- **summary**: Information regarding the vesting of a given account.
___
### contracts
▸ **accountCounter**(): `u64`
- **summary**: The subtrie counter.
▸ **codeStorage**(`CodeHash`): `Option<PrefabWasmModule>`
- **summary**: A mapping between an original code hash and instrumented wasm code, ready for execution.
▸ **contractInfoOf**(`AccountId`): `Option<ContractInfo>`
- **summary**: The code associated with a given account.
▸ **currentSchedule**(): `Schedule`
- **summary**: Current cost schedule for contracts.
▸ **gasPrice**(): `BalanceOf`
- **summary**: The price of one unit of gas.
▸ **gasSpent**(): `Gas`
- **summary**: Gas spent so far in this block.
▸ **pristineCode**(`CodeHash`): `Option<Bytes>`
- **summary**: A mapping from an original code hash to the original code, untouched by instrumentation.
___
### council
▸ **members**(): `Vec<AccountId>`
- **summary**: The current members of the collective. This is stored sorted (just by value).
▸ **proposalCount**(): `u32`
- **summary**: Proposals so far.
▸ **proposalOf**(`Hash`): `Option<Proposal>`
- **summary**: Actual proposal for a given hash, if it's current.
▸ **proposals**(): `Vec<Hash>`
- **summary**: The hashes of the active proposals.
▸ **voting**(`Hash`): `Option<Votes>`
- **summary**: Votes on a given proposal, if it is ongoing.
___
### democracy
▸ **blacklist**(`Hash`): `Option<(BlockNumber,Vec<AccountId>)>`
- **summary**: A record of who vetoed what. Maps proposal hash to a possible existent block number (until when it may not be resubmitted) and who vetoed it.
▸ **cancellations**(`Hash`): `bool`
- **summary**: Record of all proposals that have been subject to emergency cancellation.
▸ **delegations**(`AccountId`): `((AccountId,Conviction), Linkage<AccountId>)`
- **summary**: Get the account (and lock periods) to which another account is delegating vote.
▸ **depositOf**(`PropIndex`): `Option<(BalanceOf,Vec<AccountId>)>`
- **summary**: Those who have locked a deposit.
▸ **dispatchQueue**(`BlockNumber`): `Vec<Option<(Proposal,ReferendumIndex)>>`
- **summary**: Queue of successful referenda to be dispatched.
▸ **lastTabledWasExternal**(): `bool`
- **summary**: True if the last referendum tabled was submitted externally. False if it was a public proposal.
▸ **nextExternal**(): `Option<(Proposal,VoteThreshold)>`
- **summary**: The referendum to be tabled whenever it would be valid to table an external proposal. This happens when a referendum needs to be tabled and one of two conditions are met: - `LastTabledWasExternal` is `false`; or - `PublicProps` is empty.
▸ **nextTally**(): `ReferendumIndex`
- **summary**: The next referendum index that should be tallied.
▸ **proxy**(`AccountId`): `Option<AccountId>`
- **summary**: Who is able to vote for whom. Value is the fund-holding account, key is the vote-transaction-sending account.
▸ **publicPropCount**(): `PropIndex`
- **summary**: The number of (public) proposals that have been made so far.
▸ **publicProps**(): `Vec<(PropIndex,Proposal,AccountId)>`
- **summary**: The public proposals. Unsorted.
▸ **referendumCount**(): `ReferendumIndex`
- **summary**: The next free referendum index, aka the number of referenda started so far.
▸ **referendumInfoOf**(`ReferendumIndex`): `Option<ReferendumInfo>`
- **summary**: Information concerning any given referendum.
▸ **voteOf**(`(ReferendumIndex,AccountId)`): `Vote`
- **summary**: Get the vote in a given referendum of a particular voter. The result is meaningful only if `voters_for` includes the voter when called with the referendum (you'll get the default `Vote` value otherwise). If you don't want to check `voters_for`, then you can also check for simple existence with `VoteOf::exists` first.
▸ **votersFor**(`ReferendumIndex`): `Vec<AccountId>`
- **summary**: Get the voters for the current proposal.
___
### elections
▸ **approvalsOf**(`(AccountId,SetIndex)`): `Vec<ApprovalFlag>`
▸ **candidateCount**(): `u32`
- **summary**: Current number of active candidates
▸ **candidates**(): `Vec<AccountId>`
- **summary**: The present candidate list.
▸ **desiredSeats**(): `u32`
- **summary**: Number of accounts that should constitute the collective.
▸ **leaderboard**(): `Option<Vec<(BalanceOf,AccountId)>>`
- **summary**: Get the leaderboard if we're in the presentation phase. The first element is the weight of each entry; It may be the direct summed approval stakes, or a weighted version of it. Sorted from low to high.
▸ **members**(): `Vec<(AccountId,BlockNumber)>`
- **summary**: The current membership. When there's a vote going on, this should still be used for executive matters. The block number (second element in the tuple) is the block that their position is active until (calculated by the sum of the block number when the member was elected and their term duration).
▸ **nextFinalize**(): `Option<(BlockNumber,u32,Vec<AccountId>)>`
- **summary**: The accounts holding the seats that will become free on the next tally.
▸ **nextVoterSet**(): `SetIndex`
- **summary**: the next free set to store a voter in. This will keep growing.
▸ **presentationDuration**(): `BlockNumber`
- **summary**: How long to give each top candidate to present themselves after the vote ends.
▸ **proxy**(`AccountId`): `Option<AccountId>`
- **summary**: Who is able to vote for whom. Value is the fund-holding account, key is the vote-transaction-sending account.
▸ **registerInfoOf**(`AccountId`): `Option<(VoteIndex,u32)>`
- **summary**: The vote index and list slot that the candidate `who` was registered or `None` if they are not currently registered.
▸ **termDuration**(): `BlockNumber`
- **summary**: How long each position is active for.
▸ **voteCount**(): `VoteIndex`
- **summary**: The total number of vote rounds that have happened or are in progress.
▸ **voterCount**(): `SetIndex`
- **summary**: Current number of Voters.
▸ **voterInfoOf**(`AccountId`): `Option<VoterInfo>`
- **summary**: Basic information about a voter.
▸ **voters**(`SetIndex`): `Vec<Option<AccountId>>`
- **summary**: The present voter list (chunked and capped at [`VOTER_SET_SIZE`]).
___
### grandpa
▸ **authorities**(): `Vec<(AuthorityId,AuthorityWeight)>`
- **summary**: The current authority set.
▸ **currentSetId**(): `SetId`
- **summary**: The number of changes (both in terms of keys and underlying economic responsibilities) in the "set" of Grandpa validators from genesis.
▸ **nextForced**(): `Option<BlockNumber>`
- **summary**: next block number where we can force a change.
▸ **pendingChange**(): `Option<StoredPendingChange>`
- **summary**: Pending change: (signaled at, scheduled change).
▸ **setIdSession**(`SetId`): `Option<SessionIndex>`
- **summary**: A mapping from grandpa set ID to the index of the *most recent* session for which its members were responsible.
▸ **stalled**(): `Option<(BlockNumber,BlockNumber)>`
- **summary**: `true` if we are currently stalled.
▸ **state**(): `StoredState`
- **summary**: State of the current authority set.
___
### imOnline
▸ **gossipAt**(): `BlockNumber`
- **summary**: The block number when we should gossip.
▸ **keys**(): `Vec<AuthorityId>`
- **summary**: The current set of keys that may issue a heartbeat.
▸ **receivedHeartbeats**(`SessionIndex, AuthIndex`): `Bytes`
- **summary**: For each session index we keep a mapping of `AuthorityId` to `offchain::OpaqueNetworkState`.
___
### indices
▸ **enumSet**(`AccountIndex`): `Vec<AccountId>`
- **summary**: The enumeration sets.
▸ **nextEnumSet**(): `AccountIndex`
- **summary**: The next free enumeration set.
___
### offences
▸ **concurrentReportsIndex**(`Kind, OpaqueTimeSlot`): `Vec<ReportIdOf>`
- **summary**: A vector of reports of the same kind that happened at the same time slot.
▸ **reports**(`ReportIdOf`): `Option<OffenceDetails>`
- **summary**: The primary structure that holds all offence records keyed by report identifiers.
▸ **reportsByKindIndex**(`Kind`): `Bytes`
- **summary**: Enumerates all reports of a kind along with the time they happened. All reports are sorted by the time of offence. Note that the actual type of this mapping is `Vec<u8>`, this is because values of different types are not supported at the moment so we are doing the manual serialization.
___
### session
▸ **currentIndex**(): `SessionIndex`
- **summary**: Current index of the session.
▸ **disabledValidators**(): `Vec<u32>`
- **summary**: Indices of disabled validators. The set is cleared when `on_session_ending` returns a new set of identities.
▸ **keyOwner**(`Bytes, (KeyTypeId,Bytes)`): `Option<ValidatorId>`
- **summary**: The owner of a key. The second key is the `KeyTypeId` + the encoded key. The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of the trie. Having all data in the same branch should prevent slowing down other queries.
▸ **nextKeys**(`Bytes, ValidatorId`): `Option<Keys>`
- **summary**: The next session keys for a validator. The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of the trie. Having all data in the same branch should prevent slowing down other queries.
▸ **queuedChanged**(): `bool`
- **summary**: True if the underlying economic identities or weighting behind the validators has changed in the queued validator set.
▸ **queuedKeys**(): `Vec<(ValidatorId,Keys)>`
- **summary**: The queued keys for the next session. When the next session begins, these keys will be used to determine the validator's session keys.
▸ **validators**(): `Vec<ValidatorId>`
- **summary**: The current set of validators.
___
### staking
▸ **bonded**(`AccountId`): `Option<AccountId>`
- **summary**: Map from all locked "stash" accounts to the controller account.
▸ **bondedEras**(): `Vec<(EraIndex,SessionIndex)>`
- **summary**: A mapping from still-bonded eras to the first session index of that era.
▸ **currentElected**(): `Vec<AccountId>`
- **summary**: The currently elected validator set keyed by stash account ID.
▸ **currentEra**(): `EraIndex`
- **summary**: The current era index.
▸ **currentEraPointsEarned**(): `EraPoints`
- **summary**: Rewards for the current era. Using indices of current elected set.
▸ **currentEraStart**(): `MomentOf`
- **summary**: The start of the current era.
▸ **currentEraStartSessionIndex**(): `SessionIndex`
- **summary**: The session index at which the current era started.
▸ **eraSlashJournal**(`EraIndex`): `Vec<SlashJournalEntry>`
- **summary**: All slashes that have occurred in a given era.
▸ **forceEra**(): `Forcing`
- **summary**: True if the next session change will be a new era regardless of index.
▸ **invulnerables**(): `Vec<AccountId>`
- **summary**: Any validators that may never be slashed or forcibly kicked. It's a Vec since they're easy to initialize and the performance hit is minimal (we expect no more than four invulnerables) and restricted to testnets.
▸ **ledger**(`AccountId`): `Option<StakingLedger>`
- **summary**: Map from all (unlocked) "controller" accounts to the info regarding the staking.
▸ **minimumValidatorCount**(): `u32`
- **summary**: Minimum number of staking participants before emergency conditions are imposed.
▸ **nominators**(`AccountId`): `(Vec<AccountId>, Linkage<AccountId>)`
- **summary**: The map from nominator stash key to the set of stash keys of all validators to nominate.
▸ **payee**(`AccountId`): `RewardDestination`
- **summary**: Where the reward payment should be made. Keyed by stash.
▸ **slashRewardFraction**(): `Perbill`
- **summary**: The percentage of the slash that is distributed to reporters. The rest of the slashed value is handled by the `Slash`.
▸ **slotStake**(): `BalanceOf`
- **summary**: The amount of balance actively at stake for each validator slot, currently. This is used to derive rewards and punishments.
▸ **stakers**(`AccountId`): `Exposure`
- **summary**: Nominators for a particular account that is in action right now. You can't iterate through validators here, but you can find them in the Session module. This is keyed by the stash account.
▸ **validatorCount**(): `u32`
- **summary**: The ideal number of staking participants.
▸ **validators**(`AccountId`): `(ValidatorPrefs, Linkage<AccountId>)`
- **summary**: The map from (wannabe) validator stash key to the preferences of that validator.
___
### sudo
▸ **key**(): `AccountId`
- **summary**: The `AccountId` of the sudo key.
___
### system
▸ **accountNonce**(`AccountId`): `Index`
- **summary**: Extrinsics nonce for accounts.
▸ **allExtrinsicsLen**(): `Option<u32>`
- **summary**: Total length (in bytes) for all extrinsics put together, for the current block.
▸ **allExtrinsicsWeight**(): `Option<Weight>`
- **summary**: Total weight for all extrinsics put together, for the current block.
▸ **blockHash**(`BlockNumber`): `Hash`
- **summary**: Map of block numbers to block hashes.
▸ **digest**(): `DigestOf`
- **summary**: Digest of the current block, also part of the block header.
▸ **eventCount**(): `EventIndex`
- **summary**: The number of events in the `Events<T>` list.
▸ **events**(): `Vec<EventRecord>`
- **summary**: Events deposited for the current block.
▸ **eventTopics**(`Null, Hash`): `Vec<(BlockNumber,EventIndex)>`
- **summary**: Mapping between a topic (represented by T::Hash) and a vector of indexes of events in the `<Events<T>>` list. The first key serves no purpose. This field is declared as double_map just for convenience of using `remove_prefix`. All topic vectors have deterministic storage locations depending on the topic. This allows light-clients to leverage the changes trie storage tracking mechanism and in case of changes fetch the list of events of interest. The value has the type `(T::BlockNumber, EventIndex)` because if we used only just the `EventIndex` then in case if the topic has the same contents on the next block no notification will be triggered thus the event might be lost.
▸ **extrinsicCount**(): `Option<u32>`
- **summary**: Total extrinsics count for the current block.
▸ **extrinsicData**(`u32`): `Bytes`
- **summary**: Extrinsics data for the current block (maps an extrinsic's index to its data).
▸ **extrinsicsRoot**(): `Hash`
- **summary**: Extrinsics root of the current block, also part of the block header.
▸ **nextWeightMultiplier**(): `WeightMultiplier`
- **summary**: The next weight multiplier. This should be updated at the end of each block based on the saturation level (weight).
▸ **number**(): `BlockNumber`
- **summary**: The current block number being processed. Set by `execute_block`.
▸ **parentHash**(): `Hash`
- **summary**: Hash of the previous block.
▸ **randomMaterial**(): `(i8,Vec<Hash>)`
- **summary**: Series of block headers from the last 81 blocks that acts as random seed material. This is arranged as a ring buffer with the `i8` prefix being the index into the `Vec` of the oldest hash.
___
### technicalCommittee
▸ **members**(): `Vec<AccountId>`
- **summary**: The current members of the collective. This is stored sorted (just by value).
▸ **proposalCount**(): `u32`
- **summary**: Proposals so far.
▸ **proposalOf**(`Hash`): `Option<Proposal>`
- **summary**: Actual proposal for a given hash, if it's current.
▸ **proposals**(): `Vec<Hash>`
- **summary**: The hashes of the active proposals.
▸ **voting**(`Hash`): `Option<Votes>`
- **summary**: Votes on a given proposal, if it is ongoing.
___
### technicalMembership
▸ **members**(): `Vec<AccountId>`
- **summary**: The current membership, stored as an ordered Vec.
___
### timestamp
▸ **didUpdate**(): `bool`
- **summary**: Did the timestamp get updated in this block?
▸ **now**(): `Moment`
- **summary**: Current time for the current block.
___
### treasury
▸ **approvals**(): `Vec<ProposalIndex>`
- **summary**: Proposal indices that have been approved but not yet awarded.
▸ **proposalCount**(): `ProposalIndex`
- **summary**: Number of proposals that have been made.
▸ **proposals**(`ProposalIndex`): `Option<TreasuryProposal>`
- **summary**: Proposals that have been made.
---
### substrate
_These are keys that are always available to the runtime implementation_
▸ **changesTrieConfig**(): `u32`
- **summary**: Changes trie configuration is stored under this key.
▸ **childStorageKeyPrefix**(): `u32`
- **summary**: Prefix of child storage keys.
▸ **code**(): `Bytes`
- **summary**: Wasm code of the runtime.
▸ **extrinsicIndex**(): `u32`
- **summary**: Current extrinsic index (u32) is stored under this key.
▸ **heapPages**(): `u64`
- **summary**: Number of wasm linear memory pages required for execution of the runtime.
---
+4 -3
View File
@@ -7,19 +7,19 @@ module.exports = Object.assign({}, config, {
'@polkadot/api-contract(.*)$': '<rootDir>/packages/api-contract/src/$1',
'@polkadot/api-derive(.*)$': '<rootDir>/packages/api-derive/src/$1',
'@polkadot/api(.*)$': '<rootDir>/packages/api/src/$1',
'@polkadot/jsonrpc(.*)$': '<rootDir>/packages/jsonrpc/src/$1',
'@polkadot/metadata(.*)$': '<rootDir>/packages/metadata/src/$1',
'@polkadot/rpc-(core|provider)(.*)$': '<rootDir>/packages/rpc-$1/src/$2',
'@polkadot/jsonrpc(.*)$': '<rootDir>/packages/type-jsonrpc/src/$1',
'@polkadot/types(.*)$': '<rootDir>/packages/types/src/$1'
},
modulePathIgnorePatterns: [
'<rootDir>/packages/api/build',
'<rootDir>/packages/api-derive/build',
'<rootDir>/packages/api-contract/build',
'<rootDir>/packages/jsonrpc/build',
'<rootDir>/packages/metadata/build',
'<rootDir>/packages/rpc-core/build',
'<rootDir>/packages/rpc-provider/build',
'<rootDir>/packages/type-jsonrpc/build',
'<rootDir>/packages/types/build'
],
globals: {
@@ -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'
});
+14
View File
@@ -0,0 +1,14 @@
// 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')) {
return path.join(config.basedir.replace('/src', '/'), file);
}
return config.defaultResolver(file, config);
};
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "1.0.1"
"version": "1.4.1"
}
+15 -17
View File
@@ -1,5 +1,5 @@
{
"version": "1.0.1",
"version": "1.4.1",
"private": true,
"engines": {
"yarn": "^1.10.1"
@@ -8,28 +8,26 @@
"packages/*"
],
"resolutions": {
"babel-core": "^7.0.0-bridge.0",
"typescript": "^3.7.5"
"typescript": "^3.8.2"
},
"scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts",
"build:interfaces": "node packages/types/src/scripts/interfacesTsWrapper.js",
"circular": "madge --circular --extensions ts ./",
"docs": "node packages/types/src/scripts/MetadataMdWrapper.js && polkadot-dev-build-docs",
"chain:info": "node packages/types/src/scripts/extractChainWrapper.js",
"lint": "eslint --ext .js,.jsx,.ts,.tsx . && tsc --noEmit --pretty",
"build": "yarn build:interfaces && polkadot-dev-build-ts && (cd packages/typegen && copyfiles scripts/* build)",
"build:interfaces": "polkadot-types-internal-interfaces",
"docs": "polkadot-types-internal-metadata && polkadot-dev-build-docs",
"chain:info": "polkadot-types-chain-info",
"lint": "polkadot-dev-run-lint",
"clean": "polkadot-dev-clean-build",
"postinstall": "polkadot-dev-yarn-only",
"test": "jest --coverage --runInBand --testPathIgnorePatterns e2e",
"test:all": "jest",
"test:one": "jest",
"test:watch": "jest --coverage --watch"
"test": "polkadot-dev-run-test --coverage --runInBand --testPathIgnorePatterns e2e",
"test:one": "polkadot-dev-run-test",
"test:watch": "polkadot-dev-run-test --watch"
},
"devDependencies": {
"@babel/core": "^7.8.3",
"@babel/core": "^7.8.4",
"@babel/register": "^7.8.3",
"@babel/runtime": "^7.8.3",
"@polkadot/dev": "^0.33.3",
"@polkadot/ts": "^0.2.1"
"@babel/runtime": "^7.8.4",
"@polkadot/dev": "^0.41.4",
"@polkadot/ts": "^0.2.3",
"copyfiles": "^2.2.0"
}
}
+8 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-contract",
"version": "1.0.1",
"version": "1.4.1",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
"keywords": [
@@ -26,7 +26,12 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.8.3",
"@polkadot/types": "^1.0.1"
"@babel/runtime": "^7.8.4",
"@polkadot/api": "1.4.1",
"@polkadot/rpc-core": "1.4.1",
"@polkadot/types": "1.4.1",
"@polkadot/util": "^2.5.1",
"bn.js": "^5.1.1",
"rxjs": "^6.5.4"
}
}
@@ -5,7 +5,7 @@
import { CodecArg, Constructor, Registry, TypeDef } from '@polkadot/types/types';
import { ContractABIArgBasePre, ContractABIContract, ContractABIContractPre, ContractABIEvent, ContractABIEventPre, ContractABIFn, ContractABIFnArg, ContractABIMessage, ContractABIMessageBase, ContractABIMessagePre, ContractABI, ContractABIMessageCommon, ContractABIPre, ContractABIRange, ContractABIRangePre, ContractABIStorage, ContractABIStorageLayout, ContractABIStorageLayoutPre, ContractABIStoragePre, ContractABIStorageStruct, ContractABIStorageStructPre, ContractABITypePre } from './types';
import { Compact, u32, createClass, createType, encodeType } from '@polkadot/types';
import { Compact, u32, createClass, encodeType } from '@polkadot/types';
import { assert, hexToU8a, isNumber, isString, isNull, isObject, isUndefined, stringCamelCase, isHex, hexToNumber } from '@polkadot/util';
import MetaRegistry from './MetaRegistry';
@@ -14,16 +14,16 @@ import MetaRegistry from './MetaRegistry';
// just catch everything (since this is now non-standard for u32 anyway)
function parseSelector (registry: Registry, fnname: string, input: ContractABIMessageCommon['selector']): u32 {
if (isNumber(input)) {
return createType(registry, 'u32', input);
return registry.createType('u32', input);
} else if (isHex(input)) {
return createType(registry, 'u32', hexToU8a(input));
return registry.createType('u32', hexToU8a(input));
} else if (typeof input === 'string') {
try {
const array = JSON.parse(input);
assert(array.length === 4, `${fnname}: Invalid selector length`);
return createType(registry, 'u32', Uint8Array.from(
return registry.createType('u32', Uint8Array.from(
// the as number[] is here to pacify TS, it doesn't quite know how to handle the cb
(array as number[]).map((value: string | number): number =>
isHex(value)
+1 -1
View File
@@ -260,7 +260,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
return {
info: TypeDefInfo.VecFixed,
ext: { length: vecLength, type },
length: vecLength, // ex: { type: type }
type: `[${type};${vecLength}]`,
sub: this.typeDefFromMetaTypeAt(vecTypeIndex)
};
+5 -6
View File
@@ -2,16 +2,15 @@
// 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, SubmittableResultImpl } from '@polkadot/api/types';
import { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import { AccountId, Address, Hash } from '@polkadot/types/interfaces';
import { IKeyringPair } from '@polkadot/types/types';
import { IKeyringPair, ISubmittableResult } from '@polkadot/types/types';
import { ApiObject, ContractABIPre } from '../types';
import BN from 'bn.js';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { SubmittableResult } from '@polkadot/api';
import { createType } from '@polkadot/types';
import { assert } from '@polkadot/util';
import Abi from '../Abi';
@@ -27,7 +26,7 @@ export interface BlueprintCreate<ApiType extends ApiTypes> {
class BlueprintCreateResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly contract?: Contract<ApiType>;
constructor (result: SubmittableResultImpl, contract?: Contract<ApiType>) {
constructor (result: ISubmittableResult, contract?: Contract<ApiType>) {
super(result);
this.contract = contract;
@@ -41,7 +40,7 @@ export default class Blueprint<ApiType extends ApiTypes> extends BaseWithTx<ApiT
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>, codeHash: string | Hash) {
super(api, abi, decorateMethod);
this.codeHash = createType(this.registry, 'Hash', codeHash);
this.codeHash = this.registry.createType('Hash', codeHash);
}
public deployContract (constructorIndex = 0, endowment: number | BN, maxGas: number | BN, ...params: any[]): BlueprintCreate<ApiType> {
@@ -62,7 +61,7 @@ export default class Blueprint<ApiType extends ApiTypes> extends BaseWithTx<ApiT
private createResult = (result: SubmittableResult): BlueprintCreateResult<ApiType> => {
let contract: Contract<ApiType> | undefined;
if (result.isFinalized) {
if (result.isInBlock) {
const record = result.findRecord('contract', 'Instantiated');
if (record) {
+5 -5
View File
@@ -2,9 +2,9 @@
// 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, SubmittableResultImpl } from '@polkadot/api/types';
import { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import { AccountId, Address, Hash } from '@polkadot/types/interfaces';
import { IKeyringPair } from '@polkadot/types/types';
import { IKeyringPair, ISubmittableResult } from '@polkadot/types/types';
import { ApiObject, ContractABIPre } from '../types';
import BN from 'bn.js';
@@ -27,7 +27,7 @@ export interface CodePutCode<ApiType extends ApiTypes> {
class CodePutCodeResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly blueprint?: Blueprint<ApiType>;
constructor (result: SubmittableResultImpl, blueprint?: Blueprint<ApiType>) {
constructor (result: ISubmittableResult, blueprint?: Blueprint<ApiType>) {
super(result);
this.blueprint = blueprint;
@@ -55,10 +55,10 @@ export default class Code<ApiType extends ApiTypes> extends BaseWithTx<ApiType>
};
}
private createResult = (result: SubmittableResultImpl): CodePutCodeResult<ApiType> => {
private createResult = (result: ISubmittableResult): CodePutCodeResult<ApiType> => {
let blueprint: Blueprint<ApiType> | undefined;
if (result.isFinalized) {
if (result.isInBlock) {
const record = result.findRecord('contract', 'CodeStored');
if (record) {
+4 -5
View File
@@ -11,7 +11,6 @@ import BN from 'bn.js';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { SubmittableResult } from '@polkadot/api';
import { createType } from '@polkadot/types';
import Abi from '../Abi';
import { formatData } from '../util';
import { BaseWithTxAndRpcCall } from './util';
@@ -44,7 +43,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
as === 'rpc' && this.hasRpcContractsCall
? (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'rpc'> => {
return this.rpcContractsCall(
createType(this.registry, 'ContractCallRequest', {
this.registry.createType('ContractCallRequest', {
origin: account,
dest: this.address.toString(),
value,
@@ -54,7 +53,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
)
.pipe(
map((result: ContractExecResult): ContractCallOutcome =>
this.createOutcome(result, createType(this.registry, 'AccountId', account), def, params)
this.createOutcome(result, this.registry.createType('AccountId', account), def, params)
)
);
}
@@ -75,7 +74,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
output = message.returnType
? formatData(this.registry, data, message.returnType)
: createType(this.registry, 'Raw', data);
: this.registry.createType('Raw', data);
}
return {
@@ -92,6 +91,6 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>, address: string | AccountId | Address) {
super(api, abi, decorateMethod);
this.address = createType(this.registry, 'Address', address);
this.address = this.registry.createType('Address', address);
}
}
+2 -2
View File
@@ -3,9 +3,9 @@
// 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, isFunction, stringCamelCase } from '@polkadot/util';
import Abi from '../Abi';
+1 -1
View File
@@ -5,7 +5,7 @@
import { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import { AccountId, Address, ContractExecResult } from '@polkadot/types/interfaces';
import { Codec, CodecArg } from '@polkadot/types/types';
import { MetaRegistryJson, StringIndex, TypeIndex, TypeDef } from '@polkadot/types/codec/create/types';
import { MetaRegistryJson, StringIndex, TypeIndex, TypeDef } from '@polkadot/types/create/types';
// import { Observable } from 'rxjs';
import { ApiPromise, ApiRx } from '@polkadot/api';
+1 -2
View File
@@ -4,8 +4,7 @@
import { Codec, Registry, TypeDefInfo, TypeDef } from '@polkadot/types/types';
import { Option, Raw, createClass } from '@polkadot/types';
import { createTypeUnsafe } from '@polkadot/types/codec';
import { Option, Raw, createClass, createTypeUnsafe } from '@polkadot/types';
export function formatData (registry: Registry, data: Raw, { info, type }: TypeDef): Codec {
if (info === TypeDefInfo.Option) {
@@ -18,10 +18,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -71,10 +68,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -116,10 +110,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -153,10 +144,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -183,10 +171,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -223,10 +208,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -256,10 +238,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -295,10 +274,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -340,10 +316,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -381,10 +354,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -402,10 +372,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -439,10 +406,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -460,10 +424,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -506,10 +467,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -527,10 +485,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -566,10 +521,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -587,10 +539,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -628,10 +577,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -677,10 +623,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -708,10 +651,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -725,10 +665,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -757,10 +694,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -802,10 +736,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -839,10 +770,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -869,10 +797,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -909,10 +834,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -942,10 +864,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -969,10 +888,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -998,10 +914,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1047,10 +960,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1082,10 +992,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1119,10 +1026,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1149,10 +1053,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1189,10 +1090,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1230,10 +1128,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1260,10 +1155,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1300,10 +1192,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1331,10 +1220,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1361,10 +1247,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1400,10 +1283,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1445,10 +1325,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1486,10 +1363,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1507,10 +1381,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1544,10 +1415,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1565,10 +1433,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1611,10 +1476,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1632,10 +1494,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1671,10 +1530,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1692,10 +1548,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1725,10 +1578,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1746,10 +1596,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1773,10 +1620,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1814,10 +1658,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1835,10 +1676,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1872,10 +1710,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1893,10 +1728,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1939,10 +1771,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1960,10 +1789,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2007,10 +1833,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2028,10 +1851,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2065,10 +1885,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2086,10 +1903,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2132,10 +1946,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2153,10 +1964,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2190,10 +1998,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2211,10 +2016,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2248,10 +2050,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2269,10 +2068,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2305,10 +2101,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -2328,10 +2121,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -38,10 +38,7 @@
{
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -89,10 +86,7 @@
{
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -130,10 +124,7 @@
{
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -153,10 +144,7 @@
{
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -168,10 +156,7 @@
{
"info": 11,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": ""
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -181,4 +166,4 @@
"info": 6,
"type": "u8"
}
]
]
@@ -18,10 +18,7 @@
{
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 7,
"type": "u8"
@@ -71,10 +68,7 @@
{
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 7,
"type": "u8"
@@ -120,10 +114,7 @@
{
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 7,
"type": "u8"
@@ -151,10 +142,7 @@
{
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 7,
"type": "u8"
@@ -168,10 +156,7 @@
{
"info": 13,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 7,
"type": "u8"
@@ -185,4 +170,4 @@
"info": 7,
"type": "bool"
}
]
]
@@ -22,10 +22,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -67,10 +64,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -104,10 +98,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -167,10 +158,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -241,10 +229,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -308,10 +293,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -381,10 +363,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -426,10 +405,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -483,10 +459,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -528,10 +501,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -565,10 +535,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -628,10 +595,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -702,10 +666,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -769,10 +730,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -830,10 +788,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -847,10 +802,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -932,10 +884,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -977,10 +926,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1008,10 +954,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1033,10 +976,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1070,10 +1010,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1133,10 +1070,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1207,10 +1141,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1282,10 +1213,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1345,10 +1273,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1419,10 +1344,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1484,10 +1406,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1547,10 +1466,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1620,10 +1536,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1665,10 +1578,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -1714,10 +1624,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -22,10 +22,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -71,10 +68,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -288,10 +282,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -337,10 +328,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -438,10 +426,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -487,10 +472,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -518,10 +500,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -535,10 +514,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -563,10 +539,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
@@ -714,10 +687,7 @@
{
"info": 12,
"type": "[u8;32]",
"ext": {
"length": 32,
"type": "u8"
},
"length": 32,
"sub": {
"info": 6,
"type": "u8"
+12 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "1.0.1",
"version": "1.4.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"keywords": [
@@ -27,11 +27,18 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.8.3",
"@polkadot/api": "^1.0.1",
"@polkadot/types": "^1.0.1"
"@babel/runtime": "^7.8.4",
"@polkadot/api": "1.4.1",
"@polkadot/rpc-core": "1.4.1",
"@polkadot/rpc-provider": "1.4.1",
"@polkadot/types": "1.4.1",
"@polkadot/util": "^2.5.1",
"@polkadot/util-crypto": "^2.5.1",
"bn.js": "^5.1.1",
"memoizee": "^0.4.14",
"rxjs": "^6.5.4"
},
"devDependencies": {
"@polkadot/keyring": "^2.0.1"
"@polkadot/keyring": "^2.5.1"
}
}
+34 -18
View File
@@ -2,16 +2,39 @@
// 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 { AccountId, AccountIndex, BalanceOf } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
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';
import { ClassOf, Vec, createType } from '@polkadot/types';
import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
import { ClassOf, Option, Vec, createType } from '@polkadot/types';
import { memo } from '../util';
function queryEnumSet (api: ApiInterfaceRx, _accountIndex: AccountIndex | string): Observable<AccountId | undefined> {
const accountIndex = _accountIndex instanceof ClassOf(api.registry, 'AccountIndex')
? _accountIndex
: createType(api.registry, 'AccountIndex', _accountIndex);
return api.query.indices.enumSet<Vec<AccountId>>(accountIndex.div(ENUMSET_SIZE)).pipe(
startWith([]),
map((accounts): AccountId | undefined =>
(accounts || [])[accountIndex.mod(ENUMSET_SIZE).toNumber()]
)
);
}
// current
function query (api: ApiInterfaceRx, accountIndex: AccountIndex | string): Observable<AccountId | undefined> {
return api.query.indices.accounts<Option<ITuple<[AccountId, BalanceOf]>>>(accountIndex).pipe(
map((optResult): AccountId | undefined =>
optResult.unwrapOr([])[0]
)
);
}
/**
* @name indexToId
* @param {( AccountIndex | string )} accountIndex - An accounts index in different formats.
@@ -26,18 +49,11 @@ 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 memo((accountIndex: AccountIndex | string): Observable<AccountId | undefined> =>
api.query.indices
? api.query.indices.accounts
? query(api, accountIndex)
: queryEnumSet(api, accountIndex)
: of(undefined)
);
}
+38 -23
View File
@@ -6,15 +6,45 @@ 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 { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
import { Vec, createType } from '@polkadot/types';
import { memo } from '../util';
const enumsetSize = ENUMSET_SIZE.toNumber();
function queryEnumSet (api: ApiInterfaceRx): Observable<AccountIndexes> {
return 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()])
),
map((all: AccountId[][]): AccountIndexes =>
all.reduce((result: AccountIndexes, list, outerIndex): AccountIndexes => {
(list || []).forEach((accountId, innerIndex): void => {
// re-create the index based on position 0 is [0][0] and likewise
// 64 (0..63 in first) is [1][0] (the first index value in set 2)
const index = (outerIndex * enumsetSize) + innerIndex;
result[accountId.toString()] = createType(api.registry, 'AccountIndex', index);
});
return result;
}, {})
)
);
}
// TODO Reverse lookup (via query keys)
function query (): Observable<AccountIndexes> {
return of({} as AccountIndexes);
}
/**
* @name indexes
* @returns Returns all the indexes on the system.
@@ -32,25 +62,10 @@ 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()])
),
map((all: AccountId[][]): AccountIndexes =>
all.reduce((result: AccountIndexes, list, outerIndex): AccountIndexes => {
(list || []).forEach((accountId, innerIndex): void => {
// re-create the index based on position 0 is [0][0] and likewise
// 64 (0..63 in first) is [1][0] (the first index value in set 2)
const index = (outerIndex * enumsetSize) + innerIndex;
result[accountId.toString()] = createType(api.registry, 'AccountIndex', index);
});
return result;
}, {}))
));
api.query.indices
? api.query.indices.accounts
? query()
: queryEnumSet(api)
: of({} as AccountIndexes)
);
}
+10
View File
@@ -54,6 +54,16 @@ function extractIdentity (identityOfOpt?: Option<Registration>, superOf?: [Accou
email: dataAsString(info.email),
image: dataAsString(info.image),
legal: dataAsString(info.legal),
other: info.additional.reduce((other: Record<string, string>, [_key, _value]): Record<string, string> => {
const key = dataAsString(_key);
const value = dataAsString(_value);
if (key && value) {
other[key] = value;
}
return other;
}, {}),
parent: superOf
? superOf[0]
: undefined,
+101
View File
@@ -0,0 +1,101 @@
// 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, AccountInfo, Address, Balance, Index } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
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 queryBalancesFree (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 queryBalancesAccount (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]
)
);
}
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Result> {
// AccountInfo is current, support old, eg. Edgeware
return api.query.system.account<AccountInfo | ITuple<[Index, AccountData]>>(accountId).pipe(
map((infoOrTuple): Result => {
const { free, reserved, miscFrozen, feeFrozen } = (infoOrTuple as AccountInfo).nonce
? (infoOrTuple as AccountInfo).data
: (infoOrTuple as [Index, AccountData])[1];
const accountNonce = (infoOrTuple as AccountInfo).nonce || (infoOrTuple as [Index, AccountData])[0];
return [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.system.account
? queryCurrent(api, accountId)
: api.query.balances.account
? queryBalancesAccount(api, accountId)
: queryBalancesFree(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))
));
}
+70 -29
View File
@@ -2,8 +2,8 @@
// 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>, Index];
type Result = [AccountId, BlockNumber, ResultBalance];
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,16 +57,58 @@ 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
};
}
// 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]
)
);
}
/**
* @name all
* @param {( AccountIndex | AccountId | Address | string )} address - An accounts Id in different formats.
@@ -79,25 +124,21 @@ function calcBalances (api: ApiInterfaceRx, [accountId, bestNumber, [freeBalance
* });
* ```
*/
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(),
api.queryMulti<[Balance, Balance, Vec<BalanceLock>, Option<VestingSchedule>, Index]>([
[api.query.balances.freeBalance, accountId],
[api.query.balances.reservedBalance, accountId],
[api.query.balances.locks, accountId],
[api.query.balances.vesting, accountId],
[api.query.system.accountNonce, 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))
));
}
+12 -18
View File
@@ -8,25 +8,10 @@ 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 query (api: ApiInterfaceRx): Observable<Result> {
const paymentBase = api.consts.transactionPayment || api.consts.balances;
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
]);
}
/**
* @name fees
* @returns An object containing the combined results of the storage queries for
@@ -42,8 +27,17 @@ function query (api: ApiInterfaceRx): Observable<Result> {
*/
export function fees (api: ApiInterfaceRx): () => Observable<DerivedFees> {
return memo((): Observable<DerivedFees> =>
query(api).pipe(
map(([creationFee, existentialDeposit, transferFee, transactionBaseFee, transactionByteFee]): DerivedFees => ({
of([
// deprecated - remove
(api.consts.balances.creationFee as Balance) || createType(api.registry, 'Balance'),
(api.consts.balances.transferFee as Balance) || createType(api.registry, 'Balance'),
// current
api.consts.balances.existentialDeposit,
api.consts.transactionPayment.transactionBaseFee,
api.consts.transactionPayment.transactionByteFee
]).pipe(
map(([creationFee, transferFee, existentialDeposit, transactionBaseFee, transactionByteFee]): DerivedFees => ({
creationFee,
existentialDeposit,
transactionBaseFee,
+1 -1
View File
@@ -4,9 +4,9 @@
import { all } from './all';
export * from './account';
export * from './fees';
export * from './votingBalances';
export * from './votingBalancesNominatorsFor';
const votingBalance = all;
@@ -3,20 +3,20 @@
// 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-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 { 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)
)
));
}
+20 -34
View File
@@ -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
}))
);
});
}
@@ -10,13 +10,13 @@ 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, votersFor),
+11 -4
View File
@@ -13,21 +13,28 @@ import { createType, Vec, u32 } from '@polkadot/types';
import { DerivedElectionsInfo } from '../types';
import { memo } from '../util';
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';
return api.queryMulti<[Vec<AccountId>, Vec<ITuple<[AccountId, Balance]>>, 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 => ({
map(([councilMembers, candidates, members, runnersUp]): DerivedElectionsInfo => ({
candidates,
candidateCount: createType(api.registry, 'u32', candidates.length),
candidacyBond: api.consts[section].candidacyBond as Balance,
desiredSeats: api.consts[section].desiredMembers as u32,
members: members.sort((a, b): number => b[1].cmp(a[1])),
runnersUp: runnersUp.sort((a, b): number => b[1].cmp(a[1])),
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
}))
-2
View File
@@ -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', []);
});
+3 -1
View File
@@ -15,6 +15,7 @@ import * as council from './council';
import * as democracy from './democracy';
import * as elections from './elections';
import * as imOnline from './imOnline';
import * as parachains from './parachains';
import * as session from './session';
import * as society from './society';
import * as staking from './staking';
@@ -23,7 +24,7 @@ import * as treasury from './treasury';
export * from './type';
export const derive = { accounts, balances, chain, contracts, council, democracy, elections, imOnline, session, society, staking, technicalCommittee, treasury };
export const derive = { accounts, balances, chain, contracts, council, democracy, elections, imOnline, parachains, session, society, staking, technicalCommittee, treasury };
type DeriveSection<Section> = {
[Method in keyof Section]: Section[Method] extends AnyFunction
@@ -45,6 +46,7 @@ const deriveAvail: Record<string, string[]> = {
democracy: ['democracy'],
elections: ['electionsPhragmen', 'elections'],
imOnline: ['imOnline'],
parachains: ['parachains', 'registrar'],
session: ['session'],
society: ['society'],
staking: ['staking'],
@@ -0,0 +1,6 @@
// 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 './info';
export * from './overview';
@@ -0,0 +1,99 @@
// 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 { CollatorId, ParaId } from '@polkadot/types/interfaces';
import { DeriveParachainInfo, DeriveParachainFull, DeriveParachainActive } from '../types';
import { Active, DidUpdate, Heads, ParaInfoResult, PendingSwap, RelayDispatchQueue, RetryQueue, SelectedThreads, Watermarks } from './types';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { createType } from '@polkadot/types';
import { memo } from '../util';
type Result = [
Active,
RetryQueue,
SelectedThreads,
DidUpdate,
ParaInfoResult,
PendingSwap,
Heads,
RelayDispatchQueue,
Watermarks
];
function parseActive (id: ParaId, active: Active): DeriveParachainActive | null {
const found = active.find(([paraId]): boolean => paraId === id);
if (found && found[1].isSome) {
const [collatorId, retriable] = found[1].unwrap();
return {
collatorId,
...(
retriable.isWithRetries
? {
isRetriable: true,
retries: retriable.asWithRetries.toNumber()
}
: {
isRetriable: false,
retries: 0
}
)
};
}
return null;
}
function parseCollators (id: ParaId, collatorQueue: SelectedThreads | RetryQueue): (CollatorId | null)[] {
return collatorQueue
.map((queue): CollatorId | null => {
const found = queue.find(([paraId]): boolean => paraId === id);
return found ? found[1] : null;
});
}
function parse (id: ParaId, [active, retryQueue, selectedThreads, didUpdate, info, pendingSwap, heads, relayDispatchQueue, watermarks]: Result): DeriveParachainFull {
return {
active: parseActive(id, active),
didUpdate: didUpdate.isSome
? !!didUpdate.unwrap().some((paraId): boolean => paraId.eq(id))
: false,
heads,
id,
info: { id, ...info.unwrapOr(null) } as DeriveParachainInfo,
pendingSwapId: pendingSwap.unwrapOr(null),
relayDispatchQueue,
retryCollators: parseCollators(id, retryQueue),
selectedCollators: parseCollators(id, selectedThreads),
watermark: watermarks.unwrapOr(null)
};
}
export function info (api: ApiInterfaceRx): (id: ParaId | number) => Observable<DeriveParachainFull | null> {
return memo((id: ParaId | number): Observable<DeriveParachainFull | null> =>
api.query.registrar && api.query.parachains
? api.queryMulti<Result>([
api.query.registrar.active,
api.query.registrar.retryQueue,
api.query.registrar.selectedThreads,
api.query.parachains.didUpdate,
[api.query.registrar.paras, id],
[api.query.registrar.pendingSwap, id],
[api.query.parachains.heads, id],
[api.query.parachains.relayDispatchQueue, id],
[api.query.parachains.watermarks, id]
])
.pipe(
map((result: Result): DeriveParachainFull =>
parse(createType(api.registry, 'ParaId', id), result)
)
)
: of(null)
);
}
@@ -0,0 +1,59 @@
// 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 { ParaId } from '@polkadot/types/interfaces';
import { DeriveParachain, DeriveParachainInfo } from '../types';
import { DidUpdate, ParaInfoResult, PendingSwap, RelayDispatchQueueSize, Watermarks } from './types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
type Result = [
ParaId[],
DidUpdate,
ParaInfoResult[],
PendingSwap[],
RelayDispatchQueueSize[],
Watermarks[],
];
function parse ([ids, didUpdate, infos, pendingSwaps, relayDispatchQueueSizes, watermarks]: Result): DeriveParachain[] {
return ids.map((id, index): DeriveParachain => {
return {
didUpdate: didUpdate.isSome
? !!didUpdate.unwrap().some((paraId): boolean => paraId.eq(id))
: false,
id,
info: { id, ...infos[index].unwrapOr(null) } as DeriveParachainInfo,
pendingSwapId: pendingSwaps[index].unwrapOr(null),
relayDispatchQueueSize: relayDispatchQueueSizes[index][0].toNumber(),
watermark: watermarks[index].unwrapOr(null)
};
});
}
export function overview (api: ApiInterfaceRx): () => Observable<DeriveParachain[]> {
return memo((): Observable<DeriveParachain[]> =>
api.query.registrar?.parachains && api.query.parachains
? api.query.registrar.parachains<ParaId[]>().pipe(
switchMap((paraIds) =>
combineLatest([
of(paraIds),
api.query.parachains.didUpdate<DidUpdate>(),
api.query.registrar.paras.multi<ParaInfoResult>(paraIds),
api.query.registrar.pendingSwap.multi<PendingSwap>(paraIds),
api.query.parachains.relayDispatchQueueSize.multi<RelayDispatchQueueSize>(paraIds),
api.query.parachains.watermarks.multi<Watermarks>(paraIds)
])
),
map((result: Result): DeriveParachain[] =>
parse(result)
)
)
: of([] as DeriveParachain[])
);
}
@@ -0,0 +1,20 @@
// 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, CollatorId, ParaId, ParaInfo, Retriable, UpwardMessage } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { Bytes, Option, u32, Vec } from '@polkadot/types';
export type ParaInfoResult = Option<ParaInfo>;
export type PendingSwap = Option<ParaId>;
export type Active = Vec<ITuple<[ParaId, Option<ITuple<[CollatorId, Retriable]>>]>>;
export type RetryQueue = Vec<Vec<ITuple<[ParaId, CollatorId]>>>
export type SelectedThreads = Vec<Vec<ITuple<[ParaId, CollatorId]>>>
export type Code = Bytes;
export type Heads = Bytes;
export type RelayDispatchQueue = Vec<UpwardMessage>
export type RelayDispatchQueueSize = ITuple<[u32, u32]>;
export type Watermarks = Option<BlockNumber>;
export type DidUpdate = Option<Vec<ParaId>>;
+68 -14
View File
@@ -3,29 +3,83 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { EraIndex, SessionIndex } from '@polkadot/types/interfaces';
import { EraIndex, MomentOf, SessionIndex } from '@polkadot/types/interfaces';
import { DeriveSessionIndexes } from '../types';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { createType, u32 as U32 } from '@polkadot/types';
import { createType, Option, u32 } from '@polkadot/types';
import { memo } from '../util';
type Result = [EraIndex, Option<MomentOf>, EraIndex, SessionIndex, u32];
// parse into Indexes
function parse ([activeEra, activeEraStart, currentEra, currentIndex, validatorCount]: Result): DeriveSessionIndexes {
return {
activeEra,
activeEraStart,
currentEra,
currentIndex,
validatorCount
};
}
// query for previous V2
function queryNoActive (api: ApiInterfaceRx): Observable<Result> {
return api.queryMulti<[EraIndex, SessionIndex, u32]>([
api.query.staking.currentEra,
api.query.session.currentIndex,
api.query.staking.validatorCount
]).pipe(
map(([currentEra, currentIndex, validatorCount]): Result => [
currentEra,
createType(api.registry, 'Option<MomentOf>'),
currentEra,
currentIndex,
validatorCount
])
);
}
// query based on latest
function query (api: ApiInterfaceRx): Observable<Result> {
return api.queryMulti<[Option<EraIndex>, Option<MomentOf>, Option<EraIndex>, SessionIndex, u32]>([
api.query.staking.activeEra,
api.query.staking.activeEraStart,
api.query.staking.currentEra,
api.query.session.currentIndex,
api.query.staking.validatorCount
]).pipe(
map(([activeEra, activeEraStart, currentEra, currentIndex, validatorCount]): Result => [
activeEra.unwrapOr(createType(api.registry, 'EraIndex', 1)),
activeEraStart,
currentEra.unwrapOr(createType(api.registry, 'EraIndex', 1)),
currentIndex,
validatorCount
])
);
}
// empty set when none is available
function empty (api: ApiInterfaceRx): Observable<Result> {
return of([
createType(api.registry, 'EraIndex', 1),
createType(api.registry, 'Option<MomentOf>'),
createType(api.registry, 'EraIndex', 1),
createType(api.registry, 'SessionIndex', 1),
createType(api.registry, 'u32')
]);
}
export function indexes (api: ApiInterfaceRx): () => Observable<DeriveSessionIndexes> {
return memo((): Observable<DeriveSessionIndexes> =>
(
// Some chains (eg. very limited node-template), does not have session
api.query.session && api.query.staking
? api.queryMulti<[SessionIndex, EraIndex, U32]>([
api.query.session.currentIndex,
api.query.staking.currentEra,
api.query.staking.validatorCount
])
: of([createType(api.registry, 'SessionIndex', 1), createType(api.registry, 'EraIndex', 1), createType(api.registry, 'u32')])
).pipe(
map(([currentIndex, currentEra, validatorCount]): DeriveSessionIndexes => ({
currentIndex, currentEra, validatorCount
}))
));
? api.query.staking.activeEra
? query(api)
: queryNoActive(api)
: empty(api)
).pipe(map(parse))
);
}
+61 -28
View File
@@ -5,23 +5,26 @@
import { SessionIndex } from '@polkadot/types/interfaces';
import { DerivedSessionInfo, DeriveSessionIndexes } from '../types';
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { u64, createType } from '@polkadot/types';
import { createType, Option, u64 } from '@polkadot/types';
import { memo } from '../util';
type ResultSlots = [u64, u64, u64, SessionIndex];
type ResultSlots = [u64, u64, u64, Option<SessionIndex>];
type ResultSlotsFlat = [u64, u64, u64, SessionIndex];
type ResultType = [boolean, u64, SessionIndex];
type Result = [ResultType, DeriveSessionIndexes, ResultSlots];
type Result = [ResultType, DeriveSessionIndexes, ResultSlotsFlat];
function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, sessionsPerEra], { currentIndex, currentEra, validatorCount }, [currentSlot, epochIndex, epochOrGenesisStartSlot, currentEraStartSessionIndex]]: Result): DerivedSessionInfo {
function createDerived (api: ApiInterfaceRx, [[hasBabe, epochDuration, sessionsPerEra], { activeEra, activeEraStart, currentEra, currentIndex, validatorCount }, [currentSlot, epochIndex, epochOrGenesisStartSlot, activeEraStartSessionIndex]]: Result): DerivedSessionInfo {
const epochStartSlot = epochIndex.mul(epochDuration).add(epochOrGenesisStartSlot);
const sessionProgress = currentSlot.sub(epochStartSlot);
const eraProgress = currentIndex.sub(currentEraStartSessionIndex).mul(epochDuration).add(sessionProgress);
const eraProgress = currentIndex.sub(activeEraStartSessionIndex).mul(epochDuration).add(sessionProgress);
return {
activeEra,
activeEraStart,
currentEra,
currentIndex,
eraLength: createType(api.registry, 'BlockNumber', sessionsPerEra.mul(epochDuration)),
@@ -34,46 +37,76 @@ function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, ses
};
}
function infoLatestAura (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
function queryAura (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
return api.derive.session.indexes().pipe(
map((indexes): DerivedSessionInfo =>
createDerivedLatest(api, [
[false, createType(api.registry, 'u64', 1), api.consts.staking?.sessionsPerEra || createType(api.registry, 'SessionIndex', 1)],
createDerived(api, [
[
false,
createType(api.registry, 'u64', 1),
api.consts.staking?.sessionsPerEra || createType(api.registry, 'SessionIndex', 1)
],
indexes,
[createType(api.registry, 'u64', 1), createType(api.registry, 'u64', 1), createType(api.registry, 'u64', 1), createType(api.registry, 'SessionIndex', 1)]
[
createType(api.registry, 'u64', 1),
createType(api.registry, 'u64', 1),
createType(api.registry, 'u64', 1),
createType(api.registry, 'SessionIndex', 1)
]
])
)
);
}
function infoLatestBabe (api: ApiInterfaceRx): Observable<DerivedSessionInfo> {
function queryBabe (api: ApiInterfaceRx): Observable<[DeriveSessionIndexes, ResultSlotsFlat]> {
return api.derive.session.indexes().pipe(
switchMap((indexes): Observable<[DeriveSessionIndexes, ResultSlots]> =>
combineLatest([
of(indexes),
api.queryMulti<ResultSlots>([
api.query.babe.currentSlot,
api.query.babe.epochIndex,
api.query.babe.genesisSlot,
[api.query.staking.erasStartSessionIndex, indexes.activeEra]
])
])
),
map(([indexes, [currentSlot, epochIndex, genesisSlot, optStartIndex]]): [DeriveSessionIndexes, ResultSlotsFlat] => [
indexes, [currentSlot, epochIndex, genesisSlot, optStartIndex.unwrapOr(createType(api.registry, 'SessionIndex', 1))]
])
);
}
function queryBabeNoHistory (api: ApiInterfaceRx): Observable<[DeriveSessionIndexes, ResultSlotsFlat]> {
return combineLatest([
api.derive.session.indexes(),
api.queryMulti<ResultSlots>([
api.queryMulti<ResultSlotsFlat>([
api.query.babe.currentSlot,
api.query.babe.epochIndex,
api.query.babe.genesisSlot,
api.query.staking.currentEraStartSessionIndex
])
]).pipe(
map(([indexes, slots]: [DeriveSessionIndexes, ResultSlots]): DerivedSessionInfo =>
createDerivedLatest(api, [
[true, api.consts.babe.epochDuration, api.consts.staking.sessionsPerEra],
indexes,
slots
])
)
);
]);
}
/**
* @description Retrieves all the session and era info and calculates specific values on it as the length of the session and eras
* @description Retrieves all the session and era query 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.babe
? infoLatestBabe // 2.x with Babe
: infoLatestAura; // 2.x with Aura (not all info there)
return memo((): Observable<DerivedSessionInfo> =>
query(api));
api.consts.babe
? (api.query.staking.erasStartSessionIndex
? queryBabe(api) // 2.x with Babe
: queryBabeNoHistory(api)
).pipe(
map(([indexes, slots]: [DeriveSessionIndexes, ResultSlotsFlat]): DerivedSessionInfo =>
createDerived(api, [
[true, api.consts.babe.epochDuration, api.consts.staking.sessionsPerEra],
indexes,
slots
])
)
)
: queryAura(api)
);
}
@@ -14,16 +14,17 @@ import { memo } from '../util';
export function electedInfo (api: ApiInterfaceRx): () => Observable<DerivedStakingElected> {
return memo((): Observable<DerivedStakingElected> =>
api.derive.staking.validators().pipe(
switchMap(({ currentElected }): Observable<[AccountId[], DerivedStakingQuery[]]> =>
switchMap(({ nextElected }): Observable<[AccountId[], DerivedStakingQuery[]]> =>
combineLatest([
of(currentElected),
combineLatest(currentElected.map((accountId): Observable<DerivedStakingQuery> =>
of(nextElected),
combineLatest(nextElected.map((accountId): Observable<DerivedStakingQuery> =>
api.derive.staking.query(accountId)
))
])
),
map(([currentElected, info]): DerivedStakingElected => ({
currentElected, info
map(([nextElected, info]): DerivedStakingElected => ({
info,
nextElected
}))
)
);
-1
View File
@@ -7,5 +7,4 @@ export * from './controllers';
export * from './electedInfo';
export * from './overview';
export * from './query';
export * from './recentlyOffline';
export * from './validators';
@@ -1,47 +0,0 @@
// 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 { DerivedStakingStash } from '../types';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Option, Vec } from '@polkadot/types';
import { memo } from '../util';
type Result = [Option<AccountId>, [Vec<AccountId>], RewardDestination, Exposure, ValidatorPrefs, Option<Keys>?];
type ResultV2 = [Option<AccountId>, ITuple<[Vec<AccountId>]>, RewardDestination, Exposure, ValidatorPrefs, Option<Keys>];
function parse (stashId: AccountId, [_controllerId, [nominators], rewardDestination, stakers, validatorPrefs, _nextKeys]: Result): DerivedStakingStash {
return {
controllerId: _controllerId.unwrapOr(undefined),
nextKeys: _nextKeys?.unwrapOr(undefined),
nominators,
rewardDestination,
stakers,
stashId,
validatorPrefs
};
}
function query (api: ApiInterfaceRx, stashId: AccountId): Observable<Result> {
return api.queryMulti<ResultV2>([
[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]]
]);
}
export function infoStash (api: ApiInterfaceRx): (stashId: AccountId) => Observable<DerivedStakingStash> {
return memo((stashId: AccountId): Observable<DerivedStakingStash> =>
query(api, stashId).pipe(
map((result): DerivedStakingStash => parse(stashId, result))
));
}
+24 -6
View File
@@ -2,15 +2,31 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { EraPoints } from '@polkadot/types/interfaces';
import { AccountId, EraIndex, EraPoints, EraRewardPoints, RewardPoint } from '@polkadot/types/interfaces';
import { ApiInterfaceRx } from '@polkadot/api/types';
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';
function retrievePointsPrev (api: ApiInterfaceRx, activeEra: EraIndex, currentElected: AccountId[]): Observable<EraRewardPoints> {
return api.query.staking.currentEraPointsEarned<EraPoints>(activeEra).pipe(
map(({ individual, total }): EraRewardPoints =>
createType(api.registry, 'EraRewardPoints', {
total,
individual: new Map<AccountId, RewardPoint>(
individual
.map((points): RewardPoint => createType(api.registry, 'RewardPoint', points))
.map((points, index): [AccountId, RewardPoint] => [currentElected[index], points])
)
})
)
);
}
/**
* @description Retrieve the staking overview, including elected and points earned
*/
@@ -20,14 +36,16 @@ export function overview (api: ApiInterfaceRx): () => Observable<DerivedStakingO
api.derive.session.indexes(),
api.derive.staking.validators()
]).pipe(
switchMap(([{ currentEra, currentIndex, validatorCount }, { currentElected, validators }]) =>
switchMap(([indexes, { nextElected, validators }]) =>
combineLatest([
of({ currentElected, currentEra, currentIndex, validators, validatorCount }),
api.query.staking.currentEraPointsEarned<EraPoints>(currentEra)
of({ ...indexes, nextElected, validators }),
api.query.staking.erasRewardPoints
? api.query.staking.erasRewardPoints<EraRewardPoints>(indexes.activeEra)
: retrievePointsPrev(api, indexes.activeEra, nextElected)
])
),
map(([{ currentElected, currentEra, currentIndex, validators, validatorCount }, eraPoints]): DerivedStakingOverview => ({
currentElected, currentEra, currentIndex, eraPoints, validators, validatorCount
map(([info, eraPoints]): DerivedStakingOverview => ({
...info, eraPoints
}))
));
}
+54 -33
View File
@@ -3,7 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, Exposure, Keys, Nominations, RewardDestination, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
import { AccountId, Exposure, Keys, Nominations, RewardDestination, ValidatorPrefs } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DerivedStakingQuery } from '../types';
@@ -13,7 +13,7 @@ import { createType, Option, Vec } from '@polkadot/types';
import { memo } from '../util';
type MultiResultV2 = [Option<AccountId>, Option<ITuple<[Nominations]>>, RewardDestination, Exposure, [ValidatorPrefs], Option<Keys>, Option<StakingLedger>];
type MultiResult = [Option<AccountId>, Option<ITuple<[Nominations]>>, RewardDestination, ITuple<[ValidatorPrefs]>, Option<Keys>, Exposure];
function unwrapSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
const sessionIds = (queuedKeys.find(([currentId]): boolean =>
@@ -27,20 +27,52 @@ function unwrapSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][],
};
}
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]]
]) as Observable<MultiResultV2>
function retrievePrev (api: ApiInterfaceRx, stashId: AccountId): Observable<MultiResult> {
return api.queryMulti<MultiResult>([
[api.query.staking.bonded, stashId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.validators, stashId],
[api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]],
[api.query.staking.stakers, stashId]
]);
}
function retrieveCurr (api: ApiInterfaceRx, stashId: AccountId): Observable<MultiResult> {
return api.derive.session.indexes().pipe(
switchMap(({ activeEra }) =>
api.queryMulti<MultiResult>([
[api.query.staking.bonded, stashId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.validators, stashId],
[api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]],
[api.query.staking.erasStakers, [activeEra, stashId]]
])
)
);
}
function retrieveController (api: ApiInterfaceRx, stashId: AccountId, [queuedKeys, [controllerIdOpt, nominatorsOpt, rewardDestination, [validatorPrefs], nextKeys, exposure]]: [Vec<ITuple<[AccountId, Keys]>>, MultiResult]): Observable<DerivedStakingQuery> {
const controllerId = controllerIdOpt.unwrapOr(null);
return controllerId
? api.query.staking.ledger(controllerId).pipe(
map((stakingLedgerOpt): DerivedStakingQuery => ({
accountId: stashId,
controllerId,
exposure,
nominators: nominatorsOpt.unwrapOr([{ targets: [] }])[0].targets,
rewardDestination,
stakingLedger: stakingLedgerOpt.unwrapOr(undefined),
stashId,
validatorPrefs,
...unwrapSessionIds(stashId, queuedKeys, nextKeys)
}))
)
: of({ accountId: stashId, nextSessionIds: [], sessionIds: [] });
}
/**
* @description From a stash, retrieve the controllerId and all relevant details
*/
@@ -48,26 +80,15 @@ export function query (api: ApiInterfaceRx): (accountId: Uint8Array | string) =>
return memo((accountId: Uint8Array | string): Observable<DerivedStakingQuery> => {
const stashId = 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: [] });
})
return combineLatest([
api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>(),
api.query.staking.erasStakers
? retrieveCurr(api, stashId)
: retrievePrev(api, stashId)
]).pipe(
switchMap((result): Observable<DerivedStakingQuery> =>
retrieveController(api, stashId, result)
)
);
});
}
@@ -1,49 +0,0 @@
// 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, 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)
));
}
@@ -22,12 +22,16 @@ export function validators (api: ApiInterfaceRx): () => Observable<DeriveStaking
api.query.session
? api.query.session.validators()
: of([]),
api.query.staking
? api.query.staking.currentElected()
// FIXME need a replacement for currentElected in new
api.query.staking?.currentElected
? api.query.staking.erasStakers
? of(null)
: api.query.staking.currentElected()
: of([])
]).pipe(
map(([validators, currentElected]): DeriveStakingValidators => ({
currentElected, validators
map(([validators, nextElected]): DeriveStakingValidators => ({
nextElected: nextElected || validators,
validators
}))
));
}
+18 -6
View File
@@ -3,7 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, Header } from '@polkadot/types/interfaces';
import { AnyJsonObject, Constructor, Registry } from '@polkadot/types/types';
import { AnyJson, Constructor, Registry } from '@polkadot/types/types';
import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions';
import { Struct } from '@polkadot/types';
@@ -17,12 +17,12 @@ const _Header: Constructor<Header> = Struct.with(runtimeTypes.types.Header as an
* A [[Block]] header with an additional `author` field that indicates the block author
*/
export default class HeaderExtended extends _Header {
private _author?: AccountId;
readonly #author?: AccountId;
constructor (registry: Registry, header?: Header, sessionValidators?: AccountId[]) {
super(registry, header);
this._author = this.extractAuthor(sessionValidators);
this.#author = this.extractAuthor(sessionValidators);
}
private extractAuthor (sessionValidators: AccountId[] = []): AccountId | undefined {
@@ -51,15 +51,27 @@ export default class HeaderExtended extends _Header {
* @description Convenience method, returns the author for the block
*/
public get author (): AccountId | undefined {
return this._author;
return this.#author;
}
/**
* @description Creates a human-friendly JSON representation
*/
public toHuman (isExtended?: boolean): AnyJson {
return {
...super.toHuman(isExtended) as { [index: string]: AnyJson },
author: this.author
? this.author.toHuman()
: undefined
};
}
/**
* @description Creates the JSON representation
*/
public toJSON (): AnyJsonObject {
public toJSON (): AnyJson {
return {
...super.toJSON() as AnyJsonObject,
...super.toJSON() as { [index: string]: AnyJson },
author: this.author
? this.author.toJSON()
: undefined
@@ -3,11 +3,11 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ReferendumIndex, ReferendumInfo } from '@polkadot/types/interfaces/democracy';
import { AnyJsonObject, Constructor, Registry } from '@polkadot/types/types';
import { AnyJson, Constructor, Registry } from '@polkadot/types/types';
import BN from 'bn.js';
import democracyTypes from '@polkadot/types/interfaces/democracy/definitions';
import { Struct, createType } from '@polkadot/types';
import { Struct } from '@polkadot/types';
// We can ignore the properties, added via Struct.with
const _ReferendumInfo: Constructor<ReferendumInfo> = Struct.with(democracyTypes.types.ReferendumInfo as any) as any;
@@ -18,29 +18,39 @@ const _ReferendumInfo: Constructor<ReferendumInfo> = Struct.with(democracyTypes.
* A [[ReferendumInfo]] with an additional `index` field
*/
export default class ReferendumInfoExtended extends _ReferendumInfo {
private _index: ReferendumIndex;
readonly #index: ReferendumIndex;
constructor (registry: Registry, value: ReferendumInfo | ReferendumInfoExtended, index?: BN | number) {
super(registry, value);
this._index = value instanceof ReferendumInfoExtended
this.#index = value instanceof ReferendumInfoExtended
? value.index
: createType(registry, 'ReferendumIndex', index);
: registry.createType('ReferendumIndex', index);
}
/**
* @description Convenience getter, returns the referendumIndex
*/
public get index (): ReferendumIndex {
return this._index;
return this.#index;
}
/**
* @description Creates a human-friendly JSON representation
*/
public toHuman (isExtended?: boolean): AnyJson {
return {
...super.toHuman(isExtended) as { [index: string]: AnyJson },
index: this.index.toHuman(isExtended)
};
}
/**
* @description Creates the JSON representation
*/
public toJSON (): AnyJsonObject {
public toJSON (): AnyJson {
return {
...super.toJSON() as AnyJsonObject,
...super.toJSON() as { [index: string]: AnyJson },
index: this.index.toJSON()
};
}
+51 -12
View File
@@ -2,10 +2,10 @@
// 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, Balance, BalanceLock, BalanceOf, Bid, BidKind, BlockNumber, EraIndex, EraPoints, Exposure, Hash, Index, Keys, Proposal, PropIndex, ProposalIndex, ReferendumInfo, RegistrationJudgement, RewardDestination, SessionIndex, SetIndex, SocietyVote, StakingLedger, StrikeCount, TreasuryProposal, ValidatorPrefs, Vote, Votes, VoteIndex, VouchingStatus } from '@polkadot/types/interfaces';
import { AccountId, AccountIndex, Balance, BalanceLock, BalanceLockTo212, BalanceOf, Bid, BidKind, BlockNumber, CollatorId, EraIndex, EraRewardPoints, Exposure, Hash, Index, Keys, MomentOf, ParaId, ParaInfo, Proposal, PropIndex, ProposalIndex, ReferendumInfo, RegistrationJudgement, RewardDestination, SessionIndex, SetIndex, SocietyVote, StakingLedger, StrikeCount, TreasuryProposal, UpwardMessage, ValidatorPrefs, Vote, Votes, VoteIndex, VouchingStatus } from '@polkadot/types/interfaces';
import BN from 'bn.js';
import { u32, Vec } from '@polkadot/types';
import { Bytes, Option, u32, Vec } from '@polkadot/types';
export type AccountIndexes = Record<string, AccountIndex>;
@@ -15,6 +15,7 @@ export interface DeriveAccountRegistration {
email?: string;
image?: string;
legal?: string;
other?: Record<string, string>;
parent?: AccountId;
pgp?: string;
riot?: string;
@@ -30,26 +31,31 @@ export interface DeriveAccountInfo {
nickname?: string;
}
export interface DerivedBalances {
export interface DerivedBalancesAccount {
accountId: AccountId;
accountNonce: Index;
freeBalance: Balance;
frozenFee: Balance;
frozenMisc: Balance;
reservedBalance: Balance;
votingBalance: Balance;
}
export interface DerivedBalancesAll extends DerivedBalancesAccount {
isVesting: boolean;
lockedBalance: Balance;
lockedBreakdown: BalanceLock[];
lockedBreakdown: (BalanceLock | BalanceLockTo212)[];
availableBalance: Balance;
reservedBalance: Balance;
votingBalance: Balance;
vestedBalance: Balance;
vestingTotal: Balance;
}
export type DerivedBalancesMap = Record<string, DerivedBalances>;
export type DerivedBalancesMap = Record<string, DerivedBalancesAll>;
export interface DerivedContractFees {
callBaseFee: BN;
contractFee: BN;
createBaseFee: BN;
creationFee: BN;
rentByteFee: BN;
rentDepositOffset: BN;
@@ -102,6 +108,36 @@ export interface RecentlyOffline {
count: BN;
}
export interface DeriveParachainActive {
collatorId: CollatorId;
isRetriable: boolean;
retries: number;
}
export interface DeriveParachainInfo extends ParaInfo {
id: ParaId;
icon?: string;
name?: string;
owner?: string;
}
export interface DeriveParachain {
didUpdate: boolean;
pendingSwapId: ParaId | null;
id: ParaId;
info: DeriveParachainInfo | null;
relayDispatchQueueSize?: number;
watermark: BlockNumber | null;
}
export interface DeriveParachainFull extends DeriveParachain {
active: DeriveParachainActive | null;
heads: Bytes | null;
relayDispatchQueue: UpwardMessage[];
retryCollators: (CollatorId | null)[];
selectedCollators: (CollatorId | null)[];
}
export interface DeriveProposalPreImage {
at: BlockNumber;
balance: Balance;
@@ -135,6 +171,8 @@ export interface DerivedReferendumVote {
}
export interface DeriveSessionIndexes {
activeEra: EraIndex;
activeEraStart: Option<MomentOf>;
currentEra: EraIndex;
currentIndex: SessionIndex;
validatorCount: u32;
@@ -176,21 +214,22 @@ export interface DeriveSocietyMember {
}
export interface DerivedStakingElected {
currentElected: AccountId[];
nextElected: AccountId[];
info: DerivedStakingQuery[];
}
export interface DeriveStakingValidators {
currentElected: AccountId[];
nextElected: AccountId[];
validators: AccountId[];
}
export interface DerivedStakingStash {
controllerId?: AccountId;
exposure?: Exposure;
nominators?: AccountId[];
nominateAt?: EraIndex;
rewardDestination?: RewardDestination;
nextKeys?: Keys;
stakers?: Exposure;
stashId?: AccountId;
validatorPrefs?: ValidatorPrefs;
}
@@ -208,8 +247,8 @@ export interface DerivedStakingAccount extends DerivedStakingQuery {
}
export interface DerivedStakingOverview extends DeriveSessionIndexes {
currentElected: AccountId[];
eraPoints: EraPoints;
eraPoints: EraRewardPoints;
nextElected: AccountId[];
validators: AccountId[];
}
@@ -4,7 +4,7 @@
import { ApprovalFlag } from '@polkadot/types/interfaces';
import { createType, TypeRegistry } from '@polkadot/types';
import { TypeRegistry } from '@polkadot/types';
import { approvalFlagsToBools } from './approvalFlagsToBools';
@@ -20,7 +20,7 @@ describe('approvalFlagsToBools', (): void => {
it('translates a single input', (): void => {
expect(
approvalFlagsToBools([
createType(registry, 'ApprovalFlag', 0b1010)
registry.createType('ApprovalFlag', 0b1010)
])
).toEqual([false, true, false, true]);
});
@@ -28,8 +28,8 @@ describe('approvalFlagsToBools', (): void => {
it('translates multiple inputs', (): void => {
expect(
approvalFlagsToBools([
createType(registry, 'ApprovalFlag', 0b0000),
createType(registry, 'ApprovalFlag', 0b1100)
registry.createType('ApprovalFlag', 0b0000),
registry.createType('ApprovalFlag', 0b1100)
])
).toEqual([false, false, false, true, true]);
});
+14 -13
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api",
"version": "1.0.1",
"version": "1.4.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
"keywords": [
@@ -25,20 +25,21 @@
"url": "https://github.com/polkadot-js/api/issues"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"browser": {
"../package.json": "./package.json"
},
"dependencies": {
"@babel/runtime": "^7.8.3",
"@polkadot/api-derive": "^1.0.1",
"@polkadot/keyring": "^2.0.1",
"@polkadot/metadata": "^1.0.1",
"@polkadot/rpc-core": "^1.0.1",
"@polkadot/rpc-provider": "^1.0.1",
"@polkadot/types": "^1.0.1",
"@polkadot/util-crypto": "^2.0.1"
"@babel/runtime": "^7.8.4",
"@polkadot/api-derive": "1.4.1",
"@polkadot/keyring": "^2.5.1",
"@polkadot/metadata": "1.4.1",
"@polkadot/rpc-core": "1.4.1",
"@polkadot/rpc-provider": "1.4.1",
"@polkadot/types": "1.4.1",
"@polkadot/util": "^2.5.1",
"@polkadot/util-crypto": "^2.5.1",
"bn.js": "^5.1.1",
"eventemitter3": "^4.0.0",
"rxjs": "^6.5.4"
},
"devDependencies": {
"@polkadot/keyring": "^2.0.1"
"@polkadot/keyring": "^2.5.1"
}
}
+269
View File
@@ -0,0 +1,269 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { Codec } from '@polkadot/types/types';
import { Bytes, u32, u64 } from '@polkadot/types/primitive';
import { Gas } from '@polkadot/types/interfaces/contracts';
import { Balance, BalanceOf, BlockNumber, Moment, Percent, Permill } from '@polkadot/types/interfaces/runtime';
import { SessionIndex } from '@polkadot/types/interfaces/session';
import { EraIndex } from '@polkadot/types/interfaces/staking';
declare module '@polkadot/metadata/Decorated/consts/types' {
export interface Constants {
[index: string]: ModuleConstants;
babe: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The number of **slots** that an epoch takes. We couple sessions to
* epochs, i.e. we start a new session once the new epoch begins.
**/
epochDuration: AugmentedConst<u64>;
/**
* The expected average block time at which BABE should be creating
* blocks. Since BABE is probabilistic it is not trivial to figure out
* what the expected average block time should be based on the slot
* duration and the security parameter `c` (where `1 - c` represents
* the probability of a slot being empty).
**/
expectedBlockTime: AugmentedConst<Moment>;
};
timestamp: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The minimum period between blocks. Beware that this is different to the *expected* period
* that the block production apparatus provides. Your chosen consensus system will generally
* work with this to determine a sensible block time. e.g. For Aura, it will be double this
* period on default settings.
**/
minimumPeriod: AugmentedConst<Moment>;
};
balances: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The minimum amount required to keep an account open.
**/
existentialDeposit: AugmentedConst<Balance>;
};
transactionPayment: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The fee to be paid for making a transaction; the base.
**/
transactionBaseFee: AugmentedConst<BalanceOf>;
/**
* The fee to be paid for making a transaction; the per-byte portion.
**/
transactionByteFee: AugmentedConst<BalanceOf>;
};
staking: {
[index: string]: AugmentedConst<object & Codec>;
/**
* Number of sessions per era.
**/
sessionsPerEra: AugmentedConst<SessionIndex>;
/**
* Number of eras that staked funds must remain bonded for.
**/
bondingDuration: AugmentedConst<EraIndex>;
};
session: {
[index: string]: AugmentedConst<object & Codec>;
/**
* Used as first key for `NextKeys` and `KeyOwner` to put all the data into the same branch
* of the trie.
**/
dedupKeyPrefix: AugmentedConst<Bytes>;
};
democracy: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The minimum period of locking and the period between a proposal being approved and enacted.
* It should generally be a little more than the unstake period to ensure that
* voting stakers have an opportunity to remove themselves from the system in the case where
* they are on the losing side of a vote.
**/
enactmentPeriod: AugmentedConst<BlockNumber>;
/**
* How often (in blocks) new public referenda are launched.
**/
launchPeriod: AugmentedConst<BlockNumber>;
/**
* How often (in blocks) to check for new votes.
**/
votingPeriod: AugmentedConst<BlockNumber>;
/**
* The minimum amount to be used as a deposit for a public referendum proposal.
**/
minimumDeposit: AugmentedConst<BalanceOf>;
/**
* Minimum voting period allowed for an emergency referendum.
**/
emergencyVotingPeriod: AugmentedConst<BlockNumber>;
/**
* Period in blocks where an external proposal may not be re-submitted after being vetoed.
**/
cooloffPeriod: AugmentedConst<BlockNumber>;
/**
* The amount of balance that must be deposited per byte of preimage stored.
**/
preimageByteDeposit: AugmentedConst<BalanceOf>;
};
elections: {
[index: string]: AugmentedConst<object & Codec>;
candidacyBond: AugmentedConst<BalanceOf>;
votingBond: AugmentedConst<BalanceOf>;
desiredMembers: AugmentedConst<u32>;
desiredRunnersUp: AugmentedConst<u32>;
termDuration: AugmentedConst<BlockNumber>;
};
finalityTracker: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The number of recent samples to keep from this chain. Default is 101.
**/
windowSize: AugmentedConst<BlockNumber>;
/**
* The delay after which point things become suspicious. Default is 1000.
**/
reportLatency: AugmentedConst<BlockNumber>;
};
treasury: {
[index: string]: AugmentedConst<object & Codec>;
/**
* Fraction of a proposal's value that should be bonded in order to place the proposal.
* An accepted proposal gets these back. A rejected proposal does not.
**/
proposalBond: AugmentedConst<Permill>;
/**
* Minimum amount of funds that should be placed in a deposit for making a proposal.
**/
proposalBondMinimum: AugmentedConst<BalanceOf>;
/**
* Period between successive spends.
**/
spendPeriod: AugmentedConst<BlockNumber>;
/**
* Percentage of spare funds (if any) that are burnt per spend period.
**/
burn: AugmentedConst<Permill>;
/**
* The period for which a tip remains open after is has achieved threshold tippers.
**/
tipCountdown: AugmentedConst<BlockNumber>;
/**
* The amount of the final tip which goes to the original reporter of the tip.
**/
tipFindersFee: AugmentedConst<Percent>;
/**
* The amount held on deposit for placing a tip report.
**/
tipReportDepositBase: AugmentedConst<BalanceOf>;
/**
* The amount held on deposit per byte within the tip report reason.
**/
tipReportDepositPerByte: AugmentedConst<BalanceOf>;
};
contracts: {
[index: string]: AugmentedConst<object & Codec>;
/**
* Number of block delay an extrinsic claim surcharge has.
* When claim surcharge is called by an extrinsic the rent is checked
* for current_block - delay
**/
signedClaimHandicap: AugmentedConst<BlockNumber>;
/**
* The minimum amount required to generate a tombstone.
**/
tombstoneDeposit: AugmentedConst<BalanceOf>;
/**
* Size of a contract at the time of instantiaion. This is a simple way to ensure that
* empty contracts eventually gets deleted.
**/
storageSizeOffset: AugmentedConst<u32>;
/**
* Price of a byte of storage per one block interval. Should be greater than 0.
**/
rentByteFee: AugmentedConst<BalanceOf>;
/**
* The amount of funds a contract should deposit in order to offset
* the cost of one byte.
* Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day,
* then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent.
* But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000,
* then it would pay 500 BU/day.
**/
rentDepositOffset: AugmentedConst<BalanceOf>;
/**
* Reward that is received by the party whose touch has led
* to removal of a contract.
**/
surchargeReward: AugmentedConst<BalanceOf>;
/**
* The fee to be paid for making a transaction; the base.
**/
transactionBaseFee: AugmentedConst<BalanceOf>;
/**
* The fee to be paid for making a transaction; the per-byte portion.
**/
transactionByteFee: AugmentedConst<BalanceOf>;
/**
* The fee required to instantiate a contract instance. A reasonable default value
* is 21.
**/
contractFee: AugmentedConst<BalanceOf>;
/**
* The base fee charged for calling into a contract. A reasonable default
* value is 135.
**/
callBaseFee: AugmentedConst<Gas>;
/**
* The base fee charged for instantiating a contract. A reasonable default value
* is 175.
**/
instantiateBaseFee: AugmentedConst<Gas>;
/**
* The maximum nesting level of a call/instantiate stack. A reasonable default
* value is 100.
**/
maxDepth: AugmentedConst<u32>;
/**
* The maximum size of a storage value in bytes. A reasonable default is 16 KiB.
**/
maxValueSize: AugmentedConst<u32>;
/**
* The maximum amount of gas that could be expended per block. A reasonable
* default value is 10_000_000.
**/
blockGasLimit: AugmentedConst<Gas>;
};
society: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The minimum amount of a deposit required for a bid to be made.
**/
candidateDeposit: AugmentedConst<BalanceOf>;
/**
* The amount of the unpaid reward that gets deducted in the case that either a skeptic
* doesn't vote or someone votes in the wrong way.
**/
wrongSideDeduction: AugmentedConst<BalanceOf>;
/**
* The number of times a member may vote the wrong way (or not at all, when they are a skeptic)
* before they become suspended.
**/
maxStrikes: AugmentedConst<u32>;
/**
* The amount of incentive paid within each period. Doesn't include VoterTip.
**/
periodSpend: AugmentedConst<BalanceOf>;
/**
* The number of blocks between candidate/membership rotation periods.
**/
rotationPeriod: AugmentedConst<BlockNumber>;
/**
* The number of blocks between membership challenges.
**/
challengePeriod: AugmentedConst<BlockNumber>;
};
}
}
+8
View File
@@ -0,0 +1,8 @@
// 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 './consts';
import './query';
import './rpc';
import './tx';
+802
View File
@@ -0,0 +1,802 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { AnyNumber, ITuple } from '@polkadot/types/types';
import { Option, U8aFixed, Vec } from '@polkadot/types/codec';
import { Bytes, Data, bool, u32, u64 } from '@polkadot/types/primitive';
import { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
import { BabeAuthorityWeight, MaybeVrf } from '@polkadot/types/interfaces/babe';
import { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
import { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { CodeHash, ContractInfo, Gas, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
import { Conviction, PropIndex, Proposal, ReferendumIndex, ReferendumInfo } from '@polkadot/types/interfaces/democracy';
import { Vote, VoteThreshold } from '@polkadot/types/interfaces/elections';
import { AuthorityList, SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity';
import { AuthIndex } from '@polkadot/types/interfaces/imOnline';
import { Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, Hash, Index, KeyTypeId, Moment, Perbill, ValidatorId, Weight } from '@polkadot/types/interfaces/runtime';
import { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import { EraIndex, EraPoints, Exposure, Forcing, MomentOf, Nominations, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import { DigestOf, EventIndex, EventRecord } from '@polkadot/types/interfaces/system';
import { OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import { Multiplier } from '@polkadot/types/interfaces/txpayment';
import { Multisig } from '@polkadot/types/interfaces/utility';
import { VestingInfo } from '@polkadot/types/interfaces/vesting';
import { Observable } from 'rxjs';
import { ApiTypes } from '@polkadot/api/types';
declare module '@polkadot/api/types/storage' {
export interface AugmentedQueries<ApiType> {
system: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The full account information for a particular account ID.
**/
account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[Index, AccountData]>>> & QueryableStorageEntry<ApiType>;
/**
* Total extrinsics count for the current block.
**/
extrinsicCount: AugmentedQuery<ApiType, () => Observable<Option<u32>>> & QueryableStorageEntry<ApiType>;
/**
* Total weight for all extrinsics put together, for the current block.
**/
allExtrinsicsWeight: AugmentedQuery<ApiType, () => Observable<Option<Weight>>> & QueryableStorageEntry<ApiType>;
/**
* Total length (in bytes) for all extrinsics put together, for the current block.
**/
allExtrinsicsLen: AugmentedQuery<ApiType, () => Observable<Option<u32>>> & QueryableStorageEntry<ApiType>;
/**
* Map of block numbers to block hashes.
**/
blockHash: AugmentedQuery<ApiType, (arg: BlockNumber | AnyNumber | Uint8Array) => Observable<Hash>> & QueryableStorageEntry<ApiType>;
/**
* Extrinsics data for the current block (maps an extrinsic's index to its data).
**/
extrinsicData: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Bytes>> & QueryableStorageEntry<ApiType>;
/**
* The current block number being processed. Set by `execute_block`.
**/
number: AugmentedQuery<ApiType, () => Observable<BlockNumber>> & QueryableStorageEntry<ApiType>;
/**
* Hash of the previous block.
**/
parentHash: AugmentedQuery<ApiType, () => Observable<Hash>> & QueryableStorageEntry<ApiType>;
/**
* Extrinsics root of the current block, also part of the block header.
**/
extrinsicsRoot: AugmentedQuery<ApiType, () => Observable<Hash>> & QueryableStorageEntry<ApiType>;
/**
* Digest of the current block, also part of the block header.
**/
digest: AugmentedQuery<ApiType, () => Observable<DigestOf>> & QueryableStorageEntry<ApiType>;
/**
* Events deposited for the current block.
**/
events: AugmentedQuery<ApiType, () => Observable<Vec<EventRecord>>> & QueryableStorageEntry<ApiType>;
/**
* The number of events in the `Events<T>` list.
**/
eventCount: AugmentedQuery<ApiType, () => Observable<EventIndex>> & QueryableStorageEntry<ApiType>;
/**
* Mapping between a topic (represented by T::Hash) and a vector of indexes
* of events in the `<Events<T>>` list.
* All topic vectors have deterministic storage locations depending on the topic. This
* allows light-clients to leverage the changes trie storage tracking mechanism and
* in case of changes fetch the list of events of interest.
* The value has the type `(T::BlockNumber, EventIndex)` because if we used only just
* the `EventIndex` then in case if the topic has the same contents on the next block
* no notification will be triggered thus the event might be lost.
**/
eventTopics: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Vec<ITuple<[BlockNumber, EventIndex]>>>> & QueryableStorageEntry<ApiType>;
};
utility: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The set of open multisig operations.
**/
multisigs: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: U8aFixed | string | Uint8Array) => Observable<Option<Multisig>>> & QueryableStorageEntry<ApiType>;
};
babe: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* Current epoch index.
**/
epochIndex: AugmentedQuery<ApiType, () => Observable<u64>> & QueryableStorageEntry<ApiType>;
/**
* Current epoch authorities.
**/
authorities: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AuthorityId, BabeAuthorityWeight]>>>> & QueryableStorageEntry<ApiType>;
/**
* The slot at which the first epoch actually started. This is 0
* until the first block of the chain.
**/
genesisSlot: AugmentedQuery<ApiType, () => Observable<u64>> & QueryableStorageEntry<ApiType>;
/**
* Current slot number.
**/
currentSlot: AugmentedQuery<ApiType, () => Observable<u64>> & QueryableStorageEntry<ApiType>;
/**
* The epoch randomness for the *current* epoch.
* # Security
* This MUST NOT be used for gambling, as it can be influenced by a
* malicious validator in the short term. It MAY be used in many
* cryptographic protocols, however, so long as one remembers that this
* (like everything else on-chain) it is public. For example, it can be
* used where a number is needed that cannot have been chosen by an
* adversary, for purposes such as public-coin zero-knowledge proofs.
**/
randomness: AugmentedQuery<ApiType, () => Observable<U8aFixed>> & QueryableStorageEntry<ApiType>;
/**
* Next epoch randomness.
**/
nextRandomness: AugmentedQuery<ApiType, () => Observable<U8aFixed>> & QueryableStorageEntry<ApiType>;
/**
* Randomness under construction.
* We make a tradeoff between storage accesses and list length.
* We store the under-construction randomness in segments of up to
* `UNDER_CONSTRUCTION_SEGMENT_LENGTH`.
* Once a segment reaches this length, we begin the next one.
* We reset all segments and return to `0` at the beginning of every
* epoch.
**/
segmentIndex: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
underConstruction: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<U8aFixed>>> & QueryableStorageEntry<ApiType>;
/**
* Temporary value (cleared at block finalization) which is `Some`
* if per-block initialization has already been called for current block.
**/
initialized: AugmentedQuery<ApiType, () => Observable<Option<MaybeVrf>>> & QueryableStorageEntry<ApiType>;
};
timestamp: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* Current time for the current block.
**/
now: AugmentedQuery<ApiType, () => Observable<Moment>> & QueryableStorageEntry<ApiType>;
/**
* Did the timestamp get updated in this block?
**/
didUpdate: AugmentedQuery<ApiType, () => Observable<bool>> & QueryableStorageEntry<ApiType>;
};
authorship: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* Uncles
**/
uncles: AugmentedQuery<ApiType, () => Observable<Vec<UncleEntryItem>>> & QueryableStorageEntry<ApiType>;
/**
* Author of current block.
**/
author: AugmentedQuery<ApiType, () => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* Whether uncles were already set in this block.
**/
didSetUncles: AugmentedQuery<ApiType, () => Observable<bool>> & QueryableStorageEntry<ApiType>;
};
indices: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The lookup from index to account.
**/
accounts: AugmentedQuery<ApiType, (arg: AccountIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
};
balances: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The total units issued in the system.
**/
totalIssuance: AugmentedQuery<ApiType, () => Observable<Balance>> & QueryableStorageEntry<ApiType>;
/**
* The balance of an account.
* NOTE: THIS MAY NEVER BE IN EXISTENCE AND YET HAVE A `total().is_zero()`. If the total
* is ever zero, then the entry *MUST* be removed.
* NOTE: This is only used in the case that this module is used to store balances.
**/
account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>> & QueryableStorageEntry<ApiType>;
/**
* Any liquidity locks on some account balances.
* NOTE: Should only be accessed when setting, changing and freeing a lock.
**/
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<BalanceLock>>> & QueryableStorageEntry<ApiType>;
/**
* True if network has been upgraded to this version.
* True for new networks.
**/
isUpgraded: AugmentedQuery<ApiType, () => Observable<bool>> & QueryableStorageEntry<ApiType>;
};
transactionPayment: {
[index: string]: QueryableStorageEntry<ApiType>;
nextFeeMultiplier: AugmentedQuery<ApiType, () => Observable<Multiplier>> & QueryableStorageEntry<ApiType>;
};
staking: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The ideal number of staking participants.
**/
validatorCount: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
/**
* Minimum number of staking participants before emergency conditions are imposed.
**/
minimumValidatorCount: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
/**
* Any validators that may never be slashed or forcibly kicked. It's a Vec since they're
* easy to initialize and the performance hit is minimal (we expect no more than four
* invulnerables) and restricted to testnets.
**/
invulnerables: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* Map from all locked "stash" accounts to the controller account.
**/
bonded: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* Map from all (unlocked) "controller" accounts to the info regarding the staking.
**/
ledger: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<StakingLedger>>> & QueryableStorageEntry<ApiType>;
/**
* Where the reward payment should be made. Keyed by stash.
**/
payee: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<RewardDestination>> & QueryableStorageEntry<ApiType>;
/**
* The map from (wannabe) validator stash key to the preferences of that validator.
**/
validators: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ValidatorPrefs>> & QueryableStorageEntry<ApiType>;
/**
* The map from nominator stash key to the set of stash keys of all validators to nominate.
* NOTE: is private so that we can ensure upgraded before all typical accesses.
* Direct storage APIs can still bypass this protection.
**/
nominators: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<Nominations>>> & QueryableStorageEntry<ApiType>;
/**
* Nominators for a particular account that is in action right now. You can't iterate
* through validators here, but you can find them in the Session module.
* This is keyed by the stash account.
**/
stakers: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Exposure>> & QueryableStorageEntry<ApiType>;
/**
* The currently elected validator set keyed by stash account ID.
**/
currentElected: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* The current era index.
**/
currentEra: AugmentedQuery<ApiType, () => Observable<EraIndex>> & QueryableStorageEntry<ApiType>;
/**
* The start of the current era.
**/
currentEraStart: AugmentedQuery<ApiType, () => Observable<MomentOf>> & QueryableStorageEntry<ApiType>;
/**
* The session index at which the current era started.
**/
currentEraStartSessionIndex: AugmentedQuery<ApiType, () => Observable<SessionIndex>> & QueryableStorageEntry<ApiType>;
/**
* Rewards for the current era. Using indices of current elected set.
**/
currentEraPointsEarned: AugmentedQuery<ApiType, () => Observable<EraPoints>> & QueryableStorageEntry<ApiType>;
/**
* The amount of balance actively at stake for each validator slot, currently.
* This is used to derive rewards and punishments.
**/
slotStake: AugmentedQuery<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/**
* True if the next session change will be a new era regardless of index.
**/
forceEra: AugmentedQuery<ApiType, () => Observable<Forcing>> & QueryableStorageEntry<ApiType>;
/**
* The percentage of the slash that is distributed to reporters.
* The rest of the slashed value is handled by the `Slash`.
**/
slashRewardFraction: AugmentedQuery<ApiType, () => Observable<Perbill>> & QueryableStorageEntry<ApiType>;
/**
* The amount of currency given to reporters of a slash event which was
* canceled by extraordinary circumstances (e.g. governance).
**/
canceledSlashPayout: AugmentedQuery<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/**
* All unapplied slashes that are queued for later.
**/
unappliedSlashes: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<Vec<UnappliedSlash>>> & QueryableStorageEntry<ApiType>;
/**
* A mapping from still-bonded eras to the first session index of that era.
**/
bondedEras: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[EraIndex, SessionIndex]>>>> & QueryableStorageEntry<ApiType>;
/**
* All slashing events on validators, mapped by era to the highest slash proportion
* and slash value of the era.
**/
validatorSlashInEra: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ITuple<[Perbill, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
/**
* All slashing events on nominators, mapped by era to the highest slash value of the era.
**/
nominatorSlashInEra: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<BalanceOf>>> & QueryableStorageEntry<ApiType>;
/**
* Slashing spans for stash accounts.
**/
slashingSpans: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<SlashingSpans>>> & QueryableStorageEntry<ApiType>;
/**
* Records information about the maximum slash of a stash within a slashing span,
* as well as how much reward has been paid out.
**/
spanSlash: AugmentedQuery<ApiType, (arg: ITuple<[AccountId, SpanIndex]> | [AccountId | string | Uint8Array, SpanIndex | AnyNumber | Uint8Array]) => Observable<SpanRecord>> & QueryableStorageEntry<ApiType>;
/**
* The earliest era for which we have a pending, unapplied slash.
**/
earliestUnappliedSlash: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>> & QueryableStorageEntry<ApiType>;
};
session: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The current set of validators.
**/
validators: AugmentedQuery<ApiType, () => Observable<Vec<ValidatorId>>> & QueryableStorageEntry<ApiType>;
/**
* Current index of the session.
**/
currentIndex: AugmentedQuery<ApiType, () => Observable<SessionIndex>> & QueryableStorageEntry<ApiType>;
/**
* True if the underlying economic identities or weighting behind the validators
* has changed in the queued validator set.
**/
queuedChanged: AugmentedQuery<ApiType, () => Observable<bool>> & QueryableStorageEntry<ApiType>;
/**
* The queued keys for the next session. When the next session begins, these keys
* will be used to determine the validator's session keys.
**/
queuedKeys: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[ValidatorId, Keys]>>>> & QueryableStorageEntry<ApiType>;
/**
* Indices of disabled validators.
* The set is cleared when `on_session_ending` returns a new set of identities.
**/
disabledValidators: AugmentedQuery<ApiType, () => Observable<Vec<u32>>> & QueryableStorageEntry<ApiType>;
/**
* The next session keys for a validator.
* The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of
* the trie. Having all data in the same branch should prevent slowing down other queries.
**/
nextKeys: AugmentedQueryDoubleMap<ApiType, (key1: Bytes | string | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<Option<Keys>>> & QueryableStorageEntry<ApiType>;
/**
* The owner of a key. The second key is the `KeyTypeId` + the encoded key.
* The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of
* the trie. Having all data in the same branch should prevent slowing down other queries.
**/
keyOwner: AugmentedQueryDoubleMap<ApiType, (key1: Bytes | string | Uint8Array, key2: ITuple<[KeyTypeId, Bytes]> | [KeyTypeId | AnyNumber | Uint8Array, Bytes | string | Uint8Array]) => Observable<Option<ValidatorId>>> & QueryableStorageEntry<ApiType>;
};
democracy: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The number of (public) proposals that have been made so far.
**/
publicPropCount: AugmentedQuery<ApiType, () => Observable<PropIndex>> & QueryableStorageEntry<ApiType>;
/**
* The public proposals. Unsorted. The second item is the proposal's hash.
**/
publicProps: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[PropIndex, Hash, AccountId]>>>> & QueryableStorageEntry<ApiType>;
/**
* Map of hashes to the proposal preimage, along with who registered it and their deposit.
* The block number is the block at which it was deposited.
**/
preimages: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<ITuple<[Bytes, AccountId, BalanceOf, BlockNumber]>>>> & QueryableStorageEntry<ApiType>;
/**
* Those who have locked a deposit.
**/
depositOf: AugmentedQuery<ApiType, (arg: PropIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[BalanceOf, Vec<AccountId>]>>>> & QueryableStorageEntry<ApiType>;
/**
* The next free referendum index, aka the number of referenda started so far.
**/
referendumCount: AugmentedQuery<ApiType, () => Observable<ReferendumIndex>> & QueryableStorageEntry<ApiType>;
/**
* The lowest referendum index representing an unbaked referendum. Equal to
* `ReferendumCount` if there isn't a unbaked referendum.
**/
lowestUnbaked: AugmentedQuery<ApiType, () => Observable<ReferendumIndex>> & QueryableStorageEntry<ApiType>;
/**
* Information concerning any given referendum.
**/
referendumInfoOf: AugmentedQuery<ApiType, (arg: ReferendumIndex | AnyNumber | Uint8Array) => Observable<Option<ReferendumInfo>>> & QueryableStorageEntry<ApiType>;
/**
* Queue of successful referenda to be dispatched. Stored ordered by block number.
**/
dispatchQueue: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[BlockNumber, Hash, ReferendumIndex]>>>> & QueryableStorageEntry<ApiType>;
/**
* Get the voters for the current proposal.
**/
votersFor: AugmentedQuery<ApiType, (arg: ReferendumIndex | AnyNumber | Uint8Array) => Observable<Vec<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* Get the vote in a given referendum of a particular voter. The result is meaningful only
* if `voters_for` includes the voter when called with the referendum (you'll get the
* default `Vote` value otherwise). If you don't want to check `voters_for`, then you can
* also check for simple existence with `VoteOf::contains_key` first.
**/
voteOf: AugmentedQuery<ApiType, (arg: ITuple<[ReferendumIndex, AccountId]> | [ReferendumIndex | AnyNumber | Uint8Array, AccountId | string | Uint8Array]) => Observable<Vote>> & QueryableStorageEntry<ApiType>;
/**
* Who is able to vote for whom. Value is the fund-holding account, key is the
* vote-transaction-sending account.
**/
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* Get the account (and lock periods) to which another account is delegating vote.
**/
delegations: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[AccountId, Conviction]>>> & QueryableStorageEntry<ApiType>;
/**
* Accounts for which there are locks in action which may be removed at some point in the
* future. The value is the block number at which the lock expires and may be removed.
**/
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<BlockNumber>>> & QueryableStorageEntry<ApiType>;
/**
* True if the last referendum tabled was submitted externally. False if it was a public
* proposal.
**/
lastTabledWasExternal: AugmentedQuery<ApiType, () => Observable<bool>> & QueryableStorageEntry<ApiType>;
/**
* The referendum to be tabled whenever it would be valid to table an external proposal.
* This happens when a referendum needs to be tabled and one of two conditions are met:
* - `LastTabledWasExternal` is `false`; or
* - `PublicProps` is empty.
**/
nextExternal: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[Hash, VoteThreshold]>>>> & QueryableStorageEntry<ApiType>;
/**
* A record of who vetoed what. Maps proposal hash to a possible existent block number
* (until when it may not be resubmitted) and who vetoed it.
**/
blacklist: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<ITuple<[BlockNumber, Vec<AccountId>]>>>> & QueryableStorageEntry<ApiType>;
/**
* Record of all proposals that have been subject to emergency cancellation.
**/
cancellations: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<bool>> & QueryableStorageEntry<ApiType>;
};
council: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The hashes of the active proposals.
**/
proposals: AugmentedQuery<ApiType, () => Observable<Vec<Hash>>> & QueryableStorageEntry<ApiType>;
/**
* Actual proposal for a given hash, if it's current.
**/
proposalOf: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<Proposal>>> & QueryableStorageEntry<ApiType>;
/**
* Votes on a given proposal, if it is ongoing.
**/
voting: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<Votes>>> & QueryableStorageEntry<ApiType>;
/**
* Proposals so far.
**/
proposalCount: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
/**
* The current members of the collective. This is stored sorted (just by value).
**/
members: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>> & QueryableStorageEntry<ApiType>;
};
technicalCommittee: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The hashes of the active proposals.
**/
proposals: AugmentedQuery<ApiType, () => Observable<Vec<Hash>>> & QueryableStorageEntry<ApiType>;
/**
* Actual proposal for a given hash, if it's current.
**/
proposalOf: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<Proposal>>> & QueryableStorageEntry<ApiType>;
/**
* Votes on a given proposal, if it is ongoing.
**/
voting: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<Votes>>> & QueryableStorageEntry<ApiType>;
/**
* Proposals so far.
**/
proposalCount: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
/**
* The current members of the collective. This is stored sorted (just by value).
**/
members: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>> & QueryableStorageEntry<ApiType>;
};
elections: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The current elected membership. Sorted based on account id.
**/
members: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
/**
* The current runners_up. Sorted based on low to high merit (worse to best runner).
**/
runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
/**
* The total number of vote rounds that have happened, excluding the upcoming one.
**/
electionRounds: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
/**
* Votes of a particular voter, with the round index of the votes.
**/
votesOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* Locked stake of a voter.
**/
stakeOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/**
* The present candidate list. Sorted based on account-id. A current member or a runner can
* never enter this vector and is always implicitly assumed to be a candidate.
**/
candidates: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>> & QueryableStorageEntry<ApiType>;
};
technicalMembership: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The current membership, stored as an ordered Vec.
**/
members: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>> & QueryableStorageEntry<ApiType>;
};
grandpa: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* DEPRECATED
* This used to store the current authority set, which has been migrated to the well-known
* GRANDPA_AUTHORITES_KEY unhashed key.
**/
authorities: AugmentedQuery<ApiType, () => Observable<AuthorityList>> & QueryableStorageEntry<ApiType>;
/**
* State of the current authority set.
**/
state: AugmentedQuery<ApiType, () => Observable<StoredState>> & QueryableStorageEntry<ApiType>;
/**
* Pending change: (signaled at, scheduled change).
**/
pendingChange: AugmentedQuery<ApiType, () => Observable<Option<StoredPendingChange>>> & QueryableStorageEntry<ApiType>;
/**
* next block number where we can force a change.
**/
nextForced: AugmentedQuery<ApiType, () => Observable<Option<BlockNumber>>> & QueryableStorageEntry<ApiType>;
/**
* `true` if we are currently stalled.
**/
stalled: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[BlockNumber, BlockNumber]>>>> & QueryableStorageEntry<ApiType>;
/**
* The number of changes (both in terms of keys and underlying economic responsibilities)
* in the "set" of Grandpa validators from genesis.
**/
currentSetId: AugmentedQuery<ApiType, () => Observable<SetId>> & QueryableStorageEntry<ApiType>;
/**
* A mapping from grandpa set ID to the index of the *most recent* session for which its members were responsible.
**/
setIdSession: AugmentedQuery<ApiType, (arg: SetId | AnyNumber | Uint8Array) => Observable<Option<SessionIndex>>> & QueryableStorageEntry<ApiType>;
};
treasury: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* Number of proposals that have been made.
**/
proposalCount: AugmentedQuery<ApiType, () => Observable<ProposalIndex>> & QueryableStorageEntry<ApiType>;
/**
* Proposals that have been made.
**/
proposals: AugmentedQuery<ApiType, (arg: ProposalIndex | AnyNumber | Uint8Array) => Observable<Option<TreasuryProposal>>> & QueryableStorageEntry<ApiType>;
/**
* Proposal indices that have been approved but not yet awarded.
**/
approvals: AugmentedQuery<ApiType, () => Observable<Vec<ProposalIndex>>> & QueryableStorageEntry<ApiType>;
/**
* Tips that are not yet completed. Keyed by the hash of `(reason, who)` from the value.
* This has the insecure enumerable hash function since the key itself is already
* guaranteed to be a secure hash.
**/
tips: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<OpenTip>>> & QueryableStorageEntry<ApiType>;
/**
* Simple preimage lookup from the reason's hash to the original data. Again, has an
* insecure enumerable hash since the key is guaranteed to be the result of a secure hash.
**/
reasons: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<Bytes>>> & QueryableStorageEntry<ApiType>;
};
contracts: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* Gas spent so far in this block.
**/
gasSpent: AugmentedQuery<ApiType, () => Observable<Gas>> & QueryableStorageEntry<ApiType>;
/**
* Current cost schedule for contracts.
**/
currentSchedule: AugmentedQuery<ApiType, () => Observable<Schedule>> & QueryableStorageEntry<ApiType>;
/**
* A mapping from an original code hash to the original code, untouched by instrumentation.
**/
pristineCode: AugmentedQuery<ApiType, (arg: CodeHash | string | Uint8Array) => Observable<Option<Bytes>>> & QueryableStorageEntry<ApiType>;
/**
* A mapping between an original code hash and instrumented wasm code, ready for execution.
**/
codeStorage: AugmentedQuery<ApiType, (arg: CodeHash | string | Uint8Array) => Observable<Option<PrefabWasmModule>>> & QueryableStorageEntry<ApiType>;
/**
* The subtrie counter.
**/
accountCounter: AugmentedQuery<ApiType, () => Observable<u64>> & QueryableStorageEntry<ApiType>;
/**
* The code associated with a given account.
**/
contractInfoOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ContractInfo>>> & QueryableStorageEntry<ApiType>;
/**
* The price of one unit of gas.
**/
gasPrice: AugmentedQuery<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
};
sudo: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The `AccountId` of the sudo key.
**/
key: AugmentedQuery<ApiType, () => Observable<AccountId>> & QueryableStorageEntry<ApiType>;
};
imOnline: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The block number after which it's ok to send heartbeats in current session.
* At the beginning of each session we set this to a value that should
* fall roughly in the middle of the session duration.
* The idea is to first wait for the validators to produce a block
* in the current session, so that the heartbeat later on will not be necessary.
**/
heartbeatAfter: AugmentedQuery<ApiType, () => Observable<BlockNumber>> & QueryableStorageEntry<ApiType>;
/**
* The current set of keys that may issue a heartbeat.
**/
keys: AugmentedQuery<ApiType, () => Observable<Vec<AuthorityId>>> & QueryableStorageEntry<ApiType>;
/**
* For each session index, we keep a mapping of `AuthIndex`
* to `offchain::OpaqueNetworkState`.
**/
receivedHeartbeats: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: AuthIndex | AnyNumber | Uint8Array) => Observable<Option<Bytes>>> & QueryableStorageEntry<ApiType>;
/**
* For each session index, we keep a mapping of `T::ValidatorId` to the
* number of blocks authored by the given authority.
**/
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>> & QueryableStorageEntry<ApiType>;
};
offences: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The primary structure that holds all offence records keyed by report identifiers.
**/
reports: AugmentedQuery<ApiType, (arg: ReportIdOf | string | Uint8Array) => Observable<Option<OffenceDetails>>> & QueryableStorageEntry<ApiType>;
/**
* A vector of reports of the same kind that happened at the same time slot.
**/
concurrentReportsIndex: AugmentedQueryDoubleMap<ApiType, (key1: Kind | string | Uint8Array, key2: OpaqueTimeSlot | string | Uint8Array) => Observable<Vec<ReportIdOf>>> & QueryableStorageEntry<ApiType>;
/**
* Enumerates all reports of a kind along with the time they happened.
* All reports are sorted by the time of offence.
* Note that the actual type of this mapping is `Vec<u8>`, this is because values of
* different types are not supported at the moment so we are doing the manual serialization.
**/
reportsByKindIndex: AugmentedQuery<ApiType, (arg: Kind | string | Uint8Array) => Observable<Bytes>> & QueryableStorageEntry<ApiType>;
};
randomnessCollectiveFlip: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* Series of block headers from the last 81 blocks that acts as random seed material. This
* is arranged as a ring buffer with `block_number % 81` being the index into the `Vec` of
* the oldest hash.
**/
randomMaterial: AugmentedQuery<ApiType, () => Observable<Vec<Hash>>> & QueryableStorageEntry<ApiType>;
};
identity: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* Information that is pertinent to identify the entity behind an account.
**/
identityOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<Registration>>> & QueryableStorageEntry<ApiType>;
/**
* The super-identity of an alternative "sub" identity together with its name, within that
* context. If the account is not some other account's sub-identity, then just `None`.
**/
superOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ITuple<[AccountId, Data]>>>> & QueryableStorageEntry<ApiType>;
/**
* Alternative "sub" identities of this account.
* The first item is the deposit, the second is a vector of the accounts.
**/
subsOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>> & QueryableStorageEntry<ApiType>;
/**
* The set of registrars. Not expected to get very big as can only be added through a
* special origin (likely a council motion).
* The index into this can be cast to `RegistrarIndex` to get a valid value.
**/
registrars: AugmentedQuery<ApiType, () => Observable<Vec<Option<RegistrarInfo>>>> & QueryableStorageEntry<ApiType>;
};
society: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The first member.
**/
founder: AugmentedQuery<ApiType, () => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* A hash of the rules of this society concerning membership. Can only be set once and
* only by the founder.
**/
rules: AugmentedQuery<ApiType, () => Observable<Option<Hash>>> & QueryableStorageEntry<ApiType>;
/**
* The current set of candidates; bidders that are attempting to become members.
**/
candidates: AugmentedQuery<ApiType, () => Observable<Vec<Bid>>> & QueryableStorageEntry<ApiType>;
/**
* The set of suspended candidates.
**/
suspendedCandidates: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ITuple<[BalanceOf, BidKind]>>>> & QueryableStorageEntry<ApiType>;
/**
* Amount of our account balance that is specifically for the next round's bid(s).
**/
pot: AugmentedQuery<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/**
* The most primary from the most recently approved members.
**/
head: AugmentedQuery<ApiType, () => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* The current set of members, ordered.
**/
members: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* The set of suspended members.
**/
suspendedMembers: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<bool>> & QueryableStorageEntry<ApiType>;
/**
* The current bids, stored ordered by the value of the bid.
**/
bids: AugmentedQuery<ApiType, () => Observable<Vec<Bid>>> & QueryableStorageEntry<ApiType>;
/**
* Members currently vouching or banned from vouching again
**/
vouching: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<VouchingStatus>>> & QueryableStorageEntry<ApiType>;
/**
* Pending payouts; ordered by block number, with the amount that should be paid out.
**/
payouts: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<ITuple<[BlockNumber, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
/**
* The ongoing number of losing votes cast by the member.
**/
strikes: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<StrikeCount>> & QueryableStorageEntry<ApiType>;
/**
* Double map from Candidate -> Voter -> (Maybe) Vote.
**/
votes: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<SocietyVote>>> & QueryableStorageEntry<ApiType>;
/**
* The defending member currently being challenged.
**/
defender: AugmentedQuery<ApiType, () => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
/**
* Votes for the defender.
**/
defenderVotes: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<SocietyVote>>> & QueryableStorageEntry<ApiType>;
/**
* The max number of members for the society at one time.
**/
maxMembers: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
};
recovery: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The set of recoverable accounts and their recovery configuration.
**/
recoverable: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<RecoveryConfig>>> & QueryableStorageEntry<ApiType>;
/**
* Active recovery attempts.
* First account is the account to be recovered, and the second account
* is the user trying to recover the account.
**/
activeRecoveries: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ActiveRecovery>>> & QueryableStorageEntry<ApiType>;
/**
* The final list of recovered accounts.
* Map from the recovered account to the user who can access it.
**/
recovered: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
};
vesting: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* Information regarding the vesting of a given account.
**/
vesting: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<VestingInfo>>> & QueryableStorageEntry<ApiType>;
};
}
export interface QueryableStorage<ApiType extends ApiTypes> extends AugmentedQueries<ApiType> {
[index: string]: QueryableModuleStorage<ApiType>;
}
}
+191
View File
@@ -0,0 +1,191 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable @typescript-eslint/no-empty-interface */
import { AnyNumber, Codec, IExtrinsic } from '@polkadot/types/types';
import { Option, Vec } from '@polkadot/types/codec';
import { Bytes, StorageKey, Text, bool, u32, u64 } from '@polkadot/types/primitive';
import { Metadata } from '@polkadot/types';
import { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
import { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import { BlockHash, ChainProperties, ExtrinsicOrHash, ExtrinsicStatus, Health, NetworkState, PeerInfo, RpcMethods, RuntimeDispatchInfo, RuntimeVersion, StorageChangeSet } from '@polkadot/types/interfaces/rpc';
import { AccountId, BlockNumber, H256, Hash, Header, Index, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import { Observable } from 'rxjs';
declare module '@polkadot/rpc-core/types.jsonrpc' {
export interface RpcInterface {
account: {
/**
* Retrieves the next accountIndex as available on the node
**/
nextIndex(accountId: AccountId | string | Uint8Array): Observable<Index>;
};
author: {
/**
* Returns true if the keystore has private keys for the given public key and key type.
**/
hasKey(publicKey: Bytes | string | Uint8Array, keyType: Text | string): Observable<bool>;
/**
* Returns true if the keystore has private keys for the given session public keys.
**/
hasSessionKeys(sessionKeys: Bytes | string | Uint8Array): Observable<bool>;
/**
* Insert a key into the keystore.
**/
insertKey(keyType: Text | string, suri: Text | string, publicKey: Bytes | string | Uint8Array): Observable<Bytes>;
/**
* Returns all pending extrinsics, potentially grouped by sender
**/
pendingExtrinsics(): Observable<Vec<Extrinsic>>;
/**
* Remove given extrinsic from the pool and temporarily ban it to prevent reimporting
**/
removeExtrinsic(bytesOrHash: Vec<ExtrinsicOrHash> | (ExtrinsicOrHash | { hash: any } | { extrinsic: any } | string | Uint8Array)[]): Observable<Vec<Hash>>;
/**
* Generate new session keys and returns the corresponding public keys
**/
rotateKeys(): Observable<Bytes>;
/**
* Submit and subscribe to watch an extrinsic until unsubscribed
**/
submitAndWatchExtrinsic(extrinsic: IExtrinsic): Observable<ExtrinsicStatus>;
/**
* Submit a fully formatted extrinsic for block inclusion
**/
submitExtrinsic(extrinsic: IExtrinsic): Observable<Hash>;
};
chain: {
/**
* Get header and body of a relay chain block
**/
getBlock(hash?: BlockHash | string | Uint8Array): Observable<SignedBlock>;
/**
* Get the block hash for a specific block
**/
getBlockHash(blockNumber?: BlockNumber | AnyNumber | Uint8Array): Observable<BlockHash>;
/**
* Get hash of the last finalized block in the canon chain
**/
getFinalizedHead(): Observable<BlockHash>;
/**
* Retrieves the header for a specific block
**/
getHeader(hash?: BlockHash | string | Uint8Array): Observable<Header>;
/**
* Retrieves the newest header via subscription
**/
subscribeAllHeads(): Observable<Header>;
/**
* Retrieves the best finalized header via subscription
**/
subscribeFinalizedHeads(): Observable<Header>;
/**
* Retrieves the best header via subscription
**/
subscribeNewHeads(): Observable<Header>;
};
contracts: {
/**
* Executes a call to a contract
**/
call(callRequest: ContractCallRequest | { origin?: any; dest?: any; value?: any; gasLimit?: any; inputData?: any } | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<ContractExecResult>;
/**
* Returns the value under a specified storage key in a contract
**/
getStorage(address: AccountId | string | Uint8Array, key: H256 | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<Option<Bytes>>;
};
payment: {
/**
* Retrieves the fee information for an encoded extrinsic
**/
queryInfo(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<RuntimeDispatchInfo>;
};
rpc: {
/**
* Retrieves the list of RPC methods that are exposed by the node
**/
methods(): Observable<RpcMethods>;
};
state: {
/**
* Perform a call to a builtin on the chain
**/
call(method: Text | string, data: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<Bytes>;
/**
* Retrieves the keys with prefix of a specific child storage
**/
getChildKeys(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<Vec<StorageKey>>;
/**
* Retrieves the child storage for a key
**/
getChildStorage(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<StorageData>;
/**
* Retrieves the child storage hash
**/
getChildStorageHash(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<Hash>;
/**
* Retrieves the child storage size
**/
getChildStorageSize(childStorageKey: StorageKey | string | Uint8Array | any, childDefinition: StorageKey | string | Uint8Array | any, childType: u32 | AnyNumber | Uint8Array, key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<u64>;
/**
* Retrieves the keys with a certain prefix
**/
getKeys(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<Vec<StorageKey>>;
/**
* Returns the runtime metadata
**/
getMetadata(at?: BlockHash | string | Uint8Array): Observable<Metadata>;
/**
* Get the runtime version
**/
getRuntimeVersion(at?: BlockHash | string | Uint8Array): Observable<RuntimeVersion>;
getStorage<T = Codec>(key: any, block?: Hash | Uint8Array | string): Observable<T>;
/**
* Retrieves the storage hash
**/
getStorageHash(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<Hash>;
/**
* Retrieves the storage size
**/
getStorageSize(key: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array): Observable<u64>;
/**
* Query historical storage entries (by key) starting from a start block
**/
queryStorage(keys: Vec<StorageKey> | (StorageKey | string | Uint8Array | any)[], startBlock: Hash | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<Vec<StorageChangeSet>>;
/**
* Retrieves the runtime version via subscription
**/
subscribeRuntimeVersion(): Observable<RuntimeVersion>;
subscribeStorage<T = Codec[]>(keys: any[]): Observable<T>;
};
system: {
/**
* Retrieves the chain
**/
chain(): Observable<Text>;
/**
* Return health status of the node
**/
health(): Observable<Health>;
/**
* Retrieves the node name
**/
name(): Observable<Text>;
/**
* Returns current state of the network
**/
networkState(): Observable<NetworkState>;
/**
* Returns the currently connected peers
**/
peers(): Observable<Vec<PeerInfo>>;
/**
* Get a custom set of properties as a JSON object, defined in the chain spec
**/
properties(): Observable<ChainProperties>;
/**
* Retrieves the version of the node
**/
version(): Observable<Text>;
};
}
}
File diff suppressed because it is too large Load Diff
+47 -13
View File
@@ -3,8 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { Constants, Storage } from '@polkadot/metadata/Decorated/types';
import { RpcInterface } from '@polkadot/rpc-core/jsonrpc.types';
import { InterfaceRegistry } from '@polkadot/types/interfaceRegistry';
import { RpcInterface } from '@polkadot/rpc-core/types';
import { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import { AnyFunction, CallFunction, Codec, CodecArg as Arg, ITuple, InterfaceTypes, ModulesWithCalls, Registry, RegistryTypes } from '@polkadot/types/types';
import { SubmittableExtrinsic } from '../submittable/types';
@@ -14,17 +13,19 @@ import BN from 'bn.js';
import { BehaviorSubject, Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import decorateDerive, { ExactDerive } from '@polkadot/api-derive';
import DecoratedMeta from '@polkadot/metadata/Decorated';
import getHasher from '@polkadot/metadata/Decorated/storage/fromMetadata/getHasher';
import RpcCore from '@polkadot/rpc-core';
import { WsProvider } from '@polkadot/rpc-provider';
import { Metadata, Null, Option, TypeRegistry, u64, Vec } from '@polkadot/types';
import { Metadata, Null, Option, Text, TypeRegistry, u64, Vec } from '@polkadot/types';
import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage';
import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/primitive/Extrinsic/constants';
import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/extrinsic/constants';
import StorageKey, { StorageEntry } from '@polkadot/types/primitive/StorageKey';
import { assert, compactStripLength, isNull, isUndefined, u8aConcat, u8aToHex } from '@polkadot/util';
import { createSubmittable } from '../submittable';
import { decorateSections, DeriveAllSections } from '../util/decorate';
import augmentObject from '../util/augmentObject';
import Events from './Events';
interface MetaDecoration {
@@ -43,11 +44,11 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
// HACK Use BN import so decorateDerive works... yes, wtf.
protected __phantom = new BN(0);
protected _consts?: Constants;
protected _consts: Constants = {} as Constants;
protected _derive?: ReturnType<Decorate<ApiType>['decorateDerive']>;
protected _extrinsics?: SubmittableExtrinsics<ApiType>;
protected _extrinsics: SubmittableExtrinsics<ApiType> = {} as SubmittableExtrinsics<ApiType>;
protected _extrinsicType: number = EXTRINSIC_DEFAULT_VERSION;
@@ -59,7 +60,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
protected readonly _options: ApiOptions;
protected _query?: QueryableStorage<ApiType>;
protected _query: QueryableStorage<ApiType> = {} as QueryableStorage<ApiType>;
protected _queryMulti?: QueryableStorageMulti<ApiType>;
@@ -67,11 +68,17 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
protected _rpcCore: RpcCore;
protected _runtimeChain?: Text;
protected _runtimeMetadata?: Metadata;
protected _runtimeVersion?: RuntimeVersion;
protected _rx: Partial<ApiInterfaceRx> = {};
protected _rx: ApiInterfaceRx = {
consts: {} as Constants,
query: {} as QueryableStorage<'rxjs'>,
tx: {} as SubmittableExtrinsics<'rxjs'>
} as ApiInterfaceRx;
protected _type: ApiTypes;
@@ -129,9 +136,19 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
this._rx.registry = this.registry;
}
public abstract createType <K extends InterfaceTypes> (type: K, ...params: any[]): InterfaceRegistry[K];
/**
* @description Creates an instance of a type as registered
*/
public createType <K extends keyof InterfaceTypes> (type: K, ...params: any[]): InterfaceTypes[K] {
return this.registry.createType(type, ...params);
}
public abstract registerTypes (types?: RegistryTypes): void;
/**
* @description Register additional user-defined of chain-specific types in the type registry
*/
public registerTypes (types?: RegistryTypes): void {
types && this.registry.register(types);
}
/**
* @returns `true` if the API operates with subscriptions
@@ -140,6 +157,20 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
return this._rpcCore.provider.hasSubscriptions;
}
public injectMetadata (metadata: Metadata, fromEmpty?: boolean): void {
const decoratedMeta = new DecoratedMeta(this.registry, metadata);
// this API
augmentObject('tx', this.decorateExtrinsics(decoratedMeta.tx, this.decorateMethod), this._extrinsics, fromEmpty);
augmentObject('query', this.decorateStorage(decoratedMeta.query, this.decorateMethod), this._query, fromEmpty);
augmentObject('consts', decoratedMeta.consts, this._consts, fromEmpty);
// rx
augmentObject('', this.decorateExtrinsics(decoratedMeta.tx, this.rxDecorateMethod), this._rx.tx, fromEmpty);
augmentObject('', this.decorateStorage(decoratedMeta.query, this.rxDecorateMethod), this._rx.query, fromEmpty);
augmentObject('', decoratedMeta.consts, this._rx.consts, fromEmpty);
}
private decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
output.meta = input.meta;
output.method = input.method;
@@ -219,7 +250,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
}
protected decorateExtrinsics<ApiType extends ApiTypes> (extrinsics: ModulesWithCalls, decorateMethod: DecorateMethod<ApiType>): SubmittableExtrinsics<ApiType> {
const creator = createSubmittable(this._type, this._rx as ApiInterfaceRx, decorateMethod);
const creator = createSubmittable(this._type, this._rx, decorateMethod);
return Object.entries(extrinsics).reduce((out, [name, section]): SubmittableExtrinsics<ApiType> => {
out[name] = Object.entries(section).reduce((out, [name, method]): SubmittableModuleExtrinsics<ApiType> => {
@@ -285,6 +316,9 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
decorated.key = (arg1?: Arg, arg2?: Arg): string =>
u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]);
decorated.keyPrefix = (): string =>
u8aToHex(creator.keyPrefix);
if (this.hasSubscriptions) {
// When using double map storage function, user need to pass double map key as an array
decorated.multi = decorateMethod((args: (Arg | Arg[])[]): Observable<Codec[]> =>
@@ -408,13 +442,13 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
protected decorateDeriveRx (decorateMethod: DecorateMethod<ApiType>): DeriveAllSections<'rxjs', ExactDerive> {
// Pull in derive from api-derive
const derive = decorateDerive(this._rx as ApiInterfaceRx, this._options.derives);
const derive = decorateDerive(this._rx, this._options.derives);
return decorateSections<'rxjs', ExactDerive>(derive, decorateMethod);
}
protected decorateDerive (decorateMethod: DecorateMethod<ApiType>): DeriveAllSections<ApiType, ExactDerive> {
return decorateSections<ApiType, ExactDerive>(this._rx.derive as DeriveAllSections<'rxjs', ExactDerive>, decorateMethod);
return decorateSections<ApiType, ExactDerive>(this._rx.derive, decorateMethod);
}
/**

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