@xyo-network/xl1-protocol-sdk 1.26.12 → 1.26.14

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 (331) hide show
  1. package/dist/neutral/config/Actors.d.ts +1 -1
  2. package/dist/neutral/config/Base.d.ts +1 -1
  3. package/dist/neutral/config/Config.d.ts +4 -4
  4. package/dist/neutral/payloads/AddressPairPayload.d.ts +1 -1
  5. package/dist/neutral/payloads/AddressPairPayload.d.ts.map +1 -1
  6. package/dist/neutral/primitives/uncle/findBestUncle.d.ts +13 -13
  7. package/dist/neutral/primitives/uncle/findUncles.d.ts +2 -2
  8. package/dist/neutral/simple/accountBalance/SimpleAccountBalanceViewer.d.ts +2 -2
  9. package/dist/neutral/simple/block/SimpleBlockViewer.d.ts +2 -2
  10. package/dist/neutral/simple/chainContractViewer/SimpleChainContractViewer.d.ts +1 -1
  11. package/dist/neutral/simple/datalake/SimpleDataLakeRunner.d.ts +1 -1
  12. package/dist/neutral/simple/finalization/SimpleFinalizationViewer.d.ts +1 -1
  13. package/dist/neutral/simple/windowedBlock/SimpleWindowedBlockViewer.d.ts +10 -10
  14. package/dist/neutral/transaction/TransactionBuilder.d.ts +4 -4
  15. package/dist/neutral/transaction/signTransaction.d.ts +1 -1
  16. package/package.json +24 -21
  17. package/src/ChainContextHelpers.ts +0 -50
  18. package/src/CreatableProvider/AbstractCreatableProvider.ts +0 -97
  19. package/src/CreatableProvider/CreatableProvider.ts +0 -102
  20. package/src/CreatableProvider/CreatableProviderRegistry.ts +0 -94
  21. package/src/CreatableProvider/GetInstanceOptions.ts +0 -11
  22. package/src/CreatableProvider/LabeledCreatableProviderFactory.ts +0 -24
  23. package/src/CreatableProvider/ProviderFactory.ts +0 -138
  24. package/src/CreatableProvider/ProviderFactoryLocator.ts +0 -170
  25. package/src/CreatableProvider/ProviderFactoryLocatorInstance.ts +0 -70
  26. package/src/CreatableProvider/index.ts +0 -8
  27. package/src/SignedBigInt.ts +0 -59
  28. package/src/_internal/context/getTestProviderContext.ts +0 -13
  29. package/src/_internal/context/index.ts +0 -1
  30. package/src/_internal/index.ts +0 -2
  31. package/src/actor/ActorV3.ts +0 -177
  32. package/src/actor/index.ts +0 -1
  33. package/src/amount/ShiftedBigInt.ts +0 -73
  34. package/src/amount/XL1Amount.ts +0 -103
  35. package/src/amount/index.ts +0 -4
  36. package/src/amount/splitOnDecimal.ts +0 -6
  37. package/src/amount/splitOnDecimalToString.ts +0 -40
  38. package/src/block/hydrate/allHashesPresent.ts +0 -8
  39. package/src/block/hydrate/blockPayloadsFromHydratedBlock.ts +0 -12
  40. package/src/block/hydrate/flattenHydratedBlock.ts +0 -28
  41. package/src/block/hydrate/flattenHydratedBlocks.ts +0 -7
  42. package/src/block/hydrate/hydrateBlock.ts +0 -43
  43. package/src/block/hydrate/index.ts +0 -7
  44. package/src/block/hydrate/transactionsFromHydratedBlock.ts +0 -7
  45. package/src/block/hydrate/tryHydrateBlock.ts +0 -26
  46. package/src/block/index.ts +0 -2
  47. package/src/block/primitives/blockFromBlockNumber.ts +0 -69
  48. package/src/block/primitives/frames/calculateFramesFromRange.ts +0 -30
  49. package/src/block/primitives/frames/deepCalculateFramesFromRange.ts +0 -28
  50. package/src/block/primitives/frames/index.ts +0 -2
  51. package/src/block/primitives/hashFromBlockNumber.ts +0 -9
  52. package/src/block/primitives/index.ts +0 -7
  53. package/src/block/primitives/model.ts +0 -18
  54. package/src/block/primitives/payloads/ChainWindow.ts +0 -7
  55. package/src/block/primitives/payloads/index.ts +0 -1
  56. package/src/block/primitives/toStepIdentityString.ts +0 -6
  57. package/src/block/primitives/validateTransactionOpcodes.ts +0 -45
  58. package/src/config/Actor.ts +0 -32
  59. package/src/config/Actors.ts +0 -9
  60. package/src/config/Base.ts +0 -27
  61. package/src/config/Chain.ts +0 -23
  62. package/src/config/Config.ts +0 -24
  63. package/src/config/DataLake/DataLake.ts +0 -12
  64. package/src/config/DataLake/DataLakeRemoteConfig.ts +0 -11
  65. package/src/config/DataLake/RestDataLakeConfig.ts +0 -18
  66. package/src/config/DataLake/RouterDataLakeConfig.ts +0 -22
  67. package/src/config/DataLake/index.ts +0 -4
  68. package/src/config/DeepPartial.ts +0 -4
  69. package/src/config/Evm.ts +0 -38
  70. package/src/config/HostActor.ts +0 -32
  71. package/src/config/Log.ts +0 -25
  72. package/src/config/Provider.ts +0 -20
  73. package/src/config/Providers.ts +0 -9
  74. package/src/config/Remote.ts +0 -59
  75. package/src/config/Telemetry.ts +0 -49
  76. package/src/config/UsageMeta.ts +0 -46
  77. package/src/config/Validation.ts +0 -29
  78. package/src/config/index.ts +0 -12
  79. package/src/config/storage/Storage.ts +0 -16
  80. package/src/config/storage/driver/Mongo.ts +0 -53
  81. package/src/config/storage/driver/index.ts +0 -1
  82. package/src/config/storage/index.ts +0 -2
  83. package/src/constants.ts +0 -4
  84. package/src/context/Actor.ts +0 -20
  85. package/src/context/HostActor.ts +0 -20
  86. package/src/context/getEmptyProviderContext.ts +0 -19
  87. package/src/context/index.ts +0 -3
  88. package/src/createDeclarationPayload.ts +0 -15
  89. package/src/createTransferPayload.ts +0 -16
  90. package/src/driver/cache/LruCacheMap.ts +0 -48
  91. package/src/driver/cache/index.ts +0 -1
  92. package/src/driver/index.ts +0 -2
  93. package/src/driver/memory/MemoryMap.ts +0 -48
  94. package/src/driver/memory/index.ts +0 -1
  95. package/src/eip-712/Payloads/EIP712Data.ts +0 -35
  96. package/src/eip-712/Payloads/EIP712Signature.ts +0 -32
  97. package/src/eip-712/Payloads/index.ts +0 -2
  98. package/src/eip-712/Types.ts +0 -41
  99. package/src/eip-712/index.ts +0 -4
  100. package/src/eip-712/sign.ts +0 -19
  101. package/src/eip-712/spec/fixtures.ts +0 -27
  102. package/src/eip-712/verify.ts +0 -20
  103. package/src/getFileConfig.ts +0 -36
  104. package/src/index.ts +0 -27
  105. package/src/instances/Address.ts +0 -16
  106. package/src/instances/BoundWitness.ts +0 -13
  107. package/src/instances/Data.ts +0 -4
  108. package/src/instances/Fees.ts +0 -9
  109. package/src/instances/HydratedBoundWitness.ts +0 -16
  110. package/src/instances/Object.ts +0 -6
  111. package/src/instances/Payload.ts +0 -7
  112. package/src/instances/Signature.ts +0 -12
  113. package/src/instances/block/BlockFields.ts +0 -18
  114. package/src/instances/block/HydratedBlock.ts +0 -10
  115. package/src/instances/block/index.ts +0 -1
  116. package/src/instances/index.ts +0 -10
  117. package/src/instances/modifiers/BlockWindowInstance.ts +0 -8
  118. package/src/instances/modifiers/BlockWindowState.ts +0 -6
  119. package/src/instances/modifiers/Signed.ts +0 -9
  120. package/src/instances/modifiers/Validatable.ts +0 -6
  121. package/src/instances/modifiers/index.ts +0 -4
  122. package/src/instances/transaction/HydratedTransaction.ts +0 -9
  123. package/src/instances/transaction/TransactionFields.ts +0 -22
  124. package/src/instances/transaction/index.ts +0 -1
  125. package/src/isInternetAvailable.ts +0 -11
  126. package/src/model/ChainFork/ChainForkStatic.ts +0 -9
  127. package/src/model/ChainFork/index.ts +0 -1
  128. package/src/model/ChainIdentity.ts +0 -6
  129. package/src/model/ChainStore.ts +0 -16
  130. package/src/model/CreatableProviderContext.ts +0 -6
  131. package/src/model/CreatableProviderContext.zod.ts +0 -55
  132. package/src/model/PayloadBundle/bundledPayloadToHydratedBlock.ts +0 -15
  133. package/src/model/PayloadBundle/bundledPayloadToHydratedTransaction.ts +0 -15
  134. package/src/model/PayloadBundle/hydratedBlockToPayloadBundle.ts +0 -19
  135. package/src/model/PayloadBundle/hydratedTransactionToPayloadBundle.ts +0 -19
  136. package/src/model/PayloadBundle/index.ts +0 -4
  137. package/src/model/index.ts +0 -6
  138. package/src/multipliers.ts +0 -18
  139. package/src/payloads/AddressPairPayload.ts +0 -27
  140. package/src/payloads/index.ts +0 -4
  141. package/src/payloads/netBalancesForPayloads.ts +0 -24
  142. package/src/payloads/netSchemasForPayloads.ts +0 -24
  143. package/src/payloads/netTransfersForPayloads.ts +0 -27
  144. package/src/primitives/block/index.ts +0 -2
  145. package/src/primitives/block/range/blockRangeSteps.ts +0 -23
  146. package/src/primitives/block/range/index.ts +0 -1
  147. package/src/primitives/block/rate/blockRate.ts +0 -77
  148. package/src/primitives/block/rate/index.ts +0 -4
  149. package/src/primitives/block/rate/stepRate.ts +0 -37
  150. package/src/primitives/block/rate/timeHelpers.ts +0 -61
  151. package/src/primitives/block/rate/timeRate.ts +0 -121
  152. package/src/primitives/chain/getWindowedChain.ts +0 -50
  153. package/src/primitives/chain/index.ts +0 -3
  154. package/src/primitives/chain/step/chainStepRewardAddress.ts +0 -30
  155. package/src/primitives/chain/step/index.ts +0 -4
  156. package/src/primitives/chain/step/stepRewardBlock.ts +0 -13
  157. package/src/primitives/chain/step/stepRewardTotal.ts +0 -46
  158. package/src/primitives/chain/step/stepsRewardTotal.ts +0 -37
  159. package/src/primitives/chain/time/externalBlockNumberFromXL1BlockNumber.ts +0 -32
  160. package/src/primitives/chain/time/externalBlockRangeFromStep.ts +0 -21
  161. package/src/primitives/chain/time/externalBlockRangeFromXL1BlockRange.ts +0 -17
  162. package/src/primitives/chain/time/index.ts +0 -3
  163. package/src/primitives/datalake/addDataLakePayloads.ts +0 -18
  164. package/src/primitives/datalake/addDataLakePayloadsToPayloads.ts +0 -24
  165. package/src/primitives/datalake/index.ts +0 -2
  166. package/src/primitives/index.ts +0 -13
  167. package/src/primitives/mapToMapType.ts +0 -35
  168. package/src/primitives/payload/index.ts +0 -1
  169. package/src/primitives/payload/mergeTransfers.ts +0 -16
  170. package/src/primitives/readPayloadMapFromStore.ts +0 -58
  171. package/src/primitives/rewardFromBlockNumber.ts +0 -19
  172. package/src/primitives/rewards/index.ts +0 -1
  173. package/src/primitives/rewards/networkStakeStepRewardPositionWeight.ts +0 -26
  174. package/src/primitives/stake/activeStakeAtTimeByAddress.ts +0 -27
  175. package/src/primitives/stake/activeStakeAtTimeByPosition.ts +0 -25
  176. package/src/primitives/stake/allStakersForRange.ts +0 -32
  177. package/src/primitives/stake/allStakersForStep.ts +0 -24
  178. package/src/primitives/stake/index.ts +0 -6
  179. package/src/primitives/stake/mergedAddRemoveStakeEventsByPosition.ts +0 -15
  180. package/src/primitives/stake/mergedAddRemoveStakeEventsByStaker.ts +0 -17
  181. package/src/primitives/stake/weightedStakeForRangeByPosition.ts +0 -69
  182. package/src/primitives/state/findMostRecentBlock.ts +0 -44
  183. package/src/primitives/state/hydratedBlockByNumber.ts +0 -25
  184. package/src/primitives/state/index.ts +0 -2
  185. package/src/primitives/step/completedStepRewardAddress.ts +0 -10
  186. package/src/primitives/step/derivedReceiveAddress.ts +0 -9
  187. package/src/primitives/step/index.ts +0 -4
  188. package/src/primitives/step/stepBlockRange.ts +0 -9
  189. package/src/primitives/step/stepTransferIndex.ts +0 -19
  190. package/src/primitives/transaction/elevatedPayloads.ts +0 -24
  191. package/src/primitives/transaction/index.ts +0 -1
  192. package/src/primitives/uncle/findBestUncle.ts +0 -9
  193. package/src/primitives/uncle/findUncles.ts +0 -75
  194. package/src/primitives/uncle/index.ts +0 -3
  195. package/src/primitives/uncle/scoreUncle.ts +0 -7
  196. package/src/services/AccountTransfersService.ts +0 -13
  197. package/src/services/BlockProducerService.ts +0 -11
  198. package/src/services/Chain/BaseChainService.ts +0 -4
  199. package/src/services/Chain/ChainHeadService.ts +0 -8
  200. package/src/services/Chain/ChainService.ts +0 -6
  201. package/src/services/Chain/index.ts +0 -3
  202. package/src/services/Election.ts +0 -14
  203. package/src/services/NetworkStakeService.ts +0 -4
  204. package/src/services/Params.ts +0 -13
  205. package/src/services/PendingTransactionsService.ts +0 -7
  206. package/src/services/SchemasService.ts +0 -11
  207. package/src/services/StakeIntentService/ChainIndexingServiceStateSchema.ts +0 -50
  208. package/src/services/StakeIntentService/StakeIntentService.ts +0 -35
  209. package/src/services/StakeIntentService/index.ts +0 -2
  210. package/src/services/index.ts +0 -8
  211. package/src/simple/StakeEventsViewer/SimpleStakeEventsViewer.ts +0 -93
  212. package/src/simple/StakeEventsViewer/index.ts +0 -1
  213. package/src/simple/StakeTotalsViewer/SimpleStakeTotalsViewer.ts +0 -116
  214. package/src/simple/StakeTotalsViewer/index.ts +0 -1
  215. package/src/simple/StakeViewer/SimpleStakeViewer.ts +0 -164
  216. package/src/simple/StakeViewer/index.ts +0 -1
  217. package/src/simple/TransactionViewer/SimpleTransactionViewer.ts +0 -100
  218. package/src/simple/TransactionViewer/index.ts +0 -1
  219. package/src/simple/accountBalance/SimpleAccountBalanceViewer.ts +0 -271
  220. package/src/simple/accountBalance/index.ts +0 -1
  221. package/src/simple/block/SimpleBlockViewer.ts +0 -231
  222. package/src/simple/block/index.ts +0 -1
  223. package/src/simple/blockInvalidation/SimpleBlockInvalidationViewer.ts +0 -197
  224. package/src/simple/blockInvalidation/index.ts +0 -1
  225. package/src/simple/blockReward/SimpleBlockRewardViewer.ts +0 -27
  226. package/src/simple/blockReward/index.ts +0 -1
  227. package/src/simple/blockValidation/SimpleBlockValidationViewer.ts +0 -194
  228. package/src/simple/blockValidation/index.ts +0 -1
  229. package/src/simple/chainContractViewer/SimpleChainContractViewer.ts +0 -92
  230. package/src/simple/chainContractViewer/index.ts +0 -1
  231. package/src/simple/client/SimpleXyoClient.ts +0 -14
  232. package/src/simple/client/index.ts +0 -1
  233. package/src/simple/datalake/AbstractRestDataLake.ts +0 -70
  234. package/src/simple/datalake/AbstractSimpleDataLake.ts +0 -62
  235. package/src/simple/datalake/RestDataLakeRunner.ts +0 -54
  236. package/src/simple/datalake/RestDataLakeViewer.ts +0 -22
  237. package/src/simple/datalake/SimpleDataLakeRunner.ts +0 -44
  238. package/src/simple/datalake/SimpleDataLakeViewer.ts +0 -24
  239. package/src/simple/datalake/index.ts +0 -4
  240. package/src/simple/finalization/SimpleFinalizationRunner.ts +0 -45
  241. package/src/simple/finalization/SimpleFinalizationViewer.ts +0 -123
  242. package/src/simple/finalization/index.ts +0 -2
  243. package/src/simple/gateway/SimpleXyoGateway.ts +0 -30
  244. package/src/simple/gateway/SimpleXyoGatewayRunner.ts +0 -137
  245. package/src/simple/gateway/index.ts +0 -2
  246. package/src/simple/index.ts +0 -22
  247. package/src/simple/mempool/SimpleMempoolRunner.ts +0 -390
  248. package/src/simple/mempool/SimpleMempoolViewer.ts +0 -215
  249. package/src/simple/mempool/index.ts +0 -2
  250. package/src/simple/network/SimpleXyoNetwork.ts +0 -48
  251. package/src/simple/network/index.ts +0 -1
  252. package/src/simple/network/lib/FailedNetworkStatusPayloads.ts +0 -16
  253. package/src/simple/network/lib/StatusNetworks.ts +0 -32
  254. package/src/simple/network/lib/index.ts +0 -2
  255. package/src/simple/permissions/SimpleXyoPermissions.ts +0 -82
  256. package/src/simple/permissions/index.ts +0 -2
  257. package/src/simple/permissions/store/MemoryPermissions.ts +0 -32
  258. package/src/simple/permissions/store/PermissionsStore.ts +0 -17
  259. package/src/simple/permissions/store/index.ts +0 -2
  260. package/src/simple/runner/SimpleXyoRunner.ts +0 -41
  261. package/src/simple/runner/index.ts +0 -1
  262. package/src/simple/signer/SimpleXyoSigner.ts +0 -78
  263. package/src/simple/signer/index.ts +0 -1
  264. package/src/simple/timeSync2/SimpleTimeSyncViewer.ts +0 -132
  265. package/src/simple/timeSync2/index.ts +0 -1
  266. package/src/simple/transactionInvalidation/SimpleTransactionInvalidationViewer.ts +0 -197
  267. package/src/simple/transactionInvalidation/index.ts +0 -1
  268. package/src/simple/transactionValidation/SimpleTransactionValidationViewer.ts +0 -173
  269. package/src/simple/transactionValidation/index.ts +0 -1
  270. package/src/simple/windowedBlock/SimpleWindowedBlockViewer.ts +0 -207
  271. package/src/simple/windowedBlock/index.ts +0 -1
  272. package/src/status/RuntimeStatusMonitor.ts +0 -120
  273. package/src/status/ServiceStatus.ts +0 -21
  274. package/src/status/index.ts +0 -2
  275. package/src/summary/index.ts +0 -2
  276. package/src/summary/model/BalancesStepSummary.ts +0 -35
  277. package/src/summary/model/SchemasStepSummary.ts +0 -33
  278. package/src/summary/model/StepSummary.ts +0 -20
  279. package/src/summary/model/TransfersSummary.ts +0 -36
  280. package/src/summary/model/index.ts +0 -4
  281. package/src/summary/primitives/balances/balancesStepSummaryFromRange.ts +0 -94
  282. package/src/summary/primitives/balances/balancesSummary.ts +0 -48
  283. package/src/summary/primitives/balances/index.ts +0 -2
  284. package/src/summary/primitives/index.ts +0 -3
  285. package/src/summary/primitives/schemas/index.ts +0 -2
  286. package/src/summary/primitives/schemas/schemasStepSummaryFromRange.ts +0 -86
  287. package/src/summary/primitives/schemas/schemasSummary.ts +0 -44
  288. package/src/summary/primitives/transfers/index.ts +0 -2
  289. package/src/summary/primitives/transfers/transfersStepSummaryFromRange.ts +0 -109
  290. package/src/summary/primitives/transfers/transfersSummary.ts +0 -52
  291. package/src/test/BuildBlockOptions.ts +0 -81
  292. package/src/test/buildBlock.ts +0 -105
  293. package/src/test/buildGenesisBlock.ts +0 -29
  294. package/src/test/buildNextBlock.ts +0 -37
  295. package/src/test/buildRandomChain.ts +0 -92
  296. package/src/test/buildRandomGenesisBlock.ts +0 -47
  297. package/src/test/createGenesisBlock.ts +0 -41
  298. package/src/test/createProducerChainStakeIntentTransaction.ts +0 -48
  299. package/src/test/getSimpleBlockViewerLocator.ts +0 -41
  300. package/src/test/getTestProviderContext.ts +0 -8
  301. package/src/test/index.ts +0 -2
  302. package/src/time/index.ts +0 -1
  303. package/src/time/primitives/index.ts +0 -1
  304. package/src/time/primitives/xl1BlockNumberToEthBlockNumber.ts +0 -13
  305. package/src/transaction/TransactionBuilder.ts +0 -164
  306. package/src/transaction/buildRandomTransaction.ts +0 -38
  307. package/src/transaction/buildTransaction.ts +0 -68
  308. package/src/transaction/buildUnsignedTransaction.ts +0 -56
  309. package/src/transaction/confirmSubmittedTransaction.ts +0 -42
  310. package/src/transaction/hydrateTransaction.ts +0 -117
  311. package/src/transaction/index.ts +0 -9
  312. package/src/transaction/primitives/index.ts +0 -4
  313. package/src/transaction/primitives/transactionBlockByteCount.ts +0 -10
  314. package/src/transaction/primitives/transactionElevatedPayloads.ts +0 -18
  315. package/src/transaction/primitives/transactionOperations.ts +0 -13
  316. package/src/transaction/primitives/transactionRequiredGas.ts +0 -22
  317. package/src/transaction/script.ts +0 -48
  318. package/src/transaction/signTransaction.ts +0 -32
  319. package/src/utils/HydratedCache.ts +0 -39
  320. package/src/utils/index.ts +0 -2
  321. package/src/utils/isZodError.ts +0 -11
  322. package/src/validation/index.ts +0 -2
  323. package/src/validation/lib/getUrl.ts +0 -7
  324. package/src/validation/lib/index.ts +0 -2
  325. package/src/validation/lib/isLocalhost.ts +0 -9
  326. package/src/validation/schema/Address.ts +0 -2
  327. package/src/validation/schema/Mnemonic.ts +0 -21
  328. package/src/validation/schema/index.ts +0 -2
  329. package/src/wallet/generateXyoBaseWalletFromPhrase.ts +0 -13
  330. package/src/wallet/index.ts +0 -2
  331. package/src/wallet/paths.ts +0 -17
