@xyo-network/xl1-protocol-sdk 1.16.26 → 1.17.1

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 (231) hide show
  1. package/dist/neutral/ChainServiceCollectionV2.d.ts +8 -35
  2. package/dist/neutral/ChainServiceCollectionV2.d.ts.map +1 -1
  3. package/dist/neutral/block/hydrate/flattenHydratedBlocks.d.ts +2 -3
  4. package/dist/neutral/block/hydrate/flattenHydratedBlocks.d.ts.map +1 -1
  5. package/dist/neutral/index.d.ts +2 -0
  6. package/dist/neutral/index.d.ts.map +1 -1
  7. package/dist/neutral/index.mjs +1765 -1251
  8. package/dist/neutral/index.mjs.map +1 -1
  9. package/dist/neutral/model/PayloadBundle/bundledPayloadToHydratedBlock.d.ts +4 -0
  10. package/dist/neutral/model/PayloadBundle/bundledPayloadToHydratedBlock.d.ts.map +1 -0
  11. package/dist/neutral/model/PayloadBundle/hydratedBlockToPayloadBundle.d.ts +4 -0
  12. package/dist/neutral/model/PayloadBundle/hydratedBlockToPayloadBundle.d.ts.map +1 -0
  13. package/dist/neutral/model/PayloadBundle/index.d.ts +2 -0
  14. package/dist/neutral/model/PayloadBundle/index.d.ts.map +1 -1
  15. package/dist/neutral/model/Qualified.d.ts +6 -0
  16. package/dist/neutral/model/Qualified.d.ts.map +1 -0
  17. package/dist/neutral/model/index.d.ts +1 -1
  18. package/dist/neutral/model/index.d.ts.map +1 -1
  19. package/dist/neutral/payloads/index.d.ts +0 -1
  20. package/dist/neutral/payloads/index.d.ts.map +1 -1
  21. package/dist/neutral/primitives/index.d.ts +2 -1
  22. package/dist/neutral/primitives/index.d.ts.map +1 -1
  23. package/dist/neutral/primitives/rewardFromBlockNumber.d.ts +3 -0
  24. package/dist/neutral/primitives/rewardFromBlockNumber.d.ts.map +1 -0
  25. package/dist/neutral/primitives/state/findMostRecentBlock.d.ts +11 -0
  26. package/dist/neutral/primitives/state/findMostRecentBlock.d.ts.map +1 -0
  27. package/dist/neutral/primitives/state/hydratedBlockByNumber.d.ts +4 -0
  28. package/dist/neutral/primitives/state/hydratedBlockByNumber.d.ts.map +1 -0
  29. package/dist/neutral/primitives/state/index.d.ts +3 -0
  30. package/dist/neutral/primitives/state/index.d.ts.map +1 -0
  31. package/dist/neutral/provider/XyoRunner.d.ts +5 -1
  32. package/dist/neutral/provider/XyoRunner.d.ts.map +1 -1
  33. package/dist/neutral/provider/viewer/XyoViewer.d.ts +9 -4
  34. package/dist/neutral/provider/viewer/XyoViewer.d.ts.map +1 -1
  35. package/dist/neutral/provider/viewer/index.d.ts +0 -1
  36. package/dist/neutral/provider/viewer/index.d.ts.map +1 -1
  37. package/dist/neutral/runners/Block.d.ts +8 -0
  38. package/dist/neutral/runners/Block.d.ts.map +1 -0
  39. package/dist/neutral/runners/Mempool.d.ts +9 -0
  40. package/dist/neutral/runners/Mempool.d.ts.map +1 -0
  41. package/dist/neutral/runners/index.d.ts +3 -0
  42. package/dist/neutral/runners/index.d.ts.map +1 -0
  43. package/dist/neutral/services/BlockProducerService.d.ts +2 -2
  44. package/dist/neutral/services/BlockProducerService.d.ts.map +1 -1
  45. package/dist/neutral/services/Chain/BaseChainService.d.ts +0 -2
  46. package/dist/neutral/services/Chain/BaseChainService.d.ts.map +1 -1
  47. package/dist/neutral/services/Chain/ChainService.d.ts +2 -3
  48. package/dist/neutral/services/Chain/ChainService.d.ts.map +1 -1
  49. package/dist/neutral/services/Chain/index.d.ts +0 -1
  50. package/dist/neutral/services/Chain/index.d.ts.map +1 -1
  51. package/dist/neutral/services/index.d.ts +0 -2
  52. package/dist/neutral/services/index.d.ts.map +1 -1
  53. package/dist/neutral/simple/accountBalance/SimpleAccountBalanceViewer.d.ts +9 -5
  54. package/dist/neutral/simple/accountBalance/SimpleAccountBalanceViewer.d.ts.map +1 -1
  55. package/dist/neutral/simple/block/SimpleBlockViewer.d.ts +55 -0
  56. package/dist/neutral/simple/block/SimpleBlockViewer.d.ts.map +1 -0
  57. package/dist/neutral/simple/block/index.d.ts +2 -0
  58. package/dist/neutral/simple/block/index.d.ts.map +1 -0
  59. package/dist/neutral/simple/blockReward/SimpleBlockRewardViewer.d.ts +16 -0
  60. package/dist/neutral/simple/blockReward/SimpleBlockRewardViewer.d.ts.map +1 -0
  61. package/dist/neutral/simple/blockReward/index.d.ts +2 -0
  62. package/dist/neutral/simple/blockReward/index.d.ts.map +1 -0
  63. package/dist/neutral/simple/chain/SimpleChainViewer.d.ts +12 -0
  64. package/dist/neutral/simple/chain/SimpleChainViewer.d.ts.map +1 -0
  65. package/dist/neutral/simple/chain/index.d.ts +2 -0
  66. package/dist/neutral/simple/chain/index.d.ts.map +1 -0
  67. package/dist/neutral/simple/index.d.ts +3 -0
  68. package/dist/neutral/simple/index.d.ts.map +1 -1
  69. package/dist/neutral/simple/mempool/SimpleMempoolRunner.d.ts +15 -0
  70. package/dist/neutral/simple/mempool/SimpleMempoolRunner.d.ts.map +1 -0
  71. package/dist/neutral/simple/mempool/SimpleMempoolViewer.d.ts +10 -4
  72. package/dist/neutral/simple/mempool/SimpleMempoolViewer.d.ts.map +1 -1
  73. package/dist/neutral/simple/mempool/index.d.ts +1 -0
  74. package/dist/neutral/simple/mempool/index.d.ts.map +1 -1
  75. package/dist/neutral/summary/index.d.ts +3 -0
  76. package/dist/neutral/summary/index.d.ts.map +1 -0
  77. package/dist/neutral/summary/model/BalancesStepSummary.d.ts.map +1 -0
  78. package/dist/neutral/summary/model/SchemasStepSummary.d.ts.map +1 -0
  79. package/dist/neutral/summary/model/StepSummary.d.ts.map +1 -0
  80. package/dist/neutral/summary/model/TransfersSummary.d.ts.map +1 -0
  81. package/dist/neutral/{payloads/summary → summary/model}/index.d.ts +1 -0
  82. package/dist/neutral/summary/model/index.d.ts.map +1 -0
  83. package/dist/neutral/{model → summary/model}/summary.d.ts +3 -4
  84. package/dist/neutral/summary/model/summary.d.ts.map +1 -0
  85. package/dist/neutral/{primitives/summary → summary/primitives}/balances/balancesStepSummaryFromRange.d.ts +1 -2
  86. package/dist/neutral/summary/primitives/balances/balancesStepSummaryFromRange.d.ts.map +1 -0
  87. package/dist/neutral/summary/primitives/balances/balancesSummary.d.ts +5 -0
  88. package/dist/neutral/summary/primitives/balances/balancesSummary.d.ts.map +1 -0
  89. package/dist/neutral/summary/primitives/balances/index.d.ts.map +1 -0
  90. package/dist/neutral/{primitives/summary → summary/primitives}/index.d.ts.map +1 -1
  91. package/dist/neutral/summary/primitives/schemas/index.d.ts.map +1 -0
  92. package/dist/neutral/{primitives/summary → summary/primitives}/schemas/schemasStepSummaryFromRange.d.ts +1 -2
  93. package/dist/neutral/summary/primitives/schemas/schemasStepSummaryFromRange.d.ts.map +1 -0
  94. package/dist/neutral/summary/primitives/schemas/schemasSummary.d.ts +5 -0
  95. package/dist/neutral/summary/primitives/schemas/schemasSummary.d.ts.map +1 -0
  96. package/dist/neutral/summary/primitives/transfers/index.d.ts.map +1 -0
  97. package/dist/neutral/{primitives/summary → summary/primitives}/transfers/transfersStepSummaryFromRange.d.ts +1 -2
  98. package/dist/neutral/summary/primitives/transfers/transfersStepSummaryFromRange.d.ts.map +1 -0
  99. package/dist/neutral/summary/primitives/transfers/transfersSummary.d.ts +6 -0
  100. package/dist/neutral/summary/primitives/transfers/transfersSummary.d.ts.map +1 -0
  101. package/dist/neutral/utils/HydratedCache.d.ts +16 -0
  102. package/dist/neutral/utils/HydratedCache.d.ts.map +1 -0
  103. package/dist/neutral/utils/index.d.ts +1 -0
  104. package/dist/neutral/utils/index.d.ts.map +1 -1
  105. package/dist/neutral/viewers/AccountBalance.d.ts +5 -2
  106. package/dist/neutral/viewers/AccountBalance.d.ts.map +1 -1
  107. package/dist/neutral/viewers/Block.d.ts +9 -5
  108. package/dist/neutral/viewers/Block.d.ts.map +1 -1
  109. package/dist/neutral/viewers/BlockReward.d.ts +8 -0
  110. package/dist/neutral/viewers/BlockReward.d.ts.map +1 -0
  111. package/dist/neutral/viewers/Chain.d.ts +2 -0
  112. package/dist/neutral/viewers/Chain.d.ts.map +1 -1
  113. package/dist/neutral/viewers/ChainStakeViewer.d.ts +6 -0
  114. package/dist/neutral/viewers/ChainStakeViewer.d.ts.map +1 -0
  115. package/dist/neutral/viewers/Mempool.d.ts +8 -1
  116. package/dist/neutral/viewers/Mempool.d.ts.map +1 -1
  117. package/dist/neutral/viewers/StakeIntent.d.ts +10 -0
  118. package/dist/neutral/viewers/StakeIntent.d.ts.map +1 -0
  119. package/dist/neutral/{provider/viewer → viewers}/StepViewer.d.ts +2 -2
  120. package/dist/neutral/viewers/StepViewer.d.ts.map +1 -0
  121. package/dist/neutral/viewers/index.d.ts +3 -0
  122. package/dist/neutral/viewers/index.d.ts.map +1 -1
  123. package/package.json +18 -18
  124. package/src/ChainServiceCollectionV2.ts +12 -39
  125. package/src/block/hydrate/flattenHydratedBlocks.ts +2 -3
  126. package/src/index.ts +2 -1
  127. package/src/model/PayloadBundle/bundledPayloadToHydratedBlock.ts +14 -0
  128. package/src/model/PayloadBundle/hydratedBlockToPayloadBundle.ts +18 -0
  129. package/src/model/PayloadBundle/index.ts +2 -0
  130. package/src/model/Qualified.ts +9 -0
  131. package/src/model/index.ts +1 -1
  132. package/src/payloads/index.ts +0 -1
  133. package/src/primitives/index.ts +2 -1
  134. package/src/primitives/rewardFromBlockNumber.ts +25 -0
  135. package/src/primitives/state/findMostRecentBlock.ts +44 -0
  136. package/src/primitives/state/hydratedBlockByNumber.ts +19 -0
  137. package/src/primitives/state/index.ts +2 -0
  138. package/src/provider/XyoRunner.ts +7 -1
  139. package/src/provider/viewer/XyoViewer.ts +18 -7
  140. package/src/provider/viewer/index.ts +0 -1
  141. package/src/runners/Block.ts +10 -0
  142. package/src/runners/Mempool.ts +9 -0
  143. package/src/runners/index.ts +2 -0
  144. package/src/services/BlockProducerService.ts +3 -2
  145. package/src/services/Chain/BaseChainService.ts +1 -3
  146. package/src/services/Chain/ChainService.ts +4 -3
  147. package/src/services/Chain/index.ts +0 -1
  148. package/src/services/index.ts +0 -2
  149. package/src/simple/accountBalance/SimpleAccountBalanceViewer.ts +104 -18
  150. package/src/simple/block/SimpleBlockViewer.ts +172 -0
  151. package/src/simple/block/index.ts +1 -0
  152. package/src/simple/blockReward/SimpleBlockRewardViewer.ts +34 -0
  153. package/src/simple/blockReward/index.ts +1 -0
  154. package/src/simple/chain/SimpleChainViewer.ts +25 -0
  155. package/src/simple/chain/index.ts +1 -0
  156. package/src/simple/gateway/SimpleXyoGatewayRunner.ts +1 -1
  157. package/src/simple/index.ts +3 -0
  158. package/src/simple/mempool/SimpleMempoolRunner.ts +47 -0
  159. package/src/simple/mempool/SimpleMempoolViewer.ts +34 -8
  160. package/src/simple/mempool/index.ts +1 -0
  161. package/src/simple/timesync/SimpleTimeSyncViewer.ts +1 -1
  162. package/src/summary/index.ts +2 -0
  163. package/src/{payloads/summary → summary/model}/index.ts +1 -0
  164. package/src/{model → summary/model}/summary.ts +5 -4
  165. package/src/{primitives/summary → summary/primitives}/balances/balancesStepSummaryFromRange.ts +4 -3
  166. package/src/{primitives/summary → summary/primitives}/balances/balancesSummary.ts +6 -5
  167. package/src/{primitives/summary → summary/primitives}/schemas/schemasStepSummaryFromRange.ts +3 -3
  168. package/src/{primitives/summary → summary/primitives}/schemas/schemasSummary.ts +7 -6
  169. package/src/{primitives/summary → summary/primitives}/transfers/transfersStepSummaryFromRange.ts +4 -3
  170. package/src/{primitives/summary → summary/primitives}/transfers/transfersSummary.ts +6 -5
  171. package/src/utils/HydratedCache.ts +38 -0
  172. package/src/utils/index.ts +1 -0
  173. package/src/viewers/AccountBalance.ts +9 -2
  174. package/src/viewers/Block.ts +10 -6
  175. package/src/viewers/BlockReward.ts +9 -0
  176. package/src/viewers/Chain.ts +2 -0
  177. package/src/viewers/ChainStakeViewer.ts +7 -0
  178. package/src/viewers/Mempool.ts +10 -1
  179. package/src/viewers/StakeIntent.ts +14 -0
  180. package/src/{provider/viewer → viewers}/StepViewer.ts +2 -2
  181. package/src/viewers/index.ts +3 -0
  182. package/dist/neutral/model/summary.d.ts.map +0 -1
  183. package/dist/neutral/payloads/summary/BalancesStepSummary.d.ts.map +0 -1
  184. package/dist/neutral/payloads/summary/SchemasStepSummary.d.ts.map +0 -1
  185. package/dist/neutral/payloads/summary/StepSummary.d.ts.map +0 -1
  186. package/dist/neutral/payloads/summary/TransfersSummary.d.ts.map +0 -1
  187. package/dist/neutral/payloads/summary/index.d.ts.map +0 -1
  188. package/dist/neutral/primitives/summary/balances/balancesStepSummaryFromRange.d.ts.map +0 -1
  189. package/dist/neutral/primitives/summary/balances/balancesSummary.d.ts +0 -4
  190. package/dist/neutral/primitives/summary/balances/balancesSummary.d.ts.map +0 -1
  191. package/dist/neutral/primitives/summary/balances/index.d.ts.map +0 -1
  192. package/dist/neutral/primitives/summary/schemas/index.d.ts.map +0 -1
  193. package/dist/neutral/primitives/summary/schemas/schemasStepSummaryFromRange.d.ts.map +0 -1
  194. package/dist/neutral/primitives/summary/schemas/schemasSummary.d.ts +0 -4
  195. package/dist/neutral/primitives/summary/schemas/schemasSummary.d.ts.map +0 -1
  196. package/dist/neutral/primitives/summary/transfers/index.d.ts.map +0 -1
  197. package/dist/neutral/primitives/summary/transfers/transfersStepSummaryFromRange.d.ts.map +0 -1
  198. package/dist/neutral/primitives/summary/transfers/transfersSummary.d.ts +0 -5
  199. package/dist/neutral/primitives/summary/transfers/transfersSummary.d.ts.map +0 -1
  200. package/dist/neutral/provider/viewer/StepViewer.d.ts.map +0 -1
  201. package/dist/neutral/services/BlockRewardService.d.ts +0 -5
  202. package/dist/neutral/services/BlockRewardService.d.ts.map +0 -1
  203. package/dist/neutral/services/BlockRewardServiceV2.d.ts +0 -6
  204. package/dist/neutral/services/BlockRewardServiceV2.d.ts.map +0 -1
  205. package/dist/neutral/services/Chain/interfaces/ChainStakeViewer.d.ts +0 -4
  206. package/dist/neutral/services/Chain/interfaces/ChainStakeViewer.d.ts.map +0 -1
  207. package/dist/neutral/services/Chain/interfaces/ChainStaker.d.ts +0 -6
  208. package/dist/neutral/services/Chain/interfaces/ChainStaker.d.ts.map +0 -1
  209. package/dist/neutral/services/Chain/interfaces/index.d.ts +0 -3
  210. package/dist/neutral/services/Chain/interfaces/index.d.ts.map +0 -1
  211. package/src/services/BlockRewardService.ts +0 -6
  212. package/src/services/BlockRewardServiceV2.ts +0 -8
  213. package/src/services/Chain/interfaces/ChainStakeViewer.ts +0 -5
  214. package/src/services/Chain/interfaces/ChainStaker.ts +0 -5
  215. package/src/services/Chain/interfaces/index.ts +0 -2
  216. /package/dist/neutral/{payloads/summary → summary/model}/BalancesStepSummary.d.ts +0 -0
  217. /package/dist/neutral/{payloads/summary → summary/model}/SchemasStepSummary.d.ts +0 -0
  218. /package/dist/neutral/{payloads/summary → summary/model}/StepSummary.d.ts +0 -0
  219. /package/dist/neutral/{payloads/summary → summary/model}/TransfersSummary.d.ts +0 -0
  220. /package/dist/neutral/{primitives/summary → summary/primitives}/balances/index.d.ts +0 -0
  221. /package/dist/neutral/{primitives/summary → summary/primitives}/index.d.ts +0 -0
  222. /package/dist/neutral/{primitives/summary → summary/primitives}/schemas/index.d.ts +0 -0
  223. /package/dist/neutral/{primitives/summary → summary/primitives}/transfers/index.d.ts +0 -0
  224. /package/src/{payloads/summary → summary/model}/BalancesStepSummary.ts +0 -0
  225. /package/src/{payloads/summary → summary/model}/SchemasStepSummary.ts +0 -0
  226. /package/src/{payloads/summary → summary/model}/StepSummary.ts +0 -0
  227. /package/src/{payloads/summary → summary/model}/TransfersSummary.ts +0 -0
  228. /package/src/{primitives/summary → summary/primitives}/balances/index.ts +0 -0
  229. /package/src/{primitives/summary → summary/primitives}/index.ts +0 -0
  230. /package/src/{primitives/summary → summary/primitives}/schemas/index.ts +0 -0
  231. /package/src/{primitives/summary → summary/primitives}/transfers/index.ts +0 -0
@@ -108,12 +108,12 @@ var tryHydrateBlock = /* @__PURE__ */ __name(async (archivist, hash, maxDepth =
108
108
  }, "tryHydrateBlock");
109
109
 
110
110
  // src/block/primitives/blockFromBlockNumber.ts
111
- import { asHash as asHash3, isDefined as isDefined9 } from "@xylabs/sdk-js";
111
+ import { asHash as asHash3, isDefined as isDefined6 } from "@xylabs/sdk-js";
112
112
  import { toSafeJsonString } from "@xylabs/sdk-js";
113
- import { asSignedBlockBoundWitnessWithStorageMeta, SignedBlockBoundWitnessWithHashMetaZod, StepSizes as StepSizes7 } from "@xyo-network/xl1-protocol";
113
+ import { asSignedBlockBoundWitnessWithStorageMeta, SignedBlockBoundWitnessWithHashMetaZod, StepSizes as StepSizes4 } from "@xyo-network/xl1-protocol";
114
114
 
115
115
  // src/model/ChainContext/ChainContext.ts
116
- import { isDefined as isDefined7, isUndefined } from "@xylabs/sdk-js";
116
+ import { isDefined as isDefined4, isUndefined } from "@xylabs/sdk-js";
117
117
 
118
118
  // src/driver/cache/LruCacheMap.ts
119
119
  import { LRUCache } from "lru-cache";
@@ -225,6 +225,66 @@ function readPayloadMapFromStore(store) {
225
225
  }
226
226
  __name(readPayloadMapFromStore, "readPayloadMapFromStore");
227
227
 
228
+ // src/primitives/rewardFromBlockNumber.ts
229
+ import { toFixedPoint } from "@xylabs/sdk-js";
230
+ import { asAttoXL1 } from "@xyo-network/xl1-protocol";
231
+ var rewardFromBlockNumber = /* @__PURE__ */ __name((places = 18) => {
232
+ return (blockNumber, startingReward = asAttoXL1(toFixedPoint(30000n, places)), blocksPerStep = 1e6, stepFactorNumerator = 90n, stepFactorDenominator = 100n, minBlockReward = asAttoXL1(toFixedPoint(30n, places)), creatorReward = asAttoXL1(toFixedPoint(20000000000n, places))) => {
233
+ if (blockNumber === 0) {
234
+ return creatorReward;
235
+ }
236
+ const step = Math.floor((blockNumber + blocksPerStep) / blocksPerStep);
237
+ const stepExp = BigInt(step - 1);
238
+ const poweredNumerator = stepExp > 0 ? stepFactorNumerator ** stepExp : 1n;
239
+ const poweredDenominator = stepExp > 0 ? stepFactorDenominator ** stepExp : 1n;
240
+ let reward = startingReward * poweredNumerator / poweredDenominator;
241
+ return asAttoXL1(reward < minBlockReward ? minBlockReward : reward);
242
+ };
243
+ }, "rewardFromBlockNumber");
244
+
245
+ // src/primitives/state/findMostRecentBlock.ts
246
+ import { isSignedBlockBoundWitnessWithStorageMeta } from "@xyo-network/xl1-protocol";
247
+ var DEFAULT_NEXT_OPTIONS = {
248
+ limit: 50
249
+ };
250
+ var findMostRecentBlock = /* @__PURE__ */ __name(async (chainArchivist, nextOptions = DEFAULT_NEXT_OPTIONS, maxIterations = Number.POSITIVE_INFINITY) => {
251
+ let mostRecentBlock;
252
+ let cursor;
253
+ let batch;
254
+ let iterations = 0;
255
+ do {
256
+ batch = await chainArchivist.next({
257
+ ...nextOptions,
258
+ order: "desc",
259
+ cursor
260
+ });
261
+ const blocks = batch.filter(isSignedBlockBoundWitnessWithStorageMeta);
262
+ const last = blocks?.at(0);
263
+ if (last) {
264
+ mostRecentBlock = last;
265
+ break;
266
+ } else {
267
+ cursor = batch.at(-1)?._sequence;
268
+ }
269
+ iterations = iterations + 1;
270
+ } while (batch.length > 0 && iterations < maxIterations);
271
+ return mostRecentBlock;
272
+ }, "findMostRecentBlock");
273
+
274
+ // src/primitives/state/hydratedBlockByNumber.ts
275
+ import { assertEx as assertEx4 } from "@xylabs/sdk-js";
276
+ async function hydratedBlockByNumber(context, blockNumber) {
277
+ if (blockNumber < 0) throw new Error(`Block number ${blockNumber} is less than 0`);
278
+ if (blockNumber > Number.MAX_SAFE_INTEGER) throw new Error(`Block number ${blockNumber} is greater than the maximum safe integer`);
279
+ if (blockNumber % 1 !== 0) throw new Error(`Block number ${blockNumber} is not an integer`);
280
+ const cacheKey = `${blockNumber}`;
281
+ return await withContextCacheResponse(context, "hydratedBlockByNumber", cacheKey, async () => {
282
+ const block = assertEx4(await blockFromBlockNumber(context, blockNumber), () => `Could not find block for block number ${blockNumber}`);
283
+ return await hydrateBlock(context.store, block._hash);
284
+ });
285
+ }
286
+ __name(hydratedBlockByNumber, "hydratedBlockByNumber");
287
+
228
288
  // src/primitives/step/completedStepRewardAddress.ts
229
289
  import { toAddress } from "@xylabs/sdk-js";
230
290
  import { StepSizes } from "@xyo-network/xl1-protocol";
