Compare commits

...
209 Commits
Author SHA1 Message Date
github-actions[bot] 7be3cc949f [CI Skip] release/stable 6.10.2
skip-checks: true
2021-11-30 05:32:43 +00:00
Jaco 41cc8b34aa Bump util (#4272)
* Bump util

* util 8.0.4

* 8.0.4
2021-11-30 07:25:50 +02:00
github-actions[bot] 4bbba5bb35 [CI Skip] release/beta 6.10.2-0
skip-checks: true
2021-11-29 15:48:19 +00:00
Jaco feae323f5c Adjust augmentation interface consistency (#4269)
* Adjust augmetation interface consistency

* spelling

* Remove useless eslint slience

* slience escapes

* rebuild

* Fix indent

* comment fix (again)

* Adjust

* Additional adjustments
2021-11-29 17:41:23 +02:00
github-actions[bot] b363833a9f [CI Skip] release/stable 6.10.1
skip-checks: true
2021-11-29 06:45:19 +00:00
Jaco f083ea3861 6.10.1 (#4267) 2021-11-29 08:38:21 +02:00
github-actions[bot] f62e7f8bf9 [CI Skip] release/beta 6.9.3-6
skip-checks: true
2021-11-29 05:55:26 +00:00
Jaco fedb0a3f09 Re-order augmentation imports (#4266) 2021-11-29 07:46:34 +02:00
github-actions[bot] 38928448bf [CI Skip] release/beta 6.9.3-5
skip-checks: true
2021-11-26 12:54:56 +00:00
Jaco cfbde5f6bd Fix RPC non-available section init (#4263) 2021-11-26 14:47:54 +02:00
github-actions[bot] 4b0e0bc6d3 [CI Skip] release/beta 6.9.3-4
skip-checks: true
2021-11-26 10:51:45 +00:00
Jaco 9acb79f500 Bump common (#4262)
* Bump common

* Adjust
2021-11-26 12:45:02 +02:00
Github Actions 5dc0b38881 [CI Skip] release/beta 6.9.3-3
skip-checks: true
2021-11-24 14:59:43 +00:00
Jaco fab6f7e883 Adjust stale schedule (#4257) 2021-11-24 16:52:40 +02:00
Github Actions 66e635e909 [CI Skip] release/beta 6.9.3-2
skip-checks: true
2021-11-23 08:08:38 +00:00
Jaco 6e496d5a3c Add missing types -> types-known dep (#4252)
* Add missing types -> types-known dep

* Run install :)
2021-11-23 09:59:53 +02:00
Github Actions ca172c9a53 [CI Skip] release/beta 6.9.3-1
skip-checks: true
2021-11-22 09:49:34 +00:00
Jaco e9b83a9ff6 Bump static metadata (#4248)
* Bump static metadata

* metadata static json

* Adjust tests (new signed extensions)
2021-11-22 11:42:27 +02:00
Github Actions cf18d97b3a [CI Skip] release/beta 6.9.3-0
skip-checks: true
2021-11-22 06:41:45 +00:00
Jaco 0b1c715408 Bump dev (#4247) 2021-11-22 08:32:50 +02:00
Github Actions 5d493e1a03 [CI Skip] release/stable 6.9.2
skip-checks: true
2021-11-22 05:34:55 +00:00
Jaco e5437ef9e9 6.9.2 (#4246)
* 6.9.2

* Pull in new util
2021-11-22 07:26:47 +02:00
Github Actions b56bed39e1 [CI Skip] release/stable 6.9.1
skip-checks: true
2021-11-21 09:36:41 +00:00
Jaco e789f91850 6.9.1 (#4244) 2021-11-21 11:28:52 +02:00
Github Actions a236eb9453 [CI Skip] release/beta 6.8.2-18
skip-checks: true
2021-11-21 09:14:31 +00:00
Jaco 7ef01b8534 Bump common (#4243) 2021-11-21 11:06:08 +02:00
Github Actions 0e58545a9d [CI Skip] release/beta 6.8.2-17
skip-checks: true
2021-11-19 10:21:44 +00:00
Jaco c474123777 Bump common (#4239)
* Bump common

* CHANGELOG
2021-11-19 12:14:05 +02:00
Github Actions 93edfcf560 [CI Skip] release/beta 6.8.2-16
skip-checks: true
2021-11-19 07:59:40 +00:00
Daniel SavuandGithub Actions e5a67d82fa fix: Generate custom type definitions (#4224)
* fix: Generate custom type definitions

* Generate separate lookup types

* fix: Custom imports

* fix linting errors

Co-authored-by: Github Actions <action@github.com>
2021-11-19 09:51:51 +02:00
Github Actions 194f6aece1 [CI Skip] release/beta 6.8.2-15
skip-checks: true
2021-11-19 05:35:22 +00:00
Jaco 3b4fef8f6e Bump deps (#4238) 2021-11-19 07:26:28 +02:00
Github Actions 6c7323ee3a [CI Skip] release/beta 6.8.2-14
skip-checks: true
2021-11-18 20:00:39 +00:00
Jaco a97b50decb Additional isU8a decoding shortcuts (#4236) 2021-11-18 21:52:24 +02:00
Github Actions 52accf6444 [CI Skip] release/beta 6.8.2-13
skip-checks: true
2021-11-18 13:27:34 +00:00
Jaco 5b8eb231cc CHANGELOG (#4234) 2021-11-18 15:20:21 +02:00
Github Actions 5ea62367d3 [CI Skip] release/beta 6.8.2-12
skip-checks: true
2021-11-18 10:49:36 +00:00
Jaco 49a034a1a0 Place u8a decoding top-of-tree (#4230)
* Place u8a decoding top-of-tree

* Adjust
2021-11-18 12:41:27 +02:00
Github Actions 62a476cb4c [CI Skip] release/beta 6.8.2-11
skip-checks: true
2021-11-18 09:59:41 +00:00
Jaco b283673812 Squeek less recursion out of DetectCodec (#4232)
* Squeek less recursion out of DetectCodec

* Flatten more

* TS 4.5.2 for checking
2021-11-18 11:52:31 +02:00
Github Actions b6a075fefb [CI Skip] release/beta 6.8.2-10
skip-checks: true
2021-11-18 09:11:06 +00:00
Jaco afa844ae01 Bump deps (#4231) 2021-11-18 11:03:45 +02:00
Github Actions 353ef59a1c [CI Skip] release/beta 6.8.2-9
skip-checks: true
2021-11-18 06:32:55 +00:00
Jaco 6228999e6f Decoding cleanups (#4228)
* Decoding cleanups

* CHANGELOG

* Additional adjustments

* Adjust

* Ordering
2021-11-18 08:24:52 +02:00
Github Actions 56db42fedf [CI Skip] release/beta 6.8.2-8
skip-checks: true
2021-11-18 04:48:36 +00:00
Jaco df44693e5d Use stringPascalCase from @polkadot/util (#4211) 2021-11-18 06:40:28 +02:00
Github Actions cfa25f8dda [CI Skip] release/beta 6.8.2-7
skip-checks: true
2021-11-18 04:01:38 +00:00
Jaco bc8934f3c3 Ensure generation of Call/Event enums (#4226) 2021-11-18 05:53:54 +02:00
Github Actions bc67c72e9b [CI Skip] release/beta 6.8.2-6
skip-checks: true
2021-11-17 12:26:35 +00:00
Jaco 22d85e745a Bump deps (#4221)
* Bump deps

* Adjust

* Adjust
2021-11-17 14:19:21 +02:00
Github Actions 60ba2952f7 [CI Skip] release/beta 6.8.2-5
skip-checks: true
2021-11-17 08:28:22 +00:00
Jaco bb10d2813f Expand runtime Call/Event matching (#4220)
* Expand runtime Call/Event matching

* Adjust * matching

* CHANGELOG
2021-11-17 10:18:55 +02:00
Github Actions 80b581f0df [CI Skip] release/beta 6.8.2-4
skip-checks: true
2021-11-13 06:00:08 +00:00
Jaco ef37c421ac Option toJSON output same as from Substrate input (#4212)
* Option toJSON output same as from Substrate input

* CHANGELOG
2021-11-13 07:53:15 +02:00
Github Actions 6e1e8e622b [CI Skip] release/beta 6.8.2-3
skip-checks: true
2021-11-13 05:41:31 +00:00
Jaco ec38a1510f CHANGELOG (#4210) 2021-11-13 07:33:18 +02:00
Github Actions e550ca5a71 [CI Skip] release/beta 6.8.2-2
skip-checks: true
2021-11-12 10:56:32 +00:00
Jaco 80241f732f Split base/essential definition handling (#4206)
* Split base/essential definition handling

* Adjust
2021-11-12 12:47:34 +02:00
Github Actions 84fc0be12e [CI Skip] release/beta 6.8.2-1
skip-checks: true
2021-11-12 08:53:05 +00:00
flex e1f14e8a83 Change BeefySignedCommitment signatures type to EcdsaSignature (#4204) 2021-11-12 10:45:09 +02:00
Github Actions 1155724604 [CI Skip] release/beta 6.8.2-0
skip-checks: true
2021-11-11 12:55:42 +00:00
Jaco 3bb9541943 Bump deps (#4203) 2021-11-11 14:47:26 +02:00
Github Actions 25288f664a [CI Skip] release/stable 6.8.1
skip-checks: true
2021-11-11 11:15:45 +00:00
Jaco 879c5d7b44 6.8.1 (#4201)
* 6.8.1

* rx.queryAt param CHANGELOG
2021-11-11 13:08:24 +02:00
Jaco cdaec1953c Add knownVersion on rx.queryAt (#4194) 2021-11-11 11:30:16 +02:00
Github Actions f4bf7a9c52 [CI Skip] release/beta 6.7.3-7
skip-checks: true
2021-11-11 05:28:44 +00:00
Jaco 7b46c6aa15 Adjust signFake to apply large default signature (#4199)
* Adjust signFake to apply empty default signature

* 0x01... default

* Rename constant

* Add previously failing test
2021-11-11 07:19:21 +02:00
Github Actions d28f4ccfa0 [CI Skip] release/beta 6.7.3-6
skip-checks: true
2021-11-10 17:43:43 +00:00
Jaco e5b05dc700 Slight adjustment to rpc-provider LRU (#4198) 2021-11-10 19:35:20 +02:00
Github Actions bf9831753e [CI Skip] release/beta 6.7.3-5
skip-checks: true
2021-11-10 12:53:27 +00:00
Jaco 5e1670dbae Provider-level caching for historic requests (#4195)
* Provider-level caching for historic requests

* LRUCache

* Adjust

* Adjust

* Adjust

* Opts

* private variables

* Implementation link

* lru .entries adjustment (using .keys)

* Adjust expectations
2021-11-10 14:46:13 +02:00
Github Actions 0d0a230c86 [CI Skip] release/beta 6.7.3-4
skip-checks: true
2021-11-10 08:55:22 +00:00
Jaco 9989b69b46 Rename decorate method (#4193)
* Rename decorateMethod*

* Split exports
2021-11-10 10:48:20 +02:00
Github Actions 66693253ef [CI Skip] release/beta 6.7.3-3
skip-checks: true
2021-11-10 07:05:56 +00:00
Jaco cbffc37dcf Optimize PortableRegistry (#4192)
* Optimize PortableRegistry

* Additional

* Adjust shortcut

* Adjust params

* Move decorateMethod

* Ordering

* Adjust

* Exports

* Renames
2021-11-10 08:58:50 +02:00
Github Actions 74ee42ed66 [CI Skip] release/beta 6.7.3-2
skip-checks: true
2021-11-10 05:15:04 +00:00
Jaco f642e2399f Polkadot 9122 block (#4191) 2021-11-10 07:07:31 +02:00
Github Actions 8cefb055db [CI Skip] release/beta 6.7.3-1
skip-checks: true
2021-11-09 14:17:36 +00:00
Jaco 1f31756019 Ensure known types for v14 is empty (#4190) 2021-11-09 16:10:44 +02:00
Github Actions 4d6a1da6d5 [CI Skip] release/beta 6.7.3-0
skip-checks: true
2021-11-09 11:30:34 +00:00
Jaco d62e720627 Remove ::generic:: from names & namespaces (#4189) 2021-11-09 13:23:10 +02:00
Github Actions 4af4470998 [CI Skip] release/stable 6.7.2
skip-checks: true
2021-11-09 09:24:30 +00:00
Jaco 8bb6218132 Detect AccountId & Address via SpRuntime* defs (#4188)
* Detect AccountId & Address via SpRuntime* defs

* Always do check via UncheckedExtrinsic

* Adjust

* 6.7.2

* Add Signature detection

* Extract ExtrinsicSignature type
2021-11-09 11:14:31 +02:00
Github Actions f4197f8752 [CI Skip] release/beta 6.7.2-0
skip-checks: true
2021-11-08 14:31:55 +00:00
Jaco 7cfad3b1c4 Derive combineLatest order adjustments (#4186) 2021-11-08 16:24:27 +02:00
Github Actions ff67a659b6 [CI Skip] release/stable 6.7.1
skip-checks: true
2021-11-07 09:17:39 +00:00
Jaco a5c69a42fc 6.7.1 (#4184)
* 6.7.1

* packgeInfo

* voteLockingPeriod
2021-11-07 11:09:03 +02:00
Github Actions 3facbf00eb [CI Skip] release/beta 6.6.2-27
skip-checks: true
2021-11-07 07:54:42 +00:00
Jaco 5a6eece6d6 Swap to objectProperty from @polkadot/util (#4183)
* Swap to objectProperty from @polkadot/util

* Re-apply
2021-11-07 09:45:37 +02:00
Github Actions 9219fa3197 [CI Skip] release/beta 6.6.2-26
skip-checks: true
2021-11-07 01:10:02 +00:00
Jaco 32b9a39b1e Multiple Codec property assignments helper (#4182)
* Multiple Codec property assignments helper

* Pass index

* consistency in naming

* typesToMap external

* Loop on index

* any -> unknown

* CHANGELOG

* Adjust

* Fix Enum with Array keys
2021-11-07 03:00:37 +02:00
Github Actions 61a7fe6307 [CI Skip] release/beta 6.6.2-25
skip-checks: true
2021-11-06 20:50:48 +00:00
Jaco ca755d3e0d Make v4 payload driven by extension fields (#4017)
* Make v4 payload driven by extension fields

* Add getters for additional fields

* Move keys

* Re-adjust

* abstract

* SignerPayload fields

* CHANGELOG
2021-11-06 22:42:14 +02:00
Github Actions 442dba42ba [CI Skip] release/beta 6.6.2-24
skip-checks: true
2021-11-06 14:43:03 +00:00
Jaco ba80dd8873 Bump metadata (#4180)
* Bump metadata

* Re-generate types.json

* Kusama hex

* Kusama (... after some struggles)
2021-11-06 16:34:33 +02:00
Github Actions 1d35302dca [CI Skip] release/beta 6.6.2-23
skip-checks: true
2021-11-06 12:36:03 +00:00
Jaco 39c3121437 CHANGELOG (#4179) 2021-11-06 14:28:22 +02:00
Github Actions d7de1d84fb [CI Skip] release/beta 6.6.2-22
skip-checks: true
2021-11-06 10:24:30 +00:00
Jaco 0ee1dfb353 Caching for previously-created complex classes (#4177)
* Caching for previousl-created complex classes

* Drop non-output testing test
2021-11-06 12:17:07 +02:00
Github Actions 0a6f1d87d4 [CI Skip] release/beta 6.6.2-21
skip-checks: true
2021-11-06 10:12:27 +00:00
Jaco b7c563391c Remove memoized caches (Enum, Set) (#4178) 2021-11-06 12:01:40 +02:00
Github Actions b648c4ba6c [CI Skip] release/beta 6.6.2-20
skip-checks: true
2021-11-06 08:09:13 +00:00
Jaco 0eb995c9a1 Apply hashCache on Extrinsic only (no duplication) (#4176) 2021-11-06 10:01:05 +02:00
Github Actions 936d14ffea [CI Skip] release/beta 6.6.2-19
skip-checks: true
2021-11-06 07:34:38 +00:00
Nazar Mokrynskyi 72c7a0a34b Performance tweaks (#4143)
* Avoid unnecessary work in `filterEvents`

* Memoize computed extrinsic hash

* Optimize sanitize by reusing precompiled regular expressions

* Memoize generation of property names in `Enum` and `Set`

* Memoize sanitizing
2021-11-06 09:25:54 +02:00
Jaco 8402013e97 Add account::AccountId20 mapping (#4175)
Replaces https://github.com/polkadot-js/api/pull/4117

Sadly I messed up that one since I moved the PortableRegistry, so despite best-efforts cannot quite revolve the now-conflicts on GitHub itself

Will give acknowledgement since it is deserved, just cannot quite get the PR merged as of right now.
2021-11-06 09:12:12 +02:00
Github Actions fde6b72974 [CI Skip] release/beta 6.6.2-18
skip-checks: true
2021-11-05 16:06:06 +00:00
Jaco d98d4d6908 Move PortableRegistry alongside metadata (#4172) 2021-11-05 17:47:02 +02:00
Github Actions ed384666ee [CI Skip] release/beta 6.6.2-17
skip-checks: true
2021-11-05 14:38:57 +00:00
Jaco 4e64e3d654 Change initialU8aLength to non-getter (#4170)
* Change initialU8aLength to non-getter

* Remove time comments

* Adjust Compact shortcut

* Adjust

* Move isU8a check first in decoding

* #initialLength for Compact

* Compact re-adjust

* Split decodeU8aVec

* decodeVec opt

* Fix compare

* Adjust

* Additional objectSpread

* Additional objectSpread

* isU8a always first

* Comment time logs

* Convert String right at point of using

* Optimize Text from Text

* Fix Text test

* Additional ordering updates

* Enum adjustments

* Reorder Option

* Adjust

* Remove comments

* Adjust
2021-11-05 16:19:38 +02:00
Github Actions 72b4b51915 [CI Skip] release/beta 6.6.2-16
skip-checks: true
2021-11-05 07:25:57 +00:00
Jaco 81f5bf96f5 Adjust Struct loops (#4169) 2021-11-05 09:09:52 +02:00
Github Actions e935281b77 [CI Skip] release/beta 6.6.2-15
skip-checks: true
2021-11-05 06:23:39 +00:00
Jaco e132330c0b Update rpc mappings (#4168)
* Update rpc mappings

* spread
2021-11-05 08:07:57 +02:00
Github Actions 21594aa660 [CI Skip] release/beta 6.6.2-14
skip-checks: true
2021-11-04 14:14:02 +00:00
Jaco 6fb7989b41 Lazy decoration (part 9, rpc) (#4165)
* Lazy decoration (part 9, rpc)

* Flatten

* Cleanups (& bump dev, fix copy-to)

* Only RPC methods are lazy

* Decorate rpc-core lazily

* Adjust import

* Remove (now) invalid test
2021-11-04 15:59:05 +02:00
Github Actions 1f38a38bd5 [CI Skip] release/beta 6.6.2-13
skip-checks: true
2021-11-04 13:06:08 +00:00
Jaco e918aa8b14 Lazy decoration (part 10, Import lazy* from @polkadot/util) (#4166)
* Impot lazy* from @polkadot/util

* Bumps
2021-11-04 14:51:06 +02:00
Github Actions 4a33b18ac4 [CI Skip] release/beta 6.6.2-12
skip-checks: true
2021-11-04 09:36:06 +00:00
Jaco cb97fd1a48 Use new object utilities (as applicable) (#4161)
* Use new object utilities (as applicable)

* Extract utility functions

* Renames

* Comment cleanup

* Fix types
2021-11-04 11:20:03 +02:00
Github Actions 51600bc560 [CI Skip] release/beta 6.6.2-11
skip-checks: true
2021-11-04 09:01:50 +00:00
Jaco 12344ed980 Bump deps (dev & common) (#4162) 2021-11-04 10:43:42 +02:00
Github Actions 0b6773a744 [CI Skip] release/beta 6.6.2-10
skip-checks: true
2021-11-03 14:19:54 +00:00
Jaco 17a38e9c09 Rebump dev, rollup build fixes (#4158) 2021-11-03 16:01:27 +02:00
Github Actions 70499fe6ac [CI Skip] release/beta 6.6.2-9
skip-checks: true
2021-11-03 13:09:32 +00:00
Jaco 64493e0091 Bump dev (#4156) 2021-11-03 15:05:39 +02:00
Github Actions ae3efb31f8 [CI Skip] release/beta 6.6.2-8
skip-checks: true
2021-11-03 10:34:20 +00:00
Jaco 6da58d0698 Dedupe decorate for storage & storageAt (#4155)
* Dedupe decorate for storage & storageAt

* blockHash as last param

* Adjust

* Reorder

* Reorder
2021-11-03 12:16:27 +02:00
Github Actions 07f40c1429 [CI Skip] release/beta 6.6.2-7
skip-checks: true
2021-11-03 09:00:41 +00:00
Jaco f5f67e795e Lazy decoration (part 8, consistent call order) (#4153)
* Lazy decoration (part 8, consistent call order)

* Dedupe

* Flatten, no extra calls

* Dedupe more

* Adjust lazyVariants

* Additional flatten

* Adjust lazyVariants

* Reorder name/index

* Deupe strings

* Flatten createkeys

* Adjust
2021-11-03 10:47:04 +02:00
Github Actions 5b0652c272 [CI Skip] release/beta 6.6.2-6
skip-checks: true
2021-11-03 05:42:40 +00:00
Jaco 53ef5f7c56 Lazy decoration (part 7, augment optimize) (#4152)
* Lazy decoration (part 7, augment optimize)

* augment with generics

* Adjust
2021-11-03 07:26:02 +02:00
Github Actions 71f99875e4 [CI Skip] release/beta 6.6.2-5
skip-checks: true
2021-11-02 14:43:15 +00:00
Jaco a097075bfe Lazy decorate (part 6, API internals) (#4150)
* Lazy decorate (part 6, API internals)

* Rework tx decoration

* Adjust metadata decoration triggers

* Reformat registry lazy decoration

* storage
2021-11-02 16:29:08 +02:00
Jaco 527f840950 More internal reduce adjustments (#4149) 2021-11-02 16:13:20 +02:00
Github Actions 7fadc7eedb [CI Skip] release/beta 6.6.2-4
skip-checks: true
2021-11-02 11:37:04 +00:00
Jaco 35663319d9 Lazy decoration (part 5, augmentObject) (#4145)
* Lazy decoration (part 5, augmentObject)

* hasOwnProperty update

* Fix comments

* loop indexes

* Extract lazySection

* Use hasOwnProperty on is/as getters

* defineProperty helper

* Update defineProperty & use for loops

* skip/adjust for some keys
2021-11-02 13:21:16 +02:00
Github Actions b9d9670d18 [CI Skip] release/beta 6.6.2-3
skip-checks: true
2021-11-02 10:32:15 +00:00
Jaco fd027f452c Lazy decoration (part 3, derives) (#4142)
* Lazy decoration (part 3, prep for derives)

* Derives are lazy

* ... it should have derives

* dedupe api-derive lazy

* function -> inline

* Cleanup defineProperty

* Adjust

* Final readability tweaks

* ... I lied, alignment tweaks

* Exportable lazyDeriveSection

* lazy from @polkadot/types

* Adjust
2021-11-02 12:10:30 +02:00
Github Actions 10a6e03f85 [CI Skip] release/beta 6.6.2-2
skip-checks: true
2021-11-02 09:42:13 +00:00
Jaco 522eb8359f Lazy decoration (part 2, registry) (#4141)
* Lazy decoration (part 2)

* createCallFunction

* Remove previous gen

* WIP, registry dedup

* ... anbd with extrinsics

* Additional cleanups

* Creator

* This should be sharable with derive...

* getName

* Adjust

* lazy.ts in types/create

* Go crazy on comments...
2021-11-02 11:28:29 +02:00
Github Actions d1fd7f75af [CI Skip] release/beta 6.6.2-1
skip-checks: true
2021-11-02 08:05:34 +00:00
Jaco bb61b1e6ac Lazy decoration (part 1, metadata) (#4139)
* Make decoration lazy

* Extract common

* w/ Extrinsics

* Storage lazy

* V14 -> Latest

* Util

* Adjust to use create/lazy

* Adjust

* Add tests for errors & events (long-time outstanding)
2021-11-02 09:49:16 +02:00
Github Actions 7c17baa5be [CI Skip] release/beta 6.6.2-0
skip-checks: true
2021-11-02 05:56:45 +00:00
Jaco 9e7c0a1959 Lazy decoration (part 4, lazyMethod/lazyMethods) (#4144) 2021-11-02 07:35:32 +02:00
Github Actions db2e97bf66 [CI Skip] release/stable 6.6.1
skip-checks: true
2021-11-01 16:17:29 +00:00
Jaco 057f6b6041 6.6.1 (#4140)
* 6.6.1

* 6.6.1
2021-11-01 17:59:50 +02:00
Github Actions ca82336087 [CI Skip] release/beta 6.5.3-13
skip-checks: true
2021-11-01 09:50:27 +00:00
Jaco 761ceaeaa3 Internal adjustments (part 6) (#4138)
* Internal adjustments (part 6)

* Additional
2021-11-01 11:35:17 +02:00
Github Actions 0cbca0adb8 [CI Skip] release/beta 6.5.3-12
skip-checks: true
2021-11-01 09:21:33 +00:00
Jaco d24db4fd6a Internal adjustments (part 4) (#4136)
* Internal adjustments (part 3)

* Internal adjustments (part 4)

* Additional

* Additional

* Fix set encoding
2021-11-01 11:01:31 +02:00
Jaco 4a893b9feb Internal adjustments (part 5) (#4137) 2021-11-01 10:56:16 +02:00
Github Actions 71a0a84f26 [CI Skip] release/beta 6.5.3-11
skip-checks: true
2021-11-01 08:25:14 +00:00
Jaco 44d241f489 Internal adjustments (part 3) (#4135) 2021-11-01 10:03:13 +02:00
Github Actions a4cb5f558d [CI Skip] release/beta 6.5.3-10
skip-checks: true
2021-11-01 07:46:07 +00:00
Jaco aef4d07c48 Internal adjustments (part 2) (#4134) 2021-11-01 09:27:04 +02:00
Github Actions 6a5f1bbbf4 [CI Skip] release/beta 6.5.3-9
skip-checks: true
2021-10-31 05:15:37 +00:00
Jaco e60ef2d677 Optimize internal u8a decoding (#4131)
* Optimize internal u8a decoding

* linting

* tsc fixes & HexString usage

* yet more... it passes now (well... tsc & lint)
2021-10-31 06:58:14 +02:00
Github Actions f4622d05db [CI Skip] release/beta 6.5.3-8
skip-checks: true
2021-10-30 15:33:20 +00:00
Jaco 47d7900809 Adjust struct iterable creation (#4130) 2021-10-30 18:12:12 +03:00
Jaco 2c86e9347b Optimize Struct from Struct construction (#4128)
* Optimize Struct from Map constrcution

* Update packages/types/src/metadata/MetadataVersioned.ts

* CHANGELOG

* Only shortcut Struct

* tests
2021-10-30 17:50:37 +03:00
Github Actions 5827d298ad [CI Skip] release/beta 6.5.3-7
skip-checks: true
2021-10-29 15:25:42 +00:00
Jaco 60e0f69920 Adjust AbstractArray & Struct decoders (#4127)
* Adjust AbstractArray & Struct decoders

* Fixes, add Text & Bytes/Raw to shortcuts

* Additional

* Additional

* Remove debug log

* Revert extra arg, make CC happy

* BTreeSet
2021-10-29 18:06:57 +03:00
Github Actions 97f1ee17b0 [CI Skip] release/beta 6.5.3-6
skip-checks: true
2021-10-28 12:13:17 +00:00
Jaco 85215a308d Bump metadata (#4123) 2021-10-28 14:48:42 +03:00
Github Actions 89fa4edcf7 [CI Skip] release/beta 6.5.3-5
skip-checks: true
2021-10-28 11:05:51 +00:00
Jaco ec42fb9bff Update known Westend upgrade blocks (#4122) 2021-10-28 13:48:10 +03:00
Github Actions 96d696dbf3 [CI Skip] release/beta 6.5.3-4
skip-checks: true
2021-10-28 08:43:46 +00:00
Jaco b7992ecc0b Use lookupName in createClass (as available) (#4121)
* User lookupName in createClass (as available)

* CHANGELOG

* cleanups

* Adjust for Vecs

* Small check cleanups
2021-10-28 11:19:30 +03:00
Github Actions 0acae6e158 [CI Skip] release/beta 6.5.3-3
skip-checks: true
2021-10-26 12:58:10 +00:00
Jaco 6afea5043e Add and dedupe EthereumAddress (#4118)
* Add and dedupe EthereumAddress

* Override for Polkadot claims
2021-10-26 15:40:58 +03:00
Github Actions c9ee8d9942 [CI Skip] release/beta 6.5.3-2
skip-checks: true
2021-10-26 11:58:39 +00:00
Jaco 55f4e150c0 Split namespaces (#4116) 2021-10-26 14:42:18 +03:00
Github Actions 3e3e9c5f5a [CI Skip] release/beta 6.5.3-1
skip-checks: true
2021-10-26 10:40:54 +00:00
Jaco 66215890dd Correct construction of palletVersion keys (#4115) 2021-10-26 13:20:54 +03:00
Github Actions bf6c7ee0c3 [CI Skip] release/beta 6.5.3-0
skip-checks: true
2021-10-26 07:58:18 +00:00
Jaco f726edf725 Bump dev (#4113) 2021-10-26 10:42:23 +03:00
Github Actions d917861a77 [CI Skip] release/stable 6.5.2
skip-checks: true
2021-10-26 06:02:42 +00:00
Jaco 12a54efde5 Fix Struct decoding for null (#4112)
* Fix Struct decoding for null

* CHANGELOG

* 6.5.2
2021-10-26 08:46:03 +03:00
Github Actions 9ae87bed78 [CI Skip] release/beta 6.5.2-3
skip-checks: true
2021-10-25 14:27:40 +00:00
Jaco 7f5a52258c Adjust toHuman on Call (#4109) 2021-10-25 17:10:26 +03:00
Github Actions 2c212e6b4d [CI Skip] release/beta 6.5.2-2
skip-checks: true
2021-10-25 14:07:57 +00:00
Jaco 3d75744a20 Bump dev deps (#4108) 2021-10-25 16:51:05 +03:00
Github Actions d2ff259989 [CI Skip] release/beta 6.5.2-1
skip-checks: true
2021-10-25 12:08:53 +00:00
Jaco cac2ef30a1 Bump dev (#4106) 2021-10-25 14:44:47 +03:00
Github Actions ea38dedcc1 [CI Skip] release/beta 6.5.2-0
skip-checks: true
2021-10-25 06:15:30 +00:00
Jaco 0bd632e612 Allow for optional known RuntimeVersion on api.at (#4103)
* Allow for optional known RuntimeVersion on api.at

* CHANGELOG typo
2021-10-25 08:57:26 +03:00
Github Actions 4ce7163bb1 [CI Skip] release/stable 6.5.1
skip-checks: true
2021-10-24 18:18:36 +00:00
Jaco 72fbd3f829 6.5.1 (#4102) 2021-10-24 20:58:36 +03:00
Github Actions f20fadb51c [CI Skip] release/beta 6.4.3-9
skip-checks: true
2021-10-23 12:36:20 +00:00
Jaco 0e0183dc99 Adjust raw toAscii output (#4097) 2021-10-23 15:16:07 +03:00
Github Actions fa71e129c2 [CI Skip] release/beta 6.4.3-8
skip-checks: true
2021-10-23 11:39:43 +00:00
Jaco cb68842da6 Bump metadata (& deps) (#4096)
* Bump metadata (& deps)

* Bump deps
2021-10-23 14:18:20 +03:00
Github Actions 44f348ecc5 [CI Skip] release/beta 6.4.3-7
skip-checks: true
2021-10-22 11:48:06 +00:00
Jaco 891a6106f0 Ensure rpcCore correctly decorates .raw (#4091)
* Ensure rpcCore correctly decorates .json/.raw

* .raw encoding changes + memoization
2021-10-22 14:25:46 +03:00
Github Actions 90fcc234a9 [CI Skip] release/beta 6.4.3-6
skip-checks: true
2021-10-22 05:55:01 +00:00
Jaco 72fcd97cdb Add typeName to TypeDef (#4089)
* Add typeName to TypeDef

* Sanitize typeName

* Export typeName inside fuction args meta

* Correct typeName extraction
2021-10-22 08:35:09 +03:00
Github Actions 2ded2052b7 [CI Skip] release/beta 6.4.3-5
skip-checks: true
2021-10-21 11:53:24 +00:00
Jaco a8da5707f2 Add palletVersion to queries (#4088)
* Add palletVersion to queries

* Re-use raw key creator

* types

* Re-adjust test
2021-10-21 14:36:54 +03:00
Github Actions f508668c46 [CI Skip] release/beta 6.4.3-4
skip-checks: true
2021-10-21 10:14:53 +00:00
Jaco 15ed0723f1 Adjust Node Websocket options (frame sizes) (#4087) 2021-10-21 12:54:25 +03:00
Github Actions c9b0502542 [CI Skip] release/beta 6.4.3-3
skip-checks: true
2021-10-21 04:55:24 +00:00
Jaco 0d5a841a81 Expose extracted type names in PortableRegistry 2021-10-21 07:33:10 +03:00
Github Actions e47b8c1e73 [CI Skip] release/beta 6.4.3-2
skip-checks: true
2021-10-21 03:28:36 +00:00
Nikos Kontakis 50fe50d1a8 Add auction in shared types (#4085) 2021-10-21 06:07:51 +03:00
Github Actions 9e4669b8b4 [CI Skip] release/beta 6.4.3-1
skip-checks: true
2021-10-19 06:09:04 +00:00
Jaco 1e383315e2 Adjust convertSiV0toV1 import location (#4082) 2021-10-19 08:47:06 +03:00
Github Actions 6f66eb2b66 [CI Skip] release/beta 6.4.3-0
skip-checks: true
2021-10-19 05:37:39 +00:00
Jaco 0864340ae2 Adjust xcm version mapping utility (#4081) 2021-10-19 08:21:07 +03:00
309 changed files with 26456 additions and 18399 deletions
+5 -1
View File
@@ -40,4 +40,8 @@
6.0.5
6.1.2
6.4.2
6.4.2
6.5.2
6.7.2
6.9.2
6.10.2
+1 -1
View File
@@ -2,7 +2,7 @@ name: 'Lock Threads'
on:
schedule:
- cron: '30 1/2 * * *'
- cron: '10 1 * * *'
jobs:
lock:
+1 -1
View File
@@ -1,7 +1,7 @@
name: 'Close stale issues and PRs'
on:
schedule:
- cron: '30 2/2 * * *'
- cron: '55 1 * * *'
jobs:
stale:
+147
View File
@@ -1,5 +1,152 @@
# CHANGELOG
## 6.10.2 Nov 30, 2021
Upgrade priority: Low. Aligns TS augmentation and decoration with older behavior for ALL_CAPS identifiers.
Changes:
- Adjust augmentation interface consistency with top-level declarations
- Update `@polkadot/util` to 8.0.4 with adjusted `stringCamelCase`
## 6.10.1 Nov 29, 2021
Upgrade priority: Low. Recommended for users of `HttpProvider` and for chains generating types using TS augmentation.
Changes:
- Fix for HttpProvider init (RPC sections with only subscriptions)
- Re-order imports in lookup type augmentation interfaces
- Bump static metadata for latest Substrate, Polkadot & Kusama
## 6.9.2 Nov 22, 2021
Upgrade priority: Medium. Pulls in `@polkadot/util-crypto` fix for TS projects.
Changes:
- Update `@polkadot/util-crypto` with TS compilation work-around
## 6.9.1 Nov 21, 2021
Upgrade priority: Medium. Recommended for metadata v14 parachains. For TS users, the package now support TypeScript 4.5.2 and allows extraction of user types from metadata v14.
Contributed:
- Lookup TS generation for all metadata v14 chains (Thanks to https://github.com/savudani8)
- Update `BeefySignedCommitment` type (Thanks to https://github.com/czl1378)
Changes:
- Adjust runtime `*::{Call, Event}` matching for metadata v14
- Adjust derive decoration with (optional) known methods
- Expose `*{Call, Event, Error}` TS types for metadata v14
- Align Option `.toJSON` output with Substrate input
- Optimize Enum, Struct, Option & Number decoding paths
- Ajust PascalCase conversions with function from util
- Prepare pre-v13 types for optional injection
- Adjustments for TS 4.5.2 support (flatten type infers)
## 6.8.1 Nov 11, 2021
Upgrade priority: Low. Recommended for chains with non-MultiSignature variants where `paymentInfo` is required.
Changes:
- Adjust `paymentInfo` signatures to cater for non-MultiSignature variants
- Remove `::generic::` from names & namespaces under metadata v14
- Add Polkadot 9122 upgrade block
- Cleanup Polkadot/Kusama/Westend/Rococo known types (>= v14 metadata)
- Internal `decorateMethod{Promise, Rx}` renamed to `to{Promise, Rx}Method`
- Add RPC provider-level LRU for historic requests
- Add optional known runtime version param to internal `rx.queryAt`
## 6.7.2 Nov 9, 2021
Upgrade priority: Low. Recommended for chains on metadata v14 with non-default `Address` implementations.
Changes:
- Detect `AccountId` & `Address` types via `SpRuntime*` definitions
- Adjust api-derive call ordering when using `.queryAt`
## 6.7.1 Nov 7, 2021
Upgrade priority: Low. Internal maintenance updates, focussed on internal optimizations.
Changelog:
- Optimize Extrinsic & block handling (Thanks to https://github.com/nazar-pc)
- Add `account::AccountId20` mapping (Thanks to https://github.com/joelamouche)
Changes:
- Use new-gen `voteLockingPeriod` in democracy derives (as available)
- Dynamically inject getters for `Extrinsic` payloads
- Optimize caching for complex constructed type classes per registry
- Convert metadata, rpc and api to use lazy decoration
- Split u8a decoding paths for `Vec` (different from general path)
- Keep track of initial u8a decoded length inside base Codecs
- Extract multi property assignments for `Struct`, `Set`, `Json` & `Enum`
- Move `PortableRegistry` location inside `@polkadot/types/metadata`
- Bump static metadata for latest Substrate, Polkadot & Kusama
## 6.6.1 Nov 1, 2021
Upgrade priority: Low. Internal maintenance updates.
Changes:
- Fix construction for `palletVersion` keys with correct prefix
- Add Polkadot `EthereumAddress` as a known `PortableRegistry` override
- De-dupe `PortableRegistry` namespace splitting operations
- Optimize internal `AbstractArray` & `Struct` u8a decoding
- Shortcut `Struct` construction from `Struct` instance
- Use internal `lookupName` in `createClass` (allows deeply recursive lookups)
- Codec `toHex()` will now correctly return the TS `HexString` type
- Update known upgrade blocks for Westend & Kusama
- Bump static metadata for latest Substrate, Polkadot & Kusama
## 6.5.2 Oct 26, 2021
Upgrade priority: Low. Recommended for users with `.at` queries on unknown blocks.
Changes:
- Adjust `toHuman` on `Call` to return names & (not only) values
- Allow for optional known `RuntimeVersion` to short-circuit `api.at`
- Ensure `Struct` decodes fully on `null` input (equivalent to `undefined` & `{}`)
## 6.5.1 Oct 24, 2021
Upgrade priority: Low. Internal maintenance upgrades.
Contributed:
- Add `Auction` to Polkadot pre-0.9.11 `ProxyType` (Thanks to https://github.com/wirednkod)
Changes:
- Ecah module now exposes the Substrate-added `palletVersion` storage item
- Adjust Websocket `maxReceivedFrameSize` under Node
- `TypeDef` structures now contain the `typeName` from metadata v14 on fields
- Fix browser bundle imports for xcm-mapping (move to `types-known`)
- Expose all extracted type names in `PortableRegistry`
- Adjust `toJSON` (Ascii) output detection on `Raw`
- Adjust `api.rpc.*.*.raw(..args)` return to the actual over-the-wire JSON result
- Remove `api.rpc.*.*.json(..args)` since it now overlaps with new `.raw`
- Bump static metadata for latest Substrate, Polkadot & Kusama
## 6.4.2 Oct 18, 2021
Upgrade priority: Low. Recommended for Westmint runtime 500+
+20 -14
View File
@@ -1,40 +1,46 @@
{
"repository": "https://github.com/polkadot-js/api",
"author": "Jaco Greeff <jacogr@gmail.com>",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api#readme",
"license": "Apache-2",
"packageManager": "yarn@3.0.1",
"private": true,
"repository": {
"type": "git",
"url": "https://github.com/polkadot-js/api.git"
},
"sideEffects": false,
"type": "commonjs",
"version": "6.10.2",
"workspaces": [
"packages/*"
],
"resolutions": {
"typescript": "^4.4.4"
},
"scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts",
"build:extra": "(cd packages/typegen && copyfiles scripts/* build)",
"build:interfaces": "polkadot-types-internal-interfaces",
"build:release": "polkadot-ci-ghact-build",
"build:rollup": "polkadot-exec-rollup --config",
"docs:metadata": "polkadot-types-internal-metadata",
"chain:info": "polkadot-types-chain-info",
"lint": "polkadot-dev-run-lint",
"clean": "polkadot-dev-clean-build",
"docs:metadata": "polkadot-types-internal-metadata",
"lint": "polkadot-dev-run-lint",
"postinstall": "polkadot-dev-yarn-only",
"test": "polkadot-dev-run-test --coverage --forceExit --runInBand --testPathIgnorePatterns e2e",
"test:one": "polkadot-dev-run-test --detectOpenHandles --forceExit",
"test:watch": "polkadot-dev-run-test --watch"
},
"devDependencies": {
"@babel/core": "^7.15.8",
"@babel/register": "^7.15.3",
"@babel/runtime": "^7.15.4",
"@polkadot/dev": "^0.63.3",
"@polkadot/ts": "^0.4.9",
"@babel/core": "^7.16.0",
"@babel/register": "^7.16.0",
"@babel/runtime": "^7.16.3",
"@polkadot/dev": "^0.63.33",
"@polkadot/ts": "^0.4.15",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^27.0.2",
"@types/jest": "^27.0.3",
"copyfiles": "^2.4.1"
},
"version": "6.4.2",
"packageManager": "yarn@3.0.1"
"resolutions": {
"typescript": "^4.5.2"
}
}
+22 -18
View File
@@ -1,28 +1,32 @@
{
"name": "@polkadot/api-contract",
"version": "6.4.2",
"type": "module",
"author": "Jaco Greeff <jacogr@gmail.com>",
"bugs": "https://github.com/polkadot-js/api/issues",
"contributors": [],
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
"engines": {
"node": ">=14.0.0"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"license": "Apache-2.0",
"maintainers": [],
"name": "@polkadot/api-contract",
"repository": {
"directory": "packages/api-contract",
"type": "git",
"url": "https://github.com/polkadot-js/api.git"
},
"sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"engines": {
"node": ">=14.0.0"
},
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"type": "module",
"version": "6.10.2",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.15.4",
"@polkadot/api": "6.4.2",
"@polkadot/types": "6.4.2",
"@polkadot/util": "^7.5.1",
"@babel/runtime": "^7.16.3",
"@polkadot/api": "6.10.2",
"@polkadot/types": "6.10.2",
"@polkadot/util": "^8.0.4",
"rxjs": "^7.4.0"
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Bytes } from '@polkadot/types';
import type { Bytes, PortableRegistry } from '@polkadot/types';
import type { ChainProperties, ContractConstructorSpec, ContractEventSpec, ContractMessageParamSpec, ContractMessageSpec, ContractMetadataLatest, ContractProjectInfo } from '@polkadot/types/interfaces';
import type { AnyJson, Codec, Registry } from '@polkadot/types/types';
import type { AbiConstructor, AbiEvent, AbiMessage, AbiParam, DecodedEvent, DecodedMessage } from '../types';
@@ -45,7 +45,7 @@ function parseJson (json: AnyJson, chainProperties?: ChainProperties): [AnyJson,
const latest = metadata.isV0
? toLatest(registry, metadata.asV0)
: metadata.asV1;
const lookup = registry.createType('PortableRegistry', { types: latest.types });
const lookup = registry.createType<PortableRegistry>('PortableRegistry', { types: latest.types });
// attach the lookup to the registry - now the types are known
registry.setLookup(lookup);
+1 -1
View File
@@ -4,7 +4,7 @@
import type { ContractMetadataLatest, ContractMetadataV0 } from '@polkadot/types/interfaces';
import type { Registry } from '@polkadot/types/types';
import { convertSiV0toV1 } from '@polkadot/types/generic/PortableRegistry';
import { convertSiV0toV1 } from '@polkadot/types';
export function toLatest (registry: Registry, v0: ContractMetadataV0): ContractMetadataLatest {
return registry.createType('ContractMetadataLatest', {
+2 -1
View File
@@ -23,7 +23,8 @@ export abstract class Base<ApiType extends ApiTypes> {
this.api = api;
this._decorateMethod = decorateMethod;
assert(!!(api && api.isConnected && api.tx && api.tx.contracts && Object.keys(api.tx.contracts).length), 'Your API has not been initialized correctly and it not decorated with the runtime interfaces for contracts as retrieved from the on-chain runtime');
assert(!!(api && api.isConnected && api.tx), 'Your API has not been initialized correctly and is not connected to a chain');
assert(!!(api.tx.contracts && Object.keys(api.tx.contracts).length), 'You need to connect to a chain with a runtime that supports contracts');
assert(isFunction(api.tx.contracts.instantiateWithCode), 'You need to connect to a chain with a runtime with a V3 contracts module. The runtime does not expose api.tx.contracts.instantiateWithCode');
}
+4 -4
View File
@@ -6,7 +6,7 @@ import type { AnyJson } from '@polkadot/types/types';
import fs from 'fs';
import path from 'path';
import { decorateMethodPromise } from '@polkadot/api';
import { toPromiseMethod } from '@polkadot/api';
import v0contractFlipper from '../../test/contracts/ink/v0/flipper.contract.json';
import v0abiFlipper from '../../test/contracts/ink/v0/flipper.json';
@@ -19,19 +19,19 @@ const v0wasmFlipper = fs.readFileSync(path.join(__dirname, '../../test/contracts
describe('Code', (): void => {
it('can construct with an individual ABI/WASM combo', (): void => {
expect(
() => new Code(mockApi, v0abiFlipper as AnyJson, v0wasmFlipper, decorateMethodPromise)
() => new Code(mockApi, v0abiFlipper as AnyJson, v0wasmFlipper, toPromiseMethod)
).not.toThrow();
});
it('can construct with an .contract ABI (v0)', (): void => {
expect(
() => new Code(mockApi, v0contractFlipper as AnyJson, null, decorateMethodPromise)
() => new Code(mockApi, v0contractFlipper as AnyJson, null, toPromiseMethod)
).not.toThrow();
});
it.only('can construct with an .contract ABI (v1)', (): void => {
expect(
() => new Code(mockApi, v1contractFlipper as AnyJson, null, decorateMethodPromise)
() => new Code(mockApi, v1contractFlipper as AnyJson, null, toPromiseMethod)
).not.toThrow();
});
});
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-contract', version: '6.4.2' };
export const packageInfo = { name: '@polkadot/api-contract', version: '6.10.2' };
@@ -4,13 +4,13 @@
import type { Hash } from '@polkadot/types/interfaces';
import type { AnyJson } from '@polkadot/types/types';
import { ApiPromise, decorateMethodPromise } from '@polkadot/api';
import { ApiPromise, toPromiseMethod } from '@polkadot/api';
import { Abi } from '../Abi';
import { Blueprint as BaseBlueprint } from '../base';
export class Blueprint extends BaseBlueprint<'promise'> {
constructor (api: ApiPromise, abi: AnyJson | Abi, codeHash: string | Hash) {
super(api, abi, codeHash, decorateMethodPromise);
super(api, abi, codeHash, toPromiseMethod);
}
}
+2 -2
View File
@@ -4,13 +4,13 @@
import type { ApiPromise } from '@polkadot/api';
import type { AnyJson } from '@polkadot/types/types';
import { decorateMethodPromise } from '@polkadot/api';
import { toPromiseMethod } from '@polkadot/api';
import { Abi } from '../Abi';
import { Code as BaseCode } from '../base';
export class Code extends BaseCode<'promise'> {
constructor (api: ApiPromise, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined) {
super(api, abi, wasm, decorateMethodPromise);
super(api, abi, wasm, toPromiseMethod);
}
}
@@ -4,13 +4,13 @@
import type { AccountId } from '@polkadot/types/interfaces';
import type { AnyJson } from '@polkadot/types/types';
import { ApiPromise, decorateMethodPromise } from '@polkadot/api';
import { ApiPromise, toPromiseMethod } from '@polkadot/api';
import { Abi } from '../Abi';
import { Contract as BaseContract } from '../base';
export class Contract extends BaseContract<'promise'> {
constructor (api: ApiPromise, abi: AnyJson | Abi, address: string | AccountId) {
super(api, abi, address, decorateMethodPromise);
super(api, abi, address, toPromiseMethod);
}
}
+2 -2
View File
@@ -4,13 +4,13 @@
import type { Hash } from '@polkadot/types/interfaces';
import type { AnyJson } from '@polkadot/types/types';
import { ApiRx, decorateMethodRx } from '@polkadot/api';
import { ApiRx, toRxMethod } from '@polkadot/api';
import { Abi } from '../Abi';
import { Blueprint as BaseBlueprint } from '../base';
export class Blueprint extends BaseBlueprint<'rxjs'> {
constructor (api: ApiRx, abi: AnyJson | Abi, codeHash: string | Hash) {
super(api, abi, codeHash, decorateMethodRx);
super(api, abi, codeHash, toRxMethod);
}
}
+2 -2
View File
@@ -4,13 +4,13 @@
import type { ApiRx } from '@polkadot/api';
import type { AnyJson } from '@polkadot/types/types';
import { decorateMethodRx } from '@polkadot/api';
import { toRxMethod } from '@polkadot/api';
import { Abi } from '../Abi';
import { Code as BaseCode } from '../base';
export class Code extends BaseCode<'rxjs'> {
constructor (api: ApiRx, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined) {
super(api, abi, wasm, decorateMethodRx);
super(api, abi, wasm, toRxMethod);
}
}
+2 -2
View File
@@ -4,13 +4,13 @@
import type { AccountId } from '@polkadot/types/interfaces';
import type { AnyJson } from '@polkadot/types/types';
import { ApiRx, decorateMethodRx } from '@polkadot/api';
import { ApiRx, toRxMethod } from '@polkadot/api';
import { Abi } from '../Abi';
import { Contract as BaseContract } from '../base';
export class Contract extends BaseContract<'rxjs'> {
constructor (api: ApiRx, abi: AnyJson | Abi, address: string | AccountId) {
super(api, abi, address, decorateMethodRx);
super(api, abi, address, toRxMethod);
}
}
@@ -18,6 +18,7 @@
"lookupIndex": 1,
"lookupName": "RecursiveMyEnum",
"type": "Lookup1",
"typeName": "MyEnum",
"index": 1,
"name": "B"
}
+26 -22
View File
@@ -1,34 +1,38 @@
{
"name": "@polkadot/api-derive",
"version": "6.4.2",
"type": "module",
"author": "Jaco Greeff <jacogr@gmail.com>",
"bugs": "https://github.com/polkadot-js/api/issues",
"contributors": [],
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"engines": {
"node": ">=14.0.0"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"license": "Apache-2.0",
"maintainers": [],
"name": "@polkadot/api-derive",
"repository": {
"directory": "packages/api-derive",
"type": "git",
"url": "https://github.com/polkadot-js/api.git"
},
"sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"engines": {
"node": ">=14.0.0"
},
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"type": "module",
"version": "6.10.2",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.15.4",
"@polkadot/api": "6.4.2",
"@polkadot/rpc-core": "6.4.2",
"@polkadot/types": "6.4.2",
"@polkadot/util": "^7.5.1",
"@polkadot/util-crypto": "^7.5.1",
"@babel/runtime": "^7.16.3",
"@polkadot/api": "6.10.2",
"@polkadot/rpc-core": "6.10.2",
"@polkadot/types": "6.10.2",
"@polkadot/util": "^8.0.4",
"@polkadot/util-crypto": "^8.0.4",
"rxjs": "^7.4.0"
},
"devDependencies": {
"@polkadot/keyring": "^7.5.1",
"@polkadot/rpc-provider": "6.4.2"
"@polkadot/keyring": "^8.0.4",
"@polkadot/rpc-provider": "6.10.2"
}
}
+107 -35
View File
@@ -5,6 +5,7 @@ import type { Observable } from 'rxjs';
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AnyFunction } from '@polkadot/types/types';
import { lazyDeriveSection } from './util/lazy';
import * as accounts from './accounts';
import * as balances from './balances';
import * as bounties from './bounties';
@@ -29,9 +30,12 @@ export * from './type';
interface Avail {
instances: string[];
methods: string[];
withDetect?: boolean;
}
export { lazyDeriveSection };
export const derive = { accounts, balances, bounties, chain, contracts, council, crowdloan, democracy, elections, imOnline, membership, parachains, session, society, staking, technicalCommittee, treasury, tx };
type DeriveSection<Section> = {
@@ -51,64 +55,132 @@ export type ExactDerive = DeriveAllSections<typeof derive>;
// Enable derive only if some of these modules are available
const checks: Record<string, Avail> = {
contracts: { instances: ['contracts'] },
council: { instances: ['council'], withDetect: true },
crowdloan: { instances: ['crowdloan'] },
democracy: { instances: ['democracy'] },
elections: { instances: ['phragmenElection', 'electionsPhragmen', 'elections', 'council'], withDetect: true },
imOnline: { instances: ['imOnline'] },
membership: { instances: ['membership'] },
parachains: { instances: ['parachains', 'registrar'] },
session: { instances: ['session'] },
society: { instances: ['society'] },
staking: { instances: ['staking'] },
technicalCommittee: { instances: ['technicalCommittee'], withDetect: true },
treasury: { instances: ['treasury'] }
contracts: {
instances: ['contracts'],
methods: []
},
council: {
instances: ['council'],
methods: [],
withDetect: true
},
crowdloan: {
instances: ['crowdloan'],
methods: []
},
democracy: {
instances: ['democracy'],
methods: []
},
elections: {
instances: ['phragmenElection', 'electionsPhragmen', 'elections', 'council'],
methods: [],
withDetect: true
},
imOnline: {
instances: ['imOnline'],
methods: []
},
membership: {
instances: ['membership'],
methods: []
},
parachains: {
instances: ['parachains', 'registrar'],
methods: []
},
session: {
instances: ['session'],
methods: []
},
society: {
instances: ['society'],
methods: []
},
staking: {
instances: ['staking'],
methods: ['erasRewardPoints']
},
technicalCommittee: {
instances: ['technicalCommittee'],
methods: [],
withDetect: true
},
treasury: {
instances: ['treasury'],
methods: []
}
};
function getModuleInstances (api: ApiInterfaceRx, specName: string, moduleName: string): string[] {
return api.registry.getModuleInstances(specName, moduleName) || [];
}
/**
* Returns an object that will inject `api` into all the functions inside
* `allSections`, and keep the object architecture of `allSections`.
*/
/** @internal */
function injectFunctions<AllSections> (instanceId: string, api: ApiInterfaceRx, allSections: AllSections): DeriveAllSections<AllSections> {
function injectFunctions (instanceId: string, api: ApiInterfaceRx, derives: DeriveCustom): ExactDerive {
const queryKeys = Object.keys(api.query);
const specName = api.runtimeVersion.specName.toString();
return Object
.keys(allSections)
.filter((sectionName) =>
!checks[sectionName] ||
checks[sectionName].instances.some((q) => queryKeys.includes(q)) ||
const filterQueryKeys = (q: string) =>
queryKeys.includes(q);
const filterInstances = (q: string) =>
getModuleInstances(api, specName, q).some(filterQueryKeys);
const filterMethods = (instances: string[]) =>
(m: string) =>
instances.some((q) =>
queryKeys.includes(q) &&
!!api.query[q][m]
);
const isIncluded = (s: string) => (
!checks[s] ||
(
(
checks[sectionName].withDetect &&
checks[sectionName].instances.some((q) =>
(api.registry.getModuleInstances(specName, q) || []).some((q) => queryKeys.includes(q))
checks[s].instances.some(filterQueryKeys) &&
(
!checks[s].methods.length ||
checks[s].methods.every(filterMethods(checks[s].instances))
)
) ||
(
checks[s].withDetect &&
checks[s].instances.some(filterInstances)
)
)
.reduce((derives, sectionName): DeriveAllSections<AllSections> => {
const section = allSections[sectionName as keyof AllSections];
);
derives[sectionName as keyof AllSections] = Object
.entries(section)
.reduce((methods, [methodName, creator]): DeriveSection<typeof section> => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call
methods[methodName as keyof typeof section] = creator(instanceId, api);
const getKeys = (section: string) =>
Object.keys(derives[section]);
return methods;
}, {} as DeriveSection<typeof section>);
const creator = (section: string, method: string) =>
derives[section][method](instanceId, api);
return derives;
}, {} as DeriveAllSections<AllSections>);
const result: Record<string, Record<string, AnyFunction>> = {};
const names = Object.keys(derives);
for (let i = 0; i < names.length; i++) {
const name = names[i];
if (isIncluded(name)) {
lazyDeriveSection(result, name, getKeys, creator);
}
}
return result as ExactDerive;
}
// FIXME The return type of this function should be {...ExactDerive, ...DeriveCustom}
// For now we just drop the custom derive typings
/** @internal */
export function decorateDerive (instanceId: string, api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
export function getAvailableDerives (instanceId: string, api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
return {
...injectFunctions(instanceId, api, derive),
...injectFunctions(instanceId, api, derive as DeriveCustom),
...injectFunctions(instanceId, api, custom)
};
}
+14 -11
View File
@@ -25,17 +25,20 @@ import { memo } from '../util';
*/
export function getBlock (instanceId: string, api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<SignedBlockExtended | undefined> {
return memo(instanceId, (blockHash: Uint8Array | string): Observable<SignedBlockExtended | undefined> =>
api.queryAt(blockHash).pipe(
switchMap((queryAt) =>
combineLatest([
api.rpc.chain.getBlock(blockHash),
queryAt.system.events(),
queryAt.session
? queryAt.session.validators()
: of([])
])
),
map(([signedBlock, events, validators]) =>
combineLatest([
api.rpc.chain.getBlock(blockHash),
api.queryAt(blockHash).pipe(
switchMap((queryAt) =>
combineLatest([
queryAt.system.events(),
queryAt.session
? queryAt.session.validators()
: of([])
])
)
)
]).pipe(
map(([signedBlock, [events, validators]]) =>
createSignedBlockExtended(api.registry, signedBlock, events, validators)
),
catchError((): Observable<undefined> =>
+9 -8
View File
@@ -25,17 +25,18 @@ import { memo } from '../util';
* console.log(`block #${number} was authored by ${author}`);
* ```
*/
export function getHeader (instanceId: string, api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<HeaderExtended | undefined> {
return memo(instanceId, (hash: Uint8Array | string): Observable<HeaderExtended | undefined> =>
api.queryAt(hash).pipe(
switchMap((queryAt) =>
combineLatest([
api.rpc.chain.getHeader(hash),
export function getHeader (instanceId: string, api: ApiInterfaceRx): (blockHash: Uint8Array | string) => Observable<HeaderExtended | undefined> {
return memo(instanceId, (blockHash: Uint8Array | string): Observable<HeaderExtended | undefined> =>
combineLatest([
api.rpc.chain.getHeader(blockHash),
api.queryAt(blockHash).pipe(
switchMap((queryAt) =>
queryAt.session
? queryAt.session.validators()
: of([] as AccountId[])
])
),
)
)
]).pipe(
map(([header, validators]) =>
createHeaderExtended(header.registry, header, validators)
),
@@ -21,15 +21,15 @@ export function subscribeNewBlocks (instanceId: string, api: ApiInterfaceRx): ()
const blockHash = header.createdAtHash || header.hash;
// we get the block first, setting up the registry
return api.queryAt(blockHash).pipe(
switchMap((queryAt) =>
combineLatest([
of(header),
api.rpc.chain.getBlock(blockHash),
return combineLatest([
of(header),
api.rpc.chain.getBlock(blockHash),
api.queryAt(blockHash).pipe(
switchMap((queryAt) =>
queryAt.system.events()
])
)
)
);
]);
}),
map(([header, block, events]) =>
createSignedBlockExtended(block.registry, block, events, header.validators)
+10 -2
View File
@@ -25,7 +25,11 @@ function parseEnd (api: ApiInterfaceRx, vote: Vote, { approved, end }: Referendu
return [
end,
(approved.isTrue && vote.isAye) || (approved.isFalse && vote.isNay)
? end.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[vote.conviction.index]))
? end.add(
(
api.consts.democracy.voteLockingPeriod ||
api.consts.democracy.enactmentPeriod
).muln(LOCKUPS[vote.conviction.index]))
: BN_ZERO
];
}
@@ -50,7 +54,11 @@ function delegateLocks (api: ApiInterfaceRx, { balance, conviction, target }: Vo
referendumId,
unlockAt: unlockAt.isZero()
? unlockAt
: referendumEnd.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[conviction.index])),
: referendumEnd.add(
(
api.consts.democracy.voteLockingPeriod ||
api.consts.democracy.enactmentPeriod
).muln(LOCKUPS[conviction.index])),
vote: api.registry.createType('Vote', { aye: vote.isAye, conviction })
}))
)
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-derive', version: '6.4.2' };
export const packageInfo = { name: '@polkadot/api-derive', version: '6.10.2' };
+7 -6
View File
@@ -16,13 +16,14 @@ interface Result {
export function events (instanceId: string, api: ApiInterfaceRx): (at: Hash) => Observable<Result> {
return memo(instanceId, (blockHash: Hash) =>
api.queryAt(blockHash).pipe(
switchMap((queryAt) =>
combineLatest([
api.rpc.chain.getBlock(blockHash),
combineLatest([
api.rpc.chain.getBlock(blockHash),
api.queryAt(blockHash).pipe(
switchMap((queryAt) =>
queryAt.system.events()
])
),
)
)
]).pipe(
map(([block, events]): Result => ({ block, events }))
)
);
+16 -13
View File
@@ -32,20 +32,23 @@ function nextNonce (api: ApiInterfaceRx, address: string): Observable<Index> {
function signingHeader (api: ApiInterfaceRx): Observable<Header> {
return combineLatest([
api.rpc.chain.getHeader(),
api.rpc.chain.getFinalizedHead()
]).pipe(
switchMap(([bestHeader, finHash]) =>
// retrieve the headers - in the case of the current block, we use the parent
// to minimize (not completely remove) the impact that forks do have on the system
// (when at genesis, just return the current header as the last known)
bestHeader.parentHash.isEmpty
? of([bestHeader, bestHeader])
: combineLatest([
api.rpc.chain.getHeader(bestHeader.parentHash),
api.rpc.chain.getHeader(finHash)
])
api.rpc.chain.getHeader().pipe(
switchMap((header) =>
// check for chains at genesis (until block 1 is produced, e.g. 6s), since
// we do need to allow transactions at chain start (also dev/seal chains)
header.parentHash.isEmpty
? of(header)
// in the case of the current block, we use the parent to minimize the
// impact of forks on the system, but not completely remove it
: api.rpc.chain.getHeader(header.parentHash)
)
),
api.rpc.chain.getFinalizedHead().pipe(
switchMap((hash) =>
api.rpc.chain.getHeader(hash)
)
)
]).pipe(
map(([current, finalized]) =>
// determine the hash to use, current when lag > max, else finalized
current.number.unwrap().sub(finalized.number.unwrap()).gt(MAX_FINALITY_LAG)
@@ -8,14 +8,14 @@ import type { ApprovalFlag } from '@polkadot/types/interfaces/elections';
export function approvalFlagsToBools (flags: Vec<ApprovalFlag> | ApprovalFlag[]): boolean[] {
const bools: boolean[] = [];
flags.forEach((flag: ApprovalFlag): void => {
const str = flag.toString(2);
for (let i = 0; i < flags.length; i++) {
const str = flags[i].toString(2);
// read from lowest bit to highest
for (const bit of str.split('').reverse()) {
bools.push(!!parseInt(bit, 10));
}
});
}
// slice off trailing "false" values, as in substrate
const lastApproval = bools.lastIndexOf(true);
+2 -4
View File
@@ -10,10 +10,8 @@ export const deriveMapCache: DeriveCache = {
mapCache.delete(key);
},
forEach: (cb: (key: string, value: any) => void): void => {
const entries = mapCache.entries();
for (const entry in entries) {
cb(entry[0], entry[1]);
for (const [k, v] of mapCache.entries()) {
cb(k, v);
}
},
get: <T = any> (key: string): T | undefined => {
+16
View File
@@ -0,0 +1,16 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { lazyMethod, lazyMethods } from '@polkadot/util';
type LazySection <T> = Record<string, T>;
type LazyRecord <T> = Record<string, LazySection<T>>;
export function lazyDeriveSection <T> (result: LazyRecord<T>, section: string, getKeys: (s: string) => string[], creator: (s: string, m: string) => T): void {
lazyMethod(result, section, () =>
lazyMethods({}, getKeys(section), (method: string) =>
creator(section, method)
)
);
}
+27 -23
View File
@@ -1,33 +1,37 @@
{
"name": "@polkadot/api",
"version": "6.4.2",
"type": "module",
"author": "Jaco Greeff <jacogr@gmail.com>",
"bugs": "https://github.com/polkadot-js/api/issues",
"contributors": [],
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
"engines": {
"node": ">=14.0.0"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"license": "Apache-2.0",
"maintainers": [],
"name": "@polkadot/api",
"repository": {
"directory": "packages/api",
"type": "git",
"url": "https://github.com/polkadot-js/api.git"
},
"sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"engines": {
"node": ">=14.0.0"
},
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"type": "module",
"version": "6.10.2",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.15.4",
"@polkadot/api-derive": "6.4.2",
"@polkadot/keyring": "^7.5.1",
"@polkadot/rpc-core": "6.4.2",
"@polkadot/rpc-provider": "6.4.2",
"@polkadot/types": "6.4.2",
"@polkadot/types-known": "6.4.2",
"@polkadot/util": "^7.5.1",
"@polkadot/util-crypto": "^7.5.1",
"@babel/runtime": "^7.16.3",
"@polkadot/api-derive": "6.10.2",
"@polkadot/keyring": "^8.0.4",
"@polkadot/rpc-core": "6.10.2",
"@polkadot/rpc-provider": "6.10.2",
"@polkadot/types": "6.10.2",
"@polkadot/types-known": "6.10.2",
"@polkadot/util": "^8.0.4",
"@polkadot/util-crypto": "^8.0.4",
"eventemitter3": "^4.0.7",
"rxjs": "^7.4.0"
}
+12 -11
View File
@@ -1,14 +1,14 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { ApiTypes } from '@polkadot/api/types';
import type { U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types';
import type { Perbill, Percent, Permill } from '@polkadot/types/interfaces/runtime';
import type { FrameSupportPalletId, FrameSupportWeightsRuntimeDbWeight, FrameSupportWeightsWeightToFeeCoefficient, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, PalletContractsSchedule, SpVersionRuntimeVersion } from '@polkadot/types/lookup';
import type { Codec } from '@polkadot/types/types';
declare module '@polkadot/api/types/consts' {
export interface AugmentedConsts<ApiType> {
import type { ApiTypes, AugmentedConst, QueryableModuleConsts } from '@polkadot/api/types';
import type { U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types';
import type { Perbill, Percent, Permill } from '@polkadot/types/interfaces/runtime';
import type { FrameSupportPalletId, FrameSupportWeightsRuntimeDbWeight, FrameSupportWeightsWeightToFeeCoefficient, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, PalletContractsSchedule, SpVersionRuntimeVersion } from '@polkadot/types/lookup';
import type { Codec } from '@polkadot/types/types';
export interface AugmentedConsts<ApiType extends ApiTypes> {
assets: {
/**
* The amount of funds that must be reserved when creating a new approval.
@@ -741,7 +741,7 @@ declare module '@polkadot/api/types/consts' {
* that the runtime should know about the prefix in order to make use of it as
* an identifier of the chain.
**/
ss58Prefix: u16 & AugmentedConst<ApiType>;
sS58Prefix: u16 & AugmentedConst<ApiType>;
/**
* Get the chain's current version.
**/
@@ -919,9 +919,10 @@ declare module '@polkadot/api/types/consts' {
**/
[key: string]: Codec;
};
}
} // AugmentedConsts
export interface QueryableConsts<ApiType extends ApiTypes> extends AugmentedConsts<ApiType> {
[key: string]: QueryableModuleConsts;
}
}
} // QueryableConsts
} // declare module
+14 -7
View File
@@ -1,10 +1,10 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { ApiTypes } from '@polkadot/api/types';
declare module '@polkadot/api/types/errors' {
export interface AugmentedErrors<ApiType> {
import type { ApiTypes, AugmentedError, ModuleErrors } from '@polkadot/api/types';
export interface AugmentedErrors<ApiType extends ApiTypes> {
assets: {
/**
* Invalid metadata given.
@@ -1172,7 +1172,9 @@ declare module '@polkadot/api/types/errors' {
**/
IncorrectSlashingSpans: AugmentedError<ApiType>;
/**
* Can not bond with value less than minimum required.
* Cannot have a validator or nominator role, with value less than the minimum defined by
* governance (see `MinValidatorBond` and `MinNominatorBond`). If unbonding is the
* intention, `chill` first to remove one's role as validator/nominator.
**/
InsufficientBond: AugmentedError<ApiType>;
/**
@@ -1237,6 +1239,10 @@ declare module '@polkadot/api/types/errors' {
[key: string]: AugmentedError<ApiType>;
};
system: {
/**
* The origin filter prevent the call to be dispatched.
**/
CallFiltered: AugmentedError<ApiType>;
/**
* Failed to extract the runtime version from the new runtime.
*
@@ -1515,9 +1521,10 @@ declare module '@polkadot/api/types/errors' {
**/
[key: string]: AugmentedError<ApiType>;
};
}
} // AugmentedErrors
export interface DecoratedErrors<ApiType extends ApiTypes> extends AugmentedErrors<ApiType> {
[key: string]: ModuleErrors<ApiType>;
}
}
} // DecoratedErrors
} // declare module
+119 -148
View File
@@ -1,44 +1,41 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { ApiTypes } from '@polkadot/api/types';
import type { Bytes, Null, Option, Result, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types';
import type { AccountId32, H256 } from '@polkadot/types/interfaces/runtime';
import type { FrameSupportTokensMiscBalanceStatus, FrameSupportWeightsDispatchInfo, NodeRuntimeProxyType, PalletDemocracyVoteThreshold, PalletElectionProviderMultiPhaseElectionCompute, PalletImOnlineSr25519AppSr25519Public, PalletMultisigTimepoint, PalletStakingExposure, SpFinalityGrandpaAppPublic, SpRuntimeDispatchError } from '@polkadot/types/lookup';
import type { ITuple } from '@polkadot/types/types';
declare module '@polkadot/api/types/events' {
export interface AugmentedEvents<ApiType> {
import type { ApiTypes, AugmentedEvent, ModuleEvents } from '@polkadot/api/types';
import type { Bytes, Null, Option, Result, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types';
import type { AccountId32, H256 } from '@polkadot/types/interfaces/runtime';
import type { FrameSupportTokensMiscBalanceStatus, FrameSupportWeightsDispatchInfo, NodeRuntimeProxyType, PalletDemocracyVoteThreshold, PalletElectionProviderMultiPhaseElectionCompute, PalletImOnlineSr25519AppSr25519Public, PalletMultisigTimepoint, PalletStakingExposure, SpFinalityGrandpaAppPublic, SpRuntimeDispatchError } from '@polkadot/types/lookup';
import type { ITuple } from '@polkadot/types/types';
export interface AugmentedEvents<ApiType extends ApiTypes> {
assets: {
/**
* An approval for account `delegate` was cancelled by `owner`.
* \[id, owner, delegate\]
**/
ApprovalCancelled: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32]>;
/**
* (Additional) funds have been approved for transfer to a destination account.
* \[asset_id, source, delegate, amount\]
**/
ApprovedTransfer: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32, u64]>;
ApprovedTransfer: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32, u128]>;
/**
* Some asset `asset_id` was frozen. \[asset_id\]
* Some asset `asset_id` was frozen.
**/
AssetFrozen: AugmentedEvent<ApiType, [u32]>;
/**
* An asset has had its attributes changed by the `Force` origin.
* \[id\]
**/
AssetStatusChanged: AugmentedEvent<ApiType, [u32]>;
/**
* Some asset `asset_id` was thawed. \[asset_id\]
* Some asset `asset_id` was thawed.
**/
AssetThawed: AugmentedEvent<ApiType, [u32]>;
/**
* Some assets were destroyed. \[asset_id, owner, balance\]
* Some assets were destroyed.
**/
Burned: AugmentedEvent<ApiType, [u32, AccountId32, u64]>;
Burned: AugmentedEvent<ApiType, [u32, AccountId32, u128]>;
/**
* Some asset class was created. \[asset_id, creator, owner\]
* Some asset class was created.
**/
Created: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32]>;
/**
@@ -46,47 +43,46 @@ declare module '@polkadot/api/types/events' {
**/
Destroyed: AugmentedEvent<ApiType, [u32]>;
/**
* Some asset class was force-created. \[asset_id, owner\]
* Some asset class was force-created.
**/
ForceCreated: AugmentedEvent<ApiType, [u32, AccountId32]>;
/**
* Some account `who` was frozen. \[asset_id, who\]
* Some account `who` was frozen.
**/
Frozen: AugmentedEvent<ApiType, [u32, AccountId32]>;
/**
* Some assets were issued. \[asset_id, owner, total_supply\]
* Some assets were issued.
**/
Issued: AugmentedEvent<ApiType, [u32, AccountId32, u64]>;
Issued: AugmentedEvent<ApiType, [u32, AccountId32, u128]>;
/**
* Metadata has been cleared for an asset. \[asset_id\]
* Metadata has been cleared for an asset.
**/
MetadataCleared: AugmentedEvent<ApiType, [u32]>;
/**
* New metadata has been set for an asset. \[asset_id, name, symbol, decimals, is_frozen\]
* New metadata has been set for an asset.
**/
MetadataSet: AugmentedEvent<ApiType, [u32, Bytes, Bytes, u8, bool]>;
/**
* The owner changed \[asset_id, owner\]
* The owner changed.
**/
OwnerChanged: AugmentedEvent<ApiType, [u32, AccountId32]>;
/**
* The management team changed \[asset_id, issuer, admin, freezer\]
* The management team changed.
**/
TeamChanged: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32, AccountId32]>;
/**
* Some account `who` was thawed. \[asset_id, who\]
* Some account `who` was thawed.
**/
Thawed: AugmentedEvent<ApiType, [u32, AccountId32]>;
/**
* Some assets were transferred. \[asset_id, from, to, amount\]
* Some assets were transferred.
**/
Transferred: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32, u64]>;
Transferred: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32, u128]>;
/**
* An `amount` was transferred in its entirety from `owner` to `destination` by
* the approved `delegate`.
* \[id, owner, delegate, destination\]
**/
TransferredApproved: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32, AccountId32, u64]>;
TransferredApproved: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32, AccountId32, u128]>;
/**
* Generic event
**/
@@ -94,7 +90,7 @@ declare module '@polkadot/api/types/events' {
};
bagsList: {
/**
* Moved an account from one bag to another. \[who, from, to\].
* Moved an account from one bag to another.
**/
Rebagged: AugmentedEvent<ApiType, [AccountId32, u64, u64]>;
/**
@@ -104,40 +100,47 @@ declare module '@polkadot/api/types/events' {
};
balances: {
/**
* A balance was set by root. \[who, free, reserved\]
* A balance was set by root.
**/
BalanceSet: AugmentedEvent<ApiType, [AccountId32, u128, u128]>;
/**
* Some amount was deposited (e.g. for transaction fees). \[who, deposit\]
* Some amount was deposited (e.g. for transaction fees).
**/
Deposit: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
* An account was removed whose balance was non-zero but below ExistentialDeposit,
* resulting in an outright loss. \[account, balance\]
* resulting in an outright loss.
**/
DustLost: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
* An account was created with some free balance. \[account, free_balance\]
* An account was created with some free balance.
**/
Endowed: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
* Some balance was reserved (moved from free to reserved). \[who, value\]
* Some balance was reserved (moved from free to reserved).
**/
Reserved: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
* Some balance was moved from the reserve of the first account to the second account.
* Final argument indicates the destination balance type.
* \[from, to, balance, destination_status\]
**/
ReserveRepatriated: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128, FrameSupportTokensMiscBalanceStatus]>;
/**
* Transfer succeeded. \[from, to, value\]
* Some amount was removed from the account (e.g. for misbehavior).
**/
Slashed: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
* Transfer succeeded.
**/
Transfer: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128]>;
/**
* Some balance was unreserved (moved from reserved to free). \[who, value\]
* Some balance was unreserved (moved from reserved to free).
**/
Unreserved: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
* Some amount was withdrawn from the account (e.g. for transaction fees).
**/
Withdraw: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
* Generic event
**/
@@ -145,31 +148,31 @@ declare module '@polkadot/api/types/events' {
};
bounties: {
/**
* A bounty is awarded to a beneficiary. \[index, beneficiary\]
* A bounty is awarded to a beneficiary.
**/
BountyAwarded: AugmentedEvent<ApiType, [u32, AccountId32]>;
/**
* A bounty proposal is funded and became active. \[index\]
* A bounty proposal is funded and became active.
**/
BountyBecameActive: AugmentedEvent<ApiType, [u32]>;
/**
* A bounty is cancelled. \[index\]
* A bounty is cancelled.
**/
BountyCanceled: AugmentedEvent<ApiType, [u32]>;
/**
* A bounty is claimed by beneficiary. \[index, payout, beneficiary\]
* A bounty is claimed by beneficiary.
**/
BountyClaimed: AugmentedEvent<ApiType, [u32, u128, AccountId32]>;
/**
* A bounty expiry is extended. \[index\]
* A bounty expiry is extended.
**/
BountyExtended: AugmentedEvent<ApiType, [u32]>;
/**
* New bounty proposal. \[index\]
* New bounty proposal.
**/
BountyProposed: AugmentedEvent<ApiType, [u32]>;
/**
* A bounty proposal was rejected; funds were slashed. \[index, bond\]
* A bounty proposal was rejected; funds were slashed.
**/
BountyRejected: AugmentedEvent<ApiType, [u32, u128]>;
/**
@@ -217,39 +220,32 @@ declare module '@polkadot/api/types/events' {
council: {
/**
* A motion was approved by the required threshold.
* \[proposal_hash\]
**/
Approved: AugmentedEvent<ApiType, [H256]>;
/**
* A proposal was closed because its threshold was reached or after its duration was up.
* \[proposal_hash, yes, no\]
**/
Closed: AugmentedEvent<ApiType, [H256, u32, u32]>;
/**
* A motion was not approved by the required threshold.
* \[proposal_hash\]
**/
Disapproved: AugmentedEvent<ApiType, [H256]>;
/**
* A motion was executed; result will be `Ok` if it returned without error.
* \[proposal_hash, result\]
**/
Executed: AugmentedEvent<ApiType, [H256, Result<Null, SpRuntimeDispatchError>]>;
/**
* A single member did some action; result will be `Ok` if it returned without error.
* \[proposal_hash, result\]
**/
MemberExecuted: AugmentedEvent<ApiType, [H256, Result<Null, SpRuntimeDispatchError>]>;
/**
* A motion (given hash) has been proposed (by given account) with a threshold (given
* `MemberCount`).
* \[account, proposal_index, proposal_hash, threshold\]
**/
Proposed: AugmentedEvent<ApiType, [AccountId32, u32, H256, u32]>;
/**
* A motion (given hash) has been voted on by given account, leaving
* a tally (yes votes and no votes given respectively as `MemberCount`).
* \[account, proposal_hash, voted, yes, no\]
**/
Voted: AugmentedEvent<ApiType, [AccountId32, H256, bool, u32, u32]>;
/**
@@ -259,19 +255,19 @@ declare module '@polkadot/api/types/events' {
};
democracy: {
/**
* A proposal \[hash\] has been blacklisted permanently.
* A proposal_hash has been blacklisted permanently.
**/
Blacklisted: AugmentedEvent<ApiType, [H256]>;
/**
* A referendum has been cancelled. \[ref_index\]
* A referendum has been cancelled.
**/
Cancelled: AugmentedEvent<ApiType, [u32]>;
/**
* An account has delegated their vote to another account. \[who, target\]
* An account has delegated their vote to another account.
**/
Delegated: AugmentedEvent<ApiType, [AccountId32, AccountId32]>;
/**
* A proposal has been enacted. \[ref_index, result\]
* A proposal has been enacted.
**/
Executed: AugmentedEvent<ApiType, [u32, Result<Null, SpRuntimeDispatchError>]>;
/**
@@ -279,56 +275,51 @@ declare module '@polkadot/api/types/events' {
**/
ExternalTabled: AugmentedEvent<ApiType, []>;
/**
* A proposal has been rejected by referendum. \[ref_index\]
* A proposal has been rejected by referendum.
**/
NotPassed: AugmentedEvent<ApiType, [u32]>;
/**
* A proposal has been approved by referendum. \[ref_index\]
* A proposal has been approved by referendum.
**/
Passed: AugmentedEvent<ApiType, [u32]>;
/**
* A proposal could not be executed because its preimage was invalid.
* \[proposal_hash, ref_index\]
**/
PreimageInvalid: AugmentedEvent<ApiType, [H256, u32]>;
/**
* A proposal could not be executed because its preimage was missing.
* \[proposal_hash, ref_index\]
**/
PreimageMissing: AugmentedEvent<ApiType, [H256, u32]>;
/**
* A proposal's preimage was noted, and the deposit taken. \[proposal_hash, who, deposit\]
* A proposal's preimage was noted, and the deposit taken.
**/
PreimageNoted: AugmentedEvent<ApiType, [H256, AccountId32, u128]>;
/**
* A registered preimage was removed and the deposit collected by the reaper.
* \[proposal_hash, provider, deposit, reaper\]
**/
PreimageReaped: AugmentedEvent<ApiType, [H256, AccountId32, u128, AccountId32]>;
/**
* A proposal preimage was removed and used (the deposit was returned).
* \[proposal_hash, provider, deposit\]
**/
PreimageUsed: AugmentedEvent<ApiType, [H256, AccountId32, u128]>;
/**
* A motion has been proposed by a public account. \[proposal_index, deposit\]
* A motion has been proposed by a public account.
**/
Proposed: AugmentedEvent<ApiType, [u32, u128]>;
/**
* A referendum has begun. \[ref_index, threshold\]
* A referendum has begun.
**/
Started: AugmentedEvent<ApiType, [u32, PalletDemocracyVoteThreshold]>;
/**
* A public proposal has been tabled for referendum vote. \[proposal_index, deposit,
* depositors\]
* A public proposal has been tabled for referendum vote.
**/
Tabled: AugmentedEvent<ApiType, [u32, u128, Vec<AccountId32>]>;
/**
* An \[account\] has cancelled a previous delegation operation.
* An account has cancelled a previous delegation operation.
**/
Undelegated: AugmentedEvent<ApiType, [AccountId32]>;
/**
* An external proposal has been vetoed. \[who, proposal_hash, until\]
* An external proposal has been vetoed.
**/
Vetoed: AugmentedEvent<ApiType, [AccountId32, H256, u32]>;
/**
@@ -374,7 +365,7 @@ declare module '@polkadot/api/types/events' {
};
elections: {
/**
* A \[candidate\] was slashed by \[amount\] due to failing to obtain a seat as member or
* A candidate was slashed by amount due to failing to obtain a seat as member or
* runner-up.
*
* Note that old members and runners-up are also candidates.
@@ -390,12 +381,12 @@ declare module '@polkadot/api/types/events' {
**/
EmptyTerm: AugmentedEvent<ApiType, []>;
/**
* A \[member\] has been removed. This should always be followed by either `NewTerm` or
* A member has been removed. This should always be followed by either `NewTerm` or
* `EmptyTerm`.
**/
MemberKicked: AugmentedEvent<ApiType, [AccountId32]>;
/**
* A new term with \[new_members\]. This indicates that enough candidates existed to run
* A new term with new_members. This indicates that enough candidates existed to run
* the election, not that enough have has been elected. The inner value must be examined
* for this purpose. A `NewTerm(\[\])` indicates that some candidates got their bond
* slashed and none were elected, whilst `EmptyTerm` means that no candidates existed to
@@ -407,7 +398,7 @@ declare module '@polkadot/api/types/events' {
**/
Renounced: AugmentedEvent<ApiType, [AccountId32]>;
/**
* A \[seat holder\] was slashed by \[amount\] by being forcefully removed from the set.
* A seat holder was slashed by amount by being forcefully removed from the set.
**/
SeatHolderSlashed: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
@@ -418,22 +409,18 @@ declare module '@polkadot/api/types/events' {
gilt: {
/**
* A bid was successfully placed.
* \[ who, amount, duration \]
**/
BidPlaced: AugmentedEvent<ApiType, [AccountId32, u128, u32]>;
/**
* A bid was successfully removed (before being accepted as a gilt).
* \[ who, amount, duration \]
**/
BidRetracted: AugmentedEvent<ApiType, [AccountId32, u128, u32]>;
/**
* A bid was accepted as a gilt. The balance may not be released until expiry.
* \[ index, expiry, who, amount \]
**/
GiltIssued: AugmentedEvent<ApiType, [u32, u32, AccountId32, u128]>;
/**
* An expired gilt has been thawed.
* \[ index, who, original_amount, additional_amount \]
**/
GiltThawed: AugmentedEvent<ApiType, [u32, AccountId32, u128, u128]>;
/**
@@ -443,7 +430,7 @@ declare module '@polkadot/api/types/events' {
};
grandpa: {
/**
* New authority set has been applied. \[authority_set\]
* New authority set has been applied.
**/
NewAuthorities: AugmentedEvent<ApiType, [Vec<ITuple<[SpFinalityGrandpaAppPublic, u64]>>]>;
/**
@@ -461,45 +448,44 @@ declare module '@polkadot/api/types/events' {
};
identity: {
/**
* A name was cleared, and the given balance returned. \[who, deposit\]
* A name was cleared, and the given balance returned.
**/
IdentityCleared: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
* A name was removed and the given balance slashed. \[who, deposit\]
* A name was removed and the given balance slashed.
**/
IdentityKilled: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
* A name was set or reset (which will remove all judgements). \[who\]
* A name was set or reset (which will remove all judgements).
**/
IdentitySet: AugmentedEvent<ApiType, [AccountId32]>;
/**
* A judgement was given by a registrar. \[target, registrar_index\]
* A judgement was given by a registrar.
**/
JudgementGiven: AugmentedEvent<ApiType, [AccountId32, u32]>;
/**
* A judgement was asked from a registrar. \[who, registrar_index\]
* A judgement was asked from a registrar.
**/
JudgementRequested: AugmentedEvent<ApiType, [AccountId32, u32]>;
/**
* A judgement request was retracted. \[who, registrar_index\]
* A judgement request was retracted.
**/
JudgementUnrequested: AugmentedEvent<ApiType, [AccountId32, u32]>;
/**
* A registrar was added. \[registrar_index\]
* A registrar was added.
**/
RegistrarAdded: AugmentedEvent<ApiType, [u32]>;
/**
* A sub-identity was added to an identity and the deposit paid. \[sub, main, deposit\]
* A sub-identity was added to an identity and the deposit paid.
**/
SubIdentityAdded: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128]>;
/**
* A sub-identity was removed from an identity and the deposit freed.
* \[sub, main, deposit\]
**/
SubIdentityRemoved: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128]>;
/**
* A sub-identity was cleared, and the given deposit repatriated from the
* main identity account to the sub-identity account. \[sub, main, deposit\]
* main identity account to the sub-identity account.
**/
SubIdentityRevoked: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128]>;
/**
@@ -513,11 +499,11 @@ declare module '@polkadot/api/types/events' {
**/
AllGood: AugmentedEvent<ApiType, []>;
/**
* A new heartbeat was received from `AuthorityId` \[authority_id\]
* A new heartbeat was received from `AuthorityId`.
**/
HeartbeatReceived: AugmentedEvent<ApiType, [PalletImOnlineSr25519AppSr25519Public]>;
/**
* At the end of the session, at least one validator was found to be \[offline\].
* At the end of the session, at least one validator was found to be offline.
**/
SomeOffline: AugmentedEvent<ApiType, [Vec<ITuple<[AccountId32, PalletStakingExposure]>>]>;
/**
@@ -527,15 +513,15 @@ declare module '@polkadot/api/types/events' {
};
indices: {
/**
* A account index was assigned. \[index, who\]
* A account index was assigned.
**/
IndexAssigned: AugmentedEvent<ApiType, [AccountId32, u32]>;
/**
* A account index has been freed up (unassigned). \[index\]
* A account index has been freed up (unassigned).
**/
IndexFreed: AugmentedEvent<ApiType, [u32]>;
/**
* A account index has been frozen to its current account ID. \[index, who\]
* A account index has been frozen to its current account ID.
**/
IndexFrozen: AugmentedEvent<ApiType, [u32, AccountId32]>;
/**
@@ -568,19 +554,18 @@ declare module '@polkadot/api/types/events' {
multisig: {
/**
* A multisig operation has been approved by someone.
* \[approving, timepoint, multisig, call_hash\]
**/
MultisigApproval: AugmentedEvent<ApiType, [AccountId32, PalletMultisigTimepoint, AccountId32, U8aFixed]>;
/**
* A multisig operation has been cancelled. \[cancelling, timepoint, multisig, call_hash\]
* A multisig operation has been cancelled.
**/
MultisigCancelled: AugmentedEvent<ApiType, [AccountId32, PalletMultisigTimepoint, AccountId32, U8aFixed]>;
/**
* A multisig operation has been executed. \[approving, timepoint, multisig, call_hash\]
* A multisig operation has been executed.
**/
MultisigExecuted: AugmentedEvent<ApiType, [AccountId32, PalletMultisigTimepoint, AccountId32, U8aFixed, Result<Null, SpRuntimeDispatchError>]>;
/**
* A new multisig operation has begun. \[approving, multisig, call_hash\]
* A new multisig operation has begun.
**/
NewMultisig: AugmentedEvent<ApiType, [AccountId32, AccountId32, U8aFixed]>;
/**
@@ -602,21 +587,20 @@ declare module '@polkadot/api/types/events' {
};
proxy: {
/**
* An announcement was placed to make a call in the future. \[real, proxy, call_hash\]
* An announcement was placed to make a call in the future.
**/
Announced: AugmentedEvent<ApiType, [AccountId32, AccountId32, H256]>;
/**
* Anonymous account has been created by new proxy with given
* disambiguation index and proxy type. \[anonymous, who, proxy_type,
* disambiguation_index\]
* disambiguation index and proxy type.
**/
AnonymousCreated: AugmentedEvent<ApiType, [AccountId32, AccountId32, NodeRuntimeProxyType, u16]>;
/**
* A proxy was added. \[delegator, delegatee, proxy_type, delay\]
* A proxy was added.
**/
ProxyAdded: AugmentedEvent<ApiType, [AccountId32, AccountId32, NodeRuntimeProxyType, u32]>;
/**
* A proxy was executed correctly, with the given \[result\].
* A proxy was executed correctly, with the given.
**/
ProxyExecuted: AugmentedEvent<ApiType, [Result<Null, SpRuntimeDispatchError>]>;
/**
@@ -627,30 +611,26 @@ declare module '@polkadot/api/types/events' {
recovery: {
/**
* Lost account has been successfully recovered by rescuer account.
* \[lost, rescuer\]
**/
AccountRecovered: AugmentedEvent<ApiType, [AccountId32, AccountId32]>;
/**
* A recovery process for lost account by rescuer account has been closed.
* \[lost, rescuer\]
**/
RecoveryClosed: AugmentedEvent<ApiType, [AccountId32, AccountId32]>;
/**
* A recovery process has been set up for an \[account\].
* A recovery process has been set up for an account.
**/
RecoveryCreated: AugmentedEvent<ApiType, [AccountId32]>;
/**
* A recovery process has been initiated for lost account by rescuer account.
* \[lost, rescuer\]
**/
RecoveryInitiated: AugmentedEvent<ApiType, [AccountId32, AccountId32]>;
/**
* A recovery process has been removed for an \[account\].
* A recovery process has been removed for an account.
**/
RecoveryRemoved: AugmentedEvent<ApiType, [AccountId32]>;
/**
* A recovery process for lost account by rescuer account has been vouched for by sender.
* \[lost, rescuer, sender\]
**/
RecoveryVouched: AugmentedEvent<ApiType, [AccountId32, AccountId32, AccountId32]>;
/**
@@ -678,7 +658,7 @@ declare module '@polkadot/api/types/events' {
};
session: {
/**
* New session has happened. Note that the argument is the \[session_index\], not the
* New session has happened. Note that the argument is the session index, not the
* block number as the type might suggest.
**/
NewSession: AugmentedEvent<ApiType, [u32]>;
@@ -875,39 +855,32 @@ declare module '@polkadot/api/types/events' {
technicalCommittee: {
/**
* A motion was approved by the required threshold.
* \[proposal_hash\]
**/
Approved: AugmentedEvent<ApiType, [H256]>;
/**
* A proposal was closed because its threshold was reached or after its duration was up.
* \[proposal_hash, yes, no\]
**/
Closed: AugmentedEvent<ApiType, [H256, u32, u32]>;
/**
* A motion was not approved by the required threshold.
* \[proposal_hash\]
**/
Disapproved: AugmentedEvent<ApiType, [H256]>;
/**
* A motion was executed; result will be `Ok` if it returned without error.
* \[proposal_hash, result\]
**/
Executed: AugmentedEvent<ApiType, [H256, Result<Null, SpRuntimeDispatchError>]>;
/**
* A single member did some action; result will be `Ok` if it returned without error.
* \[proposal_hash, result\]
**/
MemberExecuted: AugmentedEvent<ApiType, [H256, Result<Null, SpRuntimeDispatchError>]>;
/**
* A motion (given hash) has been proposed (by given account) with a threshold (given
* `MemberCount`).
* \[account, proposal_index, proposal_hash, threshold\]
**/
Proposed: AugmentedEvent<ApiType, [AccountId32, u32, H256, u32]>;
/**
* A motion (given hash) has been voted on by given account, leaving
* a tally (yes votes and no votes given respectively as `MemberCount`).
* \[account, proposal_hash, voted, yes, no\]
**/
Voted: AugmentedEvent<ApiType, [AccountId32, H256, bool, u32, u32]>;
/**
@@ -947,23 +920,23 @@ declare module '@polkadot/api/types/events' {
};
tips: {
/**
* A new tip suggestion has been opened. \[tip_hash\]
* A new tip suggestion has been opened.
**/
NewTip: AugmentedEvent<ApiType, [H256]>;
/**
* A tip suggestion has been closed. \[tip_hash, who, payout\]
* A tip suggestion has been closed.
**/
TipClosed: AugmentedEvent<ApiType, [H256, AccountId32, u128]>;
/**
* A tip suggestion has reached threshold and is closing. \[tip_hash\]
* A tip suggestion has reached threshold and is closing.
**/
TipClosing: AugmentedEvent<ApiType, [H256]>;
/**
* A tip suggestion has been retracted. \[tip_hash\]
* A tip suggestion has been retracted.
**/
TipRetracted: AugmentedEvent<ApiType, [H256]>;
/**
* A tip suggestion has been slashed. \[tip_hash, finder, deposit\]
* A tip suggestion has been slashed.
**/
TipSlashed: AugmentedEvent<ApiType, [H256, AccountId32, u128]>;
/**
@@ -1028,97 +1001,91 @@ declare module '@polkadot/api/types/events' {
/**
* An approval for a `delegate` account to transfer the `instance` of an asset `class` was
* cancelled by its `owner`.
* \[ class, instance, owner, delegate \]
**/
ApprovalCancelled: AugmentedEvent<ApiType, [u32, u32, AccountId32, AccountId32]>;
/**
* An `instance` of an asset `class` has been approved by the `owner` for transfer by a
* `delegate`.
* \[ class, instance, owner, delegate \]
**/
ApprovedTransfer: AugmentedEvent<ApiType, [u32, u32, AccountId32, AccountId32]>;
/**
* An asset `class` has had its attributes changed by the `Force` origin.
* \[ class \]
**/
AssetStatusChanged: AugmentedEvent<ApiType, [u32]>;
/**
* Attribute metadata has been cleared for an asset class or instance.
* \[ class, maybe_instance, key, maybe_value \]
**/
AttributeCleared: AugmentedEvent<ApiType, [u32, Option<u32>, Bytes]>;
/**
* New attribute metadata has been set for an asset class or instance.
* \[ class, maybe_instance, key, value \]
**/
AttributeSet: AugmentedEvent<ApiType, [u32, Option<u32>, Bytes, Bytes]>;
/**
* An asset `instance` was destroyed. \[ class, instance, owner \]
* An asset `instance` was destroyed.
**/
Burned: AugmentedEvent<ApiType, [u32, u32, AccountId32]>;
/**
* Some asset `class` was frozen. \[ class \]
* Some asset `class` was frozen.
**/
ClassFrozen: AugmentedEvent<ApiType, [u32]>;
/**
* Metadata has been cleared for an asset class. \[ class \]
* Metadata has been cleared for an asset class.
**/
ClassMetadataCleared: AugmentedEvent<ApiType, [u32]>;
/**
* New metadata has been set for an asset class. \[ class, data, is_frozen \]
* New metadata has been set for an asset class.
**/
ClassMetadataSet: AugmentedEvent<ApiType, [u32, Bytes, bool]>;
/**
* Some asset `class` was thawed. \[ class \]
* Some asset `class` was thawed.
**/
ClassThawed: AugmentedEvent<ApiType, [u32]>;
/**
* An asset class was created. \[ class, creator, owner \]
* An asset class was created.
**/
Created: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32]>;
/**
* An asset `class` was destroyed. \[ class \]
* An asset `class` was destroyed.
**/
Destroyed: AugmentedEvent<ApiType, [u32]>;
/**
* An asset class was force-created. \[ class, owner \]
* An asset class was force-created.
**/
ForceCreated: AugmentedEvent<ApiType, [u32, AccountId32]>;
/**
* Some asset `instance` was frozen. \[ class, instance \]
* Some asset `instance` was frozen.
**/
Frozen: AugmentedEvent<ApiType, [u32, u32]>;
/**
* An asset `instance` was issued. \[ class, instance, owner \]
* An asset `instance` was issued.
**/
Issued: AugmentedEvent<ApiType, [u32, u32, AccountId32]>;
/**
* Metadata has been cleared for an asset instance. \[ class, instance \]
* Metadata has been cleared for an asset instance.
**/
MetadataCleared: AugmentedEvent<ApiType, [u32, u32]>;
/**
* New metadata has been set for an asset instance.
* \[ class, instance, data, is_frozen \]
**/
MetadataSet: AugmentedEvent<ApiType, [u32, u32, Bytes, bool]>;
/**
* The owner changed \[ class, new_owner \]
* The owner changed.
**/
OwnerChanged: AugmentedEvent<ApiType, [u32, AccountId32]>;
/**
* Metadata has been cleared for an asset instance. \[ class, successful_instances \]
* Metadata has been cleared for an asset instance.
**/
Redeposited: AugmentedEvent<ApiType, [u32, Vec<u32>]>;
/**
* The management team changed \[ class, issuer, admin, freezer \]
* The management team changed.
**/
TeamChanged: AugmentedEvent<ApiType, [u32, AccountId32, AccountId32, AccountId32]>;
/**
* Some asset `instance` was thawed. \[ class, instance \]
* Some asset `instance` was thawed.
**/
Thawed: AugmentedEvent<ApiType, [u32, u32]>;
/**
* An asset `instance` was transferred. \[ class, instance, from, to \]
* An asset `instance` was transferred.
**/
Transferred: AugmentedEvent<ApiType, [u32, u32, AccountId32, AccountId32]>;
/**
@@ -1133,9 +1100,13 @@ declare module '@polkadot/api/types/events' {
BatchCompleted: AugmentedEvent<ApiType, []>;
/**
* Batch of dispatches did not complete fully. Index of first failing dispatch given, as
* well as the error. \[index, error\]
* well as the error.
**/
BatchInterrupted: AugmentedEvent<ApiType, [u32, SpRuntimeDispatchError]>;
/**
* A call was dispatched. \[result\]
**/
DispatchedAs: AugmentedEvent<ApiType, [Result<Null, SpRuntimeDispatchError>]>;
/**
* A single item within a Batch of dispatches has completed with no error.
**/
@@ -1153,7 +1124,6 @@ declare module '@polkadot/api/types/events' {
/**
* The amount vested has been updated. This could indicate a change in funds available.
* The balance given is the amount which is left unvested (and thus locked).
* \[account, unvested\]
**/
VestingUpdated: AugmentedEvent<ApiType, [AccountId32, u128]>;
/**
@@ -1161,9 +1131,10 @@ declare module '@polkadot/api/types/events' {
**/
[key: string]: AugmentedEvent<ApiType>;
};
}
} // AugmentedEvents
export interface DecoratedEvents<ApiType extends ApiTypes> extends AugmentedEvents<ApiType> {
[key: string]: ModuleEvents<ApiType>;
}
}
} // DecoratedEvents
} // declare module
+28 -13
View File
@@ -1,14 +1,14 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { ApiTypes } from '@polkadot/api/types';
import type { BTreeMap, Bytes, Data, Null, Option, U8aFixed, Vec, WrapperOpaque, bool, u128, u32, u64, u8 } from '@polkadot/types';
import type { AccountId32, Call, H256, Perbill, Percent } from '@polkadot/types/interfaces/runtime';
import type { FrameSupportWeightsPerDispatchClassU64, FrameSystemAccountInfo, FrameSystemEventRecord, FrameSystemLastRuntimeUpgradeInfo, FrameSystemPhase, NodeRuntimeSessionKeys, PalletAssetsApproval, PalletAssetsAssetBalance, PalletAssetsAssetDetails, PalletAssetsAssetMetadata, PalletAuthorshipUncleEntryItem, PalletBagsListListBag, PalletBagsListListNode, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesReleases, PalletBalancesReserveData, PalletBountiesBounty, PalletCollectiveVotes, PalletContractsStorageDeletedContract, PalletContractsStorageRawContractInfo, PalletContractsWasmPrefabWasmModule, PalletDemocracyPreimageStatus, PalletDemocracyReferendumInfo, PalletDemocracyReleases, PalletDemocracyVoteThreshold, PalletDemocracyVoteVoting, PalletElectionProviderMultiPhasePhase, PalletElectionProviderMultiPhaseReadySolution, PalletElectionProviderMultiPhaseRoundSnapshot, PalletElectionProviderMultiPhaseSignedSignedSubmission, PalletElectionProviderMultiPhaseSolutionOrSnapshotSize, PalletElectionsPhragmenSeatHolder, PalletElectionsPhragmenVoter, PalletGiltActiveGilt, PalletGiltActiveGiltsTotal, PalletGiltGiltBid, PalletGrandpaStoredPendingChange, PalletGrandpaStoredState, PalletIdentityRegistrarInfo, PalletIdentityRegistration, PalletImOnlineBoundedOpaqueNetworkState, PalletImOnlineSr25519AppSr25519Public, PalletLotteryLotteryConfig, PalletMultisigMultisig, PalletProxyAnnouncement, PalletProxyProxyDefinition, PalletRecoveryActiveRecovery, PalletRecoveryRecoveryConfig, PalletSchedulerReleases, PalletSchedulerScheduledV2, PalletSocietyBid, PalletSocietyBidKind, PalletSocietyVote, PalletSocietyVouchingStatus, PalletStakingActiveEraInfo, PalletStakingEraRewardPoints, PalletStakingExposure, PalletStakingForcing, PalletStakingNominations, PalletStakingReleases, PalletStakingRewardDestination, PalletStakingSlashingSlashingSpans, PalletStakingSlashingSpanRecord, PalletStakingStakingLedger, PalletStakingUnappliedSlash, PalletStakingValidatorPrefs, PalletTipsOpenTip, PalletTransactionPaymentReleases, PalletTransactionStorageTransactionInfo, PalletTreasuryProposal, PalletUniquesClassDetails, PalletUniquesClassMetadata, PalletUniquesInstanceDetails, PalletUniquesInstanceMetadata, PalletVestingReleases, PalletVestingVestingInfo, SpConsensusBabeAppPublic, SpConsensusBabeBabeEpochConfiguration, SpConsensusBabeDigestsNextConfigDescriptor, SpCoreCryptoKeyTypeId, SpRuntimeGenericDigest, SpStakingOffenceOffenceDetails } from '@polkadot/types/lookup';
import type { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
declare module '@polkadot/api/types/storage' {
export interface AugmentedQueries<ApiType> {
import type { ApiTypes, AugmentedQuery, QueryableModuleStorage, QueryableStorageEntry } from '@polkadot/api/types';
import type { BTreeMap, Bytes, Data, Null, Option, U8aFixed, Vec, WrapperOpaque, bool, u128, u32, u64, u8 } from '@polkadot/types';
import type { AccountId32, Call, H256, Perbill, Percent } from '@polkadot/types/interfaces/runtime';
import type { FrameSupportWeightsPerDispatchClassU64, FrameSystemAccountInfo, FrameSystemEventRecord, FrameSystemLastRuntimeUpgradeInfo, FrameSystemPhase, NodeRuntimeSessionKeys, PalletAssetsApproval, PalletAssetsAssetBalance, PalletAssetsAssetDetails, PalletAssetsAssetMetadata, PalletAuthorshipUncleEntryItem, PalletBagsListListBag, PalletBagsListListNode, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesReleases, PalletBalancesReserveData, PalletBountiesBounty, PalletCollectiveVotes, PalletContractsStorageDeletedContract, PalletContractsStorageRawContractInfo, PalletContractsWasmPrefabWasmModule, PalletDemocracyPreimageStatus, PalletDemocracyReferendumInfo, PalletDemocracyReleases, PalletDemocracyVoteThreshold, PalletDemocracyVoteVoting, PalletElectionProviderMultiPhasePhase, PalletElectionProviderMultiPhaseReadySolution, PalletElectionProviderMultiPhaseRoundSnapshot, PalletElectionProviderMultiPhaseSignedSignedSubmission, PalletElectionProviderMultiPhaseSolutionOrSnapshotSize, PalletElectionsPhragmenSeatHolder, PalletElectionsPhragmenVoter, PalletGiltActiveGilt, PalletGiltActiveGiltsTotal, PalletGiltGiltBid, PalletGrandpaStoredPendingChange, PalletGrandpaStoredState, PalletIdentityRegistrarInfo, PalletIdentityRegistration, PalletImOnlineBoundedOpaqueNetworkState, PalletImOnlineSr25519AppSr25519Public, PalletLotteryLotteryConfig, PalletMultisigMultisig, PalletProxyAnnouncement, PalletProxyProxyDefinition, PalletRecoveryActiveRecovery, PalletRecoveryRecoveryConfig, PalletSchedulerReleases, PalletSchedulerScheduledV2, PalletSocietyBid, PalletSocietyBidKind, PalletSocietyVote, PalletSocietyVouchingStatus, PalletStakingActiveEraInfo, PalletStakingEraRewardPoints, PalletStakingExposure, PalletStakingForcing, PalletStakingNominations, PalletStakingReleases, PalletStakingRewardDestination, PalletStakingSlashingSlashingSpans, PalletStakingSlashingSpanRecord, PalletStakingStakingLedger, PalletStakingUnappliedSlash, PalletStakingValidatorPrefs, PalletTipsOpenTip, PalletTransactionPaymentReleases, PalletTransactionStorageTransactionInfo, PalletTreasuryProposal, PalletUniquesClassDetails, PalletUniquesClassMetadata, PalletUniquesInstanceDetails, PalletUniquesInstanceMetadata, PalletVestingReleases, PalletVestingVestingInfo, SpAuthorityDiscoveryAppPublic, SpConsensusBabeAppPublic, SpConsensusBabeBabeEpochConfiguration, SpConsensusBabeDigestsNextConfigDescriptor, SpCoreCryptoKeyTypeId, SpRuntimeDigest, SpStakingOffenceOffenceDetails } from '@polkadot/types/lookup';
import type { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
export interface AugmentedQueries<ApiType extends ApiTypes> {
assets: {
/**
* The number of units of assets held by any given account.
@@ -33,6 +33,20 @@ declare module '@polkadot/api/types/storage' {
**/
[key: string]: QueryableStorageEntry<ApiType>;
};
authorityDiscovery: {
/**
* Keys of the current authority set.
**/
keys: AugmentedQuery<ApiType, () => Observable<Vec<SpAuthorityDiscoveryAppPublic>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Keys of the next authority set.
**/
nextKeys: AugmentedQuery<ApiType, () => Observable<Vec<SpAuthorityDiscoveryAppPublic>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Generic query
**/
[key: string]: QueryableStorageEntry<ApiType>;
};
authorship: {
/**
* Author of current block.
@@ -135,7 +149,7 @@ declare module '@polkadot/api/types/storage' {
/**
* Randomness under construction.
*
* We make a tradeoff between storage accesses and list length.
* We make a trade-off between storage accesses and list length.
* We store the under-construction randomness in segments of up to
* `UNDER_CONSTRUCTION_SEGMENT_LENGTH`.
*
@@ -155,7 +169,7 @@ declare module '@polkadot/api/types/storage' {
};
bagsList: {
/**
* How many ids are registered.
* Counter for the related counted storage map
**/
counterForListNodes: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
@@ -1149,7 +1163,7 @@ declare module '@polkadot/api/types/storage' {
/**
* Digest of the current block, also part of the block header.
**/
digest: AugmentedQuery<ApiType, () => Observable<SpRuntimeGenericDigest>, []> & QueryableStorageEntry<ApiType, []>;
digest: AugmentedQuery<ApiType, () => Observable<SpRuntimeDigest>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The number of events in the `Events<T>` list.
**/
@@ -1400,9 +1414,10 @@ declare module '@polkadot/api/types/storage' {
**/
[key: string]: QueryableStorageEntry<ApiType>;
};
}
} // AugmentedQueries
export interface QueryableStorage<ApiType extends ApiTypes> extends AugmentedQueries<ApiType> {
[key: string]: QueryableModuleStorage<ApiType>;
}
}
} // QueryableStorage
} // declare module
+25 -23
View File
@@ -1,28 +1,29 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { Bytes, HashMap, Json, Metadata, Null, Option, StorageKey, Text, U256, U64, Vec, bool, u32, u64 } from '@polkadot/types';
import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';
import type { BeefySignedCommitment } from '@polkadot/types/interfaces/beefy';
import type { BlockHash } from '@polkadot/types/interfaces/chain';
import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { ContractCallRequest, ContractExecResult, ContractInstantiateResult, InstantiateRequest } from '@polkadot/types/interfaces/contracts';
import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthCallRequest, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { MmrLeafProof } from '@polkadot/types/interfaces/mmr';
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { RpcMethods } from '@polkadot/types/interfaces/rpc';
import type { AccountId, BlockNumber, H160, H256, H64, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import type { ReadProof, RuntimeVersion, TraceBlockResponse } from '@polkadot/types/interfaces/state';
import type { ApplyExtrinsicResult, ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo, SyncState } from '@polkadot/types/interfaces/system';
import type { AnyNumber, Codec, IExtrinsic, Observable } from '@polkadot/types/types';
declare module '@polkadot/rpc-core/types.jsonrpc' {
import type { AugmentedRpc } from '@polkadot/api/types';
import type { Bytes, HashMap, Json, Metadata, Null, Option, StorageKey, Text, U256, U64, Vec, bool, u32, u64 } from '@polkadot/types';
import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';
import type { BeefySignedCommitment } from '@polkadot/types/interfaces/beefy';
import type { BlockHash } from '@polkadot/types/interfaces/chain';
import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { ContractCallRequest, ContractExecResult, ContractInstantiateResult, InstantiateRequest } from '@polkadot/types/interfaces/contracts';
import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthCallRequest, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { MmrLeafProof } from '@polkadot/types/interfaces/mmr';
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { RpcMethods } from '@polkadot/types/interfaces/rpc';
import type { AccountId, BlockNumber, H160, H256, H64, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import type { ReadProof, RuntimeVersion, TraceBlockResponse } from '@polkadot/types/interfaces/state';
import type { ApplyExtrinsicResult, ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo, SyncState } from '@polkadot/types/interfaces/system';
import type { AnyNumber, Codec, IExtrinsic, Observable } from '@polkadot/types/types';
export interface RpcInterface {
author: {
/**
@@ -556,5 +557,6 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
**/
sha3: AugmentedRpc<(data: Bytes | string | Uint8Array) => Observable<H256>>;
};
}
}
} // RpcInterface
} // declare module
+64 -49
View File
@@ -1,15 +1,15 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
import type { Bytes, Compact, Data, Option, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { AccountId32, Call, H256, MultiAddress, Perbill, Percent, Perquintill } from '@polkadot/types/interfaces/runtime';
import type { NodeRuntimeProxyType, NodeRuntimeSessionKeys, PalletAssetsDestroyWitness, PalletDemocracyConviction, PalletDemocracyVoteAccountVote, PalletElectionProviderMultiPhaseRawSolution, PalletElectionProviderMultiPhaseSolutionOrSnapshotSize, PalletElectionsPhragmenRenouncing, PalletIdentityBitFlags, PalletIdentityIdentityInfo, PalletIdentityJudgement, PalletImOnlineHeartbeat, PalletImOnlineSr25519AppSr25519Signature, PalletMultisigTimepoint, PalletSocietyJudgement, PalletStakingRewardDestination, PalletStakingValidatorPrefs, PalletUniquesDestroyWitness, PalletVestingVestingInfo, SpConsensusBabeDigestsNextConfigDescriptor, SpConsensusSlotsEquivocationProof, SpCoreChangesTrieChangesTrieConfiguration, SpFinalityGrandpaEquivocationProof, SpNposElectionsSupport, SpRuntimeGenericHeader, SpSessionMembershipProof, SpTransactionStorageProofTransactionStorageProof } from '@polkadot/types/lookup';
import type { AnyNumber, ITuple } from '@polkadot/types/types';
declare module '@polkadot/api/types/submittable' {
export interface AugmentedSubmittables<ApiType> {
import type { ApiTypes, AugmentedSubmittable, SubmittableExtrinsic, SubmittableExtrinsicFunction, SubmittableModuleExtrinsics } from '@polkadot/api/types';
import type { Bytes, Compact, Data, Option, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { AccountId32, Call, H256, MultiAddress, Perbill, Percent, Perquintill } from '@polkadot/types/interfaces/runtime';
import type { NodeRuntimeOriginCaller, NodeRuntimeProxyType, NodeRuntimeSessionKeys, PalletAssetsDestroyWitness, PalletDemocracyConviction, PalletDemocracyVoteAccountVote, PalletElectionProviderMultiPhaseRawSolution, PalletElectionProviderMultiPhaseSolutionOrSnapshotSize, PalletElectionsPhragmenRenouncing, PalletIdentityBitFlags, PalletIdentityIdentityInfo, PalletIdentityJudgement, PalletImOnlineHeartbeat, PalletImOnlineSr25519AppSr25519Signature, PalletMultisigTimepoint, PalletSocietyJudgement, PalletStakingRewardDestination, PalletStakingValidatorPrefs, PalletUniquesDestroyWitness, PalletVestingVestingInfo, SpConsensusBabeDigestsNextConfigDescriptor, SpConsensusSlotsEquivocationProof, SpFinalityGrandpaEquivocationProof, SpNposElectionsSupport, SpRuntimeHeader, SpSessionMembershipProof, SpTransactionStorageProofTransactionStorageProof } from '@polkadot/types/lookup';
import type { AnyNumber, ITuple } from '@polkadot/types/types';
export interface AugmentedSubmittables<ApiType extends ApiTypes> {
assets: {
/**
* Approve an amount of asset for transfer by a delegated third-party account.
@@ -33,7 +33,7 @@ declare module '@polkadot/api/types/submittable' {
*
* Weight: `O(1)`
**/
approveTransfer: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, delegate: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u64> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u64>]>;
approveTransfer: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, delegate: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u128>]>;
/**
* Reduce the balance of `who` by as much as possible up to `amount` assets of `id`.
*
@@ -51,7 +51,7 @@ declare module '@polkadot/api/types/submittable' {
* Weight: `O(1)`
* Modes: Post-existence of `who`; Pre & post Zombie-status of `who`.
**/
burn: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u64> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u64>]>;
burn: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u128>]>;
/**
* Cancel all of some asset approved for delegated transfer by a third-party account.
*
@@ -103,7 +103,7 @@ declare module '@polkadot/api/types/submittable' {
*
* Weight: `O(1)`
**/
create: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, admin: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, minBalance: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, u64]>;
create: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, admin: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, minBalance: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, u128]>;
/**
* Destroy a class of fungible assets.
*
@@ -149,7 +149,7 @@ declare module '@polkadot/api/types/submittable' {
*
* Weight: `O(1)`
**/
forceAssetStatus: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, owner: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, issuer: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, admin: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, freezer: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, minBalance: Compact<u64> | AnyNumber | Uint8Array, isSufficient: bool | boolean | Uint8Array, isFrozen: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, MultiAddress, MultiAddress, MultiAddress, Compact<u64>, bool, bool]>;
forceAssetStatus: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, owner: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, issuer: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, admin: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, freezer: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, minBalance: Compact<u128> | AnyNumber | Uint8Array, isSufficient: bool | boolean | Uint8Array, isFrozen: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, MultiAddress, MultiAddress, MultiAddress, Compact<u128>, bool, bool]>;
/**
* Cancel all of some asset approved for delegated transfer by a third-party account.
*
@@ -201,7 +201,7 @@ declare module '@polkadot/api/types/submittable' {
*
* Weight: `O(1)`
**/
forceCreate: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, owner: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, isSufficient: bool | boolean | Uint8Array, minBalance: Compact<u64> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, bool, Compact<u64>]>;
forceCreate: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, owner: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, isSufficient: bool | boolean | Uint8Array, minBalance: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, bool, Compact<u128>]>;
/**
* Force the metadata for an asset to some value.
*
@@ -240,7 +240,7 @@ declare module '@polkadot/api/types/submittable' {
* Modes: Pre-existence of `dest`; Post-existence of `source`; Account pre-existence of
* `dest`.
**/
forceTransfer: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, source: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, dest: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u64> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, MultiAddress, Compact<u64>]>;
forceTransfer: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, source: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, dest: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, MultiAddress, Compact<u128>]>;
/**
* Disallow further unprivileged transfers from an account.
*
@@ -280,7 +280,7 @@ declare module '@polkadot/api/types/submittable' {
* Weight: `O(1)`
* Modes: Pre-existing balance of `beneficiary`; Account pre-existence of `beneficiary`.
**/
mint: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, beneficiary: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u64> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u64>]>;
mint: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, beneficiary: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u128>]>;
/**
* Set the metadata for an asset.
*
@@ -360,7 +360,7 @@ declare module '@polkadot/api/types/submittable' {
* Modes: Pre-existence of `target`; Post-existence of sender; Account pre-existence of
* `target`.
**/
transfer: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, target: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u64> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u64>]>;
transfer: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, target: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u128>]>;
/**
* Transfer some asset balance from a previously delegated account to some third-party
* account.
@@ -381,7 +381,7 @@ declare module '@polkadot/api/types/submittable' {
*
* Weight: `O(1)`
**/
transferApproved: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, owner: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, destination: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u64> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, MultiAddress, Compact<u64>]>;
transferApproved: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, owner: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, destination: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, MultiAddress, Compact<u128>]>;
/**
* Move some assets from the sender account to another, keeping the sender account alive.
*
@@ -402,7 +402,7 @@ declare module '@polkadot/api/types/submittable' {
* Modes: Pre-existence of `target`; Post-existence of sender; Account pre-existence of
* `target`.
**/
transferKeepAlive: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, target: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u64> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u64>]>;
transferKeepAlive: AugmentedSubmittable<(id: Compact<u32> | AnyNumber | Uint8Array, target: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, MultiAddress, Compact<u128>]>;
/**
* Change the Owner of an asset.
*
@@ -425,7 +425,7 @@ declare module '@polkadot/api/types/submittable' {
/**
* Provide a set of uncles.
**/
setUncles: AugmentedSubmittable<(newUncles: Vec<SpRuntimeGenericHeader> | (SpRuntimeGenericHeader | { parentHash?: any; number?: any; stateRoot?: any; extrinsicsRoot?: any; digest?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Vec<SpRuntimeGenericHeader>]>;
setUncles: AugmentedSubmittable<(newUncles: Vec<SpRuntimeHeader> | (SpRuntimeHeader | { parentHash?: any; number?: any; stateRoot?: any; extrinsicsRoot?: any; digest?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Vec<SpRuntimeHeader>]>;
/**
* Generic tx
**/
@@ -871,6 +871,13 @@ declare module '@polkadot/api/types/submittable' {
* NOTE: Does not enforce the expected `MaxMembers` limit on the amount of members, but
* the weight estimations rely on it to estimate dispatchable weight.
*
* # WARNING:
*
* The `pallet-collective` can also be managed by logic outside of the pallet through the
* implementation of the trait [`ChangeMembers`].
* Any call to `set_members` must be careful that the member set doesn't get out of sync
* with other logic managing the member set.
*
* # <weight>
* ## Weight
* - `O(MP + N)` where:
@@ -2567,9 +2574,13 @@ declare module '@polkadot/api/types/submittable' {
session: {
/**
* Removes any session key(s) of the function caller.
*
* This doesn't take effect until the next session.
*
* The dispatch origin of this function must be signed.
* The dispatch origin of this function must be Signed and the account must be either be
* convertible to a validator ID using the chain's typical addressing system (this usually
* means being a controller account) or directly convertible into a validator ID (which
* usually means being a stash account).
*
* # <weight>
* - Complexity: `O(1)` in number of key types. Actual cost depends on the number of length
@@ -3152,22 +3163,18 @@ declare module '@polkadot/api/types/submittable' {
**/
payoutStakers: AugmentedSubmittable<(validatorStash: AccountId32 | string | Uint8Array, era: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32, u32]>;
/**
* Remove all data structure concerning a staker/stash once its balance is at the minimum.
* This is essentially equivalent to `withdraw_unbonded` except it can be called by anyone
* and the target `stash` must have no funds left beyond the ED.
* Remove all data structures concerning a staker/stash once it is at a state where it can
* be considered `dust` in the staking system. The requirements are:
*
* This can be called from any origin.
* 1. the `total_balance` of the stash is below existential deposit.
* 2. or, the `ledger.total` of the stash is below existential deposit.
*
* - `stash`: The stash account to reap. Its balance must be zero.
* The former can happen in cases like a slash; the latter when a fully unbonded account
* is still receiving staking rewards in `RewardDestination::Staked`.
*
* # <weight>
* Complexity: O(S) where S is the number of slashing spans on the account.
* DB Weight:
* - Reads: Stash Account, Bonded, Slashing Spans, Locks
* - Writes: Bonded, Slashing Spans (if S > 0), Ledger, Payee, Validators, Nominators,
* Stash Account, Locks
* - Writes Each: SpanSlash * S
* # </weight>
* It can be called by anyone, as long as `stash` meets the above requirements.
*
* Refunds the transaction fees upon successful execution.
**/
reapStash: AugmentedSubmittable<(stash: AccountId32 | string | Uint8Array, numSlashingSpans: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32, u32]>;
/**
@@ -3452,19 +3459,6 @@ declare module '@polkadot/api/types/submittable' {
* # </weight>
**/
remarkWithEvent: AugmentedSubmittable<(remark: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes]>;
/**
* Set the new changes trie configuration.
*
* # <weight>
* - `O(1)`
* - 1 storage write or delete (codec `O(1)`).
* - 1 call to `deposit_log`: Uses `append` API, so O(1)
* - Base Weight: 7.218 µs
* - DB Weight:
* - Writes: Changes Trie, System Digest
* # </weight>
**/
setChangesTrieConfig: AugmentedSubmittable<(changesTrieConfig: Option<SpCoreChangesTrieChangesTrieConfiguration> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Option<SpCoreChangesTrieChangesTrieConfiguration>]>;
/**
* Set the new runtime code.
*
@@ -3630,6 +3624,13 @@ declare module '@polkadot/api/types/submittable' {
* NOTE: Does not enforce the expected `MaxMembers` limit on the amount of members, but
* the weight estimations rely on it to estimate dispatchable weight.
*
* # WARNING:
*
* The `pallet-collective` can also be managed by logic outside of the pallet through the
* implementation of the trait [`ChangeMembers`].
* Any call to `set_members` must be careful that the member set doesn't get out of sync
* with other logic managing the member set.
*
* # <weight>
* ## Weight
* - `O(MP + N)` where:
@@ -4388,6 +4389,19 @@ declare module '@polkadot/api/types/submittable' {
* # </weight>
**/
batchAll: AugmentedSubmittable<(calls: Vec<Call> | (Call | { callIndex?: any; args?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Vec<Call>]>;
/**
* Dispatches a function call with a provided origin.
*
* The dispatch origin for this call must be _Root_.
*
* # <weight>
* - O(1).
* - Limited storage reads.
* - One DB write (event).
* - Weight of derivative `call` execution + T::WeightInfo::dispatch_as().
* # </weight>
**/
dispatchAs: AugmentedSubmittable<(asOrigin: NodeRuntimeOriginCaller | { system: any } | { Void: any } | { Council: any } | { TechnicalCommittee: any } | string | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [NodeRuntimeOriginCaller, Call]>;
/**
* Generic tx
**/
@@ -4498,10 +4512,11 @@ declare module '@polkadot/api/types/submittable' {
**/
[key: string]: SubmittableExtrinsicFunction<ApiType>;
};
}
} // AugmentedSubmittables
export interface SubmittableExtrinsics<ApiType extends ApiTypes> extends AugmentedSubmittables<ApiType> {
(extrinsic: Call | Extrinsic | Uint8Array | string): SubmittableExtrinsic<ApiType>;
[key: string]: SubmittableModuleExtrinsics<ApiType>;
}
}
} // SubmittableExtrinsics
} // declare module
+104 -87
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { DeriveCustom } from '@polkadot/api-derive';
import type { RpcInterface } from '@polkadot/rpc-core/types';
import type { Option, Raw, StorageKey, Text, u64 } from '@polkadot/types';
import type { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
@@ -9,20 +10,20 @@ import type { DecoratedMeta } from '@polkadot/types/metadata/decorate/types';
import type { StorageEntry } from '@polkadot/types/primitive/types';
import type { AnyFunction, AnyTuple, CallFunction, Codec, DefinitionRpc, DefinitionRpcSub, DetectCodec, IMethod, IStorageKey, Registry, RegistryError, RegistryTypes } from '@polkadot/types/types';
import type { SubmittableExtrinsic } from '../submittable/types';
import type { ApiDecoration, ApiInterfaceRx, ApiOptions, ApiTypes, AugmentedQuery, DecoratedErrors, DecoratedEvents, DecoratedRpc, DecoratedRpcSection, DecorateMethod, GenericStorageEntryFunction, PaginationOptions, QueryableConsts, QueryableModuleStorage, QueryableModuleStorageAt, QueryableStorage, QueryableStorageAt, QueryableStorageEntry, QueryableStorageEntryAt, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
import type { ApiDecoration, ApiInterfaceRx, ApiOptions, ApiTypes, AugmentedQuery, DecoratedErrors, DecoratedEvents, DecoratedRpc, DecorateMethod, GenericStorageEntryFunction, PaginationOptions, QueryableConsts, QueryableStorage, QueryableStorageEntry, QueryableStorageEntryAt, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics } from '../types';
import type { VersionedRegistry } from './types';
import { BehaviorSubject, combineLatest, from, map, of, switchMap, tap, toArray } from 'rxjs';
import { decorateDerive, ExactDerive } from '@polkadot/api-derive';
import { ExactDerive, getAvailableDerives } from '@polkadot/api-derive';
import { memo, RpcCore } from '@polkadot/rpc-core';
import { WsProvider } from '@polkadot/rpc-provider';
import { expandMetadata, Metadata, TypeRegistry, unwrapStorageType } from '@polkadot/types';
import { arrayChunk, arrayFlatten, assert, BN, BN_ZERO, compactStripLength, logger, u8aToHex } from '@polkadot/util';
import { arrayChunk, arrayFlatten, assert, BN, BN_ZERO, compactStripLength, lazyMethod, lazyMethods, logger, objectSpread, u8aToHex } from '@polkadot/util';
import { createSubmittable } from '../submittable';
import { augmentObject } from '../util/augmentObject';
import { decorateSections, DeriveAllSections } from '../util/decorate';
import { decorateDeriveSections, DeriveAllSections } from '../util/decorate';
import { extractStorageArgs } from '../util/validate';
import { Events } from './Events';
import { findCall, findError } from './find';
@@ -145,8 +146,8 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
this.#instanceId = `${++instanceCounter}`;
this.#registry = options.source?.registry || options.registry || new TypeRegistry();
this._rx.queryAt = (blockHash: Uint8Array | string) =>
from(this.at(blockHash)).pipe(map((a) => a.rx.query));
this._rx.queryAt = (blockHash: Uint8Array | string, knownVersion?: RuntimeVersion) =>
from(this.at(blockHash, knownVersion)).pipe(map((a) => a.rx.query));
this._rx.registry = this.#registry;
const thisProvider = options.source
@@ -163,7 +164,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
this._rx.hasSubscriptions = this._rpcCore.provider.hasSubscriptions;
}
public abstract at (blockHash: Uint8Array | string): Promise<ApiDecoration<ApiType>>;
public abstract at (blockHash: Uint8Array | string, knownVersion?: RuntimeVersion): Promise<ApiDecoration<ApiType>>;
/**
* @description Return the current used registry
@@ -200,7 +201,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
return this._rpcCore.provider.hasSubscriptions || !!this._rpcCore.state.queryStorageAt;
}
protected _createDecorated (registry: VersionedRegistry<ApiType>, fromEmpty?: boolean, blockHash?: Uint8Array | null, decoratedApi?: ApiDecoration<ApiType>): FullDecoration<ApiType> {
protected _createDecorated (registry: VersionedRegistry<ApiType>, fromEmpty: boolean, decoratedApi: ApiDecoration<ApiType> | null, blockHash?: Uint8Array): FullDecoration<ApiType> {
if (!decoratedApi) {
decoratedApi = {
consts: {},
@@ -218,18 +219,12 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
registry.decoratedMeta = expandMetadata(registry.registry, registry.metadata);
}
// adjust the versioned registry
const storage = this._decorateStorage(registry.decoratedMeta, this._decorateMethod, blockHash);
const storageRx = this._decorateStorage(registry.decoratedMeta, this._rxDecorateMethod, blockHash);
augmentObject('consts', registry.decoratedMeta.consts, decoratedApi.consts, fromEmpty);
augmentObject('errors', registry.decoratedMeta.errors, decoratedApi.errors, fromEmpty);
augmentObject('events', registry.decoratedMeta.events, decoratedApi.events, fromEmpty);
const storage = blockHash
? this._decorateStorageAt(registry.decoratedMeta, this._decorateMethod, blockHash)
: this._decorateStorage(registry.decoratedMeta, this._decorateMethod);
const storageRx = blockHash
? this._decorateStorageAt(registry.decoratedMeta, this._rxDecorateMethod, blockHash)
: this._decorateStorage(registry.decoratedMeta, this._rxDecorateMethod);
augmentObject('query', storage, decoratedApi.query, fromEmpty);
augmentObject('query', storageRx, decoratedApi.rx.query, fromEmpty);
@@ -247,7 +242,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
};
}
protected _injectMetadata (registry: VersionedRegistry<ApiType>, fromEmpty?: boolean): void {
protected _injectMetadata (registry: VersionedRegistry<ApiType>, fromEmpty = false): void {
// clear the decoration, we are redoing it here
if (fromEmpty || !registry.decoratedApi) {
registry.decoratedApi = {
@@ -262,7 +257,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
} as ApiDecoration<ApiType>;
}
const { decoratedApi, decoratedMeta } = this._createDecorated(registry, fromEmpty, null, registry.decoratedApi);
const { decoratedApi, decoratedMeta } = this._createDecorated(registry, fromEmpty, registry.decoratedApi);
this._consts = decoratedApi.consts;
this._errors = decoratedApi.errors;
@@ -270,12 +265,15 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
this._query = decoratedApi.query;
this._rx.query = decoratedApi.rx.query;
const tx = this._decorateExtrinsics(decoratedMeta, this._decorateMethod);
const rxtx = this._decorateExtrinsics(decoratedMeta, this._rxDecorateMethod);
if (fromEmpty || !this._extrinsics) {
this._extrinsics = this._decorateExtrinsics(decoratedMeta, this._decorateMethod);
this._rx.tx = this._decorateExtrinsics(decoratedMeta, this._rxDecorateMethod);
this._extrinsics = tx;
this._rx.tx = rxtx;
} else {
augmentObject('tx', this._decorateExtrinsics(decoratedMeta, this._decorateMethod), this._extrinsics, false);
augmentObject(null, this._decorateExtrinsics(decoratedMeta, this._rxDecorateMethod), this._rx.tx, false);
augmentObject('tx', tx, this._extrinsics, false);
augmentObject(null, rxtx, this._rx.tx, false);
}
augmentObject(null, decoratedMeta.consts, this._rx.consts, fromEmpty);
@@ -322,7 +320,11 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
protected _filterRpcMethods (exposed: string[]): void {
const hasResults = exposed.length !== 0;
const allKnown = [...this._rpcCore.mapping.entries()];
const allKeys = allKnown.reduce((allKeys: string[], [, { alias, endpoint, method, pubsub, section }]): string[] => {
const allKeys: string[] = [];
for (let i = 0; i < allKnown.length; i++) {
const [, { alias, endpoint, method, pubsub, section }] = allKnown[i];
allKeys.push(`${section}_${method}`);
if (pubsub) {
@@ -337,11 +339,10 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
if (endpoint) {
allKeys.push(endpoint);
}
}
return allKeys;
}, []);
const unknown = exposed.filter((k) => !allKeys.includes(k));
const deletion = allKnown.filter(([k]) => hasResults && !exposed.includes(k) && k !== 'rpc_methods');
const filterKey = (k: string) => !allKeys.includes(k);
const unknown = exposed.filter(filterKey);
if (unknown.length) {
l.warn(`RPC methods not decorated: ${unknown.join(', ')}`);
@@ -349,36 +350,56 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
// loop through all entries we have (populated in decorate) and filter as required
// only remove when we have results and method missing, or with no results if optional
deletion.forEach(([, { method, section }]): void => {
delete (this._rpc as Record<string, Record<string, unknown>>)[section][method];
delete (this._rx.rpc as Record<string, Record<string, unknown>>)[section][method];
});
for (let i = 0; i < allKnown.length; i++) {
const [k, { method, section }] = allKnown[i];
if (hasResults && !exposed.includes(k) && k !== 'rpc_methods') {
if ((this._rpc as Record<string, Record<string, unknown>>)[section]) {
delete (this._rpc as Record<string, Record<string, unknown>>)[section][method];
delete (this._rx.rpc as Record<string, Record<string, unknown>>)[section][method];
}
}
}
}
protected _decorateRpc<ApiType extends ApiTypes> (rpc: RpcCore & RpcInterface, decorateMethod: DecorateMethod<ApiType>, input: Partial<DecoratedRpc<ApiType, RpcInterface>> = {}): DecoratedRpc<ApiType, RpcInterface> {
return rpc.sections.reduce((out, _sectionName): DecoratedRpc<ApiType, RpcInterface> => {
const sectionName = _sectionName as keyof DecoratedRpc<ApiType, RpcInterface>;
const out: Record<string, Record<string, unknown>> = input;
const decorateFn = (section: string, method: string): unknown => {
const source = rpc[section as 'chain'][method as 'getHeader'];
const fn = decorateMethod(source, { methodName: method }) as Record<string, unknown>;
fn.meta = source.meta;
fn.raw = decorateMethod(source.raw, { methodName: method }) as unknown;
return fn;
};
for (let s = 0; s < rpc.sections.length; s++) {
const section = rpc.sections[s];
if (!Object.prototype.hasOwnProperty.call(out, section)) {
const methods = Object.keys(rpc[section as 'chain']);
const decorateInternal = (method: string) =>
decorateFn(section, method);
for (let m = 0; m < methods.length; m++) {
const method = methods[m];
if (!(out as Record<string, unknown>)[sectionName]) {
// out and section here are horrors to get right from a typing perspective :(
(out as Record<string, unknown>)[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]> => {
// skip subscriptions where we have a non-subscribe interface
if (this.hasSubscriptions || !(methodName.startsWith('subscribe') || methodName.startsWith('unsubscribe'))) {
(section as Record<string, unknown>)[methodName] = decorateMethod(method, { methodName }) as unknown;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(section as Record<string, { json: unknown }>)[methodName].json = decorateMethod(method.json, { methodName }) as unknown;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(section as Record<string, { raw: unknown }>)[methodName].raw = decorateMethod(method.raw, { methodName }) as unknown;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(section as Record<string, { meta: unknown }>)[methodName].meta = method.meta;
if (this.hasSubscriptions || !(method.startsWith('subscribe') || method.startsWith('unsubscribe'))) {
if (!Object.prototype.hasOwnProperty.call(out, section)) {
out[section] = {};
}
lazyMethod(out[section], method, decorateInternal);
}
return section;
}, {} as DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]>);
}
}
}
return out;
}, input as DecoratedRpc<ApiType, RpcInterface>);
return out as DecoratedRpc<ApiType, RpcInterface>;
}
// only be called if supportMulti is true
@@ -419,17 +440,20 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
}
protected _decorateExtrinsics<ApiType extends ApiTypes> ({ tx }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>): SubmittableExtrinsics<ApiType> {
const creator = createSubmittable(this._type, this._rx, decorateMethod);
const result = createSubmittable(this._type, this._rx, decorateMethod) as SubmittableExtrinsics<ApiType>;
return Object.entries(tx).reduce((out, [name, section]): SubmittableExtrinsics<ApiType> => {
out[name] = Object.entries(section).reduce((out, [name, method]): SubmittableModuleExtrinsics<ApiType> => {
out[name] = this._decorateExtrinsicEntry(method, creator);
const lazySection = (section: string) =>
lazyMethods({}, Object.keys(tx[section]), (method: string) =>
this._decorateExtrinsicEntry(tx[section][method], result)
);
return out;
}, {} as SubmittableModuleExtrinsics<ApiType>);
const sections = Object.keys(tx);
return out;
}, creator as SubmittableExtrinsics<ApiType>);
for (let i = 0; i < sections.length; i++) {
lazyMethod(result, sections[i], lazySection);
}
return result;
}
private _decorateExtrinsicEntry<ApiType extends ApiTypes> (method: CallFunction, creator: (value: Call | Uint8Array | string) => SubmittableExtrinsic<ApiType>): SubmittableExtrinsicFunction<ApiType> {
@@ -444,28 +468,23 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
return this._decorateFunctionMeta(method as unknown as MetaDecoration, decorated as unknown as MetaDecoration) as unknown as SubmittableExtrinsicFunction<ApiType>;
}
protected _decorateStorage<ApiType extends ApiTypes> ({ query }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> {
return Object.entries(query).reduce((out, [name, section]): QueryableStorage<ApiType> => {
out[name] = Object.entries(section).reduce((out, [name, method]): QueryableModuleStorage<ApiType> => {
out[name] = this._decorateStorageEntry(method, decorateMethod);
protected _decorateStorage<ApiType extends ApiTypes> ({ query, registry }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>, blockHash?: Uint8Array): QueryableStorage<ApiType> {
const result = {} as QueryableStorage<ApiType>;
return out;
}, {} as QueryableModuleStorage<ApiType>);
const lazySection = (section: string) =>
lazyMethods({}, Object.keys(query[section]), (method: string) =>
blockHash
? this._decorateStorageEntryAt(registry, query[section][method], decorateMethod, blockHash)
: this._decorateStorageEntry(query[section][method], decorateMethod)
);
return out;
}, {} as QueryableStorage<ApiType>);
}
const sections = Object.keys(query);
protected _decorateStorageAt<ApiType extends ApiTypes> ({ query, registry }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>, blockHash: Uint8Array): QueryableStorageAt<ApiType> {
return Object.entries(query).reduce((out, [name, section]): QueryableStorageAt<ApiType> => {
out[name] = Object.entries(section).reduce((out, [name, method]): QueryableModuleStorageAt<ApiType> => {
out[name] = this._decorateStorageEntryAt(registry, method, decorateMethod, blockHash);
for (let i = 0; i < sections.length; i++) {
lazyMethod(result, sections[i], lazySection);
}
return out;
}, {} as QueryableModuleStorageAt<ApiType>);
return out;
}, {} as QueryableStorageAt<ApiType>);
return result;
}
private _decorateStorageEntry<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): QueryableStorageEntry<ApiType> {
@@ -622,9 +641,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
return this._rpcCore.state
.queryStorage<[Option<Raw>]>([decorated.key(...args)], ...range)
.pipe(map((result: [Hash, [Option<Raw>]][]): [Hash, Codec][] =>
result.map(([blockHash, [value]]): [Hash, Codec] => [
result.map(([blockHash, [value]]) => [
blockHash,
this.createType(outputType, value.isSome ? value.unwrap().toHex() : undefined)
this.createType<Codec>(outputType, value.isSome ? value.unwrap().toHex() : undefined)
])
));
}
@@ -654,10 +673,11 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const queryCall = at
? (startKey: string) => this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_K, startKey, at)
: (startKey: string) => this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_K, startKey);
const setMeta = (key: StorageKey) => key.setMeta(meta, section, method);
return startSubject.pipe(
switchMap(queryCall),
map((keys) => keys.map((key) => key.setMeta(meta, section, method))),
map((keys) => keys.map(setMeta)),
tap((keys): void => {
setTimeout((): void => {
keys.length === PAGE_SIZE_K
@@ -674,9 +694,10 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
assert(iterKey && meta.type.isMap, 'keys can only be retrieved on maps');
const headKey = iterKey(...opts.args).toHex();
const setMeta = (key: StorageKey) => key.setMeta(meta, section, method);
return this._rpcCore.state.getKeysPaged(headKey, opts.pageSize, opts.startKey || headKey).pipe(
map((keys) => keys.map((key) => key.setMeta(meta, section, method)))
map((keys) => keys.map(setMeta))
);
}
@@ -714,19 +735,15 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
protected _decorateDeriveRx (decorateMethod: DecorateMethod<ApiType>): DeriveAllSections<'rxjs', ExactDerive> {
const specName = this._runtimeVersion?.specName.toString();
const derives = {
...this._options.derives,
...(this._options.typesBundle?.spec?.[specName || '']?.derives || {})
};
// Pull in derive from api-derive
const derive = decorateDerive(this.#instanceId, this._rx, derives);
const available = getAvailableDerives(this.#instanceId, this._rx, objectSpread<DeriveCustom>({}, this._options.derives, this._options.typesBundle?.spec?.[specName || '']?.derives));
return decorateSections<'rxjs', ExactDerive>(derive, decorateMethod);
return decorateDeriveSections<'rxjs', ExactDerive>(decorateMethod, available);
}
protected _decorateDerive (decorateMethod: DecorateMethod<ApiType>): DeriveAllSections<ApiType, ExactDerive> {
return decorateSections<ApiType, ExactDerive>(this._rx.derive, decorateMethod);
return decorateDeriveSections<ApiType, ExactDerive>(decorateMethod, this._rx.derive);
}
/**
+54 -31
View File
@@ -2,9 +2,9 @@
// SPDX-License-Identifier: Apache-2.0
import type { Observable, Subscription } from 'rxjs';
import type { RpcInterfaceMethod } from '@polkadot/rpc-core/types';
import type { Text } from '@polkadot/types';
import type { ChainProperties, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import type { ExtDef } from '@polkadot/types/extrinsic/signedExtensions/types';
import type { ChainProperties, Hash, RuntimeVersion, RuntimeVersionPartial } from '@polkadot/types/interfaces';
import type { Registry } from '@polkadot/types/types';
import type { BN } from '@polkadot/util';
import type { ApiBase, ApiDecoration, ApiOptions, ApiTypes, DecorateMethod } from '../types';
@@ -14,7 +14,7 @@ import { firstValueFrom, map, of, switchMap } from 'rxjs';
import { Metadata, TypeRegistry } from '@polkadot/types';
import { getSpecAlias, getSpecExtensions, getSpecHasher, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
import { assert, BN_ZERO, isUndefined, logger, stringify, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { assert, BN_ZERO, isUndefined, logger, objectSpread, stringify, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import { detectedCapabilities } from './capabilities';
@@ -24,6 +24,10 @@ const KEEPALIVE_INTERVAL = 10000;
const l = logger('api/init');
function textToString (t: Text): string {
return t.toString();
}
export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
#healthTimer: NodeJS.Timeout | null = null;
@@ -91,10 +95,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName);
}
registry.setMetadata(metadata, undefined, {
...getSpecExtensions(registry, chain, version.specName),
...(this._options.signedExtensions || {})
});
registry.setMetadata(metadata, undefined, objectSpread<ExtDef>({}, getSpecExtensions(registry, chain, version.specName), this._options.signedExtensions));
}
/**
@@ -112,13 +113,32 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
/**
* @description Returns a decorated API instance at a specific point in time
*/
public async at (blockHash: Uint8Array | string): Promise<ApiDecoration<ApiType>> {
public async at (blockHash: Uint8Array | string, knownVersion?: RuntimeVersion): Promise<ApiDecoration<ApiType>> {
const u8aHash = u8aToU8a(blockHash);
const registry = await this.getBlockRegistry(u8aHash);
const registry = await this.getBlockRegistry(u8aHash, knownVersion);
// always create a new decoration - since we are pointing to a specific hash, this
// means that all queries needs to use that hash (not a previous one already existing)
return this._createDecorated(registry, true, u8aHash).decoratedApi;
return this._createDecorated(registry, true, null, u8aHash).decoratedApi;
}
private _getBlockRegistryViaVersion (blockHash: Uint8Array, version?: RuntimeVersionPartial): VersionedRegistry<ApiType> | null {
if (version) {
// check for pre-existing registries. We also check specName, e.g. it
// could be changed like in Westmint with upgrade from shell -> westmint
const existingViaVersion = this.#registries.find(({ specName, specVersion }) =>
specName.eq(version.specName) &&
specVersion.eq(version.specVersion)
);
if (existingViaVersion) {
existingViaVersion.lastBlockHash = blockHash;
return existingViaVersion;
}
}
return null;
}
private async _getBlockRegistry (blockHash: Uint8Array): Promise<VersionedRegistry<ApiType>> {
@@ -130,7 +150,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
const header = this.registry.createType('HeaderPartial',
this._genesisHash.eq(blockHash)
? { number: BN_ZERO, parentHash: this._genesisHash }
: await firstValueFrom((this._rpcCore.chain.getHeader as RpcInterfaceMethod).json(blockHash))
: await firstValueFrom(this._rpcCore.chain.getHeader.raw(blockHash))
);
assert(!header.parentHash.isEmpty, 'Unable to retrieve header and parent from supplied hash');
@@ -140,26 +160,19 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
const version = this.registry.createType('RuntimeVersionPartial',
(firstVersion && (lastVersion || firstVersion.specVersion.eq(this._runtimeVersion.specVersion)))
? { specName: this._runtimeVersion.specName, specVersion: firstVersion.specVersion }
: await firstValueFrom((this._rpcCore.state.getRuntimeVersion as RpcInterfaceMethod).json(header.parentHash))
: await firstValueFrom(this._rpcCore.state.getRuntimeVersion.raw(header.parentHash))
);
// check for pre-existing registries. We also check specName, e.g. it
// could be changed like in Westmint with upgrade from shell -> westmint
const existingViaVersion = this.#registries.find(({ specName, specVersion }) =>
specName.eq(version.specName) &&
specVersion.eq(version.specVersion)
);
const existingViaVersion = this._getBlockRegistryViaVersion(blockHash, version);
if (existingViaVersion) {
existingViaVersion.lastBlockHash = blockHash;
return existingViaVersion;
}
// nothing has been found, construct new
const registry = new TypeRegistry(blockHash);
const metadata = new Metadata(registry,
await firstValueFrom((this._rpcCore.state.getMetadata as RpcInterfaceMethod).raw(header.parentHash))
await firstValueFrom(this._rpcCore.state.getMetadata.raw<string>(header.parentHash))
);
this._initRegistry(registry, this._runtimeChain as Text, version, metadata);
@@ -175,7 +188,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
/**
* @description Sets up a registry based on the block hash defined
*/
public async getBlockRegistry (blockHash: Uint8Array): Promise<VersionedRegistry<ApiType>> {
public async getBlockRegistry (blockHash: Uint8Array, knownVersion?: RuntimeVersion): Promise<VersionedRegistry<ApiType>> {
const existingViaHash = this.#registries.find(({ lastBlockHash }) =>
lastBlockHash && u8aEq(lastBlockHash, blockHash)
);
@@ -184,6 +197,12 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
return existingViaHash;
}
const existingViaVersion = this._getBlockRegistryViaVersion(blockHash, knownVersion);
if (existingViaVersion) {
return existingViaVersion;
}
const blockHashHex = u8aToHex(blockHash);
let waiting = this.#waitingRegistries[blockHashHex];
@@ -225,17 +244,21 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
this._runtimeChain = source.runtimeChain;
this._runtimeVersion = source.runtimeVersion;
const methods: string[] = [];
// manually build a list of all available methods in this RPC, we are
// going to filter on it to align the cloned RPC without making a call
Object.keys(source.rpc).forEach((section): void => {
Object.keys((source.rpc as Record<string, Record<string, unknown>>)[section]).forEach((method): void => {
methods.push(`${section}_${method}`);
});
});
const sections = Object.keys(source.rpc);
const rpcs: string[] = [];
this._filterRpc(methods, getSpecRpc(this.registry, source.runtimeChain, source.runtimeVersion.specName));
for (let s = 0; s < sections.length; s++) {
const section = sections[s];
const methods = Object.keys((source.rpc as Record<string, Record<string, unknown>>)[section]);
for (let m = 0; m < methods.length; m++) {
rpcs.push(`${section}_${methods[m]}`);
}
}
this._filterRpc(rpcs, getSpecRpc(this.registry, source.runtimeChain, source.runtimeVersion.specName));
return [source.genesisHash, source.runtimeMetadata];
}
@@ -318,7 +341,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
// initializes the registry & RPC
this._initRegistry(this.registry, chain, runtimeVersion, metadata, chainProps);
this._filterRpc(rpcMethods.methods.map((t) => t.toString()), getSpecRpc(this.registry, chain, runtimeVersion.specName));
this._filterRpc(rpcMethods.methods.map(textToString), getSpecRpc(this.registry, chain, runtimeVersion.specName));
this._subscribeUpdates();
// setup the initial registry, when we have none
+1 -1
View File
@@ -182,7 +182,7 @@ export function detectedCapabilities (api: ApiInterfaceRx, blockHash?: Uint8Arra
},
extractResults<ExtractedC>(cResults, consts),
extractResults<ExtractedQ>(qResults, queries),
extractResults<ExtractedR>(rResults, raws)
extractResults<ExtractedR>(rResults.map((r) => api.registry.createType('Raw', r)), raws)
)
),
take(1),
+4 -6
View File
@@ -4,7 +4,7 @@
import type { SignerPayloadRawBase } from '@polkadot/types/types';
import type { ApiOptions, ApiTypes, DecorateMethod, Signer } from '../types';
import { assert, isString, u8aToHex, u8aToU8a } from '@polkadot/util';
import { assert, isString, objectSpread, u8aToHex, u8aToU8a } from '@polkadot/util';
import { Getters } from './Getters';
@@ -72,11 +72,9 @@ export abstract class ApiBase<ApiType extends ApiTypes> extends Getters<ApiType>
assert(_signer?.signRaw, 'No signer exists with a signRaw interface. You possibly need to pass through an explicit keypair for the origin so it can be used for signing.');
return (
await _signer.signRaw({
type: 'bytes',
...data,
address
})
await _signer.signRaw(
objectSpread({ type: 'bytes' }, data, { address })
)
).signature;
}
+2 -2
View File
@@ -5,6 +5,6 @@ export { Keyring } from '@polkadot/keyring';
export { WsProvider, HttpProvider } from '@polkadot/rpc-provider';
export { packageInfo } from './packageInfo';
export { ApiPromise, decorateMethod as decorateMethodPromise } from './promise';
export * from './promise';
export { SubmittableResult } from './submittable';
export { ApiRx, decorateMethod as decorateMethodRx } from './rx';
export * from './rx';
+1 -3
View File
@@ -177,12 +177,10 @@ async function rpc (api: ApiPromise): Promise<void> {
});
// using json & raw
await api.rpc.chain.getBlock.json('0x123456');
await api.rpc.chain.getBlock.raw('0x123456');
// using raw subs
// eslint-disable-next-line @typescript-eslint/no-floating-promises
api.rpc.chain.subscribeNewHeads.raw((result: Uint8Array): void => {
await api.rpc.chain.subscribeNewHeads.raw((result: Uint8Array): void => {
console.log(result);
});
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api', version: '6.4.2' };
export const packageInfo = { name: '@polkadot/api', version: '6.10.2' };
+215
View File
@@ -0,0 +1,215 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiOptions, UnsubscribePromise } from '../types';
import { objectSpread } from '@polkadot/util';
import { ApiBase } from '../base';
import { Combinator, CombinatorCallback, CombinatorFunction } from './Combinator';
import { promiseTracker, toPromiseMethod } from './decorateMethod';
/**
* # @polkadot/api/promise
*
* ## Overview
*
* @name ApiPromise
* @description
* ApiPromise is a standard JavaScript wrapper around the RPC and interfaces on the Polkadot network. As a full Promise-based, all interface calls return Promises, including the static `.create(...)`. Subscription calls utilise `(value) => {}` callbacks to pass through the latest values.
*
* The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of the subscription-based features of Polkadot (and Substrate) clients.
*
* @see [[ApiRx]]
*
* ## Usage
*
* Making rpc calls -
* <BR>
*
* ```javascript
* import ApiPromise from '@polkadot/api/promise';
*
* // initialise via static create
* const api = await ApiPromise.create();
*
* // make a subscription to the network head
* api.rpc.chain.subscribeNewHeads((header) => {
* console.log(`Chain is at #${header.number}`);
* });
* ```
* <BR>
*
* Subscribing to chain state -
* <BR>
*
* ```javascript
* import { ApiPromise, WsProvider } from '@polkadot/api';
*
* // initialise a provider with a specific endpoint
* const provider = new WsProvider('wss://example.com:9944')
*
* // initialise via isReady & new with specific provider
* const api = await new ApiPromise({ provider }).isReady;
*
* // retrieve the block target time
* const blockPeriod = await api.query.timestamp.blockPeriod().toNumber();
* let last = 0;
*
* // subscribe to the current block timestamp, updates automatically (callback provided)
* api.query.timestamp.now((timestamp) => {
* const elapsed = last
* ? `, ${timestamp.toNumber() - last}s since last`
* : '';
*
* last = timestamp.toNumber();
* console.log(`timestamp ${timestamp}${elapsed} (${blockPeriod}s target)`);
* });
* ```
* <BR>
*
* Submitting a transaction -
* <BR>
*
* ```javascript
* import ApiPromise from '@polkadot/api/promise';
*
* ApiPromise.create().then((api) => {
* const [nonce] = await api.query.system.account(keyring.alice.address);
*
* api.tx.balances
* // create transfer
* transfer(keyring.bob.address, 12345)
* // sign the transcation
* .sign(keyring.alice, { nonce })
* // send the transaction (optional status callback)
* .send((status) => {
* console.log(`current status ${status.type}`);
* })
* // retrieve the submitted extrinsic hash
* .then((hash) => {
* console.log(`submitted with hash ${hash}`);
* });
* });
* ```
*/
export class ApiPromise extends ApiBase<'promise'> {
#isReadyPromise: Promise<ApiPromise>;
#isReadyOrErrorPromise: Promise<ApiPromise>;
/**
* @description Creates an instance of the ApiPromise class
* @param options Options to create an instance. This can be either [[ApiOptions]] or
* an [[WsProvider]].
* @example
* <BR>
*
* ```javascript
* import Api from '@polkadot/api/promise';
*
* new Api().isReady.then((api) => {
* api.rpc.subscribeNewHeads((header) => {
* console.log(`new block #${header.number.toNumber()}`);
* });
* });
* ```
*/
constructor (options?: ApiOptions) {
super(options, 'promise', toPromiseMethod);
this.#isReadyPromise = new Promise((resolve): void => {
super.once('ready', () => resolve(this));
});
this.#isReadyOrErrorPromise = new Promise((resolve, reject): void => {
const tracker = promiseTracker(resolve, reject);
super.once('ready', () => tracker.resolve(this));
super.once('error', (error: Error) => tracker.reject(error));
});
}
/**
* @description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.
* @param options options that is passed to the class contructor. Can be either [[ApiOptions]] or a
* provider (see the constructor arguments)
* @example
* <BR>
*
* ```javascript
* import Api from '@polkadot/api/promise';
*
* Api.create().then(async (api) => {
* const timestamp = await api.query.timestamp.now();
*
* console.log(`lastest block timestamp ${timestamp}`);
* });
* ```
*/
public static create (options?: ApiOptions): Promise<ApiPromise> {
const instance = new ApiPromise(options);
if (options && options.throwOnConnect) {
return instance.isReadyOrError;
}
// Swallow any rejections on isReadyOrError
// (in Node 15.x this creates issues, when not being looked at)
instance.isReadyOrError.catch(() => {
// ignore
});
return instance.isReady;
}
/**
* @description Promise that resolves the first time we are connected and loaded
*/
public get isReady (): Promise<ApiPromise> {
return this.#isReadyPromise;
}
/**
* @description Promise that resolves if we can connect, or reject if there is an error
*/
public get isReadyOrError (): Promise<ApiPromise> {
return this.#isReadyOrErrorPromise;
}
/**
* @description Returns a clone of this ApiPromise instance (new underlying provider connection)
*/
public clone (): ApiPromise {
return new ApiPromise(
objectSpread({}, this._options, { source: this })
);
}
/**
* @description Creates a combinator that can be used to combine the latest results from multiple subscriptions
* @param fns An array of function to combine, each in the form of `(cb: (value: void)) => void`
* @param callback A callback that will return an Array of all the values this combinator has been applied to
* @example
* <BR>
*
* ```javascript
* const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7';
*
* // combines values from balance & nonce as it updates
* api.combineLatest([
* api.rpc.chain.subscribeNewHeads,
* (cb) => api.query.system.account(address, cb)
* ], ([head, [balance, nonce]]) => {
* console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`);
* });
* ```
*/
// eslint-disable-next-line @typescript-eslint/require-await
public async combineLatest <T extends any[] = any[]> (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback<T>): UnsubscribePromise {
const combinator = new Combinator(fns, callback);
return (): void => {
combinator.unsubscribe();
};
}
}
+108
View File
@@ -0,0 +1,108 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { Callback, Codec } from '@polkadot/types/types';
import type { DecorateFn, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise, VoidFn } from '../types';
import { catchError, EMPTY, Subscription, tap } from 'rxjs';
import { assert, isFunction } from '@polkadot/util';
interface Tracker<T> {
reject: (value: Error) => Observable<never>;
resolve: (value: T) => void;
}
// a Promise completion tracker, wrapping an isComplete variable that ensures the promise only resolves once
export function promiseTracker<T> (resolve: (value: T) => void, reject: (value: Error) => void): Tracker<T> {
let isCompleted = false;
return {
reject: (error: Error): Observable<never> => {
if (!isCompleted) {
isCompleted = true;
reject(error);
}
return EMPTY;
},
resolve: (value: T): void => {
if (!isCompleted) {
isCompleted = true;
resolve(value);
}
}
};
}
// extract the arguments and callback params from a value array possibly containing a callback
function extractArgs (args: unknown[], needsCallback: boolean): [unknown[], Callback<Codec> | undefined] {
let callback: Callback<Codec> | undefined;
const actualArgs = args.slice();
// If the last arg is a function, we pop it, put it into callback.
// actualArgs will then hold the actual arguments to be passed to `method`
if (args.length && isFunction(args[args.length - 1])) {
callback = actualArgs.pop() as Callback<Codec>;
}
// When we need a subscription, ensure that a valid callback is actually passed
assert(!needsCallback || isFunction(callback), 'Expected a callback to be passed with subscriptions');
return [actualArgs, callback];
}
// Decorate a call for a single-shot result - retrieve and then immediate unsubscribe
function decorateCall<M extends DecorateFn<ObsInnerType<ReturnType<M>>>> (method: M, args: unknown[]): Promise<ObsInnerType<ReturnType<M>>> {
return new Promise((resolve, reject): void => {
// single result tracker - either reject with Error or resolve with Codec result
const tracker = promiseTracker(resolve, reject);
// encoding errors reject immediately, any result unsubscribes and resolves
const subscription: Subscription = method(...args)
.pipe(
catchError((error: Error) => tracker.reject(error))
)
.subscribe((result): void => {
tracker.resolve(result);
setTimeout(() => subscription.unsubscribe(), 0);
});
});
}
// Decorate a subscription where we have a result callback specified
function decorateSubscribe<M extends DecorateFn<ObsInnerType<ReturnType<M>>>> (method: M, args: unknown[], resultCb: Callback<Codec>): UnsubscribePromise {
return new Promise<VoidFn>((resolve, reject): void => {
// either reject with error or resolve with unsubscribe callback
const tracker = promiseTracker(resolve, reject);
// errors reject immediately, the first result resolves with an unsubscribe promise, all results via callback
const subscription: Subscription = method(...args)
.pipe(
catchError((error: Error) => tracker.reject(error)),
tap(() => tracker.resolve(() => subscription.unsubscribe()))
)
.subscribe((result): void => {
// queue result (back of queue to clear current)
setTimeout(() => resultCb(result) as void, 0);
});
});
}
/**
* @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent
*/
export function toPromiseMethod<M extends DecorateFn<ObsInnerType<ReturnType<M>>>> (method: M, options?: DecorateMethodOptions): StorageEntryPromiseOverloads {
const needsCallback = !!(options && options.methodName && options.methodName.includes('subscribe'));
return function (...args: unknown[]): Promise<ObsInnerType<ReturnType<M>>> | UnsubscribePromise {
const [actualArgs, resultCb] = extractArgs(args, needsCallback);
return resultCb
? decorateSubscribe(method, actualArgs, resultCb)
: decorateCall((options?.overrideNoSub as M) || method, actualArgs);
} as StorageEntryPromiseOverloads;
}
+1 -1
View File
@@ -14,7 +14,7 @@ import { hexToU8a } from '@polkadot/util';
import { SingleAccountSigner } from '../../test/util';
import { ApiPromise } from '.';
const TRANSFER_SIG = '0x54f39e43f32376a5ab6cdfd4d0ce57802aa9ff85514a7ffa9f2a949078f02beca16af87427c45fe60d54aa847fd241d127ed39e21b101806f6b1f50f7a82500b';
const TRANSFER_SIG = '0xcc277eb341d3801c08f149508221583fa3185cc3944e6cb376cd061640305edd7dc24dfd754adb24768f1d8547389b7720e6f626bc81f5593fba1141e7f7ba07';
describe('ApiPromise', (): void => {
const registry = new TypeRegistry();
+2 -310
View File
@@ -1,313 +1,5 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { Callback, Codec } from '@polkadot/types/types';
import type { ApiOptions, DecorateFn, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise, VoidFn } from '../types';
import { catchError, EMPTY, Subscription, tap } from 'rxjs';
import { assert, isFunction } from '@polkadot/util';
import { ApiBase } from '../base';
import { Combinator, CombinatorCallback, CombinatorFunction } from './Combinator';
interface Tracker<T> {
reject: (value: Error) => Observable<never>;
resolve: (value: T) => void;
}
// extract the arguments and callback params from a value array possibly containing a callback
function extractArgs (args: unknown[], needsCallback: boolean): [unknown[], Callback<Codec> | undefined] {
let callback: Callback<Codec> | undefined;
const actualArgs = args.slice();
// If the last arg is a function, we pop it, put it into callback.
// actualArgs will then hold the actual arguments to be passed to `method`
if (args.length && isFunction(args[args.length - 1])) {
callback = actualArgs.pop() as Callback<Codec>;
}
// When we need a subscription, ensure that a valid callback is actually passed
assert(!needsCallback || isFunction(callback), 'Expected a callback to be passed with subscriptions');
return [actualArgs, callback];
}
// a Promise completion tracker, wrapping an isComplete variable that ensures the promise only resolves once
function promiseTracker<T> (resolve: (value: T) => void, reject: (value: Error) => void): Tracker<T> {
let isCompleted = false;
return {
reject: (error: Error): Observable<never> => {
if (!isCompleted) {
isCompleted = true;
reject(error);
}
return EMPTY;
},
resolve: (value: T): void => {
if (!isCompleted) {
isCompleted = true;
resolve(value);
}
}
};
}
// Decorate a call for a single-shot result - retrieve and then immediate unsubscribe
function decorateCall<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>>> (method: Method, actualArgs: unknown[]): Promise<ObsInnerType<ReturnType<Method>>> {
return new Promise((resolve, reject): void => {
// single result tracker - either reject with Error or resolve with Codec result
const tracker = promiseTracker(resolve, reject);
// encoding errors reject immediately, any result unsubscribes and resolves
const subscription: Subscription = method(...actualArgs).pipe(
catchError((error: Error) => tracker.reject(error))
).subscribe((result): void => {
tracker.resolve(result);
setTimeout(() => subscription.unsubscribe(), 0);
});
});
}
// Decorate a subscription where we have a result callback specified
function decorateSubscribe<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>>> (method: Method, actualArgs: unknown[], resultCb: Callback<Codec>): UnsubscribePromise {
return new Promise<VoidFn>((resolve, reject): void => {
// either reject with error or resolve with unsubscribe callback
const tracker = promiseTracker(resolve, reject);
// errors reject immediately, the first result resolves with an unsubscribe promise, all results via callback
const subscription: Subscription = method(...actualArgs).pipe(
catchError((error: Error) => tracker.reject(error)),
tap(() => tracker.resolve(() => subscription.unsubscribe()))
).subscribe((result): void => {
// queue result (back of queue to clear current)
setTimeout(() => resultCb(result) as void, 0);
});
});
}
/**
* @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent
*/
export function decorateMethod<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>>> (method: Method, options?: DecorateMethodOptions): StorageEntryPromiseOverloads {
const needsCallback = options && options.methodName && options.methodName.includes('subscribe');
return function (...args: unknown[]): Promise<ObsInnerType<ReturnType<Method>>> | UnsubscribePromise {
const [actualArgs, resultCb] = extractArgs(args, !!needsCallback);
return resultCb
? decorateSubscribe(method, actualArgs, resultCb)
: decorateCall((options?.overrideNoSub as Method) || method, actualArgs);
} as StorageEntryPromiseOverloads;
}
/**
* # @polkadot/api/promise
*
* ## Overview
*
* @name ApiPromise
* @description
* ApiPromise is a standard JavaScript wrapper around the RPC and interfaces on the Polkadot network. As a full Promise-based, all interface calls return Promises, including the static `.create(...)`. Subscription calls utilise `(value) => {}` callbacks to pass through the latest values.
*
* The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of the subscription-based features of Polkadot (and Substrate) clients.
*
* @see [[ApiRx]]
*
* ## Usage
*
* Making rpc calls -
* <BR>
*
* ```javascript
* import ApiPromise from '@polkadot/api/promise';
*
* // initialise via static create
* const api = await ApiPromise.create();
*
* // make a subscription to the network head
* api.rpc.chain.subscribeNewHeads((header) => {
* console.log(`Chain is at #${header.number}`);
* });
* ```
* <BR>
*
* Subscribing to chain state -
* <BR>
*
* ```javascript
* import { ApiPromise, WsProvider } from '@polkadot/api';
*
* // initialise a provider with a specific endpoint
* const provider = new WsProvider('wss://example.com:9944')
*
* // initialise via isReady & new with specific provider
* const api = await new ApiPromise({ provider }).isReady;
*
* // retrieve the block target time
* const blockPeriod = await api.query.timestamp.blockPeriod().toNumber();
* let last = 0;
*
* // subscribe to the current block timestamp, updates automatically (callback provided)
* api.query.timestamp.now((timestamp) => {
* const elapsed = last
* ? `, ${timestamp.toNumber() - last}s since last`
* : '';
*
* last = timestamp.toNumber();
* console.log(`timestamp ${timestamp}${elapsed} (${blockPeriod}s target)`);
* });
* ```
* <BR>
*
* Submitting a transaction -
* <BR>
*
* ```javascript
* import ApiPromise from '@polkadot/api/promise';
*
* ApiPromise.create().then((api) => {
* const [nonce] = await api.query.system.account(keyring.alice.address);
*
* api.tx.balances
* // create transfer
* transfer(keyring.bob.address, 12345)
* // sign the transcation
* .sign(keyring.alice, { nonce })
* // send the transaction (optional status callback)
* .send((status) => {
* console.log(`current status ${status.type}`);
* })
* // retrieve the submitted extrinsic hash
* .then((hash) => {
* console.log(`submitted with hash ${hash}`);
* });
* });
* ```
*/
export class ApiPromise extends ApiBase<'promise'> {
#isReadyPromise: Promise<ApiPromise>;
#isReadyOrErrorPromise: Promise<ApiPromise>;
/**
* @description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.
* @param options options that is passed to the class contructor. Can be either [[ApiOptions]] or a
* provider (see the constructor arguments)
* @example
* <BR>
*
* ```javascript
* import Api from '@polkadot/api/promise';
*
* Api.create().then(async (api) => {
* const timestamp = await api.query.timestamp.now();
*
* console.log(`lastest block timestamp ${timestamp}`);
* });
* ```
*/
public static create (options?: ApiOptions): Promise<ApiPromise> {
const instance = new ApiPromise(options);
if (options && options.throwOnConnect) {
return instance.isReadyOrError;
}
// Swallow any rejections on isReadyOrError
// (in Node 15.x this creates issues, when not being looked at)
instance.isReadyOrError.catch(() => {
// ignore
});
return instance.isReady;
}
/**
* @description Creates an instance of the ApiPromise class
* @param options Options to create an instance. This can be either [[ApiOptions]] or
* an [[WsProvider]].
* @example
* <BR>
*
* ```javascript
* import Api from '@polkadot/api/promise';
*
* new Api().isReady.then((api) => {
* api.rpc.subscribeNewHeads((header) => {
* console.log(`new block #${header.number.toNumber()}`);
* });
* });
* ```
*/
constructor (options?: ApiOptions) {
super(options, 'promise', decorateMethod);
this.#isReadyPromise = new Promise((resolve): void => {
super.once('ready', () => resolve(this));
});
this.#isReadyOrErrorPromise = new Promise((resolve, reject): void => {
const tracker = promiseTracker(resolve, reject);
super.once('ready', () => tracker.resolve(this));
super.once('error', (error: Error) => tracker.reject(error));
});
}
/**
* @description Promise that resolves the first time we are connected and loaded
*/
public get isReady (): Promise<ApiPromise> {
return this.#isReadyPromise;
}
/**
* @description Promise that resolves if we can connect, or reject if there is an error
*/
public get isReadyOrError (): Promise<ApiPromise> {
return this.#isReadyOrErrorPromise;
}
/**
* @description Returns a clone of this ApiPromise instance (new underlying provider connection)
*/
public clone (): ApiPromise {
return new ApiPromise({
...this._options,
source: this
});
}
/**
* @description Creates a combinator that can be used to combine the latest results from multiple subscriptions
* @param fns An array of function to combine, each in the form of `(cb: (value: void)) => void`
* @param callback A callback that will return an Array of all the values this combinator has been applied to
* @example
* <BR>
*
* ```javascript
* const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7';
*
* // combines values from balance & nonce as it updates
* api.combineLatest([
* api.rpc.chain.subscribeNewHeads,
* (cb) => api.query.system.account(address, cb)
* ], ([head, [balance, nonce]]) => {
* console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`);
* });
* ```
*/
// eslint-disable-next-line @typescript-eslint/require-await
public async combineLatest <T extends any[] = any[]> (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback<T>): UnsubscribePromise {
const combinator = new Combinator(fns, callback);
return (): void => {
combinator.unsubscribe();
};
}
}
export { ApiPromise } from './Api';
export { toPromiseMethod } from './decorateMethod';
+185
View File
@@ -0,0 +1,185 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiOptions } from '../types';
import { from, Observable } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { ApiBase } from '../base';
import { toRxMethod } from './decorateMethod';
/**
* # @polkadot/api/rx
*
* ## Overview
*
* @name ApiRx
*
* @description
* ApiRx is a powerful RxJS Observable wrapper around the RPC and interfaces on the Polkadot network. As a full Observable API, all interface calls return RxJS Observables, including the static `.create(...)`. In the same fashion and subscription-based methods return long-running Observables that update with the latest values.
*
* The API is well suited to real-time applications where the latest state is needed, unlocking the subscription-based features of Polkadot (and Substrate) clients. Some familiarity with RxJS is a requirement to use the API, however just understanding `.subscribe` and `.pipe` on Observables will unlock full-scale use thereof.
*
* @see [[ApiPromise]]
*
* ## Usage
*
* Making rpc calls -
* <BR>
*
* ```javascript
* import ApiRx from '@polkadot/api/rx';
*
* // initialize via Promise & static create
* const api = await ApiRx.create().toPromise();
*
* // make a call to retrieve the current network head
* api.rpc.chain.subscribeNewHeads().subscribe((header) => {
* console.log(`Chain is at #${header.number}`);
* });
* ```
* <BR>
*
* Subscribing to chain state -
* <BR>
*
* ```javascript
* import { combineLatest, pairwise, switchMap } from 'rxjs';
* import { ApiRx, WsProvider } from '@polkadot/api';
*
*
* // initialize a provider with a specific endpoint
* const provider = new WsProvider('wss://example.com:9944')
*
* // initialize via isReady & new with specific provider
* new ApiRx({ provider })
* .isReady
* .pipe(
* switchMap((api) =>
* combineLatest([
* api.query.timestamp.blockPeriod(),
* api.query.timestamp.now().pipe(pairwise())
* ])
* )
* )
* .subscribe(([blockPeriod, timestamp]) => {
* const elapsed = timestamp[1].toNumber() - timestamp[0].toNumber();
* console.log(`timestamp ${timestamp[1]} \nelapsed ${elapsed} \n(${blockPeriod}s target)`);
* });
* ```
* <BR>
*
* Submitting a transaction -
* <BR>
*
* ```javascript
* import { first, switchMap } from 'rxjs';
* import ApiRx from '@polkadot/api/rx';
*
* // import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
* import testingPairs from '@polkadot/keyring/testingPairs';
* const keyring = testingPairs();
*
* // get api via Promise
* const api = await ApiRx.create().toPromise();
*
* // retrieve nonce for the account
* api.query.system
* .account(keyring.alice.address)
* .pipe(
* first(),
* // pipe nonce into transfer
* switchMap(([nonce]) =>
* api.tx.balances
* // create transfer
* .transfer(keyring.bob.address, 12345)
* // sign the transaction
* .sign(keyring.alice, { nonce })
* // send the transaction
* .send()
* )
* )
* // subscribe to overall result
* .subscribe(({ status }) => {
* if (status.isInBlock) {
* console.log('Completed at block hash', status.asFinalized.toHex());
* }
* });
* ```
*/
export class ApiRx extends ApiBase<'rxjs'> {
#isReadyRx: Observable<ApiRx>;
/**
* @description Create an instance of the ApiRx class
* @param options Options to create an instance. Can be either [[ApiOptions]] or [[WsProvider]]
* @example
* <BR>
*
* ```javascript
* import { switchMap } from 'rxjs';
* import Api from '@polkadot/api/rx';
*
* new Api().isReady
* .pipe(
* switchMap((api) =>
* api.rpc.chain.subscribeNewHeads()
* ))
* .subscribe((header) => {
* console.log(`new block #${header.number.toNumber()}`);
* });
* ```
*/
constructor (options?: ApiOptions) {
super(options, 'rxjs', toRxMethod);
this.#isReadyRx = from<Promise<ApiRx>>(
// You can create an observable from an event, however my mind groks this form better
new Promise((resolve): void => {
super.on('ready', () => resolve(this));
})
);
}
/**
* @description Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance.
* @param options options that is passed to the class constructor. Can be either [[ApiOptions]] or [[WsProvider]]
* @example
* <BR>
*
* ```javascript
* import { switchMap } from 'rxjs';
* import Api from '@polkadot/api/rx';
*
* Api.create()
* .pipe(
* switchMap((api) =>
* api.rpc.chain.subscribeNewHeads()
* ))
* .subscribe((header) => {
* console.log(`new block #${header.number.toNumber()}`);
* });
* ```
*/
public static create (options?: ApiOptions): Observable<ApiRx> {
return new ApiRx(options).isReady;
}
/**
* @description Observable that returns the first time we are connected and loaded
*/
public get isReady (): Observable<ApiRx> {
return this.#isReadyRx;
}
/**
* @description Returns a clone of this ApiRx instance (new underlying provider connection)
*/
public clone (): ApiRx {
return new ApiRx(
objectSpread({}, this._options, { source: this })
);
}
}
+9
View File
@@ -0,0 +1,9 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Codec } from '@polkadot/types/types';
import type { DecorateFn } from '../types';
export function toRxMethod <M extends DecorateFn<Codec>> (method: M): M {
return method;
}
+2 -185
View File
@@ -1,188 +1,5 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Codec } from '@polkadot/types/types';
import type { ApiOptions, DecorateFn } from '../types';
import { from, Observable } from 'rxjs';
import { ApiBase } from '../base';
export function decorateMethod <Method extends DecorateFn<Codec>> (method: Method): Method {
return method;
}
/**
* # @polkadot/api/rx
*
* ## Overview
*
* @name ApiRx
*
* @description
* ApiRx is a powerful RxJS Observable wrapper around the RPC and interfaces on the Polkadot network. As a full Observable API, all interface calls return RxJS Observables, including the static `.create(...)`. In the same fashion and subscription-based methods return long-running Observables that update with the latest values.
*
* The API is well suited to real-time applications where the latest state is needed, unlocking the subscription-based features of Polkadot (and Substrate) clients. Some familiarity with RxJS is a requirement to use the API, however just understanding `.subscribe` and `.pipe` on Observables will unlock full-scale use thereof.
*
* @see [[ApiPromise]]
*
* ## Usage
*
* Making rpc calls -
* <BR>
*
* ```javascript
* import ApiRx from '@polkadot/api/rx';
*
* // initialize via Promise & static create
* const api = await ApiRx.create().toPromise();
*
* // make a call to retrieve the current network head
* api.rpc.chain.subscribeNewHeads().subscribe((header) => {
* console.log(`Chain is at #${header.number}`);
* });
* ```
* <BR>
*
* Subscribing to chain state -
* <BR>
*
* ```javascript
* import { combineLatest, pairwise, switchMap } from 'rxjs';
* import { ApiRx, WsProvider } from '@polkadot/api';
*
*
* // initialize a provider with a specific endpoint
* const provider = new WsProvider('wss://example.com:9944')
*
* // initialize via isReady & new with specific provider
* new ApiRx({ provider })
* .isReady
* .pipe(
* switchMap((api) =>
* combineLatest([
* api.query.timestamp.blockPeriod(),
* api.query.timestamp.now().pipe(pairwise())
* ])
* )
* )
* .subscribe(([blockPeriod, timestamp]) => {
* const elapsed = timestamp[1].toNumber() - timestamp[0].toNumber();
* console.log(`timestamp ${timestamp[1]} \nelapsed ${elapsed} \n(${blockPeriod}s target)`);
* });
* ```
* <BR>
*
* Submitting a transaction -
* <BR>
*
* ```javascript
* import { first, switchMap } from 'rxjs';
* import ApiRx from '@polkadot/api/rx';
*
* // import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
* import testingPairs from '@polkadot/keyring/testingPairs';
* const keyring = testingPairs();
*
* // get api via Promise
* const api = await ApiRx.create().toPromise();
*
* // retrieve nonce for the account
* api.query.system
* .account(keyring.alice.address)
* .pipe(
* first(),
* // pipe nonce into transfer
* switchMap(([nonce]) =>
* api.tx.balances
* // create transfer
* .transfer(keyring.bob.address, 12345)
* // sign the transaction
* .sign(keyring.alice, { nonce })
* // send the transaction
* .send()
* )
* )
* // subscribe to overall result
* .subscribe(({ status }) => {
* if (status.isInBlock) {
* console.log('Completed at block hash', status.asFinalized.toHex());
* }
* });
* ```
*/
export class ApiRx extends ApiBase<'rxjs'> {
#isReadyRx: Observable<ApiRx>;
/**
* @description Creates an ApiRx instance using the supplied provider. Returns an Observable containing the actual Api instance.
* @param options options that is passed to the class constructor. Can be either [[ApiOptions]] or [[WsProvider]]
* @example
* <BR>
*
* ```javascript
* import { switchMap } from 'rxjs';
* import Api from '@polkadot/api/rx';
*
* Api.create()
* .pipe(
* switchMap((api) =>
* api.rpc.chain.subscribeNewHeads()
* ))
* .subscribe((header) => {
* console.log(`new block #${header.number.toNumber()}`);
* });
* ```
*/
public static create (options?: ApiOptions): Observable<ApiRx> {
return new ApiRx(options).isReady;
}
/**
* @description Create an instance of the ApiRx class
* @param options Options to create an instance. Can be either [[ApiOptions]] or [[WsProvider]]
* @example
* <BR>
*
* ```javascript
* import { switchMap } from 'rxjs';
* import Api from '@polkadot/api/rx';
*
* new Api().isReady
* .pipe(
* switchMap((api) =>
* api.rpc.chain.subscribeNewHeads()
* ))
* .subscribe((header) => {
* console.log(`new block #${header.number.toNumber()}`);
* });
* ```
*/
constructor (options?: ApiOptions) {
super(options, 'rxjs', decorateMethod);
this.#isReadyRx = from<Promise<ApiRx>>(
// You can create an observable from an event, however my mind groks this form better
new Promise((resolve): void => {
super.on('ready', () => resolve(this));
})
);
}
/**
* @description Observable that returns the first time we are connected and loaded
*/
public get isReady (): Observable<ApiRx> {
return this.#isReadyRx;
}
/**
* @description Returns a clone of this ApiRx instance (new underlying provider connection)
*/
public clone (): ApiRx {
return new ApiRx({
...this._options,
source: this
});
}
}
export { ApiRx } from './Api';
export { toRxMethod } from './decorateMethod';
+17 -10
View File
@@ -9,22 +9,29 @@ const recordIdentity = (record: EventRecord) => record;
function filterAndApply <T> (events: EventRecord[], section: string, methods: string[], onFound: (record: EventRecord) => T): T[] {
return events
.filter(({ event }) => section === event.section && methods.includes(event.method))
.filter(({ event }) =>
section === event.section &&
methods.includes(event.method)
)
.map((record) => onFound(record));
}
function getDispatchError ({ event: { data: [dispatchError] } }: EventRecord): DispatchError {
return dispatchError as DispatchError;
}
function getDispatchInfo ({ event: { data, method } }: EventRecord): DispatchInfo {
return method === 'ExtrinsicSuccess'
? data[0] as DispatchInfo
: data[1] as DispatchInfo;
}
function extractError (events: EventRecord[] = []): DispatchError | undefined {
return filterAndApply(events, 'system', ['ExtrinsicFailed'], ({ event: { data } }) =>
data[0] as DispatchError
)[0];
return filterAndApply(events, 'system', ['ExtrinsicFailed'], getDispatchError)[0];
}
function extractInfo (events: EventRecord[] = []): DispatchInfo | undefined {
return filterAndApply(events, 'system', ['ExtrinsicFailed', 'ExtrinsicSuccess'], ({ event: { data, method } }) =>
method === 'ExtrinsicSuccess'
? data[0] as DispatchInfo
: data[1] as DispatchInfo
)[0];
return filterAndApply(events, 'system', ['ExtrinsicFailed', 'ExtrinsicSuccess'], getDispatchInfo)[0];
}
export class SubmittableResult implements ISubmittableResult {
@@ -87,7 +94,7 @@ export class SubmittableResult implements ISubmittableResult {
return {
dispatchError: this.dispatchError?.toHuman(),
dispatchInfo: this.dispatchInfo?.toHuman(),
events: this.events.map((event) => event.toHuman(isExtended)),
events: this.events.map((e) => e.toHuman(isExtended)),
internalError: this.internalError?.message.toString(),
status: this.status.toHuman(isExtended)
};
+75 -74
View File
@@ -11,7 +11,7 @@ import type { AddressOrPair, SignerOptions, SubmittableDryRunResult, Submittable
import { catchError, first, map, mapTo, mergeMap, of, switchMap, tap } from 'rxjs';
import { assert, isBn, isFunction, isNumber, isString, isU8a } from '@polkadot/util';
import { assert, isBn, isFunction, isNumber, isString, isU8a, objectSpread } from '@polkadot/util';
import { ApiBase } from '../base';
import { filterEvents, isKeyringPair } from '../util';
@@ -25,6 +25,55 @@ interface SubmittableOptions<ApiType extends ApiTypes> {
const identity = <T> (input: T): T => input;
function makeEraOptions (api: ApiInterfaceRx, registry: Registry, partialOptions: Partial<SignerOptions>, { header, mortalLength, nonce }: { header: Header | null; mortalLength: number; nonce: Index }): SignatureOptions {
if (!header) {
if (isNumber(partialOptions.era)) {
// since we have no header, it is immortal, remove any option overrides
// so we only supply the genesisHash and no era to the construction
delete partialOptions.era;
delete partialOptions.blockHash;
}
return makeSignOptions(api, partialOptions, { nonce });
}
return makeSignOptions(api, partialOptions, {
blockHash: header.hash,
era: registry.createType('ExtrinsicEra', {
current: header.number,
period: partialOptions.era || mortalLength
}),
nonce
});
}
function makeSignAndSendOptions (partialOptions?: Partial<SignerOptions> | Callback<ISubmittableResult>, statusCb?: Callback<ISubmittableResult>): [Partial<SignerOptions>, Callback<ISubmittableResult>?] {
let options: Partial<SignerOptions> = {};
if (isFunction(partialOptions)) {
statusCb = partialOptions;
} else {
options = objectSpread({}, partialOptions);
}
return [options, statusCb];
}
function makeSignOptions (api: ApiInterfaceRx, partialOptions: Partial<SignerOptions>, extras: { blockHash?: Hash; era?: ExtrinsicEra; nonce?: Index }): SignatureOptions {
return objectSpread(
{ blockHash: api.genesisHash, genesisHash: api.genesisHash },
partialOptions,
extras,
{ runtimeVersion: api.runtimeVersion, signedExtensions: api.registry.signedExtensions, version: api.extrinsicType }
);
}
function optionsOrNonce (partialOptions: Partial<SignerOptions> = {}): Partial<SignerOptions> {
return isBn(partialOptions) || isNumber(partialOptions)
? { nonce: partialOptions }
: partialOptions;
}
export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorateMethod }: SubmittableOptions<ApiType>): Constructor<SubmittableExtrinsic<ApiType>> {
// an instance of the base extrinsic for us to extend
const ExtrinsicBase = api.registry.createClass('Extrinsic');
@@ -67,7 +116,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
);
}
const [allOptions] = this.#makeSignAndSendOptions(optionsOrHash);
const [allOptions] = makeSignAndSendOptions(optionsOrHash);
const address = isKeyringPair(account) ? account.address : account.toString();
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
@@ -77,8 +126,8 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
first(),
switchMap((signingInfo): Observable<RuntimeDispatchInfo> => {
// setup our options (same way as in signAndSend)
const eraOptions = this.#makeEraOptions(allOptions, signingInfo);
const signOptions = this.#makeSignOptions(eraOptions, {});
const eraOptions = makeEraOptions(api, this.registry, allOptions, signingInfo);
const signOptions = makeSignOptions(api, eraOptions, {});
this.signFake(address, signOptions);
@@ -110,8 +159,8 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
* @description Sign a transaction, returning the this to allow chaining, i.e. .sign(...).send(). When options, e.g. nonce/blockHash are not specified, it will be inferred. To retrieve eg. nonce use `signAsync` (the preferred interface, this is provided for backwards compatibility)
* @deprecated
*/
public override sign (account: IKeyringPair, optionsOrNonce?: Partial<SignerOptions>): this {
super.sign(account, this.#makeSignOptions(this.#optionsOrNonce(optionsOrNonce), {}));
public override sign (account: IKeyringPair, partialOptions?: Partial<SignerOptions>): this {
super.sign(account, makeSignOptions(api, optionsOrNonce(partialOptions), {}));
return this;
}
@@ -119,26 +168,28 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
/**
* @description Signs a transaction, returning `this` to allow chaining. E.g.: `sign(...).send()`. Like `.signAndSend` this will retrieve the nonce and blockHash to send the tx with.
*/
public signAsync (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): SubmittableThis<ApiType, this> {
public signAsync (account: AddressOrPair, partialOptions?: Partial<SignerOptions>): SubmittableThis<ApiType, this> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
return decorateMethod(
(): Observable<this> =>
this.#observeSign(account, optionsOrNonce).pipe(mapTo(this) as OperatorFunction<number | undefined, this>)
this.#observeSign(account, partialOptions).pipe(
mapTo<number | undefined, this>(this)
)
)();
}
// signAndSend with an immediate Hash result
public signAndSend (account: AddressOrPair, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType>;
public signAndSend (account: AddressOrPair, partialOptions?: Partial<SignerOptions>): SubmittableResultResult<ApiType>;
// signAndSend with a subscription, i.e. callback provided
public signAndSend (account: AddressOrPair, statusCb: Callback<ISubmittableResult>): SubmittableResultSubscription<ApiType>;
// signAndSend with options and a callback
public signAndSend (account: AddressOrPair, options: Partial<SignerOptions>, statusCb?: Callback<ISubmittableResult>): SubmittableResultSubscription<ApiType>;
public signAndSend (account: AddressOrPair, partialOptions: Partial<SignerOptions>, statusCb?: Callback<ISubmittableResult>): SubmittableResultSubscription<ApiType>;
// signAndSend implementation for all 3 cases above
public signAndSend (account: AddressOrPair, optionsOrStatus?: Partial<SignerOptions> | Callback<ISubmittableResult>, optionalStatusCb?: Callback<ISubmittableResult>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> {
const [options, statusCb] = this.#makeSignAndSendOptions(optionsOrStatus, optionalStatusCb);
public signAndSend (account: AddressOrPair, partialOptions?: Partial<SignerOptions> | Callback<ISubmittableResult>, optionalStatusCb?: Callback<ISubmittableResult>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> {
const [options, statusCb] = makeSignAndSendOptions(partialOptions, optionalStatusCb);
const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
@@ -161,61 +212,15 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
return this;
}
#makeEraOptions = (options: Partial<SignerOptions>, { header, mortalLength, nonce }: { header: Header | null; mortalLength: number; nonce: Index }): SignatureOptions => {
if (!header) {
if (isNumber(options.era)) {
// since we have no header, it is immortal, remove any option overrides
// so we only supply the genesisHash and no era to the construction
delete options.era;
delete options.blockHash;
}
return this.#makeSignOptions(options, { nonce });
}
return this.#makeSignOptions(options, {
blockHash: header.hash,
era: this.registry.createType('ExtrinsicEra', {
current: header.number,
period: options.era || mortalLength
}),
nonce
});
};
#makeSignOptions = (options: Partial<SignerOptions>, extras: { blockHash?: Hash; era?: ExtrinsicEra; nonce?: Index }): SignatureOptions => {
return {
blockHash: api.genesisHash,
genesisHash: api.genesisHash,
...options,
...extras,
runtimeVersion: api.runtimeVersion,
signedExtensions: api.registry.signedExtensions,
version: api.extrinsicType
} as SignatureOptions;
};
#makeSignAndSendOptions = (optionsOrStatus?: Partial<SignerOptions> | Callback<ISubmittableResult>, statusCb?: Callback<ISubmittableResult>): [Partial<SignerOptions>, Callback<ISubmittableResult>?] => {
let options: Partial<SignerOptions> = {};
if (isFunction(optionsOrStatus)) {
statusCb = optionsOrStatus;
} else {
options = { ...optionsOrStatus };
}
return [options, statusCb];
};
#observeSign = (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): Observable<number | undefined> => {
#observeSign = (account: AddressOrPair, partialOptions?: Partial<SignerOptions>): Observable<number | undefined> => {
const address = isKeyringPair(account) ? account.address : account.toString();
const options = this.#optionsOrNonce(optionsOrNonce);
const options = optionsOrNonce(partialOptions);
let updateId: number | undefined;
return api.derive.tx.signingInfo(address, options.nonce, options.era).pipe(
first(),
mergeMap(async (signingInfo): Promise<void> => {
const eraOptions = this.#makeEraOptions(options, signingInfo);
const eraOptions = makeEraOptions(api, this.registry, options, signingInfo);
if (isKeyringPair(account)) {
this.sign(account, eraOptions);
@@ -229,7 +234,9 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
#observeStatus = (hash: Hash, status: ExtrinsicStatus): Observable<ISubmittableResult> => {
if (!status.isFinalized && !status.isInBlock) {
return of(this.#transformResult(new SubmittableResult({ status })));
return of(this.#transformResult(new SubmittableResult({
status
})));
}
const blockHash = status.isInBlock
@@ -244,7 +251,10 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
}))
),
catchError((internalError: Error) =>
of(this.#transformResult(new SubmittableResult({ internalError, status })))
of(this.#transformResult(new SubmittableResult({
internalError,
status
})))
)
);
};
@@ -270,25 +280,16 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
);
};
// NOTE here we actually override nonce if it was specified (backwards compat for
// the previous signature - don't let user space break, but allow then time to upgrade)
#optionsOrNonce = (optionsOrNonce: Partial<SignerOptions> = {}): Partial<SignerOptions> => {
return isBn(optionsOrNonce) || isNumber(optionsOrNonce)
? { nonce: optionsOrNonce }
: optionsOrNonce;
};
#signViaSigner = async (address: Address | string | Uint8Array, options: SignatureOptions, header: Header | null): Promise<number> => {
const signer = options.signer || api.signer;
assert(signer, 'No signer specified, either via api.setSigner or via sign options. You possibly need to pass through an explicit keypair for the origin so it can be used for signing.');
const payload = this.registry.createType('SignerPayload', {
...options,
const payload = this.registry.createType('SignerPayload', objectSpread({}, options, {
address,
blockNumber: header ? header.number : 0,
method: this.method
});
}));
let result: SignerResult;
if (signer.signPayload) {
+2 -1
View File
@@ -64,4 +64,5 @@ export interface PaginationOptions<A = unknown> {
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type DecorateMethod<ApiType extends ApiTypes> = <Method extends (...args: any[]) => Observable<any>>(method: Method, options?: DecorateMethodOptions) => any;
export type DecorateMethod<ApiType extends ApiTypes, T = any> =
<M extends (...args: any[]) => Observable<any>>(method: M, options?: DecorateMethodOptions) => T;
-3
View File
@@ -5,9 +5,6 @@ import type { PalletConstantMetadataLatest } from '@polkadot/types/interfaces';
import type { Codec } from '@polkadot/types/types';
import type { ApiTypes } from './base';
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedConsts<ApiType extends ApiTypes> { }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export interface AugmentedConst<ApiType extends ApiTypes> {
meta: PalletConstantMetadataLatest;
-4
View File
@@ -4,10 +4,6 @@
import type { IsError } from '@polkadot/types/metadata/decorate/types';
import type { ApiTypes } from './base';
// In errors we don't need the ApiType, however add it for consistency
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedErrors<ApiType extends ApiTypes> { }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type AugmentedError<ApiType extends ApiTypes> = IsError;
-4
View File
@@ -5,10 +5,6 @@ import type { IsEvent } from '@polkadot/types/metadata/decorate/types';
import type { AnyTuple } from '@polkadot/types/types';
import type { ApiTypes } from './base';
// In events we don't need the ApiType, however add it for consistency
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedEvents<ApiType extends ApiTypes> { }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type AugmentedEvent<ApiType extends ApiTypes, T extends AnyTuple = AnyTuple> = IsEvent<T>;
+14 -7
View File
@@ -1,10 +1,14 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Augment the modules
import '@polkadot/api/augment';
import type { Observable } from 'rxjs';
import type { QueryableConsts } from '@polkadot/api/types/consts';
import type { DecoratedErrors } from '@polkadot/api/types/errors';
import type { DecoratedEvents } from '@polkadot/api/types/events';
import type { QueryableStorage } from '@polkadot/api/types/storage';
import type { SubmittableExtrinsics } from '@polkadot/api/types/submittable';
import type { DeriveCustom, ExactDerive } from '@polkadot/api-derive';
import type { RpcInterface } from '@polkadot/rpc-core/types';
import type { ProviderInterface, ProviderInterfaceEmitted } from '@polkadot/rpc-provider/types';
@@ -16,14 +20,17 @@ import type { BN } from '@polkadot/util';
import type { ApiBase } from '../base';
import type { DeriveAllSections } from '../util/decorate';
import type { ApiTypes } from './base';
import type { QueryableConsts } from './consts';
import type { DecoratedErrors } from './errors';
import type { DecoratedEvents } from './events';
import type { DecoratedRpc } from './rpc';
import type { QueryableStorage, QueryableStorageMulti } from './storage';
import type { SubmittableExtrinsics } from './submittable';
import type { QueryableStorageMulti } from './storage';
export * from '@polkadot/api/types/consts';
export * from '@polkadot/api/types/errors';
export * from '@polkadot/api/types/events';
export * from '@polkadot/api/types/storage';
export * from '@polkadot/api/types/submittable';
export * from '@polkadot/api/types/rpc';
export { Signer, SignerResult } from '@polkadot/types/types';
export { ApiBase } from '../base';
export * from '../submittable/types';
export * from './base';
@@ -95,7 +102,7 @@ export interface ApiInterfaceRx {
runtimeMetadata: Metadata;
runtimeVersion: RuntimeVersion;
query: QueryableStorage<'rxjs'>;
queryAt: (blockHash: Uint8Array | string) => Observable<QueryableStorage<'rxjs'>>;
queryAt: (blockHash: Uint8Array | string, knownVersion?: RuntimeVersion) => Observable<QueryableStorage<'rxjs'>>;
queryMulti: QueryableStorageMulti<'rxjs'>;
rpc: DecoratedRpc<'rxjs', RpcInterface>;
tx: SubmittableExtrinsics<'rxjs'>;
+8 -8
View File
@@ -2,23 +2,18 @@
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { Json, Raw } from '@polkadot/types/codec';
import type { AnyFunction, Callback, DefinitionRpc } from '@polkadot/types/types';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { ApiTypes, PromiseResult, Push, RxResult, UnsubscribePromise } from './base';
export interface RpcRxResult<F extends AnyFunction> extends RxResult<F> {
json (...args: Parameters<F>): Observable<Json>;
raw (...args: Parameters<F>): Observable<Raw>;
raw <T> (...args: Parameters<F>): Observable<T>;
meta: DefinitionRpc;
}
export interface RpcPromiseResult<F extends AnyFunction> extends PromiseResult<F> {
json (...args: Parameters<F>): Promise<Json>;
json (...args: Push<Parameters<F>, Callback<Json>>): UnsubscribePromise;
raw (...args: Parameters<F>): Promise<Raw>;
raw (...args: Push<Parameters<F>, Callback<Raw>>): UnsubscribePromise;
raw <T> (...args: Parameters<F>): Promise<T>;
raw <T> (...args: Push<Parameters<F>, Callback<T>>): UnsubscribePromise;
meta: DefinitionRpc;
}
@@ -35,3 +30,8 @@ export type DecoratedRpcSection<ApiType extends ApiTypes, Section> = {
export type DecoratedRpc<ApiType extends ApiTypes, AllSections> = {
[Section in keyof AllSections]: DecoratedRpcSection<ApiType, AllSections[Section]>
}
export type AugmentedRpc<F extends AnyFunction> = F & {
raw: <T> (...params: Parameters<F>) => Observable<T>;
meta: DefinitionRpc;
};
+1 -3
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { AugmentedQueries } from '@polkadot/api/types/storage';
import type { StorageKey, u64 } from '@polkadot/types';
import type { Hash } from '@polkadot/types/interfaces';
import type { StorageEntry } from '@polkadot/types/primitive/types';
@@ -123,9 +124,6 @@ export type QueryableStorageMulti<ApiType extends ApiTypes> =
? QueryableStorageMultiBase<ApiType>
: QueryableStorageMultiPromise<ApiType>;
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedQueries<ApiType extends ApiTypes> { }
export type AugmentedQuery<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> = MethodResult<ApiType, F> & StorageEntryBase<ApiType, F, A>;
export type AugmentedQueryAt<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> = MethodResult<ApiType, F> & StorageEntryBaseAt<ApiType, F, A>;
-3
View File
@@ -5,9 +5,6 @@ import type { AnyFunction, AnyTuple, CallBase } from '@polkadot/types/types';
import type { SubmittableExtrinsic } from '../submittable/types';
import type { ApiTypes } from './base';
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedSubmittables<ApiType extends ApiTypes> { }
export type AugmentedSubmittable<T extends AnyFunction, A extends AnyTuple = AnyTuple> = T & CallBase<A>;
export interface SubmittableExtrinsicFunction<ApiType extends ApiTypes, A extends AnyTuple = AnyTuple> extends CallBase<A> {
+64 -45
View File
@@ -1,7 +1,11 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { logger } from '@polkadot/util';
import { lazyMethod, logger, objectClear } from '@polkadot/util';
type Sections <T> = Record<string, Methods<T>>;
type Methods <T> = Record<string, T>;
type StringsStrings = [string[], string[]];
@@ -26,16 +30,17 @@ function warn (prefix: string, type: 'calls' | 'modules', [added, removed]: Stri
}
}
function extractKeys (src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>): StringsStrings {
return [Object.keys(src), Object.keys(dst)];
}
function findSectionExcludes (a: string[], b: string[]): string[] {
return a.filter((section) => !b.includes(section));
return a.filter((s) => !b.includes(s));
}
function extractSections (src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>): StringsStrings {
const [srcSections, dstSections] = extractKeys(src, dst);
function findSectionIncludes (a: string[], b: string[]): string[] {
return a.filter((s) => b.includes(s));
}
function extractSections <T> (src: Sections<T>, dst: Sections<T>): StringsStrings {
const srcSections = Object.keys(src);
const dstSections = Object.keys(dst);
return [
findSectionExcludes(srcSections, dstSections),
@@ -43,64 +48,78 @@ function extractSections (src: Record<string, Record<string, any>>, dst: Record<
];
}
function findMethodExcludes (src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>): string[] {
function findMethodExcludes <T> (src: Sections<T>, dst: Sections<T>): string[] {
const srcSections = Object.keys(src);
const dstSections = Object.keys(dst);
const dstSections = findSectionIncludes(Object.keys(dst), srcSections);
const excludes: string[] = [];
return dstSections
.filter((section) => srcSections.includes(section))
.reduce((rmMethods: string[], section): string[] => {
const srcMethods = Object.keys(src[section]);
for (let s = 0; s < dstSections.length; s++) {
const section = dstSections[s];
const srcMethods = Object.keys(src[section]);
const dstMethods = Object.keys(dst[section]);
return rmMethods.concat(
...Object
.keys(dst[section])
.filter((method) => !srcMethods.includes(method))
.map((method) => `${section}.${method}`)
);
}, []);
excludes.push(
...dstMethods
.filter((m) => !srcMethods.includes(m))
.map((m) => `${section}.${m}`)
);
}
return excludes;
}
function extractMethods (src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>): StringsStrings {
function extractMethods <T> (src: Sections<T>, dst: Sections<T>): StringsStrings {
return [
findMethodExcludes(dst, src),
findMethodExcludes(src, dst)
];
}
function lazySection <T> (src: Methods<T>, dst: Methods<T>): void {
const creator = (m: string) => src[m];
const methods = Object.keys(src);
for (let i = 0; i < methods.length; i++) {
const method = methods[i];
// We use hasOwnproperty here to only check for the existence of the key,
// instead of reading dst[section][method] which will evaluate when already
// set as a lazy value previously
if (!Object.prototype.hasOwnProperty.call(dst, method)) {
lazyMethod(dst, method, creator);
}
}
}
/**
* Takes a decorated api section (e.g. api.tx) and augment it with the details. It does not override what is
* already available, but rather just adds new missing ites into the result object.
* @description Takes a decorated api section (e.g. api.tx) and augment it with the details. It does not override what is
* already available, but rather just adds new missing items into the result object.
* @internal
*/
export function augmentObject (prefix: string | null, src: Record<string, Record<string, unknown>>, dst: Record<string, Record<string, unknown>>, fromEmpty = false): Record<string, Record<string, any>> {
if (fromEmpty) {
Object.keys(dst).forEach((key): void => {
delete dst[key];
});
}
export function augmentObject <T> (prefix: string | null, src: Sections<T>, dst: Sections<T>, fromEmpty = false): Sections<T> {
fromEmpty && objectClear(dst);
// NOTE: This part is slightly problematic since it will get the
// values for at least all the sections and the names of the methods
// (Since methods won't be decorated before lazy, this _may_ be ok)
if (prefix && Object.keys(dst).length) {
warn(prefix, 'modules', extractSections(src, dst));
warn(prefix, 'calls', extractMethods(src, dst));
}
return Object
.keys(src)
.reduce((newSection, sectionName): Record<string, Record<string, unknown>> => {
const section = src[sectionName];
const sections = Object.keys(src);
newSection[sectionName] = Object
.keys(section)
.reduce((result, methodName): Record<string, unknown> => {
// TODO When it does match, check the actual details and warn when there are differences
if (!result[methodName]) {
result[methodName] = section[methodName];
}
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
return result;
}, dst[sectionName] || {});
// We don't set here with a lazy interface, we decorate based
// on the top-level structure (this bypasses adding lazy onto lazy)
if (!dst[section]) {
dst[section] = {};
}
return newSection;
}, dst);
lazySection(src[section], dst[section]);
}
return dst;
}
+27 -43
View File
@@ -4,55 +4,39 @@
import type { AnyFunction } from '@polkadot/types/types';
import type { ApiTypes, DecorateMethod, MethodResult } from '../types';
import { lazyDeriveSection } from '@polkadot/api-derive';
type AnyDeriveSection = Record<string, AnyFunction>;
// Most generic typings for `api.derive.*.*`
type AnyDerive = Record<string, Record<string, AnyFunction>>;
type AnyDerive = Record<string, AnyDeriveSection>;
// Exact typings for a particular section `api.derive.section.*`
type DeriveSection<ApiType extends ApiTypes, Section extends Record<string, AnyFunction>> = { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> };
type DeriveSection<ApiType extends ApiTypes, Section extends AnyDeriveSection> = {
[MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]>
};
// Exact typings for all sections `api.derive.*.*`
export type DeriveAllSections<ApiType extends ApiTypes, AllSections extends AnyDerive> = { [SectionName in keyof AllSections]: DeriveSection<ApiType, AllSections[SectionName]> };
// A technically unsafe version of Object.keys(obj) that assumes that
// obj only has known properties of T
function keys<T extends Record<string, unknown>> (obj: T): (keyof T)[] {
return Object.keys(obj);
}
/**
* This is a methods decorator which keeps all type information.
*/
function decorateMethods<ApiType extends ApiTypes, Section extends Record<string, AnyFunction>> (section: Section, decorateMethod: DecorateMethod<ApiType>): DeriveSection<ApiType, Section> {
return keys(section).reduce(
<MethodName extends keyof Section>(
acc: DeriveSection<ApiType, Section>,
methodName: MethodName
): DeriveSection<ApiType, Section> => {
const method = section[methodName];
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
acc[methodName] = decorateMethod(method) as MethodResult<ApiType, Section[MethodName]>;
return acc;
},
{} as DeriveSection<ApiType, Section>
);
}
export type DeriveAllSections<ApiType extends ApiTypes, AllSections extends AnyDerive> = {
[SectionName in keyof AllSections]: DeriveSection<ApiType, AllSections[SectionName]>
};
/**
* This is a section decorator which keeps all type information.
*/
export function decorateSections<ApiType extends ApiTypes, AllSections extends AnyDerive> (
allSections: AllSections,
decorateMethod: DecorateMethod<ApiType>
): DeriveAllSections<ApiType, AllSections> {
return keys(allSections).reduce(
<MethodName extends keyof AllSections>(
acc: DeriveAllSections<ApiType, AllSections>,
sectionName: MethodName
): DeriveAllSections<ApiType, AllSections> => {
acc[sectionName] = decorateMethods(allSections[sectionName], decorateMethod);
export function decorateDeriveSections<ApiType extends ApiTypes, A extends AnyDerive> (decorateMethod: DecorateMethod<ApiType>, derives: AnyDerive): DeriveAllSections<ApiType, A> {
const getKeys = (s: string) =>
Object.keys(derives[s]);
return acc;
},
{} as DeriveAllSections<ApiType, AllSections>
);
const creator = (s: string, m: string) =>
decorateMethod(derives[s][m]) as AnyFunction;
const result: AnyDerive = {};
const names = Object.keys(derives);
for (let i = 0; i < names.length; i++) {
lazyDeriveSection(result, names[i], getKeys, creator);
}
return result as DeriveAllSections<ApiType, A>;
}
+15 -17
View File
@@ -7,24 +7,22 @@ import { l } from './logging';
export function filterEvents (extHash: H256, { block: { extrinsics, header } }: SignedBlock, allEvents: EventRecord[], status: ExtrinsicStatus): EventRecord[] | undefined {
// extrinsics to hashes
const myHash = extHash.toHex();
const allHashes = extrinsics.map((ext): string => ext.hash.toHex());
// find the index of our extrinsic in the block
const index = allHashes.indexOf(myHash);
// if we do get the block after finalized, it _should_ be there
if (index === -1) {
// only warn on filtering with isInBlock (finalization finalizes after)
if (status.isInBlock) {
l.warn(`block ${header.hash.toHex()}: Unable to find extrinsic ${myHash} inside ${allHashes.join(', ')}`);
for (const [index, extrinsic] of extrinsics.entries()) {
if (extrinsic.hash.eq(extHash)) {
return allEvents.filter(({ phase }) =>
// only ApplyExtrinsic has the extrinsic index
phase.isApplyExtrinsic && phase.asApplyExtrinsic.eqn(index)
);
}
return;
}
return allEvents.filter(({ phase }) =>
// only ApplyExtrinsic has the extrinsic index
phase.isApplyExtrinsic && phase.asApplyExtrinsic.eqn(index)
);
// if we do get the block after finalized, it _should_ be there
// only warn on filtering with isInBlock (finalization finalizes after)
if (status.isInBlock) {
const allHashes = extrinsics.map((ext): string => ext.hash.toHex());
l.warn(`block ${header.hash.toHex()}: Unable to find extrinsic ${extHash.toHex()} inside ${allHashes.join(', ')}`);
}
return undefined;
}
+23 -19
View File
@@ -1,31 +1,35 @@
{
"name": "@polkadot/rpc-core",
"version": "6.4.2",
"type": "module",
"author": "Jaco Greeff <jacogr@gmail.com>",
"bugs": "https://github.com/polkadot-js/api/issues",
"contributors": [],
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
"engines": {
"node": ">=14.0.0"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"license": "Apache-2.0",
"maintainers": [],
"name": "@polkadot/rpc-core",
"repository": {
"directory": "packages/rpc-core",
"type": "git",
"url": "https://github.com/polkadot-js/api.git"
},
"sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"engines": {
"node": ">=14.0.0"
},
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"type": "module",
"version": "6.10.2",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.15.4",
"@polkadot/rpc-provider": "6.4.2",
"@polkadot/types": "6.4.2",
"@polkadot/util": "^7.5.1",
"@babel/runtime": "^7.16.3",
"@polkadot/rpc-provider": "6.10.2",
"@polkadot/types": "6.10.2",
"@polkadot/util": "^8.0.4",
"rxjs": "^7.4.0"
},
"devDependencies": {
"@polkadot/keyring": "^7.5.1"
"@polkadot/keyring": "^8.0.4"
}
}
+50 -61
View File
@@ -7,12 +7,12 @@ import type { StorageKey, Vec } from '@polkadot/types';
import type { Hash } from '@polkadot/types/interfaces';
import type { AnyJson, Codec, DefinitionRpc, DefinitionRpcExt, DefinitionRpcSub, Registry } from '@polkadot/types/types';
import type { Memoized } from '@polkadot/util/types';
import type { RpcInterface, RpcInterfaceMethod } from './types';
import type { RpcInterfaceMethod } from './types';
import { Observable, publishReplay, refCount } from 'rxjs';
import { rpcDefinitions } from '@polkadot/types';
import { assert, hexToU8a, isFunction, isNull, isUndefined, logger, memoize, u8aToU8a } from '@polkadot/util';
import { assert, hexToU8a, isFunction, isNull, isUndefined, lazyMethod, logger, memoize, objectSpread, u8aToU8a } from '@polkadot/util';
import { drr, refCountDelay } from './util';
@@ -24,8 +24,6 @@ interface StorageChangeSetJSON {
changes: [string, string | null][];
}
type OutputType = 'json' | 'raw' | 'scale';
const l = logger('rpc-core');
const EMPTY_META = {
@@ -143,84 +141,79 @@ export class RpcCore {
});
}
public addUserInterfaces<Section extends keyof RpcInterface> (userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>): void {
public addUserInterfaces (userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>): void {
// add any extra user-defined sections
this.sections.push(...Object.keys(userRpc).filter((key) => !this.sections.includes(key)));
this.sections.push(...Object.keys(userRpc).filter((k) => !this.sections.includes(k)));
// decorate the sections with base and user methods
this.sections.forEach((sectionName): void => {
(this as Record<string, unknown>)[sectionName as Section] ||= {};
for (let s = 0; s < this.sections.length; s++) {
const section = this.sections[s];
const defs = objectSpread<Record<string, DefinitionRpc | DefinitionRpcSub>>({}, rpcDefinitions[section as 'babe'], userRpc[section]);
const methods = Object.keys(defs);
const section = (this as Record<string, unknown>)[sectionName as Section] as Record<string, unknown>;
for (let m = 0; m < methods.length; m++) {
const method = methods[m];
const def = defs[method];
const jsonrpc = def.endpoint || `${section}_${method}`;
Object
.entries({
...this._createInterface(sectionName, rpcDefinitions[sectionName as 'babe'] || {}),
...this._createInterface(sectionName, userRpc[sectionName] || {})
})
.forEach(([key, value]): void => {
section[key] ||= value;
});
});
if (!this.mapping.has(jsonrpc)) {
const isSubscription = !!(def as DefinitionRpcSub).pubsub;
if (!(this as Record<string, unknown>)[section]) {
(this as Record<string, unknown>)[section] = {};
}
this.mapping.set(jsonrpc, objectSpread({}, def, { isSubscription, jsonrpc, method, section }));
lazyMethod(this[section as 'connect'], method, () =>
isSubscription
? this._createMethodSubscribe(section, method, def as DefinitionRpcSub)
: this._createMethodSend(section, method, def)
);
}
}
}
}
private _createInterface<Section extends keyof RpcInterface> (section: string, methods: Record<string, DefinitionRpc | DefinitionRpcSub>): RpcInterface[Section] {
return Object
.entries(methods)
.filter(([method, { endpoint }]) => !this.mapping.has(endpoint || `${section}_${method}`))
.reduce((exposed, [method, { endpoint }]): RpcInterface[Section] => {
const def = methods[method];
const isSubscription = !!(def as DefinitionRpcSub).pubsub;
const jsonrpc = endpoint || `${section}_${method}`;
private _memomize (creator: <T> (isScale: boolean) => (...values: unknown[]) => Observable<T>, def: DefinitionRpc): Memoized<RpcInterfaceMethod> {
const memoOpts = { getInstanceId: () => this.#instanceId };
const memoized = memoize(creator(true) as RpcInterfaceMethod, memoOpts);
this.mapping.set(jsonrpc, { ...def, isSubscription, jsonrpc, method, section });
(exposed as Record<string, unknown>)[method] = isSubscription
? this._createMethodSubscribe(section, method, def as DefinitionRpcSub)
: this._createMethodSend(section, method, def);
return exposed;
}, {} as RpcInterface[Section]);
}
private _memomize (creator: <T> (outputAs: OutputType) => (...values: unknown[]) => Observable<T>, def: DefinitionRpc): Memoized<RpcInterfaceMethod> {
const memoized = memoize(creator('scale') as RpcInterfaceMethod, {
getInstanceId: () => this.#instanceId
});
memoized.json = creator('json');
memoized.raw = creator('raw');
memoized.raw = memoize(creator(false), memoOpts);
memoized.meta = def;
return memoized;
}
private _formatResult <T> (isScale: boolean, registry: Registry, blockHash: string | Uint8Array | null | undefined, method: string, def: DefinitionRpc, params: Codec[], result: unknown): T {
return isScale
? this._formatOutput(registry, blockHash, method, def, params, result) as unknown as T
: result as T;
}
private _createMethodSend (section: string, method: string, def: DefinitionRpc): RpcInterfaceMethod {
const rpcName = def.endpoint || `${section}_${method}`;
const hashIndex = def.params.findIndex(({ isHistoric }) => isHistoric);
let memoized: null | Memoized<RpcInterfaceMethod> = null;
// execute the RPC call, doing a registry swap for historic as applicable
const callWithRegistry = async <T> (outputAs: OutputType, values: unknown[]): Promise<T> => {
const callWithRegistry = async <T> (isScale: boolean, values: unknown[]): Promise<T> => {
const blockHash = hashIndex === -1
? null
: values[hashIndex] as (Uint8Array | string | null | undefined);
const { registry } = outputAs === 'scale' && blockHash && this.#getBlockRegistry
const { registry } = isScale && blockHash && this.#getBlockRegistry
? await this.#getBlockRegistry(u8aToU8a(blockHash))
: { registry: this.#registryDefault };
const params = this._formatInputs(registry, null, def, values);
const data = await this.provider.send<AnyJson>(rpcName, params.map((param) => param.toJSON()));
const result = await this.provider.send<AnyJson>(rpcName, params.map((p) => p.toJSON()), !!blockHash);
return outputAs === 'scale'
? this._formatOutput(registry, blockHash, method, def, params, data) as unknown as T
: registry.createType(outputAs === 'raw' ? 'Raw' : 'Json', data) as unknown as T;
return this._formatResult(isScale, registry, blockHash, method, def, params, result);
};
const creator = <T> (outputAs: OutputType) => (...values: unknown[]): Observable<T> => {
const isDelayed = outputAs === 'scale' && hashIndex !== -1 && !!values[hashIndex];
const creator = <T> (isScale: boolean) => (...values: unknown[]): Observable<T> => {
const isDelayed = isScale && hashIndex !== -1 && !!values[hashIndex];
return new Observable((observer: Observer<T>): VoidCallback => {
callWithRegistry<T>(outputAs, values)
callWithRegistry<T>(isScale, values)
.then((value): void => {
observer.next(value);
observer.complete();
@@ -269,7 +262,7 @@ export class RpcCore {
const subType = `${section}_${updateType}`;
let memoized: null | Memoized<RpcInterfaceMethod> = null;
const creator = <T> (outputAs: OutputType) => (...values: unknown[]): Observable<T> => {
const creator = <T> (isScale: boolean) => (...values: unknown[]): Observable<T> => {
return new Observable((observer: Observer<T>): VoidCallback => {
// Have at least an empty promise, as used in the unsubscribe
let subscriptionPromise: Promise<number | string | null> = Promise.resolve(null);
@@ -283,9 +276,9 @@ export class RpcCore {
try {
const params = this._formatInputs(registry, null, def, values);
const paramsJson = params.map((param) => param.toJSON());
const paramsJson = params.map((p) => p.toJSON());
const update = (error?: Error | null, result?: T): void => {
const update = (error?: Error | null, result?: unknown): void => {
if (error) {
logErrorMessage(method, def, error);
@@ -293,11 +286,7 @@ export class RpcCore {
}
try {
observer.next(
outputAs === 'scale'
? this._formatOutput(registry, null, method, def, params, result) as unknown as T
: registry.createType(outputAs === 'raw' ? 'Raw' : 'Json', result) as unknown as T
);
observer.next(this._formatResult(isScale, registry, null, method, def, params, result));
} catch (error) {
observer.error(error);
}
+1 -1
View File
@@ -62,7 +62,7 @@ describe('methodSend', (): void => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
method(new Uint8Array([2 << 2, 0x12, 0x34])).subscribe((): void => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
expect(provider.send).toHaveBeenCalledWith('test_blah', ['0x1234']);
expect(provider.send).toHaveBeenCalledWith('test_blah', ['0x1234'], false);
done();
});
});
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-core', version: '6.4.2' };
export const packageInfo = { name: '@polkadot/rpc-core', version: '6.10.2' };
-18
View File
@@ -1,11 +1,8 @@
// Copyright 2017-2021 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { RpcInterface } from '@polkadot/rpc-core/types.jsonrpc';
import { of } from 'rxjs';
import { MockProvider } from '@polkadot/rpc-provider/mock';
import { TypeRegistry } from '@polkadot/types/create';
@@ -25,21 +22,6 @@ describe('replay', (): void => {
await provider.disconnect();
});
it('subscribes via the rpc section', (done): void => {
// we don't honor types or number of params here
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(rpc.chain as any).getBlockHash = jest.fn((): Observable<number> => of(1));
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
(rpc.chain as any).getBlockHash(123, false).subscribe((): void => {
expect(
// eslint-disable-next-line @typescript-eslint/unbound-method
rpc.chain.getBlockHash
).toHaveBeenCalledWith(123, false);
done();
});
});
it('returns the observable value', (done): void => {
rpc.system.chain().subscribe((value: any): void => {
if (value) {
+1 -8
View File
@@ -1,11 +1,4 @@
// Copyright 2017-2021 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0
// FIXME, this whole file needs to move to API
import type { AnyFunction } from '@polkadot/types/types';
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface RpcInterface {}
export type AugmentedRpc<F extends AnyFunction> = F;
export const __PHANTOM_RPC = 'phantom-rpc';
+2 -4
View File
@@ -2,14 +2,12 @@
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { Json, Raw } from '@polkadot/types';
import type { Codec, DefinitionRpc } from '@polkadot/types/types';
export * from './types.jsonrpc';
export * from '@polkadot/rpc-core/types.jsonrpc';
export interface RpcInterfaceMethod {
<T extends Codec> (...params: unknown[]): Observable<T>;
json (...params: unknown[]): Observable<Json>;
raw (...params: unknown[]): Observable<Raw>;
raw (...params: unknown[]): Observable<unknown>;
meta: DefinitionRpc;
}
+29 -25
View File
@@ -1,37 +1,41 @@
{
"name": "@polkadot/rpc-provider",
"version": "6.4.2",
"type": "module",
"author": "Jaco Greeff <jacogr@gmail.com>",
"bugs": "https://github.com/polkadot-js/api/issues",
"contributors": [],
"description": "Transport providers for the API",
"main": "index.js",
"engines": {
"node": ">=14.0.0"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"license": "Apache-2.0",
"maintainers": [],
"name": "@polkadot/rpc-provider",
"repository": {
"directory": "packages/rpc-provider",
"type": "git",
"url": "https://github.com/polkadot-js/api.git"
},
"sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"engines": {
"node": ">=14.0.0"
},
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"type": "module",
"version": "6.10.2",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.15.4",
"@polkadot/types": "6.4.2",
"@polkadot/util": "^7.5.1",
"@polkadot/util-crypto": "^7.5.1",
"@polkadot/x-fetch": "^7.5.1",
"@polkadot/x-global": "^7.5.1",
"@polkadot/x-ws": "^7.5.1",
"@babel/runtime": "^7.16.3",
"@polkadot/types": "6.10.2",
"@polkadot/util": "^8.0.4",
"@polkadot/util-crypto": "^8.0.4",
"@polkadot/x-fetch": "^8.0.4",
"@polkadot/x-global": "^8.0.4",
"@polkadot/x-ws": "^8.0.4",
"eventemitter3": "^4.0.7"
},
"devDependencies": {
"@polkadot/keyring": "^7.5.1",
"@polkadot/types": "6.4.2",
"mock-socket": "^9.0.5",
"nock": "^13.1.3"
"@polkadot/keyring": "^8.0.4",
"@polkadot/types": "6.10.2",
"mock-socket": "^9.0.8",
"nock": "^13.2.1"
}
}
+20 -1
View File
@@ -8,6 +8,7 @@ import { fetch } from '@polkadot/x-fetch';
import { RpcCoder } from '../coder';
import defaults from '../defaults';
import { LRUCache } from '../lru';
const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
@@ -34,6 +35,8 @@ const l = logger('api-http');
* @see [[WsProvider]]
*/
export class HttpProvider implements ProviderInterface {
readonly #callCache = new LRUCache();
readonly #coder: RpcCoder;
readonly #endpoint: string;
@@ -103,8 +106,24 @@ export class HttpProvider implements ProviderInterface {
/**
* @summary Send HTTP POST Request with Body to configured HTTP Endpoint.
*/
public async send <T> (method: string, params: unknown[]): Promise<T> {
public async send <T> (method: string, params: unknown[], isCacheable?: boolean): Promise<T> {
const body = this.#coder.encodeJson(method, params);
let resultPromise: Promise<T> | null = isCacheable
? this.#callCache.get(body) as Promise<T>
: null;
if (!resultPromise) {
resultPromise = this.#send(body);
if (isCacheable) {
this.#callCache.set(body, resultPromise);
}
}
return resultPromise;
}
async #send <T> (body: string): Promise<T> {
const response = await fetch(this.#endpoint, {
body,
headers: {
+55
View File
@@ -0,0 +1,55 @@
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { LRUCache } from './lru';
describe('LRUCache', (): void => {
it('allows getting of items below capacity', (): void => {
const keys = ['1', '2', '3', '4'];
const lru = new LRUCache(4);
keys.forEach((k) => lru.set(k, `${k}${k}${k}`));
expect(lru.keys().join(', ')).toEqual(keys.reverse().join(', '));
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
keys.forEach((k) => expect(lru.get(k)).toEqual(`${k}${k}${k}`));
});
it('drops items when at capacity', (): void => {
const keys = ['1', '2', '3', '4', '5', '6'];
const lru = new LRUCache(4);
keys.forEach((k) => lru.set(k, `${k}${k}${k}`));
expect(lru.keys().join(', ')).toEqual(keys.slice(2).reverse().join(', '));
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
keys.slice(2).forEach((k) => expect(lru.get(k)).toEqual(`${k}${k}${k}`));
});
it('adjusts the order as they are used', (): void => {
const keys = ['1', '2', '3', '4', '5'];
const lru = new LRUCache(4);
keys.forEach((k) => lru.set(k, `${k}${k}${k}`));
expect(lru.entries()).toEqual([['5', '555'], ['4', '444'], ['3', '333'], ['2', '222']]);
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
lru.get('3');
expect(lru.entries()).toEqual([['3', '333'], ['5', '555'], ['4', '444'], ['2', '222']]);
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
lru.set('4', '4433');
expect(lru.entries()).toEqual([['4', '4433'], ['3', '333'], ['5', '555'], ['2', '222']]);
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
lru.set('6', '666');
expect(lru.entries()).toEqual([['6', '666'], ['4', '4433'], ['3', '333'], ['5', '555']]);
expect(lru.length === lru.lengthData && lru.length === lru.lengthRefs).toBe(true);
});
});
+128
View File
@@ -0,0 +1,128 @@
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
const DEFAULT_CAPACITY = 2048;
class LRUNode {
public readonly key: string;
public next: LRUNode;
public prev: LRUNode;
constructor (key: string) {
this.key = key;
this.next = this.prev = this;
}
}
// https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
export class LRUCache {
readonly capacity: number;
readonly #data: Map<string, unknown> = new Map();
readonly #refs: Map<string, LRUNode> = new Map();
#length = 0;
#head: LRUNode;
#tail: LRUNode;
constructor (capacity = DEFAULT_CAPACITY) {
this.capacity = capacity;
this.#head = this.#tail = new LRUNode('<empty>');
}
get length (): number {
return this.#length;
}
get lengthData (): number {
return this.#data.size;
}
get lengthRefs (): number {
return this.#refs.size;
}
entries (): [string, unknown][] {
const keys = this.keys();
const entries = new Array<[string, unknown]>(keys.length);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
entries[i] = [key, this.#data.get(key)];
}
return entries;
}
keys (): string[] {
const keys: string[] = [];
if (this.#length) {
let curr = this.#head;
while (curr !== this.#tail) {
keys.push(curr.key);
curr = curr.next;
}
keys.push(curr.key);
}
return keys;
}
get <T> (key: string): T | null {
const data = this.#data.get(key);
if (data) {
this.#toHead(key);
return data as T;
}
return null;
}
set <T> (key: string, value: T): void {
if (this.#data.has(key)) {
this.#toHead(key);
} else {
const node = new LRUNode(key);
this.#refs.set(node.key, node);
if (this.length === 0) {
this.#head = this.#tail = node;
} else {
this.#head.prev = node;
node.next = this.#head;
this.#head = node;
}
if (this.#length === this.capacity) {
this.#data.delete(this.#tail.key);
this.#refs.delete(this.#tail.key);
this.#tail = this.#tail.prev;
} else {
this.#length += 1;
}
}
this.#data.set(key, value);
}
#toHead (key: string): void {
const ref = this.#refs.get(key);
if (ref && ref !== this.#head) {
ref.prev.next = ref.next;
ref.next.prev = ref.prev;
ref.next = this.#head;
this.#head.prev = ref;
this.#head = ref;
}
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-provider', version: '6.4.2' };
export const packageInfo = { name: '@polkadot/rpc-provider', version: '6.10.2' };
+1 -1
View File
@@ -49,7 +49,7 @@ export interface ProviderInterface {
connect (): Promise<void>;
disconnect (): Promise<void>;
on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void;
send <T = any> (method: string, params: unknown[]): Promise<T>;
send <T = any> (method: string, params: unknown[], isCacheable?: boolean): Promise<T>;
subscribe (type: string, method: string, params: unknown[], cb: ProviderInterfaceCallback): Promise<number | string>;
unsubscribe (type: string, method: string, id: number | string): Promise<boolean>;
}
+32 -10
View File
@@ -7,12 +7,13 @@ import type { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, Pro
import EventEmitter from 'eventemitter3';
import { assert, isChildClass, isNull, isUndefined, logger } from '@polkadot/util';
import { assert, isChildClass, isNull, isUndefined, logger, objectSpread } from '@polkadot/util';
import { xglobal } from '@polkadot/x-global';
import { WebSocket } from '@polkadot/x-ws';
import { RpcCoder } from '../coder';
import defaults from '../defaults';
import { LRUCache } from '../lru';
import { getWSErrorString } from './errors';
interface SubscriptionHandler {
@@ -40,6 +41,8 @@ const ALIASES: { [index: string]: string } = {
const RETRY_DELAY = 2500;
const MEGABYTE = 1024 * 1024;
const l = logger('api-ws');
function eraseRecord<T> (record: Record<string, T>, cb?: (item: T) => void): void {
@@ -73,6 +76,8 @@ function eraseRecord<T> (record: Record<string, T>, cb?: (item: T) => void): voi
* @see [[HttpProvider]]
*/
export class WsProvider implements ProviderInterface {
readonly #callCache = new LRUCache();
readonly #coder: RpcCoder;
readonly #endpoints: string[];
@@ -179,9 +184,11 @@ export class WsProvider implements ProviderInterface {
// default: true
fragmentOutgoingMessages: true,
// default: 16K (bump, the Node has issues with too many fragments, e.g. on setCode)
fragmentationThreshold: 256 * 1024,
// default: 8MB (however Polkadot api.query.staking.erasStakers.entries(356) is over that)
maxReceivedMessageSize: 16 * 1024 * 1024
fragmentationThreshold: 1 * MEGABYTE,
// default: 1MiB (also align with maxReceivedMessageSize)
maxReceivedFrameSize: 24 * MEGABYTE,
// default: 8MB (however Polkadot api.query.staking.erasStakers.entries(356) is over that, 16M is ok there)
maxReceivedMessageSize: 24 * MEGABYTE
});
this.#websocket.onclose = this.#onSocketClose;
@@ -256,12 +263,28 @@ export class WsProvider implements ProviderInterface {
* @param params Encoded parameters as applicable for the method
* @param subscription Subscription details (internally used)
*/
public send <T = any> (method: string, params: unknown[], subscription?: SubscriptionHandler): Promise<T> {
public send <T = any> (method: string, params: unknown[], isCacheable?: boolean, subscription?: SubscriptionHandler): Promise<T> {
const body = this.#coder.encodeJson(method, params);
let resultPromise: Promise<T> | null = isCacheable
? this.#callCache.get(body) as Promise<T>
: null;
if (!resultPromise) {
resultPromise = this.#send(body, method, params, subscription);
if (isCacheable) {
this.#callCache.set(body, resultPromise);
}
}
return resultPromise;
}
async #send <T> (json: string, method: string, params: unknown[], subscription?: SubscriptionHandler): Promise<T> {
return new Promise<T>((resolve, reject): void => {
try {
assert(this.isConnected && !isNull(this.#websocket), 'WebSocket is not connected');
const json = this.#coder.encodeJson(method, params);
const id = this.#coder.getId();
const callback = (error?: Error | null, result?: T): void => {
@@ -305,7 +328,7 @@ export class WsProvider implements ProviderInterface {
* ```
*/
public subscribe (type: string, method: string, params: unknown[], callback: ProviderInterfaceCallback): Promise<number | string> {
return this.send<number | string>(method, params, { callback, type });
return this.send<number | string>(method, params, false, { callback, type });
}
/**
@@ -406,11 +429,10 @@ export class WsProvider implements ProviderInterface {
if (subscription) {
const subId = `${subscription.type}::${result}`;
this.#subscriptions[subId] = {
...subscription,
this.#subscriptions[subId] = objectSpread({}, subscription, {
method,
params
};
});
// if we have a result waiting for this subscription already
if (this.#waitingForId[subId]) {
+27 -23
View File
@@ -1,16 +1,27 @@
{
"name": "@polkadot/typegen",
"version": "6.4.2",
"type": "module",
"author": "Jaco Greeff <jacogr@gmail.com>",
"bugs": "https://github.com/polkadot-js/api/issues",
"contributors": [],
"description": "Type generation scripts",
"main": "index.js",
"engines": {
"node": ">=14.0.0"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
"license": "Apache-2.0",
"maintainers": [],
"name": "@polkadot/typegen",
"repository": {
"directory": "packages/typegen",
"type": "git",
"url": "https://github.com/polkadot-js/api.git"
},
"sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"engines": {
"node": ">=14.0.0"
},
"type": "module",
"version": "6.10.2",
"main": "index.js",
"bin": {
"polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.cjs",
"polkadot-types-from-chain": "./scripts/polkadot-types-from-chain.cjs",
@@ -18,28 +29,21 @@
"polkadot-types-internal-interfaces": "./scripts/polkadot-types-internal-interfaces.cjs",
"polkadot-types-internal-metadata": "./scripts/polkadot-types-internal-metadata.cjs"
},
"repository": "github:polkadot-js/api",
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
"dependencies": {
"@babel/core": "^7.15.8",
"@babel/register": "^7.15.3",
"@babel/runtime": "^7.15.4",
"@polkadot/api": "6.4.2",
"@polkadot/rpc-provider": "6.4.2",
"@polkadot/types": "6.4.2",
"@polkadot/types-support": "6.4.2",
"@polkadot/util": "^7.5.1",
"@babel/core": "^7.16.0",
"@babel/register": "^7.16.0",
"@babel/runtime": "^7.16.3",
"@polkadot/api": "6.10.2",
"@polkadot/rpc-provider": "6.10.2",
"@polkadot/types": "6.10.2",
"@polkadot/types-support": "6.10.2",
"@polkadot/util": "^8.0.4",
"handlebars": "^4.7.7",
"websocket": "^1.0.34",
"yargs": "^17.2.1"
},
"devDependencies": {
"@types/websocket": "^1.0.4",
"@types/yargs": "^17.0.4"
"@types/yargs": "^17.0.7"
}
}
+17 -4
View File
@@ -4,6 +4,7 @@
import path from 'path';
import yargs from 'yargs';
import { Definitions } from '@polkadot/types/types';
import { formatNumber } from '@polkadot/util';
import { WebSocket } from '@polkadot/x-ws';
@@ -18,12 +19,24 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS
? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) as Record<string, any> }
: {};
generateDefaultConsts(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict);
let customLookupDefinitions;
try {
customLookupDefinitions = {
rpc: {},
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires
types: require(path.join(process.cwd(), output, 'lookup.ts')).default
} as Definitions;
} catch (error) {
console.log('No custom definitions found.');
}
generateDefaultConsts(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
generateDefaultErrors(path.join(process.cwd(), output, 'augment-api-errors.ts'), metaHex, extraTypes, isStrict);
generateDefaultEvents(path.join(process.cwd(), output, 'augment-api-events.ts'), metaHex, extraTypes, isStrict);
generateDefaultQuery(path.join(process.cwd(), output, 'augment-api-query.ts'), metaHex, extraTypes, isStrict);
generateDefaultEvents(path.join(process.cwd(), output, 'augment-api-events.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
generateDefaultQuery(path.join(process.cwd(), output, 'augment-api-query.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
generateDefaultRpc(path.join(process.cwd(), output, 'augment-api-rpc.ts'), extraTypes);
generateDefaultTx(path.join(process.cwd(), output, 'augment-api-tx.ts'), metaHex, extraTypes, isStrict);
generateDefaultTx(path.join(process.cwd(), output, 'augment-api-tx.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions);
writeFile(path.join(process.cwd(), output, 'augment-api.ts'), (): string =>
[
+14 -2
View File
@@ -8,11 +8,16 @@ import * as substrateDefs from '@polkadot/types/interfaces/definitions';
import { generateInterfaceTypes } from './generate/interfaceRegistry';
import { generateTsDef } from './generate/tsDef';
import { generateDefaultLookup } from './generate';
type ArgV = { input: string; package: string };
type ArgV = { input: string; package: string; endpoint?: string; };
export function main (): void {
const { input, package: pkg } = yargs.strict().options({
const { endpoint, input, package: pkg } = yargs.strict().options({
endpoint: {
description: 'The endpoint to connect to (e.g. wss://kusama-rpc.polkadot.io) or relative path to a file containing the JSON output of an RPC state_getMetadata call',
type: 'string'
},
input: {
description: 'The directory to use for the user definitions',
required: true,
@@ -25,6 +30,13 @@ export function main (): void {
}
}).argv as ArgV;
if (endpoint) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const metaHex = (require(path.join(process.cwd(), endpoint)) as Record<string, string>).result;
generateDefaultLookup(path.join(process.cwd(), input), metaHex);
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const userDefs = require(path.join(process.cwd(), input, 'definitions.ts')) as Record<string, any>;
const userKeys = Object.keys(userDefs);
+11 -5
View File
@@ -8,6 +8,7 @@ import Handlebars from 'handlebars';
import lookupDefinitions from '@polkadot/types/augment/lookup/definitions';
import * as defaultDefs from '@polkadot/types/interfaces/definitions';
import { Definitions } from '@polkadot/types/types';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, formatType, initMeta, readTemplate, setImports, writeFile } from '../util';
@@ -16,10 +17,15 @@ const template = readTemplate('consts');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
writeFile(dest, (): string => {
const allTypes = {
'@polkadot/types/augment': { lookup: lookupDefinitions },
'@polkadot/types/augment': {
lookup: {
...lookupDefinitions,
...customLookupDefinitions
}
},
'@polkadot/types/interfaces': defaultDefs,
...extraTypes
};
@@ -70,7 +76,7 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
types: ['ApiTypes', 'AugmentedConst', 'QueryableModuleConsts']
}
]
});
@@ -79,8 +85,8 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
const { metadata } = initMeta(data, extraTypes);
return generateForMeta(metadata, dest, extraTypes, isStrict);
return generateForMeta(metadata, dest, extraTypes, isStrict, customLookupDefinitions);
}
+1 -1
View File
@@ -39,7 +39,7 @@ function generateForMeta (meta: Metadata, dest: string, isStrict: boolean): void
types: [
{
file: '@polkadot/api/types',
types: ['ApiTypes']
types: ['ApiTypes', 'AugmentedError', 'ModuleErrors']
}
]
});
+11 -5
View File
@@ -8,6 +8,7 @@ import Handlebars from 'handlebars';
import lookupDefinitions from '@polkadot/types/augment/lookup/definitions';
import * as defaultDefs from '@polkadot/types/interfaces/definitions';
import { Definitions } from '@polkadot/types/types';
import { stringCamelCase } from '@polkadot/util';
import { compareName, createImports, formatType, initMeta, readTemplate, setImports, writeFile } from '../util';
@@ -16,10 +17,15 @@ const template = readTemplate('events');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
writeFile(dest, (): string => {
const allTypes = {
'@polkadot/types/augment': { lookup: lookupDefinitions },
'@polkadot/types/augment': {
lookup: {
...lookupDefinitions,
...customLookupDefinitions
}
},
'@polkadot/types/interfaces': defaultDefs,
...extraTypes
};
@@ -62,7 +68,7 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
types: ['ApiTypes', 'AugmentedEvent', 'ModuleEvents']
}
]
});
@@ -71,8 +77,8 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes,
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
const { metadata } = initMeta(data, extraTypes);
return generateForMeta(metadata, dest, extraTypes, isStrict);
return generateForMeta(metadata, dest, extraTypes, isStrict, customLookupDefinitions);
}
+4 -30
View File
@@ -1,7 +1,8 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { PortableRegistry, PortableType, SiLookupTypeId, SiPath, SiTypeParameter } from '@polkadot/types/interfaces';
import type { PortableType, SiLookupTypeId, SiPath, SiTypeParameter } from '@polkadot/types/interfaces';
import type { PortableRegistry } from '@polkadot/types/metadata';
import type { TypeDef } from '@polkadot/types/types';
import Handlebars from 'handlebars';
@@ -17,7 +18,6 @@ import { isString, stringify } from '@polkadot/util';
import { createImports, exportType, initMeta, readTemplate, writeFile } from '../util';
import { typeEncoders } from './tsDef';
const MAP_ENUMS = ['Call', 'Event', 'Error', 'RawEvent'];
const WITH_TYPEDEF = false;
const generateLookupDefsTmpl = Handlebars.compile(readTemplate('lookup/defs'));
@@ -130,33 +130,7 @@ function expandDefToString ({ lookupNameRoot, type }: TypeDef, indent: number):
}
function getFilteredTypes (lookup: PortableRegistry, exclude: string[] = []): [PortableType, TypeDef][] {
const named = lookup.types.filter(({ id, type: { path } }) => {
const typeDef = lookup.getTypeDef(id);
return (
// We actually only want those with lookupName set
!!typeDef.lookupName &&
!(
path.length === 2 &&
(
(
// Ensure that we match {node, kusama, *}_runtime
path[0].toString().split('_')[1] === 'runtime' &&
!['Call', 'Event'].includes(path[1].toString())
) ||
path[0].toString().startsWith('pallet_')
) &&
// Ensure we strip generics, e.g. Event<T>
MAP_ENUMS.includes(path[1].toString().split('<')[0])
) &&
!(
path.length >= 3 &&
path[path.length - 2].toString() === 'pallet' &&
// As above, cater for generics
MAP_ENUMS.includes(path[path.length - 1].toString().split('<')[0])
)
);
});
const named = lookup.types.filter(({ id }) => !!lookup.getTypeDef(id).lookupName);
const names = named.map(({ id }) => lookup.getName(id));
return named
@@ -260,7 +234,7 @@ export function generateDefaultLookup (destDir = 'packages/types/src/augment/loo
generateLookup(
destDir,
staticData
? [[undefined, staticData]]
? [['lookup', staticData]]
: [
['substrate', staticSubstrate],
['polkadot', staticPolkadot],
+13 -8
View File
@@ -1,9 +1,9 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { PortableRegistry, StorageEntryMetadataLatest } from '@polkadot/types/interfaces/metadata';
import type { Metadata } from '@polkadot/types/metadata/Metadata';
import type { Registry } from '@polkadot/types/types';
import type { StorageEntryMetadataLatest } from '@polkadot/types/interfaces';
import type { Metadata, PortableRegistry } from '@polkadot/types/metadata';
import type { Definitions, Registry } from '@polkadot/types/types';
import type { ExtraTypes } from './types';
import Handlebars from 'handlebars';
@@ -66,10 +66,15 @@ const template = readTemplate('query');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
writeFile(dest, (): string => {
const allTypes: ExtraTypes = {
'@polkadot/types/augment': { lookup: lookupDefinitions },
'@polkadot/types/augment': {
lookup: {
...lookupDefinitions,
...customLookupDefinitions
}
},
'@polkadot/types/interfaces': defaultDefs,
...extraTypes
};
@@ -120,7 +125,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes']
types: ['ApiTypes', 'AugmentedQuery', 'QueryableStorageEntry', 'QueryableModuleStorage']
}
]
});
@@ -129,8 +134,8 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultQuery (dest = 'packages/api/src/augment/query.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
export function generateDefaultQuery (dest = 'packages/api/src/augment/query.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
const { metadata, registry } = initMeta(data, extraTypes);
return generateForMeta(registry, metadata, dest, extraTypes, isStrict);
return generateForMeta(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions);
}
+5 -1
View File
@@ -134,7 +134,11 @@ export function generateRpcTypes (registry: TypeRegistry, importDefinitions: Rec
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath.replace('@polkadot/types/augment', '@polkadot/types'),
types: Object.keys(imports.localTypes[packagePath])
}))
})),
{
file: '@polkadot/api/types',
types: ['AugmentedRpc']
}
]
});
});
+2 -2
View File
@@ -11,7 +11,7 @@ import path from 'path';
import { getTypeDef, TypeRegistry } from '@polkadot/types/create';
import { TypeDefInfo } from '@polkadot/types/create/types';
import * as defaultDefinitions from '@polkadot/types/interfaces/definitions';
import { assert, isString, stringCamelCase, stringify, stringUpperFirst } from '@polkadot/util';
import { assert, isString, stringify, stringPascalCase } from '@polkadot/util';
import { createImports, exportInterface, exportType, formatType, readTemplate, setImports, TypeImports, writeFile } from '../util';
@@ -56,7 +56,7 @@ function tsEnum (registry: Registry, definitions: Record<string, ModuleTypes>, {
.filter(({ name }) => !!name && !name.startsWith('__Unused'))
.map((def, index): string => {
const { info, lookupName, name = `unknown${index}`, type } = def;
const getter = stringUpperFirst(stringCamelCase(name.replace(' ', '_')));
const getter = stringPascalCase(name.replace(' ', '_'));
const isComplex = [TypeDefInfo.Option, TypeDefInfo.Result, TypeDefInfo.Struct, TypeDefInfo.Tuple, TypeDefInfo.Vec, TypeDefInfo.VecFixed].includes(info);
const asGetter = type === 'Null' || info === TypeDefInfo.DoNotConstruct
? ''
+11 -6
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { Metadata } from '@polkadot/types/metadata/Metadata';
import type { Registry } from '@polkadot/types/types';
import type { Definitions, Registry } from '@polkadot/types/types';
import type { ExtraTypes } from './types';
import Handlebars from 'handlebars';
@@ -29,10 +29,15 @@ const template = readTemplate('tx');
const generateForMetaTemplate = Handlebars.compile(template);
/** @internal */
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean): void {
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
writeFile(dest, (): string => {
const allTypes: ExtraTypes = {
'@polkadot/types/augment': { lookup: lookupDefinitions },
'@polkadot/types/augment': {
lookup: {
...lookupDefinitions,
...customLookupDefinitions
}
},
'@polkadot/types/interfaces': defaultDefs,
...extraTypes
};
@@ -105,7 +110,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
})),
{
file: '@polkadot/api/types',
types: ['ApiTypes', 'SubmittableExtrinsic']
types: ['ApiTypes', 'AugmentedSubmittable', 'SubmittableExtrinsic', 'SubmittableExtrinsicFunction', 'SubmittableModuleExtrinsics']
}
]
});
@@ -114,8 +119,8 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultTx (dest = 'packages/api/src/augment/tx.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void {
export function generateDefaultTx (dest = 'packages/api/src/augment/tx.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
const { metadata, registry } = initMeta(data, extraTypes);
return generateForMeta(registry, metadata, dest, extraTypes, isStrict);
return generateForMeta(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions);
}
+2 -1
View File
@@ -1,7 +1,8 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { MetadataLatest, PortableRegistry, SiLookupTypeId } from '@polkadot/types/interfaces';
import type { MetadataLatest, SiLookupTypeId } from '@polkadot/types/interfaces';
import type { PortableRegistry } from '@polkadot/types/metadata';
import type { Codec, DefinitionRpcParam } from '@polkadot/types/types';
import fs from 'fs';
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/typegen', version: '6.4.2' };
export const packageInfo = { name: '@polkadot/typegen', version: '6.10.2' };
+7 -7
View File
@@ -1,9 +1,9 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/api/types/consts' {
export interface AugmentedConsts<ApiType> {
{{{ imports }}}
export interface AugmentedConsts<ApiType extends ApiTypes> {
{{#each modules}}
{{{name}}}: {
{{#each items}}
@@ -18,12 +18,12 @@ declare module '@polkadot/api/types/consts' {
{{/unless}}
};
{{/each}}
}
} // AugmentedConsts
export interface QueryableConsts<ApiType extends ApiTypes> extends AugmentedConsts<ApiType> {
{{#unless isStrict}}
[key: string]: QueryableModuleConsts;
{{/unless}}
}
}
{{> footer }}
} // QueryableConsts
} // declare module
+7 -7
View File
@@ -1,9 +1,9 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/api/types/errors' {
export interface AugmentedErrors<ApiType> {
{{{ imports }}}
export interface AugmentedErrors<ApiType extends ApiTypes> {
{{#each modules}}
{{{name}}}: {
{{#each items}}
@@ -18,12 +18,12 @@ declare module '@polkadot/api/types/errors' {
{{/unless}}
};
{{/each}}
}
} // AugmentedErrors
export interface DecoratedErrors<ApiType extends ApiTypes> extends AugmentedErrors<ApiType> {
{{#unless isStrict}}
[key: string]: ModuleErrors<ApiType>;
{{/unless}}
}
}
{{> footer }}
} // DecoratedErrors
} // declare module
+7 -7
View File
@@ -1,9 +1,9 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/api/types/events' {
export interface AugmentedEvents<ApiType> {
{{{ imports }}}
export interface AugmentedEvents<ApiType extends ApiTypes> {
{{#each modules}}
{{{name}}}: {
{{#each items}}
@@ -18,12 +18,12 @@ declare module '@polkadot/api/types/events' {
{{/unless}}
};
{{/each}}
}
} // AugmentedEvents
export interface DecoratedEvents<ApiType extends ApiTypes> extends AugmentedEvents<ApiType> {
{{#unless isStrict}}
[key: string]: ModuleEvents<ApiType>;
{{/unless}}
}
}
{{> footer }}
} // DecoratedEvents
} // declare module
@@ -1,12 +1,11 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/types/types/registry' {
{{{ imports }}}
export interface InterfaceTypes {
{{#each items}}
{{{this}}}: {{{this}}};
{{/each}}
}
}
{{> footer }}
} // InterfaceTypes
} // declare module
@@ -2,8 +2,6 @@
/* eslint-disable sort-keys */
import type { DefinitionsTypes } from '../../types';
export default {
{{#each defs}}
{{> docs}}
@@ -11,5 +9,4 @@ export default {
{{{this}}}
{{/each}}
{{/each}}
} as DefinitionsTypes;
{{> footer }}
};
@@ -2,8 +2,6 @@
/* eslint-disable sort-keys */
import type { Definitions } from '../../types';
export default {
rpc: {},
types: {
@@ -14,5 +12,4 @@ export default {
{{/each}}
{{/each}}
}
} as Definitions;
{{> footer }}
};
@@ -1,4 +1,3 @@
{{> header }}
export * from './types';
{{> footer }}
@@ -1,12 +1,10 @@
{{> header }}
{{{ imports }}}
declare module '@polkadot/types/lookup' {
{{{ imports }}}
{{#each items}}
{{#each items}}
{{{this}}}
{{/each}}
}
{{> footer }}
{{/each}}
} // declare module

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