@pezkuwi/api-derive 16.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (304) hide show
  1. package/README.md +30 -0
  2. package/build/accounts/accountId.d.ts +17 -0
  3. package/build/accounts/flags.d.ts +29 -0
  4. package/build/accounts/idAndIndex.d.ts +15 -0
  5. package/build/accounts/idToIndex.d.ts +16 -0
  6. package/build/accounts/identity.d.ts +48 -0
  7. package/build/accounts/index.d.ts +8 -0
  8. package/build/accounts/indexToId.d.ts +15 -0
  9. package/build/accounts/indexes.d.ts +16 -0
  10. package/build/accounts/info.d.ts +18 -0
  11. package/build/accounts/types.d.ts +39 -0
  12. package/build/alliance/index.d.ts +70 -0
  13. package/build/augment.d.ts +1 -0
  14. package/build/bagsList/get.d.ts +12 -0
  15. package/build/bagsList/getExpanded.d.ts +16 -0
  16. package/build/bagsList/index.d.ts +3 -0
  17. package/build/bagsList/listNodes.d.ts +9 -0
  18. package/build/bagsList/types.d.ts +13 -0
  19. package/build/bagsList/util.d.ts +2 -0
  20. package/build/balances/account.d.ts +17 -0
  21. package/build/balances/all.d.ts +20 -0
  22. package/build/balances/index.d.ts +20 -0
  23. package/build/balances/types.d.ts +69 -0
  24. package/build/balances/votingBalances.d.ts +15 -0
  25. package/build/bounties/bounties.d.ts +12 -0
  26. package/build/bounties/helpers/filterBountyProposals.d.ts +2 -0
  27. package/build/bounties/index.d.ts +1 -0
  28. package/build/bundle.d.ts +9 -0
  29. package/build/chain/bestNumber.d.ts +11 -0
  30. package/build/chain/bestNumberFinalized.d.ts +12 -0
  31. package/build/chain/bestNumberLag.d.ts +15 -0
  32. package/build/chain/getBlock.d.ts +15 -0
  33. package/build/chain/getBlockByNumber.d.ts +16 -0
  34. package/build/chain/getHeader.d.ts +16 -0
  35. package/build/chain/index.d.ts +10 -0
  36. package/build/chain/subscribeFinalizedBlocks.d.ts +14 -0
  37. package/build/chain/subscribeFinalizedHeads.d.ts +22 -0
  38. package/build/chain/subscribeNewBlocks.d.ts +14 -0
  39. package/build/chain/subscribeNewHeads.d.ts +15 -0
  40. package/build/chain/util.d.ts +9 -0
  41. package/build/collective/helpers.d.ts +6 -0
  42. package/build/collective/index.d.ts +3 -0
  43. package/build/collective/members.d.ts +2 -0
  44. package/build/collective/prime.d.ts +2 -0
  45. package/build/collective/proposals.d.ts +6 -0
  46. package/build/collective/types.d.ts +19 -0
  47. package/build/contracts/fees.d.ts +14 -0
  48. package/build/contracts/index.d.ts +1 -0
  49. package/build/council/index.d.ts +72 -0
  50. package/build/council/types.d.ts +6 -0
  51. package/build/council/votes.d.ts +11 -0
  52. package/build/council/votesOf.d.ts +16 -0
  53. package/build/crowdloan/childKey.d.ts +15 -0
  54. package/build/crowdloan/contributions.d.ts +14 -0
  55. package/build/crowdloan/index.d.ts +3 -0
  56. package/build/crowdloan/ownContributions.d.ts +15 -0
  57. package/build/crowdloan/types.d.ts +6 -0
  58. package/build/crowdloan/util.d.ts +10 -0
  59. package/build/democracy/dispatchQueue.d.ts +12 -0
  60. package/build/democracy/index.d.ts +11 -0
  61. package/build/democracy/locks.d.ts +14 -0
  62. package/build/democracy/nextExternal.d.ts +12 -0
  63. package/build/democracy/preimages.d.ts +24 -0
  64. package/build/democracy/proposals.d.ts +12 -0
  65. package/build/democracy/referendumIds.d.ts +12 -0
  66. package/build/democracy/referendums.d.ts +11 -0
  67. package/build/democracy/referendumsActive.d.ts +12 -0
  68. package/build/democracy/referendumsFinished.d.ts +15 -0
  69. package/build/democracy/referendumsInfo.d.ts +23 -0
  70. package/build/democracy/sqrtElectorate.d.ts +13 -0
  71. package/build/democracy/types.d.ts +70 -0
  72. package/build/democracy/util.d.ts +18 -0
  73. package/build/derive.d.ts +52 -0
  74. package/build/elections/index.d.ts +1 -0
  75. package/build/elections/info.d.ts +14 -0
  76. package/build/elections/types.d.ts +18 -0
  77. package/build/imOnline/index.d.ts +1 -0
  78. package/build/imOnline/receivedHeartbeats.d.ts +13 -0
  79. package/build/index.d.ts +2 -0
  80. package/build/membership/index.d.ts +70 -0
  81. package/build/packageDetect.d.ts +1 -0
  82. package/build/packageInfo.d.ts +6 -0
  83. package/build/parachains/index.d.ts +2 -0
  84. package/build/parachains/info.d.ts +19 -0
  85. package/build/parachains/overview.d.ts +15 -0
  86. package/build/parachains/types.d.ts +38 -0
  87. package/build/parachains/util.d.ts +3 -0
  88. package/build/session/index.d.ts +3 -0
  89. package/build/session/indexes.d.ts +15 -0
  90. package/build/session/info.d.ts +13 -0
  91. package/build/session/progress.d.ts +47 -0
  92. package/build/session/types.d.ts +19 -0
  93. package/build/society/candidates.d.ts +12 -0
  94. package/build/society/index.d.ts +4 -0
  95. package/build/society/info.d.ts +12 -0
  96. package/build/society/member.d.ts +14 -0
  97. package/build/society/members.d.ts +14 -0
  98. package/build/society/types.d.ts +27 -0
  99. package/build/staking/account.d.ts +31 -0
  100. package/build/staking/cache.d.ts +12 -0
  101. package/build/staking/currentPoints.d.ts +13 -0
  102. package/build/staking/electedInfo.d.ts +23 -0
  103. package/build/staking/erasExposure.d.ts +30 -0
  104. package/build/staking/erasHistoric.d.ts +8 -0
  105. package/build/staking/erasPoints.d.ts +18 -0
  106. package/build/staking/erasPrefs.d.ts +27 -0
  107. package/build/staking/erasRewards.d.ts +14 -0
  108. package/build/staking/erasSlashes.d.ts +26 -0
  109. package/build/staking/index.d.ts +22 -0
  110. package/build/staking/keys.d.ts +35 -0
  111. package/build/staking/overview.d.ts +19 -0
  112. package/build/staking/ownExposure.d.ts +37 -0
  113. package/build/staking/ownSlashes.d.ts +35 -0
  114. package/build/staking/query.d.ts +31 -0
  115. package/build/staking/stakerExposure.d.ts +33 -0
  116. package/build/staking/stakerPoints.d.ts +22 -0
  117. package/build/staking/stakerPrefs.d.ts +24 -0
  118. package/build/staking/stakerRewards.d.ts +49 -0
  119. package/build/staking/stakerSlashes.d.ts +22 -0
  120. package/build/staking/stashes.d.ts +16 -0
  121. package/build/staking/types.d.ts +139 -0
  122. package/build/staking/util.d.ts +14 -0
  123. package/build/staking/validators.d.ts +33 -0
  124. package/build/staking/waitingInfo.d.ts +16 -0
  125. package/build/technicalCommittee/index.d.ts +70 -0
  126. package/build/treasury/index.d.ts +1 -0
  127. package/build/treasury/proposals.d.ts +12 -0
  128. package/build/tx/constants.d.ts +5 -0
  129. package/build/tx/events.d.ts +22 -0
  130. package/build/tx/extrinsicInfo.d.ts +61 -0
  131. package/build/tx/index.d.ts +3 -0
  132. package/build/tx/signingInfo.d.ts +25 -0
  133. package/build/type/HeaderExtended.d.ts +4 -0
  134. package/build/type/SignedBlockExtended.d.ts +4 -0
  135. package/build/type/index.d.ts +2 -0
  136. package/build/type/types.d.ts +15 -0
  137. package/build/type/util.d.ts +2 -0
  138. package/build/types.d.ts +79 -0
  139. package/build/util/approvalFlagsToBools.d.ts +4 -0
  140. package/build/util/blockNumber.d.ts +7 -0
  141. package/build/util/cache.d.ts +4 -0
  142. package/build/util/cacheImpl.d.ts +3 -0
  143. package/build/util/first.d.ts +4 -0
  144. package/build/util/index.d.ts +7 -0
  145. package/build/util/lazy.d.ts +4 -0
  146. package/build/util/types.d.ts +6 -0
  147. package/package.json +42 -0
  148. package/src/accounts/accountId.ts +44 -0
  149. package/src/accounts/flags.ts +90 -0
  150. package/src/accounts/idAndIndex.ts +51 -0
  151. package/src/accounts/idToIndex.ts +31 -0
  152. package/src/accounts/identity.ts +235 -0
  153. package/src/accounts/index.ts +11 -0
  154. package/src/accounts/indexToId.ts +33 -0
  155. package/src/accounts/indexes.ts +56 -0
  156. package/src/accounts/info.ts +58 -0
  157. package/src/accounts/types.ts +48 -0
  158. package/src/alliance/index.ts +76 -0
  159. package/src/augment.ts +4 -0
  160. package/src/bagsList/get.ts +79 -0
  161. package/src/bagsList/getExpanded.ts +41 -0
  162. package/src/bagsList/index.ts +6 -0
  163. package/src/bagsList/listNodes.ts +50 -0
  164. package/src/bagsList/types.ts +18 -0
  165. package/src/bagsList/util.ts +14 -0
  166. package/src/balances/account.ts +210 -0
  167. package/src/balances/all.ts +246 -0
  168. package/src/balances/index.ts +26 -0
  169. package/src/balances/types.ts +79 -0
  170. package/src/balances/votingBalances.ts +33 -0
  171. package/src/bounties/bounties.spec.ts +162 -0
  172. package/src/bounties/bounties.ts +76 -0
  173. package/src/bounties/helpers/filterBountyProposals.ts +13 -0
  174. package/src/bounties/index.ts +4 -0
  175. package/src/bundle.ts +140 -0
  176. package/src/chain/bestNumber.ts +21 -0
  177. package/src/chain/bestNumberFinalized.ts +22 -0
  178. package/src/chain/bestNumberLag.ts +33 -0
  179. package/src/chain/getBlock.ts +43 -0
  180. package/src/chain/getBlockByNumber.ts +30 -0
  181. package/src/chain/getHeader.ts +37 -0
  182. package/src/chain/index.ts +13 -0
  183. package/src/chain/subscribeFinalizedBlocks.ts +30 -0
  184. package/src/chain/subscribeFinalizedHeads.ts +62 -0
  185. package/src/chain/subscribeNewBlocks.ts +30 -0
  186. package/src/chain/subscribeNewHeads.ts +38 -0
  187. package/src/chain/util.ts +112 -0
  188. package/src/checkTypes.manual.ts +8 -0
  189. package/src/collective/helpers.ts +36 -0
  190. package/src/collective/index.ts +6 -0
  191. package/src/collective/members.ts +8 -0
  192. package/src/collective/prime.ts +25 -0
  193. package/src/collective/proposals.ts +73 -0
  194. package/src/collective/types.ts +30 -0
  195. package/src/contracts/fees.ts +61 -0
  196. package/src/contracts/index.ts +4 -0
  197. package/src/council/index.ts +79 -0
  198. package/src/council/types.ts +11 -0
  199. package/src/council/votes.ts +97 -0
  200. package/src/council/votesOf.ts +35 -0
  201. package/src/crowdloan/childKey.ts +57 -0
  202. package/src/crowdloan/contributions.ts +142 -0
  203. package/src/crowdloan/index.ts +6 -0
  204. package/src/crowdloan/ownContributions.ts +81 -0
  205. package/src/crowdloan/types.ts +11 -0
  206. package/src/crowdloan/util.ts +33 -0
  207. package/src/democracy/dispatchQueue.ts +158 -0
  208. package/src/democracy/index.ts +14 -0
  209. package/src/democracy/locks.ts +114 -0
  210. package/src/democracy/nextExternal.ts +49 -0
  211. package/src/democracy/preimages.ts +171 -0
  212. package/src/democracy/proposals.ts +81 -0
  213. package/src/democracy/referendumIds.ts +37 -0
  214. package/src/democracy/referendums.ts +39 -0
  215. package/src/democracy/referendumsActive.ts +30 -0
  216. package/src/democracy/referendumsFinished.ts +37 -0
  217. package/src/democracy/referendumsInfo.ts +181 -0
  218. package/src/democracy/sqrtElectorate.ts +29 -0
  219. package/src/democracy/types.ts +84 -0
  220. package/src/democracy/util.ts +166 -0
  221. package/src/derive.ts +41 -0
  222. package/src/elections/index.ts +4 -0
  223. package/src/elections/info.ts +126 -0
  224. package/src/elections/types.ts +22 -0
  225. package/src/imOnline/index.ts +4 -0
  226. package/src/imOnline/receivedHeartbeats.ts +65 -0
  227. package/src/index.spec.ts +103 -0
  228. package/src/index.ts +6 -0
  229. package/src/membership/index.ts +76 -0
  230. package/src/mod.ts +4 -0
  231. package/src/packageDetect.ts +11 -0
  232. package/src/packageInfo.ts +6 -0
  233. package/src/parachains/index.ts +5 -0
  234. package/src/parachains/info.ts +111 -0
  235. package/src/parachains/overview.ts +63 -0
  236. package/src/parachains/types.ts +46 -0
  237. package/src/parachains/util.ts +11 -0
  238. package/src/session/index.ts +6 -0
  239. package/src/session/indexes.ts +90 -0
  240. package/src/session/info.ts +39 -0
  241. package/src/session/progress.ts +130 -0
  242. package/src/session/types.ts +25 -0
  243. package/src/society/candidates.ts +71 -0
  244. package/src/society/index.ts +7 -0
  245. package/src/society/info.ts +50 -0
  246. package/src/society/member.ts +28 -0
  247. package/src/society/members.ts +107 -0
  248. package/src/society/types.ts +33 -0
  249. package/src/staking/account.ts +112 -0
  250. package/src/staking/cache.ts +48 -0
  251. package/src/staking/currentPoints.ts +28 -0
  252. package/src/staking/electedInfo.ts +54 -0
  253. package/src/staking/erasExposure.ts +105 -0
  254. package/src/staking/erasHistoric.ts +47 -0
  255. package/src/staking/erasPoints.ts +67 -0
  256. package/src/staking/erasPrefs.ts +63 -0
  257. package/src/staking/erasRewards.ts +52 -0
  258. package/src/staking/erasSlashes.ts +69 -0
  259. package/src/staking/index.ts +25 -0
  260. package/src/staking/keys.ts +86 -0
  261. package/src/staking/overview.ts +42 -0
  262. package/src/staking/ownExposure.ts +83 -0
  263. package/src/staking/ownSlashes.ts +68 -0
  264. package/src/staking/query.ts +230 -0
  265. package/src/staking/stakerExposure.ts +78 -0
  266. package/src/staking/stakerPoints.ts +46 -0
  267. package/src/staking/stakerPrefs.ts +45 -0
  268. package/src/staking/stakerRewards.ts +298 -0
  269. package/src/staking/stakerSlashes.ts +45 -0
  270. package/src/staking/stashes.ts +55 -0
  271. package/src/staking/types.ts +174 -0
  272. package/src/staking/util.ts +94 -0
  273. package/src/staking/validators.ts +82 -0
  274. package/src/staking/waitingInfo.ts +45 -0
  275. package/src/technicalCommittee/index.ts +76 -0
  276. package/src/test/bountyFactory.ts +39 -0
  277. package/src/test/bytesFactory.ts +15 -0
  278. package/src/test/helpers.ts +23 -0
  279. package/src/test/proposalFactory.ts +25 -0
  280. package/src/treasury/index.ts +4 -0
  281. package/src/treasury/proposals.ts +109 -0
  282. package/src/tx/constants.ts +13 -0
  283. package/src/tx/events.ts +43 -0
  284. package/src/tx/extrinsicInfo.ts +123 -0
  285. package/src/tx/index.ts +6 -0
  286. package/src/tx/signingInfo.ts +129 -0
  287. package/src/type/HeaderExtended.ts +33 -0
  288. package/src/type/SignedBlockExtended.ts +75 -0
  289. package/src/type/index.ts +5 -0
  290. package/src/type/types.ts +21 -0
  291. package/src/type/util.ts +45 -0
  292. package/src/types.ts +97 -0
  293. package/src/util/approvalFlagToBools.spec.ts +37 -0
  294. package/src/util/approvalFlagsToBools.ts +26 -0
  295. package/src/util/blockNumber.ts +15 -0
  296. package/src/util/cache.ts +65 -0
  297. package/src/util/cacheImpl.ts +30 -0
  298. package/src/util/first.ts +20 -0
  299. package/src/util/index.ts +13 -0
  300. package/src/util/lazy.ts +16 -0
  301. package/src/util/types.ts +9 -0
  302. package/tsconfig.build.json +21 -0
  303. package/tsconfig.build.tsbuildinfo +1 -0
  304. package/tsconfig.spec.json +27 -0