@@ -265,7 +325,7 @@ function stepBlockRange({ block, step }) {
265
325
  __name(stepBlockRange, "stepBlockRange");
266
326
 
267
327
  // src/primitives/step/stepTransferIndex.ts
268
- import { assertEx as assertEx4 } from "@xylabs/sdk-js";
328
+ import { assertEx as assertEx5 } from "@xylabs/sdk-js";
269
329
  import { StepSizes as StepSizes3 } from "@xyo-network/xl1-protocol";
270
330
  function stepTransferIndex(block, step) {
271
331
  let rewardTransferCount = 0;
@@ -279,7 +339,7 @@ function stepTransferIndex(block, step) {
279
339
  rewardTransferCount++;
280
340
  }
281
341
  }
282
- assertEx4(rewardTransferIndex >= 0, () => `Could not find step size for step ${step} at block ${block}`);
342
+ assertEx5(rewardTransferIndex >= 0, () => `Could not find step size for step ${step} at block ${block}`);
283
343
  return [
284
344
  rewardTransferIndex,
285
345
  rewardTransferCount
@@ -287,1026 +347,621 @@ function stepTransferIndex(block, step) {
287
347
  }
288
348
  __name(stepTransferIndex, "stepTransferIndex");
289
349
 
290
- // src/primitives/summary/balances/balancesStepSummaryFromRange.ts
291
- import { assertEx as assertEx5 } from "@xylabs/sdk-js";
292
- import { PayloadBuilder } from "@xyo-network/payload-builder";
293
- import { isAnyPayload } from "@xyo-network/payload-model";
294
- import { StepSizes as StepSizes4 } from "@xyo-network/xl1-protocol";
295
-
296
- // src/payloads/AddressPairPayload.ts
297
- import { AsObjectFactory } from "@xylabs/sdk-js";
298
- import { isPayloadOfSchemaType } from "@xyo-network/payload-model";
299
- var AddressPairSchema = "network.xyo.address.pair";
300
- var isAddressPairPayload = isPayloadOfSchemaType(AddressPairSchema);
301
- var asAddressPairPayload = AsObjectFactory.create(isAddressPairPayload);
302
- var asOptionalAddressPairPayload = AsObjectFactory.createOptional(isAddressPairPayload);
303
-
304
- // src/payloads/netBalancesForPayloads.ts
305
- import { hexToBigInt, toAddress as toAddress3 } from "@xylabs/sdk-js";
306
- import { span } from "@xylabs/telemetry";
307
- import { isTransfer } from "@xyo-network/xl1-protocol";
308
- var netBalancesForPayloads = /* @__PURE__ */ __name((payloads) => {
309
- return span("netBalancesForPayloads", () => {
310
- const balances = {};
311
- for (const payload of payloads) {
312
- if (isTransfer(payload)) {
313
- const { from } = payload;
314
- for (let [address, amount] of Object.entries(payload.transfers)) {
315
- balances[toAddress3(address)] = (balances[toAddress3(address)] ?? 0n) + hexToBigInt(amount);
316
- balances[toAddress3(from)] = (balances[toAddress3(from)] ?? 0n) - hexToBigInt(amount);
317
- }
318
- }
350
+ // src/primitives/timeBudget.ts
351
+ async function timeBudget(name, logger, func, budget, status = false) {
352
+ const start = Date.now();
353
+ const timer = status ? setInterval(() => {
354
+ const duration2 = Date.now() - start;
355
+ if (budget > 0 && duration2 > budget) {
356
+ logger?.warn(`Function [${name}] execution is exceeding budget: ${duration2}ms > ${budget}ms`);
319
357
  }
320
- return balances;
321
- });
322
- }, "netBalancesForPayloads");
358
+ }, Math.max(100, budget)) : void 0;
359
+ const result = await func();
360
+ const duration = Date.now() - start;
361
+ if (!timer && budget > 0 && duration > budget) {
362
+ logger?.warn(`Function [${name}] execution exceeded budget: ${duration}ms > ${budget}ms`);
363
+ }
364
+ if (timer) {
365
+ clearInterval(timer);
366
+ }
367
+ return result;
368
+ }
369
+ __name(timeBudget, "timeBudget");
323
370
 
324
- // src/payloads/netSchemasForPayloads.ts
325
- import { hexToBigInt as hexToBigInt2, toAddress as toAddress4 } from "@xylabs/sdk-js";
326
- import { span as span2 } from "@xylabs/telemetry";
327
- import { isTransfer as isTransfer2 } from "@xyo-network/xl1-protocol";
328
- var netSchemasForPayloads = /* @__PURE__ */ __name((payloads) => {
329
- return span2("netSchemasForPayloads", () => {
330
- const balances = {};
331
- for (const payload of payloads) {
332
- if (isTransfer2(payload)) {
333
- const { from } = payload;
334
- for (let [address, amount] of Object.entries(payload.transfers)) {
335
- balances[toAddress4(address)] = (balances[toAddress4(address)] ?? 0n) + hexToBigInt2(amount);
336
- balances[toAddress4(from)] = (balances[toAddress4(from)] ?? 0n) - hexToBigInt2(amount);
337
- }
371
+ // src/primitives/transaction/elevatedPayloads.ts
372
+ import { isAllowedBlockPayload } from "@xyo-network/xl1-protocol";
373
+ var ELEVATE_OPCODE = "elevate";
374
+ function elevatedPayloads([tx, payloads]) {
375
+ const opCodes = (tx.script ?? []).filter((operation) => operation.startsWith(`${ELEVATE_OPCODE}|`));
376
+ const elevatedPayloads2 = [];
377
+ for (const opCode of opCodes) {
378
+ const [code, hash] = opCode.split("|");
379
+ if (code === ELEVATE_OPCODE) {
380
+ const elevatedPayload = payloads.find((payload) => payload._hash === hash);
381
+ if (isAllowedBlockPayload(elevatedPayload)) {
382
+ elevatedPayloads2.push(elevatedPayload);
338
383
  }
339
384
  }
340
- return balances;
341
- });
342
- }, "netSchemasForPayloads");
385
+ }
386
+ if (opCodes.length === elevatedPayloads2.length) {
387
+ return elevatedPayloads2;
388
+ }
389
+ throw new Error("Not all elevated payloads could be found in the transaction payloads");
390
+ }
391
+ __name(elevatedPayloads, "elevatedPayloads");
343
392
 
344
- // src/payloads/netTransfersForPayloads.ts
345
- import { hexToBigInt as hexToBigInt3 } from "@xylabs/sdk-js";
346
- import { span as span3 } from "@xylabs/telemetry";
347
- import { isTransfer as isTransfer3 } from "@xyo-network/xl1-protocol";
348
- function netTransfersForPayloads(payloads) {
349
- return span3("netTransfersForPayloads", () => {
350
- const transfers = {};
351
- for (const payload of payloads) {
352
- if (isTransfer3(payload)) {
353
- const { from } = payload;
354
- transfers[from] = transfers[from] ?? {};
355
- for (let [to, amount] of Object.entries(payload.transfers)) {
356
- transfers[to] = transfers[to] ?? {};
357
- transfers[to][from] = (transfers[to][from] ?? 0n) + hexToBigInt3(amount);
358
- transfers[from][to] = (transfers[from][to] ?? 0n) - hexToBigInt3(amount);
359
- }
360
- }
361
- }
362
- return transfers;
363
- });
393
+ // src/model/ChainContext/ChainContext.ts
394
+ function contextCache(context, name, create) {
395
+ if (!context.caches) {
396
+ context.caches = {};
397
+ }
398
+ if (isUndefined(context.caches[name])) {
399
+ context.caches[name] = create?.() ?? new MemoryMap();
400
+ }
401
+ return context.caches[name];
364
402
  }
365
- __name(netTransfersForPayloads, "netTransfersForPayloads");
403
+ __name(contextCache, "contextCache");
404
+ async function withContextCacheResponse(context, name, key, func, { max = 1e4, timeBudgetMs = 0 } = {}) {
405
+ const cache = contextCache(context, name, () => new LruCacheMap({
406
+ max
407
+ }));
408
+ const cacheResult = await cache.get(key);
409
+ if (isDefined4(cacheResult)) {
410
+ return cacheResult;
411
+ }
412
+ const result = timeBudgetMs > 0 ? await timeBudget(name, context.logger, func, timeBudgetMs) : await func();
413
+ await cache.set(key, result);
414
+ return result;
415
+ }
416
+ __name(withContextCacheResponse, "withContextCacheResponse");
366
417
 
367
- // src/payloads/summary/BalancesStepSummary.ts
368
- import { AsObjectFactory as AsObjectFactory2 } from "@xylabs/sdk-js";
369
- import { isPayloadOfSchemaType as isPayloadOfSchemaType2, isStorageMeta } from "@xyo-network/payload-model";
370
- var BalancesStepSummarySchema = "network.xyo.step.summary.balances";
371
- var isBalancesStepSummary = isPayloadOfSchemaType2(BalancesStepSummarySchema);
372
- var asBalancesStepSummary = AsObjectFactory2.create(isBalancesStepSummary);
373
- var isBalancesStepSummaryWithStorageMeta = /* @__PURE__ */ __name((value) => {
374
- return isBalancesStepSummary(value) && isStorageMeta(value);
375
- }, "isBalancesStepSummaryWithStorageMeta");
376
- var asBalancesStepSummaryWithStorageMeta = AsObjectFactory2.create(isBalancesStepSummaryWithStorageMeta);
418
+ // src/model/PayloadBundle/bundledPayloadToHydratedBlock.ts
419
+ import { PayloadBuilder } from "@xyo-network/payload-builder";
420
+ import { asSignedBlockBoundWitnessWithHashMeta } from "@xyo-network/xl1-protocol";
421
+ var bundledPayloadToHydratedBlock = /* @__PURE__ */ __name(async (payload) => {
422
+ const withHashMeta = await PayloadBuilder.addHashMeta(payload.payloads);
423
+ const tx = asSignedBlockBoundWitnessWithHashMeta(withHashMeta.find((p) => p._hash === payload.root));
424
+ if (tx) {
425
+ return [
426
+ tx,
427
+ withHashMeta.filter((p) => p._hash !== payload.root)
428
+ ];
429
+ }
430
+ }, "bundledPayloadToHydratedBlock");
377
431
 
378
- // src/payloads/summary/SchemasStepSummary.ts
379
- import { AsObjectFactory as AsObjectFactory3 } from "@xylabs/sdk-js";
380
- import { isPayloadOfSchemaType as isPayloadOfSchemaType3, isStorageMeta as isStorageMeta2 } from "@xyo-network/payload-model";
381
- var SchemasStepSummarySchema = "network.xyo.step.summary.schemas";
382
- var isSchemasStepSummary = isPayloadOfSchemaType3(SchemasStepSummarySchema);
383
- var asSchemasStepSummary = AsObjectFactory3.create(isSchemasStepSummary);
384
- var isSchemasStepSummaryWithStorageMeta = /* @__PURE__ */ __name((value) => {
385
- return isSchemasStepSummary(value) && isStorageMeta2(value);
386
- }, "isSchemasStepSummaryWithStorageMeta");
387
- var asSchemasStepSummaryWithStorageMeta = AsObjectFactory3.create(isSchemasStepSummaryWithStorageMeta);
432
+ // src/model/PayloadBundle/bundledPayloadToHydratedTransaction.ts
433
+ import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
434
+ import { asSignedTransactionBoundWitnessWithHashMeta } from "@xyo-network/xl1-protocol";
435
+ var bundledPayloadToHydratedTransaction = /* @__PURE__ */ __name(async (payload) => {
436
+ const withHashMeta = await PayloadBuilder2.addHashMeta(payload.payloads);
437
+ const tx = asSignedTransactionBoundWitnessWithHashMeta(withHashMeta.find((p) => p._hash === payload.root));
438
+ if (tx) {
439
+ return [
440
+ tx,
441
+ withHashMeta.filter((p) => p._hash !== payload.root)
442
+ ];
443
+ }
444
+ }, "bundledPayloadToHydratedTransaction");
388
445
 
389
- // src/payloads/summary/StepSummary.ts
390
- var StepSummarySchema = "network.xyo.step.summary";
446
+ // src/model/PayloadBundle/hydratedBlockToPayloadBundle.ts
447
+ import { PayloadBuilder as PayloadBuilder3 } from "@xyo-network/payload-builder";
448
+ import { PayloadBundleSchema } from "@xyo-network/payload-model";
449
+ var hydratedBlockToPayloadBundle = /* @__PURE__ */ __name((transaction) => {
450
+ const root = transaction[0]._hash;
451
+ return bundle(root, transaction);
452
+ }, "hydratedBlockToPayloadBundle");
453
+ var bundle = /* @__PURE__ */ __name((root, transaction) => {
454
+ const payloads = flattenHydratedBlock(transaction).flatMap((p) => PayloadBuilder3.omitStorageMeta(p));
455
+ return new PayloadBuilder3({
456
+ schema: PayloadBundleSchema
457
+ }).fields({
458
+ payloads,
459
+ root
460
+ }).build();
461
+ }, "bundle");
391
462
 
392
- // src/payloads/summary/TransfersSummary.ts
393
- import { AsObjectFactory as AsObjectFactory4 } from "@xylabs/sdk-js";
394
- import { isPayloadOfSchemaType as isPayloadOfSchemaType4, isStorageMeta as isStorageMeta3 } from "@xyo-network/payload-model";
395
- var TransfersStepSummarySchema = "network.xyo.step.summary.transfer";
396
- var isTransfersStepSummary = isPayloadOfSchemaType4(TransfersStepSummarySchema);
397
- var asTransfersStepSummary = AsObjectFactory4.create(isTransfersStepSummary);
398
- var isTransfersStepSummaryWithStorageMeta = /* @__PURE__ */ __name((value) => {
399
- return isTransfersStepSummary(value) && isStorageMeta3(value);
400
- }, "isTransfersStepSummaryWithStorageMeta");
401
- var asTransfersStepSummaryWithStorageMeta = AsObjectFactory4.create(isTransfersStepSummaryWithStorageMeta);
463
+ // src/model/PayloadBundle/hydratedTransactionToPayloadBundle.ts
464
+ import { PayloadBuilder as PayloadBuilder8 } from "@xyo-network/payload-builder";
465
+ import { PayloadBundleSchema as PayloadBundleSchema2 } from "@xyo-network/payload-model";
402
466
 
403
- // src/SignedBigInt.ts
404
- import { hexToBigInt as hexToBigInt4, toHex } from "@xylabs/sdk-js";
405
- import { isObject } from "@xylabs/sdk-js";
406
- var isNegativeBigInt = /* @__PURE__ */ __name((value) => {
407
- return isObject(value) && "negative" in value && typeof value.negative === "string";
408
- }, "isNegativeBigInt");
409
- var isPositiveBigInt = /* @__PURE__ */ __name((value) => {
410
- return isObject(value) && "positive" in value && typeof value.positive === "string";
411
- }, "isPositiveBigInt");
412
- var parseSignedBigInt = /* @__PURE__ */ __name((value) => {
413
- if (isNegativeBigInt(value)) {
414
- return -hexToBigInt4(value.negative);
415
- } else if (isPositiveBigInt(value)) {
416
- return hexToBigInt4(value.positive);
417
- } else {
418
- throw new Error("Invalid balance type");
467
+ // src/transaction/buildTransaction.ts
468
+ import { assertEx as assertEx6, toHex } from "@xylabs/sdk-js";
469
+ import { BoundWitnessBuilder } from "@xyo-network/boundwitness-builder";
470
+ import { PayloadBuilder as PayloadBuilder4 } from "@xyo-network/payload-builder";
471
+ import { defaultTransactionFees } from "@xyo-network/xl1-protocol";
472
+ async function buildTransaction(chain, onChainPayloads, offChainPayloads, signer, nbf, exp, from, fees = defaultTransactionFees) {
473
+ if (from === void 0 && Array.isArray(signer)) {
474
+ throw new Error("from is required when signer is an array");
419
475
  }
420
- }, "parseSignedBigInt");
421
- var toSignedBigInt = /* @__PURE__ */ __name((value) => {
422
- return value < 0n ? {
423
- negative: toHex(-value)
424
- } : {
425
- positive: toHex(value)
476
+ const txBoundWitnessFields = {
477
+ chain,
478
+ fees: {
479
+ base: toHex(fees.base),
480
+ gasLimit: toHex(fees.gasLimit),
481
+ gasPrice: toHex(fees.gasPrice),
482
+ priority: toHex(fees.priority)
483
+ },
484
+ nbf,
485
+ exp
426
486
  };
427
- }, "toSignedBigInt");
428
- var toPositiveBigInt = /* @__PURE__ */ __name((value) => {
429
- if (isNegativeBigInt(value)) {
430
- return {
431
- positive: toHex(0n)
432
- };
433
- }
434
- if (isPositiveBigInt(value)) {
435
- return {
436
- positive: value.positive
437
- };
487
+ const elevatedHashes = await PayloadBuilder4.hashes(onChainPayloads);
488
+ const script = [];
489
+ for (const elevatedHash of elevatedHashes) {
490
+ script.push(`elevate|${elevatedHash}`);
438
491
  }
439
- if (typeof value === "bigint") {
440
- return {
441
- positive: toHex(value)
442
- };
492
+ const fields = {
493
+ ...txBoundWitnessFields,
494
+ from: from ?? (Array.isArray(signer) ? assertEx6(signer.at(0)?.address) : signer.address)
495
+ };
496
+ if (script.length > 0) {
497
+ fields.script = script;
443
498
  }
444
- throw new Error("Invalid value for positive big int");
445
- }, "toPositiveBigInt");
499
+ const [tx, txPayloads] = await new BoundWitnessBuilder().fields(fields).meta({
500
+ $signatures: []
501
+ }).payloads([
502
+ ...onChainPayloads,
503
+ ...offChainPayloads
504
+ ]).signers(Array.isArray(signer) ? signer : [
505
+ signer
506
+ ]).build();
507
+ return [
508
+ await PayloadBuilder4.addHashMeta(tx),
509
+ await PayloadBuilder4.addHashMeta(txPayloads)
510
+ ];
511
+ }
512
+ __name(buildTransaction, "buildTransaction");
446
513
 
447
- // src/primitives/summary/balances/balancesStepSummaryFromRange.ts
448
- async function balancesStepSummaryFromRange(context, range) {
449
- const frameHeadHash = await hashFromBlockNumber(context, range[1]);
450
- const frameSize = range[1] - range[0] + 1;
451
- const [headHash] = await context.head();
452
- let result = void 0;
453
- if (frameSize === 1) {
454
- const hash = await hashFromBlockNumber(context, range[0]);
455
- const [, payloads] = await hydrateBlock(context.store, hash);
456
- const balances = {};
457
- for (const [address, balance] of Object.entries(netBalancesForPayloads(payloads))) {
458
- balances[address] = toSignedBigInt(balance);
459
- }
460
- result = {
461
- schema: BalancesStepSummarySchema,
462
- hash: headHash,
463
- stepSize: -1,
464
- balances
465
- };
466
- } else {
467
- const step = StepSizes4.indexOf(frameSize);
468
- assertEx5(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes4.join(", ")}`);
469
- const summaryResult = await context.summaryMap.get(`${frameHeadHash}|${frameSize}`);
470
- if (isAnyPayload(summaryResult)) {
471
- result = summaryResult;
472
- } else {
473
- await context.stepSemaphores[step].acquire();
474
- try {
475
- const subRanges = deepCalculateFramesFromRange(range, step - 1);
476
- const promises = subRanges.map((subRange) => balancesStepSummaryFromRange(context, subRange));
477
- const subResults = await Promise.all(promises);
478
- const bigIntBalances = {};
479
- for (const subResult of subResults) {
480
- for (const [address, balance] of Object.entries(subResult.balances)) {
481
- bigIntBalances[address] = (bigIntBalances[address] ?? 0n) + parseSignedBigInt(balance);
482
- }
483
- }
484
- const balances = {};
485
- for (const [address, balance] of Object.entries(bigIntBalances)) {
486
- balances[address] = toSignedBigInt(balance);
487
- }
488
- result = {
489
- schema: BalancesStepSummarySchema,
490
- hash: frameHeadHash,
491
- stepSize: frameSize,
492
- balances
493
- };
494
- await context.summaryMap.set(`${frameHeadHash}|${frameSize}`, result);
495
- } finally {
496
- context.stepSemaphores[step].release();
497
- }
498
- }
514
+ // src/transaction/buildUnsignedTransaction.ts
515
+ import { toHex as toHex2 } from "@xylabs/sdk-js";
516
+ import { BoundWitnessBuilder as BoundWitnessBuilder2 } from "@xyo-network/boundwitness-builder";
517
+ import { PayloadBuilder as PayloadBuilder5 } from "@xyo-network/payload-builder";
518
+ import { defaultTransactionFees as defaultTransactionFees2 } from "@xyo-network/xl1-protocol";
519
+ async function buildUnsignedTransaction(chain, onChainPayloads, offChainPayloads, nbf, exp, from, fees = defaultTransactionFees2) {
520
+ const txBoundWitnessFields = {
521
+ chain,
522
+ fees: {
523
+ base: toHex2(fees.base),
524
+ gasLimit: toHex2(fees.gasLimit),
525
+ gasPrice: toHex2(fees.gasPrice),
526
+ priority: toHex2(fees.priority)
527
+ },
528
+ nbf,
529
+ exp
530
+ };
531
+ const elevatedHashes = await PayloadBuilder5.hashes(onChainPayloads);
532
+ const script = [];
533
+ for (const elevatedHash of elevatedHashes) {
534
+ script.push(`elevate|${elevatedHash}`);
499
535
  }
500
- const finalResult = await PayloadBuilder.addStorageMeta(result);
501
- return finalResult;
536
+ const fields = {
537
+ ...txBoundWitnessFields,
538
+ from
539
+ };
540
+ if (script.length > 0) {
541
+ fields.script = script;
542
+ }
543
+ const [tx, txPayloads] = await new BoundWitnessBuilder2().fields(fields).meta({
544
+ $signatures: []
545
+ }).payloads([
546
+ ...onChainPayloads,
547
+ ...offChainPayloads
548
+ ]).build(false);
549
+ return [
550
+ tx,
551
+ txPayloads
552
+ ];
502
553
  }
503
- __name(balancesStepSummaryFromRange, "balancesStepSummaryFromRange");
554
+ __name(buildUnsignedTransaction, "buildUnsignedTransaction");
504
555
 
505
- // src/primitives/summary/balances/balancesSummary.ts
506
- import { asAddress, isDefined as isDefined4 } from "@xylabs/sdk-js";
507
- import { spanRootAsync } from "@xylabs/telemetry";
508
- import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta2, asXL1BlockNumber, asXL1BlockRange as asXL1BlockRange2 } from "@xyo-network/xl1-protocol";
509
- async function balancesSummary(context) {
510
- return await spanRootAsync("balancesSummary", async () => {
511
- const [headHash] = await context.head();
512
- const headResult = await context.store.chainMap.get(headHash);
513
- const headBoundWitness = asBlockBoundWitnessWithStorageMeta2(headResult, () => `Head block not found for hash: ${headHash}`);
514
- const rangeStart = asXL1BlockNumber(isDefined4(context.windowSize) ? Math.max(headBoundWitness.block - context.windowSize + 1, 0) : 0);
515
- const ranges = deepCalculateFramesFromRange(asXL1BlockRange2([
516
- rangeStart,
517
- headBoundWitness.block
518
- ], {
519
- name: "balancesSummary"
520
- }));
521
- const summaries = await Promise.all(ranges.map((range) => balancesStepSummaryFromRange(context, range)));
522
- const balances = {};
523
- for (let summary of summaries) {
524
- for (const [address, balance] of Object.entries(summary.balances)) {
525
- const validAddress = asAddress(address, () => `Invalid address: ${address}`);
526
- balances[validAddress] = (balances[validAddress] ?? 0n) + parseSignedBigInt(balance);
556
+ // src/transaction/confirmSubmittedTransaction.ts
557
+ import { delay, isDefined as isDefined5 } from "@xylabs/sdk-js";
558
+ var DEFAULT_CONFIRMATION_ATTEMPTS = 20;
559
+ var DEFAULT_DELAY_BETWEEN_ATTEMPTS = 1e3;
560
+ var confirmSubmittedTransaction = /* @__PURE__ */ __name(async (viewer, txHash, options) => {
561
+ const { attempts: maxAttempts = DEFAULT_CONFIRMATION_ATTEMPTS, delay: attemptDelay = DEFAULT_DELAY_BETWEEN_ATTEMPTS } = options ?? {};
562
+ options?.logger?.log("\u{1F680} confirming transaction:", txHash, "\n");
563
+ let attempts = 0;
564
+ while (true) {
565
+ const tx = await viewer.transactionByHash(txHash) ?? void 0;
566
+ if (isDefined5(tx)) {
567
+ options?.logger?.log("\u2705 Transaction confirmed:", txHash, "\n");
568
+ return tx;
569
+ } else {
570
+ attempts++;
571
+ if (attempts > maxAttempts) {
572
+ options?.logger?.error(`\u26A0\uFE0F Transaction not confirmed after ${maxAttempts} attempts`);
573
+ throw new Error(`Transaction ${txHash} not confirmed after ${maxAttempts} attempts`);
574
+ } else {
575
+ options?.logger?.log(`\u{1F504} Transaction not confirmed yet, attempt ${attempts}. Retrying...`, "\n");
576
+ await delay(attemptDelay);
527
577
  }
528
578
  }
529
- return balances;
530
- });
531
- }
532
- __name(balancesSummary, "balancesSummary");
579
+ }
580
+ }, "confirmSubmittedTransaction");
533
581
 
534
- // src/primitives/summary/schemas/schemasStepSummaryFromRange.ts
535
- import { assertEx as assertEx6 } from "@xylabs/sdk-js";
536
- import { isBoundWitness } from "@xyo-network/boundwitness-model";
537
- import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
538
- import { isAnyPayload as isAnyPayload2, isHashMeta } from "@xyo-network/payload-model";
539
- import { StepSizes as StepSizes5 } from "@xyo-network/xl1-protocol";
540
- async function schemasStepSummaryFromRange(context, range) {
541
- const frameHeadHash = await hashFromBlockNumber(context, range[1]);
542
- const frameSize = range[1] - range[0] + 1;
543
- const [headHash] = await context.head();
544
- let result = void 0;
545
- if (frameSize === 1) {
546
- const hash = await hashFromBlockNumber(context, range[0]);
547
- const [block, payloads] = await hydrateBlock(context.store, hash);
548
- const boundWitnesses = [
549
- block,
550
- ...payloads.filter((x) => isBoundWitness(x) && isHashMeta(x))
551
- ];
552
- const schemas = {};
553
- for (const bw of boundWitnesses) {
554
- schemas[bw.schema] = (schemas[bw.schema] ?? 0) + 1;
555
- for (const schema of bw.payload_schemas) {
556
- schemas[schema] = (schemas[schema] ?? 0) + 1;
557
- }
582
+ // src/transaction/hydrateTransaction.ts
583
+ import { assertEx as assertEx7 } from "@xylabs/sdk-js";
584
+ import { hydrateTypedBoundWitness, tryHydrateTypedBoundWitness } from "@xyo-network/archivist-model";
585
+ import { isAllowedBlockPayload as isAllowedBlockPayload2, isSignedTransactionBoundWitnessWithStorageMeta } from "@xyo-network/xl1-protocol";
586
+ var tryHydrateTransaction = /* @__PURE__ */ __name(async ({ chainMap }, hash) => {
587
+ return await tryHydrateTypedBoundWitness({
588
+ get(hashes) {
589
+ return chainMap.getMany(hashes);
590
+ },
591
+ next() {
592
+ throw new Error("Not implemented");
558
593
  }
559
- result = {
560
- schema: SchemasStepSummarySchema,
561
- hash: headHash,
562
- stepSize: -1,
563
- schemas
564
- };
565
- } else {
566
- const step = StepSizes5.indexOf(frameSize);
567
- assertEx6(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes5.join(", ")}`);
568
- const summaryResult = await context.summaryMap.get(`${frameHeadHash}|${frameSize}`);
569
- if (isAnyPayload2(summaryResult)) {
570
- result = summaryResult;
571
- } else {
572
- await context.stepSemaphores[step].acquire();
573
- try {
574
- const subRanges = deepCalculateFramesFromRange(range, step - 1);
575
- const promises = subRanges.map((subRange) => schemasStepSummaryFromRange(context, subRange));
576
- const subResults = await Promise.all(promises);
577
- const schemas = {};
578
- for (const subResult of subResults) {
579
- for (const [schema, count] of Object.entries(subResult.schemas)) {
580
- schemas[schema] = (schemas[schema] ?? 0) + count;
581
- }
582
- }
583
- result = {
584
- schema: SchemasStepSummarySchema,
585
- hash: frameHeadHash,
586
- stepSize: frameSize,
587
- schemas
588
- };
589
- await context.summaryMap.set(`${frameHeadHash}|${frameSize}`, result);
590
- } finally {
591
- context.stepSemaphores[step].release();
594
+ }, hash, isSignedTransactionBoundWitnessWithStorageMeta);
595
+ }, "tryHydrateTransaction");
596
+ var hydrateTransaction = /* @__PURE__ */ __name(async ({ chainMap }, hash) => {
597
+ return await hydrateTypedBoundWitness({
598
+ get(hashes) {
599
+ return chainMap.getMany(hashes);
600
+ },
601
+ next() {
602
+ throw new Error("Not implemented");
603
+ }
604
+ }, hash, isSignedTransactionBoundWitnessWithStorageMeta);
605
+ }, "hydrateTransaction");
606
+ var flattenHydratedTransaction = /* @__PURE__ */ __name((hydratedTransaction) => {
607
+ const [tx, txPayloads] = hydratedTransaction;
608
+ return [
609
+ ...txPayloads,
610
+ tx
611
+ ];
612
+ }, "flattenHydratedTransaction");
613
+ var flattenHydratedTransactions = /* @__PURE__ */ __name((hydratedTransactions) => hydratedTransactions.flatMap((tx) => flattenHydratedTransaction(tx)), "flattenHydratedTransactions");
614
+ var tryHydrateElevatedTransaction = /* @__PURE__ */ __name(async ({ chainMap }, hash) => {
615
+ const hydratedTransaction = await tryHydrateTransaction({
616
+ chainMap
617
+ }, hash);
618
+ if (!hydratedTransaction) {
619
+ return void 0;
620
+ }
621
+ const [transaction, payloads] = hydratedTransaction;
622
+ const opCodes = (transaction.script ?? []).filter((operation) => operation.startsWith("elevate|"));
623
+ const elevatedPayloads2 = [];
624
+ for (const opCode of opCodes) {
625
+ const [code, hash2] = opCode.split("|");
626
+ if (code === "elevated") {
627
+ const elevatedPayload = payloads.find((payload) => payload._hash === hash2);
628
+ if (isAllowedBlockPayload2(elevatedPayload)) {
629
+ elevatedPayloads2.push(elevatedPayload);
592
630
  }
593
631
  }
594
632
  }
595
- return await PayloadBuilder2.addHashMeta(result);
633
+ if (opCodes.length === elevatedPayloads2.length) {
634
+ return [
635
+ transaction,
636
+ elevatedPayloads2
637
+ ];
638
+ }
639
+ return void 0;
640
+ }, "tryHydrateElevatedTransaction");
641
+ var hydrateElevatedTransaction = /* @__PURE__ */ __name(async (context, hash) => {
642
+ return assertEx7(await tryHydrateElevatedTransaction(context, hash), () => "Hydration failed");
643
+ }, "hydrateElevatedTransaction");
644
+
645
+ // src/transaction/primitives/transactionBlockByteCount.ts
646
+ import { PayloadBuilder as PayloadBuilder6 } from "@xyo-network/payload-builder";
647
+ function transactionBlockByteCount([transaction, payloads]) {
648
+ const cleanTransaction = PayloadBuilder6.omitStorageMeta(transaction);
649
+ const transactionBytes = JSON.stringify(cleanTransaction).length;
650
+ const cleanPayloads = PayloadBuilder6.omitStorageMeta(payloads);
651
+ return cleanPayloads.reduce((acc, payload) => acc + JSON.stringify(payload).length, 0) + transactionBytes;
596
652
  }
597
- __name(schemasStepSummaryFromRange, "schemasStepSummaryFromRange");
653
+ __name(transactionBlockByteCount, "transactionBlockByteCount");
598
654
 
599
- // src/primitives/summary/schemas/schemasSummary.ts
600
- import { isDefined as isDefined5 } from "@xylabs/sdk-js";
601
- import { spanRootAsync as spanRootAsync2 } from "@xylabs/telemetry";
602
- import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta3, asXL1BlockNumber as asXL1BlockNumber2, asXL1BlockRange as asXL1BlockRange3 } from "@xyo-network/xl1-protocol";
603
- async function schemasSummary(context) {
604
- return await spanRootAsync2("schemasSummary", async () => {
605
- const [headHash] = await context.head();
606
- const headResult = await context.store.chainMap.get(headHash);
607
- const headBoundWitness = asBlockBoundWitnessWithStorageMeta3(headResult, () => `Head block not found for hash: ${headHash}`);
608
- const rangeStart = asXL1BlockNumber2(isDefined5(context.windowSize) ? Math.max(headBoundWitness.block - context.windowSize + 1, 0) : 0);
609
- const ranges = deepCalculateFramesFromRange(asXL1BlockRange3([
610
- rangeStart,
611
- headBoundWitness.block
612
- ], {
613
- name: "schemasSummary"
614
- }));
615
- const summaries = await Promise.all(ranges.map((range) => schemasStepSummaryFromRange(context, range)));
616
- const schemas = {};
617
- for (let summary of summaries) {
618
- for (const [schema, count] of Object.entries(summary.schemas)) {
619
- schemas[schema] = (schemas[schema] ?? 0) + count;
620
- }
621
- }
622
- return schemas;
623
- });
655
+ // src/transaction/primitives/transactionElevatedPayloads.ts
656
+ import { asHash } from "@xylabs/sdk-js";
657
+
658
+ // src/transaction/primitives/transactionOperations.ts
659
+ function crackOperation(operation) {
660
+ const parts = operation.split("|");
661
+ if (parts.length < 2) {
662
+ throw new Error(`Invalid operation format: ${operation}`);
663
+ }
664
+ return [
665
+ parts[0],
666
+ parts.slice(1)
667
+ ];
624
668
  }
625
- __name(schemasSummary, "schemasSummary");
669
+ __name(crackOperation, "crackOperation");
670
+ function crackOperations(operations) {
671
+ return operations.map((op) => crackOperation(op));
672
+ }
673
+ __name(crackOperations, "crackOperations");
626
674
 
627
- // src/primitives/summary/transfers/transfersStepSummaryFromRange.ts
628
- import { assertEx as assertEx7 } from "@xylabs/sdk-js";
629
- import { PayloadBuilder as PayloadBuilder3 } from "@xyo-network/payload-builder";
630
- import { isAnyPayload as isAnyPayload3 } from "@xyo-network/payload-model";
631
- import { StepSizes as StepSizes6 } from "@xyo-network/xl1-protocol";
675
+ // src/transaction/primitives/transactionElevatedPayloads.ts
676
+ function transactionElevatedPayloadHashes(transaction) {
677
+ const elevateOperations = crackOperations(transaction.script ?? []).filter((op) => op[0] === "elevate");
678
+ return elevateOperations.map((op) => asHash(op[1][0], true));
679
+ }
680
+ __name(transactionElevatedPayloadHashes, "transactionElevatedPayloadHashes");
681
+ function transactionElevatedPayloads([transaction, payloads]) {
682
+ const hashes = transactionElevatedPayloadHashes(transaction);
683
+ const elevatedPayloads2 = payloads.filter((payload) => hashes.includes(payload._hash));
684
+ return elevatedPayloads2;
685
+ }
686
+ __name(transactionElevatedPayloads, "transactionElevatedPayloads");
632
687
 
633
- // src/primitives/summary/transfers/transfersSummary.ts
634
- import { asAddress as asAddress2, isDefined as isDefined6 } from "@xylabs/sdk-js";
635
- import { spanRootAsync as spanRootAsync3 } from "@xylabs/telemetry";
636
- import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta4, asXL1BlockNumber as asXL1BlockNumber3, asXL1BlockRange as asXL1BlockRange4 } from "@xyo-network/xl1-protocol";
637
- async function transfersSummary(transferContext) {
638
- return await spanRootAsync3("transferSummary", async () => {
639
- const [headHash] = await transferContext.head();
640
- const headResult = await transferContext.store.chainMap.get(headHash);
641
- const headBoundWitness = asBlockBoundWitnessWithStorageMeta4(headResult, () => `Head block not found for hash: ${transferContext.head}`);
642
- const rangeStart = asXL1BlockNumber3(isDefined6(transferContext.windowSize) ? Math.max(headBoundWitness.block - transferContext.windowSize + 1, 0) : 0);
643
- const ranges = deepCalculateFramesFromRange(asXL1BlockRange4([
644
- rangeStart,
645
- headBoundWitness.block
646
- ], {
647
- name: "transfersSummary"
648
- }));
649
- const summaries = await Promise.all(ranges.map((range) => transfersStepSummaryFromRange(transferContext, range)));
650
- const transfers = {};
651
- for (let summary of summaries) {
652
- for (const [from, toMap] of Object.entries(summary.transfers)) {
653
- const validFrom = asAddress2(from, () => `Invalid address: ${from}`);
654
- transfers[validFrom] = transfers[validFrom] ?? {};
655
- for (const [to, transfer] of Object.entries(toMap)) {
656
- const validTo = asAddress2(to, () => `Invalid address: ${to}`);
657
- transfers[validFrom][validTo] = (transfers[validFrom][validTo] ?? 0n) + parseSignedBigInt(transfer);
658
- }
659
- }
660
- }
661
- return transfers;
662
- });
688
+ // src/transaction/primitives/transactionRequiredGas.ts
689
+ import { AttoXL1, TransactionGasCosts } from "@xyo-network/xl1-protocol";
690
+ function transactionBytesRequiredGas([transaction, payloads]) {
691
+ const transactionBlockBytes = transactionBlockByteCount([
692
+ transaction,
693
+ payloads
694
+ ]);
695
+ return AttoXL1(TransactionGasCosts.characterStorage * BigInt(transactionBlockBytes));
663
696
  }
664
- __name(transfersSummary, "transfersSummary");
665
- function transfersSummaryKey(frameHeadHash, frameSize) {
666
- return `${frameHeadHash}|${frameSize}`;
697
+ __name(transactionBytesRequiredGas, "transactionBytesRequiredGas");
698
+ function transactionRequiredGas(hydratedTransaction) {
699
+ const elevatedPayloads2 = transactionElevatedPayloads(hydratedTransaction);
700
+ const hashes = elevatedPayloads2.length + 1;
701
+ const signatures = hydratedTransaction[0].addresses.length;
702
+ return AttoXL1(transactionBytesRequiredGas(hydratedTransaction) + TransactionGasCosts.hashValidation * BigInt(hashes) + TransactionGasCosts.signatureValidation * BigInt(signatures) + TransactionGasCosts.payloadValidation * BigInt(elevatedPayloads2.length));
667
703
  }
668
- __name(transfersSummaryKey, "transfersSummaryKey");
704
+ __name(transactionRequiredGas, "transactionRequiredGas");
669
705
 
670
- // src/primitives/summary/transfers/transfersStepSummaryFromRange.ts
671
- async function transfersStepSummaryFromRange(context, range) {
672
- const frameHeadHash = await hashFromBlockNumber(context, range[1]);
673
- const frameSize = range[1] - range[0] + 1;
674
- const [headHash] = await context.head();
675
- let result = void 0;
676
- if (frameSize === 1) {
677
- const hash = await hashFromBlockNumber(context, range[0]);
678
- const [, payloads] = await hydrateBlock(context.store, hash);
679
- const transfers = {};
680
- for (const [from, toMap] of Object.entries(netTransfersForPayloads(payloads))) {
681
- transfers[from] = transfers[from] ?? {};
682
- for (const [to, amount] of Object.entries(toMap)) {
683
- transfers[from][to] = toSignedBigInt(amount);
684
- }
706
+ // src/transaction/script.ts
707
+ import { asHash as asHash2 } from "@xylabs/sdk-js";
708
+ import { assertEx as assertEx8, filterAs } from "@xylabs/sdk-js";
709
+ import { isAllowedBlockPayloadWithHashMeta } from "@xyo-network/xl1-protocol";
710
+ var tryExtractElevatedHashesFromScript = /* @__PURE__ */ __name((strings) => {
711
+ const hashes = strings.filter((str) => str.startsWith("elevate|")).map((str) => str.split("|")[1]);
712
+ return filterAs(hashes, (h) => asHash2(h));
713
+ }, "tryExtractElevatedHashesFromScript");
714
+ var extractElevatedHashesFromScript = /* @__PURE__ */ __name((strings) => {
715
+ const hashes = strings.filter((str) => str.startsWith("elevate|")).map((str) => str.split("|")[1]);
716
+ const filtered = filterAs(hashes, (h) => asHash2(h));
717
+ assertEx8(filtered.length === hashes.length, () => "Invalid elevated hashes");
718
+ return filtered;
719
+ }, "extractElevatedHashesFromScript");
720
+ var tryExtractElevatedHashes = /* @__PURE__ */ __name((tx) => {
721
+ const [bw, payloads] = tx;
722
+ const { script } = bw;
723
+ const hashes = script ? tryExtractElevatedHashesFromScript(script) : [];
724
+ return payloads.filter((p) => hashes.includes(p._hash)).filter(isAllowedBlockPayloadWithHashMeta);
725
+ }, "tryExtractElevatedHashes");
726
+ var extractElevatedHashes = /* @__PURE__ */ __name((tx) => {
727
+ const [bw, payloads] = tx;
728
+ const { script } = bw;
729
+ const hashes = script ? tryExtractElevatedHashesFromScript(script) : [];
730
+ const filtered = payloads.filter((p) => hashes.includes(p._hash)).filter(isAllowedBlockPayloadWithHashMeta);
731
+ assertEx8(filtered.length === hashes.length, () => "Invalid elevated hashes");
732
+ return filtered;
733
+ }, "extractElevatedHashes");
734
+
735
+ // src/transaction/signTransaction.ts
736
+ import { assertEx as assertEx9, hexFromArrayBuffer, toArrayBuffer } from "@xylabs/sdk-js";
737
+ import { PayloadBuilder as PayloadBuilder7 } from "@xyo-network/payload-builder";
738
+ async function signTransaction(tx, account) {
739
+ assertEx9(tx.from === account.address, () => "Signer address does not match transaction from address");
740
+ const unsignedTx = structuredClone(tx);
741
+ unsignedTx.addresses = [
742
+ account.address
743
+ ];
744
+ unsignedTx.previous_hashes = [
745
+ account.previousHash ?? null
746
+ ];
747
+ const hash = await PayloadBuilder7.dataHash(unsignedTx);
748
+ const hashBytes = toArrayBuffer(hash);
749
+ const [signature] = await account.sign(hashBytes);
750
+ const result = {
751
+ ...unsignedTx,
752
+ $signatures: [
753
+ hexFromArrayBuffer(signature)
754
+ ]
755
+ };
756
+ return result;
757
+ }
758
+ __name(signTransaction, "signTransaction");
759
+
760
+ // src/model/PayloadBundle/hydratedTransactionToPayloadBundle.ts
761
+ var hydratedTransactionToPayloadBundle = /* @__PURE__ */ __name((transaction) => {
762
+ const root = transaction[0]._hash;
763
+ return bundle2(root, transaction);
764
+ }, "hydratedTransactionToPayloadBundle");
765
+ var bundle2 = /* @__PURE__ */ __name((root, transaction) => {
766
+ const payloads = flattenHydratedTransaction(transaction).flatMap((p) => PayloadBuilder8.omitStorageMeta(p));
767
+ return new PayloadBuilder8({
768
+ schema: PayloadBundleSchema2
769
+ }).fields({
770
+ payloads,
771
+ root
772
+ }).build();
773
+ }, "bundle");
774
+
775
+ // src/model/Qualified.ts
776
+ import { HashZod } from "@xylabs/sdk-js";
777
+ import { XL1BlockRangeZod } from "@xyo-network/xl1-protocol";
778
+ import z from "zod";
779
+ var QualifiedZod = /* @__PURE__ */ __name((zodType) => {
780
+ return z.tuple([
781
+ zodType,
782
+ XL1BlockRangeZod,
783
+ HashZod
784
+ ]);
785
+ }, "QualifiedZod");
786
+
787
+ // src/block/primitives/blockFromBlockNumber.ts
788
+ async function blockFromBlockNumber(context, blockNumber) {
789
+ const cacheKey = `${blockNumber}`;
790
+ return await withContextCacheResponse(context, "blockFromBlockNumber", cacheKey, async () => {
791
+ const [headHash] = await context.head();
792
+ const result = await context.store.chainMap.get(headHash);
793
+ if (!isDefined6(result)) {
794
+ throw new Error(`Head block not found for hash: ${headHash}`);
685
795
  }
686
- result = {
687
- schema: TransfersStepSummarySchema,
688
- hash: headHash,
689
- stepSize: -1,
690
- transfers
691
- };
692
- } else {
693
- const step = StepSizes6.indexOf(frameSize);
694
- assertEx7(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes6.join(", ")}`);
695
- const key = transfersSummaryKey(frameHeadHash, frameSize);
696
- const summaryResult = await context.summaryMap.get(key);
697
- if (isAnyPayload3(summaryResult)) {
698
- result = summaryResult;
699
- } else {
700
- await context.stepSemaphores[step].acquire();
701
- try {
702
- const subRanges = deepCalculateFramesFromRange(range, step - 1);
703
- const promises = subRanges.map((subRange) => transfersStepSummaryFromRange(context, subRange));
704
- const subResults = await Promise.all(promises);
705
- const bigIntBalances = {};
706
- for (const subResult of subResults) {
707
- for (const [from, toMap] of Object.entries(subResult.transfers)) {
708
- bigIntBalances[from] = bigIntBalances[from] ?? {};
709
- for (const [to, transfer] of Object.entries(toMap)) {
710
- bigIntBalances[from][to] = (bigIntBalances[from][to] ?? 0n) + parseSignedBigInt(transfer);
711
- }
712
- }
713
- }
714
- const transfers = {};
715
- for (const [from, toMap] of Object.entries(bigIntBalances)) {
716
- transfers[from] = transfers[from] ?? {};
717
- for (const [to, transfer] of Object.entries(toMap)) {
718
- transfers[from][to] = toSignedBigInt(transfer);
719
- }
796
+ let currentBlock = asSignedBlockBoundWitnessWithStorageMeta(result, () => `Found Payload is not a Signed<BlockBoundWitness>: ${JSON.stringify(result, null, 2)}`);
797
+ if (currentBlock.block < blockNumber) {
798
+ throw new Error(`Block number ${blockNumber} is greater than head ${currentBlock.block}.`);
799
+ }
800
+ while (currentBlock.block > blockNumber) {
801
+ let jumpHash = currentBlock.previous;
802
+ let jumpBlockNumber = currentBlock.block - 1;
803
+ for (const [step, stepSize2] of StepSizes4.entries()) {
804
+ const possibleJumpBlockNumber = currentBlock.block - currentBlock.block % stepSize2 - 1;
805
+ if (possibleJumpBlockNumber >= blockNumber && possibleJumpBlockNumber <= jumpBlockNumber) {
806
+ jumpBlockNumber = possibleJumpBlockNumber;
807
+ jumpHash = asHash3(currentBlock.step_hashes?.at(step), () => `Step hash not found for step ${step} in block ${currentBlock.block}`);
720
808
  }
721
- result = {
722
- schema: TransfersStepSummarySchema,
723
- hash: frameHeadHash,
724
- stepSize: frameSize,
725
- transfers
726
- };
727
- await context.summaryMap.set(key, result);
728
- } finally {
729
- context.stepSemaphores[step].release();
809
+ }
810
+ const newBlock = await context.store.chainMap.get(asHash3(jumpHash, () => `Jump hash not found for block number [${blockNumber}]: ${jumpBlockNumber} ${toSafeJsonString(currentBlock, 10)}`));
811
+ if (!isDefined6(newBlock)) {
812
+ throw new Error(`Block not found for jump hash: ${jumpHash}`);
813
+ }
814
+ currentBlock = asSignedBlockBoundWitnessWithStorageMeta(newBlock, () => {
815
+ const result2 = SignedBlockBoundWitnessWithHashMetaZod.safeParse(newBlock);
816
+ return `Found Payload [jump hash] is not a Signed<BlockBoundWitness>: ${result2.error}`;
817
+ });
818
+ if (currentBlock.block === blockNumber) {
819
+ break;
820
+ }
821
+ if (currentBlock.block < blockNumber) {
822
+ throw new Error(`Block number ${blockNumber} is not a valid step block number for block ${headHash}.`);
730
823
  }
731
824
  }
732
- }
733
- const finalResult = await PayloadBuilder3.addStorageMeta(result);
734
- return finalResult;
825
+ return currentBlock;
826
+ });
735
827
  }
736
- __name(transfersStepSummaryFromRange, "transfersStepSummaryFromRange");
828
+ __name(blockFromBlockNumber, "blockFromBlockNumber");
737
829
 
738
- // src/primitives/timeBudget.ts
739
- async function timeBudget(name, logger, func, budget, status = false) {
740
- const start = Date.now();
741
- const timer = status ? setInterval(() => {
742
- const duration2 = Date.now() - start;
743
- if (budget > 0 && duration2 > budget) {
744
- logger?.warn(`Function [${name}] execution is exceeding budget: ${duration2}ms > ${budget}ms`);
745
- }
746
- }, Math.max(100, budget)) : void 0;
747
- const result = await func();
748
- const duration = Date.now() - start;
749
- if (!timer && budget > 0 && duration > budget) {
750
- logger?.warn(`Function [${name}] execution exceeded budget: ${duration}ms > ${budget}ms`);
830
+ // src/block/primitives/frames/calculateFramesFromRange.ts
831
+ import { asXL1BlockNumber, stepSize } from "@xyo-network/xl1-protocol";
832
+ function calculateFramesFromRange(range, step) {
833
+ const size = stepSize(step);
834
+ let start = Math.trunc(range[0] / size) * size;
835
+ const fitted = [];
836
+ const remaining = [];
837
+ if (start !== range[0]) {
838
+ start += size;
839
+ remaining.push([
840
+ range[0],
841
+ asXL1BlockNumber(Math.min(start - 1, range[1]), true)
842
+ ]);
751
843
  }
752
- if (timer) {
753
- clearInterval(timer);
844
+ for (let i = start; i <= range[1]; i += size) {
845
+ if (i + size - 1 <= range[1]) {
846
+ fitted.push([
847
+ asXL1BlockNumber(i, {
848
+ name: "calculateFramesFromRange A"
849
+ }),
850
+ asXL1BlockNumber(Math.min(i + size - 1, range[1]), {
851
+ name: "calculateFramesFromRange B"
852
+ })
853
+ ]);
854
+ } else {
855
+ remaining.push([
856
+ asXL1BlockNumber(i, {
857
+ name: "calculateFramesFromRange C"
858
+ }),
859
+ range[1]
860
+ ]);
861
+ }
754
862
  }
755
- return result;
863
+ return [
864
+ fitted,
865
+ remaining
866
+ ];
756
867
  }
757
- __name(timeBudget, "timeBudget");
868
+ __name(calculateFramesFromRange, "calculateFramesFromRange");
758
869
 
759
- // src/primitives/transaction/elevatedPayloads.ts
760
- import { isAllowedBlockPayload } from "@xyo-network/xl1-protocol";
761
- var ELEVATE_OPCODE = "elevate";
762
- function elevatedPayloads([tx, payloads]) {
763
- const opCodes = (tx.script ?? []).filter((operation) => operation.startsWith(`${ELEVATE_OPCODE}|`));
764
- const elevatedPayloads2 = [];
765
- for (const opCode of opCodes) {
766
- const [code, hash] = opCode.split("|");
767
- if (code === ELEVATE_OPCODE) {
768
- const elevatedPayload = payloads.find((payload) => payload._hash === hash);
769
- if (isAllowedBlockPayload(elevatedPayload)) {
770
- elevatedPayloads2.push(elevatedPayload);
771
- }
870
+ // src/block/primitives/frames/deepCalculateFramesFromRange.ts
871
+ import { StepSizes as StepSizes5 } from "@xyo-network/xl1-protocol";
872
+ function deepCalculateFramesFromRange(range, startingStep = StepSizes5.length - 1) {
873
+ const fitted = [];
874
+ let remaining = [
875
+ range
876
+ ];
877
+ for (let step = startingStep; step >= 0; step--) {
878
+ const newRemaining = [];
879
+ for (const range2 of remaining) {
880
+ const [newFittedFrames, newRemainingFrames] = calculateFramesFromRange(range2, step);
881
+ fitted.push(...newFittedFrames);
882
+ newRemaining.push(...newRemainingFrames);
772
883
  }
884
+ remaining = newRemaining;
773
885
  }
774
- if (opCodes.length === elevatedPayloads2.length) {
775
- return elevatedPayloads2;
886
+ for (const range2 of remaining) {
887
+ for (let i = range2[0]; i <= range2[1]; i++) {
888
+ fitted.push([
889
+ i,
890
+ i
891
+ ]);
892
+ }
776
893
  }
777
- throw new Error("Not all elevated payloads could be found in the transaction payloads");
894
+ return fitted.toSorted((a, b) => a[0] - b[0]);
778
895
  }
779
- __name(elevatedPayloads, "elevatedPayloads");
896
+ __name(deepCalculateFramesFromRange, "deepCalculateFramesFromRange");
780
897
 
781
- // src/model/ChainContext/ChainContext.ts
782
- function contextCache(context, name, create) {
783
- if (!context.caches) {
784
- context.caches = {};
785
- }
786
- if (isUndefined(context.caches[name])) {
787
- context.caches[name] = create?.() ?? new MemoryMap();
788
- }
789
- return context.caches[name];
898
+ // src/block/primitives/hashFromBlockNumber.ts
899
+ async function hashFromBlockNumber(context, blockNumber) {
900
+ return (await blockFromBlockNumber(context, blockNumber))._hash;
790
901
  }
791
- __name(contextCache, "contextCache");
792
- async function withContextCacheResponse(context, name, key, func, { max = 1e4, timeBudgetMs = 0 } = {}) {
793
- const cache = contextCache(context, name, () => new LruCacheMap({
794
- max
795
- }));
796
- const cacheResult = await cache.get(key);
797
- if (isDefined7(cacheResult)) {
798
- return cacheResult;
799
- }
800
- const result = timeBudgetMs > 0 ? await timeBudget(name, context.logger, func, timeBudgetMs) : await func();
801
- await cache.set(key, result);
802
- return result;
902
+ __name(hashFromBlockNumber, "hashFromBlockNumber");
903
+
904
+ // src/block/primitives/model.ts
905
+ function isReadArchivist(value) {
906
+ return value.get !== void 0 && value.next !== void 0;
803
907
  }
804
- __name(withContextCacheResponse, "withContextCacheResponse");
908
+ __name(isReadArchivist, "isReadArchivist");
909
+ function isWriteArchivist(value) {
910
+ return value.insert !== void 0;
911
+ }
912
+ __name(isWriteArchivist, "isWriteArchivist");
913
+ function isReadWriteArchivist(value) {
914
+ return isReadArchivist(value) && isWriteArchivist(value);
915
+ }
916
+ __name(isReadWriteArchivist, "isReadWriteArchivist");
805
917
 
806
- // src/model/PayloadBundle/bundledPayloadToHydratedTransaction.ts
807
- import { PayloadBuilder as PayloadBuilder4 } from "@xyo-network/payload-builder";
808
- import { asSignedTransactionBoundWitnessWithHashMeta } from "@xyo-network/xl1-protocol";
809
- var bundledPayloadToHydratedTransaction = /* @__PURE__ */ __name(async (payload) => {
810
- const withHashMeta = await PayloadBuilder4.addHashMeta(payload.payloads);
811
- const tx = asSignedTransactionBoundWitnessWithHashMeta(withHashMeta.find((p) => p._hash === payload.root));
812
- if (tx) {
813
- return [
814
- tx,
815
- withHashMeta.filter((p) => p._hash !== payload.root)
816
- ];
817
- }
818
- }, "bundledPayloadToHydratedTransaction");
918
+ // src/block/primitives/toStepIdentityString.ts
919
+ function toStepIdentityString({ block, step }) {
920
+ return `${block}|${step}`;
921
+ }
922
+ __name(toStepIdentityString, "toStepIdentityString");
819
923
 
820
- // src/model/PayloadBundle/hydratedTransactionToPayloadBundle.ts
821
- import { PayloadBuilder as PayloadBuilder9 } from "@xyo-network/payload-builder";
822
- import { PayloadBundleSchema } from "@xyo-network/payload-model";
924
+ // src/config/Config.ts
925
+ import * as z16 from "zod";
823
926
 
824
- // src/transaction/buildTransaction.ts
825
- import { assertEx as assertEx8, toHex as toHex2 } from "@xylabs/sdk-js";
826
- import { BoundWitnessBuilder } from "@xyo-network/boundwitness-builder";
827
- import { PayloadBuilder as PayloadBuilder5 } from "@xyo-network/payload-builder";
828
- import { defaultTransactionFees } from "@xyo-network/xl1-protocol";
829
- async function buildTransaction(chain, onChainPayloads, offChainPayloads, signer, nbf, exp, from, fees = defaultTransactionFees) {
830
- if (from === void 0 && Array.isArray(signer)) {
831
- throw new Error("from is required when signer is an array");
832
- }
833
- const txBoundWitnessFields = {
834
- chain,
835
- fees: {
836
- base: toHex2(fees.base),
837
- gasLimit: toHex2(fees.gasLimit),
838
- gasPrice: toHex2(fees.gasPrice),
839
- priority: toHex2(fees.priority)
840
- },
841
- nbf,
842
- exp
843
- };
844
- const elevatedHashes = await PayloadBuilder5.hashes(onChainPayloads);
845
- const script = [];
846
- for (const elevatedHash of elevatedHashes) {
847
- script.push(`elevate|${elevatedHash}`);
927
+ // src/config/Api.ts
928
+ import { globalRegistry } from "zod";
929
+ import * as z3 from "zod";
930
+
931
+ // src/validation/block/error.ts
932
+ import { isValidationError, ValidationError } from "@xyo-network/xl1-protocol";
933
+ var BlockValidationError = class extends ValidationError {
934
+ static {
935
+ __name(this, "BlockValidationError");
848
936
  }
849
- const fields = {
850
- ...txBoundWitnessFields,
851
- from: from ?? (Array.isArray(signer) ? assertEx8(signer.at(0)?.address) : signer.address)
852
- };
853
- if (script.length > 0) {
854
- fields.script = script;
937
+ };
938
+ var isBlockValidationError = /* @__PURE__ */ __name((error) => {
939
+ if (!isValidationError(error)) return false;
940
+ return error.name === BlockValidationError.constructor.name;
941
+ }, "isBlockValidationError");
942
+ var HydratedBlockValidationError = class extends ValidationError {
943
+ static {
944
+ __name(this, "HydratedBlockValidationError");
855
945
  }
856
- const [tx, txPayloads] = await new BoundWitnessBuilder().fields(fields).meta({
857
- $signatures: []
858
- }).payloads([
859
- ...onChainPayloads,
860
- ...offChainPayloads
861
- ]).signers(Array.isArray(signer) ? signer : [
862
- signer
863
- ]).build();
864
- return [
865
- await PayloadBuilder5.addHashMeta(tx),
866
- await PayloadBuilder5.addHashMeta(txPayloads)
867
- ];
868
- }
869
- __name(buildTransaction, "buildTransaction");
870
-
871
- // src/transaction/buildUnsignedTransaction.ts
872
- import { toHex as toHex3 } from "@xylabs/sdk-js";
873
- import { BoundWitnessBuilder as BoundWitnessBuilder2 } from "@xyo-network/boundwitness-builder";
874
- import { PayloadBuilder as PayloadBuilder6 } from "@xyo-network/payload-builder";
875
- import { defaultTransactionFees as defaultTransactionFees2 } from "@xyo-network/xl1-protocol";
876
- async function buildUnsignedTransaction(chain, onChainPayloads, offChainPayloads, nbf, exp, from, fees = defaultTransactionFees2) {
877
- const txBoundWitnessFields = {
878
- chain,
879
- fees: {
880
- base: toHex3(fees.base),
881
- gasLimit: toHex3(fees.gasLimit),
882
- gasPrice: toHex3(fees.gasPrice),
883
- priority: toHex3(fees.priority)
884
- },
885
- nbf,
886
- exp
887
- };
888
- const elevatedHashes = await PayloadBuilder6.hashes(onChainPayloads);
889
- const script = [];
890
- for (const elevatedHash of elevatedHashes) {
891
- script.push(`elevate|${elevatedHash}`);
946
+ };
947
+ var isHydratedBlockValidationError = /* @__PURE__ */ __name((error) => {
948
+ if (!isValidationError(error)) return false;
949
+ return error.name === HydratedBlockValidationError.constructor.name;
950
+ }, "isHydratedBlockValidationError");
951
+ var HydratedBlockStateValidationError = class extends ValidationError {
952
+ static {
953
+ __name(this, "HydratedBlockStateValidationError");
892
954
  }
893
- const fields = {
894
- ...txBoundWitnessFields,
895
- from
896
- };
897
- if (script.length > 0) {
898
- fields.script = script;
955
+ chainId;
956
+ constructor(hash, chainId, value, message, cause) {
957
+ super(hash, value, message, cause);
958
+ this.chainId = chainId;
899
959
  }
900
- const [tx, txPayloads] = await new BoundWitnessBuilder2().fields(fields).meta({
901
- $signatures: []
902
- }).payloads([
903
- ...onChainPayloads,
904
- ...offChainPayloads
905
- ]).build(false);
906
- return [
907
- tx,
908
- txPayloads
909
- ];
910
- }
911
- __name(buildUnsignedTransaction, "buildUnsignedTransaction");
912
-
913
- // src/transaction/confirmSubmittedTransaction.ts
914
- import { delay, isDefined as isDefined8 } from "@xylabs/sdk-js";
915
- var DEFAULT_CONFIRMATION_ATTEMPTS = 20;
916
- var DEFAULT_DELAY_BETWEEN_ATTEMPTS = 1e3;
917
- var confirmSubmittedTransaction = /* @__PURE__ */ __name(async (viewer, txHash, options) => {
918
- const { attempts: maxAttempts = DEFAULT_CONFIRMATION_ATTEMPTS, delay: attemptDelay = DEFAULT_DELAY_BETWEEN_ATTEMPTS } = options ?? {};
919
- options?.logger?.log("\u{1F680} confirming transaction:", txHash, "\n");
920
- let attempts = 0;
921
- while (true) {
922
- const tx = await viewer.transactionByHash(txHash) ?? void 0;
923
- if (isDefined8(tx)) {
924
- options?.logger?.log("\u2705 Transaction confirmed:", txHash, "\n");
925
- return tx;
926
- } else {
927
- attempts++;
928
- if (attempts > maxAttempts) {
929
- options?.logger?.error(`\u26A0\uFE0F Transaction not confirmed after ${maxAttempts} attempts`);
930
- throw new Error(`Transaction ${txHash} not confirmed after ${maxAttempts} attempts`);
931
- } else {
932
- options?.logger?.log(`\u{1F504} Transaction not confirmed yet, attempt ${attempts}. Retrying...`, "\n");
933
- await delay(attemptDelay);
934
- }
935
- }
936
- }
937
- }, "confirmSubmittedTransaction");
938
-
939
- // src/transaction/hydrateTransaction.ts
940
- import { assertEx as assertEx9 } from "@xylabs/sdk-js";
941
- import { hydrateTypedBoundWitness, tryHydrateTypedBoundWitness } from "@xyo-network/archivist-model";
942
- import { isAllowedBlockPayload as isAllowedBlockPayload2, isSignedTransactionBoundWitnessWithStorageMeta } from "@xyo-network/xl1-protocol";
943
- var tryHydrateTransaction = /* @__PURE__ */ __name(async ({ chainMap }, hash) => {
944
- return await tryHydrateTypedBoundWitness({
945
- get(hashes) {
946
- return chainMap.getMany(hashes);
947
- },
948
- next() {
949
- throw new Error("Not implemented");
950
- }
951
- }, hash, isSignedTransactionBoundWitnessWithStorageMeta);
952
- }, "tryHydrateTransaction");
953
- var hydrateTransaction = /* @__PURE__ */ __name(async ({ chainMap }, hash) => {
954
- return await hydrateTypedBoundWitness({
955
- get(hashes) {
956
- return chainMap.getMany(hashes);
957
- },
958
- next() {
959
- throw new Error("Not implemented");
960
- }
961
- }, hash, isSignedTransactionBoundWitnessWithStorageMeta);
962
- }, "hydrateTransaction");
963
- var flattenHydratedTransaction = /* @__PURE__ */ __name((hydratedTransaction) => {
964
- const [tx, txPayloads] = hydratedTransaction;
965
- return [
966
- ...txPayloads,
967
- tx
968
- ];
969
- }, "flattenHydratedTransaction");
970
- var flattenHydratedTransactions = /* @__PURE__ */ __name((hydratedTransactions) => hydratedTransactions.flatMap((tx) => flattenHydratedTransaction(tx)), "flattenHydratedTransactions");
971
- var tryHydrateElevatedTransaction = /* @__PURE__ */ __name(async ({ chainMap }, hash) => {
972
- const hydratedTransaction = await tryHydrateTransaction({
973
- chainMap
974
- }, hash);
975
- if (!hydratedTransaction) {
976
- return void 0;
977
- }
978
- const [transaction, payloads] = hydratedTransaction;
979
- const opCodes = (transaction.script ?? []).filter((operation) => operation.startsWith("elevate|"));
980
- const elevatedPayloads2 = [];
981
- for (const opCode of opCodes) {
982
- const [code, hash2] = opCode.split("|");
983
- if (code === "elevated") {
984
- const elevatedPayload = payloads.find((payload) => payload._hash === hash2);
985
- if (isAllowedBlockPayload2(elevatedPayload)) {
986
- elevatedPayloads2.push(elevatedPayload);
987
- }
988
- }
989
- }
990
- if (opCodes.length === elevatedPayloads2.length) {
991
- return [
992
- transaction,
993
- elevatedPayloads2
994
- ];
995
- }
996
- return void 0;
997
- }, "tryHydrateElevatedTransaction");
998
- var hydrateElevatedTransaction = /* @__PURE__ */ __name(async (context, hash) => {
999
- return assertEx9(await tryHydrateElevatedTransaction(context, hash), () => "Hydration failed");
1000
- }, "hydrateElevatedTransaction");
1001
-
1002
- // src/transaction/primitives/transactionBlockByteCount.ts
1003
- import { PayloadBuilder as PayloadBuilder7 } from "@xyo-network/payload-builder";
1004
- function transactionBlockByteCount([transaction, payloads]) {
1005
- const cleanTransaction = PayloadBuilder7.omitStorageMeta(transaction);
1006
- const transactionBytes = JSON.stringify(cleanTransaction).length;
1007
- const cleanPayloads = PayloadBuilder7.omitStorageMeta(payloads);
1008
- return cleanPayloads.reduce((acc, payload) => acc + JSON.stringify(payload).length, 0) + transactionBytes;
1009
- }
1010
- __name(transactionBlockByteCount, "transactionBlockByteCount");
1011
-
1012
- // src/transaction/primitives/transactionElevatedPayloads.ts
1013
- import { asHash } from "@xylabs/sdk-js";
1014
-
1015
- // src/transaction/primitives/transactionOperations.ts
1016
- function crackOperation(operation) {
1017
- const parts = operation.split("|");
1018
- if (parts.length < 2) {
1019
- throw new Error(`Invalid operation format: ${operation}`);
1020
- }
1021
- return [
1022
- parts[0],
1023
- parts.slice(1)
1024
- ];
1025
- }
1026
- __name(crackOperation, "crackOperation");
1027
- function crackOperations(operations) {
1028
- return operations.map((op) => crackOperation(op));
1029
- }
1030
- __name(crackOperations, "crackOperations");
1031
-
1032
- // src/transaction/primitives/transactionElevatedPayloads.ts
1033
- function transactionElevatedPayloadHashes(transaction) {
1034
- const elevateOperations = crackOperations(transaction.script ?? []).filter((op) => op[0] === "elevate");
1035
- return elevateOperations.map((op) => asHash(op[1][0], true));
1036
- }
1037
- __name(transactionElevatedPayloadHashes, "transactionElevatedPayloadHashes");
1038
- function transactionElevatedPayloads([transaction, payloads]) {
1039
- const hashes = transactionElevatedPayloadHashes(transaction);
1040
- const elevatedPayloads2 = payloads.filter((payload) => hashes.includes(payload._hash));
1041
- return elevatedPayloads2;
1042
- }
1043
- __name(transactionElevatedPayloads, "transactionElevatedPayloads");
1044
-
1045
- // src/transaction/primitives/transactionRequiredGas.ts
1046
- import { AttoXL1, TransactionGasCosts } from "@xyo-network/xl1-protocol";
1047
- function transactionBytesRequiredGas([transaction, payloads]) {
1048
- const transactionBlockBytes = transactionBlockByteCount([
1049
- transaction,
1050
- payloads
1051
- ]);
1052
- return AttoXL1(TransactionGasCosts.characterStorage * BigInt(transactionBlockBytes));
1053
- }
1054
- __name(transactionBytesRequiredGas, "transactionBytesRequiredGas");
1055
- function transactionRequiredGas(hydratedTransaction) {
1056
- const elevatedPayloads2 = transactionElevatedPayloads(hydratedTransaction);
1057
- const hashes = elevatedPayloads2.length + 1;
1058
- const signatures = hydratedTransaction[0].addresses.length;
1059
- return AttoXL1(transactionBytesRequiredGas(hydratedTransaction) + TransactionGasCosts.hashValidation * BigInt(hashes) + TransactionGasCosts.signatureValidation * BigInt(signatures) + TransactionGasCosts.payloadValidation * BigInt(elevatedPayloads2.length));
1060
- }
1061
- __name(transactionRequiredGas, "transactionRequiredGas");
1062
-
1063
- // src/transaction/script.ts
1064
- import { asHash as asHash2 } from "@xylabs/sdk-js";
1065
- import { assertEx as assertEx10, filterAs } from "@xylabs/sdk-js";
1066
- import { isAllowedBlockPayloadWithHashMeta } from "@xyo-network/xl1-protocol";
1067
- var tryExtractElevatedHashesFromScript = /* @__PURE__ */ __name((strings) => {
1068
- const hashes = strings.filter((str) => str.startsWith("elevate|")).map((str) => str.split("|")[1]);
1069
- return filterAs(hashes, (h) => asHash2(h));
1070
- }, "tryExtractElevatedHashesFromScript");
1071
- var extractElevatedHashesFromScript = /* @__PURE__ */ __name((strings) => {
1072
- const hashes = strings.filter((str) => str.startsWith("elevate|")).map((str) => str.split("|")[1]);
1073
- const filtered = filterAs(hashes, (h) => asHash2(h));
1074
- assertEx10(filtered.length === hashes.length, () => "Invalid elevated hashes");
1075
- return filtered;
1076
- }, "extractElevatedHashesFromScript");
1077
- var tryExtractElevatedHashes = /* @__PURE__ */ __name((tx) => {
1078
- const [bw, payloads] = tx;
1079
- const { script } = bw;
1080
- const hashes = script ? tryExtractElevatedHashesFromScript(script) : [];
1081
- return payloads.filter((p) => hashes.includes(p._hash)).filter(isAllowedBlockPayloadWithHashMeta);
1082
- }, "tryExtractElevatedHashes");
1083
- var extractElevatedHashes = /* @__PURE__ */ __name((tx) => {
1084
- const [bw, payloads] = tx;
1085
- const { script } = bw;
1086
- const hashes = script ? tryExtractElevatedHashesFromScript(script) : [];
1087
- const filtered = payloads.filter((p) => hashes.includes(p._hash)).filter(isAllowedBlockPayloadWithHashMeta);
1088
- assertEx10(filtered.length === hashes.length, () => "Invalid elevated hashes");
1089
- return filtered;
1090
- }, "extractElevatedHashes");
1091
-
1092
- // src/transaction/signTransaction.ts
1093
- import { assertEx as assertEx11, hexFromArrayBuffer, toArrayBuffer } from "@xylabs/sdk-js";
1094
- import { PayloadBuilder as PayloadBuilder8 } from "@xyo-network/payload-builder";
1095
- async function signTransaction(tx, account) {
1096
- assertEx11(tx.from === account.address, () => "Signer address does not match transaction from address");
1097
- const unsignedTx = structuredClone(tx);
1098
- unsignedTx.addresses = [
1099
- account.address
1100
- ];
1101
- unsignedTx.previous_hashes = [
1102
- account.previousHash ?? null
1103
- ];
1104
- const hash = await PayloadBuilder8.dataHash(unsignedTx);
1105
- const hashBytes = toArrayBuffer(hash);
1106
- const [signature] = await account.sign(hashBytes);
1107
- const result = {
1108
- ...unsignedTx,
1109
- $signatures: [
1110
- hexFromArrayBuffer(signature)
1111
- ]
1112
- };
1113
- return result;
1114
- }
1115
- __name(signTransaction, "signTransaction");
1116
-
1117
- // src/model/PayloadBundle/hydratedTransactionToPayloadBundle.ts
1118
- var hydratedTransactionToPayloadBundle = /* @__PURE__ */ __name((transaction) => {
1119
- const root = transaction[0]._hash;
1120
- return bundle(root, transaction);
1121
- }, "hydratedTransactionToPayloadBundle");
1122
- var bundle = /* @__PURE__ */ __name((root, transaction) => {
1123
- const payloads = flattenHydratedTransaction(transaction).flatMap((p) => PayloadBuilder9.omitStorageMeta(p));
1124
- return new PayloadBuilder9({
1125
- schema: PayloadBundleSchema
1126
- }).fields({
1127
- payloads,
1128
- root
1129
- }).build();
1130
- }, "bundle");
1131
-
1132
- // src/block/primitives/blockFromBlockNumber.ts
1133
- async function blockFromBlockNumber(context, blockNumber) {
1134
- const cacheKey = `${blockNumber}`;
1135
- return await withContextCacheResponse(context, "blockFromBlockNumber", cacheKey, async () => {
1136
- const [headHash] = await context.head();
1137
- const result = await context.store.chainMap.get(headHash);
1138
- if (!isDefined9(result)) {
1139
- throw new Error(`Head block not found for hash: ${headHash}`);
1140
- }
1141
- let currentBlock = asSignedBlockBoundWitnessWithStorageMeta(result, () => `Found Payload is not a Signed<BlockBoundWitness>: ${JSON.stringify(result, null, 2)}`);
1142
- if (currentBlock.block < blockNumber) {
1143
- throw new Error(`Block number ${blockNumber} is greater than head ${currentBlock.block}.`);
1144
- }
1145
- while (currentBlock.block > blockNumber) {
1146
- let jumpHash = currentBlock.previous;
1147
- let jumpBlockNumber = currentBlock.block - 1;
1148
- for (const [step, stepSize2] of StepSizes7.entries()) {
1149
- const possibleJumpBlockNumber = currentBlock.block - currentBlock.block % stepSize2 - 1;
1150
- if (possibleJumpBlockNumber >= blockNumber && possibleJumpBlockNumber <= jumpBlockNumber) {
1151
- jumpBlockNumber = possibleJumpBlockNumber;
1152
- jumpHash = asHash3(currentBlock.step_hashes?.at(step), () => `Step hash not found for step ${step} in block ${currentBlock.block}`);
1153
- }
1154
- }
1155
- const newBlock = await context.store.chainMap.get(asHash3(jumpHash, () => `Jump hash not found for block number [${blockNumber}]: ${jumpBlockNumber} ${toSafeJsonString(currentBlock, 10)}`));
1156
- if (!isDefined9(newBlock)) {
1157
- throw new Error(`Block not found for jump hash: ${jumpHash}`);
1158
- }
1159
- currentBlock = asSignedBlockBoundWitnessWithStorageMeta(newBlock, () => {
1160
- const result2 = SignedBlockBoundWitnessWithHashMetaZod.safeParse(newBlock);
1161
- return `Found Payload [jump hash] is not a Signed<BlockBoundWitness>: ${result2.error}`;
1162
- });
1163
- if (currentBlock.block === blockNumber) {
1164
- break;
1165
- }
1166
- if (currentBlock.block < blockNumber) {
1167
- throw new Error(`Block number ${blockNumber} is not a valid step block number for block ${headHash}.`);
1168
- }
1169
- }
1170
- return currentBlock;
1171
- });
1172
- }
1173
- __name(blockFromBlockNumber, "blockFromBlockNumber");
1174
-
1175
- // src/block/primitives/frames/calculateFramesFromRange.ts
1176
- import { asXL1BlockNumber as asXL1BlockNumber4, stepSize } from "@xyo-network/xl1-protocol";
1177
- function calculateFramesFromRange(range, step) {
1178
- const size = stepSize(step);
1179
- let start = Math.trunc(range[0] / size) * size;
1180
- const fitted = [];
1181
- const remaining = [];
1182
- if (start !== range[0]) {
1183
- start += size;
1184
- remaining.push([
1185
- range[0],
1186
- asXL1BlockNumber4(Math.min(start - 1, range[1]), true)
1187
- ]);
1188
- }
1189
- for (let i = start; i <= range[1]; i += size) {
1190
- if (i + size - 1 <= range[1]) {
1191
- fitted.push([
1192
- asXL1BlockNumber4(i, {
1193
- name: "calculateFramesFromRange A"
1194
- }),
1195
- asXL1BlockNumber4(Math.min(i + size - 1, range[1]), {
1196
- name: "calculateFramesFromRange B"
1197
- })
1198
- ]);
1199
- } else {
1200
- remaining.push([
1201
- asXL1BlockNumber4(i, {
1202
- name: "calculateFramesFromRange C"
1203
- }),
1204
- range[1]
1205
- ]);
1206
- }
1207
- }
1208
- return [
1209
- fitted,
1210
- remaining
1211
- ];
1212
- }
1213
- __name(calculateFramesFromRange, "calculateFramesFromRange");
1214
-
1215
- // src/block/primitives/frames/deepCalculateFramesFromRange.ts
1216
- import { StepSizes as StepSizes8 } from "@xyo-network/xl1-protocol";
1217
- function deepCalculateFramesFromRange(range, startingStep = StepSizes8.length - 1) {
1218
- const fitted = [];
1219
- let remaining = [
1220
- range
1221
- ];
1222
- for (let step = startingStep; step >= 0; step--) {
1223
- const newRemaining = [];
1224
- for (const range2 of remaining) {
1225
- const [newFittedFrames, newRemainingFrames] = calculateFramesFromRange(range2, step);
1226
- fitted.push(...newFittedFrames);
1227
- newRemaining.push(...newRemainingFrames);
1228
- }
1229
- remaining = newRemaining;
1230
- }
1231
- for (const range2 of remaining) {
1232
- for (let i = range2[0]; i <= range2[1]; i++) {
1233
- fitted.push([
1234
- i,
1235
- i
1236
- ]);
1237
- }
1238
- }
1239
- return fitted.toSorted((a, b) => a[0] - b[0]);
1240
- }
1241
- __name(deepCalculateFramesFromRange, "deepCalculateFramesFromRange");
1242
-
1243
- // src/block/primitives/hashFromBlockNumber.ts
1244
- async function hashFromBlockNumber(context, blockNumber) {
1245
- return (await blockFromBlockNumber(context, blockNumber))._hash;
1246
- }
1247
- __name(hashFromBlockNumber, "hashFromBlockNumber");
1248
-
1249
- // src/block/primitives/model.ts
1250
- function isReadArchivist(value) {
1251
- return value.get !== void 0 && value.next !== void 0;
1252
- }
1253
- __name(isReadArchivist, "isReadArchivist");
1254
- function isWriteArchivist(value) {
1255
- return value.insert !== void 0;
1256
- }
1257
- __name(isWriteArchivist, "isWriteArchivist");
1258
- function isReadWriteArchivist(value) {
1259
- return isReadArchivist(value) && isWriteArchivist(value);
1260
- }
1261
- __name(isReadWriteArchivist, "isReadWriteArchivist");
1262
-
1263
- // src/block/primitives/toStepIdentityString.ts
1264
- function toStepIdentityString({ block, step }) {
1265
- return `${block}|${step}`;
1266
- }
1267
- __name(toStepIdentityString, "toStepIdentityString");
1268
-
1269
- // src/config/Config.ts
1270
- import * as z15 from "zod";
1271
-
1272
- // src/config/Api.ts
1273
- import { globalRegistry } from "zod";
1274
- import * as z2 from "zod";
1275
-
1276
- // src/validation/block/error.ts
1277
- import { isValidationError, ValidationError } from "@xyo-network/xl1-protocol";
1278
- var BlockValidationError = class extends ValidationError {
1279
- static {
1280
- __name(this, "BlockValidationError");
1281
- }
1282
- };
1283
- var isBlockValidationError = /* @__PURE__ */ __name((error) => {
1284
- if (!isValidationError(error)) return false;
1285
- return error.name === BlockValidationError.constructor.name;
1286
- }, "isBlockValidationError");
1287
- var HydratedBlockValidationError = class extends ValidationError {
1288
- static {
1289
- __name(this, "HydratedBlockValidationError");
1290
- }
1291
- };
1292
- var isHydratedBlockValidationError = /* @__PURE__ */ __name((error) => {
1293
- if (!isValidationError(error)) return false;
1294
- return error.name === HydratedBlockValidationError.constructor.name;
1295
- }, "isHydratedBlockValidationError");
1296
- var HydratedBlockStateValidationError = class extends ValidationError {
1297
- static {
1298
- __name(this, "HydratedBlockStateValidationError");
1299
- }
1300
- chainId;
1301
- constructor(hash, chainId, value, message, cause) {
1302
- super(hash, value, message, cause);
1303
- this.chainId = chainId;
1304
- }
1305
- };
1306
- var isHydratedBlockStateValidationError = /* @__PURE__ */ __name((error) => {
1307
- if (!isValidationError(error)) return false;
1308
- return error.name === HydratedBlockStateValidationError.constructor.name;
1309
- }, "isHydratedBlockStateValidationError");
960
+ };
961
+ var isHydratedBlockStateValidationError = /* @__PURE__ */ __name((error) => {
962
+ if (!isValidationError(error)) return false;
963
+ return error.name === HydratedBlockStateValidationError.constructor.name;
964
+ }, "isHydratedBlockStateValidationError");
1310
965
 
1311
966
  // src/validation/lib/isLocalhost.ts
1312
967
  var isLocalhost = /* @__PURE__ */ __name((hostname) => {
@@ -1323,8 +978,8 @@ var getUrl = /* @__PURE__ */ __name((host, port) => {
1323
978
  var TODO = true;
1324
979
 
1325
980
  // src/validation/schema/Mnemonic.ts
1326
- import * as z from "zod";
1327
- var MnemonicStringZod = z.string().transform((s) => s.trim().replaceAll(/\s+/g, " ")).refine((s) => [
981
+ import * as z2 from "zod";
982
+ var MnemonicStringZod = z2.string().transform((s) => s.trim().replaceAll(/\s+/g, " ")).refine((s) => [
1328
983
  12,
1329
984
  15,
1330
985
  18,
@@ -1335,16 +990,16 @@ var MnemonicStringZod = z.string().transform((s) => s.trim().replaceAll(/\s+/g,
1335
990
  }).describe("BIP-39 mnemonic string");
1336
991
 
1337
992
  // src/config/Api.ts
1338
- var ApiConfigZod = z2.object({
1339
- host: z2.string().default("localhost").register(globalRegistry, {
993
+ var ApiConfigZod = z3.object({
994
+ host: z3.string().default("localhost").register(globalRegistry, {
1340
995
  default: "localhost",
1341
996
  description: "Host for the API",
1342
997
  title: "api.host",
1343
998
  type: "string"
1344
999
  }),
1345
- initRewardsCache: z2.union([
1346
- z2.number(),
1347
- z2.string()
1000
+ initRewardsCache: z3.union([
1001
+ z3.number(),
1002
+ z3.string()
1348
1003
  ]).transform((v) => v !== "0" && v !== "false").default(true).register(globalRegistry, {
1349
1004
  description: "Whether to initialize the rewards cache on startup",
1350
1005
  title: "api.initRewardsCache",
@@ -1355,7 +1010,7 @@ var ApiConfigZod = z2.object({
1355
1010
  title: "api.mnemonic",
1356
1011
  type: "string"
1357
1012
  }),
1358
- port: z2.coerce.number().default(8080).register(globalRegistry, {
1013
+ port: z3.coerce.number().default(8080).register(globalRegistry, {
1359
1014
  default: 8080,
1360
1015
  description: "Port for the API",
1361
1016
  title: "api.port",
@@ -1365,9 +1020,9 @@ var ApiConfigZod = z2.object({
1365
1020
 
1366
1021
  // src/config/Bridge.ts
1367
1022
  import { globalRegistry as globalRegistry2 } from "zod";
1368
- import * as z3 from "zod";
1369
- var BridgeConfigZod = z3.object({
1370
- host: z3.string().default("localhost").register(globalRegistry2, {
1023
+ import * as z4 from "zod";
1024
+ var BridgeConfigZod = z4.object({
1025
+ host: z4.string().default("localhost").register(globalRegistry2, {
1371
1026
  default: "localhost",
1372
1027
  description: "Host for the Bridge",
1373
1028
  title: "api.host",
@@ -1378,7 +1033,7 @@ var BridgeConfigZod = z3.object({
1378
1033
  title: "api.mnemonic",
1379
1034
  type: "string"
1380
1035
  }),
1381
- port: z3.coerce.number().default(8081).register(globalRegistry2, {
1036
+ port: z4.coerce.number().default(8081).register(globalRegistry2, {
1382
1037
  default: 8081,
1383
1038
  description: "Port for the Bridge",
1384
1039
  title: "api.port",
@@ -1389,9 +1044,9 @@ var BridgeConfigZod = z3.object({
1389
1044
  // src/config/Chain.ts
1390
1045
  import { AddressZod } from "@xylabs/sdk-js";
1391
1046
  import { globalRegistry as globalRegistry3 } from "zod";
1392
- import * as z4 from "zod";
1393
- var ChainConfigZod = z4.object({
1394
- id: z4.string().optional().register(globalRegistry3, {
1047
+ import * as z5 from "zod";
1048
+ var ChainConfigZod = z5.object({
1049
+ id: z5.string().optional().register(globalRegistry3, {
1395
1050
  description: "The unique identifier for the chain. Should be the staking contract address for contract-backed chains.",
1396
1051
  title: "chain.id",
1397
1052
  type: "string"
@@ -1405,28 +1060,28 @@ var ChainConfigZod = z4.object({
1405
1060
 
1406
1061
  // src/config/Evm.ts
1407
1062
  import { globalRegistry as globalRegistry4 } from "zod";
1408
- import * as z5 from "zod";
1409
- var EvmInfuraConfigZod = z5.object({
1410
- projectId: z5.string().optional().register(globalRegistry4, {
1063
+ import * as z6 from "zod";
1064
+ var EvmInfuraConfigZod = z6.object({
1065
+ projectId: z6.string().optional().register(globalRegistry4, {
1411
1066
  description: "Infura project ID",
1412
1067
  title: "evm.infura.projectId",
1413
1068
  type: "string"
1414
1069
  }),
1415
- projectSecret: z5.string().optional().register(globalRegistry4, {
1070
+ projectSecret: z6.string().optional().register(globalRegistry4, {
1416
1071
  description: "Infura project secret",
1417
1072
  title: "evm.infura.projectSecret",
1418
1073
  type: "string"
1419
1074
  })
1420
1075
  });
1421
- var EvmJsonRpcConfigZod = z5.object({
1422
- url: z5.url().optional().register(globalRegistry4, {
1076
+ var EvmJsonRpcConfigZod = z6.object({
1077
+ url: z6.url().optional().register(globalRegistry4, {
1423
1078
  description: "JSON-RPC URL",
1424
1079
  title: "evm.jsonRpc.url",
1425
1080
  type: "string"
1426
1081
  })
1427
1082
  });
1428
- var EvmConfigZod = z5.object({
1429
- chainId: z5.string().optional().register(globalRegistry4, {
1083
+ var EvmConfigZod = z6.object({
1084
+ chainId: z6.string().optional().register(globalRegistry4, {
1430
1085
  description: "EVM chain ID",
1431
1086
  title: "evm.chainId",
1432
1087
  type: "string"
@@ -1438,17 +1093,17 @@ var EvmConfigZod = z5.object({
1438
1093
  // src/config/Log.ts
1439
1094
  import { LogLevel } from "@xylabs/sdk-js";
1440
1095
  import { globalRegistry as globalRegistry5 } from "zod";
1441
- import * as z6 from "zod";
1096
+ import * as z7 from "zod";
1442
1097
  var LogLevels = Object.keys(LogLevel);
1443
- var LogConfigZod = z6.object({
1444
- logLevel: z6.enum(LogLevels).default("info").register(globalRegistry5, {
1098
+ var LogConfigZod = z7.object({
1099
+ logLevel: z7.enum(LogLevels).default("info").register(globalRegistry5, {
1445
1100
  choices: LogLevels,
1446
1101
  default: "info",
1447
1102
  description: "Desired process verbosity",
1448
1103
  title: "logLevel",
1449
1104
  type: "string"
1450
1105
  }),
1451
- silent: z6.boolean().default(false).register(globalRegistry5, {
1106
+ silent: z7.boolean().default(false).register(globalRegistry5, {
1452
1107
  default: false,
1453
1108
  description: "Whether to run in silent mode",
1454
1109
  title: "silent",
@@ -1458,9 +1113,9 @@ var LogConfigZod = z6.object({
1458
1113
 
1459
1114
  // src/config/Mempool.ts
1460
1115
  import { globalRegistry as globalRegistry6 } from "zod";
1461
- import * as z7 from "zod";
1462
- var MempoolConfigZod = z7.object({
1463
- enabled: z7.string().default("false").transform((val, ctx) => {
1116
+ import * as z8 from "zod";
1117
+ var MempoolConfigZod = z8.object({
1118
+ enabled: z8.string().default("false").transform((val, ctx) => {
1464
1119
  const normalized = val.toLowerCase().trim();
1465
1120
  if ([
1466
1121
  "true",
@@ -1479,14 +1134,14 @@ var MempoolConfigZod = z7.object({
1479
1134
  expected: "boolean",
1480
1135
  message: `Invalid boolean value: "${val}". Use true/false, 1/0, yes/no.`
1481
1136
  });
1482
- return z7.NEVER;
1137
+ return z8.NEVER;
1483
1138
  }).register(globalRegistry6, {
1484
1139
  default: "false",
1485
1140
  description: "Enable the Mempool",
1486
1141
  title: "mempool.enabled",
1487
1142
  type: "boolean"
1488
1143
  }),
1489
- host: z7.string().default("localhost").register(globalRegistry6, {
1144
+ host: z8.string().default("localhost").register(globalRegistry6, {
1490
1145
  default: "localhost",
1491
1146
  description: "Host for the Mempool",
1492
1147
  title: "mempool.host",
@@ -1497,7 +1152,7 @@ var MempoolConfigZod = z7.object({
1497
1152
  title: "mempool.mnemonic",
1498
1153
  type: "string"
1499
1154
  }),
1500
- port: z7.coerce.number().default(8083).register(globalRegistry6, {
1155
+ port: z8.coerce.number().default(8083).register(globalRegistry6, {
1501
1156
  default: 8083,
1502
1157
  description: "Port for the Mempool",
1503
1158
  title: "mempool.port",
@@ -1506,38 +1161,38 @@ var MempoolConfigZod = z7.object({
1506
1161
  });
1507
1162
 
1508
1163
  // src/config/Producer.ts
1509
- import { AddressZod as AddressZod2, asAddress as asAddress3 } from "@xylabs/sdk-js";
1164
+ import { AddressZod as AddressZod2, asAddress } from "@xylabs/sdk-js";
1510
1165
  import { globalRegistry as globalRegistry7 } from "zod";
1511
- import * as z8 from "zod";
1512
- var ProducerConfigZod = z8.object({
1513
- allowlist: z8.preprocess((val) => {
1166
+ import * as z9 from "zod";
1167
+ var ProducerConfigZod = z9.object({
1168
+ allowlist: z9.preprocess((val) => {
1514
1169
  if (typeof val === "string") {
1515
- return val.split(",").map((s) => asAddress3(s.trim()));
1170
+ return val.split(",").map((s) => asAddress(s.trim()));
1516
1171
  }
1517
1172
  return val;
1518
- }, z8.array(AddressZod2).optional().register(globalRegistry7, {
1173
+ }, z9.array(AddressZod2).optional().register(globalRegistry7, {
1519
1174
  description: "List of allowed producer addresses, if undefined anyone can participate",
1520
1175
  title: "allowlist",
1521
1176
  type: "array"
1522
1177
  })),
1523
- disableIntentRedeclaration: z8.boolean().optional().register(globalRegistry7, {
1178
+ disableIntentRedeclaration: z9.boolean().optional().register(globalRegistry7, {
1524
1179
  description: "Should the producer skip redeclaring their intent to continue producing blocks",
1525
1180
  title: "producer.disableIntentRedeclaration",
1526
1181
  type: "boolean"
1527
1182
  }),
1528
1183
  // TODO: Port schema
1529
- healthCheckPort: z8.coerce.number().optional().register(globalRegistry7, {
1184
+ healthCheckPort: z9.coerce.number().optional().register(globalRegistry7, {
1530
1185
  description: "Port for the Producer health checks",
1531
1186
  title: "producer.healthCheckPort",
1532
1187
  type: "number"
1533
1188
  }),
1534
- heartbeatInterval: z8.coerce.number().default(36e5).register(globalRegistry7, {
1189
+ heartbeatInterval: z9.coerce.number().default(36e5).register(globalRegistry7, {
1535
1190
  description: "The number of milliseconds between heartbeats if no blocks are produced",
1536
1191
  title: "producer.heartbeatInterval",
1537
1192
  type: "number"
1538
1193
  }),
1539
1194
  // TODO: BigInt schema
1540
- minStake: z8.coerce.number().default(1).register(globalRegistry7, {
1195
+ minStake: z9.coerce.number().default(1).register(globalRegistry7, {
1541
1196
  description: "Minimum stake required to be a Producer",
1542
1197
  title: "producer.minStake",
1543
1198
  type: "number"
@@ -1548,14 +1203,14 @@ var ProducerConfigZod = z8.object({
1548
1203
  type: "string"
1549
1204
  }),
1550
1205
  // TODO: Port schema
1551
- port: z8.coerce.number().default(8081).register(globalRegistry7, {
1206
+ port: z9.coerce.number().default(8081).register(globalRegistry7, {
1552
1207
  default: 8081,
1553
1208
  description: "Port for the Producer",
1554
1209
  title: "producer.port",
1555
1210
  type: "number"
1556
1211
  }),
1557
1212
  // TODO: Address schema
1558
- rewardAddress: z8.string().optional().register(globalRegistry7, {
1213
+ rewardAddress: z9.string().optional().register(globalRegistry7, {
1559
1214
  description: "Address to receive block rewards",
1560
1215
  title: "producer.rewardAddress",
1561
1216
  type: "string"
@@ -1564,15 +1219,15 @@ var ProducerConfigZod = z8.object({
1564
1219
 
1565
1220
  // src/config/RewardRedemptionApi.ts
1566
1221
  import { globalRegistry as globalRegistry8 } from "zod";
1567
- import * as z9 from "zod";
1568
- var RewardRedemptionApiConfigZod = z9.object({
1569
- chainRpcApiUrl: z9.string().default("http://localhost:8080/rpc").register(globalRegistry8, {
1222
+ import * as z10 from "zod";
1223
+ var RewardRedemptionApiConfigZod = z10.object({
1224
+ chainRpcApiUrl: z10.string().default("http://localhost:8080/rpc").register(globalRegistry8, {
1570
1225
  default: "http://localhost:8080/rpc",
1571
1226
  description: "URL for the Chain RPC API",
1572
1227
  title: "rewardRedemptionApi.chainRpcApiUrl",
1573
1228
  type: "string"
1574
1229
  }),
1575
- host: z9.string().default("localhost").register(globalRegistry8, {
1230
+ host: z10.string().default("localhost").register(globalRegistry8, {
1576
1231
  default: "localhost",
1577
1232
  description: "Host for the Redemption API",
1578
1233
  title: "rewardRedemptionApi.host",
@@ -1583,7 +1238,7 @@ var RewardRedemptionApiConfigZod = z9.object({
1583
1238
  title: "rewardRedemptionApi.mnemonic",
1584
1239
  type: "string"
1585
1240
  }),
1586
- port: z9.coerce.number().default(8082).register(globalRegistry8, {
1241
+ port: z10.coerce.number().default(8082).register(globalRegistry8, {
1587
1242
  default: 8082,
1588
1243
  description: "Port for the Redemption API",
1589
1244
  title: "rewardRedemptionApi.port",
@@ -1593,14 +1248,14 @@ var RewardRedemptionApiConfigZod = z9.object({
1593
1248
 
1594
1249
  // src/config/Services.ts
1595
1250
  import { globalRegistry as globalRegistry9 } from "zod";
1596
- import * as z10 from "zod";
1597
- var ServicesConfigZod = z10.object({
1598
- accountBalanceViewerEndpoint: z10.string().optional().register(globalRegistry9, {
1251
+ import * as z11 from "zod";
1252
+ var ServicesConfigZod = z11.object({
1253
+ accountBalanceViewerEndpoint: z11.string().optional().register(globalRegistry9, {
1599
1254
  description: "Endpoint of the API to use for instantiating an external AccountBalanceViewer",
1600
1255
  title: "services.accountBalanceViewerEndpoint",
1601
1256
  type: "string"
1602
1257
  }),
1603
- apiEndpoint: z10.string().optional().register(globalRegistry9, {
1258
+ apiEndpoint: z11.string().optional().register(globalRegistry9, {
1604
1259
  description: "Endpoint of the API to use for instantiating an external Viewers",
1605
1260
  title: "services.apiEndpoint",
1606
1261
  type: "string"
@@ -1608,36 +1263,36 @@ var ServicesConfigZod = z10.object({
1608
1263
  });
1609
1264
 
1610
1265
  // src/config/storage/driver/Mongo.ts
1611
- import { isDefined as isDefined10, isUndefined as isUndefined2 } from "@xylabs/sdk-js";
1266
+ import { isDefined as isDefined7, isUndefined as isUndefined2 } from "@xylabs/sdk-js";
1612
1267
  import { globalRegistry as globalRegistry10 } from "zod";
1613
- import * as z11 from "zod";
1268
+ import * as z12 from "zod";
1614
1269
  var hasMongoConfig = /* @__PURE__ */ __name((config) => {
1615
1270
  if (isUndefined2(config)) return false;
1616
- return isDefined10(config.connectionString) && isDefined10(config.database) && isDefined10(config.domain) && isDefined10(config.password) && isDefined10(config.username);
1271
+ return isDefined7(config.connectionString) && isDefined7(config.database) && isDefined7(config.domain) && isDefined7(config.password) && isDefined7(config.username);
1617
1272
  }, "hasMongoConfig");
1618
- var MongoConfigZod = z11.object({
1273
+ var MongoConfigZod = z12.object({
1619
1274
  // TODO: Create from other arguments
1620
- connectionString: z11.string().nonempty().optional().register(globalRegistry10, {
1275
+ connectionString: z12.string().nonempty().optional().register(globalRegistry10, {
1621
1276
  description: "MongoDB connection string",
1622
1277
  title: "storage.mongo.connectionString",
1623
1278
  type: "string"
1624
1279
  }),
1625
- database: z11.string().nonempty().optional().register(globalRegistry10, {
1280
+ database: z12.string().nonempty().optional().register(globalRegistry10, {
1626
1281
  description: "MongoDB database name",
1627
1282
  title: "storage.mongo.database",
1628
1283
  type: "string"
1629
1284
  }),
1630
- domain: z11.string().nonempty().optional().register(globalRegistry10, {
1285
+ domain: z12.string().nonempty().optional().register(globalRegistry10, {
1631
1286
  description: "MongoDB domain",
1632
1287
  title: "storage.mongo.domain",
1633
1288
  type: "string"
1634
1289
  }),
1635
- password: z11.string().nonempty().optional().register(globalRegistry10, {
1290
+ password: z12.string().nonempty().optional().register(globalRegistry10, {
1636
1291
  description: "MongoDB password",
1637
1292
  title: "storage.mongo.password",
1638
1293
  type: "string"
1639
1294
  }),
1640
- username: z11.string().nonempty().optional().register(globalRegistry10, {
1295
+ username: z12.string().nonempty().optional().register(globalRegistry10, {
1641
1296
  description: "MongoDB username",
1642
1297
  title: "storage.mongo.username",
1643
1298
  type: "string"
@@ -1646,10 +1301,10 @@ var MongoConfigZod = z11.object({
1646
1301
 
1647
1302
  // src/config/storage/Storage.ts
1648
1303
  import { globalRegistry as globalRegistry11 } from "zod";
1649
- import * as z12 from "zod";
1650
- var StorageConfigZod = z12.object({
1304
+ import * as z13 from "zod";
1305
+ var StorageConfigZod = z13.object({
1651
1306
  mongo: MongoConfigZod.optional().describe("Configuration for the MongoD storage driver"),
1652
- root: z12.string().optional().register(globalRegistry11, {
1307
+ root: z13.string().optional().register(globalRegistry11, {
1653
1308
  description: "Root directory for local storage",
1654
1309
  title: "storage.root",
1655
1310
  type: "string"
@@ -1658,33 +1313,33 @@ var StorageConfigZod = z12.object({
1658
1313
 
1659
1314
  // src/config/Telemetry.ts
1660
1315
  import { globalRegistry as globalRegistry12 } from "zod";
1661
- import * as z13 from "zod";
1662
- var MetricsScrapeConfigZod = z13.object({
1663
- path: z13.string().default("/metrics").register(globalRegistry12, {
1316
+ import * as z14 from "zod";
1317
+ var MetricsScrapeConfigZod = z14.object({
1318
+ path: z14.string().default("/metrics").register(globalRegistry12, {
1664
1319
  default: "/metrics",
1665
1320
  description: "Path for the metrics scrape endpoint",
1666
1321
  title: "telemetry.metrics.scrape.path",
1667
1322
  type: "string"
1668
1323
  }),
1669
- port: z13.coerce.number().default(9464).register(globalRegistry12, {
1324
+ port: z14.coerce.number().default(9464).register(globalRegistry12, {
1670
1325
  default: 9464,
1671
1326
  description: "Port for the metrics scrape endpoint",
1672
1327
  title: "telemetry.metrics.scrape.port",
1673
1328
  type: "number"
1674
1329
  })
1675
1330
  }).describe("Metrics scrape configuration");
1676
- var MetricsConfigZod = z13.object({
1331
+ var MetricsConfigZod = z14.object({
1677
1332
  scrape: MetricsScrapeConfigZod
1678
1333
  }).describe("Metrics configuration options");
1679
- var OpenTelemetryConfigZod = z13.object({
1334
+ var OpenTelemetryConfigZod = z14.object({
1680
1335
  // OpenTelemetry options
1681
- otlpEndpoint: z13.url().optional().register(globalRegistry12, {
1336
+ otlpEndpoint: z14.url().optional().register(globalRegistry12, {
1682
1337
  description: "OTLP endpoint for exporting telemetry data",
1683
1338
  title: "telemetry.otel.otlpEndpoint",
1684
1339
  type: "string"
1685
1340
  })
1686
1341
  });
1687
- var TelemetryConfigZod = z13.object({
1342
+ var TelemetryConfigZod = z14.object({
1688
1343
  // Metrics configuration
1689
1344
  metrics: MetricsConfigZod.optional().describe("Metrics configuration"),
1690
1345
  // OpenTelemetry configuration
@@ -1692,26 +1347,26 @@ var TelemetryConfigZod = z13.object({
1692
1347
  }).describe("Telemetry configuration options");
1693
1348
 
1694
1349
  // src/config/Validation.ts
1695
- import { AddressZod as AddressZod3, asAddress as asAddress4 } from "@xylabs/sdk-js";
1350
+ import { AddressZod as AddressZod3, asAddress as asAddress2 } from "@xylabs/sdk-js";
1696
1351
  import { globalRegistry as globalRegistry13 } from "zod";
1697
- import * as z14 from "zod";
1698
- var ValidationConfigZod = z14.object({
1699
- allowedRewardRedeemers: z14.preprocess((val) => {
1352
+ import * as z15 from "zod";
1353
+ var ValidationConfigZod = z15.object({
1354
+ allowedRewardRedeemers: z15.preprocess((val) => {
1700
1355
  if (typeof val === "string") {
1701
- return val.split(",").map((s) => asAddress4(s.trim()));
1356
+ return val.split(",").map((s) => asAddress2(s.trim()));
1702
1357
  }
1703
1358
  return val;
1704
- }, z14.array(AddressZod3).optional().register(globalRegistry13, {
1359
+ }, z15.array(AddressZod3).optional().register(globalRegistry13, {
1705
1360
  description: "List of allowed reward redeemer addresses, if undefined anyone can participate",
1706
1361
  title: "allowedRewardRedeemers",
1707
1362
  type: "array"
1708
1363
  })),
1709
- allowedRewardEscrowAccountSigners: z14.preprocess((val) => {
1364
+ allowedRewardEscrowAccountSigners: z15.preprocess((val) => {
1710
1365
  if (typeof val === "string") {
1711
- return val.split(",").map((s) => asAddress4(s.trim()));
1366
+ return val.split(",").map((s) => asAddress2(s.trim()));
1712
1367
  }
1713
1368
  return val;
1714
- }, z14.array(AddressZod3).optional().register(globalRegistry13, {
1369
+ }, z15.array(AddressZod3).optional().register(globalRegistry13, {
1715
1370
  description: "List of allowed reward escrow account signer addresses, if undefined anyone can participate",
1716
1371
  title: "allowedRewardEscrowAccountSigners",
1717
1372
  type: "array"
@@ -1719,10 +1374,10 @@ var ValidationConfigZod = z14.object({
1719
1374
  });
1720
1375
 
1721
1376
  // src/config/Config.ts
1722
- var Xl1CommonConfigSchema = z15.object({
1377
+ var Xl1CommonConfigSchema = z16.object({
1723
1378
  ...LogConfigZod.shape
1724
1379
  }).describe("XL1 common configuration options");
1725
- var ConfigZod = z15.object({
1380
+ var ConfigZod = z16.object({
1726
1381
  ...Xl1CommonConfigSchema.shape,
1727
1382
  api: ApiConfigZod.default(ApiConfigZod.parse({})).describe("Configuration for the API node"),
1728
1383
  bridge: BridgeConfigZod.default(BridgeConfigZod.parse({})).describe("Configuration for the Bridge node"),
@@ -1739,35 +1394,35 @@ var ConfigZod = z15.object({
1739
1394
  var getDefaultConfig = /* @__PURE__ */ __name(() => ConfigZod.parse({}), "getDefaultConfig");
1740
1395
 
1741
1396
  // src/config/UsageMeta.ts
1742
- import * as z16 from "zod";
1743
- var DescriptionSchema = z16.string();
1744
- var TitleSchema = z16.string();
1745
- var JSONSchemaMetaSchema = z16.object({
1746
- id: z16.string().optional(),
1397
+ import * as z17 from "zod";
1398
+ var DescriptionSchema = z17.string();
1399
+ var TitleSchema = z17.string();
1400
+ var JSONSchemaMetaSchema = z17.object({
1401
+ id: z17.string().optional(),
1747
1402
  title: TitleSchema.optional(),
1748
1403
  description: DescriptionSchema.optional(),
1749
- deprecated: z16.boolean().optional()
1750
- }).catchall(z16.unknown());
1404
+ deprecated: z17.boolean().optional()
1405
+ }).catchall(z17.unknown());
1751
1406
  var GlobalMetaSchema = JSONSchemaMetaSchema.extend({});
1752
- var ChoicesSchema = z16.array(z16.union([
1753
- z16.string(),
1754
- z16.number(),
1755
- z16.literal(true),
1756
- z16.undefined()
1407
+ var ChoicesSchema = z17.array(z17.union([
1408
+ z17.string(),
1409
+ z17.number(),
1410
+ z17.literal(true),
1411
+ z17.undefined()
1757
1412
  ])).readonly();
1758
1413
  var UsageMetaSchema = GlobalMetaSchema.extend({
1759
1414
  choices: ChoicesSchema.optional(),
1760
- default: z16.unknown().optional(),
1415
+ default: z17.unknown().optional(),
1761
1416
  description: DescriptionSchema,
1762
- group: z16.string().optional(),
1763
- hidden: z16.boolean().optional(),
1417
+ group: z17.string().optional(),
1418
+ hidden: z17.boolean().optional(),
1764
1419
  title: TitleSchema,
1765
- type: z16.union([
1766
- z16.literal("array"),
1767
- z16.literal("count"),
1768
- z16.literal("boolean"),
1769
- z16.literal("number"),
1770
- z16.literal("string")
1420
+ type: z17.union([
1421
+ z17.literal("array"),
1422
+ z17.literal("count"),
1423
+ z17.literal("boolean"),
1424
+ z17.literal("number"),
1425
+ z17.literal("string")
1771
1426
  ])
1772
1427
  });
1773
1428
  function isUsageMeta(v) {
@@ -1775,116 +1430,585 @@ function isUsageMeta(v) {
1775
1430
  }
1776
1431
  __name(isUsageMeta, "isUsageMeta");
1777
1432
 
1778
- // src/constants.ts
1779
- var XL1_NETWORK_STAKING_GENESIS_PERIOD_END_EPOCH = 1760572800;
1780
- var XL1_NETWORK_STAKING_GENESIS_PERIOD_END_XL1_BLOCK = 107496;
1433
+ // src/constants.ts
1434
+ var XL1_NETWORK_STAKING_GENESIS_PERIOD_END_EPOCH = 1760572800;
1435
+ var XL1_NETWORK_STAKING_GENESIS_PERIOD_END_XL1_BLOCK = 107496;
1436
+
1437
+ // src/eip-712/Payloads/EIP712Data.ts
1438
+ import { AsObjectFactory } from "@xylabs/sdk-js";
1439
+ import { isPayloadOfZodType } from "@xyo-network/payload-model";
1440
+ import z19 from "zod";
1441
+
1442
+ // src/eip-712/Types.ts
1443
+ import z18 from "zod";
1444
+ var TypedDataDomainZod = z18.object({
1445
+ name: z18.string().nullable().optional(),
1446
+ version: z18.string().nullable().optional(),
1447
+ chainId: z18.union([
1448
+ z18.string(),
1449
+ z18.number(),
1450
+ z18.bigint()
1451
+ ]).nullable().optional(),
1452
+ verifyingContract: z18.string().nullable().optional(),
1453
+ salt: z18.union([
1454
+ z18.string(),
1455
+ z18.instanceof(Uint8Array)
1456
+ ]).nullable().optional()
1457
+ });
1458
+ var TypedDataFieldZod = z18.object({
1459
+ name: z18.string(),
1460
+ type: z18.string()
1461
+ });
1462
+ var TypedDataTypesZod = z18.record(z18.string(), z18.array(TypedDataFieldZod));
1463
+ var TypedDataValueZod = z18.record(z18.string(), z18.any());
1464
+
1465
+ // src/eip-712/Payloads/EIP712Data.ts
1466
+ var EIP712DataPayloadFieldsZod = z19.object({
1467
+ domain: TypedDataDomainZod,
1468
+ types: TypedDataTypesZod,
1469
+ values: TypedDataValueZod
1470
+ });
1471
+ var EIP712DataPayloadSchema = "network.xyo.chains.ethereum.eip712.data";
1472
+ var isEIP712DataPayload = isPayloadOfZodType(EIP712DataPayloadFieldsZod, EIP712DataPayloadSchema);
1473
+ var asEIP712DataPayload = AsObjectFactory.create(isEIP712DataPayload);
1474
+
1475
+ // src/eip-712/Payloads/EIP712Signature.ts
1476
+ import { AsObjectFactory as AsObjectFactory2, HashZod as HashZod2 } from "@xylabs/sdk-js";
1477
+ import { isPayloadOfZodType as isPayloadOfZodType2 } from "@xyo-network/payload-model";
1478
+ import z20 from "zod";
1479
+ var EIP712SignaturePayloadFieldsZod = z20.object({
1480
+ address: z20.string(),
1481
+ hash: HashZod2,
1482
+ signature: z20.string()
1483
+ });
1484
+ var EIP712SignaturePayloadSchema = "network.xyo.chains.ethereum.eip712.signature";
1485
+ var isEIP712SignaturePayload = isPayloadOfZodType2(EIP712SignaturePayloadFieldsZod, EIP712SignaturePayloadSchema);
1486
+ var asEIP712SignaturePayload = AsObjectFactory2.create(isEIP712SignaturePayload);
1487
+
1488
+ // src/eip-712/sign.ts
1489
+ import { PayloadBuilder as PayloadBuilder9 } from "@xyo-network/payload-builder";
1490
+ var signEIP712Message = /* @__PURE__ */ __name(async (signer, data) => {
1491
+ const { domain, types, values } = data;
1492
+ const signature = await signer.signTypedData(domain, types, values);
1493
+ const hash = await PayloadBuilder9.hash(data);
1494
+ const address = await signer.getAddress();
1495
+ return {
1496
+ address,
1497
+ hash,
1498
+ schema: EIP712SignaturePayloadSchema,
1499
+ signature
1500
+ };
1501
+ }, "signEIP712Message");
1502
+
1503
+ // src/eip-712/verify.ts
1504
+ import { asHash as asHash4, isUndefined as isUndefined3 } from "@xylabs/sdk-js";
1505
+ import { PayloadBuilder as PayloadBuilder10 } from "@xyo-network/payload-builder";
1506
+ import { verifyTypedData } from "ethers/hash";
1507
+ var verifyEIP712Message = /* @__PURE__ */ __name(async (data, sig) => {
1508
+ const { address, signature, hash } = sig;
1509
+ const { schema, ...fields } = data;
1510
+ const signedHash = asHash4(hash);
1511
+ if (isUndefined3(signedHash) || signedHash !== await PayloadBuilder10.hash(data)) return false;
1512
+ const recoveredAddress = verifyTypedData(fields.domain, fields.types, fields.values, signature);
1513
+ return recoveredAddress.toLowerCase() === address.toLowerCase();
1514
+ }, "verifyEIP712Message");
1515
+
1516
+ // src/multipliers.ts
1517
+ import { asAttoXL1 as asAttoXL12 } from "@xyo-network/xl1-protocol";
1518
+ var XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_EARNED_REWARDS = asAttoXL12(1343884111859145740576652n);
1519
+ var XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_BONUS_REWARDS = asAttoXL12(100000000000000000000000000n);
1520
+ var XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_REWARDS = XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_EARNED_REWARDS + XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_BONUS_REWARDS;
1521
+ var RewardMultipliers = {
1522
+ [`0|${XL1_NETWORK_STAKING_GENESIS_PERIOD_END_XL1_BLOCK}`]: [
1523
+ XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_BONUS_REWARDS,
1524
+ XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_EARNED_REWARDS
1525
+ ]
1526
+ };
1527
+
1528
+ // src/payloads/AddressPairPayload.ts
1529
+ import { AsObjectFactory as AsObjectFactory3 } from "@xylabs/sdk-js";
1530
+ import { isPayloadOfSchemaType } from "@xyo-network/payload-model";
1531
+ var AddressPairSchema = "network.xyo.address.pair";
1532
+ var isAddressPairPayload = isPayloadOfSchemaType(AddressPairSchema);
1533
+ var asAddressPairPayload = AsObjectFactory3.create(isAddressPairPayload);
1534
+ var asOptionalAddressPairPayload = AsObjectFactory3.createOptional(isAddressPairPayload);
1535
+
1536
+ // src/payloads/netBalancesForPayloads.ts
1537
+ import { hexToBigInt, toAddress as toAddress3 } from "@xylabs/sdk-js";
1538
+ import { span } from "@xylabs/telemetry";
1539
+ import { isTransfer } from "@xyo-network/xl1-protocol";
1540
+ var netBalancesForPayloads = /* @__PURE__ */ __name((payloads) => {
1541
+ return span("netBalancesForPayloads", () => {
1542
+ const balances = {};
1543
+ for (const payload of payloads) {
1544
+ if (isTransfer(payload)) {
1545
+ const { from } = payload;
1546
+ for (let [address, amount] of Object.entries(payload.transfers)) {
1547
+ balances[toAddress3(address)] = (balances[toAddress3(address)] ?? 0n) + hexToBigInt(amount);
1548
+ balances[toAddress3(from)] = (balances[toAddress3(from)] ?? 0n) - hexToBigInt(amount);
1549
+ }
1550
+ }
1551
+ }
1552
+ return balances;
1553
+ });
1554
+ }, "netBalancesForPayloads");
1555
+
1556
+ // src/payloads/netSchemasForPayloads.ts
1557
+ import { hexToBigInt as hexToBigInt2, toAddress as toAddress4 } from "@xylabs/sdk-js";
1558
+ import { span as span2 } from "@xylabs/telemetry";
1559
+ import { isTransfer as isTransfer2 } from "@xyo-network/xl1-protocol";
1560
+ var netSchemasForPayloads = /* @__PURE__ */ __name((payloads) => {
1561
+ return span2("netSchemasForPayloads", () => {
1562
+ const balances = {};
1563
+ for (const payload of payloads) {
1564
+ if (isTransfer2(payload)) {
1565
+ const { from } = payload;
1566
+ for (let [address, amount] of Object.entries(payload.transfers)) {
1567
+ balances[toAddress4(address)] = (balances[toAddress4(address)] ?? 0n) + hexToBigInt2(amount);
1568
+ balances[toAddress4(from)] = (balances[toAddress4(from)] ?? 0n) - hexToBigInt2(amount);
1569
+ }
1570
+ }
1571
+ }
1572
+ return balances;
1573
+ });
1574
+ }, "netSchemasForPayloads");
1575
+
1576
+ // src/payloads/netTransfersForPayloads.ts
1577
+ import { hexToBigInt as hexToBigInt3 } from "@xylabs/sdk-js";
1578
+ import { span as span3 } from "@xylabs/telemetry";
1579
+ import { isTransfer as isTransfer3 } from "@xyo-network/xl1-protocol";
1580
+ function netTransfersForPayloads(payloads) {
1581
+ return span3("netTransfersForPayloads", () => {
1582
+ const transfers = {};
1583
+ for (const payload of payloads) {
1584
+ if (isTransfer3(payload)) {
1585
+ const { from } = payload;
1586
+ transfers[from] = transfers[from] ?? {};
1587
+ for (let [to, amount] of Object.entries(payload.transfers)) {
1588
+ transfers[to] = transfers[to] ?? {};
1589
+ transfers[to][from] = (transfers[to][from] ?? 0n) + hexToBigInt3(amount);
1590
+ transfers[from][to] = (transfers[from][to] ?? 0n) - hexToBigInt3(amount);
1591
+ }
1592
+ }
1593
+ }
1594
+ return transfers;
1595
+ });
1596
+ }
1597
+ __name(netTransfersForPayloads, "netTransfersForPayloads");
1598
+
1599
+ // src/services/StakeIntentService/ChainIndexingServiceStateSchema.ts
1600
+ import { AsObjectFactory as AsObjectFactory4 } from "@xylabs/sdk-js";
1601
+ import { isPayloadOfSchemaType as isPayloadOfSchemaType2, isStorageMeta } from "@xyo-network/payload-model";
1602
+ var ChainIndexingServiceStateSchema = "network.xyo.chain.indexing.service.state";
1603
+ var isChainIndexingServiceState = /* @__PURE__ */ __name((payload) => {
1604
+ return isPayloadOfSchemaType2(ChainIndexingServiceStateSchema)(payload);
1605
+ }, "isChainIndexingServiceState");
1606
+ var asChainIndexingServiceState = AsObjectFactory4.create(isChainIndexingServiceState);
1607
+ var isChainIndexingServiceStateWithStorageMeta = /* @__PURE__ */ __name((value) => isChainIndexingServiceState(value) && isStorageMeta(value), "isChainIndexingServiceStateWithStorageMeta");
1608
+ var asChainIndexingServiceStateWithStorageMeta = AsObjectFactory4.create(isChainIndexingServiceStateWithStorageMeta);
1609
+
1610
+ // src/SignedBigInt.ts
1611
+ import { hexToBigInt as hexToBigInt4, toHex as toHex3 } from "@xylabs/sdk-js";
1612
+ import { isObject } from "@xylabs/sdk-js";
1613
+ var isNegativeBigInt = /* @__PURE__ */ __name((value) => {
1614
+ return isObject(value) && "negative" in value && typeof value.negative === "string";
1615
+ }, "isNegativeBigInt");
1616
+ var isPositiveBigInt = /* @__PURE__ */ __name((value) => {
1617
+ return isObject(value) && "positive" in value && typeof value.positive === "string";
1618
+ }, "isPositiveBigInt");
1619
+ var parseSignedBigInt = /* @__PURE__ */ __name((value) => {
1620
+ if (isNegativeBigInt(value)) {
1621
+ return -hexToBigInt4(value.negative);
1622
+ } else if (isPositiveBigInt(value)) {
1623
+ return hexToBigInt4(value.positive);
1624
+ } else {
1625
+ throw new Error("Invalid balance type");
1626
+ }
1627
+ }, "parseSignedBigInt");
1628
+ var toSignedBigInt = /* @__PURE__ */ __name((value) => {
1629
+ return value < 0n ? {
1630
+ negative: toHex3(-value)
1631
+ } : {
1632
+ positive: toHex3(value)
1633
+ };
1634
+ }, "toSignedBigInt");
1635
+ var toPositiveBigInt = /* @__PURE__ */ __name((value) => {
1636
+ if (isNegativeBigInt(value)) {
1637
+ return {
1638
+ positive: toHex3(0n)
1639
+ };
1640
+ }
1641
+ if (isPositiveBigInt(value)) {
1642
+ return {
1643
+ positive: value.positive
1644
+ };
1645
+ }
1646
+ if (typeof value === "bigint") {
1647
+ return {
1648
+ positive: toHex3(value)
1649
+ };
1650
+ }
1651
+ throw new Error("Invalid value for positive big int");
1652
+ }, "toPositiveBigInt");
1653
+
1654
+ // src/simple/accountBalance/SimpleAccountBalanceViewer.ts
1655
+ import { AbstractCreatable, asHash as asHash5, assertEx as assertEx13, exists, isDefined as isDefined11 } from "@xylabs/sdk-js";
1656
+ import { spanRootAsync as spanRootAsync4 } from "@xylabs/telemetry";
1657
+ import { asRange, asXL1BlockNumber as asXL1BlockNumber5, asXL1BlockRange as asXL1BlockRange5, AttoXL1 as AttoXL12, StepSizes as StepSizes9, TransferSchema } from "@xyo-network/xl1-protocol";
1781
1658
 
1782
- // src/eip-712/Payloads/EIP712Data.ts
1659
+ // src/summary/model/BalancesStepSummary.ts
1783
1660
  import { AsObjectFactory as AsObjectFactory5 } from "@xylabs/sdk-js";
1784
- import { isPayloadOfZodType } from "@xyo-network/payload-model";
1785
- import z18 from "zod";
1786
-
1787
- // src/eip-712/Types.ts
1788
- import z17 from "zod";
1789
- var TypedDataDomainZod = z17.object({
1790
- name: z17.string().nullable().optional(),
1791
- version: z17.string().nullable().optional(),
1792
- chainId: z17.union([
1793
- z17.string(),
1794
- z17.number(),
1795
- z17.bigint()
1796
- ]).nullable().optional(),
1797
- verifyingContract: z17.string().nullable().optional(),
1798
- salt: z17.union([
1799
- z17.string(),
1800
- z17.instanceof(Uint8Array)
1801
- ]).nullable().optional()
1802
- });
1803
- var TypedDataFieldZod = z17.object({
1804
- name: z17.string(),
1805
- type: z17.string()
1806
- });
1807
- var TypedDataTypesZod = z17.record(z17.string(), z17.array(TypedDataFieldZod));
1808
- var TypedDataValueZod = z17.record(z17.string(), z17.any());
1661
+ import { isPayloadOfSchemaType as isPayloadOfSchemaType3, isStorageMeta as isStorageMeta2 } from "@xyo-network/payload-model";
1662
+ var BalancesStepSummarySchema = "network.xyo.step.summary.balances";
1663
+ var isBalancesStepSummary = isPayloadOfSchemaType3(BalancesStepSummarySchema);
1664
+ var asBalancesStepSummary = AsObjectFactory5.create(isBalancesStepSummary);
1665
+ var isBalancesStepSummaryWithStorageMeta = /* @__PURE__ */ __name((value) => {
1666
+ return isBalancesStepSummary(value) && isStorageMeta2(value);
1667
+ }, "isBalancesStepSummaryWithStorageMeta");
1668
+ var asBalancesStepSummaryWithStorageMeta = AsObjectFactory5.create(isBalancesStepSummaryWithStorageMeta);
1809
1669
 
1810
- // src/eip-712/Payloads/EIP712Data.ts
1811
- var EIP712DataPayloadFieldsZod = z18.object({
1812
- domain: TypedDataDomainZod,
1813
- types: TypedDataTypesZod,
1814
- values: TypedDataValueZod
1815
- });
1816
- var EIP712DataPayloadSchema = "network.xyo.chains.ethereum.eip712.data";
1817
- var isEIP712DataPayload = isPayloadOfZodType(EIP712DataPayloadFieldsZod, EIP712DataPayloadSchema);
1818
- var asEIP712DataPayload = AsObjectFactory5.create(isEIP712DataPayload);
1670
+ // src/summary/model/SchemasStepSummary.ts
1671
+ import { AsObjectFactory as AsObjectFactory6 } from "@xylabs/sdk-js";
1672
+ import { isPayloadOfSchemaType as isPayloadOfSchemaType4, isStorageMeta as isStorageMeta3 } from "@xyo-network/payload-model";
1673
+ var SchemasStepSummarySchema = "network.xyo.step.summary.schemas";
1674
+ var isSchemasStepSummary = isPayloadOfSchemaType4(SchemasStepSummarySchema);
1675
+ var asSchemasStepSummary = AsObjectFactory6.create(isSchemasStepSummary);
1676
+ var isSchemasStepSummaryWithStorageMeta = /* @__PURE__ */ __name((value) => {
1677
+ return isSchemasStepSummary(value) && isStorageMeta3(value);
1678
+ }, "isSchemasStepSummaryWithStorageMeta");
1679
+ var asSchemasStepSummaryWithStorageMeta = AsObjectFactory6.create(isSchemasStepSummaryWithStorageMeta);
1819
1680
 
1820
- // src/eip-712/Payloads/EIP712Signature.ts
1821
- import { AsObjectFactory as AsObjectFactory6, HashZod } from "@xylabs/sdk-js";
1822
- import { isPayloadOfZodType as isPayloadOfZodType2 } from "@xyo-network/payload-model";
1823
- import z19 from "zod";
1824
- var EIP712SignaturePayloadFieldsZod = z19.object({
1825
- address: z19.string(),
1826
- hash: HashZod,
1827
- signature: z19.string()
1828
- });
1829
- var EIP712SignaturePayloadSchema = "network.xyo.chains.ethereum.eip712.signature";
1830
- var isEIP712SignaturePayload = isPayloadOfZodType2(EIP712SignaturePayloadFieldsZod, EIP712SignaturePayloadSchema);
1831
- var asEIP712SignaturePayload = AsObjectFactory6.create(isEIP712SignaturePayload);
1681
+ // src/summary/model/StepSummary.ts
1682
+ var StepSummarySchema = "network.xyo.step.summary";
1832
1683
 
1833
- // src/eip-712/sign.ts
1834
- import { PayloadBuilder as PayloadBuilder10 } from "@xyo-network/payload-builder";
1835
- var signEIP712Message = /* @__PURE__ */ __name(async (signer, data) => {
1836
- const { domain, types, values } = data;
1837
- const signature = await signer.signTypedData(domain, types, values);
1838
- const hash = await PayloadBuilder10.hash(data);
1839
- const address = await signer.getAddress();
1840
- return {
1841
- address,
1842
- hash,
1843
- schema: EIP712SignaturePayloadSchema,
1844
- signature
1845
- };
1846
- }, "signEIP712Message");
1684
+ // src/summary/model/TransfersSummary.ts
1685
+ import { AsObjectFactory as AsObjectFactory7 } from "@xylabs/sdk-js";
1686
+ import { isPayloadOfSchemaType as isPayloadOfSchemaType5, isStorageMeta as isStorageMeta4 } from "@xyo-network/payload-model";
1687
+ var TransfersStepSummarySchema = "network.xyo.step.summary.transfer";
1688
+ var isTransfersStepSummary = isPayloadOfSchemaType5(TransfersStepSummarySchema);
1689
+ var asTransfersStepSummary = AsObjectFactory7.create(isTransfersStepSummary);
1690
+ var isTransfersStepSummaryWithStorageMeta = /* @__PURE__ */ __name((value) => {
1691
+ return isTransfersStepSummary(value) && isStorageMeta4(value);
1692
+ }, "isTransfersStepSummaryWithStorageMeta");
1693
+ var asTransfersStepSummaryWithStorageMeta = AsObjectFactory7.create(isTransfersStepSummaryWithStorageMeta);
1847
1694
 
1848
- // src/eip-712/verify.ts
1849
- import { asHash as asHash4, isUndefined as isUndefined3 } from "@xylabs/sdk-js";
1695
+ // src/summary/primitives/balances/balancesStepSummaryFromRange.ts
1696
+ import { assertEx as assertEx10 } from "@xylabs/sdk-js";
1850
1697
  import { PayloadBuilder as PayloadBuilder11 } from "@xyo-network/payload-builder";
1851
- import { verifyTypedData } from "ethers/hash";
1852
- var verifyEIP712Message = /* @__PURE__ */ __name(async (data, sig) => {
1853
- const { address, signature, hash } = sig;
1854
- const { schema, ...fields } = data;
1855
- const signedHash = asHash4(hash);
1856
- if (isUndefined3(signedHash) || signedHash !== await PayloadBuilder11.hash(data)) return false;
1857
- const recoveredAddress = verifyTypedData(fields.domain, fields.types, fields.values, signature);
1858
- return recoveredAddress.toLowerCase() === address.toLowerCase();
1859
- }, "verifyEIP712Message");
1698
+ import { isAnyPayload } from "@xyo-network/payload-model";
1699
+ import { StepSizes as StepSizes6 } from "@xyo-network/xl1-protocol";
1700
+ async function balancesStepSummaryFromRange(context, range) {
1701
+ const frameHeadHash = await hashFromBlockNumber(context, range[1]);
1702
+ const frameSize = range[1] - range[0] + 1;
1703
+ const [headHash] = await context.head();
1704
+ let result = void 0;
1705
+ if (frameSize === 1) {
1706
+ const hash = await hashFromBlockNumber(context, range[0]);
1707
+ const [, payloads] = await hydrateBlock(context.store, hash);
1708
+ const balances = {};
1709
+ for (const [address, balance] of Object.entries(netBalancesForPayloads(payloads))) {
1710
+ balances[address] = toSignedBigInt(balance);
1711
+ }
1712
+ result = {
1713
+ schema: BalancesStepSummarySchema,
1714
+ hash: headHash,
1715
+ stepSize: -1,
1716
+ balances
1717
+ };
1718
+ } else {
1719
+ const step = StepSizes6.indexOf(frameSize);
1720
+ assertEx10(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes6.join(", ")}`);
1721
+ const summaryResult = await context.summaryMap.get(`${frameHeadHash}|${frameSize}`);
1722
+ if (isAnyPayload(summaryResult)) {
1723
+ result = summaryResult;
1724
+ } else {
1725
+ await context.stepSemaphores[step].acquire();
1726
+ try {
1727
+ const subRanges = deepCalculateFramesFromRange(range, step - 1);
1728
+ const promises = subRanges.map((subRange) => balancesStepSummaryFromRange(context, subRange));
1729
+ const subResults = await Promise.all(promises);
1730
+ const bigIntBalances = {};
1731
+ for (const subResult of subResults) {
1732
+ for (const [address, balance] of Object.entries(subResult.balances)) {
1733
+ bigIntBalances[address] = (bigIntBalances[address] ?? 0n) + parseSignedBigInt(balance);
1734
+ }
1735
+ }
1736
+ const balances = {};
1737
+ for (const [address, balance] of Object.entries(bigIntBalances)) {
1738
+ balances[address] = toSignedBigInt(balance);
1739
+ }
1740
+ result = {
1741
+ schema: BalancesStepSummarySchema,
1742
+ hash: frameHeadHash,
1743
+ stepSize: frameSize,
1744
+ balances
1745
+ };
1746
+ await context.summaryMap.set(`${frameHeadHash}|${frameSize}`, result);
1747
+ } finally {
1748
+ context.stepSemaphores[step].release();
1749
+ }
1750
+ }
1751
+ }
1752
+ const finalResult = await PayloadBuilder11.addStorageMeta(result);
1753
+ return finalResult;
1754
+ }
1755
+ __name(balancesStepSummaryFromRange, "balancesStepSummaryFromRange");
1860
1756
 
1861
- // src/multipliers.ts
1862
- import { asAttoXL1 } from "@xyo-network/xl1-protocol";
1863
- var XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_EARNED_REWARDS = asAttoXL1(1343884111859145740576652n);
1864
- var XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_BONUS_REWARDS = asAttoXL1(100000000000000000000000000n);
1865
- var XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_REWARDS = XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_EARNED_REWARDS + XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_BONUS_REWARDS;
1866
- var RewardMultipliers = {
1867
- [`0|${XL1_NETWORK_STAKING_GENESIS_PERIOD_END_XL1_BLOCK}`]: [
1868
- XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_BONUS_REWARDS,
1869
- XL1_NETWORK_STAKING_GENESIS_PERIOD_TOTAL_EARNED_REWARDS
1870
- ]
1871
- };
1757
+ // src/summary/primitives/balances/balancesSummary.ts
1758
+ import { asAddress as asAddress3, isDefined as isDefined8 } from "@xylabs/sdk-js";
1759
+ import { spanRootAsync } from "@xylabs/telemetry";
1760
+ import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta2, asXL1BlockNumber as asXL1BlockNumber2, asXL1BlockRange as asXL1BlockRange2 } from "@xyo-network/xl1-protocol";
1761
+ async function balancesSummary(context) {
1762
+ return await spanRootAsync("balancesSummary", async () => {
1763
+ const [headHash] = await context.head();
1764
+ const headResult = await context.store.chainMap.get(headHash);
1765
+ const headBoundWitness = asBlockBoundWitnessWithStorageMeta2(headResult, () => `Head block not found for hash: ${headHash}`);
1766
+ const rangeStart = asXL1BlockNumber2(isDefined8(context.windowSize) ? Math.max(headBoundWitness.block - context.windowSize + 1, 0) : 0, true);
1767
+ const ranges = deepCalculateFramesFromRange(asXL1BlockRange2([
1768
+ rangeStart,
1769
+ headBoundWitness.block
1770
+ ], {
1771
+ name: "balancesSummary"
1772
+ }));
1773
+ const summaries = await Promise.all(ranges.map((range) => balancesStepSummaryFromRange(context, range)));
1774
+ const balances = {};
1775
+ for (let summary of summaries) {
1776
+ for (const [address, balance] of Object.entries(summary.balances)) {
1777
+ const validAddress = asAddress3(address, () => `Invalid address: ${address}`);
1778
+ balances[validAddress] = (balances[validAddress] ?? 0n) + parseSignedBigInt(balance);
1779
+ }
1780
+ }
1781
+ return [
1782
+ balances,
1783
+ [
1784
+ rangeStart,
1785
+ headBoundWitness.block
1786
+ ],
1787
+ headHash
1788
+ ];
1789
+ });
1790
+ }
1791
+ __name(balancesSummary, "balancesSummary");
1792
+
1793
+ // src/summary/primitives/schemas/schemasStepSummaryFromRange.ts
1794
+ import { assertEx as assertEx11 } from "@xylabs/sdk-js";
1795
+ import { isBoundWitness } from "@xyo-network/boundwitness-model";
1796
+ import { PayloadBuilder as PayloadBuilder12 } from "@xyo-network/payload-builder";
1797
+ import { isAnyPayload as isAnyPayload2, isHashMeta } from "@xyo-network/payload-model";
1798
+ import { StepSizes as StepSizes7 } from "@xyo-network/xl1-protocol";
1799
+ async function schemasStepSummaryFromRange(context, range) {
1800
+ const frameHeadHash = await hashFromBlockNumber(context, range[1]);
1801
+ const frameSize = range[1] - range[0] + 1;
1802
+ const [headHash] = await context.head();
1803
+ let result = void 0;
1804
+ if (frameSize === 1) {
1805
+ const hash = await hashFromBlockNumber(context, range[0]);
1806
+ const [block, payloads] = await hydrateBlock(context.store, hash);
1807
+ const boundWitnesses = [
1808
+ block,
1809
+ ...payloads.filter((x) => isBoundWitness(x) && isHashMeta(x))
1810
+ ];
1811
+ const schemas = {};
1812
+ for (const bw of boundWitnesses) {
1813
+ schemas[bw.schema] = (schemas[bw.schema] ?? 0) + 1;
1814
+ for (const schema of bw.payload_schemas) {
1815
+ schemas[schema] = (schemas[schema] ?? 0) + 1;
1816
+ }
1817
+ }
1818
+ result = {
1819
+ schema: SchemasStepSummarySchema,
1820
+ hash: headHash,
1821
+ stepSize: -1,
1822
+ schemas
1823
+ };
1824
+ } else {
1825
+ const step = StepSizes7.indexOf(frameSize);
1826
+ assertEx11(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes7.join(", ")}`);
1827
+ const summaryResult = await context.summaryMap.get(`${frameHeadHash}|${frameSize}`);
1828
+ if (isAnyPayload2(summaryResult)) {
1829
+ result = summaryResult;
1830
+ } else {
1831
+ await context.stepSemaphores[step].acquire();
1832
+ try {
1833
+ const subRanges = deepCalculateFramesFromRange(range, step - 1);
1834
+ const promises = subRanges.map((subRange) => schemasStepSummaryFromRange(context, subRange));
1835
+ const subResults = await Promise.all(promises);
1836
+ const schemas = {};
1837
+ for (const subResult of subResults) {
1838
+ for (const [schema, count] of Object.entries(subResult.schemas)) {
1839
+ schemas[schema] = (schemas[schema] ?? 0) + count;
1840
+ }
1841
+ }
1842
+ result = {
1843
+ schema: SchemasStepSummarySchema,
1844
+ hash: frameHeadHash,
1845
+ stepSize: frameSize,
1846
+ schemas
1847
+ };
1848
+ await context.summaryMap.set(`${frameHeadHash}|${frameSize}`, result);
1849
+ } finally {
1850
+ context.stepSemaphores[step].release();
1851
+ }
1852
+ }
1853
+ }
1854
+ return await PayloadBuilder12.addHashMeta(result);
1855
+ }
1856
+ __name(schemasStepSummaryFromRange, "schemasStepSummaryFromRange");
1857
+
1858
+ // src/summary/primitives/schemas/schemasSummary.ts
1859
+ import { isDefined as isDefined9 } from "@xylabs/sdk-js";
1860
+ import { spanRootAsync as spanRootAsync2 } from "@xylabs/telemetry";
1861
+ import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta3, asXL1BlockNumber as asXL1BlockNumber3, asXL1BlockRange as asXL1BlockRange3 } from "@xyo-network/xl1-protocol";
1862
+ async function schemasSummary(context) {
1863
+ return await spanRootAsync2("schemasSummary", async () => {
1864
+ const [headHash] = await context.head();
1865
+ const headResult = await context.store.chainMap.get(headHash);
1866
+ const headBoundWitness = asBlockBoundWitnessWithStorageMeta3(headResult, () => `Head block not found for hash: ${headHash}`);
1867
+ const rangeStart = asXL1BlockNumber3(isDefined9(context.windowSize) ? Math.max(headBoundWitness.block - context.windowSize + 1, 0) : 0, true);
1868
+ const ranges = deepCalculateFramesFromRange(asXL1BlockRange3([
1869
+ rangeStart,
1870
+ headBoundWitness.block
1871
+ ], {
1872
+ name: "schemasSummary"
1873
+ }));
1874
+ const summaries = await Promise.all(ranges.map((range) => schemasStepSummaryFromRange(context, range)));
1875
+ const results = {};
1876
+ for (let summary of summaries) {
1877
+ for (const [schema, count] of Object.entries(summary.schemas)) {
1878
+ results[schema] = (results[schema] ?? 0) + count;
1879
+ }
1880
+ }
1881
+ return [
1882
+ results,
1883
+ [
1884
+ rangeStart,
1885
+ headBoundWitness.block
1886
+ ],
1887
+ headHash
1888
+ ];
1889
+ });
1890
+ }
1891
+ __name(schemasSummary, "schemasSummary");
1892
+
1893
+ // src/summary/primitives/transfers/transfersStepSummaryFromRange.ts
1894
+ import { assertEx as assertEx12 } from "@xylabs/sdk-js";
1895
+ import { PayloadBuilder as PayloadBuilder13 } from "@xyo-network/payload-builder";
1896
+ import { isAnyPayload as isAnyPayload3 } from "@xyo-network/payload-model";
1897
+ import { StepSizes as StepSizes8 } from "@xyo-network/xl1-protocol";
1898
+
1899
+ // src/summary/primitives/transfers/transfersSummary.ts
1900
+ import { asAddress as asAddress4, isDefined as isDefined10 } from "@xylabs/sdk-js";
1901
+ import { spanRootAsync as spanRootAsync3 } from "@xylabs/telemetry";
1902
+ import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta4, asXL1BlockNumber as asXL1BlockNumber4, asXL1BlockRange as asXL1BlockRange4 } from "@xyo-network/xl1-protocol";
1903
+ async function transfersSummary(transferContext) {
1904
+ return await spanRootAsync3("transferSummary", async () => {
1905
+ const [headHash] = await transferContext.head();
1906
+ const headResult = await transferContext.store.chainMap.get(headHash);
1907
+ const headBoundWitness = asBlockBoundWitnessWithStorageMeta4(headResult, () => `Head block not found for hash: ${transferContext.head}`);
1908
+ const rangeStart = asXL1BlockNumber4(isDefined10(transferContext.windowSize) ? Math.max(headBoundWitness.block - transferContext.windowSize + 1, 0) : 0, true);
1909
+ const ranges = deepCalculateFramesFromRange(asXL1BlockRange4([
1910
+ rangeStart,
1911
+ headBoundWitness.block
1912
+ ], {
1913
+ name: "transfersSummary"
1914
+ }));
1915
+ const summaries = await Promise.all(ranges.map((range) => transfersStepSummaryFromRange(transferContext, range)));
1916
+ const transfers = {};
1917
+ for (let summary of summaries) {
1918
+ for (const [from, toMap] of Object.entries(summary.transfers)) {
1919
+ const validFrom = asAddress4(from, () => `Invalid address: ${from}`);
1920
+ transfers[validFrom] = transfers[validFrom] ?? {};
1921
+ for (const [to, transfer] of Object.entries(toMap)) {
1922
+ const validTo = asAddress4(to, () => `Invalid address: ${to}`);
1923
+ transfers[validFrom][validTo] = (transfers[validFrom][validTo] ?? 0n) + parseSignedBigInt(transfer);
1924
+ }
1925
+ }
1926
+ }
1927
+ return [
1928
+ transfers,
1929
+ [
1930
+ rangeStart,
1931
+ headBoundWitness.block
1932
+ ],
1933
+ headHash
1934
+ ];
1935
+ });
1936
+ }
1937
+ __name(transfersSummary, "transfersSummary");
1938
+ function transfersSummaryKey(frameHeadHash, frameSize) {
1939
+ return `${frameHeadHash}|${frameSize}`;
1940
+ }
1941
+ __name(transfersSummaryKey, "transfersSummaryKey");
1872
1942
 
1873
- // src/services/StakeIntentService/ChainIndexingServiceStateSchema.ts
1874
- import { AsObjectFactory as AsObjectFactory7 } from "@xylabs/sdk-js";
1875
- import { isPayloadOfSchemaType as isPayloadOfSchemaType5, isStorageMeta as isStorageMeta4 } from "@xyo-network/payload-model";
1876
- var ChainIndexingServiceStateSchema = "network.xyo.chain.indexing.service.state";
1877
- var isChainIndexingServiceState = /* @__PURE__ */ __name((payload) => {
1878
- return isPayloadOfSchemaType5(ChainIndexingServiceStateSchema)(payload);
1879
- }, "isChainIndexingServiceState");
1880
- var asChainIndexingServiceState = AsObjectFactory7.create(isChainIndexingServiceState);
1881
- var isChainIndexingServiceStateWithStorageMeta = /* @__PURE__ */ __name((value) => isChainIndexingServiceState(value) && isStorageMeta4(value), "isChainIndexingServiceStateWithStorageMeta");
1882
- var asChainIndexingServiceStateWithStorageMeta = AsObjectFactory7.create(isChainIndexingServiceStateWithStorageMeta);
1943
+ // src/summary/primitives/transfers/transfersStepSummaryFromRange.ts
1944
+ async function transfersStepSummaryFromRange(context, range) {
1945
+ const frameHeadHash = await hashFromBlockNumber(context, range[1]);
1946
+ const frameSize = range[1] - range[0] + 1;
1947
+ const [headHash] = await context.head();
1948
+ let result = void 0;
1949
+ if (frameSize === 1) {
1950
+ const hash = await hashFromBlockNumber(context, range[0]);
1951
+ const [, payloads] = await hydrateBlock(context.store, hash);
1952
+ const transfers = {};
1953
+ for (const [from, toMap] of Object.entries(netTransfersForPayloads(payloads))) {
1954
+ transfers[from] = transfers[from] ?? {};
1955
+ for (const [to, amount] of Object.entries(toMap)) {
1956
+ transfers[from][to] = toSignedBigInt(amount);
1957
+ }
1958
+ }
1959
+ result = {
1960
+ schema: TransfersStepSummarySchema,
1961
+ hash: headHash,
1962
+ stepSize: -1,
1963
+ transfers
1964
+ };
1965
+ } else {
1966
+ const step = StepSizes8.indexOf(frameSize);
1967
+ assertEx12(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes8.join(", ")}`);
1968
+ const key = transfersSummaryKey(frameHeadHash, frameSize);
1969
+ const summaryResult = await context.summaryMap.get(key);
1970
+ if (isAnyPayload3(summaryResult)) {
1971
+ result = summaryResult;
1972
+ } else {
1973
+ await context.stepSemaphores[step].acquire();
1974
+ try {
1975
+ const subRanges = deepCalculateFramesFromRange(range, step - 1);
1976
+ const promises = subRanges.map((subRange) => transfersStepSummaryFromRange(context, subRange));
1977
+ const subResults = await Promise.all(promises);
1978
+ const bigIntBalances = {};
1979
+ for (const subResult of subResults) {
1980
+ for (const [from, toMap] of Object.entries(subResult.transfers)) {
1981
+ bigIntBalances[from] = bigIntBalances[from] ?? {};
1982
+ for (const [to, transfer] of Object.entries(toMap)) {
1983
+ bigIntBalances[from][to] = (bigIntBalances[from][to] ?? 0n) + parseSignedBigInt(transfer);
1984
+ }
1985
+ }
1986
+ }
1987
+ const transfers = {};
1988
+ for (const [from, toMap] of Object.entries(bigIntBalances)) {
1989
+ transfers[from] = transfers[from] ?? {};
1990
+ for (const [to, transfer] of Object.entries(toMap)) {
1991
+ transfers[from][to] = toSignedBigInt(transfer);
1992
+ }
1993
+ }
1994
+ result = {
1995
+ schema: TransfersStepSummarySchema,
1996
+ hash: frameHeadHash,
1997
+ stepSize: frameSize,
1998
+ transfers
1999
+ };
2000
+ await context.summaryMap.set(key, result);
2001
+ } finally {
2002
+ context.stepSemaphores[step].release();
2003
+ }
2004
+ }
2005
+ }
2006
+ const finalResult = await PayloadBuilder13.addStorageMeta(result);
2007
+ return finalResult;
2008
+ }
2009
+ __name(transfersStepSummaryFromRange, "transfersStepSummaryFromRange");
1883
2010
 
1884
2011
  // src/simple/accountBalance/SimpleAccountBalanceViewer.ts
1885
- import { AbstractCreatable, assertEx as assertEx12, exists, isDefined as isDefined11 } from "@xylabs/sdk-js";
1886
- import { spanRootAsync as spanRootAsync4 } from "@xylabs/telemetry";
1887
- import { asRange, asXL1BlockNumber as asXL1BlockNumber5, asXL1BlockRange as asXL1BlockRange5, AttoXL1 as AttoXL12, StepSizes as StepSizes9, TransferSchema } from "@xyo-network/xl1-protocol";
1888
2012
  var SimpleAccountBalanceViewer = class extends AbstractCreatable {
1889
2013
  static {
1890
2014
  __name(this, "SimpleAccountBalanceViewer");
@@ -1895,23 +2019,26 @@ var SimpleAccountBalanceViewer = class extends AbstractCreatable {
1895
2019
  get context() {
1896
2020
  return this.params.context;
1897
2021
  }
1898
- get transferContext() {
1899
- return this.params.transferContext;
2022
+ get transfersSummaryContext() {
2023
+ return this.params.transfersSummaryContext;
1900
2024
  }
1901
2025
  static async paramsHandler(params) {
1902
- assertEx12(params.blockViewer, () => "blockViewer is required");
1903
- assertEx12(params.context, () => "context is required");
1904
- assertEx12(params.transferContext, () => "transferContext is required");
2026
+ assertEx13(params.blockViewer, () => "blockViewer is required");
2027
+ assertEx13(params.context, () => "context is required");
2028
+ assertEx13(params.transfersSummaryContext, () => "transfersSummaryContext is required");
1905
2029
  return {
1906
2030
  ...await super.paramsHandler(params)
1907
2031
  };
1908
2032
  }
1909
2033
  async accountBalance(address, headOrRange) {
1910
- const balances = await this.accountsBalances([
2034
+ const balances = await this.accountBalances([
1911
2035
  address
1912
2036
  ], headOrRange);
1913
2037
  return balances[address] ?? AttoXL12(0n);
1914
2038
  }
2039
+ accountBalanceHistories(_addresses, _rangeOrHash) {
2040
+ throw new Error("Method [accountBalanceHistories] not implemented.");
2041
+ }
1915
2042
  async accountBalanceHistory(address, headOrRange) {
1916
2043
  const range = asRange(headOrRange);
1917
2044
  const startingRange = asXL1BlockRange5(range ?? [
@@ -1925,7 +2052,7 @@ var SimpleAccountBalanceViewer = class extends AbstractCreatable {
1925
2052
  const transferIndexes = block[0].payload_schemas.map((schema, index) => schema === TransferSchema ? index : void 0).filter(exists);
1926
2053
  const transfers = transferIndexes.map((index) => {
1927
2054
  const hash = block[0].payload_hashes[index];
1928
- return assertEx12(block[1].find((p) => p._hash === hash), () => `Error: Could not find Transfer with hash ${hash} in block ${block[0]._hash}`);
2055
+ return assertEx13(block[1].find((p) => p._hash === hash), () => `Error: Could not find Transfer with hash ${hash} in block ${block[0]._hash}`);
1929
2056
  }).filter(exists).filter((t) => t.from === address || isDefined11(t.transfers[address]));
1930
2057
  if (transfers.length === 0) {
1931
2058
  continue;
@@ -1944,20 +2071,53 @@ var SimpleAccountBalanceViewer = class extends AbstractCreatable {
1944
2071
  }
1945
2072
  return result;
1946
2073
  }
1947
- async accountsBalances(address, _headOrRange) {
1948
- return await spanRootAsync4("balances", async () => {
1949
- const summary = await balancesSummary(this.context);
2074
+ async accountBalances(address, _headOrRange) {
2075
+ const [result] = await this.qualifiedAccountBalances(address, _headOrRange);
2076
+ return result;
2077
+ }
2078
+ async qualifiedAccountBalanceHistories(addresses, headOrRange) {
2079
+ const head = asHash5(headOrRange) ?? await this.blockViewer.currentBlockHash();
2080
+ const range = asXL1BlockRange5(headOrRange) ?? asXL1BlockRange5([
2081
+ 0,
2082
+ assertEx13(await this.blockViewer.blockByHash(head), () => `Error: Could not find block with hash ${head}`)[0].block
2083
+ ]);
2084
+ const qualifiedEntries = await Promise.all(addresses.map(async (address) => [
2085
+ address,
2086
+ await this.qualifiedAccountBalanceHistory(address, range)
2087
+ ]));
2088
+ const entries = qualifiedEntries.map(([address, [history]]) => {
2089
+ return [
2090
+ address,
2091
+ history
2092
+ ];
2093
+ });
2094
+ const qualifiedRange = qualifiedEntries[0][1][1];
2095
+ const qualifiedHeadHash = qualifiedEntries[0][1][2];
2096
+ for (const [_, [__, range2, headHash]] of qualifiedEntries) {
2097
+ assertEx13(range2[0] === qualifiedRange[0] && range2[1] === qualifiedRange[1], () => "Inconsistent ranges in qualifiedAccountBalanceHistories");
2098
+ assertEx13(headHash === qualifiedHeadHash, () => "Inconsistent head hashes in qualifiedAccountBalanceHistories");
2099
+ }
2100
+ return [
2101
+ Object.fromEntries(entries),
2102
+ qualifiedRange,
2103
+ qualifiedHeadHash
2104
+ ];
2105
+ }
2106
+ async qualifiedAccountBalances(address, _headOrRange) {
2107
+ return await spanRootAsync4("qualifiedAccountsBalances", async () => {
2108
+ const qualifiedSummary = await balancesSummary(this.context);
1950
2109
  const result = {};
1951
2110
  for (const addr of address) {
1952
- const summaryBalance = summary[addr] ?? 0n;
2111
+ const summaryBalance = qualifiedSummary[0][addr] ?? 0n;
1953
2112
  result[addr] = AttoXL12(summaryBalance < 0n ? 0n : summaryBalance);
1954
2113
  }
1955
- return result;
2114
+ return [
2115
+ result,
2116
+ qualifiedSummary[1],
2117
+ qualifiedSummary[2]
2118
+ ];
1956
2119
  });
1957
2120
  }
1958
- accountsBalancesHistory(_addresses, _rangeOrHash) {
1959
- throw new Error("Method not implemented.");
1960
- }
1961
2121
  async distillTransferHistory(address, range, max = 50) {
1962
2122
  if (range[1] - range[0] <= StepSizes9[0] || max <= 1) {
1963
2123
  return Array.from({
@@ -1968,7 +2128,7 @@ var SimpleAccountBalanceViewer = class extends AbstractCreatable {
1968
2128
  const transferSummaryPairs = await Promise.all(frames.map(async (frame) => {
1969
2129
  return [
1970
2130
  frame,
1971
- await transfersStepSummaryFromRange(this.transferContext, frame)
2131
+ await transfersStepSummaryFromRange(this.transfersSummaryContext, frame)
1972
2132
  ];
1973
2133
  }));
1974
2134
  const filteredTransferSummaryPairs = transferSummaryPairs.filter(([_, summary]) => Object.keys(summary.transfers).includes(address));
@@ -1999,23 +2159,263 @@ var SimpleAccountBalanceViewer = class extends AbstractCreatable {
1999
2159
  ...resultBlockNumbers
2000
2160
  ].toSorted((a, b) => b - a).slice(0, max);
2001
2161
  }
2162
+ async qualifiedAccountBalanceHistory(address, headOrRange) {
2163
+ const range = asRange(headOrRange);
2164
+ const headHash = asHash5(headOrRange);
2165
+ const [head] = assertEx13(isDefined11(headHash) ? await this.blockViewer.blockByHash(headHash) : await this.blockViewer.currentBlock(), () => "Could not resolve head block");
2166
+ const startingRange = asXL1BlockRange5(range ?? [
2167
+ 0,
2168
+ head.block
2169
+ ], true);
2170
+ const blockNumbers = await this.distillTransferHistory(address, startingRange);
2171
+ const blocks = (await Promise.all(blockNumbers.map(async (bn) => await this.blockViewer.blockByNumber(bn)))).filter(exists);
2172
+ const result = [];
2173
+ for (const block of blocks) {
2174
+ const transferIndexes = block[0].payload_schemas.map((schema, index) => schema === TransferSchema ? index : void 0).filter(exists);
2175
+ const transfers = transferIndexes.map((index) => {
2176
+ const hash = block[0].payload_hashes[index];
2177
+ return assertEx13(block[1].find((p) => p._hash === hash), () => `Error: Could not find Transfer with hash ${hash} in block ${block[0]._hash}`);
2178
+ }).filter(exists).filter((t) => t.from === address || isDefined11(t.transfers[address]));
2179
+ if (transfers.length === 0) {
2180
+ continue;
2181
+ }
2182
+ const pairs = transfers.map((transfer) => {
2183
+ return [
2184
+ block[0],
2185
+ transfer
2186
+ ];
2187
+ });
2188
+ result.push(...pairs.map(([block2, transfer]) => [
2189
+ block2,
2190
+ null,
2191
+ transfer
2192
+ ]));
2193
+ }
2194
+ return [
2195
+ result,
2196
+ startingRange,
2197
+ head._hash
2198
+ ];
2199
+ }
2200
+ };
2201
+
2202
+ // src/simple/block/SimpleBlockViewer.ts
2203
+ import { AbstractCreatable as AbstractCreatable2, assertEx as assertEx14, exists as exists2, isDefined as isDefined12, spanRootAsync as spanRootAsync5 } from "@xylabs/sdk-js";
2204
+ import { asSignedHydratedBlockWithHashMeta, asXL1BlockNumber as asXL1BlockNumber6 } from "@xyo-network/xl1-protocol";
2205
+
2206
+ // src/utils/HydratedCache.ts
2207
+ import { LRUCache as LRUCache2 } from "lru-cache";
2208
+ var HydratedCache = class {
2209
+ static {
2210
+ __name(this, "HydratedCache");
2211
+ }
2212
+ cache;
2213
+ chainMap;
2214
+ hydrateFunction;
2215
+ constructor(chainMap, hydrateFunction, maxSize = 200) {
2216
+ this.chainMap = chainMap;
2217
+ this.hydrateFunction = hydrateFunction;
2218
+ this.cache = new LRUCache2({
2219
+ max: maxSize
2220
+ });
2221
+ }
2222
+ async get(hash) {
2223
+ const existing = this.cache.get(hash);
2224
+ if (existing !== void 0) return existing;
2225
+ const block = await this.hydrateFunction({
2226
+ chainMap: this.chainMap
2227
+ }, hash) ?? null;
2228
+ if (block !== null) this.cache.set(hash, block);
2229
+ return block;
2230
+ }
2231
+ has(hash) {
2232
+ return this.cache.has(hash);
2233
+ }
2234
+ };
2235
+
2236
+ // src/utils/isZodError.ts
2237
+ import * as z21 from "zod";
2238
+ var isZodError = /* @__PURE__ */ __name((error) => {
2239
+ return error instanceof z21.ZodError;
2240
+ }, "isZodError");
2241
+ var prettifyZodError = /* @__PURE__ */ __name((error) => {
2242
+ return z21.prettifyError(error);
2243
+ }, "prettifyZodError");
2244
+
2245
+ // src/simple/block/SimpleBlockViewer.ts
2246
+ var SimpleBlockViewer = class extends AbstractCreatable2 {
2247
+ static {
2248
+ __name(this, "SimpleBlockViewer");
2249
+ }
2250
+ _payloadCache;
2251
+ _signedHydratedBlockCache;
2252
+ get context() {
2253
+ return this.params.context;
2254
+ }
2255
+ get finalizedArchivist() {
2256
+ return this.params.finalizedArchivist;
2257
+ }
2258
+ get hydratedBlockCache() {
2259
+ if (this._signedHydratedBlockCache) return this._signedHydratedBlockCache;
2260
+ const chainMap = this.context.store.chainMap;
2261
+ this._signedHydratedBlockCache = new HydratedCache(chainMap, async ({ chainMap: chainMap2 }, hash, maxDepth, minDepth) => {
2262
+ const result = await hydrateBlock({
2263
+ chainMap: chainMap2
2264
+ }, hash, maxDepth, minDepth);
2265
+ return asSignedHydratedBlockWithHashMeta(result, true);
2266
+ }, 200);
2267
+ return this._signedHydratedBlockCache;
2268
+ }
2269
+ get payloadCache() {
2270
+ if (this._payloadCache) return this._payloadCache;
2271
+ this._payloadCache = new LruCacheMap({
2272
+ max: 1e4
2273
+ });
2274
+ return this._payloadCache;
2275
+ }
2276
+ static async paramsHandler(params) {
2277
+ assertEx14(params.context, () => "context is required");
2278
+ assertEx14(params.finalizedArchivist, () => "finalizedArchivist is required");
2279
+ return {
2280
+ ...await super.paramsHandler(params)
2281
+ };
2282
+ }
2283
+ async blockByHash(hash) {
2284
+ return await spanRootAsync5("blockByHash", async () => {
2285
+ const cache = this.hydratedBlockCache;
2286
+ return await cache.get(hash);
2287
+ }, this.tracer);
2288
+ }
2289
+ async blockByNumber(blockNumber) {
2290
+ return await spanRootAsync5("blockByNumber", async () => {
2291
+ return asSignedHydratedBlockWithHashMeta(await hydratedBlockByNumber(this.context, blockNumber)) ?? null;
2292
+ }, this.tracer);
2293
+ }
2294
+ async blocksByHash(hash, limit = 50) {
2295
+ return await spanRootAsync5("blocksByHash", async () => {
2296
+ assertEx14(limit > 0, () => "limit must be greater than 0");
2297
+ assertEx14(limit <= 100, () => "limit must be less than 100");
2298
+ const blocks = [];
2299
+ let current = await this.blockByHash(hash);
2300
+ while (current && blocks.length < limit) {
2301
+ blocks.push(current);
2302
+ const previousHash = current[0].previous;
2303
+ if (previousHash === null) break;
2304
+ current = await this.blockByHash(previousHash);
2305
+ }
2306
+ return blocks.map((b) => asSignedHydratedBlockWithHashMeta(b, true));
2307
+ }, this.tracer);
2308
+ }
2309
+ async blocksByNumber(blockNumber, limit = 50) {
2310
+ return await spanRootAsync5("blocksByHash", async () => {
2311
+ assertEx14(limit > 0, () => "limit must be greater than 0");
2312
+ assertEx14(limit <= 100, () => "limit must be less than 100");
2313
+ const blocks = [];
2314
+ let current = await this.blockByNumber(blockNumber);
2315
+ while (current && blocks.length < limit) {
2316
+ blocks.push(current);
2317
+ if (current[0].block === 0) break;
2318
+ const previousNumber = asXL1BlockNumber6(current[0].block - 1, true);
2319
+ current = await this.blockByNumber(previousNumber);
2320
+ }
2321
+ return blocks.map((b) => asSignedHydratedBlockWithHashMeta(b, true));
2322
+ }, this.tracer);
2323
+ }
2324
+ async currentBlock() {
2325
+ return await spanRootAsync5("currentBlock", async () => {
2326
+ const currentHead = assertEx14(await this.getCurrentHead(), () => "Could not find most recent block");
2327
+ const cache = this.hydratedBlockCache;
2328
+ const block = await cache.get(currentHead._hash);
2329
+ if (!block) {
2330
+ console.log(`Could not find current block with hash ${currentHead._hash}`);
2331
+ }
2332
+ return assertEx14(block, () => "Could not find current block");
2333
+ }, this.tracer);
2334
+ }
2335
+ async currentBlockHash() {
2336
+ return await spanRootAsync5("currentBlockHash", async () => {
2337
+ const currentHead = assertEx14(await this.getCurrentHead(), () => "Could not find most recent block");
2338
+ return currentHead._hash;
2339
+ }, this.tracer);
2340
+ }
2341
+ async currentBlockNumber() {
2342
+ return await spanRootAsync5("currentBlockNumber", async () => {
2343
+ const currentHead = assertEx14(await this.getCurrentHead(), () => "Could not find most recent block");
2344
+ return asXL1BlockNumber6(currentHead.block, {
2345
+ name: "currentBlockNumber"
2346
+ });
2347
+ }, this.tracer);
2348
+ }
2349
+ async payloadByHash(hash) {
2350
+ const cachedPayload = await this.payloadCache.get(hash);
2351
+ if (cachedPayload) {
2352
+ return cachedPayload;
2353
+ } else {
2354
+ const [result] = await this.finalizedArchivist.get([
2355
+ hash
2356
+ ]);
2357
+ if (isDefined12(result)) {
2358
+ await this.payloadCache.set(hash, result);
2359
+ }
2360
+ return result ?? null;
2361
+ }
2362
+ }
2363
+ async payloadsByHash(hashes) {
2364
+ let remainingHashes = [
2365
+ ...hashes
2366
+ ];
2367
+ const cachedPayloads = await this.payloadCache.getMany(remainingHashes);
2368
+ const cachedHashes = new Set(cachedPayloads.map((p) => p._hash));
2369
+ remainingHashes = remainingHashes.filter((h) => !cachedHashes.has(h));
2370
+ const remainingPayloads = remainingHashes.length > 0 ? await this.finalizedArchivist.get(remainingHashes) : [];
2371
+ return [
2372
+ ...cachedPayloads,
2373
+ ...remainingPayloads.filter(exists2)
2374
+ ];
2375
+ }
2376
+ async getCurrentHead() {
2377
+ const chainArchivist = this.finalizedArchivist;
2378
+ return await findMostRecentBlock(chainArchivist);
2379
+ }
2380
+ };
2381
+
2382
+ // src/simple/blockReward/SimpleBlockRewardViewer.ts
2383
+ import { AbstractCreatable as AbstractCreatable3, creatable } from "@xylabs/sdk-js";
2384
+ function _ts_decorate(decorators, target, key, desc) {
2385
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2386
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2387
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2388
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2389
+ }
2390
+ __name(_ts_decorate, "_ts_decorate");
2391
+ var SimpleBlockRewardViewer = class extends AbstractCreatable3 {
2392
+ static {
2393
+ __name(this, "SimpleBlockRewardViewer");
2394
+ }
2395
+ rewardFromBlockNumber = rewardFromBlockNumber(18);
2396
+ allowedRewardForBlock(block) {
2397
+ return this.rewardFromBlockNumber(block, this.params.initialReward, this.params.stepSize, this.params.stepFactorNumerator, this.params.stepFactorDenominator, this.params.minRewardPerBlock, this.params.creatorReward);
2398
+ }
2002
2399
  };
2400
+ SimpleBlockRewardViewer = _ts_decorate([
2401
+ creatable()
2402
+ ], SimpleBlockRewardViewer);
2003
2403
 
2004
2404
  // src/simple/chainStake/SimpleChainStakeViewer.ts
2005
2405
  import { asAddress as asAddress5, toAddress as toAddress5 } from "@xylabs/sdk-js";
2006
- import { AbstractCreatable as AbstractCreatable3, assertEx as assertEx13, creatable as creatable2 } from "@xylabs/sdk-js";
2406
+ import { AbstractCreatable as AbstractCreatable5, assertEx as assertEx15, creatable as creatable3 } from "@xylabs/sdk-js";
2007
2407
  import { Account } from "@xyo-network/account";
2008
2408
 
2009
2409
  // src/simple/chainStakeEvents/SimpleChainStakeEventsViewer.ts
2010
- import { AbstractCreatable as AbstractCreatable2, creatable, isDefined as isDefined12 } from "@xylabs/sdk-js";
2011
- function _ts_decorate(decorators, target, key, desc) {
2410
+ import { AbstractCreatable as AbstractCreatable4, creatable as creatable2, isDefined as isDefined13 } from "@xylabs/sdk-js";
2411
+ function _ts_decorate2(decorators, target, key, desc) {
2012
2412
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2013
2413
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2014
2414
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2015
2415
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2016
2416
  }
2017
- __name(_ts_decorate, "_ts_decorate");
2018
- var SimpleChainStakeEventsViewer = class extends AbstractCreatable2 {
2417
+ __name(_ts_decorate2, "_ts_decorate");
2418
+ var SimpleChainStakeEventsViewer = class extends AbstractCreatable4 {
2019
2419
  static {
2020
2420
  __name(this, "SimpleChainStakeEventsViewer");
2021
2421
  }
@@ -2028,7 +2428,7 @@ var SimpleChainStakeEventsViewer = class extends AbstractCreatable2 {
2028
2428
  stakeEvents(range, { name } = {}) {
2029
2429
  const positions = this.positionsFromRange(range);
2030
2430
  const events = this.eventsFromPositions(positions);
2031
- if (isDefined12(name)) {
2431
+ if (isDefined13(name)) {
2032
2432
  return events.filter((event) => event.name === name);
2033
2433
  }
2034
2434
  return events;
@@ -2087,26 +2487,26 @@ var SimpleChainStakeEventsViewer = class extends AbstractCreatable2 {
2087
2487
  return filteredPositions;
2088
2488
  }
2089
2489
  };
2090
- SimpleChainStakeEventsViewer = _ts_decorate([
2091
- creatable()
2490
+ SimpleChainStakeEventsViewer = _ts_decorate2([
2491
+ creatable2()
2092
2492
  ], SimpleChainStakeEventsViewer);
2093
2493
 
2094
2494
  // src/simple/chainStake/SimpleChainStakeViewer.ts
2095
- function _ts_decorate2(decorators, target, key, desc) {
2495
+ function _ts_decorate3(decorators, target, key, desc) {
2096
2496
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2097
2497
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2098
2498
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2099
2499
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2100
2500
  }
2101
- __name(_ts_decorate2, "_ts_decorate");
2102
- var SimpleChainStakeViewer = class extends AbstractCreatable3 {
2501
+ __name(_ts_decorate3, "_ts_decorate");
2502
+ var SimpleChainStakeViewer = class extends AbstractCreatable5 {
2103
2503
  static {
2104
2504
  __name(this, "SimpleChainStakeViewer");
2105
2505
  }
2106
2506
  _chainId;
2107
2507
  _chainStakeEventsViewer;
2108
2508
  get chainId() {
2109
- return assertEx13(this._chainId, () => "Chain ID not set");
2509
+ return assertEx15(this._chainId, () => "Chain ID not set");
2110
2510
  }
2111
2511
  get chainMap() {
2112
2512
  return this.params.chainMap;
@@ -2118,7 +2518,7 @@ var SimpleChainStakeViewer = class extends AbstractCreatable3 {
2118
2518
  return toAddress5(toAddress5(1n));
2119
2519
  }
2120
2520
  get stakeEvents() {
2121
- return assertEx13(this._chainStakeEventsViewer, () => "Stake events viewer not set");
2521
+ return assertEx15(this._chainStakeEventsViewer, () => "Stake events viewer not set");
2122
2522
  }
2123
2523
  get stakingTokenAddress() {
2124
2524
  return toAddress5("0x000000000000000000000000000011");
@@ -2172,7 +2572,7 @@ var SimpleChainStakeViewer = class extends AbstractCreatable3 {
2172
2572
  return pending;
2173
2573
  }
2174
2574
  stakeById(id) {
2175
- return assertEx13(this.positions[id], () => new Error(`Stake with id ${id} not found`));
2575
+ return assertEx15(this.positions[id], () => new Error(`Stake with id ${id} not found`));
2176
2576
  }
2177
2577
  stakeByStaker(staker, slot) {
2178
2578
  return this.positions.filter((s) => asAddress5(s.staker) === asAddress5(staker))[slot];
@@ -2217,8 +2617,8 @@ var SimpleChainStakeViewer = class extends AbstractCreatable3 {
2217
2617
  });
2218
2618
  }
2219
2619
  };
2220
- SimpleChainStakeViewer = _ts_decorate2([
2221
- creatable2()
2620
+ SimpleChainStakeViewer = _ts_decorate3([
2621
+ creatable3()
2222
2622
  ], SimpleChainStakeViewer);
2223
2623
 
2224
2624
  // src/simple/client/SimpleXyoClient.ts
@@ -2339,9 +2739,9 @@ var SimpleXyoGateway = class {
2339
2739
  };
2340
2740
 
2341
2741
  // src/simple/gateway/SimpleXyoGatewayRunner.ts
2342
- import { assertEx as assertEx14, BigIntToJsonZod, isDefined as isDefined13 } from "@xylabs/sdk-js";
2343
- import { PayloadBuilder as PayloadBuilder12 } from "@xyo-network/payload-builder";
2344
- import { asXL1BlockNumber as asXL1BlockNumber6, TransferSchema as TransferSchema2 } from "@xyo-network/xl1-protocol";
2742
+ import { assertEx as assertEx16, BigIntToJsonZod, isDefined as isDefined14 } from "@xylabs/sdk-js";
2743
+ import { PayloadBuilder as PayloadBuilder14 } from "@xyo-network/payload-builder";
2744
+ import { asXL1BlockNumber as asXL1BlockNumber7, TransferSchema as TransferSchema2 } from "@xyo-network/xl1-protocol";
2345
2745
  var SimpleXyoGatewayRunner = class {
2346
2746
  static {
2347
2747
  __name(this, "SimpleXyoGatewayRunner");
@@ -2360,7 +2760,7 @@ var SimpleXyoGatewayRunner = class {
2360
2760
  return this._connection;
2361
2761
  }
2362
2762
  get dataLakes() {
2363
- throw new Error("Method not implemented.");
2763
+ throw new Error("Method [dataLakes] not implemented.");
2364
2764
  }
2365
2765
  get signerInstance() {
2366
2766
  return this._signer;
@@ -2370,18 +2770,18 @@ var SimpleXyoGatewayRunner = class {
2370
2770
  return this._dataLakes.length - 1;
2371
2771
  }
2372
2772
  async addPayloadsToChain(onChain, offChain, options) {
2373
- const viewer = assertEx14(this.connectionInstance.viewer, () => "No viewer available on connection");
2773
+ const viewer = assertEx16(this.connectionInstance.viewer, () => "No viewer available on connection");
2374
2774
  const { nbf, exp, chain, fees } = options ?? {};
2375
- const resolvedChainId = isDefined13(chain) ? chain : await viewer.chainId();
2376
- const resolvedNbf = asXL1BlockNumber6(isDefined13(nbf) ? nbf : await viewer.currentBlockNumber(), true);
2377
- const resolvedExp = asXL1BlockNumber6(isDefined13(exp) ? exp : resolvedNbf + 10, true);
2775
+ const resolvedChainId = isDefined14(chain) ? chain : await viewer.chainId();
2776
+ const resolvedNbf = asXL1BlockNumber7(isDefined14(nbf) ? nbf : await viewer.currentBlockNumber(), true);
2777
+ const resolvedExp = asXL1BlockNumber7(isDefined14(exp) ? exp : resolvedNbf + 10, true);
2378
2778
  const tx = await buildUnsignedTransaction(resolvedChainId, onChain, offChain, resolvedNbf, resolvedExp, await (await this.signer()).address(), fees);
2379
2779
  return await this.addTransactionToChain(tx);
2380
2780
  }
2381
2781
  async addTransactionToChain(tx) {
2382
2782
  const connection = this.connectionInstance;
2383
2783
  const signer = this.signerInstance;
2384
- const runner = assertEx14(connection.runner, () => "No runner available on connection");
2784
+ const runner = assertEx16(connection.runner, () => "No runner available on connection");
2385
2785
  const signedTx = await signer.signTransaction(tx);
2386
2786
  await this.addPayloadsToDataLakes(signedTx[1]);
2387
2787
  return [
@@ -2393,7 +2793,7 @@ var SimpleXyoGatewayRunner = class {
2393
2793
  ];
2394
2794
  }
2395
2795
  async confirmSubmittedTransaction(txHash, options) {
2396
- return await confirmSubmittedTransaction(assertEx14(this.connectionInstance.viewer, () => "Connection viewer is undefined"), txHash, options);
2796
+ return await confirmSubmittedTransaction(assertEx16(this.connectionInstance.viewer, () => "Connection viewer is undefined"), txHash, options);
2397
2797
  }
2398
2798
  /** @deprecated use connectionInstance instead */
2399
2799
  connection() {
@@ -2413,7 +2813,7 @@ var SimpleXyoGatewayRunner = class {
2413
2813
  address,
2414
2814
  BigIntToJsonZod.parse(amount)
2415
2815
  ]));
2416
- const transfer = new PayloadBuilder12({
2816
+ const transfer = new PayloadBuilder14({
2417
2817
  schema: TransferSchema2
2418
2818
  }).fields({
2419
2819
  from,
@@ -2438,6 +2838,112 @@ var SimpleXyoGatewayRunner = class {
2438
2838
  }
2439
2839
  };
2440
2840
 
2841
+ // src/simple/mempool/SimpleMempoolRunner.ts
2842
+ import { AbstractCreatable as AbstractCreatable6, creatable as creatable4 } from "@xylabs/sdk-js";
2843
+ import { PayloadBuilder as PayloadBuilder15 } from "@xyo-network/payload-builder";
2844
+ function _ts_decorate4(decorators, target, key, desc) {
2845
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2846
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2847
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2848
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2849
+ }
2850
+ __name(_ts_decorate4, "_ts_decorate");
2851
+ var SimpleMempoolRunner = class extends AbstractCreatable6 {
2852
+ static {
2853
+ __name(this, "SimpleMempoolRunner");
2854
+ }
2855
+ get pendingBlocksArchivist() {
2856
+ return this.params.pendingBlocksArchivist;
2857
+ }
2858
+ get pendingTransactionsArchivist() {
2859
+ return this.params.pendingTransactionsArchivist;
2860
+ }
2861
+ async submitBlocks(blocks) {
2862
+ const bundles = await Promise.all(blocks.map(async ([bw, payloads]) => {
2863
+ return hydratedBlockToPayloadBundle([
2864
+ await PayloadBuilder15.addHashMeta(bw),
2865
+ await PayloadBuilder15.addHashMeta(payloads)
2866
+ ]);
2867
+ }));
2868
+ const inserted = await this.pendingBlocksArchivist.insert(bundles);
2869
+ return inserted.map((p) => p._hash);
2870
+ }
2871
+ async submitTransactions(transactions) {
2872
+ const bundles = await Promise.all(transactions.map(async ([tx, payloads]) => {
2873
+ return hydratedTransactionToPayloadBundle([
2874
+ await PayloadBuilder15.addHashMeta(tx),
2875
+ await PayloadBuilder15.addHashMeta(payloads)
2876
+ ]);
2877
+ }));
2878
+ const inserted = await this.pendingBlocksArchivist.insert(bundles);
2879
+ return inserted.map((p) => p._hash);
2880
+ }
2881
+ };
2882
+ SimpleMempoolRunner = _ts_decorate4([
2883
+ creatable4()
2884
+ ], SimpleMempoolRunner);
2885
+
2886
+ // src/simple/mempool/SimpleMempoolViewer.ts
2887
+ import { AbstractCreatable as AbstractCreatable7, creatable as creatable5, exists as exists3, isDefined as isDefined15, isHash } from "@xylabs/sdk-js";
2888
+ import { isHashMeta as isHashMeta2, isPayloadBundle } from "@xyo-network/payload-model";
2889
+ function _ts_decorate5(decorators, target, key, desc) {
2890
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2891
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2892
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2893
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2894
+ }
2895
+ __name(_ts_decorate5, "_ts_decorate");
2896
+ var SimpleMempoolViewer = class extends AbstractCreatable7 {
2897
+ static {
2898
+ __name(this, "SimpleMempoolViewer");
2899
+ }
2900
+ get pendingBlocksArchivist() {
2901
+ return this.params.pendingBlocksArchivist;
2902
+ }
2903
+ get pendingTransactionsArchivist() {
2904
+ return this.params.pendingTransactionsArchivist;
2905
+ }
2906
+ async pendingBlocks({ cursor: providedCursor } = {}) {
2907
+ let cursor = void 0;
2908
+ if (isHash(providedCursor)) {
2909
+ const [p] = await this.pendingBlocksArchivist.get([
2910
+ providedCursor
2911
+ ]);
2912
+ if (isDefined15(p)) {
2913
+ cursor = p._sequence;
2914
+ }
2915
+ }
2916
+ const bundles = await this.pendingBlocksArchivist.next({
2917
+ order: "asc",
2918
+ limit: 100,
2919
+ cursor
2920
+ });
2921
+ const filteredBundles = bundles.filter(isPayloadBundle).filter(isHashMeta2);
2922
+ return (await Promise.all(filteredBundles.map(async (bundle3) => await bundledPayloadToHydratedBlock(bundle3)))).filter(exists3);
2923
+ }
2924
+ async pendingTransactions({ cursor: providedCursor } = {}) {
2925
+ let cursor = void 0;
2926
+ if (isHash(providedCursor)) {
2927
+ const [p] = await this.pendingTransactionsArchivist.get([
2928
+ providedCursor
2929
+ ]);
2930
+ if (isDefined15(p)) {
2931
+ cursor = p._sequence;
2932
+ }
2933
+ }
2934
+ const bundles = await this.pendingTransactionsArchivist.next({
2935
+ order: "asc",
2936
+ limit: 100,
2937
+ cursor
2938
+ });
2939
+ const filteredBundles = bundles.filter(isPayloadBundle).filter(isHashMeta2);
2940
+ return (await Promise.all(filteredBundles.map(async (bundle3) => await bundledPayloadToHydratedTransaction(bundle3)))).filter(exists3);
2941
+ }
2942
+ };
2943
+ SimpleMempoolViewer = _ts_decorate5([
2944
+ creatable5()
2945
+ ], SimpleMempoolViewer);
2946
+
2441
2947
  // src/simple/network/SimpleXyoNetwork.ts
2442
2948
  import { isUndefined as isUndefined4 } from "@xylabs/sdk-js";
2443
2949
  import { isNetworkStatus } from "@xyo-network/xl1-protocol";
@@ -2511,7 +3017,7 @@ var SimpleXyoNetwork = class {
2511
3017
  };
2512
3018
 
2513
3019
  // src/simple/permissions/SimpleXyoPermissions.ts
2514
- import { assertEx as assertEx15 } from "@xylabs/sdk-js";
3020
+ import { assertEx as assertEx17 } from "@xylabs/sdk-js";
2515
3021
  var SimpleXyoPermissions = class {
2516
3022
  static {
2517
3023
  __name(this, "SimpleXyoPermissions");
@@ -2523,7 +3029,7 @@ var SimpleXyoPermissions = class {
2523
3029
  this.invoker = store.invoker;
2524
3030
  }
2525
3031
  get store() {
2526
- return assertEx15(this._store, () => "Store must be defined to get permissions");
3032
+ return assertEx17(this._store, () => "Store must be defined to get permissions");
2527
3033
  }
2528
3034
  async getPermissions() {
2529
3035
  return await this.store.getPermissions();
@@ -2581,7 +3087,7 @@ var SimpleXyoPermissions = class {
2581
3087
  };
2582
3088
 
2583
3089
  // src/simple/permissions/store/MemoryPermissions.ts
2584
- import { assertEx as assertEx16 } from "@xylabs/sdk-js";
3090
+ import { assertEx as assertEx18 } from "@xylabs/sdk-js";
2585
3091
  var MemoryPermissionsStore = class {
2586
3092
  static {
2587
3093
  __name(this, "MemoryPermissionsStore");
@@ -2592,7 +3098,7 @@ var MemoryPermissionsStore = class {
2592
3098
  this._invoker = invoker;
2593
3099
  }
2594
3100
  get invoker() {
2595
- return assertEx16(this._invoker, () => "Invoker must be defined to get permissions");
3101
+ return assertEx18(this._invoker, () => "Invoker must be defined to get permissions");
2596
3102
  }
2597
3103
  async getPermissions() {
2598
3104
  await Promise.resolve();
@@ -2606,7 +3112,7 @@ var MemoryPermissionsStore = class {
2606
3112
 
2607
3113
  // src/simple/runner/SimpleXyoRunner.ts
2608
3114
  import { MemoryArchivist } from "@xyo-network/archivist-memory";
2609
- import { PayloadBuilder as PayloadBuilder13 } from "@xyo-network/payload-builder";
3115
+ import { PayloadBuilder as PayloadBuilder16 } from "@xyo-network/payload-builder";
2610
3116
  var SimpleXyoRunner = class {
2611
3117
  static {
2612
3118
  __name(this, "SimpleXyoRunner");
@@ -2618,7 +3124,7 @@ var SimpleXyoRunner = class {
2618
3124
  async broadcastTransaction(transaction) {
2619
3125
  const archivist = await this.getMempoolArchivist();
2620
3126
  await archivist.insert(flattenHydratedTransaction(transaction));
2621
- return await PayloadBuilder13.hash(transaction[0]);
3127
+ return await PayloadBuilder16.hash(transaction[0]);
2622
3128
  }
2623
3129
  async getMempoolArchivist() {
2624
3130
  if (!this._mempoolArchivist) {
@@ -2631,7 +3137,7 @@ var SimpleXyoRunner = class {
2631
3137
  };
2632
3138
 
2633
3139
  // src/simple/signer/SimpleXyoSigner.ts
2634
- import { PayloadBuilder as PayloadBuilder14 } from "@xyo-network/payload-builder";
3140
+ import { PayloadBuilder as PayloadBuilder17 } from "@xyo-network/payload-builder";
2635
3141
  import { SignedHydratedTransactionWithHashMetaZod } from "@xyo-network/xl1-protocol";
2636
3142
  var SimpleXyoSigner = class {
2637
3143
  static {
@@ -2652,15 +3158,15 @@ var SimpleXyoSigner = class {
2652
3158
  async signTransaction(tx) {
2653
3159
  const txBW = await signTransaction(tx[0], this._account);
2654
3160
  return SignedHydratedTransactionWithHashMetaZod.parse([
2655
- await PayloadBuilder14.addStorageMeta(txBW),
2656
- await PayloadBuilder14.addStorageMeta(tx[1])
3161
+ await PayloadBuilder17.addStorageMeta(txBW),
3162
+ await PayloadBuilder17.addStorageMeta(tx[1])
2657
3163
  ]);
2658
3164
  }
2659
3165
  };
2660
3166
 
2661
3167
  // src/simple/timesync/SimpleTimeSyncViewer.ts
2662
- import { asHash as asHash5, assertEx as assertEx17, isDefined as isDefined14 } from "@xylabs/sdk-js";
2663
- import { asTimePayload, asXL1BlockNumber as asXL1BlockNumber7, TimeSchema } from "@xyo-network/xl1-protocol";
3168
+ import { asHash as asHash6, assertEx as assertEx19, isDefined as isDefined16 } from "@xylabs/sdk-js";
3169
+ import { asTimePayload, asXL1BlockNumber as asXL1BlockNumber8, TimeSchema } from "@xyo-network/xl1-protocol";
2664
3170
  var SimpleTimeSyncViewer = class {
2665
3171
  static {
2666
3172
  __name(this, "SimpleTimeSyncViewer");
@@ -2674,10 +3180,10 @@ var SimpleTimeSyncViewer = class {
2674
3180
  async convertTime(fromDomain, toDomain, from) {
2675
3181
  switch (fromDomain) {
2676
3182
  case "xl1": {
2677
- const [block, payloads] = assertEx17(await this.blockViewer.blockByNumber(asXL1BlockNumber7(from, true)), () => "Block not found");
3183
+ const [block, payloads] = assertEx19(await this.blockViewer.blockByNumber(asXL1BlockNumber8(from, true)), () => "Block not found");
2678
3184
  const timeSchemaIndex = block.payload_schemas.indexOf(TimeSchema);
2679
3185
  const hash = timeSchemaIndex === -1 ? void 0 : block.payload_hashes[timeSchemaIndex];
2680
- const timePayload = asTimePayload(isDefined14(hash) ? payloads.find((p) => p._hash === hash) : void 0);
3186
+ const timePayload = asTimePayload(isDefined16(hash) ? payloads.find((p) => p._hash === hash) : void 0);
2681
3187
  if (timePayload === void 0) return 0;
2682
3188
  switch (toDomain) {
2683
3189
  case "xl1": {
@@ -2740,10 +3246,10 @@ var SimpleTimeSyncViewer = class {
2740
3246
  ];
2741
3247
  }
2742
3248
  case "ethereum": {
2743
- const provider = assertEx17(this.ethProvider, () => "Ethereum provider not configured");
3249
+ const provider = assertEx19(this.ethProvider, () => "Ethereum provider not configured");
2744
3250
  const blockNumber = await provider.getBlockNumber() ?? 0;
2745
3251
  const block = await provider.getBlock(blockNumber);
2746
- const blockHash = asHash5(assertEx17(block?.hash, () => "Block hash not found"), true);
3252
+ const blockHash = asHash6(assertEx19(block?.hash, () => "Block hash not found"), true);
2747
3253
  return [
2748
3254
  blockNumber,
2749
3255
  blockHash
@@ -2755,12 +3261,12 @@ var SimpleTimeSyncViewer = class {
2755
3261
  }
2756
3262
  }
2757
3263
  currentTimePayload() {
2758
- throw new Error("Method not implemented.");
3264
+ throw new Error("Method [currentTimePayload] not implemented.");
2759
3265
  }
2760
3266
  };
2761
3267
 
2762
3268
  // src/time/primitives/xl1BlockNumberToEthBlockNumber.ts
2763
- import { assertEx as assertEx18 } from "@xylabs/sdk-js";
3269
+ import { assertEx as assertEx20 } from "@xylabs/sdk-js";
2764
3270
  import { asTimePayload as asTimePayload2, TimeSchema as TimeSchema2 } from "@xyo-network/xl1-protocol";
2765
3271
  async function xl1BlockNumberToEthBlockNumber(context, xl1BlockNumber) {
2766
3272
  const blockHash = await hashFromBlockNumber(context, xl1BlockNumber);
@@ -2768,38 +3274,34 @@ async function xl1BlockNumberToEthBlockNumber(context, xl1BlockNumber) {
2768
3274
  const timePayload = asTimePayload2(hydratedBlock[1].find((p) => p.schema === TimeSchema2), {
2769
3275
  required: true
2770
3276
  });
2771
- return assertEx18(timePayload.ethereum, () => "No ethereum timestamp found on block");
3277
+ return assertEx20(timePayload.ethereum, () => "No ethereum timestamp found on block");
2772
3278
  }
2773
3279
  __name(xl1BlockNumberToEthBlockNumber, "xl1BlockNumberToEthBlockNumber");
2774
3280
 
2775
- // src/utils/isZodError.ts
2776
- import * as z20 from "zod";
2777
- var isZodError = /* @__PURE__ */ __name((error) => {
2778
- return error instanceof z20.ZodError;
2779
- }, "isZodError");
2780
- var prettifyZodError = /* @__PURE__ */ __name((error) => {
2781
- return z20.prettifyError(error);
2782
- }, "prettifyZodError");
2783
-
2784
3281
  // src/viewers/AccountBalance.ts
2785
3282
  import { WithHashMetaZod } from "@xyo-network/payload-model";
2786
3283
  import { TransferZod } from "@xyo-network/xl1-protocol";
2787
3284
  import { BlockBoundWitnessZod, TransactionBoundWitnessZod } from "@xyo-network/xl1-protocol";
2788
- import z21 from "zod";
2789
- var AccountBalanceHistoryItemZod = z21.tuple([
3285
+ import z22 from "zod";
3286
+ var AccountBalanceHistoryItemZod = z22.tuple([
2790
3287
  WithHashMetaZod(BlockBoundWitnessZod),
2791
3288
  WithHashMetaZod(TransactionBoundWitnessZod).nullable(),
2792
3289
  WithHashMetaZod(TransferZod)
2793
3290
  ]);
2794
3291
 
2795
3292
  // src/viewers/Mempool.ts
2796
- import { HashZod as HashZod2 } from "@xylabs/sdk-js";
2797
- import { XL1BlockRangeZod } from "@xyo-network/xl1-protocol";
2798
- import z22 from "zod";
2799
- var PendingTransactionsOptionsZod = z22.object({
2800
- cursor: HashZod2.optional(),
2801
- limit: z22.number().int().positive().optional(),
2802
- window: XL1BlockRangeZod.optional()
3293
+ import { HashZod as HashZod3 } from "@xylabs/sdk-js";
3294
+ import { XL1BlockRangeZod as XL1BlockRangeZod2 } from "@xyo-network/xl1-protocol";
3295
+ import z23 from "zod";
3296
+ var PendingTransactionsOptionsZod = z23.object({
3297
+ cursor: HashZod3.optional(),
3298
+ limit: z23.number().int().positive().optional(),
3299
+ window: XL1BlockRangeZod2.optional()
3300
+ });
3301
+ var PendingBlocksOptionsZod = z23.object({
3302
+ cursor: HashZod3.optional(),
3303
+ limit: z23.number().int().positive().optional(),
3304
+ window: XL1BlockRangeZod2.optional()
2803
3305
  });
2804
3306
 
2805
3307
  // src/viewers/StakeEvents.ts
@@ -2855,18 +3357,25 @@ export {
2855
3357
  GlobalMetaSchema,
2856
3358
  HydratedBlockStateValidationError,
2857
3359
  HydratedBlockValidationError,
3360
+ HydratedCache,
2858
3361
  JSONSchemaMetaSchema,
2859
3362
  LruCacheMap,
2860
3363
  MemoryMap,
2861
3364
  MemoryPermissionsStore,
2862
3365
  MnemonicStringZod,
3366
+ PendingBlocksOptionsZod,
2863
3367
  PendingTransactionsOptionsZod,
3368
+ QualifiedZod,
2864
3369
  RewardMultipliers,
2865
3370
  SchemasStepSummarySchema,
2866
3371
  SimpleAccountBalanceViewer,
3372
+ SimpleBlockRewardViewer,
3373
+ SimpleBlockViewer,
2867
3374
  SimpleChainStakeViewer,
2868
3375
  SimpleDataLakeRunner,
2869
3376
  SimpleDataLakeViewer,
3377
+ SimpleMempoolRunner,
3378
+ SimpleMempoolViewer,
2870
3379
  SimpleTimeSyncViewer,
2871
3380
  SimpleXyoClient,
2872
3381
  SimpleXyoGateway,
@@ -2910,6 +3419,7 @@ export {
2910
3419
  blockPayloadsFromHydratedBlock,
2911
3420
  buildTransaction,
2912
3421
  buildUnsignedTransaction,
3422
+ bundledPayloadToHydratedBlock,
2913
3423
  bundledPayloadToHydratedTransaction,
2914
3424
  calculateFramesFromRange,
2915
3425
  completedStepRewardAddress,
@@ -2922,6 +3432,7 @@ export {
2922
3432
  elevatedPayloads,
2923
3433
  extractElevatedHashes,
2924
3434
  extractElevatedHashesFromScript,
3435
+ findMostRecentBlock,
2925
3436
  flattenHydratedBlock,
2926
3437
  flattenHydratedBlocks,
2927
3438
  flattenHydratedTransaction,
@@ -2934,6 +3445,8 @@ export {
2934
3445
  hydrateBlock,
2935
3446
  hydrateElevatedTransaction,
2936
3447
  hydrateTransaction,
3448
+ hydratedBlockByNumber,
3449
+ hydratedBlockToPayloadBundle,
2937
3450
  hydratedTransactionToPayloadBundle,
2938
3451
  isAddressPairPayload,
2939
3452
  isBalancesStepSummary,
@@ -2963,6 +3476,7 @@ export {
2963
3476
  parseSignedBigInt,
2964
3477
  prettifyZodError,
2965
3478
  readPayloadMapFromStore,
3479
+ rewardFromBlockNumber,
2966
3480
  schemasStepSummaryFromRange,
2967
3481
  schemasSummary,
2968
3482
  signEIP712Message,