@@ -1,13 +0,0 @@
1
- import type { Config } from '../../config/index.ts'
2
- import { ProviderFactoryLocator } from '../../CreatableProvider/index.ts'
3
- import type { CreatableProviderContext } from '../../model/index.ts'
4
-
5
- // This file should not be exported from the package
6
- export function getTestProviderContext(config: Config): CreatableProviderContext {
7
- const singletons = {}
8
- const caches = {}
9
- const locator = new ProviderFactoryLocator({
10
- config, singletons, caches, logger: console,
11
- })
12
- return locator.context
13
- }
@@ -1 +0,0 @@
1
- export * from './getTestProviderContext.ts'
@@ -1,2 +0,0 @@
1
- // _internal should never be exported from public barrel
2
- export * from './context/index.ts'
@@ -1,177 +0,0 @@
1
- import type {
2
- CreatableInstance, CreatableName, CreatableParams, CreatableStatusReporter, EmptyObject,
3
- Logger,
4
- } from '@xylabs/sdk-js'
5
- import {
6
- AbstractCreatable,
7
- assertEx,
8
- delay, IdLogger,
9
- } from '@xylabs/sdk-js'
10
- import type { AccountInstance } from '@xyo-network/sdk-js'
11
- import { Semaphore } from 'async-mutex'
12
- import z from 'zod'
13
-
14
- import type { ProviderFactoryLocatorInstance } from '../CreatableProvider/index.ts'
15
-
16
- const CreatableNameZod = z.custom<CreatableName>(val => typeof val === 'string' && val.length > 0)
17
- const StatusReporterInstanceZod = z.custom<CreatableStatusReporter>(val => val && typeof val === 'object' && 'report' in val)
18
- const AccountInstanceZod = z.custom<AccountInstance>(val => val && typeof val === 'object' && 'address' in val)
19
-
20
- /** ActorParamsV3Zod constant. */
21
- export const ActorParamsV3Zod = z.object({
22
- account: AccountInstanceZod,
23
- locator: z.unknown(),
24
- name: CreatableNameZod,
25
- statusReporter: StatusReporterInstanceZod.optional(),
26
- })
27
-
28
- /** ActorParamsV3Zod type. */
29
- export type ActorParamsV3Zod = z.infer<typeof ActorParamsV3Zod>
30
-
31
- /** ActorParamsV3 type. */
32
- export type ActorParamsV3<T extends EmptyObject | void = void> = CreatableParams & {
33
- account: AccountInstance
34
- locator: ProviderFactoryLocatorInstance
35
- } & (T extends void ? EmptyObject : T)
36
-
37
- /** ActorInstanceV3 type. */
38
- export type ActorInstanceV3<T extends ActorParamsV3 = ActorParamsV3> = CreatableInstance<T>
39
-
40
- /** ActorV3 implementation. */
41
- export abstract class ActorV3<TParams extends ActorParamsV3 = ActorParamsV3> extends AbstractCreatable<TParams> {
42
- protected readonly _intervals: Map<string, ReturnType<typeof setInterval>> = new Map()
43
- protected readonly _semaphores: Map<string, Semaphore> = new Map()
44
- protected readonly _timeouts: Map<string, ReturnType<typeof setTimeout>> = new Map()
45
-
46
- private _logger?: Logger
47
-
48
- override get logger() {
49
- this._logger = new IdLogger(assertEx(this.context.logger, () => `Logger is required in context for actor ${this.name}.`), () => this.name)
50
- return this._logger
51
- }
52
-
53
- protected get account() {
54
- return this.params.account
55
- }
56
-
57
- protected get context() {
58
- return this.locator.context
59
- }
60
-
61
- protected get locator() {
62
- return this.params.locator
63
- }
64
-
65
- static override async paramsHandler<T extends ActorInstanceV3>(params: Partial<T['params']>) {
66
- const baseParams = await super.paramsHandler({ ...params, name: params.name ?? 'UnknownActor' })
67
- const account = assertEx(params.account, () => `params.account is required for actor ${baseParams.name}.`)
68
- const locator = assertEx(params.locator, () => `params.locator is required for actor ${baseParams.name}.`)
69
- return {
70
- ...baseParams, account, locator,
71
- } satisfies ActorParamsV3
72
- }
73
-
74
- /**
75
- * The timer runs until the actor is deactivated (or you manually stop it).
76
- */
77
- registerTimer(timerName: string, callback: () => Promise<void>, dueTimeMs: number, periodMs: number) {
78
- if (this.status !== 'starting') {
79
- this.logger?.warn(
80
- `Cannot register timer '${timerName}' because actor is not starting.`,
81
- )
82
- return
83
- }
84
-
85
- let running = false
86
-
87
- this._semaphores.set(timerName, new Semaphore(1))
88
-
89
- const timeoutId = setTimeout(() => {
90
- const intervalId = setInterval(() => {
91
- const semaphore = this._semaphores.get(timerName)
92
- if (this.status !== 'started' || !this._intervals.has(timerName) || !semaphore || running) return
93
- if (semaphore.isLocked()) {
94
- this.logger?.warn(
95
- `Skipping timer '${this.name}:${timerName}' execution because previous execution is still running.`,
96
- )
97
- return
98
- }
99
- semaphore.acquire().then(([, release]) => {
100
- const startTime = Date.now()
101
- running = true
102
- callback()
103
- .then(() => {
104
- const duration = Date.now() - startTime
105
- if (duration > periodMs) {
106
- this.logger?.warn(
107
- `Timer '${this.name}:${timerName}' execution took longer (${duration}ms) than the period (${periodMs}ms).`,
108
- )
109
- } else if (duration > 5000) {
110
- this.logger?.warn(
111
- `Timer '${this.name}:${timerName}' execution took longer (${duration}ms) than 5000ms.`,
112
- )
113
- }
114
- })
115
- .catch((error) => {
116
- this.logger?.error(`Error in timer '${this.name}:${timerName}': ${error}`)
117
- this.logger?.error(error.stack)
118
- })
119
- .finally(() => {
120
- release()
121
- running = false
122
- })
123
- }).catch((error) => {
124
- this.logger?.error(`Error acquiring semaphore for timer '${this.name}:${timerName}': ${error}`)
125
- })
126
- }, periodMs)
127
-
128
- // store interval so we can clear it on stop()
129
- this._intervals.set(timerName, intervalId)
130
- }, dueTimeMs)
131
-
132
- // store timeout so we can clear it on stop() if interval hasn't started yet
133
- this._timeouts.set(timerName, timeoutId)
134
-
135
- this.logger?.log(
136
- `Timer '${this.name}:${timerName}' registered: first call after ${dueTimeMs}ms, recurring every ${periodMs}ms.`,
137
- )
138
- }
139
-
140
- /**
141
- * Called by the Orchestrator when the actor is deactivated.
142
- * Stop all running timers.
143
- */
144
- override async stopHandler() {
145
- await super.stopHandler()
146
- this.logger?.log('Stopping all timers...')
147
-
148
- // wait for all semaphores to be free and acquire them to prevent new tasks from starting
149
- await Promise.all(
150
- [...this._semaphores.values()].map(async (semaphore) => {
151
- // Wait for any running tasks to complete
152
- while (semaphore.isLocked()) {
153
- this.logger?.log('Waiting for running timer task to complete...')
154
- await delay(500)
155
- }
156
- await semaphore.acquire()
157
- }),
158
- )
159
-
160
- this._semaphores.clear()
161
-
162
- for (const [, timeoutRef] of this._timeouts.entries()) {
163
- clearTimeout(timeoutRef)
164
- }
165
- this._timeouts.clear()
166
-
167
- for (const [, intervalRef] of this._intervals.entries()) {
168
- clearInterval(intervalRef)
169
- }
170
- this._intervals.clear()
171
-
172
- this.logger?.log('Stopped.')
173
- }
174
- }
175
-
176
- /** Actor implementation. */
177
- export abstract class Actor<TParams extends ActorParamsV3 = ActorParamsV3> extends ActorV3<TParams> {}
@@ -1 +0,0 @@
1
- export * from './ActorV3.ts'
@@ -1,73 +0,0 @@
1
- import type { ShiftedBigIntConfig } from '@xyo-network/xl1-protocol-lib'
2
-
3
- import { splitOnDecimalToString } from './splitOnDecimalToString.ts'
4
-
5
- /** Represents a bigint with a fixed decimal point shift, supporting locale-aware string formatting */
6
- export class ShiftedBigInt {
7
- static readonly defaultConfig: ShiftedBigIntConfig = {
8
- places: 18,
9
- maxDecimal: 18,
10
- maxCharacters: 9,
11
- minDecimals: 1,
12
- locale: 'en-US',
13
- }
14
-
15
- config: ShiftedBigIntConfig
16
- value: bigint
17
-
18
- constructor(
19
- value: bigint | ShiftedBigInt,
20
- config: Partial<ShiftedBigIntConfig> = {},
21
- ) {
22
- this.value = typeof value === 'bigint' ? value : value.value
23
- this.config = {
24
- ...ShiftedBigInt.defaultConfig, ...(typeof value === 'bigint' ? {} : value.config), ...config,
25
- }
26
- }
27
-
28
- get locale(): Intl.LocalesArgument {
29
- return this.config.locale ?? 'en-US'
30
- }
31
-
32
- get maxCharacters(): number {
33
- return this.config.maxCharacters ?? 9
34
- }
35
-
36
- get maxDecimal(): number {
37
- return this.config.maxDecimal ?? this.places
38
- }
39
-
40
- get minDecimals(): number {
41
- return this.config.minDecimals ?? 1
42
- }
43
-
44
- get places(): number {
45
- return this.config.places ?? 18
46
- }
47
-
48
- toFullString(): string {
49
- return splitOnDecimalToString(
50
- this.value,
51
- this.places,
52
- this.places,
53
- Infinity,
54
- this.places,
55
- this.locale,
56
- )
57
- }
58
-
59
- toShortString(): string {
60
- return splitOnDecimalToString(
61
- this.value,
62
- this.places,
63
- this.maxDecimal,
64
- this.maxCharacters,
65
- this.minDecimals,
66
- this.locale,
67
- )
68
- }
69
-
70
- toString(): string {
71
- return this.toFullString()
72
- }
73
- }
@@ -1,103 +0,0 @@
1
- /* eslint-disable @typescript-eslint/member-ordering */
2
- import { assertEx } from '@xylabs/sdk-js'
3
- import type { ShiftedBigIntConfig, XL1AmountInstance } from '@xyo-network/xl1-protocol-lib'
4
- import {
5
- AttoXL1, FemtoXL1, MicroXL1, MilliXL1, NanoXL1, PicoXL1, XL1,
6
- XL1Places,
7
- } from '@xyo-network/xl1-protocol-lib'
8
-
9
- import { ShiftedBigInt } from './ShiftedBigInt.ts'
10
-
11
- const MAX_XL1_AMOUNT = 2n ** 256n - 1n
12
- const allowedPlaces = Object.values(XL1Places)
13
-
14
- /** Represents an XL1 token amount stored in AttoXL1, with conversions to milli, micro, nano, pico, femto, and atto denominations */
15
- export class XL1Amount implements XL1AmountInstance {
16
- value: AttoXL1
17
- private locale: Intl.LocalesArgument
18
-
19
- constructor(value: bigint, locale: Intl.LocalesArgument = 'en-US') {
20
- this.locale = locale
21
- this.value = AttoXL1(value > MAX_XL1_AMOUNT ? MAX_XL1_AMOUNT : value < 0n ? 0n : value)
22
- }
23
-
24
- static from(value: bigint, places: bigint = XL1Places.atto) {
25
- assertEx(allowedPlaces.includes(places), () => `Invalid conversion places (${places} not in ${allowedPlaces})`)
26
- return new XL1Amount(value * 10n ** BigInt(places))
27
- }
28
-
29
- static fromMilli(value: MilliXL1) {
30
- return this.from(value, XL1Places.milli)
31
- }
32
-
33
- static fromMicro(value: MicroXL1) {
34
- return this.from(value, XL1Places.micro)
35
- }
36
-
37
- static fromNano(value: NanoXL1) {
38
- return this.from(value, XL1Places.nano)
39
- }
40
-
41
- static fromPico(value: PicoXL1) {
42
- return this.from(value, XL1Places.pico)
43
- }
44
-
45
- static fromFemto(value: FemtoXL1) {
46
- return this.from(value, XL1Places.femto)
47
- }
48
-
49
- static fromAtto(value: AttoXL1) {
50
- return this.from(value, XL1Places.atto)
51
- }
52
-
53
- static fromXL1(value: XL1) {
54
- return this.from(value, XL1Places.xl1)
55
- }
56
-
57
- to(places: number | bigint = XL1Places.atto) {
58
- return this.value / 10n ** BigInt(places)
59
- }
60
-
61
- get milli() {
62
- return MilliXL1(this.to(XL1Places.milli))
63
- }
64
-
65
- get micro() {
66
- return MicroXL1(this.to(XL1Places.micro))
67
- }
68
-
69
- get nano() {
70
- return NanoXL1(this.to(XL1Places.nano))
71
- }
72
-
73
- get pico() {
74
- return PicoXL1(this.to(XL1Places.pico))
75
- }
76
-
77
- get femto() {
78
- return FemtoXL1(this.to(XL1Places.femto))
79
- }
80
-
81
- get atto() {
82
- return AttoXL1(this.to(XL1Places.atto))
83
- }
84
-
85
- get xl1() {
86
- return XL1(this.to(XL1Places.xl1))
87
- }
88
-
89
- toString(places: number = Number(XL1Places.atto), config: Partial<ShiftedBigIntConfig> = {}): string {
90
- assertEx(allowedPlaces.includes(BigInt(places)), () => `Invalid conversion places (${places} not in ${allowedPlaces})`)
91
- return new ShiftedBigInt(
92
- this.value,
93
- {
94
- places,
95
- locale: this.locale,
96
- maxDecimal: places,
97
- minDecimals: 0,
98
- maxCharacters: places,
99
- ...config,
100
- },
101
- ).toShortString()
102
- }
103
- }
@@ -1,4 +0,0 @@
1
- export * from './ShiftedBigInt.ts'
2
- export * from './splitOnDecimal.ts'
3
- export * from './splitOnDecimalToString.ts'
4
- export * from './XL1Amount.ts'
@@ -1,6 +0,0 @@
1
- /** Splits a bigint into whole and decimal parts based on the specified number of decimal places */
2
- export const splitOnDecimal = (value: bigint, places = 18): [bigint, bigint] => {
3
- const whole = value / BigInt(10 ** places)
4
- const decimal = value % BigInt(10 ** places)
5
- return [whole, decimal]
6
- }
@@ -1,40 +0,0 @@
1
- import { splitOnDecimal } from './splitOnDecimal.ts'
2
-
3
- /** Formats a bigint as a locale-aware decimal string with configurable precision and character limits */
4
- export const splitOnDecimalToString = (
5
- value: bigint,
6
- places = 18,
7
- maxDecimal = places,
8
- maxCharacters = 9,
9
- minDecimals = 1,
10
- locale: Intl.LocalesArgument = 'en-US',
11
- ): string => {
12
- const [whole, decimal] = splitOnDecimal(value, places)
13
- const remainderLength = decimal.toString().length
14
- const precedingZerosInDecimal = places - remainderLength
15
- if (whole === 0n && precedingZerosInDecimal >= maxDecimal && decimal !== 0n) return '< 0.'.padEnd(maxDecimal + 5, '0') + '1'
16
-
17
- const wholeCharacters = whole.toString(10).length
18
- const calcMaxDecimalCharacters = maxCharacters === -1 ? places : wholeCharacters > maxCharacters ? 0 : maxCharacters - wholeCharacters
19
- const maxDecimalCharacters = Math.min(maxDecimal, calcMaxDecimalCharacters)
20
-
21
- // Format whole number with thousand separators according to locale
22
- const formattedWhole = new Intl.NumberFormat(locale, {
23
- maximumFractionDigits: 0,
24
- useGrouping: true,
25
- }).format(whole)
26
-
27
- // Get decimal separator for the locale
28
- const decimalSeparator = new Intl.NumberFormat(locale)
29
- .formatToParts(1.1)
30
- .find(part => part.type === 'decimal')?.value ?? '.'
31
-
32
- // Pad decimal part to correct number of places
33
- let paddedDecimal = decimal.toString().padStart(places, '0').slice(0, maxDecimalCharacters)
34
- // remove unneeded trailing zeros (honoring minDecimals)
35
- while (paddedDecimal.length > minDecimals && paddedDecimal.endsWith('0')) {
36
- paddedDecimal = paddedDecimal.slice(0, -1)
37
- }
38
-
39
- return `${formattedWhole}${paddedDecimal.length > 0 ? decimalSeparator : ''}${paddedDecimal}`
40
- }
@@ -1,8 +0,0 @@
1
- import type { Hash } from '@xylabs/sdk-js'
2
- import type { Payload, WithHashMeta } from '@xyo-network/sdk-js'
3
-
4
- /** AllHashesPresent helper function. */
5
- export function allHashesPresent(hashes: Hash[], payloads: WithHashMeta<Payload>[]): boolean {
6
- const payloadHashes = new Set(payloads.map(p => p._hash))
7
- return hashes.every(hash => payloadHashes.has(hash))
8
- }
@@ -1,12 +0,0 @@
1
- import { assertEx } from '@xylabs/sdk-js'
2
- import type { WithStorageMeta } from '@xyo-network/sdk-js'
3
- import type { HydratedBlockWithStorageMeta } from '@xyo-network/xl1-protocol-lib'
4
- import { isTransactionBoundWitness } from '@xyo-network/xl1-protocol-lib'
5
-
6
- /** blockPayloadsFromHydratedBlock constant. */
7
- export const blockPayloadsFromHydratedBlock = (block: HydratedBlockWithStorageMeta): WithStorageMeta[] => {
8
- return block[0].payload_hashes.map(hash => assertEx(
9
- block[1].find(p => p._hash === hash),
10
- () => `missing payload ${hash}`,
11
- )).filter(x => !isTransactionBoundWitness(x))
12
- }
@@ -1,28 +0,0 @@
1
- import type { Payload } from '@xyo-network/sdk-js'
2
- import { type BlockBoundWitness, toHydratedBlock } from '@xyo-network/xl1-protocol-lib'
3
-
4
- /** flattenHydratedBlock constant. */
5
- export const flattenHydratedBlock = <B extends BlockBoundWitness, P extends Payload>(hydratedBlock: [B, P[]]): (P | B)[] => {
6
- const [blk, blkPayloads] = hydratedBlock
7
- return [...blkPayloads, blk]
8
- }
9
-
10
- /** tryUnflattenHydratedBlock constant. */
11
- export const tryUnflattenHydratedBlock = <
12
- B extends BlockBoundWitness,
13
- P extends Payload,
14
- >(flattened: (P | B)[]): [B, P[]] | undefined => {
15
- // Last element is the block
16
- const blk = flattened.at(-1) as B
17
-
18
- // All previous elements are payloads
19
- const payloads = flattened.slice(0, -1) as P[]
20
-
21
- return toHydratedBlock([blk, payloads])
22
- }
23
-
24
- /** unflattenHydratedBlock constant. */
25
- export const unflattenHydratedBlock = <
26
- B extends BlockBoundWitness,
27
- P extends Payload,
28
- >(flattened: (P | B)[]): [B, P[]] => toHydratedBlock(tryUnflattenHydratedBlock(flattened), true) as [B, P[]]
@@ -1,7 +0,0 @@
1
- import type { HydratedBlock } from '@xyo-network/xl1-protocol-lib'
2
-
3
- import { flattenHydratedBlock } from './flattenHydratedBlock.ts'
4
-
5
- /** flattenHydratedBlocks constant. */
6
- export const flattenHydratedBlocks = <T extends HydratedBlock>(hydratedBlocks: T[]): (T[0] | T[1][number])[] =>
7
- hydratedBlocks.flatMap(blk => flattenHydratedBlock(blk))
@@ -1,43 +0,0 @@
1
- import type { Hash } from '@xylabs/sdk-js'
2
- import { assertEx } from '@xylabs/sdk-js'
3
- import { asAnyPayload } from '@xyo-network/sdk-js'
4
- import type { BlockContextRead, HydratedBlockWithStorageMeta } from '@xyo-network/xl1-protocol-lib'
5
- import { asBlockBoundWitnessWithStorageMeta, isTransactionBoundWitnessWithStorageMeta } from '@xyo-network/xl1-protocol-lib'
6
-
7
- import { allHashesPresent } from './allHashesPresent.ts'
8
-
9
- /** hydrateBlock constant. */
10
- export const hydrateBlock = async (
11
- context: BlockContextRead,
12
- hash: Hash,
13
- maxDepth: number = 1,
14
- minDepth = maxDepth,
15
- ): Promise<HydratedBlockWithStorageMeta> => {
16
- assertEx(maxDepth >= 0, () => 'maxDepth must be greater than or equal to 0')
17
- assertEx(minDepth >= 0, () => 'minDepth must be greater than or equal to 0')
18
- assertEx(maxDepth >= minDepth, () => 'maxDepth must be greater than or equal to minDepth')
19
-
20
- const { chainMap } = context
21
-
22
- const [block] = await chainMap.get([hash])
23
- const bw = assertEx(asBlockBoundWitnessWithStorageMeta(
24
- assertEx(block, () => `block ${hash} not found`),
25
- ), () => `hash ${hash} is not a BlockBoundWitness`)
26
-
27
- if (maxDepth === 0) return [bw, []]
28
- const blkPayloads = (await chainMap.get(bw.payload_hashes)).map(p => asAnyPayload(p, true))
29
- if (minDepth === 1) assertEx(allHashesPresent(bw.payload_hashes, blkPayloads), () => `Unable to find all payloads for block ${hash}`)
30
- if (maxDepth === 1) return [bw, blkPayloads]
31
- const transactions = blkPayloads.filter(isTransactionBoundWitnessWithStorageMeta)
32
- const transactionsPayloadHashes = transactions.flatMap(tx => tx.payload_hashes)
33
- const transactionsPayloads = (await chainMap.get(transactionsPayloadHashes)).map(p => asAnyPayload(p, true))
34
- assertEx(allHashesPresent(transactionsPayloadHashes, transactionsPayloads), () => `Unable to find all payloads for transactions in block ${hash}`)
35
- const allPayloadsHashes = new Set([...blkPayloads, ...transactionsPayloads].flatMap(p => p._hash))
36
- const allPayloads = (await chainMap.get([...allPayloadsHashes])).map(p => asAnyPayload(p, true))
37
- const allPayloadsFiltered = allPayloads.filter(p => allPayloadsHashes.has(p._hash))
38
- if (maxDepth === 2) assertEx(allHashesPresent(
39
- [...allPayloadsHashes],
40
- allPayloadsFiltered,
41
- ), () => `Unable to find all payloads for transactions in block ${hash}`)
42
- return [bw, allPayloadsFiltered]
43
- }
@@ -1,7 +0,0 @@
1
- export * from './allHashesPresent.ts'
2
- export * from './blockPayloadsFromHydratedBlock.ts'
3
- export * from './flattenHydratedBlock.ts'
4
- export * from './flattenHydratedBlocks.ts'
5
- export * from './hydrateBlock.ts'
6
- export * from './transactionsFromHydratedBlock.ts'
7
- export * from './tryHydrateBlock.ts'
@@ -1,7 +0,0 @@
1
- import type { HydratedBlock, TransactionBoundWitnessWithStorageMeta } from '@xyo-network/xl1-protocol-lib'
2
- import { isTransactionBoundWitnessWithStorageMeta } from '@xyo-network/xl1-protocol-lib'
3
-
4
- /** transactionsFromHydratedBlock constant. */
5
- export const transactionsFromHydratedBlock = (block: HydratedBlock): TransactionBoundWitnessWithStorageMeta[] => {
6
- return block[1].filter(isTransactionBoundWitnessWithStorageMeta)
7
- }
@@ -1,26 +0,0 @@
1
- import type { Hash } from '@xylabs/sdk-js'
2
- import { assertEx } from '@xylabs/sdk-js'
3
- import type { ReadArchivist } from '@xyo-network/sdk-js'
4
- import type { HydratedBlock } from '@xyo-network/xl1-protocol-lib'
5
- import { isBlockBoundWitnessWithStorageMeta, isTransactionBoundWitnessWithStorageMeta } from '@xyo-network/xl1-protocol-lib'
6
-
7
- /** tryHydrateBlock constant. */
8
- export const tryHydrateBlock = async (
9
- archivist: ReadArchivist,
10
- hash: Hash,
11
- maxDepth: number = 1,
12
- ): Promise<HydratedBlock | undefined> => {
13
- assertEx(maxDepth >= 0, () => 'maxDepth must be greater than or equal to 0')
14
- const bw = (await archivist.get([hash])).find(isBlockBoundWitnessWithStorageMeta)
15
- if (!bw) return undefined
16
- if (maxDepth === 0) return [bw, []]
17
- const blkPayloads = await archivist.get(bw.payload_hashes)
18
- if (maxDepth === 1) return [bw, blkPayloads]
19
- const transactions = blkPayloads.filter(isTransactionBoundWitnessWithStorageMeta)
20
- const transactionsPayloadHashes = transactions.flatMap(tx => tx.payload_hashes)
21
- const transactionsPayloads = await archivist.get(transactionsPayloadHashes)
22
- const allPayloadsHashes = new Set([...blkPayloads, ...transactionsPayloads].flatMap(p => p._hash))
23
- const allPayloads = await archivist.get([...allPayloadsHashes])
24
- const allPayloadsFiltered = allPayloads.filter(p => allPayloadsHashes.has(p._hash))
25
- return [bw, allPayloadsFiltered]
26
- }
@@ -1,2 +0,0 @@
1
- export * from './hydrate/index.ts'
2
- export * from './primitives/index.ts'
@@ -1,69 +0,0 @@
1
- import {
2
- asHash, type Hash, isDefined,
3
- spanAsync,
4
- } from '@xylabs/sdk-js'
5
- import { toSafeJsonString } from '@xylabs/sdk-js'
6
- import type { Signed, WithHashMeta } from '@xyo-network/sdk-js'
7
- import type {
8
- BlockBoundWitness, ChainContextRead, XL1BlockNumber,
9
- } from '@xyo-network/xl1-protocol-lib'
10
- import {
11
- asSignedBlockBoundWitnessWithStorageMeta, SignedBlockBoundWitnessWithHashMetaZod, StepSizes,
12
- } from '@xyo-network/xl1-protocol-lib'
13
-
14
- import { withContextCacheResponse } from '../../ChainContextHelpers.ts'
15
-
16
- /** BlockFromBlockNumber helper function. */
17
- export async function blockFromBlockNumber(
18
- context: ChainContextRead,
19
- blockNumber: XL1BlockNumber,
20
- ): Promise<WithHashMeta<Signed<BlockBoundWitness>>> {
21
- return await spanAsync('blockFromBlockNumber', async () => {
22
- const cacheKey = `${blockNumber}`
23
- const { chainMap, head } = context
24
- return await withContextCacheResponse(context, 'blockFromBlockNumber', cacheKey, async () => {
25
- const [result] = await chainMap.get([head._hash])
26
- if (!isDefined(result)) {
27
- throw new Error(`Head block not found for hash: ${head._hash}`)
28
- }
29
- let currentBlock = asSignedBlockBoundWitnessWithStorageMeta(
30
- result,
31
- () => `Found Payload is not a Signed<BlockBoundWitness>: ${JSON.stringify(result, null, 2)}`,
32
- )
33
- if (currentBlock.block < blockNumber) {
34
- throw new Error(`Block number ${blockNumber} is greater than head ${currentBlock.block}.`)
35
- }
36
- while (currentBlock.block > blockNumber) {
37
- let jumpHash: Hash | null = currentBlock.previous
38
- let jumpBlockNumber = currentBlock.block - 1
39
- for (const [step, stepSize] of StepSizes.entries()) {
40
- const possibleJumpBlockNumber = currentBlock.block - (currentBlock.block % stepSize) - 1
41
- if (possibleJumpBlockNumber >= blockNumber && possibleJumpBlockNumber <= jumpBlockNumber) {
42
- jumpBlockNumber = possibleJumpBlockNumber
43
- jumpHash = asHash(currentBlock.step_hashes?.at(step), () => `Step hash not found for step ${step} in block ${currentBlock.block}`)
44
- }
45
- }
46
- const [newBlock] = await chainMap.get([
47
- asHash(jumpHash, () => `Jump hash not found for block number [${blockNumber}]: ${jumpBlockNumber} ${toSafeJsonString(currentBlock, 10)}`),
48
- ])
49
- if (!isDefined(newBlock)) {
50
- throw new Error(`Block not found for jump hash: ${jumpHash}`)
51
- }
52
- currentBlock = asSignedBlockBoundWitnessWithStorageMeta(
53
- newBlock,
54
- () => {
55
- const result = SignedBlockBoundWitnessWithHashMetaZod.safeParse(newBlock)
56
- return `Found Payload [jump hash] is not a Signed<BlockBoundWitness>: ${result.error}`
57
- },
58
- )
59
- if (currentBlock.block === blockNumber) {
60
- break
61
- }
62
- if (currentBlock.block < blockNumber) {
63
- throw new Error(`Block number ${blockNumber} is not a valid step block number for block ${head._hash}.`)
64
- }
65
- }
66
- return currentBlock
67
- })
68
- }, { ...context, timeBudgetLimit: 500 })
69
- }