@@ -0,0 +1,130 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Observable } from 'rxjs';
5
+ import type { Option, u64 } from '@pezkuwi/types';
6
+ import type { BlockNumber, SessionIndex } from '@pezkuwi/types/interfaces';
7
+ import type { DeriveApi, DeriveSessionInfo, DeriveSessionProgress } from '../types.js';
8
+
9
+ import { combineLatest, map, of, switchMap } from 'rxjs';
10
+
11
+ import { objectSpread } from '@pezkuwi/util';
12
+
13
+ import { memo } from '../util/index.js';
14
+
15
+ type ResultSlotsNoSession = [u64, u64, u64];
16
+ type ResultSlots = [u64, u64, u64, Option<SessionIndex>];
17
+ type ResultSlotsFlat = [u64, u64, u64, SessionIndex];
18
+
19
+ function withProgressField (field: 'eraLength' | 'eraProgress' | 'sessionProgress'): (instanceId: string, api: DeriveApi) => () => Observable<BlockNumber> {
20
+ return (instanceId: string, api: DeriveApi) =>
21
+ memo(instanceId, (): Observable<BlockNumber> =>
22
+ api.derive.session.progress().pipe(
23
+ map((info) => info[field])
24
+ )
25
+ );
26
+ }
27
+
28
+ function createDerive (api: DeriveApi, info: DeriveSessionInfo, [currentSlot, epochIndex, epochOrGenesisStartSlot, activeEraStartSessionIndex]: ResultSlotsFlat): DeriveSessionProgress {
29
+ const epochStartSlot = epochIndex.mul(info.sessionLength).iadd(epochOrGenesisStartSlot);
30
+ const sessionProgress = currentSlot.sub(epochStartSlot);
31
+ const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).imul(info.sessionLength).iadd(sessionProgress);
32
+
33
+ return objectSpread({
34
+ eraProgress: api.registry.createType('BlockNumber', eraProgress),
35
+ sessionProgress: api.registry.createType('BlockNumber', sessionProgress)
36
+ }, info);
37
+ }
38
+
39
+ function queryAura (api: DeriveApi): Observable<DeriveSessionProgress> {
40
+ return api.derive.session.info().pipe(
41
+ map((info): DeriveSessionProgress =>
42
+ objectSpread({
43
+ eraProgress: api.registry.createType('BlockNumber'),
44
+ sessionProgress: api.registry.createType('BlockNumber')
45
+ }, info)
46
+ )
47
+ );
48
+ }
49
+
50
+ function queryBabe (api: DeriveApi): Observable<[DeriveSessionInfo, ResultSlotsFlat]> {
51
+ return api.derive.session.info().pipe(
52
+ switchMap((info): Observable<[DeriveSessionInfo, ResultSlots | ResultSlotsNoSession]> =>
53
+ combineLatest([
54
+ of(info),
55
+ // we may have no staking, but have babe (permissioned)
56
+ api.query.staking?.erasStartSessionIndex
57
+ ? api.queryMulti<ResultSlots>([
58
+ api.query.babe.currentSlot,
59
+ api.query.babe.epochIndex,
60
+ api.query.babe.genesisSlot,
61
+ [api.query.staking.erasStartSessionIndex, info.activeEra]
62
+ ])
63
+ : api.queryMulti<ResultSlotsNoSession>([
64
+ api.query.babe.currentSlot,
65
+ api.query.babe.epochIndex,
66
+ api.query.babe.genesisSlot
67
+ ])
68
+ ])
69
+ ),
70
+ map(([info, [currentSlot, epochIndex, genesisSlot, optStartIndex]]): [DeriveSessionInfo, ResultSlotsFlat] => [
71
+ info, [currentSlot, epochIndex, genesisSlot, optStartIndex && optStartIndex.isSome ? optStartIndex.unwrap() : api.registry.createType('SessionIndex', 1)]
72
+ ])
73
+ );
74
+ }
75
+
76
+ /**
77
+ * @name progress
78
+ * @description Retrieves session information and progress.
79
+ * @example
80
+ * ```javascript
81
+ * api.derive.session.progress((progress) => {
82
+ * console.log(`Session progress ${JSON.stringify(progress)}`);
83
+ * });
84
+ * ```
85
+ */
86
+ export function progress (instanceId: string, api: DeriveApi): () => Observable<DeriveSessionProgress> {
87
+ return memo(instanceId, (): Observable<DeriveSessionProgress> =>
88
+ api.query.babe
89
+ ? queryBabe(api).pipe(
90
+ map(([info, slots]: [DeriveSessionInfo, ResultSlotsFlat]): DeriveSessionProgress =>
91
+ createDerive(api, info, slots)
92
+ )
93
+ )
94
+ : queryAura(api)
95
+ );
96
+ }
97
+
98
+ /**
99
+ * @name eraLenght
100
+ * @description Retrieves the total length of the current era.
101
+ * @example
102
+ * ```javascript
103
+ * api.derive.session.eraLength((length) => {
104
+ * console.log(`Current era length: ${length} sessions`);
105
+ * });
106
+ * ```
107
+ */
108
+ export const eraLength = /*#__PURE__*/ withProgressField('eraLength');
109
+ /**
110
+ * @name eraProgress
111
+ * @description Retrieves the progress of the current era.
112
+ * @example
113
+ * ```javascript
114
+ * api.derive.session.eraProgress((progress) => {
115
+ * console.log(`Current era progress: ${progress} sessions`);
116
+ * });
117
+ * ```
118
+ */
119
+ export const eraProgress = /*#__PURE__*/ withProgressField('eraProgress');
120
+ /**
121
+ * @name sessionProgress
122
+ * @description Retrieves the progress of the current session.
123
+ * @example
124
+ * ```javascript
125
+ * api.derive.session.sessionProgress((progress) => {
126
+ * console.log(`Current session progress: ${progress} slots`);
127
+ * });
128
+ * ```
129
+ */
130
+ export const sessionProgress = /*#__PURE__*/ withProgressField('sessionProgress');
@@ -0,0 +1,25 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Option, u32, u64 } from '@pezkuwi/types';
5
+ import type { BlockNumber, EraIndex, Moment, SessionIndex } from '@pezkuwi/types/interfaces';
6
+
7
+ export interface DeriveSessionIndexes {
8
+ activeEra: EraIndex;
9
+ activeEraStart: Option<Moment>;
10
+ currentEra: EraIndex;
11
+ currentIndex: SessionIndex;
12
+ validatorCount: u32;
13
+ }
14
+
15
+ export interface DeriveSessionInfo extends DeriveSessionIndexes {
16
+ eraLength: BlockNumber;
17
+ isEpoch: boolean;
18
+ sessionLength: u64;
19
+ sessionsPerEra: SessionIndex;
20
+ }
21
+
22
+ export interface DeriveSessionProgress extends DeriveSessionInfo {
23
+ eraProgress: BlockNumber;
24
+ sessionProgress: BlockNumber;
25
+ }
@@ -0,0 +1,71 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Observable } from 'rxjs';
5
+ import type { AccountId32, BalanceOf } from '@pezkuwi/types/interfaces';
6
+ import type { PalletSocietyBid, PalletSocietyBidKind, PalletSocietyCandidacy } from '@pezkuwi/types/lookup';
7
+ import type { ITuple } from '@pezkuwi/types/types';
8
+ import type { Option, Vec } from '@pezkuwi/types-codec';
9
+ import type { DeriveApi, DeriveSocietyCandidate } from '../types.js';
10
+
11
+ import { combineLatest, map, of, switchMap } from 'rxjs';
12
+
13
+ import { memo } from '../util/index.js';
14
+
15
+ type ResultSuspend = Option<ITuple<[BalanceOf, PalletSocietyBidKind]>>;
16
+ type Result = [PalletSocietyBid[], ResultSuspend[]]
17
+
18
+ function getPrev (api: DeriveApi): Observable<DeriveSocietyCandidate[]> {
19
+ return api.query.society.candidates<Vec<PalletSocietyBid>>().pipe(
20
+ switchMap((candidates): Observable<Result> =>
21
+ combineLatest([
22
+ of(candidates),
23
+ api.query.society['suspendedCandidates'].multi<Option<ITuple<[BalanceOf, PalletSocietyBidKind]>>>(
24
+ candidates.map(({ who }) => who)
25
+ )
26
+ ])
27
+ ),
28
+ map(([candidates, suspended]: Result): DeriveSocietyCandidate[] =>
29
+ candidates.map(({ kind, value, who }, index) => ({
30
+ accountId: who,
31
+ isSuspended: suspended[index].isSome,
32
+ kind,
33
+ value
34
+ }))
35
+ )
36
+ );
37
+ }
38
+
39
+ function getCurr (api: DeriveApi) {
40
+ return api.query.society.candidates.entries().pipe(
41
+ map((entries) =>
42
+ entries
43
+ .filter(([, opt]) => opt.isSome)
44
+ .map(([{ args: [accountId] }, opt]): [AccountId32, PalletSocietyCandidacy] => [accountId, opt.unwrap()])
45
+ // FIXME We are missing the new fields from the candidate record
46
+ .map(([accountId, { bid, kind }]) => ({
47
+ accountId,
48
+ isSuspended: false,
49
+ kind,
50
+ value: bid
51
+ }))
52
+ )
53
+ );
54
+ }
55
+
56
+ /**
57
+ * @name candidate
58
+ * @description Retrieves the list of candidates for the society module.
59
+ * @example
60
+ * ```javascript
61
+ * const societyCandidates = await api.derive.society.candidates();
62
+ * console.log(societyCandidates);
63
+ * ```
64
+ */
65
+ export function candidates (instanceId: string, api: DeriveApi): () => Observable<DeriveSocietyCandidate[]> {
66
+ return memo(instanceId, (): Observable<DeriveSocietyCandidate[]> =>
67
+ api.query.society['suspendedCandidates'] && api.query.society.candidates.creator.meta.type.isPlain
68
+ ? getPrev(api)
69
+ : getCurr(api)
70
+ );
71
+ }
@@ -0,0 +1,7 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export * from './candidates.js';
5
+ export * from './info.js';
6
+ export * from './member.js';
7
+ export * from './members.js';
@@ -0,0 +1,50 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Observable } from 'rxjs';
5
+ import type { Option, u32, Vec } from '@pezkuwi/types';
6
+ import type { AccountId, BalanceOf } from '@pezkuwi/types/interfaces';
7
+ import type { PalletSocietyBid } from '@pezkuwi/types/lookup';
8
+ import type { DeriveApi, DeriveSociety } from '../types.js';
9
+
10
+ import { combineLatest, map, of } from 'rxjs';
11
+
12
+ import { memo } from '../util/index.js';
13
+
14
+ type Result = [Vec<PalletSocietyBid>, Option<AccountId> | undefined, Option<AccountId>, Option<AccountId>, u32 | undefined, BalanceOf]
15
+
16
+ /**
17
+ * @name info
18
+ * @description Get the overall info for a society.
19
+ * @example
20
+ * ```javascript
21
+ * const societyInfo = await api.derive.society.candidates();
22
+ * console.log(societyInfo);
23
+ * ```
24
+ */
25
+ export function info (instanceId: string, api: DeriveApi): () => Observable<DeriveSociety> {
26
+ return memo(instanceId, (): Observable<DeriveSociety> =>
27
+ combineLatest<Result>([
28
+ api.query.society.bids(),
29
+ api.query.society['defender']
30
+ ? api.query.society['defender']<Option<AccountId>>()
31
+ : of(undefined),
32
+ api.query.society.founder(),
33
+ api.query.society.head(),
34
+ api.query.society['maxMembers']
35
+ ? api.query.society['maxMembers']<u32>()
36
+ : of(undefined),
37
+ api.query.society.pot()
38
+ ]).pipe(
39
+ map(([bids, defender, founder, head, maxMembers, pot]: Result): DeriveSociety => ({
40
+ bids,
41
+ defender: defender?.unwrapOr(undefined),
42
+ founder: founder.unwrapOr(undefined),
43
+ hasDefender: (defender?.isSome && head.isSome && !head.eq(defender)) || false,
44
+ head: head.unwrapOr(undefined),
45
+ maxMembers,
46
+ pot
47
+ }))
48
+ )
49
+ );
50
+ }
@@ -0,0 +1,28 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Observable } from 'rxjs';
5
+ import type { AccountId } from '@pezkuwi/types/interfaces';
6
+ import type { DeriveApi, DeriveSocietyMember } from '../types.js';
7
+
8
+ import { map } from 'rxjs';
9
+
10
+ import { memo } from '../util/index.js';
11
+
12
+ /**
13
+ * @name member
14
+ * @description Get the member info for a society.
15
+ * @param { AccountId } accountId
16
+ * @example
17
+ * ```javascript
18
+ * const member = await api.derive.society.member(ALICE);
19
+ * console.log(member);
20
+ * ```
21
+ */
22
+ export function member (instanceId: string, api: DeriveApi): (accountId: AccountId) => Observable<DeriveSocietyMember> {
23
+ return memo(instanceId, (accountId: AccountId): Observable<DeriveSocietyMember> =>
24
+ api.derive.society._members([accountId]).pipe(
25
+ map(([result]) => result)
26
+ )
27
+ );
28
+ }
@@ -0,0 +1,107 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Observable } from 'rxjs';
5
+ import type { AccountId } from '@pezkuwi/types/interfaces';
6
+ import type { PalletSocietyVote, PalletSocietyVouchingStatus } from '@pezkuwi/types/lookup';
7
+ import type { ITuple } from '@pezkuwi/types/types';
8
+ import type { bool, Option, u32, u128, Vec } from '@pezkuwi/types-codec';
9
+ import type { DeriveApi, DeriveSocietyMember } from '../types.js';
10
+
11
+ import { combineLatest, map, of, switchMap } from 'rxjs';
12
+
13
+ import { memo } from '../util/index.js';
14
+
15
+ function _membersPrev (api: DeriveApi, accountIds: AccountId[]): Observable<DeriveSocietyMember[]> {
16
+ return combineLatest([
17
+ of(accountIds),
18
+ api.query.society.payouts.multi<Vec<ITuple<[u32, u128]>>>(accountIds),
19
+ api.query.society['strikes'].multi<u32>(accountIds),
20
+ api.query.society.defenderVotes.multi<Option<PalletSocietyVote>>(accountIds),
21
+ api.query.society.suspendedMembers.multi<bool>(accountIds),
22
+ api.query.society['vouching'].multi<Option<PalletSocietyVouchingStatus>>(accountIds)
23
+ ]).pipe(
24
+ map(([accountIds, payouts, strikes, defenderVotes, suspended, vouching]) =>
25
+ accountIds.map((accountId, index) => ({
26
+ accountId,
27
+ isDefenderVoter: defenderVotes[index].isSome,
28
+ isSuspended: suspended[index].isTrue,
29
+ payouts: payouts[index],
30
+ strikes: strikes[index],
31
+ vote: defenderVotes[index].unwrapOr(undefined),
32
+ vouching: vouching[index].unwrapOr(undefined)
33
+ }))
34
+ )
35
+ );
36
+ }
37
+
38
+ function _membersCurr (api: DeriveApi, accountIds: AccountId[]): Observable<DeriveSocietyMember[]> {
39
+ return combineLatest([
40
+ of(accountIds),
41
+ api.query.society.members.multi(accountIds),
42
+ api.query.society.payouts.multi(accountIds),
43
+ api.query.society.challengeRoundCount().pipe(
44
+ switchMap((round) =>
45
+ api.query.society.defenderVotes.multi(accountIds.map((accountId) => [round, accountId]))
46
+ )
47
+ ),
48
+ api.query.society.suspendedMembers.multi(accountIds)
49
+ ]).pipe(
50
+ map(([accountIds, members, payouts, defenderVotes, suspendedMembers]) =>
51
+ accountIds
52
+ .map((accountId, index) =>
53
+ members[index].isSome
54
+ ? {
55
+ accountId,
56
+ isDefenderVoter: defenderVotes[index].isSome,
57
+ isSuspended: suspendedMembers[index].isSome,
58
+ member: members[index].unwrap(),
59
+ payouts: payouts[index].payouts
60
+ }
61
+ : null
62
+ )
63
+ .filter((m): m is NonNullable<typeof m> => !!m)
64
+ .map(({ accountId, isDefenderVoter, isSuspended, member, payouts }) => ({
65
+ accountId,
66
+ isDefenderVoter,
67
+ isSuspended,
68
+ payouts,
69
+ strikes: member.strikes,
70
+ vouching: member.vouching.unwrapOr(undefined)
71
+ }))
72
+ )
73
+ );
74
+ }
75
+
76
+ export function _members (instanceId: string, api: DeriveApi): (accountIds: AccountId[]) => Observable<DeriveSocietyMember[]> {
77
+ return memo(instanceId, (accountIds: AccountId[]): Observable<DeriveSocietyMember[]> =>
78
+ api.query.society.members.creator.meta.type.isMap
79
+ ? _membersCurr(api, accountIds)
80
+ : _membersPrev(api, accountIds)
81
+ );
82
+ }
83
+
84
+ /**
85
+ * @name members
86
+ * @description Get the society members.
87
+ * @example
88
+ * ```javascript
89
+ * const members = await api.derive.society.members();
90
+ * console.log(members);
91
+ * ```
92
+ */
93
+ export function members (instanceId: string, api: DeriveApi): () => Observable<DeriveSocietyMember[]> {
94
+ return memo(instanceId, (): Observable<DeriveSocietyMember[]> =>
95
+ api.query.society.members.creator.meta.type.isMap
96
+ ? api.query.society.members.keys().pipe(
97
+ switchMap((keys) =>
98
+ api.derive.society._members(
99
+ keys.map(({ args: [accountId] }) => accountId)
100
+ )
101
+ )
102
+ )
103
+ : api.query.society.members<Vec<AccountId>>().pipe(
104
+ switchMap((members) => api.derive.society._members(members))
105
+ )
106
+ );
107
+ }
@@ -0,0 +1,33 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { u32 } from '@pezkuwi/types';
5
+ import type { AccountId, Balance, BalanceOf, BlockNumber, StrikeCount } from '@pezkuwi/types/interfaces';
6
+ import type { PalletSocietyBid, PalletSocietyBidKind, PalletSocietyVote, PalletSocietyVouchingStatus } from '@pezkuwi/types/lookup';
7
+
8
+ export interface DeriveSociety {
9
+ bids: PalletSocietyBid[];
10
+ defender?: AccountId | undefined;
11
+ hasDefender: boolean;
12
+ head?: AccountId | undefined;
13
+ founder?: AccountId | undefined;
14
+ maxMembers?: u32 | undefined;
15
+ pot: BalanceOf;
16
+ }
17
+
18
+ export interface DeriveSocietyCandidate {
19
+ accountId: AccountId;
20
+ kind: PalletSocietyBidKind;
21
+ value: Balance;
22
+ isSuspended: boolean;
23
+ }
24
+
25
+ export interface DeriveSocietyMember {
26
+ accountId: AccountId;
27
+ isDefenderVoter: boolean;
28
+ isSuspended: boolean;
29
+ payouts: [BlockNumber, Balance][];
30
+ strikes: StrikeCount;
31
+ vote?: PalletSocietyVote | undefined;
32
+ vouching?: PalletSocietyVouchingStatus | undefined;
33
+ }
@@ -0,0 +1,112 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Observable } from 'rxjs';
5
+ import type { Balance } from '@pezkuwi/types/interfaces';
6
+ import type { PalletStakingStakingLedger, PalletStakingUnlockChunk } from '@pezkuwi/types/lookup';
7
+ import type { DeriveApi, DeriveSessionInfo, DeriveStakingAccount, DeriveStakingKeys, DeriveStakingQuery, DeriveUnlocking } from '../types.js';
8
+ import type { StakingQueryFlags } from './types.js';
9
+
10
+ import { combineLatest, map, switchMap } from 'rxjs';
11
+
12
+ import { BN, BN_ZERO, objectSpread } from '@pezkuwi/util';
13
+
14
+ import { firstMemo, memo } from '../util/index.js';
15
+
16
+ const QUERY_OPTS = {
17
+ withDestination: true,
18
+ withLedger: true,
19
+ withNominations: true,
20
+ withPrefs: true
21
+ };
22
+
23
+ function groupByEra (list: PalletStakingUnlockChunk[]): Record<string, BN> {
24
+ return list.reduce((map: Record<string, BN>, { era, value }): Record<string, BN> => {
25
+ const key = era.toString();
26
+
27
+ map[key] = (map[key] || BN_ZERO).add(value.unwrap());
28
+
29
+ return map;
30
+ }, {});
31
+ }
32
+
33
+ function calculateUnlocking (api: DeriveApi, stakingLedger: PalletStakingStakingLedger | undefined, sessionInfo: DeriveSessionInfo): DeriveUnlocking[] | undefined {
34
+ const results = Object
35
+ .entries(groupByEra(
36
+ (stakingLedger?.unlocking || []).filter(({ era }) => era.unwrap().gt(sessionInfo.activeEra))
37
+ ))
38
+ .map(([eraString, value]): DeriveUnlocking => ({
39
+ remainingEras: new BN(eraString).isub(sessionInfo.activeEra),
40
+ value: api.registry.createType('Balance', value)
41
+ }));
42
+
43
+ return results.length
44
+ ? results
45
+ : undefined;
46
+ }
47
+
48
+ function redeemableSum (api: DeriveApi, stakingLedger: PalletStakingStakingLedger | undefined, sessionInfo: DeriveSessionInfo): Balance {
49
+ return api.registry.createType('Balance', (stakingLedger?.unlocking || [] as PalletStakingUnlockChunk[]).reduce((total, { era, value }): BN => {
50
+ // aligns with https://github.com/paritytech/substrate/blob/fdfdc73f9e64dc47934b72eb9af3e1989e4ba699/frame/staking/src/pallet/mod.rs#L973-L975
51
+ // (ensure currentEra >= era passed, as per https://github.com/paritytech/substrate/blob/fdfdc73f9e64dc47934b72eb9af3e1989e4ba699/frame/staking/src/lib.rs#L477-L494)
52
+ // NOTE: Previously we used activeEra >= era, which is incorrect for the last session
53
+ return era.unwrap().gt(sessionInfo.currentEra)
54
+ ? total
55
+ : total.iadd(value.unwrap());
56
+ }, new BN(0)));
57
+ }
58
+
59
+ function parseResult (api: DeriveApi, sessionInfo: DeriveSessionInfo, keys: DeriveStakingKeys, query: DeriveStakingQuery): DeriveStakingAccount {
60
+ return objectSpread({}, keys, query, {
61
+ redeemable: redeemableSum(api, query.stakingLedger, sessionInfo),
62
+ unlocking: calculateUnlocking(api, query.stakingLedger, sessionInfo)
63
+ });
64
+ }
65
+
66
+ /**
67
+ * @name accounts
68
+ * @param {(Uint8Array | string)[]} accountIds List of account stashes
69
+ * @param {StakingQueryFlags} opts optional filtering flag
70
+ * @description From a list of stashes, fill in all the relevant staking details
71
+ * @example
72
+ * ```javascript
73
+ * const accounts = await api.derive.staking.accounts([
74
+ * "149B17nn7zVL4SkLSNmANupEkGexUBAxVrdk4bbWFZYibkFc",
75
+ * ]);
76
+ * console.log("First account staking info:", accounts[0]);
77
+ * ```
78
+ */
79
+ export function accounts (instanceId: string, api: DeriveApi): (accountIds: (Uint8Array | string)[], opts?: StakingQueryFlags) => Observable<DeriveStakingAccount[]> {
80
+ return memo(instanceId, (accountIds: (Uint8Array | string)[], opts: StakingQueryFlags = QUERY_OPTS): Observable<DeriveStakingAccount[]> =>
81
+ api.derive.session.info().pipe(
82
+ switchMap((sessionInfo) =>
83
+ combineLatest([
84
+ api.derive.staking.keysMulti(accountIds),
85
+ api.derive.staking.queryMulti(accountIds, opts)
86
+ ]).pipe(
87
+ map(([keys, queries]) =>
88
+ queries.map((q, index) => parseResult(api, sessionInfo, keys[index], q))
89
+ )
90
+ )
91
+ )
92
+ )
93
+ );
94
+ }
95
+
96
+ /**
97
+ * @name account
98
+ * @param {(Uint8Array | string)} accountId AccountId of the stash.
99
+ * @param {StakingQueryFlags} opts (Optional) filtering flag.
100
+ * @description From a stash, retrieve the controllerId and fill in all the relevant staking details.
101
+ * @example
102
+ * ```javascript
103
+ * const accountStakingData = await api.derive.staking.account(
104
+ * "149B17nn7zVL4SkLSNmANupEkGexUBAxVrdk4bbWFZYibkFc"
105
+ * );
106
+ * console.log(accountStakingData);
107
+ * ```
108
+ */
109
+ export const account = /*#__PURE__*/ firstMemo(
110
+ (api: DeriveApi, accountId: Uint8Array | string, opts?: StakingQueryFlags) =>
111
+ api.derive.staking.accounts([accountId], opts)
112
+ );
@@ -0,0 +1,48 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { EraIndex } from '@pezkuwi/types/interfaces';
5
+
6
+ import { deriveCache } from '../util/index.js';
7
+
8
+ export function getEraCache <T> (CACHE_KEY: string, era: EraIndex, withActive?: boolean): [string, T | undefined] {
9
+ const cacheKey = `${CACHE_KEY}-${era.toString()}`;
10
+
11
+ return [
12
+ cacheKey,
13
+ withActive
14
+ ? undefined
15
+ : deriveCache.get<T>(cacheKey)
16
+ ];
17
+ }
18
+
19
+ export function getEraMultiCache <T> (CACHE_KEY: string, eras: EraIndex[], withActive?: boolean): T[] {
20
+ const cached: T[] = withActive
21
+ ? []
22
+ : eras
23
+ .map((e) => deriveCache.get<T>(`${CACHE_KEY}-${e.toString()}`))
24
+ .filter((v): v is T => !!v);
25
+
26
+ return cached;
27
+ }
28
+
29
+ export function setEraCache <T extends { era: EraIndex }> (cacheKey: string, withActive: boolean, value: T): T {
30
+ !withActive && deriveCache.set(cacheKey, value);
31
+
32
+ return value;
33
+ }
34
+
35
+ export function setEraMultiCache <T extends { era: EraIndex }> (CACHE_KEY: string, withActive: boolean, values: T[]): T[] {
36
+ !withActive && values.forEach((v) => deriveCache.set(`${CACHE_KEY}-${v.era.toString()}`, v));
37
+
38
+ return values;
39
+ }
40
+
41
+ export function filterCachedEras <T extends { era: EraIndex }> (eras: EraIndex[], cached: T[], query: T[]): T[] {
42
+ return eras
43
+ .map((e) =>
44
+ cached.find(({ era }) => e.eq(era)) ||
45
+ query.find(({ era }) => e.eq(era))
46
+ )
47
+ .filter((e): e is T => !!e);
48
+ }
@@ -0,0 +1,28 @@
1
+ // Copyright 2017-2025 @polkadot/api-derive authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Observable } from 'rxjs';
5
+ import type { PalletStakingEraRewardPoints } from '@pezkuwi/types/lookup';
6
+ import type { DeriveApi } from '../types.js';
7
+
8
+ import { switchMap } from 'rxjs';
9
+
10
+ import { memo } from '../util/index.js';
11
+
12
+ /**
13
+ * @name currentPoints
14
+ * @description Retrieve the staking overview, including elected and points earned.
15
+ * @example
16
+ * ```javascript
17
+ * const currentPoints = await api.derive.staking.currentPoints();
18
+ * console.log(currentPoints.toHuman());
19
+ * ```
20
+ */
21
+ export function currentPoints (instanceId: string, api: DeriveApi): () => Observable<PalletStakingEraRewardPoints> {
22
+ return memo(instanceId, (): Observable<PalletStakingEraRewardPoints> =>
23
+ api.derive.session.indexes().pipe(
24
+ switchMap(({ activeEra }) =>
25
+ api.query.staking.erasRewardPoints(activeEra)
26
+ )
27
+ ));
28
+ }