From 3398a549fbfcf9a90bd253b60db9db6d59fcceaf Mon Sep 17 00:00:00 2001 From: Eyal Chojnowski Date: Tue, 28 Nov 2023 14:45:17 +0100 Subject: [PATCH] :floppy_disk: Commit build files --- .gitignore | 6 +- bundles/web.bundle.min.js | 142 +++ bundles/web.iife.bundle.min.js | 142 +++ lib/cjs/cache/BasicSortKeyCache.js | 3 + lib/cjs/cache/BasicSortKeyCache.js.map | 1 + lib/cjs/cache/SortKeyCache.js | 18 + lib/cjs/cache/SortKeyCache.js.map | 1 + lib/cjs/cache/SortKeyCacheRangeOptions.js | 3 + lib/cjs/cache/SortKeyCacheRangeOptions.js.map | 1 + lib/cjs/cache/WarpCache.js | 12 + lib/cjs/cache/WarpCache.js.map | 1 + lib/cjs/cache/impl/LevelDbCache.js | 316 +++++ lib/cjs/cache/impl/LevelDbCache.js.map | 1 + lib/cjs/cache/impl/MemCache.js | 30 + lib/cjs/cache/impl/MemCache.js.map | 1 + lib/cjs/common/SimpleLRUCache.js | 38 + lib/cjs/common/SimpleLRUCache.js.map | 1 + lib/cjs/contract/Contract.js | 3 + lib/cjs/contract/Contract.js.map | 1 + .../contract/EvaluationOptionsEvaluator.js | 191 +++ .../EvaluationOptionsEvaluator.js.map | 1 + lib/cjs/contract/HandlerBasedContract.js | 712 ++++++++++++ lib/cjs/contract/HandlerBasedContract.js.map | 1 + lib/cjs/contract/InnerWritesEvaluator.js | 31 + lib/cjs/contract/InnerWritesEvaluator.js.map | 1 + lib/cjs/contract/PstContract.js | 3 + lib/cjs/contract/PstContract.js.map | 1 + lib/cjs/contract/PstContractImpl.js | 21 + lib/cjs/contract/PstContractImpl.js.map | 1 + lib/cjs/contract/Signature.js | 127 ++ lib/cjs/contract/Signature.js.map | 1 + lib/cjs/contract/deploy/CreateContract.js | 9 + lib/cjs/contract/deploy/CreateContract.js.map | 1 + lib/cjs/contract/deploy/Source.js | 3 + lib/cjs/contract/deploy/Source.js.map | 1 + .../states/ContractInteractionState.js | 147 +++ .../states/ContractInteractionState.js.map | 1 + lib/cjs/contract/states/InteractionState.js | 3 + .../contract/states/InteractionState.js.map | 1 + lib/cjs/contract/testing/Testing.js | 33 + lib/cjs/contract/testing/Testing.js.map | 1 + lib/cjs/core/ContractCallRecord.js | 67 ++ lib/cjs/core/ContractCallRecord.js.map | 1 + lib/cjs/core/ContractDefinition.js | 35 + lib/cjs/core/ContractDefinition.js.map | 1 + lib/cjs/core/ExecutionContext.js | 3 + lib/cjs/core/ExecutionContext.js.map | 1 + lib/cjs/core/ExecutionContextModifier.js | 3 + lib/cjs/core/ExecutionContextModifier.js.map | 1 + lib/cjs/core/KnownTags.js | 44 + lib/cjs/core/KnownTags.js.map | 1 + lib/cjs/core/Warp.js | 156 +++ lib/cjs/core/Warp.js.map | 1 + lib/cjs/core/WarpBuilder.js | 68 ++ lib/cjs/core/WarpBuilder.js.map | 1 + lib/cjs/core/WarpFactory.js | 113 ++ lib/cjs/core/WarpFactory.js.map | 1 + lib/cjs/core/WarpFetchWrapper.js | 34 + lib/cjs/core/WarpFetchWrapper.js.map | 1 + lib/cjs/core/WarpPlugin.js | 16 + lib/cjs/core/WarpPlugin.js.map | 1 + lib/cjs/core/modules/DefinitionLoader.js | 3 + lib/cjs/core/modules/DefinitionLoader.js.map | 1 + lib/cjs/core/modules/ExecutorFactory.js | 3 + lib/cjs/core/modules/ExecutorFactory.js.map | 1 + lib/cjs/core/modules/InteractionsLoader.js | 3 + .../core/modules/InteractionsLoader.js.map | 1 + lib/cjs/core/modules/InteractionsSorter.js | 3 + .../core/modules/InteractionsSorter.js.map | 1 + lib/cjs/core/modules/StateEvaluator.js | 68 ++ lib/cjs/core/modules/StateEvaluator.js.map | 1 + .../core/modules/impl/ArweaveGQLTxsFetcher.js | 148 +++ .../modules/impl/ArweaveGQLTxsFetcher.js.map | 1 + ...eGatewayBundledContractDefinitionLoader.js | 165 +++ ...ewayBundledContractDefinitionLoader.js.map | 1 + .../ArweaveGatewayBundledInteractionLoader.js | 212 ++++ ...eaveGatewayBundledInteractionLoader.js.map | 1 + .../impl/ArweaveGatewayInteractionsLoader.js | 124 ++ .../ArweaveGatewayInteractionsLoader.js.map | 1 + .../impl/CacheableInteractionsLoader.js | 49 + .../impl/CacheableInteractionsLoader.js.map | 1 + .../modules/impl/CacheableStateEvaluator.js | 154 +++ .../impl/CacheableStateEvaluator.js.map | 1 + .../modules/impl/ContractDefinitionLoader.js | 137 +++ .../impl/ContractDefinitionLoader.js.map | 1 + .../modules/impl/DefaultStateEvaluator.js | 303 +++++ .../modules/impl/DefaultStateEvaluator.js.map | 1 + .../modules/impl/HandlerExecutorFactory.js | 202 ++++ .../impl/HandlerExecutorFactory.js.map | 1 + .../impl/LexicographicalInteractionsSorter.js | 59 + .../LexicographicalInteractionsSorter.js.map | 1 + lib/cjs/core/modules/impl/TagsParser.js | 107 ++ lib/cjs/core/modules/impl/TagsParser.js.map | 1 + .../WarpGatewayContractDefinitionLoader.js | 134 +++ ...WarpGatewayContractDefinitionLoader.js.map | 1 + .../impl/WarpGatewayInteractionsLoader.js | 91 ++ .../impl/WarpGatewayInteractionsLoader.js.map | 1 + .../impl/handler/AbstractContractHandler.js | 133 +++ .../handler/AbstractContractHandler.js.map | 1 + .../core/modules/impl/handler/JsHandlerApi.js | 193 +++ .../modules/impl/handler/JsHandlerApi.js.map | 1 + .../modules/impl/handler/WasmHandlerApi.js | 166 +++ .../impl/handler/WasmHandlerApi.js.map | 1 + lib/cjs/core/modules/impl/normalize-source.js | 56 + .../core/modules/impl/normalize-source.js.map | 1 + lib/cjs/core/modules/impl/wasm/WasmSrc.js | 71 ++ lib/cjs/core/modules/impl/wasm/WasmSrc.js.map | 1 + .../modules/impl/wasm/rust-wasm-imports.js | 1035 +++++++++++++++++ .../impl/wasm/rust-wasm-imports.js.map | 1 + .../modules/impl/wasm/wasm-bindgen-tools.js | 10 + .../impl/wasm/wasm-bindgen-tools.js.map | 1 + lib/cjs/index.js | 79 ++ lib/cjs/index.js.map | 1 + lib/cjs/legacy/create-interaction-tx.js | 103 ++ lib/cjs/legacy/create-interaction-tx.js.map | 1 + lib/cjs/legacy/errors.js | 24 + lib/cjs/legacy/errors.js.map | 1 + lib/cjs/legacy/gqlResult.js | 3 + lib/cjs/legacy/gqlResult.js.map | 1 + lib/cjs/legacy/smartweave-global.js | 262 +++++ lib/cjs/legacy/smartweave-global.js.map | 1 + lib/cjs/legacy/utils.js | 12 + lib/cjs/legacy/utils.js.map | 1 + lib/cjs/logging/Benchmark.js | 29 + lib/cjs/logging/Benchmark.js.map | 1 + lib/cjs/logging/LoggerFactory.js | 29 + lib/cjs/logging/LoggerFactory.js.map | 1 + lib/cjs/logging/LoggerSettings.js | 18 + lib/cjs/logging/LoggerSettings.js.map | 1 + lib/cjs/logging/WarpLogger.js | 3 + lib/cjs/logging/WarpLogger.js.map | 1 + lib/cjs/logging/web/ConsoleLogger.js | 64 + lib/cjs/logging/web/ConsoleLogger.js.map | 1 + lib/cjs/logging/web/ConsoleLoggerFactory.js | 78 ++ .../logging/web/ConsoleLoggerFactory.js.map | 1 + lib/cjs/plugins/DebuggableExecutorFactor.js | 32 + .../plugins/DebuggableExecutorFactor.js.map | 1 + lib/cjs/plugins/Evolve.js | 106 ++ lib/cjs/plugins/Evolve.js.map | 1 + lib/cjs/utils/ArweaveWrapper.js | 104 ++ lib/cjs/utils/ArweaveWrapper.js.map | 1 + lib/cjs/utils/types/arweave-types.js | 149 +++ lib/cjs/utils/types/arweave-types.js.map | 1 + lib/cjs/utils/utils.js | 124 ++ lib/cjs/utils/utils.js.map | 1 + lib/mjs/index.js | 105 ++ lib/mjs/package.json | 3 + lib/types/cache/BasicSortKeyCache.d.ts | 58 + lib/types/cache/BasicSortKeyCache.d.ts.map | 1 + lib/types/cache/SortKeyCache.d.ts | 56 + lib/types/cache/SortKeyCache.d.ts.map | 1 + lib/types/cache/SortKeyCacheRangeOptions.d.ts | 14 + .../cache/SortKeyCacheRangeOptions.d.ts.map | 1 + lib/types/cache/WarpCache.d.ts | 32 + lib/types/cache/WarpCache.d.ts.map | 1 + lib/types/cache/impl/LevelDbCache.d.ts | 74 ++ lib/types/cache/impl/LevelDbCache.d.ts.map | 1 + lib/types/cache/impl/MemCache.d.ts | 13 + lib/types/cache/impl/MemCache.d.ts.map | 1 + lib/types/common/SimpleLRUCache.d.ts | 11 + lib/types/common/SimpleLRUCache.d.ts.map | 1 + lib/types/contract/Contract.d.ts | 209 ++++ lib/types/contract/Contract.d.ts.map | 1 + .../contract/EvaluationOptionsEvaluator.d.ts | 70 ++ .../EvaluationOptionsEvaluator.d.ts.map | 1 + lib/types/contract/HandlerBasedContract.d.ts | 90 ++ .../contract/HandlerBasedContract.d.ts.map | 1 + lib/types/contract/InnerWritesEvaluator.d.ts | 6 + .../contract/InnerWritesEvaluator.d.ts.map | 1 + lib/types/contract/PstContract.d.ts | 47 + lib/types/contract/PstContract.d.ts.map | 1 + lib/types/contract/PstContractImpl.d.ts | 9 + lib/types/contract/PstContractImpl.d.ts.map | 1 + lib/types/contract/Signature.d.ts | 38 + lib/types/contract/Signature.d.ts.map | 1 + lib/types/contract/deploy/CreateContract.d.ts | 88 ++ .../contract/deploy/CreateContract.d.ts.map | 1 + lib/types/contract/deploy/Source.d.ts | 34 + lib/types/contract/deploy/Source.d.ts.map | 1 + .../states/ContractInteractionState.d.ts | 32 + .../states/ContractInteractionState.d.ts.map | 1 + .../contract/states/InteractionState.d.ts | 43 + .../contract/states/InteractionState.d.ts.map | 1 + lib/types/contract/testing/Testing.d.ts | 15 + lib/types/contract/testing/Testing.d.ts.map | 1 + lib/types/core/ContractCallRecord.d.ts | 48 + lib/types/core/ContractCallRecord.d.ts.map | 1 + lib/types/core/ContractDefinition.d.ts | 39 + lib/types/core/ContractDefinition.d.ts.map | 1 + lib/types/core/ExecutionContext.d.ts | 46 + lib/types/core/ExecutionContext.d.ts.map | 1 + lib/types/core/ExecutionContextModifier.d.ts | 10 + .../core/ExecutionContextModifier.d.ts.map | 1 + lib/types/core/KnownTags.d.ts | 45 + lib/types/core/KnownTags.d.ts.map | 1 + lib/types/core/Warp.d.ts | 82 ++ lib/types/core/Warp.d.ts.map | 1 + lib/types/core/WarpBuilder.d.ts | 30 + lib/types/core/WarpBuilder.d.ts.map | 1 + lib/types/core/WarpFactory.d.ts | 65 ++ lib/types/core/WarpFactory.d.ts.map | 1 + lib/types/core/WarpFetchWrapper.d.ts | 13 + lib/types/core/WarpFetchWrapper.d.ts.map | 1 + lib/types/core/WarpPlugin.d.ts | 16 + lib/types/core/WarpPlugin.d.ts.map | 1 + lib/types/core/modules/DefinitionLoader.d.ts | 18 + .../core/modules/DefinitionLoader.d.ts.map | 1 + lib/types/core/modules/ExecutorFactory.d.ts | 15 + .../core/modules/ExecutorFactory.d.ts.map | 1 + .../core/modules/InteractionsLoader.d.ts | 26 + .../core/modules/InteractionsLoader.d.ts.map | 1 + .../core/modules/InteractionsSorter.d.ts | 21 + .../core/modules/InteractionsSorter.d.ts.map | 1 + lib/types/core/modules/StateEvaluator.d.ts | 124 ++ .../core/modules/StateEvaluator.d.ts.map | 1 + .../modules/impl/ArweaveGQLTxsFetcher.d.ts | 34 + .../impl/ArweaveGQLTxsFetcher.d.ts.map | 1 + ...atewayBundledContractDefinitionLoader.d.ts | 26 + ...ayBundledContractDefinitionLoader.d.ts.map | 1 + ...rweaveGatewayBundledInteractionLoader.d.ts | 43 + ...veGatewayBundledInteractionLoader.d.ts.map | 1 + .../ArweaveGatewayInteractionsLoader.d.ts | 21 + .../ArweaveGatewayInteractionsLoader.d.ts.map | 1 + .../impl/CacheableInteractionsLoader.d.ts | 15 + .../impl/CacheableInteractionsLoader.d.ts.map | 1 + .../modules/impl/CacheableStateEvaluator.d.ts | 37 + .../impl/CacheableStateEvaluator.d.ts.map | 1 + .../impl/ContractDefinitionLoader.d.ts | 26 + .../impl/ContractDefinitionLoader.d.ts.map | 1 + .../modules/impl/DefaultStateEvaluator.d.ts | 40 + .../impl/DefaultStateEvaluator.d.ts.map | 1 + .../modules/impl/HandlerExecutorFactory.d.ts | 81 ++ .../impl/HandlerExecutorFactory.d.ts.map | 1 + .../LexicographicalInteractionsSorter.d.ts | 22 + ...LexicographicalInteractionsSorter.d.ts.map | 1 + lib/types/core/modules/impl/TagsParser.d.ts | 25 + .../core/modules/impl/TagsParser.d.ts.map | 1 + .../WarpGatewayContractDefinitionLoader.d.ts | 38 + ...rpGatewayContractDefinitionLoader.d.ts.map | 1 + .../impl/WarpGatewayInteractionsLoader.d.ts | 46 + .../WarpGatewayInteractionsLoader.d.ts.map | 1 + .../impl/handler/AbstractContractHandler.d.ts | 21 + .../handler/AbstractContractHandler.d.ts.map | 1 + .../modules/impl/handler/JsHandlerApi.d.ts | 25 + .../impl/handler/JsHandlerApi.d.ts.map | 1 + .../modules/impl/handler/WasmHandlerApi.d.ts | 17 + .../impl/handler/WasmHandlerApi.d.ts.map | 1 + .../core/modules/impl/normalize-source.d.ts | 4 + .../modules/impl/normalize-source.d.ts.map | 1 + lib/types/core/modules/impl/wasm/WasmSrc.d.ts | 12 + .../core/modules/impl/wasm/WasmSrc.d.ts.map | 1 + .../modules/impl/wasm/rust-wasm-imports.d.ts | 3 + .../impl/wasm/rust-wasm-imports.d.ts.map | 1 + .../modules/impl/wasm/wasm-bindgen-tools.d.ts | 2 + .../impl/wasm/wasm-bindgen-tools.d.ts.map | 1 + lib/types/index.d.ts | 63 + lib/types/index.d.ts.map | 1 + lib/types/legacy/create-interaction-tx.d.ts | 9 + .../legacy/create-interaction-tx.d.ts.map | 1 + lib/types/legacy/errors.d.ts | 15 + lib/types/legacy/errors.d.ts.map | 1 + lib/types/legacy/gqlResult.d.ts | 92 ++ lib/types/legacy/gqlResult.d.ts.map | 1 + lib/types/legacy/smartweave-global.d.ts | 110 ++ lib/types/legacy/smartweave-global.d.ts.map | 1 + lib/types/legacy/utils.d.ts | 2 + lib/types/legacy/utils.d.ts.map | 1 + lib/types/logging/Benchmark.d.ts | 10 + lib/types/logging/Benchmark.d.ts.map | 1 + lib/types/logging/LoggerFactory.d.ts | 18 + lib/types/logging/LoggerFactory.d.ts.map | 1 + lib/types/logging/LoggerSettings.d.ts | 19 + lib/types/logging/LoggerSettings.d.ts.map | 1 + lib/types/logging/WarpLogger.d.ts | 10 + lib/types/logging/WarpLogger.d.ts.map | 1 + lib/types/logging/web/ConsoleLogger.d.ts | 19 + lib/types/logging/web/ConsoleLogger.d.ts.map | 1 + .../logging/web/ConsoleLoggerFactory.d.ts | 14 + .../logging/web/ConsoleLoggerFactory.d.ts.map | 1 + .../plugins/DebuggableExecutorFactor.d.ts | 22 + .../plugins/DebuggableExecutorFactor.d.ts.map | 1 + lib/types/plugins/Evolve.d.ts | 10 + lib/types/plugins/Evolve.d.ts.map | 1 + lib/types/utils/ArweaveWrapper.d.ts | 27 + lib/types/utils/ArweaveWrapper.d.ts.map | 1 + lib/types/utils/types/arweave-types.d.ts | 160 +++ lib/types/utils/types/arweave-types.d.ts.map | 1 + lib/types/utils/utils.d.ts | 25 + lib/types/utils/utils.d.ts.map | 1 + 289 files changed, 10325 insertions(+), 5 deletions(-) create mode 100644 bundles/web.bundle.min.js create mode 100644 bundles/web.iife.bundle.min.js create mode 100644 lib/cjs/cache/BasicSortKeyCache.js create mode 100644 lib/cjs/cache/BasicSortKeyCache.js.map create mode 100644 lib/cjs/cache/SortKeyCache.js create mode 100644 lib/cjs/cache/SortKeyCache.js.map create mode 100644 lib/cjs/cache/SortKeyCacheRangeOptions.js create mode 100644 lib/cjs/cache/SortKeyCacheRangeOptions.js.map create mode 100644 lib/cjs/cache/WarpCache.js create mode 100644 lib/cjs/cache/WarpCache.js.map create mode 100644 lib/cjs/cache/impl/LevelDbCache.js create mode 100644 lib/cjs/cache/impl/LevelDbCache.js.map create mode 100644 lib/cjs/cache/impl/MemCache.js create mode 100644 lib/cjs/cache/impl/MemCache.js.map create mode 100644 lib/cjs/common/SimpleLRUCache.js create mode 100644 lib/cjs/common/SimpleLRUCache.js.map create mode 100644 lib/cjs/contract/Contract.js create mode 100644 lib/cjs/contract/Contract.js.map create mode 100644 lib/cjs/contract/EvaluationOptionsEvaluator.js create mode 100644 lib/cjs/contract/EvaluationOptionsEvaluator.js.map create mode 100644 lib/cjs/contract/HandlerBasedContract.js create mode 100644 lib/cjs/contract/HandlerBasedContract.js.map create mode 100644 lib/cjs/contract/InnerWritesEvaluator.js create mode 100644 lib/cjs/contract/InnerWritesEvaluator.js.map create mode 100644 lib/cjs/contract/PstContract.js create mode 100644 lib/cjs/contract/PstContract.js.map create mode 100644 lib/cjs/contract/PstContractImpl.js create mode 100644 lib/cjs/contract/PstContractImpl.js.map create mode 100644 lib/cjs/contract/Signature.js create mode 100644 lib/cjs/contract/Signature.js.map create mode 100644 lib/cjs/contract/deploy/CreateContract.js create mode 100644 lib/cjs/contract/deploy/CreateContract.js.map create mode 100644 lib/cjs/contract/deploy/Source.js create mode 100644 lib/cjs/contract/deploy/Source.js.map create mode 100644 lib/cjs/contract/states/ContractInteractionState.js create mode 100644 lib/cjs/contract/states/ContractInteractionState.js.map create mode 100644 lib/cjs/contract/states/InteractionState.js create mode 100644 lib/cjs/contract/states/InteractionState.js.map create mode 100644 lib/cjs/contract/testing/Testing.js create mode 100644 lib/cjs/contract/testing/Testing.js.map create mode 100644 lib/cjs/core/ContractCallRecord.js create mode 100644 lib/cjs/core/ContractCallRecord.js.map create mode 100644 lib/cjs/core/ContractDefinition.js create mode 100644 lib/cjs/core/ContractDefinition.js.map create mode 100644 lib/cjs/core/ExecutionContext.js create mode 100644 lib/cjs/core/ExecutionContext.js.map create mode 100644 lib/cjs/core/ExecutionContextModifier.js create mode 100644 lib/cjs/core/ExecutionContextModifier.js.map create mode 100644 lib/cjs/core/KnownTags.js create mode 100644 lib/cjs/core/KnownTags.js.map create mode 100644 lib/cjs/core/Warp.js create mode 100644 lib/cjs/core/Warp.js.map create mode 100644 lib/cjs/core/WarpBuilder.js create mode 100644 lib/cjs/core/WarpBuilder.js.map create mode 100644 lib/cjs/core/WarpFactory.js create mode 100644 lib/cjs/core/WarpFactory.js.map create mode 100644 lib/cjs/core/WarpFetchWrapper.js create mode 100644 lib/cjs/core/WarpFetchWrapper.js.map create mode 100644 lib/cjs/core/WarpPlugin.js create mode 100644 lib/cjs/core/WarpPlugin.js.map create mode 100644 lib/cjs/core/modules/DefinitionLoader.js create mode 100644 lib/cjs/core/modules/DefinitionLoader.js.map create mode 100644 lib/cjs/core/modules/ExecutorFactory.js create mode 100644 lib/cjs/core/modules/ExecutorFactory.js.map create mode 100644 lib/cjs/core/modules/InteractionsLoader.js create mode 100644 lib/cjs/core/modules/InteractionsLoader.js.map create mode 100644 lib/cjs/core/modules/InteractionsSorter.js create mode 100644 lib/cjs/core/modules/InteractionsSorter.js.map create mode 100644 lib/cjs/core/modules/StateEvaluator.js create mode 100644 lib/cjs/core/modules/StateEvaluator.js.map create mode 100644 lib/cjs/core/modules/impl/ArweaveGQLTxsFetcher.js create mode 100644 lib/cjs/core/modules/impl/ArweaveGQLTxsFetcher.js.map create mode 100644 lib/cjs/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.js create mode 100644 lib/cjs/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.js.map create mode 100644 lib/cjs/core/modules/impl/ArweaveGatewayBundledInteractionLoader.js create mode 100644 lib/cjs/core/modules/impl/ArweaveGatewayBundledInteractionLoader.js.map create mode 100644 lib/cjs/core/modules/impl/ArweaveGatewayInteractionsLoader.js create mode 100644 lib/cjs/core/modules/impl/ArweaveGatewayInteractionsLoader.js.map create mode 100644 lib/cjs/core/modules/impl/CacheableInteractionsLoader.js create mode 100644 lib/cjs/core/modules/impl/CacheableInteractionsLoader.js.map create mode 100644 lib/cjs/core/modules/impl/CacheableStateEvaluator.js create mode 100644 lib/cjs/core/modules/impl/CacheableStateEvaluator.js.map create mode 100644 lib/cjs/core/modules/impl/ContractDefinitionLoader.js create mode 100644 lib/cjs/core/modules/impl/ContractDefinitionLoader.js.map create mode 100644 lib/cjs/core/modules/impl/DefaultStateEvaluator.js create mode 100644 lib/cjs/core/modules/impl/DefaultStateEvaluator.js.map create mode 100644 lib/cjs/core/modules/impl/HandlerExecutorFactory.js create mode 100644 lib/cjs/core/modules/impl/HandlerExecutorFactory.js.map create mode 100644 lib/cjs/core/modules/impl/LexicographicalInteractionsSorter.js create mode 100644 lib/cjs/core/modules/impl/LexicographicalInteractionsSorter.js.map create mode 100644 lib/cjs/core/modules/impl/TagsParser.js create mode 100644 lib/cjs/core/modules/impl/TagsParser.js.map create mode 100644 lib/cjs/core/modules/impl/WarpGatewayContractDefinitionLoader.js create mode 100644 lib/cjs/core/modules/impl/WarpGatewayContractDefinitionLoader.js.map create mode 100644 lib/cjs/core/modules/impl/WarpGatewayInteractionsLoader.js create mode 100644 lib/cjs/core/modules/impl/WarpGatewayInteractionsLoader.js.map create mode 100644 lib/cjs/core/modules/impl/handler/AbstractContractHandler.js create mode 100644 lib/cjs/core/modules/impl/handler/AbstractContractHandler.js.map create mode 100644 lib/cjs/core/modules/impl/handler/JsHandlerApi.js create mode 100644 lib/cjs/core/modules/impl/handler/JsHandlerApi.js.map create mode 100644 lib/cjs/core/modules/impl/handler/WasmHandlerApi.js create mode 100644 lib/cjs/core/modules/impl/handler/WasmHandlerApi.js.map create mode 100644 lib/cjs/core/modules/impl/normalize-source.js create mode 100644 lib/cjs/core/modules/impl/normalize-source.js.map create mode 100644 lib/cjs/core/modules/impl/wasm/WasmSrc.js create mode 100644 lib/cjs/core/modules/impl/wasm/WasmSrc.js.map create mode 100644 lib/cjs/core/modules/impl/wasm/rust-wasm-imports.js create mode 100644 lib/cjs/core/modules/impl/wasm/rust-wasm-imports.js.map create mode 100644 lib/cjs/core/modules/impl/wasm/wasm-bindgen-tools.js create mode 100644 lib/cjs/core/modules/impl/wasm/wasm-bindgen-tools.js.map create mode 100644 lib/cjs/index.js create mode 100644 lib/cjs/index.js.map create mode 100644 lib/cjs/legacy/create-interaction-tx.js create mode 100644 lib/cjs/legacy/create-interaction-tx.js.map create mode 100644 lib/cjs/legacy/errors.js create mode 100644 lib/cjs/legacy/errors.js.map create mode 100644 lib/cjs/legacy/gqlResult.js create mode 100644 lib/cjs/legacy/gqlResult.js.map create mode 100644 lib/cjs/legacy/smartweave-global.js create mode 100644 lib/cjs/legacy/smartweave-global.js.map create mode 100644 lib/cjs/legacy/utils.js create mode 100644 lib/cjs/legacy/utils.js.map create mode 100644 lib/cjs/logging/Benchmark.js create mode 100644 lib/cjs/logging/Benchmark.js.map create mode 100644 lib/cjs/logging/LoggerFactory.js create mode 100644 lib/cjs/logging/LoggerFactory.js.map create mode 100644 lib/cjs/logging/LoggerSettings.js create mode 100644 lib/cjs/logging/LoggerSettings.js.map create mode 100644 lib/cjs/logging/WarpLogger.js create mode 100644 lib/cjs/logging/WarpLogger.js.map create mode 100644 lib/cjs/logging/web/ConsoleLogger.js create mode 100644 lib/cjs/logging/web/ConsoleLogger.js.map create mode 100644 lib/cjs/logging/web/ConsoleLoggerFactory.js create mode 100644 lib/cjs/logging/web/ConsoleLoggerFactory.js.map create mode 100644 lib/cjs/plugins/DebuggableExecutorFactor.js create mode 100644 lib/cjs/plugins/DebuggableExecutorFactor.js.map create mode 100644 lib/cjs/plugins/Evolve.js create mode 100644 lib/cjs/plugins/Evolve.js.map create mode 100644 lib/cjs/utils/ArweaveWrapper.js create mode 100644 lib/cjs/utils/ArweaveWrapper.js.map create mode 100644 lib/cjs/utils/types/arweave-types.js create mode 100644 lib/cjs/utils/types/arweave-types.js.map create mode 100644 lib/cjs/utils/utils.js create mode 100644 lib/cjs/utils/utils.js.map create mode 100644 lib/mjs/index.js create mode 100644 lib/mjs/package.json create mode 100644 lib/types/cache/BasicSortKeyCache.d.ts create mode 100644 lib/types/cache/BasicSortKeyCache.d.ts.map create mode 100644 lib/types/cache/SortKeyCache.d.ts create mode 100644 lib/types/cache/SortKeyCache.d.ts.map create mode 100644 lib/types/cache/SortKeyCacheRangeOptions.d.ts create mode 100644 lib/types/cache/SortKeyCacheRangeOptions.d.ts.map create mode 100644 lib/types/cache/WarpCache.d.ts create mode 100644 lib/types/cache/WarpCache.d.ts.map create mode 100644 lib/types/cache/impl/LevelDbCache.d.ts create mode 100644 lib/types/cache/impl/LevelDbCache.d.ts.map create mode 100644 lib/types/cache/impl/MemCache.d.ts create mode 100644 lib/types/cache/impl/MemCache.d.ts.map create mode 100644 lib/types/common/SimpleLRUCache.d.ts create mode 100644 lib/types/common/SimpleLRUCache.d.ts.map create mode 100644 lib/types/contract/Contract.d.ts create mode 100644 lib/types/contract/Contract.d.ts.map create mode 100644 lib/types/contract/EvaluationOptionsEvaluator.d.ts create mode 100644 lib/types/contract/EvaluationOptionsEvaluator.d.ts.map create mode 100644 lib/types/contract/HandlerBasedContract.d.ts create mode 100644 lib/types/contract/HandlerBasedContract.d.ts.map create mode 100644 lib/types/contract/InnerWritesEvaluator.d.ts create mode 100644 lib/types/contract/InnerWritesEvaluator.d.ts.map create mode 100644 lib/types/contract/PstContract.d.ts create mode 100644 lib/types/contract/PstContract.d.ts.map create mode 100644 lib/types/contract/PstContractImpl.d.ts create mode 100644 lib/types/contract/PstContractImpl.d.ts.map create mode 100644 lib/types/contract/Signature.d.ts create mode 100644 lib/types/contract/Signature.d.ts.map create mode 100644 lib/types/contract/deploy/CreateContract.d.ts create mode 100644 lib/types/contract/deploy/CreateContract.d.ts.map create mode 100644 lib/types/contract/deploy/Source.d.ts create mode 100644 lib/types/contract/deploy/Source.d.ts.map create mode 100644 lib/types/contract/states/ContractInteractionState.d.ts create mode 100644 lib/types/contract/states/ContractInteractionState.d.ts.map create mode 100644 lib/types/contract/states/InteractionState.d.ts create mode 100644 lib/types/contract/states/InteractionState.d.ts.map create mode 100644 lib/types/contract/testing/Testing.d.ts create mode 100644 lib/types/contract/testing/Testing.d.ts.map create mode 100644 lib/types/core/ContractCallRecord.d.ts create mode 100644 lib/types/core/ContractCallRecord.d.ts.map create mode 100644 lib/types/core/ContractDefinition.d.ts create mode 100644 lib/types/core/ContractDefinition.d.ts.map create mode 100644 lib/types/core/ExecutionContext.d.ts create mode 100644 lib/types/core/ExecutionContext.d.ts.map create mode 100644 lib/types/core/ExecutionContextModifier.d.ts create mode 100644 lib/types/core/ExecutionContextModifier.d.ts.map create mode 100644 lib/types/core/KnownTags.d.ts create mode 100644 lib/types/core/KnownTags.d.ts.map create mode 100644 lib/types/core/Warp.d.ts create mode 100644 lib/types/core/Warp.d.ts.map create mode 100644 lib/types/core/WarpBuilder.d.ts create mode 100644 lib/types/core/WarpBuilder.d.ts.map create mode 100644 lib/types/core/WarpFactory.d.ts create mode 100644 lib/types/core/WarpFactory.d.ts.map create mode 100644 lib/types/core/WarpFetchWrapper.d.ts create mode 100644 lib/types/core/WarpFetchWrapper.d.ts.map create mode 100644 lib/types/core/WarpPlugin.d.ts create mode 100644 lib/types/core/WarpPlugin.d.ts.map create mode 100644 lib/types/core/modules/DefinitionLoader.d.ts create mode 100644 lib/types/core/modules/DefinitionLoader.d.ts.map create mode 100644 lib/types/core/modules/ExecutorFactory.d.ts create mode 100644 lib/types/core/modules/ExecutorFactory.d.ts.map create mode 100644 lib/types/core/modules/InteractionsLoader.d.ts create mode 100644 lib/types/core/modules/InteractionsLoader.d.ts.map create mode 100644 lib/types/core/modules/InteractionsSorter.d.ts create mode 100644 lib/types/core/modules/InteractionsSorter.d.ts.map create mode 100644 lib/types/core/modules/StateEvaluator.d.ts create mode 100644 lib/types/core/modules/StateEvaluator.d.ts.map create mode 100644 lib/types/core/modules/impl/ArweaveGQLTxsFetcher.d.ts create mode 100644 lib/types/core/modules/impl/ArweaveGQLTxsFetcher.d.ts.map create mode 100644 lib/types/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.d.ts create mode 100644 lib/types/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.d.ts.map create mode 100644 lib/types/core/modules/impl/ArweaveGatewayBundledInteractionLoader.d.ts create mode 100644 lib/types/core/modules/impl/ArweaveGatewayBundledInteractionLoader.d.ts.map create mode 100644 lib/types/core/modules/impl/ArweaveGatewayInteractionsLoader.d.ts create mode 100644 lib/types/core/modules/impl/ArweaveGatewayInteractionsLoader.d.ts.map create mode 100644 lib/types/core/modules/impl/CacheableInteractionsLoader.d.ts create mode 100644 lib/types/core/modules/impl/CacheableInteractionsLoader.d.ts.map create mode 100644 lib/types/core/modules/impl/CacheableStateEvaluator.d.ts create mode 100644 lib/types/core/modules/impl/CacheableStateEvaluator.d.ts.map create mode 100644 lib/types/core/modules/impl/ContractDefinitionLoader.d.ts create mode 100644 lib/types/core/modules/impl/ContractDefinitionLoader.d.ts.map create mode 100644 lib/types/core/modules/impl/DefaultStateEvaluator.d.ts create mode 100644 lib/types/core/modules/impl/DefaultStateEvaluator.d.ts.map create mode 100644 lib/types/core/modules/impl/HandlerExecutorFactory.d.ts create mode 100644 lib/types/core/modules/impl/HandlerExecutorFactory.d.ts.map create mode 100644 lib/types/core/modules/impl/LexicographicalInteractionsSorter.d.ts create mode 100644 lib/types/core/modules/impl/LexicographicalInteractionsSorter.d.ts.map create mode 100644 lib/types/core/modules/impl/TagsParser.d.ts create mode 100644 lib/types/core/modules/impl/TagsParser.d.ts.map create mode 100644 lib/types/core/modules/impl/WarpGatewayContractDefinitionLoader.d.ts create mode 100644 lib/types/core/modules/impl/WarpGatewayContractDefinitionLoader.d.ts.map create mode 100644 lib/types/core/modules/impl/WarpGatewayInteractionsLoader.d.ts create mode 100644 lib/types/core/modules/impl/WarpGatewayInteractionsLoader.d.ts.map create mode 100644 lib/types/core/modules/impl/handler/AbstractContractHandler.d.ts create mode 100644 lib/types/core/modules/impl/handler/AbstractContractHandler.d.ts.map create mode 100644 lib/types/core/modules/impl/handler/JsHandlerApi.d.ts create mode 100644 lib/types/core/modules/impl/handler/JsHandlerApi.d.ts.map create mode 100644 lib/types/core/modules/impl/handler/WasmHandlerApi.d.ts create mode 100644 lib/types/core/modules/impl/handler/WasmHandlerApi.d.ts.map create mode 100644 lib/types/core/modules/impl/normalize-source.d.ts create mode 100644 lib/types/core/modules/impl/normalize-source.d.ts.map create mode 100644 lib/types/core/modules/impl/wasm/WasmSrc.d.ts create mode 100644 lib/types/core/modules/impl/wasm/WasmSrc.d.ts.map create mode 100644 lib/types/core/modules/impl/wasm/rust-wasm-imports.d.ts create mode 100644 lib/types/core/modules/impl/wasm/rust-wasm-imports.d.ts.map create mode 100644 lib/types/core/modules/impl/wasm/wasm-bindgen-tools.d.ts create mode 100644 lib/types/core/modules/impl/wasm/wasm-bindgen-tools.d.ts.map create mode 100644 lib/types/index.d.ts create mode 100644 lib/types/index.d.ts.map create mode 100644 lib/types/legacy/create-interaction-tx.d.ts create mode 100644 lib/types/legacy/create-interaction-tx.d.ts.map create mode 100644 lib/types/legacy/errors.d.ts create mode 100644 lib/types/legacy/errors.d.ts.map create mode 100644 lib/types/legacy/gqlResult.d.ts create mode 100644 lib/types/legacy/gqlResult.d.ts.map create mode 100644 lib/types/legacy/smartweave-global.d.ts create mode 100644 lib/types/legacy/smartweave-global.d.ts.map create mode 100644 lib/types/legacy/utils.d.ts create mode 100644 lib/types/legacy/utils.d.ts.map create mode 100644 lib/types/logging/Benchmark.d.ts create mode 100644 lib/types/logging/Benchmark.d.ts.map create mode 100644 lib/types/logging/LoggerFactory.d.ts create mode 100644 lib/types/logging/LoggerFactory.d.ts.map create mode 100644 lib/types/logging/LoggerSettings.d.ts create mode 100644 lib/types/logging/LoggerSettings.d.ts.map create mode 100644 lib/types/logging/WarpLogger.d.ts create mode 100644 lib/types/logging/WarpLogger.d.ts.map create mode 100644 lib/types/logging/web/ConsoleLogger.d.ts create mode 100644 lib/types/logging/web/ConsoleLogger.d.ts.map create mode 100644 lib/types/logging/web/ConsoleLoggerFactory.d.ts create mode 100644 lib/types/logging/web/ConsoleLoggerFactory.d.ts.map create mode 100644 lib/types/plugins/DebuggableExecutorFactor.d.ts create mode 100644 lib/types/plugins/DebuggableExecutorFactor.d.ts.map create mode 100644 lib/types/plugins/Evolve.d.ts create mode 100644 lib/types/plugins/Evolve.d.ts.map create mode 100644 lib/types/utils/ArweaveWrapper.d.ts create mode 100644 lib/types/utils/ArweaveWrapper.d.ts.map create mode 100644 lib/types/utils/types/arweave-types.d.ts create mode 100644 lib/types/utils/types/arweave-types.d.ts.map create mode 100644 lib/types/utils/utils.d.ts create mode 100644 lib/types/utils/utils.d.ts.map diff --git a/.gitignore b/.gitignore index 469221a3..16b635ff 100644 --- a/.gitignore +++ b/.gitignore @@ -8,8 +8,6 @@ crates/pst/cache/ # Optional eslint cache .eslintcache -lib/ - # WebStorm Local files .idea/ @@ -27,10 +25,8 @@ yalc.lock /db/ -bundles/ - .secrets logs target -metafile.json \ No newline at end of file +metafile.json diff --git a/bundles/web.bundle.min.js b/bundles/web.bundle.min.js new file mode 100644 index 00000000..445e52c2 --- /dev/null +++ b/bundles/web.bundle.min.js @@ -0,0 +1,142 @@ +var _h=Object.create;var is=Object.defineProperty;var bh=Object.getOwnPropertyDescriptor;var Sh=Object.getOwnPropertyNames;var Eh=Object.getPrototypeOf,Th=Object.prototype.hasOwnProperty;var xh=(n,t,e)=>t in n?is(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var Ch=(n,t)=>()=>(n&&(t=n(n=0)),t);var nt=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Ih=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Sh(t))!Th.call(n,i)&&i!==e&&is(n,i,{get:()=>t[i],enumerable:!(r=bh(t,i))||r.enumerable});return n};var jt=(n,t,e)=>(e=n!=null?_h(Eh(n)):{},Ih(t||!n||!n.__esModule?is(e,"default",{value:n,enumerable:!0}):e,n));var nr=(n,t,e)=>(xh(n,typeof t!="symbol"?t+"":t,e),e);var ss=nt(vi=>{"use strict";b();vi.byteLength=kh;vi.toByteArray=Oh;vi.fromByteArray=Ph;var Te=[],he=[],Ah=typeof Uint8Array<"u"?Uint8Array:Array,os="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Tr=0,Oc=os.length;Tr0)throw new Error("Invalid string. Length must be a multiple of 4");var e=n.indexOf("=");e===-1&&(e=t);var r=e===t?0:4-e%4;return[e,r]}function kh(n){var t=Rc(n),e=t[0],r=t[1];return(e+r)*3/4-r}function Lh(n,t,e){return(t+e)*3/4-e}function Oh(n){var t,e=Rc(n),r=e[0],i=e[1],o=new Ah(Lh(n,r,i)),s=0,c=i>0?r-4:r,l;for(l=0;l>16&255,o[s++]=t>>8&255,o[s++]=t&255;return i===2&&(t=he[n.charCodeAt(l)]<<2|he[n.charCodeAt(l+1)]>>4,o[s++]=t&255),i===1&&(t=he[n.charCodeAt(l)]<<10|he[n.charCodeAt(l+1)]<<4|he[n.charCodeAt(l+2)]>>2,o[s++]=t>>8&255,o[s++]=t&255),o}function Rh(n){return Te[n>>18&63]+Te[n>>12&63]+Te[n>>6&63]+Te[n&63]}function Bh(n,t,e){for(var r,i=[],o=t;oc?c:s+o));return r===1?(t=n[e-1],i.push(Te[t>>2]+Te[t<<4&63]+"==")):r===2&&(t=(n[e-2]<<8)+n[e-1],i.push(Te[t>>10]+Te[t>>4&63]+Te[t<<2&63]+"=")),i.join("")}});var Bc=nt(as=>{b();as.read=function(n,t,e,r,i){var o,s,c=i*8-r-1,l=(1<>1,w=-7,v=e?i-1:0,E=e?-1:1,d=n[t+v];for(v+=E,o=d&(1<<-w)-1,d>>=-w,w+=c;w>0;o=o*256+n[t+v],v+=E,w-=8);for(s=o&(1<<-w)-1,o>>=-w,w+=r;w>0;s=s*256+n[t+v],v+=E,w-=8);if(o===0)o=1-g;else{if(o===l)return s?NaN:(d?-1:1)*(1/0);s=s+Math.pow(2,r),o=o-g}return(d?-1:1)*s*Math.pow(2,o-r)};as.write=function(n,t,e,r,i,o){var s,c,l,g=o*8-i-1,w=(1<>1,E=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,y=r?1:-1,k=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,s=w):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+v>=1?t+=E/l:t+=E*Math.pow(2,1-v),t*l>=2&&(s++,l/=2),s+v>=w?(c=0,s=w):s+v>=1?(c=(t*l-1)*Math.pow(2,i),s=s+v):(c=t*Math.pow(2,v-1)*Math.pow(2,i),s=0));i>=8;n[e+d]=c&255,d+=y,c/=256,i-=8);for(s=s<0;n[e+d]=s&255,d+=y,s/=256,g-=8);n[e+d-y]|=k*128}});var Cr=nt(Jr=>{"use strict";b();var cs=ss(),zr=Bc(),Pc=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Jr.Buffer=V;Jr.SlowBuffer=Fh;Jr.INSPECT_MAX_BYTES=50;var _i=2147483647;Jr.kMaxLength=_i;V.TYPED_ARRAY_SUPPORT=Nh();!V.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Nh(){try{var n=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(n,t),n.foo()===42}catch{return!1}}Object.defineProperty(V.prototype,"parent",{enumerable:!0,get:function(){if(V.isBuffer(this))return this.buffer}});Object.defineProperty(V.prototype,"offset",{enumerable:!0,get:function(){if(V.isBuffer(this))return this.byteOffset}});function We(n){if(n>_i)throw new RangeError('The value "'+n+'" is invalid for option "size"');var t=new Uint8Array(n);return Object.setPrototypeOf(t,V.prototype),t}function V(n,t,e){if(typeof n=="number"){if(typeof t=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return hs(n)}return Wc(n,t,e)}V.poolSize=8192;function Wc(n,t,e){if(typeof n=="string")return Wh(n,t);if(ArrayBuffer.isView(n))return Dh(n);if(n==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n);if(xe(n,ArrayBuffer)||n&&xe(n.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(xe(n,SharedArrayBuffer)||n&&xe(n.buffer,SharedArrayBuffer)))return ls(n,t,e);if(typeof n=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var r=n.valueOf&&n.valueOf();if(r!=null&&r!==n)return V.from(r,t,e);var i=Mh(n);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof n[Symbol.toPrimitive]=="function")return V.from(n[Symbol.toPrimitive]("string"),t,e);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n)}V.from=function(n,t,e){return Wc(n,t,e)};Object.setPrototypeOf(V.prototype,Uint8Array.prototype);Object.setPrototypeOf(V,Uint8Array);function Dc(n){if(typeof n!="number")throw new TypeError('"size" argument must be of type number');if(n<0)throw new RangeError('The value "'+n+'" is invalid for option "size"')}function Uh(n,t,e){return Dc(n),n<=0?We(n):t!==void 0?typeof e=="string"?We(n).fill(t,e):We(n).fill(t):We(n)}V.alloc=function(n,t,e){return Uh(n,t,e)};function hs(n){return Dc(n),We(n<0?0:gs(n)|0)}V.allocUnsafe=function(n){return hs(n)};V.allocUnsafeSlow=function(n){return hs(n)};function Wh(n,t){if((typeof t!="string"||t==="")&&(t="utf8"),!V.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var e=Mc(n,t)|0,r=We(e),i=r.write(n,t);return i!==e&&(r=r.slice(0,i)),r}function us(n){for(var t=n.length<0?0:gs(n.length)|0,e=We(t),r=0;r=_i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+_i.toString(16)+" bytes");return n|0}function Fh(n){return+n!=n&&(n=0),V.alloc(+n)}V.isBuffer=function(t){return t!=null&&t._isBuffer===!0&&t!==V.prototype};V.compare=function(t,e){if(xe(t,Uint8Array)&&(t=V.from(t,t.offset,t.byteLength)),xe(e,Uint8Array)&&(e=V.from(e,e.offset,e.byteLength)),!V.isBuffer(t)||!V.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;for(var r=t.length,i=e.length,o=0,s=Math.min(r,i);oi.length?V.from(s).copy(i,o):Uint8Array.prototype.set.call(i,s,o);else if(V.isBuffer(s))s.copy(i,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return i};function Mc(n,t){if(V.isBuffer(n))return n.length;if(ArrayBuffer.isView(n)||xe(n,ArrayBuffer))return n.byteLength;if(typeof n!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof n);var e=n.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&e===0)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":return fs(n).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return e*2;case"hex":return e>>>1;case"base64":return qc(n).length;default:if(i)return r?-1:fs(n).length;t=(""+t).toLowerCase(),i=!0}}V.byteLength=Mc;function $h(n,t,e){var r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((e===void 0||e>this.length)&&(e=this.length),e<=0)||(e>>>=0,t>>>=0,e<=t))return"";for(n||(n="utf8");;)switch(n){case"hex":return Yh(this,t,e);case"utf8":case"utf-8":return $c(this,t,e);case"ascii":return zh(this,t,e);case"latin1":case"binary":return Jh(this,t,e);case"base64":return Hh(this,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Xh(this,t,e);default:if(r)throw new TypeError("Unknown encoding: "+n);n=(n+"").toLowerCase(),r=!0}}V.prototype._isBuffer=!0;function xr(n,t,e){var r=n[t];n[t]=n[e],n[e]=r}V.prototype.swap16=function(){var t=this.length;if(t%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;ee&&(t+=" ... "),""};Pc&&(V.prototype[Pc]=V.prototype.inspect);V.prototype.compare=function(t,e,r,i,o){if(xe(t,Uint8Array)&&(t=V.from(t,t.offset,t.byteLength)),!V.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(e===void 0&&(e=0),r===void 0&&(r=t?t.length:0),i===void 0&&(i=0),o===void 0&&(o=this.length),e<0||r>t.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&e>=r)return 0;if(i>=o)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,i>>>=0,o>>>=0,this===t)return 0;for(var s=o-i,c=r-e,l=Math.min(s,c),g=this.slice(i,o),w=t.slice(e,r),v=0;v2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,ds(e)&&(e=i?0:n.length-1),e<0&&(e=n.length+e),e>=n.length){if(i)return-1;e=n.length-1}else if(e<0)if(i)e=0;else return-1;if(typeof t=="string"&&(t=V.from(t,r)),V.isBuffer(t))return t.length===0?-1:Nc(n,t,e,r,i);if(typeof t=="number")return t=t&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(n,t,e):Uint8Array.prototype.lastIndexOf.call(n,t,e):Nc(n,[t],e,r,i);throw new TypeError("val must be string, number or Buffer")}function Nc(n,t,e,r,i){var o=1,s=n.length,c=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(n.length<2||t.length<2)return-1;o=2,s/=2,c/=2,e/=2}function l(d,y){return o===1?d[y]:d.readUInt16BE(y*o)}var g;if(i){var w=-1;for(g=e;gs&&(e=s-c),g=e;g>=0;g--){for(var v=!0,E=0;Ei&&(r=i)):r=i;var o=t.length;r>o/2&&(r=o/2);for(var s=0;s>>0,isFinite(r)?(r=r>>>0,i===void 0&&(i="utf8")):(i=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var o=this.length-e;if((r===void 0||r>o)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var s=!1;;)switch(i){case"hex":return Kh(this,t,e,r);case"utf8":case"utf-8":return Vh(this,t,e,r);case"ascii":case"latin1":case"binary":return Gh(this,t,e,r);case"base64":return qh(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return jh(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}};V.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Hh(n,t,e){return t===0&&e===n.length?cs.fromByteArray(n):cs.fromByteArray(n.slice(t,e))}function $c(n,t,e){e=Math.min(n.length,e);for(var r=[],i=t;i239?4:o>223?3:o>191?2:1;if(i+c<=e){var l,g,w,v;switch(c){case 1:o<128&&(s=o);break;case 2:l=n[i+1],(l&192)===128&&(v=(o&31)<<6|l&63,v>127&&(s=v));break;case 3:l=n[i+1],g=n[i+2],(l&192)===128&&(g&192)===128&&(v=(o&15)<<12|(l&63)<<6|g&63,v>2047&&(v<55296||v>57343)&&(s=v));break;case 4:l=n[i+1],g=n[i+2],w=n[i+3],(l&192)===128&&(g&192)===128&&(w&192)===128&&(v=(o&15)<<18|(l&63)<<12|(g&63)<<6|w&63,v>65535&&v<1114112&&(s=v))}}s===null?(s=65533,c=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|s&1023),r.push(s),i+=c}return Qh(r)}var Uc=4096;function Qh(n){var t=n.length;if(t<=Uc)return String.fromCharCode.apply(String,n);for(var e="",r=0;rr)&&(e=r);for(var i="",o=t;or&&(t=r),e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),ee)throw new RangeError("Trying to access beyond buffer length")}V.prototype.readUintLE=V.prototype.readUIntLE=function(t,e,r){t=t>>>0,e=e>>>0,r||Mt(t,e,this.length);for(var i=this[t],o=1,s=0;++s>>0,e=e>>>0,r||Mt(t,e,this.length);for(var i=this[t+--e],o=1;e>0&&(o*=256);)i+=this[t+--e]*o;return i};V.prototype.readUint8=V.prototype.readUInt8=function(t,e){return t=t>>>0,e||Mt(t,1,this.length),this[t]};V.prototype.readUint16LE=V.prototype.readUInt16LE=function(t,e){return t=t>>>0,e||Mt(t,2,this.length),this[t]|this[t+1]<<8};V.prototype.readUint16BE=V.prototype.readUInt16BE=function(t,e){return t=t>>>0,e||Mt(t,2,this.length),this[t]<<8|this[t+1]};V.prototype.readUint32LE=V.prototype.readUInt32LE=function(t,e){return t=t>>>0,e||Mt(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};V.prototype.readUint32BE=V.prototype.readUInt32BE=function(t,e){return t=t>>>0,e||Mt(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};V.prototype.readIntLE=function(t,e,r){t=t>>>0,e=e>>>0,r||Mt(t,e,this.length);for(var i=this[t],o=1,s=0;++s=o&&(i-=Math.pow(2,8*e)),i};V.prototype.readIntBE=function(t,e,r){t=t>>>0,e=e>>>0,r||Mt(t,e,this.length);for(var i=e,o=1,s=this[t+--i];i>0&&(o*=256);)s+=this[t+--i]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*e)),s};V.prototype.readInt8=function(t,e){return t=t>>>0,e||Mt(t,1,this.length),this[t]&128?(255-this[t]+1)*-1:this[t]};V.prototype.readInt16LE=function(t,e){t=t>>>0,e||Mt(t,2,this.length);var r=this[t]|this[t+1]<<8;return r&32768?r|4294901760:r};V.prototype.readInt16BE=function(t,e){t=t>>>0,e||Mt(t,2,this.length);var r=this[t+1]|this[t]<<8;return r&32768?r|4294901760:r};V.prototype.readInt32LE=function(t,e){return t=t>>>0,e||Mt(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24};V.prototype.readInt32BE=function(t,e){return t=t>>>0,e||Mt(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]};V.prototype.readFloatLE=function(t,e){return t=t>>>0,e||Mt(t,4,this.length),zr.read(this,t,!0,23,4)};V.prototype.readFloatBE=function(t,e){return t=t>>>0,e||Mt(t,4,this.length),zr.read(this,t,!1,23,4)};V.prototype.readDoubleLE=function(t,e){return t=t>>>0,e||Mt(t,8,this.length),zr.read(this,t,!0,52,8)};V.prototype.readDoubleBE=function(t,e){return t=t>>>0,e||Mt(t,8,this.length),zr.read(this,t,!1,52,8)};function te(n,t,e,r,i,o){if(!V.isBuffer(n))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||tn.length)throw new RangeError("Index out of range")}V.prototype.writeUintLE=V.prototype.writeUIntLE=function(t,e,r,i){if(t=+t,e=e>>>0,r=r>>>0,!i){var o=Math.pow(2,8*r)-1;te(this,t,e,r,o,0)}var s=1,c=0;for(this[e]=t&255;++c>>0,r=r>>>0,!i){var o=Math.pow(2,8*r)-1;te(this,t,e,r,o,0)}var s=r-1,c=1;for(this[e+s]=t&255;--s>=0&&(c*=256);)this[e+s]=t/c&255;return e+r};V.prototype.writeUint8=V.prototype.writeUInt8=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,1,255,0),this[e]=t&255,e+1};V.prototype.writeUint16LE=V.prototype.writeUInt16LE=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,2,65535,0),this[e]=t&255,this[e+1]=t>>>8,e+2};V.prototype.writeUint16BE=V.prototype.writeUInt16BE=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=t&255,e+2};V.prototype.writeUint32LE=V.prototype.writeUInt32LE=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=t&255,e+4};V.prototype.writeUint32BE=V.prototype.writeUInt32BE=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t&255,e+4};V.prototype.writeIntLE=function(t,e,r,i){if(t=+t,e=e>>>0,!i){var o=Math.pow(2,8*r-1);te(this,t,e,r,o-1,-o)}var s=0,c=1,l=0;for(this[e]=t&255;++s>0)-l&255;return e+r};V.prototype.writeIntBE=function(t,e,r,i){if(t=+t,e=e>>>0,!i){var o=Math.pow(2,8*r-1);te(this,t,e,r,o-1,-o)}var s=r-1,c=1,l=0;for(this[e+s]=t&255;--s>=0&&(c*=256);)t<0&&l===0&&this[e+s+1]!==0&&(l=1),this[e+s]=(t/c>>0)-l&255;return e+r};V.prototype.writeInt8=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=t&255,e+1};V.prototype.writeInt16LE=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,2,32767,-32768),this[e]=t&255,this[e+1]=t>>>8,e+2};V.prototype.writeInt16BE=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=t&255,e+2};V.prototype.writeInt32LE=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,4,2147483647,-2147483648),this[e]=t&255,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4};V.prototype.writeInt32BE=function(t,e,r){return t=+t,e=e>>>0,r||te(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t&255,e+4};function Kc(n,t,e,r,i,o){if(e+r>n.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function Vc(n,t,e,r,i){return t=+t,e=e>>>0,i||Kc(n,t,e,4,34028234663852886e22,-34028234663852886e22),zr.write(n,t,e,r,23,4),e+4}V.prototype.writeFloatLE=function(t,e,r){return Vc(this,t,e,!0,r)};V.prototype.writeFloatBE=function(t,e,r){return Vc(this,t,e,!1,r)};function Gc(n,t,e,r,i){return t=+t,e=e>>>0,i||Kc(n,t,e,8,17976931348623157e292,-17976931348623157e292),zr.write(n,t,e,r,52,8),e+8}V.prototype.writeDoubleLE=function(t,e,r){return Gc(this,t,e,!0,r)};V.prototype.writeDoubleBE=function(t,e,r){return Gc(this,t,e,!1,r)};V.prototype.copy=function(t,e,r,i){if(!V.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),!i&&i!==0&&(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e>>0,r=r===void 0?this.length:r>>>0,t||(t=0);var s;if(typeof t=="number")for(s=e;s55295&&e<57344){if(!i){if(e>56319){(t-=3)>-1&&o.push(239,191,189);continue}else if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(t-=3)>-1&&o.push(239,191,189),i=e;continue}e=(i-55296<<10|e-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((t-=1)<0)break;o.push(e)}else if(e<2048){if((t-=2)<0)break;o.push(e>>6|192,e&63|128)}else if(e<65536){if((t-=3)<0)break;o.push(e>>12|224,e>>6&63|128,e&63|128)}else if(e<1114112){if((t-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,e&63|128)}else throw new Error("Invalid code point")}return o}function eg(n){for(var t=[],e=0;e>8,i=e%256,o.push(i),o.push(r);return o}function qc(n){return cs.toByteArray(tg(n))}function bi(n,t,e,r){for(var i=0;i=t.length||i>=n.length);++i)t[i+e]=n[i];return i}function xe(n,t){return n instanceof t||n!=null&&n.constructor!=null&&n.constructor.name!=null&&n.constructor.name===t.name}function ds(n){return n!==n}var ng=function(){for(var n="0123456789abcdef",t=new Array(256),e=0;e<16;++e)for(var r=e*16,i=0;i<16;++i)t[r+i]=n[e]+n[i];return t}()});var Jc=nt((cy,zc)=>{b();var Rt=zc.exports={},Ce,Ie;function ps(){throw new Error("setTimeout has not been defined")}function ms(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Ce=setTimeout:Ce=ps}catch{Ce=ps}try{typeof clearTimeout=="function"?Ie=clearTimeout:Ie=ms}catch{Ie=ms}})();function jc(n){if(Ce===setTimeout)return setTimeout(n,0);if((Ce===ps||!Ce)&&setTimeout)return Ce=setTimeout,setTimeout(n,0);try{return Ce(n,0)}catch{try{return Ce.call(null,n,0)}catch{return Ce.call(this,n,0)}}}function ig(n){if(Ie===clearTimeout)return clearTimeout(n);if((Ie===ms||!Ie)&&clearTimeout)return Ie=clearTimeout,clearTimeout(n);try{return Ie(n)}catch{try{return Ie.call(null,n)}catch{return Ie.call(this,n)}}}var De=[],Yr=!1,Ir,Si=-1;function og(){!Yr||!Ir||(Yr=!1,Ir.length?De=Ir.concat(De):Si=-1,De.length&&Hc())}function Hc(){if(!Yr){var n=jc(og);Yr=!0;for(var t=De.length;t;){for(Ir=De,De=[];++Si1)for(var e=1;e{F=jt(Cr()),$=jt(Jc()),sg=function(n){function t(){var r=this||self;return delete n.prototype.__magic__,r}if(typeof globalThis=="object")return globalThis;if(this)return t();n.defineProperty(n.prototype,"__magic__",{configurable:!0,get:t});var e=__magic__;return e}(Object),K=sg});var Xc=nt(Yc=>{"use strict";b();Yc.supports=function(...t){let e=t.reduce((r,i)=>Object.assign(r,i),{});return Object.assign(e,{snapshots:e.snapshots||!1,permanence:e.permanence||!1,seek:e.seek||!1,clear:e.clear||!1,getMany:e.getMany||!1,keyIterator:e.keyIterator||!1,valueIterator:e.valueIterator||!1,iteratorNextv:e.iteratorNextv||!1,iteratorAll:e.iteratorAll||!1,status:e.status||!1,createIfMissing:e.createIfMissing||!1,errorIfExists:e.errorIfExists||!1,deferredOpen:e.deferredOpen||!1,promises:e.promises||!1,streams:e.streams||!1,encodings:Object.assign({},e.encodings),events:Object.assign({},e.events),additionalMethods:Object.assign({},e.additionalMethods)})}});var ge=nt((Ry,Zc)=>{"use strict";b();Zc.exports=class extends Error{constructor(t,e){super(t||""),typeof e=="object"&&e!==null&&(e.code&&(this.code=String(e.code)),e.expected&&(this.expected=!0),e.transient&&(this.transient=!0),e.cause&&(this.cause=e.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}});var vs=nt((Py,tu)=>{"use strict";b();var ws=null;tu.exports=function(){return ws===null&&(ws={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),ws}});var Ss=nt(eu=>{"use strict";b();var _s=ge(),cg=new Set(["buffer","view","utf8"]),bs=class{constructor(t){if(this.encode=t.encode||this.encode,this.decode=t.decode||this.decode,this.name=t.name||this.name,this.format=t.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!cg.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");t.createViewTranscoder&&(this.createViewTranscoder=t.createViewTranscoder),t.createBufferTranscoder&&(this.createBufferTranscoder=t.createBufferTranscoder),t.createUTF8Transcoder&&(this.createUTF8Transcoder=t.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new _s(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new _s(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new _s(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};eu.Encoding=bs});var Cs=nt(xi=>{"use strict";b();var{Buffer:Ts}=Cr()||{},{Encoding:xs}=Ss(),ug=vs(),Tn=class extends xs{constructor(t){super({...t,format:"buffer"})}createViewTranscoder(){return new xn({encode:this.encode,decode:t=>this.decode(Ts.from(t.buffer,t.byteOffset,t.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},xn=class extends xs{constructor(t){super({...t,format:"view"})}createBufferTranscoder(){return new Tn({encode:t=>{let e=this.encode(t);return Ts.from(e.buffer,e.byteOffset,e.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},Es=class extends xs{constructor(t){super({...t,format:"utf8"})}createBufferTranscoder(){return new Tn({encode:t=>Ts.from(this.encode(t),"utf8"),decode:t=>this.decode(t.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:t,textDecoder:e}=ug();return new xn({encode:r=>t.encode(this.encode(r)),decode:r=>this.decode(e.decode(r)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};xi.BufferFormat=Tn;xi.ViewFormat=xn;xi.UTF8Format=Es});var ou=nt(kr=>{"use strict";b();var{Buffer:Ht}=Cr()||{Buffer:{isBuffer:()=>!1}},{textEncoder:nu,textDecoder:ru}=vs()(),{BufferFormat:Cn,ViewFormat:Is,UTF8Format:iu}=Cs(),Ci=n=>n;kr.utf8=new iu({encode:function(n){return Ht.isBuffer(n)?n.toString("utf8"):ArrayBuffer.isView(n)?ru.decode(n):String(n)},decode:Ci,name:"utf8",createViewTranscoder(){return new Is({encode:function(n){return ArrayBuffer.isView(n)?n:nu.encode(n)},decode:function(n){return ru.decode(n)},name:`${this.name}+view`})},createBufferTranscoder(){return new Cn({encode:function(n){return Ht.isBuffer(n)?n:ArrayBuffer.isView(n)?Ht.from(n.buffer,n.byteOffset,n.byteLength):Ht.from(String(n),"utf8")},decode:function(n){return n.toString("utf8")},name:`${this.name}+buffer`})}});kr.json=new iu({encode:JSON.stringify,decode:JSON.parse,name:"json"});kr.buffer=new Cn({encode:function(n){return Ht.isBuffer(n)?n:ArrayBuffer.isView(n)?Ht.from(n.buffer,n.byteOffset,n.byteLength):Ht.from(String(n),"utf8")},decode:Ci,name:"buffer",createViewTranscoder(){return new Is({encode:function(n){return ArrayBuffer.isView(n)?n:Ht.from(String(n),"utf8")},decode:function(n){return Ht.from(n.buffer,n.byteOffset,n.byteLength)},name:`${this.name}+view`})}});kr.view=new Is({encode:function(n){return ArrayBuffer.isView(n)?n:nu.encode(n)},decode:Ci,name:"view",createBufferTranscoder(){return new Cn({encode:function(n){return Ht.isBuffer(n)?n:ArrayBuffer.isView(n)?Ht.from(n.buffer,n.byteOffset,n.byteLength):Ht.from(String(n),"utf8")},decode:Ci,name:`${this.name}+buffer`})}});kr.hex=new Cn({encode:function(n){return Ht.isBuffer(n)?n:Ht.from(String(n),"hex")},decode:function(n){return n.toString("hex")},name:"hex"});kr.base64=new Cn({encode:function(n){return Ht.isBuffer(n)?n:Ht.from(String(n),"base64")},decode:function(n){return n.toString("base64")},name:"base64"})});var cu=nt(au=>{"use strict";b();var su=ge(),Ai=ou(),{Encoding:lg}=Ss(),{BufferFormat:fg,ViewFormat:hg,UTF8Format:gg}=Cs(),In=Symbol("formats"),Ii=Symbol("encodings"),dg=new Set(["buffer","view","utf8"]),As=class{constructor(t){if(Array.isArray(t)){if(!t.every(e=>dg.has(e)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[Ii]=new Map,this[In]=new Set(t);for(let e in Ai)try{this.encoding(e)}catch(r){if(r.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw r}}encodings(){return Array.from(new Set(this[Ii].values()))}encoding(t){let e=this[Ii].get(t);if(e===void 0){if(typeof t=="string"&&t!==""){if(e=wg[t],!e)throw new su(`Encoding '${t}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof t!="object"||t===null)throw new TypeError("First argument 'encoding' must be a string or object");e=pg(t)}let{name:r,format:i}=e;if(!this[In].has(i))if(this[In].has("view"))e=e.createViewTranscoder();else if(this[In].has("buffer"))e=e.createBufferTranscoder();else if(this[In].has("utf8"))e=e.createUTF8Transcoder();else throw new su(`Encoding '${r}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[t,r,e.name,e.commonName])this[Ii].set(o,e)}return e}};au.Transcoder=As;function pg(n){if(n instanceof lg)return n;let t="type"in n&&typeof n.type=="string"?n.type:void 0,e=n.name||t||`anonymous-${vg++}`;switch(mg(n)){case"view":return new hg({...n,name:e});case"utf8":return new gg({...n,name:e});case"buffer":return new fg({...n,name:e});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function mg(n){return"format"in n&&n.format!==void 0?n.format:"buffer"in n&&typeof n.buffer=="boolean"?n.buffer?"buffer":"utf8":"code"in n&&Number.isInteger(n.code)?"view":"buffer"}var yg={binary:Ai.buffer,"utf-8":Ai.utf8},wg={...Ai,...yg},vg=0});var vu=nt((Gy,ks)=>{"use strict";b();var Xr=typeof Reflect=="object"?Reflect:null,uu=Xr&&typeof Xr.apply=="function"?Xr.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},ki;Xr&&typeof Xr.ownKeys=="function"?ki=Xr.ownKeys:Object.getOwnPropertySymbols?ki=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ki=function(t){return Object.getOwnPropertyNames(t)};function _g(n){console&&console.warn&&console.warn(n)}var fu=Number.isNaN||function(t){return t!==t};function xt(){xt.init.call(this)}ks.exports=xt;ks.exports.once=Tg;xt.EventEmitter=xt;xt.prototype._events=void 0;xt.prototype._eventsCount=0;xt.prototype._maxListeners=void 0;var lu=10;function Li(n){if(typeof n!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof n)}Object.defineProperty(xt,"defaultMaxListeners",{enumerable:!0,get:function(){return lu},set:function(n){if(typeof n!="number"||n<0||fu(n))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+n+".");lu=n}});xt.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};xt.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||fu(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function hu(n){return n._maxListeners===void 0?xt.defaultMaxListeners:n._maxListeners}xt.prototype.getMaxListeners=function(){return hu(this)};xt.prototype.emit=function(t){for(var e=[],r=1;r0&&(s=e[0]),s instanceof Error)throw s;var c=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw c.context=s,c}var l=o[t];if(l===void 0)return!1;if(typeof l=="function")uu(l,this,e);else for(var g=l.length,w=yu(l,g),r=0;r0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=n,c.type=t,c.count=s.length,_g(c)}return n}xt.prototype.addListener=function(t,e){return gu(this,t,e,!1)};xt.prototype.on=xt.prototype.addListener;xt.prototype.prependListener=function(t,e){return gu(this,t,e,!0)};function bg(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function du(n,t,e){var r={fired:!1,wrapFn:void 0,target:n,type:t,listener:e},i=bg.bind(r);return i.listener=e,r.wrapFn=i,i}xt.prototype.once=function(t,e){return Li(e),this.on(t,du(this,t,e)),this};xt.prototype.prependOnceListener=function(t,e){return Li(e),this.prependListener(t,du(this,t,e)),this};xt.prototype.removeListener=function(t,e){var r,i,o,s,c;if(Li(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(o=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){c=r[s].listener,o=s;break}if(o<0)return this;o===0?r.shift():Sg(r,o),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};xt.prototype.off=xt.prototype.removeListener;xt.prototype.removeAllListeners=function(t){var e,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var o=Object.keys(r),s;for(i=0;i=0;i--)this.removeListener(t,e[i]);return this};function pu(n,t,e){var r=n._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?Eg(i):yu(i,i.length)}xt.prototype.listeners=function(t){return pu(this,t,!0)};xt.prototype.rawListeners=function(t){return pu(this,t,!1)};xt.listenerCount=function(n,t){return typeof n.listenerCount=="function"?n.listenerCount(t):mu.call(n,t)};xt.prototype.listenerCount=mu;function mu(n){var t=this._events;if(t!==void 0){var e=t[n];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}xt.prototype.eventNames=function(){return this._eventsCount>0?ki(this._events):[]};function yu(n,t){for(var e=new Array(t),r=0;r{b();_u.exports=typeof queueMicrotask=="function"?queueMicrotask:n=>Promise.resolve().then(n)});var An=nt(Ls=>{"use strict";b();var Su=bu();Ls.fromCallback=function(n,t){if(n===void 0){var e=new Promise(function(r,i){n=function(o,s){o?i(o):r(s)}});n[t!==void 0?t:"promise"]=e}else if(typeof n!="function")throw new TypeError("Callback must be a function");return n};Ls.fromPromise=function(n,t){if(t===void 0)return n;n.then(function(e){Su(()=>t(null,e))}).catch(function(e){Su(()=>t(e))})}});var Oi=nt(Os=>{"use strict";b();Os.getCallback=function(n,t){return typeof n=="function"?n:t};Os.getOptions=function(n,t){return typeof n=="object"&&n!==null?n:t!==void 0?t:{}}});var ur=nt(Ni=>{"use strict";b();var{fromCallback:Rs}=An(),ie=ge(),{getOptions:Bs,getCallback:Eu}=Oi(),Lr=Symbol("promise"),Zr=Symbol("callback"),Ae=Symbol("working"),Or=Symbol("handleOne"),Fe=Symbol("handleMany"),Ps=Symbol("autoClose"),ar=Symbol("finishWork"),ke=Symbol("returnMany"),ir=Symbol("closing"),kn=Symbol("handleClose"),Ri=Symbol("closed"),Ln=Symbol("closeCallbacks"),sr=Symbol("keyEncoding"),Rr=Symbol("valueEncoding"),Ns=Symbol("abortOnClose"),Bi=Symbol("legacy"),Us=Symbol("keys"),Ws=Symbol("values"),or=Symbol("limit"),de=Symbol("count"),Pi=Object.freeze({}),Cg=()=>{},Tu=!1,On=class{constructor(t,e,r){if(typeof t!="object"||t===null){let i=t===null?"null":typeof t;throw new TypeError(`The first argument must be an abstract-level database, received ${i}`)}if(typeof e!="object"||e===null)throw new TypeError("The second argument must be an options object");this[Ri]=!1,this[Ln]=[],this[Ae]=!1,this[ir]=!1,this[Ps]=!1,this[Zr]=null,this[Or]=this[Or].bind(this),this[Fe]=this[Fe].bind(this),this[kn]=this[kn].bind(this),this[sr]=e[sr],this[Rr]=e[Rr],this[Bi]=r,this[or]=Number.isInteger(e.limit)&&e.limit>=0?e.limit:1/0,this[de]=0,this[Ns]=!!e.abortOnClose,this.db=t,this.db.attachResource(this),this.nextTick=t.nextTick}get count(){return this[de]}get limit(){return this[or]}next(t){let e;if(t===void 0)e=new Promise((r,i)=>{t=(o,s,c)=>{o?i(o):this[Bi]?s===void 0&&c===void 0?r():r([s,c]):r(s)}});else if(typeof t!="function")throw new TypeError("Callback must be a function");return this[ir]?this.nextTick(t,new ie("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Ae]?this.nextTick(t,new ie("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Ae]=!0,this[Zr]=t,this[de]>=this[or]?this.nextTick(this[Or],null):this._next(this[Or])),e}_next(t){this.nextTick(t)}nextv(t,e,r){return r=Eu(e,r),r=Rs(r,Lr),e=Bs(e,Pi),Number.isInteger(t)?(this[ir]?this.nextTick(r,new ie("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Ae]?this.nextTick(r,new ie("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(t<1&&(t=1),this[or]<1/0&&(t=Math.min(t,this[or]-this[de])),this[Ae]=!0,this[Zr]=r,t<=0?this.nextTick(this[Fe],null,[]):this._nextv(t,e,this[Fe])),r[Lr]):(this.nextTick(r,new TypeError("The first argument 'size' must be an integer")),r[Lr])}_nextv(t,e,r){let i=[],o=(s,c,l)=>{if(s)return r(s);if(this[Bi]?c===void 0&&l===void 0:c===void 0)return r(null,i);i.push(this[Bi]?[c,l]:c),i.length===t?r(null,i):this._next(o)};this._next(o)}all(t,e){return e=Eu(t,e),e=Rs(e,Lr),t=Bs(t,Pi),this[ir]?this.nextTick(e,new ie("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Ae]?this.nextTick(e,new ie("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Ae]=!0,this[Zr]=e,this[Ps]=!0,this[de]>=this[or]?this.nextTick(this[Fe],null,[]):this._all(t,this[Fe])),e[Lr]}_all(t,e){let r=this[de],i=[],o=()=>{let c=this[or]<1/0?Math.min(1e3,this[or]-r):1e3;c<=0?this.nextTick(e,null,i):this._nextv(c,Pi,s)},s=(c,l)=>{c?e(c):l.length===0?e(null,i):(i.push.apply(i,l),r+=l.length,o())};o()}[ar](){let t=this[Zr];return this[Ns]&&t===null?Cg:(this[Ae]=!1,this[Zr]=null,this[ir]&&this._close(this[kn]),t)}[ke](t,e,r){this[Ps]?this.close(t.bind(null,e,r)):t(e,r)}seek(t,e){if(e=Bs(e,Pi),!this[ir]){if(this[Ae])throw new ie("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let r=this.db.keyEncoding(e.keyEncoding||this[sr]),i=r.format;e.keyEncoding!==i&&(e={...e,keyEncoding:i});let o=this.db.prefixKey(r.encode(t),i);this._seek(o,e)}}}_seek(t,e){throw new ie("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(t){return t=Rs(t,Lr),this[Ri]?this.nextTick(t):this[ir]?this[Ln].push(t):(this[ir]=!0,this[Ln].push(t),this[Ae]?this[Ns]&&this[ar]()(new ie("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[kn])),t[Lr]}_close(t){this.nextTick(t)}[kn](){this[Ri]=!0,this.db.detachResource(this);let t=this[Ln];this[Ln]=[];for(let e of t)e()}async*[Symbol.asyncIterator](){try{let t;for(;(t=await this.next())!==void 0;)yield t}finally{this[Ri]||await this.close()}}},tn=class extends On{constructor(t,e){super(t,e,!0),this[Us]=e.keys!==!1,this[Ws]=e.values!==!1}[Or](t,e,r){let i=this[ar]();if(t)return i(t);try{e=this[Us]&&e!==void 0?this[sr].decode(e):void 0,r=this[Ws]&&r!==void 0?this[Rr].decode(r):void 0}catch(o){return i(new cr("entry",o))}e===void 0&&r===void 0||this[de]++,i(null,e,r)}[Fe](t,e){let r=this[ar]();if(t)return this[ke](r,t);try{for(let i of e){let o=i[0],s=i[1];i[0]=this[Us]&&o!==void 0?this[sr].decode(o):void 0,i[1]=this[Ws]&&s!==void 0?this[Rr].decode(s):void 0}}catch(i){return this[ke](r,new cr("entries",i))}this[de]+=e.length,this[ke](r,null,e)}end(t){return!Tu&&typeof console<"u"&&(Tu=!0,console.warn(new ie("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(t)}},Ds=class extends On{constructor(t,e){super(t,e,!1)}[Or](t,e){let r=this[ar]();if(t)return r(t);try{e=e!==void 0?this[sr].decode(e):void 0}catch(i){return r(new cr("key",i))}e!==void 0&&this[de]++,r(null,e)}[Fe](t,e){let r=this[ar]();if(t)return this[ke](r,t);try{for(let i=0;i{"use strict";b();var{AbstractKeyIterator:Ig,AbstractValueIterator:Ag}=ur(),Br=Symbol("iterator"),Rn=Symbol("callback"),en=Symbol("handleOne"),Pr=Symbol("handleMany"),Bn=class extends Ig{constructor(t,e){super(t,e),this[Br]=t.iterator({...e,keys:!0,values:!1}),this[en]=this[en].bind(this),this[Pr]=this[Pr].bind(this)}},Ui=class extends Ag{constructor(t,e){super(t,e),this[Br]=t.iterator({...e,keys:!1,values:!0}),this[en]=this[en].bind(this),this[Pr]=this[Pr].bind(this)}};for(let n of[Bn,Ui]){let t=n===Bn,e=t?r=>r[0]:r=>r[1];n.prototype._next=function(r){this[Rn]=r,this[Br].next(this[en])},n.prototype[en]=function(r,i,o){let s=this[Rn];r?s(r):s(null,t?i:o)},n.prototype._nextv=function(r,i,o){this[Rn]=o,this[Br].nextv(r,i,this[Pr])},n.prototype._all=function(r,i){this[Rn]=i,this[Br].all(r,this[Pr])},n.prototype[Pr]=function(r,i){let o=this[Rn];r?o(r):o(null,i.map(e))},n.prototype._seek=function(r,i){this[Br].seek(r,i)},n.prototype._close=function(r){this[Br].close(r)}}Fs.DefaultKeyIterator=Bn;Fs.DefaultValueIterator=Ui});var Cu=nt(Ki=>{"use strict";b();var{AbstractIterator:kg,AbstractKeyIterator:Lg,AbstractValueIterator:Og}=ur(),$s=ge(),ee=Symbol("nut"),Fi=Symbol("undefer"),$i=Symbol("factory"),Wi=class extends kg{constructor(t,e){super(t,e),this[ee]=null,this[$i]=()=>t.iterator(e),this.db.defer(()=>this[Fi]())}},Di=class extends Lg{constructor(t,e){super(t,e),this[ee]=null,this[$i]=()=>t.keys(e),this.db.defer(()=>this[Fi]())}},Mi=class extends Og{constructor(t,e){super(t,e),this[ee]=null,this[$i]=()=>t.values(e),this.db.defer(()=>this[Fi]())}};for(let n of[Wi,Di,Mi])n.prototype[Fi]=function(){this.db.status==="open"&&(this[ee]=this[$i]())},n.prototype._next=function(t){this[ee]!==null?this[ee].next(t):this.db.status==="opening"?this.db.defer(()=>this._next(t)):this.nextTick(t,new $s("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},n.prototype._nextv=function(t,e,r){this[ee]!==null?this[ee].nextv(t,e,r):this.db.status==="opening"?this.db.defer(()=>this._nextv(t,e,r)):this.nextTick(r,new $s("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},n.prototype._all=function(t,e){this[ee]!==null?this[ee].all(e):this.db.status==="opening"?this.db.defer(()=>this._all(t,e)):this.nextTick(e,new $s("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},n.prototype._seek=function(t,e){this[ee]!==null?this[ee]._seek(t,e):this.db.status==="opening"&&this.db.defer(()=>this._seek(t,e))},n.prototype._close=function(t){this[ee]!==null?this[ee].close(t):this.db.status==="opening"?this.db.defer(()=>this._close(t)):this.nextTick(t)};Ki.DeferredIterator=Wi;Ki.DeferredKeyIterator=Di;Ki.DeferredValueIterator=Mi});var Vs=nt(Au=>{"use strict";b();var{fromCallback:Iu}=An(),Vi=ge(),{getCallback:Rg,getOptions:Bg}=Oi(),Gi=Symbol("promise"),pe=Symbol("status"),rn=Symbol("operations"),Pn=Symbol("finishClose"),nn=Symbol("closeCallbacks"),Ks=class{constructor(t){if(typeof t!="object"||t===null){let e=t===null?"null":typeof t;throw new TypeError(`The first argument must be an abstract-level database, received ${e}`)}this[rn]=[],this[nn]=[],this[pe]="open",this[Pn]=this[Pn].bind(this),this.db=t,this.db.attachResource(this),this.nextTick=t.nextTick}get length(){return this[rn].length}put(t,e,r){if(this[pe]!=="open")throw new Vi("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let i=this.db._checkKey(t)||this.db._checkValue(e);if(i)throw i;let o=r&&r.sublevel!=null?r.sublevel:this.db,s=r,c=o.keyEncoding(r&&r.keyEncoding),l=o.valueEncoding(r&&r.valueEncoding),g=c.format;r={...r,keyEncoding:g,valueEncoding:l.format},o!==this.db&&(r.sublevel=null);let w=o.prefixKey(c.encode(t),g),v=l.encode(e);return this._put(w,v,r),this[rn].push({...s,type:"put",key:t,value:e}),this}_put(t,e,r){}del(t,e){if(this[pe]!=="open")throw new Vi("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let r=this.db._checkKey(t);if(r)throw r;let i=e&&e.sublevel!=null?e.sublevel:this.db,o=e,s=i.keyEncoding(e&&e.keyEncoding),c=s.format;return e={...e,keyEncoding:c},i!==this.db&&(e.sublevel=null),this._del(i.prefixKey(s.encode(t),c),e),this[rn].push({...o,type:"del",key:t}),this}_del(t,e){}clear(){if(this[pe]!=="open")throw new Vi("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[rn]=[],this}_clear(){}write(t,e){return e=Rg(t,e),e=Iu(e,Gi),t=Bg(t),this[pe]!=="open"?this.nextTick(e,new Vi("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(e):(this[pe]="writing",this._write(t,r=>{this[pe]="closing",this[nn].push(()=>e(r)),r||this.db.emit("batch",this[rn]),this._close(this[Pn])})),e[Gi]}_write(t,e){}close(t){return t=Iu(t,Gi),this[pe]==="closing"?this[nn].push(t):this[pe]==="closed"?this.nextTick(t):(this[nn].push(t),this[pe]!=="writing"&&(this[pe]="closing",this._close(this[Pn]))),t[Gi]}_close(t){this.nextTick(t)}[Pn](){this[pe]="closed",this.db.detachResource(this);let t=this[nn];this[nn]=[];for(let e of t)e()}};Au.AbstractChainedBatch=Ks});var Lu=nt(ku=>{"use strict";b();var{AbstractChainedBatch:Pg}=Vs(),Ng=ge(),on=Symbol("encoded"),Gs=class extends Pg{constructor(t){super(t),this[on]=[]}_put(t,e,r){this[on].push({...r,type:"put",key:t,value:e})}_del(t,e){this[on].push({...e,type:"del",key:t})}_clear(){this[on]=[]}_write(t,e){this.db.status==="opening"?this.db.defer(()=>this._write(t,e)):this.db.status==="open"?this[on].length===0?this.nextTick(e):this.db._batch(this[on],t,e):this.nextTick(e,new Ng("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};ku.DefaultChainedBatch=Gs});var Bu=nt((cw,Ru)=>{"use strict";b();var Ou=ge(),Ug=Object.prototype.hasOwnProperty,Wg=new Set(["lt","lte","gt","gte"]);Ru.exports=function(n,t){let e={};for(let r in n)if(Ug.call(n,r)&&!(r==="keyEncoding"||r==="valueEncoding")){if(r==="start"||r==="end")throw new Ou(`The legacy range option '${r}' has been removed`,{code:"LEVEL_LEGACY"});if(r==="encoding")throw new Ou("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});Wg.has(r)?e[r]=t.encode(n[r]):e[r]=n[r]}return e.reverse=!!e.reverse,e.limit=Number.isInteger(e.limit)&&e.limit>=0?e.limit:-1,e}});var qs=nt((lw,Nu)=>{b();var Pu;Nu.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:K):n=>(Pu||(Pu=Promise.resolve())).then(n).catch(t=>setTimeout(()=>{throw t},0))});var Du=nt((hw,Wu)=>{"use strict";b();var Uu=qs();Wu.exports=function(n,...t){t.length===0?Uu(n):Uu(()=>n(...t))}});var Mu=nt(qi=>{"use strict";b();var{AbstractIterator:Dg,AbstractKeyIterator:Mg,AbstractValueIterator:Fg}=ur(),sn=Symbol("unfix"),we=Symbol("iterator"),Nr=Symbol("handleOne"),lr=Symbol("handleMany"),$e=Symbol("callback"),Nn=class extends Dg{constructor(t,e,r,i){super(t,e),this[we]=r,this[sn]=i,this[Nr]=this[Nr].bind(this),this[lr]=this[lr].bind(this),this[$e]=null}[Nr](t,e,r){let i=this[$e];if(t)return i(t);e!==void 0&&(e=this[sn](e)),i(t,e,r)}[lr](t,e){let r=this[$e];if(t)return r(t);for(let i of e){let o=i[0];o!==void 0&&(i[0]=this[sn](o))}r(t,e)}},Un=class extends Mg{constructor(t,e,r,i){super(t,e),this[we]=r,this[sn]=i,this[Nr]=this[Nr].bind(this),this[lr]=this[lr].bind(this),this[$e]=null}[Nr](t,e){let r=this[$e];if(t)return r(t);e!==void 0&&(e=this[sn](e)),r(t,e)}[lr](t,e){let r=this[$e];if(t)return r(t);for(let i=0;i{"use strict";b();var js=ge(),{Buffer:zs}=Cr()||{},{AbstractSublevelIterator:$g,AbstractSublevelKeyIterator:Kg,AbstractSublevelValueIterator:Vg}=Mu(),Ke=Symbol("prefix"),Fu=Symbol("upperBound"),Dn=Symbol("prefixRange"),oe=Symbol("parent"),Hs=Symbol("unfix"),$u=new TextEncoder,Gg={separator:"!"};Ku.exports=function({AbstractLevel:n}){class t extends n{static defaults(r){if(typeof r=="string")throw new js("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(r&&r.open)throw new js("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return r==null?Gg:r.separator?r:{...r,separator:"!"}}constructor(r,i,o){let{separator:s,manifest:c,...l}=t.defaults(o);i=jg(i,s);let g=s.charCodeAt(0)+1,w=r[oe]||r;if(!$u.encode(i).every(d=>d>g&&d<127))throw new js(`Prefix must use bytes > ${g} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(qg(w,c),l);let v=(r.prefix||"")+s+i+s,E=v.slice(0,-1)+String.fromCharCode(g);this[oe]=w,this[Ke]=new ji(v),this[Fu]=new ji(E),this[Hs]=new Js,this.nextTick=w.nextTick}prefixKey(r,i){if(i==="utf8")return this[Ke].utf8+r;if(r.byteLength===0)return this[Ke][i];if(i==="view"){let o=this[Ke].view,s=new Uint8Array(o.byteLength+r.byteLength);return s.set(o,0),s.set(r,o.byteLength),s}else{let o=this[Ke].buffer;return zs.concat([o,r],o.byteLength+r.byteLength)}}[Dn](r,i){r.gte!==void 0?r.gte=this.prefixKey(r.gte,i):r.gt!==void 0?r.gt=this.prefixKey(r.gt,i):r.gte=this[Ke][i],r.lte!==void 0?r.lte=this.prefixKey(r.lte,i):r.lt!==void 0?r.lt=this.prefixKey(r.lt,i):r.lte=this[Fu][i]}get prefix(){return this[Ke].utf8}get db(){return this[oe]}_open(r,i){this[oe].open({passive:!0},i)}_put(r,i,o,s){this[oe].put(r,i,o,s)}_get(r,i,o){this[oe].get(r,i,o)}_getMany(r,i,o){this[oe].getMany(r,i,o)}_del(r,i,o){this[oe].del(r,i,o)}_batch(r,i,o){this[oe].batch(r,i,o)}_clear(r,i){this[Dn](r,r.keyEncoding),this[oe].clear(r,i)}_iterator(r){this[Dn](r,r.keyEncoding);let i=this[oe].iterator(r),o=this[Hs].get(this[Ke].utf8.length,r.keyEncoding);return new $g(this,r,i,o)}_keys(r){this[Dn](r,r.keyEncoding);let i=this[oe].keys(r),o=this[Hs].get(this[Ke].utf8.length,r.keyEncoding);return new Kg(this,r,i,o)}_values(r){this[Dn](r,r.keyEncoding);let i=this[oe].values(r);return new Vg(this,r,i)}}return{AbstractSublevel:t}};var qg=function(n,t){return{...n.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...t,encodings:{utf8:Qs(n,"utf8"),buffer:Qs(n,"buffer"),view:Qs(n,"view")}}},Qs=function(n,t){return n.supports.encodings[t]?n.keyEncoding(t).name===t:!1},ji=class{constructor(t){this.utf8=t,this.view=$u.encode(t),this.buffer=zs?zs.from(this.view.buffer,0,this.view.byteLength):{}}},Js=class{constructor(){this.cache=new Map}get(t,e){let r=this.cache.get(e);return r===void 0&&(e==="view"?r=function(i,o){return o.subarray(i)}.bind(null,t):r=function(i,o){return o.slice(i)}.bind(null,t),this.cache.set(e,r)),r}},jg=function(n,t){let e=0,r=n.length;for(;ee&&n[r-1]===t;)r--;return n.slice(e,r)}});var ea=nt(ta=>{"use strict";b();var{supports:Hg}=Xc(),{Transcoder:Qg}=cu(),{EventEmitter:zg}=vu(),{fromCallback:fr}=An(),ve=ge(),{AbstractIterator:Ur}=ur(),{DefaultKeyIterator:Jg,DefaultValueIterator:Yg}=xu(),{DeferredIterator:Xg,DeferredKeyIterator:Zg,DeferredValueIterator:td}=Cu(),{DefaultChainedBatch:Gu}=Lu(),{getCallback:Wr,getOptions:hr}=Oi(),Hi=Bu(),gt=Symbol("promise"),Ve=Symbol("landed"),Dr=Symbol("resources"),Ys=Symbol("closeResources"),Mn=Symbol("operations"),Fn=Symbol("undefer"),Qi=Symbol("deferOpen"),qu=Symbol("options"),mt=Symbol("status"),Mr=Symbol("defaultOptions"),an=Symbol("transcoder"),zi=Symbol("keyEncoding"),Xs=Symbol("valueEncoding"),ed=()=>{},$n=class extends zg{constructor(t,e){if(super(),typeof t!="object"||t===null)throw new TypeError("The first argument 'manifest' must be an object");e=hr(e);let{keyEncoding:r,valueEncoding:i,passive:o,...s}=e;this[Dr]=new Set,this[Mn]=[],this[Qi]=!0,this[qu]=s,this[mt]="opening",this.supports=Hg(t,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:t.snapshots!==!1,permanence:t.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:t.encodings||{},events:Object.assign({},t.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[an]=new Qg(rd(this)),this[zi]=this[an].encoding(r||"utf8"),this[Xs]=this[an].encoding(i||"utf8");for(let c of this[an].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[Mr]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[zi].commonName,valueEncoding:this[Xs].commonName}),key:Object.freeze({keyEncoding:this[zi].commonName})},this.nextTick(()=>{this[Qi]&&this.open({passive:!1},ed)})}get status(){return this[mt]}keyEncoding(t){return this[an].encoding(t??this[zi])}valueEncoding(t){return this[an].encoding(t??this[Xs])}open(t,e){e=Wr(t,e),e=fr(e,gt),t={...this[qu],...hr(t)},t.createIfMissing=t.createIfMissing!==!1,t.errorIfExists=!!t.errorIfExists;let r=i=>{this[mt]==="closing"||this[mt]==="opening"?this.once(Ve,i?()=>r(i):r):this[mt]!=="open"?e(new ve("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):e()};return t.passive?this[mt]==="opening"?this.once(Ve,r):this.nextTick(r):this[mt]==="closed"||this[Qi]?(this[Qi]=!1,this[mt]="opening",this.emit("opening"),this._open(t,i=>{if(i){this[mt]="closed",this[Ys](()=>{this.emit(Ve),r(i)}),this[Fn]();return}this[mt]="open",this[Fn](),this.emit(Ve),this[mt]==="open"&&this.emit("open"),this[mt]==="open"&&this.emit("ready"),r()})):this[mt]==="open"?this.nextTick(r):this.once(Ve,()=>this.open(t,e)),e[gt]}_open(t,e){this.nextTick(e)}close(t){t=fr(t,gt);let e=r=>{this[mt]==="opening"||this[mt]==="closing"?this.once(Ve,r?e(r):e):this[mt]!=="closed"?t(new ve("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:r})):t()};if(this[mt]==="open"){this[mt]="closing",this.emit("closing");let r=i=>{this[mt]="open",this[Fn](),this.emit(Ve),e(i)};this[Ys](()=>{this._close(i=>{if(i)return r(i);this[mt]="closed",this[Fn](),this.emit(Ve),this[mt]==="closed"&&this.emit("closed"),e()})})}else this[mt]==="closed"?this.nextTick(e):this.once(Ve,()=>this.close(t));return t[gt]}[Ys](t){if(this[Dr].size===0)return this.nextTick(t);let e=this[Dr].size,r=!0,i=()=>{--e===0&&(r?this.nextTick(t):t())};for(let o of this[Dr])o.close(i);r=!1,this[Dr].clear()}_close(t){this.nextTick(t)}get(t,e,r){if(r=Wr(e,r),r=fr(r,gt),e=hr(e,this[Mr].entry),this[mt]==="opening")return this.defer(()=>this.get(t,e,r)),r[gt];if(cn(this,r))return r[gt];let i=this._checkKey(t);if(i)return this.nextTick(r,i),r[gt];let o=this.keyEncoding(e.keyEncoding),s=this.valueEncoding(e.valueEncoding),c=o.format,l=s.format;return(e.keyEncoding!==c||e.valueEncoding!==l)&&(e=Object.assign({},e,{keyEncoding:c,valueEncoding:l})),this._get(this.prefixKey(o.encode(t),c),e,(g,w)=>{if(g)return(g.code==="LEVEL_NOT_FOUND"||g.notFound||/NotFound/i.test(g))&&(g.code||(g.code="LEVEL_NOT_FOUND"),g.notFound||(g.notFound=!0),g.status||(g.status=404)),r(g);try{w=s.decode(w)}catch(v){return r(new ve("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:v}))}r(null,w)}),r[gt]}_get(t,e,r){this.nextTick(r,new Error("NotFound"))}getMany(t,e,r){if(r=Wr(e,r),r=fr(r,gt),e=hr(e,this[Mr].entry),this[mt]==="opening")return this.defer(()=>this.getMany(t,e,r)),r[gt];if(cn(this,r))return r[gt];if(!Array.isArray(t))return this.nextTick(r,new TypeError("The first argument 'keys' must be an array")),r[gt];if(t.length===0)return this.nextTick(r,null,[]),r[gt];let i=this.keyEncoding(e.keyEncoding),o=this.valueEncoding(e.valueEncoding),s=i.format,c=o.format;(e.keyEncoding!==s||e.valueEncoding!==c)&&(e=Object.assign({},e,{keyEncoding:s,valueEncoding:c}));let l=new Array(t.length);for(let g=0;g{if(g)return r(g);try{for(let v=0;vthis.put(t,e,r,i)),i[gt];if(cn(this,i))return i[gt];let o=this._checkKey(t)||this._checkValue(e);if(o)return this.nextTick(i,o),i[gt];let s=this.keyEncoding(r.keyEncoding),c=this.valueEncoding(r.valueEncoding),l=s.format,g=c.format;(r.keyEncoding!==l||r.valueEncoding!==g)&&(r=Object.assign({},r,{keyEncoding:l,valueEncoding:g}));let w=this.prefixKey(s.encode(t),l),v=c.encode(e);return this._put(w,v,r,E=>{if(E)return i(E);this.emit("put",t,e),i()}),i[gt]}_put(t,e,r,i){this.nextTick(i)}del(t,e,r){if(r=Wr(e,r),r=fr(r,gt),e=hr(e,this[Mr].key),this[mt]==="opening")return this.defer(()=>this.del(t,e,r)),r[gt];if(cn(this,r))return r[gt];let i=this._checkKey(t);if(i)return this.nextTick(r,i),r[gt];let o=this.keyEncoding(e.keyEncoding),s=o.format;return e.keyEncoding!==s&&(e=Object.assign({},e,{keyEncoding:s})),this._del(this.prefixKey(o.encode(t),s),e,c=>{if(c)return r(c);this.emit("del",t),r()}),r[gt]}_del(t,e,r){this.nextTick(r)}batch(t,e,r){if(!arguments.length){if(this[mt]==="opening")return new Gu(this);if(this[mt]!=="open")throw new ve("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof t=="function"?r=t:r=Wr(e,r),r=fr(r,gt),e=hr(e,this[Mr].empty),this[mt]==="opening")return this.defer(()=>this.batch(t,e,r)),r[gt];if(cn(this,r))return r[gt];if(!Array.isArray(t))return this.nextTick(r,new TypeError("The first argument 'operations' must be an array")),r[gt];if(t.length===0)return this.nextTick(r),r[gt];let i=new Array(t.length),{keyEncoding:o,valueEncoding:s,...c}=e;for(let l=0;l{if(l)return r(l);this.emit("batch",t),r()}),r[gt]}_batch(t,e,r){this.nextTick(r)}sublevel(t,e){return this._sublevel(t,Zs.defaults(e))}_sublevel(t,e){return new Zs(this,t,e)}prefixKey(t,e){return t}clear(t,e){if(e=Wr(t,e),e=fr(e,gt),t=hr(t,this[Mr].empty),this[mt]==="opening")return this.defer(()=>this.clear(t,e)),e[gt];if(cn(this,e))return e[gt];let r=t,i=this.keyEncoding(t.keyEncoding);return t=Hi(t,i),t.keyEncoding=i.format,t.limit===0?this.nextTick(e):this._clear(t,o=>{if(o)return e(o);this.emit("clear",r),e()}),e[gt]}_clear(t,e){this.nextTick(e)}iterator(t){let e=this.keyEncoding(t&&t.keyEncoding),r=this.valueEncoding(t&&t.valueEncoding);if(t=Hi(t,e),t.keys=t.keys!==!1,t.values=t.values!==!1,t[Ur.keyEncoding]=e,t[Ur.valueEncoding]=r,t.keyEncoding=e.format,t.valueEncoding=r.format,this[mt]==="opening")return new Xg(this,t);if(this[mt]!=="open")throw new ve("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(t)}_iterator(t){return new Ur(this,t)}keys(t){let e=this.keyEncoding(t&&t.keyEncoding),r=this.valueEncoding(t&&t.valueEncoding);if(t=Hi(t,e),t[Ur.keyEncoding]=e,t[Ur.valueEncoding]=r,t.keyEncoding=e.format,t.valueEncoding=r.format,this[mt]==="opening")return new Zg(this,t);if(this[mt]!=="open")throw new ve("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(t)}_keys(t){return new Jg(this,t)}values(t){let e=this.keyEncoding(t&&t.keyEncoding),r=this.valueEncoding(t&&t.valueEncoding);if(t=Hi(t,e),t[Ur.keyEncoding]=e,t[Ur.valueEncoding]=r,t.keyEncoding=e.format,t.valueEncoding=r.format,this[mt]==="opening")return new td(this,t);if(this[mt]!=="open")throw new ve("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(t)}_values(t){return new Yg(this,t)}defer(t){if(typeof t!="function")throw new TypeError("The first argument must be a function");this[Mn].push(t)}[Fn](){if(this[Mn].length===0)return;let t=this[Mn];this[Mn]=[];for(let e of t)e()}attachResource(t){if(typeof t!="object"||t===null||typeof t.close!="function")throw new TypeError("The first argument must be a resource object");this[Dr].add(t)}detachResource(t){this[Dr].delete(t)}_chainedBatch(){return new Gu(this)}_checkKey(t){if(t==null)return new ve("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(t){if(t==null)return new ve("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};$n.prototype.nextTick=Du();var{AbstractSublevel:Zs}=Vu()({AbstractLevel:$n});ta.AbstractLevel=$n;ta.AbstractSublevel=Zs;var cn=function(n,t){return n[mt]!=="open"?(n.nextTick(t,new ve("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},rd=function(n){return Object.keys(n.supports.encodings).filter(t=>!!n.supports.encodings[t])}});var Ji=nt(Fr=>{"use strict";b();Fr.AbstractLevel=ea().AbstractLevel;Fr.AbstractSublevel=ea().AbstractSublevel;Fr.AbstractIterator=ur().AbstractIterator;Fr.AbstractKeyIterator=ur().AbstractKeyIterator;Fr.AbstractValueIterator=ur().AbstractValueIterator;Fr.AbstractChainedBatch=Vs().AbstractChainedBatch});var Hu=nt((Sw,ju)=>{b();ju.exports=id;var nd=qs();function id(n,t,e){if(typeof t!="number")throw new Error("second argument must be a Number");let r,i,o,s,c,l=!0,g;Array.isArray(n)?(r=[],o=i=n.length):(s=Object.keys(n),r={},o=i=s.length);function w(E){function d(){e&&e(E,r),e=null}l?nd(d):d()}function v(E,d,y){if(r[E]=y,d&&(c=!0),--o===0||d)w(d);else if(!c&&g{"use strict";b();Qu.exports=function(t){let e=t.gte!==void 0?t.gte:t.gt!==void 0?t.gt:void 0,r=t.lte!==void 0?t.lte:t.lt!==void 0?t.lt:void 0,i=t.gte===void 0,o=t.lte===void 0;return e!==void 0&&r!==void 0?IDBKeyRange.bound(e,r,i,o):e!==void 0?IDBKeyRange.lowerBound(e,i):r!==void 0?IDBKeyRange.upperBound(r,o):null}});var na=nt((Cw,zu)=>{"use strict";b();var od=new TextEncoder;zu.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):od.encode(n)}});var tl=nt(Zu=>{"use strict";b();var{AbstractIterator:sd}=Ji(),Ju=ra(),Yi=na(),Le=Symbol("cache"),Ge=Symbol("finished"),se=Symbol("options"),qe=Symbol("currentOptions"),$r=Symbol("position"),ia=Symbol("location"),un=Symbol("first"),Yu={},oa=class extends sd{constructor(t,e,r){super(t,r),this[Le]=[],this[Ge]=this.limit===0,this[se]=r,this[qe]={...r},this[$r]=void 0,this[ia]=e,this[un]=!0}_nextv(t,e,r){if(this[un]=!1,this[Ge])return this.nextTick(r,null,[]);if(this[Le].length>0)return t=Math.min(t,this[Le].length),this.nextTick(r,null,this[Le].splice(0,t));this[$r]!==void 0&&(this[se].reverse?(this[qe].lt=this[$r],this[qe].lte=void 0):(this[qe].gt=this[$r],this[qe].gte=void 0));let i;try{i=Ju(this[qe])}catch{return this[Ge]=!0,this.nextTick(r,null,[])}let o=this.db.db.transaction([this[ia]],"readonly"),s=o.objectStore(this[ia]),c=[];if(this[se].reverse){let l=!this[se].values&&s.openKeyCursor?"openKeyCursor":"openCursor";s[l](i,"prev").onsuccess=g=>{let w=g.target.result;if(w){let{key:v,value:E}=w;this[$r]=v,c.push([this[se].keys&&v!==void 0?Yi(v):void 0,this[se].values&&E!==void 0?Yi(E):void 0]),c.length{if(l===void 0||g===void 0)return;let v=Math.max(l.length,g.length);v===0||t===1/0?this[Ge]=!0:this[$r]=l[v-1],c.length=v;for(let E=0;E{l=v.target.result,w()}:(l=[],this.nextTick(w)),this[se].values?s.getAll(i,t<1/0?t:void 0).onsuccess=v=>{g=v.target.result,w()}:(g=[],this.nextTick(w))}o.onabort=()=>{r(o.error||new Error("aborted by user")),r=null},o.oncomplete=()=>{r(null,c),r=null}}_next(t){if(this[Le].length>0){let[e,r]=this[Le].shift();this.nextTick(t,null,e,r)}else if(this[Ge])this.nextTick(t);else{let e=Math.min(100,this.limit-this.count);this[un]&&(this[un]=!1,e=1),this._nextv(e,Yu,(r,i)=>{if(r)return t(r);this[Le]=i,this._next(t)})}}_all(t,e){this[un]=!1;let r=this[Le].splice(0,this[Le].length),i=this.limit-this.count-r.length;if(i<=0)return this.nextTick(e,null,r);this._nextv(i,Yu,(o,s)=>{if(o)return e(o);r.length>0&&(s=r.concat(s)),e(null,s)})}_seek(t,e){this[un]=!0,this[Le]=[],this[Ge]=!1,this[$r]=void 0,this[qe]={...this[se]};let r;try{r=Ju(this[se])}catch{this[Ge]=!0;return}r!==null&&!r.includes(t)?this[Ge]=!0:this[se].reverse?this[qe].lte=t:this[qe].gte=t}};Zu.Iterator=oa;function Xu(n){typeof n.commit=="function"&&n.commit()}});var rl=nt((Lw,el)=>{"use strict";b();el.exports=function(t,e,r,i,o){if(i.limit===0)return t.nextTick(o);let s=t.db.transaction([e],"readwrite"),c=s.objectStore(e),l=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let g=c.openKeyCursor?"openKeyCursor":"openCursor",w=i.reverse?"prev":"next";c[g](r,w).onsuccess=function(v){let E=v.target.result;E&&(c.delete(E.key).onsuccess=function(){(i.limit<=0||++l{"use strict";b();var{AbstractLevel:ad}=Ji(),nl=ge(),cd=Hu(),{fromCallback:ud}=An(),{Iterator:ld}=tl(),il=na(),fd=rl(),hd=ra(),sl="level-js-",Kn=Symbol("idb"),sa=Symbol("namePrefix"),je=Symbol("location"),aa=Symbol("version"),Kr=Symbol("store"),Vn=Symbol("onComplete"),ol=Symbol("promise"),Xi=class extends ad{constructor(t,e,r){if(typeof e=="function"||typeof r=="function")throw new nl("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:i,version:o,...s}=e||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},s),typeof t!="string")throw new Error("constructor requires a location string argument");this[je]=t,this[sa]=i??sl,this[aa]=parseInt(o||1,10),this[Kn]=null}get location(){return this[je]}get namePrefix(){return this[sa]}get version(){return this[aa]}get db(){return this[Kn]}get type(){return"browser-level"}_open(t,e){let r=indexedDB.open(this[sa]+this[je],this[aa]);r.onerror=function(){e(r.error||new Error("unknown error"))},r.onsuccess=()=>{this[Kn]=r.result,e()},r.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[je])||o.createObjectStore(this[je])}}[Kr](t){return this[Kn].transaction([this[je]],t).objectStore(this[je])}[Vn](t,e){let r=t.transaction;r.onabort=function(){e(r.error||new Error("aborted by user"))},r.oncomplete=function(){e(null,t.result)}}_get(t,e,r){let i=this[Kr]("readonly"),o;try{o=i.get(t)}catch(s){return this.nextTick(r,s)}this[Vn](o,function(s,c){if(s)return r(s);if(c===void 0)return r(new nl("Entry not found",{code:"LEVEL_NOT_FOUND"}));r(null,il(c))})}_getMany(t,e,r){let i=this[Kr]("readonly"),o=t.map(s=>c=>{let l;try{l=i.get(s)}catch(g){return c(g)}l.onsuccess=()=>{let g=l.result;c(null,g===void 0?g:il(g))},l.onerror=g=>{g.stopPropagation(),c(l.error)}});cd(o,16,r)}_del(t,e,r){let i=this[Kr]("readwrite"),o;try{o=i.delete(t)}catch(s){return this.nextTick(r,s)}this[Vn](o,r)}_put(t,e,r,i){let o=this[Kr]("readwrite"),s;try{s=o.put(e,t)}catch(c){return this.nextTick(i,c)}this[Vn](s,i)}_iterator(t){return new ld(this,this[je],t)}_batch(t,e,r){let i=this[Kr]("readwrite"),o=i.transaction,s=0,c;o.onabort=function(){r(c||o.error||new Error("aborted by user"))},o.oncomplete=function(){r()};function l(){let g=t[s++],w=g.key,v;try{v=g.type==="del"?i.delete(w):i.put(g.value,w)}catch(E){c=E,o.abort();return}s=0)return fd(this,this[je],r,t,e);try{let o=this[Kr]("readwrite");i=r?o.delete(r):o.clear()}catch(o){return this.nextTick(e,o)}this[Vn](i,e)}_close(t){this[Kn].close(),this.nextTick(t)}};Xi.destroy=function(n,t,e){typeof t=="function"&&(e=t,t=sl),e=ud(e,ol);let r=indexedDB.deleteDatabase(t+n);return r.onsuccess=function(){e()},r.onerror=function(i){e(i)},e[ol]};al.BrowserLevel=Xi});var ll=nt(ul=>{b();ul.Level=cl().BrowserLevel});var gl=nt((Uw,hl)=>{"use strict";b();hl.exports=pd;var At=0,St=1;function ae(n,t,e,r,i,o){this._color=n,this.key=t,this.value=e,this.left=r,this.right=i,this._count=o}function Oe(n){return new ae(n._color,n.key,n.value,n.left,n.right,n._count)}function gr(n,t){return new ae(n,t.key,t.value,t.left,t.right,t._count)}function kt(n){n._count=1+(n.left?n.left._count:0)+(n.right?n.right._count:0)}function dr(n,t){this._compare=n,this.root=t}var Yt=dr.prototype;Object.defineProperty(Yt,"keys",{get:function(){var n=[];return this.forEach(function(t,e){n.push(t)}),n}});Object.defineProperty(Yt,"values",{get:function(){var n=[];return this.forEach(function(t,e){n.push(e)}),n}});Object.defineProperty(Yt,"length",{get:function(){return this.root?this.root._count:0}});Yt.insert=function(n,t){for(var e=this._compare,r=this.root,i=[],o=[];r;){var s=e(n,r.key);i.push(r),o.push(s),s<=0?r=r.left:r=r.right}i.push(new ae(At,n,t,null,null,1));for(var c=i.length-2;c>=0;--c){var r=i[c];o[c]<=0?i[c]=new ae(r._color,r.key,r.value,i[c+1],r.right,r._count+1):i[c]=new ae(r._color,r.key,r.value,r.left,i[c+1],r._count+1)}for(var c=i.length-1;c>1;--c){var l=i[c-1],r=i[c];if(l._color===St||r._color===St)break;var g=i[c-2];if(g.left===l)if(l.left===r){var w=g.right;if(w&&w._color===At)l._color=St,g.right=gr(St,w),g._color=At,c-=1;else{if(g._color=At,g.left=l.right,l._color=St,l.right=g,i[c-2]=l,i[c-1]=r,kt(g),kt(l),c>=3){var v=i[c-3];v.left===g?v.left=l:v.right=l}break}}else{var w=g.right;if(w&&w._color===At)l._color=St,g.right=gr(St,w),g._color=At,c-=1;else{if(l.right=r.left,g._color=At,g.left=r.right,r._color=St,r.left=l,r.right=g,i[c-2]=r,i[c-1]=l,kt(g),kt(l),kt(r),c>=3){var v=i[c-3];v.left===g?v.left=r:v.right=r}break}}else if(l.right===r){var w=g.left;if(w&&w._color===At)l._color=St,g.left=gr(St,w),g._color=At,c-=1;else{if(g._color=At,g.right=l.left,l._color=St,l.left=g,i[c-2]=l,i[c-1]=r,kt(g),kt(l),c>=3){var v=i[c-3];v.right===g?v.right=l:v.left=l}break}}else{var w=g.left;if(w&&w._color===At)l._color=St,g.left=gr(St,w),g._color=At,c-=1;else{if(l.left=r.right,g._color=At,g.right=r.left,r._color=St,r.right=l,r.left=g,i[c-2]=r,i[c-1]=l,kt(g),kt(l),kt(r),c>=3){var v=i[c-3];v.right===g?v.right=r:v.left=r}break}}}return i[0]._color=St,new dr(e,i[0])};function ca(n,t){if(t.left){var e=ca(n,t.left);if(e)return e}var e=n(t.key,t.value);if(e)return e;if(t.right)return ca(n,t.right)}function ua(n,t,e,r){var i=t(n,r.key);if(i<=0){if(r.left){var o=ua(n,t,e,r.left);if(o)return o}var o=e(r.key,r.value);if(o)return o}if(r.right)return ua(n,t,e,r.right)}function la(n,t,e,r,i){var o=e(n,i.key),s=e(t,i.key),c;if(o<=0&&(i.left&&(c=la(n,t,e,r,i.left),c)||s>0&&(c=r(i.key,i.value),c)))return c;if(s>0&&i.right)return la(n,t,e,r,i.right)}Yt.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return ca(t,this.root);case 2:return ua(e,this._compare,t,this.root);case 3:return this._compare(e,r)>=0?void 0:la(e,r,this._compare,t,this.root)}};Object.defineProperty(Yt,"begin",{get:function(){for(var n=[],t=this.root;t;)n.push(t),t=t.left;return new ce(this,n)}});Object.defineProperty(Yt,"end",{get:function(){for(var n=[],t=this.root;t;)n.push(t),t=t.right;return new ce(this,n)}});Yt.at=function(n){if(n<0)return new ce(this,[]);for(var t=this.root,e=[];;){if(e.push(t),t.left){if(n=t.right._count)break;t=t.right}else break}return new ce(this,[])};Yt.ge=function(n){for(var t=this._compare,e=this.root,r=[],i=0;e;){var o=t(n,e.key);r.push(e),o<=0&&(i=r.length),o<=0?e=e.left:e=e.right}return r.length=i,new ce(this,r)};Yt.gt=function(n){for(var t=this._compare,e=this.root,r=[],i=0;e;){var o=t(n,e.key);r.push(e),o<0&&(i=r.length),o<0?e=e.left:e=e.right}return r.length=i,new ce(this,r)};Yt.lt=function(n){for(var t=this._compare,e=this.root,r=[],i=0;e;){var o=t(n,e.key);r.push(e),o>0&&(i=r.length),o<=0?e=e.left:e=e.right}return r.length=i,new ce(this,r)};Yt.le=function(n){for(var t=this._compare,e=this.root,r=[],i=0;e;){var o=t(n,e.key);r.push(e),o>=0&&(i=r.length),o<0?e=e.left:e=e.right}return r.length=i,new ce(this,r)};Yt.find=function(n){for(var t=this._compare,e=this.root,r=[];e;){var i=t(n,e.key);if(r.push(e),i===0)return new ce(this,r);i<=0?e=e.left:e=e.right}return new ce(this,[])};Yt.remove=function(n){var t=this.find(n);return t?t.remove():this};Yt.get=function(n){for(var t=this._compare,e=this.root;e;){var r=t(n,e.key);if(r===0)return e.value;r<=0?e=e.left:e=e.right}};function ce(n,t){this.tree=n,this._stack=t}var me=ce.prototype;Object.defineProperty(me,"valid",{get:function(){return this._stack.length>0}});Object.defineProperty(me,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0});me.clone=function(){return new ce(this.tree,this._stack.slice())};function fl(n,t){n.key=t.key,n.value=t.value,n.left=t.left,n.right=t.right,n._color=t._color,n._count=t._count}function gd(n){for(var t,e,r,i,o=n.length-1;o>=0;--o){if(t=n[o],o===0){t._color=St;return}if(e=n[o-1],e.left===t){if(r=e.right,r.right&&r.right._color===At){if(r=e.right=Oe(r),i=r.right=Oe(r.right),e.right=r.left,r.left=e,r.right=i,r._color=e._color,t._color=St,e._color=St,i._color=St,kt(e),kt(r),o>1){var s=n[o-2];s.left===e?s.left=r:s.right=r}n[o-1]=r;return}else if(r.left&&r.left._color===At){if(r=e.right=Oe(r),i=r.left=Oe(r.left),e.right=i.left,r.left=i.right,i.left=e,i.right=r,i._color=e._color,e._color=St,r._color=St,t._color=St,kt(e),kt(r),kt(i),o>1){var s=n[o-2];s.left===e?s.left=i:s.right=i}n[o-1]=i;return}if(r._color===St)if(e._color===At){e._color=St,e.right=gr(At,r);return}else{e.right=gr(At,r);continue}else{if(r=Oe(r),e.right=r.left,r.left=e,r._color=e._color,e._color=At,kt(e),kt(r),o>1){var s=n[o-2];s.left===e?s.left=r:s.right=r}n[o-1]=r,n[o]=e,o+11){var s=n[o-2];s.right===e?s.right=r:s.left=r}n[o-1]=r;return}else if(r.right&&r.right._color===At){if(r=e.left=Oe(r),i=r.right=Oe(r.right),e.left=i.right,r.right=i.left,i.right=e,i.left=r,i._color=e._color,e._color=St,r._color=St,t._color=St,kt(e),kt(r),kt(i),o>1){var s=n[o-2];s.right===e?s.right=i:s.left=i}n[o-1]=i;return}if(r._color===St)if(e._color===At){e._color=St,e.left=gr(At,r);return}else{e.left=gr(At,r);continue}else{if(r=Oe(r),e.left=r.right,r.right=e,r._color=e._color,e._color=At,kt(e),kt(r),o>1){var s=n[o-2];s.right===e?s.right=r:s.left=r}n[o-1]=r,n[o]=e,o+1=0;--r){var e=n[r];e.left===n[r+1]?t[r]=new ae(e._color,e.key,e.value,t[r+1],e.right,e._count):t[r]=new ae(e._color,e.key,e.value,e.left,t[r+1],e._count)}if(e=t[t.length-1],e.left&&e.right){var i=t.length;for(e=e.left;e.right;)t.push(e),e=e.right;var o=t[i-1];t.push(new ae(e._color,o.key,o.value,e.left,e.right,e._count)),t[i-1].key=e.key,t[i-1].value=e.value;for(var r=t.length-2;r>=i;--r)e=t[r],t[r]=new ae(e._color,e.key,e.value,e.left,t[r+1],e._count);t[i-1].left=t[i]}if(e=t[t.length-1],e._color===At){var s=t[t.length-2];s.left===e?s.left=null:s.right===e&&(s.right=null),t.pop();for(var r=0;r0)return this._stack[this._stack.length-1].key},enumerable:!0});Object.defineProperty(me,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0});Object.defineProperty(me,"index",{get:function(){var n=0,t=this._stack;if(t.length===0){var e=this.tree.root;return e?e._count:0}else t[t.length-1].left&&(n=t[t.length-1].left._count);for(var r=t.length-2;r>=0;--r)t[r+1]===t[r].right&&(++n,t[r].left&&(n+=t[r].left._count));return n},enumerable:!0});me.next=function(){var n=this._stack;if(n.length!==0){var t=n[n.length-1];if(t.right)for(t=t.right;t;)n.push(t),t=t.left;else for(n.pop();n.length>0&&n[n.length-1].right===t;)t=n[n.length-1],n.pop()}};Object.defineProperty(me,"hasNext",{get:function(){var n=this._stack;if(n.length===0)return!1;if(n[n.length-1].right)return!0;for(var t=n.length-1;t>0;--t)if(n[t-1].left===n[t])return!0;return!1}});me.update=function(n){var t=this._stack;if(t.length===0)throw new Error("Can't update empty node!");var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new ae(r._color,r.key,n,r.left,r.right,r._count);for(var i=t.length-2;i>=0;--i)r=t[i],r.left===t[i+1]?e[i]=new ae(r._color,r.key,r.value,e[i+1],r.right,r._count):e[i]=new ae(r._color,r.key,r.value,r.left,e[i+1],r._count);return new dr(this.tree._compare,e[0])};me.prev=function(){var n=this._stack;if(n.length!==0){var t=n[n.length-1];if(t.left)for(t=t.left;t;)n.push(t),t=t.right;else for(n.pop();n.length>0&&n[n.length-1].left===t;)t=n[n.length-1],n.pop()}};Object.defineProperty(me,"hasPrev",{get:function(){var n=this._stack;if(n.length===0)return!1;if(n[n.length-1].left)return!0;for(var t=n.length-1;t>0;--t)if(n[t-1].right===n[t])return!0;return!1}});function dd(n,t){return nt?1:0}function pd(n){return new dr(n||dd,null)}});var wl=nt(yl=>{"use strict";b();var{AbstractLevel:md,AbstractIterator:yd,AbstractKeyIterator:wd,AbstractValueIterator:vd}=Ji(),dl=ge(),pl=gl(),_d=new Set(["gt","gte","lt","lte"]),He=Symbol("none"),Gt=Symbol("tree"),vt=Symbol("iterator"),ue=Symbol("lowerBound"),pr=Symbol("upperBound"),ml=Symbol("outOfRange"),Zi=Symbol("reverse"),fa=Symbol("options"),re=Symbol("test"),ye=Symbol("advance"),io=Symbol("init");function Re(n,t){if(typeof n=="string")return nt?1:0;let e=Math.min(n.byteLength,t.byteLength);for(let r=0;r0}function Sd(n){return Re(n,this[pr])>=0}function Ed(n){return Re(n,this[pr])<0}function Td(n){return Re(n,this[pr])<=0}var to=class extends yd{constructor(t,e){super(t,e),this[io](t[Gt],e)}_next(t){if(!this[vt].valid)return this.nextTick(t);let e=this[vt].key,r=this[vt].value;if(!this[re](e))return this.nextTick(t);this[vt][this[ye]](),this.nextTick(t,null,e,r)}_nextv(t,e,r){let i=this[vt],o=[];for(;i.valid&&o.length0:Re(t,this[ue])>=0:"gte"in this[fa]?Re(t,this[ue])<0:Re(t,this[ue])<=0:!0},n.prototype._seek=function(t,e){this[ml](t)?(this[vt]=this[vt].tree.end,this[vt].next()):this[Zi]?this[vt]=this[vt].tree.le(t):this[vt]=this[vt].tree.ge(t)};var no=class extends md{constructor(t,e,r){if(typeof t=="object"&&t!==null&&(e=t),typeof t=="function"||typeof e=="function"||typeof r=="function")throw new dl("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{storeEncoding:i,...o}=e||{};if(i=i||"buffer",!["buffer","view","utf8"].includes(i))throw new dl("The storeEncoding option must be 'buffer', 'view' or 'utf8'",{code:"LEVEL_ENCODING_NOT_SUPPORTED"});super({seek:!0,permanence:!1,createIfMissing:!1,errorIfExists:!1,encodings:{[i]:!0}},o),this[Gt]=pl(Re)}_put(t,e,r,i){let o=this[Gt].find(t);o.valid?this[Gt]=o.update(e):this[Gt]=this[Gt].insert(t,e),this.nextTick(i)}_get(t,e,r){let i=this[Gt].get(t);if(typeof i>"u")return this.nextTick(r,new Error("NotFound"));this.nextTick(r,null,i)}_getMany(t,e,r){this.nextTick(r,null,t.map(i=>this[Gt].get(i)))}_del(t,e,r){this[Gt]=this[Gt].remove(t),this.nextTick(r)}_batch(t,e,r){let i=this[Gt];for(let o of t){let s=o.key,c=i.find(s);o.type==="put"?i=c.valid?c.update(o.value):i.insert(s,o.value):i=c.remove()}this[Gt]=i,this.nextTick(r)}_clear(t,e){if(t.limit===-1&&!Object.keys(t).some(xd))return this[Gt]=pl(Re),this.nextTick(e);let r=this._keys({...t}),i=r.limit,o=0,s=()=>{for(let c=0;c<500;c++){if(++o>i||!r[vt].valid||!r[re](r[vt].key))return e();this[Gt]=this[Gt].remove(r[vt].key),r[vt][r[ye]]()}this.nextTick(s)};this.nextTick(s)}_iterator(t){return new to(this,t)}_keys(t){return new eo(this,t)}_values(t){return new ro(this,t)}};yl.MemoryLevel=no;if(typeof $.default<"u"&&!$.default.browser&&typeof K<"u"&&typeof K.setImmediate=="function"){let n=K.setImmediate;no.prototype.nextTick=function(t,...e){e.length===0?n(t):n(()=>t(...e))}}function xd(n){return _d.has(n)}});var mr=nt((zw,ha)=>{b();typeof window<"u"?(window.global=window,K.fetch=window.fetch,ha.exports={Buffer:Cr().Buffer,Crypto:window.crypto}):ha.exports={Buffer:Cr().Buffer,Crypto:crypto}});var _a=nt((Nl,lo)=>{b();(function(n){"use strict";var t,e=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,i=Math.floor,o="[BigNumber Error] ",s=o+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,g=9007199254740991,w=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],v=1e7,E=1e9;function d(D){var G,it,et,O=Y.prototype={constructor:Y,toString:null,valueOf:null},ft=new Y(1),tt=20,lt=4,st=-7,wt=21,Pt=-1e7,Tt=1e7,ht=!1,_t=1,Nt=0,Ue={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},yt="0123456789abcdefghijklmnopqrstuvwxyz",Lt=!0;function Y(p,_){var S,U,C,R,W,x,A,B,P=this;if(!(P instanceof Y))return new Y(p,_);if(_==null){if(p&&p._isBigNumber===!0){P.s=p.s,!p.c||p.e>Tt?P.c=P.e=null:p.e=10;W/=10,R++);R>Tt?P.c=P.e=null:(P.e=R,P.c=[p]);return}B=String(p)}else{if(!e.test(B=String(p)))return et(P,B,x);P.s=B.charCodeAt(0)==45?(B=B.slice(1),-1):1}(R=B.indexOf("."))>-1&&(B=B.replace(".","")),(W=B.search(/e/i))>0?(R<0&&(R=W),R+=+B.slice(W+1),B=B.substring(0,W)):R<0&&(R=B.length)}else{if(q(_,2,yt.length,"Base"),_==10&&Lt)return P=new Y(p),Vt(P,tt+P.e+1,lt);if(B=String(p),x=typeof p=="number"){if(p*0!=0)return et(P,B,x,_);if(P.s=1/p<0?(B=B.slice(1),-1):1,Y.DEBUG&&B.replace(/^0\.0*|\./,"").length>15)throw Error(s+p)}else P.s=B.charCodeAt(0)===45?(B=B.slice(1),-1):1;for(S=yt.slice(0,_),R=W=0,A=B.length;WR){R=A;continue}}else if(!C&&(B==B.toUpperCase()&&(B=B.toLowerCase())||B==B.toLowerCase()&&(B=B.toUpperCase()))){C=!0,W=-1,R=0;continue}return et(P,String(p),x,_)}x=!1,B=it(B,_,10,P.s),(R=B.indexOf("."))>-1?B=B.replace(".",""):R=B.length}for(W=0;B.charCodeAt(W)===48;W++);for(A=B.length;B.charCodeAt(--A)===48;);if(B=B.slice(W,++A)){if(A-=W,x&&Y.DEBUG&&A>15&&(p>g||p!==i(p)))throw Error(s+P.s*p);if((R=R-W-1)>Tt)P.c=P.e=null;else if(R=-E&&C<=E&&C===i(C)){if(U[0]===0){if(C===0&&U.length===1)return!0;break t}if(_=(C+1)%l,_<1&&(_+=l),String(U[0]).length==_){for(_=0;_=c||S!==i(S))break t;if(S!==0)return!0}}}else if(U===null&&C===null&&(R===null||R===1||R===-1))return!0;throw Error(o+"Invalid BigNumber: "+p)},Y.maximum=Y.max=function(){return Er(arguments,O.lt)},Y.minimum=Y.min=function(){return Er(arguments,O.gt)},Y.random=function(){var p=9007199254740992,_=Math.random()*p&2097151?function(){return i(Math.random()*p)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(S){var U,C,R,W,x,A=0,B=[],P=new Y(ft);if(S==null?S=tt:q(S,0,E),W=r(S/l),ht)if(crypto.getRandomValues){for(U=crypto.getRandomValues(new Uint32Array(W*=2));A>>11),x>=9e15?(C=crypto.getRandomValues(new Uint32Array(2)),U[A]=C[0],U[A+1]=C[1]):(B.push(x%1e14),A+=2);A=W/2}else if(crypto.randomBytes){for(U=crypto.randomBytes(W*=7);A=9e15?crypto.randomBytes(7).copy(U,A):(B.push(x%1e14),A+=7);A=W/7}else throw ht=!1,Error(o+"crypto unavailable");if(!ht)for(;A=10;x/=10,A++);AC-1&&(x[W+1]==null&&(x[W+1]=0),x[W+1]+=x[W]/C|0,x[W]%=C)}return x.reverse()}return function(S,U,C,R,W){var x,A,B,P,H,h,m,I,j=S.indexOf("."),Z=tt,rt=lt;for(j>=0&&(P=Nt,Nt=0,S=S.replace(".",""),I=new Y(U),h=I.pow(S.length-j),Nt=P,I.c=_(X(k(h.c),h.e,"0"),10,C,p),I.e=I.c.length),m=_(S,U,C,W?(x=yt,p):(x=p,yt)),B=P=m.length;m[--P]==0;m.pop());if(!m[0])return x.charAt(0);if(j<0?--B:(h.c=m,h.e=B,h.s=R,h=G(h,I,Z,rt,C),m=h.c,H=h.r,B=h.e),A=B+Z+1,j=m[A],P=C/2,H=H||A<0||m[A+1]!=null,H=rt<4?(j!=null||H)&&(rt==0||rt==(h.s<0?3:2)):j>P||j==P&&(rt==4||H||rt==6&&m[A-1]&1||rt==(h.s<0?8:7)),A<1||!m[0])S=H?X(x.charAt(1),-Z,x.charAt(0)):x.charAt(0);else{if(m.length=A,H)for(--C;++m[--A]>C;)m[A]=0,A||(++B,m=[1].concat(m));for(P=m.length;!m[--P];);for(j=0,S="";j<=P;S+=x.charAt(m[j++]));S=X(S,B,x.charAt(0))}return S}}(),G=function(){function p(U,C,R){var W,x,A,B,P=0,H=U.length,h=C%v,m=C/v|0;for(U=U.slice();H--;)A=U[H]%v,B=U[H]/v|0,W=m*A+B*h,x=h*A+W%v*v+P,P=(x/R|0)+(W/v|0)+m*B,U[H]=x%R;return P&&(U=[P].concat(U)),U}function _(U,C,R,W){var x,A;if(R!=W)A=R>W?1:-1;else for(x=A=0;xC[x]?1:-1;break}return A}function S(U,C,R,W){for(var x=0;R--;)U[R]-=x,x=U[R]1;U.splice(0,1));}return function(U,C,R,W,x){var A,B,P,H,h,m,I,j,Z,rt,a,u,f,T,L,M,J,dt=U.s==C.s?1:-1,bt=U.c,ut=C.c;if(!bt||!bt[0]||!ut||!ut[0])return new Y(!U.s||!C.s||(bt?ut&&bt[0]==ut[0]:!ut)?NaN:bt&&bt[0]==0||!ut?dt*0:dt/0);for(j=new Y(dt),Z=j.c=[],B=U.e-C.e,dt=R+B+1,x||(x=c,B=y(U.e/l)-y(C.e/l),dt=dt/l|0),P=0;ut[P]==(bt[P]||0);P++);if(ut[P]>(bt[P]||0)&&B--,dt<0)Z.push(1),H=!0;else{for(T=bt.length,M=ut.length,P=0,dt+=2,h=i(x/(ut[0]+1)),h>1&&(ut=p(ut,h,x),bt=p(bt,h,x),M=ut.length,T=bt.length),f=M,rt=bt.slice(0,M),a=rt.length;a=x/2&&L++;do{if(h=0,A=_(ut,rt,M,a),A<0){if(u=rt[0],M!=a&&(u=u*x+(rt[1]||0)),h=i(u/L),h>1)for(h>=x&&(h=x-1),m=p(ut,h,x),I=m.length,a=rt.length;_(m,rt,I,a)==1;)h--,S(m,M=10;dt/=10,P++);Vt(j,R+(j.e=P+B*l-1)+1,W,H)}else j.e=B,j.r=+H;return j}}();function er(p,_,S,U){var C,R,W,x,A;if(S==null?S=lt:q(S,0,8),!p.c)return p.toString();if(C=p.c[0],W=p.e,_==null)A=k(p.c),A=U==1||U==2&&(W<=st||W>=wt)?z(A,W):X(A,W,"0");else if(p=Vt(new Y(p),_,S),R=p.e,A=k(p.c),x=A.length,U==1||U==2&&(_<=R||R<=st)){for(;x<_;A+="0",x++);A=z(A,R)}else if(_-=W,A=X(A,R,"0"),R+1>x){if(--_>0)for(A+=".";_--;A+="0");}else if(_+=R-x,_>0)for(R+1==x&&(A+=".");_--;A+="0");return p.s<0&&C?"-"+A:A}function Er(p,_){for(var S,U=1,C=new Y(p[0]);U=10;C/=10,U++);return(S=U+S*l-1)>Tt?p.c=p.e=null:S=10;x/=10,C++);if(R=_-C,R<0)R+=l,W=_,A=H[B=0],P=A/h[C-W-1]%10|0;else if(B=r((R+1)/l),B>=H.length)if(U){for(;H.length<=B;H.push(0));A=P=0,C=1,R%=l,W=R-l+1}else break t;else{for(A=x=H[B],C=1;x>=10;x/=10,C++);R%=l,W=R-l+C,P=W<0?0:A/h[C-W-1]%10|0}if(U=U||_<0||H[B+1]!=null||(W<0?A:A%h[C-W-1]),U=S<4?(P||U)&&(S==0||S==(p.s<0?3:2)):P>5||P==5&&(S==4||U||S==6&&(R>0?W>0?A/h[C-W]:0:H[B-1])%10&1||S==(p.s<0?8:7)),_<1||!H[0])return H.length=0,U?(_-=p.e+1,H[0]=h[(l-_%l)%l],p.e=-_||0):H[0]=p.e=0,p;if(R==0?(H.length=B,x=1,B--):(H.length=B+1,x=h[l-R],H[B]=W>0?i(A/h[C-W]%h[W])*x:0),U)for(;;)if(B==0){for(R=1,W=H[0];W>=10;W/=10,R++);for(W=H[0]+=x,x=1;W>=10;W/=10,x++);R!=x&&(p.e++,H[0]==c&&(H[0]=1));break}else{if(H[B]+=x,H[B]!=c)break;H[B--]=0,x=1}for(R=H.length;H[--R]===0;H.pop());}p.e>Tt?p.c=p.e=null:p.e=wt?z(_,S):X(_,S,"0"),p.s<0?"-"+_:_)}return O.absoluteValue=O.abs=function(){var p=new Y(this);return p.s<0&&(p.s=1),p},O.comparedTo=function(p,_){return N(this,new Y(p,_))},O.decimalPlaces=O.dp=function(p,_){var S,U,C,R=this;if(p!=null)return q(p,0,E),_==null?_=lt:q(_,0,8),Vt(new Y(R),p+R.e+1,_);if(!(S=R.c))return null;if(U=((C=S.length-1)-y(this.e/l))*l,C=S[C])for(;C%10==0;C/=10,U--);return U<0&&(U=0),U},O.dividedBy=O.div=function(p,_){return G(this,new Y(p,_),tt,lt)},O.dividedToIntegerBy=O.idiv=function(p,_){return G(this,new Y(p,_),0,1)},O.exponentiatedBy=O.pow=function(p,_){var S,U,C,R,W,x,A,B,P,H=this;if(p=new Y(p),p.c&&!p.isInteger())throw Error(o+"Exponent not an integer: "+Dt(p));if(_!=null&&(_=new Y(_)),x=p.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!p.c||!p.c[0])return P=new Y(Math.pow(+Dt(H),x?p.s*(2-Q(p)):+Dt(p))),_?P.mod(_):P;if(A=p.s<0,_){if(_.c?!_.c[0]:!_.s)return new Y(NaN);U=!A&&H.isInteger()&&_.isInteger(),U&&(H=H.mod(_))}else{if(p.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||x&&H.c[1]>=24e7:H.c[0]<8e13||x&&H.c[0]<=9999975e7)))return R=H.s<0&&Q(p)?-0:0,H.e>-1&&(R=1/R),new Y(A?1/R:R);Nt&&(R=r(Nt/l+2))}for(x?(S=new Y(.5),A&&(p.s=1),B=Q(p)):(C=Math.abs(+Dt(p)),B=C%2),P=new Y(ft);;){if(B){if(P=P.times(H),!P.c)break;R?P.c.length>R&&(P.c.length=R):U&&(P=P.mod(_))}if(C){if(C=i(C/2),C===0)break;B=C%2}else if(p=p.times(S),Vt(p,p.e+1,1),p.e>14)B=Q(p);else{if(C=+Dt(p),C===0)break;B=C%2}H=H.times(H),R?H.c&&H.c.length>R&&(H.c.length=R):U&&(H=H.mod(_))}return U?P:(A&&(P=ft.div(P)),_?P.mod(_):R?Vt(P,Nt,lt,W):P)},O.integerValue=function(p){var _=new Y(this);return p==null?p=lt:q(p,0,8),Vt(_,_.e+1,p)},O.isEqualTo=O.eq=function(p,_){return N(this,new Y(p,_))===0},O.isFinite=function(){return!!this.c},O.isGreaterThan=O.gt=function(p,_){return N(this,new Y(p,_))>0},O.isGreaterThanOrEqualTo=O.gte=function(p,_){return(_=N(this,new Y(p,_)))===1||_===0},O.isInteger=function(){return!!this.c&&y(this.e/l)>this.c.length-2},O.isLessThan=O.lt=function(p,_){return N(this,new Y(p,_))<0},O.isLessThanOrEqualTo=O.lte=function(p,_){return(_=N(this,new Y(p,_)))===-1||_===0},O.isNaN=function(){return!this.s},O.isNegative=function(){return this.s<0},O.isPositive=function(){return this.s>0},O.isZero=function(){return!!this.c&&this.c[0]==0},O.minus=function(p,_){var S,U,C,R,W=this,x=W.s;if(p=new Y(p,_),_=p.s,!x||!_)return new Y(NaN);if(x!=_)return p.s=-_,W.plus(p);var A=W.e/l,B=p.e/l,P=W.c,H=p.c;if(!A||!B){if(!P||!H)return P?(p.s=-_,p):new Y(H?W:NaN);if(!P[0]||!H[0])return H[0]?(p.s=-_,p):new Y(P[0]?W:lt==3?-0:0)}if(A=y(A),B=y(B),P=P.slice(),x=A-B){for((R=x<0)?(x=-x,C=P):(B=A,C=H),C.reverse(),_=x;_--;C.push(0));C.reverse()}else for(U=(R=(x=P.length)<(_=H.length))?x:_,x=_=0;_0)for(;_--;P[S++]=0);for(_=c-1;U>x;){if(P[--U]=0;){for(S=0,h=u[C]%Z,m=u[C]/Z|0,W=A,R=C+W;R>C;)B=a[--W]%Z,P=a[W]/Z|0,x=m*B+P*h,B=h*B+x%Z*Z+I[R]+S,S=(B/j|0)+(x/Z|0)+m*P,I[R--]=B%j;I[R]=S}return S?++U:I.splice(0,1),rr(p,I,U)},O.negated=function(){var p=new Y(this);return p.s=-p.s||null,p},O.plus=function(p,_){var S,U=this,C=U.s;if(p=new Y(p,_),_=p.s,!C||!_)return new Y(NaN);if(C!=_)return p.s=-_,U.minus(p);var R=U.e/l,W=p.e/l,x=U.c,A=p.c;if(!R||!W){if(!x||!A)return new Y(C/0);if(!x[0]||!A[0])return A[0]?p:new Y(x[0]?U:C*0)}if(R=y(R),W=y(W),x=x.slice(),C=R-W){for(C>0?(W=R,S=A):(C=-C,S=x),S.reverse();C--;S.push(0));S.reverse()}for(C=x.length,_=A.length,C-_<0&&(S=A,A=x,x=S,_=C),C=0;_;)C=(x[--_]=x[_]+A[_]+C)/c|0,x[_]=c===x[_]?0:x[_]%c;return C&&(x=[C].concat(x),++W),rr(p,x,W)},O.precision=O.sd=function(p,_){var S,U,C,R=this;if(p!=null&&p!==!!p)return q(p,1,E),_==null?_=lt:q(_,0,8),Vt(new Y(R),p,_);if(!(S=R.c))return null;if(C=S.length-1,U=C*l+1,C=S[C]){for(;C%10==0;C/=10,U--);for(C=S[0];C>=10;C/=10,U++);}return p&&R.e+1>U&&(U=R.e+1),U},O.shiftedBy=function(p){return q(p,-g,g),this.times("1e"+p)},O.squareRoot=O.sqrt=function(){var p,_,S,U,C,R=this,W=R.c,x=R.s,A=R.e,B=tt+4,P=new Y("0.5");if(x!==1||!W||!W[0])return new Y(!x||x<0&&(!W||W[0])?NaN:W?R:1/0);if(x=Math.sqrt(+Dt(R)),x==0||x==1/0?(_=k(W),(_.length+A)%2==0&&(_+="0"),x=Math.sqrt(+_),A=y((A+1)/2)-(A<0||A%2),x==1/0?_="5e"+A:(_=x.toExponential(),_=_.slice(0,_.indexOf("e")+1)+A),S=new Y(_)):S=new Y(x+""),S.c[0]){for(A=S.e,x=A+B,x<3&&(x=0);;)if(C=S,S=P.times(C.plus(G(R,C,B,1))),k(C.c).slice(0,x)===(_=k(S.c)).slice(0,x))if(S.e0&&I>0){for(R=I%x||x,P=m.substr(0,R);R0&&(P+=B+m.slice(R)),h&&(P="-"+P)}U=H?P+(S.decimalSeparator||"")+((A=+S.fractionGroupSize)?H.replace(new RegExp("\\d{"+A+"}\\B","g"),"$&"+(S.fractionGroupSeparator||"")):H):P}return(S.prefix||"")+U+(S.suffix||"")},O.toFraction=function(p){var _,S,U,C,R,W,x,A,B,P,H,h,m=this,I=m.c;if(p!=null&&(x=new Y(p),!x.isInteger()&&(x.c||x.s!==1)||x.lt(ft)))throw Error(o+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+Dt(x));if(!I)return new Y(m);for(_=new Y(ft),B=S=new Y(ft),U=A=new Y(ft),h=k(I),R=_.e=h.length-m.e-1,_.c[0]=w[(W=R%l)<0?l+W:W],p=!p||x.comparedTo(_)>0?R>0?_:B:x,W=Tt,Tt=1/0,x=new Y(h),A.c[0]=0;P=G(x,_,0,1),C=S.plus(P.times(U)),C.comparedTo(p)!=1;)S=U,U=C,B=A.plus(P.times(C=B)),A=C,_=x.minus(P.times(C=_)),x=C;return C=G(p.minus(S),U,0,1),A=A.plus(C.times(B)),S=S.plus(C.times(U)),A.s=B.s=m.s,R=R*2,H=G(B,U,R,lt).minus(m).abs().comparedTo(G(A,S,R,lt).minus(m).abs())<1?[B,U]:[A,S],Tt=W,H},O.toNumber=function(){return+Dt(this)},O.toPrecision=function(p,_){return p!=null&&q(p,1,E),er(this,p,_,2)},O.toString=function(p){var _,S=this,U=S.s,C=S.e;return C===null?U?(_="Infinity",U<0&&(_="-"+_)):_="NaN":(p==null?_=C<=st||C>=wt?z(k(S.c),C):X(k(S.c),C,"0"):p===10&&Lt?(S=Vt(new Y(S),tt+C+1,lt),_=X(k(S.c),S.e,"0")):(q(p,2,yt.length,"Base"),_=it(X(k(S.c),C,"0"),10,p,U,!0)),U<0&&S.c[0]&&(_="-"+_)),_},O.valueOf=O.toJSON=function(){return Dt(this)},O._isBigNumber=!0,D!=null&&Y.set(D),Y}function y(D){var G=D|0;return D>0||D===G?G:G-1}function k(D){for(var G,it,et=1,O=D.length,ft=D[0]+"";etwt^it?1:-1;for(lt=(st=O.length)<(wt=ft.length)?st:wt,tt=0;ttft[tt]^it?1:-1;return st==wt?0:st>wt^it?1:-1}function q(D,G,it,et){if(Dit||D!==i(D))throw Error(o+(et||"Argument")+(typeof D=="number"?Dit?" out of range: ":" not an integer: ":" not a primitive number: ")+String(D))}function Q(D){var G=D.c.length-1;return y(D.e/l)==G&&D.c[G]%2!=0}function z(D,G){return(D.length>1?D.charAt(0)+"."+D.slice(1):D)+(G<0?"e":"e+")+G}function X(D,G,it){var et,O;if(G<0){for(O=it+".";++G;O+=it);D=O+D}else if(et=D.length,++G>et){for(O=it,G-=et;--G;O+=it);D+=O}else G{"use strict";b();Object.defineProperty(xa,"__esModule",{value:!0});var lp=_a(),Ta=class{BigNum;constructor(){this.BigNum=(t,e)=>{let r=lp.BigNumber.clone({DECIMAL_PLACES:e});return new r(t)}}winstonToAr(t,{formatted:e=!1,decimals:r=12,trim:i=!0}={}){let o=this.stringToBigNum(t,r).shiftedBy(-12);return e?o.toFormat(r):o.toFixed(r)}arToWinston(t,{formatted:e=!1}={}){let r=this.stringToBigNum(t).shiftedBy(12);return e?r.toFormat():r.toFixed(0)}compare(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.comparedTo(i)}isEqual(t,e){return this.compare(t,e)===0}isLessThan(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.isLessThan(i)}isGreaterThan(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.isGreaterThan(i)}add(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.plus(e).toFixed(0)}sub(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.minus(e).toFixed(0)}stringToBigNum(t,e=12){return this.BigNum(t,e)}};xa.default=Ta});var ql=nt(Ia=>{"use strict";b();Object.defineProperty(Ia,"__esModule",{value:!0});var Ca=class{METHOD_GET="GET";METHOD_POST="POST";config;constructor(t){this.applyConfig(t)}applyConfig(t){this.config=this.mergeDefaults(t)}getConfig(){return this.config}mergeDefaults(t){let e=t.protocol||"http",r=t.port||(e==="https"?443:80);return{host:t.host||"127.0.0.1",protocol:e,port:r,timeout:t.timeout||2e4,logging:t.logging||!1,logger:t.logger||console.log,network:t.network}}async get(t,e){return await this.request(t,{...e,method:this.METHOD_GET})}async post(t,e,r){let i=new Headers(r?.headers||{});return i.get("content-type")?.includes("application/json")||i.append("content-type","application/json"),i.append("accept","application/json, text/plain, */*"),await this.request(t,{...r,method:this.METHOD_POST,body:typeof e!="string"?JSON.stringify(e):e,headers:i})}async request(t,e){let r=new Headers(e?.headers||{}),i=`${this.config.protocol}://${this.config.host}:${this.config.port}`,o=e?.responseType;delete e?.responseType,t.startsWith("/")&&(t=t.slice(1)),this.config.network&&r.append("x-network",this.config.network),this.config.logging&&this.config.logger(`Requesting: ${i}/${t}`);let s=await fetch(`${i}/${t}`,{...e||{},headers:r});this.config.logging&&this.config.logger(`Response: ${s.url} - ${s.status}`);let l=s.headers.get("content-type")?.match(/charset=([^()<>@,;:\"/[\]?.=\s]*)/i)?.[1],g=s,w=async()=>{if(l)try{g.data=new TextDecoder(l).decode(await s.arrayBuffer())}catch{g.data=await s.text()}else g.data=await s.text()};if(o==="arraybuffer")g.data=await s.arrayBuffer();else if(o==="text")await w();else if(o==="webstream")g.data=fp(s.body);else try{let v=await s.clone().json();typeof v!="object"?await w():g.data=await s.json(),v=null}catch{await w()}return g}};Ia.default=Ca;var fp=n=>{let t=n;return typeof t[Symbol.asyncIterator]>"u"?(t[Symbol.asyncIterator]=hp(n),t):n},hp=function(n){return async function*(){let e=n.getReader();try{for(;;){let{done:r,value:i}=await e.read();if(r)return;yield i}}finally{e.releaseLock()}}}});var be=nt(Ot=>{"use strict";b();Object.defineProperty(Ot,"__esModule",{value:!0});Ot.b64UrlDecode=Ot.b64UrlEncode=Ot.bufferTob64Url=Ot.bufferTob64=Ot.b64UrlToBuffer=Ot.stringToB64Url=Ot.stringToBuffer=Ot.bufferToString=Ot.b64UrlToString=Ot.concatBuffers=void 0;var jl=ss();function gp(n){let t=0;for(let i=0;i{"use strict";b();Object.defineProperty(ka,"__esModule",{value:!0});var wr=be(),Aa=class{keyLength=4096;publicExponent=65537;hashAlgorithm="sha256";driver;constructor(){if(!this.detectWebCrypto())throw new Error("SubtleCrypto not available!");this.driver=crypto.subtle}async generateJWK(){let t=await this.driver.generateKey({name:"RSA-PSS",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign"]),e=await this.driver.exportKey("jwk",t.privateKey);return{kty:e.kty,e:e.e,n:e.n,d:e.d,p:e.p,q:e.q,dp:e.dp,dq:e.dq,qi:e.qi}}async sign(t,e,{saltLength:r}={}){let i=await this.driver.sign({name:"RSA-PSS",saltLength:32},await this.jwkToCryptoKey(t),e);return new Uint8Array(i)}async hash(t,e="SHA-256"){let r=await this.driver.digest(e,t);return new Uint8Array(r)}async verify(t,e,r){let i={kty:"RSA",e:"AQAB",n:t},o=await this.jwkToPublicCryptoKey(i),s=await this.driver.digest("SHA-256",e),c=await this.driver.verify({name:"RSA-PSS",saltLength:0},o,r,e),l=await this.driver.verify({name:"RSA-PSS",saltLength:32},o,r,e),g=await this.driver.verify({name:"RSA-PSS",saltLength:Math.ceil((o.algorithm.modulusLength-1)/8)-s.byteLength-2},o,r,e);return c||l||g}async jwkToCryptoKey(t){return this.driver.importKey("jwk",t,{name:"RSA-PSS",hash:{name:"SHA-256"}},!1,["sign"])}async jwkToPublicCryptoKey(t){return this.driver.importKey("jwk",t,{name:"RSA-PSS",hash:{name:"SHA-256"}},!1,["verify"])}detectWebCrypto(){if(typeof crypto>"u")return!1;let t=crypto?.subtle;return t===void 0?!1:["generateKey","importKey","exportKey","digest","sign"].every(r=>typeof t[r]=="function")}async encrypt(t,e,r){let i=await this.driver.importKey("raw",typeof e=="string"?wr.stringToBuffer(e):e,{name:"PBKDF2",length:32},!1,["deriveKey"]),o=await this.driver.deriveKey({name:"PBKDF2",salt:r?wr.stringToBuffer(r):wr.stringToBuffer("salt"),iterations:1e5,hash:"SHA-256"},i,{name:"AES-CBC",length:256},!1,["encrypt","decrypt"]),s=new Uint8Array(16);crypto.getRandomValues(s);let c=await this.driver.encrypt({name:"AES-CBC",iv:s},o,t);return wr.concatBuffers([s,c])}async decrypt(t,e,r){let i=await this.driver.importKey("raw",typeof e=="string"?wr.stringToBuffer(e):e,{name:"PBKDF2",length:32},!1,["deriveKey"]),o=await this.driver.deriveKey({name:"PBKDF2",salt:r?wr.stringToBuffer(r):wr.stringToBuffer("salt"),iterations:1e5,hash:"SHA-256"},i,{name:"AES-CBC",length:256},!1,["encrypt","decrypt"]),s=t.slice(0,16),c=await this.driver.decrypt({name:"AES-CBC",iv:s},o,t.slice(16));return wr.concatBuffers([c])}};ka.default=Aa});var ef=nt(Oa=>{"use strict";b();Object.defineProperty(Oa,"__esModule",{value:!0});var La=class{api;constructor(t){this.api=t}getInfo(){return this.api.get("info").then(t=>t.data)}getPeers(){return this.api.get("peers").then(t=>t.data)}};Oa.default=La});var Yn=nt(Jn=>{"use strict";b();Object.defineProperty(Jn,"__esModule",{value:!0});Jn.getError=void 0;var Ra=class extends Error{type;response;constructor(t,e={}){e.message?super(e.message):super(),this.type=t,this.response=e.response}getType(){return this.type}};Jn.default=Ra;function mp(n){let t=n.data;if(typeof n.data=="string")try{t=JSON.parse(n.data)}catch{}if(n.data instanceof ArrayBuffer||n.data instanceof Uint8Array)try{t=JSON.parse(t.toString())}catch{}return t?t.error||t:n.statusText||"unknown"}Jn.getError=mp});var of=nt(Ba=>{"use strict";b();Object.defineProperty(Ba,"__esModule",{value:!0});var le=Xn();async function rf(n){if(Array.isArray(n)){let r=le.default.utils.concatBuffers([le.default.utils.stringToBuffer("list"),le.default.utils.stringToBuffer(n.length.toString())]);return await nf(n,await le.default.crypto.hash(r,"SHA-384"))}let t=le.default.utils.concatBuffers([le.default.utils.stringToBuffer("blob"),le.default.utils.stringToBuffer(n.byteLength.toString())]),e=le.default.utils.concatBuffers([await le.default.crypto.hash(t,"SHA-384"),await le.default.crypto.hash(n,"SHA-384")]);return await le.default.crypto.hash(e,"SHA-384")}Ba.default=rf;async function nf(n,t){if(n.length<1)return t;let e=le.default.utils.concatBuffers([t,await rf(n[0])]),r=await le.default.crypto.hash(e,"SHA-384");return await nf(n.slice(1),r)}});var Ma=nt(pt=>{"use strict";b();Object.defineProperty(pt,"__esModule",{value:!0});pt.debug=pt.validatePath=pt.arrayCompare=pt.bufferToInt=pt.intToBuffer=pt.arrayFlatten=pt.generateProofs=pt.buildLayers=pt.generateTransactionChunks=pt.generateTree=pt.computeRootHash=pt.generateLeaves=pt.chunkData=pt.MIN_CHUNK_SIZE=pt.MAX_CHUNK_SIZE=void 0;var So=Xn(),sf=be();pt.MAX_CHUNK_SIZE=256*1024;pt.MIN_CHUNK_SIZE=32*1024;var ti=32,hn=32;async function Na(n){let t=[],e=n,r=0;for(;e.byteLength>=pt.MAX_CHUNK_SIZE;){let i=pt.MAX_CHUNK_SIZE,o=e.byteLength-pt.MAX_CHUNK_SIZE;o>0&&o({type:"leaf",id:await Kt(await Promise.all([Kt(t),Kt(ei(r))])),dataHash:t,minByteRange:e,maxByteRange:r})))}pt.generateLeaves=Ua;async function yp(n){return(await af(n)).id}pt.computeRootHash=yp;async function af(n){return await Eo(await Ua(await Na(n)))}pt.generateTree=af;async function wp(n){let t=await Na(n),e=await Ua(t),r=await Eo(e),i=await cf(r),o=t.slice(-1)[0];return o.maxByteRange-o.minByteRange===0&&(t.splice(t.length-1,1),i.splice(i.length-1,1)),{data_root:r.id,chunks:t,proofs:i}}pt.generateTransactionChunks=wp;async function Eo(n,t=0){if(n.length<2)return n[0];let e=[];for(let r=0;r{Array.isArray(e)?t.push(...Wa(e)):t.push(e)}),t}pt.arrayFlatten=Wa;async function vp(n,t){return t?{type:"branch",id:await Kt([await Kt(n.id),await Kt(t.id),await Kt(ei(n.maxByteRange))]),byteRange:n.maxByteRange,maxByteRange:t.maxByteRange,leftChild:n,rightChild:t}:n}async function Kt(n){return Array.isArray(n)&&(n=So.default.utils.concatBuffers(n)),new Uint8Array(await So.default.crypto.hash(n))}function ei(n){let t=new Uint8Array(ti);for(var e=t.length-1;e>=0;e--){var r=n%256;t[e]=r,n=(n-r)/256}return t}pt.intToBuffer=ei;function Da(n){let t=0;for(var e=0;en.every((e,r)=>t[r]===e);pt.arrayCompare=_p;async function Zn(n,t,e,r,i){if(r<=0)return!1;if(t>=r)return Zn(n,0,r-1,r,i);if(t<0)return Zn(n,0,0,r,i);if(i.length==hn+ti){let v=i.slice(0,hn),E=i.slice(v.length,v.length+ti),d=await Kt([await Kt(v),await Kt(E)]);return(0,pt.arrayCompare)(n,d)?{offset:r-1,leftBound:e,rightBound:r,chunkSize:r-e}:!1}let o=i.slice(0,hn),s=i.slice(o.length,o.length+hn),c=i.slice(o.length+s.length,o.length+s.length+ti),l=Da(c),g=i.slice(o.length+s.length+c.length),w=await Kt([await Kt(o),await Kt(s),await Kt(c)]);return(0,pt.arrayCompare)(n,w)?t ${JSON.stringify(c)}`;return uf(s,l)}pt.debug=uf});var xo=nt(ni=>{"use strict";b();Object.defineProperty(ni,"__esModule",{value:!0});ni.Tag=void 0;var Wt=be(),bp=of(),Sp=Ma(),To=class{get(t,e){if(!Object.getOwnPropertyNames(this).includes(t))throw new Error(`Field "${t}" is not a property of the Arweave Transaction class.`);if(this[t]instanceof Uint8Array)return e&&e.decode&&e.string?Wt.bufferToString(this[t]):e&&e.decode&&!e.string?this[t]:Wt.bufferTob64Url(this[t]);if(this[t]instanceof Array){if(e?.decode!==void 0||e?.string!==void 0)throw t==="tags"&&console.warn(`Did you mean to use 'transaction["tags"]' ?`),new Error("Cannot decode or stringify an array.");return this[t]}return e&&e.decode==!0?e&&e.string?Wt.b64UrlToString(this[t]):Wt.b64UrlToBuffer(this[t]):this[t]}},ri=class extends To{name;value;constructor(t,e,r=!1){super(),this.name=t,this.value=e}};ni.Tag=ri;var Fa=class extends To{format=2;id="";last_tx="";owner="";tags=[];target="";quantity="0";data_size="0";data=new Uint8Array;data_root="";reward="0";signature="";chunks;constructor(t={}){super(),Object.assign(this,t),typeof this.data=="string"&&(this.data=Wt.b64UrlToBuffer(this.data)),t.tags&&(this.tags=t.tags.map(e=>new ri(e.name,e.value)))}addTag(t,e){this.tags.push(new ri(Wt.stringToB64Url(t),Wt.stringToB64Url(e)))}toJSON(){return{format:this.format,id:this.id,last_tx:this.last_tx,owner:this.owner,tags:this.tags,target:this.target,quantity:this.quantity,data:Wt.bufferTob64Url(this.data),data_size:this.data_size,data_root:this.data_root,data_tree:this.data_tree,reward:this.reward,signature:this.signature}}setOwner(t){this.owner=t}setSignature({id:t,owner:e,reward:r,tags:i,signature:o}){this.id=t,this.owner=e,r&&(this.reward=r),i&&(this.tags=i),this.signature=o}async prepareChunks(t){!this.chunks&&t.byteLength>0&&(this.chunks=await(0,Sp.generateTransactionChunks)(t),this.data_root=Wt.bufferTob64Url(this.chunks.data_root)),!this.chunks&&t.byteLength===0&&(this.chunks={chunks:[],data_root:new Uint8Array,proofs:[]},this.data_root="")}getChunk(t,e){if(!this.chunks)throw new Error("Chunks have not been prepared");let r=this.chunks.proofs[t],i=this.chunks.chunks[t];return{data_root:this.data_root,data_size:this.data_size,data_path:Wt.bufferTob64Url(r.proof),offset:r.offset.toString(),chunk:Wt.bufferTob64Url(e.slice(i.minByteRange,i.maxByteRange))}}async getSignatureData(){switch(this.format){case 1:let t=this.tags.reduce((r,i)=>Wt.concatBuffers([r,i.get("name",{decode:!0,string:!1}),i.get("value",{decode:!0,string:!1})]),new Uint8Array);return Wt.concatBuffers([this.get("owner",{decode:!0,string:!1}),this.get("target",{decode:!0,string:!1}),this.get("data",{decode:!0,string:!1}),Wt.stringToBuffer(this.quantity),Wt.stringToBuffer(this.reward),this.get("last_tx",{decode:!0,string:!1}),t]);case 2:this.data_root||await this.prepareChunks(this.data);let e=this.tags.map(r=>[r.get("name",{decode:!0,string:!1}),r.get("value",{decode:!0,string:!1})]);return await(0,bp.default)([Wt.stringToBuffer(this.format.toString()),this.get("owner",{decode:!0,string:!1}),this.get("target",{decode:!0,string:!1}),Wt.stringToBuffer(this.quantity),Wt.stringToBuffer(this.reward),this.get("last_tx",{decode:!0,string:!1}),e,Wt.stringToBuffer(this.data_size),this.get("data_root",{decode:!0,string:!1})]);default:throw new Error(`Unexpected transaction format: ${this.format}`)}}};ni.default=Fa});var gf=nt(Co=>{"use strict";b();Object.defineProperty(Co,"__esModule",{value:!0});Co.TransactionUploader=void 0;var lf=xo(),Ep=be(),$a=Yn(),Tp=Ma(),ff=1,xp=["invalid_json","chunk_too_big","data_path_too_big","offset_too_big","data_size_too_big","chunk_proof_ratio_not_attractive","invalid_proof"],hf=1e3*40,ii=class{api;chunkIndex=0;txPosted=!1;transaction;lastRequestTimeEnd=0;totalErrors=0;data;lastResponseStatus=0;lastResponseError="";get isComplete(){return this.txPosted&&this.chunkIndex===this.transaction.chunks.chunks.length}get totalChunks(){return this.transaction.chunks.chunks.length}get uploadedChunks(){return this.chunkIndex}get pctComplete(){return Math.trunc(this.uploadedChunks/this.totalChunks*100)}constructor(t,e){if(this.api=t,!e.id)throw new Error("Transaction is not signed");if(!e.chunks)throw new Error("Transaction chunks not prepared");this.data=e.data,this.transaction=new lf.default(Object.assign({},e,{data:new Uint8Array(0)}))}async uploadChunk(t){if(this.isComplete)throw new Error("Upload is already complete");if(this.lastResponseError!==""?this.totalErrors++:this.totalErrors=0,this.totalErrors===100)throw new Error(`Unable to complete upload: ${this.lastResponseStatus}: ${this.lastResponseError}`);let e=this.lastResponseError===""?0:Math.max(this.lastRequestTimeEnd+hf-Date.now(),hf);if(e>0&&(e=e-e*Math.random()*.3,await new Promise(s=>setTimeout(s,e))),this.lastResponseError="",!this.txPosted){await this.postTransaction();return}t&&(this.chunkIndex=t);let r=this.transaction.getChunk(t||this.chunkIndex,this.data);if(!await(0,Tp.validatePath)(this.transaction.chunks.data_root,parseInt(r.offset),0,parseInt(r.data_size),Ep.b64UrlToBuffer(r.data_path)))throw new Error(`Unable to validate chunk ${this.chunkIndex}`);let o=await this.api.post("chunk",this.transaction.getChunk(this.chunkIndex,this.data)).catch(s=>(console.error(s.message),{status:-1,data:{error:s.message}}));if(this.lastRequestTimeEnd=Date.now(),this.lastResponseStatus=o.status,this.lastResponseStatus==200)this.chunkIndex++;else if(this.lastResponseError=(0,$a.getError)(o),xp.includes(this.lastResponseError))throw new Error(`Fatal error uploading chunk ${this.chunkIndex}: ${this.lastResponseError}`)}static async fromSerialized(t,e,r){if(!e||typeof e.chunkIndex!="number"||typeof e.transaction!="object")throw new Error("Serialized object does not match expected format.");var i=new lf.default(e.transaction);i.chunks||await i.prepareChunks(r);let o=new ii(t,i);if(o.chunkIndex=e.chunkIndex,o.lastRequestTimeEnd=e.lastRequestTimeEnd,o.lastResponseError=e.lastResponseError,o.lastResponseStatus=e.lastResponseStatus,o.txPosted=e.txPosted,o.data=r,o.transaction.data_root!==e.transaction.data_root)throw new Error("Data mismatch: Uploader doesn't match provided data.");return o}static async fromTransactionId(t,e){let r=await t.get(`tx/${e}`);if(r.status!==200)throw new Error(`Tx ${e} not found: ${r.status}`);let i=r.data;return i.data=new Uint8Array(0),{txPosted:!0,chunkIndex:0,lastResponseError:"",lastRequestTimeEnd:0,lastResponseStatus:0,transaction:i}}toJSON(){return{chunkIndex:this.chunkIndex,transaction:this.transaction,lastRequestTimeEnd:this.lastRequestTimeEnd,lastResponseStatus:this.lastResponseStatus,lastResponseError:this.lastResponseError,txPosted:this.txPosted}}async postTransaction(){if(this.totalChunks<=ff){this.transaction.data=this.data;let r=await this.api.post("tx",this.transaction).catch(i=>(console.error(i),{status:-1,data:{error:i.message}}));if(this.lastRequestTimeEnd=Date.now(),this.lastResponseStatus=r.status,this.transaction.data=new Uint8Array(0),r.status>=200&&r.status<300){this.txPosted=!0,this.chunkIndex=ff;return}throw this.lastResponseError=(0,$a.getError)(r),new Error(`Unable to upload transaction: ${r.status}, ${this.lastResponseError}`)}let e=await this.api.post("tx",this.transaction);if(this.lastRequestTimeEnd=Date.now(),this.lastResponseStatus=e.status,!(e.status>=200&&e.status<300))throw this.lastResponseError=(0,$a.getError)(e),new Error(`Unable to upload transaction: ${e.status}, ${this.lastResponseError}`);this.txPosted=!0}};Co.TransactionUploader=ii});var Io=nt((jv,df)=>{b();df.exports={}});var pf=nt(qa=>{"use strict";b();Object.defineProperty(qa,"__esModule",{value:!0});var Ka=Yn(),Ye=xo(),oi=be(),Va=gf();Io();var Ga=class{api;crypto;chunks;constructor(t,e,r){this.api=t,this.crypto=e,this.chunks=r}async getTransactionAnchor(){let t=await this.api.get("tx_anchor");if(!t.data.match(/^[a-z0-9_-]{43,}/i)||!t.ok)throw new Error(`Could not getTransactionAnchor. Received: ${t.data}. Status: ${t.status}, ${t.statusText}`);return t.data}async getPrice(t,e){let r=e?`price/${t}/${e}`:`price/${t}`,i=await this.api.get(r);if(!/^\d+$/.test(i.data)||!i.ok)throw new Error(`Could not getPrice. Received: ${i.data}. Status: ${i.status}, ${i.statusText}`);return i.data}async get(t){let e=await this.api.get(`tx/${t}`);if(e.status==200){let r=parseInt(e.data.data_size);if(e.data.format>=2&&r>0&&r<=1024*1024*12){let i=await this.getData(t);return new Ye.default({...e.data,data:i})}return new Ye.default({...e.data,format:e.data.format||1})}throw e.status==404?new Ka.default("TX_NOT_FOUND"):e.status==410?new Ka.default("TX_FAILED"):new Ka.default("TX_INVALID")}fromRaw(t){return new Ye.default(t)}async search(t,e){return this.api.post("arql",{op:"equals",expr1:t,expr2:e}).then(r=>r.data?r.data:[])}getStatus(t){return this.api.get(`tx/${t}/status`).then(e=>e.status==200?{status:200,confirmed:e.data}:{status:e.status,confirmed:null})}async getData(t,e){let r;try{r=await this.chunks.downloadChunkedData(t)}catch(i){console.error(`Error while trying to download chunked data for ${t}`),console.error(i)}if(!r){console.warn(`Falling back to gateway cache for ${t}`);try{let{data:i,ok:o,status:s,statusText:c}=await this.api.get(`/${t}`,{responseType:"arraybuffer"});if(!o)throw new Error("Bad http status code",{cause:{status:s,statusText:c}});r=i}catch(i){console.error(`Error while trying to download contiguous data from gateway cache for ${t}`),console.error(i)}}if(!r)throw new Error(`${t} data was not found!`);return e&&e.decode&&!e.string?r:e&&e.decode&&e.string?oi.bufferToString(r):oi.bufferTob64Url(r)}async sign(t,e,r){let o=typeof e=="object"&&(c=>{let l=!0;return["n","e","d","p","q","dp","dq","qi"].map(g=>!(g in c)&&(l=!1)),l})(e),s=typeof arweaveWallet=="object";if(!o&&!s)throw new Error("No valid JWK or external wallet found to sign transaction.");if(s){try{(await arweaveWallet.getPermissions()).includes("SIGN_TRANSACTION")||await arweaveWallet.connect(["SIGN_TRANSACTION"])}catch{}let c=await arweaveWallet.sign(t,r);t.setSignature({id:c.id,owner:c.owner,reward:c.reward,tags:c.tags,signature:c.signature})}else if(o){t.setOwner(e.n);let c=await t.getSignatureData(),l=await this.crypto.sign(e,c,r),g=await this.crypto.hash(l);t.setSignature({id:oi.bufferTob64Url(g),owner:e.n,signature:oi.bufferTob64Url(l)})}else throw new Error("An error occurred while signing. Check wallet is valid")}async verify(t){let e=await t.getSignatureData(),r=t.get("signature",{decode:!0,string:!1}),i=oi.bufferTob64Url(await this.crypto.hash(r));if(t.id!==i)throw new Error("Invalid transaction signature or ID! The transaction ID doesn't match the expected SHA-256 hash of the signature.");return this.crypto.verify(t.owner,e,r)}async post(t){if(typeof t=="string"?t=new Ye.default(JSON.parse(t)):typeof t.readInt32BE=="function"?t=new Ye.default(JSON.parse(t.toString())):typeof t=="object"&&!(t instanceof Ye.default)&&(t=new Ye.default(t)),!(t instanceof Ye.default))throw new Error("Must be Transaction object");t.chunks||await t.prepareChunks(t.data);let e=await this.getUploader(t,t.data);try{for(;!e.isComplete;)await e.uploadChunk()}catch(r){if(e.lastResponseStatus>0)return{status:e.lastResponseStatus,statusText:e.lastResponseError,data:{error:e.lastResponseError}};throw r}return{status:200,statusText:"OK",data:{}}}async getUploader(t,e){let r;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),t instanceof Ye.default){if(e||(e=t.data),!(e instanceof Uint8Array))throw new Error("Data format is invalid");t.chunks||await t.prepareChunks(e),r=new Va.TransactionUploader(this.api,t),(!r.data||r.data.length===0)&&(r.data=e)}else{if(typeof t=="string"&&(t=await Va.TransactionUploader.fromTransactionId(this.api,t)),!e||!(e instanceof Uint8Array))throw new Error("Must provide data when resuming upload");r=await Va.TransactionUploader.fromSerialized(this.api,t,e)}return r}async*upload(t,e){let r=await this.getUploader(t,e);for(;!r.isComplete;)await r.uploadChunk(),yield r;return r}};qa.default=Ga});var yf=nt(Ha=>{"use strict";b();Object.defineProperty(Ha,"__esModule",{value:!0});var mf=be();Io();var ja=class{api;crypto;constructor(t,e){this.api=t,this.crypto=e}getBalance(t){return this.api.get(`wallet/${t}/balance`).then(e=>e.data)}getLastTransactionID(t){return this.api.get(`wallet/${t}/last_tx`).then(e=>e.data)}generate(){return this.crypto.generateJWK()}async jwkToAddress(t){return!t||t==="use_wallet"?this.getAddress():this.getAddress(t)}async getAddress(t){if(!t||t==="use_wallet"){try{await arweaveWallet.connect(["ACCESS_ADDRESS"])}catch{}return arweaveWallet.getActiveAddress()}else return this.ownerToAddress(t.n)}async ownerToAddress(t){return mf.bufferTob64Url(await this.crypto.hash(mf.b64UrlToBuffer(t)))}};Ha.default=ja});var vf=nt(si=>{"use strict";b();Object.defineProperty(si,"__esModule",{value:!0});si.SiloResource=void 0;var wf=be(),Qa=class{api;crypto;transactions;constructor(t,e,r){this.api=t,this.crypto=e,this.transactions=r}async get(t){if(!t)throw new Error("No Silo URI specified");let e=await this.parseUri(t),r=await this.transactions.search("Silo-Name",e.getAccessKey());if(r.length==0)throw new Error(`No data could be found for the Silo URI: ${t}`);let i=await this.transactions.get(r[0]);if(!i)throw new Error(`No data could be found for the Silo URI: ${t}`);let o=i.get("data",{decode:!0,string:!1});return this.crypto.decrypt(o,e.getEncryptionKey())}async readTransactionData(t,e){if(!e)throw new Error("No Silo URI specified");let r=await this.parseUri(e),i=t.get("data",{decode:!0,string:!1});return this.crypto.decrypt(i,r.getEncryptionKey())}async parseUri(t){let e=t.match(/^([a-z0-9-_]+)\.([0-9]+)/i);if(!e)throw new Error("Invalid Silo name, must be a name in the format of [a-z0-9]+.[0-9]+, e.g. 'bubble.7'");let r=e[1],i=Math.pow(2,parseInt(e[2])),o=await this.hash(wf.stringToBuffer(r),i),s=wf.bufferTob64(o.slice(0,15)),c=await this.hash(o.slice(16,31),1);return new Ao(t,s,c)}async hash(t,e){let r=await this.crypto.hash(t);for(let i=0;i{"use strict";b();Object.defineProperty(Ja,"__esModule",{value:!0});var _f=Yn(),Cp=be(),za=class{api;constructor(t){this.api=t}async getTransactionOffset(t){let e=await this.api.get(`tx/${t}/offset`);if(e.status===200)return e.data;throw new Error(`Unable to get transaction offset: ${(0,_f.getError)(e)}`)}async getChunk(t){let e=await this.api.get(`chunk/${t}`);if(e.status===200)return e.data;throw new Error(`Unable to get chunk: ${(0,_f.getError)(e)}`)}async getChunkData(t){let e=await this.getChunk(t);return Cp.b64UrlToBuffer(e.chunk)}firstChunkOffset(t){return parseInt(t.offset)-parseInt(t.size)+1}async downloadChunkedData(t){let e=await this.getTransactionOffset(t),r=parseInt(e.size),o=parseInt(e.offset)-r+1,s=new Uint8Array(r),c=0;for(;c{"use strict";b();Object.defineProperty(Ya,"__esModule",{value:!0});var Ip=Yn();Io();var Xa=class{api;network;constructor(t,e){this.api=t,this.network=e}async get(t){let e=await this.api.get(`${Xa.ENDPOINT}${t}`);if(e.status===200)return e.data;throw e.status===404?new Ip.default("BLOCK_NOT_FOUND"):new Error(`Error while loading block data: ${e}`)}async getCurrent(){let{current:t}=await this.network.getInfo();return await this.get(t)}},ko=Xa;nr(ko,"ENDPOINT","block/hash/");Ya.default=ko});var Xn=nt(Za=>{"use strict";b();Object.defineProperty(Za,"__esModule",{value:!0});var Ap=Gl(),kp=ql(),Lp=tf(),Op=ef(),Rp=pf(),Bp=yf(),Ef=xo(),ai=be(),Pp=vf(),Np=bf(),Up=Sf(),dn=class{api;wallets;transactions;network;blocks;ar;silo;chunks;constructor(t){this.api=new kp.default(t),this.wallets=new Bp.default(this.api,dn.crypto),this.chunks=new Np.default(this.api),this.transactions=new Rp.default(this.api,dn.crypto,this.chunks),this.silo=new Pp.default(this.api,this.crypto,this.transactions),this.network=new Op.default(this.api),this.blocks=new Up.default(this.api,this.network),this.ar=new Ap.default}get crypto(){return dn.crypto}get utils(){return dn.utils}getConfig(){return{api:this.api.getConfig(),crypto:null}}async createTransaction(t,e){let r={};if(Object.assign(r,t),!t.data&&!(t.target&&t.quantity))throw new Error("A new Arweave transaction must have a 'data' value, or 'target' and 'quantity' values.");if(t.owner==null&&e&&e!=="use_wallet"&&(r.owner=e.n),t.last_tx==null&&(r.last_tx=await this.transactions.getTransactionAnchor()),typeof t.data=="string"&&(t.data=ai.stringToBuffer(t.data)),t.data instanceof ArrayBuffer&&(t.data=new Uint8Array(t.data)),t.data&&!(t.data instanceof Uint8Array))throw new Error("Expected data to be a string, Uint8Array or ArrayBuffer");if(t.reward==null){let o=t.data?t.data.byteLength:0;r.reward=await this.transactions.getPrice(o,r.target)}r.data_root="",r.data_size=t.data?t.data.byteLength.toString():"0",r.data=t.data||new Uint8Array(0);let i=new Ef.default(r);return await i.getSignatureData(),i}async createSiloTransaction(t,e,r){let i={};if(Object.assign(i,t),!t.data)throw new Error("Silo transactions must have a 'data' value");if(!r)throw new Error("No Silo URI specified.");if(t.target||t.quantity)throw new Error("Silo transactions can only be used for storing data, sending AR to other wallets isn't supported.");if(t.owner==null){if(!e||!e.n)throw new Error("A new Arweave transaction must either have an 'owner' attribute, or you must provide the jwk parameter.");i.owner=e.n}t.last_tx==null&&(i.last_tx=await this.transactions.getTransactionAnchor());let o=await this.silo.parseUri(r);if(typeof t.data=="string"){let c=await this.crypto.encrypt(ai.stringToBuffer(t.data),o.getEncryptionKey());i.reward=await this.transactions.getPrice(c.byteLength),i.data=ai.bufferTob64Url(c)}if(t.data instanceof Uint8Array){let c=await this.crypto.encrypt(t.data,o.getEncryptionKey());i.reward=await this.transactions.getPrice(c.byteLength),i.data=ai.bufferTob64Url(c)}let s=new Ef.default(i);return s.addTag("Silo-Name",o.getAccessKey()),s.addTag("Silo-Version","0.1.0"),s}arql(t){return this.api.post("/arql",t).then(e=>e.data||[])}},gn=dn;nr(gn,"init"),nr(gn,"crypto",new Lp.default),nr(gn,"utils",ai);Za.default=gn});var Tf=nt(Lo=>{"use strict";b();Object.defineProperty(Lo,"__esModule",{value:!0});Lo.getDefaultConfig=void 0;var Wp=(n,t)=>{let e=/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,r=t.split("."),i=r[r.length-1],o=["localhost","[::1]"];return o.includes(t)||n=="file"||o.includes(i)||!!t.match(e)||!!i.match(e)},Dp=n=>{let t=n.charAt(0)==="[",e=/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;return!!n.match(e)||t},Mp=(n,t)=>{if(Wp(n,t))return{protocol:"https",host:"arweave.net",port:443};if(!Dp(t)){let e=t.split(".");if(e.length>=3){e.shift();let r=e.join(".");return{protocol:n,host:r}}}return{protocol:n,host:t}};Lo.getDefaultConfig=Mp});var Oo=nt(vr=>{"use strict";b();var Fp=vr&&vr.__createBinding||(Object.create?function(n,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,r,i)}:function(n,t,e,r){r===void 0&&(r=e),n[r]=t[e]}),$p=vr&&vr.__exportStar||function(n,t){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&Fp(t,n,e)};Object.defineProperty(vr,"__esModule",{value:!0});var pn=Xn(),Kp=Tf();pn.default.init=function(n={}){let t={host:"arweave.net",port:443,protocol:"https"};if(typeof location!="object"||!location.protocol||!location.hostname)return new pn.default({...n,...t});let e=location.protocol.replace(":",""),r=location.hostname,i=location.port?parseInt(location.port):e=="https"?443:80,o=(0,Kp.getDefaultConfig)(e,r),s=n.protocol||o.protocol,c=n.host||o.host,l=n.port||o.port||i;return new pn.default({...n,host:c,protocol:s,port:l})};typeof globalThis=="object"?globalThis.Arweave=pn.default:typeof self=="object"&&(self.Arweave=pn.default);$p(Xn(),vr);vr.default=pn.default});var th=nt((pc,Zf)=>{"use strict";b();var{hasOwnProperty:Ko}=Object.prototype,jr=dc();jr.configure=dc;jr.stringify=jr;jr.default=jr;pc.stringify=jr;pc.configure=dc;Zf.exports=jr;var Xf=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/,bm=new RegExp(Xf,"g"),gc=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000b","\\f","\\r","\\u000e","\\u000f","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001a","\\u001b","\\u001c","\\u001d","\\u001e","\\u001f","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\"];function Sm(n){if(n.length===2){let e=n.charCodeAt(1);return`${n[0]}\\u${e.toString(16)}`}let t=n.charCodeAt(0);return gc.length>t?gc[t]:`\\u${t.toString(16)}`}function br(n){if(n.length<5e3&&!Xf.test(n))return n;if(n.length>100)return n.replace(bm,Sm);let t="",e=0;for(let r=0;r=55296&&i<=57343){if(i<=56319&&r+1=56320&&o<=57343){r++;continue}}t+=`${n.slice(e,r)}\\u${i.toString(16)}`,e=r+1}}return t+=n.slice(e),t}function lc(n){if(n.length>200)return n.sort();for(let t=1;te;)n[r]=n[r-1],r--;n[r]=e}return n}var Em=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function fc(n){return Em.call(n)!==void 0&&n.length!==0}function hc(n,t,e){n.length= 1`)}return e===void 0?1/0:e}function qr(n){return n===1?"1 item":`${n} items`}function xm(n){let t=new Set;for(let e of n)(typeof e=="string"||typeof e=="number")&&t.add(String(e));return t}function Cm(n){if(Ko.call(n,"strict")){let t=n.strict;if(typeof t!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(t)return e=>{let r=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!="function"&&(r+=` (${e.toString()})`),new Error(r)}}}function dc(n){n={...n};let t=Cm(n);t&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let e=Tm(n),r=Jf(n,"bigint"),i=Jf(n,"deterministic"),o=Yf(n,"maximumDepth"),s=Yf(n,"maximumBreadth");function c(E,d,y,k,N,q){let Q=d[E];switch(typeof Q=="object"&&Q!==null&&typeof Q.toJSON=="function"&&(Q=Q.toJSON(E)),Q=k.call(d,E,Q),typeof Q){case"string":return`"${br(Q)}"`;case"object":{if(Q===null)return"null";if(y.indexOf(Q)!==-1)return e;let z="",X=",",D=q;if(Array.isArray(Q)){if(Q.length===0)return"[]";if(os){let wt=Q.length-s-1;z+=`${X}"... ${qr(wt)} not stringified"`}return N!==""&&(z+=` +${D}`),y.pop(),`[${z}]`}let G=Object.keys(Q),it=G.length;if(it===0)return"{}";if(os){let tt=it-s;z+=`${O}"...":${et}"${qr(tt)} not stringified"`,O=X}return N!==""&&O.length>1&&(z=` +${q}${z} +${D}`),y.pop(),`{${z}}`}case"number":return isFinite(Q)?String(Q):t?t(Q):"null";case"boolean":return Q===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(Q);default:return t?t(Q):void 0}}function l(E,d,y,k,N,q){switch(typeof d=="object"&&d!==null&&typeof d.toJSON=="function"&&(d=d.toJSON(E)),typeof d){case"string":return`"${br(d)}"`;case"object":{if(d===null)return"null";if(y.indexOf(d)!==-1)return e;let Q=q,z="",X=",";if(Array.isArray(d)){if(d.length===0)return"[]";if(os){let ft=d.length-s-1;z+=`${X}"... ${qr(ft)} not stringified"`}return N!==""&&(z+=` +${Q}`),y.pop(),`[${z}]`}if(k.size===0)return"{}";y.push(d);let D="";N!==""&&(q+=N,X=`, +${q}`,D=" ");let G="";for(let it of k){let et=l(it,d[it],y,k,N,q);et!==void 0&&(z+=`${G}"${br(it)}":${D}${et}`,G=X)}return N!==""&&G.length>1&&(z=` +${q}${z} +${Q}`),y.pop(),`{${z}}`}case"number":return isFinite(d)?String(d):t?t(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(d);default:return t?t(d):void 0}}function g(E,d,y,k,N){switch(typeof d){case"string":return`"${br(d)}"`;case"object":{if(d===null)return"null";if(typeof d.toJSON=="function"){if(d=d.toJSON(E),typeof d!="object")return g(E,d,y,k,N);if(d===null)return"null"}if(y.indexOf(d)!==-1)return e;let q=N;if(Array.isArray(d)){if(d.length===0)return"[]";if(os){let st=d.length-s-1;et+=`${O}"... ${qr(st)} not stringified"`}return et+=` +${q}`,y.pop(),`[${et}]`}let Q=Object.keys(d),z=Q.length;if(z===0)return"{}";if(os){let et=z-s;D+=`${G}"...": "${qr(et)} not stringified"`,G=X}return G!==""&&(D=` +${N}${D} +${q}`),y.pop(),`{${D}}`}case"number":return isFinite(d)?String(d):t?t(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(d);default:return t?t(d):void 0}}function w(E,d,y){switch(typeof d){case"string":return`"${br(d)}"`;case"object":{if(d===null)return"null";if(typeof d.toJSON=="function"){if(d=d.toJSON(E),typeof d!="object")return w(E,d,y);if(d===null)return"null"}if(y.indexOf(d)!==-1)return e;let k="";if(Array.isArray(d)){if(d.length===0)return"[]";if(os){let it=d.length-s-1;k+=`,"... ${qr(it)} not stringified"`}return y.pop(),`[${k}]`}let N=Object.keys(d),q=N.length;if(q===0)return"{}";if(os){let X=q-s;k+=`${Q}"...":"${qr(X)} not stringified"`}return y.pop(),`{${k}}`}case"number":return isFinite(d)?String(d):t?t(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(d);default:return t?t(d):void 0}}function v(E,d,y){if(arguments.length>1){let k="";if(typeof y=="number"?k=" ".repeat(Math.min(y,10)):typeof y=="string"&&(k=y.slice(0,10)),d!=null){if(typeof d=="function")return c("",{"":E},[],d,k,"");if(Array.isArray(d))return l("",E,[],xm(d),k,"")}if(k.length!==0)return g("",E,[],k,"")}return w("",E,[])}return v}});b();b();b();var ag={silly:0,trace:1,debug:2,info:3,warn:4,error:5,fatal:6,none:7};function ys(n){return ag[n]}var Ei=class{constructor(t,e){this.moduleName=t;this.settings=e}trace(t,...e){this.shouldLog("trace")&&console.debug(this.message("trace",t),e)}error(t,...e){this.shouldLog("error")&&console.error(this.message("error",t),e)}info(t,...e){this.shouldLog("info")&&console.info(this.message("info",t),e)}silly(t,...e){this.shouldLog("silly")&&console.debug(this.message("silly",t),e)}debug(t,...e){this.shouldLog("debug")&&console.debug(this.message("debug",t),e)}warn(t,...e){this.shouldLog("warn")&&console.warn(this.message("warn",t),e)}log(t,...e){this.shouldLog("info")&&console.info(this.message("info",t),e)}fatal(t,...e){this.shouldLog("fatal")&&console.error(this.message("fatal",t),e)}shouldLog(t){return ys(t)>=ys(this.settings.minLevel)}setSettings(t){this.settings=t}message(t,e){return`${new Date().toISOString()} ${t.toUpperCase()} [${this.moduleName}] ${e}`}};b();var Ti=class{registeredLoggers={};registeredOptions={};defOptions={minLevel:"info"};constructor(){this.setOptions=this.setOptions.bind(this),this.getOptions=this.getOptions.bind(this),this.create=this.create.bind(this),this.logLevel=this.logLevel.bind(this)}setOptions(t,e){e?this.registeredLoggers[e]?this.registeredLoggers[e].setSettings({...this.registeredLoggers[e].settings,...t}):this.registeredOptions[e]={...this.defOptions,...t}:(this.defOptions=t,Object.keys(this.registeredLoggers).forEach(r=>{this.registeredLoggers[r].setSettings({...this.registeredLoggers[r].settings,...t})}))}getOptions(t){return t?this.registeredLoggers[t]?this.registeredLoggers[t].settings:this.registeredOptions[t]?this.registeredOptions[t]:this.defOptions:this.defOptions}logLevel(t,e){this.setOptions({minLevel:t},e)}create(t="SWC"){return Object.prototype.hasOwnProperty.call(this.registeredLoggers,t)||(this.registeredLoggers[t]=new Ei(t,this.getOptions(t))),this.registeredLoggers[t]}};b();var Ar=class{constructor(){}setOptions(t,e){Ar.INST.setOptions(t,e)}getOptions(t){return Ar.INST.getOptions(t)}logLevel(t,e){Ar.INST.logLevel(t,e)}create(t){return Ar.INST.create(t)}static use(t){Ar.INST=t}},ct=Ar;nr(ct,"INST",new Ti);b();var Et=class{static measure(){return new Et}constructor(){}start=Date.now();end=null;reset(){this.start=Date.now(),this.end=null}stop(){this.end=Date.now()}elapsed(t=!1){this.end===null&&(this.end=Date.now());let e=this.end-this.start;return t?e:`${(this.end-this.start).toFixed(0)}ms`}};b();var Jt=class{constructor(t,e){this.key=t;this.sortKey=e}},Ut=class{constructor(t,e){this.sortKey=t;this.cachedValue=e}};b();var vl=jt(ll()),_l=jt(wl());var oo=class{constructor(t,e=!1){this.value=t;this.tomb=e}},Qe=class{constructor(t){this.cacheOptions=t;this.subLevelSeparator=t.subLevelSeparator||"!",this.subLevelOptions={valueEncoding:"json",separator:this.subLevelSeparator}}ongoingTransactionMark="$$warp-internal-transaction$$";logger=ct.INST.create("LevelDbCache");subLevelSeparator;subLevelOptions;_db;_rollbackBatch;get db(){if(!this._db)if(this.cacheOptions.inMemory)this._db=new _l.MemoryLevel(this.subLevelOptions);else{if(!this.cacheOptions.dbLocation)throw new Error("LevelDb cache configuration error - no db location specified");let t=this.cacheOptions.dbLocation;this.logger.info(`Using location ${t}`),this._db=new vl.Level(t,this.subLevelOptions)}return this._db}async get(t,e){this.validateKey(t.key);let r=this.db.sublevel(t.key,this.subLevelOptions);await r.open();let i=await this.getValueFromLevel(t.sortKey,r);return i?new Ut(t.sortKey,i):null}async getLast(t){let e=this.db.sublevel(t,this.subLevelOptions);await e.open();let r=await e.keys({reverse:!0,limit:1}).all();if(r.length){let i=await this.getValueFromLevel(r[0],e);if(i)return new Ut(r[0],i)}return null}async getLessOrEqual(t,e){let r=this.db.sublevel(t,this.subLevelOptions);await r.open();let i=await r.keys({reverse:!0,lte:e,limit:1}).all();if(i.length){let o=await this.getValueFromLevel(i[0],r);if(o!=null)return new Ut(i[0],o)}return null}async getValueFromLevel(t,e){try{let r=await e.get(t);if(r&&r.tomb===void 0&&r.value===void 0)return r;if(r&&r.tomb===!1&&r.value!=null)return r.value}catch(r){if(r.code!="LEVEL_NOT_FOUND")throw r}return null}async put(t,e){await this.setClientValue(t,new oo(e))}async del(t){await this.setClientValue(t,new oo(null,!0))}async setClientValue(t,e){this.validateKey(t.key);let r=this.db.sublevel(t.key,this.subLevelOptions);await r.open(),await r.put(t.sortKey,e),this._rollbackBatch&&this._rollbackBatch.del(t.sortKey,{sublevel:r})}async delete(t){let e=this.db.sublevel(t,this.subLevelOptions);await e.open(),await e.clear()}async batch(t){for(let e of t)e.type==="put"?await this.put(e.key,e.value):e.type==="del"&&await this.delete(e.key)}async open(){await this.db.open()}async close(){this._db&&await this._db.close()}async begin(){await this.initRollbackBatch()}async rollback(){this._rollbackBatch&&(this._rollbackBatch.del(this.ongoingTransactionMark),await this._rollbackBatch.write(),await this._rollbackBatch.close()),this._rollbackBatch=null}async initRollbackBatch(){return this._rollbackBatch==null&&(await this.checkPreviousTransactionFinished(),await this.db.put(this.ongoingTransactionMark,"ongoing"),this._rollbackBatch=this.db.batch()),this._rollbackBatch}async checkPreviousTransactionFinished(){let t;try{t=await this.db.get(this.ongoingTransactionMark)}catch(e){if(e.code!="LEVEL_NOT_FOUND")throw e}if(t=="ongoing")throw new Error("Database seems to be in inconsistent state. The previous transaction has not finished.")}async commit(){this._rollbackBatch&&(await this._rollbackBatch.clear(),await this.db.del(this.ongoingTransactionMark),await this._rollbackBatch.close()),this._rollbackBatch=null}async dump(){return await this.db.iterator().all()}async getLastSortKey(){let t="";await this.db.open();let e=await this.db.keys().all();for(let r of e){let i=r.split(this.subLevelSeparator)[1];i.localeCompare(t)>0&&(t=i)}return t==""?null:t}async keys(t,e){return Array.from((await this.kvMap(t,e)).keys())}validateKey(t){if(t.includes(this.ongoingTransactionMark))throw new Error(`Validation error: Key ${t} for internal use only`);if(t.includes(this.subLevelSeparator))throw new Error(`Validation error: key ${t} contains db separator ${this.subLevelSeparator}`)}extractOriginalKey(t){return t.split(this.subLevelSeparator)[1]}extractSortKey(t){return t.split(this.subLevelSeparator)[2]}async kvMap(t,e){let r=new Map,i=(await this.db.keys(this.levelRangeOptions(e)).all()).filter(o=>o!=this.ongoingTransactionMark).filter(o=>!t||this.extractSortKey(o).localeCompare(t)<=0).map(o=>this.extractOriginalKey(o));for(let o of i){let s=await this.getLessOrEqual(o,t);s&&r.set(o,s.cachedValue)}if(e?.limit){let o=new Map;for(let s of Array.from(r.entries()).slice(0,e.limit))o.set(s[0],s[1]);return o}return r}levelRangeOptions(t){let e={reverse:t?.reverse};return t?.gte&&(e.gte=this.subLevelSeparator+t.gte),t?.lt&&(e.lt=this.subLevelSeparator+t.lt),e}storage(){return this.db}async getNumEntries(){return(await this.db.keys().all()).length}async prune(t=5){(!t||t<=0)&&(t=1);let e=await this.allKeys();for(let r=0;rt!=this.ongoingTransactionMark).map(t=>this.extractOriginalKey(t))}};b();var bl=class{storage={};clearAll(){Object.keys(this.storage).forEach(t=>{delete this.storage[t]})}contains(t){return Object.prototype.hasOwnProperty.call(this.storage,t)}get(t){return this.storage[t]}put(t,e){this.storage[t]=e}remove(t){delete this.storage[t]}};b();b();var mv=jt(mr());b();b();var Cd=Function.prototype.toString,ga=Object.create,Id=Object.prototype.toString,Ad=function(){function n(){this._keys=[],this._values=[]}return n.prototype.has=function(t){return!!~this._keys.indexOf(t)},n.prototype.get=function(t){return this._values[this._keys.indexOf(t)]},n.prototype.set=function(t,e){this._keys.push(t),this._values.push(e)},n}();function kd(){return new Ad}function Ld(){return new WeakMap}var Od=typeof WeakMap<"u"?Ld:kd;function pa(n){if(!n)return ga(null);var t=n.constructor;if(t===Object)return n===Object.prototype?{}:ga(n);if(~Cd.call(t).indexOf("[native code]"))try{return new t}catch{}return ga(n)}function Rd(n){var t="";return n.global&&(t+="g"),n.ignoreCase&&(t+="i"),n.multiline&&(t+="m"),n.unicode&&(t+="u"),n.sticky&&(t+="y"),t}function Bd(n){return n.flags}var Pd=/test/g.flags==="g"?Bd:Rd;function Sl(n){var t=Id.call(n);return t.substring(8,t.length-1)}function Nd(n){return n[Symbol.toStringTag]||Sl(n)}var Ud=typeof Symbol<"u"?Nd:Sl,Wd=Object.defineProperty,Dd=Object.getOwnPropertyDescriptor,El=Object.getOwnPropertyNames,ma=Object.getOwnPropertySymbols,Tl=Object.prototype,xl=Tl.hasOwnProperty,Md=Tl.propertyIsEnumerable,Cl=typeof ma=="function";function Fd(n){return El(n).concat(ma(n))}var $d=Cl?Fd:El;function ao(n,t,e){for(var r=$d(n),i=0,o=r.length,s=void 0,c=void 0;i{throw new Error("Not implemented - should be set by HandlerApi implementor")},viewContractState:(s,c)=>{throw new Error("Not implemented - should be set by HandlerApi implementor")},write:(s,c,l)=>{throw new Error("Not implemented - should be set by HandlerApi implementor")},refreshState:()=>{throw new Error("Not implemented - should be set by HandlerApi implementor")}},this.vrf=new jn(this),this.useGas=this.useGas.bind(this),this.getBalance=this.getBalance.bind(this),this.extensions={},this.kv=new wa(o,i,this.transaction,this.contract.id)}useGas(t){if(t<0)throw new Error("[RE:GNE] Gas number exception - gas < 0.");if(this.gasUsed+=t,this.gasUsed>this.gasLimit)throw new Error(`[RE:OOG] Out of gas! Used: ${this.gasUsed}, limit: ${this.gasLimit}`)}async getBalance(t,e){if(!this._activeTx)throw new Error("Cannot read balance - active tx is not set.");if(!this.block.height)throw new Error("Cannot read balance - block height not set.");let r=e||this.block.height;return await fetch(`${this.evaluationOptions.walletBalanceUrl}block/height/${r}/wallet/${t}/balance`).then(i=>i.ok?i.text():Promise.reject(i)).catch(i=>{throw new Error(`Unable to read wallet balance. ${i.status}. ${i.body?.message}`)})}},Gn=class{constructor(t){this.smartWeaveGlobal=t}get id(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.id}get owner(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.owner.address}get target(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.recipient}get tags(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.tags}get sortKey(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.sortKey}get dryRun(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.dry===!0}get quantity(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.quantity.winston}get reward(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.fee.winston}get origin(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.source==="redstone-sequencer"?"L2":"L1"}},qn=class{constructor(t){this.smartWeaveGlobal=t}get height(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.block.height}get indep_hash(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.block.id}get timestamp(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current tx");return this.smartWeaveGlobal._activeTx.block.timestamp}},jn=class{constructor(t){this.smartWeaveGlobal=t}get data(){return this.smartWeaveGlobal._activeTx.vrf}get value(){return this.smartWeaveGlobal._activeTx.vrf.bigint}randomInt(t){if(!Number.isInteger(t))throw new Error("Integer max value required for random integer generation");let e=BigInt(this.smartWeaveGlobal._activeTx.vrf.bigint)%BigInt(t)+BigInt(1);if(e>Number.MAX_SAFE_INTEGER||e{let o=ct.INST.create("WASM:Rust"),s={metering:{usegas:n.useGas},console:{log:function(h){o.debug(`${n.contract.id}: ${h}`)}},Block:{height:function(){return n.block.height},indep_hash:function(){return n.block.indep_hash},timestamp:function(){return n.block.timestamp}},Transaction:{id:function(){return n.transaction.id},owner:function(){return n.transaction.owner},target:function(){return n.transaction.target}},Contract:{id:function(){return n.contract.id},owner:function(){return n.contract.owner}},KV:{get:async function(h){return await n.kv.get(h)},put:async function(h,m){await n.kv.put(h,m)},del:async function(h){await n.kv.del(h)},map:async function(h,m,I,j){return await n.kv.kvMap({gte:h,lt:m,reverse:I,limit:j})},keys:async function(h,m,I,j){return await n.kv.keys({gte:h,lt:m,reverse:I,limit:j})}},SmartWeave:{caller:function(){return n.caller},readContractState:async function(h){return await n.contracts.readContractState(h)},viewContractState:async function(h,m){return await n.contracts.viewContractState(h,m)},write:async function(h,m){return await n.contracts.write(h,m,!1)}},Vrf:{value:function(){return n.vrf.value},randomInt:function(h){return n.vrf.randomInt(h)}}},c=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});c.decode();let l=null;function g(){return(l===null||l.byteLength===0)&&(l=new Uint8Array(e.exports.memory.buffer)),l}function w(h,m){return c.decode(g().subarray(h,h+m))}let v=new Array(128).fill(void 0);v.push(void 0,null,!0,!1);let E=v.length;function d(h){E===v.length&&v.push(v.length+1);let m=E;if(E=v[m],typeof E!="number")throw new Error("corrupt heap");return v[m]=h,m}function y(h){return v[h]}function k(h){if(typeof h!="boolean")throw new Error("expected a boolean argument")}function N(h){return h==null}function q(h){if(typeof h!="number")throw new Error("expected a number argument")}let Q=null;function z(){return(Q===null||Q.byteLength===0)&&(Q=new Float64Array(e.exports.memory.buffer)),Q}let X=null;function D(){return(X===null||X.byteLength===0)&&(X=new Int32Array(e.exports.memory.buffer)),X}let G=0,it=new TextEncoder("utf-8"),et=typeof it.encodeInto=="function"?function(h,m){return it.encodeInto(h,m)}:function(h,m){let I=it.encode(h);return m.set(I),{read:h.length,written:I.length}};function O(h,m,I){if(I===void 0){let u=it.encode(h),f=m(u.length);return g().subarray(f,f+u.length).set(u),G=u.length,f}let j=h.length,Z=m(j),rt=g(),a=0;for(;a127)break;rt[Z+a]=u}if(a!==j){a!==0&&(h=h.slice(a)),Z=I(Z,j,j=a+h.length*3);let u=g().subarray(Z+a,Z+j),f=et(h,u);a+=f.written}return G=a,Z}function ft(h){h<132||(v[h]=E,E=h)}function tt(h){let m=y(h);return ft(h),m}function lt(h){let m=typeof h;if(m=="number"||m=="boolean"||h==null)return`${h}`;if(m=="string")return`"${h}"`;if(m=="symbol"){let Z=h.description;return Z==null?"Symbol":`Symbol(${Z})`}if(m=="function"){let Z=h.name;return typeof Z=="string"&&Z.length>0?`Function(${Z})`:"Function"}if(Array.isArray(h)){let Z=h.length,rt="[";Z>0&&(rt+=lt(h[0]));for(let a=1;a1)j=I[1];else return toString.call(h);if(j=="Object")try{return"Object("+JSON.stringify(h)+")"}catch{return"Object"}return h instanceof Error?`${h.name}: ${h.message} +${h.stack}`:j}function st(h){if(typeof h!="bigint")throw new Error("expected a bigint argument")}let wt=null;function Pt(){return(wt===null||wt.byteLength===0)&&(wt=new BigInt64Array(e.exports.memory.buffer)),wt}function Tt(h,m,I,j){let Z={a:h,b:m,cnt:1,dtor:I},rt=(...a)=>{Z.cnt++;let u=Z.a;Z.a=0;try{return j(u,Z.b,...a)}finally{--Z.cnt===0?e.exports.__wbindgen_export_2.get(Z.dtor)(u,Z.b):Z.a=u}};return rt.original=Z,rt}function ht(h,m){try{return h.apply(this,m)}catch(I){let j=function(){try{return I instanceof Error?`${I.message} + +Stack: +${I.stack}`:I.toString()}catch{return""}}();throw console.error("wasm-bindgen: imported JS function that was not marked as `catch` threw an error:",j),I}}function _t(h,m,I){e.modifiedExports._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__(h,m,d(I))}function Nt(h){let m=e.exports.warpContractWrite(d(h));return tt(m)}function Ue(h){var m=e.exports.handle(d(h));return tt(m)}let yt=128;function Lt(h){if(yt==1)throw new Error("out of js stack");return v[--yt]=h,yt}function Y(h){try{e.exports.initState(Lt(h))}finally{v[yt++]=void 0}}function er(h){try{e.exports.initState(Lt(h))}finally{v[yt++]=void 0}}function Er(){let h=e.exports.currentState();return tt(h)}function rr(){return e.exports.version()}function Vt(){return e.exports.lang()}function Dt(h){let m=e.exports.warpContractView(d(h));return tt(m)}function p(h,m){try{return h.apply(this,m)}catch(I){e.exports.__wbindgen_exn_store(d(I))}}function _(h,m,I,j){e.modifiedExports.wasm_bindgen__convert__closures__invoke2_mut__(h,m,d(I),d(j))}function S(h){return()=>{throw new Error(`${h} is not defined`)}}let U={__wbindgen_json_parse:function(h,m){let I=JSON.parse(w(h,m));return d(I)},__wbindgen_json_serialize:function(h,m){let I=y(m),j=JSON.stringify(I===void 0?null:I),Z=O(j,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),rt=G;D()[h/4+1]=rt,D()[h/4+0]=Z},__wbindgen_error_new:function(h,m){let I=new Error(w(h,m));return d(I)},__wbindgen_is_undefined:function(h){return y(h)===void 0},__wbindgen_in:function(h,m){return y(h)in y(m)},__wbindgen_number_get:function(h,m){let I=y(m),j=typeof I=="number"?I:void 0;z()[h/8+1]=N(j)?0:j,D()[h/4+0]=!N(j)},__wbindgen_boolean_get:function(h){let m=y(h),I=typeof m=="boolean"?m?1:0:2;return q(I),I},__wbindgen_is_null:function(h){let m=y(h)===null;return k(m),m},__wbindgen_string_new:function(h,m){let I=w(h,m);return d(I)},__wbindgen_string_get:function(h,m){let I=y(m),j=typeof I=="string"?I:void 0;var Z=N(j)?0:O(j,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),rt=G;D()[h/4+1]=rt,D()[h/4+0]=Z},__wbindgen_is_bigint:function(h){return typeof y(h)=="bigint"},__wbindgen_is_object:function(h){let m=y(h);return typeof m=="object"&&m!==null},__wbindgen_object_clone_ref:function(h){let m=y(h);return d(m)},__wbindgen_jsval_eq:function(h,m){return y(h)===y(m)},__wbindgen_bigint_from_i64:function(h){return d(h)},__wbindgen_bigint_from_u64:function(h){let m=BigInt.asUintN(64,h);return d(m)},__wbg_readContractState:function(){return p(function(h,m){let I=s.SmartWeave.readContractState(w(h,m));return d(I)},arguments)},__wbg_viewContractState:function(){return p(function(h,m,I){let j=s.SmartWeave.viewContractState(w(h,m),tt(I));return d(j)},arguments)},__wbg_write:function(){return p(function(h,m,I){let j=s.SmartWeave.write(w(h,m),tt(I));return d(j)},arguments)},__wbg_refreshState:function(h,m){},__wbg_kvGet:function(){return p(function(h,m){let I=s.KV.get(w(h,m));return d(I)},arguments)},__wbg_kvPut:function(){return p(function(h,m,I){let j=s.KV.put(w(h,m),tt(I));return d(j)},arguments)},__wbg_kvDel:function(){return p(function(h,m){let I=s.KV.del(w(h,m));return d(I)},arguments)},__wbg_kvMap:function(){return p(function(h,m,I,j,Z,rt,a){let u=s.KV.map(h===0?void 0:w(h,m),I===0?void 0:w(I,j),Z===16777215?void 0:Z!==0,rt===0?void 0:a>>>0);return d(u)},arguments)},__wbg_kvKeys:function(){return p(function(h,m,I,j,Z,rt,a){let u=s.KV.keys(h===0?void 0:w(h,m),I===0?void 0:w(I,j),Z===16777215?void 0:Z!==0,rt===0?void 0:a>>>0);return d(u)},arguments)},__wbindgen_object_drop_ref:function(h){tt(h)},__wbg_error:function(){return ht(function(h,m){try{s.console.log(w(h,m))}finally{e.exports.__wbindgen_free(h,m)}},arguments)},__wbg_new_abda76e883ba8a5f:function(){return ht(function(){let h=new Error;return d(h)},arguments)},__wbg_stack:function(){return ht(function(h,m){let I=Error.stackTraceLimit;Error.stackTraceLimit=25;let j=y(m).stack,Z=O(j,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),rt=G;D()[h/4+1]=rt,D()[h/4+0]=Z,Error.stackTraceLimit=I},arguments)},__wbg_indephash:function(){return ht(function(h){let m=s.Block.indep_hash(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_height:function(){return ht(function(){let h=s.Block.height();return q(h),h},arguments)},__wbg_timestamp:function(){return ht(function(){let h=s.Block.timestamp();return q(h),h},arguments)},__wbg_contractId:function(){return ht(function(h){let m=s.Contract.id(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_contractOwner:function(){return ht(function(h){let m=s.Contract.owner(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_id:function(h){let m=s.Transaction.id(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},__wbg_owner:function(h){let m=s.Transaction.owner(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},__wbg_target:function(){return ht(function(h){let m=s.Transaction.target(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_caller:function(h){let m=s.SmartWeave.caller(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},__wbg_value_b245bf3240b21a48:function(){return ht(function(h){let m=s.Vrf.value(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_value_7d69ddc3f1ad7876:function(){return ht(function(h){let m=s.Vrf.value(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_vrfValue:function(){return ht(function(h){let m=s.Vrf.value(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_randomInt:function(){return ht(function(h){let m=s.Vrf.randomInt(h);return q(m),m},arguments)},__wbg_log:function(h,m){console.log(w(h,m))},__wbindgen_cb_drop:function(h){let m=tt(h).original;return m.cnt--==1?(m.a=0,!0):!1},__wbg_debug:function(){return ht(function(h){console.log(y(h))},arguments)},__wbg_String:function(){return ht(function(h,m){let I=String(y(m)),j=O(I,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),Z=G;D()[h/4+1]=Z,D()[h/4+0]=j},arguments)},__wbg_getwithrefkey:function(h,m){let I=y(h)[y(m)];return d(I)},__wbg_set_841ac57cff3d672b:function(h,m,I){y(h)[tt(m)]=tt(I)},__wbindgen_number_new:function(h){return d(h)},__wbindgen_jsval_loose_eq:function(h,m){return y(h)==y(m)},__wbg_get_27fe3dac1c4d0224:function(h,m){let I=y(h)[m>>>0];return d(I)},__wbg_set_17224bc548dd1d7b:function(h,m,I){y(h)[m>>>0]=tt(I)},__wbg_isArray:function(h){return Array.isArray(y(h))},__wbg_length_e498fbc24f9c1d4f:function(h){return y(h).length},__wbg_new_b525de17f44a8943:function(){let h=new Array;return d(h)},__wbg_instanceof_ArrayBuffer:function(h){let m;try{m=y(h)instanceof ArrayBuffer}catch{m=!1}return m},__wbg_call_95d1ea488d03e4e8:function(){return p(function(h,m){let I=y(h).call(y(m));return d(I)},arguments)},__wbg_call_9495de66fdbe016b:function(){return p(function(h,m,I){let j=y(h).call(y(m),y(I));return d(j)},arguments)},__wbg_call_94697a95cb7e239c:function(){return p(function(h,m,I){let j=y(h).call(y(m),y(I));return d(j)},arguments)},__wbg_new_f841cc6f2098f4b5:function(){return d(new Map)},__wbg_set_388c4c6422704173:function(h,m,I){let j=y(h).set(y(m),y(I));return d(j)},__wbg_next_88560ec06a094dea:function(){return p(function(h){let m=y(h).next();return d(m)},arguments)},__wbg_next_b7d530c04fd8b217:function(h){let m=y(h).next;return d(m)},__wbg_done:function(h){return y(h).done},__wbg_value_6ac8da5cc5b3efda:function(h){let m=y(h).value;return d(m)},__wbg_isSafeInteger:function(h){return Number.isSafeInteger(y(h))},__wbg_entries:function(h){let m=Object.entries(y(h));return d(m)},__wbg_new_f9876326328f45ed:function(){let h=new Object;return d(h)},__wbg_iterator:function(){return d(Symbol.iterator)},__wbg_new_9d3a9ce4282a18a8:function(h,m){try{var I={a:h,b:m},j=(rt,a)=>{let u=I.a;I.a=0;try{return _(u,I.b,rt,a)}finally{I.a=u}};let Z=new Promise(j);return d(Z)}finally{I.a=I.b=0}},__wbg_resolve:function(h){let m=Promise.resolve(y(h));return d(m)},__wbg_then_ec5db6d509eb475f:function(h,m){let I=y(h).then(y(m));return d(I)},__wbg_then_a6860c82b90816ca:function(){return ht(function(h,m){let I=y(h).then(y(m));return d(I)},arguments)},__wbg_then_f753623316e2873a:function(h,m,I){let j=y(h).then(y(m),y(I));return d(j)},__wbg_then_58a04e42527f52c6:function(){return ht(function(h,m,I){let j=y(h).then(y(m),y(I));return d(j)},arguments)},__wbg_instanceof_Uint8Array:function(h){let m;try{m=y(h)instanceof Uint8Array}catch{m=!1}return m},__wbg_new_537b7341ce90bb31:function(h){let m=new Uint8Array(y(h));return d(m)},__wbg_length_27a2afe8ab42b09f:function(h){return y(h).length},__wbg_set_17499e8aa4003ebd:function(h,m,I){y(h).set(y(m),I>>>0)},__wbindgen_is_function:function(h){return typeof y(h)=="function"},__wbindgen_is_string:function(h){return typeof y(h)=="string"},__wbg_buffer:function(h){let m=y(h).buffer;return d(m)},__wbg_get_baf4855f9a986186:function(){return p(function(h,m){let I=Reflect.get(y(h),y(m));return d(I)},arguments)},__wbindgen_debug_string:function(h,m){let I=lt(y(m)),j=O(I,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),Z=G;D()[h/4+1]=Z,D()[h/4+0]=j},__wbindgen_bigint_get_as_i64:function(h,m){let I=y(m),j=typeof I=="bigint"?I:void 0;Pt()[h/8+1]=N(j)?BigInt(0):j,D()[h/4+0]=!N(j)},__wbindgen_throw:function(h,m){throw new Error(w(h,m))},__wbindgen_memory:function(){let h=e.exports.memory;return d(h)},__wbindgen_closure_wrapper:function(h,m,I){let j=Tt(h,m,r,_t);return d(j)}},C={_assertBoolean:k,_assertNum:q,addBorrowedObject:Lt,addHeapObject:d,getInt32Memory0:D,getObject:y,getStringFromWasm0:w,handleError:p,heap:()=>v,logError:ht,notDefined:S,passStringToWasm0:O,takeObject:tt,wasm:()=>e.exports,WASM_VECTOR_LEN:()=>G,__wbg_adapter_1:_,__wbg_adapter_5:_t};function R(h){return function(){return ht(function(m){let I=h(tt(m));return d(I)},arguments)}}function W(h,m){let I={};for(let[j,Z]of Object.entries(h.extensions)){let rt=Z.rustImports?.(m)??{};for(let[a,u]of Object.entries(rt))a.startsWith("__wbg_")?I[a]=u:I["__wbg_"+a]=R(u)}return I}let x={...U,...W(n,C)},A=Object.keys(x),B=t.reduce((h,m)=>{let I=A.find(j=>m.startsWith(j));if(I===void 0)throw new Error(`Cannot find import mapping for ${m}. Please file a bug.`);if(A.filter(j=>m.startsWith(j)).length!=1)throw new Error(`Multiple import mappings for ${m}. Please file a bug.`);if(h.usedKeys.has(I))throw new Error(`Multiple methods maps to ${I}. Please file a bug.`);return h.res[m]=x[I],h.usedKeys.add(I),h},{res:{},usedKeys:new Set}).res;i==="__WARP_CONTRACTS_VERSION_LEGACY"?(B.initStateLegacy=er,B.handle=Ue):(B.initState=Y,B.warpContractWrite=Nt,B.warpContractView=Dt),B.currentState=Er,B.version=rr,B.lang=Vt;let P={};P.__wbindgen_placeholder__=B;class H{__destroy_into_raw(){let m=this.ptr;return this.ptr=0,m}free(){let m=this.__destroy_into_raw();e.exports.__wbg_statewrapper_free(m)}}return B.StateWrapper=H,P.metering=s.metering,{imports:P,exports:B}};b();b();var ln=class{constructor(t,e){this.swGlobal=t;this.contractDefinition=e;this.assignReadContractState=this.assignReadContractState.bind(this),this.assignViewContractState=this.assignViewContractState.bind(this),this.assignWrite=this.assignWrite.bind(this),this.assignRefreshState=this.assignRefreshState.bind(this)}logger=ct.INST.create("ContractHandler");async dispose(){}assignWrite(t){this.swGlobal.contracts.write=async(e,r,i)=>{if(!t.evaluationOptions.internalWrites)throw new Error("Internal writes feature switched off. Change EvaluationOptions.internalWrites flag to 'true'");let o=i??t.evaluationOptions.throwOnInternalWriteError,s={from:this.contractDefinition.txId,to:e,input:r};this.logger.debug("swGlobal.write call:",s);let c=t.warp.contract(e,t.contract,{callingInteraction:this.swGlobal._activeTx,callType:"write"}),l=await c.applyInput(r,this.swGlobal._activeTx);this.logger.debug("Cache result?:",!this.swGlobal._activeTx.dry);let g=l.type!=="ok"&&o&&(!this.swGlobal._activeTx.dry||this.swGlobal._activeTx.dry&&this.swGlobal._activeTx.strict),w=g?`Internal write auto error for call [${JSON.stringify(s)}]: ${l.errorMessage}`:l.errorMessage,v=w?{...l.originalErrorMessages,[this.swGlobal._activeTx.id]:w}:l.originalErrorMessages;if(c.interactionState().update(c.txId(),{state:l.state,validity:{...l.originalValidity,[this.swGlobal._activeTx.id]:l.type=="ok"},errorMessages:v},this.swGlobal._activeTx.sortKey),g)throw new Ft(l.type==="error"&&l.error?l.error:w);return l}}assignViewContractState(t){this.swGlobal.contracts.viewContractState=async(e,r)=>(this.logger.debug("swGlobal.viewContractState call:",{from:this.contractDefinition.txId,to:e,input:r}),await t.warp.contract(e,t.contract,{callingInteraction:this.swGlobal._activeTx,callType:"view"}).viewStateForTx(r,this.swGlobal._activeTx))}assignReadContractState(t,e){this.swGlobal.contracts.readContractState=async(r,i)=>{this.logger.debug("swGlobal.readContractState call:",{from:this.contractDefinition.txId,to:r,sortKey:e.sortKey,transaction:this.swGlobal.transaction.id});let{contract:o,warp:s}=t,l=await s.contract(r,o,{callingInteraction:e,callType:"read"}).readState(e.sortKey);if(l?.cachedValue?.errorMessages){let w=Reflect.ownKeys(l?.cachedValue?.errorMessages);if(w.length){let v=w[w.length-1],E=l?.cachedValue?.errorMessages[v];if(E&&E.startsWith&&(E.startsWith("[SkipUnsafeError]")||E.startsWith("[NonWhitelistedSourceError]")))throw new Ft(E)}}return i?{state:Vr(l.cachedValue.state),validity:l.cachedValue.validity,errorMessages:l.cachedValue.errorMessages}:Vr(l.cachedValue.state)}}assignRefreshState(t){this.swGlobal.contracts.refreshState=async()=>t.contract.interactionState().get(this.swGlobal.contract.id,this.swGlobal._activeTx.sortKey)?.state}};var uo=class extends ln{constructor(e,r,i){super(e,r);this.wasmExports=i}async handle(e,r,i){try{let{interaction:o,interactionTx:s}=i;this.swGlobal._activeTx=s,this.swGlobal.caller=o.caller,this.swGlobal.gasLimit=e.evaluationOptions.gasLimit,this.swGlobal.gasUsed=0,this.assignReadContractState(e,s),this.assignViewContractState(e),this.assignWrite(e),await this.swGlobal.kv.open(),await this.swGlobal.kv.begin();let c=await this.doHandle(o);return i.interaction.interactionType==="view"?await this.swGlobal.kv.rollback():await this.swGlobal.kv.commit(),{type:"ok",result:c,state:this.doGetCurrentState(),gasUsed:this.swGlobal.gasUsed,event:null}}catch(o){await this.swGlobal.kv.rollback();let s={errorMessage:o.message,state:r.state,result:null};if(o instanceof Ft||o instanceof Hn)return{...s,error:o.error,type:"error",event:null};if(o instanceof ze)throw o;return{...s,type:"exception",event:null}}finally{await this.swGlobal.kv.close()}}initState(e){switch(this.contractDefinition.srcWasmLang){case"rust":{if("initStateLegacy"in this.wasmExports){this.wasmExports.initStateLegacy(e);return}let r=this.wasmExports.initState(e);if(r)throw new Error(r);return}default:throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`)}}async doHandleLegacy(e){let r=await this.wasmExports.handle(e.input);if(!r)return;if(Object.prototype.hasOwnProperty.call(r,"Ok"))return r.Ok;let i,o="";if(typeof r.Err=="string"||r.Err instanceof String)i=r.Err;else{if("kind"in r.Err)throw new Ft(r.Err);i=Object.keys(r.Err)[0],o=" "+r.Err[i]}throw i=="RuntimeError"?new Error(`[RE:RE]${o}`):new Ft(`[CE:${i}${o}]`)}async doHandle(e){switch(this.contractDefinition.srcWasmLang){case"rust":{if("handle"in this.wasmExports)return await this.doHandleLegacy(e);let r=e.interactionType==="write"?await this.wasmExports.warpContractWrite(e.input):await this.wasmExports.warpContractView(e.input);if(!r)return;if(r.type==="ok")return r.result;throw this.logger.error("Error from rust",r),r.type==="error"?new Ft(r.error):new Error(r.errorMessage)}default:throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`)}}async maybeCallStateConstructor(e,r){if(this.contractDefinition.manifest?.evaluationOptions?.useConstructor)throw Error("Constructor is not implemented for wasm");return e}doGetCurrentState(){switch(this.contractDefinition.srcWasmLang){case"rust":return this.wasmExports.currentState();default:throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`)}}};b();function va(n,t){let e=n.trim().split(` +`),r=e[0],i=e[e.length-1];return(/\(\s*\(\)\s*=>\s*{/g.test(r)||/\s*\(\s*function\s*\(\)\s*{/g.test(r))&&/}\s*\)\s*\(\)\s*;/g.test(i)&&(e.shift(),e.pop(),n=e.join(` +`)),n=n.replace(/export\s+async\s+function\s+handle/gmu,"async function handle").replace(/export\s+function\s+handle/gmu,"function handle"),t?` + ${n} + module.exports = handle;`:` + const window=void 0,document=void 0,eval=void 0,globalThis=void 0; + const [SmartWeave, BigNumber, logger${fn()?", Buffer, atob, btoa":""}] = arguments; + class ContractError extends Error { constructor(message) { super(message); this.name = 'ContractError' } }; + function ContractAssert(cond, message) { if (!cond) throw new ContractError(message) }; + ${n}; + return handle; + `}function x0(n,t){try{let e=va(n,!1);return new Function(e)(),!0}catch(e){return t?.error(e),!1}}var Wl=jt(mr()),Ul=_a(),Ft=class extends Error{constructor(e,r){super(e.toString());this.error=e;this.subtype=r;this.name="ContractError"}},Hn=class extends Error{constructor(e){super(e.toString());this.error=e;this.name="NonWhitelistedSourceError"}},fo=class{constructor(t){this.arweave=t}logger=ct.INST.create("HandlerExecutorFactory");async create(t,e,r,i){r.hasPlugin("contract-blacklist")&&await this.blacklistContracts(r,t),this.checkWhiteListContractSources(t,e);let o=null;e.useKVStorage&&(o=r.kvStorageFactory(t.txId));let s=new co(this.arweave,{id:t.txId,owner:t.owner},e,i,o);if(r.matchPlugins("^smartweave-extension-").forEach(l=>{r.loadPlugin(l).process(s.extensions)}),t.contractType=="wasm"){this.logger.info("Creating handler for wasm contract",t.txId);let l=Et.measure(),g,w=null,v=op(t.srcBinary);switch(t.srcWasmLang){case"rust":{let E={exports:null,modifiedExports:{wasm_bindgen__convert__closures__invoke2_mut__:null,_dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__:null}},d=await sp(v,t.srcBinary),y=WebAssembly.Module.exports(d).filter(z=>z.kind==="global"&&z.name.startsWith("__WARP_CONTRACTS_VERSION_")).map(z=>z.name).shift()||"__WARP_CONTRACTS_VERSION_LEGACY",k=WebAssembly.Module.imports(d).filter(z=>z.module==="__wbindgen_placeholder__").map(z=>z.name),{imports:N,exports:q}=Pl(s,k,E,t.metadata.dtor,y);w=q,g=await WebAssembly.instantiate(d,N),E.exports=g.exports,Object.keys(g.exports).forEach(z=>{z.startsWith("wasm_bindgen__convert__closures__invoke2_mut__")&&(E.modifiedExports.wasm_bindgen__convert__closures__invoke2_mut__=g.exports[z]),z.startsWith("_dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__")&&(E.modifiedExports._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__=g.exports[z])});break}default:throw new Error(`Support for ${t.srcWasmLang} not implemented yet.`)}return this.logger.info(`WASM ${t.srcWasmLang} handler created in ${l.elapsed()}`),new uo(s,t,w||g.exports)}else{let l=va(t.src,r.hasPlugin("vm2"));if(l.includes("unsafeClient"))switch(e.unsafeClient){case"allow":{this.logger.warn(`Reading unsafe contract ${t.txId}, evaluation is non-deterministic!`);break}case"throw":throw new Error(`[SkipUnsafeError] Using unsafeClient is not allowed by default. Use EvaluationOptions.unsafeClient flag to evaluate ${t.txId}.`);case"skip":throw new Ft(`[SkipUnsafeError] Skipping evaluation of the unsafe contract ${t.txId}.`,"unsafeClientSkip");default:throw new Error(`Unknown unsafeClient setting ${e.unsafeClient}`)}if(!e.allowBigInt&&l.includes("BigInt"))throw new Error("Using BigInt is not allowed by default. Use EvaluationOptions.allowBigInt flag.");if(r.hasPlugin("vm2"))return r.loadPlugin("vm2").process({normalizedSource:l,swGlobal:s,logger:this.logger,contractDefinition:t});if(r.hasPlugin("ivm-handler-api"))return r.loadPlugin("ivm-handler-api").process({contractSource:t.src,evaluationOptions:e,arweave:this.arweave,swGlobal:s,contractDefinition:t});{let g=new Function(l),w=fn()?g(s,Ul,ct.INST.create(s.contract.id),Wl.Buffer,atob,btoa):g(s,Ul,ct.INST.create(s.contract.id));return new ho(s,t,w)}}}checkWhiteListContractSources(t,e){if(e&&e.whitelistSources.length>0&&!e.whitelistSources.includes(t.srcTxId))throw new Hn(`[NonWhitelistedSourceError] Contract source not part of whitelisted sources list: ${t.srcTxId}.`)}async blacklistContracts(t,e){let r=t.loadPlugin("contract-blacklist"),i=!1;try{i=await r.process(e.txId)}catch(o){this.logger.error(o)}if(i==!0)throw new Ft(`[SkipUnsafeError] Skipping evaluation of the blacklisted contract ${e.txId}.`,"blacklistedSkip")}};function op(n){let t={status:200,statusText:"OK",headers:{"Content-Type":"application/wasm"}};return new Response(n,t)}async function sp(n,t){return WebAssembly.compileStreaming?await WebAssembly.compileStreaming(n):await WebAssembly.compile(t)}b();b();function Ml(n){let t="";for(let e of n)t+=("0"+e.toString(16)).slice(-2);return t}var ap="".padEnd(13,"0"),ba="".padEnd(13,"9"),Sa="".padEnd(13,"0"),cp="".padEnd(64,"0"),Fl="".padEnd(64,"z"),Qn=`${"".padStart(12,"0")},${ap},${cp}`,G0=`${"".padStart(12,"9")},${ba},${Fl}`,yr=class{constructor(t){this.arweave=t}logger=ct.INST.create("LexicographicalInteractionsSorter");async sort(t){let e=[...t],r=e.map(i=>this.addSortKey(i));return await Promise.all(r),e.sort((i,o)=>i.node.sortKey.localeCompare(o.node.sortKey))}async createSortKey(t,e,r,i=!1){let o=this.arweave.utils.b64UrlToBuffer(t),s=this.arweave.utils.b64UrlToBuffer(e),c=this.arweave.utils.concatBuffers([o,s]),l=Ml(await this.arweave.crypto.hash(c));return`${`${r}`.padStart(12,"0")},${i?ba:Sa},${l}`}extractBlockHeight(t){return t?parseInt(t.split(",")[0]):null}async addSortKey(t){let{node:e}=t,r=t.node.sortKey;r?(t.node.sortKey=r,this.logger.debug("Using sortKey from sequencer",t.node.sortKey)):t.node.sortKey=await this.createSortKey(e.block.id,e.id,e.block.height)}generateLastSortKey(t){return`${`${t}`.padStart(12,"0")},${ba},${Fl}`}};var Ea="__init",zn=(n,t)=>{let e=new Error(t);throw e.name=n,e},Dl=(i=>(i.ContractError="ContractError",i.ConstructorError="ConstructorError",i.NetworkCommunicationError="NetworkCommunicationError",i.NonWhitelistedSourceError="NonWhitelistedSourceError",i))(Dl||{}),ho=class extends ln{constructor(e,r,i){super(e,r);this.contractFunction=i}async handle(e,r,i){let{interaction:o,interactionTx:s}=i;return this.setupSwGlobal(i),this.enableInternalWrites(e,s),this.assertNotConstructorCall(o),await this.runContractFunction(e,o,r.state)}initState(e){}async maybeCallStateConstructor(e,r){if(this.contractDefinition.manifest?.evaluationOptions?.useConstructor){let i={input:{function:Ea,args:e},caller:this.contractDefinition.owner,interactionType:"write"},o={owner:{address:r.caller,key:null},sortKey:Qn},s={interaction:i,interactionTx:o};this.setupSwGlobal(s);let c=this.configureSwGlobalForConstructor(),l=await this.runContractFunction(r,i,{});if(c(),l.type!=="ok")throw r.contract.isRoot()?new Error(`ConstructorError: ${l.errorMessage}`):new Ft(`ConstructorError [${r.contract.txId()}]: ${l.errorMessage}`,"constructor");return l.state}else return e}assertNotConstructorCall(e){if(this.contractDefinition.manifest?.evaluationOptions?.useConstructor&&e.input.function===Ea)throw new Error(`You have enabled {useConstructor: true} option, so you can't call function ${Ea}`)}configureSwGlobalForConstructor(){let e=s=>({get:(c,l)=>zn("ConstructorError",`SmartWeave.${s}.${String(l)} is not accessible in constructor context`)});this.swGlobal.contracts.readContractState=()=>zn("ConstructorError","Internal writes feature is not available in constructor"),this.swGlobal.contracts.viewContractState=()=>zn("ConstructorError","Internal writes feature is not available in constructor"),this.swGlobal.contracts.refreshState=()=>zn("ConstructorError","Internal writes feature is not available in constructor"),this.swGlobal.contracts.write=()=>zn("ConstructorError","Internal writes feature is not available in constructor");let r=new qn(this.swGlobal);this.swGlobal.block=new Proxy(this.swGlobal.block,e("block"));let i=new jn(this.swGlobal);this.swGlobal.vrf=new Proxy(this.swGlobal.vrf,e("vrf"));let o=new Gn(this.swGlobal);return this.swGlobal.transaction=new Proxy(this.swGlobal.vrf,e("transaction")),()=>{this.swGlobal.block=r,this.swGlobal.vrf=i,this.swGlobal.transaction=o}}async runContractFunction(e,r,i){let o=Vr(i),{timeoutId:s,timeoutPromise:c}=$l(e.evaluationOptions.maxInteractionEvaluationTimeSeconds);try{await this.swGlobal.kv.open(),await this.swGlobal.kv.begin();let l=await Promise.race([c,this.contractFunction(o,r)]);if(l&&(l.state!==void 0||l.result!==void 0)){await this.swGlobal.kv.commit();let g=null;return l.event&&(g={contractTxId:this.swGlobal.contract.id,sortKey:this.swGlobal.transaction.sortKey,transactionId:this.swGlobal.transaction.id,caller:r.caller,input:r.input,blockTimestamp:this.swGlobal.block.timestamp,blockHeight:this.swGlobal.block.height,data:l.event}),{type:"ok",result:l.result,state:l.state||o,event:g}}throw new Error(`Unexpected result from contract: ${JSON.stringify(l)}`)}catch(l){switch(await this.swGlobal.kv.rollback(),l.name){case"ContractError":return{type:"error",errorMessage:l.message,state:i,result:null,event:null};case"ConstructorError":throw e.contract.isRoot()?Error(`ConstructorError: ${l.message}`):new Ft(`ConstructorError [${e.contract.txId()}]: ${l.message}`,"constructor");case"NetworkCommunicationError":throw l;case"NonWhitelistedSourceError":return{type:"error",errorMessage:l.message,state:i,result:null,event:null};default:return{type:"exception",errorMessage:`${l&&l.stack||l&&l.message||l}`,state:i,result:null,event:null}}}finally{s&&clearTimeout(s),await this.swGlobal.kv.close()}}setupSwGlobal({interaction:e,interactionTx:r}){this.swGlobal._activeTx=r,this.swGlobal.caller=e.caller}enableInternalWrites(e,r){this.assignReadContractState(e,r),this.assignViewContractState(e),this.assignWrite(e),this.assignRefreshState(e)}};var go=n=>new Promise(t=>setTimeout(t,n)),po=n=>{let t=Number.parseInt(n);if(Number.isNaN(t)&&!Number.isSafeInteger(t))throw Error(`Failed to cast ${n} to integer`);return t},Vr=n=>Rl(n),ov=(n,t)=>t instanceof Map?{dataType:"Map",value:Array.from(t.entries())}:t,sv=(n,t)=>typeof t=="object"&&t!==null&&t.dataType==="Map"?new Map(t.value):t,av=(n,t)=>n-t,cv=(n,t)=>+n-+t,uv=(n,t)=>t-n,lv=(n,t)=>+t-+n;function $l(n){let t=null,e=new Promise((r,i)=>{t=setTimeout(()=>{clearTimeout(t),i("timeout")},n*1e3)});return{timeoutId:t,timeoutPromise:e}}function Je(n){return n.endsWith("/")?n.slice(0,-1):n}function Be(n){return`[d:${n}]`.padEnd(n*2,"-").concat("> ")}function fv(n){let t=[];return Uint8Array.from(n).forEach(function(r){let i=r.toString(16);i.length%2&&(i="0"+i),t.push(i)}),BigInt("0x"+t.join(""))}var fn=new Function("try {return this===window;}catch(e){ return false;}"),ze=class extends Error{constructor(e){super(e.toString());this.error=e;this.name="NetworkCommunicationError"}};async function _e(n){let t;try{t=await n}catch(e){throw new ze(`Error during network communication: ${JSON.stringify(e)}`)}if(!t?.ok){let e=await t.text();throw new ze(`Wrong response code: ${t.status}. ${e}`)}try{return await t.json()}catch(e){throw new ze(`Error while parsing json response: ${JSON.stringify(e)}`)}}async function Bl(n,t){return _e(fetch(n,t))}var up=(r=>(r.ARWEAVE="arweave",r.WARP_SEQUENCER="redstone-sequencer",r.BOTH="both",r))(up||{}),mo=class{constructor(t=null,e="both"){this.confirmationStatus=t;this.source=e;Object.assign(this,t),this.source=e}_warp;logger=ct.INST.create("WarpGatewayInteractionsLoader");async load(t,e,r,i){this.logger.debug("Loading interactions: for ",{contractId:t,fromSortKey:e,toSortKey:r});let o=[],s=0,c=0,l=0,g=i?i.sourceType:this.source,w=Et.measure(),v=Je(this._warp.gwUrl());do{let E=Et.measure(),d=`${v}/gateway/v2/interactions-sort-key`,y=await _e(fetch(`${d}?${new URLSearchParams({contractId:t,...this._warp.whoAmI?{client:this._warp.whoAmI}:"",...e?{from:e}:"",...r?{to:r}:"",page:(++s).toString(),fromSdk:"true",...this.confirmationStatus&&this.confirmationStatus.confirmed?{confirmationStatus:"confirmed"}:"",...this.confirmationStatus&&this.confirmationStatus.notCorrupted?{confirmationStatus:"not_corrupted"}:"",...g=="both"?"":{source:g}})}`));this.logger.debug(`Loading interactions: page ${s} loaded in ${E.elapsed()}`),o.push(...y.interactions),c=y.paging.limit,l=y.paging.items,this.logger.debug(`Loaded interactions length: ${o.length}, from: ${e}, to: ${r}`)}while(l==c);return this.logger.debug("All loaded interactions:",{from:e,to:r,loaded:o.length,time:w.elapsed()}),o}type(){return"warp"}clearCache(){}set warp(t){this._warp=t}};var $t=class{constructor(t,e,r){this.state=t;this.validity=e;this.errorMessages=r}},yo=class{ignoreExceptions=!0;waitForConfirmation=!1;updateCacheForEachInteraction=!1;internalWrites=!1;maxCallDepth=7;maxInteractionEvaluationTimeSeconds=60;stackTrace={saveState:!1};sequencerUrl="https://d1o5nlqr4okus2.cloudfront.net/";gasLimit=Number.MAX_SAFE_INTEGER;sourceType="both";unsafeClient="throw";allowBigInt=!1;walletBalanceUrl="http://nyc-1.dev.arweave.net:1984/";mineArLocalBlocks=!0;throwOnInternalWriteError=!0;cacheEveryNInteractions=-1;useKVStorage=!1;remoteStateSyncEnabled=!1;remoteStateSyncSource="https://dre-1.warp.cc/contract";useConstructor=!1;whitelistSources=[]},wo=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e.detail}},Kl=class{constructor(t,e,r,i,o,s,c,l){this.contractTxId=t;this.sortKey=e;this.transactionId=r;this.caller=i;this.input=o;this.blockTimestamp=s;this.blockHeight=c;this.data=l}};b();b();var bo=["application/javascript","application/wasm"],Vl=class{dtor},vo=class{src;srcBinary;srcWasmLang;constructor(t){this.src=t.src,this.srcBinary=t.srcBinary,this.srcWasmLang=t.srcWasmLang}},_o=class{txId;srcTxId;initState;minFee;owner;contractType;metadata;manifest;contractTx;srcTx;testnet;constructor(t){this.txId=t.txId,this.srcTxId=t.srcTxId,this.initState=t.initState,this.manifest=t.manifest,this.minFee=t.minFee,this.owner=t.owner,this.contractType=t.contractType,this.metadata=t.metadata,this.contractTx=t.contractTx,this.srcTx=t.srcTx,this.testnet=t.testnet}};b();var Ct={APP_NAME:"App-Name",APP_VERSION:"App-Version",CONTRACT_TX_ID:"Contract",INPUT:"Input",CONTENT_TYPE:"Content-Type",CONTRACT_SRC_TX_ID:"Contract-Src",SDK:"SDK",MIN_FEE:"Min-Fee"},at={SEQUENCER:"Sequencer",SEQUENCER_OWNER:"Sequencer-Owner",SEQUENCER_MILLIS:"Sequencer-Mills",SEQUENCER_SORT_KEY:"Sequencer-Sort-Key",SEQUENCER_PREV_SORT_KEY:"Sequencer-Prev-Sort-Key",SEQUENCER_LAST_SORT_KEY:"Sequencer-Last-Sort-Key",SEQUENCER_TX_ID:"Sequencer-Tx-Id",SEQUENCER_BLOCK_HEIGHT:"Sequencer-Block-Height",SEQUENCER_BLOCK_ID:"Sequencer-Block-Id",SEQUENCER_BLOCK_TIMESTAMP:"Sequencer-Block-Timestamp",INIT_STATE:"Init-State",INIT_STATE_TX:"Init-State-TX",INTERACT_WRITE:"Interact-Write",WASM_LANG:"Wasm-Lang",WASM_LANG_VERSION:"Wasm-Lang-Version",WASM_META:"Wasm-Meta",REQUEST_VRF:"Request-Vrf",SIGNATURE_TYPE:"Signature-Type",UPLOADER_TX_ID:"Uploader-Tx-Id",WARP_TESTNET:"Warp-Testnet",MANIFEST:"Contract-Manifest",NONCE:"Nonce"};b();var xf=jt(Oo()),tc=jt(mr());b();var Xt=jt(be()),Ro=class{get(t,e){if(!Object.getOwnPropertyNames(this).includes(t))throw new Error(`Field "${t}" is not a property of the Arweave Transaction class.`);return this[t]instanceof Uint8Array?e&&e.decode&&e.string?Xt.bufferToString(this[t]):e&&e.decode&&!e.string?this[t]:Xt.bufferTob64Url(this[t]):e&&e.decode==!0?e&&e.string?Xt.b64UrlToString(this[t]):Xt.b64UrlToBuffer(this[t]):this[t]}},mn=class extends Ro{format=2;id="";last_tx="";owner="";tags=[];target="";quantity="0";data_size="0";data=new Uint8Array;data_root="";reward="0";signature="";chunks;constructor(t={}){super(),Object.assign(this,t),typeof this.data=="string"&&(this.data=Xt.b64UrlToBuffer(this.data)),t.tags&&(this.tags=t.tags.map(e=>new Qt(e.name,e.value)))}addTag(t,e){this.tags.push(new Qt(Xt.stringToB64Url(t),Xt.stringToB64Url(e)))}toJSON(){return{format:this.format,id:this.id,last_tx:this.last_tx,owner:this.owner,tags:this.tags,target:this.target,quantity:this.quantity,data:Xt.bufferTob64Url(this.data),data_size:this.data_size,data_root:this.data_root,data_tree:this.data_tree,reward:this.reward,signature:this.signature}}setOwner(t){this.owner=t}setSignature({id:t,owner:e,reward:r,tags:i,signature:o}){this.id=t,this.owner=e,r&&(this.reward=r),i&&(this.tags=i),this.signature=o}async prepareChunks(t){throw new Error("Should not be called, use arweave-js version.")}getChunk(t,e){if(!this.chunks)throw new Error("Chunks have not been prepared");let r=this.chunks.proofs[t],i=this.chunks.chunks[t];return{data_root:this.data_root,data_size:this.data_size,data_path:Xt.bufferTob64Url(r.proof),offset:r.offset.toString(),chunk:Xt.bufferTob64Url(e.slice(i.minByteRange,i.maxByteRange))}}async getSignatureData(){throw new Error("Should not be called, use arweave-js version.")}},Qt=class extends Ro{name;value;constructor(t,e,r=!1){super(),this.name=t,this.value=e}};var ne=class{constructor(t){this.warp=t;let{arweave:e}=t;this.baseUrl=`${e.api.config.protocol}://${e.api.config.host}:${e.api.config.port}`,this.logger.debug("baseurl",this.baseUrl)}logger=ct.INST.create("ArweaveWrapper");baseUrl;async warpGwInfo(){return await this.doFetchInfo(`${Je(this.warp.gwUrl())}/gateway/arweave/info`)}async warpGwBlock(){return this.logger.debug("Calling warp gw block info"),await this.doFetchInfo(`${Je(this.warp.gwUrl())}/gateway/arweave/block`)}async info(){return await this.doFetchInfo(`${this.baseUrl}/info`)}async gql(t,e){try{let r=JSON.stringify({query:t,variables:e});return{data:await _e(fetch(`${this.baseUrl}/graphql`,{method:"POST",body:r,headers:{"Accept-Encoding":"gzip, deflate, br","Content-Type":"application/json",Accept:"application/json"}})),status:200}}catch(r){throw this.logger.error("Error while loading gql",r),r}}async tx(t){let e=await fetch(`${this.baseUrl}/tx/${t}`).then(r=>r.ok?r.json():Promise.reject(r)).catch(r=>{throw r.body?.message&&this.logger.error(r.body.message),new ze(`Unable to retrieve tx ${t}. ${r.status}. ${r.body?.message}`)});return new mn({...e})}async txData(t){let e=await fetch(`${this.baseUrl}/${t}`);if(e.ok){let r=await e.arrayBuffer();return tc.Buffer.from(r)}else{this.logger.warn(`Unable to load data from arweave.net/${t} endpoint, falling back to arweave.js`);let r=await this.warp.arweave.transactions.getData(t,{decode:!0});return tc.Buffer.from(r)}}async txDataString(t){let e=await this.txData(t);return xf.default.utils.bufferToString(e)}async doFetchInfo(t){return await _e(fetch(t))}};b();var zt=class{logger=ct.INST.create("TagsParser");getInputTag(t,e){if(zt.hasMultipleInteractions(t)){this.logger.debug("Interaction transaction is using multiple input tx tag format.");let r=t.tags.findIndex(o=>o.name===Ct.CONTRACT_TX_ID&&o.value===e);if(t.tags.length-1===r){this.logger.warn("Wrong tags format: 'Contract' is the last tag");return}let i=t.tags[r+1];if(i.name!==Ct.INPUT){this.logger.warn(`No 'Input' tag found after 'Contract' tag. Instead ${i.name} was found`);return}return i}else return t.tags.find(r=>r.name===Ct.INPUT)}isInteractWrite(t,e){return t.tags.some(r=>r.name===at.INTERACT_WRITE&&r.value===e)}getInteractWritesContracts(t){return t.tags.filter(e=>e.name===at.INTERACT_WRITE).map(e=>e.value)}getContractTag(t){return t.tags.find(e=>e.name===Ct.CONTRACT_TX_ID)?.value}getContractsWithInputs(t){let e=new Map;return t.tags.filter(i=>i.name===Ct.CONTRACT_TX_ID).forEach(i=>{e.set(i.value,this.getInputTag(t,i.value))}),e}isEvmSigned(t){return t.tags.some(e=>e.name===at.SIGNATURE_TYPE&&e.value==="ethereum")}static hasMultipleInteractions(t){return t.tags.filter(e=>e.name===Ct.CONTRACT_TX_ID).length>1}decodeTags(t){let e=t.get("tags"),r=[];for(let i of e)try{let o=i.get("name",{decode:!0,string:!0}),s=i.get("value",{decode:!0,string:!0});r.push({name:o,value:s})}catch{}return r}getTag(t,e){let r=t.get("tags");for(let i of r)try{if(i.get("name",{decode:!0,string:!0})===e)return i.get("value",{decode:!0,string:!0})}catch{}return!1}hasVrfTag(t){return t.tags.some(e=>e.name==at.REQUEST_VRF&&e.value==="true")}};b();b();function Of(n){return n.arrayBuffer?n.arrayBuffer():new Promise((t,e)=>{let r=new FileReader;r.addEventListener("loadend",()=>{t(r.result)}),r.addEventListener("error",e),r.readAsArrayBuffer(n)})}async function Vp(n){let t=await Of(n);return new Uint8Array(t)}function Rf(n){return typeof Blob<"u"&&n instanceof Blob}function fi(n){return typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}var Gp=typeof $.default<"u"&&$.default.versions&&typeof $.default.versions.node<"u"&&typeof $.default.versions.electron>"u";function qp(n){return n.byteOffset===0&&n.byteLength===n.buffer.byteLength}var Po=class{constructor(t){this.typedArray=t instanceof ArrayBuffer||fi(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}async getLength(){return this.typedArray.byteLength}async read(t,e){return new Uint8Array(this.typedArray.buffer,this.typedArray.byteOffset+t,e)}},No=class{constructor(t){this.blob=t}async getLength(){return this.blob.size}async read(t,e){let r=this.blob.slice(t,t+e),i=await Of(r);return new Uint8Array(i)}async sliceAsBlob(t,e,r=""){return this.blob.slice(t,t+e,r)}};function jp(n,t){var e=Uint8Array;if(n[0]==3&&n[1]==0)return t||new e(0);var r=Qp,i=Bf,o=Hp,s=Pf,c=t==null;c&&(t=new e(n.length>>>2<<3));for(var l=0,g=0,w=0,v=0,E=0,d=0,y=0,k=0,N=0,q,Q;l==0;){if(l=r(n,N,1),g=r(n,N+1,2),N+=3,g==0){N&7&&(N+=8-(N&7));var z=(N>>>3)+4,X=n[z-4]|n[z-3]<<8;c&&(t=ec(t,k+X)),t.set(new e(n.buffer,n.byteOffset+z,X),k),N=z+X<<3,k+=X;continue}if(c&&(t=ec(t,k+(1<<17))),g==1&&(q=ot.flmap,Q=ot.fdmap,d=(1<<9)-1,y=(1<<5)-1),g==2){w=i(n,N,5)+257,v=i(n,N+5,5)+1,E=i(n,N+10,4)+4,N+=14;for(var D=0;D<38;D+=2)ot.itree[D]=0,ot.itree[D+1]=0;for(var G=1,D=0;DG&&(G=it)}N+=3*E,ci(ot.itree,G),ui(ot.itree,G,ot.imap),q=ot.lmap,Q=ot.dmap,N=o(ot.imap,(1<>>4;if(!(tt>>>8))t[k++]=tt;else{if(tt==256)break;var lt=k+tt-254;if(tt>264){var st=ot.ldef[tt-257];lt=k+(st>>>3)+i(n,N,st&7),N+=st&7}var wt=Q[s(n,N)&y];N+=wt&15;var Pt=wt>>>4,Tt=ot.ddef[Pt],ht=(Tt>>>4)+r(n,N,Tt&15);for(N+=Tt&15,c&&(t=ec(t,k+(1<<17)));k>>4;if(w<=15)o[l]=w,l++;else{var v=0,E=0;w==16?(E=3+s(r,i,2),i+=2,v=o[l-1]):w==17?(E=3+s(r,i,3),i+=3):w==18&&(E=11+s(r,i,7),i+=7);for(var d=l+E;l>>1;oi&&(i=c),o++}for(;o>1,c=n[o+1],l=s<<4|c,g=t-c,w=n[o]<>>15-t;e[E]=l,w++}}function If(n,t){for(var e=ot.rev15,r=15-t,i=0;i>>r}}function Bf(n,t,e){return(n[t>>>3]|n[(t>>>3)+1]<<8)>>>(t&7)&(1<>>3]|n[(t>>>3)+1]<<8|n[(t>>>3)+2]<<16)>>>(t&7)&(1<>>3]|n[(t>>>3)+1]<<8|n[(t>>>3)+2]<<16)>>>(t&7)}var ot=function(){var n=Uint16Array,t=Uint32Array;return{next_code:new n(16),bl_count:new n(16),ordr:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],of0:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],exb:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],ldef:new n(32),df0:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],dxb:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],ddef:new t(32),flmap:new n(512),fltree:[],fdmap:new n(32),fdtree:[],lmap:new n(32768),ltree:[],ttree:[],dmap:new n(32768),dtree:[],imap:new n(512),itree:[],rev15:new n(1<<15),lhst:new t(286),dhst:new t(30),ihst:new t(19),lits:new t(15e3),strt:new n(1<<16),prev:new n(1<<15)}}();(function(){for(var n=32768,t=0;t>>1|(e&1431655765)<<1,e=(e&3435973836)>>>2|(e&858993459)<<2,e=(e&4042322160)>>>4|(e&252645135)<<4,e=(e&4278255360)>>>8|(e&16711935)<<8,ot.rev15[t]=(e>>>16|e<<16)>>>17}function r(i,o,s){for(;o--!=0;)i.push(0,s)}for(var t=0;t<32;t++)ot.ldef[t]=ot.of0[t]<<3|ot.exb[t],ot.ddef[t]=ot.df0[t]<<4|ot.dxb[t];r(ot.fltree,144,8),r(ot.fltree,255-143,9),r(ot.fltree,279-255,7),r(ot.fltree,287-279,8),ci(ot.fltree,9),ui(ot.fltree,9,ot.flmap),If(ot.fltree,9),r(ot.fdtree,32,5),ci(ot.fdtree,5),ui(ot.fdtree,5,ot.fdmap),If(ot.fdtree,5),r(ot.itree,19,0),r(ot.ltree,286,0),r(ot.dtree,30,0),r(ot.ttree,320,0)})();var Af={table:function(){for(var n=new Uint32Array(256),t=0;t<256;t++){for(var e=t,r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;n[t]=e}return n}(),update:function(n,t,e,r){for(var i=0;i>>8;return n},crc:function(n,t,e){return Af.update(4294967295,n,t,e)^4294967295}};function zp(n,t){return jp(n,t)}var hi={numWorkers:1,workerURL:"",useWorkers:!1},Jp=0,kf=0,ic=!0,Yp=[],Bo=[],yn=[],oc=new Map;function Xp(n){Nf(n.target);let{id:t,error:e,data:r}=n.data,i=oc.get(t);oc.delete(t),e?i.reject(e):i.resolve(r)}function rc(n){return new Promise((t,e)=>{let r=new Worker(n);r.onmessage=i=>{i.data==="start"?(r.onerror=void 0,r.onmessage=void 0,t(r)):e(new Error(`unexpected message: ${i.data}`))},r.onerror=e})}function Zp(n,t){return n.require?n.require(t):{}}var Lf=function(){if(Gp){let{Worker:n}=Zp(module,"worker_threads");return{async createWorker(t){return new n(t)},addEventListener(t,e){t.on("message",r=>{e({target:t,data:r})})},async terminate(t){await t.terminate()}}}else return{async createWorker(n){try{return await rc(n)}catch{console.warn("could not load worker:",n)}let t;try{let e=await fetch(n,{mode:"cors"});if(!e.ok)throw new Error(`could not load: ${n}`);t=await e.text(),n=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));let r=await rc(n);return hi.workerURL=n,r}catch{console.warn("could not load worker via fetch:",n)}if(t!==void 0)try{n=`data:application/javascript;base64,${btoa(t)}`;let e=await rc(n);return hi.workerURL=n,e}catch{console.warn("could not load worker via dataURI")}throw console.warn("workers will not be used"),new Error("can not start workers")},addEventListener(n,t){n.addEventListener("message",t)},async terminate(n){n.terminate()}}}();function Nf(n){Bo.push(n),Uf()}async function tm(){if(Bo.length===0&&kf{yn.push({src:n,uncompressedSize:t,type:e,resolve:r,reject:i,id:Jp++}),Uf()})}function rm(n,t){let e=n&31,r=(n>>5&15)-1,i=(n>>9&127)+1980,o=0,s=(t&31)*2,c=t>>5&63,l=t>>11&31;return new Date(i,r,e,l,c,s,o)}var sc=class{constructor(t,e){this._reader=t,this._rawEntry=e,this.name=e.name,this.nameBytes=e.nameBytes,this.size=e.uncompressedSize,this.compressedSize=e.compressedSize,this.comment=e.comment,this.commentBytes=e.commentBytes,this.compressionMethod=e.compressionMethod,this.lastModDate=rm(e.lastModFileDate,e.lastModFileTime),this.isDirectory=e.uncompressedSize===0&&e.name.endsWith("/"),this.encrypted=!!(e.generalPurposeBitFlag&1),this.externalFileAttributes=e.externalFileAttributes,this.versionMadeBy=e.versionMadeBy}async blob(t="application/octet-stream"){return await gm(this._reader,this._rawEntry,t)}async arrayBuffer(){return await hm(this._reader,this._rawEntry)}async text(){let t=await this.arrayBuffer();return li(new Uint8Array(t))}async json(){let t=await this.text();return JSON.parse(t)}},nc=22,nm=65535,im=101010256,om=101075792;async function wn(n,t,e){return await n.read(t,e)}async function ac(n,t,e,r){return n.sliceAsBlob?await n.sliceAsBlob(t,e,r):await n.read(t,e)}var sm={unsigned(){return 0}};function qt(n,t){return n[t]+n[t+1]*256}function Zt(n,t){return n[t]+n[t+1]*256+n[t+2]*65536+n[t+3]*16777216}function Gr(n,t){return Zt(n,t)+Zt(n,t+4)*4294967296}var am=new TextDecoder;function li(n,t){return fi(n.buffer)&&(n=new Uint8Array(n)),am.decode(n)}async function cm(n,t){let e=Math.min(nc+nm,t),r=t-e,i=await wn(n,r,e);for(let o=e-nc;o>=0;--o){if(Zt(i,o)!==im)continue;let s=new Uint8Array(i.buffer,i.byteOffset+o,i.byteLength-o),c=qt(s,4);if(c!==0)throw new Error(`multi-volume zip files are not supported. This is volume: ${c}`);let l=qt(s,10),g=Zt(s,12),w=Zt(s,16),v=qt(s,20),E=s.length-nc;if(v!==E)throw new Error(`invalid comment length. expected: ${E}, actual: ${v}`);let d=new Uint8Array(s.buffer,s.byteOffset+22,v),y=li(d);return l===65535||w===4294967295?await lm(n,r+o,y,d):await Df(n,w,g,l,y,d)}throw new Error("could not find end of central directory. maybe not zip file")}var um=117853008;async function lm(n,t,e,r){let i=t-20,o=await wn(n,i,20);if(Zt(o,0)!==um)throw new Error("invalid zip64 end of central directory locator signature");let s=Gr(o,8),c=await wn(n,s,56);if(Zt(c,0)!==om)throw new Error("invalid zip64 end of central directory record signature");let l=Gr(c,32),g=Gr(c,40),w=Gr(c,48);return Df(n,w,g,l,e,r)}var fm=33639248;async function Df(n,t,e,r,i,o){let s=0,c=await wn(n,t,e),l=[];for(let w=0;wN.length)throw new Error("extra field length exceeds extra field buffer size");d.extraFields.push({id:z,data:N.slice(D,G)}),q=G}if(d.commentBytes=y.slice(k,k+d.fileCommentLength),d.comment=li(d.commentBytes),s+=y.length,d.uncompressedSize===4294967295||d.compressedSize===4294967295||d.relativeOffsetOfLocalHeader===4294967295){let z=d.extraFields.find(G=>G.id===1);if(!z)throw new Error("expected zip64 extended information extra field");let X=z.data,D=0;if(d.uncompressedSize===4294967295){if(D+8>X.length)throw new Error("zip64 extended information extra field does not include uncompressed size");d.uncompressedSize=Gr(X,D),D+=8}if(d.compressedSize===4294967295){if(D+8>X.length)throw new Error("zip64 extended information extra field does not include compressed size");d.compressedSize=Gr(X,D),D+=8}if(d.relativeOffsetOfLocalHeader===4294967295){if(D+8>X.length)throw new Error("zip64 extended information extra field does not include relative header offset");d.relativeOffsetOfLocalHeader=Gr(X,D),D+=8}}let Q=d.extraFields.find(z=>z.id===28789&&z.data.length>=6&&z.data[0]===1&&Zt(z.data,1),sm.unsigned(d.nameBytes));if(Q&&(d.fileName=li(Q.data.slice(5))),d.compressionMethod===0){let z=d.uncompressedSize;if(d.generalPurposeBitFlag&1&&(z+=12),d.compressedSize!==z)throw new Error(`compressed size mismatch for stored file: ${d.compressedSize} != ${z}`)}l.push(d)}return{zip:{comment:i,commentBytes:o},entries:l.map(w=>new sc(n,w))}}async function Mf(n,t){if(t.generalPurposeBitFlag&1)throw new Error("encrypted entries not supported");let e=await wn(n,t.relativeOffsetOfLocalHeader,30),r=await n.getLength(),i=Zt(e,0);if(i!==67324752)throw new Error(`invalid local file header signature: 0x${i.toString(16)}`);let o=qt(e,26),s=qt(e,28),c=t.relativeOffsetOfLocalHeader+e.length+o+s,l;if(t.compressionMethod===0)l=!1;else if(t.compressionMethod===8)l=!0;else throw new Error(`unsupported compression method: ${t.compressionMethod}`);let g=c,w=g+t.compressedSize;if(t.compressedSize!==0&&w>r)throw new Error(`file data overflows file bounds: ${g} + ${t.compressedSize} > ${r}`);return{decompress:l,fileDataStart:g}}async function hm(n,t){let{decompress:e,fileDataStart:r}=await Mf(n,t);if(!e){let s=await wn(n,r,t.compressedSize);return qp(s)?s.buffer:s.slice().buffer}let i=await ac(n,r,t.compressedSize);return await Wf(i,t.uncompressedSize)}async function gm(n,t,e){let{decompress:r,fileDataStart:i}=await Mf(n,t);if(!r){let c=await ac(n,i,t.compressedSize,e);return Rf(c)?c:new Blob([fi(c.buffer)?new Uint8Array(c):c],{type:e})}let o=await ac(n,i,t.compressedSize);return await Wf(o,t.uncompressedSize,e)}async function dm(n){let t;if(typeof Blob<"u"&&n instanceof Blob)t=new No(n);else if(n instanceof ArrayBuffer||n&&n.buffer&&n.buffer instanceof ArrayBuffer)t=new Po(n);else if(fi(n)||fi(n.buffer))t=new Po(n);else if(typeof n=="string"){let r=await fetch(n);if(!r.ok)throw new Error(`failed http request ${n}, status: ${r.status}: ${r.statusText}`);let i=await r.blob();t=new No(i)}else if(typeof n.getLength=="function"&&typeof n.read=="function")t=n;else throw new Error("unsupported source type");let e=await t.getLength();if(e>Number.MAX_SAFE_INTEGER)throw new Error(`file too large. size: ${e}. Only file sizes up 4503599627370496 bytes are supported`);return await cm(t,e)}async function Ff(n){let{zip:t,entries:e}=await dm(n);return{zip:t,entries:Object.fromEntries(e.map(r=>[r.name,r]))}}var $f=jt(mr());var _r=class{constructor(t){this.src=t;this.splitted=this.splitBuffer(t),this.logger.debug(`Buffer splitted into ${this.splitted.length} parts`)}logger=ct.INST.create("WasmSrc");splitted;wasmBinary(){return this.splitted[0]}async sourceCode(){let{entries:t}=await Ff(this.splitted[1]),e=new Map;for(let[r,i]of Object.entries(t)){if(i.isDirectory)continue;let o=await i.text();e.set(r,o)}return e}additionalCode(){return this.splitted.length==2?null:this.splitted[2].toString()}splitBuffer(t){let e="",r=parseInt(t.toString("utf8",0,1));this.logger.debug(`Number of elements: ${r}`);let i=t.length,o=0,s=0;for(let g=2;gparseInt(g));this.logger.debug("Lengths",c);let l=[];for(let g of c){let w=$f.Buffer.alloc(g),v=s+g;t.copy(w,0,s,v),s=v,l.push(w)}return l}};var vn=class{constructor(t,e){this.arweave=t;this.env=e;this.tagsParser=new zt}logger=ct.INST.create("ContractDefinitionLoader");arweaveWrapper;tagsParser;async load(t,e){let r=Et.measure(),i=await this.doLoad(t,e);return this.logger.info(`Contract definition loaded in: ${r.elapsed()}`),i}async doLoad(t,e){let r=Et.measure(),i=await this.arweaveWrapper.tx(t),o=await this.arweave.wallets.ownerToAddress(i.owner);this.logger.debug("Contract tx and owner",r.elapsed()),r.reset();let s=e||this.tagsParser.getTag(i,Ct.CONTRACT_SRC_TX_ID),c=this.tagsParser.getTag(i,at.WARP_TESTNET)||null;if(c&&this.env!=="testnet")throw new Error('Trying to use testnet contract in a non-testnet env. Use the "forTestnet" factory method.');if(!c&&this.env==="testnet")throw new Error("Trying to use non-testnet contract in a testnet env.");let l=this.tagsParser.getTag(i,Ct.MIN_FEE),g=null,w=this.tagsParser.getTag(i,at.MANIFEST);w&&(g=JSON.parse(w)),this.logger.debug("Tags decoding",r.elapsed()),r.reset();let v=await this.evalInitialState(i);this.logger.debug("init state",v);let E=JSON.parse(v);this.logger.debug("Parsing src and init state",r.elapsed());let{src:d,srcBinary:y,srcWasmLang:k,contractType:N,metadata:q,srcTx:Q}=await this.loadContractSource(s);return{txId:t,srcTxId:s,src:d,srcBinary:y,srcWasmLang:k,initState:E,minFee:l,owner:o,contractType:N,metadata:q,manifest:g,contractTx:i.toJSON(),srcTx:Q,testnet:c}}async loadContractSource(t){let e=Et.measure(),r=await this.arweaveWrapper.tx(t),i=this.tagsParser.getTag(r,Ct.CONTENT_TYPE);if(!bo.includes(i))throw new Error(`Contract source content type ${i} not supported`);let o=i=="application/javascript"?"js":"wasm",s=o=="js"?await this.arweaveWrapper.txDataString(t):await this.arweaveWrapper.txData(t),c,l,g;if(o=="wasm"){if(l=new _r(s),c=this.tagsParser.getTag(r,at.WASM_LANG),!c)throw new Error(`Wasm lang not set for wasm contract src ${t}`);g=JSON.parse(this.tagsParser.getTag(r,at.WASM_META))}return this.logger.debug("Contract src tx load",e.elapsed()),e.reset(),{src:o=="js"?s:null,srcBinary:o=="wasm"?l.wasmBinary():null,srcWasmLang:c,contractType:o,metadata:g,srcTx:r.toJSON()}}async evalInitialState(t){if(this.tagsParser.getTag(t,at.INIT_STATE))return this.tagsParser.getTag(t,at.INIT_STATE);if(this.tagsParser.getTag(t,at.INIT_STATE_TX)){let e=this.tagsParser.getTag(t,at.INIT_STATE_TX);return this.arweaveWrapper.txDataString(e)}else return this.arweaveWrapper.txDataString(t.id)}type(){return"arweave"}setCache(t){throw new Error("No cache implemented for this loader")}setSrcCache(t){throw new Error("No cache implemented for this loader")}getCache(){throw new Error("No cache implemented for this loader")}getSrcCache(){throw new Error("No cache implemented for this loader")}set warp(t){this.arweaveWrapper=new ne(t)}};b();var Uo=jt(mr());var Wo=class{constructor(t,e,r,i){this.definitionCache=e;this.srcCache=r;this.env=i;this.contractDefinitionLoader=new vn(t,i),this.tagsParser=new zt}rLogger=ct.INST.create("WarpGatewayContractDefinitionLoader");contractDefinitionLoader;arweaveWrapper;tagsParser;_warp;async load(t,e){let r=await this.getFromCache(t,e);if(r)return this.rLogger.debug("WarpGatewayContractDefinitionLoader: Hit from cache!"),r.contractType=="wasm"&&r.srcBinary.data&&(r.srcBinary=Uo.Buffer.from(r.srcBinary.data)),this.verifyEnv(r),r;let i=Et.measure(),o=await this.doLoad(t,e);return this.rLogger.info(`Contract definition loaded in: ${i.elapsed()}`),this.verifyEnv(o),await this.putToCache(t,o,e),o}async doLoad(t,e){try{let r=Je(this._warp.gwUrl()),i=await _e(fetch(`${r}/gateway/contract?txId=${t}${e?`&srcTxId=${e}`:""}`));if(i.srcBinary!=null&&!(i.srcBinary instanceof Uo.Buffer)&&(i.srcBinary=Uo.Buffer.from(i.srcBinary.data)),i.srcBinary){let o=new _r(i.srcBinary);i.srcBinary=o.wasmBinary();let s;i.srcTx?s=new mn({...i.srcTx}):s=await this.arweaveWrapper.tx(i.srcTxId);let c=JSON.parse(this.tagsParser.getTag(s,at.WASM_META));i.metadata=c}return i.contractType=i.src?"js":"wasm",i}catch(r){return this.rLogger.warn("Falling back to default contracts loader",r),await this.contractDefinitionLoader.doLoad(t,e)}}async loadContractSource(t){return await this.contractDefinitionLoader.loadContractSource(t)}type(){return"warp"}setCache(t){this.definitionCache=t}setSrcCache(t){this.srcCache=t}getCache(){return this.definitionCache}getSrcCache(){return this.srcCache}verifyEnv(t){if(t.testnet&&this.env!=="testnet")throw new Error('Trying to use testnet contract in a non-testnet env. Use the "forTestnet" factory method.');if(!t.testnet&&this.env==="testnet")throw new Error("Trying to use non-testnet contract in a testnet env.")}async getFromCache(t,e){let r=await this.definitionCache.get(new Jt(t,"cd"));if(!r)return null;let i=await this.srcCache.get(new Jt(e||r.cachedValue.srcTxId,"src"));return i?{...r.cachedValue,...i.cachedValue}:null}async putToCache(t,e,r){let i=new vo(e),o=new _o(e);await this.definitionCache.put({key:t,sortKey:"cd"},o),await this.srcCache.put({key:r||o.srcTxId,sortKey:"src"},i)}set warp(t){this._warp=t,this.arweaveWrapper=new ne(t),this.contractDefinitionLoader.warp=t}};b();b();var Kf=`query Transactions($tags: [TagFilter!]!, $blockFilter: BlockFilter!, $first: Int!, $after: String) { + transactions(tags: $tags, block: $blockFilter, first: $first, sort: HEIGHT_ASC, after: $after) { + pageInfo { + hasNextPage + } + edges { + node { + id + owner { address } + recipient + tags { + name + value + } + block { + height + id + timestamp + } + fee { winston } + quantity { winston } + parent { id } + bundledIn { id } + } + cursor + } + } + }`,pm=`query Transaction($id: ID!) { + transaction(id: $id) { + id + owner { address, key } + recipient + tags { + name + value + } + block { + height + id + timestamp + } + fee { winston, ar } + quantity { winston, ar } + bundledIn { id } + parent{ id } + signature + } +}`,mm=`query Transactions($tags: [TagFilter!]!) { + transactions(tags: $tags) { + edges { + node { + id + owner { address, key } + recipient + tags { + name + value + } + block { + height + id + timestamp + } + fee { winston, ar } + quantity { winston, ar } + parent { id } + bundledIn { id } + signature + } + } + } +}`,Vf=30*1e3,ym=100,Pe=class{constructor(t){this.warp=t;this.arweaveWrapper=new ne(t)}arweaveWrapper;logger=ct.INST.create(Pe.name);async transaction(t){return(await this.fetch(pm,{id:t})).transaction}async transactionUsingUploaderTag(t){let e={name:at.UPLOADER_TX_ID,values:[t]},r=(await this.fetch(mm,{tags:[e]})).transactions;if(r.edges.length<1)throw new Error(`No interaction with tag ${at.UPLOADER_TX_ID}:${t}`);return r.edges[0].node}async transactions(t){let e=(await this.fetch(Kf,t)).transactions,r=[...e.edges];for(;e.pageInfo.hasNextPage;){let i=e.edges[ym-1].cursor,o={...t,after:i};e=(await this.fetch(Kf,o)).transactions,r.push(...e.edges)}return r}async fetch(t,e){let r=Et.measure(),i=await this.arweaveWrapper.gql(t,e);for(this.logger.debug("GQL page load:",r.elapsed());i.status===403;)this.logger.warn(`GQL rate limiting, waiting ${Vf}ms before next try.`),await go(Vf),i=await this.arweaveWrapper.gql(t,e);if(i.status!==200)throw new Error(`Unable to retrieve transactions. Arweave gateway responded with status ${i.status}.`);if(i.data.errors)throw this.logger.error(i.data.errors),new Error("Error while fetching arweave transactions");return i.data.data}};var Gf=100;function qf(n){return!n.node.parent?.id&&!n.node.bundledIn?.id}var Do=class{constructor(t,e){this.arweave=t;this.environment=e;this.sorter=new yr(t)}logger=ct.INST.create("ArweaveGatewayInteractionsLoader");sorter;arweaveTransactionQuery;_warp;tagsParser=new zt;async load(t,e,r,i){this.logger.debug("Loading interactions for",{contractId:t,fromSortKey:e,toSortKey:r});let o=this.sorter.extractBlockHeight(e),s=this.sorter.extractBlockHeight(r),c={tags:[{name:Ct.APP_NAME,values:["SmartWeaveAction"]},{name:Ct.CONTRACT_TX_ID,values:[t]}],blockFilter:{min:o,max:s},first:Gf},l=Et.measure(),g=(await this.arweaveTransactionQuery.transactions(c)).filter(qf);if(l.stop(),i.internalWrites){let d={tags:[{name:at.INTERACT_WRITE,values:[t]}],blockFilter:{min:o,max:s},first:Gf},y=(await this.arweaveTransactionQuery.transactions(d)).filter(qf);this.logger.debug("Inner writes interactions length:",y.length),g=g.concat(y)}g=g.filter(d=>d.node.block&&d.node.block.id&&d.node.block.height);let w=await this.sorter.sort(g);e&&r?w=w.filter(d=>d.node.sortKey.localeCompare(e)>0&&d.node.sortKey.localeCompare(r)<=0):e&&!r?w=w.filter(d=>d.node.sortKey.localeCompare(e)>0):!e&&r&&(w=w.filter(d=>d.node.sortKey.localeCompare(r)<=0)),this.logger.debug("All loaded interactions:",{from:e,to:r,loaded:w.length,time:l.elapsed()});let v=this.environment==="local"||this.environment==="testnet",E=this._warp.maybeLoadPlugin("vrf");return w.map(d=>{let y=d.node;return v&&this.tagsParser.hasVrfTag(y)&&(E?y.vrf=E.process().generateMockVrf(y.sortKey):this.logger.warn('Cannot generate mock vrf for interaction - no "warp-contracts-plugin-vrf" attached!')),y})}type(){return"arweave"}clearCache(){}set warp(t){this.arweaveTransactionQuery=new Pe(t),this._warp=t}};b();var gi=class{constructor(t){this.delegate=t}logger=ct.INST.create("CacheableInteractionsLoader");interactionsCache=new Map;async load(t,e,r,i){if(this.logger.debug("Loading interactions for",{contractTxId:t,fromSortKey:e,toSortKey:r}),this.interactionsCache.has(t)){let o=this.interactionsCache.get(t);if(o?.length){let s=o[o.length-1].sortKey;if(s.localeCompare(r)<0){let c=await this.delegate.load(t,s,r,i),l=o.concat(c);return this.interactionsCache.set(t,l),l}}return o}else{let o=await this.delegate.load(t,e,r,i);return o.length&&this.interactionsCache.set(t,o),o}}type(){return this.delegate.type()}clearCache(){this.interactionsCache.clear()}set warp(t){this.delegate.warp=t}};b();var Mo=class{constructor(t,e=[]){this.arweave=t;this.executionContextModifiers=e}logger=ct.INST.create("DefaultStateEvaluator");tagsParser=new zt;async eval(t){return this.doReadState(t.sortedInteractions,new $t(t.contractDefinition.initState,{},{}),t)}async doReadState(t,e,r){let{ignoreExceptions:i,stackTrace:o,internalWrites:s}=r.evaluationOptions,{contract:c,contractDefinition:l,sortedInteractions:g,warp:w}=r,v=e.state,E=null,d=e.validity,y=e.errorMessages;r?.handler.initState(v);let k=r.contract.callDepth();this.logger.debug(`${Be(k)}Evaluating state for ${l.txId} [${t.length} non-cached of ${g.length} all]`);let N=null,q=null,Q=t.length,z=w.maybeLoadPlugin("evm-signature-verification"),X=w.maybeLoadPlugin("evaluation-progress"),D=w.maybeLoadPlugin("vrf"),G=!1;for(let et=0;et0&&et%r.evaluationOptions.cacheEveryNInteractions===0;if(c.isRoot())c.clearChildren(),q&&(c.interactionState().update(c.txId(),q.state,q.tx.sortKey),d[O.id]?await c.interactionState().commit(O,lt):await c.interactionState().rollback(O,lt));else{let st=new $t(v,d,y);c.interactionState().update(c.txId(),st,E)}}let it=new $t(v,d,y);return q!==null&&await this.onStateEvaluated(q.tx,r,q.state),new Ut(E,it)}logResult(t,e,r){t.type==="exception"&&this.logger.error(`Executing of interaction: [${r.contractDefinition.txId} -> ${e.id}] threw exception:`,`${t.errorMessage}`),t.type==="error"&&this.logger.warn(`Executing of interaction: [${r.contractDefinition.txId} -> ${e.id}] returned error:`,t.errorMessage)}parseInput(t){try{return JSON.parse(t.value)}catch(e){return this.logger.error(e),null}}};function cc(n){return n.confirmationStatus===void 0?!0:n.confirmationStatus==="confirmed"}b();var Fo=class extends Mo{constructor(e,r,i=[]){super(e,i);this.cache=r}cLogger=ct.INST.create("CacheableStateEvaluator");async eval(e){let{cachedState:r,contract:i}=e,o=e.sortedInteractions;if(r&&r.sortKey==e.requestedSortKey&&!o?.length)return this.cLogger.info(`Exact cache hit for sortKey ${e?.contractDefinition?.txId}:${r.sortKey}`),e.handler?.initState(r.cachedValue.state),r;let s=e.contractDefinition.txId;if(!s)throw new Error("Contract tx id not set in the execution context");let c=r==null,l=c?e.contractDefinition.initState:r.cachedValue.state,g=c?{}:r.cachedValue.validity,w=c?{}:r.cachedValue.errorMessages;if(c&&(l=await e.handler.maybeCallStateConstructor(e.contractDefinition.initState,e),await i.interactionState().commitKV()),o.length==0)if(this.cLogger.info(`No missing interactions ${s}`),c){e.handler?.initState(l),this.cLogger.debug("Inserting initial state into cache");let v=new $t(l,{},{});return await this.cache.put(new Jt(s,Qn),v),new Ut(Qn,v)}else return e.handler?.initState(r.cachedValue.state),r;return await this.doReadState(o,new $t(l,g,w||{}),e)}async onStateEvaluated(e,r,i){let o=r.contractDefinition.txId;this.cLogger.debug(`${Be(r.contract.callDepth())}onStateEvaluated: cache update for contract ${o} [${e.sortKey}]`),await this.putInCache(o,e,i)}async onStateUpdate(e,r,i,o=!1){(r.evaluationOptions.updateCacheForEachInteraction||o)&&(this.cLogger.debug(`onStateUpdate: cache update for contract ${r.contractDefinition.txId} [${e.sortKey}]`,{contract:r.contractDefinition.txId,state:i.state,sortKey:e.sortKey}),await this.putInCache(r.contractDefinition.txId,e,i))}async latestAvailableState(e,r){if(this.cLogger.debug("Searching for",{contractTxId:e,sortKey:r}),r){let i=await this.cache.getLessOrEqual(e,r);return i&&this.cLogger.debug(`Latest available state at ${e}: ${i.sortKey}`),i}else return await this.cache.getLast(e)}async onInternalWriteStateUpdate(e,r,i){this.cLogger.debug("Internal write state update:",{sortKey:e.sortKey,dry:e.dry,contractTxId:r,state:i.state}),await this.putInCache(r,e,i)}async onContractCall(e,r,i){if(r.sortedInteractions?.length==0)return;let o=r.sortedInteractions.indexOf(e);o<1||await this.putInCache(r.contractDefinition.txId,r.sortedInteractions[o-1],i)}async putInCache(e,r,i){if(r.dry||r.confirmationStatus!==void 0&&r.confirmationStatus!=="confirmed")return;let o=new $t(i.state,i.validity,i.errorMessages||{});this.cLogger.debug("Putting into cache",{contractTxId:e,transaction:r.id,sortKey:r.sortKey,dry:r.dry}),await this.cache.put(new Jt(e,r.sortKey),o)}async syncState(e,r,i,o){let s=new $t(i,o,{});return await this.cache.put(new Jt(e,r),s),new Ut(r,s)}async dumpCache(){return await this.cache.dump()}async internalWriteState(e,r){return await this.cache.get(new Jt(e,r))}async hasContractCached(e){return await this.cache.getLast(e)!=null}async lastCachedSortKey(){return await this.cache.getLastSortKey()}setCache(e){this.cache=e}getCache(){return this.cache}};b();var Hf=jt(mr()),_n=class{constructor(t,e,r=null){this.contractTxId=t;this.depth=e;this.innerCallType=r;this.id=Hf.Crypto.randomUUID()}interactions={};id;addInteractionData(t){let{interaction:e,interactionTx:r}=t,i=di.create(new uc(r.id,r.sortKey,r.block.height,r.block.timestamp,e?.caller,e?.input.function,e?.input,r.dry,{}));return this.interactions[r.id]=i,i}getInteraction(t){return this.interactions[t]}print(){return JSON.stringify(this,null,2)}},di=class{constructor(t){this.interactionInput=t}interactionOutput;static create(t){return new di(t)}update(t){this.interactionOutput=t}},uc=class{constructor(t,e,r,i,o,s,c,l,g={}){this.txId=t;this.sortKey=e;this.blockHeight=r;this.blockTimestamp=i;this.caller=o;this.functionName=s;this.functionArguments=c;this.dryWrite=l;this.foreignContractCalls=g}},jf=class{constructor(t,e,r,i,o="",s){this.cacheHit=t;this.outputState=e;this.executionTime=r;this.valid=i;this.errorMessage=o;this.gasUsed=s}};b();var rs=jt(Oo());b();b();var Qf=(t=>(t.CONTRACT_NOT_FOUND="CONTRACT_NOT_FOUND",t))(Qf||{}),$o=class extends Error{type;otherInfo;constructor(t,e={}){e.message?super(e.message):super(),this.type=t,this.otherInfo=e}getType(){return this.type}};function wm(n){if(!n)return!1;let t=zf(n);return n.evolve!==void 0||t.has("evolve")}var Xe=class{logger=ct.INST.create("Evolve");constructor(){this.modify=this.modify.bind(this)}async modify(t,e){let{definitionLoader:r,executorFactory:i}=e.warp,o=e.contractDefinition.txId,s=Xe.evolvedSrcTxId(t),c=e.contractDefinition.srcTxId;if(s&&c!==s)try{this.logger.info("Evolving to: ",s);let l=await r.load(o,s),g=await i.create(l,e.evaluationOptions,e.warp,e.contract.interactionState());return e.contractDefinition=l,e.handler=g,e.handler.initState(t),this.logger.debug("evolved to:",{evolve:s,newSrcTxId:e.contractDefinition.srcTxId,currentSrcTxId:c,contract:e.contractDefinition.txId}),e}catch(l){throw l.name==="ContractError"&&l.subtype==="unsafeClientSkip"||l.name=="NonWhitelistedSourceError"?l:new $o("CONTRACT_NOT_FOUND",{message:`Error while evolving ${o} from ${c} to ${s}: ${l}`,requestedTxId:o})}return e}static evolvedSrcTxId(t){if(!wm(t))return;let e=zf(t),r=t.evolve||e.get("evolve"),i=t.canEvolve||e.get("canEvolve");if(i==null&&(i=!0),r&&/[a-z0-9_-]{43}/i.test(r)&&i)return r}};function zf(n){let t=new Map;return n.settings&&(vm(n.settings)?t=new Map(n.settings):_m(n.settings)&&(t=new Map(Object.entries(n.settings)))),t}function vm(n){return n==null?!1:typeof n[Symbol.iterator]=="function"}function _m(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}b();b();b();var mc=jt(th(),1),Yb=mc.default.configure;var eh=mc.default;b();async function yc(n,t,e,r,i,o="",s="0",c=!1,l,g){let w={data:Math.random().toString().slice(-4)};o&&o.length&&(w.target=o.toString(),s&&+s>0&&(w.quantity=s.toString())),c&&(w.reward="0",w.last_tx="p7vc1iSP6bvH_fCeUFa9LqoV5qiyW-jdEKouAT0XMoSwrNraB9mgpi29Q10waEpO"),g&&g.length&&(w.reward=g);let v=await n.createTransaction(w);return wc(e,r,l,i).forEach(d=>v.addTag(d.name,d.value)),t&&await t(v),v}function rh(n,t,e){let i=new zt().decodeTags(n);return{id:n.id,owner:{address:t,key:""},recipient:n.target,tags:i,fee:{winston:n.reward,ar:""},quantity:{winston:n.quantity,ar:""},block:{id:e.indep_hash,height:e.height,timestamp:e.timestamp,previous:null},dry:!0,anchor:null,signature:null,data:null,parent:null,bundledIn:null}}function wc(n,t,e,r){let i=[];if(r&&r.length)for(let o of r)i.push(new Qt(o.name.toString(),o.value.toString()));return i.push(new Qt(Ct.APP_NAME,"SmartWeaveAction")),i.push(new Qt(Ct.APP_VERSION,"0.3.0")),i.push(new Qt(Ct.SDK,"Warp")),i.push(new Qt(Ct.CONTRACT_TX_ID,n)),i.push(new Qt(Ct.INPUT,JSON.stringify(t))),e&&i.push(new Qt(at.WARP_TESTNET,"1.0.0")),i}b();var Hr={target:"",winstonQty:"0"},cS=["node1","node2","arweave"];b();var Vo=class{eval(t){let e=[];return Object.keys(t.interactions).forEach(r=>{let i=t.interactions[r];this.evalForeignCalls(t.contractTxId,i,e)}),e}evalForeignCalls(t,e,r){Object.keys(e.interactionInput.foreignContractCalls).forEach(i=>{let o=e.interactionInput.foreignContractCalls[i];o.innerCallType=="write"&&Object.keys(o.interactions).forEach(s=>{let c=o.interactions[s];c.interactionInput.dryWrite&&!r.includes(o.contractTxId)&&t!==o.contractTxId&&r.push(o.contractTxId),this.evalForeignCalls(t,c,r)})})}};b();b();var Im=Object.create,Ec=Object.defineProperty,Am=Object.getOwnPropertyDescriptor,km=Object.getOwnPropertyNames,Lm=Object.getPrototypeOf,Om=Object.prototype.hasOwnProperty,tr=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),Rm=(n,t)=>{for(var e in t)Ec(n,e,{get:t[e],enumerable:!0})},Bm=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of km(t))!Om.call(n,i)&&i!==e&&Ec(n,i,{get:()=>t[i],enumerable:!(r=Am(t,i))||r.enumerable});return n},Qr=(n,t,e)=>(e=n!=null?Im(Lm(n)):{},Bm(t||!n||!n.__esModule?Ec(e,"default",{value:n,enumerable:!0}):e,n)),Pm=tr(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});function t(e){var r=4,i=e.length,o=i%r;if(!o)return e;var s=i,c=r-o,l=i+c,g=F.Buffer.alloc(l);for(g.write(e);c--;)g.write("=",s++);return g.toString()}n.default=t}),Nm=tr(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=Pm();function e(l,g){return g===void 0&&(g="utf8"),F.Buffer.isBuffer(l)?o(l.toString("base64")):o(F.Buffer.from(l,g).toString("base64"))}function r(l,g){return g===void 0&&(g="utf8"),F.Buffer.from(i(l),"base64").toString(g)}function i(l){return l=l.toString(),t.default(l).replace(/\-/g,"+").replace(/_/g,"/")}function o(l){return l.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function s(l){return F.Buffer.from(i(l),"base64")}var c=e;c.encode=e,c.decode=r,c.toBase64=i,c.fromBase64=o,c.toBuffer=s,n.default=c}),Tc=tr((n,t)=>{t.exports=Nm().default,t.exports.default=t.exports}),ih=tr(n=>{"use strict";n.byteLength=l,n.toByteArray=w,n.fromByteArray=d;var t=[],e=[],r=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(o=0,s=i.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var N=y.indexOf("=");N===-1&&(N=k);var q=N===k?0:4-N%4;return[N,q]}function l(y){var k=c(y),N=k[0],q=k[1];return(N+q)*3/4-q}function g(y,k,N){return(k+N)*3/4-N}function w(y){var k,N=c(y),q=N[0],Q=N[1],z=new r(g(y,q,Q)),X=0,D=Q>0?q-4:q,G;for(G=0;G>16&255,z[X++]=k>>8&255,z[X++]=k&255;return Q===2&&(k=e[y.charCodeAt(G)]<<2|e[y.charCodeAt(G+1)]>>4,z[X++]=k&255),Q===1&&(k=e[y.charCodeAt(G)]<<10|e[y.charCodeAt(G+1)]<<4|e[y.charCodeAt(G+2)]>>2,z[X++]=k>>8&255,z[X++]=k&255),z}function v(y){return t[y>>18&63]+t[y>>12&63]+t[y>>6&63]+t[y&63]}function E(y,k,N){for(var q,Q=[],z=k;zD?D:X+z));return q===1?(k=y[N-1],Q.push(t[k>>2]+t[k<<4&63]+"==")):q===2&&(k=(y[N-2]<<8)+y[N-1],Q.push(t[k>>10]+t[k>>4&63]+t[k<<2&63]+"=")),Q.join("")}}),oh=tr(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.b64UrlDecode=n.b64UrlEncode=n.bufferTob64Url=n.bufferTob64=n.b64UrlToBuffer=n.stringToB64Url=n.stringToBuffer=n.bufferToString=n.b64UrlToString=n.concatBuffers=void 0;var t=ih();function e(E){let d=0;for(let N=0;N{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=oh(),e=class{keyLength=4096;publicExponent=65537;hashAlgorithm="sha256";driver;constructor(){if(!this.detectWebCrypto())throw new Error("SubtleCrypto not available!");this.driver=crypto.subtle}async generateJWK(){let r=await this.driver.generateKey({name:"RSA-PSS",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign"]),i=await this.driver.exportKey("jwk",r.privateKey);return{kty:i.kty,e:i.e,n:i.n,d:i.d,p:i.p,q:i.q,dp:i.dp,dq:i.dq,qi:i.qi}}async sign(r,i,{saltLength:o}={}){let s=await this.driver.sign({name:"RSA-PSS",saltLength:32},await this.jwkToCryptoKey(r),i);return new Uint8Array(s)}async hash(r,i="SHA-256"){let o=await this.driver.digest(i,r);return new Uint8Array(o)}async verify(r,i,o){let s={kty:"RSA",e:"AQAB",n:r},c=await this.jwkToPublicCryptoKey(s),l=await this.driver.digest("SHA-256",i),g=await this.driver.verify({name:"RSA-PSS",saltLength:0},c,o,i),w=await this.driver.verify({name:"RSA-PSS",saltLength:32},c,o,i),v=await this.driver.verify({name:"RSA-PSS",saltLength:Math.ceil((c.algorithm.modulusLength-1)/8)-l.byteLength-2},c,o,i);return g||w||v}async jwkToCryptoKey(r){return this.driver.importKey("jwk",r,{name:"RSA-PSS",hash:{name:"SHA-256"}},!1,["sign"])}async jwkToPublicCryptoKey(r){return this.driver.importKey("jwk",r,{name:"RSA-PSS",hash:{name:"SHA-256"}},!1,["verify"])}detectWebCrypto(){if(typeof crypto>"u")return!1;let r=crypto?.subtle;return r===void 0?!1:["generateKey","importKey","exportKey","digest","sign"].every(i=>typeof r[i]=="function")}async encrypt(r,i,o){let s=await this.driver.importKey("raw",typeof i=="string"?t.stringToBuffer(i):i,{name:"PBKDF2",length:32},!1,["deriveKey"]),c=await this.driver.deriveKey({name:"PBKDF2",salt:o?t.stringToBuffer(o):t.stringToBuffer("salt"),iterations:1e5,hash:"SHA-256"},s,{name:"AES-CBC",length:256},!1,["encrypt","decrypt"]),l=new Uint8Array(16);crypto.getRandomValues(l);let g=await this.driver.encrypt({name:"AES-CBC",iv:l},c,r);return t.concatBuffers([l,g])}async decrypt(r,i,o){let s=await this.driver.importKey("raw",typeof i=="string"?t.stringToBuffer(i):i,{name:"PBKDF2",length:32},!1,["deriveKey"]),c=await this.driver.deriveKey({name:"PBKDF2",salt:o?t.stringToBuffer(o):t.stringToBuffer("salt"),iterations:1e5,hash:"SHA-256"},s,{name:"AES-CBC",length:256},!1,["encrypt","decrypt"]),l=r.slice(0,16),g=await this.driver.decrypt({name:"AES-CBC",iv:l},c,r.slice(16));return t.concatBuffers([g])}};n.default=e}),Wm=tr(n=>{n.read=function(t,e,r,i,o){var s,c,l=o*8-i-1,g=(1<>1,v=-7,E=r?o-1:0,d=r?-1:1,y=t[e+E];for(E+=d,s=y&(1<<-v)-1,y>>=-v,v+=l;v>0;s=s*256+t[e+E],E+=d,v-=8);for(c=s&(1<<-v)-1,s>>=-v,v+=i;v>0;c=c*256+t[e+E],E+=d,v-=8);if(s===0)s=1-w;else{if(s===g)return c?NaN:(y?-1:1)*(1/0);c=c+Math.pow(2,i),s=s-w}return(y?-1:1)*c*Math.pow(2,s-i)},n.write=function(t,e,r,i,o,s){var c,l,g,w=s*8-o-1,v=(1<>1,d=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=i?0:s-1,k=i?1:-1,N=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,c=v):(c=Math.floor(Math.log(e)/Math.LN2),e*(g=Math.pow(2,-c))<1&&(c--,g*=2),c+E>=1?e+=d/g:e+=d*Math.pow(2,1-E),e*g>=2&&(c++,g/=2),c+E>=v?(l=0,c=v):c+E>=1?(l=(e*g-1)*Math.pow(2,o),c=c+E):(l=e*Math.pow(2,E-1)*Math.pow(2,o),c=0));o>=8;t[r+y]=l&255,y+=k,l/=256,o-=8);for(c=c<0;t[r+y]=c&255,y+=k,c/=256,w-=8);t[r+y-k]|=N*128}}),_c=tr(n=>{"use strict";var t=ih(),e=Wm(),r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;n.Buffer=c,n.SlowBuffer=Q,n.INSPECT_MAX_BYTES=50;var i=2147483647;n.kMaxLength=i,c.TYPED_ARRAY_SUPPORT=o(),!c.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function o(){try{let a=new Uint8Array(1),u={foo:function(){return 42}};return Object.setPrototypeOf(u,Uint8Array.prototype),Object.setPrototypeOf(a,u),a.foo()===42}catch{return!1}}Object.defineProperty(c.prototype,"parent",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.buffer}}),Object.defineProperty(c.prototype,"offset",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.byteOffset}});function s(a){if(a>i)throw new RangeError('The value "'+a+'" is invalid for option "size"');let u=new Uint8Array(a);return Object.setPrototypeOf(u,c.prototype),u}function c(a,u,f){if(typeof a=="number"){if(typeof u=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return v(a)}return l(a,u,f)}c.poolSize=8192;function l(a,u,f){if(typeof a=="string")return E(a,u);if(ArrayBuffer.isView(a))return y(a);if(a==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a);if(m(a,ArrayBuffer)||a&&m(a.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(m(a,SharedArrayBuffer)||a&&m(a.buffer,SharedArrayBuffer)))return k(a,u,f);if(typeof a=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let T=a.valueOf&&a.valueOf();if(T!=null&&T!==a)return c.from(T,u,f);let L=N(a);if(L)return L;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof a[Symbol.toPrimitive]=="function")return c.from(a[Symbol.toPrimitive]("string"),u,f);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a)}c.from=function(a,u,f){return l(a,u,f)},Object.setPrototypeOf(c.prototype,Uint8Array.prototype),Object.setPrototypeOf(c,Uint8Array);function g(a){if(typeof a!="number")throw new TypeError('"size" argument must be of type number');if(a<0)throw new RangeError('The value "'+a+'" is invalid for option "size"')}function w(a,u,f){return g(a),a<=0?s(a):u!==void 0?typeof f=="string"?s(a).fill(u,f):s(a).fill(u):s(a)}c.alloc=function(a,u,f){return w(a,u,f)};function v(a){return g(a),s(a<0?0:q(a)|0)}c.allocUnsafe=function(a){return v(a)},c.allocUnsafeSlow=function(a){return v(a)};function E(a,u){if((typeof u!="string"||u==="")&&(u="utf8"),!c.isEncoding(u))throw new TypeError("Unknown encoding: "+u);let f=z(a,u)|0,T=s(f),L=T.write(a,u);return L!==f&&(T=T.slice(0,L)),T}function d(a){let u=a.length<0?0:q(a.length)|0,f=s(u);for(let T=0;T=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return a|0}function Q(a){return+a!=a&&(a=0),c.alloc(+a)}c.isBuffer=function(a){return a!=null&&a._isBuffer===!0&&a!==c.prototype},c.compare=function(a,u){if(m(a,Uint8Array)&&(a=c.from(a,a.offset,a.byteLength)),m(u,Uint8Array)&&(u=c.from(u,u.offset,u.byteLength)),!c.isBuffer(a)||!c.isBuffer(u))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(a===u)return 0;let f=a.length,T=u.length;for(let L=0,M=Math.min(f,T);LT.length?(c.isBuffer(M)||(M=c.from(M)),M.copy(T,L)):Uint8Array.prototype.set.call(T,M,L);else if(c.isBuffer(M))M.copy(T,L);else throw new TypeError('"list" argument must be an Array of Buffers');L+=M.length}return T};function z(a,u){if(c.isBuffer(a))return a.length;if(ArrayBuffer.isView(a)||m(a,ArrayBuffer))return a.byteLength;if(typeof a!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof a);let f=a.length,T=arguments.length>2&&arguments[2]===!0;if(!T&&f===0)return 0;let L=!1;for(;;)switch(u){case"ascii":case"latin1":case"binary":return f;case"utf8":case"utf-8":return A(a).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return f*2;case"hex":return f>>>1;case"base64":return H(a).length;default:if(L)return T?-1:A(a).length;u=(""+u).toLowerCase(),L=!0}}c.byteLength=z;function X(a,u,f){let T=!1;if((u===void 0||u<0)&&(u=0),u>this.length||((f===void 0||f>this.length)&&(f=this.length),f<=0)||(f>>>=0,u>>>=0,f<=u))return"";for(a||(a="utf8");;)switch(a){case"hex":return Nt(this,u,f);case"utf8":case"utf-8":return wt(this,u,f);case"ascii":return ht(this,u,f);case"latin1":case"binary":return _t(this,u,f);case"base64":return st(this,u,f);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ue(this,u,f);default:if(T)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase(),T=!0}}c.prototype._isBuffer=!0;function D(a,u,f){let T=a[u];a[u]=a[f],a[f]=T}c.prototype.swap16=function(){let a=this.length;if(a%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let u=0;uu&&(a+=" ... "),""},r&&(c.prototype[r]=c.prototype.inspect),c.prototype.compare=function(a,u,f,T,L){if(m(a,Uint8Array)&&(a=c.from(a,a.offset,a.byteLength)),!c.isBuffer(a))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof a);if(u===void 0&&(u=0),f===void 0&&(f=a?a.length:0),T===void 0&&(T=0),L===void 0&&(L=this.length),u<0||f>a.length||T<0||L>this.length)throw new RangeError("out of range index");if(T>=L&&u>=f)return 0;if(T>=L)return-1;if(u>=f)return 1;if(u>>>=0,f>>>=0,T>>>=0,L>>>=0,this===a)return 0;let M=L-T,J=f-u,dt=Math.min(M,J),bt=this.slice(T,L),ut=a.slice(u,f);for(let It=0;It2147483647?f=2147483647:f<-2147483648&&(f=-2147483648),f=+f,I(f)&&(f=L?0:a.length-1),f<0&&(f=a.length+f),f>=a.length){if(L)return-1;f=a.length-1}else if(f<0)if(L)f=0;else return-1;if(typeof u=="string"&&(u=c.from(u,T)),c.isBuffer(u))return u.length===0?-1:it(a,u,f,T,L);if(typeof u=="number")return u=u&255,typeof Uint8Array.prototype.indexOf=="function"?L?Uint8Array.prototype.indexOf.call(a,u,f):Uint8Array.prototype.lastIndexOf.call(a,u,f):it(a,[u],f,T,L);throw new TypeError("val must be string, number or Buffer")}function it(a,u,f,T,L){let M=1,J=a.length,dt=u.length;if(T!==void 0&&(T=String(T).toLowerCase(),T==="ucs2"||T==="ucs-2"||T==="utf16le"||T==="utf-16le")){if(a.length<2||u.length<2)return-1;M=2,J/=2,dt/=2,f/=2}function bt(It,Bt){return M===1?It[Bt]:It.readUInt16BE(Bt*M)}let ut;if(L){let It=-1;for(ut=f;utJ&&(f=J-dt),ut=f;ut>=0;ut--){let It=!0;for(let Bt=0;BtL&&(T=L)):T=L;let M=u.length;T>M/2&&(T=M/2);let J;for(J=0;J>>0,isFinite(f)?(f=f>>>0,T===void 0&&(T="utf8")):(T=f,f=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let L=this.length-u;if((f===void 0||f>L)&&(f=L),a.length>0&&(f<0||u<0)||u>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");let M=!1;for(;;)switch(T){case"hex":return et(this,a,u,f);case"utf8":case"utf-8":return O(this,a,u,f);case"ascii":case"latin1":case"binary":return ft(this,a,u,f);case"base64":return tt(this,a,u,f);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return lt(this,a,u,f);default:if(M)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),M=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function st(a,u,f){return u===0&&f===a.length?t.fromByteArray(a):t.fromByteArray(a.slice(u,f))}function wt(a,u,f){f=Math.min(a.length,f);let T=[],L=u;for(;L239?4:M>223?3:M>191?2:1;if(L+dt<=f){let bt,ut,It,Bt;switch(dt){case 1:M<128&&(J=M);break;case 2:bt=a[L+1],(bt&192)===128&&(Bt=(M&31)<<6|bt&63,Bt>127&&(J=Bt));break;case 3:bt=a[L+1],ut=a[L+2],(bt&192)===128&&(ut&192)===128&&(Bt=(M&15)<<12|(bt&63)<<6|ut&63,Bt>2047&&(Bt<55296||Bt>57343)&&(J=Bt));break;case 4:bt=a[L+1],ut=a[L+2],It=a[L+3],(bt&192)===128&&(ut&192)===128&&(It&192)===128&&(Bt=(M&15)<<18|(bt&63)<<12|(ut&63)<<6|It&63,Bt>65535&&Bt<1114112&&(J=Bt))}}J===null?(J=65533,dt=1):J>65535&&(J-=65536,T.push(J>>>10&1023|55296),J=56320|J&1023),T.push(J),L+=dt}return Tt(T)}var Pt=4096;function Tt(a){let u=a.length;if(u<=Pt)return String.fromCharCode.apply(String,a);let f="",T=0;for(;TT)&&(f=T);let L="";for(let M=u;Mf&&(a=f),u<0?(u+=f,u<0&&(u=0)):u>f&&(u=f),uf)throw new RangeError("Trying to access beyond buffer length")}c.prototype.readUintLE=c.prototype.readUIntLE=function(a,u,f){a=a>>>0,u=u>>>0,f||yt(a,u,this.length);let T=this[a],L=1,M=0;for(;++M>>0,u=u>>>0,f||yt(a,u,this.length);let T=this[a+--u],L=1;for(;u>0&&(L*=256);)T+=this[a+--u]*L;return T},c.prototype.readUint8=c.prototype.readUInt8=function(a,u){return a=a>>>0,u||yt(a,1,this.length),this[a]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(a,u){return a=a>>>0,u||yt(a,2,this.length),this[a]|this[a+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(a,u){return a=a>>>0,u||yt(a,2,this.length),this[a]<<8|this[a+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),(this[a]|this[a+1]<<8|this[a+2]<<16)+this[a+3]*16777216},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),this[a]*16777216+(this[a+1]<<16|this[a+2]<<8|this[a+3])},c.prototype.readBigUInt64LE=Z(function(a){a=a>>>0,C(a,"offset");let u=this[a],f=this[a+7];(u===void 0||f===void 0)&&R(a,this.length-8);let T=u+this[++a]*2**8+this[++a]*2**16+this[++a]*2**24,L=this[++a]+this[++a]*2**8+this[++a]*2**16+f*2**24;return BigInt(T)+(BigInt(L)<>>0,C(a,"offset");let u=this[a],f=this[a+7];(u===void 0||f===void 0)&&R(a,this.length-8);let T=u*2**24+this[++a]*2**16+this[++a]*2**8+this[++a],L=this[++a]*2**24+this[++a]*2**16+this[++a]*2**8+f;return(BigInt(T)<>>0,u=u>>>0,f||yt(a,u,this.length);let T=this[a],L=1,M=0;for(;++M=L&&(T-=Math.pow(2,8*u)),T},c.prototype.readIntBE=function(a,u,f){a=a>>>0,u=u>>>0,f||yt(a,u,this.length);let T=u,L=1,M=this[a+--T];for(;T>0&&(L*=256);)M+=this[a+--T]*L;return L*=128,M>=L&&(M-=Math.pow(2,8*u)),M},c.prototype.readInt8=function(a,u){return a=a>>>0,u||yt(a,1,this.length),this[a]&128?(255-this[a]+1)*-1:this[a]},c.prototype.readInt16LE=function(a,u){a=a>>>0,u||yt(a,2,this.length);let f=this[a]|this[a+1]<<8;return f&32768?f|4294901760:f},c.prototype.readInt16BE=function(a,u){a=a>>>0,u||yt(a,2,this.length);let f=this[a+1]|this[a]<<8;return f&32768?f|4294901760:f},c.prototype.readInt32LE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),this[a]|this[a+1]<<8|this[a+2]<<16|this[a+3]<<24},c.prototype.readInt32BE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]},c.prototype.readBigInt64LE=Z(function(a){a=a>>>0,C(a,"offset");let u=this[a],f=this[a+7];(u===void 0||f===void 0)&&R(a,this.length-8);let T=this[a+4]+this[a+5]*2**8+this[a+6]*2**16+(f<<24);return(BigInt(T)<>>0,C(a,"offset");let u=this[a],f=this[a+7];(u===void 0||f===void 0)&&R(a,this.length-8);let T=(u<<24)+this[++a]*2**16+this[++a]*2**8+this[++a];return(BigInt(T)<>>0,u||yt(a,4,this.length),e.read(this,a,!0,23,4)},c.prototype.readFloatBE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),e.read(this,a,!1,23,4)},c.prototype.readDoubleLE=function(a,u){return a=a>>>0,u||yt(a,8,this.length),e.read(this,a,!0,52,8)},c.prototype.readDoubleBE=function(a,u){return a=a>>>0,u||yt(a,8,this.length),e.read(this,a,!1,52,8)};function Lt(a,u,f,T,L,M){if(!c.isBuffer(a))throw new TypeError('"buffer" argument must be a Buffer instance');if(u>L||ua.length)throw new RangeError("Index out of range")}c.prototype.writeUintLE=c.prototype.writeUIntLE=function(a,u,f,T){if(a=+a,u=u>>>0,f=f>>>0,!T){let J=Math.pow(2,8*f)-1;Lt(this,a,u,f,J,0)}let L=1,M=0;for(this[u]=a&255;++M>>0,f=f>>>0,!T){let J=Math.pow(2,8*f)-1;Lt(this,a,u,f,J,0)}let L=f-1,M=1;for(this[u+L]=a&255;--L>=0&&(M*=256);)this[u+L]=a/M&255;return u+f},c.prototype.writeUint8=c.prototype.writeUInt8=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,1,255,0),this[u]=a&255,u+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,2,65535,0),this[u]=a&255,this[u+1]=a>>>8,u+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,2,65535,0),this[u]=a>>>8,this[u+1]=a&255,u+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,4,4294967295,0),this[u+3]=a>>>24,this[u+2]=a>>>16,this[u+1]=a>>>8,this[u]=a&255,u+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,4,4294967295,0),this[u]=a>>>24,this[u+1]=a>>>16,this[u+2]=a>>>8,this[u+3]=a&255,u+4};function Y(a,u,f,T,L){U(u,T,L,a,f,7);let M=Number(u&BigInt(4294967295));a[f++]=M,M=M>>8,a[f++]=M,M=M>>8,a[f++]=M,M=M>>8,a[f++]=M;let J=Number(u>>BigInt(32)&BigInt(4294967295));return a[f++]=J,J=J>>8,a[f++]=J,J=J>>8,a[f++]=J,J=J>>8,a[f++]=J,f}function er(a,u,f,T,L){U(u,T,L,a,f,7);let M=Number(u&BigInt(4294967295));a[f+7]=M,M=M>>8,a[f+6]=M,M=M>>8,a[f+5]=M,M=M>>8,a[f+4]=M;let J=Number(u>>BigInt(32)&BigInt(4294967295));return a[f+3]=J,J=J>>8,a[f+2]=J,J=J>>8,a[f+1]=J,J=J>>8,a[f]=J,f+8}c.prototype.writeBigUInt64LE=Z(function(a,u=0){return Y(this,a,u,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeBigUInt64BE=Z(function(a,u=0){return er(this,a,u,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeIntLE=function(a,u,f,T){if(a=+a,u=u>>>0,!T){let dt=Math.pow(2,8*f-1);Lt(this,a,u,f,dt-1,-dt)}let L=0,M=1,J=0;for(this[u]=a&255;++L>0)-J&255;return u+f},c.prototype.writeIntBE=function(a,u,f,T){if(a=+a,u=u>>>0,!T){let dt=Math.pow(2,8*f-1);Lt(this,a,u,f,dt-1,-dt)}let L=f-1,M=1,J=0;for(this[u+L]=a&255;--L>=0&&(M*=256);)a<0&&J===0&&this[u+L+1]!==0&&(J=1),this[u+L]=(a/M>>0)-J&255;return u+f},c.prototype.writeInt8=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,1,127,-128),a<0&&(a=255+a+1),this[u]=a&255,u+1},c.prototype.writeInt16LE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,2,32767,-32768),this[u]=a&255,this[u+1]=a>>>8,u+2},c.prototype.writeInt16BE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,2,32767,-32768),this[u]=a>>>8,this[u+1]=a&255,u+2},c.prototype.writeInt32LE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,4,2147483647,-2147483648),this[u]=a&255,this[u+1]=a>>>8,this[u+2]=a>>>16,this[u+3]=a>>>24,u+4},c.prototype.writeInt32BE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,4,2147483647,-2147483648),a<0&&(a=4294967295+a+1),this[u]=a>>>24,this[u+1]=a>>>16,this[u+2]=a>>>8,this[u+3]=a&255,u+4},c.prototype.writeBigInt64LE=Z(function(a,u=0){return Y(this,a,u,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeBigInt64BE=Z(function(a,u=0){return er(this,a,u,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Er(a,u,f,T,L,M){if(f+T>a.length)throw new RangeError("Index out of range");if(f<0)throw new RangeError("Index out of range")}function rr(a,u,f,T,L){return u=+u,f=f>>>0,L||Er(a,u,f,4,34028234663852886e22,-34028234663852886e22),e.write(a,u,f,T,23,4),f+4}c.prototype.writeFloatLE=function(a,u,f){return rr(this,a,u,!0,f)},c.prototype.writeFloatBE=function(a,u,f){return rr(this,a,u,!1,f)};function Vt(a,u,f,T,L){return u=+u,f=f>>>0,L||Er(a,u,f,8,17976931348623157e292,-17976931348623157e292),e.write(a,u,f,T,52,8),f+8}c.prototype.writeDoubleLE=function(a,u,f){return Vt(this,a,u,!0,f)},c.prototype.writeDoubleBE=function(a,u,f){return Vt(this,a,u,!1,f)},c.prototype.copy=function(a,u,f,T){if(!c.isBuffer(a))throw new TypeError("argument should be a Buffer");if(f||(f=0),!T&&T!==0&&(T=this.length),u>=a.length&&(u=a.length),u||(u=0),T>0&&T=this.length)throw new RangeError("Index out of range");if(T<0)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),a.length-u>>0,f=f===void 0?this.length:f>>>0,a||(a=0);let L;if(typeof a=="number")for(L=u;L2**32?L=_(String(f)):typeof f=="bigint"&&(L=String(f),(f>BigInt(2)**BigInt(32)||f<-(BigInt(2)**BigInt(32)))&&(L=_(L)),L+="n"),T+=` It must be ${u}. Received ${L}`,T},RangeError);function _(a){let u="",f=a.length,T=a[0]==="-"?1:0;for(;f>=T+4;f-=3)u=`_${a.slice(f-3,f)}${u}`;return`${a.slice(0,f)}${u}`}function S(a,u,f){C(u,"offset"),(a[u]===void 0||a[u+f]===void 0)&&R(u,a.length-(f+1))}function U(a,u,f,T,L,M){if(a>f||a3?u===0||u===BigInt(0)?dt=`>= 0${J} and < 2${J} ** ${(M+1)*8}${J}`:dt=`>= -(2${J} ** ${(M+1)*8-1}${J}) and < 2 ** ${(M+1)*8-1}${J}`:dt=`>= ${u}${J} and <= ${f}${J}`,new Dt.ERR_OUT_OF_RANGE("value",dt,a)}S(T,L,M)}function C(a,u){if(typeof a!="number")throw new Dt.ERR_INVALID_ARG_TYPE(u,"number",a)}function R(a,u,f){throw Math.floor(a)!==a?(C(a,f),new Dt.ERR_OUT_OF_RANGE(f||"offset","an integer",a)):u<0?new Dt.ERR_BUFFER_OUT_OF_BOUNDS:new Dt.ERR_OUT_OF_RANGE(f||"offset",`>= ${f?1:0} and <= ${u}`,a)}var W=/[^+/0-9A-Za-z-_]/g;function x(a){if(a=a.split("=")[0],a=a.trim().replace(W,""),a.length<2)return"";for(;a.length%4!==0;)a=a+"=";return a}function A(a,u){u=u||1/0;let f,T=a.length,L=null,M=[];for(let J=0;J55295&&f<57344){if(!L){if(f>56319){(u-=3)>-1&&M.push(239,191,189);continue}else if(J+1===T){(u-=3)>-1&&M.push(239,191,189);continue}L=f;continue}if(f<56320){(u-=3)>-1&&M.push(239,191,189),L=f;continue}f=(L-55296<<10|f-56320)+65536}else L&&(u-=3)>-1&&M.push(239,191,189);if(L=null,f<128){if((u-=1)<0)break;M.push(f)}else if(f<2048){if((u-=2)<0)break;M.push(f>>6|192,f&63|128)}else if(f<65536){if((u-=3)<0)break;M.push(f>>12|224,f>>6&63|128,f&63|128)}else if(f<1114112){if((u-=4)<0)break;M.push(f>>18|240,f>>12&63|128,f>>6&63|128,f&63|128)}else throw new Error("Invalid code point")}return M}function B(a){let u=[];for(let f=0;f>8,L=f%256,M.push(L),M.push(T);return M}function H(a){return t.toByteArray(x(a))}function h(a,u,f,T){let L;for(L=0;L=u.length||L>=a.length);++L)u[L+f]=a[L];return L}function m(a,u){return a instanceof u||a!=null&&a.constructor!=null&&a.constructor.name!=null&&a.constructor.name===u.name}function I(a){return a!==a}var j=function(){let a="0123456789abcdef",u=new Array(256);for(let f=0;f<16;++f){let T=f*16;for(let L=0;L<16;++L)u[T+L]=a[f]+a[L]}return u}();function Z(a){return typeof BigInt>"u"?rt:a}function rt(){throw new Error("BigInt not supported")}}),Dm=tr((n,t)=>{typeof window<"u"?(window.global=window,K.fetch=window.fetch,t.exports={Buffer:_c().Buffer,Crypto:window.crypto}):t.exports={Buffer:_c().Buffer,Crypto:crypto}}),sh={};Rm(sh,{AVSCTap:()=>jo,ArweaveSigner:()=>qo,DataItem:()=>Go,MAX_TAG_BYTES:()=>Cc,MIN_BINARY_SIZE:()=>fh,SIG_CONFIG:()=>pi,SignatureConfig:()=>Ee,Signer:()=>Mm,createData:()=>Ic,deserializeTags:()=>Sc,indexToType:()=>uh,serializeTags:()=>lh,tagsExceedLimit:()=>xc});var Mm=class{signer;publicKey;signatureType;signatureLength;ownerLength;pem;static verify(n,t,e,r){throw new Error("You must implement verify method on child")}},Fm=Qr(Tc(),1),Se=Qr(oh(),1);async function ah(n){if(Array.isArray(n)){let i=(0,Se.concatBuffers)([(0,Se.stringToBuffer)("list"),(0,Se.stringToBuffer)(n.length.toString())]);return await ch(n,await Ze().hash(i,"SHA-384"))}let t=n,e=(0,Se.concatBuffers)([(0,Se.stringToBuffer)("blob"),(0,Se.stringToBuffer)(t.byteLength.toString())]),r=(0,Se.concatBuffers)([await Ze().hash(e,"SHA-384"),await Ze().hash(t,"SHA-384")]);return await Ze().hash(r,"SHA-384")}async function ch(n,t){if(n.length<1)return t;let e=(0,Se.concatBuffers)([t,await ah(n[0])]),r=await Ze().hash(e,"SHA-384");return await ch(n.slice(1),r)}var vc=Qr(Um(),1),$m=vc.default.default?vc.default.default:vc.default,Km=class extends $m{getPublicKey(n){throw new Error("Unimplemented")}},Vm;function Ze(){return Vm??=new Km}var Ee;(function(n){n[n.ARWEAVE=1]="ARWEAVE",n[n.ED25519=2]="ED25519",n[n.ETHEREUM=3]="ETHEREUM",n[n.SOLANA=4]="SOLANA",n[n.INJECTEDAPTOS=5]="INJECTEDAPTOS",n[n.MULTIAPTOS=6]="MULTIAPTOS",n[n.TYPEDETHEREUM=7]="TYPEDETHEREUM"})(Ee||(Ee={}));var pi={[Ee.ARWEAVE]:{sigLength:512,pubLength:512,sigName:"arweave"},[Ee.ED25519]:{sigLength:64,pubLength:32,sigName:"ed25519"},[Ee.ETHEREUM]:{sigLength:65,pubLength:65,sigName:"ethereum"},[Ee.SOLANA]:{sigLength:64,pubLength:32,sigName:"solana"},[Ee.INJECTEDAPTOS]:{sigLength:64,pubLength:32,sigName:"injectedAptos"},[Ee.MULTIAPTOS]:{sigLength:64*32+4,pubLength:32*32+1,sigName:"multiAptos"},[Ee.TYPEDETHEREUM]:{sigLength:65,pubLength:42,sigName:"typedEthereum"}},qo=class{signatureType=1;ownerLength=pi[1].pubLength;signatureLength=pi[1].sigLength;jwk;pk;constructor(n){this.pk=n.n,this.jwk=n}get publicKey(){return Fm.default.toBuffer(this.pk)}sign(n){return Ze().sign(this.jwk,n)}static async verify(n,t,e){return await Ze().verify(n,t,e)}},uh={1:qo},Ne=Qr(Tc(),1);async function bc(n){return ah([(0,Se.stringToBuffer)("dataitem"),(0,Se.stringToBuffer)("1"),(0,Se.stringToBuffer)(n.signatureType.toString()),n.rawOwner,n.rawTarget,n.rawAnchor,n.rawTags,n.rawData])}async function Gm(n,t){let e=await bc(n),r=await t.sign(e),i=await Ze().hash(r);return{signature:F.Buffer.from(r),id:F.Buffer.from(i)}}async function qm(n,t){let{signature:e,id:r}=await Gm(n,t);return n.getRaw().set(e,2),r}var jo=class{buf;pos;constructor(n=F.Buffer.alloc(Cc),t=0){this.buf=n,this.pos=t}writeTags(n){if(!Array.isArray(n))throw new Error("input must be array");let t=n.length,e;if(t)for(this.writeLong(t),e=0;ethis.buf.length)throw new Error(`Too many tag bytes (${this.pos} > ${this.buf.length})`);return this.buf.copy(n,0,0,this.pos),n}tagsExceedLimit(){return this.pos>this.buf.length}writeLong(n){let t=this.buf,e,r;if(n>=-1073741824&&n<1073741824){r=n>=0?n<<1:~n<<1|1;do t[this.pos]=r&127,r>>=7;while(r&&(t[this.pos++]|=128))}else{e=n>=0?n*2:-n*2-1;do t[this.pos]=e&127,e/=128;while(e>=1&&(t[this.pos++]|=128))}this.pos++,this.buf=t}writeString(n){let t=F.Buffer.byteLength(n),e=this.buf;this.writeLong(t);let r=this.pos;if(this.pos+=t,!(this.pos>e.length)){if(t>64)this.buf.write(n,this.pos-t,t,"utf8");else{let i,o,s,c;for(i=0,o=t;i>6|192,e[r++]=s&63|128):(s&64512)===55296&&((c=n.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(c&1023),i++,e[r++]=s>>18|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128,e[r++]=s&63|128):(e[r++]=s>>12|224,e[r++]=s>>6&63|128,e[r++]=s&63|128)}this.buf=e}}readLong(){let n=0,t=0,e=this.buf,r,i,o,s;do r=e[this.pos++],i=r&128,n|=(r&127)<>1^-(n&1)}skipLong(){let n=this.buf;for(;n[this.pos++]&128;);}readTags(){let n=[],t;for(;t=this.readLong();)for(t<0&&(t=-t,this.skipLong());t--;){let e=this.readString(),r=this.readString();n.push({name:e,value:r})}return n}readString(){let n=this.readLong(),t=this.pos,e=this.buf;if(this.pos+=n,!(this.pos>e.length))return this.buf.slice(t,t+n).toString()}};function lh(n){let t=new jo;return t.writeTags(n),t.toBuffer()}function xc(n){let t=new jo;return t.writeTags(n),t.tagsExceedLimit()}function Sc(n){return new jo(n).readTags()}function Sr(n){let t=0;for(let e=n.length-1;e>=0;e--)t=t*256+n[e];return t}function jm(n){if(n>(2^32-1))throw new Error("Short too long");let t=[0,0];for(let e=0;eNe.default.encode(await this.rawId))()}set id(n){this._id=Ne.default.toBuffer(n)}get rawId(){return(async()=>bn.Buffer.from(await Hm.Crypto.subtle.digest("SHA-256",this.rawSignature)))()}set rawId(n){this._id=n}get rawSignature(){return this.binary.subarray(2,2+this.signatureLength)}get signature(){return Ne.default.encode(this.rawSignature)}set rawOwner(n){if(n.byteLength!=this.ownerLength)throw new Error(`Expected raw owner (pubkey) to be ${this.ownerLength} bytes, got ${n.byteLength} bytes.`);this.binary.set(n,2+this.signatureLength)}get rawOwner(){return this.binary.subarray(2+this.signatureLength,2+this.signatureLength+this.ownerLength)}get signatureLength(){return pi[this.signatureType].sigLength}get owner(){return Ne.default.encode(this.rawOwner)}get ownerLength(){return pi[this.signatureType].pubLength}get rawTarget(){let n=this.getTargetStart();return this.binary[n]==1?this.binary.subarray(n+1,n+33):bn.Buffer.alloc(0)}get target(){return Ne.default.encode(this.rawTarget)}get rawAnchor(){let n=this.getAnchorStart();return this.binary[n]==1?this.binary.subarray(n+1,n+33):bn.Buffer.alloc(0)}get anchor(){return this.rawAnchor.toString()}get rawTags(){let n=this.getTagsStart(),t=Sr(this.binary.subarray(n+8,n+16));return this.binary.subarray(n+16,n+16+t)}get tags(){let n=this.getTagsStart();if(Sr(this.binary.subarray(n,n+8))==0)return[];let t=Sr(this.binary.subarray(n+8,n+16));return Sc(bn.Buffer.from(this.binary.subarray(n+16,n+16+t)))}get tagsB64Url(){return this.tags.map(n=>({name:Ne.default.encode(n.name),value:Ne.default.encode(n.value)}))}getStartOfData(){let n=this.getTagsStart(),t=this.binary.subarray(n+8,n+16),e=Sr(t);return n+16+e}get rawData(){let n=this.getTagsStart(),t=this.binary.subarray(n+8,n+16),e=Sr(t),r=n+16+e;return this.binary.subarray(r,this.binary.length)}get data(){return Ne.default.encode(this.rawData)}getRaw(){return this.binary}async sign(n){return this._id=await qm(this,n),this.rawId}async setSignature(n){this.binary.set(n,2),this._id=bn.Buffer.from(await Ze().hash(n))}isSigned(){return(this._id?.length??0)>0}toJSON(){return{signature:this.signature,owner:this.owner,target:this.target,tags:this.tags.map(n=>({name:Ne.default.encode(n.name),value:Ne.default.encode(n.value)})),data:this.data}}static async verify(n){if(n.byteLengthCc)return!1;if(i>0)try{if(Sc(bn.Buffer.from(n.subarray(r+16,r+16+s))).length!==i)return!1}catch{return!1}let c=uh[e],l=await bc(t);return await c.verify(t.rawOwner,l,t.rawSignature)}async getSignatureData(){return bc(this)}getTagsStart(){let n=this.getTargetStart(),t=this.binary[n]==1,e=n+(t?33:1),r=this.binary[e]==1;return e+=r?33:1,e}getTargetStart(){return 2+this.signatureLength+this.ownerLength}getAnchorStart(){let n=this.getTargetStart()+1,t=this.binary[this.getTargetStart()]==1;return n+=t?32:0,n}},Qm=Qr(Tc(),1);function Ic(n,t,e){let r=t.publicKey,i=e?.target?Qm.default.toBuffer(e.target):null,o=1+(i?.byteLength??0),s=e?.anchor?F.Buffer.from(e.anchor):null,c=1+(s?.byteLength??0),l=(e?.tags?.length??0)>0?lh(e.tags):null,g=16+(l?l.byteLength:0),w=F.Buffer.from(n),v=w.byteLength,E=2+t.signatureLength+t.ownerLength+o+c+g+v,d=F.Buffer.alloc(E);if(d.set(jm(t.signatureType),0),d.set(new Uint8Array(t.signatureLength).fill(0),2),r.byteLength!==t.ownerLength)throw new Error(`Owner must be ${t.ownerLength} bytes, but was incorrectly ${r.byteLength}`);d.set(r,2+t.signatureLength);let y=2+t.signatureLength+t.ownerLength;if(d[y]=i?1:0,i){if(i.byteLength!==32)throw new Error(`Target must be 32 bytes but was incorrectly ${i.byteLength}`);d.set(i,y+1)}let k=y+o,N=k+1;if(d[k]=s?1:0,s){if(N+=s.byteLength,s.byteLength!==32)throw new Error("Anchor must be 32 bytes");d.set(s,k+1)}d.set(nh(e?.tags?.length??0),N);let q=nh(l?.byteLength??0);d.set(q,N+8),l&&d.set(l,N+16);let Q=N+g;return d.set(w,Q),new Go(d)}var zm={...sh};globalThis.arbundles??=zm;var Ho=class{signer;bundlerSigner;type;warp;signatureProviderType;wallet;cachedAddress;constructor(t,e){this.warp=t,this.isCustomSignature(e)?(this.assertEnvForCustomSigner(e.type),this.signer=e.signer,this.type=e.type,this.signatureProviderType="CustomSignature"):this.isValidBundlerSignature(e)?(this.signatureProviderType="BundlerSigner",this.type=Jm(e.signatureType),this.bundlerSigner=e):(this.assignArweaveSigner(e),this.bundlerSigner=typeof e=="string"?null:new qo(e),this.signatureProviderType="ArWallet",this.type="arweave"),this.wallet=e}async getAddress(){if(this.cachedAddress)return this.cachedAddress;switch(this.signatureProviderType){case"CustomSignature":return this.wallet.getAddress?this.cachedAddress=await this.wallet.getAddress():this.cachedAddress=await this.deduceSignerBySigning(),this.cachedAddress;case"ArWallet":return this.cachedAddress=await this.deduceSignerBySigning(),this.cachedAddress;case"BundlerSigner":return this.cachedAddress=await this.deduceSignerBySigning(),this.cachedAddress;default:throw Error("Unknown Signature::signatureProvider : "+this.signatureProviderType)}}async deduceSignerBySigning(){let{arweave:t}=this.warp;if(this.signatureProviderType=="BundlerSigner")try{return await this.bundlerSigner.getAddress()}catch{throw new Error("Could not get address from the signer. Is the 'getAddress' implementation correct?'")}else if(this.signatureProviderType=="ArWallet"||this.signatureProviderType=="CustomSignature"){let e=await t.createTransaction({data:Math.random().toString().slice(-4),reward:"72600854",last_tx:"p7vc1iSP6bvH_fCeUFa9LqoV5qiyW-jdEKouAT0XMoSwrNraB9mgpi29Q10waEpO"});return await this.signer(e),t.wallets.ownerToAddress(e.owner)}else throw Error("Unknown Signature::type")}checkNonArweaveSigningAvailability(t){if(this.type!=="arweave"&&!t)throw new Error(`Unable to use signing function of type: ${this.type} when bundling is disabled.`)}checkBundlerSignerAvailability(t){if((!t||this.warp.environment=="local")&&this.signatureProviderType=="BundlerSigner")throw new Error("Only wallet of type 'ArWallet' or 'CustomSignature' is allowed when bundling is disabled or in local environment.")}assignArweaveSigner(t){this.signer=async e=>{await this.warp.arweave.transactions.sign(e,t)}}assertEnvForCustomSigner(t){if(this.warp.interactionsLoader.type()==="warp")throw new Error("Unable to use signing function when bundling is enabled.");if(t=="ethereum")throw new Error(`Unable to use signing function with signature of type: ${t}.`)}isCustomSignature(t){return t.signer!==void 0&&t.type!==void 0}isValidBundlerSignature(t){let e=t,r=!!e.signatureType&&!!e.ownerLength&&!!e.signatureLength;if(r&&!e.publicKey)throw new Error("It seems that you are using BundlerSigner, but publicKey is not set! Maybe try calling await bundlerSigner.setPublicKey() before using it.");return r}};function Jm(n){if(n===3)return"ethereum";if(n===1)return"arweave";throw Error(`Not supported arbundle SignatureType : ${n}`)}b();var Qo=class{rootOptions;saferEvaluationOptions={internalWrites:t=>{if(t.internalWrites===void 0||this.rootOptions.internalWrites==t.internalWrites)return this.rootOptions.internalWrites;if(this.rootOptions.internalWrites&&!t.internalWrites||!this.rootOptions.internalWrites&&t.internalWrites)return t.internalWrites;throw new Error('Could not determine "internalWrites" value ')},throwOnInternalWriteError:t=>t.throwOnInternalWriteError===void 0?this.rootOptions.throwOnInternalWriteError:t.throwOnInternalWriteError,unsafeClient:t=>{if(t.unsafeClient===void 0||this.rootOptions.unsafeClient==t.unsafeClient)return this.rootOptions.unsafeClient;if(this.rootOptions.unsafeClient==="throw"||this.rootOptions.unsafeClient==="skip")return this.rootOptions.unsafeClient;if(this.rootOptions.unsafeClient==="allow")return t.unsafeClient==="throw"?"skip":t.unsafeClient;throw new Error('Could not determine "unsafeClient" value')},ignoreExceptions:t=>{if(t.ignoreExceptions===void 0||this.rootOptions.ignoreExceptions==t.ignoreExceptions)return this.rootOptions.ignoreExceptions;if(this.rootOptions.ignoreExceptions&&!t.ignoreExceptions)return this.rootOptions.ignoreExceptions;if(!this.rootOptions.ignoreExceptions&&t.ignoreExceptions)return this.rootOptions.ignoreExceptions;throw new Error('Could not determine "ignoreExceptions" value')},waitForConfirmation:()=>this.rootOptions.waitForConfirmation,updateCacheForEachInteraction:()=>this.rootOptions.updateCacheForEachInteraction,maxCallDepth:()=>this.rootOptions.maxCallDepth,maxInteractionEvaluationTimeSeconds:()=>this.rootOptions.maxInteractionEvaluationTimeSeconds,stackTrace:()=>this.rootOptions.stackTrace,sourceType:()=>this.rootOptions.sourceType,sequencerUrl:()=>this.rootOptions.sequencerUrl,gasLimit:()=>this.rootOptions.gasLimit,allowBigInt:()=>this.rootOptions.allowBigInt,walletBalanceUrl:()=>this.rootOptions.walletBalanceUrl,mineArLocalBlocks:()=>this.rootOptions.mineArLocalBlocks,cacheEveryNInteractions:()=>this.rootOptions.cacheEveryNInteractions,remoteStateSyncEnabled:()=>this.rootOptions.remoteStateSyncEnabled,remoteStateSyncSource:()=>this.rootOptions.remoteStateSyncSource,useKVStorage:t=>t.useKVStorage,useConstructor:t=>t.useConstructor,whitelistSources:()=>this.rootOptions.whitelistSources};notConflictingEvaluationOptions=["useKVStorage","sourceType","useConstructor"];constructor(t,e){if(e){let r=[];for(let i in e){if(!t.hasOwnProperty(i))throw new Error("Unknown option set in contract's manifest. You probably need to update the Warp SDK version.");let o=i,s=e[i],c=t[i];if(!this.notConflictingEvaluationOptions.includes(o))if(o==="internalWrites"){if(c===!1&&s===!0)throw new Error("Cannot proceed with contract evaluation. User is blocking internal writes, while contract requires them.")}else if(o==="unsafeClient"){if(c==="throw"&&s!=="throw"||c==="skip"&&s==="allow")throw new Error(`Cannot proceed with contract evaluation. User requires to ${c} on any unsafeClient usage, while contract uses ${s} option.`)}else t[i]!==e[i]&&r.push(`Option {${i}} differs. EvaluationOptions: [${t[i]}], manifest: [${e[i]}]. Use contract.setEvaluationOptions({${i}: ${e[i]}}) to evaluate contract state.`)}if(r.length)throw new Error(r.join(` +`))}this.rootOptions=Object.freeze(Object.assign({},t,e||{}))}forForeignContract(t){let e=Vr(this.rootOptions);if(t)for(let r in t)e[r]=this.saferEvaluationOptions[r](t);return Object.freeze(e)}};b();var zo=class{constructor(t){this.warp=t;this.warp=t}name="WarpFetchWrapper";logger=ct.INST.create(this.name);fetch(t,e){let r;if(this.warp.hasPlugin("fetch-options")){let i=this.warp.loadPlugin("fetch-options");try{let o=i.process({input:t,init:e||{}});r={...e,...o}}catch(o){throw o.message&&this.logger.error(o.message),new Error(`Unable to process fetch options: ${o.message}`)}}else r=e;return fetch(t,r)}};b();var RS=new Error("timeout while waiting for mutex to become available"),BS=new Error("mutex already locked"),Ym=new Error("request for lock canceled"),Xm=function(n,t,e,r){function i(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function c(w){try{g(r.next(w))}catch(v){s(v)}}function l(w){try{g(r.throw(w))}catch(v){s(v)}}function g(w){w.done?o(w.value):i(w.value).then(c,l)}g((r=r.apply(n,t||[])).next())})},Ac=class{constructor(t,e=Ym){this._value=t,this._cancelError=e,this._weightedQueues=[],this._weightedWaiters=[]}acquire(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise((e,r)=>{this._weightedQueues[t-1]||(this._weightedQueues[t-1]=[]),this._weightedQueues[t-1].push({resolve:e,reject:r}),this._dispatch()})}runExclusive(t,e=1){return Xm(this,void 0,void 0,function*(){let[r,i]=yield this.acquire(e);try{return yield t(r)}finally{i()}})}waitForUnlock(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise(e=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),this._weightedWaiters[t-1].push(e),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatch()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatch()}cancel(){this._weightedQueues.forEach(t=>t.forEach(e=>e.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var t;for(let e=this._value;e>0;e--){let r=(t=this._weightedQueues[e-1])===null||t===void 0?void 0:t.shift();if(!r)continue;let i=this._value,o=e;this._value-=e,e=this._value+1,r.resolve([i,this._newReleaser(o)])}this._drainUnlockWaiters()}_newReleaser(t){let e=!1;return()=>{e||(e=!0,this.release(t))}}_drainUnlockWaiters(){for(let t=this._value;t>0;t--)this._weightedWaiters[t-1]&&(this._weightedWaiters[t-1].forEach(e=>e()),this._weightedWaiters[t-1]=[])}},Zm=function(n,t,e,r){function i(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function c(w){try{g(r.next(w))}catch(v){s(v)}}function l(w){try{g(r.throw(w))}catch(v){s(v)}}function g(w){w.done?o(w.value):i(w.value).then(c,l)}g((r=r.apply(n,t||[])).next())})},Jo=class{constructor(t){this._semaphore=new Ac(1,t)}acquire(){return Zm(this,void 0,void 0,function*(){let[,t]=yield this._semaphore.acquire();return t})}runExclusive(t){return this._semaphore.runExclusive(()=>t())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};b();b();var Yo=class{cache;capacity;constructor(t){this.cache=new Map,this.capacity=t||10}has(t){return this.cache.has(t)}size(){return this.cache.size}get(t){if(!this.cache.has(t))return null;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}set(t,e){this.cache.delete(t),this.cache.size===this.capacity?(this.cache.delete(this.cache.keys().next().value),this.cache.set(t,e)):this.cache.set(t,e)}keys(){return Array.from(this.cache.keys())}};var mi=class{constructor(t){this._warp=t}_json=new Map;_initialJson=new Map;_kv=new Map;has(t,e){return this._json.get(t)?.has(e)||!1}get(t,e){return this._json.get(t)?.get(e)||null}getLessOrEqual(t,e){let r=this._json.get(t);if(r!=null&&r.size()>0){let i=r.keys();e&&(i=i.filter(s=>s.localeCompare(e)<=0)),i=i.sort((s,c)=>s.localeCompare(c));let o=i[i.length-1];if(r.get(o))return new Ut(o,r.get(o))}return null}async getKV(t,e){return this._kv.has(t)&&(await this._kv.get(t).get(e))?.cachedValue||null}async delKV(t,e){this._kv.has(t)&&await this._kv.get(t).del(e)}getKvKeys(t,e,r){return this._warp.kvStorageFactory(t).keys(e,r)}getKvRange(t,e,r){return this._warp.kvStorageFactory(t).kvMap(e,r)}async commit(t,e=!1){if(t.dry)return await this.rollbackKVs(),this.reset();try{let r=new Map;this._json.forEach((i,o)=>{let s=this.getLessOrEqual(o,t.sortKey);s!=null&&r.set(o,s.cachedValue)}),await this.doStoreJson(r,t,e),await this.commitKVs()}finally{this.reset()}}async commitKV(){await this.commitKVs(),this._kv.clear()}async rollback(t,e){try{await this.doStoreJson(this._initialJson,t,e),await this.rollbackKVs()}finally{this.reset()}}setInitial(t,e,r){this._initialJson.set(t,e),this.update(t,e,r)}update(t,e,r){if(!this._json.has(t)){let i=new Yo(10);this._json.set(t,i)}this._json.get(t).set(r,e)}async updateKV(t,e,r){await(await this.getOrInitKvStorage(t)).put(e,r)}async getOrInitKvStorage(t){if(this._kv.has(t))return this._kv.get(t);let e=this._warp.kvStorageFactory(t);return this._kv.set(t,e),await e.open(),e}reset(){this._json.clear(),this._initialJson.clear(),this._kv.clear()}async doStoreJson(t,e,r=!1){if(t.size>1||r)for(let[i,o]of t)await this._warp.stateEvaluator.putInCache(i,e,o)}async rollbackKVs(){for(let t of this._kv.values())try{await t.rollback()}finally{await t.close()}}async commitKVs(){for(let t of this._kv.values())try{await t.commit()}finally{await t.close()}}};var hh=jt(mr());var Sn=class{constructor(t,e,r=null,i=null){this._contractTxId=t;this.warp=e;this._parentContract=r;this._innerCallData=i;if(this.waitForConfirmation=this.waitForConfirmation.bind(this),this._arweaveWrapper=new ne(e),this._sorter=new yr(e.arweave),r!=null){this._evaluationOptions=this.getRoot().evaluationOptions(),this._callDepth=r.callDepth()+1;let o=r.getCallStack().getInteraction(i.callingInteraction.id);if(this._callDepth>this._evaluationOptions.maxCallDepth)throw new Error(`Max call depth of ${this._evaluationOptions.maxCallDepth} has been exceeded for interaction ${JSON.stringify(o.interactionInput)}`);if(this.logger.debug("Calling interaction",{id:i.callingInteraction.id,sortKey:i.callingInteraction.sortKey,type:i.callType}),o.interactionInput?.foreignContractCalls[t]?.innerCallType==="write"&&i.callType==="read")throw new Error("Calling a readContractState after performing an inner write is wrong - instead use a state from the result of an internal write.");let s=new _n(t,this._callDepth,i?.callType);o.interactionInput.foreignContractCalls[t]=s,this._callStack=s,this._rootSortKey=r.rootSortKey,r._children.push(this)}else this._callDepth=0,this._callStack=new _n(t,0),this._rootSortKey=null,this._evaluationOptions=new yo,this._children=[],this._interactionState=new mi(e);this.getCallStack=this.getCallStack.bind(this),this._warpFetchWrapper=new zo(this.warp)}logger=ct.INST.create("HandlerBasedContract");ecLogger=ct.INST.create("ExecutionContext");_innerWritesEvaluator=new Vo;_callDepth;_arweaveWrapper;_mutex=new Jo;_callStack;_evaluationOptions;_eoEvaluator;_benchmarkStats=null;_sorter;_rootSortKey;_signature;_warpFetchWrapper;_children=[];_interactionState;_dreStates=new Map;async readState(t,e,r){if(this.logger.info("Read state for",{contractTxId:this._contractTxId,sortKeyOrBlockHeight:t}),!this.isRoot()&&t==null)throw new Error("SortKey MUST be always set for non-root contract calls");let{stateEvaluator:i}=this.warp,o=typeof t=="number"?this._sorter.generateLastSortKey(t):t;if(o&&!this.isRoot()&&this.interactionState().has(this.txId(),o)){let c=this.interactionState().get(this.txId(),o);return new Ut(o,c)}let s=await this._mutex.acquire();try{let c=Et.measure();this.maybeResetRootContract();let l=await this.createExecutionContext(this._contractTxId,o,!1,r);this.logger.info("Execution Context",{srcTxId:l.contractDefinition?.srcTxId,missingInteractions:l.sortedInteractions?.length,cachedSortKey:l.cachedState?.sortKey}),c.stop();let g=Et.measure(),w=await i.eval(l);g.stop();let v=c.elapsed(!0)+g.elapsed(!0);return this._benchmarkStats={gatewayCommunication:c.elapsed(!0),stateEvaluation:g.elapsed(!0),total:v},this.logger.info("Benchmark",{"Gateway communication ":c.elapsed(),"Contract evaluation ":g.elapsed(),"Total: ":`${v.toFixed(0)}ms`}),o&&!this.isRoot()&&this.interactionState().update(this.txId(),w.cachedValue,o),w}finally{s()}}async readStateFor(t,e){return this.readState(t,void 0,e)}async viewState(t,e=[],r=Hr,i){return this.logger.info("View state for",this._contractTxId),await this.callContract(t,"view",i,void 0,e,r)}async viewStateForTx(t,e){return this.logger.info(`View state for ${this._contractTxId}`),await this.doApplyInputOnTx(t,e,"view")}async dryWrite(t,e,r,i,o){return this.logger.info("Dry-write for",this._contractTxId),await this.callContract(t,"write",e,void 0,r,i,void 0,o)}async applyInput(t,e){return this.logger.info(`Apply-input from transaction ${e.id} for ${this._contractTxId}`),await this.doApplyInputOnTx(t,e,"write")}async writeInteraction(t,e){if(this.logger.info("Write interaction",{input:t,options:e}),!this._signature)throw new Error("Wallet not connected. Use 'connect' method first.");let{arweave:r,interactionsLoader:i,environment:o}=this.warp;await this.warp.definitionLoader.load(this._contractTxId);let s=e?.tags||[],c=e?.transfer||Hr,l=e?.strict===!0,g=e?.vrf===!0,w=e?.disableBundling===!0,v=e?.reward,E=i.type()=="warp"&&!w;if(this._signature.checkNonArweaveSigningAvailability(E),this._signature.checkBundlerSignerAvailability(E),E&&c.target!=Hr.target&&c.winstonQty!=Hr.winstonQty)throw new Error("Ar Transfers are not allowed for bundled interactions");if(g&&!E&&o==="mainnet")throw new Error("Vrf generation is only available for bundle interaction");if(!t)throw new Error(`Input should be a truthy value: ${JSON.stringify(t)}`);if(E)return await this.bundleInteraction(t,{tags:s,strict:l,vrf:g});{let d=await this.createInteraction(t,s,c,l,!1,g&&o!=="mainnet",v),y=await r.transactions.post(d);if(y.status!==200)return this.logger.error("Error while posting transaction",y),null;if(this._evaluationOptions.waitForConfirmation){this.logger.info("Waiting for confirmation of",d.id);let k=Et.measure();await this.waitForConfirmation(d.id),this.logger.info("Transaction confirmed after",k.elapsed())}return this.warp.environment=="local"&&this._evaluationOptions.mineArLocalBlocks&&await this.warp.testing.mineBlock(),{originalTxId:d.id,interactionTx:d}}}async bundleInteraction(t,e){this.logger.info("Bundle interaction input",t);let r=await this.createInteractionDataItem(t,e.tags,Hr,e.strict,e.vrf),i=this._warpFetchWrapper.fetch(`${Je(this._evaluationOptions.sequencerUrl)}/gateway/v2/sequencer/register`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Accept:"application/json"},body:r.getRaw()}),o=await r.id;return{bundlrResponse:await _e(i),originalTxId:o,interactionTx:r}}async createInteractionDataItem(t,e,r,i,o=!1){this._evaluationOptions.internalWrites&&await this.discoverInternalWrites(t,e,r,i,o),o&&e.push(new Qt(at.REQUEST_VRF,"true"));let s=wc(this._contractTxId,t,this.warp.environment==="testnet",e);if(xc(s))throw new Error("Interaction tags exceed limit of 4096 bytes.");let c=Math.random().toString().slice(-4),l=this._signature.bundlerSigner;if(!l)throw new Error("Signer not set correctly. If you connect wallet through 'use_wallet', please remember that it only works when bundling is disabled.");let g;return fn()&&l.signer?.signDataItem?g=await l.signDataItem(c,s):(g=Ic(c,l,{tags:s}),await g.sign(l)),!this._evaluationOptions.internalWrites&&i&&await this.checkInteractionInStrictMode(g.owner,t,e,r,i,o),g}async createInteraction(t,e,r,i,o=!1,s=!1,c){this._evaluationOptions.internalWrites&&await this.discoverInternalWrites(t,e,r,i,s),s&&e.push(new Qt(at.REQUEST_VRF,"true"));let l=await yc(this.warp.arweave,this._signature.signer,this._contractTxId,t,e,r.target,r.winstonQty,o,this.warp.environment==="testnet",c);return!this._evaluationOptions.internalWrites&&i&&await this.checkInteractionInStrictMode(l.owner,t,e,r,i,s),l}async checkInteractionInStrictMode(t,e,r,i,o,s){let{arweave:c}=this.warp,l=this._signature.type=="arweave"?await c.wallets.ownerToAddress(t):await this._signature.getAddress(),g=await this.callContract(e,"write",l,void 0,r,i,o,s);if(g.type==="error")throw new Ft(g.error);if(g.type!=="ok")throw Error("Cannot create interaction: "+JSON.stringify(g.error||g.errorMessage))}txId(){return this._contractTxId}getCallStack(){return this._callStack}connect(t){return this._signature=new Ho(this.warp,t),this}setEvaluationOptions(t){if(!this.isRoot())throw new Error("Evaluation options can be set only for the root contract");return this._evaluationOptions={...this._evaluationOptions,...t},this}async waitForConfirmation(t){let{arweave:e}=this.warp,r=await e.transactions.getStatus(t);return r.confirmed===null?(this.logger.info(`Transaction ${t} not yet confirmed. Waiting another 20 seconds before next check.`),await go(2e4),this.waitForConfirmation(t)):(this.logger.info(`Transaction ${t} confirmed`,r),r)}async createExecutionContext(t,e,r=!1,i){let{definitionLoader:o,interactionsLoader:s,stateEvaluator:c}=this.warp,l,g=Et.measure();this.isRoot()||(l=this.interactionState().getLessOrEqual(this.txId(),e)),l=l||await c.latestAvailableState(t,e),this.logger.debug("cache lookup",g.elapsed()),g.reset();let w=Xe.evolvedSrcTxId(l?.cachedValue?.state),v,E,d,y,k=i||[];if(this.logger.debug("Cached state",l,e),l&&l.sortKey==e)this.logger.debug("State fully cached, not loading interactions."),(r||w||i?.length)&&(E=await o.load(t,w),i?.length&&(k=(await this._sorter.sort(i.map(N=>({node:N,cursor:null})))).map(N=>N.node)));else{if(i?.length)throw new Error(`Cannot apply requested interactions at ${e}`);if(E=await o.load(t,w),d=this.resolveEvaluationOptions(E.manifest?.evaluationOptions),d.remoteStateSyncEnabled&&!d.useKVStorage){y=await this.getRemoteContractState(t),l=await this.maybeSyncStateWithRemoteSource(y,e,l);let N=Xe.evolvedSrcTxId(l?.cachedValue?.state);N&&N!==E.srcTxId&&(E=await o.load(t,N))}this.warp.executorFactory.checkWhiteListContractSources(E,d),!y&&k.length==0&&(k=await s.load(t,l?.sortKey,this.getToSortKey(e),d)),l?.sortKey&&(k=k.filter(N=>N.sortKey.localeCompare(l?.sortKey)>0)),e&&(k=k.filter(N=>N.sortKey.localeCompare(e)<=0)),this.logger.debug("contract and interactions load",g.elapsed()),this.isRoot()&&k.length&&(this._rootSortKey=k[k.length-1].sortKey)}return E&&(d||(d=this.resolveEvaluationOptions(E.manifest?.evaluationOptions)),this.ecLogger.debug(`Evaluation options ${t}:`,d),v=await this.warp.executorFactory.create(E,d,this.warp,this.interactionState())),{warp:this.warp,contract:this,contractDefinition:E,sortedInteractions:k,evaluationOptions:d||this.evaluationOptions(),handler:v,cachedState:l,requestedSortKey:e}}resolveEvaluationOptions(t){return this.isRoot()?(this._eoEvaluator=new Qo(this.evaluationOptions(),t),this._eoEvaluator.rootOptions):this.getRootEoEvaluator().forForeignContract(t)}async getRemoteContractState(t){if(this.hasDreState(t))return this.getDreState(t);{let e=await this.fetchRemoteContractState(t);return e!=null?this.setDREState(t,e):null}}async fetchRemoteContractState(t){return _e(this._warpFetchWrapper.fetch(`${this._evaluationOptions.remoteStateSyncSource}?id=${t}&events=false`))}getToSortKey(t){return this._parentContract?.rootSortKey?t?this._parentContract.rootSortKey.localeCompare(t)>0?this._parentContract.rootSortKey:t:this._parentContract.rootSortKey:t}async createExecutionContextFromTx(t,e){let r=e.owner.address,i=e.sortKey;return{...await this.createExecutionContext(t,i,!0),caller:r}}maybeResetRootContract(){this.isRoot()&&(this.logger.debug("Clearing call stack for the root contract"),this._callStack=new _n(this.txId(),0),this._rootSortKey=null,this.warp.interactionsLoader.clearCache(),this._children=[],this._interactionState=new mi(this.warp),this._dreStates=new Map)}async callContract(t,e,r,i,o=[],s=Hr,c=!1,l=!1,g=!0){this.logger.info("Call contract input",t),this.maybeResetRootContract(),this._signature||this.logger.warn("Wallet not set.");let{arweave:w,stateEvaluator:v}=this.warp,E=await this.createExecutionContext(this._contractTxId,i,!0),d=this.warp.environment=="mainnet"?await this._arweaveWrapper.warpGwBlock():await w.blocks.getCurrent(),y;r?y=r:this._signature?y=await this._signature.getAddress():y="",this.logger.info("effectiveCaller",y),E={...E,caller:y};let k=await v.eval(E);this.logger.info("Current state",k.cachedValue.state);let N={input:t,caller:E.caller,interactionType:e};this.logger.debug("interaction",N);let q=await yc(w,g?this._signature?.signer:void 0,this._contractTxId,t,o,s.target,s.winstonQty,!0,this.warp.environment==="testnet"),Q=rh(q,E.caller,d);if(this.logger.debug("Creating sortKey for",{blockId:Q.block.id,id:Q.id,height:Q.block.height}),Q.sortKey=await this._sorter.createSortKey(Q.block.id,Q.id,Q.block.height,!0),Q.strict=c,l){let X=this.warp.maybeLoadPlugin("vrf");X?Q.vrf=X.process().generateMockVrf(Q.sortKey):this.logger.warn('Cannot generate mock vrf for interaction - no "warp-contracts-plugin-vrf" attached!')}let z=await this.evalInteraction({interaction:N,interactionTx:Q},E,k.cachedValue);return z.type!=="ok"&&this.logger.fatal("Error while interacting with contract",{type:z.type,error:z.errorMessage}),z}async doApplyInputOnTx(t,e,r){this.maybeResetRootContract();let i,o=await this.createExecutionContextFromTx(this._contractTxId,e);!this.isRoot()&&this.interactionState().has(this.txId(),e.sortKey)?i=new Ut(e.sortKey,this.interactionState().get(this.txId(),e.sortKey)):(i=await this.warp.stateEvaluator.eval(o),this.interactionState().update(this.txId(),i.cachedValue,e.sortKey)),this.logger.debug("callContractForTx - evalStateResult",{result:i.cachedValue.state,txId:this._contractTxId});let c={interaction:{input:t,caller:this._parentContract.txId(),interactionType:r},interactionTx:e},l=await this.evalInteraction(c,o,i.cachedValue);return l.originalValidity=i.cachedValue.validity,l.originalErrorMessages=i.cachedValue.errorMessages,l}async evalInteraction(t,e,r){let i=this.getCallStack().addInteractionData(t),o=Et.measure();await e.handler.initState(r.state);let s=await e.handler.handle(e,r,t);return i.update({cacheHit:!1,outputState:this._evaluationOptions.stackTrace.saveState?s.state:void 0,executionTime:o.elapsed(!0),valid:s.type==="ok",errorMessage:s.errorMessage,gasUsed:s.gasUsed}),s}parent(){return this._parentContract}callDepth(){return this._callDepth}evaluationOptions(){return this._evaluationOptions}lastReadStateStats(){return this._benchmarkStats}async stateHash(t){let e=eh(t),r=await hh.Crypto.subtle.digest("SHA-256",F.Buffer.from(e,"utf-8"));return F.Buffer.from(r).toString("hex")}async syncState(t,e){let{stateEvaluator:r}=this.warp,i=await this._warpFetchWrapper.fetch(`${t}?${new URLSearchParams({id:this._contractTxId,...e})}`).then(o=>o.ok?o.json():Promise.reject(o)).catch(o=>{throw o.body?.message&&this.logger.error(o.body.message),new Error(`Unable to retrieve state. ${o.status}: ${o.body?.message}`)});return await r.syncState(this._contractTxId,i.sortKey,i.state,i.validity),this}async evolve(t,e){return await this.writeInteraction({function:"evolve",value:t},e)}get rootSortKey(){return this._rootSortKey}getRootEoEvaluator(){return this.getRoot()._eoEvaluator}isRoot(){return this._parentContract==null}async getStorageValues(t){let e=await this.warp.stateEvaluator.getCache().getLast(this.txId());if(e==null)return new Ut(null,new Map);let r=this.warp.kvStorageFactory(this.txId()),i=new Map;try{await r.open();for(let o of t){let s=await r.getLessOrEqual(o,e.sortKey);i.set(o,s==null?null:s.cachedValue)}return new Ut(e.sortKey,i)}finally{await r.close()}}interactionState(){return this.getRoot()._interactionState}getRoot(){let t=this;for(;!t.isRoot();)t=t.parent();return t}async maybeSyncStateWithRemoteSource(t,e,r){let{stateEvaluator:i}=this.warp;return this.isStateHigherThanAndUpTo(t,r?.sortKey,e)?await i.syncState(this._contractTxId,t.sortKey,t.cachedValue.state,t.cachedValue.validity):r}isStateHigherThanAndUpTo(t,e,r){return t&&(!r||r>=t.sortKey)&&(!e||t.sortKey>e)}setDREState(t,e){let r=new Ut(e.sortKey,new $t(e.state,{},e.errorMessages));return this.getRoot()._dreStates.set(t,r),r}getDreState(t){return this.getRoot()._dreStates.get(t)}hasDreState(t){return this.getRoot()._dreStates.has(t)}async discoverInternalWrites(t,e,r,i,o){let s=await this.callContract(t,"write",void 0,void 0,e,r,i,o,!1);if(i){if(s.type==="error")throw new Ft(s.error);if(s.type!=="ok")throw Error("Cannot create interaction: "+JSON.stringify(s.error||s.errorMessage))}let c=this.getCallStack(),l=this._innerWritesEvaluator.eval(c);this.logger.debug("Input",t),this.logger.debug("Callstack",c.print()),l.forEach(g=>{e.push(new Qt(at.INTERACT_WRITE,g))}),this.logger.debug("Tags with inner calls",e)}clearChildren(){for(let t of this._children)t.clearChildren();this._children=[]}};b();var Xo=class extends Sn{async currentBalance(t){let e=await this.viewState({function:"balance",target:t});if(e.type!=="ok")throw Error(e.errorMessage);return e.result}async currentState(){return(await super.readState()).cachedValue.state}async transfer(t,e){return await this.writeInteraction({function:"transfer",...t},e)}};b();var Zo=class{constructor(t){this.arweave=t}async mineBlock(){this.validateEnv(),await this.arweave.api.get("mine")}async addFunds(t){let e=await this.arweave.wallets.getAddress(t);await this.arweave.api.get(`/mint/${e}/1000000000000000`)}async isArlocal(){return(await fetch(`${this.arweave.api.config.protocol}://${this.arweave.api.config.host}:${this.arweave.api.config.port}/info`).then(e=>e.ok?e.json():Promise.reject()).catch(e=>{throw new Error(`Unable to get network info: ${e.message}`)})).network.includes("arlocal")}async validateEnv(){if(!await this.isArlocal())throw new Error("Testing features are not available in a non testing environment")}};b();b();var ts=class{constructor(t,e){this.baseImplementation=t;this.sourceCode=e}async create(t,e,r,i){return Object.prototype.hasOwnProperty.call(this.sourceCode,t.txId)&&(t={...t,src:this.sourceCode[t.txId]}),await this.baseImplementation.create(t,e,r,i)}checkWhiteListContractSources(t,e){return this.baseImplementation.checkWhiteListContractSources(t,e)}};var es=class{constructor(t,e,r="custom"){this._arweave=t;this._stateCache=e;this._environment=r}_definitionLoader;_interactionsLoader;_executorFactory;_stateEvaluator;setDefinitionLoader(t){return this._definitionLoader=t,this}setInteractionsLoader(t){return this._interactionsLoader=t,this}setExecutorFactory(t){return this._executorFactory=t,this}setStateEvaluator(t){return this._stateEvaluator=t,this}overwriteSource(t){if(this._executorFactory==null)throw new Error("Set base ExecutorFactory first");return this._executorFactory=new ts(this._executorFactory,t),this.build()}useWarpGateway(t,e){this._interactionsLoader=new gi(new mo(t.confirmationStatus,t.source));let r=new Qe({...e,dbLocation:`${e.dbLocation}/contracts`}),i=new Qe({...e,dbLocation:`${e.dbLocation}/source`});return this._definitionLoader=new Wo(this._arweave,r,i,this._environment),this}useArweaveGateway(){return this._definitionLoader=new vn(this._arweave,this._environment),this._interactionsLoader=new gi(new Do(this._arweave,this._environment)),this}build(){let t=new En(this._arweave,this._definitionLoader,this._interactionsLoader,this._executorFactory,this._stateEvaluator,this._environment);return this._definitionLoader.warp=t,this._interactionsLoader.warp=t,t}};b();var gh=["^smartweave-extension-"],dh=["evm-signature-verification","subscription","ivm-handler-api","evaluation-progress","fetch-options","deploy","contract-blacklist","vm2","vrf"];var En=class{constructor(t,e,r,i,o,s="custom"){this.arweave=t;this.definitionLoader=e;this.interactionsLoader=r;this.executorFactory=i;this.stateEvaluator=o;this.environment=s;this.testing=new Zo(t),this.kvStorageFactory=c=>new Qe({inMemory:!1,dbLocation:`${kc}/kv/ldb/${c}`}),this.eventTarget=new EventTarget}_createContract;_gwUrl=ph;get createContract(){if(!this._createContract)if(this.plugins.has("deploy")){let t=this.loadPlugin("deploy");this._createContract=t.process(this)}else throw new Error("In order to use CreateContract methods please attach DeployPlugin.");return this._createContract}testing;kvStorageFactory;whoAmI;eventTarget;plugins=new Map;static builder(t,e,r){return new es(t,e,r)}contract(t,e,r){return new Sn(t,this,e,r)}async deploy(t,e){return await this.createContract.deploy(t,e)}async deployFromSourceTx(t,e){return await this.createContract.deployFromSourceTx(t,e)}async deployBundled(t){return await this.createContract.deployBundled(t)}async register(t,e){return await this.createContract.register(t,e)}async createSource(t,e,r=!1){return await this.createContract.createSource(t,e,r)}async saveSource(t,e){return await this.createContract.saveSource(t,e)}pst(t){return new Xo(t,this)}useStateCache(t){return this.stateEvaluator.setCache(t),this}useContractCache(t,e){return this.definitionLoader.setSrcCache(e),this.definitionLoader.setCache(t),this}use(t){let e=t.type();if(!this.isPluginType(e))throw new Error(`Unknown plugin type ${e}.`);return this.plugins.set(e,t),this}hasPlugin(t){return this.plugins.has(t)}matchPlugins(t){return[...this.plugins.keys()].filter(r=>r.match(t))}loadPlugin(t){if(!this.hasPlugin(t))throw new Error(`Plugin ${t} not registered.`);return this.plugins.get(t)}maybeLoadPlugin(t){return this.hasPlugin(t)?this.plugins.get(t):null}async close(){return Promise.all([this.definitionLoader.getSrcCache().close(),this.definitionLoader.getCache().close(),this.stateEvaluator.getCache().close()]).then()}async generateWallet(){let t=await this.arweave.wallets.generate();return await this.testing.isArlocal()&&await this.testing.addFunds(t),{jwk:t,address:await this.arweave.wallets.jwkToAddress(t)}}isPluginType(t){return dh.includes(t)||gh.some(e=>t.match(e))}useKVStorageFactory(t){return this.kvStorageFactory=t,this}useGwUrl(t){return this._gwUrl=t,this}gwUrl(){return this._gwUrl}};var Lc={confirmationStatus:{notCorrupted:!0},source:"both"},ph="https://gw.warp.cc",kc="./cache/warp",yi={inMemory:!1,dbLocation:kc},mh=class{static forLocal(t=1984,e=rs.default.init({host:"localhost",port:t,protocol:"http"}),r={...yi,inMemory:!0}){return this.customArweaveGw(e,r,"local")}static forTestnet(t=yi,e=!1,r=rs.default.init({host:"arweave.net",port:443,protocol:"https"})){return e?this.customArweaveGw(r,t,"testnet"):this.customWarpGw(r,Lc,t,"testnet")}static forMainnet(t=yi,e=!1,r=rs.default.init({host:"arweave.net",port:443,protocol:"https"})){return e?this.customArweaveGw(r,t,"mainnet"):this.customWarpGw(r,Lc,t,"mainnet")}static custom(t,e,r){let i=new Qe({...e,dbLocation:`${e.dbLocation}/state`}),o=new fo(t),s=new Fo(t,i,[new Xe]);return En.builder(t,i,r).setExecutorFactory(o).setStateEvaluator(s)}static customArweaveGw(t,e=yi,r){return this.custom(t,e,r).useArweaveGateway().build()}static customWarpGw(t,e=Lc,r=yi,i){return this.custom(t,r,i).useWarpGateway(e,r).build()}};b();function mT(n){let t=/(const|var) ret = makeMutClosure\(arg0, arg1, (\d+?), __wbg_adapter/;return n.match(t)[2]}b();var yh=jt(Oo());function fe(n,t,e=void 0){let r=n.find(({name:i})=>i===t);return r?r.value:e}var ns=class{constructor(t){this.env=t}arweaveWrapper;arweaveTransactions;logger=ct.INST.create(ns.name);async load(t,e){let r=Et.measure(),i=await this.fetchContractTx(t);this.logger.debug("Contract tx fetch time",r.elapsed());let o=i.owner.address,s=e||fe(i.tags,Ct.CONTRACT_SRC_TX_ID),c=fe(i.tags,at.WARP_TESTNET)||null;if(c&&this.env!=="testnet")throw new Error('Trying to use testnet contract in a non-testnet env. Use the "forTestnet" factory method.');if(!c&&this.env==="testnet")throw new Error("Trying to use non-testnet contract in a testnet env.");let l=fe(i.tags,Ct.MIN_FEE),g=fe(i.tags,at.MANIFEST)?JSON.parse(fe(i.tags,at.MANIFEST)):null;this.logger.debug("Tags decoding",r.elapsed());let w=await this.evalInitialState(i);this.logger.debug("init state",w);let v=JSON.parse(w);this.logger.debug("Parsing src and init state",r.elapsed());let{src:E,srcBinary:d,srcWasmLang:y,contractType:k,metadata:N,srcTx:q}=await this.loadContractSource(s),Q={txId:t,srcTxId:s,src:E,srcBinary:d,srcWasmLang:y,initState:v,minFee:l,owner:o,contractType:k,metadata:N,manifest:g,contractTx:await this.convertToWarpCompatibleContractTx(i),srcTx:await this.convertToWarpCompatibleContractTx(q),testnet:c};return this.logger.info(`Contract definition loaded in: ${r.elapsed()}`),Q}async fetchContractTx(t){let e=await this.arweaveTransactions.transaction(t);return e??await this.arweaveTransactions.transactionUsingUploaderTag(t)}async convertToWarpCompatibleContractTx(t){return{tags:t.tags.map(({name:r,value:i})=>({name:F.Buffer.from(r).toString("base64url"),value:F.Buffer.from(i).toString("base64url")})),owner:t.owner.key,target:t.recipient,signature:t.signature,data:(await this.arweaveWrapper.txData(t.id)).toString("base64url")}}async loadContractSource(t){let e=Et.measure(),r=await this.fetchContractTx(t),i=fe(r.tags,Ct.CONTENT_TYPE);if(!bo.includes(i))throw new Error(`Contract source content type ${i} not supported`);let o=i==="application/javascript"?"js":"wasm",s=await this.contractSource(r,o),c,l,g;if(o=="wasm"){if(l=new _r(s),c=fe(r.tags,at.WASM_LANG),!c)throw new Error(`Wasm lang not set for wasm contract src ${r.id}`);g=JSON.parse(fe(r.tags,at.WASM_META))}return this.logger.debug("Contract src tx load",e.elapsed()),e.reset(),{src:o=="js"?s:null,srcBinary:o=="wasm"?l.wasmBinary():null,srcWasmLang:c,contractType:o,metadata:g,srcTx:r}}async contractSource(t,e){if(fe(t.tags,at.UPLOADER_TX_ID)!=null){let i=await this.arweaveWrapper.txDataString(t.id);if(e==="wasm")throw new Error("WASM contracts in legacy format are not supported using AR GW");return yh.default.utils.b64UrlToString(JSON.parse(i).data)}return e==="js"?await this.arweaveWrapper.txDataString(t.id):await this.arweaveWrapper.txData(t.id)}async evalInitialState(t){if(fe(t.tags,at.INIT_STATE))return fe(t.tags,at.INIT_STATE);if(fe(t.tags,at.INIT_STATE_TX)){let e=fe(t.tags,at.INIT_STATE_TX);return this.arweaveWrapper.txDataString(e)}else return this.arweaveWrapper.txDataString(t.id)}setCache(){throw new Error("Method not implemented.")}setSrcCache(){throw new Error("Method not implemented.")}getCache(){throw new Error("Method not implemented.")}getSrcCache(){throw new Error("Method not implemented.")}type(){return"arweave"}set warp(t){this.arweaveWrapper=new ne(t),this.arweaveTransactions=new Pe(t)}};b();var wh=100,ty=100,vh=1057409,wi=class{constructor(t,e){this.arweave=t;this.environment=e;this.sorter=new yr(t)}logger=ct.INST.create(wi.name);arweaveFetcher;arweaveWrapper;_warp;sorter;tagsParser=new zt;async load(t,e,r,i){this.logger.debug("Loading interactions for",{contractId:t,fromSortKey:e,toSortKey:r});let o=this.sorter.extractBlockHeight(e)||0,s=this.sorter.extractBlockHeight(r)||await this.currentBlockHeight(),c={tags:[{name:Ct.APP_NAME,values:["SmartWeaveAction"]},{name:Ct.CONTRACT_TX_ID,values:[t]},{name:at.SEQUENCER,values:["RedStone"]}],blockFilter:{min:o,max:s+ty},first:wh},l=Et.measure(),g=await this.arweaveFetcher.transactions(c);i.internalWrites&&(g=await this.appendInternalWriteInteractions(t,o,s,g)),l.stop(),this.logger.debug("All loaded interactions:",{from:e,to:r,loaded:g.length,time:l.elapsed()}),g.forEach(d=>{d.node.sortKey=d.node.sortKey??d.node?.tags?.find(y=>y.name===at.SEQUENCER_SORT_KEY)?.value});let w=await this.sorter.sort(g),v=this.environment==="local"||this.environment==="testnet",E=this._warp.maybeLoadPlugin("vrf");return w.filter(d=>this.isNewerThenSortKeyBlockHeight(d)).filter(d=>this.isSortKeyInBounds(e,r,d)).map(d=>this.attachSequencerDataToInteraction(d)).map(d=>this.maybeAddMockVrf(v,d,E)).map((d,y,k)=>this.verifySortKeyIntegrity(d,y,k)).map(({node:d})=>d)}verifySortKeyIntegrity(t,e,r){if(e!==0){let i=r[e-1],o=r[e];if(this.logger.debug(`prev: ${i.node.id} | current: ${o.node.id}`),o.node.block.height<=vh||o.node.lastSortKey?.split(",")[1]===Sa)return t;i.node.source==="redstone-sequencer"&&i.node.sortKey!==o.node.lastSortKey&&this.logger.warn(`Interaction loading error: interaction ${o.node.id} lastSortKey is not pointing on prev interaction ${i.node.id}`)}return t}isSortKeyInBounds(t,e,r){return t&&e?r.node.sortKey.localeCompare(t)>0&&r.node.sortKey.localeCompare(e)<=0:t&&!e?r.node.sortKey.localeCompare(t)>0:!t&&e?r.node.sortKey.localeCompare(e)<=0:!0}attachSequencerDataToInteraction(t){let e=v=>t.node.tags.find(E=>E.name===v)?.value,r=e(at.SEQUENCER_TX_ID),i=e(at.SEQUENCER_OWNER),o=e(at.SEQUENCER_BLOCK_ID),s=e(at.SEQUENCER_BLOCK_HEIGHT),c=e(at.SEQUENCER_PREV_SORT_KEY)||e(at.SEQUENCER_LAST_SORT_KEY),l=e(at.SEQUENCER_SORT_KEY),g=e(at.SEQUENCER_BLOCK_TIMESTAMP),w=po(s);if(!i||!o||!s||!c&&w>vh||!r||!l)throw Error(`Interaction ${t.node.id} is not sequenced by sequencer aborting. Only Sequenced transactions are supported by loader ${wi.name}`);return{...t,node:{...t.node,owner:{address:i,key:null},block:{...t.node.block,height:po(s),id:o,timestamp:g?po(g):t.node.block.timestamp},sortKey:l,lastSortKey:c,id:r,source:"redstone-sequencer"}}}async appendInternalWriteInteractions(t,e,r,i){let o={tags:[{name:at.INTERACT_WRITE,values:[t]}],blockFilter:{min:e,max:r},first:wh},s=await this.arweaveFetcher.transactions(o);return this.logger.debug("Inner writes interactions length:",s.length),i=i.concat(s),i}maybeAddMockVrf(t,e,r){return t&&this.tagsParser.hasVrfTag(e.node)&&(r?e.node.vrf=r.process().generateMockVrf(e.node.sortKey):this.logger.warn('Cannot generate mock vrf for interaction - no "warp-contracts-plugin-vrf" attached!')),e}isNewerThenSortKeyBlockHeight(t){if(t.node.sortKey){let e=t.node.sortKey.split(",")[0],r=Number.parseInt(e);return Number(t.node.block.height)-r>=0}return!0}async currentBlockHeight(){return(await this.arweaveWrapper.info()).height}type(){return"arweave"}clearCache(){}set warp(t){this.arweaveWrapper=new ne(t),this.arweaveFetcher=new Pe(t),this._warp=t}};export{ln as AbstractContractHandler,ns as ArweaveGatewayBundledContractDefinitionLoader,wi as ArweaveGatewayBundledInteractionLoader,Do as ArweaveGatewayInteractionsLoader,ne as ArweaveWrapper,Et as Benchmark,Jt as CacheKey,gi as CacheableInteractionsLoader,Fo as CacheableStateEvaluator,Ei as ConsoleLogger,Ti as ConsoleLoggerFactory,_o as ContractCache,_n as ContractCallRecord,vn as ContractDefinitionLoader,Ft as ContractError,Vl as ContractMetadata,wo as CustomEvent,kc as DEFAULT_LEVEL_DB_LOCATION,yo as DefaultEvaluationOptions,Mo as DefaultStateEvaluator,$t as EvalStateResult,Qo as EvaluationOptionsEvaluator,Sn as HandlerBasedContract,fo as HandlerExecutorFactory,Vo as InnerWritesEvaluator,di as InteractionCall,Kl as InteractionCompleteEvent,uc as InteractionInput,jf as InteractionOutput,ho as JsHandlerApi,wa as KV,Dl as KnownErrors,Qe as LevelDbCache,yr as LexicographicalInteractionsSorter,ag as LogLevelOrder,ct as LoggerFactory,bl as MemCache,ze as NetworkCommunicationError,Hn as NonWhitelistedSourceError,Xo as PstContractImpl,cS as REGISTER_PROVIDER,Ct as SMART_WEAVE_TAGS,bo as SUPPORTED_SRC_CONTENT_TYPES,qn as SWBlock,Gn as SWTransaction,jn as SWVrf,Ho as Signature,$o as SmartWeaveError,Qf as SmartWeaveErrorType,co as SmartWeaveGlobal,Ut as SortKeyCacheResult,up as SourceType,vo as SrcCache,Qt as Tag,zt as TagsParser,mn as Transaction,ph as WARP_GW_URL,at as WARP_TAGS,En as Warp,es as WarpBuilder,mh as WarpFactory,zo as WarpFetchWrapper,Wo as WarpGatewayContractDefinitionLoader,mo as WarpGatewayInteractionsLoader,uo as WasmHandlerApi,_r as WasmSrc,Ml as arrayToHex,av as asc,cv as ascS,fv as bufToBn,qf as bundledTxsFilter,x0 as checkJsSrc,rh as createDummyTx,wc as createInteractionTagsList,yc as createInteractionTx,Vr as deepCopy,Sa as defaultArweaveMs,yi as defaultCacheOptions,Lc as defaultWarpGwOptions,uv as desc,lv as descS,Hr as emptyTransfer,Qn as genesisSortKey,_e as getJsonResponse,Be as indent,fn as isBrowser,dh as knownWarpPlugins,gh as knownWarpPluginsPartial,G0 as lastPossibleSortKey,ys as lvlToOrder,ov as mapReplacer,sv as mapReviver,mT as matchMutClosureDtor,va as normalizeContractSource,Pl as rustWasmImports,Bl as safeGet,po as safeParseInt,go as sleep,cp as sortingFirst,Fl as sortingLast,Je as stripTrailingSlash,$l as timeout}; +/*! Bundled license information: + +ieee754/index.js: + (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) + +buffer/index.js: + (*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + *) + +queue-microtask/index.js: + (*! queue-microtask. MIT License. Feross Aboukhadijeh *) + +run-parallel-limit/index.js: + (*! run-parallel-limit. MIT License. Feross Aboukhadijeh *) + +warp-arbundles/build/web/esm/bundle.js: + (*! Bundled license information: + + ieee754/index.js: + (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) + + buffer/index.js: + (*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + *) + *) +*/ diff --git a/bundles/web.iife.bundle.min.js b/bundles/web.iife.bundle.min.js new file mode 100644 index 00000000..f3aebca1 --- /dev/null +++ b/bundles/web.iife.bundle.min.js @@ -0,0 +1,142 @@ +var warp=(()=>{var Th=Object.create;var Bn=Object.defineProperty;var xh=Object.getOwnPropertyDescriptor;var Ch=Object.getOwnPropertyNames;var Ih=Object.getPrototypeOf,Ah=Object.prototype.hasOwnProperty;var kh=(n,t,e)=>t in n?Bn(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var Lh=(n,t)=>()=>(n&&(t=n(n=0)),t);var nt=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),Oh=(n,t)=>{for(var e in t)Bn(n,e,{get:t[e],enumerable:!0})},Qc=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ch(t))!Ah.call(n,i)&&i!==e&&Bn(n,i,{get:()=>t[i],enumerable:!(r=xh(t,i))||r.enumerable});return n};var Qt=(n,t,e)=>(e=n!=null?Th(Ih(n)):{},Qc(t||!n||!n.__esModule?Bn(e,"default",{value:n,enumerable:!0}):e,n)),Rh=n=>Qc(Bn({},"__esModule",{value:!0}),n);var or=(n,t,e)=>(kh(n,typeof t!="symbol"?t+"":t,e),e);var ps=nt(ji=>{"use strict";b();ji.byteLength=Ph;ji.toByteArray=Uh;ji.fromByteArray=Mh;var xe=[],he=[],Bh=typeof Uint8Array<"u"?Uint8Array:Array,ds="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Cr=0,zc=ds.length;Cr0)throw new Error("Invalid string. Length must be a multiple of 4");var e=n.indexOf("=");e===-1&&(e=t);var r=e===t?0:4-e%4;return[e,r]}function Ph(n){var t=Jc(n),e=t[0],r=t[1];return(e+r)*3/4-r}function Nh(n,t,e){return(t+e)*3/4-e}function Uh(n){var t,e=Jc(n),r=e[0],i=e[1],o=new Bh(Nh(n,r,i)),s=0,c=i>0?r-4:r,l;for(l=0;l>16&255,o[s++]=t>>8&255,o[s++]=t&255;return i===2&&(t=he[n.charCodeAt(l)]<<2|he[n.charCodeAt(l+1)]>>4,o[s++]=t&255),i===1&&(t=he[n.charCodeAt(l)]<<10|he[n.charCodeAt(l+1)]<<4|he[n.charCodeAt(l+2)]>>2,o[s++]=t>>8&255,o[s++]=t&255),o}function Wh(n){return xe[n>>18&63]+xe[n>>12&63]+xe[n>>6&63]+xe[n&63]}function Dh(n,t,e){for(var r,i=[],o=t;oc?c:s+o));return r===1?(t=n[e-1],i.push(xe[t>>2]+xe[t<<4&63]+"==")):r===2&&(t=(n[e-2]<<8)+n[e-1],i.push(xe[t>>10]+xe[t>>4&63]+xe[t<<2&63]+"=")),i.join("")}});var Yc=nt(ms=>{b();ms.read=function(n,t,e,r,i){var o,s,c=i*8-r-1,l=(1<>1,w=-7,v=e?i-1:0,E=e?-1:1,d=n[t+v];for(v+=E,o=d&(1<<-w)-1,d>>=-w,w+=c;w>0;o=o*256+n[t+v],v+=E,w-=8);for(s=o&(1<<-w)-1,o>>=-w,w+=r;w>0;s=s*256+n[t+v],v+=E,w-=8);if(o===0)o=1-g;else{if(o===l)return s?NaN:(d?-1:1)*(1/0);s=s+Math.pow(2,r),o=o-g}return(d?-1:1)*s*Math.pow(2,o-r)};ms.write=function(n,t,e,r,i,o){var s,c,l,g=o*8-i-1,w=(1<>1,E=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,y=r?1:-1,k=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,s=w):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+v>=1?t+=E/l:t+=E*Math.pow(2,1-v),t*l>=2&&(s++,l/=2),s+v>=w?(c=0,s=w):s+v>=1?(c=(t*l-1)*Math.pow(2,i),s=s+v):(c=t*Math.pow(2,v-1)*Math.pow(2,i),s=0));i>=8;n[e+d]=c&255,d+=y,c/=256,i-=8);for(s=s<0;n[e+d]=s&255,d+=y,s/=256,g-=8);n[e+d-y]|=k*128}});var Ar=nt(nn=>{"use strict";b();var ys=ps(),rn=Yc(),Xc=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;nn.Buffer=V;nn.SlowBuffer=qh;nn.INSPECT_MAX_BYTES=50;var Hi=2147483647;nn.kMaxLength=Hi;V.TYPED_ARRAY_SUPPORT=Fh();!V.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Fh(){try{var n=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(n,t),n.foo()===42}catch{return!1}}Object.defineProperty(V.prototype,"parent",{enumerable:!0,get:function(){if(V.isBuffer(this))return this.buffer}});Object.defineProperty(V.prototype,"offset",{enumerable:!0,get:function(){if(V.isBuffer(this))return this.byteOffset}});function Fe(n){if(n>Hi)throw new RangeError('The value "'+n+'" is invalid for option "size"');var t=new Uint8Array(n);return Object.setPrototypeOf(t,V.prototype),t}function V(n,t,e){if(typeof n=="number"){if(typeof t=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return bs(n)}return eu(n,t,e)}V.poolSize=8192;function eu(n,t,e){if(typeof n=="string")return Kh(n,t);if(ArrayBuffer.isView(n))return Vh(n);if(n==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n);if(Ce(n,ArrayBuffer)||n&&Ce(n.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ce(n,SharedArrayBuffer)||n&&Ce(n.buffer,SharedArrayBuffer)))return vs(n,t,e);if(typeof n=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var r=n.valueOf&&n.valueOf();if(r!=null&&r!==n)return V.from(r,t,e);var i=Gh(n);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof n[Symbol.toPrimitive]=="function")return V.from(n[Symbol.toPrimitive]("string"),t,e);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n)}V.from=function(n,t,e){return eu(n,t,e)};Object.setPrototypeOf(V.prototype,Uint8Array.prototype);Object.setPrototypeOf(V,Uint8Array);function ru(n){if(typeof n!="number")throw new TypeError('"size" argument must be of type number');if(n<0)throw new RangeError('The value "'+n+'" is invalid for option "size"')}function $h(n,t,e){return ru(n),n<=0?Fe(n):t!==void 0?typeof e=="string"?Fe(n).fill(t,e):Fe(n).fill(t):Fe(n)}V.alloc=function(n,t,e){return $h(n,t,e)};function bs(n){return ru(n),Fe(n<0?0:Ss(n)|0)}V.allocUnsafe=function(n){return bs(n)};V.allocUnsafeSlow=function(n){return bs(n)};function Kh(n,t){if((typeof t!="string"||t==="")&&(t="utf8"),!V.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var e=nu(n,t)|0,r=Fe(e),i=r.write(n,t);return i!==e&&(r=r.slice(0,i)),r}function ws(n){for(var t=n.length<0?0:Ss(n.length)|0,e=Fe(t),r=0;r=Hi)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Hi.toString(16)+" bytes");return n|0}function qh(n){return+n!=n&&(n=0),V.alloc(+n)}V.isBuffer=function(t){return t!=null&&t._isBuffer===!0&&t!==V.prototype};V.compare=function(t,e){if(Ce(t,Uint8Array)&&(t=V.from(t,t.offset,t.byteLength)),Ce(e,Uint8Array)&&(e=V.from(e,e.offset,e.byteLength)),!V.isBuffer(t)||!V.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;for(var r=t.length,i=e.length,o=0,s=Math.min(r,i);oi.length?V.from(s).copy(i,o):Uint8Array.prototype.set.call(i,s,o);else if(V.isBuffer(s))s.copy(i,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return i};function nu(n,t){if(V.isBuffer(n))return n.length;if(ArrayBuffer.isView(n)||Ce(n,ArrayBuffer))return n.byteLength;if(typeof n!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof n);var e=n.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&e===0)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":return _s(n).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return e*2;case"hex":return e>>>1;case"base64":return uu(n).length;default:if(i)return r?-1:_s(n).length;t=(""+t).toLowerCase(),i=!0}}V.byteLength=nu;function jh(n,t,e){var r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((e===void 0||e>this.length)&&(e=this.length),e<=0)||(e>>>=0,t>>>=0,e<=t))return"";for(n||(n="utf8");;)switch(n){case"hex":return rg(this,t,e);case"utf8":case"utf-8":return ou(this,t,e);case"ascii":return tg(this,t,e);case"latin1":case"binary":return eg(this,t,e);case"base64":return Xh(this,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ng(this,t,e);default:if(r)throw new TypeError("Unknown encoding: "+n);n=(n+"").toLowerCase(),r=!0}}V.prototype._isBuffer=!0;function Ir(n,t,e){var r=n[t];n[t]=n[e],n[e]=r}V.prototype.swap16=function(){var t=this.length;if(t%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;ee&&(t+=" ... "),""};Xc&&(V.prototype[Xc]=V.prototype.inspect);V.prototype.compare=function(t,e,r,i,o){if(Ce(t,Uint8Array)&&(t=V.from(t,t.offset,t.byteLength)),!V.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(e===void 0&&(e=0),r===void 0&&(r=t?t.length:0),i===void 0&&(i=0),o===void 0&&(o=this.length),e<0||r>t.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&e>=r)return 0;if(i>=o)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,i>>>=0,o>>>=0,this===t)return 0;for(var s=o-i,c=r-e,l=Math.min(s,c),g=this.slice(i,o),w=t.slice(e,r),v=0;v2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,Es(e)&&(e=i?0:n.length-1),e<0&&(e=n.length+e),e>=n.length){if(i)return-1;e=n.length-1}else if(e<0)if(i)e=0;else return-1;if(typeof t=="string"&&(t=V.from(t,r)),V.isBuffer(t))return t.length===0?-1:Zc(n,t,e,r,i);if(typeof t=="number")return t=t&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(n,t,e):Uint8Array.prototype.lastIndexOf.call(n,t,e):Zc(n,[t],e,r,i);throw new TypeError("val must be string, number or Buffer")}function Zc(n,t,e,r,i){var o=1,s=n.length,c=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(n.length<2||t.length<2)return-1;o=2,s/=2,c/=2,e/=2}function l(d,y){return o===1?d[y]:d.readUInt16BE(y*o)}var g;if(i){var w=-1;for(g=e;gs&&(e=s-c),g=e;g>=0;g--){for(var v=!0,E=0;Ei&&(r=i)):r=i;var o=t.length;r>o/2&&(r=o/2);for(var s=0;s>>0,isFinite(r)?(r=r>>>0,i===void 0&&(i="utf8")):(i=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var o=this.length-e;if((r===void 0||r>o)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var s=!1;;)switch(i){case"hex":return Hh(this,t,e,r);case"utf8":case"utf-8":return Qh(this,t,e,r);case"ascii":case"latin1":case"binary":return zh(this,t,e,r);case"base64":return Jh(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Yh(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}};V.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Xh(n,t,e){return t===0&&e===n.length?ys.fromByteArray(n):ys.fromByteArray(n.slice(t,e))}function ou(n,t,e){e=Math.min(n.length,e);for(var r=[],i=t;i239?4:o>223?3:o>191?2:1;if(i+c<=e){var l,g,w,v;switch(c){case 1:o<128&&(s=o);break;case 2:l=n[i+1],(l&192)===128&&(v=(o&31)<<6|l&63,v>127&&(s=v));break;case 3:l=n[i+1],g=n[i+2],(l&192)===128&&(g&192)===128&&(v=(o&15)<<12|(l&63)<<6|g&63,v>2047&&(v<55296||v>57343)&&(s=v));break;case 4:l=n[i+1],g=n[i+2],w=n[i+3],(l&192)===128&&(g&192)===128&&(w&192)===128&&(v=(o&15)<<18|(l&63)<<12|(g&63)<<6|w&63,v>65535&&v<1114112&&(s=v))}}s===null?(s=65533,c=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|s&1023),r.push(s),i+=c}return Zh(r)}var tu=4096;function Zh(n){var t=n.length;if(t<=tu)return String.fromCharCode.apply(String,n);for(var e="",r=0;rr)&&(e=r);for(var i="",o=t;or&&(t=r),e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),ee)throw new RangeError("Trying to access beyond buffer length")}V.prototype.readUintLE=V.prototype.readUIntLE=function(t,e,r){t=t>>>0,e=e>>>0,r||$t(t,e,this.length);for(var i=this[t],o=1,s=0;++s>>0,e=e>>>0,r||$t(t,e,this.length);for(var i=this[t+--e],o=1;e>0&&(o*=256);)i+=this[t+--e]*o;return i};V.prototype.readUint8=V.prototype.readUInt8=function(t,e){return t=t>>>0,e||$t(t,1,this.length),this[t]};V.prototype.readUint16LE=V.prototype.readUInt16LE=function(t,e){return t=t>>>0,e||$t(t,2,this.length),this[t]|this[t+1]<<8};V.prototype.readUint16BE=V.prototype.readUInt16BE=function(t,e){return t=t>>>0,e||$t(t,2,this.length),this[t]<<8|this[t+1]};V.prototype.readUint32LE=V.prototype.readUInt32LE=function(t,e){return t=t>>>0,e||$t(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};V.prototype.readUint32BE=V.prototype.readUInt32BE=function(t,e){return t=t>>>0,e||$t(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};V.prototype.readIntLE=function(t,e,r){t=t>>>0,e=e>>>0,r||$t(t,e,this.length);for(var i=this[t],o=1,s=0;++s=o&&(i-=Math.pow(2,8*e)),i};V.prototype.readIntBE=function(t,e,r){t=t>>>0,e=e>>>0,r||$t(t,e,this.length);for(var i=e,o=1,s=this[t+--i];i>0&&(o*=256);)s+=this[t+--i]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*e)),s};V.prototype.readInt8=function(t,e){return t=t>>>0,e||$t(t,1,this.length),this[t]&128?(255-this[t]+1)*-1:this[t]};V.prototype.readInt16LE=function(t,e){t=t>>>0,e||$t(t,2,this.length);var r=this[t]|this[t+1]<<8;return r&32768?r|4294901760:r};V.prototype.readInt16BE=function(t,e){t=t>>>0,e||$t(t,2,this.length);var r=this[t+1]|this[t]<<8;return r&32768?r|4294901760:r};V.prototype.readInt32LE=function(t,e){return t=t>>>0,e||$t(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24};V.prototype.readInt32BE=function(t,e){return t=t>>>0,e||$t(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]};V.prototype.readFloatLE=function(t,e){return t=t>>>0,e||$t(t,4,this.length),rn.read(this,t,!0,23,4)};V.prototype.readFloatBE=function(t,e){return t=t>>>0,e||$t(t,4,this.length),rn.read(this,t,!1,23,4)};V.prototype.readDoubleLE=function(t,e){return t=t>>>0,e||$t(t,8,this.length),rn.read(this,t,!0,52,8)};V.prototype.readDoubleBE=function(t,e){return t=t>>>0,e||$t(t,8,this.length),rn.read(this,t,!1,52,8)};function ee(n,t,e,r,i,o){if(!V.isBuffer(n))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||tn.length)throw new RangeError("Index out of range")}V.prototype.writeUintLE=V.prototype.writeUIntLE=function(t,e,r,i){if(t=+t,e=e>>>0,r=r>>>0,!i){var o=Math.pow(2,8*r)-1;ee(this,t,e,r,o,0)}var s=1,c=0;for(this[e]=t&255;++c>>0,r=r>>>0,!i){var o=Math.pow(2,8*r)-1;ee(this,t,e,r,o,0)}var s=r-1,c=1;for(this[e+s]=t&255;--s>=0&&(c*=256);)this[e+s]=t/c&255;return e+r};V.prototype.writeUint8=V.prototype.writeUInt8=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,1,255,0),this[e]=t&255,e+1};V.prototype.writeUint16LE=V.prototype.writeUInt16LE=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,2,65535,0),this[e]=t&255,this[e+1]=t>>>8,e+2};V.prototype.writeUint16BE=V.prototype.writeUInt16BE=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=t&255,e+2};V.prototype.writeUint32LE=V.prototype.writeUInt32LE=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=t&255,e+4};V.prototype.writeUint32BE=V.prototype.writeUInt32BE=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t&255,e+4};V.prototype.writeIntLE=function(t,e,r,i){if(t=+t,e=e>>>0,!i){var o=Math.pow(2,8*r-1);ee(this,t,e,r,o-1,-o)}var s=0,c=1,l=0;for(this[e]=t&255;++s>0)-l&255;return e+r};V.prototype.writeIntBE=function(t,e,r,i){if(t=+t,e=e>>>0,!i){var o=Math.pow(2,8*r-1);ee(this,t,e,r,o-1,-o)}var s=r-1,c=1,l=0;for(this[e+s]=t&255;--s>=0&&(c*=256);)t<0&&l===0&&this[e+s+1]!==0&&(l=1),this[e+s]=(t/c>>0)-l&255;return e+r};V.prototype.writeInt8=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=t&255,e+1};V.prototype.writeInt16LE=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,2,32767,-32768),this[e]=t&255,this[e+1]=t>>>8,e+2};V.prototype.writeInt16BE=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=t&255,e+2};V.prototype.writeInt32LE=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,4,2147483647,-2147483648),this[e]=t&255,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4};V.prototype.writeInt32BE=function(t,e,r){return t=+t,e=e>>>0,r||ee(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t&255,e+4};function su(n,t,e,r,i,o){if(e+r>n.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function au(n,t,e,r,i){return t=+t,e=e>>>0,i||su(n,t,e,4,34028234663852886e22,-34028234663852886e22),rn.write(n,t,e,r,23,4),e+4}V.prototype.writeFloatLE=function(t,e,r){return au(this,t,e,!0,r)};V.prototype.writeFloatBE=function(t,e,r){return au(this,t,e,!1,r)};function cu(n,t,e,r,i){return t=+t,e=e>>>0,i||su(n,t,e,8,17976931348623157e292,-17976931348623157e292),rn.write(n,t,e,r,52,8),e+8}V.prototype.writeDoubleLE=function(t,e,r){return cu(this,t,e,!0,r)};V.prototype.writeDoubleBE=function(t,e,r){return cu(this,t,e,!1,r)};V.prototype.copy=function(t,e,r,i){if(!V.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),!i&&i!==0&&(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e>>0,r=r===void 0?this.length:r>>>0,t||(t=0);var s;if(typeof t=="number")for(s=e;s55295&&e<57344){if(!i){if(e>56319){(t-=3)>-1&&o.push(239,191,189);continue}else if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(t-=3)>-1&&o.push(239,191,189),i=e;continue}e=(i-55296<<10|e-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((t-=1)<0)break;o.push(e)}else if(e<2048){if((t-=2)<0)break;o.push(e>>6|192,e&63|128)}else if(e<65536){if((t-=3)<0)break;o.push(e>>12|224,e>>6&63|128,e&63|128)}else if(e<1114112){if((t-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,e&63|128)}else throw new Error("Invalid code point")}return o}function sg(n){for(var t=[],e=0;e>8,i=e%256,o.push(i),o.push(r);return o}function uu(n){return ys.toByteArray(og(n))}function Qi(n,t,e,r){for(var i=0;i=t.length||i>=n.length);++i)t[i+e]=n[i];return i}function Ce(n,t){return n instanceof t||n!=null&&n.constructor!=null&&n.constructor.name!=null&&n.constructor.name===t.name}function Es(n){return n!==n}var cg=function(){for(var n="0123456789abcdef",t=new Array(256),e=0;e<16;++e)for(var r=e*16,i=0;i<16;++i)t[r+i]=n[e]+n[i];return t}()});var du=nt((Sy,gu)=>{b();var Rt=gu.exports={},Ie,Ae;function Ts(){throw new Error("setTimeout has not been defined")}function xs(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Ie=setTimeout:Ie=Ts}catch{Ie=Ts}try{typeof clearTimeout=="function"?Ae=clearTimeout:Ae=xs}catch{Ae=xs}})();function lu(n){if(Ie===setTimeout)return setTimeout(n,0);if((Ie===Ts||!Ie)&&setTimeout)return Ie=setTimeout,setTimeout(n,0);try{return Ie(n,0)}catch{try{return Ie.call(null,n,0)}catch{return Ie.call(this,n,0)}}}function ug(n){if(Ae===clearTimeout)return clearTimeout(n);if((Ae===xs||!Ae)&&clearTimeout)return Ae=clearTimeout,clearTimeout(n);try{return Ae(n)}catch{try{return Ae.call(null,n)}catch{return Ae.call(this,n)}}}var $e=[],on=!1,kr,zi=-1;function lg(){!on||!kr||(on=!1,kr.length?$e=kr.concat($e):zi=-1,$e.length&&fu())}function fu(){if(!on){var n=lu(lg);on=!0;for(var t=$e.length;t;){for(kr=$e,$e=[];++zi1)for(var e=1;e{F=Qt(Ar()),$=Qt(du()),fg=function(n){function t(){var r=this||self;return delete n.prototype.__magic__,r}if(typeof globalThis=="object")return globalThis;if(this)return t();n.defineProperty(n.prototype,"__magic__",{configurable:!0,get:t});var e=__magic__;return e}(Object),K=fg});var yu=nt(mu=>{"use strict";b();mu.supports=function(...t){let e=t.reduce((r,i)=>Object.assign(r,i),{});return Object.assign(e,{snapshots:e.snapshots||!1,permanence:e.permanence||!1,seek:e.seek||!1,clear:e.clear||!1,getMany:e.getMany||!1,keyIterator:e.keyIterator||!1,valueIterator:e.valueIterator||!1,iteratorNextv:e.iteratorNextv||!1,iteratorAll:e.iteratorAll||!1,status:e.status||!1,createIfMissing:e.createIfMissing||!1,errorIfExists:e.errorIfExists||!1,deferredOpen:e.deferredOpen||!1,promises:e.promises||!1,streams:e.streams||!1,encodings:Object.assign({},e.encodings),events:Object.assign({},e.events),additionalMethods:Object.assign({},e.additionalMethods)})}});var ge=nt((jy,wu)=>{"use strict";b();wu.exports=class extends Error{constructor(t,e){super(t||""),typeof e=="object"&&e!==null&&(e.code&&(this.code=String(e.code)),e.expected&&(this.expected=!0),e.transient&&(this.transient=!0),e.cause&&(this.cause=e.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}});var Is=nt((Qy,vu)=>{"use strict";b();var Cs=null;vu.exports=function(){return Cs===null&&(Cs={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),Cs}});var Ls=nt(_u=>{"use strict";b();var As=ge(),hg=new Set(["buffer","view","utf8"]),ks=class{constructor(t){if(this.encode=t.encode||this.encode,this.decode=t.decode||this.decode,this.name=t.name||this.name,this.format=t.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!hg.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");t.createViewTranscoder&&(this.createViewTranscoder=t.createViewTranscoder),t.createBufferTranscoder&&(this.createBufferTranscoder=t.createBufferTranscoder),t.createUTF8Transcoder&&(this.createUTF8Transcoder=t.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new As(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new As(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new As(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};_u.Encoding=ks});var Ps=nt(Yi=>{"use strict";b();var{Buffer:Rs}=Ar()||{},{Encoding:Bs}=Ls(),gg=Is(),Un=class extends Bs{constructor(t){super({...t,format:"buffer"})}createViewTranscoder(){return new Wn({encode:this.encode,decode:t=>this.decode(Rs.from(t.buffer,t.byteOffset,t.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},Wn=class extends Bs{constructor(t){super({...t,format:"view"})}createBufferTranscoder(){return new Un({encode:t=>{let e=this.encode(t);return Rs.from(e.buffer,e.byteOffset,e.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},Os=class extends Bs{constructor(t){super({...t,format:"utf8"})}createBufferTranscoder(){return new Un({encode:t=>Rs.from(this.encode(t),"utf8"),decode:t=>this.decode(t.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:t,textDecoder:e}=gg();return new Wn({encode:r=>t.encode(this.encode(r)),decode:r=>this.decode(e.decode(r)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};Yi.BufferFormat=Un;Yi.ViewFormat=Wn;Yi.UTF8Format=Os});var Tu=nt(Or=>{"use strict";b();var{Buffer:Jt}=Ar()||{Buffer:{isBuffer:()=>!1}},{textEncoder:Su,textDecoder:bu}=Is()(),{BufferFormat:Dn,ViewFormat:Ns,UTF8Format:Eu}=Ps(),Xi=n=>n;Or.utf8=new Eu({encode:function(n){return Jt.isBuffer(n)?n.toString("utf8"):ArrayBuffer.isView(n)?bu.decode(n):String(n)},decode:Xi,name:"utf8",createViewTranscoder(){return new Ns({encode:function(n){return ArrayBuffer.isView(n)?n:Su.encode(n)},decode:function(n){return bu.decode(n)},name:`${this.name}+view`})},createBufferTranscoder(){return new Dn({encode:function(n){return Jt.isBuffer(n)?n:ArrayBuffer.isView(n)?Jt.from(n.buffer,n.byteOffset,n.byteLength):Jt.from(String(n),"utf8")},decode:function(n){return n.toString("utf8")},name:`${this.name}+buffer`})}});Or.json=new Eu({encode:JSON.stringify,decode:JSON.parse,name:"json"});Or.buffer=new Dn({encode:function(n){return Jt.isBuffer(n)?n:ArrayBuffer.isView(n)?Jt.from(n.buffer,n.byteOffset,n.byteLength):Jt.from(String(n),"utf8")},decode:Xi,name:"buffer",createViewTranscoder(){return new Ns({encode:function(n){return ArrayBuffer.isView(n)?n:Jt.from(String(n),"utf8")},decode:function(n){return Jt.from(n.buffer,n.byteOffset,n.byteLength)},name:`${this.name}+view`})}});Or.view=new Ns({encode:function(n){return ArrayBuffer.isView(n)?n:Su.encode(n)},decode:Xi,name:"view",createBufferTranscoder(){return new Dn({encode:function(n){return Jt.isBuffer(n)?n:ArrayBuffer.isView(n)?Jt.from(n.buffer,n.byteOffset,n.byteLength):Jt.from(String(n),"utf8")},decode:Xi,name:`${this.name}+buffer`})}});Or.hex=new Dn({encode:function(n){return Jt.isBuffer(n)?n:Jt.from(String(n),"hex")},decode:function(n){return n.toString("hex")},name:"hex"});Or.base64=new Dn({encode:function(n){return Jt.isBuffer(n)?n:Jt.from(String(n),"base64")},decode:function(n){return n.toString("base64")},name:"base64"})});var Iu=nt(Cu=>{"use strict";b();var xu=ge(),to=Tu(),{Encoding:dg}=Ls(),{BufferFormat:pg,ViewFormat:mg,UTF8Format:yg}=Ps(),Mn=Symbol("formats"),Zi=Symbol("encodings"),wg=new Set(["buffer","view","utf8"]),Us=class{constructor(t){if(Array.isArray(t)){if(!t.every(e=>wg.has(e)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[Zi]=new Map,this[Mn]=new Set(t);for(let e in to)try{this.encoding(e)}catch(r){if(r.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw r}}encodings(){return Array.from(new Set(this[Zi].values()))}encoding(t){let e=this[Zi].get(t);if(e===void 0){if(typeof t=="string"&&t!==""){if(e=Sg[t],!e)throw new xu(`Encoding '${t}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof t!="object"||t===null)throw new TypeError("First argument 'encoding' must be a string or object");e=vg(t)}let{name:r,format:i}=e;if(!this[Mn].has(i))if(this[Mn].has("view"))e=e.createViewTranscoder();else if(this[Mn].has("buffer"))e=e.createBufferTranscoder();else if(this[Mn].has("utf8"))e=e.createUTF8Transcoder();else throw new xu(`Encoding '${r}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[t,r,e.name,e.commonName])this[Zi].set(o,e)}return e}};Cu.Transcoder=Us;function vg(n){if(n instanceof dg)return n;let t="type"in n&&typeof n.type=="string"?n.type:void 0,e=n.name||t||`anonymous-${Eg++}`;switch(_g(n)){case"view":return new mg({...n,name:e});case"utf8":return new yg({...n,name:e});case"buffer":return new pg({...n,name:e});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function _g(n){return"format"in n&&n.format!==void 0?n.format:"buffer"in n&&typeof n.buffer=="boolean"?n.buffer?"buffer":"utf8":"code"in n&&Number.isInteger(n.code)?"view":"buffer"}var bg={binary:to.buffer,"utf-8":to.utf8},Sg={...to,...bg},Eg=0});var Du=nt((iw,Ws)=>{"use strict";b();var sn=typeof Reflect=="object"?Reflect:null,Au=sn&&typeof sn.apply=="function"?sn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},eo;sn&&typeof sn.ownKeys=="function"?eo=sn.ownKeys:Object.getOwnPropertySymbols?eo=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:eo=function(t){return Object.getOwnPropertyNames(t)};function Tg(n){console&&console.warn&&console.warn(n)}var Lu=Number.isNaN||function(t){return t!==t};function xt(){xt.init.call(this)}Ws.exports=xt;Ws.exports.once=Ag;xt.EventEmitter=xt;xt.prototype._events=void 0;xt.prototype._eventsCount=0;xt.prototype._maxListeners=void 0;var ku=10;function ro(n){if(typeof n!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof n)}Object.defineProperty(xt,"defaultMaxListeners",{enumerable:!0,get:function(){return ku},set:function(n){if(typeof n!="number"||n<0||Lu(n))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+n+".");ku=n}});xt.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};xt.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Lu(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Ou(n){return n._maxListeners===void 0?xt.defaultMaxListeners:n._maxListeners}xt.prototype.getMaxListeners=function(){return Ou(this)};xt.prototype.emit=function(t){for(var e=[],r=1;r0&&(s=e[0]),s instanceof Error)throw s;var c=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw c.context=s,c}var l=o[t];if(l===void 0)return!1;if(typeof l=="function")Au(l,this,e);else for(var g=l.length,w=Uu(l,g),r=0;r0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=n,c.type=t,c.count=s.length,Tg(c)}return n}xt.prototype.addListener=function(t,e){return Ru(this,t,e,!1)};xt.prototype.on=xt.prototype.addListener;xt.prototype.prependListener=function(t,e){return Ru(this,t,e,!0)};function xg(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Bu(n,t,e){var r={fired:!1,wrapFn:void 0,target:n,type:t,listener:e},i=xg.bind(r);return i.listener=e,r.wrapFn=i,i}xt.prototype.once=function(t,e){return ro(e),this.on(t,Bu(this,t,e)),this};xt.prototype.prependOnceListener=function(t,e){return ro(e),this.prependListener(t,Bu(this,t,e)),this};xt.prototype.removeListener=function(t,e){var r,i,o,s,c;if(ro(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(o=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){c=r[s].listener,o=s;break}if(o<0)return this;o===0?r.shift():Cg(r,o),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};xt.prototype.off=xt.prototype.removeListener;xt.prototype.removeAllListeners=function(t){var e,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var o=Object.keys(r),s;for(i=0;i=0;i--)this.removeListener(t,e[i]);return this};function Pu(n,t,e){var r=n._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?Ig(i):Uu(i,i.length)}xt.prototype.listeners=function(t){return Pu(this,t,!0)};xt.prototype.rawListeners=function(t){return Pu(this,t,!1)};xt.listenerCount=function(n,t){return typeof n.listenerCount=="function"?n.listenerCount(t):Nu.call(n,t)};xt.prototype.listenerCount=Nu;function Nu(n){var t=this._events;if(t!==void 0){var e=t[n];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}xt.prototype.eventNames=function(){return this._eventsCount>0?eo(this._events):[]};function Uu(n,t){for(var e=new Array(t),r=0;r{b();Mu.exports=typeof queueMicrotask=="function"?queueMicrotask:n=>Promise.resolve().then(n)});var Fn=nt(Ds=>{"use strict";b();var $u=Fu();Ds.fromCallback=function(n,t){if(n===void 0){var e=new Promise(function(r,i){n=function(o,s){o?i(o):r(s)}});n[t!==void 0?t:"promise"]=e}else if(typeof n!="function")throw new TypeError("Callback must be a function");return n};Ds.fromPromise=function(n,t){if(t===void 0)return n;n.then(function(e){$u(()=>t(null,e))}).catch(function(e){$u(()=>t(e))})}});var no=nt(Ms=>{"use strict";b();Ms.getCallback=function(n,t){return typeof n=="function"?n:t};Ms.getOptions=function(n,t){return typeof n=="object"&&n!==null?n:t!==void 0?t:{}}});var fr=nt(ao=>{"use strict";b();var{fromCallback:Fs}=Fn(),ie=ge(),{getOptions:$s,getCallback:Ku}=no(),Rr=Symbol("promise"),an=Symbol("callback"),ke=Symbol("working"),Br=Symbol("handleOne"),Ve=Symbol("handleMany"),Ks=Symbol("autoClose"),ur=Symbol("finishWork"),Le=Symbol("returnMany"),sr=Symbol("closing"),$n=Symbol("handleClose"),io=Symbol("closed"),Kn=Symbol("closeCallbacks"),cr=Symbol("keyEncoding"),Pr=Symbol("valueEncoding"),Vs=Symbol("abortOnClose"),oo=Symbol("legacy"),Gs=Symbol("keys"),qs=Symbol("values"),ar=Symbol("limit"),de=Symbol("count"),so=Object.freeze({}),Lg=()=>{},Vu=!1,Vn=class{constructor(t,e,r){if(typeof t!="object"||t===null){let i=t===null?"null":typeof t;throw new TypeError(`The first argument must be an abstract-level database, received ${i}`)}if(typeof e!="object"||e===null)throw new TypeError("The second argument must be an options object");this[io]=!1,this[Kn]=[],this[ke]=!1,this[sr]=!1,this[Ks]=!1,this[an]=null,this[Br]=this[Br].bind(this),this[Ve]=this[Ve].bind(this),this[$n]=this[$n].bind(this),this[cr]=e[cr],this[Pr]=e[Pr],this[oo]=r,this[ar]=Number.isInteger(e.limit)&&e.limit>=0?e.limit:1/0,this[de]=0,this[Vs]=!!e.abortOnClose,this.db=t,this.db.attachResource(this),this.nextTick=t.nextTick}get count(){return this[de]}get limit(){return this[ar]}next(t){let e;if(t===void 0)e=new Promise((r,i)=>{t=(o,s,c)=>{o?i(o):this[oo]?s===void 0&&c===void 0?r():r([s,c]):r(s)}});else if(typeof t!="function")throw new TypeError("Callback must be a function");return this[sr]?this.nextTick(t,new ie("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[ke]?this.nextTick(t,new ie("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[ke]=!0,this[an]=t,this[de]>=this[ar]?this.nextTick(this[Br],null):this._next(this[Br])),e}_next(t){this.nextTick(t)}nextv(t,e,r){return r=Ku(e,r),r=Fs(r,Rr),e=$s(e,so),Number.isInteger(t)?(this[sr]?this.nextTick(r,new ie("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[ke]?this.nextTick(r,new ie("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(t<1&&(t=1),this[ar]<1/0&&(t=Math.min(t,this[ar]-this[de])),this[ke]=!0,this[an]=r,t<=0?this.nextTick(this[Ve],null,[]):this._nextv(t,e,this[Ve])),r[Rr]):(this.nextTick(r,new TypeError("The first argument 'size' must be an integer")),r[Rr])}_nextv(t,e,r){let i=[],o=(s,c,l)=>{if(s)return r(s);if(this[oo]?c===void 0&&l===void 0:c===void 0)return r(null,i);i.push(this[oo]?[c,l]:c),i.length===t?r(null,i):this._next(o)};this._next(o)}all(t,e){return e=Ku(t,e),e=Fs(e,Rr),t=$s(t,so),this[sr]?this.nextTick(e,new ie("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[ke]?this.nextTick(e,new ie("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[ke]=!0,this[an]=e,this[Ks]=!0,this[de]>=this[ar]?this.nextTick(this[Ve],null,[]):this._all(t,this[Ve])),e[Rr]}_all(t,e){let r=this[de],i=[],o=()=>{let c=this[ar]<1/0?Math.min(1e3,this[ar]-r):1e3;c<=0?this.nextTick(e,null,i):this._nextv(c,so,s)},s=(c,l)=>{c?e(c):l.length===0?e(null,i):(i.push.apply(i,l),r+=l.length,o())};o()}[ur](){let t=this[an];return this[Vs]&&t===null?Lg:(this[ke]=!1,this[an]=null,this[sr]&&this._close(this[$n]),t)}[Le](t,e,r){this[Ks]?this.close(t.bind(null,e,r)):t(e,r)}seek(t,e){if(e=$s(e,so),!this[sr]){if(this[ke])throw new ie("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let r=this.db.keyEncoding(e.keyEncoding||this[cr]),i=r.format;e.keyEncoding!==i&&(e={...e,keyEncoding:i});let o=this.db.prefixKey(r.encode(t),i);this._seek(o,e)}}}_seek(t,e){throw new ie("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(t){return t=Fs(t,Rr),this[io]?this.nextTick(t):this[sr]?this[Kn].push(t):(this[sr]=!0,this[Kn].push(t),this[ke]?this[Vs]&&this[ur]()(new ie("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[$n])),t[Rr]}_close(t){this.nextTick(t)}[$n](){this[io]=!0,this.db.detachResource(this);let t=this[Kn];this[Kn]=[];for(let e of t)e()}async*[Symbol.asyncIterator](){try{let t;for(;(t=await this.next())!==void 0;)yield t}finally{this[io]||await this.close()}}},cn=class extends Vn{constructor(t,e){super(t,e,!0),this[Gs]=e.keys!==!1,this[qs]=e.values!==!1}[Br](t,e,r){let i=this[ur]();if(t)return i(t);try{e=this[Gs]&&e!==void 0?this[cr].decode(e):void 0,r=this[qs]&&r!==void 0?this[Pr].decode(r):void 0}catch(o){return i(new lr("entry",o))}e===void 0&&r===void 0||this[de]++,i(null,e,r)}[Ve](t,e){let r=this[ur]();if(t)return this[Le](r,t);try{for(let i of e){let o=i[0],s=i[1];i[0]=this[Gs]&&o!==void 0?this[cr].decode(o):void 0,i[1]=this[qs]&&s!==void 0?this[Pr].decode(s):void 0}}catch(i){return this[Le](r,new lr("entries",i))}this[de]+=e.length,this[Le](r,null,e)}end(t){return!Vu&&typeof console<"u"&&(Vu=!0,console.warn(new ie("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(t)}},js=class extends Vn{constructor(t,e){super(t,e,!1)}[Br](t,e){let r=this[ur]();if(t)return r(t);try{e=e!==void 0?this[cr].decode(e):void 0}catch(i){return r(new lr("key",i))}e!==void 0&&this[de]++,r(null,e)}[Ve](t,e){let r=this[ur]();if(t)return this[Le](r,t);try{for(let i=0;i{"use strict";b();var{AbstractKeyIterator:Og,AbstractValueIterator:Rg}=fr(),Nr=Symbol("iterator"),Gn=Symbol("callback"),un=Symbol("handleOne"),Ur=Symbol("handleMany"),qn=class extends Og{constructor(t,e){super(t,e),this[Nr]=t.iterator({...e,keys:!0,values:!1}),this[un]=this[un].bind(this),this[Ur]=this[Ur].bind(this)}},co=class extends Rg{constructor(t,e){super(t,e),this[Nr]=t.iterator({...e,keys:!1,values:!0}),this[un]=this[un].bind(this),this[Ur]=this[Ur].bind(this)}};for(let n of[qn,co]){let t=n===qn,e=t?r=>r[0]:r=>r[1];n.prototype._next=function(r){this[Gn]=r,this[Nr].next(this[un])},n.prototype[un]=function(r,i,o){let s=this[Gn];r?s(r):s(null,t?i:o)},n.prototype._nextv=function(r,i,o){this[Gn]=o,this[Nr].nextv(r,i,this[Ur])},n.prototype._all=function(r,i){this[Gn]=i,this[Nr].all(r,this[Ur])},n.prototype[Ur]=function(r,i){let o=this[Gn];r?o(r):o(null,i.map(e))},n.prototype._seek=function(r,i){this[Nr].seek(r,i)},n.prototype._close=function(r){this[Nr].close(r)}}Qs.DefaultKeyIterator=qn;Qs.DefaultValueIterator=co});var qu=nt(po=>{"use strict";b();var{AbstractIterator:Bg,AbstractKeyIterator:Pg,AbstractValueIterator:Ng}=fr(),zs=ge(),re=Symbol("nut"),ho=Symbol("undefer"),go=Symbol("factory"),uo=class extends Bg{constructor(t,e){super(t,e),this[re]=null,this[go]=()=>t.iterator(e),this.db.defer(()=>this[ho]())}},lo=class extends Pg{constructor(t,e){super(t,e),this[re]=null,this[go]=()=>t.keys(e),this.db.defer(()=>this[ho]())}},fo=class extends Ng{constructor(t,e){super(t,e),this[re]=null,this[go]=()=>t.values(e),this.db.defer(()=>this[ho]())}};for(let n of[uo,lo,fo])n.prototype[ho]=function(){this.db.status==="open"&&(this[re]=this[go]())},n.prototype._next=function(t){this[re]!==null?this[re].next(t):this.db.status==="opening"?this.db.defer(()=>this._next(t)):this.nextTick(t,new zs("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},n.prototype._nextv=function(t,e,r){this[re]!==null?this[re].nextv(t,e,r):this.db.status==="opening"?this.db.defer(()=>this._nextv(t,e,r)):this.nextTick(r,new zs("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},n.prototype._all=function(t,e){this[re]!==null?this[re].all(e):this.db.status==="opening"?this.db.defer(()=>this._all(t,e)):this.nextTick(e,new zs("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},n.prototype._seek=function(t,e){this[re]!==null?this[re]._seek(t,e):this.db.status==="opening"&&this.db.defer(()=>this._seek(t,e))},n.prototype._close=function(t){this[re]!==null?this[re].close(t):this.db.status==="opening"?this.db.defer(()=>this._close(t)):this.nextTick(t)};po.DeferredIterator=uo;po.DeferredKeyIterator=lo;po.DeferredValueIterator=fo});var Ys=nt(Hu=>{"use strict";b();var{fromCallback:ju}=Fn(),mo=ge(),{getCallback:Ug,getOptions:Wg}=no(),yo=Symbol("promise"),pe=Symbol("status"),ln=Symbol("operations"),jn=Symbol("finishClose"),fn=Symbol("closeCallbacks"),Js=class{constructor(t){if(typeof t!="object"||t===null){let e=t===null?"null":typeof t;throw new TypeError(`The first argument must be an abstract-level database, received ${e}`)}this[ln]=[],this[fn]=[],this[pe]="open",this[jn]=this[jn].bind(this),this.db=t,this.db.attachResource(this),this.nextTick=t.nextTick}get length(){return this[ln].length}put(t,e,r){if(this[pe]!=="open")throw new mo("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let i=this.db._checkKey(t)||this.db._checkValue(e);if(i)throw i;let o=r&&r.sublevel!=null?r.sublevel:this.db,s=r,c=o.keyEncoding(r&&r.keyEncoding),l=o.valueEncoding(r&&r.valueEncoding),g=c.format;r={...r,keyEncoding:g,valueEncoding:l.format},o!==this.db&&(r.sublevel=null);let w=o.prefixKey(c.encode(t),g),v=l.encode(e);return this._put(w,v,r),this[ln].push({...s,type:"put",key:t,value:e}),this}_put(t,e,r){}del(t,e){if(this[pe]!=="open")throw new mo("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let r=this.db._checkKey(t);if(r)throw r;let i=e&&e.sublevel!=null?e.sublevel:this.db,o=e,s=i.keyEncoding(e&&e.keyEncoding),c=s.format;return e={...e,keyEncoding:c},i!==this.db&&(e.sublevel=null),this._del(i.prefixKey(s.encode(t),c),e),this[ln].push({...o,type:"del",key:t}),this}_del(t,e){}clear(){if(this[pe]!=="open")throw new mo("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[ln]=[],this}_clear(){}write(t,e){return e=Ug(t,e),e=ju(e,yo),t=Wg(t),this[pe]!=="open"?this.nextTick(e,new mo("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(e):(this[pe]="writing",this._write(t,r=>{this[pe]="closing",this[fn].push(()=>e(r)),r||this.db.emit("batch",this[ln]),this._close(this[jn])})),e[yo]}_write(t,e){}close(t){return t=ju(t,yo),this[pe]==="closing"?this[fn].push(t):this[pe]==="closed"?this.nextTick(t):(this[fn].push(t),this[pe]!=="writing"&&(this[pe]="closing",this._close(this[jn]))),t[yo]}_close(t){this.nextTick(t)}[jn](){this[pe]="closed",this.db.detachResource(this);let t=this[fn];this[fn]=[];for(let e of t)e()}};Hu.AbstractChainedBatch=Js});var zu=nt(Qu=>{"use strict";b();var{AbstractChainedBatch:Dg}=Ys(),Mg=ge(),hn=Symbol("encoded"),Xs=class extends Dg{constructor(t){super(t),this[hn]=[]}_put(t,e,r){this[hn].push({...r,type:"put",key:t,value:e})}_del(t,e){this[hn].push({...e,type:"del",key:t})}_clear(){this[hn]=[]}_write(t,e){this.db.status==="opening"?this.db.defer(()=>this._write(t,e)):this.db.status==="open"?this[hn].length===0?this.nextTick(e):this.db._batch(this[hn],t,e):this.nextTick(e,new Mg("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};Qu.DefaultChainedBatch=Xs});var Xu=nt((Sw,Yu)=>{"use strict";b();var Ju=ge(),Fg=Object.prototype.hasOwnProperty,$g=new Set(["lt","lte","gt","gte"]);Yu.exports=function(n,t){let e={};for(let r in n)if(Fg.call(n,r)&&!(r==="keyEncoding"||r==="valueEncoding")){if(r==="start"||r==="end")throw new Ju(`The legacy range option '${r}' has been removed`,{code:"LEVEL_LEGACY"});if(r==="encoding")throw new Ju("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});$g.has(r)?e[r]=t.encode(n[r]):e[r]=n[r]}return e.reverse=!!e.reverse,e.limit=Number.isInteger(e.limit)&&e.limit>=0?e.limit:-1,e}});var Zs=nt((Tw,tl)=>{b();var Zu;tl.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:K):n=>(Zu||(Zu=Promise.resolve())).then(n).catch(t=>setTimeout(()=>{throw t},0))});var nl=nt((Cw,rl)=>{"use strict";b();var el=Zs();rl.exports=function(n,...t){t.length===0?el(n):el(()=>n(...t))}});var il=nt(wo=>{"use strict";b();var{AbstractIterator:Kg,AbstractKeyIterator:Vg,AbstractValueIterator:Gg}=fr(),gn=Symbol("unfix"),ve=Symbol("iterator"),Wr=Symbol("handleOne"),hr=Symbol("handleMany"),Ge=Symbol("callback"),Hn=class extends Kg{constructor(t,e,r,i){super(t,e),this[ve]=r,this[gn]=i,this[Wr]=this[Wr].bind(this),this[hr]=this[hr].bind(this),this[Ge]=null}[Wr](t,e,r){let i=this[Ge];if(t)return i(t);e!==void 0&&(e=this[gn](e)),i(t,e,r)}[hr](t,e){let r=this[Ge];if(t)return r(t);for(let i of e){let o=i[0];o!==void 0&&(i[0]=this[gn](o))}r(t,e)}},Qn=class extends Vg{constructor(t,e,r,i){super(t,e),this[ve]=r,this[gn]=i,this[Wr]=this[Wr].bind(this),this[hr]=this[hr].bind(this),this[Ge]=null}[Wr](t,e){let r=this[Ge];if(t)return r(t);e!==void 0&&(e=this[gn](e)),r(t,e)}[hr](t,e){let r=this[Ge];if(t)return r(t);for(let i=0;i{"use strict";b();var ta=ge(),{Buffer:na}=Ar()||{},{AbstractSublevelIterator:qg,AbstractSublevelKeyIterator:jg,AbstractSublevelValueIterator:Hg}=il(),qe=Symbol("prefix"),ol=Symbol("upperBound"),Jn=Symbol("prefixRange"),oe=Symbol("parent"),ea=Symbol("unfix"),sl=new TextEncoder,Qg={separator:"!"};al.exports=function({AbstractLevel:n}){class t extends n{static defaults(r){if(typeof r=="string")throw new ta("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(r&&r.open)throw new ta("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return r==null?Qg:r.separator?r:{...r,separator:"!"}}constructor(r,i,o){let{separator:s,manifest:c,...l}=t.defaults(o);i=Jg(i,s);let g=s.charCodeAt(0)+1,w=r[oe]||r;if(!sl.encode(i).every(d=>d>g&&d<127))throw new ta(`Prefix must use bytes > ${g} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(zg(w,c),l);let v=(r.prefix||"")+s+i+s,E=v.slice(0,-1)+String.fromCharCode(g);this[oe]=w,this[qe]=new vo(v),this[ol]=new vo(E),this[ea]=new ia,this.nextTick=w.nextTick}prefixKey(r,i){if(i==="utf8")return this[qe].utf8+r;if(r.byteLength===0)return this[qe][i];if(i==="view"){let o=this[qe].view,s=new Uint8Array(o.byteLength+r.byteLength);return s.set(o,0),s.set(r,o.byteLength),s}else{let o=this[qe].buffer;return na.concat([o,r],o.byteLength+r.byteLength)}}[Jn](r,i){r.gte!==void 0?r.gte=this.prefixKey(r.gte,i):r.gt!==void 0?r.gt=this.prefixKey(r.gt,i):r.gte=this[qe][i],r.lte!==void 0?r.lte=this.prefixKey(r.lte,i):r.lt!==void 0?r.lt=this.prefixKey(r.lt,i):r.lte=this[ol][i]}get prefix(){return this[qe].utf8}get db(){return this[oe]}_open(r,i){this[oe].open({passive:!0},i)}_put(r,i,o,s){this[oe].put(r,i,o,s)}_get(r,i,o){this[oe].get(r,i,o)}_getMany(r,i,o){this[oe].getMany(r,i,o)}_del(r,i,o){this[oe].del(r,i,o)}_batch(r,i,o){this[oe].batch(r,i,o)}_clear(r,i){this[Jn](r,r.keyEncoding),this[oe].clear(r,i)}_iterator(r){this[Jn](r,r.keyEncoding);let i=this[oe].iterator(r),o=this[ea].get(this[qe].utf8.length,r.keyEncoding);return new qg(this,r,i,o)}_keys(r){this[Jn](r,r.keyEncoding);let i=this[oe].keys(r),o=this[ea].get(this[qe].utf8.length,r.keyEncoding);return new jg(this,r,i,o)}_values(r){this[Jn](r,r.keyEncoding);let i=this[oe].values(r);return new Hg(this,r,i)}}return{AbstractSublevel:t}};var zg=function(n,t){return{...n.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...t,encodings:{utf8:ra(n,"utf8"),buffer:ra(n,"buffer"),view:ra(n,"view")}}},ra=function(n,t){return n.supports.encodings[t]?n.keyEncoding(t).name===t:!1},vo=class{constructor(t){this.utf8=t,this.view=sl.encode(t),this.buffer=na?na.from(this.view.buffer,0,this.view.byteLength):{}}},ia=class{constructor(){this.cache=new Map}get(t,e){let r=this.cache.get(e);return r===void 0&&(e==="view"?r=function(i,o){return o.subarray(i)}.bind(null,t):r=function(i,o){return o.slice(i)}.bind(null,t),this.cache.set(e,r)),r}},Jg=function(n,t){let e=0,r=n.length;for(;ee&&n[r-1]===t;)r--;return n.slice(e,r)}});var ua=nt(ca=>{"use strict";b();var{supports:Yg}=yu(),{Transcoder:Xg}=Iu(),{EventEmitter:Zg}=Du(),{fromCallback:gr}=Fn(),_e=ge(),{AbstractIterator:Dr}=fr(),{DefaultKeyIterator:td,DefaultValueIterator:ed}=Gu(),{DeferredIterator:rd,DeferredKeyIterator:nd,DeferredValueIterator:id}=qu(),{DefaultChainedBatch:ul}=zu(),{getCallback:Mr,getOptions:dr}=no(),_o=Xu(),gt=Symbol("promise"),je=Symbol("landed"),Fr=Symbol("resources"),oa=Symbol("closeResources"),Yn=Symbol("operations"),Xn=Symbol("undefer"),bo=Symbol("deferOpen"),ll=Symbol("options"),mt=Symbol("status"),$r=Symbol("defaultOptions"),dn=Symbol("transcoder"),So=Symbol("keyEncoding"),sa=Symbol("valueEncoding"),od=()=>{},Zn=class extends Zg{constructor(t,e){if(super(),typeof t!="object"||t===null)throw new TypeError("The first argument 'manifest' must be an object");e=dr(e);let{keyEncoding:r,valueEncoding:i,passive:o,...s}=e;this[Fr]=new Set,this[Yn]=[],this[bo]=!0,this[ll]=s,this[mt]="opening",this.supports=Yg(t,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:t.snapshots!==!1,permanence:t.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:t.encodings||{},events:Object.assign({},t.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[dn]=new Xg(sd(this)),this[So]=this[dn].encoding(r||"utf8"),this[sa]=this[dn].encoding(i||"utf8");for(let c of this[dn].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[$r]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[So].commonName,valueEncoding:this[sa].commonName}),key:Object.freeze({keyEncoding:this[So].commonName})},this.nextTick(()=>{this[bo]&&this.open({passive:!1},od)})}get status(){return this[mt]}keyEncoding(t){return this[dn].encoding(t??this[So])}valueEncoding(t){return this[dn].encoding(t??this[sa])}open(t,e){e=Mr(t,e),e=gr(e,gt),t={...this[ll],...dr(t)},t.createIfMissing=t.createIfMissing!==!1,t.errorIfExists=!!t.errorIfExists;let r=i=>{this[mt]==="closing"||this[mt]==="opening"?this.once(je,i?()=>r(i):r):this[mt]!=="open"?e(new _e("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):e()};return t.passive?this[mt]==="opening"?this.once(je,r):this.nextTick(r):this[mt]==="closed"||this[bo]?(this[bo]=!1,this[mt]="opening",this.emit("opening"),this._open(t,i=>{if(i){this[mt]="closed",this[oa](()=>{this.emit(je),r(i)}),this[Xn]();return}this[mt]="open",this[Xn](),this.emit(je),this[mt]==="open"&&this.emit("open"),this[mt]==="open"&&this.emit("ready"),r()})):this[mt]==="open"?this.nextTick(r):this.once(je,()=>this.open(t,e)),e[gt]}_open(t,e){this.nextTick(e)}close(t){t=gr(t,gt);let e=r=>{this[mt]==="opening"||this[mt]==="closing"?this.once(je,r?e(r):e):this[mt]!=="closed"?t(new _e("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:r})):t()};if(this[mt]==="open"){this[mt]="closing",this.emit("closing");let r=i=>{this[mt]="open",this[Xn](),this.emit(je),e(i)};this[oa](()=>{this._close(i=>{if(i)return r(i);this[mt]="closed",this[Xn](),this.emit(je),this[mt]==="closed"&&this.emit("closed"),e()})})}else this[mt]==="closed"?this.nextTick(e):this.once(je,()=>this.close(t));return t[gt]}[oa](t){if(this[Fr].size===0)return this.nextTick(t);let e=this[Fr].size,r=!0,i=()=>{--e===0&&(r?this.nextTick(t):t())};for(let o of this[Fr])o.close(i);r=!1,this[Fr].clear()}_close(t){this.nextTick(t)}get(t,e,r){if(r=Mr(e,r),r=gr(r,gt),e=dr(e,this[$r].entry),this[mt]==="opening")return this.defer(()=>this.get(t,e,r)),r[gt];if(pn(this,r))return r[gt];let i=this._checkKey(t);if(i)return this.nextTick(r,i),r[gt];let o=this.keyEncoding(e.keyEncoding),s=this.valueEncoding(e.valueEncoding),c=o.format,l=s.format;return(e.keyEncoding!==c||e.valueEncoding!==l)&&(e=Object.assign({},e,{keyEncoding:c,valueEncoding:l})),this._get(this.prefixKey(o.encode(t),c),e,(g,w)=>{if(g)return(g.code==="LEVEL_NOT_FOUND"||g.notFound||/NotFound/i.test(g))&&(g.code||(g.code="LEVEL_NOT_FOUND"),g.notFound||(g.notFound=!0),g.status||(g.status=404)),r(g);try{w=s.decode(w)}catch(v){return r(new _e("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:v}))}r(null,w)}),r[gt]}_get(t,e,r){this.nextTick(r,new Error("NotFound"))}getMany(t,e,r){if(r=Mr(e,r),r=gr(r,gt),e=dr(e,this[$r].entry),this[mt]==="opening")return this.defer(()=>this.getMany(t,e,r)),r[gt];if(pn(this,r))return r[gt];if(!Array.isArray(t))return this.nextTick(r,new TypeError("The first argument 'keys' must be an array")),r[gt];if(t.length===0)return this.nextTick(r,null,[]),r[gt];let i=this.keyEncoding(e.keyEncoding),o=this.valueEncoding(e.valueEncoding),s=i.format,c=o.format;(e.keyEncoding!==s||e.valueEncoding!==c)&&(e=Object.assign({},e,{keyEncoding:s,valueEncoding:c}));let l=new Array(t.length);for(let g=0;g{if(g)return r(g);try{for(let v=0;vthis.put(t,e,r,i)),i[gt];if(pn(this,i))return i[gt];let o=this._checkKey(t)||this._checkValue(e);if(o)return this.nextTick(i,o),i[gt];let s=this.keyEncoding(r.keyEncoding),c=this.valueEncoding(r.valueEncoding),l=s.format,g=c.format;(r.keyEncoding!==l||r.valueEncoding!==g)&&(r=Object.assign({},r,{keyEncoding:l,valueEncoding:g}));let w=this.prefixKey(s.encode(t),l),v=c.encode(e);return this._put(w,v,r,E=>{if(E)return i(E);this.emit("put",t,e),i()}),i[gt]}_put(t,e,r,i){this.nextTick(i)}del(t,e,r){if(r=Mr(e,r),r=gr(r,gt),e=dr(e,this[$r].key),this[mt]==="opening")return this.defer(()=>this.del(t,e,r)),r[gt];if(pn(this,r))return r[gt];let i=this._checkKey(t);if(i)return this.nextTick(r,i),r[gt];let o=this.keyEncoding(e.keyEncoding),s=o.format;return e.keyEncoding!==s&&(e=Object.assign({},e,{keyEncoding:s})),this._del(this.prefixKey(o.encode(t),s),e,c=>{if(c)return r(c);this.emit("del",t),r()}),r[gt]}_del(t,e,r){this.nextTick(r)}batch(t,e,r){if(!arguments.length){if(this[mt]==="opening")return new ul(this);if(this[mt]!=="open")throw new _e("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof t=="function"?r=t:r=Mr(e,r),r=gr(r,gt),e=dr(e,this[$r].empty),this[mt]==="opening")return this.defer(()=>this.batch(t,e,r)),r[gt];if(pn(this,r))return r[gt];if(!Array.isArray(t))return this.nextTick(r,new TypeError("The first argument 'operations' must be an array")),r[gt];if(t.length===0)return this.nextTick(r),r[gt];let i=new Array(t.length),{keyEncoding:o,valueEncoding:s,...c}=e;for(let l=0;l{if(l)return r(l);this.emit("batch",t),r()}),r[gt]}_batch(t,e,r){this.nextTick(r)}sublevel(t,e){return this._sublevel(t,aa.defaults(e))}_sublevel(t,e){return new aa(this,t,e)}prefixKey(t,e){return t}clear(t,e){if(e=Mr(t,e),e=gr(e,gt),t=dr(t,this[$r].empty),this[mt]==="opening")return this.defer(()=>this.clear(t,e)),e[gt];if(pn(this,e))return e[gt];let r=t,i=this.keyEncoding(t.keyEncoding);return t=_o(t,i),t.keyEncoding=i.format,t.limit===0?this.nextTick(e):this._clear(t,o=>{if(o)return e(o);this.emit("clear",r),e()}),e[gt]}_clear(t,e){this.nextTick(e)}iterator(t){let e=this.keyEncoding(t&&t.keyEncoding),r=this.valueEncoding(t&&t.valueEncoding);if(t=_o(t,e),t.keys=t.keys!==!1,t.values=t.values!==!1,t[Dr.keyEncoding]=e,t[Dr.valueEncoding]=r,t.keyEncoding=e.format,t.valueEncoding=r.format,this[mt]==="opening")return new rd(this,t);if(this[mt]!=="open")throw new _e("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(t)}_iterator(t){return new Dr(this,t)}keys(t){let e=this.keyEncoding(t&&t.keyEncoding),r=this.valueEncoding(t&&t.valueEncoding);if(t=_o(t,e),t[Dr.keyEncoding]=e,t[Dr.valueEncoding]=r,t.keyEncoding=e.format,t.valueEncoding=r.format,this[mt]==="opening")return new nd(this,t);if(this[mt]!=="open")throw new _e("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(t)}_keys(t){return new td(this,t)}values(t){let e=this.keyEncoding(t&&t.keyEncoding),r=this.valueEncoding(t&&t.valueEncoding);if(t=_o(t,e),t[Dr.keyEncoding]=e,t[Dr.valueEncoding]=r,t.keyEncoding=e.format,t.valueEncoding=r.format,this[mt]==="opening")return new id(this,t);if(this[mt]!=="open")throw new _e("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(t)}_values(t){return new ed(this,t)}defer(t){if(typeof t!="function")throw new TypeError("The first argument must be a function");this[Yn].push(t)}[Xn](){if(this[Yn].length===0)return;let t=this[Yn];this[Yn]=[];for(let e of t)e()}attachResource(t){if(typeof t!="object"||t===null||typeof t.close!="function")throw new TypeError("The first argument must be a resource object");this[Fr].add(t)}detachResource(t){this[Fr].delete(t)}_chainedBatch(){return new ul(this)}_checkKey(t){if(t==null)return new _e("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(t){if(t==null)return new _e("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};Zn.prototype.nextTick=nl();var{AbstractSublevel:aa}=cl()({AbstractLevel:Zn});ca.AbstractLevel=Zn;ca.AbstractSublevel=aa;var pn=function(n,t){return n[mt]!=="open"?(n.nextTick(t,new _e("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},sd=function(n){return Object.keys(n.supports.encodings).filter(t=>!!n.supports.encodings[t])}});var Eo=nt(Kr=>{"use strict";b();Kr.AbstractLevel=ua().AbstractLevel;Kr.AbstractSublevel=ua().AbstractSublevel;Kr.AbstractIterator=fr().AbstractIterator;Kr.AbstractKeyIterator=fr().AbstractKeyIterator;Kr.AbstractValueIterator=fr().AbstractValueIterator;Kr.AbstractChainedBatch=Ys().AbstractChainedBatch});var hl=nt((Uw,fl)=>{b();fl.exports=cd;var ad=Zs();function cd(n,t,e){if(typeof t!="number")throw new Error("second argument must be a Number");let r,i,o,s,c,l=!0,g;Array.isArray(n)?(r=[],o=i=n.length):(s=Object.keys(n),r={},o=i=s.length);function w(E){function d(){e&&e(E,r),e=null}l?ad(d):d()}function v(E,d,y){if(r[E]=y,d&&(c=!0),--o===0||d)w(d);else if(!c&&g{"use strict";b();gl.exports=function(t){let e=t.gte!==void 0?t.gte:t.gt!==void 0?t.gt:void 0,r=t.lte!==void 0?t.lte:t.lt!==void 0?t.lt:void 0,i=t.gte===void 0,o=t.lte===void 0;return e!==void 0&&r!==void 0?IDBKeyRange.bound(e,r,i,o):e!==void 0?IDBKeyRange.lowerBound(e,i):r!==void 0?IDBKeyRange.upperBound(r,o):null}});var fa=nt((Fw,dl)=>{"use strict";b();var ud=new TextEncoder;dl.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):ud.encode(n)}});var vl=nt(wl=>{"use strict";b();var{AbstractIterator:ld}=Eo(),pl=la(),To=fa(),Oe=Symbol("cache"),He=Symbol("finished"),se=Symbol("options"),Qe=Symbol("currentOptions"),Vr=Symbol("position"),ha=Symbol("location"),mn=Symbol("first"),ml={},ga=class extends ld{constructor(t,e,r){super(t,r),this[Oe]=[],this[He]=this.limit===0,this[se]=r,this[Qe]={...r},this[Vr]=void 0,this[ha]=e,this[mn]=!0}_nextv(t,e,r){if(this[mn]=!1,this[He])return this.nextTick(r,null,[]);if(this[Oe].length>0)return t=Math.min(t,this[Oe].length),this.nextTick(r,null,this[Oe].splice(0,t));this[Vr]!==void 0&&(this[se].reverse?(this[Qe].lt=this[Vr],this[Qe].lte=void 0):(this[Qe].gt=this[Vr],this[Qe].gte=void 0));let i;try{i=pl(this[Qe])}catch{return this[He]=!0,this.nextTick(r,null,[])}let o=this.db.db.transaction([this[ha]],"readonly"),s=o.objectStore(this[ha]),c=[];if(this[se].reverse){let l=!this[se].values&&s.openKeyCursor?"openKeyCursor":"openCursor";s[l](i,"prev").onsuccess=g=>{let w=g.target.result;if(w){let{key:v,value:E}=w;this[Vr]=v,c.push([this[se].keys&&v!==void 0?To(v):void 0,this[se].values&&E!==void 0?To(E):void 0]),c.length{if(l===void 0||g===void 0)return;let v=Math.max(l.length,g.length);v===0||t===1/0?this[He]=!0:this[Vr]=l[v-1],c.length=v;for(let E=0;E{l=v.target.result,w()}:(l=[],this.nextTick(w)),this[se].values?s.getAll(i,t<1/0?t:void 0).onsuccess=v=>{g=v.target.result,w()}:(g=[],this.nextTick(w))}o.onabort=()=>{r(o.error||new Error("aborted by user")),r=null},o.oncomplete=()=>{r(null,c),r=null}}_next(t){if(this[Oe].length>0){let[e,r]=this[Oe].shift();this.nextTick(t,null,e,r)}else if(this[He])this.nextTick(t);else{let e=Math.min(100,this.limit-this.count);this[mn]&&(this[mn]=!1,e=1),this._nextv(e,ml,(r,i)=>{if(r)return t(r);this[Oe]=i,this._next(t)})}}_all(t,e){this[mn]=!1;let r=this[Oe].splice(0,this[Oe].length),i=this.limit-this.count-r.length;if(i<=0)return this.nextTick(e,null,r);this._nextv(i,ml,(o,s)=>{if(o)return e(o);r.length>0&&(s=r.concat(s)),e(null,s)})}_seek(t,e){this[mn]=!0,this[Oe]=[],this[He]=!1,this[Vr]=void 0,this[Qe]={...this[se]};let r;try{r=pl(this[se])}catch{this[He]=!0;return}r!==null&&!r.includes(t)?this[He]=!0:this[se].reverse?this[Qe].lte=t:this[Qe].gte=t}};wl.Iterator=ga;function yl(n){typeof n.commit=="function"&&n.commit()}});var bl=nt((Gw,_l)=>{"use strict";b();_l.exports=function(t,e,r,i,o){if(i.limit===0)return t.nextTick(o);let s=t.db.transaction([e],"readwrite"),c=s.objectStore(e),l=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let g=c.openKeyCursor?"openKeyCursor":"openCursor",w=i.reverse?"prev":"next";c[g](r,w).onsuccess=function(v){let E=v.target.result;E&&(c.delete(E.key).onsuccess=function(){(i.limit<=0||++l{"use strict";b();var{AbstractLevel:fd}=Eo(),Sl=ge(),hd=hl(),{fromCallback:gd}=Fn(),{Iterator:dd}=vl(),El=fa(),pd=bl(),md=la(),xl="level-js-",ti=Symbol("idb"),da=Symbol("namePrefix"),ze=Symbol("location"),pa=Symbol("version"),Gr=Symbol("store"),ei=Symbol("onComplete"),Tl=Symbol("promise"),xo=class extends fd{constructor(t,e,r){if(typeof e=="function"||typeof r=="function")throw new Sl("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:i,version:o,...s}=e||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},s),typeof t!="string")throw new Error("constructor requires a location string argument");this[ze]=t,this[da]=i??xl,this[pa]=parseInt(o||1,10),this[ti]=null}get location(){return this[ze]}get namePrefix(){return this[da]}get version(){return this[pa]}get db(){return this[ti]}get type(){return"browser-level"}_open(t,e){let r=indexedDB.open(this[da]+this[ze],this[pa]);r.onerror=function(){e(r.error||new Error("unknown error"))},r.onsuccess=()=>{this[ti]=r.result,e()},r.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[ze])||o.createObjectStore(this[ze])}}[Gr](t){return this[ti].transaction([this[ze]],t).objectStore(this[ze])}[ei](t,e){let r=t.transaction;r.onabort=function(){e(r.error||new Error("aborted by user"))},r.oncomplete=function(){e(null,t.result)}}_get(t,e,r){let i=this[Gr]("readonly"),o;try{o=i.get(t)}catch(s){return this.nextTick(r,s)}this[ei](o,function(s,c){if(s)return r(s);if(c===void 0)return r(new Sl("Entry not found",{code:"LEVEL_NOT_FOUND"}));r(null,El(c))})}_getMany(t,e,r){let i=this[Gr]("readonly"),o=t.map(s=>c=>{let l;try{l=i.get(s)}catch(g){return c(g)}l.onsuccess=()=>{let g=l.result;c(null,g===void 0?g:El(g))},l.onerror=g=>{g.stopPropagation(),c(l.error)}});hd(o,16,r)}_del(t,e,r){let i=this[Gr]("readwrite"),o;try{o=i.delete(t)}catch(s){return this.nextTick(r,s)}this[ei](o,r)}_put(t,e,r,i){let o=this[Gr]("readwrite"),s;try{s=o.put(e,t)}catch(c){return this.nextTick(i,c)}this[ei](s,i)}_iterator(t){return new dd(this,this[ze],t)}_batch(t,e,r){let i=this[Gr]("readwrite"),o=i.transaction,s=0,c;o.onabort=function(){r(c||o.error||new Error("aborted by user"))},o.oncomplete=function(){r()};function l(){let g=t[s++],w=g.key,v;try{v=g.type==="del"?i.delete(w):i.put(g.value,w)}catch(E){c=E,o.abort();return}s=0)return pd(this,this[ze],r,t,e);try{let o=this[Gr]("readwrite");i=r?o.delete(r):o.clear()}catch(o){return this.nextTick(e,o)}this[ei](i,e)}_close(t){this[ti].close(),this.nextTick(t)}};xo.destroy=function(n,t,e){typeof t=="function"&&(e=t,t=xl),e=gd(e,Tl);let r=indexedDB.deleteDatabase(t+n);return r.onsuccess=function(){e()},r.onerror=function(i){e(i)},e[Tl]};Cl.BrowserLevel=xo});var kl=nt(Al=>{b();Al.Level=Il().BrowserLevel});var Rl=nt((Jw,Ol)=>{"use strict";b();Ol.exports=vd;var At=0,Et=1;function ae(n,t,e,r,i,o){this._color=n,this.key=t,this.value=e,this.left=r,this.right=i,this._count=o}function Re(n){return new ae(n._color,n.key,n.value,n.left,n.right,n._count)}function pr(n,t){return new ae(n,t.key,t.value,t.left,t.right,t._count)}function kt(n){n._count=1+(n.left?n.left._count:0)+(n.right?n.right._count:0)}function mr(n,t){this._compare=n,this.root=t}var Yt=mr.prototype;Object.defineProperty(Yt,"keys",{get:function(){var n=[];return this.forEach(function(t,e){n.push(t)}),n}});Object.defineProperty(Yt,"values",{get:function(){var n=[];return this.forEach(function(t,e){n.push(e)}),n}});Object.defineProperty(Yt,"length",{get:function(){return this.root?this.root._count:0}});Yt.insert=function(n,t){for(var e=this._compare,r=this.root,i=[],o=[];r;){var s=e(n,r.key);i.push(r),o.push(s),s<=0?r=r.left:r=r.right}i.push(new ae(At,n,t,null,null,1));for(var c=i.length-2;c>=0;--c){var r=i[c];o[c]<=0?i[c]=new ae(r._color,r.key,r.value,i[c+1],r.right,r._count+1):i[c]=new ae(r._color,r.key,r.value,r.left,i[c+1],r._count+1)}for(var c=i.length-1;c>1;--c){var l=i[c-1],r=i[c];if(l._color===Et||r._color===Et)break;var g=i[c-2];if(g.left===l)if(l.left===r){var w=g.right;if(w&&w._color===At)l._color=Et,g.right=pr(Et,w),g._color=At,c-=1;else{if(g._color=At,g.left=l.right,l._color=Et,l.right=g,i[c-2]=l,i[c-1]=r,kt(g),kt(l),c>=3){var v=i[c-3];v.left===g?v.left=l:v.right=l}break}}else{var w=g.right;if(w&&w._color===At)l._color=Et,g.right=pr(Et,w),g._color=At,c-=1;else{if(l.right=r.left,g._color=At,g.left=r.right,r._color=Et,r.left=l,r.right=g,i[c-2]=r,i[c-1]=l,kt(g),kt(l),kt(r),c>=3){var v=i[c-3];v.left===g?v.left=r:v.right=r}break}}else if(l.right===r){var w=g.left;if(w&&w._color===At)l._color=Et,g.left=pr(Et,w),g._color=At,c-=1;else{if(g._color=At,g.right=l.left,l._color=Et,l.left=g,i[c-2]=l,i[c-1]=r,kt(g),kt(l),c>=3){var v=i[c-3];v.right===g?v.right=l:v.left=l}break}}else{var w=g.left;if(w&&w._color===At)l._color=Et,g.left=pr(Et,w),g._color=At,c-=1;else{if(l.left=r.right,g._color=At,g.right=r.left,r._color=Et,r.right=l,r.left=g,i[c-2]=r,i[c-1]=l,kt(g),kt(l),kt(r),c>=3){var v=i[c-3];v.right===g?v.right=r:v.left=r}break}}}return i[0]._color=Et,new mr(e,i[0])};function ma(n,t){if(t.left){var e=ma(n,t.left);if(e)return e}var e=n(t.key,t.value);if(e)return e;if(t.right)return ma(n,t.right)}function ya(n,t,e,r){var i=t(n,r.key);if(i<=0){if(r.left){var o=ya(n,t,e,r.left);if(o)return o}var o=e(r.key,r.value);if(o)return o}if(r.right)return ya(n,t,e,r.right)}function wa(n,t,e,r,i){var o=e(n,i.key),s=e(t,i.key),c;if(o<=0&&(i.left&&(c=wa(n,t,e,r,i.left),c)||s>0&&(c=r(i.key,i.value),c)))return c;if(s>0&&i.right)return wa(n,t,e,r,i.right)}Yt.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return ma(t,this.root);case 2:return ya(e,this._compare,t,this.root);case 3:return this._compare(e,r)>=0?void 0:wa(e,r,this._compare,t,this.root)}};Object.defineProperty(Yt,"begin",{get:function(){for(var n=[],t=this.root;t;)n.push(t),t=t.left;return new ce(this,n)}});Object.defineProperty(Yt,"end",{get:function(){for(var n=[],t=this.root;t;)n.push(t),t=t.right;return new ce(this,n)}});Yt.at=function(n){if(n<0)return new ce(this,[]);for(var t=this.root,e=[];;){if(e.push(t),t.left){if(n=t.right._count)break;t=t.right}else break}return new ce(this,[])};Yt.ge=function(n){for(var t=this._compare,e=this.root,r=[],i=0;e;){var o=t(n,e.key);r.push(e),o<=0&&(i=r.length),o<=0?e=e.left:e=e.right}return r.length=i,new ce(this,r)};Yt.gt=function(n){for(var t=this._compare,e=this.root,r=[],i=0;e;){var o=t(n,e.key);r.push(e),o<0&&(i=r.length),o<0?e=e.left:e=e.right}return r.length=i,new ce(this,r)};Yt.lt=function(n){for(var t=this._compare,e=this.root,r=[],i=0;e;){var o=t(n,e.key);r.push(e),o>0&&(i=r.length),o<=0?e=e.left:e=e.right}return r.length=i,new ce(this,r)};Yt.le=function(n){for(var t=this._compare,e=this.root,r=[],i=0;e;){var o=t(n,e.key);r.push(e),o>=0&&(i=r.length),o<0?e=e.left:e=e.right}return r.length=i,new ce(this,r)};Yt.find=function(n){for(var t=this._compare,e=this.root,r=[];e;){var i=t(n,e.key);if(r.push(e),i===0)return new ce(this,r);i<=0?e=e.left:e=e.right}return new ce(this,[])};Yt.remove=function(n){var t=this.find(n);return t?t.remove():this};Yt.get=function(n){for(var t=this._compare,e=this.root;e;){var r=t(n,e.key);if(r===0)return e.value;r<=0?e=e.left:e=e.right}};function ce(n,t){this.tree=n,this._stack=t}var me=ce.prototype;Object.defineProperty(me,"valid",{get:function(){return this._stack.length>0}});Object.defineProperty(me,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0});me.clone=function(){return new ce(this.tree,this._stack.slice())};function Ll(n,t){n.key=t.key,n.value=t.value,n.left=t.left,n.right=t.right,n._color=t._color,n._count=t._count}function yd(n){for(var t,e,r,i,o=n.length-1;o>=0;--o){if(t=n[o],o===0){t._color=Et;return}if(e=n[o-1],e.left===t){if(r=e.right,r.right&&r.right._color===At){if(r=e.right=Re(r),i=r.right=Re(r.right),e.right=r.left,r.left=e,r.right=i,r._color=e._color,t._color=Et,e._color=Et,i._color=Et,kt(e),kt(r),o>1){var s=n[o-2];s.left===e?s.left=r:s.right=r}n[o-1]=r;return}else if(r.left&&r.left._color===At){if(r=e.right=Re(r),i=r.left=Re(r.left),e.right=i.left,r.left=i.right,i.left=e,i.right=r,i._color=e._color,e._color=Et,r._color=Et,t._color=Et,kt(e),kt(r),kt(i),o>1){var s=n[o-2];s.left===e?s.left=i:s.right=i}n[o-1]=i;return}if(r._color===Et)if(e._color===At){e._color=Et,e.right=pr(At,r);return}else{e.right=pr(At,r);continue}else{if(r=Re(r),e.right=r.left,r.left=e,r._color=e._color,e._color=At,kt(e),kt(r),o>1){var s=n[o-2];s.left===e?s.left=r:s.right=r}n[o-1]=r,n[o]=e,o+11){var s=n[o-2];s.right===e?s.right=r:s.left=r}n[o-1]=r;return}else if(r.right&&r.right._color===At){if(r=e.left=Re(r),i=r.right=Re(r.right),e.left=i.right,r.right=i.left,i.right=e,i.left=r,i._color=e._color,e._color=Et,r._color=Et,t._color=Et,kt(e),kt(r),kt(i),o>1){var s=n[o-2];s.right===e?s.right=i:s.left=i}n[o-1]=i;return}if(r._color===Et)if(e._color===At){e._color=Et,e.left=pr(At,r);return}else{e.left=pr(At,r);continue}else{if(r=Re(r),e.left=r.right,r.right=e,r._color=e._color,e._color=At,kt(e),kt(r),o>1){var s=n[o-2];s.right===e?s.right=r:s.left=r}n[o-1]=r,n[o]=e,o+1=0;--r){var e=n[r];e.left===n[r+1]?t[r]=new ae(e._color,e.key,e.value,t[r+1],e.right,e._count):t[r]=new ae(e._color,e.key,e.value,e.left,t[r+1],e._count)}if(e=t[t.length-1],e.left&&e.right){var i=t.length;for(e=e.left;e.right;)t.push(e),e=e.right;var o=t[i-1];t.push(new ae(e._color,o.key,o.value,e.left,e.right,e._count)),t[i-1].key=e.key,t[i-1].value=e.value;for(var r=t.length-2;r>=i;--r)e=t[r],t[r]=new ae(e._color,e.key,e.value,e.left,t[r+1],e._count);t[i-1].left=t[i]}if(e=t[t.length-1],e._color===At){var s=t[t.length-2];s.left===e?s.left=null:s.right===e&&(s.right=null),t.pop();for(var r=0;r0)return this._stack[this._stack.length-1].key},enumerable:!0});Object.defineProperty(me,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0});Object.defineProperty(me,"index",{get:function(){var n=0,t=this._stack;if(t.length===0){var e=this.tree.root;return e?e._count:0}else t[t.length-1].left&&(n=t[t.length-1].left._count);for(var r=t.length-2;r>=0;--r)t[r+1]===t[r].right&&(++n,t[r].left&&(n+=t[r].left._count));return n},enumerable:!0});me.next=function(){var n=this._stack;if(n.length!==0){var t=n[n.length-1];if(t.right)for(t=t.right;t;)n.push(t),t=t.left;else for(n.pop();n.length>0&&n[n.length-1].right===t;)t=n[n.length-1],n.pop()}};Object.defineProperty(me,"hasNext",{get:function(){var n=this._stack;if(n.length===0)return!1;if(n[n.length-1].right)return!0;for(var t=n.length-1;t>0;--t)if(n[t-1].left===n[t])return!0;return!1}});me.update=function(n){var t=this._stack;if(t.length===0)throw new Error("Can't update empty node!");var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new ae(r._color,r.key,n,r.left,r.right,r._count);for(var i=t.length-2;i>=0;--i)r=t[i],r.left===t[i+1]?e[i]=new ae(r._color,r.key,r.value,e[i+1],r.right,r._count):e[i]=new ae(r._color,r.key,r.value,r.left,e[i+1],r._count);return new mr(this.tree._compare,e[0])};me.prev=function(){var n=this._stack;if(n.length!==0){var t=n[n.length-1];if(t.left)for(t=t.left;t;)n.push(t),t=t.right;else for(n.pop();n.length>0&&n[n.length-1].left===t;)t=n[n.length-1],n.pop()}};Object.defineProperty(me,"hasPrev",{get:function(){var n=this._stack;if(n.length===0)return!1;if(n[n.length-1].left)return!0;for(var t=n.length-1;t>0;--t)if(n[t-1].right===n[t])return!0;return!1}});function wd(n,t){return nt?1:0}function vd(n){return new mr(n||wd,null)}});var Wl=nt(Ul=>{"use strict";b();var{AbstractLevel:_d,AbstractIterator:bd,AbstractKeyIterator:Sd,AbstractValueIterator:Ed}=Eo(),Bl=ge(),Pl=Rl(),Td=new Set(["gt","gte","lt","lte"]),Je=Symbol("none"),Gt=Symbol("tree"),vt=Symbol("iterator"),ue=Symbol("lowerBound"),yr=Symbol("upperBound"),Nl=Symbol("outOfRange"),Co=Symbol("reverse"),va=Symbol("options"),ne=Symbol("test"),ye=Symbol("advance"),Oo=Symbol("init");function Be(n,t){if(typeof n=="string")return nt?1:0;let e=Math.min(n.byteLength,t.byteLength);for(let r=0;r0}function Cd(n){return Be(n,this[yr])>=0}function Id(n){return Be(n,this[yr])<0}function Ad(n){return Be(n,this[yr])<=0}var Io=class extends bd{constructor(t,e){super(t,e),this[Oo](t[Gt],e)}_next(t){if(!this[vt].valid)return this.nextTick(t);let e=this[vt].key,r=this[vt].value;if(!this[ne](e))return this.nextTick(t);this[vt][this[ye]](),this.nextTick(t,null,e,r)}_nextv(t,e,r){let i=this[vt],o=[];for(;i.valid&&o.length0:Be(t,this[ue])>=0:"gte"in this[va]?Be(t,this[ue])<0:Be(t,this[ue])<=0:!0},n.prototype._seek=function(t,e){this[Nl](t)?(this[vt]=this[vt].tree.end,this[vt].next()):this[Co]?this[vt]=this[vt].tree.le(t):this[vt]=this[vt].tree.ge(t)};var Lo=class extends _d{constructor(t,e,r){if(typeof t=="object"&&t!==null&&(e=t),typeof t=="function"||typeof e=="function"||typeof r=="function")throw new Bl("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{storeEncoding:i,...o}=e||{};if(i=i||"buffer",!["buffer","view","utf8"].includes(i))throw new Bl("The storeEncoding option must be 'buffer', 'view' or 'utf8'",{code:"LEVEL_ENCODING_NOT_SUPPORTED"});super({seek:!0,permanence:!1,createIfMissing:!1,errorIfExists:!1,encodings:{[i]:!0}},o),this[Gt]=Pl(Be)}_put(t,e,r,i){let o=this[Gt].find(t);o.valid?this[Gt]=o.update(e):this[Gt]=this[Gt].insert(t,e),this.nextTick(i)}_get(t,e,r){let i=this[Gt].get(t);if(typeof i>"u")return this.nextTick(r,new Error("NotFound"));this.nextTick(r,null,i)}_getMany(t,e,r){this.nextTick(r,null,t.map(i=>this[Gt].get(i)))}_del(t,e,r){this[Gt]=this[Gt].remove(t),this.nextTick(r)}_batch(t,e,r){let i=this[Gt];for(let o of t){let s=o.key,c=i.find(s);o.type==="put"?i=c.valid?c.update(o.value):i.insert(s,o.value):i=c.remove()}this[Gt]=i,this.nextTick(r)}_clear(t,e){if(t.limit===-1&&!Object.keys(t).some(kd))return this[Gt]=Pl(Be),this.nextTick(e);let r=this._keys({...t}),i=r.limit,o=0,s=()=>{for(let c=0;c<500;c++){if(++o>i||!r[vt].valid||!r[ne](r[vt].key))return e();this[Gt]=this[Gt].remove(r[vt].key),r[vt][r[ye]]()}this.nextTick(s)};this.nextTick(s)}_iterator(t){return new Io(this,t)}_keys(t){return new Ao(this,t)}_values(t){return new ko(this,t)}};Ul.MemoryLevel=Lo;if(typeof $.default<"u"&&!$.default.browser&&typeof K<"u"&&typeof K.setImmediate=="function"){let n=K.setImmediate;Lo.prototype.nextTick=function(t,...e){e.length===0?n(t):n(()=>t(...e))}}function kd(n){return Td.has(n)}});var wr=nt((u0,ba)=>{b();typeof window<"u"?(window.global=window,K.fetch=window.fetch,ba.exports={Buffer:Ar().Buffer,Crypto:window.crypto}):ba.exports={Buffer:Ar().Buffer,Crypto:crypto}});var ka=nt((Yl,Wo)=>{b();(function(n){"use strict";var t,e=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,i=Math.floor,o="[BigNumber Error] ",s=o+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,g=9007199254740991,w=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],v=1e7,E=1e9;function d(D){var G,it,et,O=Y.prototype={constructor:Y,toString:null,valueOf:null},ft=new Y(1),tt=20,lt=4,at=-7,wt=21,Nt=-1e7,Tt=1e7,ht=!1,_t=1,Ut=0,Me={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},yt="0123456789abcdefghijklmnopqrstuvwxyz",Lt=!0;function Y(p,_){var S,U,C,R,W,x,A,B,P=this;if(!(P instanceof Y))return new Y(p,_);if(_==null){if(p&&p._isBigNumber===!0){P.s=p.s,!p.c||p.e>Tt?P.c=P.e=null:p.e=10;W/=10,R++);R>Tt?P.c=P.e=null:(P.e=R,P.c=[p]);return}B=String(p)}else{if(!e.test(B=String(p)))return et(P,B,x);P.s=B.charCodeAt(0)==45?(B=B.slice(1),-1):1}(R=B.indexOf("."))>-1&&(B=B.replace(".","")),(W=B.search(/e/i))>0?(R<0&&(R=W),R+=+B.slice(W+1),B=B.substring(0,W)):R<0&&(R=B.length)}else{if(q(_,2,yt.length,"Base"),_==10&&Lt)return P=new Y(p),Vt(P,tt+P.e+1,lt);if(B=String(p),x=typeof p=="number"){if(p*0!=0)return et(P,B,x,_);if(P.s=1/p<0?(B=B.slice(1),-1):1,Y.DEBUG&&B.replace(/^0\.0*|\./,"").length>15)throw Error(s+p)}else P.s=B.charCodeAt(0)===45?(B=B.slice(1),-1):1;for(S=yt.slice(0,_),R=W=0,A=B.length;WR){R=A;continue}}else if(!C&&(B==B.toUpperCase()&&(B=B.toLowerCase())||B==B.toLowerCase()&&(B=B.toUpperCase()))){C=!0,W=-1,R=0;continue}return et(P,String(p),x,_)}x=!1,B=it(B,_,10,P.s),(R=B.indexOf("."))>-1?B=B.replace(".",""):R=B.length}for(W=0;B.charCodeAt(W)===48;W++);for(A=B.length;B.charCodeAt(--A)===48;);if(B=B.slice(W,++A)){if(A-=W,x&&Y.DEBUG&&A>15&&(p>g||p!==i(p)))throw Error(s+P.s*p);if((R=R-W-1)>Tt)P.c=P.e=null;else if(R=-E&&C<=E&&C===i(C)){if(U[0]===0){if(C===0&&U.length===1)return!0;break t}if(_=(C+1)%l,_<1&&(_+=l),String(U[0]).length==_){for(_=0;_=c||S!==i(S))break t;if(S!==0)return!0}}}else if(U===null&&C===null&&(R===null||R===1||R===-1))return!0;throw Error(o+"Invalid BigNumber: "+p)},Y.maximum=Y.max=function(){return xr(arguments,O.lt)},Y.minimum=Y.min=function(){return xr(arguments,O.gt)},Y.random=function(){var p=9007199254740992,_=Math.random()*p&2097151?function(){return i(Math.random()*p)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(S){var U,C,R,W,x,A=0,B=[],P=new Y(ft);if(S==null?S=tt:q(S,0,E),W=r(S/l),ht)if(crypto.getRandomValues){for(U=crypto.getRandomValues(new Uint32Array(W*=2));A>>11),x>=9e15?(C=crypto.getRandomValues(new Uint32Array(2)),U[A]=C[0],U[A+1]=C[1]):(B.push(x%1e14),A+=2);A=W/2}else if(crypto.randomBytes){for(U=crypto.randomBytes(W*=7);A=9e15?crypto.randomBytes(7).copy(U,A):(B.push(x%1e14),A+=7);A=W/7}else throw ht=!1,Error(o+"crypto unavailable");if(!ht)for(;A=10;x/=10,A++);AC-1&&(x[W+1]==null&&(x[W+1]=0),x[W+1]+=x[W]/C|0,x[W]%=C)}return x.reverse()}return function(S,U,C,R,W){var x,A,B,P,H,h,m,I,j=S.indexOf("."),Z=tt,rt=lt;for(j>=0&&(P=Ut,Ut=0,S=S.replace(".",""),I=new Y(U),h=I.pow(S.length-j),Ut=P,I.c=_(X(k(h.c),h.e,"0"),10,C,p),I.e=I.c.length),m=_(S,U,C,W?(x=yt,p):(x=p,yt)),B=P=m.length;m[--P]==0;m.pop());if(!m[0])return x.charAt(0);if(j<0?--B:(h.c=m,h.e=B,h.s=R,h=G(h,I,Z,rt,C),m=h.c,H=h.r,B=h.e),A=B+Z+1,j=m[A],P=C/2,H=H||A<0||m[A+1]!=null,H=rt<4?(j!=null||H)&&(rt==0||rt==(h.s<0?3:2)):j>P||j==P&&(rt==4||H||rt==6&&m[A-1]&1||rt==(h.s<0?8:7)),A<1||!m[0])S=H?X(x.charAt(1),-Z,x.charAt(0)):x.charAt(0);else{if(m.length=A,H)for(--C;++m[--A]>C;)m[A]=0,A||(++B,m=[1].concat(m));for(P=m.length;!m[--P];);for(j=0,S="";j<=P;S+=x.charAt(m[j++]));S=X(S,B,x.charAt(0))}return S}}(),G=function(){function p(U,C,R){var W,x,A,B,P=0,H=U.length,h=C%v,m=C/v|0;for(U=U.slice();H--;)A=U[H]%v,B=U[H]/v|0,W=m*A+B*h,x=h*A+W%v*v+P,P=(x/R|0)+(W/v|0)+m*B,U[H]=x%R;return P&&(U=[P].concat(U)),U}function _(U,C,R,W){var x,A;if(R!=W)A=R>W?1:-1;else for(x=A=0;xC[x]?1:-1;break}return A}function S(U,C,R,W){for(var x=0;R--;)U[R]-=x,x=U[R]1;U.splice(0,1));}return function(U,C,R,W,x){var A,B,P,H,h,m,I,j,Z,rt,a,u,f,T,L,M,J,dt=U.s==C.s?1:-1,bt=U.c,ut=C.c;if(!bt||!bt[0]||!ut||!ut[0])return new Y(!U.s||!C.s||(bt?ut&&bt[0]==ut[0]:!ut)?NaN:bt&&bt[0]==0||!ut?dt*0:dt/0);for(j=new Y(dt),Z=j.c=[],B=U.e-C.e,dt=R+B+1,x||(x=c,B=y(U.e/l)-y(C.e/l),dt=dt/l|0),P=0;ut[P]==(bt[P]||0);P++);if(ut[P]>(bt[P]||0)&&B--,dt<0)Z.push(1),H=!0;else{for(T=bt.length,M=ut.length,P=0,dt+=2,h=i(x/(ut[0]+1)),h>1&&(ut=p(ut,h,x),bt=p(bt,h,x),M=ut.length,T=bt.length),f=M,rt=bt.slice(0,M),a=rt.length;a=x/2&&L++;do{if(h=0,A=_(ut,rt,M,a),A<0){if(u=rt[0],M!=a&&(u=u*x+(rt[1]||0)),h=i(u/L),h>1)for(h>=x&&(h=x-1),m=p(ut,h,x),I=m.length,a=rt.length;_(m,rt,I,a)==1;)h--,S(m,M=10;dt/=10,P++);Vt(j,R+(j.e=P+B*l-1)+1,W,H)}else j.e=B,j.r=+H;return j}}();function nr(p,_,S,U){var C,R,W,x,A;if(S==null?S=lt:q(S,0,8),!p.c)return p.toString();if(C=p.c[0],W=p.e,_==null)A=k(p.c),A=U==1||U==2&&(W<=at||W>=wt)?z(A,W):X(A,W,"0");else if(p=Vt(new Y(p),_,S),R=p.e,A=k(p.c),x=A.length,U==1||U==2&&(_<=R||R<=at)){for(;x<_;A+="0",x++);A=z(A,R)}else if(_-=W,A=X(A,R,"0"),R+1>x){if(--_>0)for(A+=".";_--;A+="0");}else if(_+=R-x,_>0)for(R+1==x&&(A+=".");_--;A+="0");return p.s<0&&C?"-"+A:A}function xr(p,_){for(var S,U=1,C=new Y(p[0]);U=10;C/=10,U++);return(S=U+S*l-1)>Tt?p.c=p.e=null:S=10;x/=10,C++);if(R=_-C,R<0)R+=l,W=_,A=H[B=0],P=A/h[C-W-1]%10|0;else if(B=r((R+1)/l),B>=H.length)if(U){for(;H.length<=B;H.push(0));A=P=0,C=1,R%=l,W=R-l+1}else break t;else{for(A=x=H[B],C=1;x>=10;x/=10,C++);R%=l,W=R-l+C,P=W<0?0:A/h[C-W-1]%10|0}if(U=U||_<0||H[B+1]!=null||(W<0?A:A%h[C-W-1]),U=S<4?(P||U)&&(S==0||S==(p.s<0?3:2)):P>5||P==5&&(S==4||U||S==6&&(R>0?W>0?A/h[C-W]:0:H[B-1])%10&1||S==(p.s<0?8:7)),_<1||!H[0])return H.length=0,U?(_-=p.e+1,H[0]=h[(l-_%l)%l],p.e=-_||0):H[0]=p.e=0,p;if(R==0?(H.length=B,x=1,B--):(H.length=B+1,x=h[l-R],H[B]=W>0?i(A/h[C-W]%h[W])*x:0),U)for(;;)if(B==0){for(R=1,W=H[0];W>=10;W/=10,R++);for(W=H[0]+=x,x=1;W>=10;W/=10,x++);R!=x&&(p.e++,H[0]==c&&(H[0]=1));break}else{if(H[B]+=x,H[B]!=c)break;H[B--]=0,x=1}for(R=H.length;H[--R]===0;H.pop());}p.e>Tt?p.c=p.e=null:p.e=wt?z(_,S):X(_,S,"0"),p.s<0?"-"+_:_)}return O.absoluteValue=O.abs=function(){var p=new Y(this);return p.s<0&&(p.s=1),p},O.comparedTo=function(p,_){return N(this,new Y(p,_))},O.decimalPlaces=O.dp=function(p,_){var S,U,C,R=this;if(p!=null)return q(p,0,E),_==null?_=lt:q(_,0,8),Vt(new Y(R),p+R.e+1,_);if(!(S=R.c))return null;if(U=((C=S.length-1)-y(this.e/l))*l,C=S[C])for(;C%10==0;C/=10,U--);return U<0&&(U=0),U},O.dividedBy=O.div=function(p,_){return G(this,new Y(p,_),tt,lt)},O.dividedToIntegerBy=O.idiv=function(p,_){return G(this,new Y(p,_),0,1)},O.exponentiatedBy=O.pow=function(p,_){var S,U,C,R,W,x,A,B,P,H=this;if(p=new Y(p),p.c&&!p.isInteger())throw Error(o+"Exponent not an integer: "+Ft(p));if(_!=null&&(_=new Y(_)),x=p.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!p.c||!p.c[0])return P=new Y(Math.pow(+Ft(H),x?p.s*(2-Q(p)):+Ft(p))),_?P.mod(_):P;if(A=p.s<0,_){if(_.c?!_.c[0]:!_.s)return new Y(NaN);U=!A&&H.isInteger()&&_.isInteger(),U&&(H=H.mod(_))}else{if(p.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||x&&H.c[1]>=24e7:H.c[0]<8e13||x&&H.c[0]<=9999975e7)))return R=H.s<0&&Q(p)?-0:0,H.e>-1&&(R=1/R),new Y(A?1/R:R);Ut&&(R=r(Ut/l+2))}for(x?(S=new Y(.5),A&&(p.s=1),B=Q(p)):(C=Math.abs(+Ft(p)),B=C%2),P=new Y(ft);;){if(B){if(P=P.times(H),!P.c)break;R?P.c.length>R&&(P.c.length=R):U&&(P=P.mod(_))}if(C){if(C=i(C/2),C===0)break;B=C%2}else if(p=p.times(S),Vt(p,p.e+1,1),p.e>14)B=Q(p);else{if(C=+Ft(p),C===0)break;B=C%2}H=H.times(H),R?H.c&&H.c.length>R&&(H.c.length=R):U&&(H=H.mod(_))}return U?P:(A&&(P=ft.div(P)),_?P.mod(_):R?Vt(P,Ut,lt,W):P)},O.integerValue=function(p){var _=new Y(this);return p==null?p=lt:q(p,0,8),Vt(_,_.e+1,p)},O.isEqualTo=O.eq=function(p,_){return N(this,new Y(p,_))===0},O.isFinite=function(){return!!this.c},O.isGreaterThan=O.gt=function(p,_){return N(this,new Y(p,_))>0},O.isGreaterThanOrEqualTo=O.gte=function(p,_){return(_=N(this,new Y(p,_)))===1||_===0},O.isInteger=function(){return!!this.c&&y(this.e/l)>this.c.length-2},O.isLessThan=O.lt=function(p,_){return N(this,new Y(p,_))<0},O.isLessThanOrEqualTo=O.lte=function(p,_){return(_=N(this,new Y(p,_)))===-1||_===0},O.isNaN=function(){return!this.s},O.isNegative=function(){return this.s<0},O.isPositive=function(){return this.s>0},O.isZero=function(){return!!this.c&&this.c[0]==0},O.minus=function(p,_){var S,U,C,R,W=this,x=W.s;if(p=new Y(p,_),_=p.s,!x||!_)return new Y(NaN);if(x!=_)return p.s=-_,W.plus(p);var A=W.e/l,B=p.e/l,P=W.c,H=p.c;if(!A||!B){if(!P||!H)return P?(p.s=-_,p):new Y(H?W:NaN);if(!P[0]||!H[0])return H[0]?(p.s=-_,p):new Y(P[0]?W:lt==3?-0:0)}if(A=y(A),B=y(B),P=P.slice(),x=A-B){for((R=x<0)?(x=-x,C=P):(B=A,C=H),C.reverse(),_=x;_--;C.push(0));C.reverse()}else for(U=(R=(x=P.length)<(_=H.length))?x:_,x=_=0;_0)for(;_--;P[S++]=0);for(_=c-1;U>x;){if(P[--U]=0;){for(S=0,h=u[C]%Z,m=u[C]/Z|0,W=A,R=C+W;R>C;)B=a[--W]%Z,P=a[W]/Z|0,x=m*B+P*h,B=h*B+x%Z*Z+I[R]+S,S=(B/j|0)+(x/Z|0)+m*P,I[R--]=B%j;I[R]=S}return S?++U:I.splice(0,1),ir(p,I,U)},O.negated=function(){var p=new Y(this);return p.s=-p.s||null,p},O.plus=function(p,_){var S,U=this,C=U.s;if(p=new Y(p,_),_=p.s,!C||!_)return new Y(NaN);if(C!=_)return p.s=-_,U.minus(p);var R=U.e/l,W=p.e/l,x=U.c,A=p.c;if(!R||!W){if(!x||!A)return new Y(C/0);if(!x[0]||!A[0])return A[0]?p:new Y(x[0]?U:C*0)}if(R=y(R),W=y(W),x=x.slice(),C=R-W){for(C>0?(W=R,S=A):(C=-C,S=x),S.reverse();C--;S.push(0));S.reverse()}for(C=x.length,_=A.length,C-_<0&&(S=A,A=x,x=S,_=C),C=0;_;)C=(x[--_]=x[_]+A[_]+C)/c|0,x[_]=c===x[_]?0:x[_]%c;return C&&(x=[C].concat(x),++W),ir(p,x,W)},O.precision=O.sd=function(p,_){var S,U,C,R=this;if(p!=null&&p!==!!p)return q(p,1,E),_==null?_=lt:q(_,0,8),Vt(new Y(R),p,_);if(!(S=R.c))return null;if(C=S.length-1,U=C*l+1,C=S[C]){for(;C%10==0;C/=10,U--);for(C=S[0];C>=10;C/=10,U++);}return p&&R.e+1>U&&(U=R.e+1),U},O.shiftedBy=function(p){return q(p,-g,g),this.times("1e"+p)},O.squareRoot=O.sqrt=function(){var p,_,S,U,C,R=this,W=R.c,x=R.s,A=R.e,B=tt+4,P=new Y("0.5");if(x!==1||!W||!W[0])return new Y(!x||x<0&&(!W||W[0])?NaN:W?R:1/0);if(x=Math.sqrt(+Ft(R)),x==0||x==1/0?(_=k(W),(_.length+A)%2==0&&(_+="0"),x=Math.sqrt(+_),A=y((A+1)/2)-(A<0||A%2),x==1/0?_="5e"+A:(_=x.toExponential(),_=_.slice(0,_.indexOf("e")+1)+A),S=new Y(_)):S=new Y(x+""),S.c[0]){for(A=S.e,x=A+B,x<3&&(x=0);;)if(C=S,S=P.times(C.plus(G(R,C,B,1))),k(C.c).slice(0,x)===(_=k(S.c)).slice(0,x))if(S.e0&&I>0){for(R=I%x||x,P=m.substr(0,R);R0&&(P+=B+m.slice(R)),h&&(P="-"+P)}U=H?P+(S.decimalSeparator||"")+((A=+S.fractionGroupSize)?H.replace(new RegExp("\\d{"+A+"}\\B","g"),"$&"+(S.fractionGroupSeparator||"")):H):P}return(S.prefix||"")+U+(S.suffix||"")},O.toFraction=function(p){var _,S,U,C,R,W,x,A,B,P,H,h,m=this,I=m.c;if(p!=null&&(x=new Y(p),!x.isInteger()&&(x.c||x.s!==1)||x.lt(ft)))throw Error(o+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+Ft(x));if(!I)return new Y(m);for(_=new Y(ft),B=S=new Y(ft),U=A=new Y(ft),h=k(I),R=_.e=h.length-m.e-1,_.c[0]=w[(W=R%l)<0?l+W:W],p=!p||x.comparedTo(_)>0?R>0?_:B:x,W=Tt,Tt=1/0,x=new Y(h),A.c[0]=0;P=G(x,_,0,1),C=S.plus(P.times(U)),C.comparedTo(p)!=1;)S=U,U=C,B=A.plus(P.times(C=B)),A=C,_=x.minus(P.times(C=_)),x=C;return C=G(p.minus(S),U,0,1),A=A.plus(C.times(B)),S=S.plus(C.times(U)),A.s=B.s=m.s,R=R*2,H=G(B,U,R,lt).minus(m).abs().comparedTo(G(A,S,R,lt).minus(m).abs())<1?[B,U]:[A,S],Tt=W,H},O.toNumber=function(){return+Ft(this)},O.toPrecision=function(p,_){return p!=null&&q(p,1,E),nr(this,p,_,2)},O.toString=function(p){var _,S=this,U=S.s,C=S.e;return C===null?U?(_="Infinity",U<0&&(_="-"+_)):_="NaN":(p==null?_=C<=at||C>=wt?z(k(S.c),C):X(k(S.c),C,"0"):p===10&&Lt?(S=Vt(new Y(S),tt+C+1,lt),_=X(k(S.c),S.e,"0")):(q(p,2,yt.length,"Base"),_=it(X(k(S.c),C,"0"),10,p,U,!0)),U<0&&S.c[0]&&(_="-"+_)),_},O.valueOf=O.toJSON=function(){return Ft(this)},O._isBigNumber=!0,D!=null&&Y.set(D),Y}function y(D){var G=D|0;return D>0||D===G?G:G-1}function k(D){for(var G,it,et=1,O=D.length,ft=D[0]+"";etwt^it?1:-1;for(lt=(at=O.length)<(wt=ft.length)?at:wt,tt=0;ttft[tt]^it?1:-1;return at==wt?0:at>wt^it?1:-1}function q(D,G,it,et){if(Dit||D!==i(D))throw Error(o+(et||"Argument")+(typeof D=="number"?Dit?" out of range: ":" not an integer: ":" not a primitive number: ")+String(D))}function Q(D){var G=D.c.length-1;return y(D.e/l)==G&&D.c[G]%2!=0}function z(D,G){return(D.length>1?D.charAt(0)+"."+D.slice(1):D)+(G<0?"e":"e+")+G}function X(D,G,it){var et,O;if(G<0){for(O=it+".";++G;O+=it);D=O+D}else if(et=D.length,++G>et){for(O=it,G-=et;--G;O+=it);D+=O}else G{"use strict";b();Object.defineProperty(Ma,"__esModule",{value:!0});var bp=ka(),Da=class{BigNum;constructor(){this.BigNum=(t,e)=>{let r=bp.BigNumber.clone({DECIMAL_PLACES:e});return new r(t)}}winstonToAr(t,{formatted:e=!1,decimals:r=12,trim:i=!0}={}){let o=this.stringToBigNum(t,r).shiftedBy(-12);return e?o.toFormat(r):o.toFixed(r)}arToWinston(t,{formatted:e=!1}={}){let r=this.stringToBigNum(t).shiftedBy(12);return e?r.toFormat():r.toFixed(0)}compare(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.comparedTo(i)}isEqual(t,e){return this.compare(t,e)===0}isLessThan(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.isLessThan(i)}isGreaterThan(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.isGreaterThan(i)}add(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.plus(e).toFixed(0)}sub(t,e){let r=this.stringToBigNum(t),i=this.stringToBigNum(e);return r.minus(e).toFixed(0)}stringToBigNum(t,e=12){return this.BigNum(t,e)}};Ma.default=Da});var nf=nt($a=>{"use strict";b();Object.defineProperty($a,"__esModule",{value:!0});var Fa=class{METHOD_GET="GET";METHOD_POST="POST";config;constructor(t){this.applyConfig(t)}applyConfig(t){this.config=this.mergeDefaults(t)}getConfig(){return this.config}mergeDefaults(t){let e=t.protocol||"http",r=t.port||(e==="https"?443:80);return{host:t.host||"127.0.0.1",protocol:e,port:r,timeout:t.timeout||2e4,logging:t.logging||!1,logger:t.logger||console.log,network:t.network}}async get(t,e){return await this.request(t,{...e,method:this.METHOD_GET})}async post(t,e,r){let i=new Headers(r?.headers||{});return i.get("content-type")?.includes("application/json")||i.append("content-type","application/json"),i.append("accept","application/json, text/plain, */*"),await this.request(t,{...r,method:this.METHOD_POST,body:typeof e!="string"?JSON.stringify(e):e,headers:i})}async request(t,e){let r=new Headers(e?.headers||{}),i=`${this.config.protocol}://${this.config.host}:${this.config.port}`,o=e?.responseType;delete e?.responseType,t.startsWith("/")&&(t=t.slice(1)),this.config.network&&r.append("x-network",this.config.network),this.config.logging&&this.config.logger(`Requesting: ${i}/${t}`);let s=await fetch(`${i}/${t}`,{...e||{},headers:r});this.config.logging&&this.config.logger(`Response: ${s.url} - ${s.status}`);let l=s.headers.get("content-type")?.match(/charset=([^()<>@,;:\"/[\]?.=\s]*)/i)?.[1],g=s,w=async()=>{if(l)try{g.data=new TextDecoder(l).decode(await s.arrayBuffer())}catch{g.data=await s.text()}else g.data=await s.text()};if(o==="arraybuffer")g.data=await s.arrayBuffer();else if(o==="text")await w();else if(o==="webstream")g.data=Sp(s.body);else try{let v=await s.clone().json();typeof v!="object"?await w():g.data=await s.json(),v=null}catch{await w()}return g}};$a.default=Fa;var Sp=n=>{let t=n;return typeof t[Symbol.asyncIterator]>"u"?(t[Symbol.asyncIterator]=Ep(n),t):n},Ep=function(n){return async function*(){let e=n.getReader();try{for(;;){let{done:r,value:i}=await e.read();if(r)return;yield i}}finally{e.releaseLock()}}}});var Se=nt(Ot=>{"use strict";b();Object.defineProperty(Ot,"__esModule",{value:!0});Ot.b64UrlDecode=Ot.b64UrlEncode=Ot.bufferTob64Url=Ot.bufferTob64=Ot.b64UrlToBuffer=Ot.stringToB64Url=Ot.stringToBuffer=Ot.bufferToString=Ot.b64UrlToString=Ot.concatBuffers=void 0;var of=ps();function Tp(n){let t=0;for(let i=0;i{"use strict";b();Object.defineProperty(Va,"__esModule",{value:!0});var _r=Se(),Ka=class{keyLength=4096;publicExponent=65537;hashAlgorithm="sha256";driver;constructor(){if(!this.detectWebCrypto())throw new Error("SubtleCrypto not available!");this.driver=crypto.subtle}async generateJWK(){let t=await this.driver.generateKey({name:"RSA-PSS",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign"]),e=await this.driver.exportKey("jwk",t.privateKey);return{kty:e.kty,e:e.e,n:e.n,d:e.d,p:e.p,q:e.q,dp:e.dp,dq:e.dq,qi:e.qi}}async sign(t,e,{saltLength:r}={}){let i=await this.driver.sign({name:"RSA-PSS",saltLength:32},await this.jwkToCryptoKey(t),e);return new Uint8Array(i)}async hash(t,e="SHA-256"){let r=await this.driver.digest(e,t);return new Uint8Array(r)}async verify(t,e,r){let i={kty:"RSA",e:"AQAB",n:t},o=await this.jwkToPublicCryptoKey(i),s=await this.driver.digest("SHA-256",e),c=await this.driver.verify({name:"RSA-PSS",saltLength:0},o,r,e),l=await this.driver.verify({name:"RSA-PSS",saltLength:32},o,r,e),g=await this.driver.verify({name:"RSA-PSS",saltLength:Math.ceil((o.algorithm.modulusLength-1)/8)-s.byteLength-2},o,r,e);return c||l||g}async jwkToCryptoKey(t){return this.driver.importKey("jwk",t,{name:"RSA-PSS",hash:{name:"SHA-256"}},!1,["sign"])}async jwkToPublicCryptoKey(t){return this.driver.importKey("jwk",t,{name:"RSA-PSS",hash:{name:"SHA-256"}},!1,["verify"])}detectWebCrypto(){if(typeof crypto>"u")return!1;let t=crypto?.subtle;return t===void 0?!1:["generateKey","importKey","exportKey","digest","sign"].every(r=>typeof t[r]=="function")}async encrypt(t,e,r){let i=await this.driver.importKey("raw",typeof e=="string"?_r.stringToBuffer(e):e,{name:"PBKDF2",length:32},!1,["deriveKey"]),o=await this.driver.deriveKey({name:"PBKDF2",salt:r?_r.stringToBuffer(r):_r.stringToBuffer("salt"),iterations:1e5,hash:"SHA-256"},i,{name:"AES-CBC",length:256},!1,["encrypt","decrypt"]),s=new Uint8Array(16);crypto.getRandomValues(s);let c=await this.driver.encrypt({name:"AES-CBC",iv:s},o,t);return _r.concatBuffers([s,c])}async decrypt(t,e,r){let i=await this.driver.importKey("raw",typeof e=="string"?_r.stringToBuffer(e):e,{name:"PBKDF2",length:32},!1,["deriveKey"]),o=await this.driver.deriveKey({name:"PBKDF2",salt:r?_r.stringToBuffer(r):_r.stringToBuffer("salt"),iterations:1e5,hash:"SHA-256"},i,{name:"AES-CBC",length:256},!1,["encrypt","decrypt"]),s=t.slice(0,16),c=await this.driver.decrypt({name:"AES-CBC",iv:s},o,t.slice(16));return _r.concatBuffers([c])}};Va.default=Ka});var df=nt(qa=>{"use strict";b();Object.defineProperty(qa,"__esModule",{value:!0});var Ga=class{api;constructor(t){this.api=t}getInfo(){return this.api.get("info").then(t=>t.data)}getPeers(){return this.api.get("peers").then(t=>t.data)}};qa.default=Ga});var mi=nt(pi=>{"use strict";b();Object.defineProperty(pi,"__esModule",{value:!0});pi.getError=void 0;var ja=class extends Error{type;response;constructor(t,e={}){e.message?super(e.message):super(),this.type=t,this.response=e.response}getType(){return this.type}};pi.default=ja;function Ip(n){let t=n.data;if(typeof n.data=="string")try{t=JSON.parse(n.data)}catch{}if(n.data instanceof ArrayBuffer||n.data instanceof Uint8Array)try{t=JSON.parse(t.toString())}catch{}return t?t.error||t:n.statusText||"unknown"}pi.getError=Ip});var yf=nt(Ha=>{"use strict";b();Object.defineProperty(Ha,"__esModule",{value:!0});var le=yi();async function pf(n){if(Array.isArray(n)){let r=le.default.utils.concatBuffers([le.default.utils.stringToBuffer("list"),le.default.utils.stringToBuffer(n.length.toString())]);return await mf(n,await le.default.crypto.hash(r,"SHA-384"))}let t=le.default.utils.concatBuffers([le.default.utils.stringToBuffer("blob"),le.default.utils.stringToBuffer(n.byteLength.toString())]),e=le.default.utils.concatBuffers([await le.default.crypto.hash(t,"SHA-384"),await le.default.crypto.hash(n,"SHA-384")]);return await le.default.crypto.hash(e,"SHA-384")}Ha.default=pf;async function mf(n,t){if(n.length<1)return t;let e=le.default.utils.concatBuffers([t,await pf(n[0])]),r=await le.default.crypto.hash(e,"SHA-384");return await mf(n.slice(1),r)}});var Za=nt(pt=>{"use strict";b();Object.defineProperty(pt,"__esModule",{value:!0});pt.debug=pt.validatePath=pt.arrayCompare=pt.bufferToInt=pt.intToBuffer=pt.arrayFlatten=pt.generateProofs=pt.buildLayers=pt.generateTransactionChunks=pt.generateTree=pt.computeRootHash=pt.generateLeaves=pt.chunkData=pt.MIN_CHUNK_SIZE=pt.MAX_CHUNK_SIZE=void 0;var Mo=yi(),wf=Se();pt.MAX_CHUNK_SIZE=256*1024;pt.MIN_CHUNK_SIZE=32*1024;var vi=32,Sn=32;async function za(n){let t=[],e=n,r=0;for(;e.byteLength>=pt.MAX_CHUNK_SIZE;){let i=pt.MAX_CHUNK_SIZE,o=e.byteLength-pt.MAX_CHUNK_SIZE;o>0&&o({type:"leaf",id:await Kt(await Promise.all([Kt(t),Kt(_i(r))])),dataHash:t,minByteRange:e,maxByteRange:r})))}pt.generateLeaves=Ja;async function Ap(n){return(await vf(n)).id}pt.computeRootHash=Ap;async function vf(n){return await Fo(await Ja(await za(n)))}pt.generateTree=vf;async function kp(n){let t=await za(n),e=await Ja(t),r=await Fo(e),i=await _f(r),o=t.slice(-1)[0];return o.maxByteRange-o.minByteRange===0&&(t.splice(t.length-1,1),i.splice(i.length-1,1)),{data_root:r.id,chunks:t,proofs:i}}pt.generateTransactionChunks=kp;async function Fo(n,t=0){if(n.length<2)return n[0];let e=[];for(let r=0;r{Array.isArray(e)?t.push(...Ya(e)):t.push(e)}),t}pt.arrayFlatten=Ya;async function Lp(n,t){return t?{type:"branch",id:await Kt([await Kt(n.id),await Kt(t.id),await Kt(_i(n.maxByteRange))]),byteRange:n.maxByteRange,maxByteRange:t.maxByteRange,leftChild:n,rightChild:t}:n}async function Kt(n){return Array.isArray(n)&&(n=Mo.default.utils.concatBuffers(n)),new Uint8Array(await Mo.default.crypto.hash(n))}function _i(n){let t=new Uint8Array(vi);for(var e=t.length-1;e>=0;e--){var r=n%256;t[e]=r,n=(n-r)/256}return t}pt.intToBuffer=_i;function Xa(n){let t=0;for(var e=0;en.every((e,r)=>t[r]===e);pt.arrayCompare=Op;async function wi(n,t,e,r,i){if(r<=0)return!1;if(t>=r)return wi(n,0,r-1,r,i);if(t<0)return wi(n,0,0,r,i);if(i.length==Sn+vi){let v=i.slice(0,Sn),E=i.slice(v.length,v.length+vi),d=await Kt([await Kt(v),await Kt(E)]);return(0,pt.arrayCompare)(n,d)?{offset:r-1,leftBound:e,rightBound:r,chunkSize:r-e}:!1}let o=i.slice(0,Sn),s=i.slice(o.length,o.length+Sn),c=i.slice(o.length+s.length,o.length+s.length+vi),l=Xa(c),g=i.slice(o.length+s.length+c.length),w=await Kt([await Kt(o),await Kt(s),await Kt(c)]);return(0,pt.arrayCompare)(n,w)?t ${JSON.stringify(c)}`;return bf(s,l)}pt.debug=bf});var Ko=nt(Si=>{"use strict";b();Object.defineProperty(Si,"__esModule",{value:!0});Si.Tag=void 0;var Mt=Se(),Rp=yf(),Bp=Za(),$o=class{get(t,e){if(!Object.getOwnPropertyNames(this).includes(t))throw new Error(`Field "${t}" is not a property of the Arweave Transaction class.`);if(this[t]instanceof Uint8Array)return e&&e.decode&&e.string?Mt.bufferToString(this[t]):e&&e.decode&&!e.string?this[t]:Mt.bufferTob64Url(this[t]);if(this[t]instanceof Array){if(e?.decode!==void 0||e?.string!==void 0)throw t==="tags"&&console.warn(`Did you mean to use 'transaction["tags"]' ?`),new Error("Cannot decode or stringify an array.");return this[t]}return e&&e.decode==!0?e&&e.string?Mt.b64UrlToString(this[t]):Mt.b64UrlToBuffer(this[t]):this[t]}},bi=class extends $o{name;value;constructor(t,e,r=!1){super(),this.name=t,this.value=e}};Si.Tag=bi;var tc=class extends $o{format=2;id="";last_tx="";owner="";tags=[];target="";quantity="0";data_size="0";data=new Uint8Array;data_root="";reward="0";signature="";chunks;constructor(t={}){super(),Object.assign(this,t),typeof this.data=="string"&&(this.data=Mt.b64UrlToBuffer(this.data)),t.tags&&(this.tags=t.tags.map(e=>new bi(e.name,e.value)))}addTag(t,e){this.tags.push(new bi(Mt.stringToB64Url(t),Mt.stringToB64Url(e)))}toJSON(){return{format:this.format,id:this.id,last_tx:this.last_tx,owner:this.owner,tags:this.tags,target:this.target,quantity:this.quantity,data:Mt.bufferTob64Url(this.data),data_size:this.data_size,data_root:this.data_root,data_tree:this.data_tree,reward:this.reward,signature:this.signature}}setOwner(t){this.owner=t}setSignature({id:t,owner:e,reward:r,tags:i,signature:o}){this.id=t,this.owner=e,r&&(this.reward=r),i&&(this.tags=i),this.signature=o}async prepareChunks(t){!this.chunks&&t.byteLength>0&&(this.chunks=await(0,Bp.generateTransactionChunks)(t),this.data_root=Mt.bufferTob64Url(this.chunks.data_root)),!this.chunks&&t.byteLength===0&&(this.chunks={chunks:[],data_root:new Uint8Array,proofs:[]},this.data_root="")}getChunk(t,e){if(!this.chunks)throw new Error("Chunks have not been prepared");let r=this.chunks.proofs[t],i=this.chunks.chunks[t];return{data_root:this.data_root,data_size:this.data_size,data_path:Mt.bufferTob64Url(r.proof),offset:r.offset.toString(),chunk:Mt.bufferTob64Url(e.slice(i.minByteRange,i.maxByteRange))}}async getSignatureData(){switch(this.format){case 1:let t=this.tags.reduce((r,i)=>Mt.concatBuffers([r,i.get("name",{decode:!0,string:!1}),i.get("value",{decode:!0,string:!1})]),new Uint8Array);return Mt.concatBuffers([this.get("owner",{decode:!0,string:!1}),this.get("target",{decode:!0,string:!1}),this.get("data",{decode:!0,string:!1}),Mt.stringToBuffer(this.quantity),Mt.stringToBuffer(this.reward),this.get("last_tx",{decode:!0,string:!1}),t]);case 2:this.data_root||await this.prepareChunks(this.data);let e=this.tags.map(r=>[r.get("name",{decode:!0,string:!1}),r.get("value",{decode:!0,string:!1})]);return await(0,Rp.default)([Mt.stringToBuffer(this.format.toString()),this.get("owner",{decode:!0,string:!1}),this.get("target",{decode:!0,string:!1}),Mt.stringToBuffer(this.quantity),Mt.stringToBuffer(this.reward),this.get("last_tx",{decode:!0,string:!1}),e,Mt.stringToBuffer(this.data_size),this.get("data_root",{decode:!0,string:!1})]);default:throw new Error(`Unexpected transaction format: ${this.format}`)}}};Si.default=tc});var xf=nt(Vo=>{"use strict";b();Object.defineProperty(Vo,"__esModule",{value:!0});Vo.TransactionUploader=void 0;var Sf=Ko(),Pp=Se(),ec=mi(),Np=Za(),Ef=1,Up=["invalid_json","chunk_too_big","data_path_too_big","offset_too_big","data_size_too_big","chunk_proof_ratio_not_attractive","invalid_proof"],Tf=1e3*40,Ei=class{api;chunkIndex=0;txPosted=!1;transaction;lastRequestTimeEnd=0;totalErrors=0;data;lastResponseStatus=0;lastResponseError="";get isComplete(){return this.txPosted&&this.chunkIndex===this.transaction.chunks.chunks.length}get totalChunks(){return this.transaction.chunks.chunks.length}get uploadedChunks(){return this.chunkIndex}get pctComplete(){return Math.trunc(this.uploadedChunks/this.totalChunks*100)}constructor(t,e){if(this.api=t,!e.id)throw new Error("Transaction is not signed");if(!e.chunks)throw new Error("Transaction chunks not prepared");this.data=e.data,this.transaction=new Sf.default(Object.assign({},e,{data:new Uint8Array(0)}))}async uploadChunk(t){if(this.isComplete)throw new Error("Upload is already complete");if(this.lastResponseError!==""?this.totalErrors++:this.totalErrors=0,this.totalErrors===100)throw new Error(`Unable to complete upload: ${this.lastResponseStatus}: ${this.lastResponseError}`);let e=this.lastResponseError===""?0:Math.max(this.lastRequestTimeEnd+Tf-Date.now(),Tf);if(e>0&&(e=e-e*Math.random()*.3,await new Promise(s=>setTimeout(s,e))),this.lastResponseError="",!this.txPosted){await this.postTransaction();return}t&&(this.chunkIndex=t);let r=this.transaction.getChunk(t||this.chunkIndex,this.data);if(!await(0,Np.validatePath)(this.transaction.chunks.data_root,parseInt(r.offset),0,parseInt(r.data_size),Pp.b64UrlToBuffer(r.data_path)))throw new Error(`Unable to validate chunk ${this.chunkIndex}`);let o=await this.api.post("chunk",this.transaction.getChunk(this.chunkIndex,this.data)).catch(s=>(console.error(s.message),{status:-1,data:{error:s.message}}));if(this.lastRequestTimeEnd=Date.now(),this.lastResponseStatus=o.status,this.lastResponseStatus==200)this.chunkIndex++;else if(this.lastResponseError=(0,ec.getError)(o),Up.includes(this.lastResponseError))throw new Error(`Fatal error uploading chunk ${this.chunkIndex}: ${this.lastResponseError}`)}static async fromSerialized(t,e,r){if(!e||typeof e.chunkIndex!="number"||typeof e.transaction!="object")throw new Error("Serialized object does not match expected format.");var i=new Sf.default(e.transaction);i.chunks||await i.prepareChunks(r);let o=new Ei(t,i);if(o.chunkIndex=e.chunkIndex,o.lastRequestTimeEnd=e.lastRequestTimeEnd,o.lastResponseError=e.lastResponseError,o.lastResponseStatus=e.lastResponseStatus,o.txPosted=e.txPosted,o.data=r,o.transaction.data_root!==e.transaction.data_root)throw new Error("Data mismatch: Uploader doesn't match provided data.");return o}static async fromTransactionId(t,e){let r=await t.get(`tx/${e}`);if(r.status!==200)throw new Error(`Tx ${e} not found: ${r.status}`);let i=r.data;return i.data=new Uint8Array(0),{txPosted:!0,chunkIndex:0,lastResponseError:"",lastRequestTimeEnd:0,lastResponseStatus:0,transaction:i}}toJSON(){return{chunkIndex:this.chunkIndex,transaction:this.transaction,lastRequestTimeEnd:this.lastRequestTimeEnd,lastResponseStatus:this.lastResponseStatus,lastResponseError:this.lastResponseError,txPosted:this.txPosted}}async postTransaction(){if(this.totalChunks<=Ef){this.transaction.data=this.data;let r=await this.api.post("tx",this.transaction).catch(i=>(console.error(i),{status:-1,data:{error:i.message}}));if(this.lastRequestTimeEnd=Date.now(),this.lastResponseStatus=r.status,this.transaction.data=new Uint8Array(0),r.status>=200&&r.status<300){this.txPosted=!0,this.chunkIndex=Ef;return}throw this.lastResponseError=(0,ec.getError)(r),new Error(`Unable to upload transaction: ${r.status}, ${this.lastResponseError}`)}let e=await this.api.post("tx",this.transaction);if(this.lastRequestTimeEnd=Date.now(),this.lastResponseStatus=e.status,!(e.status>=200&&e.status<300))throw this.lastResponseError=(0,ec.getError)(e),new Error(`Unable to upload transaction: ${e.status}, ${this.lastResponseError}`);this.txPosted=!0}};Vo.TransactionUploader=Ei});var Go=nt((Yv,Cf)=>{b();Cf.exports={}});var If=nt(oc=>{"use strict";b();Object.defineProperty(oc,"__esModule",{value:!0});var rc=mi(),Xe=Ko(),Ti=Se(),nc=xf();Go();var ic=class{api;crypto;chunks;constructor(t,e,r){this.api=t,this.crypto=e,this.chunks=r}async getTransactionAnchor(){let t=await this.api.get("tx_anchor");if(!t.data.match(/^[a-z0-9_-]{43,}/i)||!t.ok)throw new Error(`Could not getTransactionAnchor. Received: ${t.data}. Status: ${t.status}, ${t.statusText}`);return t.data}async getPrice(t,e){let r=e?`price/${t}/${e}`:`price/${t}`,i=await this.api.get(r);if(!/^\d+$/.test(i.data)||!i.ok)throw new Error(`Could not getPrice. Received: ${i.data}. Status: ${i.status}, ${i.statusText}`);return i.data}async get(t){let e=await this.api.get(`tx/${t}`);if(e.status==200){let r=parseInt(e.data.data_size);if(e.data.format>=2&&r>0&&r<=1024*1024*12){let i=await this.getData(t);return new Xe.default({...e.data,data:i})}return new Xe.default({...e.data,format:e.data.format||1})}throw e.status==404?new rc.default("TX_NOT_FOUND"):e.status==410?new rc.default("TX_FAILED"):new rc.default("TX_INVALID")}fromRaw(t){return new Xe.default(t)}async search(t,e){return this.api.post("arql",{op:"equals",expr1:t,expr2:e}).then(r=>r.data?r.data:[])}getStatus(t){return this.api.get(`tx/${t}/status`).then(e=>e.status==200?{status:200,confirmed:e.data}:{status:e.status,confirmed:null})}async getData(t,e){let r;try{r=await this.chunks.downloadChunkedData(t)}catch(i){console.error(`Error while trying to download chunked data for ${t}`),console.error(i)}if(!r){console.warn(`Falling back to gateway cache for ${t}`);try{let{data:i,ok:o,status:s,statusText:c}=await this.api.get(`/${t}`,{responseType:"arraybuffer"});if(!o)throw new Error("Bad http status code",{cause:{status:s,statusText:c}});r=i}catch(i){console.error(`Error while trying to download contiguous data from gateway cache for ${t}`),console.error(i)}}if(!r)throw new Error(`${t} data was not found!`);return e&&e.decode&&!e.string?r:e&&e.decode&&e.string?Ti.bufferToString(r):Ti.bufferTob64Url(r)}async sign(t,e,r){let o=typeof e=="object"&&(c=>{let l=!0;return["n","e","d","p","q","dp","dq","qi"].map(g=>!(g in c)&&(l=!1)),l})(e),s=typeof arweaveWallet=="object";if(!o&&!s)throw new Error("No valid JWK or external wallet found to sign transaction.");if(s){try{(await arweaveWallet.getPermissions()).includes("SIGN_TRANSACTION")||await arweaveWallet.connect(["SIGN_TRANSACTION"])}catch{}let c=await arweaveWallet.sign(t,r);t.setSignature({id:c.id,owner:c.owner,reward:c.reward,tags:c.tags,signature:c.signature})}else if(o){t.setOwner(e.n);let c=await t.getSignatureData(),l=await this.crypto.sign(e,c,r),g=await this.crypto.hash(l);t.setSignature({id:Ti.bufferTob64Url(g),owner:e.n,signature:Ti.bufferTob64Url(l)})}else throw new Error("An error occurred while signing. Check wallet is valid")}async verify(t){let e=await t.getSignatureData(),r=t.get("signature",{decode:!0,string:!1}),i=Ti.bufferTob64Url(await this.crypto.hash(r));if(t.id!==i)throw new Error("Invalid transaction signature or ID! The transaction ID doesn't match the expected SHA-256 hash of the signature.");return this.crypto.verify(t.owner,e,r)}async post(t){if(typeof t=="string"?t=new Xe.default(JSON.parse(t)):typeof t.readInt32BE=="function"?t=new Xe.default(JSON.parse(t.toString())):typeof t=="object"&&!(t instanceof Xe.default)&&(t=new Xe.default(t)),!(t instanceof Xe.default))throw new Error("Must be Transaction object");t.chunks||await t.prepareChunks(t.data);let e=await this.getUploader(t,t.data);try{for(;!e.isComplete;)await e.uploadChunk()}catch(r){if(e.lastResponseStatus>0)return{status:e.lastResponseStatus,statusText:e.lastResponseError,data:{error:e.lastResponseError}};throw r}return{status:200,statusText:"OK",data:{}}}async getUploader(t,e){let r;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),t instanceof Xe.default){if(e||(e=t.data),!(e instanceof Uint8Array))throw new Error("Data format is invalid");t.chunks||await t.prepareChunks(e),r=new nc.TransactionUploader(this.api,t),(!r.data||r.data.length===0)&&(r.data=e)}else{if(typeof t=="string"&&(t=await nc.TransactionUploader.fromTransactionId(this.api,t)),!e||!(e instanceof Uint8Array))throw new Error("Must provide data when resuming upload");r=await nc.TransactionUploader.fromSerialized(this.api,t,e)}return r}async*upload(t,e){let r=await this.getUploader(t,e);for(;!r.isComplete;)await r.uploadChunk(),yield r;return r}};oc.default=ic});var kf=nt(ac=>{"use strict";b();Object.defineProperty(ac,"__esModule",{value:!0});var Af=Se();Go();var sc=class{api;crypto;constructor(t,e){this.api=t,this.crypto=e}getBalance(t){return this.api.get(`wallet/${t}/balance`).then(e=>e.data)}getLastTransactionID(t){return this.api.get(`wallet/${t}/last_tx`).then(e=>e.data)}generate(){return this.crypto.generateJWK()}async jwkToAddress(t){return!t||t==="use_wallet"?this.getAddress():this.getAddress(t)}async getAddress(t){if(!t||t==="use_wallet"){try{await arweaveWallet.connect(["ACCESS_ADDRESS"])}catch{}return arweaveWallet.getActiveAddress()}else return this.ownerToAddress(t.n)}async ownerToAddress(t){return Af.bufferTob64Url(await this.crypto.hash(Af.b64UrlToBuffer(t)))}};ac.default=sc});var Of=nt(xi=>{"use strict";b();Object.defineProperty(xi,"__esModule",{value:!0});xi.SiloResource=void 0;var Lf=Se(),cc=class{api;crypto;transactions;constructor(t,e,r){this.api=t,this.crypto=e,this.transactions=r}async get(t){if(!t)throw new Error("No Silo URI specified");let e=await this.parseUri(t),r=await this.transactions.search("Silo-Name",e.getAccessKey());if(r.length==0)throw new Error(`No data could be found for the Silo URI: ${t}`);let i=await this.transactions.get(r[0]);if(!i)throw new Error(`No data could be found for the Silo URI: ${t}`);let o=i.get("data",{decode:!0,string:!1});return this.crypto.decrypt(o,e.getEncryptionKey())}async readTransactionData(t,e){if(!e)throw new Error("No Silo URI specified");let r=await this.parseUri(e),i=t.get("data",{decode:!0,string:!1});return this.crypto.decrypt(i,r.getEncryptionKey())}async parseUri(t){let e=t.match(/^([a-z0-9-_]+)\.([0-9]+)/i);if(!e)throw new Error("Invalid Silo name, must be a name in the format of [a-z0-9]+.[0-9]+, e.g. 'bubble.7'");let r=e[1],i=Math.pow(2,parseInt(e[2])),o=await this.hash(Lf.stringToBuffer(r),i),s=Lf.bufferTob64(o.slice(0,15)),c=await this.hash(o.slice(16,31),1);return new qo(t,s,c)}async hash(t,e){let r=await this.crypto.hash(t);for(let i=0;i{"use strict";b();Object.defineProperty(lc,"__esModule",{value:!0});var Rf=mi(),Wp=Se(),uc=class{api;constructor(t){this.api=t}async getTransactionOffset(t){let e=await this.api.get(`tx/${t}/offset`);if(e.status===200)return e.data;throw new Error(`Unable to get transaction offset: ${(0,Rf.getError)(e)}`)}async getChunk(t){let e=await this.api.get(`chunk/${t}`);if(e.status===200)return e.data;throw new Error(`Unable to get chunk: ${(0,Rf.getError)(e)}`)}async getChunkData(t){let e=await this.getChunk(t);return Wp.b64UrlToBuffer(e.chunk)}firstChunkOffset(t){return parseInt(t.offset)-parseInt(t.size)+1}async downloadChunkedData(t){let e=await this.getTransactionOffset(t),r=parseInt(e.size),o=parseInt(e.offset)-r+1,s=new Uint8Array(r),c=0;for(;c{"use strict";b();Object.defineProperty(fc,"__esModule",{value:!0});var Dp=mi();Go();var hc=class{api;network;constructor(t,e){this.api=t,this.network=e}async get(t){let e=await this.api.get(`${hc.ENDPOINT}${t}`);if(e.status===200)return e.data;throw e.status===404?new Dp.default("BLOCK_NOT_FOUND"):new Error(`Error while loading block data: ${e}`)}async getCurrent(){let{current:t}=await this.network.getInfo();return await this.get(t)}},jo=hc;or(jo,"ENDPOINT","block/hash/");fc.default=jo});var yi=nt(gc=>{"use strict";b();Object.defineProperty(gc,"__esModule",{value:!0});var Mp=rf(),Fp=nf(),$p=gf(),Kp=df(),Vp=If(),Gp=kf(),Nf=Ko(),Ci=Se(),qp=Of(),jp=Bf(),Hp=Pf(),Tn=class{api;wallets;transactions;network;blocks;ar;silo;chunks;constructor(t){this.api=new Fp.default(t),this.wallets=new Gp.default(this.api,Tn.crypto),this.chunks=new jp.default(this.api),this.transactions=new Vp.default(this.api,Tn.crypto,this.chunks),this.silo=new qp.default(this.api,this.crypto,this.transactions),this.network=new Kp.default(this.api),this.blocks=new Hp.default(this.api,this.network),this.ar=new Mp.default}get crypto(){return Tn.crypto}get utils(){return Tn.utils}getConfig(){return{api:this.api.getConfig(),crypto:null}}async createTransaction(t,e){let r={};if(Object.assign(r,t),!t.data&&!(t.target&&t.quantity))throw new Error("A new Arweave transaction must have a 'data' value, or 'target' and 'quantity' values.");if(t.owner==null&&e&&e!=="use_wallet"&&(r.owner=e.n),t.last_tx==null&&(r.last_tx=await this.transactions.getTransactionAnchor()),typeof t.data=="string"&&(t.data=Ci.stringToBuffer(t.data)),t.data instanceof ArrayBuffer&&(t.data=new Uint8Array(t.data)),t.data&&!(t.data instanceof Uint8Array))throw new Error("Expected data to be a string, Uint8Array or ArrayBuffer");if(t.reward==null){let o=t.data?t.data.byteLength:0;r.reward=await this.transactions.getPrice(o,r.target)}r.data_root="",r.data_size=t.data?t.data.byteLength.toString():"0",r.data=t.data||new Uint8Array(0);let i=new Nf.default(r);return await i.getSignatureData(),i}async createSiloTransaction(t,e,r){let i={};if(Object.assign(i,t),!t.data)throw new Error("Silo transactions must have a 'data' value");if(!r)throw new Error("No Silo URI specified.");if(t.target||t.quantity)throw new Error("Silo transactions can only be used for storing data, sending AR to other wallets isn't supported.");if(t.owner==null){if(!e||!e.n)throw new Error("A new Arweave transaction must either have an 'owner' attribute, or you must provide the jwk parameter.");i.owner=e.n}t.last_tx==null&&(i.last_tx=await this.transactions.getTransactionAnchor());let o=await this.silo.parseUri(r);if(typeof t.data=="string"){let c=await this.crypto.encrypt(Ci.stringToBuffer(t.data),o.getEncryptionKey());i.reward=await this.transactions.getPrice(c.byteLength),i.data=Ci.bufferTob64Url(c)}if(t.data instanceof Uint8Array){let c=await this.crypto.encrypt(t.data,o.getEncryptionKey());i.reward=await this.transactions.getPrice(c.byteLength),i.data=Ci.bufferTob64Url(c)}let s=new Nf.default(i);return s.addTag("Silo-Name",o.getAccessKey()),s.addTag("Silo-Version","0.1.0"),s}arql(t){return this.api.post("/arql",t).then(e=>e.data||[])}},En=Tn;or(En,"init"),or(En,"crypto",new $p.default),or(En,"utils",Ci);gc.default=En});var Uf=nt(Ho=>{"use strict";b();Object.defineProperty(Ho,"__esModule",{value:!0});Ho.getDefaultConfig=void 0;var Qp=(n,t)=>{let e=/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,r=t.split("."),i=r[r.length-1],o=["localhost","[::1]"];return o.includes(t)||n=="file"||o.includes(i)||!!t.match(e)||!!i.match(e)},zp=n=>{let t=n.charAt(0)==="[",e=/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;return!!n.match(e)||t},Jp=(n,t)=>{if(Qp(n,t))return{protocol:"https",host:"arweave.net",port:443};if(!zp(t)){let e=t.split(".");if(e.length>=3){e.shift();let r=e.join(".");return{protocol:n,host:r}}}return{protocol:n,host:t}};Ho.getDefaultConfig=Jp});var Qo=nt(br=>{"use strict";b();var Yp=br&&br.__createBinding||(Object.create?function(n,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,r,i)}:function(n,t,e,r){r===void 0&&(r=e),n[r]=t[e]}),Xp=br&&br.__exportStar||function(n,t){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&Yp(t,n,e)};Object.defineProperty(br,"__esModule",{value:!0});var xn=yi(),Zp=Uf();xn.default.init=function(n={}){let t={host:"arweave.net",port:443,protocol:"https"};if(typeof location!="object"||!location.protocol||!location.hostname)return new xn.default({...n,...t});let e=location.protocol.replace(":",""),r=location.hostname,i=location.port?parseInt(location.port):e=="https"?443:80,o=(0,Zp.getDefaultConfig)(e,r),s=n.protocol||o.protocol,c=n.host||o.host,l=n.port||o.port||i;return new xn.default({...n,host:c,protocol:s,port:l})};typeof globalThis=="object"?globalThis.Arweave=xn.default:typeof self=="object"&&(self.Arweave=xn.default);Xp(yi(),br);br.default=xn.default});var uh=nt((Oc,ch)=>{"use strict";b();var{hasOwnProperty:es}=Object.prototype,Xr=Lc();Xr.configure=Lc;Xr.stringify=Xr;Xr.default=Xr;Oc.stringify=Xr;Oc.configure=Lc;ch.exports=Xr;var ah=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/,Rm=new RegExp(ah,"g"),kc=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000b","\\f","\\r","\\u000e","\\u000f","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001a","\\u001b","\\u001c","\\u001d","\\u001e","\\u001f","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\"];function Bm(n){if(n.length===2){let e=n.charCodeAt(1);return`${n[0]}\\u${e.toString(16)}`}let t=n.charCodeAt(0);return kc.length>t?kc[t]:`\\u${t.toString(16)}`}function Sr(n){if(n.length<5e3&&!ah.test(n))return n;if(n.length>100)return n.replace(Rm,Bm);let t="",e=0;for(let r=0;r=55296&&i<=57343){if(i<=56319&&r+1=56320&&o<=57343){r++;continue}}t+=`${n.slice(e,r)}\\u${i.toString(16)}`,e=r+1}}return t+=n.slice(e),t}function Cc(n){if(n.length>200)return n.sort();for(let t=1;te;)n[r]=n[r-1],r--;n[r]=e}return n}var Pm=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Ic(n){return Pm.call(n)!==void 0&&n.length!==0}function Ac(n,t,e){n.length= 1`)}return e===void 0?1/0:e}function Yr(n){return n===1?"1 item":`${n} items`}function Um(n){let t=new Set;for(let e of n)(typeof e=="string"||typeof e=="number")&&t.add(String(e));return t}function Wm(n){if(es.call(n,"strict")){let t=n.strict;if(typeof t!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(t)return e=>{let r=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!="function"&&(r+=` (${e.toString()})`),new Error(r)}}}function Lc(n){n={...n};let t=Wm(n);t&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let e=Nm(n),r=oh(n,"bigint"),i=oh(n,"deterministic"),o=sh(n,"maximumDepth"),s=sh(n,"maximumBreadth");function c(E,d,y,k,N,q){let Q=d[E];switch(typeof Q=="object"&&Q!==null&&typeof Q.toJSON=="function"&&(Q=Q.toJSON(E)),Q=k.call(d,E,Q),typeof Q){case"string":return`"${Sr(Q)}"`;case"object":{if(Q===null)return"null";if(y.indexOf(Q)!==-1)return e;let z="",X=",",D=q;if(Array.isArray(Q)){if(Q.length===0)return"[]";if(os){let wt=Q.length-s-1;z+=`${X}"... ${Yr(wt)} not stringified"`}return N!==""&&(z+=` +${D}`),y.pop(),`[${z}]`}let G=Object.keys(Q),it=G.length;if(it===0)return"{}";if(os){let tt=it-s;z+=`${O}"...":${et}"${Yr(tt)} not stringified"`,O=X}return N!==""&&O.length>1&&(z=` +${q}${z} +${D}`),y.pop(),`{${z}}`}case"number":return isFinite(Q)?String(Q):t?t(Q):"null";case"boolean":return Q===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(Q);default:return t?t(Q):void 0}}function l(E,d,y,k,N,q){switch(typeof d=="object"&&d!==null&&typeof d.toJSON=="function"&&(d=d.toJSON(E)),typeof d){case"string":return`"${Sr(d)}"`;case"object":{if(d===null)return"null";if(y.indexOf(d)!==-1)return e;let Q=q,z="",X=",";if(Array.isArray(d)){if(d.length===0)return"[]";if(os){let ft=d.length-s-1;z+=`${X}"... ${Yr(ft)} not stringified"`}return N!==""&&(z+=` +${Q}`),y.pop(),`[${z}]`}if(k.size===0)return"{}";y.push(d);let D="";N!==""&&(q+=N,X=`, +${q}`,D=" ");let G="";for(let it of k){let et=l(it,d[it],y,k,N,q);et!==void 0&&(z+=`${G}"${Sr(it)}":${D}${et}`,G=X)}return N!==""&&G.length>1&&(z=` +${q}${z} +${Q}`),y.pop(),`{${z}}`}case"number":return isFinite(d)?String(d):t?t(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(d);default:return t?t(d):void 0}}function g(E,d,y,k,N){switch(typeof d){case"string":return`"${Sr(d)}"`;case"object":{if(d===null)return"null";if(typeof d.toJSON=="function"){if(d=d.toJSON(E),typeof d!="object")return g(E,d,y,k,N);if(d===null)return"null"}if(y.indexOf(d)!==-1)return e;let q=N;if(Array.isArray(d)){if(d.length===0)return"[]";if(os){let at=d.length-s-1;et+=`${O}"... ${Yr(at)} not stringified"`}return et+=` +${q}`,y.pop(),`[${et}]`}let Q=Object.keys(d),z=Q.length;if(z===0)return"{}";if(os){let et=z-s;D+=`${G}"...": "${Yr(et)} not stringified"`,G=X}return G!==""&&(D=` +${N}${D} +${q}`),y.pop(),`{${D}}`}case"number":return isFinite(d)?String(d):t?t(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(d);default:return t?t(d):void 0}}function w(E,d,y){switch(typeof d){case"string":return`"${Sr(d)}"`;case"object":{if(d===null)return"null";if(typeof d.toJSON=="function"){if(d=d.toJSON(E),typeof d!="object")return w(E,d,y);if(d===null)return"null"}if(y.indexOf(d)!==-1)return e;let k="";if(Array.isArray(d)){if(d.length===0)return"[]";if(os){let it=d.length-s-1;k+=`,"... ${Yr(it)} not stringified"`}return y.pop(),`[${k}]`}let N=Object.keys(d),q=N.length;if(q===0)return"{}";if(os){let X=q-s;k+=`${Q}"...":"${Yr(X)} not stringified"`}return y.pop(),`{${k}}`}case"number":return isFinite(d)?String(d):t?t(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(d);default:return t?t(d):void 0}}function v(E,d,y){if(arguments.length>1){let k="";if(typeof y=="number"?k=" ".repeat(Math.min(y,10)):typeof y=="string"&&(k=y.slice(0,10)),d!=null){if(typeof d=="function")return c("",{"":E},[],d,k,"");if(Array.isArray(d))return l("",E,[],Um(d),k,"")}if(k.length!==0)return g("",E,[],k,"")}return w("",E,[])}return v}});var dy={};Oh(dy,{AbstractContractHandler:()=>qr,ArweaveGatewayBundledContractDefinitionLoader:()=>qi,ArweaveGatewayBundledInteractionLoader:()=>Rn,ArweaveGatewayInteractionsLoader:()=>Bi,ArweaveWrapper:()=>Zt,Benchmark:()=>St,CacheKey:()=>zt,CacheableInteractionsLoader:()=>An,CacheableStateEvaluator:()=>Ni,ConsoleLogger:()=>Pn,ConsoleLoggerFactory:()=>Nn,ContractCache:()=>gi,ContractCallRecord:()=>Jr,ContractDefinitionLoader:()=>zr,ContractError:()=>Wt,ContractMetadata:()=>Wa,CustomEvent:()=>fi,DEFAULT_LEVEL_DB_LOCATION:()=>fs,DefaultEvaluationOptions:()=>li,DefaultStateEvaluator:()=>Pi,EvalStateResult:()=>Dt,EvaluationOptionsEvaluator:()=>Fi,HandlerBasedContract:()=>tn,HandlerExecutorFactory:()=>ii,InnerWritesEvaluator:()=>Wi,InteractionCall:()=>kn,InteractionCompleteEvent:()=>Ua,InteractionInput:()=>ts,InteractionOutput:()=>Tc,JsHandlerApi:()=>oi,KV:()=>No,KnownErrors:()=>La,LevelDbCache:()=>Pe,LexicographicalInteractionsSorter:()=>Ye,LogLevelOrder:()=>pu,LoggerFactory:()=>ct,MemCache:()=>_a,NetworkCommunicationError:()=>Ne,NonWhitelistedSourceError:()=>_n,PstContractImpl:()=>Vi,REGISTER_PROVIDER:()=>Dm,SMART_WEAVE_TAGS:()=>Ct,SUPPORTED_SRC_CONTENT_TYPES:()=>di,SWBlock:()=>wn,SWTransaction:()=>yn,SWVrf:()=>vn,Signature:()=>Mi,SmartWeaveError:()=>Ui,SmartWeaveErrorType:()=>xc,SmartWeaveGlobal:()=>ri,SortKeyCacheResult:()=>Pt,SourceType:()=>ef,SrcCache:()=>hi,Tag:()=>qt,TagsParser:()=>jt,Transaction:()=>Hr,WARP_GW_URL:()=>jc,WARP_TAGS:()=>ot,Warp:()=>en,WarpBuilder:()=>Gi,WarpFactory:()=>Hc,WarpFetchWrapper:()=>$i,WarpGatewayContractDefinitionLoader:()=>Ri,WarpGatewayInteractionsLoader:()=>ui,WasmHandlerApi:()=>ni,WasmSrc:()=>Ze,arrayToHex:()=>Oa,asc:()=>mp,ascS:()=>yp,bufToBn:()=>_p,bundledTxsFilter:()=>Sc,checkJsSrc:()=>up,createDummyTx:()=>Bc,createInteractionTagsList:()=>ns,createInteractionTx:()=>rs,deepCopy:()=>vr,defaultArweaveMs:()=>Do,defaultCacheOptions:()=>On,defaultWarpGwOptions:()=>gs,desc:()=>wp,descS:()=>vp,emptyTransfer:()=>Er,genesisSortKey:()=>bn,getJsonResponse:()=>we,indent:()=>be,isBrowser:()=>jr,knownWarpPlugins:()=>qc,knownWarpPluginsPartial:()=>Gc,lastPossibleSortKey:()=>gp,lvlToOrder:()=>Ji,mapReplacer:()=>dp,mapReviver:()=>pp,matchMutClosureDtor:()=>hy,normalizeContractSource:()=>Uo,rustWasmImports:()=>Aa,safeGet:()=>Ia,safeParseInt:()=>ci,sleep:()=>ai,sortingFirst:()=>tf,sortingLast:()=>Ba,stripTrailingSlash:()=>Ue,timeout:()=>Na});b();b();b();var pu={silly:0,trace:1,debug:2,info:3,warn:4,error:5,fatal:6,none:7};function Ji(n){return pu[n]}var Pn=class{constructor(t,e){this.moduleName=t;this.settings=e}trace(t,...e){this.shouldLog("trace")&&console.debug(this.message("trace",t),e)}error(t,...e){this.shouldLog("error")&&console.error(this.message("error",t),e)}info(t,...e){this.shouldLog("info")&&console.info(this.message("info",t),e)}silly(t,...e){this.shouldLog("silly")&&console.debug(this.message("silly",t),e)}debug(t,...e){this.shouldLog("debug")&&console.debug(this.message("debug",t),e)}warn(t,...e){this.shouldLog("warn")&&console.warn(this.message("warn",t),e)}log(t,...e){this.shouldLog("info")&&console.info(this.message("info",t),e)}fatal(t,...e){this.shouldLog("fatal")&&console.error(this.message("fatal",t),e)}shouldLog(t){return Ji(t)>=Ji(this.settings.minLevel)}setSettings(t){this.settings=t}message(t,e){return`${new Date().toISOString()} ${t.toUpperCase()} [${this.moduleName}] ${e}`}};b();var Nn=class{registeredLoggers={};registeredOptions={};defOptions={minLevel:"info"};constructor(){this.setOptions=this.setOptions.bind(this),this.getOptions=this.getOptions.bind(this),this.create=this.create.bind(this),this.logLevel=this.logLevel.bind(this)}setOptions(t,e){e?this.registeredLoggers[e]?this.registeredLoggers[e].setSettings({...this.registeredLoggers[e].settings,...t}):this.registeredOptions[e]={...this.defOptions,...t}:(this.defOptions=t,Object.keys(this.registeredLoggers).forEach(r=>{this.registeredLoggers[r].setSettings({...this.registeredLoggers[r].settings,...t})}))}getOptions(t){return t?this.registeredLoggers[t]?this.registeredLoggers[t].settings:this.registeredOptions[t]?this.registeredOptions[t]:this.defOptions:this.defOptions}logLevel(t,e){this.setOptions({minLevel:t},e)}create(t="SWC"){return Object.prototype.hasOwnProperty.call(this.registeredLoggers,t)||(this.registeredLoggers[t]=new Pn(t,this.getOptions(t))),this.registeredLoggers[t]}};b();var Lr=class{constructor(){}setOptions(t,e){Lr.INST.setOptions(t,e)}getOptions(t){return Lr.INST.getOptions(t)}logLevel(t,e){Lr.INST.logLevel(t,e)}create(t){return Lr.INST.create(t)}static use(t){Lr.INST=t}},ct=Lr;or(ct,"INST",new Nn);b();var St=class{static measure(){return new St}constructor(){}start=Date.now();end=null;reset(){this.start=Date.now(),this.end=null}stop(){this.end=Date.now()}elapsed(t=!1){this.end===null&&(this.end=Date.now());let e=this.end-this.start;return t?e:`${(this.end-this.start).toFixed(0)}ms`}};b();var zt=class{constructor(t,e){this.key=t;this.sortKey=e}},Pt=class{constructor(t,e){this.sortKey=t;this.cachedValue=e}};b();var Dl=Qt(kl()),Ml=Qt(Wl());var Ro=class{constructor(t,e=!1){this.value=t;this.tomb=e}},Pe=class{constructor(t){this.cacheOptions=t;this.subLevelSeparator=t.subLevelSeparator||"!",this.subLevelOptions={valueEncoding:"json",separator:this.subLevelSeparator}}ongoingTransactionMark="$$warp-internal-transaction$$";logger=ct.INST.create("LevelDbCache");subLevelSeparator;subLevelOptions;_db;_rollbackBatch;get db(){if(!this._db)if(this.cacheOptions.inMemory)this._db=new Ml.MemoryLevel(this.subLevelOptions);else{if(!this.cacheOptions.dbLocation)throw new Error("LevelDb cache configuration error - no db location specified");let t=this.cacheOptions.dbLocation;this.logger.info(`Using location ${t}`),this._db=new Dl.Level(t,this.subLevelOptions)}return this._db}async get(t,e){this.validateKey(t.key);let r=this.db.sublevel(t.key,this.subLevelOptions);await r.open();let i=await this.getValueFromLevel(t.sortKey,r);return i?new Pt(t.sortKey,i):null}async getLast(t){let e=this.db.sublevel(t,this.subLevelOptions);await e.open();let r=await e.keys({reverse:!0,limit:1}).all();if(r.length){let i=await this.getValueFromLevel(r[0],e);if(i)return new Pt(r[0],i)}return null}async getLessOrEqual(t,e){let r=this.db.sublevel(t,this.subLevelOptions);await r.open();let i=await r.keys({reverse:!0,lte:e,limit:1}).all();if(i.length){let o=await this.getValueFromLevel(i[0],r);if(o!=null)return new Pt(i[0],o)}return null}async getValueFromLevel(t,e){try{let r=await e.get(t);if(r&&r.tomb===void 0&&r.value===void 0)return r;if(r&&r.tomb===!1&&r.value!=null)return r.value}catch(r){if(r.code!="LEVEL_NOT_FOUND")throw r}return null}async put(t,e){await this.setClientValue(t,new Ro(e))}async del(t){await this.setClientValue(t,new Ro(null,!0))}async setClientValue(t,e){this.validateKey(t.key);let r=this.db.sublevel(t.key,this.subLevelOptions);await r.open(),await r.put(t.sortKey,e),this._rollbackBatch&&this._rollbackBatch.del(t.sortKey,{sublevel:r})}async delete(t){let e=this.db.sublevel(t,this.subLevelOptions);await e.open(),await e.clear()}async batch(t){for(let e of t)e.type==="put"?await this.put(e.key,e.value):e.type==="del"&&await this.delete(e.key)}async open(){await this.db.open()}async close(){this._db&&await this._db.close()}async begin(){await this.initRollbackBatch()}async rollback(){this._rollbackBatch&&(this._rollbackBatch.del(this.ongoingTransactionMark),await this._rollbackBatch.write(),await this._rollbackBatch.close()),this._rollbackBatch=null}async initRollbackBatch(){return this._rollbackBatch==null&&(await this.checkPreviousTransactionFinished(),await this.db.put(this.ongoingTransactionMark,"ongoing"),this._rollbackBatch=this.db.batch()),this._rollbackBatch}async checkPreviousTransactionFinished(){let t;try{t=await this.db.get(this.ongoingTransactionMark)}catch(e){if(e.code!="LEVEL_NOT_FOUND")throw e}if(t=="ongoing")throw new Error("Database seems to be in inconsistent state. The previous transaction has not finished.")}async commit(){this._rollbackBatch&&(await this._rollbackBatch.clear(),await this.db.del(this.ongoingTransactionMark),await this._rollbackBatch.close()),this._rollbackBatch=null}async dump(){return await this.db.iterator().all()}async getLastSortKey(){let t="";await this.db.open();let e=await this.db.keys().all();for(let r of e){let i=r.split(this.subLevelSeparator)[1];i.localeCompare(t)>0&&(t=i)}return t==""?null:t}async keys(t,e){return Array.from((await this.kvMap(t,e)).keys())}validateKey(t){if(t.includes(this.ongoingTransactionMark))throw new Error(`Validation error: Key ${t} for internal use only`);if(t.includes(this.subLevelSeparator))throw new Error(`Validation error: key ${t} contains db separator ${this.subLevelSeparator}`)}extractOriginalKey(t){return t.split(this.subLevelSeparator)[1]}extractSortKey(t){return t.split(this.subLevelSeparator)[2]}async kvMap(t,e){let r=new Map,i=(await this.db.keys(this.levelRangeOptions(e)).all()).filter(o=>o!=this.ongoingTransactionMark).filter(o=>!t||this.extractSortKey(o).localeCompare(t)<=0).map(o=>this.extractOriginalKey(o));for(let o of i){let s=await this.getLessOrEqual(o,t);s&&r.set(o,s.cachedValue)}if(e?.limit){let o=new Map;for(let s of Array.from(r.entries()).slice(0,e.limit))o.set(s[0],s[1]);return o}return r}levelRangeOptions(t){let e={reverse:t?.reverse};return t?.gte&&(e.gte=this.subLevelSeparator+t.gte),t?.lt&&(e.lt=this.subLevelSeparator+t.lt),e}storage(){return this.db}async getNumEntries(){return(await this.db.keys().all()).length}async prune(t=5){(!t||t<=0)&&(t=1);let e=await this.allKeys();for(let r=0;rt!=this.ongoingTransactionMark).map(t=>this.extractOriginalKey(t))}};b();var _a=class{storage={};clearAll(){Object.keys(this.storage).forEach(t=>{delete this.storage[t]})}contains(t){return Object.prototype.hasOwnProperty.call(this.storage,t)}get(t){return this.storage[t]}put(t,e){this.storage[t]=e}remove(t){delete this.storage[t]}};b();b();var bv=Qt(wr());b();b();var Ld=Function.prototype.toString,Sa=Object.create,Od=Object.prototype.toString,Rd=function(){function n(){this._keys=[],this._values=[]}return n.prototype.has=function(t){return!!~this._keys.indexOf(t)},n.prototype.get=function(t){return this._values[this._keys.indexOf(t)]},n.prototype.set=function(t,e){this._keys.push(t),this._values.push(e)},n}();function Bd(){return new Rd}function Pd(){return new WeakMap}var Nd=typeof WeakMap<"u"?Pd:Bd;function Ta(n){if(!n)return Sa(null);var t=n.constructor;if(t===Object)return n===Object.prototype?{}:Sa(n);if(~Ld.call(t).indexOf("[native code]"))try{return new t}catch{}return Sa(n)}function Ud(n){var t="";return n.global&&(t+="g"),n.ignoreCase&&(t+="i"),n.multiline&&(t+="m"),n.unicode&&(t+="u"),n.sticky&&(t+="y"),t}function Wd(n){return n.flags}var Dd=/test/g.flags==="g"?Wd:Ud;function Fl(n){var t=Od.call(n);return t.substring(8,t.length-1)}function Md(n){return n[Symbol.toStringTag]||Fl(n)}var Fd=typeof Symbol<"u"?Md:Fl,$d=Object.defineProperty,Kd=Object.getOwnPropertyDescriptor,$l=Object.getOwnPropertyNames,xa=Object.getOwnPropertySymbols,Kl=Object.prototype,Vl=Kl.hasOwnProperty,Vd=Kl.propertyIsEnumerable,Gl=typeof xa=="function";function Gd(n){return $l(n).concat(xa(n))}var qd=Gl?Gd:$l;function Po(n,t,e){for(var r=qd(n),i=0,o=r.length,s=void 0,c=void 0;i{throw new Error("Not implemented - should be set by HandlerApi implementor")},viewContractState:(s,c)=>{throw new Error("Not implemented - should be set by HandlerApi implementor")},write:(s,c,l)=>{throw new Error("Not implemented - should be set by HandlerApi implementor")},refreshState:()=>{throw new Error("Not implemented - should be set by HandlerApi implementor")}},this.vrf=new vn(this),this.useGas=this.useGas.bind(this),this.getBalance=this.getBalance.bind(this),this.extensions={},this.kv=new No(o,i,this.transaction,this.contract.id)}useGas(t){if(t<0)throw new Error("[RE:GNE] Gas number exception - gas < 0.");if(this.gasUsed+=t,this.gasUsed>this.gasLimit)throw new Error(`[RE:OOG] Out of gas! Used: ${this.gasUsed}, limit: ${this.gasLimit}`)}async getBalance(t,e){if(!this._activeTx)throw new Error("Cannot read balance - active tx is not set.");if(!this.block.height)throw new Error("Cannot read balance - block height not set.");let r=e||this.block.height;return await fetch(`${this.evaluationOptions.walletBalanceUrl}block/height/${r}/wallet/${t}/balance`).then(i=>i.ok?i.text():Promise.reject(i)).catch(i=>{throw new Error(`Unable to read wallet balance. ${i.status}. ${i.body?.message}`)})}},yn=class{constructor(t){this.smartWeaveGlobal=t}get id(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.id}get owner(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.owner.address}get target(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.recipient}get tags(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.tags}get sortKey(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.sortKey}get dryRun(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.dry===!0}get quantity(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.quantity.winston}get reward(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.fee.winston}get origin(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.source==="redstone-sequencer"?"L2":"L1"}},wn=class{constructor(t){this.smartWeaveGlobal=t}get height(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.block.height}get indep_hash(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current Tx");return this.smartWeaveGlobal._activeTx.block.id}get timestamp(){if(!this.smartWeaveGlobal._activeTx)throw new Error("No current tx");return this.smartWeaveGlobal._activeTx.block.timestamp}},vn=class{constructor(t){this.smartWeaveGlobal=t}get data(){return this.smartWeaveGlobal._activeTx.vrf}get value(){return this.smartWeaveGlobal._activeTx.vrf.bigint}randomInt(t){if(!Number.isInteger(t))throw new Error("Integer max value required for random integer generation");let e=BigInt(this.smartWeaveGlobal._activeTx.vrf.bigint)%BigInt(t)+BigInt(1);if(e>Number.MAX_SAFE_INTEGER||e{let o=ct.INST.create("WASM:Rust"),s={metering:{usegas:n.useGas},console:{log:function(h){o.debug(`${n.contract.id}: ${h}`)}},Block:{height:function(){return n.block.height},indep_hash:function(){return n.block.indep_hash},timestamp:function(){return n.block.timestamp}},Transaction:{id:function(){return n.transaction.id},owner:function(){return n.transaction.owner},target:function(){return n.transaction.target}},Contract:{id:function(){return n.contract.id},owner:function(){return n.contract.owner}},KV:{get:async function(h){return await n.kv.get(h)},put:async function(h,m){await n.kv.put(h,m)},del:async function(h){await n.kv.del(h)},map:async function(h,m,I,j){return await n.kv.kvMap({gte:h,lt:m,reverse:I,limit:j})},keys:async function(h,m,I,j){return await n.kv.keys({gte:h,lt:m,reverse:I,limit:j})}},SmartWeave:{caller:function(){return n.caller},readContractState:async function(h){return await n.contracts.readContractState(h)},viewContractState:async function(h,m){return await n.contracts.viewContractState(h,m)},write:async function(h,m){return await n.contracts.write(h,m,!1)}},Vrf:{value:function(){return n.vrf.value},randomInt:function(h){return n.vrf.randomInt(h)}}},c=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});c.decode();let l=null;function g(){return(l===null||l.byteLength===0)&&(l=new Uint8Array(e.exports.memory.buffer)),l}function w(h,m){return c.decode(g().subarray(h,h+m))}let v=new Array(128).fill(void 0);v.push(void 0,null,!0,!1);let E=v.length;function d(h){E===v.length&&v.push(v.length+1);let m=E;if(E=v[m],typeof E!="number")throw new Error("corrupt heap");return v[m]=h,m}function y(h){return v[h]}function k(h){if(typeof h!="boolean")throw new Error("expected a boolean argument")}function N(h){return h==null}function q(h){if(typeof h!="number")throw new Error("expected a number argument")}let Q=null;function z(){return(Q===null||Q.byteLength===0)&&(Q=new Float64Array(e.exports.memory.buffer)),Q}let X=null;function D(){return(X===null||X.byteLength===0)&&(X=new Int32Array(e.exports.memory.buffer)),X}let G=0,it=new TextEncoder("utf-8"),et=typeof it.encodeInto=="function"?function(h,m){return it.encodeInto(h,m)}:function(h,m){let I=it.encode(h);return m.set(I),{read:h.length,written:I.length}};function O(h,m,I){if(I===void 0){let u=it.encode(h),f=m(u.length);return g().subarray(f,f+u.length).set(u),G=u.length,f}let j=h.length,Z=m(j),rt=g(),a=0;for(;a127)break;rt[Z+a]=u}if(a!==j){a!==0&&(h=h.slice(a)),Z=I(Z,j,j=a+h.length*3);let u=g().subarray(Z+a,Z+j),f=et(h,u);a+=f.written}return G=a,Z}function ft(h){h<132||(v[h]=E,E=h)}function tt(h){let m=y(h);return ft(h),m}function lt(h){let m=typeof h;if(m=="number"||m=="boolean"||h==null)return`${h}`;if(m=="string")return`"${h}"`;if(m=="symbol"){let Z=h.description;return Z==null?"Symbol":`Symbol(${Z})`}if(m=="function"){let Z=h.name;return typeof Z=="string"&&Z.length>0?`Function(${Z})`:"Function"}if(Array.isArray(h)){let Z=h.length,rt="[";Z>0&&(rt+=lt(h[0]));for(let a=1;a1)j=I[1];else return toString.call(h);if(j=="Object")try{return"Object("+JSON.stringify(h)+")"}catch{return"Object"}return h instanceof Error?`${h.name}: ${h.message} +${h.stack}`:j}function at(h){if(typeof h!="bigint")throw new Error("expected a bigint argument")}let wt=null;function Nt(){return(wt===null||wt.byteLength===0)&&(wt=new BigInt64Array(e.exports.memory.buffer)),wt}function Tt(h,m,I,j){let Z={a:h,b:m,cnt:1,dtor:I},rt=(...a)=>{Z.cnt++;let u=Z.a;Z.a=0;try{return j(u,Z.b,...a)}finally{--Z.cnt===0?e.exports.__wbindgen_export_2.get(Z.dtor)(u,Z.b):Z.a=u}};return rt.original=Z,rt}function ht(h,m){try{return h.apply(this,m)}catch(I){let j=function(){try{return I instanceof Error?`${I.message} + +Stack: +${I.stack}`:I.toString()}catch{return""}}();throw console.error("wasm-bindgen: imported JS function that was not marked as `catch` threw an error:",j),I}}function _t(h,m,I){e.modifiedExports._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__(h,m,d(I))}function Ut(h){let m=e.exports.warpContractWrite(d(h));return tt(m)}function Me(h){var m=e.exports.handle(d(h));return tt(m)}let yt=128;function Lt(h){if(yt==1)throw new Error("out of js stack");return v[--yt]=h,yt}function Y(h){try{e.exports.initState(Lt(h))}finally{v[yt++]=void 0}}function nr(h){try{e.exports.initState(Lt(h))}finally{v[yt++]=void 0}}function xr(){let h=e.exports.currentState();return tt(h)}function ir(){return e.exports.version()}function Vt(){return e.exports.lang()}function Ft(h){let m=e.exports.warpContractView(d(h));return tt(m)}function p(h,m){try{return h.apply(this,m)}catch(I){e.exports.__wbindgen_exn_store(d(I))}}function _(h,m,I,j){e.modifiedExports.wasm_bindgen__convert__closures__invoke2_mut__(h,m,d(I),d(j))}function S(h){return()=>{throw new Error(`${h} is not defined`)}}let U={__wbindgen_json_parse:function(h,m){let I=JSON.parse(w(h,m));return d(I)},__wbindgen_json_serialize:function(h,m){let I=y(m),j=JSON.stringify(I===void 0?null:I),Z=O(j,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),rt=G;D()[h/4+1]=rt,D()[h/4+0]=Z},__wbindgen_error_new:function(h,m){let I=new Error(w(h,m));return d(I)},__wbindgen_is_undefined:function(h){return y(h)===void 0},__wbindgen_in:function(h,m){return y(h)in y(m)},__wbindgen_number_get:function(h,m){let I=y(m),j=typeof I=="number"?I:void 0;z()[h/8+1]=N(j)?0:j,D()[h/4+0]=!N(j)},__wbindgen_boolean_get:function(h){let m=y(h),I=typeof m=="boolean"?m?1:0:2;return q(I),I},__wbindgen_is_null:function(h){let m=y(h)===null;return k(m),m},__wbindgen_string_new:function(h,m){let I=w(h,m);return d(I)},__wbindgen_string_get:function(h,m){let I=y(m),j=typeof I=="string"?I:void 0;var Z=N(j)?0:O(j,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),rt=G;D()[h/4+1]=rt,D()[h/4+0]=Z},__wbindgen_is_bigint:function(h){return typeof y(h)=="bigint"},__wbindgen_is_object:function(h){let m=y(h);return typeof m=="object"&&m!==null},__wbindgen_object_clone_ref:function(h){let m=y(h);return d(m)},__wbindgen_jsval_eq:function(h,m){return y(h)===y(m)},__wbindgen_bigint_from_i64:function(h){return d(h)},__wbindgen_bigint_from_u64:function(h){let m=BigInt.asUintN(64,h);return d(m)},__wbg_readContractState:function(){return p(function(h,m){let I=s.SmartWeave.readContractState(w(h,m));return d(I)},arguments)},__wbg_viewContractState:function(){return p(function(h,m,I){let j=s.SmartWeave.viewContractState(w(h,m),tt(I));return d(j)},arguments)},__wbg_write:function(){return p(function(h,m,I){let j=s.SmartWeave.write(w(h,m),tt(I));return d(j)},arguments)},__wbg_refreshState:function(h,m){},__wbg_kvGet:function(){return p(function(h,m){let I=s.KV.get(w(h,m));return d(I)},arguments)},__wbg_kvPut:function(){return p(function(h,m,I){let j=s.KV.put(w(h,m),tt(I));return d(j)},arguments)},__wbg_kvDel:function(){return p(function(h,m){let I=s.KV.del(w(h,m));return d(I)},arguments)},__wbg_kvMap:function(){return p(function(h,m,I,j,Z,rt,a){let u=s.KV.map(h===0?void 0:w(h,m),I===0?void 0:w(I,j),Z===16777215?void 0:Z!==0,rt===0?void 0:a>>>0);return d(u)},arguments)},__wbg_kvKeys:function(){return p(function(h,m,I,j,Z,rt,a){let u=s.KV.keys(h===0?void 0:w(h,m),I===0?void 0:w(I,j),Z===16777215?void 0:Z!==0,rt===0?void 0:a>>>0);return d(u)},arguments)},__wbindgen_object_drop_ref:function(h){tt(h)},__wbg_error:function(){return ht(function(h,m){try{s.console.log(w(h,m))}finally{e.exports.__wbindgen_free(h,m)}},arguments)},__wbg_new_abda76e883ba8a5f:function(){return ht(function(){let h=new Error;return d(h)},arguments)},__wbg_stack:function(){return ht(function(h,m){let I=Error.stackTraceLimit;Error.stackTraceLimit=25;let j=y(m).stack,Z=O(j,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),rt=G;D()[h/4+1]=rt,D()[h/4+0]=Z,Error.stackTraceLimit=I},arguments)},__wbg_indephash:function(){return ht(function(h){let m=s.Block.indep_hash(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_height:function(){return ht(function(){let h=s.Block.height();return q(h),h},arguments)},__wbg_timestamp:function(){return ht(function(){let h=s.Block.timestamp();return q(h),h},arguments)},__wbg_contractId:function(){return ht(function(h){let m=s.Contract.id(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_contractOwner:function(){return ht(function(h){let m=s.Contract.owner(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_id:function(h){let m=s.Transaction.id(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},__wbg_owner:function(h){let m=s.Transaction.owner(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},__wbg_target:function(){return ht(function(h){let m=s.Transaction.target(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_caller:function(h){let m=s.SmartWeave.caller(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},__wbg_value_b245bf3240b21a48:function(){return ht(function(h){let m=s.Vrf.value(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_value_7d69ddc3f1ad7876:function(){return ht(function(h){let m=s.Vrf.value(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_vrfValue:function(){return ht(function(h){let m=s.Vrf.value(),I=O(m,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),j=G;D()[h/4+1]=j,D()[h/4+0]=I},arguments)},__wbg_randomInt:function(){return ht(function(h){let m=s.Vrf.randomInt(h);return q(m),m},arguments)},__wbg_log:function(h,m){console.log(w(h,m))},__wbindgen_cb_drop:function(h){let m=tt(h).original;return m.cnt--==1?(m.a=0,!0):!1},__wbg_debug:function(){return ht(function(h){console.log(y(h))},arguments)},__wbg_String:function(){return ht(function(h,m){let I=String(y(m)),j=O(I,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),Z=G;D()[h/4+1]=Z,D()[h/4+0]=j},arguments)},__wbg_getwithrefkey:function(h,m){let I=y(h)[y(m)];return d(I)},__wbg_set_841ac57cff3d672b:function(h,m,I){y(h)[tt(m)]=tt(I)},__wbindgen_number_new:function(h){return d(h)},__wbindgen_jsval_loose_eq:function(h,m){return y(h)==y(m)},__wbg_get_27fe3dac1c4d0224:function(h,m){let I=y(h)[m>>>0];return d(I)},__wbg_set_17224bc548dd1d7b:function(h,m,I){y(h)[m>>>0]=tt(I)},__wbg_isArray:function(h){return Array.isArray(y(h))},__wbg_length_e498fbc24f9c1d4f:function(h){return y(h).length},__wbg_new_b525de17f44a8943:function(){let h=new Array;return d(h)},__wbg_instanceof_ArrayBuffer:function(h){let m;try{m=y(h)instanceof ArrayBuffer}catch{m=!1}return m},__wbg_call_95d1ea488d03e4e8:function(){return p(function(h,m){let I=y(h).call(y(m));return d(I)},arguments)},__wbg_call_9495de66fdbe016b:function(){return p(function(h,m,I){let j=y(h).call(y(m),y(I));return d(j)},arguments)},__wbg_call_94697a95cb7e239c:function(){return p(function(h,m,I){let j=y(h).call(y(m),y(I));return d(j)},arguments)},__wbg_new_f841cc6f2098f4b5:function(){return d(new Map)},__wbg_set_388c4c6422704173:function(h,m,I){let j=y(h).set(y(m),y(I));return d(j)},__wbg_next_88560ec06a094dea:function(){return p(function(h){let m=y(h).next();return d(m)},arguments)},__wbg_next_b7d530c04fd8b217:function(h){let m=y(h).next;return d(m)},__wbg_done:function(h){return y(h).done},__wbg_value_6ac8da5cc5b3efda:function(h){let m=y(h).value;return d(m)},__wbg_isSafeInteger:function(h){return Number.isSafeInteger(y(h))},__wbg_entries:function(h){let m=Object.entries(y(h));return d(m)},__wbg_new_f9876326328f45ed:function(){let h=new Object;return d(h)},__wbg_iterator:function(){return d(Symbol.iterator)},__wbg_new_9d3a9ce4282a18a8:function(h,m){try{var I={a:h,b:m},j=(rt,a)=>{let u=I.a;I.a=0;try{return _(u,I.b,rt,a)}finally{I.a=u}};let Z=new Promise(j);return d(Z)}finally{I.a=I.b=0}},__wbg_resolve:function(h){let m=Promise.resolve(y(h));return d(m)},__wbg_then_ec5db6d509eb475f:function(h,m){let I=y(h).then(y(m));return d(I)},__wbg_then_a6860c82b90816ca:function(){return ht(function(h,m){let I=y(h).then(y(m));return d(I)},arguments)},__wbg_then_f753623316e2873a:function(h,m,I){let j=y(h).then(y(m),y(I));return d(j)},__wbg_then_58a04e42527f52c6:function(){return ht(function(h,m,I){let j=y(h).then(y(m),y(I));return d(j)},arguments)},__wbg_instanceof_Uint8Array:function(h){let m;try{m=y(h)instanceof Uint8Array}catch{m=!1}return m},__wbg_new_537b7341ce90bb31:function(h){let m=new Uint8Array(y(h));return d(m)},__wbg_length_27a2afe8ab42b09f:function(h){return y(h).length},__wbg_set_17499e8aa4003ebd:function(h,m,I){y(h).set(y(m),I>>>0)},__wbindgen_is_function:function(h){return typeof y(h)=="function"},__wbindgen_is_string:function(h){return typeof y(h)=="string"},__wbg_buffer:function(h){let m=y(h).buffer;return d(m)},__wbg_get_baf4855f9a986186:function(){return p(function(h,m){let I=Reflect.get(y(h),y(m));return d(I)},arguments)},__wbindgen_debug_string:function(h,m){let I=lt(y(m)),j=O(I,e.exports.__wbindgen_malloc,e.exports.__wbindgen_realloc),Z=G;D()[h/4+1]=Z,D()[h/4+0]=j},__wbindgen_bigint_get_as_i64:function(h,m){let I=y(m),j=typeof I=="bigint"?I:void 0;Nt()[h/8+1]=N(j)?BigInt(0):j,D()[h/4+0]=!N(j)},__wbindgen_throw:function(h,m){throw new Error(w(h,m))},__wbindgen_memory:function(){let h=e.exports.memory;return d(h)},__wbindgen_closure_wrapper:function(h,m,I){let j=Tt(h,m,r,_t);return d(j)}},C={_assertBoolean:k,_assertNum:q,addBorrowedObject:Lt,addHeapObject:d,getInt32Memory0:D,getObject:y,getStringFromWasm0:w,handleError:p,heap:()=>v,logError:ht,notDefined:S,passStringToWasm0:O,takeObject:tt,wasm:()=>e.exports,WASM_VECTOR_LEN:()=>G,__wbg_adapter_1:_,__wbg_adapter_5:_t};function R(h){return function(){return ht(function(m){let I=h(tt(m));return d(I)},arguments)}}function W(h,m){let I={};for(let[j,Z]of Object.entries(h.extensions)){let rt=Z.rustImports?.(m)??{};for(let[a,u]of Object.entries(rt))a.startsWith("__wbg_")?I[a]=u:I["__wbg_"+a]=R(u)}return I}let x={...U,...W(n,C)},A=Object.keys(x),B=t.reduce((h,m)=>{let I=A.find(j=>m.startsWith(j));if(I===void 0)throw new Error(`Cannot find import mapping for ${m}. Please file a bug.`);if(A.filter(j=>m.startsWith(j)).length!=1)throw new Error(`Multiple import mappings for ${m}. Please file a bug.`);if(h.usedKeys.has(I))throw new Error(`Multiple methods maps to ${I}. Please file a bug.`);return h.res[m]=x[I],h.usedKeys.add(I),h},{res:{},usedKeys:new Set}).res;i==="__WARP_CONTRACTS_VERSION_LEGACY"?(B.initStateLegacy=nr,B.handle=Me):(B.initState=Y,B.warpContractWrite=Ut,B.warpContractView=Ft),B.currentState=xr,B.version=ir,B.lang=Vt;let P={};P.__wbindgen_placeholder__=B;class H{__destroy_into_raw(){let m=this.ptr;return this.ptr=0,m}free(){let m=this.__destroy_into_raw();e.exports.__wbg_statewrapper_free(m)}}return B.StateWrapper=H,P.metering=s.metering,{imports:P,exports:B}};b();b();var qr=class{constructor(t,e){this.swGlobal=t;this.contractDefinition=e;this.assignReadContractState=this.assignReadContractState.bind(this),this.assignViewContractState=this.assignViewContractState.bind(this),this.assignWrite=this.assignWrite.bind(this),this.assignRefreshState=this.assignRefreshState.bind(this)}logger=ct.INST.create("ContractHandler");async dispose(){}assignWrite(t){this.swGlobal.contracts.write=async(e,r,i)=>{if(!t.evaluationOptions.internalWrites)throw new Error("Internal writes feature switched off. Change EvaluationOptions.internalWrites flag to 'true'");let o=i??t.evaluationOptions.throwOnInternalWriteError,s={from:this.contractDefinition.txId,to:e,input:r};this.logger.debug("swGlobal.write call:",s);let c=t.warp.contract(e,t.contract,{callingInteraction:this.swGlobal._activeTx,callType:"write"}),l=await c.applyInput(r,this.swGlobal._activeTx);this.logger.debug("Cache result?:",!this.swGlobal._activeTx.dry);let g=l.type!=="ok"&&o&&(!this.swGlobal._activeTx.dry||this.swGlobal._activeTx.dry&&this.swGlobal._activeTx.strict),w=g?`Internal write auto error for call [${JSON.stringify(s)}]: ${l.errorMessage}`:l.errorMessage,v=w?{...l.originalErrorMessages,[this.swGlobal._activeTx.id]:w}:l.originalErrorMessages;if(c.interactionState().update(c.txId(),{state:l.state,validity:{...l.originalValidity,[this.swGlobal._activeTx.id]:l.type=="ok"},errorMessages:v},this.swGlobal._activeTx.sortKey),g)throw new Wt(l.type==="error"&&l.error?l.error:w);return l}}assignViewContractState(t){this.swGlobal.contracts.viewContractState=async(e,r)=>(this.logger.debug("swGlobal.viewContractState call:",{from:this.contractDefinition.txId,to:e,input:r}),await t.warp.contract(e,t.contract,{callingInteraction:this.swGlobal._activeTx,callType:"view"}).viewStateForTx(r,this.swGlobal._activeTx))}assignReadContractState(t,e){this.swGlobal.contracts.readContractState=async(r,i)=>{this.logger.debug("swGlobal.readContractState call:",{from:this.contractDefinition.txId,to:r,sortKey:e.sortKey,transaction:this.swGlobal.transaction.id});let{contract:o,warp:s}=t,l=await s.contract(r,o,{callingInteraction:e,callType:"read"}).readState(e.sortKey);if(l?.cachedValue?.errorMessages){let w=Reflect.ownKeys(l?.cachedValue?.errorMessages);if(w.length){let v=w[w.length-1],E=l?.cachedValue?.errorMessages[v];if(E&&E.startsWith&&(E.startsWith("[SkipUnsafeError]")||E.startsWith("[NonWhitelistedSourceError]")))throw new Wt(E)}}return i?{state:vr(l.cachedValue.state),validity:l.cachedValue.validity,errorMessages:l.cachedValue.errorMessages}:vr(l.cachedValue.state)}}assignRefreshState(t){this.swGlobal.contracts.refreshState=async()=>t.contract.interactionState().get(this.swGlobal.contract.id,this.swGlobal._activeTx.sortKey)?.state}};var ni=class extends qr{constructor(e,r,i){super(e,r);this.wasmExports=i}async handle(e,r,i){try{let{interaction:o,interactionTx:s}=i;this.swGlobal._activeTx=s,this.swGlobal.caller=o.caller,this.swGlobal.gasLimit=e.evaluationOptions.gasLimit,this.swGlobal.gasUsed=0,this.assignReadContractState(e,s),this.assignViewContractState(e),this.assignWrite(e),await this.swGlobal.kv.open(),await this.swGlobal.kv.begin();let c=await this.doHandle(o);return i.interaction.interactionType==="view"?await this.swGlobal.kv.rollback():await this.swGlobal.kv.commit(),{type:"ok",result:c,state:this.doGetCurrentState(),gasUsed:this.swGlobal.gasUsed,event:null}}catch(o){await this.swGlobal.kv.rollback();let s={errorMessage:o.message,state:r.state,result:null};if(o instanceof Wt||o instanceof _n)return{...s,error:o.error,type:"error",event:null};if(o instanceof Ne)throw o;return{...s,type:"exception",event:null}}finally{await this.swGlobal.kv.close()}}initState(e){switch(this.contractDefinition.srcWasmLang){case"rust":{if("initStateLegacy"in this.wasmExports){this.wasmExports.initStateLegacy(e);return}let r=this.wasmExports.initState(e);if(r)throw new Error(r);return}default:throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`)}}async doHandleLegacy(e){let r=await this.wasmExports.handle(e.input);if(!r)return;if(Object.prototype.hasOwnProperty.call(r,"Ok"))return r.Ok;let i,o="";if(typeof r.Err=="string"||r.Err instanceof String)i=r.Err;else{if("kind"in r.Err)throw new Wt(r.Err);i=Object.keys(r.Err)[0],o=" "+r.Err[i]}throw i=="RuntimeError"?new Error(`[RE:RE]${o}`):new Wt(`[CE:${i}${o}]`)}async doHandle(e){switch(this.contractDefinition.srcWasmLang){case"rust":{if("handle"in this.wasmExports)return await this.doHandleLegacy(e);let r=e.interactionType==="write"?await this.wasmExports.warpContractWrite(e.input):await this.wasmExports.warpContractView(e.input);if(!r)return;if(r.type==="ok")return r.result;throw this.logger.error("Error from rust",r),r.type==="error"?new Wt(r.error):new Error(r.errorMessage)}default:throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`)}}async maybeCallStateConstructor(e,r){if(this.contractDefinition.manifest?.evaluationOptions?.useConstructor)throw Error("Constructor is not implemented for wasm");return e}doGetCurrentState(){switch(this.contractDefinition.srcWasmLang){case"rust":return this.wasmExports.currentState();default:throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`)}}};b();function Uo(n,t){let e=n.trim().split(` +`),r=e[0],i=e[e.length-1];return(/\(\s*\(\)\s*=>\s*{/g.test(r)||/\s*\(\s*function\s*\(\)\s*{/g.test(r))&&/}\s*\)\s*\(\)\s*;/g.test(i)&&(e.shift(),e.pop(),n=e.join(` +`)),n=n.replace(/export\s+async\s+function\s+handle/gmu,"async function handle").replace(/export\s+function\s+handle/gmu,"function handle"),t?` + ${n} + module.exports = handle;`:` + const window=void 0,document=void 0,eval=void 0,globalThis=void 0; + const [SmartWeave, BigNumber, logger${jr()?", Buffer, atob, btoa":""}] = arguments; + class ContractError extends Error { constructor(message) { super(message); this.name = 'ContractError' } }; + function ContractAssert(cond, message) { if (!cond) throw new ContractError(message) }; + ${n}; + return handle; + `}function up(n,t){try{let e=Uo(n,!1);return new Function(e)(),!0}catch(e){return t?.error(e),!1}}var Zl=Qt(wr()),Xl=ka(),Wt=class extends Error{constructor(e,r){super(e.toString());this.error=e;this.subtype=r;this.name="ContractError"}},_n=class extends Error{constructor(e){super(e.toString());this.error=e;this.name="NonWhitelistedSourceError"}},ii=class{constructor(t){this.arweave=t}logger=ct.INST.create("HandlerExecutorFactory");async create(t,e,r,i){r.hasPlugin("contract-blacklist")&&await this.blacklistContracts(r,t),this.checkWhiteListContractSources(t,e);let o=null;e.useKVStorage&&(o=r.kvStorageFactory(t.txId));let s=new ri(this.arweave,{id:t.txId,owner:t.owner},e,i,o);if(r.matchPlugins("^smartweave-extension-").forEach(l=>{r.loadPlugin(l).process(s.extensions)}),t.contractType=="wasm"){this.logger.info("Creating handler for wasm contract",t.txId);let l=St.measure(),g,w=null,v=lp(t.srcBinary);switch(t.srcWasmLang){case"rust":{let E={exports:null,modifiedExports:{wasm_bindgen__convert__closures__invoke2_mut__:null,_dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__:null}},d=await fp(v,t.srcBinary),y=WebAssembly.Module.exports(d).filter(z=>z.kind==="global"&&z.name.startsWith("__WARP_CONTRACTS_VERSION_")).map(z=>z.name).shift()||"__WARP_CONTRACTS_VERSION_LEGACY",k=WebAssembly.Module.imports(d).filter(z=>z.module==="__wbindgen_placeholder__").map(z=>z.name),{imports:N,exports:q}=Aa(s,k,E,t.metadata.dtor,y);w=q,g=await WebAssembly.instantiate(d,N),E.exports=g.exports,Object.keys(g.exports).forEach(z=>{z.startsWith("wasm_bindgen__convert__closures__invoke2_mut__")&&(E.modifiedExports.wasm_bindgen__convert__closures__invoke2_mut__=g.exports[z]),z.startsWith("_dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__")&&(E.modifiedExports._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__=g.exports[z])});break}default:throw new Error(`Support for ${t.srcWasmLang} not implemented yet.`)}return this.logger.info(`WASM ${t.srcWasmLang} handler created in ${l.elapsed()}`),new ni(s,t,w||g.exports)}else{let l=Uo(t.src,r.hasPlugin("vm2"));if(l.includes("unsafeClient"))switch(e.unsafeClient){case"allow":{this.logger.warn(`Reading unsafe contract ${t.txId}, evaluation is non-deterministic!`);break}case"throw":throw new Error(`[SkipUnsafeError] Using unsafeClient is not allowed by default. Use EvaluationOptions.unsafeClient flag to evaluate ${t.txId}.`);case"skip":throw new Wt(`[SkipUnsafeError] Skipping evaluation of the unsafe contract ${t.txId}.`,"unsafeClientSkip");default:throw new Error(`Unknown unsafeClient setting ${e.unsafeClient}`)}if(!e.allowBigInt&&l.includes("BigInt"))throw new Error("Using BigInt is not allowed by default. Use EvaluationOptions.allowBigInt flag.");if(r.hasPlugin("vm2"))return r.loadPlugin("vm2").process({normalizedSource:l,swGlobal:s,logger:this.logger,contractDefinition:t});if(r.hasPlugin("ivm-handler-api"))return r.loadPlugin("ivm-handler-api").process({contractSource:t.src,evaluationOptions:e,arweave:this.arweave,swGlobal:s,contractDefinition:t});{let g=new Function(l),w=jr()?g(s,Xl,ct.INST.create(s.contract.id),Zl.Buffer,atob,btoa):g(s,Xl,ct.INST.create(s.contract.id));return new oi(s,t,w)}}}checkWhiteListContractSources(t,e){if(e&&e.whitelistSources.length>0&&!e.whitelistSources.includes(t.srcTxId))throw new _n(`[NonWhitelistedSourceError] Contract source not part of whitelisted sources list: ${t.srcTxId}.`)}async blacklistContracts(t,e){let r=t.loadPlugin("contract-blacklist"),i=!1;try{i=await r.process(e.txId)}catch(o){this.logger.error(o)}if(i==!0)throw new Wt(`[SkipUnsafeError] Skipping evaluation of the blacklisted contract ${e.txId}.`,"blacklistedSkip")}};function lp(n){let t={status:200,statusText:"OK",headers:{"Content-Type":"application/wasm"}};return new Response(n,t)}async function fp(n,t){return WebAssembly.compileStreaming?await WebAssembly.compileStreaming(n):await WebAssembly.compile(t)}b();b();function Oa(n){let t="";for(let e of n)t+=("0"+e.toString(16)).slice(-2);return t}var hp="".padEnd(13,"0"),Ra="".padEnd(13,"9"),Do="".padEnd(13,"0"),tf="".padEnd(64,"0"),Ba="".padEnd(64,"z"),bn=`${"".padStart(12,"0")},${hp},${tf}`,gp=`${"".padStart(12,"9")},${Ra},${Ba}`,Ye=class{constructor(t){this.arweave=t}logger=ct.INST.create("LexicographicalInteractionsSorter");async sort(t){let e=[...t],r=e.map(i=>this.addSortKey(i));return await Promise.all(r),e.sort((i,o)=>i.node.sortKey.localeCompare(o.node.sortKey))}async createSortKey(t,e,r,i=!1){let o=this.arweave.utils.b64UrlToBuffer(t),s=this.arweave.utils.b64UrlToBuffer(e),c=this.arweave.utils.concatBuffers([o,s]),l=Oa(await this.arweave.crypto.hash(c));return`${`${r}`.padStart(12,"0")},${i?Ra:Do},${l}`}extractBlockHeight(t){return t?parseInt(t.split(",")[0]):null}async addSortKey(t){let{node:e}=t,r=t.node.sortKey;r?(t.node.sortKey=r,this.logger.debug("Using sortKey from sequencer",t.node.sortKey)):t.node.sortKey=await this.createSortKey(e.block.id,e.id,e.block.height)}generateLastSortKey(t){return`${`${t}`.padStart(12,"0")},${Ra},${Ba}`}};var Pa="__init",si=(n,t)=>{let e=new Error(t);throw e.name=n,e},La=(i=>(i.ContractError="ContractError",i.ConstructorError="ConstructorError",i.NetworkCommunicationError="NetworkCommunicationError",i.NonWhitelistedSourceError="NonWhitelistedSourceError",i))(La||{}),oi=class extends qr{constructor(e,r,i){super(e,r);this.contractFunction=i}async handle(e,r,i){let{interaction:o,interactionTx:s}=i;return this.setupSwGlobal(i),this.enableInternalWrites(e,s),this.assertNotConstructorCall(o),await this.runContractFunction(e,o,r.state)}initState(e){}async maybeCallStateConstructor(e,r){if(this.contractDefinition.manifest?.evaluationOptions?.useConstructor){let i={input:{function:Pa,args:e},caller:this.contractDefinition.owner,interactionType:"write"},o={owner:{address:r.caller,key:null},sortKey:bn},s={interaction:i,interactionTx:o};this.setupSwGlobal(s);let c=this.configureSwGlobalForConstructor(),l=await this.runContractFunction(r,i,{});if(c(),l.type!=="ok")throw r.contract.isRoot()?new Error(`ConstructorError: ${l.errorMessage}`):new Wt(`ConstructorError [${r.contract.txId()}]: ${l.errorMessage}`,"constructor");return l.state}else return e}assertNotConstructorCall(e){if(this.contractDefinition.manifest?.evaluationOptions?.useConstructor&&e.input.function===Pa)throw new Error(`You have enabled {useConstructor: true} option, so you can't call function ${Pa}`)}configureSwGlobalForConstructor(){let e=s=>({get:(c,l)=>si("ConstructorError",`SmartWeave.${s}.${String(l)} is not accessible in constructor context`)});this.swGlobal.contracts.readContractState=()=>si("ConstructorError","Internal writes feature is not available in constructor"),this.swGlobal.contracts.viewContractState=()=>si("ConstructorError","Internal writes feature is not available in constructor"),this.swGlobal.contracts.refreshState=()=>si("ConstructorError","Internal writes feature is not available in constructor"),this.swGlobal.contracts.write=()=>si("ConstructorError","Internal writes feature is not available in constructor");let r=new wn(this.swGlobal);this.swGlobal.block=new Proxy(this.swGlobal.block,e("block"));let i=new vn(this.swGlobal);this.swGlobal.vrf=new Proxy(this.swGlobal.vrf,e("vrf"));let o=new yn(this.swGlobal);return this.swGlobal.transaction=new Proxy(this.swGlobal.vrf,e("transaction")),()=>{this.swGlobal.block=r,this.swGlobal.vrf=i,this.swGlobal.transaction=o}}async runContractFunction(e,r,i){let o=vr(i),{timeoutId:s,timeoutPromise:c}=Na(e.evaluationOptions.maxInteractionEvaluationTimeSeconds);try{await this.swGlobal.kv.open(),await this.swGlobal.kv.begin();let l=await Promise.race([c,this.contractFunction(o,r)]);if(l&&(l.state!==void 0||l.result!==void 0)){await this.swGlobal.kv.commit();let g=null;return l.event&&(g={contractTxId:this.swGlobal.contract.id,sortKey:this.swGlobal.transaction.sortKey,transactionId:this.swGlobal.transaction.id,caller:r.caller,input:r.input,blockTimestamp:this.swGlobal.block.timestamp,blockHeight:this.swGlobal.block.height,data:l.event}),{type:"ok",result:l.result,state:l.state||o,event:g}}throw new Error(`Unexpected result from contract: ${JSON.stringify(l)}`)}catch(l){switch(await this.swGlobal.kv.rollback(),l.name){case"ContractError":return{type:"error",errorMessage:l.message,state:i,result:null,event:null};case"ConstructorError":throw e.contract.isRoot()?Error(`ConstructorError: ${l.message}`):new Wt(`ConstructorError [${e.contract.txId()}]: ${l.message}`,"constructor");case"NetworkCommunicationError":throw l;case"NonWhitelistedSourceError":return{type:"error",errorMessage:l.message,state:i,result:null,event:null};default:return{type:"exception",errorMessage:`${l&&l.stack||l&&l.message||l}`,state:i,result:null,event:null}}}finally{s&&clearTimeout(s),await this.swGlobal.kv.close()}}setupSwGlobal({interaction:e,interactionTx:r}){this.swGlobal._activeTx=r,this.swGlobal.caller=e.caller}enableInternalWrites(e,r){this.assignReadContractState(e,r),this.assignViewContractState(e),this.assignWrite(e),this.assignRefreshState(e)}};var ai=n=>new Promise(t=>setTimeout(t,n)),ci=n=>{let t=Number.parseInt(n);if(Number.isNaN(t)&&!Number.isSafeInteger(t))throw Error(`Failed to cast ${n} to integer`);return t},vr=n=>Jl(n),dp=(n,t)=>t instanceof Map?{dataType:"Map",value:Array.from(t.entries())}:t,pp=(n,t)=>typeof t=="object"&&t!==null&&t.dataType==="Map"?new Map(t.value):t,mp=(n,t)=>n-t,yp=(n,t)=>+n-+t,wp=(n,t)=>t-n,vp=(n,t)=>+t-+n;function Na(n){let t=null,e=new Promise((r,i)=>{t=setTimeout(()=>{clearTimeout(t),i("timeout")},n*1e3)});return{timeoutId:t,timeoutPromise:e}}function Ue(n){return n.endsWith("/")?n.slice(0,-1):n}function be(n){return`[d:${n}]`.padEnd(n*2,"-").concat("> ")}function _p(n){let t=[];return Uint8Array.from(n).forEach(function(r){let i=r.toString(16);i.length%2&&(i="0"+i),t.push(i)}),BigInt("0x"+t.join(""))}var jr=new Function("try {return this===window;}catch(e){ return false;}"),Ne=class extends Error{constructor(e){super(e.toString());this.error=e;this.name="NetworkCommunicationError"}};async function we(n){let t;try{t=await n}catch(e){throw new Ne(`Error during network communication: ${JSON.stringify(e)}`)}if(!t?.ok){let e=await t.text();throw new Ne(`Wrong response code: ${t.status}. ${e}`)}try{return await t.json()}catch(e){throw new Ne(`Error while parsing json response: ${JSON.stringify(e)}`)}}async function Ia(n,t){return we(fetch(n,t))}var ef=(r=>(r.ARWEAVE="arweave",r.WARP_SEQUENCER="redstone-sequencer",r.BOTH="both",r))(ef||{}),ui=class{constructor(t=null,e="both"){this.confirmationStatus=t;this.source=e;Object.assign(this,t),this.source=e}_warp;logger=ct.INST.create("WarpGatewayInteractionsLoader");async load(t,e,r,i){this.logger.debug("Loading interactions: for ",{contractId:t,fromSortKey:e,toSortKey:r});let o=[],s=0,c=0,l=0,g=i?i.sourceType:this.source,w=St.measure(),v=Ue(this._warp.gwUrl());do{let E=St.measure(),d=`${v}/gateway/v2/interactions-sort-key`,y=await we(fetch(`${d}?${new URLSearchParams({contractId:t,...this._warp.whoAmI?{client:this._warp.whoAmI}:"",...e?{from:e}:"",...r?{to:r}:"",page:(++s).toString(),fromSdk:"true",...this.confirmationStatus&&this.confirmationStatus.confirmed?{confirmationStatus:"confirmed"}:"",...this.confirmationStatus&&this.confirmationStatus.notCorrupted?{confirmationStatus:"not_corrupted"}:"",...g=="both"?"":{source:g}})}`));this.logger.debug(`Loading interactions: page ${s} loaded in ${E.elapsed()}`),o.push(...y.interactions),c=y.paging.limit,l=y.paging.items,this.logger.debug(`Loaded interactions length: ${o.length}, from: ${e}, to: ${r}`)}while(l==c);return this.logger.debug("All loaded interactions:",{from:e,to:r,loaded:o.length,time:w.elapsed()}),o}type(){return"warp"}clearCache(){}set warp(t){this._warp=t}};var Dt=class{constructor(t,e,r){this.state=t;this.validity=e;this.errorMessages=r}},li=class{ignoreExceptions=!0;waitForConfirmation=!1;updateCacheForEachInteraction=!1;internalWrites=!1;maxCallDepth=7;maxInteractionEvaluationTimeSeconds=60;stackTrace={saveState:!1};sequencerUrl="https://d1o5nlqr4okus2.cloudfront.net/";gasLimit=Number.MAX_SAFE_INTEGER;sourceType="both";unsafeClient="throw";allowBigInt=!1;walletBalanceUrl="http://nyc-1.dev.arweave.net:1984/";mineArLocalBlocks=!0;throwOnInternalWriteError=!0;cacheEveryNInteractions=-1;useKVStorage=!1;remoteStateSyncEnabled=!1;remoteStateSyncSource="https://dre-1.warp.cc/contract";useConstructor=!1;whitelistSources=[]},fi=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e.detail}},Ua=class{constructor(t,e,r,i,o,s,c,l){this.contractTxId=t;this.sortKey=e;this.transactionId=r;this.caller=i;this.input=o;this.blockTimestamp=s;this.blockHeight=c;this.data=l}};b();b();var di=["application/javascript","application/wasm"],Wa=class{dtor},hi=class{src;srcBinary;srcWasmLang;constructor(t){this.src=t.src,this.srcBinary=t.srcBinary,this.srcWasmLang=t.srcWasmLang}},gi=class{txId;srcTxId;initState;minFee;owner;contractType;metadata;manifest;contractTx;srcTx;testnet;constructor(t){this.txId=t.txId,this.srcTxId=t.srcTxId,this.initState=t.initState,this.manifest=t.manifest,this.minFee=t.minFee,this.owner=t.owner,this.contractType=t.contractType,this.metadata=t.metadata,this.contractTx=t.contractTx,this.srcTx=t.srcTx,this.testnet=t.testnet}};b();var Ct={APP_NAME:"App-Name",APP_VERSION:"App-Version",CONTRACT_TX_ID:"Contract",INPUT:"Input",CONTENT_TYPE:"Content-Type",CONTRACT_SRC_TX_ID:"Contract-Src",SDK:"SDK",MIN_FEE:"Min-Fee"},ot={SEQUENCER:"Sequencer",SEQUENCER_OWNER:"Sequencer-Owner",SEQUENCER_MILLIS:"Sequencer-Mills",SEQUENCER_SORT_KEY:"Sequencer-Sort-Key",SEQUENCER_PREV_SORT_KEY:"Sequencer-Prev-Sort-Key",SEQUENCER_LAST_SORT_KEY:"Sequencer-Last-Sort-Key",SEQUENCER_TX_ID:"Sequencer-Tx-Id",SEQUENCER_BLOCK_HEIGHT:"Sequencer-Block-Height",SEQUENCER_BLOCK_ID:"Sequencer-Block-Id",SEQUENCER_BLOCK_TIMESTAMP:"Sequencer-Block-Timestamp",INIT_STATE:"Init-State",INIT_STATE_TX:"Init-State-TX",INTERACT_WRITE:"Interact-Write",WASM_LANG:"Wasm-Lang",WASM_LANG_VERSION:"Wasm-Lang-Version",WASM_META:"Wasm-Meta",REQUEST_VRF:"Request-Vrf",SIGNATURE_TYPE:"Signature-Type",UPLOADER_TX_ID:"Uploader-Tx-Id",WARP_TESTNET:"Warp-Testnet",MANIFEST:"Contract-Manifest",NONCE:"Nonce"};b();var Wf=Qt(Qo()),dc=Qt(wr());b();var Xt=Qt(Se()),zo=class{get(t,e){if(!Object.getOwnPropertyNames(this).includes(t))throw new Error(`Field "${t}" is not a property of the Arweave Transaction class.`);return this[t]instanceof Uint8Array?e&&e.decode&&e.string?Xt.bufferToString(this[t]):e&&e.decode&&!e.string?this[t]:Xt.bufferTob64Url(this[t]):e&&e.decode==!0?e&&e.string?Xt.b64UrlToString(this[t]):Xt.b64UrlToBuffer(this[t]):this[t]}},Hr=class extends zo{format=2;id="";last_tx="";owner="";tags=[];target="";quantity="0";data_size="0";data=new Uint8Array;data_root="";reward="0";signature="";chunks;constructor(t={}){super(),Object.assign(this,t),typeof this.data=="string"&&(this.data=Xt.b64UrlToBuffer(this.data)),t.tags&&(this.tags=t.tags.map(e=>new qt(e.name,e.value)))}addTag(t,e){this.tags.push(new qt(Xt.stringToB64Url(t),Xt.stringToB64Url(e)))}toJSON(){return{format:this.format,id:this.id,last_tx:this.last_tx,owner:this.owner,tags:this.tags,target:this.target,quantity:this.quantity,data:Xt.bufferTob64Url(this.data),data_size:this.data_size,data_root:this.data_root,data_tree:this.data_tree,reward:this.reward,signature:this.signature}}setOwner(t){this.owner=t}setSignature({id:t,owner:e,reward:r,tags:i,signature:o}){this.id=t,this.owner=e,r&&(this.reward=r),i&&(this.tags=i),this.signature=o}async prepareChunks(t){throw new Error("Should not be called, use arweave-js version.")}getChunk(t,e){if(!this.chunks)throw new Error("Chunks have not been prepared");let r=this.chunks.proofs[t],i=this.chunks.chunks[t];return{data_root:this.data_root,data_size:this.data_size,data_path:Xt.bufferTob64Url(r.proof),offset:r.offset.toString(),chunk:Xt.bufferTob64Url(e.slice(i.minByteRange,i.maxByteRange))}}async getSignatureData(){throw new Error("Should not be called, use arweave-js version.")}},qt=class extends zo{name;value;constructor(t,e,r=!1){super(),this.name=t,this.value=e}};var Zt=class{constructor(t){this.warp=t;let{arweave:e}=t;this.baseUrl=`${e.api.config.protocol}://${e.api.config.host}:${e.api.config.port}`,this.logger.debug("baseurl",this.baseUrl)}logger=ct.INST.create("ArweaveWrapper");baseUrl;async warpGwInfo(){return await this.doFetchInfo(`${Ue(this.warp.gwUrl())}/gateway/arweave/info`)}async warpGwBlock(){return this.logger.debug("Calling warp gw block info"),await this.doFetchInfo(`${Ue(this.warp.gwUrl())}/gateway/arweave/block`)}async info(){return await this.doFetchInfo(`${this.baseUrl}/info`)}async gql(t,e){try{let r=JSON.stringify({query:t,variables:e});return{data:await we(fetch(`${this.baseUrl}/graphql`,{method:"POST",body:r,headers:{"Accept-Encoding":"gzip, deflate, br","Content-Type":"application/json",Accept:"application/json"}})),status:200}}catch(r){throw this.logger.error("Error while loading gql",r),r}}async tx(t){let e=await fetch(`${this.baseUrl}/tx/${t}`).then(r=>r.ok?r.json():Promise.reject(r)).catch(r=>{throw r.body?.message&&this.logger.error(r.body.message),new Ne(`Unable to retrieve tx ${t}. ${r.status}. ${r.body?.message}`)});return new Hr({...e})}async txData(t){let e=await fetch(`${this.baseUrl}/${t}`);if(e.ok){let r=await e.arrayBuffer();return dc.Buffer.from(r)}else{this.logger.warn(`Unable to load data from arweave.net/${t} endpoint, falling back to arweave.js`);let r=await this.warp.arweave.transactions.getData(t,{decode:!0});return dc.Buffer.from(r)}}async txDataString(t){let e=await this.txData(t);return Wf.default.utils.bufferToString(e)}async doFetchInfo(t){return await we(fetch(t))}};b();var jt=class{logger=ct.INST.create("TagsParser");getInputTag(t,e){if(jt.hasMultipleInteractions(t)){this.logger.debug("Interaction transaction is using multiple input tx tag format.");let r=t.tags.findIndex(o=>o.name===Ct.CONTRACT_TX_ID&&o.value===e);if(t.tags.length-1===r){this.logger.warn("Wrong tags format: 'Contract' is the last tag");return}let i=t.tags[r+1];if(i.name!==Ct.INPUT){this.logger.warn(`No 'Input' tag found after 'Contract' tag. Instead ${i.name} was found`);return}return i}else return t.tags.find(r=>r.name===Ct.INPUT)}isInteractWrite(t,e){return t.tags.some(r=>r.name===ot.INTERACT_WRITE&&r.value===e)}getInteractWritesContracts(t){return t.tags.filter(e=>e.name===ot.INTERACT_WRITE).map(e=>e.value)}getContractTag(t){return t.tags.find(e=>e.name===Ct.CONTRACT_TX_ID)?.value}getContractsWithInputs(t){let e=new Map;return t.tags.filter(i=>i.name===Ct.CONTRACT_TX_ID).forEach(i=>{e.set(i.value,this.getInputTag(t,i.value))}),e}isEvmSigned(t){return t.tags.some(e=>e.name===ot.SIGNATURE_TYPE&&e.value==="ethereum")}static hasMultipleInteractions(t){return t.tags.filter(e=>e.name===Ct.CONTRACT_TX_ID).length>1}decodeTags(t){let e=t.get("tags"),r=[];for(let i of e)try{let o=i.get("name",{decode:!0,string:!0}),s=i.get("value",{decode:!0,string:!0});r.push({name:o,value:s})}catch{}return r}getTag(t,e){let r=t.get("tags");for(let i of r)try{if(i.get("name",{decode:!0,string:!0})===e)return i.get("value",{decode:!0,string:!0})}catch{}return!1}hasVrfTag(t){return t.tags.some(e=>e.name==ot.REQUEST_VRF&&e.value==="true")}};b();b();function Vf(n){return n.arrayBuffer?n.arrayBuffer():new Promise((t,e)=>{let r=new FileReader;r.addEventListener("loadend",()=>{t(r.result)}),r.addEventListener("error",e),r.readAsArrayBuffer(n)})}async function tm(n){let t=await Vf(n);return new Uint8Array(t)}function Gf(n){return typeof Blob<"u"&&n instanceof Blob}function Li(n){return typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}var em=typeof $.default<"u"&&$.default.versions&&typeof $.default.versions.node<"u"&&typeof $.default.versions.electron>"u";function rm(n){return n.byteOffset===0&&n.byteLength===n.buffer.byteLength}var Yo=class{constructor(t){this.typedArray=t instanceof ArrayBuffer||Li(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}async getLength(){return this.typedArray.byteLength}async read(t,e){return new Uint8Array(this.typedArray.buffer,this.typedArray.byteOffset+t,e)}},Xo=class{constructor(t){this.blob=t}async getLength(){return this.blob.size}async read(t,e){let r=this.blob.slice(t,t+e),i=await Vf(r);return new Uint8Array(i)}async sliceAsBlob(t,e,r=""){return this.blob.slice(t,t+e,r)}};function nm(n,t){var e=Uint8Array;if(n[0]==3&&n[1]==0)return t||new e(0);var r=om,i=qf,o=im,s=jf,c=t==null;c&&(t=new e(n.length>>>2<<3));for(var l=0,g=0,w=0,v=0,E=0,d=0,y=0,k=0,N=0,q,Q;l==0;){if(l=r(n,N,1),g=r(n,N+1,2),N+=3,g==0){N&7&&(N+=8-(N&7));var z=(N>>>3)+4,X=n[z-4]|n[z-3]<<8;c&&(t=pc(t,k+X)),t.set(new e(n.buffer,n.byteOffset+z,X),k),N=z+X<<3,k+=X;continue}if(c&&(t=pc(t,k+(1<<17))),g==1&&(q=st.flmap,Q=st.fdmap,d=(1<<9)-1,y=(1<<5)-1),g==2){w=i(n,N,5)+257,v=i(n,N+5,5)+1,E=i(n,N+10,4)+4,N+=14;for(var D=0;D<38;D+=2)st.itree[D]=0,st.itree[D+1]=0;for(var G=1,D=0;DG&&(G=it)}N+=3*E,Ii(st.itree,G),Ai(st.itree,G,st.imap),q=st.lmap,Q=st.dmap,N=o(st.imap,(1<>>4;if(!(tt>>>8))t[k++]=tt;else{if(tt==256)break;var lt=k+tt-254;if(tt>264){var at=st.ldef[tt-257];lt=k+(at>>>3)+i(n,N,at&7),N+=at&7}var wt=Q[s(n,N)&y];N+=wt&15;var Nt=wt>>>4,Tt=st.ddef[Nt],ht=(Tt>>>4)+r(n,N,Tt&15);for(N+=Tt&15,c&&(t=pc(t,k+(1<<17)));k>>4;if(w<=15)o[l]=w,l++;else{var v=0,E=0;w==16?(E=3+s(r,i,2),i+=2,v=o[l-1]):w==17?(E=3+s(r,i,3),i+=3):w==18&&(E=11+s(r,i,7),i+=7);for(var d=l+E;l>>1;oi&&(i=c),o++}for(;o>1,c=n[o+1],l=s<<4|c,g=t-c,w=n[o]<>>15-t;e[E]=l,w++}}function Mf(n,t){for(var e=st.rev15,r=15-t,i=0;i>>r}}function qf(n,t,e){return(n[t>>>3]|n[(t>>>3)+1]<<8)>>>(t&7)&(1<>>3]|n[(t>>>3)+1]<<8|n[(t>>>3)+2]<<16)>>>(t&7)&(1<>>3]|n[(t>>>3)+1]<<8|n[(t>>>3)+2]<<16)>>>(t&7)}var st=function(){var n=Uint16Array,t=Uint32Array;return{next_code:new n(16),bl_count:new n(16),ordr:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],of0:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],exb:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],ldef:new n(32),df0:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],dxb:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],ddef:new t(32),flmap:new n(512),fltree:[],fdmap:new n(32),fdtree:[],lmap:new n(32768),ltree:[],ttree:[],dmap:new n(32768),dtree:[],imap:new n(512),itree:[],rev15:new n(1<<15),lhst:new t(286),dhst:new t(30),ihst:new t(19),lits:new t(15e3),strt:new n(1<<16),prev:new n(1<<15)}}();(function(){for(var n=32768,t=0;t>>1|(e&1431655765)<<1,e=(e&3435973836)>>>2|(e&858993459)<<2,e=(e&4042322160)>>>4|(e&252645135)<<4,e=(e&4278255360)>>>8|(e&16711935)<<8,st.rev15[t]=(e>>>16|e<<16)>>>17}function r(i,o,s){for(;o--!=0;)i.push(0,s)}for(var t=0;t<32;t++)st.ldef[t]=st.of0[t]<<3|st.exb[t],st.ddef[t]=st.df0[t]<<4|st.dxb[t];r(st.fltree,144,8),r(st.fltree,255-143,9),r(st.fltree,279-255,7),r(st.fltree,287-279,8),Ii(st.fltree,9),Ai(st.fltree,9,st.flmap),Mf(st.fltree,9),r(st.fdtree,32,5),Ii(st.fdtree,5),Ai(st.fdtree,5,st.fdmap),Mf(st.fdtree,5),r(st.itree,19,0),r(st.ltree,286,0),r(st.dtree,30,0),r(st.ttree,320,0)})();var Ff={table:function(){for(var n=new Uint32Array(256),t=0;t<256;t++){for(var e=t,r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;n[t]=e}return n}(),update:function(n,t,e,r){for(var i=0;i>>8;return n},crc:function(n,t,e){return Ff.update(4294967295,n,t,e)^4294967295}};function sm(n,t){return nm(n,t)}var Oi={numWorkers:1,workerURL:"",useWorkers:!1},am=0,$f=0,wc=!0,cm=[],Jo=[],Cn=[],vc=new Map;function um(n){Hf(n.target);let{id:t,error:e,data:r}=n.data,i=vc.get(t);vc.delete(t),e?i.reject(e):i.resolve(r)}function mc(n){return new Promise((t,e)=>{let r=new Worker(n);r.onmessage=i=>{i.data==="start"?(r.onerror=void 0,r.onmessage=void 0,t(r)):e(new Error(`unexpected message: ${i.data}`))},r.onerror=e})}function lm(n,t){return n.require?n.require(t):{}}var Kf=function(){if(em){let{Worker:n}=lm(module,"worker_threads");return{async createWorker(t){return new n(t)},addEventListener(t,e){t.on("message",r=>{e({target:t,data:r})})},async terminate(t){await t.terminate()}}}else return{async createWorker(n){try{return await mc(n)}catch{console.warn("could not load worker:",n)}let t;try{let e=await fetch(n,{mode:"cors"});if(!e.ok)throw new Error(`could not load: ${n}`);t=await e.text(),n=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));let r=await mc(n);return Oi.workerURL=n,r}catch{console.warn("could not load worker via fetch:",n)}if(t!==void 0)try{n=`data:application/javascript;base64,${btoa(t)}`;let e=await mc(n);return Oi.workerURL=n,e}catch{console.warn("could not load worker via dataURI")}throw console.warn("workers will not be used"),new Error("can not start workers")},addEventListener(n,t){n.addEventListener("message",t)},async terminate(n){n.terminate()}}}();function Hf(n){Jo.push(n),Qf()}async function fm(){if(Jo.length===0&&$f{Cn.push({src:n,uncompressedSize:t,type:e,resolve:r,reject:i,id:am++}),Qf()})}function gm(n,t){let e=n&31,r=(n>>5&15)-1,i=(n>>9&127)+1980,o=0,s=(t&31)*2,c=t>>5&63,l=t>>11&31;return new Date(i,r,e,l,c,s,o)}var _c=class{constructor(t,e){this._reader=t,this._rawEntry=e,this.name=e.name,this.nameBytes=e.nameBytes,this.size=e.uncompressedSize,this.compressedSize=e.compressedSize,this.comment=e.comment,this.commentBytes=e.commentBytes,this.compressionMethod=e.compressionMethod,this.lastModDate=gm(e.lastModFileDate,e.lastModFileTime),this.isDirectory=e.uncompressedSize===0&&e.name.endsWith("/"),this.encrypted=!!(e.generalPurposeBitFlag&1),this.externalFileAttributes=e.externalFileAttributes,this.versionMadeBy=e.versionMadeBy}async blob(t="application/octet-stream"){return await Tm(this._reader,this._rawEntry,t)}async arrayBuffer(){return await Em(this._reader,this._rawEntry)}async text(){let t=await this.arrayBuffer();return ki(new Uint8Array(t))}async json(){let t=await this.text();return JSON.parse(t)}},yc=22,dm=65535,pm=101010256,mm=101075792;async function In(n,t,e){return await n.read(t,e)}async function bc(n,t,e,r){return n.sliceAsBlob?await n.sliceAsBlob(t,e,r):await n.read(t,e)}var ym={unsigned(){return 0}};function Ht(n,t){return n[t]+n[t+1]*256}function te(n,t){return n[t]+n[t+1]*256+n[t+2]*65536+n[t+3]*16777216}function Qr(n,t){return te(n,t)+te(n,t+4)*4294967296}var wm=new TextDecoder;function ki(n,t){return Li(n.buffer)&&(n=new Uint8Array(n)),wm.decode(n)}async function vm(n,t){let e=Math.min(yc+dm,t),r=t-e,i=await In(n,r,e);for(let o=e-yc;o>=0;--o){if(te(i,o)!==pm)continue;let s=new Uint8Array(i.buffer,i.byteOffset+o,i.byteLength-o),c=Ht(s,4);if(c!==0)throw new Error(`multi-volume zip files are not supported. This is volume: ${c}`);let l=Ht(s,10),g=te(s,12),w=te(s,16),v=Ht(s,20),E=s.length-yc;if(v!==E)throw new Error(`invalid comment length. expected: ${E}, actual: ${v}`);let d=new Uint8Array(s.buffer,s.byteOffset+22,v),y=ki(d);return l===65535||w===4294967295?await bm(n,r+o,y,d):await Jf(n,w,g,l,y,d)}throw new Error("could not find end of central directory. maybe not zip file")}var _m=117853008;async function bm(n,t,e,r){let i=t-20,o=await In(n,i,20);if(te(o,0)!==_m)throw new Error("invalid zip64 end of central directory locator signature");let s=Qr(o,8),c=await In(n,s,56);if(te(c,0)!==mm)throw new Error("invalid zip64 end of central directory record signature");let l=Qr(c,32),g=Qr(c,40),w=Qr(c,48);return Jf(n,w,g,l,e,r)}var Sm=33639248;async function Jf(n,t,e,r,i,o){let s=0,c=await In(n,t,e),l=[];for(let w=0;wN.length)throw new Error("extra field length exceeds extra field buffer size");d.extraFields.push({id:z,data:N.slice(D,G)}),q=G}if(d.commentBytes=y.slice(k,k+d.fileCommentLength),d.comment=ki(d.commentBytes),s+=y.length,d.uncompressedSize===4294967295||d.compressedSize===4294967295||d.relativeOffsetOfLocalHeader===4294967295){let z=d.extraFields.find(G=>G.id===1);if(!z)throw new Error("expected zip64 extended information extra field");let X=z.data,D=0;if(d.uncompressedSize===4294967295){if(D+8>X.length)throw new Error("zip64 extended information extra field does not include uncompressed size");d.uncompressedSize=Qr(X,D),D+=8}if(d.compressedSize===4294967295){if(D+8>X.length)throw new Error("zip64 extended information extra field does not include compressed size");d.compressedSize=Qr(X,D),D+=8}if(d.relativeOffsetOfLocalHeader===4294967295){if(D+8>X.length)throw new Error("zip64 extended information extra field does not include relative header offset");d.relativeOffsetOfLocalHeader=Qr(X,D),D+=8}}let Q=d.extraFields.find(z=>z.id===28789&&z.data.length>=6&&z.data[0]===1&&te(z.data,1),ym.unsigned(d.nameBytes));if(Q&&(d.fileName=ki(Q.data.slice(5))),d.compressionMethod===0){let z=d.uncompressedSize;if(d.generalPurposeBitFlag&1&&(z+=12),d.compressedSize!==z)throw new Error(`compressed size mismatch for stored file: ${d.compressedSize} != ${z}`)}l.push(d)}return{zip:{comment:i,commentBytes:o},entries:l.map(w=>new _c(n,w))}}async function Yf(n,t){if(t.generalPurposeBitFlag&1)throw new Error("encrypted entries not supported");let e=await In(n,t.relativeOffsetOfLocalHeader,30),r=await n.getLength(),i=te(e,0);if(i!==67324752)throw new Error(`invalid local file header signature: 0x${i.toString(16)}`);let o=Ht(e,26),s=Ht(e,28),c=t.relativeOffsetOfLocalHeader+e.length+o+s,l;if(t.compressionMethod===0)l=!1;else if(t.compressionMethod===8)l=!0;else throw new Error(`unsupported compression method: ${t.compressionMethod}`);let g=c,w=g+t.compressedSize;if(t.compressedSize!==0&&w>r)throw new Error(`file data overflows file bounds: ${g} + ${t.compressedSize} > ${r}`);return{decompress:l,fileDataStart:g}}async function Em(n,t){let{decompress:e,fileDataStart:r}=await Yf(n,t);if(!e){let s=await In(n,r,t.compressedSize);return rm(s)?s.buffer:s.slice().buffer}let i=await bc(n,r,t.compressedSize);return await zf(i,t.uncompressedSize)}async function Tm(n,t,e){let{decompress:r,fileDataStart:i}=await Yf(n,t);if(!r){let c=await bc(n,i,t.compressedSize,e);return Gf(c)?c:new Blob([Li(c.buffer)?new Uint8Array(c):c],{type:e})}let o=await bc(n,i,t.compressedSize);return await zf(o,t.uncompressedSize,e)}async function xm(n){let t;if(typeof Blob<"u"&&n instanceof Blob)t=new Xo(n);else if(n instanceof ArrayBuffer||n&&n.buffer&&n.buffer instanceof ArrayBuffer)t=new Yo(n);else if(Li(n)||Li(n.buffer))t=new Yo(n);else if(typeof n=="string"){let r=await fetch(n);if(!r.ok)throw new Error(`failed http request ${n}, status: ${r.status}: ${r.statusText}`);let i=await r.blob();t=new Xo(i)}else if(typeof n.getLength=="function"&&typeof n.read=="function")t=n;else throw new Error("unsupported source type");let e=await t.getLength();if(e>Number.MAX_SAFE_INTEGER)throw new Error(`file too large. size: ${e}. Only file sizes up 4503599627370496 bytes are supported`);return await vm(t,e)}async function Xf(n){let{zip:t,entries:e}=await xm(n);return{zip:t,entries:Object.fromEntries(e.map(r=>[r.name,r]))}}var Zf=Qt(wr());var Ze=class{constructor(t){this.src=t;this.splitted=this.splitBuffer(t),this.logger.debug(`Buffer splitted into ${this.splitted.length} parts`)}logger=ct.INST.create("WasmSrc");splitted;wasmBinary(){return this.splitted[0]}async sourceCode(){let{entries:t}=await Xf(this.splitted[1]),e=new Map;for(let[r,i]of Object.entries(t)){if(i.isDirectory)continue;let o=await i.text();e.set(r,o)}return e}additionalCode(){return this.splitted.length==2?null:this.splitted[2].toString()}splitBuffer(t){let e="",r=parseInt(t.toString("utf8",0,1));this.logger.debug(`Number of elements: ${r}`);let i=t.length,o=0,s=0;for(let g=2;gparseInt(g));this.logger.debug("Lengths",c);let l=[];for(let g of c){let w=Zf.Buffer.alloc(g),v=s+g;t.copy(w,0,s,v),s=v,l.push(w)}return l}};var zr=class{constructor(t,e){this.arweave=t;this.env=e;this.tagsParser=new jt}logger=ct.INST.create("ContractDefinitionLoader");arweaveWrapper;tagsParser;async load(t,e){let r=St.measure(),i=await this.doLoad(t,e);return this.logger.info(`Contract definition loaded in: ${r.elapsed()}`),i}async doLoad(t,e){let r=St.measure(),i=await this.arweaveWrapper.tx(t),o=await this.arweave.wallets.ownerToAddress(i.owner);this.logger.debug("Contract tx and owner",r.elapsed()),r.reset();let s=e||this.tagsParser.getTag(i,Ct.CONTRACT_SRC_TX_ID),c=this.tagsParser.getTag(i,ot.WARP_TESTNET)||null;if(c&&this.env!=="testnet")throw new Error('Trying to use testnet contract in a non-testnet env. Use the "forTestnet" factory method.');if(!c&&this.env==="testnet")throw new Error("Trying to use non-testnet contract in a testnet env.");let l=this.tagsParser.getTag(i,Ct.MIN_FEE),g=null,w=this.tagsParser.getTag(i,ot.MANIFEST);w&&(g=JSON.parse(w)),this.logger.debug("Tags decoding",r.elapsed()),r.reset();let v=await this.evalInitialState(i);this.logger.debug("init state",v);let E=JSON.parse(v);this.logger.debug("Parsing src and init state",r.elapsed());let{src:d,srcBinary:y,srcWasmLang:k,contractType:N,metadata:q,srcTx:Q}=await this.loadContractSource(s);return{txId:t,srcTxId:s,src:d,srcBinary:y,srcWasmLang:k,initState:E,minFee:l,owner:o,contractType:N,metadata:q,manifest:g,contractTx:i.toJSON(),srcTx:Q,testnet:c}}async loadContractSource(t){let e=St.measure(),r=await this.arweaveWrapper.tx(t),i=this.tagsParser.getTag(r,Ct.CONTENT_TYPE);if(!di.includes(i))throw new Error(`Contract source content type ${i} not supported`);let o=i=="application/javascript"?"js":"wasm",s=o=="js"?await this.arweaveWrapper.txDataString(t):await this.arweaveWrapper.txData(t),c,l,g;if(o=="wasm"){if(l=new Ze(s),c=this.tagsParser.getTag(r,ot.WASM_LANG),!c)throw new Error(`Wasm lang not set for wasm contract src ${t}`);g=JSON.parse(this.tagsParser.getTag(r,ot.WASM_META))}return this.logger.debug("Contract src tx load",e.elapsed()),e.reset(),{src:o=="js"?s:null,srcBinary:o=="wasm"?l.wasmBinary():null,srcWasmLang:c,contractType:o,metadata:g,srcTx:r.toJSON()}}async evalInitialState(t){if(this.tagsParser.getTag(t,ot.INIT_STATE))return this.tagsParser.getTag(t,ot.INIT_STATE);if(this.tagsParser.getTag(t,ot.INIT_STATE_TX)){let e=this.tagsParser.getTag(t,ot.INIT_STATE_TX);return this.arweaveWrapper.txDataString(e)}else return this.arweaveWrapper.txDataString(t.id)}type(){return"arweave"}setCache(t){throw new Error("No cache implemented for this loader")}setSrcCache(t){throw new Error("No cache implemented for this loader")}getCache(){throw new Error("No cache implemented for this loader")}getSrcCache(){throw new Error("No cache implemented for this loader")}set warp(t){this.arweaveWrapper=new Zt(t)}};b();var Zo=Qt(wr());var Ri=class{constructor(t,e,r,i){this.definitionCache=e;this.srcCache=r;this.env=i;this.contractDefinitionLoader=new zr(t,i),this.tagsParser=new jt}rLogger=ct.INST.create("WarpGatewayContractDefinitionLoader");contractDefinitionLoader;arweaveWrapper;tagsParser;_warp;async load(t,e){let r=await this.getFromCache(t,e);if(r)return this.rLogger.debug("WarpGatewayContractDefinitionLoader: Hit from cache!"),r.contractType=="wasm"&&r.srcBinary.data&&(r.srcBinary=Zo.Buffer.from(r.srcBinary.data)),this.verifyEnv(r),r;let i=St.measure(),o=await this.doLoad(t,e);return this.rLogger.info(`Contract definition loaded in: ${i.elapsed()}`),this.verifyEnv(o),await this.putToCache(t,o,e),o}async doLoad(t,e){try{let r=Ue(this._warp.gwUrl()),i=await we(fetch(`${r}/gateway/contract?txId=${t}${e?`&srcTxId=${e}`:""}`));if(i.srcBinary!=null&&!(i.srcBinary instanceof Zo.Buffer)&&(i.srcBinary=Zo.Buffer.from(i.srcBinary.data)),i.srcBinary){let o=new Ze(i.srcBinary);i.srcBinary=o.wasmBinary();let s;i.srcTx?s=new Hr({...i.srcTx}):s=await this.arweaveWrapper.tx(i.srcTxId);let c=JSON.parse(this.tagsParser.getTag(s,ot.WASM_META));i.metadata=c}return i.contractType=i.src?"js":"wasm",i}catch(r){return this.rLogger.warn("Falling back to default contracts loader",r),await this.contractDefinitionLoader.doLoad(t,e)}}async loadContractSource(t){return await this.contractDefinitionLoader.loadContractSource(t)}type(){return"warp"}setCache(t){this.definitionCache=t}setSrcCache(t){this.srcCache=t}getCache(){return this.definitionCache}getSrcCache(){return this.srcCache}verifyEnv(t){if(t.testnet&&this.env!=="testnet")throw new Error('Trying to use testnet contract in a non-testnet env. Use the "forTestnet" factory method.');if(!t.testnet&&this.env==="testnet")throw new Error("Trying to use non-testnet contract in a testnet env.")}async getFromCache(t,e){let r=await this.definitionCache.get(new zt(t,"cd"));if(!r)return null;let i=await this.srcCache.get(new zt(e||r.cachedValue.srcTxId,"src"));return i?{...r.cachedValue,...i.cachedValue}:null}async putToCache(t,e,r){let i=new hi(e),o=new gi(e);await this.definitionCache.put({key:t,sortKey:"cd"},o),await this.srcCache.put({key:r||o.srcTxId,sortKey:"src"},i)}set warp(t){this._warp=t,this.arweaveWrapper=new Zt(t),this.contractDefinitionLoader.warp=t}};b();b();var th=`query Transactions($tags: [TagFilter!]!, $blockFilter: BlockFilter!, $first: Int!, $after: String) { + transactions(tags: $tags, block: $blockFilter, first: $first, sort: HEIGHT_ASC, after: $after) { + pageInfo { + hasNextPage + } + edges { + node { + id + owner { address } + recipient + tags { + name + value + } + block { + height + id + timestamp + } + fee { winston } + quantity { winston } + parent { id } + bundledIn { id } + } + cursor + } + } + }`,Cm=`query Transaction($id: ID!) { + transaction(id: $id) { + id + owner { address, key } + recipient + tags { + name + value + } + block { + height + id + timestamp + } + fee { winston, ar } + quantity { winston, ar } + bundledIn { id } + parent{ id } + signature + } +}`,Im=`query Transactions($tags: [TagFilter!]!) { + transactions(tags: $tags) { + edges { + node { + id + owner { address, key } + recipient + tags { + name + value + } + block { + height + id + timestamp + } + fee { winston, ar } + quantity { winston, ar } + parent { id } + bundledIn { id } + signature + } + } + } +}`,eh=30*1e3,Am=100,We=class{constructor(t){this.warp=t;this.arweaveWrapper=new Zt(t)}arweaveWrapper;logger=ct.INST.create(We.name);async transaction(t){return(await this.fetch(Cm,{id:t})).transaction}async transactionUsingUploaderTag(t){let e={name:ot.UPLOADER_TX_ID,values:[t]},r=(await this.fetch(Im,{tags:[e]})).transactions;if(r.edges.length<1)throw new Error(`No interaction with tag ${ot.UPLOADER_TX_ID}:${t}`);return r.edges[0].node}async transactions(t){let e=(await this.fetch(th,t)).transactions,r=[...e.edges];for(;e.pageInfo.hasNextPage;){let i=e.edges[Am-1].cursor,o={...t,after:i};e=(await this.fetch(th,o)).transactions,r.push(...e.edges)}return r}async fetch(t,e){let r=St.measure(),i=await this.arweaveWrapper.gql(t,e);for(this.logger.debug("GQL page load:",r.elapsed());i.status===403;)this.logger.warn(`GQL rate limiting, waiting ${eh}ms before next try.`),await ai(eh),i=await this.arweaveWrapper.gql(t,e);if(i.status!==200)throw new Error(`Unable to retrieve transactions. Arweave gateway responded with status ${i.status}.`);if(i.data.errors)throw this.logger.error(i.data.errors),new Error("Error while fetching arweave transactions");return i.data.data}};var rh=100;function Sc(n){return!n.node.parent?.id&&!n.node.bundledIn?.id}var Bi=class{constructor(t,e){this.arweave=t;this.environment=e;this.sorter=new Ye(t)}logger=ct.INST.create("ArweaveGatewayInteractionsLoader");sorter;arweaveTransactionQuery;_warp;tagsParser=new jt;async load(t,e,r,i){this.logger.debug("Loading interactions for",{contractId:t,fromSortKey:e,toSortKey:r});let o=this.sorter.extractBlockHeight(e),s=this.sorter.extractBlockHeight(r),c={tags:[{name:Ct.APP_NAME,values:["SmartWeaveAction"]},{name:Ct.CONTRACT_TX_ID,values:[t]}],blockFilter:{min:o,max:s},first:rh},l=St.measure(),g=(await this.arweaveTransactionQuery.transactions(c)).filter(Sc);if(l.stop(),i.internalWrites){let d={tags:[{name:ot.INTERACT_WRITE,values:[t]}],blockFilter:{min:o,max:s},first:rh},y=(await this.arweaveTransactionQuery.transactions(d)).filter(Sc);this.logger.debug("Inner writes interactions length:",y.length),g=g.concat(y)}g=g.filter(d=>d.node.block&&d.node.block.id&&d.node.block.height);let w=await this.sorter.sort(g);e&&r?w=w.filter(d=>d.node.sortKey.localeCompare(e)>0&&d.node.sortKey.localeCompare(r)<=0):e&&!r?w=w.filter(d=>d.node.sortKey.localeCompare(e)>0):!e&&r&&(w=w.filter(d=>d.node.sortKey.localeCompare(r)<=0)),this.logger.debug("All loaded interactions:",{from:e,to:r,loaded:w.length,time:l.elapsed()});let v=this.environment==="local"||this.environment==="testnet",E=this._warp.maybeLoadPlugin("vrf");return w.map(d=>{let y=d.node;return v&&this.tagsParser.hasVrfTag(y)&&(E?y.vrf=E.process().generateMockVrf(y.sortKey):this.logger.warn('Cannot generate mock vrf for interaction - no "warp-contracts-plugin-vrf" attached!')),y})}type(){return"arweave"}clearCache(){}set warp(t){this.arweaveTransactionQuery=new We(t),this._warp=t}};b();var An=class{constructor(t){this.delegate=t}logger=ct.INST.create("CacheableInteractionsLoader");interactionsCache=new Map;async load(t,e,r,i){if(this.logger.debug("Loading interactions for",{contractTxId:t,fromSortKey:e,toSortKey:r}),this.interactionsCache.has(t)){let o=this.interactionsCache.get(t);if(o?.length){let s=o[o.length-1].sortKey;if(s.localeCompare(r)<0){let c=await this.delegate.load(t,s,r,i),l=o.concat(c);return this.interactionsCache.set(t,l),l}}return o}else{let o=await this.delegate.load(t,e,r,i);return o.length&&this.interactionsCache.set(t,o),o}}type(){return this.delegate.type()}clearCache(){this.interactionsCache.clear()}set warp(t){this.delegate.warp=t}};b();var Pi=class{constructor(t,e=[]){this.arweave=t;this.executionContextModifiers=e}logger=ct.INST.create("DefaultStateEvaluator");tagsParser=new jt;async eval(t){return this.doReadState(t.sortedInteractions,new Dt(t.contractDefinition.initState,{},{}),t)}async doReadState(t,e,r){let{ignoreExceptions:i,stackTrace:o,internalWrites:s}=r.evaluationOptions,{contract:c,contractDefinition:l,sortedInteractions:g,warp:w}=r,v=e.state,E=null,d=e.validity,y=e.errorMessages;r?.handler.initState(v);let k=r.contract.callDepth();this.logger.debug(`${be(k)}Evaluating state for ${l.txId} [${t.length} non-cached of ${g.length} all]`);let N=null,q=null,Q=t.length,z=w.maybeLoadPlugin("evm-signature-verification"),X=w.maybeLoadPlugin("evaluation-progress"),D=w.maybeLoadPlugin("vrf"),G=!1;for(let et=0;et0&&et%r.evaluationOptions.cacheEveryNInteractions===0;if(c.isRoot())c.clearChildren(),q&&(c.interactionState().update(c.txId(),q.state,q.tx.sortKey),d[O.id]?await c.interactionState().commit(O,lt):await c.interactionState().rollback(O,lt));else{let at=new Dt(v,d,y);c.interactionState().update(c.txId(),at,E)}}let it=new Dt(v,d,y);return q!==null&&await this.onStateEvaluated(q.tx,r,q.state),new Pt(E,it)}logResult(t,e,r){t.type==="exception"&&this.logger.error(`Executing of interaction: [${r.contractDefinition.txId} -> ${e.id}] threw exception:`,`${t.errorMessage}`),t.type==="error"&&this.logger.warn(`Executing of interaction: [${r.contractDefinition.txId} -> ${e.id}] returned error:`,t.errorMessage)}parseInput(t){try{return JSON.parse(t.value)}catch(e){return this.logger.error(e),null}}};function Ec(n){return n.confirmationStatus===void 0?!0:n.confirmationStatus==="confirmed"}b();var Ni=class extends Pi{constructor(e,r,i=[]){super(e,i);this.cache=r}cLogger=ct.INST.create("CacheableStateEvaluator");async eval(e){let{cachedState:r,contract:i}=e,o=e.sortedInteractions;if(r&&r.sortKey==e.requestedSortKey&&!o?.length)return this.cLogger.info(`Exact cache hit for sortKey ${e?.contractDefinition?.txId}:${r.sortKey}`),e.handler?.initState(r.cachedValue.state),r;let s=e.contractDefinition.txId;if(!s)throw new Error("Contract tx id not set in the execution context");let c=r==null,l=c?e.contractDefinition.initState:r.cachedValue.state,g=c?{}:r.cachedValue.validity,w=c?{}:r.cachedValue.errorMessages;if(c&&(l=await e.handler.maybeCallStateConstructor(e.contractDefinition.initState,e),await i.interactionState().commitKV()),o.length==0)if(this.cLogger.info(`No missing interactions ${s}`),c){e.handler?.initState(l),this.cLogger.debug("Inserting initial state into cache");let v=new Dt(l,{},{});return await this.cache.put(new zt(s,bn),v),new Pt(bn,v)}else return e.handler?.initState(r.cachedValue.state),r;return await this.doReadState(o,new Dt(l,g,w||{}),e)}async onStateEvaluated(e,r,i){let o=r.contractDefinition.txId;this.cLogger.debug(`${be(r.contract.callDepth())}onStateEvaluated: cache update for contract ${o} [${e.sortKey}]`),await this.putInCache(o,e,i)}async onStateUpdate(e,r,i,o=!1){(r.evaluationOptions.updateCacheForEachInteraction||o)&&(this.cLogger.debug(`onStateUpdate: cache update for contract ${r.contractDefinition.txId} [${e.sortKey}]`,{contract:r.contractDefinition.txId,state:i.state,sortKey:e.sortKey}),await this.putInCache(r.contractDefinition.txId,e,i))}async latestAvailableState(e,r){if(this.cLogger.debug("Searching for",{contractTxId:e,sortKey:r}),r){let i=await this.cache.getLessOrEqual(e,r);return i&&this.cLogger.debug(`Latest available state at ${e}: ${i.sortKey}`),i}else return await this.cache.getLast(e)}async onInternalWriteStateUpdate(e,r,i){this.cLogger.debug("Internal write state update:",{sortKey:e.sortKey,dry:e.dry,contractTxId:r,state:i.state}),await this.putInCache(r,e,i)}async onContractCall(e,r,i){if(r.sortedInteractions?.length==0)return;let o=r.sortedInteractions.indexOf(e);o<1||await this.putInCache(r.contractDefinition.txId,r.sortedInteractions[o-1],i)}async putInCache(e,r,i){if(r.dry||r.confirmationStatus!==void 0&&r.confirmationStatus!=="confirmed")return;let o=new Dt(i.state,i.validity,i.errorMessages||{});this.cLogger.debug("Putting into cache",{contractTxId:e,transaction:r.id,sortKey:r.sortKey,dry:r.dry}),await this.cache.put(new zt(e,r.sortKey),o)}async syncState(e,r,i,o){let s=new Dt(i,o,{});return await this.cache.put(new zt(e,r),s),new Pt(r,s)}async dumpCache(){return await this.cache.dump()}async internalWriteState(e,r){return await this.cache.get(new zt(e,r))}async hasContractCached(e){return await this.cache.getLast(e)!=null}async lastCachedSortKey(){return await this.cache.getLastSortKey()}setCache(e){this.cache=e}getCache(){return this.cache}};b();var nh=Qt(wr()),Jr=class{constructor(t,e,r=null){this.contractTxId=t;this.depth=e;this.innerCallType=r;this.id=nh.Crypto.randomUUID()}interactions={};id;addInteractionData(t){let{interaction:e,interactionTx:r}=t,i=kn.create(new ts(r.id,r.sortKey,r.block.height,r.block.timestamp,e?.caller,e?.input.function,e?.input,r.dry,{}));return this.interactions[r.id]=i,i}getInteraction(t){return this.interactions[t]}print(){return JSON.stringify(this,null,2)}},kn=class{constructor(t){this.interactionInput=t}interactionOutput;static create(t){return new kn(t)}update(t){this.interactionOutput=t}},ts=class{constructor(t,e,r,i,o,s,c,l,g={}){this.txId=t;this.sortKey=e;this.blockHeight=r;this.blockTimestamp=i;this.caller=o;this.functionName=s;this.functionArguments=c;this.dryWrite=l;this.foreignContractCalls=g}},Tc=class{constructor(t,e,r,i,o="",s){this.cacheHit=t;this.outputState=e;this.executionTime=r;this.valid=i;this.errorMessage=o;this.gasUsed=s}};b();var hs=Qt(Qo());b();b();var xc=(t=>(t.CONTRACT_NOT_FOUND="CONTRACT_NOT_FOUND",t))(xc||{}),Ui=class extends Error{type;otherInfo;constructor(t,e={}){e.message?super(e.message):super(),this.type=t,this.otherInfo=e}getType(){return this.type}};function km(n){if(!n)return!1;let t=ih(n);return n.evolve!==void 0||t.has("evolve")}var tr=class{logger=ct.INST.create("Evolve");constructor(){this.modify=this.modify.bind(this)}async modify(t,e){let{definitionLoader:r,executorFactory:i}=e.warp,o=e.contractDefinition.txId,s=tr.evolvedSrcTxId(t),c=e.contractDefinition.srcTxId;if(s&&c!==s)try{this.logger.info("Evolving to: ",s);let l=await r.load(o,s),g=await i.create(l,e.evaluationOptions,e.warp,e.contract.interactionState());return e.contractDefinition=l,e.handler=g,e.handler.initState(t),this.logger.debug("evolved to:",{evolve:s,newSrcTxId:e.contractDefinition.srcTxId,currentSrcTxId:c,contract:e.contractDefinition.txId}),e}catch(l){throw l.name==="ContractError"&&l.subtype==="unsafeClientSkip"||l.name=="NonWhitelistedSourceError"?l:new Ui("CONTRACT_NOT_FOUND",{message:`Error while evolving ${o} from ${c} to ${s}: ${l}`,requestedTxId:o})}return e}static evolvedSrcTxId(t){if(!km(t))return;let e=ih(t),r=t.evolve||e.get("evolve"),i=t.canEvolve||e.get("canEvolve");if(i==null&&(i=!0),r&&/[a-z0-9_-]{43}/i.test(r)&&i)return r}};function ih(n){let t=new Map;return n.settings&&(Lm(n.settings)?t=new Map(n.settings):Om(n.settings)&&(t=new Map(Object.entries(n.settings)))),t}function Lm(n){return n==null?!1:typeof n[Symbol.iterator]=="function"}function Om(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}b();b();b();var Rc=Qt(uh(),1),rS=Rc.default.configure;var lh=Rc.default;b();async function rs(n,t,e,r,i,o="",s="0",c=!1,l,g){let w={data:Math.random().toString().slice(-4)};o&&o.length&&(w.target=o.toString(),s&&+s>0&&(w.quantity=s.toString())),c&&(w.reward="0",w.last_tx="p7vc1iSP6bvH_fCeUFa9LqoV5qiyW-jdEKouAT0XMoSwrNraB9mgpi29Q10waEpO"),g&&g.length&&(w.reward=g);let v=await n.createTransaction(w);return ns(e,r,l,i).forEach(d=>v.addTag(d.name,d.value)),t&&await t(v),v}function Bc(n,t,e){let i=new jt().decodeTags(n);return{id:n.id,owner:{address:t,key:""},recipient:n.target,tags:i,fee:{winston:n.reward,ar:""},quantity:{winston:n.quantity,ar:""},block:{id:e.indep_hash,height:e.height,timestamp:e.timestamp,previous:null},dry:!0,anchor:null,signature:null,data:null,parent:null,bundledIn:null}}function ns(n,t,e,r){let i=[];if(r&&r.length)for(let o of r)i.push(new qt(o.name.toString(),o.value.toString()));return i.push(new qt(Ct.APP_NAME,"SmartWeaveAction")),i.push(new qt(Ct.APP_VERSION,"0.3.0")),i.push(new qt(Ct.SDK,"Warp")),i.push(new qt(Ct.CONTRACT_TX_ID,n)),i.push(new qt(Ct.INPUT,JSON.stringify(t))),e&&i.push(new qt(ot.WARP_TESTNET,"1.0.0")),i}b();var Er={target:"",winstonQty:"0"},Dm=["node1","node2","arweave"];b();var Wi=class{eval(t){let e=[];return Object.keys(t.interactions).forEach(r=>{let i=t.interactions[r];this.evalForeignCalls(t.contractTxId,i,e)}),e}evalForeignCalls(t,e,r){Object.keys(e.interactionInput.foreignContractCalls).forEach(i=>{let o=e.interactionInput.foreignContractCalls[i];o.innerCallType=="write"&&Object.keys(o.interactions).forEach(s=>{let c=o.interactions[s];c.interactionInput.dryWrite&&!r.includes(o.contractTxId)&&t!==o.contractTxId&&r.push(o.contractTxId),this.evalForeignCalls(t,c,r)})})}};b();b();var Mm=Object.create,Dc=Object.defineProperty,Fm=Object.getOwnPropertyDescriptor,$m=Object.getOwnPropertyNames,Km=Object.getPrototypeOf,Vm=Object.prototype.hasOwnProperty,rr=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),Gm=(n,t)=>{for(var e in t)Dc(n,e,{get:t[e],enumerable:!0})},qm=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $m(t))!Vm.call(n,i)&&i!==e&&Dc(n,i,{get:()=>t[i],enumerable:!(r=Fm(t,i))||r.enumerable});return n},Zr=(n,t,e)=>(e=n!=null?Mm(Km(n)):{},qm(t||!n||!n.__esModule?Dc(e,"default",{value:n,enumerable:!0}):e,n)),jm=rr(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});function t(e){var r=4,i=e.length,o=i%r;if(!o)return e;var s=i,c=r-o,l=i+c,g=F.Buffer.alloc(l);for(g.write(e);c--;)g.write("=",s++);return g.toString()}n.default=t}),Hm=rr(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=jm();function e(l,g){return g===void 0&&(g="utf8"),F.Buffer.isBuffer(l)?o(l.toString("base64")):o(F.Buffer.from(l,g).toString("base64"))}function r(l,g){return g===void 0&&(g="utf8"),F.Buffer.from(i(l),"base64").toString(g)}function i(l){return l=l.toString(),t.default(l).replace(/\-/g,"+").replace(/_/g,"/")}function o(l){return l.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function s(l){return F.Buffer.from(i(l),"base64")}var c=e;c.encode=e,c.decode=r,c.toBase64=i,c.fromBase64=o,c.toBuffer=s,n.default=c}),Mc=rr((n,t)=>{t.exports=Hm().default,t.exports.default=t.exports}),hh=rr(n=>{"use strict";n.byteLength=l,n.toByteArray=w,n.fromByteArray=d;var t=[],e=[],r=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(o=0,s=i.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var N=y.indexOf("=");N===-1&&(N=k);var q=N===k?0:4-N%4;return[N,q]}function l(y){var k=c(y),N=k[0],q=k[1];return(N+q)*3/4-q}function g(y,k,N){return(k+N)*3/4-N}function w(y){var k,N=c(y),q=N[0],Q=N[1],z=new r(g(y,q,Q)),X=0,D=Q>0?q-4:q,G;for(G=0;G>16&255,z[X++]=k>>8&255,z[X++]=k&255;return Q===2&&(k=e[y.charCodeAt(G)]<<2|e[y.charCodeAt(G+1)]>>4,z[X++]=k&255),Q===1&&(k=e[y.charCodeAt(G)]<<10|e[y.charCodeAt(G+1)]<<4|e[y.charCodeAt(G+2)]>>2,z[X++]=k>>8&255,z[X++]=k&255),z}function v(y){return t[y>>18&63]+t[y>>12&63]+t[y>>6&63]+t[y&63]}function E(y,k,N){for(var q,Q=[],z=k;zD?D:X+z));return q===1?(k=y[N-1],Q.push(t[k>>2]+t[k<<4&63]+"==")):q===2&&(k=(y[N-2]<<8)+y[N-1],Q.push(t[k>>10]+t[k>>4&63]+t[k<<2&63]+"=")),Q.join("")}}),gh=rr(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.b64UrlDecode=n.b64UrlEncode=n.bufferTob64Url=n.bufferTob64=n.b64UrlToBuffer=n.stringToB64Url=n.stringToBuffer=n.bufferToString=n.b64UrlToString=n.concatBuffers=void 0;var t=hh();function e(E){let d=0;for(let N=0;N{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=gh(),e=class{keyLength=4096;publicExponent=65537;hashAlgorithm="sha256";driver;constructor(){if(!this.detectWebCrypto())throw new Error("SubtleCrypto not available!");this.driver=crypto.subtle}async generateJWK(){let r=await this.driver.generateKey({name:"RSA-PSS",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign"]),i=await this.driver.exportKey("jwk",r.privateKey);return{kty:i.kty,e:i.e,n:i.n,d:i.d,p:i.p,q:i.q,dp:i.dp,dq:i.dq,qi:i.qi}}async sign(r,i,{saltLength:o}={}){let s=await this.driver.sign({name:"RSA-PSS",saltLength:32},await this.jwkToCryptoKey(r),i);return new Uint8Array(s)}async hash(r,i="SHA-256"){let o=await this.driver.digest(i,r);return new Uint8Array(o)}async verify(r,i,o){let s={kty:"RSA",e:"AQAB",n:r},c=await this.jwkToPublicCryptoKey(s),l=await this.driver.digest("SHA-256",i),g=await this.driver.verify({name:"RSA-PSS",saltLength:0},c,o,i),w=await this.driver.verify({name:"RSA-PSS",saltLength:32},c,o,i),v=await this.driver.verify({name:"RSA-PSS",saltLength:Math.ceil((c.algorithm.modulusLength-1)/8)-l.byteLength-2},c,o,i);return g||w||v}async jwkToCryptoKey(r){return this.driver.importKey("jwk",r,{name:"RSA-PSS",hash:{name:"SHA-256"}},!1,["sign"])}async jwkToPublicCryptoKey(r){return this.driver.importKey("jwk",r,{name:"RSA-PSS",hash:{name:"SHA-256"}},!1,["verify"])}detectWebCrypto(){if(typeof crypto>"u")return!1;let r=crypto?.subtle;return r===void 0?!1:["generateKey","importKey","exportKey","digest","sign"].every(i=>typeof r[i]=="function")}async encrypt(r,i,o){let s=await this.driver.importKey("raw",typeof i=="string"?t.stringToBuffer(i):i,{name:"PBKDF2",length:32},!1,["deriveKey"]),c=await this.driver.deriveKey({name:"PBKDF2",salt:o?t.stringToBuffer(o):t.stringToBuffer("salt"),iterations:1e5,hash:"SHA-256"},s,{name:"AES-CBC",length:256},!1,["encrypt","decrypt"]),l=new Uint8Array(16);crypto.getRandomValues(l);let g=await this.driver.encrypt({name:"AES-CBC",iv:l},c,r);return t.concatBuffers([l,g])}async decrypt(r,i,o){let s=await this.driver.importKey("raw",typeof i=="string"?t.stringToBuffer(i):i,{name:"PBKDF2",length:32},!1,["deriveKey"]),c=await this.driver.deriveKey({name:"PBKDF2",salt:o?t.stringToBuffer(o):t.stringToBuffer("salt"),iterations:1e5,hash:"SHA-256"},s,{name:"AES-CBC",length:256},!1,["encrypt","decrypt"]),l=r.slice(0,16),g=await this.driver.decrypt({name:"AES-CBC",iv:l},c,r.slice(16));return t.concatBuffers([g])}};n.default=e}),zm=rr(n=>{n.read=function(t,e,r,i,o){var s,c,l=o*8-i-1,g=(1<>1,v=-7,E=r?o-1:0,d=r?-1:1,y=t[e+E];for(E+=d,s=y&(1<<-v)-1,y>>=-v,v+=l;v>0;s=s*256+t[e+E],E+=d,v-=8);for(c=s&(1<<-v)-1,s>>=-v,v+=i;v>0;c=c*256+t[e+E],E+=d,v-=8);if(s===0)s=1-w;else{if(s===g)return c?NaN:(y?-1:1)*(1/0);c=c+Math.pow(2,i),s=s-w}return(y?-1:1)*c*Math.pow(2,s-i)},n.write=function(t,e,r,i,o,s){var c,l,g,w=s*8-o-1,v=(1<>1,d=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=i?0:s-1,k=i?1:-1,N=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,c=v):(c=Math.floor(Math.log(e)/Math.LN2),e*(g=Math.pow(2,-c))<1&&(c--,g*=2),c+E>=1?e+=d/g:e+=d*Math.pow(2,1-E),e*g>=2&&(c++,g/=2),c+E>=v?(l=0,c=v):c+E>=1?(l=(e*g-1)*Math.pow(2,o),c=c+E):(l=e*Math.pow(2,E-1)*Math.pow(2,o),c=0));o>=8;t[r+y]=l&255,y+=k,l/=256,o-=8);for(c=c<0;t[r+y]=c&255,y+=k,c/=256,w-=8);t[r+y-k]|=N*128}}),Nc=rr(n=>{"use strict";var t=hh(),e=zm(),r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;n.Buffer=c,n.SlowBuffer=Q,n.INSPECT_MAX_BYTES=50;var i=2147483647;n.kMaxLength=i,c.TYPED_ARRAY_SUPPORT=o(),!c.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function o(){try{let a=new Uint8Array(1),u={foo:function(){return 42}};return Object.setPrototypeOf(u,Uint8Array.prototype),Object.setPrototypeOf(a,u),a.foo()===42}catch{return!1}}Object.defineProperty(c.prototype,"parent",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.buffer}}),Object.defineProperty(c.prototype,"offset",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.byteOffset}});function s(a){if(a>i)throw new RangeError('The value "'+a+'" is invalid for option "size"');let u=new Uint8Array(a);return Object.setPrototypeOf(u,c.prototype),u}function c(a,u,f){if(typeof a=="number"){if(typeof u=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return v(a)}return l(a,u,f)}c.poolSize=8192;function l(a,u,f){if(typeof a=="string")return E(a,u);if(ArrayBuffer.isView(a))return y(a);if(a==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a);if(m(a,ArrayBuffer)||a&&m(a.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(m(a,SharedArrayBuffer)||a&&m(a.buffer,SharedArrayBuffer)))return k(a,u,f);if(typeof a=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let T=a.valueOf&&a.valueOf();if(T!=null&&T!==a)return c.from(T,u,f);let L=N(a);if(L)return L;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof a[Symbol.toPrimitive]=="function")return c.from(a[Symbol.toPrimitive]("string"),u,f);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a)}c.from=function(a,u,f){return l(a,u,f)},Object.setPrototypeOf(c.prototype,Uint8Array.prototype),Object.setPrototypeOf(c,Uint8Array);function g(a){if(typeof a!="number")throw new TypeError('"size" argument must be of type number');if(a<0)throw new RangeError('The value "'+a+'" is invalid for option "size"')}function w(a,u,f){return g(a),a<=0?s(a):u!==void 0?typeof f=="string"?s(a).fill(u,f):s(a).fill(u):s(a)}c.alloc=function(a,u,f){return w(a,u,f)};function v(a){return g(a),s(a<0?0:q(a)|0)}c.allocUnsafe=function(a){return v(a)},c.allocUnsafeSlow=function(a){return v(a)};function E(a,u){if((typeof u!="string"||u==="")&&(u="utf8"),!c.isEncoding(u))throw new TypeError("Unknown encoding: "+u);let f=z(a,u)|0,T=s(f),L=T.write(a,u);return L!==f&&(T=T.slice(0,L)),T}function d(a){let u=a.length<0?0:q(a.length)|0,f=s(u);for(let T=0;T=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return a|0}function Q(a){return+a!=a&&(a=0),c.alloc(+a)}c.isBuffer=function(a){return a!=null&&a._isBuffer===!0&&a!==c.prototype},c.compare=function(a,u){if(m(a,Uint8Array)&&(a=c.from(a,a.offset,a.byteLength)),m(u,Uint8Array)&&(u=c.from(u,u.offset,u.byteLength)),!c.isBuffer(a)||!c.isBuffer(u))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(a===u)return 0;let f=a.length,T=u.length;for(let L=0,M=Math.min(f,T);LT.length?(c.isBuffer(M)||(M=c.from(M)),M.copy(T,L)):Uint8Array.prototype.set.call(T,M,L);else if(c.isBuffer(M))M.copy(T,L);else throw new TypeError('"list" argument must be an Array of Buffers');L+=M.length}return T};function z(a,u){if(c.isBuffer(a))return a.length;if(ArrayBuffer.isView(a)||m(a,ArrayBuffer))return a.byteLength;if(typeof a!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof a);let f=a.length,T=arguments.length>2&&arguments[2]===!0;if(!T&&f===0)return 0;let L=!1;for(;;)switch(u){case"ascii":case"latin1":case"binary":return f;case"utf8":case"utf-8":return A(a).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return f*2;case"hex":return f>>>1;case"base64":return H(a).length;default:if(L)return T?-1:A(a).length;u=(""+u).toLowerCase(),L=!0}}c.byteLength=z;function X(a,u,f){let T=!1;if((u===void 0||u<0)&&(u=0),u>this.length||((f===void 0||f>this.length)&&(f=this.length),f<=0)||(f>>>=0,u>>>=0,f<=u))return"";for(a||(a="utf8");;)switch(a){case"hex":return Ut(this,u,f);case"utf8":case"utf-8":return wt(this,u,f);case"ascii":return ht(this,u,f);case"latin1":case"binary":return _t(this,u,f);case"base64":return at(this,u,f);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Me(this,u,f);default:if(T)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase(),T=!0}}c.prototype._isBuffer=!0;function D(a,u,f){let T=a[u];a[u]=a[f],a[f]=T}c.prototype.swap16=function(){let a=this.length;if(a%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let u=0;uu&&(a+=" ... "),""},r&&(c.prototype[r]=c.prototype.inspect),c.prototype.compare=function(a,u,f,T,L){if(m(a,Uint8Array)&&(a=c.from(a,a.offset,a.byteLength)),!c.isBuffer(a))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof a);if(u===void 0&&(u=0),f===void 0&&(f=a?a.length:0),T===void 0&&(T=0),L===void 0&&(L=this.length),u<0||f>a.length||T<0||L>this.length)throw new RangeError("out of range index");if(T>=L&&u>=f)return 0;if(T>=L)return-1;if(u>=f)return 1;if(u>>>=0,f>>>=0,T>>>=0,L>>>=0,this===a)return 0;let M=L-T,J=f-u,dt=Math.min(M,J),bt=this.slice(T,L),ut=a.slice(u,f);for(let It=0;It2147483647?f=2147483647:f<-2147483648&&(f=-2147483648),f=+f,I(f)&&(f=L?0:a.length-1),f<0&&(f=a.length+f),f>=a.length){if(L)return-1;f=a.length-1}else if(f<0)if(L)f=0;else return-1;if(typeof u=="string"&&(u=c.from(u,T)),c.isBuffer(u))return u.length===0?-1:it(a,u,f,T,L);if(typeof u=="number")return u=u&255,typeof Uint8Array.prototype.indexOf=="function"?L?Uint8Array.prototype.indexOf.call(a,u,f):Uint8Array.prototype.lastIndexOf.call(a,u,f):it(a,[u],f,T,L);throw new TypeError("val must be string, number or Buffer")}function it(a,u,f,T,L){let M=1,J=a.length,dt=u.length;if(T!==void 0&&(T=String(T).toLowerCase(),T==="ucs2"||T==="ucs-2"||T==="utf16le"||T==="utf-16le")){if(a.length<2||u.length<2)return-1;M=2,J/=2,dt/=2,f/=2}function bt(It,Bt){return M===1?It[Bt]:It.readUInt16BE(Bt*M)}let ut;if(L){let It=-1;for(ut=f;utJ&&(f=J-dt),ut=f;ut>=0;ut--){let It=!0;for(let Bt=0;BtL&&(T=L)):T=L;let M=u.length;T>M/2&&(T=M/2);let J;for(J=0;J>>0,isFinite(f)?(f=f>>>0,T===void 0&&(T="utf8")):(T=f,f=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let L=this.length-u;if((f===void 0||f>L)&&(f=L),a.length>0&&(f<0||u<0)||u>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");let M=!1;for(;;)switch(T){case"hex":return et(this,a,u,f);case"utf8":case"utf-8":return O(this,a,u,f);case"ascii":case"latin1":case"binary":return ft(this,a,u,f);case"base64":return tt(this,a,u,f);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return lt(this,a,u,f);default:if(M)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),M=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function at(a,u,f){return u===0&&f===a.length?t.fromByteArray(a):t.fromByteArray(a.slice(u,f))}function wt(a,u,f){f=Math.min(a.length,f);let T=[],L=u;for(;L239?4:M>223?3:M>191?2:1;if(L+dt<=f){let bt,ut,It,Bt;switch(dt){case 1:M<128&&(J=M);break;case 2:bt=a[L+1],(bt&192)===128&&(Bt=(M&31)<<6|bt&63,Bt>127&&(J=Bt));break;case 3:bt=a[L+1],ut=a[L+2],(bt&192)===128&&(ut&192)===128&&(Bt=(M&15)<<12|(bt&63)<<6|ut&63,Bt>2047&&(Bt<55296||Bt>57343)&&(J=Bt));break;case 4:bt=a[L+1],ut=a[L+2],It=a[L+3],(bt&192)===128&&(ut&192)===128&&(It&192)===128&&(Bt=(M&15)<<18|(bt&63)<<12|(ut&63)<<6|It&63,Bt>65535&&Bt<1114112&&(J=Bt))}}J===null?(J=65533,dt=1):J>65535&&(J-=65536,T.push(J>>>10&1023|55296),J=56320|J&1023),T.push(J),L+=dt}return Tt(T)}var Nt=4096;function Tt(a){let u=a.length;if(u<=Nt)return String.fromCharCode.apply(String,a);let f="",T=0;for(;TT)&&(f=T);let L="";for(let M=u;Mf&&(a=f),u<0?(u+=f,u<0&&(u=0)):u>f&&(u=f),uf)throw new RangeError("Trying to access beyond buffer length")}c.prototype.readUintLE=c.prototype.readUIntLE=function(a,u,f){a=a>>>0,u=u>>>0,f||yt(a,u,this.length);let T=this[a],L=1,M=0;for(;++M>>0,u=u>>>0,f||yt(a,u,this.length);let T=this[a+--u],L=1;for(;u>0&&(L*=256);)T+=this[a+--u]*L;return T},c.prototype.readUint8=c.prototype.readUInt8=function(a,u){return a=a>>>0,u||yt(a,1,this.length),this[a]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(a,u){return a=a>>>0,u||yt(a,2,this.length),this[a]|this[a+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(a,u){return a=a>>>0,u||yt(a,2,this.length),this[a]<<8|this[a+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),(this[a]|this[a+1]<<8|this[a+2]<<16)+this[a+3]*16777216},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),this[a]*16777216+(this[a+1]<<16|this[a+2]<<8|this[a+3])},c.prototype.readBigUInt64LE=Z(function(a){a=a>>>0,C(a,"offset");let u=this[a],f=this[a+7];(u===void 0||f===void 0)&&R(a,this.length-8);let T=u+this[++a]*2**8+this[++a]*2**16+this[++a]*2**24,L=this[++a]+this[++a]*2**8+this[++a]*2**16+f*2**24;return BigInt(T)+(BigInt(L)<>>0,C(a,"offset");let u=this[a],f=this[a+7];(u===void 0||f===void 0)&&R(a,this.length-8);let T=u*2**24+this[++a]*2**16+this[++a]*2**8+this[++a],L=this[++a]*2**24+this[++a]*2**16+this[++a]*2**8+f;return(BigInt(T)<>>0,u=u>>>0,f||yt(a,u,this.length);let T=this[a],L=1,M=0;for(;++M=L&&(T-=Math.pow(2,8*u)),T},c.prototype.readIntBE=function(a,u,f){a=a>>>0,u=u>>>0,f||yt(a,u,this.length);let T=u,L=1,M=this[a+--T];for(;T>0&&(L*=256);)M+=this[a+--T]*L;return L*=128,M>=L&&(M-=Math.pow(2,8*u)),M},c.prototype.readInt8=function(a,u){return a=a>>>0,u||yt(a,1,this.length),this[a]&128?(255-this[a]+1)*-1:this[a]},c.prototype.readInt16LE=function(a,u){a=a>>>0,u||yt(a,2,this.length);let f=this[a]|this[a+1]<<8;return f&32768?f|4294901760:f},c.prototype.readInt16BE=function(a,u){a=a>>>0,u||yt(a,2,this.length);let f=this[a+1]|this[a]<<8;return f&32768?f|4294901760:f},c.prototype.readInt32LE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),this[a]|this[a+1]<<8|this[a+2]<<16|this[a+3]<<24},c.prototype.readInt32BE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]},c.prototype.readBigInt64LE=Z(function(a){a=a>>>0,C(a,"offset");let u=this[a],f=this[a+7];(u===void 0||f===void 0)&&R(a,this.length-8);let T=this[a+4]+this[a+5]*2**8+this[a+6]*2**16+(f<<24);return(BigInt(T)<>>0,C(a,"offset");let u=this[a],f=this[a+7];(u===void 0||f===void 0)&&R(a,this.length-8);let T=(u<<24)+this[++a]*2**16+this[++a]*2**8+this[++a];return(BigInt(T)<>>0,u||yt(a,4,this.length),e.read(this,a,!0,23,4)},c.prototype.readFloatBE=function(a,u){return a=a>>>0,u||yt(a,4,this.length),e.read(this,a,!1,23,4)},c.prototype.readDoubleLE=function(a,u){return a=a>>>0,u||yt(a,8,this.length),e.read(this,a,!0,52,8)},c.prototype.readDoubleBE=function(a,u){return a=a>>>0,u||yt(a,8,this.length),e.read(this,a,!1,52,8)};function Lt(a,u,f,T,L,M){if(!c.isBuffer(a))throw new TypeError('"buffer" argument must be a Buffer instance');if(u>L||ua.length)throw new RangeError("Index out of range")}c.prototype.writeUintLE=c.prototype.writeUIntLE=function(a,u,f,T){if(a=+a,u=u>>>0,f=f>>>0,!T){let J=Math.pow(2,8*f)-1;Lt(this,a,u,f,J,0)}let L=1,M=0;for(this[u]=a&255;++M>>0,f=f>>>0,!T){let J=Math.pow(2,8*f)-1;Lt(this,a,u,f,J,0)}let L=f-1,M=1;for(this[u+L]=a&255;--L>=0&&(M*=256);)this[u+L]=a/M&255;return u+f},c.prototype.writeUint8=c.prototype.writeUInt8=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,1,255,0),this[u]=a&255,u+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,2,65535,0),this[u]=a&255,this[u+1]=a>>>8,u+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,2,65535,0),this[u]=a>>>8,this[u+1]=a&255,u+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,4,4294967295,0),this[u+3]=a>>>24,this[u+2]=a>>>16,this[u+1]=a>>>8,this[u]=a&255,u+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,4,4294967295,0),this[u]=a>>>24,this[u+1]=a>>>16,this[u+2]=a>>>8,this[u+3]=a&255,u+4};function Y(a,u,f,T,L){U(u,T,L,a,f,7);let M=Number(u&BigInt(4294967295));a[f++]=M,M=M>>8,a[f++]=M,M=M>>8,a[f++]=M,M=M>>8,a[f++]=M;let J=Number(u>>BigInt(32)&BigInt(4294967295));return a[f++]=J,J=J>>8,a[f++]=J,J=J>>8,a[f++]=J,J=J>>8,a[f++]=J,f}function nr(a,u,f,T,L){U(u,T,L,a,f,7);let M=Number(u&BigInt(4294967295));a[f+7]=M,M=M>>8,a[f+6]=M,M=M>>8,a[f+5]=M,M=M>>8,a[f+4]=M;let J=Number(u>>BigInt(32)&BigInt(4294967295));return a[f+3]=J,J=J>>8,a[f+2]=J,J=J>>8,a[f+1]=J,J=J>>8,a[f]=J,f+8}c.prototype.writeBigUInt64LE=Z(function(a,u=0){return Y(this,a,u,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeBigUInt64BE=Z(function(a,u=0){return nr(this,a,u,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeIntLE=function(a,u,f,T){if(a=+a,u=u>>>0,!T){let dt=Math.pow(2,8*f-1);Lt(this,a,u,f,dt-1,-dt)}let L=0,M=1,J=0;for(this[u]=a&255;++L>0)-J&255;return u+f},c.prototype.writeIntBE=function(a,u,f,T){if(a=+a,u=u>>>0,!T){let dt=Math.pow(2,8*f-1);Lt(this,a,u,f,dt-1,-dt)}let L=f-1,M=1,J=0;for(this[u+L]=a&255;--L>=0&&(M*=256);)a<0&&J===0&&this[u+L+1]!==0&&(J=1),this[u+L]=(a/M>>0)-J&255;return u+f},c.prototype.writeInt8=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,1,127,-128),a<0&&(a=255+a+1),this[u]=a&255,u+1},c.prototype.writeInt16LE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,2,32767,-32768),this[u]=a&255,this[u+1]=a>>>8,u+2},c.prototype.writeInt16BE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,2,32767,-32768),this[u]=a>>>8,this[u+1]=a&255,u+2},c.prototype.writeInt32LE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,4,2147483647,-2147483648),this[u]=a&255,this[u+1]=a>>>8,this[u+2]=a>>>16,this[u+3]=a>>>24,u+4},c.prototype.writeInt32BE=function(a,u,f){return a=+a,u=u>>>0,f||Lt(this,a,u,4,2147483647,-2147483648),a<0&&(a=4294967295+a+1),this[u]=a>>>24,this[u+1]=a>>>16,this[u+2]=a>>>8,this[u+3]=a&255,u+4},c.prototype.writeBigInt64LE=Z(function(a,u=0){return Y(this,a,u,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeBigInt64BE=Z(function(a,u=0){return nr(this,a,u,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function xr(a,u,f,T,L,M){if(f+T>a.length)throw new RangeError("Index out of range");if(f<0)throw new RangeError("Index out of range")}function ir(a,u,f,T,L){return u=+u,f=f>>>0,L||xr(a,u,f,4,34028234663852886e22,-34028234663852886e22),e.write(a,u,f,T,23,4),f+4}c.prototype.writeFloatLE=function(a,u,f){return ir(this,a,u,!0,f)},c.prototype.writeFloatBE=function(a,u,f){return ir(this,a,u,!1,f)};function Vt(a,u,f,T,L){return u=+u,f=f>>>0,L||xr(a,u,f,8,17976931348623157e292,-17976931348623157e292),e.write(a,u,f,T,52,8),f+8}c.prototype.writeDoubleLE=function(a,u,f){return Vt(this,a,u,!0,f)},c.prototype.writeDoubleBE=function(a,u,f){return Vt(this,a,u,!1,f)},c.prototype.copy=function(a,u,f,T){if(!c.isBuffer(a))throw new TypeError("argument should be a Buffer");if(f||(f=0),!T&&T!==0&&(T=this.length),u>=a.length&&(u=a.length),u||(u=0),T>0&&T=this.length)throw new RangeError("Index out of range");if(T<0)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),a.length-u>>0,f=f===void 0?this.length:f>>>0,a||(a=0);let L;if(typeof a=="number")for(L=u;L2**32?L=_(String(f)):typeof f=="bigint"&&(L=String(f),(f>BigInt(2)**BigInt(32)||f<-(BigInt(2)**BigInt(32)))&&(L=_(L)),L+="n"),T+=` It must be ${u}. Received ${L}`,T},RangeError);function _(a){let u="",f=a.length,T=a[0]==="-"?1:0;for(;f>=T+4;f-=3)u=`_${a.slice(f-3,f)}${u}`;return`${a.slice(0,f)}${u}`}function S(a,u,f){C(u,"offset"),(a[u]===void 0||a[u+f]===void 0)&&R(u,a.length-(f+1))}function U(a,u,f,T,L,M){if(a>f||a3?u===0||u===BigInt(0)?dt=`>= 0${J} and < 2${J} ** ${(M+1)*8}${J}`:dt=`>= -(2${J} ** ${(M+1)*8-1}${J}) and < 2 ** ${(M+1)*8-1}${J}`:dt=`>= ${u}${J} and <= ${f}${J}`,new Ft.ERR_OUT_OF_RANGE("value",dt,a)}S(T,L,M)}function C(a,u){if(typeof a!="number")throw new Ft.ERR_INVALID_ARG_TYPE(u,"number",a)}function R(a,u,f){throw Math.floor(a)!==a?(C(a,f),new Ft.ERR_OUT_OF_RANGE(f||"offset","an integer",a)):u<0?new Ft.ERR_BUFFER_OUT_OF_BOUNDS:new Ft.ERR_OUT_OF_RANGE(f||"offset",`>= ${f?1:0} and <= ${u}`,a)}var W=/[^+/0-9A-Za-z-_]/g;function x(a){if(a=a.split("=")[0],a=a.trim().replace(W,""),a.length<2)return"";for(;a.length%4!==0;)a=a+"=";return a}function A(a,u){u=u||1/0;let f,T=a.length,L=null,M=[];for(let J=0;J55295&&f<57344){if(!L){if(f>56319){(u-=3)>-1&&M.push(239,191,189);continue}else if(J+1===T){(u-=3)>-1&&M.push(239,191,189);continue}L=f;continue}if(f<56320){(u-=3)>-1&&M.push(239,191,189),L=f;continue}f=(L-55296<<10|f-56320)+65536}else L&&(u-=3)>-1&&M.push(239,191,189);if(L=null,f<128){if((u-=1)<0)break;M.push(f)}else if(f<2048){if((u-=2)<0)break;M.push(f>>6|192,f&63|128)}else if(f<65536){if((u-=3)<0)break;M.push(f>>12|224,f>>6&63|128,f&63|128)}else if(f<1114112){if((u-=4)<0)break;M.push(f>>18|240,f>>12&63|128,f>>6&63|128,f&63|128)}else throw new Error("Invalid code point")}return M}function B(a){let u=[];for(let f=0;f>8,L=f%256,M.push(L),M.push(T);return M}function H(a){return t.toByteArray(x(a))}function h(a,u,f,T){let L;for(L=0;L=u.length||L>=a.length);++L)u[L+f]=a[L];return L}function m(a,u){return a instanceof u||a!=null&&a.constructor!=null&&a.constructor.name!=null&&a.constructor.name===u.name}function I(a){return a!==a}var j=function(){let a="0123456789abcdef",u=new Array(256);for(let f=0;f<16;++f){let T=f*16;for(let L=0;L<16;++L)u[T+L]=a[f]+a[L]}return u}();function Z(a){return typeof BigInt>"u"?rt:a}function rt(){throw new Error("BigInt not supported")}}),Jm=rr((n,t)=>{typeof window<"u"?(window.global=window,K.fetch=window.fetch,t.exports={Buffer:Nc().Buffer,Crypto:window.crypto}):t.exports={Buffer:Nc().Buffer,Crypto:crypto}}),dh={};Gm(dh,{AVSCTap:()=>ss,ArweaveSigner:()=>os,DataItem:()=>is,MAX_TAG_BYTES:()=>$c,MIN_BINARY_SIZE:()=>vh,SIG_CONFIG:()=>Di,SignatureConfig:()=>Te,Signer:()=>Ym,createData:()=>Kc,deserializeTags:()=>Wc,indexToType:()=>yh,serializeTags:()=>wh,tagsExceedLimit:()=>Fc});var Ym=class{signer;publicKey;signatureType;signatureLength;ownerLength;pem;static verify(n,t,e,r){throw new Error("You must implement verify method on child")}},Xm=Zr(Mc(),1),Ee=Zr(gh(),1);async function ph(n){if(Array.isArray(n)){let i=(0,Ee.concatBuffers)([(0,Ee.stringToBuffer)("list"),(0,Ee.stringToBuffer)(n.length.toString())]);return await mh(n,await er().hash(i,"SHA-384"))}let t=n,e=(0,Ee.concatBuffers)([(0,Ee.stringToBuffer)("blob"),(0,Ee.stringToBuffer)(t.byteLength.toString())]),r=(0,Ee.concatBuffers)([await er().hash(e,"SHA-384"),await er().hash(t,"SHA-384")]);return await er().hash(r,"SHA-384")}async function mh(n,t){if(n.length<1)return t;let e=(0,Ee.concatBuffers)([t,await ph(n[0])]),r=await er().hash(e,"SHA-384");return await mh(n.slice(1),r)}var Pc=Zr(Qm(),1),Zm=Pc.default.default?Pc.default.default:Pc.default,ty=class extends Zm{getPublicKey(n){throw new Error("Unimplemented")}},ey;function er(){return ey??=new ty}var Te;(function(n){n[n.ARWEAVE=1]="ARWEAVE",n[n.ED25519=2]="ED25519",n[n.ETHEREUM=3]="ETHEREUM",n[n.SOLANA=4]="SOLANA",n[n.INJECTEDAPTOS=5]="INJECTEDAPTOS",n[n.MULTIAPTOS=6]="MULTIAPTOS",n[n.TYPEDETHEREUM=7]="TYPEDETHEREUM"})(Te||(Te={}));var Di={[Te.ARWEAVE]:{sigLength:512,pubLength:512,sigName:"arweave"},[Te.ED25519]:{sigLength:64,pubLength:32,sigName:"ed25519"},[Te.ETHEREUM]:{sigLength:65,pubLength:65,sigName:"ethereum"},[Te.SOLANA]:{sigLength:64,pubLength:32,sigName:"solana"},[Te.INJECTEDAPTOS]:{sigLength:64,pubLength:32,sigName:"injectedAptos"},[Te.MULTIAPTOS]:{sigLength:64*32+4,pubLength:32*32+1,sigName:"multiAptos"},[Te.TYPEDETHEREUM]:{sigLength:65,pubLength:42,sigName:"typedEthereum"}},os=class{signatureType=1;ownerLength=Di[1].pubLength;signatureLength=Di[1].sigLength;jwk;pk;constructor(n){this.pk=n.n,this.jwk=n}get publicKey(){return Xm.default.toBuffer(this.pk)}sign(n){return er().sign(this.jwk,n)}static async verify(n,t,e){return await er().verify(n,t,e)}},yh={1:os},De=Zr(Mc(),1);async function Uc(n){return ph([(0,Ee.stringToBuffer)("dataitem"),(0,Ee.stringToBuffer)("1"),(0,Ee.stringToBuffer)(n.signatureType.toString()),n.rawOwner,n.rawTarget,n.rawAnchor,n.rawTags,n.rawData])}async function ry(n,t){let e=await Uc(n),r=await t.sign(e),i=await er().hash(r);return{signature:F.Buffer.from(r),id:F.Buffer.from(i)}}async function ny(n,t){let{signature:e,id:r}=await ry(n,t);return n.getRaw().set(e,2),r}var ss=class{buf;pos;constructor(n=F.Buffer.alloc($c),t=0){this.buf=n,this.pos=t}writeTags(n){if(!Array.isArray(n))throw new Error("input must be array");let t=n.length,e;if(t)for(this.writeLong(t),e=0;ethis.buf.length)throw new Error(`Too many tag bytes (${this.pos} > ${this.buf.length})`);return this.buf.copy(n,0,0,this.pos),n}tagsExceedLimit(){return this.pos>this.buf.length}writeLong(n){let t=this.buf,e,r;if(n>=-1073741824&&n<1073741824){r=n>=0?n<<1:~n<<1|1;do t[this.pos]=r&127,r>>=7;while(r&&(t[this.pos++]|=128))}else{e=n>=0?n*2:-n*2-1;do t[this.pos]=e&127,e/=128;while(e>=1&&(t[this.pos++]|=128))}this.pos++,this.buf=t}writeString(n){let t=F.Buffer.byteLength(n),e=this.buf;this.writeLong(t);let r=this.pos;if(this.pos+=t,!(this.pos>e.length)){if(t>64)this.buf.write(n,this.pos-t,t,"utf8");else{let i,o,s,c;for(i=0,o=t;i>6|192,e[r++]=s&63|128):(s&64512)===55296&&((c=n.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(c&1023),i++,e[r++]=s>>18|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128,e[r++]=s&63|128):(e[r++]=s>>12|224,e[r++]=s>>6&63|128,e[r++]=s&63|128)}this.buf=e}}readLong(){let n=0,t=0,e=this.buf,r,i,o,s;do r=e[this.pos++],i=r&128,n|=(r&127)<>1^-(n&1)}skipLong(){let n=this.buf;for(;n[this.pos++]&128;);}readTags(){let n=[],t;for(;t=this.readLong();)for(t<0&&(t=-t,this.skipLong());t--;){let e=this.readString(),r=this.readString();n.push({name:e,value:r})}return n}readString(){let n=this.readLong(),t=this.pos,e=this.buf;if(this.pos+=n,!(this.pos>e.length))return this.buf.slice(t,t+n).toString()}};function wh(n){let t=new ss;return t.writeTags(n),t.toBuffer()}function Fc(n){let t=new ss;return t.writeTags(n),t.tagsExceedLimit()}function Wc(n){return new ss(n).readTags()}function Tr(n){let t=0;for(let e=n.length-1;e>=0;e--)t=t*256+n[e];return t}function iy(n){if(n>(2^32-1))throw new Error("Short too long");let t=[0,0];for(let e=0;eDe.default.encode(await this.rawId))()}set id(n){this._id=De.default.toBuffer(n)}get rawId(){return(async()=>Ln.Buffer.from(await oy.Crypto.subtle.digest("SHA-256",this.rawSignature)))()}set rawId(n){this._id=n}get rawSignature(){return this.binary.subarray(2,2+this.signatureLength)}get signature(){return De.default.encode(this.rawSignature)}set rawOwner(n){if(n.byteLength!=this.ownerLength)throw new Error(`Expected raw owner (pubkey) to be ${this.ownerLength} bytes, got ${n.byteLength} bytes.`);this.binary.set(n,2+this.signatureLength)}get rawOwner(){return this.binary.subarray(2+this.signatureLength,2+this.signatureLength+this.ownerLength)}get signatureLength(){return Di[this.signatureType].sigLength}get owner(){return De.default.encode(this.rawOwner)}get ownerLength(){return Di[this.signatureType].pubLength}get rawTarget(){let n=this.getTargetStart();return this.binary[n]==1?this.binary.subarray(n+1,n+33):Ln.Buffer.alloc(0)}get target(){return De.default.encode(this.rawTarget)}get rawAnchor(){let n=this.getAnchorStart();return this.binary[n]==1?this.binary.subarray(n+1,n+33):Ln.Buffer.alloc(0)}get anchor(){return this.rawAnchor.toString()}get rawTags(){let n=this.getTagsStart(),t=Tr(this.binary.subarray(n+8,n+16));return this.binary.subarray(n+16,n+16+t)}get tags(){let n=this.getTagsStart();if(Tr(this.binary.subarray(n,n+8))==0)return[];let t=Tr(this.binary.subarray(n+8,n+16));return Wc(Ln.Buffer.from(this.binary.subarray(n+16,n+16+t)))}get tagsB64Url(){return this.tags.map(n=>({name:De.default.encode(n.name),value:De.default.encode(n.value)}))}getStartOfData(){let n=this.getTagsStart(),t=this.binary.subarray(n+8,n+16),e=Tr(t);return n+16+e}get rawData(){let n=this.getTagsStart(),t=this.binary.subarray(n+8,n+16),e=Tr(t),r=n+16+e;return this.binary.subarray(r,this.binary.length)}get data(){return De.default.encode(this.rawData)}getRaw(){return this.binary}async sign(n){return this._id=await ny(this,n),this.rawId}async setSignature(n){this.binary.set(n,2),this._id=Ln.Buffer.from(await er().hash(n))}isSigned(){return(this._id?.length??0)>0}toJSON(){return{signature:this.signature,owner:this.owner,target:this.target,tags:this.tags.map(n=>({name:De.default.encode(n.name),value:De.default.encode(n.value)})),data:this.data}}static async verify(n){if(n.byteLength$c)return!1;if(i>0)try{if(Wc(Ln.Buffer.from(n.subarray(r+16,r+16+s))).length!==i)return!1}catch{return!1}let c=yh[e],l=await Uc(t);return await c.verify(t.rawOwner,l,t.rawSignature)}async getSignatureData(){return Uc(this)}getTagsStart(){let n=this.getTargetStart(),t=this.binary[n]==1,e=n+(t?33:1),r=this.binary[e]==1;return e+=r?33:1,e}getTargetStart(){return 2+this.signatureLength+this.ownerLength}getAnchorStart(){let n=this.getTargetStart()+1,t=this.binary[this.getTargetStart()]==1;return n+=t?32:0,n}},sy=Zr(Mc(),1);function Kc(n,t,e){let r=t.publicKey,i=e?.target?sy.default.toBuffer(e.target):null,o=1+(i?.byteLength??0),s=e?.anchor?F.Buffer.from(e.anchor):null,c=1+(s?.byteLength??0),l=(e?.tags?.length??0)>0?wh(e.tags):null,g=16+(l?l.byteLength:0),w=F.Buffer.from(n),v=w.byteLength,E=2+t.signatureLength+t.ownerLength+o+c+g+v,d=F.Buffer.alloc(E);if(d.set(iy(t.signatureType),0),d.set(new Uint8Array(t.signatureLength).fill(0),2),r.byteLength!==t.ownerLength)throw new Error(`Owner must be ${t.ownerLength} bytes, but was incorrectly ${r.byteLength}`);d.set(r,2+t.signatureLength);let y=2+t.signatureLength+t.ownerLength;if(d[y]=i?1:0,i){if(i.byteLength!==32)throw new Error(`Target must be 32 bytes but was incorrectly ${i.byteLength}`);d.set(i,y+1)}let k=y+o,N=k+1;if(d[k]=s?1:0,s){if(N+=s.byteLength,s.byteLength!==32)throw new Error("Anchor must be 32 bytes");d.set(s,k+1)}d.set(fh(e?.tags?.length??0),N);let q=fh(l?.byteLength??0);d.set(q,N+8),l&&d.set(l,N+16);let Q=N+g;return d.set(w,Q),new is(d)}var ay={...dh};globalThis.arbundles??=ay;var Mi=class{signer;bundlerSigner;type;warp;signatureProviderType;wallet;cachedAddress;constructor(t,e){this.warp=t,this.isCustomSignature(e)?(this.assertEnvForCustomSigner(e.type),this.signer=e.signer,this.type=e.type,this.signatureProviderType="CustomSignature"):this.isValidBundlerSignature(e)?(this.signatureProviderType="BundlerSigner",this.type=cy(e.signatureType),this.bundlerSigner=e):(this.assignArweaveSigner(e),this.bundlerSigner=typeof e=="string"?null:new os(e),this.signatureProviderType="ArWallet",this.type="arweave"),this.wallet=e}async getAddress(){if(this.cachedAddress)return this.cachedAddress;switch(this.signatureProviderType){case"CustomSignature":return this.wallet.getAddress?this.cachedAddress=await this.wallet.getAddress():this.cachedAddress=await this.deduceSignerBySigning(),this.cachedAddress;case"ArWallet":return this.cachedAddress=await this.deduceSignerBySigning(),this.cachedAddress;case"BundlerSigner":return this.cachedAddress=await this.deduceSignerBySigning(),this.cachedAddress;default:throw Error("Unknown Signature::signatureProvider : "+this.signatureProviderType)}}async deduceSignerBySigning(){let{arweave:t}=this.warp;if(this.signatureProviderType=="BundlerSigner")try{return await this.bundlerSigner.getAddress()}catch{throw new Error("Could not get address from the signer. Is the 'getAddress' implementation correct?'")}else if(this.signatureProviderType=="ArWallet"||this.signatureProviderType=="CustomSignature"){let e=await t.createTransaction({data:Math.random().toString().slice(-4),reward:"72600854",last_tx:"p7vc1iSP6bvH_fCeUFa9LqoV5qiyW-jdEKouAT0XMoSwrNraB9mgpi29Q10waEpO"});return await this.signer(e),t.wallets.ownerToAddress(e.owner)}else throw Error("Unknown Signature::type")}checkNonArweaveSigningAvailability(t){if(this.type!=="arweave"&&!t)throw new Error(`Unable to use signing function of type: ${this.type} when bundling is disabled.`)}checkBundlerSignerAvailability(t){if((!t||this.warp.environment=="local")&&this.signatureProviderType=="BundlerSigner")throw new Error("Only wallet of type 'ArWallet' or 'CustomSignature' is allowed when bundling is disabled or in local environment.")}assignArweaveSigner(t){this.signer=async e=>{await this.warp.arweave.transactions.sign(e,t)}}assertEnvForCustomSigner(t){if(this.warp.interactionsLoader.type()==="warp")throw new Error("Unable to use signing function when bundling is enabled.");if(t=="ethereum")throw new Error(`Unable to use signing function with signature of type: ${t}.`)}isCustomSignature(t){return t.signer!==void 0&&t.type!==void 0}isValidBundlerSignature(t){let e=t,r=!!e.signatureType&&!!e.ownerLength&&!!e.signatureLength;if(r&&!e.publicKey)throw new Error("It seems that you are using BundlerSigner, but publicKey is not set! Maybe try calling await bundlerSigner.setPublicKey() before using it.");return r}};function cy(n){if(n===3)return"ethereum";if(n===1)return"arweave";throw Error(`Not supported arbundle SignatureType : ${n}`)}b();var Fi=class{rootOptions;saferEvaluationOptions={internalWrites:t=>{if(t.internalWrites===void 0||this.rootOptions.internalWrites==t.internalWrites)return this.rootOptions.internalWrites;if(this.rootOptions.internalWrites&&!t.internalWrites||!this.rootOptions.internalWrites&&t.internalWrites)return t.internalWrites;throw new Error('Could not determine "internalWrites" value ')},throwOnInternalWriteError:t=>t.throwOnInternalWriteError===void 0?this.rootOptions.throwOnInternalWriteError:t.throwOnInternalWriteError,unsafeClient:t=>{if(t.unsafeClient===void 0||this.rootOptions.unsafeClient==t.unsafeClient)return this.rootOptions.unsafeClient;if(this.rootOptions.unsafeClient==="throw"||this.rootOptions.unsafeClient==="skip")return this.rootOptions.unsafeClient;if(this.rootOptions.unsafeClient==="allow")return t.unsafeClient==="throw"?"skip":t.unsafeClient;throw new Error('Could not determine "unsafeClient" value')},ignoreExceptions:t=>{if(t.ignoreExceptions===void 0||this.rootOptions.ignoreExceptions==t.ignoreExceptions)return this.rootOptions.ignoreExceptions;if(this.rootOptions.ignoreExceptions&&!t.ignoreExceptions)return this.rootOptions.ignoreExceptions;if(!this.rootOptions.ignoreExceptions&&t.ignoreExceptions)return this.rootOptions.ignoreExceptions;throw new Error('Could not determine "ignoreExceptions" value')},waitForConfirmation:()=>this.rootOptions.waitForConfirmation,updateCacheForEachInteraction:()=>this.rootOptions.updateCacheForEachInteraction,maxCallDepth:()=>this.rootOptions.maxCallDepth,maxInteractionEvaluationTimeSeconds:()=>this.rootOptions.maxInteractionEvaluationTimeSeconds,stackTrace:()=>this.rootOptions.stackTrace,sourceType:()=>this.rootOptions.sourceType,sequencerUrl:()=>this.rootOptions.sequencerUrl,gasLimit:()=>this.rootOptions.gasLimit,allowBigInt:()=>this.rootOptions.allowBigInt,walletBalanceUrl:()=>this.rootOptions.walletBalanceUrl,mineArLocalBlocks:()=>this.rootOptions.mineArLocalBlocks,cacheEveryNInteractions:()=>this.rootOptions.cacheEveryNInteractions,remoteStateSyncEnabled:()=>this.rootOptions.remoteStateSyncEnabled,remoteStateSyncSource:()=>this.rootOptions.remoteStateSyncSource,useKVStorage:t=>t.useKVStorage,useConstructor:t=>t.useConstructor,whitelistSources:()=>this.rootOptions.whitelistSources};notConflictingEvaluationOptions=["useKVStorage","sourceType","useConstructor"];constructor(t,e){if(e){let r=[];for(let i in e){if(!t.hasOwnProperty(i))throw new Error("Unknown option set in contract's manifest. You probably need to update the Warp SDK version.");let o=i,s=e[i],c=t[i];if(!this.notConflictingEvaluationOptions.includes(o))if(o==="internalWrites"){if(c===!1&&s===!0)throw new Error("Cannot proceed with contract evaluation. User is blocking internal writes, while contract requires them.")}else if(o==="unsafeClient"){if(c==="throw"&&s!=="throw"||c==="skip"&&s==="allow")throw new Error(`Cannot proceed with contract evaluation. User requires to ${c} on any unsafeClient usage, while contract uses ${s} option.`)}else t[i]!==e[i]&&r.push(`Option {${i}} differs. EvaluationOptions: [${t[i]}], manifest: [${e[i]}]. Use contract.setEvaluationOptions({${i}: ${e[i]}}) to evaluate contract state.`)}if(r.length)throw new Error(r.join(` +`))}this.rootOptions=Object.freeze(Object.assign({},t,e||{}))}forForeignContract(t){let e=vr(this.rootOptions);if(t)for(let r in t)e[r]=this.saferEvaluationOptions[r](t);return Object.freeze(e)}};b();var $i=class{constructor(t){this.warp=t;this.warp=t}name="WarpFetchWrapper";logger=ct.INST.create(this.name);fetch(t,e){let r;if(this.warp.hasPlugin("fetch-options")){let i=this.warp.loadPlugin("fetch-options");try{let o=i.process({input:t,init:e||{}});r={...e,...o}}catch(o){throw o.message&&this.logger.error(o.message),new Error(`Unable to process fetch options: ${o.message}`)}}else r=e;return fetch(t,r)}};b();var US=new Error("timeout while waiting for mutex to become available"),WS=new Error("mutex already locked"),uy=new Error("request for lock canceled"),ly=function(n,t,e,r){function i(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function c(w){try{g(r.next(w))}catch(v){s(v)}}function l(w){try{g(r.throw(w))}catch(v){s(v)}}function g(w){w.done?o(w.value):i(w.value).then(c,l)}g((r=r.apply(n,t||[])).next())})},Vc=class{constructor(t,e=uy){this._value=t,this._cancelError=e,this._weightedQueues=[],this._weightedWaiters=[]}acquire(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise((e,r)=>{this._weightedQueues[t-1]||(this._weightedQueues[t-1]=[]),this._weightedQueues[t-1].push({resolve:e,reject:r}),this._dispatch()})}runExclusive(t,e=1){return ly(this,void 0,void 0,function*(){let[r,i]=yield this.acquire(e);try{return yield t(r)}finally{i()}})}waitForUnlock(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise(e=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),this._weightedWaiters[t-1].push(e),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatch()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatch()}cancel(){this._weightedQueues.forEach(t=>t.forEach(e=>e.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var t;for(let e=this._value;e>0;e--){let r=(t=this._weightedQueues[e-1])===null||t===void 0?void 0:t.shift();if(!r)continue;let i=this._value,o=e;this._value-=e,e=this._value+1,r.resolve([i,this._newReleaser(o)])}this._drainUnlockWaiters()}_newReleaser(t){let e=!1;return()=>{e||(e=!0,this.release(t))}}_drainUnlockWaiters(){for(let t=this._value;t>0;t--)this._weightedWaiters[t-1]&&(this._weightedWaiters[t-1].forEach(e=>e()),this._weightedWaiters[t-1]=[])}},fy=function(n,t,e,r){function i(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function c(w){try{g(r.next(w))}catch(v){s(v)}}function l(w){try{g(r.throw(w))}catch(v){s(v)}}function g(w){w.done?o(w.value):i(w.value).then(c,l)}g((r=r.apply(n,t||[])).next())})},as=class{constructor(t){this._semaphore=new Vc(1,t)}acquire(){return fy(this,void 0,void 0,function*(){let[,t]=yield this._semaphore.acquire();return t})}runExclusive(t){return this._semaphore.runExclusive(()=>t())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};b();b();var cs=class{cache;capacity;constructor(t){this.cache=new Map,this.capacity=t||10}has(t){return this.cache.has(t)}size(){return this.cache.size}get(t){if(!this.cache.has(t))return null;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}set(t,e){this.cache.delete(t),this.cache.size===this.capacity?(this.cache.delete(this.cache.keys().next().value),this.cache.set(t,e)):this.cache.set(t,e)}keys(){return Array.from(this.cache.keys())}};var Ki=class{constructor(t){this._warp=t}_json=new Map;_initialJson=new Map;_kv=new Map;has(t,e){return this._json.get(t)?.has(e)||!1}get(t,e){return this._json.get(t)?.get(e)||null}getLessOrEqual(t,e){let r=this._json.get(t);if(r!=null&&r.size()>0){let i=r.keys();e&&(i=i.filter(s=>s.localeCompare(e)<=0)),i=i.sort((s,c)=>s.localeCompare(c));let o=i[i.length-1];if(r.get(o))return new Pt(o,r.get(o))}return null}async getKV(t,e){return this._kv.has(t)&&(await this._kv.get(t).get(e))?.cachedValue||null}async delKV(t,e){this._kv.has(t)&&await this._kv.get(t).del(e)}getKvKeys(t,e,r){return this._warp.kvStorageFactory(t).keys(e,r)}getKvRange(t,e,r){return this._warp.kvStorageFactory(t).kvMap(e,r)}async commit(t,e=!1){if(t.dry)return await this.rollbackKVs(),this.reset();try{let r=new Map;this._json.forEach((i,o)=>{let s=this.getLessOrEqual(o,t.sortKey);s!=null&&r.set(o,s.cachedValue)}),await this.doStoreJson(r,t,e),await this.commitKVs()}finally{this.reset()}}async commitKV(){await this.commitKVs(),this._kv.clear()}async rollback(t,e){try{await this.doStoreJson(this._initialJson,t,e),await this.rollbackKVs()}finally{this.reset()}}setInitial(t,e,r){this._initialJson.set(t,e),this.update(t,e,r)}update(t,e,r){if(!this._json.has(t)){let i=new cs(10);this._json.set(t,i)}this._json.get(t).set(r,e)}async updateKV(t,e,r){await(await this.getOrInitKvStorage(t)).put(e,r)}async getOrInitKvStorage(t){if(this._kv.has(t))return this._kv.get(t);let e=this._warp.kvStorageFactory(t);return this._kv.set(t,e),await e.open(),e}reset(){this._json.clear(),this._initialJson.clear(),this._kv.clear()}async doStoreJson(t,e,r=!1){if(t.size>1||r)for(let[i,o]of t)await this._warp.stateEvaluator.putInCache(i,e,o)}async rollbackKVs(){for(let t of this._kv.values())try{await t.rollback()}finally{await t.close()}}async commitKVs(){for(let t of this._kv.values())try{await t.commit()}finally{await t.close()}}};var _h=Qt(wr());var tn=class{constructor(t,e,r=null,i=null){this._contractTxId=t;this.warp=e;this._parentContract=r;this._innerCallData=i;if(this.waitForConfirmation=this.waitForConfirmation.bind(this),this._arweaveWrapper=new Zt(e),this._sorter=new Ye(e.arweave),r!=null){this._evaluationOptions=this.getRoot().evaluationOptions(),this._callDepth=r.callDepth()+1;let o=r.getCallStack().getInteraction(i.callingInteraction.id);if(this._callDepth>this._evaluationOptions.maxCallDepth)throw new Error(`Max call depth of ${this._evaluationOptions.maxCallDepth} has been exceeded for interaction ${JSON.stringify(o.interactionInput)}`);if(this.logger.debug("Calling interaction",{id:i.callingInteraction.id,sortKey:i.callingInteraction.sortKey,type:i.callType}),o.interactionInput?.foreignContractCalls[t]?.innerCallType==="write"&&i.callType==="read")throw new Error("Calling a readContractState after performing an inner write is wrong - instead use a state from the result of an internal write.");let s=new Jr(t,this._callDepth,i?.callType);o.interactionInput.foreignContractCalls[t]=s,this._callStack=s,this._rootSortKey=r.rootSortKey,r._children.push(this)}else this._callDepth=0,this._callStack=new Jr(t,0),this._rootSortKey=null,this._evaluationOptions=new li,this._children=[],this._interactionState=new Ki(e);this.getCallStack=this.getCallStack.bind(this),this._warpFetchWrapper=new $i(this.warp)}logger=ct.INST.create("HandlerBasedContract");ecLogger=ct.INST.create("ExecutionContext");_innerWritesEvaluator=new Wi;_callDepth;_arweaveWrapper;_mutex=new as;_callStack;_evaluationOptions;_eoEvaluator;_benchmarkStats=null;_sorter;_rootSortKey;_signature;_warpFetchWrapper;_children=[];_interactionState;_dreStates=new Map;async readState(t,e,r){if(this.logger.info("Read state for",{contractTxId:this._contractTxId,sortKeyOrBlockHeight:t}),!this.isRoot()&&t==null)throw new Error("SortKey MUST be always set for non-root contract calls");let{stateEvaluator:i}=this.warp,o=typeof t=="number"?this._sorter.generateLastSortKey(t):t;if(o&&!this.isRoot()&&this.interactionState().has(this.txId(),o)){let c=this.interactionState().get(this.txId(),o);return new Pt(o,c)}let s=await this._mutex.acquire();try{let c=St.measure();this.maybeResetRootContract();let l=await this.createExecutionContext(this._contractTxId,o,!1,r);this.logger.info("Execution Context",{srcTxId:l.contractDefinition?.srcTxId,missingInteractions:l.sortedInteractions?.length,cachedSortKey:l.cachedState?.sortKey}),c.stop();let g=St.measure(),w=await i.eval(l);g.stop();let v=c.elapsed(!0)+g.elapsed(!0);return this._benchmarkStats={gatewayCommunication:c.elapsed(!0),stateEvaluation:g.elapsed(!0),total:v},this.logger.info("Benchmark",{"Gateway communication ":c.elapsed(),"Contract evaluation ":g.elapsed(),"Total: ":`${v.toFixed(0)}ms`}),o&&!this.isRoot()&&this.interactionState().update(this.txId(),w.cachedValue,o),w}finally{s()}}async readStateFor(t,e){return this.readState(t,void 0,e)}async viewState(t,e=[],r=Er,i){return this.logger.info("View state for",this._contractTxId),await this.callContract(t,"view",i,void 0,e,r)}async viewStateForTx(t,e){return this.logger.info(`View state for ${this._contractTxId}`),await this.doApplyInputOnTx(t,e,"view")}async dryWrite(t,e,r,i,o){return this.logger.info("Dry-write for",this._contractTxId),await this.callContract(t,"write",e,void 0,r,i,void 0,o)}async applyInput(t,e){return this.logger.info(`Apply-input from transaction ${e.id} for ${this._contractTxId}`),await this.doApplyInputOnTx(t,e,"write")}async writeInteraction(t,e){if(this.logger.info("Write interaction",{input:t,options:e}),!this._signature)throw new Error("Wallet not connected. Use 'connect' method first.");let{arweave:r,interactionsLoader:i,environment:o}=this.warp;await this.warp.definitionLoader.load(this._contractTxId);let s=e?.tags||[],c=e?.transfer||Er,l=e?.strict===!0,g=e?.vrf===!0,w=e?.disableBundling===!0,v=e?.reward,E=i.type()=="warp"&&!w;if(this._signature.checkNonArweaveSigningAvailability(E),this._signature.checkBundlerSignerAvailability(E),E&&c.target!=Er.target&&c.winstonQty!=Er.winstonQty)throw new Error("Ar Transfers are not allowed for bundled interactions");if(g&&!E&&o==="mainnet")throw new Error("Vrf generation is only available for bundle interaction");if(!t)throw new Error(`Input should be a truthy value: ${JSON.stringify(t)}`);if(E)return await this.bundleInteraction(t,{tags:s,strict:l,vrf:g});{let d=await this.createInteraction(t,s,c,l,!1,g&&o!=="mainnet",v),y=await r.transactions.post(d);if(y.status!==200)return this.logger.error("Error while posting transaction",y),null;if(this._evaluationOptions.waitForConfirmation){this.logger.info("Waiting for confirmation of",d.id);let k=St.measure();await this.waitForConfirmation(d.id),this.logger.info("Transaction confirmed after",k.elapsed())}return this.warp.environment=="local"&&this._evaluationOptions.mineArLocalBlocks&&await this.warp.testing.mineBlock(),{originalTxId:d.id,interactionTx:d}}}async bundleInteraction(t,e){this.logger.info("Bundle interaction input",t);let r=await this.createInteractionDataItem(t,e.tags,Er,e.strict,e.vrf),i=this._warpFetchWrapper.fetch(`${Ue(this._evaluationOptions.sequencerUrl)}/gateway/v2/sequencer/register`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Accept:"application/json"},body:r.getRaw()}),o=await r.id;return{bundlrResponse:await we(i),originalTxId:o,interactionTx:r}}async createInteractionDataItem(t,e,r,i,o=!1){this._evaluationOptions.internalWrites&&await this.discoverInternalWrites(t,e,r,i,o),o&&e.push(new qt(ot.REQUEST_VRF,"true"));let s=ns(this._contractTxId,t,this.warp.environment==="testnet",e);if(Fc(s))throw new Error("Interaction tags exceed limit of 4096 bytes.");let c=Math.random().toString().slice(-4),l=this._signature.bundlerSigner;if(!l)throw new Error("Signer not set correctly. If you connect wallet through 'use_wallet', please remember that it only works when bundling is disabled.");let g;return jr()&&l.signer?.signDataItem?g=await l.signDataItem(c,s):(g=Kc(c,l,{tags:s}),await g.sign(l)),!this._evaluationOptions.internalWrites&&i&&await this.checkInteractionInStrictMode(g.owner,t,e,r,i,o),g}async createInteraction(t,e,r,i,o=!1,s=!1,c){this._evaluationOptions.internalWrites&&await this.discoverInternalWrites(t,e,r,i,s),s&&e.push(new qt(ot.REQUEST_VRF,"true"));let l=await rs(this.warp.arweave,this._signature.signer,this._contractTxId,t,e,r.target,r.winstonQty,o,this.warp.environment==="testnet",c);return!this._evaluationOptions.internalWrites&&i&&await this.checkInteractionInStrictMode(l.owner,t,e,r,i,s),l}async checkInteractionInStrictMode(t,e,r,i,o,s){let{arweave:c}=this.warp,l=this._signature.type=="arweave"?await c.wallets.ownerToAddress(t):await this._signature.getAddress(),g=await this.callContract(e,"write",l,void 0,r,i,o,s);if(g.type==="error")throw new Wt(g.error);if(g.type!=="ok")throw Error("Cannot create interaction: "+JSON.stringify(g.error||g.errorMessage))}txId(){return this._contractTxId}getCallStack(){return this._callStack}connect(t){return this._signature=new Mi(this.warp,t),this}setEvaluationOptions(t){if(!this.isRoot())throw new Error("Evaluation options can be set only for the root contract");return this._evaluationOptions={...this._evaluationOptions,...t},this}async waitForConfirmation(t){let{arweave:e}=this.warp,r=await e.transactions.getStatus(t);return r.confirmed===null?(this.logger.info(`Transaction ${t} not yet confirmed. Waiting another 20 seconds before next check.`),await ai(2e4),this.waitForConfirmation(t)):(this.logger.info(`Transaction ${t} confirmed`,r),r)}async createExecutionContext(t,e,r=!1,i){let{definitionLoader:o,interactionsLoader:s,stateEvaluator:c}=this.warp,l,g=St.measure();this.isRoot()||(l=this.interactionState().getLessOrEqual(this.txId(),e)),l=l||await c.latestAvailableState(t,e),this.logger.debug("cache lookup",g.elapsed()),g.reset();let w=tr.evolvedSrcTxId(l?.cachedValue?.state),v,E,d,y,k=i||[];if(this.logger.debug("Cached state",l,e),l&&l.sortKey==e)this.logger.debug("State fully cached, not loading interactions."),(r||w||i?.length)&&(E=await o.load(t,w),i?.length&&(k=(await this._sorter.sort(i.map(N=>({node:N,cursor:null})))).map(N=>N.node)));else{if(i?.length)throw new Error(`Cannot apply requested interactions at ${e}`);if(E=await o.load(t,w),d=this.resolveEvaluationOptions(E.manifest?.evaluationOptions),d.remoteStateSyncEnabled&&!d.useKVStorage){y=await this.getRemoteContractState(t),l=await this.maybeSyncStateWithRemoteSource(y,e,l);let N=tr.evolvedSrcTxId(l?.cachedValue?.state);N&&N!==E.srcTxId&&(E=await o.load(t,N))}this.warp.executorFactory.checkWhiteListContractSources(E,d),!y&&k.length==0&&(k=await s.load(t,l?.sortKey,this.getToSortKey(e),d)),l?.sortKey&&(k=k.filter(N=>N.sortKey.localeCompare(l?.sortKey)>0)),e&&(k=k.filter(N=>N.sortKey.localeCompare(e)<=0)),this.logger.debug("contract and interactions load",g.elapsed()),this.isRoot()&&k.length&&(this._rootSortKey=k[k.length-1].sortKey)}return E&&(d||(d=this.resolveEvaluationOptions(E.manifest?.evaluationOptions)),this.ecLogger.debug(`Evaluation options ${t}:`,d),v=await this.warp.executorFactory.create(E,d,this.warp,this.interactionState())),{warp:this.warp,contract:this,contractDefinition:E,sortedInteractions:k,evaluationOptions:d||this.evaluationOptions(),handler:v,cachedState:l,requestedSortKey:e}}resolveEvaluationOptions(t){return this.isRoot()?(this._eoEvaluator=new Fi(this.evaluationOptions(),t),this._eoEvaluator.rootOptions):this.getRootEoEvaluator().forForeignContract(t)}async getRemoteContractState(t){if(this.hasDreState(t))return this.getDreState(t);{let e=await this.fetchRemoteContractState(t);return e!=null?this.setDREState(t,e):null}}async fetchRemoteContractState(t){return we(this._warpFetchWrapper.fetch(`${this._evaluationOptions.remoteStateSyncSource}?id=${t}&events=false`))}getToSortKey(t){return this._parentContract?.rootSortKey?t?this._parentContract.rootSortKey.localeCompare(t)>0?this._parentContract.rootSortKey:t:this._parentContract.rootSortKey:t}async createExecutionContextFromTx(t,e){let r=e.owner.address,i=e.sortKey;return{...await this.createExecutionContext(t,i,!0),caller:r}}maybeResetRootContract(){this.isRoot()&&(this.logger.debug("Clearing call stack for the root contract"),this._callStack=new Jr(this.txId(),0),this._rootSortKey=null,this.warp.interactionsLoader.clearCache(),this._children=[],this._interactionState=new Ki(this.warp),this._dreStates=new Map)}async callContract(t,e,r,i,o=[],s=Er,c=!1,l=!1,g=!0){this.logger.info("Call contract input",t),this.maybeResetRootContract(),this._signature||this.logger.warn("Wallet not set.");let{arweave:w,stateEvaluator:v}=this.warp,E=await this.createExecutionContext(this._contractTxId,i,!0),d=this.warp.environment=="mainnet"?await this._arweaveWrapper.warpGwBlock():await w.blocks.getCurrent(),y;r?y=r:this._signature?y=await this._signature.getAddress():y="",this.logger.info("effectiveCaller",y),E={...E,caller:y};let k=await v.eval(E);this.logger.info("Current state",k.cachedValue.state);let N={input:t,caller:E.caller,interactionType:e};this.logger.debug("interaction",N);let q=await rs(w,g?this._signature?.signer:void 0,this._contractTxId,t,o,s.target,s.winstonQty,!0,this.warp.environment==="testnet"),Q=Bc(q,E.caller,d);if(this.logger.debug("Creating sortKey for",{blockId:Q.block.id,id:Q.id,height:Q.block.height}),Q.sortKey=await this._sorter.createSortKey(Q.block.id,Q.id,Q.block.height,!0),Q.strict=c,l){let X=this.warp.maybeLoadPlugin("vrf");X?Q.vrf=X.process().generateMockVrf(Q.sortKey):this.logger.warn('Cannot generate mock vrf for interaction - no "warp-contracts-plugin-vrf" attached!')}let z=await this.evalInteraction({interaction:N,interactionTx:Q},E,k.cachedValue);return z.type!=="ok"&&this.logger.fatal("Error while interacting with contract",{type:z.type,error:z.errorMessage}),z}async doApplyInputOnTx(t,e,r){this.maybeResetRootContract();let i,o=await this.createExecutionContextFromTx(this._contractTxId,e);!this.isRoot()&&this.interactionState().has(this.txId(),e.sortKey)?i=new Pt(e.sortKey,this.interactionState().get(this.txId(),e.sortKey)):(i=await this.warp.stateEvaluator.eval(o),this.interactionState().update(this.txId(),i.cachedValue,e.sortKey)),this.logger.debug("callContractForTx - evalStateResult",{result:i.cachedValue.state,txId:this._contractTxId});let c={interaction:{input:t,caller:this._parentContract.txId(),interactionType:r},interactionTx:e},l=await this.evalInteraction(c,o,i.cachedValue);return l.originalValidity=i.cachedValue.validity,l.originalErrorMessages=i.cachedValue.errorMessages,l}async evalInteraction(t,e,r){let i=this.getCallStack().addInteractionData(t),o=St.measure();await e.handler.initState(r.state);let s=await e.handler.handle(e,r,t);return i.update({cacheHit:!1,outputState:this._evaluationOptions.stackTrace.saveState?s.state:void 0,executionTime:o.elapsed(!0),valid:s.type==="ok",errorMessage:s.errorMessage,gasUsed:s.gasUsed}),s}parent(){return this._parentContract}callDepth(){return this._callDepth}evaluationOptions(){return this._evaluationOptions}lastReadStateStats(){return this._benchmarkStats}async stateHash(t){let e=lh(t),r=await _h.Crypto.subtle.digest("SHA-256",F.Buffer.from(e,"utf-8"));return F.Buffer.from(r).toString("hex")}async syncState(t,e){let{stateEvaluator:r}=this.warp,i=await this._warpFetchWrapper.fetch(`${t}?${new URLSearchParams({id:this._contractTxId,...e})}`).then(o=>o.ok?o.json():Promise.reject(o)).catch(o=>{throw o.body?.message&&this.logger.error(o.body.message),new Error(`Unable to retrieve state. ${o.status}: ${o.body?.message}`)});return await r.syncState(this._contractTxId,i.sortKey,i.state,i.validity),this}async evolve(t,e){return await this.writeInteraction({function:"evolve",value:t},e)}get rootSortKey(){return this._rootSortKey}getRootEoEvaluator(){return this.getRoot()._eoEvaluator}isRoot(){return this._parentContract==null}async getStorageValues(t){let e=await this.warp.stateEvaluator.getCache().getLast(this.txId());if(e==null)return new Pt(null,new Map);let r=this.warp.kvStorageFactory(this.txId()),i=new Map;try{await r.open();for(let o of t){let s=await r.getLessOrEqual(o,e.sortKey);i.set(o,s==null?null:s.cachedValue)}return new Pt(e.sortKey,i)}finally{await r.close()}}interactionState(){return this.getRoot()._interactionState}getRoot(){let t=this;for(;!t.isRoot();)t=t.parent();return t}async maybeSyncStateWithRemoteSource(t,e,r){let{stateEvaluator:i}=this.warp;return this.isStateHigherThanAndUpTo(t,r?.sortKey,e)?await i.syncState(this._contractTxId,t.sortKey,t.cachedValue.state,t.cachedValue.validity):r}isStateHigherThanAndUpTo(t,e,r){return t&&(!r||r>=t.sortKey)&&(!e||t.sortKey>e)}setDREState(t,e){let r=new Pt(e.sortKey,new Dt(e.state,{},e.errorMessages));return this.getRoot()._dreStates.set(t,r),r}getDreState(t){return this.getRoot()._dreStates.get(t)}hasDreState(t){return this.getRoot()._dreStates.has(t)}async discoverInternalWrites(t,e,r,i,o){let s=await this.callContract(t,"write",void 0,void 0,e,r,i,o,!1);if(i){if(s.type==="error")throw new Wt(s.error);if(s.type!=="ok")throw Error("Cannot create interaction: "+JSON.stringify(s.error||s.errorMessage))}let c=this.getCallStack(),l=this._innerWritesEvaluator.eval(c);this.logger.debug("Input",t),this.logger.debug("Callstack",c.print()),l.forEach(g=>{e.push(new qt(ot.INTERACT_WRITE,g))}),this.logger.debug("Tags with inner calls",e)}clearChildren(){for(let t of this._children)t.clearChildren();this._children=[]}};b();var Vi=class extends tn{async currentBalance(t){let e=await this.viewState({function:"balance",target:t});if(e.type!=="ok")throw Error(e.errorMessage);return e.result}async currentState(){return(await super.readState()).cachedValue.state}async transfer(t,e){return await this.writeInteraction({function:"transfer",...t},e)}};b();var us=class{constructor(t){this.arweave=t}async mineBlock(){this.validateEnv(),await this.arweave.api.get("mine")}async addFunds(t){let e=await this.arweave.wallets.getAddress(t);await this.arweave.api.get(`/mint/${e}/1000000000000000`)}async isArlocal(){return(await fetch(`${this.arweave.api.config.protocol}://${this.arweave.api.config.host}:${this.arweave.api.config.port}/info`).then(e=>e.ok?e.json():Promise.reject()).catch(e=>{throw new Error(`Unable to get network info: ${e.message}`)})).network.includes("arlocal")}async validateEnv(){if(!await this.isArlocal())throw new Error("Testing features are not available in a non testing environment")}};b();b();var ls=class{constructor(t,e){this.baseImplementation=t;this.sourceCode=e}async create(t,e,r,i){return Object.prototype.hasOwnProperty.call(this.sourceCode,t.txId)&&(t={...t,src:this.sourceCode[t.txId]}),await this.baseImplementation.create(t,e,r,i)}checkWhiteListContractSources(t,e){return this.baseImplementation.checkWhiteListContractSources(t,e)}};var Gi=class{constructor(t,e,r="custom"){this._arweave=t;this._stateCache=e;this._environment=r}_definitionLoader;_interactionsLoader;_executorFactory;_stateEvaluator;setDefinitionLoader(t){return this._definitionLoader=t,this}setInteractionsLoader(t){return this._interactionsLoader=t,this}setExecutorFactory(t){return this._executorFactory=t,this}setStateEvaluator(t){return this._stateEvaluator=t,this}overwriteSource(t){if(this._executorFactory==null)throw new Error("Set base ExecutorFactory first");return this._executorFactory=new ls(this._executorFactory,t),this.build()}useWarpGateway(t,e){this._interactionsLoader=new An(new ui(t.confirmationStatus,t.source));let r=new Pe({...e,dbLocation:`${e.dbLocation}/contracts`}),i=new Pe({...e,dbLocation:`${e.dbLocation}/source`});return this._definitionLoader=new Ri(this._arweave,r,i,this._environment),this}useArweaveGateway(){return this._definitionLoader=new zr(this._arweave,this._environment),this._interactionsLoader=new An(new Bi(this._arweave,this._environment)),this}build(){let t=new en(this._arweave,this._definitionLoader,this._interactionsLoader,this._executorFactory,this._stateEvaluator,this._environment);return this._definitionLoader.warp=t,this._interactionsLoader.warp=t,t}};b();var Gc=["^smartweave-extension-"],qc=["evm-signature-verification","subscription","ivm-handler-api","evaluation-progress","fetch-options","deploy","contract-blacklist","vm2","vrf"];var en=class{constructor(t,e,r,i,o,s="custom"){this.arweave=t;this.definitionLoader=e;this.interactionsLoader=r;this.executorFactory=i;this.stateEvaluator=o;this.environment=s;this.testing=new us(t),this.kvStorageFactory=c=>new Pe({inMemory:!1,dbLocation:`${fs}/kv/ldb/${c}`}),this.eventTarget=new EventTarget}_createContract;_gwUrl=jc;get createContract(){if(!this._createContract)if(this.plugins.has("deploy")){let t=this.loadPlugin("deploy");this._createContract=t.process(this)}else throw new Error("In order to use CreateContract methods please attach DeployPlugin.");return this._createContract}testing;kvStorageFactory;whoAmI;eventTarget;plugins=new Map;static builder(t,e,r){return new Gi(t,e,r)}contract(t,e,r){return new tn(t,this,e,r)}async deploy(t,e){return await this.createContract.deploy(t,e)}async deployFromSourceTx(t,e){return await this.createContract.deployFromSourceTx(t,e)}async deployBundled(t){return await this.createContract.deployBundled(t)}async register(t,e){return await this.createContract.register(t,e)}async createSource(t,e,r=!1){return await this.createContract.createSource(t,e,r)}async saveSource(t,e){return await this.createContract.saveSource(t,e)}pst(t){return new Vi(t,this)}useStateCache(t){return this.stateEvaluator.setCache(t),this}useContractCache(t,e){return this.definitionLoader.setSrcCache(e),this.definitionLoader.setCache(t),this}use(t){let e=t.type();if(!this.isPluginType(e))throw new Error(`Unknown plugin type ${e}.`);return this.plugins.set(e,t),this}hasPlugin(t){return this.plugins.has(t)}matchPlugins(t){return[...this.plugins.keys()].filter(r=>r.match(t))}loadPlugin(t){if(!this.hasPlugin(t))throw new Error(`Plugin ${t} not registered.`);return this.plugins.get(t)}maybeLoadPlugin(t){return this.hasPlugin(t)?this.plugins.get(t):null}async close(){return Promise.all([this.definitionLoader.getSrcCache().close(),this.definitionLoader.getCache().close(),this.stateEvaluator.getCache().close()]).then()}async generateWallet(){let t=await this.arweave.wallets.generate();return await this.testing.isArlocal()&&await this.testing.addFunds(t),{jwk:t,address:await this.arweave.wallets.jwkToAddress(t)}}isPluginType(t){return qc.includes(t)||Gc.some(e=>t.match(e))}useKVStorageFactory(t){return this.kvStorageFactory=t,this}useGwUrl(t){return this._gwUrl=t,this}gwUrl(){return this._gwUrl}};var gs={confirmationStatus:{notCorrupted:!0},source:"both"},jc="https://gw.warp.cc",fs="./cache/warp",On={inMemory:!1,dbLocation:fs},Hc=class{static forLocal(t=1984,e=hs.default.init({host:"localhost",port:t,protocol:"http"}),r={...On,inMemory:!0}){return this.customArweaveGw(e,r,"local")}static forTestnet(t=On,e=!1,r=hs.default.init({host:"arweave.net",port:443,protocol:"https"})){return e?this.customArweaveGw(r,t,"testnet"):this.customWarpGw(r,gs,t,"testnet")}static forMainnet(t=On,e=!1,r=hs.default.init({host:"arweave.net",port:443,protocol:"https"})){return e?this.customArweaveGw(r,t,"mainnet"):this.customWarpGw(r,gs,t,"mainnet")}static custom(t,e,r){let i=new Pe({...e,dbLocation:`${e.dbLocation}/state`}),o=new ii(t),s=new Ni(t,i,[new tr]);return en.builder(t,i,r).setExecutorFactory(o).setStateEvaluator(s)}static customArweaveGw(t,e=On,r){return this.custom(t,e,r).useArweaveGateway().build()}static customWarpGw(t,e=gs,r=On,i){return this.custom(t,r,i).useWarpGateway(e,r).build()}};b();function hy(n){let t=/(const|var) ret = makeMutClosure\(arg0, arg1, (\d+?), __wbg_adapter/;return n.match(t)[2]}b();var bh=Qt(Qo());function fe(n,t,e=void 0){let r=n.find(({name:i})=>i===t);return r?r.value:e}var qi=class{constructor(t){this.env=t}arweaveWrapper;arweaveTransactions;logger=ct.INST.create(qi.name);async load(t,e){let r=St.measure(),i=await this.fetchContractTx(t);this.logger.debug("Contract tx fetch time",r.elapsed());let o=i.owner.address,s=e||fe(i.tags,Ct.CONTRACT_SRC_TX_ID),c=fe(i.tags,ot.WARP_TESTNET)||null;if(c&&this.env!=="testnet")throw new Error('Trying to use testnet contract in a non-testnet env. Use the "forTestnet" factory method.');if(!c&&this.env==="testnet")throw new Error("Trying to use non-testnet contract in a testnet env.");let l=fe(i.tags,Ct.MIN_FEE),g=fe(i.tags,ot.MANIFEST)?JSON.parse(fe(i.tags,ot.MANIFEST)):null;this.logger.debug("Tags decoding",r.elapsed());let w=await this.evalInitialState(i);this.logger.debug("init state",w);let v=JSON.parse(w);this.logger.debug("Parsing src and init state",r.elapsed());let{src:E,srcBinary:d,srcWasmLang:y,contractType:k,metadata:N,srcTx:q}=await this.loadContractSource(s),Q={txId:t,srcTxId:s,src:E,srcBinary:d,srcWasmLang:y,initState:v,minFee:l,owner:o,contractType:k,metadata:N,manifest:g,contractTx:await this.convertToWarpCompatibleContractTx(i),srcTx:await this.convertToWarpCompatibleContractTx(q),testnet:c};return this.logger.info(`Contract definition loaded in: ${r.elapsed()}`),Q}async fetchContractTx(t){let e=await this.arweaveTransactions.transaction(t);return e??await this.arweaveTransactions.transactionUsingUploaderTag(t)}async convertToWarpCompatibleContractTx(t){return{tags:t.tags.map(({name:r,value:i})=>({name:F.Buffer.from(r).toString("base64url"),value:F.Buffer.from(i).toString("base64url")})),owner:t.owner.key,target:t.recipient,signature:t.signature,data:(await this.arweaveWrapper.txData(t.id)).toString("base64url")}}async loadContractSource(t){let e=St.measure(),r=await this.fetchContractTx(t),i=fe(r.tags,Ct.CONTENT_TYPE);if(!di.includes(i))throw new Error(`Contract source content type ${i} not supported`);let o=i==="application/javascript"?"js":"wasm",s=await this.contractSource(r,o),c,l,g;if(o=="wasm"){if(l=new Ze(s),c=fe(r.tags,ot.WASM_LANG),!c)throw new Error(`Wasm lang not set for wasm contract src ${r.id}`);g=JSON.parse(fe(r.tags,ot.WASM_META))}return this.logger.debug("Contract src tx load",e.elapsed()),e.reset(),{src:o=="js"?s:null,srcBinary:o=="wasm"?l.wasmBinary():null,srcWasmLang:c,contractType:o,metadata:g,srcTx:r}}async contractSource(t,e){if(fe(t.tags,ot.UPLOADER_TX_ID)!=null){let i=await this.arweaveWrapper.txDataString(t.id);if(e==="wasm")throw new Error("WASM contracts in legacy format are not supported using AR GW");return bh.default.utils.b64UrlToString(JSON.parse(i).data)}return e==="js"?await this.arweaveWrapper.txDataString(t.id):await this.arweaveWrapper.txData(t.id)}async evalInitialState(t){if(fe(t.tags,ot.INIT_STATE))return fe(t.tags,ot.INIT_STATE);if(fe(t.tags,ot.INIT_STATE_TX)){let e=fe(t.tags,ot.INIT_STATE_TX);return this.arweaveWrapper.txDataString(e)}else return this.arweaveWrapper.txDataString(t.id)}setCache(){throw new Error("Method not implemented.")}setSrcCache(){throw new Error("Method not implemented.")}getCache(){throw new Error("Method not implemented.")}getSrcCache(){throw new Error("Method not implemented.")}type(){return"arweave"}set warp(t){this.arweaveWrapper=new Zt(t),this.arweaveTransactions=new We(t)}};b();var Sh=100,gy=100,Eh=1057409,Rn=class{constructor(t,e){this.arweave=t;this.environment=e;this.sorter=new Ye(t)}logger=ct.INST.create(Rn.name);arweaveFetcher;arweaveWrapper;_warp;sorter;tagsParser=new jt;async load(t,e,r,i){this.logger.debug("Loading interactions for",{contractId:t,fromSortKey:e,toSortKey:r});let o=this.sorter.extractBlockHeight(e)||0,s=this.sorter.extractBlockHeight(r)||await this.currentBlockHeight(),c={tags:[{name:Ct.APP_NAME,values:["SmartWeaveAction"]},{name:Ct.CONTRACT_TX_ID,values:[t]},{name:ot.SEQUENCER,values:["RedStone"]}],blockFilter:{min:o,max:s+gy},first:Sh},l=St.measure(),g=await this.arweaveFetcher.transactions(c);i.internalWrites&&(g=await this.appendInternalWriteInteractions(t,o,s,g)),l.stop(),this.logger.debug("All loaded interactions:",{from:e,to:r,loaded:g.length,time:l.elapsed()}),g.forEach(d=>{d.node.sortKey=d.node.sortKey??d.node?.tags?.find(y=>y.name===ot.SEQUENCER_SORT_KEY)?.value});let w=await this.sorter.sort(g),v=this.environment==="local"||this.environment==="testnet",E=this._warp.maybeLoadPlugin("vrf");return w.filter(d=>this.isNewerThenSortKeyBlockHeight(d)).filter(d=>this.isSortKeyInBounds(e,r,d)).map(d=>this.attachSequencerDataToInteraction(d)).map(d=>this.maybeAddMockVrf(v,d,E)).map((d,y,k)=>this.verifySortKeyIntegrity(d,y,k)).map(({node:d})=>d)}verifySortKeyIntegrity(t,e,r){if(e!==0){let i=r[e-1],o=r[e];if(this.logger.debug(`prev: ${i.node.id} | current: ${o.node.id}`),o.node.block.height<=Eh||o.node.lastSortKey?.split(",")[1]===Do)return t;i.node.source==="redstone-sequencer"&&i.node.sortKey!==o.node.lastSortKey&&this.logger.warn(`Interaction loading error: interaction ${o.node.id} lastSortKey is not pointing on prev interaction ${i.node.id}`)}return t}isSortKeyInBounds(t,e,r){return t&&e?r.node.sortKey.localeCompare(t)>0&&r.node.sortKey.localeCompare(e)<=0:t&&!e?r.node.sortKey.localeCompare(t)>0:!t&&e?r.node.sortKey.localeCompare(e)<=0:!0}attachSequencerDataToInteraction(t){let e=v=>t.node.tags.find(E=>E.name===v)?.value,r=e(ot.SEQUENCER_TX_ID),i=e(ot.SEQUENCER_OWNER),o=e(ot.SEQUENCER_BLOCK_ID),s=e(ot.SEQUENCER_BLOCK_HEIGHT),c=e(ot.SEQUENCER_PREV_SORT_KEY)||e(ot.SEQUENCER_LAST_SORT_KEY),l=e(ot.SEQUENCER_SORT_KEY),g=e(ot.SEQUENCER_BLOCK_TIMESTAMP),w=ci(s);if(!i||!o||!s||!c&&w>Eh||!r||!l)throw Error(`Interaction ${t.node.id} is not sequenced by sequencer aborting. Only Sequenced transactions are supported by loader ${Rn.name}`);return{...t,node:{...t.node,owner:{address:i,key:null},block:{...t.node.block,height:ci(s),id:o,timestamp:g?ci(g):t.node.block.timestamp},sortKey:l,lastSortKey:c,id:r,source:"redstone-sequencer"}}}async appendInternalWriteInteractions(t,e,r,i){let o={tags:[{name:ot.INTERACT_WRITE,values:[t]}],blockFilter:{min:e,max:r},first:Sh},s=await this.arweaveFetcher.transactions(o);return this.logger.debug("Inner writes interactions length:",s.length),i=i.concat(s),i}maybeAddMockVrf(t,e,r){return t&&this.tagsParser.hasVrfTag(e.node)&&(r?e.node.vrf=r.process().generateMockVrf(e.node.sortKey):this.logger.warn('Cannot generate mock vrf for interaction - no "warp-contracts-plugin-vrf" attached!')),e}isNewerThenSortKeyBlockHeight(t){if(t.node.sortKey){let e=t.node.sortKey.split(",")[0],r=Number.parseInt(e);return Number(t.node.block.height)-r>=0}return!0}async currentBlockHeight(){return(await this.arweaveWrapper.info()).height}type(){return"arweave"}clearCache(){}set warp(t){this.arweaveWrapper=new Zt(t),this.arweaveFetcher=new We(t),this._warp=t}};return Rh(dy);})(); +/*! Bundled license information: + +ieee754/index.js: + (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) + +buffer/index.js: + (*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + *) + +queue-microtask/index.js: + (*! queue-microtask. MIT License. Feross Aboukhadijeh *) + +run-parallel-limit/index.js: + (*! run-parallel-limit. MIT License. Feross Aboukhadijeh *) + +warp-arbundles/build/web/esm/bundle.js: + (*! Bundled license information: + + ieee754/index.js: + (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) + + buffer/index.js: + (*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + *) + *) +*/ diff --git a/lib/cjs/cache/BasicSortKeyCache.js b/lib/cjs/cache/BasicSortKeyCache.js new file mode 100644 index 00000000..d552747a --- /dev/null +++ b/lib/cjs/cache/BasicSortKeyCache.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=BasicSortKeyCache.js.map \ No newline at end of file diff --git a/lib/cjs/cache/BasicSortKeyCache.js.map b/lib/cjs/cache/BasicSortKeyCache.js.map new file mode 100644 index 00000000..bfb3732e --- /dev/null +++ b/lib/cjs/cache/BasicSortKeyCache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BasicSortKeyCache.js","sourceRoot":"","sources":["../../../src/cache/BasicSortKeyCache.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/cache/SortKeyCache.js b/lib/cjs/cache/SortKeyCache.js new file mode 100644 index 00000000..b28cca8c --- /dev/null +++ b/lib/cjs/cache/SortKeyCache.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SortKeyCacheResult = exports.CacheKey = void 0; +class CacheKey { + constructor(key, sortKey) { + this.key = key; + this.sortKey = sortKey; + } +} +exports.CacheKey = CacheKey; +class SortKeyCacheResult { + constructor(sortKey, cachedValue) { + this.sortKey = sortKey; + this.cachedValue = cachedValue; + } +} +exports.SortKeyCacheResult = SortKeyCacheResult; +//# sourceMappingURL=SortKeyCache.js.map \ No newline at end of file diff --git a/lib/cjs/cache/SortKeyCache.js.map b/lib/cjs/cache/SortKeyCache.js.map new file mode 100644 index 00000000..4c8b9c5f --- /dev/null +++ b/lib/cjs/cache/SortKeyCache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SortKeyCache.js","sourceRoot":"","sources":["../../../src/cache/SortKeyCache.ts"],"names":[],"mappings":";;;AAyCA,MAAa,QAAQ;IACnB,YAAqB,GAAW,EAAW,OAAe;QAArC,QAAG,GAAH,GAAG,CAAQ;QAAW,YAAO,GAAP,OAAO,CAAQ;IAAG,CAAC;CAC/D;AAFD,4BAEC;AAED,MAAa,kBAAkB;IAC7B,YAAqB,OAAe,EAAW,WAAc;QAAxC,YAAO,GAAP,OAAO,CAAQ;QAAW,gBAAW,GAAX,WAAW,CAAG;IAAG,CAAC;CAClE;AAFD,gDAEC"} \ No newline at end of file diff --git a/lib/cjs/cache/SortKeyCacheRangeOptions.js b/lib/cjs/cache/SortKeyCacheRangeOptions.js new file mode 100644 index 00000000..031bfdc0 --- /dev/null +++ b/lib/cjs/cache/SortKeyCacheRangeOptions.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SortKeyCacheRangeOptions.js.map \ No newline at end of file diff --git a/lib/cjs/cache/SortKeyCacheRangeOptions.js.map b/lib/cjs/cache/SortKeyCacheRangeOptions.js.map new file mode 100644 index 00000000..59cb9dd5 --- /dev/null +++ b/lib/cjs/cache/SortKeyCacheRangeOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SortKeyCacheRangeOptions.js","sourceRoot":"","sources":["../../../src/cache/SortKeyCacheRangeOptions.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/cache/WarpCache.js b/lib/cjs/cache/WarpCache.js new file mode 100644 index 00000000..5ca70c4e --- /dev/null +++ b/lib/cjs/cache/WarpCache.js @@ -0,0 +1,12 @@ +"use strict"; +/** + * Base interface for Warp Cache implementors. + * Useful for simple, non block-height dependant caches + * - like contract's source code cache. + * See {@link MemCache} for example implementation. + * + * @typeParam K - type of the cache key. + * @typeParam V - type of the cache value. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=WarpCache.js.map \ No newline at end of file diff --git a/lib/cjs/cache/WarpCache.js.map b/lib/cjs/cache/WarpCache.js.map new file mode 100644 index 00000000..1f49aed8 --- /dev/null +++ b/lib/cjs/cache/WarpCache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpCache.js","sourceRoot":"","sources":["../../../src/cache/WarpCache.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG"} \ No newline at end of file diff --git a/lib/cjs/cache/impl/LevelDbCache.js b/lib/cjs/cache/impl/LevelDbCache.js new file mode 100644 index 00000000..7cd38255 --- /dev/null +++ b/lib/cjs/cache/impl/LevelDbCache.js @@ -0,0 +1,316 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LevelDbCache = void 0; +const SortKeyCache_1 = require("../SortKeyCache"); +const level_1 = require("level"); +const memory_level_1 = require("memory-level"); +const LoggerFactory_1 = require("../../logging/LoggerFactory"); +/** + * The LevelDB is a lexicographically sorted key-value database - so it's ideal for this use case + * - as it simplifies cache look-ups (e.g. lastly stored value or value "lower-or-equal" than given sortKey). + * The cache for contracts are implemented as sub-levels - https://www.npmjs.com/package/level#sublevel--dbsublevelname-options. + * + * The default location for the node.js cache is ./cache/warp. + * The default name for the browser IndexedDB cache is warp-cache + * + * In order to reduce the cache size, the oldest entries are automatically pruned. + */ +class ClientValueWrapper { + constructor(value, tomb = false) { + this.value = value; + this.tomb = tomb; + } +} +class LevelDbCache { + // Lazy initialization upon first access + get db() { + if (!this._db) { + if (this.cacheOptions.inMemory) { + this._db = new memory_level_1.MemoryLevel(this.subLevelOptions); + } + else { + if (!this.cacheOptions.dbLocation) { + throw new Error('LevelDb cache configuration error - no db location specified'); + } + const dbLocation = this.cacheOptions.dbLocation; + this.logger.info(`Using location ${dbLocation}`); + this._db = new level_1.Level(dbLocation, this.subLevelOptions); + } + } + return this._db; + } + constructor(cacheOptions) { + this.cacheOptions = cacheOptions; + this.ongoingTransactionMark = '$$warp-internal-transaction$$'; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('LevelDbCache'); + this.subLevelSeparator = cacheOptions.subLevelSeparator || '!'; + this.subLevelOptions = { + valueEncoding: 'json', + separator: this.subLevelSeparator + }; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async get(cacheKey, returnDeepCopy) { + this.validateKey(cacheKey.key); + const contractCache = this.db.sublevel(cacheKey.key, this.subLevelOptions); + // manually opening to fix https://github.com/Level/level/issues/221 + await contractCache.open(); + const subLevelValue = await this.getValueFromLevel(cacheKey.sortKey, contractCache); + if (subLevelValue) { + return new SortKeyCache_1.SortKeyCacheResult(cacheKey.sortKey, subLevelValue); + } + return null; + } + async getLast(key) { + const contractCache = this.db.sublevel(key, this.subLevelOptions); + // manually opening to fix https://github.com/Level/level/issues/221 + await contractCache.open(); + const keys = await contractCache.keys({ reverse: true, limit: 1 }).all(); + if (keys.length) { + const subLevelValue = await this.getValueFromLevel(keys[0], contractCache); + if (subLevelValue) { + return new SortKeyCache_1.SortKeyCacheResult(keys[0], subLevelValue); + } + } + return null; + } + async getLessOrEqual(key, sortKey) { + const contractCache = this.db.sublevel(key, this.subLevelOptions); + // manually opening to fix https://github.com/Level/level/issues/221 + await contractCache.open(); + const keys = await contractCache.keys({ reverse: true, lte: sortKey, limit: 1 }).all(); + if (keys.length) { + const subLevelValue = await this.getValueFromLevel(keys[0], contractCache); + if (subLevelValue != null) { + return new SortKeyCache_1.SortKeyCacheResult(keys[0], subLevelValue); + } + } + return null; + } + async getValueFromLevel(key, level) { + try { + const wrappedValue = await level.get(key); + if (wrappedValue && wrappedValue.tomb === undefined && wrappedValue.value === undefined) { + return wrappedValue; + } + if (wrappedValue && wrappedValue.tomb === false && wrappedValue.value != null) { + return wrappedValue.value; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + catch (e) { + if (e.code != 'LEVEL_NOT_FOUND') { + throw e; + } + } + return null; + } + async put(stateCacheKey, value) { + await this.setClientValue(stateCacheKey, new ClientValueWrapper(value)); + } + /** + * Delete operation under the hood is a write operation with setting tomb flag to true. + * The idea behind is based on Cassandra Tombstone + * https://www.instaclustr.com/support/documentation/cassandra/using-cassandra/managing-tombstones-in-cassandra/ + * There is a couple of benefits to this approach: + * This allows to use kv storage range operations with ease. + * The value will not be accessible only to the next interactions. Interactions reading state for lower sortKey will be able to access it. + * Revert operation for rollback is much easier to implement + */ + async del(cacheKey) { + await this.setClientValue(cacheKey, new ClientValueWrapper(null, true)); + } + async setClientValue(stateCacheKey, valueWrapper) { + this.validateKey(stateCacheKey.key); + const contractCache = this.db.sublevel(stateCacheKey.key, this.subLevelOptions); + // manually opening to fix https://github.com/Level/level/issues/221 + await contractCache.open(); + await contractCache.put(stateCacheKey.sortKey, valueWrapper); + if (this._rollbackBatch) { + this._rollbackBatch.del(stateCacheKey.sortKey, { sublevel: contractCache }); + } + } + async delete(key) { + const contractCache = this.db.sublevel(key, this.subLevelOptions); + await contractCache.open(); + await contractCache.clear(); + } + async batch(opStack) { + for (const op of opStack) { + if (op.type === 'put') { + await this.put(op.key, op.value); + } + else if (op.type === 'del') { + await this.delete(op.key); + } + } + } + async open() { + await this.db.open(); + } + async close() { + if (this._db) { + await this._db.close(); + } + } + async begin() { + await this.initRollbackBatch(); + } + async rollback() { + if (this._rollbackBatch) { + this._rollbackBatch.del(this.ongoingTransactionMark); + await this._rollbackBatch.write(); + await this._rollbackBatch.close(); + } + this._rollbackBatch = null; + } + async initRollbackBatch() { + if (this._rollbackBatch == null) { + await this.checkPreviousTransactionFinished(); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + await this.db.put(this.ongoingTransactionMark, 'ongoing'); + this._rollbackBatch = this.db.batch(); + } + return this._rollbackBatch; + } + async checkPreviousTransactionFinished() { + let transactionMarkValue; + try { + transactionMarkValue = await this.db.get(this.ongoingTransactionMark); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + catch (e) { + if (e.code != 'LEVEL_NOT_FOUND') { + throw e; + } + } + if (transactionMarkValue == 'ongoing') { + throw new Error(`Database seems to be in inconsistent state. The previous transaction has not finished.`); + } + } + async commit() { + if (this._rollbackBatch) { + await this._rollbackBatch.clear(); + await this.db.del(this.ongoingTransactionMark); + await this._rollbackBatch.close(); + } + this._rollbackBatch = null; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async dump() { + const result = await this.db.iterator().all(); + return result; + } + // TODO: this implementation is sub-optimal + // the lastSortKey should be probably memoized during "put" + async getLastSortKey() { + let lastSortKey = ''; + await this.db.open(); + const keys = await this.db.keys().all(); + for (const joinedKey of keys) { + // default joined key format used by sub-levels: + // + const sortKey = joinedKey.split(this.subLevelSeparator)[1]; + if (sortKey.localeCompare(lastSortKey) > 0) { + lastSortKey = sortKey; + } + } + return lastSortKey == '' ? null : lastSortKey; + } + async keys(sortKey, options) { + return Array.from((await this.kvMap(sortKey, options)).keys()); + } + validateKey(key) { + if (key.includes(this.ongoingTransactionMark)) { + throw new Error(`Validation error: Key ${key} for internal use only`); + } + if (key.includes(this.subLevelSeparator)) { + throw new Error(`Validation error: key ${key} contains db separator ${this.subLevelSeparator}`); + } + } + extractOriginalKey(joinedKey) { + return joinedKey.split(this.subLevelSeparator)[1]; + } + extractSortKey(joinedKey) { + return joinedKey.split(this.subLevelSeparator)[2]; + } + async kvMap(sortKey, options) { + const result = new Map(); + const allKeys = (await this.db.keys(this.levelRangeOptions(options)).all()) + .filter((k) => k != this.ongoingTransactionMark) + .filter((k) => !sortKey || this.extractSortKey(k).localeCompare(sortKey) <= 0) + .map((k) => this.extractOriginalKey(k)); + for (const k of allKeys) { + const lastValue = await this.getLessOrEqual(k, sortKey); + if (lastValue) { + result.set(k, lastValue.cachedValue); + } + } + if (options === null || options === void 0 ? void 0 : options.limit) { + const limitedResult = new Map(); + for (const item of Array.from(result.entries()).slice(0, options.limit)) { + limitedResult.set(item[0], item[1]); + } + return limitedResult; + } + return result; + } + levelRangeOptions(options) { + const rangeOptions = { + reverse: options === null || options === void 0 ? void 0 : options.reverse + }; + if (options === null || options === void 0 ? void 0 : options.gte) { + rangeOptions.gte = this.subLevelSeparator + options.gte; + } + if (options === null || options === void 0 ? void 0 : options.lt) { + rangeOptions.lt = this.subLevelSeparator + options.lt; + } + return rangeOptions; + } + storage() { + return this.db; + } + async getNumEntries() { + const keys = await this.db.keys().all(); + return keys.length; + } + /** + Let's assume that given contract cache contains these sortKeys: [a, b, c, d, e, f] + Let's assume entriesStored = 2 + After pruning, the cache should be left with these keys: [e,f]. + + const entries = await contractCache.keys({ reverse: true, limit: entriesStored }).all(); + This would return in this case entries [f, e] (notice the "reverse: true"). + + await contractCache.clear({ lt: entries[entries.length - 1] }); + This effectively means: await contractCache.clear({ lt: e }); + -> hence the entries [a,b,c,d] are removed and left are the [e,f] + */ + async prune(entriesStored = 5) { + if (!entriesStored || entriesStored <= 0) { + entriesStored = 1; + } + const contracts = await this.allKeys(); + for (let i = 0; i < contracts.length; i++) { + const contractCache = this.db.sublevel(contracts[i], this.subLevelOptions); + // manually opening to fix https://github.com/Level/level/issues/221 + await contractCache.open(); + // Get keys that will be left, just to get the last one of them + const entries = await contractCache.keys({ reverse: true, limit: entriesStored }).all(); + if (!entries || entries.length < entriesStored) { + continue; + } + await contractCache.clear({ lt: entries[entries.length - 1] }); + await contractCache.close(); + } + return null; + } + async allKeys() { + return (await this.db.keys().all()) + .filter((k) => k != this.ongoingTransactionMark) + .map((k) => this.extractOriginalKey(k)); + } +} +exports.LevelDbCache = LevelDbCache; +//# sourceMappingURL=LevelDbCache.js.map \ No newline at end of file diff --git a/lib/cjs/cache/impl/LevelDbCache.js.map b/lib/cjs/cache/impl/LevelDbCache.js.map new file mode 100644 index 00000000..aed01dd5 --- /dev/null +++ b/lib/cjs/cache/impl/LevelDbCache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"LevelDbCache.js","sourceRoot":"","sources":["../../../../src/cache/impl/LevelDbCache.ts"],"names":[],"mappings":";;;AAAA,kDAAwF;AACxF,iCAA8B;AAC9B,+CAA2C;AAE3C,+DAA4D;AAM5D;;;;;;;;;GASG;AAEH,MAAM,kBAAkB;IACtB,YAAqB,KAAQ,EAAW,OAAgB,KAAK;QAAxC,UAAK,GAAL,KAAK,CAAG;QAAW,SAAI,GAAJ,IAAI,CAAiB;IAAG,CAAC;CAClE;AAED,MAAa,YAAY;IAyBvB,wCA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AC,IAAI,IAAI,CAAC,sBAAsB,CAAC;aAC/C,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5C,CAAC;CACF;AAzWD,oCAyWC"} \ No newline at end of file diff --git a/lib/cjs/cache/impl/MemCache.js b/lib/cjs/cache/impl/MemCache.js new file mode 100644 index 00000000..4c964a7d --- /dev/null +++ b/lib/cjs/cache/impl/MemCache.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MemCache = void 0; +/** + * A simple, in-memory cache, with keys being transaction ids (e.g. contract transaction id). + */ +class MemCache { + constructor() { + this.storage = {}; + } + clearAll() { + Object.keys(this.storage).forEach((key) => { + delete this.storage[key]; + }); + } + contains(key) { + return Object.prototype.hasOwnProperty.call(this.storage, key); + } + get(key) { + return this.storage[key]; + } + put(key, value) { + this.storage[key] = value; + } + remove(key) { + delete this.storage[key]; + } +} +exports.MemCache = MemCache; +//# sourceMappingURL=MemCache.js.map \ No newline at end of file diff --git a/lib/cjs/cache/impl/MemCache.js.map b/lib/cjs/cache/impl/MemCache.js.map new file mode 100644 index 00000000..6f68baa6 --- /dev/null +++ b/lib/cjs/cache/impl/MemCache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MemCache.js","sourceRoot":"","sources":["../../../../src/cache/impl/MemCache.ts"],"names":[],"mappings":";;;AAEA;;GAEG;AACH,MAAa,QAAQ;IAArB;QACmB,YAAO,GAAyB,EAAE,CAAC;IAuBtD,CAAC;IArBC,QAAQ;QACN,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;YACxC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC3B,CAAC,CAAC,CAAC;IACL,CAAC;IAED,QAAQ,CAAC,GAAW;QAClB,OAAO,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IACjE,CAAC;IAED,GAAG,CAAC,GAAW;QACb,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;IAED,GAAG,CAAC,GAAW,EAAE,KAAQ;QACvB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IAC5B,CAAC;IAED,MAAM,CAAC,GAAW;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;CACF;AAxBD,4BAwBC"} \ No newline at end of file diff --git a/lib/cjs/common/SimpleLRUCache.js b/lib/cjs/common/SimpleLRUCache.js new file mode 100644 index 00000000..e3ed6ffe --- /dev/null +++ b/lib/cjs/common/SimpleLRUCache.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SimpleLRUCache = void 0; +class SimpleLRUCache { + constructor(capacity) { + this.cache = new Map(); + this.capacity = capacity || 10; + } + has(key) { + return this.cache.has(key); + } + size() { + return this.cache.size; + } + get(key) { + if (!this.cache.has(key)) + return null; + const val = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, val); + return val; + } + set(key, value) { + this.cache.delete(key); + if (this.cache.size === this.capacity) { + this.cache.delete(this.cache.keys().next().value); + this.cache.set(key, value); + } + else { + this.cache.set(key, value); + } + } + keys() { + return Array.from(this.cache.keys()); + } +} +exports.SimpleLRUCache = SimpleLRUCache; +//# sourceMappingURL=SimpleLRUCache.js.map \ No newline at end of file diff --git a/lib/cjs/common/SimpleLRUCache.js.map b/lib/cjs/common/SimpleLRUCache.js.map new file mode 100644 index 00000000..aa73b15f --- /dev/null +++ b/lib/cjs/common/SimpleLRUCache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SimpleLRUCache.js","sourceRoot":"","sources":["../../../src/common/SimpleLRUCache.ts"],"names":[],"mappings":";;;AAAA,MAAa,cAA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C,CAAC;IACvC,CAAC;CACF;AAzCD,wCAyCC"} \ No newline at end of file diff --git a/lib/cjs/contract/Contract.js b/lib/cjs/contract/Contract.js new file mode 100644 index 00000000..7b558da6 --- /dev/null +++ b/lib/cjs/contract/Contract.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Contract.js.map \ No newline at end of file diff --git a/lib/cjs/contract/Contract.js.map b/lib/cjs/contract/Contract.js.map new file mode 100644 index 00000000..e320f219 --- /dev/null +++ b/lib/cjs/contract/Contract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Contract.js","sourceRoot":"","sources":["../../../src/contract/Contract.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/contract/EvaluationOptionsEvaluator.js b/lib/cjs/contract/EvaluationOptionsEvaluator.js new file mode 100644 index 00000000..51c81609 --- /dev/null +++ b/lib/cjs/contract/EvaluationOptionsEvaluator.js @@ -0,0 +1,191 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EvaluationOptionsEvaluator = void 0; +const utils_1 = require("../utils/utils"); +class EvaluationOptionsEvaluator { + /** + * @param userSetOptions evaluation options set via {@link Contract.setEvaluationOptions} + * @param manifestOptions evaluation options from the root contract's manifest (i.e. the contract that + * the user is trying to read - e.g. via warp.contract().readState(); + */ + constructor(userSetOptions, manifestOptions) { + this.saferEvaluationOptions = { + // CRITICAL! + internalWrites: (foreignOptions) => { + if (foreignOptions['internalWrites'] === undefined || + this.rootOptions['internalWrites'] == foreignOptions['internalWrites']) { + return this.rootOptions['internalWrites']; + } + if (this.rootOptions['internalWrites'] && !foreignOptions['internalWrites']) { + return foreignOptions['internalWrites']; + } + if (!this.rootOptions['internalWrites'] && foreignOptions['internalWrites']) { + return foreignOptions['internalWrites']; + } + throw new Error('Could not determine "internalWrites" value '); + }, + throwOnInternalWriteError: (foreignOptions) => { + if (foreignOptions['throwOnInternalWriteError'] === undefined) { + return this.rootOptions['throwOnInternalWriteError']; + } + // or should the root take precedence if foreignOptions["throwOnInternalWriteError"] = false + // and root["throwOnInternalWriteError"] = true + return foreignOptions['throwOnInternalWriteError']; + }, + // CRITICAL! + unsafeClient: (foreignOptions) => { + // options from less secure to most secure + // allow, skip, throw + if (foreignOptions['unsafeClient'] === undefined || + this.rootOptions['unsafeClient'] == foreignOptions['unsafeClient']) { + return this.rootOptions['unsafeClient']; + } + if (this.rootOptions['unsafeClient'] === 'throw' || this.rootOptions['unsafeClient'] === 'skip') { + return this.rootOptions['unsafeClient']; + } + if (this.rootOptions['unsafeClient'] === 'allow') { + if (foreignOptions['unsafeClient'] === 'throw') { + return 'skip'; // we don't the foreing contract to stop the evaluation of the root contract + } + else { + return foreignOptions['unsafeClient']; + } + } + throw new Error('Could not determine "unsafeClient" value'); + }, + ignoreExceptions: (foreignOptions) => { + if (foreignOptions['ignoreExceptions'] === undefined || + this.rootOptions['ignoreExceptions'] == foreignOptions['ignoreExceptions']) { + return this.rootOptions['ignoreExceptions']; + } + // true in root vs false in foreign = root wins - not sure in this case. + // if we decide to set a value from foreign contract in this case + // - it could break the execution of the original contract + if (this.rootOptions['ignoreExceptions'] && !foreignOptions['ignoreExceptions']) { + return this.rootOptions['ignoreExceptions']; + } + // false in root vs true in foreign = root wins + if (!this.rootOptions['ignoreExceptions'] && foreignOptions['ignoreExceptions']) { + return this.rootOptions['ignoreExceptions']; + } + throw new Error('Could not determine "ignoreExceptions" value'); + }, + waitForConfirmation: () => this.rootOptions['waitForConfirmation'], + updateCacheForEachInteraction: () => this.rootOptions['updateCacheForEachInteraction'], + maxCallDepth: () => this.rootOptions['maxCallDepth'], + maxInteractionEvaluationTimeSeconds: () => this.rootOptions['maxInteractionEvaluationTimeSeconds'], + stackTrace: () => this.rootOptions['stackTrace'], + sourceType: () => this.rootOptions['sourceType'], + sequencerUrl: () => this.rootOptions['sequencerUrl'], + gasLimit: () => this.rootOptions['gasLimit'], + allowBigInt: () => this.rootOptions['allowBigInt'], + walletBalanceUrl: () => this.rootOptions['walletBalanceUrl'], + mineArLocalBlocks: () => this.rootOptions['mineArLocalBlocks'], + cacheEveryNInteractions: () => this.rootOptions['cacheEveryNInteractions'], + remoteStateSyncEnabled: () => this.rootOptions['remoteStateSyncEnabled'], + remoteStateSyncSource: () => this.rootOptions['remoteStateSyncSource'], + useKVStorage: (foreignOptions) => foreignOptions['useKVStorage'], + useConstructor: (foreignOptions) => foreignOptions['useConstructor'], + whitelistSources: () => this.rootOptions['whitelistSources'] + }; + this.notConflictingEvaluationOptions = [ + 'useKVStorage', + 'sourceType', + 'useConstructor' + ]; + if (manifestOptions) { + const errors = []; + for (const k in manifestOptions) { + // eslint-disable-next-line no-prototype-builtins + if (!userSetOptions.hasOwnProperty(k)) { + throw new Error("Unknown option set in contract's manifest. You probably need to update the Warp SDK version."); + } + const optionKey = k; + const manifestValue = manifestOptions[k]; + const userValue = userSetOptions[k]; + if (this.notConflictingEvaluationOptions.includes(optionKey)) { + continue; + } + // https://github.com/warp-contracts/warp/issues/425#issuecomment-1591212639 + if (optionKey === 'internalWrites') { + if (userValue === false && manifestValue === true) { + throw new Error('Cannot proceed with contract evaluation. User is blocking internal writes, while contract requires them.'); + } + } + else if (optionKey === 'unsafeClient') { + // 'allow' | 'skip' | 'throw' + if ((userValue === 'throw' && manifestValue !== 'throw') || + (userValue === 'skip' && manifestValue === 'allow')) { + throw new Error(`Cannot proceed with contract evaluation. User requires to ${userValue} on any unsafeClient usage, while contract uses ${manifestValue} option.`); + } + } + else { + if (userSetOptions[k] !== manifestOptions[k]) { + errors.push(`Option {${k}} differs. EvaluationOptions: [${userSetOptions[k]}], manifest: [${manifestOptions[k]}]. Use contract.setEvaluationOptions({${k}: ${manifestOptions[k]}}) to evaluate contract state.`); + } + } + } + if (errors.length) { + throw new Error(errors.join('\n')); + } + } + this.rootOptions = Object.freeze(Object.assign({}, userSetOptions, manifestOptions || {})); + } + /** + * The idea here is that evaluation of the foreign contract should not be processed with "less secure" + * evaluation options than those set for the main/root contract (i.e. the one that is being read by the User). + * + * Currently, one exception to this rule are the internal writes. + * Consider the examples below: + * + * Example 1: + * 1. The root contract blocks internal writes + * 2. The foreign contract allows for internal writes + * => the internal writes should be allowed during evaluation of the foreign contract + * + * Example 2: + * 1. The root contract has the 'unsafeClient' set to 'skip' + * 2. The foreign contract has the 'unsafeClient' to 'allow' + * => the 'unsafeClient' should be set to 'skip' for foreign contract + * + * Example 3: + * 1. The root contract has the 'vm2' set to 'true' + * 2. The foreign contract has the 'vm2' set to 'false' + * => the 'vm2' for the foreign contract should be set to 'true' + * + * Example 4: + * 1. The root contract has the 'maxCallDepth' set to 3 + * 2. The foreign contract has the 'maxCallDepth' set to 5 + * => the 'maxCallDepth' for the foreign contract should be set to '3' + * NOTE: call depth is always verified from the perspective of the root contract! + * + * Example 5: + * 1. The root contract has the 'maxInteractionEvaluationTimeSeconds' set to 10 + * 2. The foreign contract has the 'maxInteractionEvaluationTimeSeconds' set to 60 + * => the 'maxInteractionEvaluationTimeSeconds' for the foreign contract should be set to '10' + * + * On the other hand - if the root contract has less secure options than the foreign contract - + * the more secure options of the foreign contract should be respected. + * Example: + * 1. Contract "A" with 'unsafeClient' = 'allow' (and unsafeClient used in its source) is performing + * write operation on Contract "B" that has 'unsafeClient' set to 'skip'. + * i.e. Contract A calls SmartWeave.contracts.write on Contract B. + * + * In this case the more secure setting of the Contract B should be reflected - and write itself + * should be blocked (i.e. it should not be even created during the `A.writeInteraction` - when a dry-run + * is being performed, and we're evaluating a list of internal writes for a newly created interaction). + * + * @param foreignContractManifest the manifest of the foreign contract that we want read/write to + */ + forForeignContract(foreignContractOptions) { + const options = (0, utils_1.deepCopy)(this.rootOptions); //or default evaluation options? + if (foreignContractOptions) { + for (const k in foreignContractOptions) { + options[k] = this.saferEvaluationOptions[k](foreignContractOptions); + } + } + return Object.freeze(options); + } +} +exports.EvaluationOptionsEvaluator = EvaluationOptionsEvaluator; +//# sourceMappingURL=EvaluationOptionsEvaluator.js.map \ No newline at end of file diff --git a/lib/cjs/contract/EvaluationOptionsEvaluator.js.map b/lib/cjs/contract/EvaluationOptionsEvaluator.js.map new file mode 100644 index 00000000..7daefff9 --- /dev/null +++ b/lib/cjs/contract/EvaluationOptionsEvaluator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EvaluationOptionsEvaluator.js","sourceRoot":"","sources":["../../../src/contract/EvaluationOptionsEvaluator.ts"],"names":[],"mappings":";;;AACA,0CAA0C;AAM1C,MAAa,0BAA0B;IA+GrC;;;;OAIG;IACH,YAAY,cAAiC,EAAE,eAA2C;QAvGzE,2BAAsB,GAA2B;YAChE,YAAY;YACZ,cAAc,EAAE,CAAC,cAAc,EAAE,EAAE;gBACjC,IACE,cAAc,CAAC,gBAAgB,CAAC,KAAK,SAAS;oBAC9C,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,IAAI,cAAc,CAAC,gBAAgB,CAAC,EACtE;oBACA,OAAO,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;iBAC3C;gBAED,IAAI,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,IAAI,CAAC,cAAc,CAAC,gBAAgB,CAAC,EAAE;oBAC3E,OAAO,cAAc,CAAC,gBAAgB,CAAC,CAAC;iBACzC;gBACD,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,IAAI,cAAc,CAAC,gBAAgB,CAAC,EAAE;oBAC3E,OAAO,cAAc,CAAC,gBAAgB,CAAC,CAAC;iBACzC;gBAED,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;YACjE,CAAC;YACD,yBAAyB,EAAE,CAAC,cAAc,EAAE,EAAE;gBAC5C,IAAI,cAAc,CAAC,2BAA2B,CAAC,KAAK,SAAS,EAAE;oBAC7D,OAAO,IAAI,CAAC,WAAW,CAAC,2BAA2B,CAAC,CAAC;iBACtD;gBACD,4FAA4F;gBAC5F,+CAA+C;gBAC/C,OAAO,cAAc,CAAC,2BAA2B,C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AM,IAAI,KAAK,CACb,6DAA6D,SAAS,mDAAmD,aAAa,UAAU,CACjJ,CAAC;qBACH;iBACF;qBAAM;oBACL,IAAI,cAAc,CAAC,CAAC,CAAC,KAAK,eAAe,CAAC,CAAC,CAAC,EAAE;wBAC5C,MAAM,CAAC,IAAI,CACT,WAAW,CAAC,kCAAkC,cAAc,CAAC,CAAC,CAAC,iBAAiB,eAAe,CAAC,CAAC,CAAC,yCAAyC,CAAC,KAAK,eAAe,CAAC,CAAC,CAAC,gCAAgC,CACpM,CAAC;qBACH;iBACF;aACF;YACD,IAAI,MAAM,CAAC,MAAM,EAAE;gBACjB,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;aACpC;SACF;QAED,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,cAAc,EAAE,eAAe,IAAI,EAAE,CAAC,CAAC,CAAC;IAC7F,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6CG;IACH,kBAAkB,CAAC,sBAAmD;QACpE,MAAM,OAAO,GAAG,IAAA,gBAAQ,EAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,gCAAgC;QAE5E,IAAI,sBAAsB,EAAE;YAC1B,KAAK,MAAM,CAAC,IAAI,sBAAsB,EAAE;gBACtC,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC;aACrE;SACF;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;CACF;AA9ND,gEA8NC"} \ No newline at end of file diff --git a/lib/cjs/contract/HandlerBasedContract.js b/lib/cjs/contract/HandlerBasedContract.js new file mode 100644 index 00000000..35192acd --- /dev/null +++ b/lib/cjs/contract/HandlerBasedContract.js @@ -0,0 +1,712 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HandlerBasedContract = void 0; +const safe_stable_stringify_1 = __importDefault(require("safe-stable-stringify")); +const SortKeyCache_1 = require("../cache/SortKeyCache"); +const ContractCallRecord_1 = require("../core/ContractCallRecord"); +const HandlerExecutorFactory_1 = require("../core/modules/impl/HandlerExecutorFactory"); +const LexicographicalInteractionsSorter_1 = require("../core/modules/impl/LexicographicalInteractionsSorter"); +const StateEvaluator_1 = require("../core/modules/StateEvaluator"); +const KnownTags_1 = require("../core/KnownTags"); +const create_interaction_tx_1 = require("../legacy/create-interaction-tx"); +const Benchmark_1 = require("../logging/Benchmark"); +const LoggerFactory_1 = require("../logging/LoggerFactory"); +const Evolve_1 = require("../plugins/Evolve"); +const ArweaveWrapper_1 = require("../utils/ArweaveWrapper"); +const utils_1 = require("../utils/utils"); +const CreateContract_1 = require("./deploy/CreateContract"); +const InnerWritesEvaluator_1 = require("./InnerWritesEvaluator"); +const Signature_1 = require("./Signature"); +const EvaluationOptionsEvaluator_1 = require("./EvaluationOptionsEvaluator"); +const WarpFetchWrapper_1 = require("../core/WarpFetchWrapper"); +const async_mutex_1 = require("async-mutex"); +const arweave_types_1 = require("../utils/types/arweave-types"); +const ContractInteractionState_1 = require("./states/ContractInteractionState"); +const warp_isomorphic_1 = require("warp-isomorphic"); +const warp_arbundles_1 = require("warp-arbundles"); +/** + * An implementation of {@link Contract} that is backwards compatible with current style + * of writing SW contracts (ie. using the "handle" function). + * + * It requires {@link ExecutorFactory} that is using {@link HandlerApi} generic type. + */ +class HandlerBasedContract { + constructor(_contractTxId, warp, _parentContract = null, _innerCallData = null) { + var _a, _b; + this._contractTxId = _contractTxId; + this.warp = warp; + this._parentContract = _parentContract; + this._innerCallData = _innerCallData; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('HandlerBasedContract'); + // TODO: refactor: extract execution context logic to a separate class + this.ecLogger = LoggerFactory_1.LoggerFactory.INST.create('ExecutionContext'); + this._innerWritesEvaluator = new InnerWritesEvaluator_1.InnerWritesEvaluator(); + this._mutex = new async_mutex_1.Mutex(); + this._benchmarkStats = null; + this._children = []; + this._dreStates = new Map(); + this.waitForConfirmation = this.waitForConfirmation.bind(this); + this._arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(warp); + this._sorter = new LexicographicalInteractionsSorter_1.LexicographicalInteractionsSorter(warp.arweave); + if (_parentContract != null) { + this._evaluationOptions = this.getRoot().evaluationOptions(); + this._callDepth = _parentContract.callDepth() + 1; + const callingInteraction = _parentContract + .getCallStack() + .getInteraction(_innerCallData.callingInteraction.id); + if (this._callDepth > this._evaluationOptions.maxCallDepth) { + throw new Error(`Max call depth of ${this._evaluationOptions.maxCallDepth} has been exceeded for interaction ${JSON.stringify(callingInteraction.interactionInput)}`); + } + this.logger.debug('Calling interaction', { + id: _innerCallData.callingInteraction.id, + sortKey: _innerCallData.callingInteraction.sortKey, + type: _innerCallData.callType + }); + // if you're reading a state of the contract, on which you've just made a write - you're doing it wrong. + // the current state of the callee contract is always in the result of an internal write. + // following is a protection against naughty developers who might be doing such crazy things ;-) + if (((_b = (_a = callingInteraction.interactionInput) === null || _a === void 0 ? void 0 : _a.foreignContractCalls[_contractTxId]) === null || _b === void 0 ? void 0 : _b.innerCallType) === 'write' && + _innerCallData.callType === 'read') { + throw new Error('Calling a readContractState after performing an inner write is wrong - instead use a state from the result of an internal write.'); + } + const callStack = new ContractCallRecord_1.ContractCallRecord(_contractTxId, this._callDepth, _innerCallData === null || _innerCallData === void 0 ? void 0 : _innerCallData.callType); + callingInteraction.interactionInput.foreignContractCalls[_contractTxId] = callStack; + this._callStack = callStack; + this._rootSortKey = _parentContract.rootSortKey; + _parentContract._children.push(this); + } + else { + this._callDepth = 0; + this._callStack = new ContractCallRecord_1.ContractCallRecord(_contractTxId, 0); + this._rootSortKey = null; + this._evaluationOptions = new StateEvaluator_1.DefaultEvaluationOptions(); + this._children = []; + this._interactionState = new ContractInteractionState_1.ContractInteractionState(warp); + } + this.getCallStack = this.getCallStack.bind(this); + this._warpFetchWrapper = new WarpFetchWrapper_1.WarpFetchWrapper(this.warp); + } + async readState(sortKeyOrBlockHeight, caller, interactions) { + var _a, _b, _c; + this.logger.info('Read state for', { + contractTxId: this._contractTxId, + sortKeyOrBlockHeight + }); + if (!this.isRoot() && sortKeyOrBlockHeight == null) { + throw new Error('SortKey MUST be always set for non-root contract calls'); + } + const { stateEvaluator } = this.warp; + const sortKey = typeof sortKeyOrBlockHeight == 'number' + ? this._sorter.generateLastSortKey(sortKeyOrBlockHeight) + : sortKeyOrBlockHeight; + if (sortKey && !this.isRoot() && this.interactionState().has(this.txId(), sortKey)) { + const result = this.interactionState().get(this.txId(), sortKey); + return new SortKeyCache_1.SortKeyCacheResult(sortKey, result); + } + // TODO: not sure if we should synchronize on a contract instance or contractTxId + // in the latter case, the warp instance should keep a map contractTxId -> mutex + const releaseMutex = await this._mutex.acquire(); + try { + const initBenchmark = Benchmark_1.Benchmark.measure(); + this.maybeResetRootContract(); + const executionContext = await this.createExecutionContext(this._contractTxId, sortKey, false, interactions); + this.logger.info('Execution Context', { + srcTxId: (_a = executionContext.contractDefinition) === null || _a === void 0 ? void 0 : _a.srcTxId, + missingInteractions: (_b = executionContext.sortedInteractions) === null || _b === void 0 ? void 0 : _b.length, + cachedSortKey: (_c = executionContext.cachedState) === null || _c === void 0 ? void 0 : _c.sortKey + }); + initBenchmark.stop(); + const stateBenchmark = Benchmark_1.Benchmark.measure(); + const result = await stateEvaluator.eval(executionContext); + stateBenchmark.stop(); + const total = initBenchmark.elapsed(true) + stateBenchmark.elapsed(true); + this._benchmarkStats = { + gatewayCommunication: initBenchmark.elapsed(true), + stateEvaluation: stateBenchmark.elapsed(true), + total + }; + this.logger.info('Benchmark', { + 'Gateway communication ': initBenchmark.elapsed(), + 'Contract evaluation ': stateBenchmark.elapsed(), + 'Total: ': `${total.toFixed(0)}ms` + }); + if (sortKey && !this.isRoot()) { + this.interactionState().update(this.txId(), result.cachedValue, sortKey); + } + return result; + } + finally { + releaseMutex(); + } + } + async readStateFor(sortKey, interactions) { + return this.readState(sortKey, undefined, interactions); + } + async viewState(input, tags = [], transfer = CreateContract_1.emptyTransfer, caller) { + this.logger.info('View state for', this._contractTxId); + return await this.callContract(input, 'view', caller, undefined, tags, transfer); + } + async viewStateForTx(input, interactionTx) { + this.logger.info(`View state for ${this._contractTxId}`); + return await this.doApplyInputOnTx(input, interactionTx, 'view'); + } + async dryWrite(input, caller, tags, transfer, vrf) { + this.logger.info('Dry-write for', this._contractTxId); + return await this.callContract(input, 'write', caller, undefined, tags, transfer, undefined, vrf); + } + async applyInput(input, transaction) { + this.logger.info(`Apply-input from transaction ${transaction.id} for ${this._contractTxId}`); + return await this.doApplyInputOnTx(input, transaction, 'write'); + } + async writeInteraction(input, options) { + this.logger.info('Write interaction', { input, options }); + if (!this._signature) { + throw new Error("Wallet not connected. Use 'connect' method first."); + } + const { arweave, interactionsLoader, environment } = this.warp; + // we're calling this to verify whether proper env is used for this contract + // (e.g. test env for test contract) + await this.warp.definitionLoader.load(this._contractTxId); + const effectiveTags = (options === null || options === void 0 ? void 0 : options.tags) || []; + const effectiveTransfer = (options === null || options === void 0 ? void 0 : options.transfer) || CreateContract_1.emptyTransfer; + const effectiveStrict = (options === null || options === void 0 ? void 0 : options.strict) === true; + const effectiveVrf = (options === null || options === void 0 ? void 0 : options.vrf) === true; + const effectiveDisableBundling = (options === null || options === void 0 ? void 0 : options.disableBundling) === true; + const effectiveReward = options === null || options === void 0 ? void 0 : options.reward; + const bundleInteraction = interactionsLoader.type() == 'warp' && !effectiveDisableBundling; + this._signature.checkNonArweaveSigningAvailability(bundleInteraction); + this._signature.checkBundlerSignerAvailability(bundleInteraction); + if (bundleInteraction && + effectiveTransfer.target != CreateContract_1.emptyTransfer.target && + effectiveTransfer.winstonQty != CreateContract_1.emptyTransfer.winstonQty) { + throw new Error('Ar Transfers are not allowed for bundled interactions'); + } + if (effectiveVrf && !bundleInteraction && environment === 'mainnet') { + throw new Error('Vrf generation is only available for bundle interaction'); + } + if (!input) { + throw new Error(`Input should be a truthy value: ${JSON.stringify(input)}`); + } + if (bundleInteraction) { + return await this.bundleInteraction(input, { + tags: effectiveTags, + strict: effectiveStrict, + vrf: effectiveVrf + }); + } + else { + const interactionTx = await this.createInteraction(input, effectiveTags, effectiveTransfer, effectiveStrict, false, effectiveVrf && environment !== 'mainnet', effectiveReward); + const response = await arweave.transactions.post(interactionTx); + if (response.status !== 200) { + this.logger.error('Error while posting transaction', response); + return null; + } + if (this._evaluationOptions.waitForConfirmation) { + this.logger.info('Waiting for confirmation of', interactionTx.id); + const benchmark = Benchmark_1.Benchmark.measure(); + await this.waitForConfirmation(interactionTx.id); + this.logger.info('Transaction confirmed after', benchmark.elapsed()); + } + if (this.warp.environment == 'local' && this._evaluationOptions.mineArLocalBlocks) { + await this.warp.testing.mineBlock(); + } + return { originalTxId: interactionTx.id, interactionTx }; + } + } + async bundleInteraction(input, options) { + this.logger.info('Bundle interaction input', input); + const interactionDataItem = await this.createInteractionDataItem(input, options.tags, CreateContract_1.emptyTransfer, options.strict, options.vrf); + const response = this._warpFetchWrapper.fetch(`${(0, utils_1.stripTrailingSlash)(this._evaluationOptions.sequencerUrl)}/gateway/v2/sequencer/register`, { + method: 'POST', + headers: { + 'Content-Type': 'application/octet-stream', + Accept: 'application/json' + }, + body: interactionDataItem.getRaw() + }); + const dataItemId = await interactionDataItem.id; + return { + bundlrResponse: await (0, utils_1.getJsonResponse)(response), + originalTxId: dataItemId, + interactionTx: interactionDataItem + }; + } + async createInteractionDataItem(input, tags, transfer, strict, vrf = false) { + var _a; + if (this._evaluationOptions.internalWrites) { + // it modifies tags + await this.discoverInternalWrites(input, tags, transfer, strict, vrf); + } + if (vrf) { + tags.push(new arweave_types_1.Tag(KnownTags_1.WARP_TAGS.REQUEST_VRF, 'true')); + } + const interactionTags = (0, create_interaction_tx_1.createInteractionTagsList)(this._contractTxId, input, this.warp.environment === 'testnet', tags); + if ((0, warp_arbundles_1.tagsExceedLimit)(interactionTags)) { + throw new Error(`Interaction tags exceed limit of 4096 bytes.`); + } + const data = Math.random().toString().slice(-4); + const bundlerSigner = this._signature.bundlerSigner; + if (!bundlerSigner) { + throw new Error(`Signer not set correctly. If you connect wallet through 'use_wallet', please remember that it only works when bundling is disabled.`); + } + let interactionDataItem; + if ((0, utils_1.isBrowser)() && ((_a = bundlerSigner.signer) === null || _a === void 0 ? void 0 : _a.signDataItem)) { + interactionDataItem = await bundlerSigner.signDataItem(data, interactionTags); + } + else { + interactionDataItem = (0, warp_arbundles_1.createData)(data, bundlerSigner, { tags: interactionTags }); + await interactionDataItem.sign(bundlerSigner); + } + if (!this._evaluationOptions.internalWrites && strict) { + await this.checkInteractionInStrictMode(interactionDataItem.owner, input, tags, transfer, strict, vrf); + } + return interactionDataItem; + } + async createInteraction(input, tags, transfer, strict, bundle = false, vrf = false, reward) { + if (this._evaluationOptions.internalWrites) { + // it modifies tags + await this.discoverInternalWrites(input, tags, transfer, strict, vrf); + } + if (vrf) { + tags.push(new arweave_types_1.Tag(KnownTags_1.WARP_TAGS.REQUEST_VRF, 'true')); + } + const interactionTx = await (0, create_interaction_tx_1.createInteractionTx)(this.warp.arweave, this._signature.signer, this._contractTxId, input, tags, transfer.target, transfer.winstonQty, bundle, this.warp.environment === 'testnet', reward); + if (!this._evaluationOptions.internalWrites && strict) { + await this.checkInteractionInStrictMode(interactionTx.owner, input, tags, transfer, strict, vrf); + } + return interactionTx; + } + async checkInteractionInStrictMode(owner, input, tags, transfer, strict, vrf) { + const { arweave } = this.warp; + const caller = this._signature.type == 'arweave' + ? await arweave.wallets.ownerToAddress(owner) + : await this._signature.getAddress(); + const handlerResult = await this.callContract(input, 'write', caller, undefined, tags, transfer, strict, vrf); + if (handlerResult.type === 'error') { + throw new HandlerExecutorFactory_1.ContractError(handlerResult.error); + } + else if (handlerResult.type !== 'ok') { + throw Error('Cannot create interaction: ' + JSON.stringify(handlerResult.error || handlerResult.errorMessage)); + } + } + txId() { + return this._contractTxId; + } + getCallStack() { + return this._callStack; + } + connect(signature) { + this._signature = new Signature_1.Signature(this.warp, signature); + return this; + } + setEvaluationOptions(options) { + if (!this.isRoot()) { + throw new Error('Evaluation options can be set only for the root contract'); + } + this._evaluationOptions = { + ...this._evaluationOptions, + ...options + }; + return this; + } + async waitForConfirmation(transactionId) { + const { arweave } = this.warp; + const status = await arweave.transactions.getStatus(transactionId); + if (status.confirmed === null) { + this.logger.info(`Transaction ${transactionId} not yet confirmed. Waiting another 20 seconds before next check.`); + await (0, utils_1.sleep)(20000); + return this.waitForConfirmation(transactionId); + } + else { + this.logger.info(`Transaction ${transactionId} confirmed`, status); + return status; + } + } + async createExecutionContext(contractTxId, upToSortKey, forceDefinitionLoad = false, interactions) { + var _a, _b, _c, _d; + const { definitionLoader, interactionsLoader, stateEvaluator } = this.warp; + let cachedState; + const benchmark = Benchmark_1.Benchmark.measure(); + if (!this.isRoot()) { + cachedState = this.interactionState().getLessOrEqual(this.txId(), upToSortKey); + } + cachedState = cachedState || (await stateEvaluator.latestAvailableState(contractTxId, upToSortKey)); + this.logger.debug('cache lookup', benchmark.elapsed()); + benchmark.reset(); + const evolvedSrcTxId = Evolve_1.Evolve.evolvedSrcTxId((_a = cachedState === null || cachedState === void 0 ? void 0 : cachedState.cachedValue) === null || _a === void 0 ? void 0 : _a.state); + let handler, contractDefinition, contractEvaluationOptions, remoteState; + let sortedInteractions = interactions || []; + this.logger.debug('Cached state', cachedState, upToSortKey); + if (cachedState && cachedState.sortKey == upToSortKey) { + this.logger.debug('State fully cached, not loading interactions.'); + if (forceDefinitionLoad || evolvedSrcTxId || (interactions === null || interactions === void 0 ? void 0 : interactions.length)) { + contractDefinition = await definitionLoader.load(contractTxId, evolvedSrcTxId); + if (interactions === null || interactions === void 0 ? void 0 : interactions.length) { + sortedInteractions = (await this._sorter.sort(interactions.map((i) => ({ node: i, cursor: null })))).map((i) => i.node); + } + } + } + else { + // if we want to apply some 'external' interactions on top of the state cached at given sort key + // AND we don't have the state cached at the exact requested sort key - throw. + // NOTE: this feature is used by the D.R.E. nodes. + if (interactions === null || interactions === void 0 ? void 0 : interactions.length) { + throw new Error(`Cannot apply requested interactions at ${upToSortKey}`); + } + contractDefinition = await definitionLoader.load(contractTxId, evolvedSrcTxId); + contractEvaluationOptions = this.resolveEvaluationOptions((_b = contractDefinition.manifest) === null || _b === void 0 ? void 0 : _b.evaluationOptions); + if (contractEvaluationOptions.remoteStateSyncEnabled && !contractEvaluationOptions.useKVStorage) { + remoteState = await this.getRemoteContractState(contractTxId); + cachedState = await this.maybeSyncStateWithRemoteSource(remoteState, upToSortKey, cachedState); + const maybeEvolvedSrcTxId = Evolve_1.Evolve.evolvedSrcTxId((_c = cachedState === null || cachedState === void 0 ? void 0 : cachedState.cachedValue) === null || _c === void 0 ? void 0 : _c.state); + if (maybeEvolvedSrcTxId && maybeEvolvedSrcTxId !== contractDefinition.srcTxId) { + // even though the state will be synced, the CacheableStateEvaluator will + // still try to init it in the WASM module (https://github.com/warp-contracts/warp/issues/372) + // if the state struct definition has changed via evolve - there is a risk of panic in Rust. + // that's why the contract definition has to be updated. + contractDefinition = await definitionLoader.load(contractTxId, maybeEvolvedSrcTxId); + } + } + this.warp.executorFactory.checkWhiteListContractSources(contractDefinition, contractEvaluationOptions); + if (!remoteState && sortedInteractions.length == 0) { + sortedInteractions = await interactionsLoader.load(contractTxId, cachedState === null || cachedState === void 0 ? void 0 : cachedState.sortKey, this.getToSortKey(upToSortKey), contractEvaluationOptions); + } + // we still need to return only interactions up to original "upToSortKey" + if (cachedState === null || cachedState === void 0 ? void 0 : cachedState.sortKey) { + sortedInteractions = sortedInteractions.filter((i) => i.sortKey.localeCompare(cachedState === null || cachedState === void 0 ? void 0 : cachedState.sortKey) > 0); + } + if (upToSortKey) { + sortedInteractions = sortedInteractions.filter((i) => i.sortKey.localeCompare(upToSortKey) <= 0); + } + this.logger.debug('contract and interactions load', benchmark.elapsed()); + if (this.isRoot() && sortedInteractions.length) { + // note: if the root contract has zero interactions, it still should be safe + // - as no other contracts will be called. + this._rootSortKey = sortedInteractions[sortedInteractions.length - 1].sortKey; + } + } + if (contractDefinition) { + if (!contractEvaluationOptions) { + contractEvaluationOptions = this.resolveEvaluationOptions((_d = contractDefinition.manifest) === null || _d === void 0 ? void 0 : _d.evaluationOptions); + } + this.ecLogger.debug(`Evaluation options ${contractTxId}:`, contractEvaluationOptions); + handler = (await this.warp.executorFactory.create(contractDefinition, contractEvaluationOptions, this.warp, this.interactionState())); + } + return { + warp: this.warp, + contract: this, + contractDefinition, + sortedInteractions, + evaluationOptions: contractEvaluationOptions || this.evaluationOptions(), + handler, + cachedState, + requestedSortKey: upToSortKey + }; + } + resolveEvaluationOptions(rootManifestEvalOptions) { + if (this.isRoot()) { + this._eoEvaluator = new EvaluationOptionsEvaluator_1.EvaluationOptionsEvaluator(this.evaluationOptions(), rootManifestEvalOptions); + return this._eoEvaluator.rootOptions; + } + return this.getRootEoEvaluator().forForeignContract(rootManifestEvalOptions); + } + async getRemoteContractState(contractId) { + if (this.hasDreState(contractId)) { + return this.getDreState(contractId); + } + else { + const dreResponse = await this.fetchRemoteContractState(contractId); + if (dreResponse != null) { + return this.setDREState(contractId, dreResponse); + } + return null; + } + } + async fetchRemoteContractState(contractId) { + return (0, utils_1.getJsonResponse)(this._warpFetchWrapper.fetch(`${this._evaluationOptions.remoteStateSyncSource}?id=${contractId}&events=false`)); + } + getToSortKey(upToSortKey) { + var _a; + if ((_a = this._parentContract) === null || _a === void 0 ? void 0 : _a.rootSortKey) { + if (!upToSortKey) { + return this._parentContract.rootSortKey; + } + return this._parentContract.rootSortKey.localeCompare(upToSortKey) > 0 + ? this._parentContract.rootSortKey + : upToSortKey; + } + else { + return upToSortKey; + } + } + async createExecutionContextFromTx(contractTxId, transaction) { + const caller = transaction.owner.address; + const sortKey = transaction.sortKey; + const baseContext = await this.createExecutionContext(contractTxId, sortKey, true); + return { + ...baseContext, + caller + }; + } + maybeResetRootContract() { + if (this.isRoot()) { + this.logger.debug('Clearing call stack for the root contract'); + this._callStack = new ContractCallRecord_1.ContractCallRecord(this.txId(), 0); + this._rootSortKey = null; + this.warp.interactionsLoader.clearCache(); + this._children = []; + this._interactionState = new ContractInteractionState_1.ContractInteractionState(this.warp); + this._dreStates = new Map(); + } + } + async callContract(input, interactionType, caller, sortKey, tags = [], transfer = CreateContract_1.emptyTransfer, strict = false, vrf = false, sign = true) { + var _a; + this.logger.info('Call contract input', input); + this.maybeResetRootContract(); + if (!this._signature) { + this.logger.warn('Wallet not set.'); + } + const { arweave, stateEvaluator } = this.warp; + // create execution context + let executionContext = await this.createExecutionContext(this._contractTxId, sortKey, true); + const currentBlockData = this.warp.environment == 'mainnet' ? await this._arweaveWrapper.warpGwBlock() : await arweave.blocks.getCurrent(); + // add caller info to execution context + let effectiveCaller; + if (caller) { + effectiveCaller = caller; + } + else if (this._signature) { + effectiveCaller = await this._signature.getAddress(); + } + else { + effectiveCaller = ''; + } + this.logger.info('effectiveCaller', effectiveCaller); + executionContext = { + ...executionContext, + caller: effectiveCaller + }; + // eval current state + const evalStateResult = await stateEvaluator.eval(executionContext); + this.logger.info('Current state', evalStateResult.cachedValue.state); + // create interaction transaction + const interaction = { + input, + caller: executionContext.caller, + interactionType + }; + this.logger.debug('interaction', interaction); + const tx = await (0, create_interaction_tx_1.createInteractionTx)(arweave, sign ? (_a = this._signature) === null || _a === void 0 ? void 0 : _a.signer : undefined, this._contractTxId, input, tags, transfer.target, transfer.winstonQty, true, this.warp.environment === 'testnet'); + const dummyTx = (0, create_interaction_tx_1.createDummyTx)(tx, executionContext.caller, currentBlockData); + this.logger.debug('Creating sortKey for', { + blockId: dummyTx.block.id, + id: dummyTx.id, + height: dummyTx.block.height + }); + dummyTx.sortKey = await this._sorter.createSortKey(dummyTx.block.id, dummyTx.id, dummyTx.block.height, true); + dummyTx.strict = strict; + if (vrf) { + const vrfPlugin = this.warp.maybeLoadPlugin('vrf'); + if (vrfPlugin) { + dummyTx.vrf = vrfPlugin.process().generateMockVrf(dummyTx.sortKey); + } + else { + this.logger.warn('Cannot generate mock vrf for interaction - no "warp-contracts-plugin-vrf" attached!'); + } + } + const handleResult = await this.evalInteraction({ + interaction, + interactionTx: dummyTx + }, executionContext, evalStateResult.cachedValue); + if (handleResult.type !== 'ok') { + this.logger.fatal('Error while interacting with contract', { + type: handleResult.type, + error: handleResult.errorMessage + }); + } + return handleResult; + } + async doApplyInputOnTx(input, interactionTx, interactionType) { + this.maybeResetRootContract(); + let evalStateResult; + const executionContext = await this.createExecutionContextFromTx(this._contractTxId, interactionTx); + if (!this.isRoot() && this.interactionState().has(this.txId(), interactionTx.sortKey)) { + evalStateResult = new SortKeyCache_1.SortKeyCacheResult(interactionTx.sortKey, this.interactionState().get(this.txId(), interactionTx.sortKey)); + } + else { + evalStateResult = await this.warp.stateEvaluator.eval(executionContext); + this.interactionState().update(this.txId(), evalStateResult.cachedValue, interactionTx.sortKey); + } + this.logger.debug('callContractForTx - evalStateResult', { + result: evalStateResult.cachedValue.state, + txId: this._contractTxId + }); + const interaction = { + input, + caller: this._parentContract.txId(), + interactionType + }; + const interactionData = { + interaction, + interactionTx + }; + const result = await this.evalInteraction(interactionData, executionContext, evalStateResult.cachedValue); + result.originalValidity = evalStateResult.cachedValue.validity; + result.originalErrorMessages = evalStateResult.cachedValue.errorMessages; + return result; + } + async evalInteraction(interactionData, executionContext, evalStateResult) { + const interactionCall = this.getCallStack().addInteractionData(interactionData); + const benchmark = Benchmark_1.Benchmark.measure(); + await executionContext.handler.initState(evalStateResult.state); + const result = await executionContext.handler.handle(executionContext, evalStateResult, interactionData); + interactionCall.update({ + cacheHit: false, + outputState: this._evaluationOptions.stackTrace.saveState ? result.state : undefined, + executionTime: benchmark.elapsed(true), + valid: result.type === 'ok', + errorMessage: result.errorMessage, + gasUsed: result.gasUsed + }); + return result; + } + parent() { + return this._parentContract; + } + callDepth() { + return this._callDepth; + } + evaluationOptions() { + return this._evaluationOptions; + } + lastReadStateStats() { + return this._benchmarkStats; + } + async stateHash(state) { + const jsonState = (0, safe_stable_stringify_1.default)(state); + const hash = await warp_isomorphic_1.Crypto.subtle.digest('SHA-256', Buffer.from(jsonState, 'utf-8')); + return Buffer.from(hash).toString('hex'); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- params can be anything + async syncState(externalUrl, params) { + const { stateEvaluator } = this.warp; + const response = await this._warpFetchWrapper + .fetch(`${externalUrl}?${new URLSearchParams({ + id: this._contractTxId, + ...params + })}`) + .then((res) => { + return res.ok ? res.json() : Promise.reject(res); + }) + .catch((error) => { + var _a, _b; + if ((_a = error.body) === null || _a === void 0 ? void 0 : _a.message) { + this.logger.error(error.body.message); + } + throw new Error(`Unable to retrieve state. ${error.status}: ${(_b = error.body) === null || _b === void 0 ? void 0 : _b.message}`); + }); + await stateEvaluator.syncState(this._contractTxId, response.sortKey, response.state, response.validity); + return this; + } + async evolve(newSrcTxId, options) { + return await this.writeInteraction({ function: 'evolve', value: newSrcTxId }, options); + } + get rootSortKey() { + return this._rootSortKey; + } + getRootEoEvaluator() { + const root = this.getRoot(); + return root._eoEvaluator; + } + isRoot() { + return this._parentContract == null; + } + async getStorageValues(keys) { + const lastCached = await this.warp.stateEvaluator.getCache().getLast(this.txId()); + if (lastCached == null) { + return new SortKeyCache_1.SortKeyCacheResult(null, new Map()); + } + const storage = this.warp.kvStorageFactory(this.txId()); + const result = new Map(); + try { + await storage.open(); + for (const key of keys) { + const lastValue = await storage.getLessOrEqual(key, lastCached.sortKey); + result.set(key, lastValue == null ? null : lastValue.cachedValue); + } + return new SortKeyCache_1.SortKeyCacheResult(lastCached.sortKey, result); + } + finally { + await storage.close(); + } + } + interactionState() { + return this.getRoot()._interactionState; + } + getRoot() { + let result = this; + while (!result.isRoot()) { + result = result.parent(); + } + return result; + } + async maybeSyncStateWithRemoteSource(remoteState, upToSortKey, cachedState) { + const { stateEvaluator } = this.warp; + if (this.isStateHigherThanAndUpTo(remoteState, cachedState === null || cachedState === void 0 ? void 0 : cachedState.sortKey, upToSortKey)) { + return await stateEvaluator.syncState(this._contractTxId, remoteState.sortKey, remoteState.cachedValue.state, remoteState.cachedValue.validity); + } + return cachedState; + } + isStateHigherThanAndUpTo(remoteState, fromSortKey, upToSortKey) { + return (remoteState && + (!upToSortKey || upToSortKey >= remoteState.sortKey) && + (!fromSortKey || remoteState.sortKey > fromSortKey)); + } + setDREState(contractTxId, result) { + const dreCachedState = new SortKeyCache_1.SortKeyCacheResult(result.sortKey, new StateEvaluator_1.EvalStateResult(result.state, {}, result.errorMessages)); + this.getRoot()._dreStates.set(contractTxId, dreCachedState); + return dreCachedState; + } + getDreState(contractTxId) { + return this.getRoot()._dreStates.get(contractTxId); + } + hasDreState(contractTxId) { + return this.getRoot()._dreStates.has(contractTxId); + } + // Call contract and verify if there are any internal writes: + // 1. Evaluate current contract state + // 2. Apply input as "dry-run" transaction + // 3. Verify the callStack and search for any "internalWrites" transactions + // 4. For each found "internalWrite" transaction - generate additional tag: + // {name: 'InternalWrite', value: callingContractTxId} + async discoverInternalWrites(input, tags, transfer, strict, vrf) { + const handlerResult = await this.callContract(input, 'write', undefined, undefined, tags, transfer, strict, vrf, false); + if (strict) { + if (handlerResult.type === 'error') { + throw new HandlerExecutorFactory_1.ContractError(handlerResult.error); + } + else if (handlerResult.type !== 'ok') { + throw Error('Cannot create interaction: ' + JSON.stringify(handlerResult.error || handlerResult.errorMessage)); + } + } + const callStack = this.getCallStack(); + const innerWrites = this._innerWritesEvaluator.eval(callStack); + this.logger.debug('Input', input); + this.logger.debug('Callstack', callStack.print()); + innerWrites.forEach((contractTxId) => { + tags.push(new arweave_types_1.Tag(KnownTags_1.WARP_TAGS.INTERACT_WRITE, contractTxId)); + }); + this.logger.debug('Tags with inner calls', tags); + } + clearChildren() { + for (const child of this._children) { + child.clearChildren(); + } + this._children = []; + } +} +exports.HandlerBasedContract = HandlerBasedContract; +//# sourceMappingURL=HandlerBasedContract.js.map \ No newline at end of file diff --git a/lib/cjs/contract/HandlerBasedContract.js.map b/lib/cjs/contract/HandlerBasedContract.js.map new file mode 100644 index 00000000..4f485851 --- /dev/null +++ b/lib/cjs/contract/HandlerBasedContract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"HandlerBasedContract.js","sourceRoot":"","sources":["../../../src/contract/HandlerBasedContract.ts"],"names":[],"mappings":";;;;;;AAAA,kFAA8C;AAC9C,wDAA2D;AAC3D,mEAAiF;AAEjF,wFAOqD;AACrD,8GAA2G;AAE3G,mEAA8G;AAC9G,iDAA8C;AAE9C,2EAAgH;AAEhH,oDAAiD;AACjD,4DAAyD;AACzD,8CAA2C;AAC3C,4DAAyD;AACzD,0CAAuF;AASvF,4DAAoF;AACpF,iEAA8D;AAC9D,2CAAyD;AACzD,6EAA0E;AAC1E,+DAA4D;AAC5D,6CAAoC;AACpC,gEAA2F;AAE3F,gFAA6E;AAC7E,qDAAyC;AAEzC,mDAA+E;AAE/E;;;;;GAKG;AAEH,MAAa,oBAAoB;IAwB/B,YACmB,aAAqB,EACnB,IAAU,EACZ,kBAA4B,IAAI,EAChC,iBAAgC,IAAI;;QAHpC,kBAAa,GAAb,aAAa,CAAQ;QACnB,SAAI,GAAJ,IAAI,CAAM;QACZ,oBAAe,GAAf,eAAe,CAAiB;QAChC,mBAAc,GAAd,cAAc,CAAsB;QA3BtC,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,sBAAsB,CAAC,CAAC;QAE5E,sEAAsE;QACrD,aAAQ,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC;QAEzD,0BAAqB,GAAG,IAAI,2CAAoB,EAAE,CAAC;QAGnD,WAAM,GAAG,IAAI,mBAAK,EAAE,CAAC;QAK9B,oBAAe,GAAmB,IAAI,CAAC;QAMvC,cAAS,GAAoC,EAAE,CAAC;QAEhD,eAAU,GAAG,IAAI,GAA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AAM,IAAI,sCAAa,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;aAC9C;iBAAM,IAAI,aAAa,CAAC,IAAI,KAAK,IAAI,EAAE;gBACtC,MAAM,KAAK,CAAC,6BAA6B,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,KAAK,IAAI,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC;aAChH;SACF;QACD,MAAM,SAAS,GAAuB,IAAI,CAAC,YAAY,EAAE,CAAC;QAC1D,MAAM,WAAW,GAAG,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC/D,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QAClC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC,CAAC;QAElD,WAAW,CAAC,OAAO,CAAC,CAAC,YAAY,EAAE,EAAE;YACnC,IAAI,CAAC,IAAI,CAAC,IAAI,mBAAG,CAAC,qBAAS,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC,CAAC;QAC7D,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,uBAAuB,EAAE,IAAI,CAAC,CAAC;IACnD,CAAC;IAED,aAAa;QACX,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,SAAS,EAAE;YAClC,KAAK,CAAC,aAAa,EAAE,CAAC;SACvB;QACD,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAp/BD,oDAo/BC"} \ No newline at end of file diff --git a/lib/cjs/contract/InnerWritesEvaluator.js b/lib/cjs/contract/InnerWritesEvaluator.js new file mode 100644 index 00000000..c7c3d17d --- /dev/null +++ b/lib/cjs/contract/InnerWritesEvaluator.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InnerWritesEvaluator = void 0; +class InnerWritesEvaluator { + eval(callStack) { + const result = []; + Object.keys(callStack.interactions).forEach((k) => { + const interaction = callStack.interactions[k]; + this.evalForeignCalls(callStack.contractTxId, interaction, result); + }); + return result; + } + evalForeignCalls(rootContractTxId, interaction, result) { + Object.keys(interaction.interactionInput.foreignContractCalls).forEach((foreignContractCallKey) => { + const foreignContractCall = interaction.interactionInput.foreignContractCalls[foreignContractCallKey]; + if (foreignContractCall.innerCallType == 'write') { + Object.keys(foreignContractCall.interactions).forEach((k) => { + const foreignInteraction = foreignContractCall.interactions[k]; + if (foreignInteraction.interactionInput.dryWrite && + !result.includes(foreignContractCall.contractTxId) && + rootContractTxId !== foreignContractCall.contractTxId /*"write-backs"*/) { + result.push(foreignContractCall.contractTxId); + } + this.evalForeignCalls(rootContractTxId, foreignInteraction, result); + }); + } + }); + } +} +exports.InnerWritesEvaluator = InnerWritesEvaluator; +//# sourceMappingURL=InnerWritesEvaluator.js.map \ No newline at end of file diff --git a/lib/cjs/contract/InnerWritesEvaluator.js.map b/lib/cjs/contract/InnerWritesEvaluator.js.map new file mode 100644 index 00000000..f34f6277 --- /dev/null +++ b/lib/cjs/contract/InnerWritesEvaluator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"InnerWritesEvaluator.js","sourceRoot":"","sources":["../../../src/contract/InnerWritesEvaluator.ts"],"names":[],"mappings":";;;AAEA,MAAa,oBAAoB;IAC/B,IAAI,CAAC,SAA6B;QAChC,MAAM,MAAM,GAAG,EAAE,CAAC;QAClB,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;YAChD,MAAM,WAAW,GAAG,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;YAC9C,IAAI,CAAC,gBAAgB,CAAC,SAAS,CAAC,YAAY,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC;QACrE,CAAC,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,gBAAgB,CAAC,gBAAwB,EAAE,WAA4B,EAAE,MAAqB;QACpG,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC,CAAC,sBAAsB,EAAE,EAAE;YAChG,MAAM,mBAAmB,GAAG,WAAW,CAAC,gBAAgB,CAAC,oBAAoB,CAAC,sBAAsB,CAAC,CAAC;YACtG,IAAI,mBAAmB,CAAC,aAAa,IAAI,OAAO,EAAE;gBAChD,MAAM,CAAC,IAAI,CAAC,mBAAmB,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;oBAC1D,MAAM,kBAAkB,GAAG,mBAAmB,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;oBAC/D,IACE,kBAAkB,CAAC,gBAAgB,CAAC,QAAQ;wBAC5C,CAAC,MAAM,CAAC,QAAQ,CAAC,mBAAmB,CAAC,YAAY,CAAC;wBAClD,gBAAgB,KAAK,mBAAmB,CAAC,YAAY,CAAC,iBAAiB,EACvE;wBACA,MAAM,CAAC,IAAI,CAAC,mBAAmB,CAAC,YAAY,CAAC,CAAC;qBAC/C;oBACD,IAAI,CAAC,gBAAgB,CAAC,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,CAAC,CAAC;gBACtE,CAAC,CAAC,CAAC;aACJ;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA7BD,oDA6BC"} \ No newline at end of file diff --git a/lib/cjs/contract/PstContract.js b/lib/cjs/contract/PstContract.js new file mode 100644 index 00000000..690dafda --- /dev/null +++ b/lib/cjs/contract/PstContract.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=PstContract.js.map \ No newline at end of file diff --git a/lib/cjs/contract/PstContract.js.map b/lib/cjs/contract/PstContract.js.map new file mode 100644 index 00000000..0c250f31 --- /dev/null +++ b/lib/cjs/contract/PstContract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PstContract.js","sourceRoot":"","sources":["../../../src/contract/PstContract.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/contract/PstContractImpl.js b/lib/cjs/contract/PstContractImpl.js new file mode 100644 index 00000000..d69c0f56 --- /dev/null +++ b/lib/cjs/contract/PstContractImpl.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PstContractImpl = void 0; +const HandlerBasedContract_1 = require("./HandlerBasedContract"); +class PstContractImpl extends HandlerBasedContract_1.HandlerBasedContract { + async currentBalance(target) { + const interactionResult = await this.viewState({ function: 'balance', target }); + if (interactionResult.type !== 'ok') { + throw Error(interactionResult.errorMessage); + } + return interactionResult.result; + } + async currentState() { + return (await super.readState()).cachedValue.state; + } + async transfer(transfer, options) { + return await this.writeInteraction({ function: 'transfer', ...transfer }, options); + } +} +exports.PstContractImpl = PstContractImpl; +//# sourceMappingURL=PstContractImpl.js.map \ No newline at end of file diff --git a/lib/cjs/contract/PstContractImpl.js.map b/lib/cjs/contract/PstContractImpl.js.map new file mode 100644 index 00000000..c924bc44 --- /dev/null +++ b/lib/cjs/contract/PstContractImpl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PstContractImpl.js","sourceRoot":"","sources":["../../../src/contract/PstContractImpl.ts"],"names":[],"mappings":";;;AAEA,iEAA8D;AAO9D,MAAa,eAAgB,SAAQ,2CAA8B;IACjE,KAAK,CAAC,cAAc,CAAC,MAAc;QACjC,MAAM,iBAAiB,GAAG,MAAM,IAAI,CAAC,SAAS,CAA8B,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;QAC7G,IAAI,iBAAiB,CAAC,IAAI,KAAK,IAAI,EAAE;YACnC,MAAM,KAAK,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;SAC7C;QACD,OAAO,iBAAiB,CAAC,MAAM,CAAC;IAClC,CAAC;IAED,KAAK,CAAC,YAAY;QAChB,OAAO,CAAC,MAAM,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC;IACrD,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,QAAuB,EAAE,OAAiC;QACvE,OAAO,MAAM,IAAI,CAAC,gBAAgB,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,QAAQ,EAAE,EAAE,OAAO,CAAC,CAAC;IACrF,CAAC;CACF;AAhBD,0CAgBC"} \ No newline at end of file diff --git a/lib/cjs/contract/Signature.js b/lib/cjs/contract/Signature.js new file mode 100644 index 00000000..b9c58a1b --- /dev/null +++ b/lib/cjs/contract/Signature.js @@ -0,0 +1,127 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Signature = void 0; +const warp_arbundles_1 = require("warp-arbundles"); +class Signature { + constructor(warp, walletOrSignature) { + this.warp = warp; + if (this.isCustomSignature(walletOrSignature)) { + this.assertEnvForCustomSigner(walletOrSignature.type); + this.signer = walletOrSignature.signer; + this.type = walletOrSignature.type; + this.signatureProviderType = 'CustomSignature'; + } + else if (this.isValidBundlerSignature(walletOrSignature)) { + this.signatureProviderType = 'BundlerSigner'; + this.type = decodeBundleSignatureType(walletOrSignature.signatureType); + this.bundlerSigner = walletOrSignature; + } + else { + this.assignArweaveSigner(walletOrSignature); + this.bundlerSigner = + typeof walletOrSignature == 'string' ? null : new warp_arbundles_1.ArweaveSigner(walletOrSignature); + this.signatureProviderType = 'ArWallet'; + this.type = 'arweave'; + } + this.wallet = walletOrSignature; + } + async getAddress() { + if (this.cachedAddress) { + return this.cachedAddress; + } + switch (this.signatureProviderType) { + case 'CustomSignature': { + if (this.wallet.getAddress) { + this.cachedAddress = await this.wallet.getAddress(); + } + else { + this.cachedAddress = await this.deduceSignerBySigning(); + } + return this.cachedAddress; + } + case 'ArWallet': { + this.cachedAddress = await this.deduceSignerBySigning(); + return this.cachedAddress; + } + case 'BundlerSigner': { + // If we can parse publicKey to `signatureType` address, we don't have to call it + this.cachedAddress = await this.deduceSignerBySigning(); + return this.cachedAddress; + } + default: + throw Error('Unknown Signature::signatureProvider : ' + this.signatureProviderType); + } + } + async deduceSignerBySigning() { + const { arweave } = this.warp; + if (this.signatureProviderType == 'BundlerSigner') { + try { + return await this.bundlerSigner.getAddress(); + } + catch (e) { + throw new Error(`Could not get address from the signer. Is the 'getAddress' implementation correct?'`); + } + } + else if (this.signatureProviderType == 'ArWallet' || this.signatureProviderType == 'CustomSignature') { + const dummyTx = await arweave.createTransaction({ + data: Math.random().toString().slice(-4), + reward: '72600854', + last_tx: 'p7vc1iSP6bvH_fCeUFa9LqoV5qiyW-jdEKouAT0XMoSwrNraB9mgpi29Q10waEpO' + }); + await this.signer(dummyTx); + return arweave.wallets.ownerToAddress(dummyTx.owner); + } + else { + throw Error('Unknown Signature::type'); + } + } + checkNonArweaveSigningAvailability(bundling) { + if (this.type !== 'arweave' && !bundling) { + throw new Error(`Unable to use signing function of type: ${this.type} when bundling is disabled.`); + } + } + checkBundlerSignerAvailability(bundling) { + if ((!bundling || this.warp.environment == 'local') && this.signatureProviderType == 'BundlerSigner') { + throw new Error(`Only wallet of type 'ArWallet' or 'CustomSignature' is allowed when bundling is disabled or in local environment.`); + } + } + assignArweaveSigner(walletOrSignature) { + this.signer = async (tx) => { + await this.warp.arweave.transactions.sign(tx, walletOrSignature); + }; + } + assertEnvForCustomSigner(signatureType) { + if (this.warp.interactionsLoader.type() === 'warp') { + throw new Error(`Unable to use signing function when bundling is enabled.`); + } + if (signatureType == 'ethereum') { + throw new Error(`Unable to use signing function with signature of type: ${signatureType}.`); + } + } + isCustomSignature(signature) { + return signature.signer !== undefined && signature.type !== undefined; + } + isValidBundlerSignature(signature) { + const bundlerSignature = signature; + // "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck" + const isBundlerSignature = !!bundlerSignature.signatureType && !!bundlerSignature.ownerLength && !!bundlerSignature.signatureLength; + if (isBundlerSignature && !bundlerSignature.publicKey) { + throw new Error(`It seems that you are using BundlerSigner, but publicKey is not set! Maybe try calling await bundlerSigner.setPublicKey() before using it.`); + } + return isBundlerSignature; + } +} +exports.Signature = Signature; +function decodeBundleSignatureType(bundlerSignatureType) { + // enum: https://github.com/Bundlr-Network/arbundles/blob/9fafdbfec6fbfcbcb538b92ae9bd0d9fbe413fb8/src/constants.ts#L1 + if (bundlerSignatureType === 3) { + return 'ethereum'; + } + else if (bundlerSignatureType === 1) { + return 'arweave'; + } + else { + throw Error(`Not supported arbundle SignatureType : ${bundlerSignatureType}`); + } +} +//# sourceMappingURL=Signature.js.map \ No newline at end of file diff --git a/lib/cjs/contract/Signature.js.map b/lib/cjs/contract/Signature.js.map new file mode 100644 index 00000000..a1569199 --- /dev/null +++ b/lib/cjs/contract/Signature.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Signature.js","sourceRoot":"","sources":["../../../src/contract/Signature.ts"],"names":[],"mappings":";;;AAIA,mDAAwE;AAmBxE,MAAa,SAAS;IASpB,YAAY,IAAU,EAAE,iBAAoC;QAC1D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,IAAI,IAAI,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,EAAE;YAC7C,IAAI,CAAC,wBAAwB,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;YACtD,IAAI,CAAC,MAAM,GAAG,iBAAiB,CAAC,MAAM,CAAC;YACvC,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC;YACnC,IAAI,CAAC,qBAAqB,GAAG,iBAAiB,CAAC;SAChD;aAAM,IAAI,IAAI,CAAC,uBAAuB,CAAC,iBAAiB,CAAC,EAAE;YAC1D,IAAI,CAAC,qBAAqB,GAAG,eAAe,CAAC;YAC7C,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC,iBAAiB,CAAC,aAAa,CAAC,CAAC;YACvE,IAAI,CAAC,aAAa,GAAG,iBAAiB,CAAC;SACxC;aAAM;YACL,IAAI,CAAC,mBAAmB,CAAC,iBAAiB,CA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s/contract/deploy/CreateContract.js b/lib/cjs/contract/deploy/CreateContract.js new file mode 100644 index 00000000..18f2777e --- /dev/null +++ b/lib/cjs/contract/deploy/CreateContract.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.REGISTER_PROVIDER = exports.emptyTransfer = void 0; +exports.emptyTransfer = { + target: '', + winstonQty: '0' +}; +exports.REGISTER_PROVIDER = ['node1', 'node2', 'arweave']; +//# sourceMappingURL=CreateContract.js.map \ No newline at end of file diff --git a/lib/cjs/contract/deploy/CreateContract.js.map b/lib/cjs/contract/deploy/CreateContract.js.map new file mode 100644 index 00000000..d1b0ae91 --- /dev/null +++ b/lib/cjs/contract/deploy/CreateContract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"CreateContract.js","sourceRoot":"","sources":["../../../../src/contract/deploy/CreateContract.ts"],"names":[],"mappings":";;;AAmBa,QAAA,aAAa,GAAe;IACvC,MAAM,EAAE,EAAE;IACV,UAAU,EAAE,GAAG;CAChB,CAAC;AAOW,QAAA,iBAAiB,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,CAAU,CAAC"} \ No newline at end of file diff --git a/lib/cjs/contract/deploy/Source.js b/lib/cjs/contract/deploy/Source.js new file mode 100644 index 00000000..2c712ecc --- /dev/null +++ b/lib/cjs/contract/deploy/Source.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Source.js.map \ No newline at end of file diff --git a/lib/cjs/contract/deploy/Source.js.map b/lib/cjs/contract/deploy/Source.js.map new file mode 100644 index 00000000..a37e550a --- /dev/null +++ b/lib/cjs/contract/deploy/Source.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Source.js","sourceRoot":"","sources":["../../../../src/contract/deploy/Source.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/contract/states/ContractInteractionState.js b/lib/cjs/contract/states/ContractInteractionState.js new file mode 100644 index 00000000..dd649b60 --- /dev/null +++ b/lib/cjs/contract/states/ContractInteractionState.js @@ -0,0 +1,147 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContractInteractionState = void 0; +const SortKeyCache_1 = require("../../cache/SortKeyCache"); +const SimpleLRUCache_1 = require("../../common/SimpleLRUCache"); +class ContractInteractionState { + constructor(_warp) { + this._warp = _warp; + this._json = new Map(); + this._initialJson = new Map(); + this._kv = new Map(); + } + has(contractTx, sortKey) { + var _a; + return ((_a = this._json.get(contractTx)) === null || _a === void 0 ? void 0 : _a.has(sortKey)) || false; + } + get(contractTxId, sortKey) { + var _a; + return ((_a = this._json.get(contractTxId)) === null || _a === void 0 ? void 0 : _a.get(sortKey)) || null; + } + getLessOrEqual(contractTxId, sortKey) { + const states = this._json.get(contractTxId); + if (states != null && states.size() > 0) { + let keys = states.keys(); + if (sortKey) { + keys = keys.filter((k) => k.localeCompare(sortKey) <= 0); + } + keys = keys.sort((a, b) => a.localeCompare(b)); + const resultSortKey = keys[keys.length - 1]; + if (states.get(resultSortKey)) { + return new SortKeyCache_1.SortKeyCacheResult(resultSortKey, states.get(resultSortKey)); + } + } + return null; + } + async getKV(contractTxId, cacheKey) { + var _a; + if (this._kv.has(contractTxId)) { + return ((_a = (await this._kv.get(contractTxId).get(cacheKey))) === null || _a === void 0 ? void 0 : _a.cachedValue) || null; + } + return null; + } + async delKV(contractTxId, cacheKey) { + if (this._kv.has(contractTxId)) { + await this._kv.get(contractTxId).del(cacheKey); + } + } + getKvKeys(contractTxId, sortKey, options) { + const storage = this._warp.kvStorageFactory(contractTxId); + return storage.keys(sortKey, options); + } + getKvRange(contractTxId, sortKey, options) { + const storage = this._warp.kvStorageFactory(contractTxId); + return storage.kvMap(sortKey, options); + } + async commit(interaction, forceStore = false) { + if (interaction.dry) { + await this.rollbackKVs(); + return this.reset(); + } + try { + const latestState = new Map(); + this._json.forEach((val, k) => { + const state = this.getLessOrEqual(k, interaction.sortKey); + if (state != null) { + latestState.set(k, state.cachedValue); + } + }); + await this.doStoreJson(latestState, interaction, forceStore); + await this.commitKVs(); + } + finally { + this.reset(); + } + } + async commitKV() { + await this.commitKVs(); + this._kv.clear(); + } + async rollback(interaction, forceStateStoreToCache) { + try { + await this.doStoreJson(this._initialJson, interaction, forceStateStoreToCache); + await this.rollbackKVs(); + } + finally { + this.reset(); + } + } + setInitial(contractTxId, state, sortKey) { + // think twice here. + this._initialJson.set(contractTxId, state); + this.update(contractTxId, state, sortKey); + } + update(contractTxId, state, sortKey) { + if (!this._json.has(contractTxId)) { + const cache = new SimpleLRUCache_1.SimpleLRUCache(10); + this._json.set(contractTxId, cache); + } + this._json.get(contractTxId).set(sortKey, state); + } + async updateKV(contractTxId, key, value) { + await (await this.getOrInitKvStorage(contractTxId)).put(key, value); + } + async getOrInitKvStorage(contractTxId) { + if (this._kv.has(contractTxId)) { + return this._kv.get(contractTxId); + } + const storage = this._warp.kvStorageFactory(contractTxId); + this._kv.set(contractTxId, storage); + await storage.open(); + return storage; + } + reset() { + this._json.clear(); + this._initialJson.clear(); + this._kv.clear(); + } + async doStoreJson(states, interaction, forceStore = false) { + if (states.size > 1 || forceStore) { + for (const [k, v] of states) { + await this._warp.stateEvaluator.putInCache(k, interaction, v); + } + } + } + async rollbackKVs() { + for (const storage of this._kv.values()) { + try { + await storage.rollback(); + } + finally { + await storage.close(); + } + } + } + async commitKVs() { + for (const storage of this._kv.values()) { + try { + await storage.commit(); + } + finally { + await storage.close(); + } + } + } +} +exports.ContractInteractionState = ContractInteractionState; +//# sourceMappingURL=ContractInteractionState.js.map \ No newline at end of file diff --git a/lib/cjs/contract/states/ContractInteractionState.js.map b/lib/cjs/contract/states/ContractInteractionState.js.map new file mode 100644 index 00000000..87950f5c --- /dev/null +++ b/lib/cjs/contract/states/ContractInteractionState.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ContractInteractionState.js","sourceRoot":"","sources":["../../../../src/contract/states/ContractInteractionState.ts"],"names":[],"mappings":";;;AACA,2DAAsF;AA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,GAAG,KAAK;QAElB,IAAI,MAAM,CAAC,IAAI,GAAG,CAAC,IAAI,UAAU,EAAE;YACjC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,EAAE;gBAC3B,MAAM,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC;aAC/D;SACF;IACH,CAAC;IAEO,KAAK,CAAC,WAAW;QACvB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE;YACvC,IAAI;gBACF,MAAM,OAAO,CAAC,QAAQ,EAAE,CAAC;aAC1B;oBAAS;gBACR,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;aACvB;SACF;IACH,CAAC;IAEO,KAAK,CAAC,SAAS;QACrB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE;YACvC,IAAI;gBACF,MAAM,OAAO,CAAC,MAAM,EAAE,CAAC;aACxB;oBAAS;gBACR,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;aACvB;SACF;IACH,CAAC;CACF;AA7JD,4DA6JC"} \ No newline at end of file diff --git a/lib/cjs/contract/states/InteractionState.js b/lib/cjs/contract/states/InteractionState.js new file mode 100644 index 00000000..6fa2cd7b --- /dev/null +++ b/lib/cjs/contract/states/InteractionState.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=InteractionState.js.map \ No newline at end of file diff --git a/lib/cjs/contract/states/InteractionState.js.map b/lib/cjs/contract/states/InteractionState.js.map new file mode 100644 index 00000000..552270c5 --- /dev/null +++ b/lib/cjs/contract/states/InteractionState.js.map @@ -0,0 +1 @@ +{"version":3,"file":"InteractionState.js","sourceRoot":"","sources":["../../../../src/contract/states/InteractionState.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/contract/testing/Testing.js b/lib/cjs/contract/testing/Testing.js new file mode 100644 index 00000000..7bf38f16 --- /dev/null +++ b/lib/cjs/contract/testing/Testing.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Testing = void 0; +class Testing { + constructor(arweave) { + this.arweave = arweave; + } + async mineBlock() { + this.validateEnv(); + await this.arweave.api.get('mine'); + } + async addFunds(wallet) { + const walletAddress = await this.arweave.wallets.getAddress(wallet); + await this.arweave.api.get(`/mint/${walletAddress}/1000000000000000`); + } + async isArlocal() { + const response = await fetch(`${this.arweave.api.config.protocol}://${this.arweave.api.config.host}:${this.arweave.api.config.port}/info`) + .then((res) => { + return res.ok ? res.json() : Promise.reject(); + }) + .catch((e) => { + throw new Error(`Unable to get network info: ${e.message}`); + }); + return response.network.includes('arlocal'); + } + async validateEnv() { + if (!(await this.isArlocal())) { + throw new Error('Testing features are not available in a non testing environment'); + } + } +} +exports.Testing = Testing; +//# sourceMappingURL=Testing.js.map \ No newline at end of file diff --git a/lib/cjs/contract/testing/Testing.js.map b/lib/cjs/contract/testing/Testing.js.map new file mode 100644 index 00000000..1ac5df75 --- /dev/null +++ b/lib/cjs/contract/testing/Testing.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Testing.js","sourceRoot":"","sources":["../../../../src/contract/testing/Testing.ts"],"names":[],"mappings":";;;AAQA,MAAa,OAAO;IAClB,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IAAG,CAAC;IAEjD,KAAK,CAAC,SAAS;QACb,IAAI,CAAC,WAAW,EAAE,CAAC;QACnB,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,MAAoB;QACjC,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACpE,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,SAAS,aAAa,mBAAmB,CAAC,CAAC;IACxE,CAAC;IAED,KAAK,CAAC,SAAS;QACb,MAAM,QAAQ,GAAG,MAAM,KAAK,CAC1B,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,OAAO,CAC7G;aACE,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE;YACZ,OAAO,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;QAChD,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;YACX,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QAC9D,CAAC,CAAC,CAAC;QAEL,OAAO,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IAC9C,CAAC;IAEO,KAAK,CAAC,WAAW;QACvB,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC,EAAE;YAC7B,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;SACpF;IACH,CAAC;CACF;AAhCD,0BAgCC"} \ No newline at end of file diff --git a/lib/cjs/core/ContractCallRecord.js b/lib/cjs/core/ContractCallRecord.js new file mode 100644 index 00000000..3618be36 --- /dev/null +++ b/lib/cjs/core/ContractCallRecord.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InteractionOutput = exports.InteractionInput = exports.InteractionCall = exports.ContractCallRecord = void 0; +const warp_isomorphic_1 = require("warp-isomorphic"); +class ContractCallRecord { + constructor(contractTxId, depth, innerCallType = null) { + this.contractTxId = contractTxId; + this.depth = depth; + this.innerCallType = innerCallType; + this.interactions = {}; + this.id = warp_isomorphic_1.Crypto.randomUUID(); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + addInteractionData(interactionData) { + const { interaction, interactionTx } = interactionData; + const interactionCall = InteractionCall.create(new InteractionInput(interactionTx.id, interactionTx.sortKey, interactionTx.block.height, interactionTx.block.timestamp, interaction === null || interaction === void 0 ? void 0 : interaction.caller, interaction === null || interaction === void 0 ? void 0 : interaction.input.function, interaction === null || interaction === void 0 ? void 0 : interaction.input, interactionTx.dry, {})); + this.interactions[interactionTx.id] = interactionCall; + return interactionCall; + } + getInteraction(txId) { + return this.interactions[txId]; + } + print() { + return JSON.stringify(this, null, 2); + } +} +exports.ContractCallRecord = ContractCallRecord; +class InteractionCall { + constructor(interactionInput) { + this.interactionInput = interactionInput; + } + static create(interactionInput) { + return new InteractionCall(interactionInput); + } + update(interactionOutput) { + this.interactionOutput = interactionOutput; + } +} +exports.InteractionCall = InteractionCall; +class InteractionInput { + constructor(txId, sortKey, blockHeight, blockTimestamp, caller, functionName, functionArguments, dryWrite, foreignContractCalls = {}) { + this.txId = txId; + this.sortKey = sortKey; + this.blockHeight = blockHeight; + this.blockTimestamp = blockTimestamp; + this.caller = caller; + this.functionName = functionName; + this.functionArguments = functionArguments; + this.dryWrite = dryWrite; + this.foreignContractCalls = foreignContractCalls; + } +} +exports.InteractionInput = InteractionInput; +class InteractionOutput { + constructor(cacheHit, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + outputState, executionTime, valid, errorMessage = '', gasUsed) { + this.cacheHit = cacheHit; + this.outputState = outputState; + this.executionTime = executionTime; + this.valid = valid; + this.errorMessage = errorMessage; + this.gasUsed = gasUsed; + } +} +exports.InteractionOutput = InteractionOutput; +//# sourceMappingURL=ContractCallRecord.js.map \ No newline at end of file diff --git a/lib/cjs/core/ContractCallRecord.js.map b/lib/cjs/core/ContractCallRecord.js.map new file mode 100644 index 00000000..a3c78fe3 --- /dev/null +++ b/lib/cjs/core/ContractCallRecord.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ContractCallRecord.js","sourceRoot":"","sources":["../../../src/core/ContractCallRecord.ts"],"names":[],"mappings":";;;AAEA,qDAAyC;AAEzC,MAAa,kBAAkB;IAI7B,YAAqB,YAAoB,EAAW,KAAa,EAAW,gBAA+B,IAAI;QAA1F,iBAAY,GAAZ,YAAY,CAAQ;QAAW,UAAK,GAAL,KAAK,CAAQ;QAAW,kBAAa,GAAb,aAAa,CAAsB;QAHtG,iBAAY,GAAuC,EAAE,CAAC;QAI7D,IAAI,CAAC,EAAE,GAAG,wBAAM,CAAC,UAAU,EAAE,CAAC;IAChC,CAAC;IAED,8DAA8D;IAC9D,kBAAkB,CAAC,eAAqC;QACtD,MAAM,EAAE,WAAW,EAAE,aAAa,EAAE,GAAG,eAAe,CAAC;QAEvD,MAAM,eAAe,GAAG,eAAe,CAAC,MAAM,CAC5C,IAAI,gBAAgB,CAClB,aAAa,CAAC,EAAE,EAChB,aAAa,CAAC,OAAO,EACrB,aAAa,CAAC,KAAK,CAAC,MAAM,EAC1B,aAAa,CAAC,KAAK,CAAC,SAAS,EAC7B,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,MAAM,EACnB,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,KAAK,CAAC,QAAQ,EAC3B,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,KAAK,EAClB,aAAa,CAAC,GAAG,EACjB,EAAE,CACH,CACF,CAAC;QAEF,IAAI,CAAC,YAAY,CAAC,aAAa,CAAC,EAAE,CAAC,GAAG,eAAe,CAAC;QAEtD,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,cAAc,CAAC,IAAY;QACzB,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IACjC,CAAC;IAED,KAAK;QACH,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACvC,CAAC;CACF;AAtCD,gDAsCC;AAED,MAAa,eAAe;IAG1B,YAA6B,gBAAkC;QAAlC,qBAAgB,GAAhB,gBAAgB,CAAkB;IAAG,CAAC;IAEnE,MAAM,CAAC,MAAM,CAAC,gBAAkC;QAC9C,OAAO,IAAI,eAAe,CAAC,gBAAgB,CAAC,CAAC;IAC/C,CAAC;IAED,MAAM,CAAC,iBAAoC;QACzC,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IAC7C,CAAC;CACF;AAZD,0CAYC;AAED,MAAa,gBAAgB;IAC3B,YACkB,IAAY,EACZ,OAAe,EACf,WAAmB,EACnB,cAAsB,EACtB,MAAc,EACd,YAAoB,EACpB,iBAAqB,EACrB,QAAiB,EACjB,uBAA8D,EAAE;QARhE,SAAI,GAAJ,IAAI,CAAQ;QACZ,YAAO,GAAP,OAAO,CAAQ;QACf,gBAAW,GAAX,WAAW,CAAQ;QACnB,mBAAc,GAAd,cAAc,CAAQ;QACtB,WAAM,GAAN,MAAM,CAAQ;QACd,iBAAY,GAAZ,YAAY,CAAQ;QACpB,sBAAiB,GAAjB,iBAAiB,CAAI;QACrB,aAAQ,GAAR,QAAQ,CAAS;QACjB,yBAAoB,GAApB,oBAAoB,CAA4C;IAC/E,CAAC;CACL;AAZD,4CAYC;AAED,MAAa,iBAAiB;IAC5B,YACkB,QAAiB;IACjC,8DAA8D;IAC9C,WAAgB,EAChB,aAAqB,EACrB,KAAc,EACd,eAAuB,EAAE,EACzB,OAAe;QANf,aAAQ,GAAR,QAAQ,CAAS;QAEjB,gBAAW,GAAX,WAAW,CAAK;QAChB,kBAAa,GAAb,aAAa,CAAQ;QACrB,UAAK,GAAL,KAAK,CAAS;QACd,iBAAY,GAAZ,YAAY,CAAa;QACzB,YAAO,GAAP,OAAO,CAAQ;IAC9B,CAAC;CACL;AAVD,8CAUC"} \ No newline at end of file diff --git a/lib/cjs/core/ContractDefinition.js b/lib/cjs/core/ContractDefinition.js new file mode 100644 index 00000000..64e1b12e --- /dev/null +++ b/lib/cjs/core/ContractDefinition.js @@ -0,0 +1,35 @@ +"use strict"; +/** + * This type contains all data and meta-data of the given contact. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContractCache = exports.SrcCache = exports.ContractMetadata = exports.SUPPORTED_SRC_CONTENT_TYPES = void 0; +exports.SUPPORTED_SRC_CONTENT_TYPES = ['application/javascript', 'application/wasm']; +class ContractMetadata { +} +exports.ContractMetadata = ContractMetadata; +class SrcCache { + constructor(value) { + this.src = value.src; + this.srcBinary = value.srcBinary; + this.srcWasmLang = value.srcWasmLang; + } +} +exports.SrcCache = SrcCache; +class ContractCache { + constructor(value) { + this.txId = value.txId; + this.srcTxId = value.srcTxId; + this.initState = value.initState; + this.manifest = value.manifest; + this.minFee = value.minFee; + this.owner = value.owner; + this.contractType = value.contractType; + this.metadata = value.metadata; + this.contractTx = value.contractTx; + this.srcTx = value.srcTx; + this.testnet = value.testnet; + } +} +exports.ContractCache = ContractCache; +//# sourceMappingURL=ContractDefinition.js.map \ No newline at end of file diff --git a/lib/cjs/core/ContractDefinition.js.map b/lib/cjs/core/ContractDefinition.js.map new file mode 100644 index 00000000..47af8380 --- /dev/null +++ b/lib/cjs/core/ContractDefinition.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ContractDefinition.js","sourceRoot":"","sources":["../../../src/core/ContractDefinition.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAIU,QAAA,2BAA2B,GAAG,CAAC,wBAAwB,EAAE,kBAAkB,CAAC,CAAC;AAE1F,MAAa,gBAAgB;CAE5B;AAFD,4CAEC;AAWD,MAAa,QAAQ;IAKnB,YAAY,KAAkC;QAC5C,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC;QACjC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;IACvC,CAAC;CACF;AAVD,4BAUC;AAED,MAAa,aAAa;IAaxB,YAAY,KAAgC;QAC1C,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;QAC7B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;QAC3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QACzB,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;QACvC,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;QACnC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC/B,CAAC;CACF;AA1BD,sCA0BC"} \ No newline at end of file diff --git a/lib/cjs/core/ExecutionContext.js b/lib/cjs/core/ExecutionContext.js new file mode 100644 index 00000000..91ffc101 --- /dev/null +++ b/lib/cjs/core/ExecutionContext.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ExecutionContext.js.map \ No newline at end of file diff --git a/lib/cjs/core/ExecutionContext.js.map b/lib/cjs/core/ExecutionContext.js.map new file mode 100644 index 00000000..ce68fa0a --- /dev/null +++ b/lib/cjs/core/ExecutionContext.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ExecutionContext.js","sourceRoot":"","sources":["../../../src/core/ExecutionContext.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/core/ExecutionContextModifier.js b/lib/cjs/core/ExecutionContextModifier.js new file mode 100644 index 00000000..f4ea6f45 --- /dev/null +++ b/lib/cjs/core/ExecutionContextModifier.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ExecutionContextModifier.js.map \ No newline at end of file diff --git a/lib/cjs/core/ExecutionContextModifier.js.map b/lib/cjs/core/ExecutionContextModifier.js.map new file mode 100644 index 00000000..3d70069d --- /dev/null +++ b/lib/cjs/core/ExecutionContextModifier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ExecutionContextModifier.js","sourceRoot":"","sources":["../../../src/core/ExecutionContextModifier.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/core/KnownTags.js b/lib/cjs/core/KnownTags.js new file mode 100644 index 00000000..d3c9a827 --- /dev/null +++ b/lib/cjs/core/KnownTags.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WARP_TAGS = exports.SMART_WEAVE_TAGS = void 0; +/** + * Definition of all transaction tags used by the SmartWeave "protocol" + */ +exports.SMART_WEAVE_TAGS = { + APP_NAME: 'App-Name', + APP_VERSION: 'App-Version', + CONTRACT_TX_ID: 'Contract', + INPUT: 'Input', + CONTENT_TYPE: 'Content-Type', + CONTRACT_SRC_TX_ID: 'Contract-Src', + SDK: 'SDK', + MIN_FEE: 'Min-Fee' +}; +/** + * Definition of all transaction tags specific to Warp platform + */ +exports.WARP_TAGS = { + SEQUENCER: 'Sequencer', + SEQUENCER_OWNER: 'Sequencer-Owner', + SEQUENCER_MILLIS: 'Sequencer-Mills', + SEQUENCER_SORT_KEY: 'Sequencer-Sort-Key', + SEQUENCER_PREV_SORT_KEY: 'Sequencer-Prev-Sort-Key', + SEQUENCER_LAST_SORT_KEY: 'Sequencer-Last-Sort-Key', + SEQUENCER_TX_ID: 'Sequencer-Tx-Id', + SEQUENCER_BLOCK_HEIGHT: 'Sequencer-Block-Height', + SEQUENCER_BLOCK_ID: 'Sequencer-Block-Id', + SEQUENCER_BLOCK_TIMESTAMP: 'Sequencer-Block-Timestamp', + INIT_STATE: 'Init-State', + INIT_STATE_TX: 'Init-State-TX', + INTERACT_WRITE: 'Interact-Write', + WASM_LANG: 'Wasm-Lang', + WASM_LANG_VERSION: 'Wasm-Lang-Version', + WASM_META: 'Wasm-Meta', + REQUEST_VRF: 'Request-Vrf', + SIGNATURE_TYPE: 'Signature-Type', + UPLOADER_TX_ID: 'Uploader-Tx-Id', + WARP_TESTNET: 'Warp-Testnet', + MANIFEST: 'Contract-Manifest', + NONCE: 'Nonce' +}; +//# sourceMappingURL=KnownTags.js.map \ No newline at end of file diff --git a/lib/cjs/core/KnownTags.js.map b/lib/cjs/core/KnownTags.js.map new file mode 100644 index 00000000..d134db77 --- /dev/null +++ b/lib/cjs/core/KnownTags.js.map @@ -0,0 +1 @@ +{"version":3,"file":"KnownTags.js","sourceRoot":"","sources":["../../../src/core/KnownTags.ts"],"names":[],"mappings":";;;AACA;;GAEG;AACU,QAAA,gBAAgB,GAAG;IAC9B,QAAQ,EAAE,UAAU;IACpB,WAAW,EAAE,aAAa;IAC1B,cAAc,EAAE,UAAU;IAC1B,KAAK,EAAE,OAAO;IACd,YAAY,EAAE,cAAc;IAC5B,kBAAkB,EAAE,cAAc;IAClC,GAAG,EAAE,KAAK;IACV,OAAO,EAAE,SAAS;CACV,CAAC;AAGX;;GAEG;AACU,QAAA,SAAS,GAAG;IACvB,SAAS,EAAE,WAAW;IACtB,eAAe,EAAE,iBAAiB;IAClC,gBAAgB,EAAE,iBAAiB;IACnC,kBAAkB,EAAE,oBAAoB;IACxC,uBAAuB,EAAE,yBAAyB;IAClD,uBAAuB,EAAE,yBAAyB;IAClD,eAAe,EAAE,iBAAiB;IAClC,sBAAsB,EAAE,wBAAwB;IAChD,kBAAkB,EAAE,oBAAoB;IACxC,yBAAyB,EAAE,2BAA2B;IACtD,UAAU,EAAE,YAAY;IACxB,aAAa,EAAE,eAAe;IAC9B,cAAc,EAAE,gBAAgB;IAChC,SAAS,EAAE,WAAW;IACtB,iBAAiB,EAAE,mBAAmB;IACtC,SAAS,EAAE,WAAW;IACtB,WAAW,EAAE,aAAa;IAC1B,cAAc,EAAE,gBAAgB;IAChC,cAAc,EAAE,gBAAgB;IAChC,YAAY,EAAE,cAAc;IAC5B,QAAQ,EAAE,mBAAmB;IAC7B,KAAK,EAAE,OAAO;CACN,CAAC"} \ No newline at end of file diff --git a/lib/cjs/core/Warp.js b/lib/cjs/core/Warp.js new file mode 100644 index 00000000..30aef284 --- /dev/null +++ b/lib/cjs/core/Warp.js @@ -0,0 +1,156 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Warp = void 0; +const HandlerBasedContract_1 = require("../contract/HandlerBasedContract"); +const PstContractImpl_1 = require("../contract/PstContractImpl"); +const Testing_1 = require("../contract/testing/Testing"); +const WarpBuilder_1 = require("./WarpBuilder"); +const WarpPlugin_1 = require("./WarpPlugin"); +const WarpFactory_1 = require("./WarpFactory"); +const LevelDbCache_1 = require("../cache/impl/LevelDbCache"); +/** + * The Warp "motherboard" ;-). + * This is the base class that supplies the implementation of the SmartWeave protocol + * Allows to plug-in different implementation of all the modules defined in the constructor. + * + * After being fully configured, it allows to "connect" to + * contract and perform operations on them (see {@link Contract}) + */ +class Warp { + get createContract() { + if (!this._createContract) { + if (this.plugins.has('deploy')) { + const deployPlugin = this.loadPlugin('deploy'); + this._createContract = deployPlugin.process(this); + } + else { + throw new Error(`In order to use CreateContract methods please attach DeployPlugin.`); + } + } + return this._createContract; + } + constructor(arweave, definitionLoader, interactionsLoader, executorFactory, stateEvaluator, environment = 'custom') { + this.arweave = arweave; + this.definitionLoader = definitionLoader; + this.interactionsLoader = interactionsLoader; + this.executorFactory = executorFactory; + this.stateEvaluator = stateEvaluator; + this.environment = environment; + this._gwUrl = WarpFactory_1.WARP_GW_URL; + this.plugins = new Map(); + this.testing = new Testing_1.Testing(arweave); + this.kvStorageFactory = (contractTxId) => { + return new LevelDbCache_1.LevelDbCache({ + inMemory: false, + dbLocation: `${WarpFactory_1.DEFAULT_LEVEL_DB_LOCATION}/kv/ldb/${contractTxId}` + }); + }; + this.eventTarget = new EventTarget(); + } + static builder(arweave, stateCache, environment) { + return new WarpBuilder_1.WarpBuilder(arweave, stateCache, environment); + } + /** + * Allows to connect to any contract using its transaction id. + * @param contractTxId + * @param callingContract + */ + contract(contractTxId, callingContract, innerCallData) { + return new HandlerBasedContract_1.HandlerBasedContract(contractTxId, this, callingContract, innerCallData); + } + async deploy(contractData, disableBundling) { + return await this.createContract.deploy(contractData, disableBundling); + } + async deployFromSourceTx(contractData, disableBundling) { + return await this.createContract.deployFromSourceTx(contractData, disableBundling); + } + async deployBundled(rawDataItem) { + return await this.createContract.deployBundled(rawDataItem); + } + async register(id, registerProvider) { + return await this.createContract.register(id, registerProvider); + } + async createSource(sourceData, wallet, disableBundling = false) { + return await this.createContract.createSource(sourceData, wallet, disableBundling); + } + async saveSource(src, disableBundling) { + return await this.createContract.saveSource(src, disableBundling); + } + /** + * Allows to connect to a contract that conforms to the Profit Sharing Token standard + * @param contractTxId + */ + pst(contractTxId) { + return new PstContractImpl_1.PstContractImpl(contractTxId, this); + } + useStateCache(stateCache) { + this.stateEvaluator.setCache(stateCache); + return this; + } + useContractCache(definition, src) { + this.definitionLoader.setSrcCache(src); + this.definitionLoader.setCache(definition); + return this; + } + use(plugin) { + const pluginType = plugin.type(); + if (!this.isPluginType(pluginType)) { + throw new Error(`Unknown plugin type ${pluginType}.`); + } + this.plugins.set(pluginType, plugin); + return this; + } + hasPlugin(type) { + return this.plugins.has(type); + } + matchPlugins(type) { + const pluginTypes = [...this.plugins.keys()]; + return pluginTypes.filter((p) => p.match(type)); + } + loadPlugin(type) { + if (!this.hasPlugin(type)) { + throw new Error(`Plugin ${type} not registered.`); + } + return this.plugins.get(type); + } + maybeLoadPlugin(type) { + if (!this.hasPlugin(type)) { + return null; + } + return this.plugins.get(type); + } + // Close cache connection + async close() { + return Promise.all([ + this.definitionLoader.getSrcCache().close(), + this.definitionLoader.getCache().close(), + this.stateEvaluator.getCache().close() + ]).then(); + } + async generateWallet() { + const wallet = await this.arweave.wallets.generate(); + if (await this.testing.isArlocal()) { + await this.testing.addFunds(wallet); + } + return { + jwk: wallet, + address: await this.arweave.wallets.jwkToAddress(wallet) + }; + } + isPluginType(value) { + return (WarpPlugin_1.knownWarpPlugins.includes(value) || WarpPlugin_1.knownWarpPluginsPartial.some((p) => value.match(p))); + } + useKVStorageFactory(factory) { + this.kvStorageFactory = factory; + return this; + } + useGwUrl(url) { + this._gwUrl = url; + return this; + } + gwUrl() { + return this._gwUrl; + } +} +exports.Warp = Warp; +//# sourceMappingURL=Warp.js.map \ No newline at end of file diff --git a/lib/cjs/core/Warp.js.map b/lib/cjs/core/Warp.js.map new file mode 100644 index 00000000..5a350b4b --- /dev/null +++ b/lib/cjs/core/Warp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Warp.js","sourceRoot":"","sources":["../../../src/core/Warp.ts"],"names":[],"mappings":";;;AAUA,2EAAwE;AAExE,iEAA8D;AAC9D,yDAA8D;AAM9D,+CAA4C;AAC5C,6CAMsB;AAKtB,+CAAuE;AACvE,6DAA0D;AAQ1D;;;;;;;GAOG;AAEH,MAAa,IAAI;IAIf,IAAY,cAAc;QACxB,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE;YACzB,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;gBAC9B,MAAM,YAAY,GAAG,IAAI,CAAC,UAAU,CAAuB,QAAQ,CAAC,CAAC;gBACrE,IAAI,CAAC,eAAe,GAAG,YAAY,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;aACnD;iBAAM;gBACL,MAAM,IAAI,KAAK,CAAC,oEAAoE,CAAC,CAAC;aACvF;SACF;QACD,OAAO,IAAI,CAAC,eAAe,CAAC;IAC9B,CAAC;IASD,YACW,OAAgB,EAChB,gBAAkC,EAClC,kBAAsC,EACtC,eAAqD,EACrD,cAA8B,EAC9B,cAA+B,QAAQ;QALvC,YAAO,GAAP,OAAO,CAAS;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AC,OAAO,CAAC,QAAQ,EAAE,CAAC;QAErD,IAAI,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE;YAClC,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;SACrC;QAED,OAAO;YACL,GAAG,EAAE,MAAM;YACX,OAAO,EAAE,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC;SACzD,CAAC;IACJ,CAAC;IAEO,YAAY,CAAC,KAAa;QAChC,OAAO,CACL,6BAAgB,CAAC,QAAQ,CAAC,KAA4B,CAAC,IAAI,oCAAuB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAC/G,CAAC;IACJ,CAAC;IAED,mBAAmB,CAAC,OAAyB;QAC3C,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,QAAQ,CAAC,GAAW;QAClB,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC;QAClB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK;QACH,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;AApLD,oBAoLC"} \ No newline at end of file diff --git a/lib/cjs/core/WarpBuilder.js b/lib/cjs/core/WarpBuilder.js new file mode 100644 index 00000000..8f13bd63 --- /dev/null +++ b/lib/cjs/core/WarpBuilder.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WarpBuilder = void 0; +const DebuggableExecutorFactor_1 = require("../plugins/DebuggableExecutorFactor"); +const ArweaveGatewayInteractionsLoader_1 = require("./modules/impl/ArweaveGatewayInteractionsLoader"); +const CacheableInteractionsLoader_1 = require("./modules/impl/CacheableInteractionsLoader"); +const ContractDefinitionLoader_1 = require("./modules/impl/ContractDefinitionLoader"); +const WarpGatewayContractDefinitionLoader_1 = require("./modules/impl/WarpGatewayContractDefinitionLoader"); +const WarpGatewayInteractionsLoader_1 = require("./modules/impl/WarpGatewayInteractionsLoader"); +const Warp_1 = require("./Warp"); +const LevelDbCache_1 = require("../cache/impl/LevelDbCache"); +class WarpBuilder { + constructor(_arweave, _stateCache, _environment = 'custom') { + this._arweave = _arweave; + this._stateCache = _stateCache; + this._environment = _environment; + } + setDefinitionLoader(value) { + this._definitionLoader = value; + return this; + } + setInteractionsLoader(value) { + this._interactionsLoader = value; + return this; + } + setExecutorFactory(value) { + this._executorFactory = value; + return this; + } + setStateEvaluator(value) { + this._stateEvaluator = value; + return this; + } + overwriteSource(sourceCode) { + if (this._executorFactory == null) { + throw new Error('Set base ExecutorFactory first'); + } + this._executorFactory = new DebuggableExecutorFactor_1.DebuggableExecutorFactory(this._executorFactory, sourceCode); + return this.build(); + } + useWarpGateway(gatewayOptions, cacheOptions) { + this._interactionsLoader = new CacheableInteractionsLoader_1.CacheableInteractionsLoader(new WarpGatewayInteractionsLoader_1.WarpGatewayInteractionsLoader(gatewayOptions.confirmationStatus, gatewayOptions.source)); + const contractsCache = new LevelDbCache_1.LevelDbCache({ + ...cacheOptions, + dbLocation: `${cacheOptions.dbLocation}/contracts` + }); + // Separate cache for sources to minimize duplicates + const sourceCache = new LevelDbCache_1.LevelDbCache({ + ...cacheOptions, + dbLocation: `${cacheOptions.dbLocation}/source` + }); + this._definitionLoader = new WarpGatewayContractDefinitionLoader_1.WarpGatewayContractDefinitionLoader(this._arweave, contractsCache, sourceCache, this._environment); + return this; + } + useArweaveGateway() { + this._definitionLoader = new ContractDefinitionLoader_1.ContractDefinitionLoader(this._arweave, this._environment); + this._interactionsLoader = new CacheableInteractionsLoader_1.CacheableInteractionsLoader(new ArweaveGatewayInteractionsLoader_1.ArweaveGatewayInteractionsLoader(this._arweave, this._environment)); + return this; + } + build() { + const warp = new Warp_1.Warp(this._arweave, this._definitionLoader, this._interactionsLoader, this._executorFactory, this._stateEvaluator, this._environment); + this._definitionLoader.warp = warp; + this._interactionsLoader.warp = warp; + return warp; + } +} +exports.WarpBuilder = WarpBuilder; +//# sourceMappingURL=WarpBuilder.js.map \ No newline at end of file diff --git a/lib/cjs/core/WarpBuilder.js.map b/lib/cjs/core/WarpBuilder.js.map new file mode 100644 index 00000000..40a022de --- /dev/null +++ b/lib/cjs/core/WarpBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpBuilder.js","sourceRoot":"","sources":["../../../src/core/WarpBuilder.ts"],"names":[],"mappings":";;;AACA,kFAAgF;AAGhF,sGAAmG;AACnG,4FAAyF;AACzF,sFAAmF;AAEnF,4GAAyG;AACzG,gGAA6F;AAG7F,iCAA+C;AAE/C,6DAA0D;AAI1D,MAAa,WAAW;IAMtB,YACmB,QAAiB,EACjB,WAAwD,EACxD,eAAgC,QAAQ;QAFxC,aAAQ,GAAR,QAAQ,CAAS;QACjB,gBAAW,GAAX,WAAW,CAA6C;QACxD,iBAAY,GAAZ,YAAY,CAA4B;IACxD,CAAC;IAEG,mBAAmB,CAAC,KAAuB;QAChD,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,qBAAqB,CAAC,KAAyB;QACpD,IAAI,CAAC,mBAAmB,GAAG,KAAK,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,kBAAkB,CAAC,KAA2C;QACnE,IAAI,CAAC,gBAAgB,GAAG,KAAK,CAAC;QAC9B,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,iBAAiB,CAAC,KAAqB;QAC5C,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,eAAe,CAAC,UAAqC;QAC1D,IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,EAAE;YACjC,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;SACnD;QACD,IAAI,CAAC,gBAAgB,GAAG,IA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F,IAAI,CAAC,iBAAiB,CAAC,IAAI,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,mBAAmB,CAAC,IAAI,GAAG,IAAI,CAAC;QAErC,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAxFD,kCAwFC"} \ No newline at end of file diff --git a/lib/cjs/core/WarpFactory.js b/lib/cjs/core/WarpFactory.js new file mode 100644 index 00000000..9edb8d96 --- /dev/null +++ b/lib/cjs/core/WarpFactory.js @@ -0,0 +1,113 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WarpFactory = exports.defaultCacheOptions = exports.DEFAULT_LEVEL_DB_LOCATION = exports.WARP_GW_URL = exports.defaultWarpGwOptions = void 0; +const arweave_1 = __importDefault(require("arweave")); +const LevelDbCache_1 = require("../cache/impl/LevelDbCache"); +const Evolve_1 = require("../plugins/Evolve"); +const CacheableStateEvaluator_1 = require("./modules/impl/CacheableStateEvaluator"); +const HandlerExecutorFactory_1 = require("./modules/impl/HandlerExecutorFactory"); +const WarpGatewayInteractionsLoader_1 = require("./modules/impl/WarpGatewayInteractionsLoader"); +const Warp_1 = require("./Warp"); +exports.defaultWarpGwOptions = { + confirmationStatus: { notCorrupted: true }, + source: WarpGatewayInteractionsLoader_1.SourceType.BOTH +}; +/** + * @Deprecated - will be removed soon, left for backwards compatibility with deploy plugin + */ +exports.WARP_GW_URL = 'https://gw.warp.cc'; +exports.DEFAULT_LEVEL_DB_LOCATION = './cache/warp'; +exports.defaultCacheOptions = { + inMemory: false, + dbLocation: exports.DEFAULT_LEVEL_DB_LOCATION +}; +/** + * A factory that simplifies the process of creating different versions of {@link Warp}. + * All versions use the {@link Evolve} plugin. + */ +class WarpFactory { + /** + * creates a Warp instance suitable for testing in a local environment + * (e.g. usually using ArLocal) + * @param arweave - an instance of Arweave + * @param cacheOptions - optional cache options. By default, the in-memory cache is used. + */ + static forLocal(port = 1984, arweave = arweave_1.default.init({ + host: 'localhost', + port: port, + protocol: 'http' + }), cacheOptions = { + ...exports.defaultCacheOptions, + inMemory: true + }) { + return this.customArweaveGw(arweave, cacheOptions, 'local'); + } + /** + * creates a Warp instance suitable for testing + * with Warp testnet (https://testnet.redstone.tools/) + */ + static forTestnet(cacheOptions = exports.defaultCacheOptions, useArweaveGw = false, arweave = arweave_1.default.init({ + host: 'arweave.net', + port: 443, + protocol: 'https' + })) { + if (useArweaveGw) { + return this.customArweaveGw(arweave, cacheOptions, 'testnet'); + } + else { + return this.customWarpGw(arweave, exports.defaultWarpGwOptions, cacheOptions, 'testnet'); + } + } + /** + * creates a Warp instance suitable for use with mainnet. + * By default, the Warp gateway (https://github.com/warp-contracts/gateway#warp-gateway) + * is being used for: + * 1. deploying contracts + * 2. writing new transactions through Warp Sequencer + * 3. loading contract interactions + * + * @param cacheOptions - cache options, defaults {@link defaultCacheOptions} + * @param useArweaveGw - use arweave.net gateway for deploying contracts, + * writing and loading interactions + * @param arweave - custom Arweave instance + */ + static forMainnet(cacheOptions = exports.defaultCacheOptions, useArweaveGw = false, arweave = arweave_1.default.init({ + host: 'arweave.net', + port: 443, + protocol: 'https' + })) { + if (useArweaveGw) { + return this.customArweaveGw(arweave, cacheOptions, 'mainnet'); + } + else { + return this.customWarpGw(arweave, exports.defaultWarpGwOptions, cacheOptions, 'mainnet'); + } + } + /** + * returns an instance of {@link WarpBuilder} that allows to fully customize the Warp instance. + * @param arweave + * @param cacheOptions + */ + static custom(arweave, cacheOptions, environment) { + const stateCache = new LevelDbCache_1.LevelDbCache({ + ...cacheOptions, + dbLocation: `${cacheOptions.dbLocation}/state` + }); + const executorFactory = new HandlerExecutorFactory_1.HandlerExecutorFactory(arweave); + const stateEvaluator = new CacheableStateEvaluator_1.CacheableStateEvaluator(arweave, stateCache, [new Evolve_1.Evolve()]); + return Warp_1.Warp.builder(arweave, stateCache, environment) + .setExecutorFactory(executorFactory) + .setStateEvaluator(stateEvaluator); + } + static customArweaveGw(arweave, cacheOptions = exports.defaultCacheOptions, environment) { + return this.custom(arweave, cacheOptions, environment).useArweaveGateway().build(); + } + static customWarpGw(arweave, gatewayOptions = exports.defaultWarpGwOptions, cacheOptions = exports.defaultCacheOptions, environment) { + return this.custom(arweave, cacheOptions, environment).useWarpGateway(gatewayOptions, cacheOptions).build(); + } +} +exports.WarpFactory = WarpFactory; +//# sourceMappingURL=WarpFactory.js.map \ No newline at end of file diff --git a/lib/cjs/core/WarpFactory.js.map b/lib/cjs/core/WarpFactory.js.map new file mode 100644 index 00000000..4fb49db4 --- /dev/null +++ b/lib/cjs/core/WarpFactory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpFactory.js","sourceRoot":"","sources":["../../../src/core/WarpFactory.ts"],"names":[],"mappings":";;;;;;AAAA,sDAA8B;AAC9B,6DAA0D;AAC1D,8CAA2C;AAC3C,oFAAiF;AACjF,kFAA+E;AAC/E,gGAA8F;AAE9F,iCAA+C;AAclC,QAAA,oBAAoB,GAAmB;IAClD,kBAAkB,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE;IAC1C,MAAM,EAAE,0CAAU,CAAC,IAAI;CACxB,CAAC;AAEF;;GAEG;AACU,QAAA,WAAW,GAAG,oBAAoB,CAAC;AAEnC,QAAA,yBAAyB,GAAG,cAAc,CAAC;AAE3C,QAAA,mBAAmB,GAAiB;IAC/C,QAAQ,EAAE,KAAK;IACf,UAAU,EAAE,iCAAyB;CACtC,CAAC;AAEF;;;GAGG;AACH,MAAa,WAAW;IACtB;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CACb,IAAI,GAAG,IAAI,EACX,OAAO,GAAG,iBAAO,CAAC,IAAI,CAAC;QACrB,IAAI,EAAE,WAAW;QACjB,IAAI,EAAE,IAAI;QACV,QAAQ,EAAE,MAAM;KACjB,CAAC,EACF,YAAY,GAAG;QACb,GAAG,2BAAmB;QACtB,QAAQ,EAAE,IAAI;KACf;QAED,OAAO,IAAI,CAAC,eA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,cAAc,GAAG,IAAI,iDAAuB,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC,IAAI,eAAM,EAAE,CAAC,CAAC,CAAC;QAExF,OAAO,WAAI,CAAC,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,WAAW,CAAC;aAClD,kBAAkB,CAAC,eAAe,CAAC;aACnC,iBAAiB,CAAC,cAAc,CAAC,CAAC;IACvC,CAAC;IAEO,MAAM,CAAC,eAAe,CAC5B,OAAgB,EAChB,eAA6B,2BAAmB,EAChD,WAA4B;QAE5B,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,YAAY,EAAE,WAAW,CAAC,CAAC,iBAAiB,EAAE,CAAC,KAAK,EAAE,CAAC;IACrF,CAAC;IAEO,MAAM,CAAC,YAAY,CACzB,OAAgB,EAChB,iBAAiC,4BAAoB,EACrD,eAA6B,2BAAmB,EAChD,WAA4B;QAE5B,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,YAAY,EAAE,WAAW,CAAC,CAAC,cAAc,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC,KAAK,EAAE,CAAC;IAC9G,CAAC;CACF;AAzGD,kCAyGC"} \ No newline at end of file diff --git a/lib/cjs/core/WarpFetchWrapper.js b/lib/cjs/core/WarpFetchWrapper.js new file mode 100644 index 00000000..a9021f33 --- /dev/null +++ b/lib/cjs/core/WarpFetchWrapper.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WarpFetchWrapper = void 0; +const LoggerFactory_1 = require("../logging/LoggerFactory"); +class WarpFetchWrapper { + constructor(warp) { + this.warp = warp; + this.name = 'WarpFetchWrapper'; + this.logger = LoggerFactory_1.LoggerFactory.INST.create(this.name); + this.warp = warp; + } + fetch(input, init) { + let fetchOptions; + if (this.warp.hasPlugin('fetch-options')) { + const fetchOptionsPlugin = this.warp.loadPlugin('fetch-options'); + try { + const updatedFetchOptions = fetchOptionsPlugin.process({ input, init: init || {} }); + fetchOptions = { ...init, ...updatedFetchOptions }; + } + catch (e) { + if (e.message) { + this.logger.error(e.message); + } + throw new Error(`Unable to process fetch options: ${e.message}`); + } + } + else { + fetchOptions = init; + } + return fetch(input, fetchOptions); + } +} +exports.WarpFetchWrapper = WarpFetchWrapper; +//# sourceMappingURL=WarpFetchWrapper.js.map \ No newline at end of file diff --git a/lib/cjs/core/WarpFetchWrapper.js.map b/lib/cjs/core/WarpFetchWrapper.js.map new file mode 100644 index 00000000..7c7603ba --- /dev/null +++ b/lib/cjs/core/WarpFetchWrapper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpFetchWrapper.js","sourceRoot":"","sources":["../../../src/core/WarpFetchWrapper.ts"],"names":[],"mappings":";;;AAAA,4DAAyD;AAQzD,MAAa,gBAAgB;IAI3B,YAAoB,IAAU;QAAV,SAAI,GAAJ,IAAI,CAAM;QAHb,SAAI,GAAG,kBAAkB,CAAC;QAC1B,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAG7D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,KAAK,CAAC,KAAwB,EAAE,IAAkB;QAChD,IAAI,YAAyB,CAAC;QAE9B,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,EAAE;YACxC,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAqC,eAAe,CAAC,CAAC;YACrG,IAAI;gBACF,MAAM,mBAAmB,GAAG,kBAAkB,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,IAAI,EAAE,EAAE,CAAC,CAAC;gBACpF,YAAY,GAAG,EAAE,GAAG,IAAI,EAAE,GAAG,mBAAmB,EAAE,CAAC;aACpD;YAAC,OAAO,CAAC,EAAE;gBACV,IAAI,CAAC,CAAC,OAAO,EAAE;oBACb,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;iBAC9B;gBACD,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;aAClE;SACF;aAAM;YACL,YAAY,GAAG,IAAI,CAAC;SACrB;QAED,OAAO,KAAK,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;IACpC,CAAC;CACF;AA5BD,4CA4BC"} \ No newline at end of file diff --git a/lib/cjs/core/WarpPlugin.js b/lib/cjs/core/WarpPlugin.js new file mode 100644 index 00000000..4e326b65 --- /dev/null +++ b/lib/cjs/core/WarpPlugin.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.knownWarpPlugins = exports.knownWarpPluginsPartial = void 0; +exports.knownWarpPluginsPartial = [`^smartweave-extension-`]; +exports.knownWarpPlugins = [ + 'evm-signature-verification', + 'subscription', + 'ivm-handler-api', + 'evaluation-progress', + 'fetch-options', + 'deploy', + 'contract-blacklist', + 'vm2', + 'vrf' +]; +//# sourceMappingURL=WarpPlugin.js.map \ No newline at end of file diff --git a/lib/cjs/core/WarpPlugin.js.map b/lib/cjs/core/WarpPlugin.js.map new file mode 100644 index 00000000..316cc9ae --- /dev/null +++ b/lib/cjs/core/WarpPlugin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpPlugin.js","sourceRoot":"","sources":["../../../src/core/WarpPlugin.ts"],"names":[],"mappings":";;;AAEa,QAAA,uBAAuB,GAAG,CAAC,wBAAwB,CAAU,CAAC;AAC9D,QAAA,gBAAgB,GAAG;IAC9B,4BAA4B;IAC5B,cAAc;IACd,iBAAiB;IACjB,qBAAqB;IACrB,eAAe;IACf,QAAQ;IACR,oBAAoB;IACpB,KAAK;IACL,KAAK;CACG,CAAC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/DefinitionLoader.js b/lib/cjs/core/modules/DefinitionLoader.js new file mode 100644 index 00000000..de3103ed --- /dev/null +++ b/lib/cjs/core/modules/DefinitionLoader.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=DefinitionLoader.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/DefinitionLoader.js.map b/lib/cjs/core/modules/DefinitionLoader.js.map new file mode 100644 index 00000000..7ffc1ca1 --- /dev/null +++ b/lib/cjs/core/modules/DefinitionLoader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DefinitionLoader.js","sourceRoot":"","sources":["../../../../src/core/modules/DefinitionLoader.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/core/modules/ExecutorFactory.js b/lib/cjs/core/modules/ExecutorFactory.js new file mode 100644 index 00000000..1c9b379a --- /dev/null +++ b/lib/cjs/core/modules/ExecutorFactory.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ExecutorFactory.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/ExecutorFactory.js.map b/lib/cjs/core/modules/ExecutorFactory.js.map new file mode 100644 index 00000000..53e8d7f1 --- /dev/null +++ b/lib/cjs/core/modules/ExecutorFactory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ExecutorFactory.js","sourceRoot":"","sources":["../../../../src/core/modules/ExecutorFactory.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/core/modules/InteractionsLoader.js b/lib/cjs/core/modules/InteractionsLoader.js new file mode 100644 index 00000000..fcf8e256 --- /dev/null +++ b/lib/cjs/core/modules/InteractionsLoader.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=InteractionsLoader.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/InteractionsLoader.js.map b/lib/cjs/core/modules/InteractionsLoader.js.map new file mode 100644 index 00000000..00ec4e35 --- /dev/null +++ b/lib/cjs/core/modules/InteractionsLoader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"InteractionsLoader.js","sourceRoot":"","sources":["../../../../src/core/modules/InteractionsLoader.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/core/modules/InteractionsSorter.js b/lib/cjs/core/modules/InteractionsSorter.js new file mode 100644 index 00000000..4607662d --- /dev/null +++ b/lib/cjs/core/modules/InteractionsSorter.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=InteractionsSorter.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/InteractionsSorter.js.map b/lib/cjs/core/modules/InteractionsSorter.js.map new file mode 100644 index 00000000..92f42a7b --- /dev/null +++ b/lib/cjs/core/modules/InteractionsSorter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"InteractionsSorter.js","sourceRoot":"","sources":["../../../../src/core/modules/InteractionsSorter.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/core/modules/StateEvaluator.js b/lib/cjs/core/modules/StateEvaluator.js new file mode 100644 index 00000000..f4e08b46 --- /dev/null +++ b/lib/cjs/core/modules/StateEvaluator.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InteractionCompleteEvent = exports.CustomEvent = exports.DefaultEvaluationOptions = exports.EvalStateResult = void 0; +const WarpGatewayInteractionsLoader_1 = require("./impl/WarpGatewayInteractionsLoader"); +class EvalStateResult { + constructor(state, validity, errorMessages) { + this.state = state; + this.validity = validity; + this.errorMessages = errorMessages; + } +} +exports.EvalStateResult = EvalStateResult; +class DefaultEvaluationOptions { + constructor() { + // default = true - still cannot decide whether true or false should be the default. + // "false" may lead to some fairly simple attacks on contract, if the contract + // does not properly validate input data. + // "true" may lead to wrongly calculated state, even without noticing the problem + // (e.g. when using unsafe client and Arweave does not respond properly for a while) + this.ignoreExceptions = true; + this.waitForConfirmation = false; + this.updateCacheForEachInteraction = false; + this.internalWrites = false; + this.maxCallDepth = 7; // your lucky number... + this.maxInteractionEvaluationTimeSeconds = 60; + this.stackTrace = { + saveState: false + }; + this.sequencerUrl = `https://d1o5nlqr4okus2.cloudfront.net/`; + this.gasLimit = Number.MAX_SAFE_INTEGER; + this.sourceType = WarpGatewayInteractionsLoader_1.SourceType.BOTH; + this.unsafeClient = 'throw'; + this.allowBigInt = false; + this.walletBalanceUrl = 'http://nyc-1.dev.arweave.net:1984/'; + this.mineArLocalBlocks = true; + this.throwOnInternalWriteError = true; + this.cacheEveryNInteractions = -1; + this.useKVStorage = false; + this.remoteStateSyncEnabled = false; + this.remoteStateSyncSource = 'https://dre-1.warp.cc/contract'; + this.useConstructor = false; + this.whitelistSources = []; + } +} +exports.DefaultEvaluationOptions = DefaultEvaluationOptions; +// https://github.com/nodejs/node/issues/40678 duh... +class CustomEvent extends Event { + constructor(message, data) { + super(message, data); + this.detail = data.detail; + } +} +exports.CustomEvent = CustomEvent; +class InteractionCompleteEvent { + constructor(contractTxId, sortKey, transactionId, caller, input, blockTimestamp, blockHeight, data // eslint-disable-next-line @typescript-eslint/no-empty-function + ) { + this.contractTxId = contractTxId; + this.sortKey = sortKey; + this.transactionId = transactionId; + this.caller = caller; + this.input = input; + this.blockTimestamp = blockTimestamp; + this.blockHeight = blockHeight; + this.data = data; + } +} +exports.InteractionCompleteEvent = InteractionCompleteEvent; +//# sourceMappingURL=StateEvaluator.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/StateEvaluator.js.map b/lib/cjs/core/modules/StateEvaluator.js.map new file mode 100644 index 00000000..895e0609 --- /dev/null +++ b/lib/cjs/core/modules/StateEvaluator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StateEvaluator.js","sourceRoot":"","sources":["../../../../src/core/modules/StateEvaluator.ts"],"names":[],"mappings":";;;AAGA,wFAAkE;AA4FlE,MAAa,eAAe;IAC1B,YACW,KAAY,EACZ,QAAiC,EACjC,aAAqC;QAFrC,UAAK,GAAL,KAAK,CAAO;QACZ,aAAQ,GAAR,QAAQ,CAAyB;QACjC,kBAAa,GAAb,aAAa,CA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,cAAsB,EACtB,WAAmB,EACnB,IAAO,CAAC,gEAAgE;;QAPxE,iBAAY,GAAZ,YAAY,CAAQ;QACpB,YAAO,GAAP,OAAO,CAAQ;QACf,kBAAa,GAAb,aAAa,CAAQ;QACrB,WAAM,GAAN,MAAM,CAAQ;QACd,UAAK,GAAL,KAAK,CAAO;QACZ,mBAAc,GAAd,cAAc,CAAQ;QACtB,gBAAW,GAAX,WAAW,CAAQ;QACnB,SAAI,GAAJ,IAAI,CAAG;IACf,CAAC;CACL;AAXD,4DAWC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/ArweaveGQLTxsFetcher.js b/lib/cjs/core/modules/impl/ArweaveGQLTxsFetcher.js new file mode 100644 index 00000000..abe70c06 --- /dev/null +++ b/lib/cjs/core/modules/impl/ArweaveGQLTxsFetcher.js @@ -0,0 +1,148 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ArweaveGQLTxsFetcher = void 0; +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +const ArweaveWrapper_1 = require("../../../utils/ArweaveWrapper"); +const utils_1 = require("../../../utils/utils"); +const Benchmark_1 = require("../../../logging/Benchmark"); +const KnownTags_1 = require("../../KnownTags"); +const TRANSACTIONS_QUERY = `query Transactions($tags: [TagFilter!]!, $blockFilter: BlockFilter!, $first: Int!, $after: String) { + transactions(tags: $tags, block: $blockFilter, first: $first, sort: HEIGHT_ASC, after: $after) { + pageInfo { + hasNextPage + } + edges { + node { + id + owner { address } + recipient + tags { + name + value + } + block { + height + id + timestamp + } + fee { winston } + quantity { winston } + parent { id } + bundledIn { id } + } + cursor + } + } + }`; +const TRANSACTION_QUERY = `query Transaction($id: ID!) { + transaction(id: $id) { + id + owner { address, key } + recipient + tags { + name + value + } + block { + height + id + timestamp + } + fee { winston, ar } + quantity { winston, ar } + bundledIn { id } + parent{ id } + signature + } +}`; +// this is a query for old/legacy bundler format +const TRANSACTION_QUERY_USING_TAG = `query Transactions($tags: [TagFilter!]!) { + transactions(tags: $tags) { + edges { + node { + id + owner { address, key } + recipient + tags { + name + value + } + block { + height + id + timestamp + } + fee { winston, ar } + quantity { winston, ar } + parent { id } + bundledIn { id } + signature + } + } + } +}`; +const RETRY_TIMEOUT = 30 * 1000; +const MAX_REQUEST = 100; +/** + * Query all transactions from arweave gateway + */ +class ArweaveGQLTxsFetcher { + constructor(warp) { + this.warp = warp; + this.logger = LoggerFactory_1.LoggerFactory.INST.create(ArweaveGQLTxsFetcher.name); + this.arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(warp); + } + async transaction(transactionId) { + const response = await this.fetch(TRANSACTION_QUERY, { id: transactionId }); + return response.transaction; + } + /** + * Fetches transaction stored using legacy bundling format. + */ + async transactionUsingUploaderTag(transactionId) { + const txTag = { + name: KnownTags_1.WARP_TAGS.UPLOADER_TX_ID, + values: [transactionId] + }; + const response = (await this.fetch(TRANSACTION_QUERY_USING_TAG, { tags: [txTag] })) + .transactions; + if (response.edges.length < 1) { + throw new Error(`No interaction with tag ${KnownTags_1.WARP_TAGS.UPLOADER_TX_ID}:${transactionId}`); + } + return response.edges[0].node; + } + async transactions(variables) { + let pageResult = (await this.fetch(TRANSACTIONS_QUERY, variables)).transactions; + const edges = [...pageResult.edges]; + while (pageResult.pageInfo.hasNextPage) { + const cursor = pageResult.edges[MAX_REQUEST - 1].cursor; + const newVariables = { + ...variables, + after: cursor + }; + pageResult = (await this.fetch(TRANSACTIONS_QUERY, newVariables)).transactions; + edges.push(...pageResult.edges); + } + return edges; + } + async fetch(gqlQuery, variables) { + const benchmark = Benchmark_1.Benchmark.measure(); + let response = await this.arweaveWrapper.gql(gqlQuery, variables); + this.logger.debug('GQL page load:', benchmark.elapsed()); + while (response.status === 403) { + this.logger.warn(`GQL rate limiting, waiting ${RETRY_TIMEOUT}ms before next try.`); + await (0, utils_1.sleep)(RETRY_TIMEOUT); + response = await this.arweaveWrapper.gql(gqlQuery, variables); + } + if (response.status !== 200) { + throw new Error(`Unable to retrieve transactions. Arweave gateway responded with status ${response.status}.`); + } + if (response.data.errors) { + this.logger.error(response.data.errors); + throw new Error('Error while fetching arweave transactions'); + } + return response.data.data; + } +} +exports.ArweaveGQLTxsFetcher = ArweaveGQLTxsFetcher; +//# sourceMappingURL=ArweaveGQLTxsFetcher.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/ArweaveGQLTxsFetcher.js.map b/lib/cjs/core/modules/impl/ArweaveGQLTxsFetcher.js.map new file mode 100644 index 00000000..1843cda2 --- /dev/null +++ b/lib/cjs/core/modules/impl/ArweaveGQLTxsFetcher.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveGQLTxsFetcher.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ArweaveGQLTxsFetcher.ts"],"names":[],"mappings":";;;AACA,kEAA+D;AAC/D,kEAA+D;AAC/D,gDAA6C;AAC7C,0DAAuD;AAEvD,+CAA4C;AAE5C,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;IA2BvB,CAAC;AAEL,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;EAoBxB,CAAC;AAEH,gDAAgD;AAChD,MAAM,2BAA2B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;EAwBlC,CAAC;AAmBH,MAAM,aAAa,GAAG,EAAE,GAAG,IAAI,CAAC;AAChC,MAAM,WAAW,GAAG,GAAG,CAAC;AAExB;;GAEG;AACH,MAAa,oBAAoB;IAI/B,YAA+B,IAAU;QAAV,SAAI,GAAJ,IAAI,CAAM;QAFxB,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC;QAG7E,IAAI,CAAC,cAAc,GAAG,IAAI,+BAAc,CAAC,IAAI,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,aAAqB;QACrC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,KAAK,CAAyB,iBAAiB,EAAE,EA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K,CAAC,CAAC;SACjC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAEO,KAAK,CAAC,KAAK,CAAc,QAAgB,EAAE,SAAkB;QACnE,MAAM,SAAS,GAAG,qBAAS,CAAC,OAAO,EAAE,CAAC;QACtC,IAAI,QAAQ,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;QAClE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC;QAEzD,OAAO,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE;YAC9B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,8BAA8B,aAAa,qBAAqB,CAAC,CAAC;YAEnF,MAAM,IAAA,aAAK,EAAC,aAAa,CAAC,CAAC;YAE3B,QAAQ,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;SAC/D;QAED,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE;YAC3B,MAAM,IAAI,KAAK,CAAC,0EAA0E,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;SAC/G;QAED,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE;YACxB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;SAC9D;QAED,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC;IAC5B,CAAC;CACF;AAxED,oDAwEC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.js b/lib/cjs/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.js new file mode 100644 index 00000000..1ed6d82e --- /dev/null +++ b/lib/cjs/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.js @@ -0,0 +1,165 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ArweaveGatewayBundledContractDefinitionLoader = void 0; +const ContractDefinition_1 = require("../../../core/ContractDefinition"); +const KnownTags_1 = require("../../KnownTags"); +const Benchmark_1 = require("../../../logging/Benchmark"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +const ArweaveWrapper_1 = require("../../../utils/ArweaveWrapper"); +const ArweaveGQLTxsFetcher_1 = require("./ArweaveGQLTxsFetcher"); +const WasmSrc_1 = require("./wasm/WasmSrc"); +const arweave_1 = __importDefault(require("arweave")); +function getTagValue(tags, tagName, orDefault = undefined) { + const tag = tags.find(({ name }) => name === tagName); + return tag ? tag.value : orDefault; +} +class ArweaveGatewayBundledContractDefinitionLoader { + constructor(env) { + this.env = env; + this.logger = LoggerFactory_1.LoggerFactory.INST.create(ArweaveGatewayBundledContractDefinitionLoader.name); + } + async load(contractTxId, evolvedSrcTxId) { + const benchmark = Benchmark_1.Benchmark.measure(); + const contractTx = await this.fetchContractTx(contractTxId); + this.logger.debug('Contract tx fetch time', benchmark.elapsed()); + const owner = contractTx.owner.address; + const contractSrcTxId = evolvedSrcTxId + ? evolvedSrcTxId + : getTagValue(contractTx.tags, KnownTags_1.SMART_WEAVE_TAGS.CONTRACT_SRC_TX_ID); + const testnet = getTagValue(contractTx.tags, KnownTags_1.WARP_TAGS.WARP_TESTNET) || null; + if (testnet && this.env !== 'testnet') { + throw new Error('Trying to use testnet contract in a non-testnet env. Use the "forTestnet" factory method.'); + } + if (!testnet && this.env === 'testnet') { + throw new Error('Trying to use non-testnet contract in a testnet env.'); + } + const minFee = getTagValue(contractTx.tags, KnownTags_1.SMART_WEAVE_TAGS.MIN_FEE); + const manifest = getTagValue(contractTx.tags, KnownTags_1.WARP_TAGS.MANIFEST) + ? JSON.parse(getTagValue(contractTx.tags, KnownTags_1.WARP_TAGS.MANIFEST)) + : null; + this.logger.debug('Tags decoding', benchmark.elapsed()); + const rawInitState = await this.evalInitialState(contractTx); + this.logger.debug('init state', rawInitState); + const initState = JSON.parse(rawInitState); + this.logger.debug('Parsing src and init state', benchmark.elapsed()); + const { src, srcBinary, srcWasmLang, contractType, metadata, srcTx } = await this.loadContractSource(contractSrcTxId); + const contractDefinition = { + txId: contractTxId, + srcTxId: contractSrcTxId, + src, + srcBinary, + srcWasmLang, + initState, + minFee, + owner, + contractType, + metadata, + manifest, + contractTx: await this.convertToWarpCompatibleContractTx(contractTx), + srcTx: await this.convertToWarpCompatibleContractTx(srcTx), + testnet + }; + this.logger.info(`Contract definition loaded in: ${benchmark.elapsed()}`); + return contractDefinition; + } + async fetchContractTx(contractTxId) { + const txUsingId = await this.arweaveTransactions.transaction(contractTxId); + if (txUsingId == null) { + return await this.arweaveTransactions.transactionUsingUploaderTag(contractTxId); + } + return txUsingId; + } + async convertToWarpCompatibleContractTx(gqlTransaction) { + const tags = gqlTransaction.tags.map(({ name, value }) => ({ + name: Buffer.from(name).toString('base64url'), + value: Buffer.from(value).toString('base64url') + })); + return { + tags, + owner: gqlTransaction.owner.key, + target: gqlTransaction.recipient, + signature: gqlTransaction.signature, + data: (await this.arweaveWrapper.txData(gqlTransaction.id)).toString('base64url') + }; + } + async loadContractSource(srcTxId) { + const benchmark = Benchmark_1.Benchmark.measure(); + const contractSrcTx = await this.fetchContractTx(srcTxId); + const srcContentType = getTagValue(contractSrcTx.tags, KnownTags_1.SMART_WEAVE_TAGS.CONTENT_TYPE); + if (!ContractDefinition_1.SUPPORTED_SRC_CONTENT_TYPES.includes(srcContentType)) { + throw new Error(`Contract source content type ${srcContentType} not supported`); + } + const contractType = srcContentType === 'application/javascript' ? 'js' : 'wasm'; + const src = await this.contractSource(contractSrcTx, contractType); + let srcWasmLang; + let wasmSrc; + let srcMetaData; + if (contractType == 'wasm') { + wasmSrc = new WasmSrc_1.WasmSrc(src); + srcWasmLang = getTagValue(contractSrcTx.tags, KnownTags_1.WARP_TAGS.WASM_LANG); + if (!srcWasmLang) { + throw new Error(`Wasm lang not set for wasm contract src ${contractSrcTx.id}`); + } + srcMetaData = JSON.parse(getTagValue(contractSrcTx.tags, KnownTags_1.WARP_TAGS.WASM_META)); + } + this.logger.debug('Contract src tx load', benchmark.elapsed()); + benchmark.reset(); + return { + src: contractType == 'js' ? src : null, + srcBinary: contractType == 'wasm' ? wasmSrc.wasmBinary() : null, + srcWasmLang, + contractType, + metadata: srcMetaData, + srcTx: contractSrcTx + }; + } + async contractSource(contractSrcTx, contractType) { + const uploaderId = getTagValue(contractSrcTx.tags, KnownTags_1.WARP_TAGS.UPLOADER_TX_ID); + if (uploaderId != null) { + const txString = await this.arweaveWrapper.txDataString(contractSrcTx.id); + if (contractType === 'wasm') { + throw new Error('WASM contracts in legacy format are not supported using AR GW'); + } + return arweave_1.default.utils.b64UrlToString(JSON.parse(txString).data); + } + return contractType === 'js' + ? await this.arweaveWrapper.txDataString(contractSrcTx.id) + : await this.arweaveWrapper.txData(contractSrcTx.id); + } + async evalInitialState(contractTx) { + if (getTagValue(contractTx.tags, KnownTags_1.WARP_TAGS.INIT_STATE)) { + return getTagValue(contractTx.tags, KnownTags_1.WARP_TAGS.INIT_STATE); + } + else if (getTagValue(contractTx.tags, KnownTags_1.WARP_TAGS.INIT_STATE_TX)) { + const stateTX = getTagValue(contractTx.tags, KnownTags_1.WARP_TAGS.INIT_STATE_TX); + return this.arweaveWrapper.txDataString(stateTX); + } + else { + return this.arweaveWrapper.txDataString(contractTx.id); + } + } + setCache() { + throw new Error('Method not implemented.'); + } + setSrcCache() { + throw new Error('Method not implemented.'); + } + getCache() { + throw new Error('Method not implemented.'); + } + getSrcCache() { + throw new Error('Method not implemented.'); + } + type() { + return 'arweave'; + } + set warp(warp) { + this.arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(warp); + this.arweaveTransactions = new ArweaveGQLTxsFetcher_1.ArweaveGQLTxsFetcher(warp); + } +} +exports.ArweaveGatewayBundledContractDefinitionLoader = ArweaveGatewayBundledContractDefinitionLoader; +//# sourceMappingURL=ArweaveGatewayBundledContractDefinitionLoader.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.js.map b/lib/cjs/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.js.map new file mode 100644 index 00000000..83d9a93f --- /dev/null +++ b/lib/cjs/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveGatewayBundledContractDefinitionLoader.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.ts"],"names":[],"mappings":";;;;;;AAGA,yEAM0C;AAC1C,+CAA8D;AAE9D,0DAAuD;AACvD,kEAA+D;AAC/D,kEAA+D;AAG/D,iEAA8D;AAC9D,4CAAyC;AACzC,sDAA8B;AAE9B,SAAS,WAAW,CAAC,IAAuB,EAAE,OAAe,EAAE,SAAS,GAAG,SAAS;IAClF,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC;IACtD,OAAO,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACrC,CAAC;AAED,MAAa,6CAA6C;IAKxD,YAA6B,GAAoB;QAApB,QAAG,GAAH,GAAG,CAAiB;QAFhC,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,6CAA6C,CAAC,IAAI,CAAC,CAAC;IAEpD,CAAC;IAErD,KAAK,CAAC,IAAI,CAAQ,YAAoB,EAAE,cAAuB;QAC7D,MAAM,SAAS,GAAG,qBAAS,CAAC,OAAO,EAAE,CAAC;QACtC,MAAM,UAAU,GAAmB,MAAM,IAAI,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC;QA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,CAAC;CACF;AA5KD,sGA4KC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/ArweaveGatewayBundledInteractionLoader.js b/lib/cjs/core/modules/impl/ArweaveGatewayBundledInteractionLoader.js new file mode 100644 index 00000000..be013e14 --- /dev/null +++ b/lib/cjs/core/modules/impl/ArweaveGatewayBundledInteractionLoader.js @@ -0,0 +1,212 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ArweaveGatewayBundledInteractionLoader = void 0; +const KnownTags_1 = require("../../KnownTags"); +const Benchmark_1 = require("../../../logging/Benchmark"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +const ArweaveWrapper_1 = require("../../../utils/ArweaveWrapper"); +const LexicographicalInteractionsSorter_1 = require("./LexicographicalInteractionsSorter"); +const ArweaveGQLTxsFetcher_1 = require("./ArweaveGQLTxsFetcher"); +const utils_1 = require("../../../utils/utils"); +const TagsParser_1 = require("./TagsParser"); +const MAX_REQUEST = 100; +// SortKey.blockHeight is block height +// at which interaction was sent to bundler +// it can be actually finalized in later block +// we assume that this maximal "delay" +const EMPIRIC_BUNDLR_FINALITY_TIME = 100; +// a height from which the last sort key value is being set by the sequencer +const LAST_SORT_KEY_MIN_HEIGHT = 1057409; +class ArweaveGatewayBundledInteractionLoader { + constructor(arweave, environment) { + this.arweave = arweave; + this.environment = environment; + this.logger = LoggerFactory_1.LoggerFactory.INST.create(ArweaveGatewayBundledInteractionLoader.name); + this.tagsParser = new TagsParser_1.TagsParser(); + this.sorter = new LexicographicalInteractionsSorter_1.LexicographicalInteractionsSorter(arweave); + } + async load(contractId, fromSortKey, toSortKey, evaluationOptions) { + this.logger.debug('Loading interactions for', { contractId, fromSortKey, toSortKey }); + const fromBlockHeight = this.sorter.extractBlockHeight(fromSortKey) || 0; + const toBlockHeight = this.sorter.extractBlockHeight(toSortKey) || (await this.currentBlockHeight()); + const mainTransactionsQuery = { + tags: [ + { + name: KnownTags_1.SMART_WEAVE_TAGS.APP_NAME, + values: ['SmartWeaveAction'] + }, + { + name: KnownTags_1.SMART_WEAVE_TAGS.CONTRACT_TX_ID, + values: [contractId] + }, + { + name: KnownTags_1.WARP_TAGS.SEQUENCER, + values: ['RedStone'] + } + ], + blockFilter: { + min: fromBlockHeight, + max: toBlockHeight + EMPIRIC_BUNDLR_FINALITY_TIME + }, + first: MAX_REQUEST + }; + const loadingBenchmark = Benchmark_1.Benchmark.measure(); + let interactions = await this.arweaveFetcher.transactions(mainTransactionsQuery); + if (evaluationOptions.internalWrites) { + interactions = await this.appendInternalWriteInteractions(contractId, fromBlockHeight, toBlockHeight, interactions); + } + loadingBenchmark.stop(); + this.logger.debug('All loaded interactions:', { + from: fromSortKey, + to: toSortKey, + loaded: interactions.length, + time: loadingBenchmark.elapsed() + }); + // add sortKey from sequencer tag + interactions.forEach((interaction) => { + var _a, _b, _c, _d; + interaction.node.sortKey = + (_a = interaction.node.sortKey) !== null && _a !== void 0 ? _a : (_d = (_c = (_b = interaction.node) === null || _b === void 0 ? void 0 : _b.tags) === null || _c === void 0 ? void 0 : _c.find((tag) => tag.name === KnownTags_1.WARP_TAGS.SEQUENCER_SORT_KEY)) === null || _d === void 0 ? void 0 : _d.value; + }); + const sortedInteractions = await this.sorter.sort(interactions); + const isLocalOrTestnetEnv = this.environment === 'local' || this.environment === 'testnet'; + const vrfPlugin = this._warp.maybeLoadPlugin('vrf'); + return sortedInteractions + .filter((interaction) => this.isNewerThenSortKeyBlockHeight(interaction)) + .filter((interaction) => this.isSortKeyInBounds(fromSortKey, toSortKey, interaction)) + .map((interaction) => this.attachSequencerDataToInteraction(interaction)) + .map((interaction) => this.maybeAddMockVrf(isLocalOrTestnetEnv, interaction, vrfPlugin)) + .map((interaction, index, allInteractions) => this.verifySortKeyIntegrity(interaction, index, allInteractions)) + .map(({ node: interaction }) => interaction); + } + verifySortKeyIntegrity(interaction, index, allInteractions) { + var _a; + if (index !== 0) { + const prevInteraction = allInteractions[index - 1]; + const nextInteraction = allInteractions[index]; + this.logger.debug(`prev: ${prevInteraction.node.id} | current: ${nextInteraction.node.id}`); + if (nextInteraction.node.block.height <= LAST_SORT_KEY_MIN_HEIGHT) { + return interaction; + } + if (((_a = nextInteraction.node.lastSortKey) === null || _a === void 0 ? void 0 : _a.split(',')[1]) === LexicographicalInteractionsSorter_1.defaultArweaveMs) { + // cannot verify this one + return interaction; + } + if (prevInteraction.node.source === 'redstone-sequencer' && + prevInteraction.node.sortKey !== nextInteraction.node.lastSortKey) { + this.logger.warn(`Interaction loading error: interaction ${nextInteraction.node.id} lastSortKey is not pointing on prev interaction ${prevInteraction.node.id}`); + } + } + return interaction; + } + isSortKeyInBounds(fromSortKey, toSortKey, interaction) { + if (fromSortKey && toSortKey) { + return (interaction.node.sortKey.localeCompare(fromSortKey) > 0 && + interaction.node.sortKey.localeCompare(toSortKey) <= 0); + } + else if (fromSortKey && !toSortKey) { + return interaction.node.sortKey.localeCompare(fromSortKey) > 0; + } + else if (!fromSortKey && toSortKey) { + return interaction.node.sortKey.localeCompare(toSortKey) <= 0; + } + return true; + } + attachSequencerDataToInteraction(interaction) { + const extractTag = (tagName) => { var _a; return (_a = interaction.node.tags.find((tag) => tag.name === tagName)) === null || _a === void 0 ? void 0 : _a.value; }; + const sequencerTxId = extractTag(KnownTags_1.WARP_TAGS.SEQUENCER_TX_ID); + const sequencerOwner = extractTag(KnownTags_1.WARP_TAGS.SEQUENCER_OWNER); + const sequencerBlockId = extractTag(KnownTags_1.WARP_TAGS.SEQUENCER_BLOCK_ID); + const sequencerBlockHeight = extractTag(KnownTags_1.WARP_TAGS.SEQUENCER_BLOCK_HEIGHT); + const sequencerLastSortKey = extractTag(KnownTags_1.WARP_TAGS.SEQUENCER_PREV_SORT_KEY) || extractTag(KnownTags_1.WARP_TAGS.SEQUENCER_LAST_SORT_KEY); + const sequencerSortKey = extractTag(KnownTags_1.WARP_TAGS.SEQUENCER_SORT_KEY); + // this field was added in sequencer from 15.03.2023 + const sequencerBlockTimestamp = extractTag(KnownTags_1.WARP_TAGS.SEQUENCER_BLOCK_TIMESTAMP); + const parsedBlockHeight = (0, utils_1.safeParseInt)(sequencerBlockHeight); + if (!sequencerOwner || + !sequencerBlockId || + !sequencerBlockHeight || + // note: old sequencer transactions do not have last sort key set + (!sequencerLastSortKey && parsedBlockHeight > LAST_SORT_KEY_MIN_HEIGHT) || + !sequencerTxId || + !sequencerSortKey) { + throw Error(`Interaction ${interaction.node.id} is not sequenced by sequencer aborting. Only Sequenced transactions are supported by loader ${ArweaveGatewayBundledInteractionLoader.name}`); + } + return { + ...interaction, + node: { + ...interaction.node, + owner: { address: sequencerOwner, key: null }, + block: { + ...interaction.node.block, + height: (0, utils_1.safeParseInt)(sequencerBlockHeight), + id: sequencerBlockId, + timestamp: sequencerBlockTimestamp ? (0, utils_1.safeParseInt)(sequencerBlockTimestamp) : interaction.node.block.timestamp + }, + sortKey: sequencerSortKey, + lastSortKey: sequencerLastSortKey, + id: sequencerTxId, + source: 'redstone-sequencer' + } + }; + } + async appendInternalWriteInteractions(contractId, fromBlockHeight, toBlockHeight, interactions) { + const innerWritesVariables = { + tags: [ + { + name: KnownTags_1.WARP_TAGS.INTERACT_WRITE, + values: [contractId] + } + ], + blockFilter: { + min: fromBlockHeight, + max: toBlockHeight + }, + first: MAX_REQUEST + }; + const innerWritesInteractions = await this.arweaveFetcher.transactions(innerWritesVariables); + this.logger.debug('Inner writes interactions length:', innerWritesInteractions.length); + interactions = interactions.concat(innerWritesInteractions); + return interactions; + } + maybeAddMockVrf(isLocalOrTestnetEnv, interaction, vrfPlugin) { + if (isLocalOrTestnetEnv) { + if (this.tagsParser.hasVrfTag(interaction.node)) { + if (vrfPlugin) { + interaction.node.vrf = vrfPlugin.process().generateMockVrf(interaction.node.sortKey); + } + else { + this.logger.warn('Cannot generate mock vrf for interaction - no "warp-contracts-plugin-vrf" attached!'); + } + } + } + return interaction; + } + isNewerThenSortKeyBlockHeight(interaction) { + if (interaction.node.sortKey) { + const blockHeightSortKey = interaction.node.sortKey.split(',')[0]; + const sendToBundlerBlockHeight = Number.parseInt(blockHeightSortKey); + const finalizedBlockHeight = Number(interaction.node.block.height); + const blockHeightDiff = finalizedBlockHeight - sendToBundlerBlockHeight; + return blockHeightDiff >= 0; + } + return true; + } + async currentBlockHeight() { + const info = await this.arweaveWrapper.info(); + return info.height; + } + type() { + return 'arweave'; + } + clearCache() { + // noop + } + set warp(warp) { + this.arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(warp); + this.arweaveFetcher = new ArweaveGQLTxsFetcher_1.ArweaveGQLTxsFetcher(warp); + this._warp = warp; + } +} +exports.ArweaveGatewayBundledInteractionLoader = ArweaveGatewayBundledInteractionLoader; +//# sourceMappingURL=ArweaveGatewayBundledInteractionLoader.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/ArweaveGatewayBundledInteractionLoader.js.map b/lib/cjs/core/modules/impl/ArweaveGatewayBundledInteractionLoader.js.map new file mode 100644 index 00000000..e4b120af --- /dev/null +++ b/lib/cjs/core/modules/impl/ArweaveGatewayBundledInteractionLoader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveGatewayBundledInteractionLoader.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ArweaveGatewayBundledInteractionLoader.ts"],"names":[],"mappings":";;;AACA,+CAAwE;AAExE,0DAAuD;AACvD,kEAA+D;AAC/D,kEAA+D;AAI/D,2FAA0G;AAG1G,iEAA8D;AAC9D,gDAAoD;AAEpD,6CAA0C;AAE1C,MAAM,WAAW,GAAG,GAAG,CAAC;AACxB,sCAAsC;AACtC,2CAA2C;AAC3C,8CAA8C;AAC9C,sCAAsC;AACtC,MAAM,4BAA4B,GAAG,GAAG,CAAC;AAmBzC,4EAA4E;AAC5E,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAEzC,MAAa,sCAAsC;IASjD,YAA+B,OAAgB,EAAmB,WAA4B;QAA/D,YAAO,GAAP,OAAO,CAAS;QAAmB,gBAAW,GAAX,WAAW,CAAiB;QAR7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CAAC,CAAC;YAElE,MAAM,wBAAwB,GAAG,MAAM,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC;YACrE,MAAM,oBAAoB,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YACnE,MAAM,eAAe,GAAG,oBAAoB,GAAG,wBAAwB,CAAC;YACxE,OAAO,eAAe,IAAI,CAAC,CAAC;SAC7B;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,KAAK,CAAC,kBAAkB;QAC9B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;QAC9C,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,IAAI;QACF,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,UAAU;QACR,OAAO;IACT,CAAC;IAED,IAAI,IAAI,CAAC,IAAU;QACjB,IAAI,CAAC,cAAc,GAAG,IAAI,+BAAc,CAAC,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,cAAc,GAAG,IAAI,2CAAoB,CAAC,IAAI,CAAC,CAAC;QACrD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;CACF;AA7PD,wFA6PC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/ArweaveGatewayInteractionsLoader.js b/lib/cjs/core/modules/impl/ArweaveGatewayInteractionsLoader.js new file mode 100644 index 00000000..71f5110b --- /dev/null +++ b/lib/cjs/core/modules/impl/ArweaveGatewayInteractionsLoader.js @@ -0,0 +1,124 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ArweaveGatewayInteractionsLoader = exports.bundledTxsFilter = void 0; +const KnownTags_1 = require("../../KnownTags"); +const Benchmark_1 = require("../../../logging/Benchmark"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +const LexicographicalInteractionsSorter_1 = require("./LexicographicalInteractionsSorter"); +const ArweaveGQLTxsFetcher_1 = require("./ArweaveGQLTxsFetcher"); +const TagsParser_1 = require("./TagsParser"); +const MAX_REQUEST = 100; +function bundledTxsFilter(tx) { + var _a, _b; + return !((_a = tx.node.parent) === null || _a === void 0 ? void 0 : _a.id) && !((_b = tx.node.bundledIn) === null || _b === void 0 ? void 0 : _b.id); +} +exports.bundledTxsFilter = bundledTxsFilter; +class ArweaveGatewayInteractionsLoader { + constructor(arweave, environment) { + this.arweave = arweave; + this.environment = environment; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('ArweaveGatewayInteractionsLoader'); + this.tagsParser = new TagsParser_1.TagsParser(); + this.sorter = new LexicographicalInteractionsSorter_1.LexicographicalInteractionsSorter(arweave); + } + async load(contractId, fromSortKey, toSortKey, evaluationOptions) { + this.logger.debug('Loading interactions for', { contractId, fromSortKey, toSortKey }); + const fromBlockHeight = this.sorter.extractBlockHeight(fromSortKey); + const toBlockHeight = this.sorter.extractBlockHeight(toSortKey); + const mainTransactionsQuery = { + tags: [ + { + name: KnownTags_1.SMART_WEAVE_TAGS.APP_NAME, + values: ['SmartWeaveAction'] + }, + { + name: KnownTags_1.SMART_WEAVE_TAGS.CONTRACT_TX_ID, + values: [contractId] + } + ], + blockFilter: { + min: fromBlockHeight, + max: toBlockHeight + }, + first: MAX_REQUEST + }; + const loadingBenchmark = Benchmark_1.Benchmark.measure(); + let interactions = (await this.arweaveTransactionQuery.transactions(mainTransactionsQuery)).filter(bundledTxsFilter); + loadingBenchmark.stop(); + if (evaluationOptions.internalWrites) { + const innerWritesVariables = { + tags: [ + { + name: KnownTags_1.WARP_TAGS.INTERACT_WRITE, + values: [contractId] + } + ], + blockFilter: { + min: fromBlockHeight, + max: toBlockHeight + }, + first: MAX_REQUEST + }; + const innerWritesInteractions = (await this.arweaveTransactionQuery.transactions(innerWritesVariables)).filter(bundledTxsFilter); + this.logger.debug('Inner writes interactions length:', innerWritesInteractions.length); + interactions = interactions.concat(innerWritesInteractions); + } + /** + * Because the behaviour of the Arweave gateway in case of passing null to min/max block height + * in the gql query params is unknown (https://discord.com/channels/908759493943394334/908766823342801007/983643012947144725) + * - we're removing all the interactions, that have null block data. + */ + interactions = interactions.filter((i) => i.node.block && i.node.block.id && i.node.block.height); + // note: this operation adds the "sortKey" to the interactions + let sortedInteractions = await this.sorter.sort(interactions); + if (fromSortKey && toSortKey) { + sortedInteractions = sortedInteractions.filter((i) => { + return i.node.sortKey.localeCompare(fromSortKey) > 0 && i.node.sortKey.localeCompare(toSortKey) <= 0; + }); + } + else if (fromSortKey && !toSortKey) { + sortedInteractions = sortedInteractions.filter((i) => { + return i.node.sortKey.localeCompare(fromSortKey) > 0; + }); + } + else if (!fromSortKey && toSortKey) { + sortedInteractions = sortedInteractions.filter((i) => { + return i.node.sortKey.localeCompare(toSortKey) <= 0; + }); + } + this.logger.debug('All loaded interactions:', { + from: fromSortKey, + to: toSortKey, + loaded: sortedInteractions.length, + time: loadingBenchmark.elapsed() + }); + const isLocalOrTestnetEnv = this.environment === 'local' || this.environment === 'testnet'; + const vrfPlugin = this._warp.maybeLoadPlugin('vrf'); + return sortedInteractions.map((i) => { + const interaction = i.node; + if (isLocalOrTestnetEnv) { + if (this.tagsParser.hasVrfTag(interaction)) { + if (vrfPlugin) { + interaction.vrf = vrfPlugin.process().generateMockVrf(interaction.sortKey); + } + else { + this.logger.warn('Cannot generate mock vrf for interaction - no "warp-contracts-plugin-vrf" attached!'); + } + } + } + return interaction; + }); + } + type() { + return 'arweave'; + } + clearCache() { + // noop + } + set warp(warp) { + this.arweaveTransactionQuery = new ArweaveGQLTxsFetcher_1.ArweaveGQLTxsFetcher(warp); + this._warp = warp; + } +} +exports.ArweaveGatewayInteractionsLoader = ArweaveGatewayInteractionsLoader; +//# sourceMappingURL=ArweaveGatewayInteractionsLoader.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/ArweaveGatewayInteractionsLoader.js.map b/lib/cjs/core/modules/impl/ArweaveGatewayInteractionsLoader.js.map new file mode 100644 index 00000000..0d01ba9e --- /dev/null +++ b/lib/cjs/core/modules/impl/ArweaveGatewayInteractionsLoader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveGatewayInteractionsLoader.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ArweaveGatewayInteractionsLoader.ts"],"names":[],"mappings":";;;AACA,+CAA8D;AAE9D,0DAAuD;AACvD,kEAA+D;AAI/D,2FAAwF;AAExF,iEAAuF;AAEvF,6CAA0C;AAE1C,MAAM,WAAW,GAAG,GAAG,CAAC;AAExB,SAAgB,gBAAgB,CAAC,EAAoB;;IACnD,OAAO,CAAC,CAAA,MAAA,EAAE,CAAC,IAAI,CAAC,MAAM,0CAAE,EAAE,CAAA,IAAI,CAAC,CAAA,MAAA,EAAE,CAAC,IAAI,CAAC,SAAS,0CAAE,EAAE,CAAA,CAAC;AACvD,CAAC;AAFD,4CAEC;AAED,MAAa,gCAAgC;IAQ3C,YAA+B,OAAgB,EAAmB,WAA4B;QAA/D,YAAO,GAAP,OAAO,CAAS;QAAmB,gBAAW,GAAX,WAAW,CAAiB;QAP7E,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,kCAAkC,CAAC,CAAC;QAKvE,eAAU,GAAG,IAAI,uBAAU,EAAE,CAAC;QAG7C,IAAI,CAAC,MAAM,GAAG,IAAI,qEAAiC,CAAC,OAAO,CAAC,CAAC;IAC/D,CAAC;IAED,KAAK,CAAC,IAAI,CACR,UAAkB,EAClB,WAAoB,EACpB,SAAkB,EAClB,iBAAqC;QAErC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,0BAA0B,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,CAAC,CAAC;QAEtF,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QACpE,MAAM,aAAa,GAAG,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC;QAEhE,MAAM,qBAAqB,GAA4B;YACrD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AAI,CAAC,WAAW,KAAK,OAAO,IAAI,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC;QAC3F,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,eAAe,CAA2B,KAAK,CAAC,CAAC;QAE9E,OAAO,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YAClC,MAAM,WAAW,GAAG,CAAC,CAAC,IAAI,CAAC;YAC3B,IAAI,mBAAmB,EAAE;gBACvB,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE;oBAC1C,IAAI,SAAS,EAAE;wBACb,WAAW,CAAC,GAAG,GAAG,SAAS,CAAC,OAAO,EAAE,CAAC,eAAe,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;qBAC5E;yBAAM;wBACL,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,qFAAqF,CAAC,CAAC;qBACzG;iBACF;aACF;YAED,OAAO,WAAW,CAAC;QACrB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,IAAI;QACF,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,UAAU;QACR,OAAO;IACT,CAAC;IAED,IAAI,IAAI,CAAC,IAAU;QACjB,IAAI,CAAC,uBAAuB,GAAG,IAAI,2CAAoB,CAAC,IAAI,CAAC,CAAC;QAC9D,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;CACF;AAnID,4EAmIC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/CacheableInteractionsLoader.js b/lib/cjs/core/modules/impl/CacheableInteractionsLoader.js new file mode 100644 index 00000000..f0a0fe78 --- /dev/null +++ b/lib/cjs/core/modules/impl/CacheableInteractionsLoader.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CacheableInteractionsLoader = void 0; +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +class CacheableInteractionsLoader { + constructor(delegate) { + this.delegate = delegate; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('CacheableInteractionsLoader'); + this.interactionsCache = new Map(); + } + async load(contractTxId, fromSortKey, toSortKey, evaluationOptions) { + this.logger.debug(`Loading interactions for`, { + contractTxId, + fromSortKey, + toSortKey + }); + if (!this.interactionsCache.has(contractTxId)) { + const interactions = await this.delegate.load(contractTxId, fromSortKey, toSortKey, evaluationOptions); + if (interactions.length) { + this.interactionsCache.set(contractTxId, interactions); + } + return interactions; + } + else { + const cachedInteractions = this.interactionsCache.get(contractTxId); + if (cachedInteractions === null || cachedInteractions === void 0 ? void 0 : cachedInteractions.length) { + const lastCachedKey = cachedInteractions[cachedInteractions.length - 1].sortKey; + if (lastCachedKey.localeCompare(toSortKey) < 0) { + const missingInteractions = await this.delegate.load(contractTxId, lastCachedKey, toSortKey, evaluationOptions); + const allInteractions = cachedInteractions.concat(missingInteractions); + this.interactionsCache.set(contractTxId, allInteractions); + return allInteractions; + } + } + return cachedInteractions; + } + } + type() { + return this.delegate.type(); + } + clearCache() { + this.interactionsCache.clear(); + } + set warp(warp) { + this.delegate.warp = warp; + } +} +exports.CacheableInteractionsLoader = CacheableInteractionsLoader; +//# sourceMappingURL=CacheableInteractionsLoader.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/CacheableInteractionsLoader.js.map b/lib/cjs/core/modules/impl/CacheableInteractionsLoader.js.map new file mode 100644 index 00000000..56adbf40 --- /dev/null +++ b/lib/cjs/core/modules/impl/CacheableInteractionsLoader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"CacheableInteractionsLoader.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/CacheableInteractionsLoader.ts"],"names":[],"mappings":";;;AACA,kEAA+D;AAK/D,MAAa,2BAA2B;IAItC,YAA6B,QAA4B;QAA5B,aAAQ,GAAR,QAAQ,CAAoB;QAHxC,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAC,CAAC;QAClE,sBAAiB,GAAoC,IAAI,GAA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H,CAAC;IAED,IAAI;QACF,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC9B,CAAC;IAED,UAAU;QACR,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC;IACjC,CAAC;IAED,IAAI,IAAI,CAAC,IAAU;QACjB,IAAI,CAAC,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC;IAC5B,CAAC;CACF;AAxDD,kEAwDC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/CacheableStateEvaluator.js b/lib/cjs/core/modules/impl/CacheableStateEvaluator.js new file mode 100644 index 00000000..60ae481e --- /dev/null +++ b/lib/cjs/core/modules/impl/CacheableStateEvaluator.js @@ -0,0 +1,154 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CacheableStateEvaluator = void 0; +const SortKeyCache_1 = require("../../../cache/SortKeyCache"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +const utils_1 = require("../../../utils/utils"); +const StateEvaluator_1 = require("../StateEvaluator"); +const DefaultStateEvaluator_1 = require("./DefaultStateEvaluator"); +const LexicographicalInteractionsSorter_1 = require("./LexicographicalInteractionsSorter"); +/** + * An implementation of DefaultStateEvaluator that adds caching capabilities. + * + * The main responsibility of this class is to compute whether there are + * any interaction transactions, for which the state hasn't been evaluated yet - + * if so - it generates a list of such transactions and evaluates the state + * for them - taking as an input state the last cached state. + */ +class CacheableStateEvaluator extends DefaultStateEvaluator_1.DefaultStateEvaluator { + constructor(arweave, cache, executionContextModifiers = []) { + super(arweave, executionContextModifiers); + this.cache = cache; + this.cLogger = LoggerFactory_1.LoggerFactory.INST.create('CacheableStateEvaluator'); + } + async eval(executionContext) { + var _a, _b, _c, _d; + const { cachedState, contract } = executionContext; + const missingInteractions = executionContext.sortedInteractions; + if (cachedState && cachedState.sortKey == executionContext.requestedSortKey && !(missingInteractions === null || missingInteractions === void 0 ? void 0 : missingInteractions.length)) { + this.cLogger.info(`Exact cache hit for sortKey ${(_a = executionContext === null || executionContext === void 0 ? void 0 : executionContext.contractDefinition) === null || _a === void 0 ? void 0 : _a.txId}:${cachedState.sortKey}`); + (_b = executionContext.handler) === null || _b === void 0 ? void 0 : _b.initState(cachedState.cachedValue.state); + return cachedState; + } + const contractTxId = executionContext.contractDefinition.txId; + // sanity check... + if (!contractTxId) { + throw new Error('Contract tx id not set in the execution context'); + } + const isFirstEvaluation = cachedState == null; + let baseState = isFirstEvaluation ? executionContext.contractDefinition.initState : cachedState.cachedValue.state; + const baseValidity = isFirstEvaluation ? {} : cachedState.cachedValue.validity; + const baseErrorMessages = isFirstEvaluation ? {} : cachedState.cachedValue.errorMessages; + if (isFirstEvaluation) { + baseState = await executionContext.handler.maybeCallStateConstructor(executionContext.contractDefinition.initState, executionContext); + await contract.interactionState().commitKV(); + } + if (missingInteractions.length == 0) { + this.cLogger.info(`No missing interactions ${contractTxId}`); + if (isFirstEvaluation) { + (_c = executionContext.handler) === null || _c === void 0 ? void 0 : _c.initState(baseState); + this.cLogger.debug('Inserting initial state into cache'); + const stateToCache = new StateEvaluator_1.EvalStateResult(baseState, {}, {}); + // no real sort-key - as we're returning the initial state + await this.cache.put(new SortKeyCache_1.CacheKey(contractTxId, LexicographicalInteractionsSorter_1.genesisSortKey), stateToCache); + return new SortKeyCache_1.SortKeyCacheResult(LexicographicalInteractionsSorter_1.genesisSortKey, stateToCache); + } + else { + (_d = executionContext.handler) === null || _d === void 0 ? void 0 : _d.initState(cachedState.cachedValue.state); + return cachedState; + } + } + // eval state for the missing transactions - starting from the latest value from cache. + return await this.doReadState(missingInteractions, new StateEvaluator_1.EvalStateResult(baseState, baseValidity, baseErrorMessages || {}), executionContext); + } + async onStateEvaluated(transaction, executionContext, state) { + const contractTxId = executionContext.contractDefinition.txId; + this.cLogger.debug(`${(0, utils_1.indent)(executionContext.contract.callDepth())}onStateEvaluated: cache update for contract ${contractTxId} [${transaction.sortKey}]`); + await this.putInCache(contractTxId, transaction, state); + } + async onStateUpdate(transaction, executionContext, state, force = false) { + if (executionContext.evaluationOptions.updateCacheForEachInteraction || force) { + this.cLogger.debug(`onStateUpdate: cache update for contract ${executionContext.contractDefinition.txId} [${transaction.sortKey}]`, { + contract: executionContext.contractDefinition.txId, + state: state.state, + sortKey: transaction.sortKey + }); + await this.putInCache(executionContext.contractDefinition.txId, transaction, state); + } + } + async latestAvailableState(contractTxId, sortKey) { + this.cLogger.debug('Searching for', { contractTxId, sortKey }); + if (sortKey) { + const stateCache = (await this.cache.getLessOrEqual(contractTxId, sortKey)); + if (stateCache) { + this.cLogger.debug(`Latest available state at ${contractTxId}: ${stateCache.sortKey}`); + } + return stateCache; + } + else { + return (await this.cache.getLast(contractTxId)); + } + } + async onInternalWriteStateUpdate(transaction, contractTxId, state) { + this.cLogger.debug('Internal write state update:', { + sortKey: transaction.sortKey, + dry: transaction.dry, + contractTxId, + state: state.state + }); + await this.putInCache(contractTxId, transaction, state); + } + async onContractCall(transaction, executionContext, state) { + var _a; + if (((_a = executionContext.sortedInteractions) === null || _a === void 0 ? void 0 : _a.length) == 0) { + return; + } + const txIndex = executionContext.sortedInteractions.indexOf(transaction); + if (txIndex < 1) { + return; + } + await this.putInCache(executionContext.contractDefinition.txId, executionContext.sortedInteractions[txIndex - 1], state); + } + async putInCache(contractTxId, transaction, state) { + if (transaction.dry) { + return; + } + if (transaction.confirmationStatus !== undefined && transaction.confirmationStatus !== 'confirmed') { + return; + } + const stateToCache = new StateEvaluator_1.EvalStateResult(state.state, state.validity, state.errorMessages || {}); + this.cLogger.debug('Putting into cache', { + contractTxId, + transaction: transaction.id, + sortKey: transaction.sortKey, + dry: transaction.dry + }); + await this.cache.put(new SortKeyCache_1.CacheKey(contractTxId, transaction.sortKey), stateToCache); + } + async syncState(contractTxId, sortKey, state, validity) { + const stateToCache = new StateEvaluator_1.EvalStateResult(state, validity, {}); + await this.cache.put(new SortKeyCache_1.CacheKey(contractTxId, sortKey), stateToCache); + return new SortKeyCache_1.SortKeyCacheResult(sortKey, stateToCache); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async dumpCache() { + return await this.cache.dump(); + } + async internalWriteState(contractTxId, sortKey) { + return (await this.cache.get(new SortKeyCache_1.CacheKey(contractTxId, sortKey))); + } + async hasContractCached(contractTxId) { + return (await this.cache.getLast(contractTxId)) != null; + } + async lastCachedSortKey() { + return await this.cache.getLastSortKey(); + } + setCache(cache) { + this.cache = cache; + } + getCache() { + return this.cache; + } +} +exports.CacheableStateEvaluator = CacheableStateEvaluator; +//# sourceMappingURL=CacheableStateEvaluator.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/CacheableStateEvaluator.js.map b/lib/cjs/core/modules/impl/CacheableStateEvaluator.js.map new file mode 100644 index 00000000..cac93a44 --- /dev/null +++ b/lib/cjs/core/modules/impl/CacheableStateEvaluator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"CacheableStateEvaluator.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/CacheableStateEvaluator.ts"],"names":[],"mappings":";;;AACA,8DAA2E;AAI3E,kEAA+D;AAC/D,gDAA8C;AAC9C,sDAAoD;AACpD,mEAAgE;AAEhE,2FAAqE;AAGrE;;;;;;;GAOG;AACH,MAAa,uBAAwB,SAAQ,6CAAqB;IAGhE,YACE,OAAgB,EACR,KAAkD,EAC1D,4BAAwD,EAAE;QAE1D,KAAK,CAAC,OAAO,EAAE,yBAAyB,CAAC,CAAC;QAHlC,UAAK,GAAL,KAAK,CAA6C;QAJ3C,YAAO,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,yBAAyB,CAAC,CAAC;IAQhF,CAAC;IAED,KAAK,CAAC,IAAI,CACR,gBAA4D;;QAE5D,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,GAAG,gBAAgB,CAAC;QACnD,MAAM,mBAAmB,GAAG,gBAAgB,CAAC,kBAAkB,CAAC;QAEhE,IAAI,WAAW,IAAI,WAAW,CAAC,OAAO,IAAI,gBAAgB,CAAC,gBAAgB,IA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s/core/modules/impl/ContractDefinitionLoader.js b/lib/cjs/core/modules/impl/ContractDefinitionLoader.js new file mode 100644 index 00000000..ad5ea3a9 --- /dev/null +++ b/lib/cjs/core/modules/impl/ContractDefinitionLoader.js @@ -0,0 +1,137 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContractDefinitionLoader = void 0; +const ContractDefinition_1 = require("../../../core/ContractDefinition"); +const KnownTags_1 = require("../../KnownTags"); +const Benchmark_1 = require("../../../logging/Benchmark"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +const ArweaveWrapper_1 = require("../../../utils/ArweaveWrapper"); +const TagsParser_1 = require("./TagsParser"); +const WasmSrc_1 = require("./wasm/WasmSrc"); +class ContractDefinitionLoader { + constructor(arweave, env) { + this.arweave = arweave; + this.env = env; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('ContractDefinitionLoader'); + this.tagsParser = new TagsParser_1.TagsParser(); + } + async load(contractTxId, evolvedSrcTxId) { + const benchmark = Benchmark_1.Benchmark.measure(); + const contract = await this.doLoad(contractTxId, evolvedSrcTxId); + this.logger.info(`Contract definition loaded in: ${benchmark.elapsed()}`); + return contract; + } + async doLoad(contractTxId, forcedSrcTxId) { + const benchmark = Benchmark_1.Benchmark.measure(); + const contractTx = await this.arweaveWrapper.tx(contractTxId); + const owner = await this.arweave.wallets.ownerToAddress(contractTx.owner); + this.logger.debug('Contract tx and owner', benchmark.elapsed()); + benchmark.reset(); + const contractSrcTxId = forcedSrcTxId + ? forcedSrcTxId + : this.tagsParser.getTag(contractTx, KnownTags_1.SMART_WEAVE_TAGS.CONTRACT_SRC_TX_ID); + const testnet = this.tagsParser.getTag(contractTx, KnownTags_1.WARP_TAGS.WARP_TESTNET) || null; + if (testnet && this.env !== 'testnet') { + throw new Error('Trying to use testnet contract in a non-testnet env. Use the "forTestnet" factory method.'); + } + if (!testnet && this.env === 'testnet') { + throw new Error('Trying to use non-testnet contract in a testnet env.'); + } + const minFee = this.tagsParser.getTag(contractTx, KnownTags_1.SMART_WEAVE_TAGS.MIN_FEE); + let manifest = null; + const rawManifest = this.tagsParser.getTag(contractTx, KnownTags_1.WARP_TAGS.MANIFEST); + if (rawManifest) { + manifest = JSON.parse(rawManifest); + } + this.logger.debug('Tags decoding', benchmark.elapsed()); + benchmark.reset(); + const s = await this.evalInitialState(contractTx); + this.logger.debug('init state', s); + const initState = JSON.parse(s); + this.logger.debug('Parsing src and init state', benchmark.elapsed()); + const { src, srcBinary, srcWasmLang, contractType, metadata, srcTx } = await this.loadContractSource(contractSrcTxId); + return { + txId: contractTxId, + srcTxId: contractSrcTxId, + src, + srcBinary, + srcWasmLang, + initState, + minFee, + owner, + contractType, + metadata, + manifest, + contractTx: contractTx.toJSON(), + srcTx, + testnet + }; + } + async loadContractSource(contractSrcTxId) { + const benchmark = Benchmark_1.Benchmark.measure(); + const contractSrcTx = await this.arweaveWrapper.tx(contractSrcTxId); + const srcContentType = this.tagsParser.getTag(contractSrcTx, KnownTags_1.SMART_WEAVE_TAGS.CONTENT_TYPE); + if (!ContractDefinition_1.SUPPORTED_SRC_CONTENT_TYPES.includes(srcContentType)) { + throw new Error(`Contract source content type ${srcContentType} not supported`); + } + const contractType = srcContentType == 'application/javascript' ? 'js' : 'wasm'; + const src = contractType == 'js' + ? await this.arweaveWrapper.txDataString(contractSrcTxId) + : await this.arweaveWrapper.txData(contractSrcTxId); + let srcWasmLang; + let wasmSrc; + let srcMetaData; + if (contractType == 'wasm') { + wasmSrc = new WasmSrc_1.WasmSrc(src); + srcWasmLang = this.tagsParser.getTag(contractSrcTx, KnownTags_1.WARP_TAGS.WASM_LANG); + if (!srcWasmLang) { + throw new Error(`Wasm lang not set for wasm contract src ${contractSrcTxId}`); + } + srcMetaData = JSON.parse(this.tagsParser.getTag(contractSrcTx, KnownTags_1.WARP_TAGS.WASM_META)); + } + this.logger.debug('Contract src tx load', benchmark.elapsed()); + benchmark.reset(); + return { + src: contractType == 'js' ? src : null, + srcBinary: contractType == 'wasm' ? wasmSrc.wasmBinary() : null, + srcWasmLang, + contractType, + metadata: srcMetaData, + srcTx: contractSrcTx.toJSON() + }; + } + async evalInitialState(contractTx) { + if (this.tagsParser.getTag(contractTx, KnownTags_1.WARP_TAGS.INIT_STATE)) { + return this.tagsParser.getTag(contractTx, KnownTags_1.WARP_TAGS.INIT_STATE); + } + else if (this.tagsParser.getTag(contractTx, KnownTags_1.WARP_TAGS.INIT_STATE_TX)) { + const stateTX = this.tagsParser.getTag(contractTx, KnownTags_1.WARP_TAGS.INIT_STATE_TX); + return this.arweaveWrapper.txDataString(stateTX); + } + else { + return this.arweaveWrapper.txDataString(contractTx.id); + } + } + type() { + return 'arweave'; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + setCache(cache) { + throw new Error('No cache implemented for this loader'); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + setSrcCache(cache) { + throw new Error('No cache implemented for this loader'); + } + getCache() { + throw new Error('No cache implemented for this loader'); + } + getSrcCache() { + throw new Error('No cache implemented for this loader'); + } + set warp(warp) { + this.arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(warp); + } +} +exports.ContractDefinitionLoader = ContractDefinitionLoader; +//# sourceMappingURL=ContractDefinitionLoader.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/ContractDefinitionLoader.js.map b/lib/cjs/core/modules/impl/ContractDefinitionLoader.js.map new file mode 100644 index 00000000..b560ec6f --- /dev/null +++ b/lib/cjs/core/modules/impl/ContractDefinitionLoader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ContractDefinitionLoader.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ContractDefinitionLoader.ts"],"names":[],"mappings":";;;AAEA,yEAM0C;AAC1C,+CAA8D;AAC9D,0DAAuD;AACvD,kEAA+D;AAC/D,kEAA+D;AAG/D,6CAA0C;AAC1C,4CAAyC;AAKzC,MAAa,wBAAwB;IAMnC,YAA6B,OAAgB,EAAmB,GAAoB;QAAvD,YAAO,GAAP,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D;IAC7D,QAAQ,CAAC,KAAqD;QAC5D,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC1D,CAAC;IAED,6DAA6D;IAC7D,WAAW,CAAC,KAAkC;QAC5C,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC1D,CAAC;IAED,QAAQ;QACN,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC1D,CAAC;IAED,WAAW;QACT,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC1D,CAAC;IAED,IAAI,IAAI,CAAC,IAAU;QACjB,IAAI,CAAC,cAAc,GAAG,IAAI,+BAAc,CAAC,IAAI,CAAC,CAAC;IACjD,CAAC;CACF;AApJD,4DAoJC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/DefaultStateEvaluator.js b/lib/cjs/core/modules/impl/DefaultStateEvaluator.js new file mode 100644 index 00000000..a21f7d7f --- /dev/null +++ b/lib/cjs/core/modules/impl/DefaultStateEvaluator.js @@ -0,0 +1,303 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefaultStateEvaluator = void 0; +const SortKeyCache_1 = require("../../../cache/SortKeyCache"); +const Benchmark_1 = require("../../../logging/Benchmark"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +const utils_1 = require("../../../utils/utils"); +const StateEvaluator_1 = require("../StateEvaluator"); +const TagsParser_1 = require("./TagsParser"); +const JsHandlerApi_1 = require("./handler/JsHandlerApi"); +/** + * This class contains the base functionality of evaluating the contracts state - according + * to the SmartWeave protocol. + * Marked as abstract - as without help of any cache - the evaluation in real-life applications + * would be really slow - so using this class without any caching ({@link CacheableStateEvaluator}) + * mechanism built on top makes no sense. + */ +class DefaultStateEvaluator { + constructor(arweave, executionContextModifiers = []) { + this.arweave = arweave; + this.executionContextModifiers = executionContextModifiers; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('DefaultStateEvaluator'); + this.tagsParser = new TagsParser_1.TagsParser(); + } + async eval(executionContext) { + return this.doReadState(executionContext.sortedInteractions, new StateEvaluator_1.EvalStateResult(executionContext.contractDefinition.initState, {}, {}), executionContext); + } + async doReadState(missingInteractions, baseState, executionContext) { + var _a; + const { ignoreExceptions, stackTrace, internalWrites } = executionContext.evaluationOptions; + const { contract, contractDefinition, sortedInteractions, warp } = executionContext; + let currentState = baseState.state; + let currentSortKey = null; + const validity = baseState.validity; + const errorMessages = baseState.errorMessages; + // TODO: opt - reuse wasm handlers + executionContext === null || executionContext === void 0 ? void 0 : executionContext.handler.initState(currentState); + const depth = executionContext.contract.callDepth(); + this.logger.debug(`${(0, utils_1.indent)(depth)}Evaluating state for ${contractDefinition.txId} [${missingInteractions.length} non-cached of ${sortedInteractions.length} all]`); + let errorMessage = null; + let lastConfirmedTxState = null; + const missingInteractionsLength = missingInteractions.length; + const evmSignatureVerificationPlugin = warp.maybeLoadPlugin('evm-signature-verification'); + const progressPlugin = warp.maybeLoadPlugin('evaluation-progress'); + const vrfPlugin = warp.maybeLoadPlugin('vrf'); + let shouldBreakAfterEvolve = false; + for (let i = 0; i < missingInteractionsLength; i++) { + if (shouldBreakAfterEvolve) { + break; + } + const missingInteraction = missingInteractions[i]; + currentSortKey = missingInteraction.sortKey; + contract + .interactionState() + .setInitial(contract.txId(), new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages), currentSortKey); + const singleInteractionBenchmark = Benchmark_1.Benchmark.measure(); + if (missingInteraction.vrf) { + if (!vrfPlugin) { + this.logger.warn('Cannot verify vrf for interaction - no "warp-contracts-plugin-vrf" attached!'); + } + else { + if (!vrfPlugin.process().verify(missingInteraction.vrf, missingInteraction.sortKey)) { + throw new Error('Vrf verification failed.'); + } + } + } + if (evmSignatureVerificationPlugin && this.tagsParser.isEvmSigned(missingInteraction)) { + try { + if (!(await evmSignatureVerificationPlugin.process(missingInteraction))) { + this.logger.warn(`Interaction ${missingInteraction.id} was not verified, skipping.`); + continue; + } + } + catch (e) { + this.logger.error(e); + continue; + } + } + this.logger.debug(`${(0, utils_1.indent)(depth)}[${contractDefinition.txId}][${missingInteraction.id}][${missingInteraction.block.height}]: ${missingInteractions.indexOf(missingInteraction) + 1}/${missingInteractions.length} [of all:${sortedInteractions.length}]`); + const isInteractWrite = this.tagsParser.isInteractWrite(missingInteraction, contractDefinition.txId); + // other contract makes write ("writing contract") on THIS contract + if (isInteractWrite && internalWrites) { + // evaluating txId of the contract that is writing on THIS contract + const writingContractTxId = this.tagsParser.getContractTag(missingInteraction); + this.logger.debug(`${(0, utils_1.indent)(depth)}Internal Write - Loading writing contract`, writingContractTxId); + const interactionCall = contract + .getCallStack() + .addInteractionData({ interaction: null, interactionTx: missingInteraction }); + // creating a Contract instance for the "writing" contract + const writingContract = warp.contract(writingContractTxId, executionContext.contract, { + callingInteraction: missingInteraction, + callType: 'read' + }); + this.logger.debug(`${(0, utils_1.indent)(depth)}Reading state of the calling contract at`, missingInteraction.sortKey); + /** + Reading the state of the writing contract. + This in turn will cause the state of THIS contract to be + updated in 'interaction state' + */ + let newState = null; + let writingContractState = null; + try { + writingContractState = await writingContract.readState(missingInteraction.sortKey); + newState = contract.interactionState().get(contract.txId(), missingInteraction.sortKey); + } + catch (e) { + // ppe: not sure why we're not handling all ContractErrors here... + if ((e.name == JsHandlerApi_1.KnownErrors.ContractError && + (e.subtype == 'unsafeClientSkip' || e.subtype == 'constructor' || e.subtype == 'blacklistedSkip')) || + e.name == JsHandlerApi_1.KnownErrors.NonWhitelistedSourceError) { + this.logger.warn(`Skipping contract in internal write, reason ${e.subtype || e.name}`); + errorMessages[missingInteraction.id] = e; + if (canBeCached(missingInteraction)) { + const toCache = new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages); + lastConfirmedTxState = { + tx: missingInteraction, + state: toCache + }; + } + } + else { + throw e; + } + } + if (newState !== null && writingContractState !== null) { + const parentValidity = writingContractState.cachedValue.validity[missingInteraction.id]; + if (parentValidity) { + currentState = newState.state; + } + // we need to update the state in the wasm module + // TODO: opt - reuse wasm handlers... + executionContext === null || executionContext === void 0 ? void 0 : executionContext.handler.initState(currentState); + if (parentValidity) { + validity[missingInteraction.id] = newState.validity[missingInteraction.id]; + if ((_a = newState.errorMessages) === null || _a === void 0 ? void 0 : _a[missingInteraction.id]) { + errorMessages[missingInteraction.id] = newState.errorMessages[missingInteraction.id]; + } + } + else { + validity[missingInteraction.id] = false; + errorMessages[missingInteraction.id] = + writingContractState.cachedValue.errorMessages[missingInteraction.id]; + } + const toCache = new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages); + if (canBeCached(missingInteraction)) { + lastConfirmedTxState = { + tx: missingInteraction, + state: toCache + }; + } + } + else { + validity[missingInteraction.id] = false; + } + interactionCall.update({ + cacheHit: false, + outputState: stackTrace.saveState ? currentState : undefined, + executionTime: singleInteractionBenchmark.elapsed(true), + valid: validity[missingInteraction.id], + errorMessage: errorMessage, + gasUsed: 0 // TODO... + }); + } + else { + // "direct" interaction with this contract - "standard" processing + const inputTag = this.tagsParser.getInputTag(missingInteraction, executionContext.contractDefinition.txId); + if (!inputTag) { + this.logger.error(`${(0, utils_1.indent)(depth)}Skipping tx - Input tag not found for ${missingInteraction.id}`); + continue; + } + const input = this.parseInput(inputTag); + if (!input) { + this.logger.error(`${(0, utils_1.indent)(depth)}Skipping tx - invalid Input tag - ${missingInteraction.id}`); + continue; + } + const interaction = { + input, + caller: missingInteraction.owner.address, + interactionType: 'write' + }; + const interactionData = { + interaction, + interactionTx: missingInteraction + }; + const interactionCall = contract.getCallStack().addInteractionData(interactionData); + const result = await executionContext.handler.handle(executionContext, new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages), interactionData); + errorMessage = result.errorMessage; + if (result.type !== 'ok') { + errorMessages[missingInteraction.id] = errorMessage; + } + this.logResult(result, missingInteraction, executionContext); + this.logger.debug(`${(0, utils_1.indent)(depth)}Interaction evaluation`, singleInteractionBenchmark.elapsed()); + interactionCall.update({ + cacheHit: false, + outputState: stackTrace.saveState ? currentState : undefined, + executionTime: singleInteractionBenchmark.elapsed(true), + valid: validity[missingInteraction.id], + errorMessage: errorMessage, + gasUsed: result.gasUsed + }); + if (result.type === 'exception' && ignoreExceptions !== true) { + throw new Error(`Exception while processing ${JSON.stringify(interaction)}:\n${result.errorMessage}`); + } + const isValidInteraction = result.type === 'ok'; + validity[missingInteraction.id] = isValidInteraction; + currentState = result.state; + const toCache = new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages); + if (canBeCached(missingInteraction)) { + lastConfirmedTxState = { + tx: missingInteraction, + state: toCache + }; + } + const event = result.event; + if (event) { + warp.eventTarget.dispatchEvent(new StateEvaluator_1.CustomEvent(isValidInteraction ? 'interactionCompleted' : 'interactionFailed', { detail: event })); + } + } + if (progressPlugin) { + progressPlugin.process({ + contractTxId: contractDefinition.txId, + allInteractions: missingInteractionsLength, + currentInteraction: i, + lastInteractionProcessingTime: singleInteractionBenchmark.elapsed() + }); + } + try { + for (const { modify } of this.executionContextModifiers) { + executionContext = await modify(currentState, executionContext); + } + } + catch (e) { + if ((e.name == JsHandlerApi_1.KnownErrors.ContractError && e.subtype == 'unsafeClientSkip') || + e.name == JsHandlerApi_1.KnownErrors.NonWhitelistedSourceError) { + validity[missingInteraction.id] = false; + errorMessages[missingInteraction.id] = e.message; + shouldBreakAfterEvolve = true; + } + else { + throw e; + } + } + const forceStateStoreToCache = executionContext.evaluationOptions.cacheEveryNInteractions > 0 && + i % executionContext.evaluationOptions.cacheEveryNInteractions === 0; + // if that's the end of the root contract's interaction - commit all the uncommitted states to cache. + if (contract.isRoot()) { + contract.clearChildren(); + // update the uncommitted state of the root contract + if (lastConfirmedTxState) { + contract + .interactionState() + .update(contract.txId(), lastConfirmedTxState.state, lastConfirmedTxState.tx.sortKey); + if (validity[missingInteraction.id]) { + await contract.interactionState().commit(missingInteraction, forceStateStoreToCache); + } + else { + await contract.interactionState().rollback(missingInteraction, forceStateStoreToCache); + } + } + } + else { + // if that's an inner contract call - only update the state in the uncommitted states + const interactionState = new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages); + contract.interactionState().update(contract.txId(), interactionState, currentSortKey); + } + } + const evalStateResult = new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages); + // state could have been fully retrieved from cache + // or there were no interactions below requested sort key + if (lastConfirmedTxState !== null) { + await this.onStateEvaluated(lastConfirmedTxState.tx, executionContext, lastConfirmedTxState.state); + } + return new SortKeyCache_1.SortKeyCacheResult(currentSortKey, evalStateResult); + } + logResult(result, currentTx, executionContext) { + if (result.type === 'exception') { + this.logger.error(`Executing of interaction: [${executionContext.contractDefinition.txId} -> ${currentTx.id}] threw exception:`, `${result.errorMessage}`); + } + if (result.type === 'error') { + this.logger.warn(`Executing of interaction: [${executionContext.contractDefinition.txId} -> ${currentTx.id}] returned error:`, result.errorMessage); + } + } + parseInput(inputTag) { + try { + return JSON.parse(inputTag.value); + } + catch (e) { + this.logger.error(e); + return null; + } + } +} +exports.DefaultStateEvaluator = DefaultStateEvaluator; +function canBeCached(tx) { + // in case of using non-redstone gateway + if (tx.confirmationStatus === undefined) { + return true; + } + else { + return tx.confirmationStatus === 'confirmed'; + } +} +//# sourceMappingURL=DefaultStateEvaluator.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/DefaultStateEvaluator.js.map b/lib/cjs/core/modules/impl/DefaultStateEvaluator.js.map new file mode 100644 index 00000000..e87d220c --- /dev/null +++ b/lib/cjs/core/modules/impl/DefaultStateEvaluator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DefaultStateEvaluator.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/DefaultStateEvaluator.ts"],"names":[],"mappings":";;;AAEA,8DAAiE;AAKjE,0DAAuD;AACvD,kEAA+D;AAC/D,gDAA8C;AAC9C,sDAAiF;AAEjF,6CAA0C;AAG1C,yDAAqD;AASrD;;;;;;GAMG;AACH,MAAsB,qBAAqB;IAKzC,YACqB,OAAgB,EAClB,4BAAwD,EAAE;QADxD,YAAO,GAAP,OAAO,CAAS;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YACjC,MAAM,IAAI,CAAC,gBAAgB,CAAC,oBAAoB,CAAC,EAAE,EAAE,gBAAgB,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC;SACpG;QAED,OAAO,IAAI,iCAAkB,CAAC,cAAc,EAAE,eAAe,CAAC,CAAC;IACjE,CAAC;IAEO,SAAS,CACf,MAAyC,EACzC,SAA2B,EAC3B,gBAA4D;QAE5D,IAAI,MAAM,CAAC,IAAI,KAAK,WAAW,EAAE;YAC/B,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,8BAA8B,gBAAgB,CAAC,kBAAkB,CAAC,IAAI,OAAO,SAAS,CAAC,EAAE,oBAAoB,EAC7G,GAAG,MAAM,CAAC,YAAY,EAAE,CACzB,CAAC;SACH;QACD,IAAI,MAAM,CAAC,IAAI,KAAK,OAAO,EAAE;YAC3B,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,8BAA8B,gBAAgB,CAAC,kBAAkB,CAAC,IAAI,OAAO,SAAS,CAAC,EAAE,mBAAmB,EAC5G,MAAM,CAAC,YAAY,CACpB,CAAC;SACH;IACH,CAAC;IAEO,UAAU,CAAC,QAAyB;QAC1C,IAAI;YACF,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;SACnC;QAAC,OAAO,CAAC,EAAE;YACV,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACrB,OAAO,IAAI,CAAC;SACb;IACH,CAAC;CA4DF;AApZD,sDAoZC;AAED,SAAS,WAAW,CAAC,EAAoB;IACvC,wCAAwC;IACxC,IAAI,EAAE,CAAC,kBAAkB,KAAK,SAAS,EAAE;QACvC,OAAO,IAAI,CAAC;KACb;SAAM;QACL,OAAO,EAAE,CAAC,kBAAkB,KAAK,WAAW,CAAC;KAC9C;AACH,CAAC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/HandlerExecutorFactory.js b/lib/cjs/core/modules/impl/HandlerExecutorFactory.js new file mode 100644 index 00000000..04cd34bf --- /dev/null +++ b/lib/cjs/core/modules/impl/HandlerExecutorFactory.js @@ -0,0 +1,202 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HandlerExecutorFactory = exports.NonWhitelistedSourceError = exports.ContractError = void 0; +const rust_wasm_imports_1 = require("./wasm/rust-wasm-imports"); +const smartweave_global_1 = require("../../../legacy/smartweave-global"); +const Benchmark_1 = require("../../../logging/Benchmark"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +const JsHandlerApi_1 = require("./handler/JsHandlerApi"); +const WasmHandlerApi_1 = require("./handler/WasmHandlerApi"); +const normalize_source_1 = require("./normalize-source"); +const utils_1 = require("../../../utils/utils"); +const warp_isomorphic_1 = require("warp-isomorphic"); +// 'require' to fix esbuild adding same lib in both cjs and esm format +// https://github.com/evanw/esbuild/issues/1950 +// eslint-disable-next-line +const BigNumber = require('bignumber.js'); +class ContractError extends Error { + constructor(error, subtype) { + super(error.toString()); + this.error = error; + this.subtype = subtype; + this.name = JsHandlerApi_1.KnownErrors.ContractError; + } +} +exports.ContractError = ContractError; +class NonWhitelistedSourceError extends Error { + constructor(error) { + super(error.toString()); + this.error = error; + this.name = JsHandlerApi_1.KnownErrors.NonWhitelistedSourceError; + } +} +exports.NonWhitelistedSourceError = NonWhitelistedSourceError; +/** + * A factory that produces handlers that are compatible with the "current" style of + * writing SW contracts (i.e. using "handle" function). + */ +class HandlerExecutorFactory { + constructor(arweave) { + this.arweave = arweave; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('HandlerExecutorFactory'); + } + async create(contractDefinition, evaluationOptions, warp, interactionState) { + if (warp.hasPlugin('contract-blacklist')) { + await this.blacklistContracts(warp, contractDefinition); + } + this.checkWhiteListContractSources(contractDefinition, evaluationOptions); + let kvStorage = null; + if (evaluationOptions.useKVStorage) { + kvStorage = warp.kvStorageFactory(contractDefinition.txId); + } + const swGlobal = new smartweave_global_1.SmartWeaveGlobal(this.arweave, { + id: contractDefinition.txId, + owner: contractDefinition.owner + }, evaluationOptions, interactionState, kvStorage); + const extensionPlugins = warp.matchPlugins(`^smartweave-extension-`); + extensionPlugins.forEach((ex) => { + const extension = warp.loadPlugin(ex); + extension.process(swGlobal.extensions); + }); + if (contractDefinition.contractType == 'wasm') { + this.logger.info('Creating handler for wasm contract', contractDefinition.txId); + const benchmark = Benchmark_1.Benchmark.measure(); + let wasmInstance; + let jsExports = null; + const wasmResponse = generateResponse(contractDefinition.srcBinary); + switch (contractDefinition.srcWasmLang) { + case 'rust': { + const wasmInstanceExports = { + exports: null, + modifiedExports: { + wasm_bindgen__convert__closures__invoke2_mut__: null, + _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__: null + } + }; + /** + * wasm-bindgen mangles import function names (adds some random number after "base name") + * - that's why we cannot statically build the imports in the SDK. + * Instead - we need to first compile the module and check the generated + * import function names (all imports from the "__wbindgen_placeholder__" import module). + * Having those generated function names - we need to then map them to import functions - + * see {@link rustWasmImports} + * + * That's probably a temporary solution - it would be the best to force the wasm-bindgen + * to NOT mangle the import function names - unfortunately that is not currently possible + * - https://github.com/rustwasm/wasm-bindgen/issues/1128 + */ + const wasmModule = await getWasmModule(wasmResponse, contractDefinition.srcBinary); + const warpContractsCrateVersion = WebAssembly.Module.exports(wasmModule) + .filter((exp) => exp.kind === 'global' && exp.name.startsWith('__WARP_CONTRACTS_VERSION_')) + .map((exp) => exp.name) + .shift() || '__WARP_CONTRACTS_VERSION_LEGACY'; + const wbindgenImports = WebAssembly.Module.imports(wasmModule) + .filter((imp) => { + return imp.module === '__wbindgen_placeholder__'; + }) + .map((imp) => imp.name); + const { imports, exports } = (0, rust_wasm_imports_1.rustWasmImports)(swGlobal, wbindgenImports, wasmInstanceExports, contractDefinition.metadata.dtor, warpContractsCrateVersion); + jsExports = exports; + wasmInstance = await WebAssembly.instantiate(wasmModule, imports); + wasmInstanceExports.exports = wasmInstance.exports; + const moduleExports = Object.keys(wasmInstance.exports); + // ... no comments ... + moduleExports.forEach((moduleExport) => { + if (moduleExport.startsWith('wasm_bindgen__convert__closures__invoke2_mut__')) { + wasmInstanceExports.modifiedExports.wasm_bindgen__convert__closures__invoke2_mut__ = + wasmInstance.exports[moduleExport]; + } + if (moduleExport.startsWith('_dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__')) { + wasmInstanceExports.modifiedExports._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ = + wasmInstance.exports[moduleExport]; + } + }); + break; + } + default: { + throw new Error(`Support for ${contractDefinition.srcWasmLang} not implemented yet.`); + } + } + this.logger.info(`WASM ${contractDefinition.srcWasmLang} handler created in ${benchmark.elapsed()}`); + return new WasmHandlerApi_1.WasmHandlerApi(swGlobal, contractDefinition, jsExports || wasmInstance.exports); + } + else { + const normalizedSource = (0, normalize_source_1.normalizeContractSource)(contractDefinition.src, warp.hasPlugin('vm2')); + if (normalizedSource.includes('unsafeClient')) { + switch (evaluationOptions.unsafeClient) { + case 'allow': { + this.logger.warn(`Reading unsafe contract ${contractDefinition.txId}, evaluation is non-deterministic!`); + break; + } + case 'throw': + throw new Error(`[SkipUnsafeError] Using unsafeClient is not allowed by default. Use EvaluationOptions.unsafeClient flag to evaluate ${contractDefinition.txId}.`); + case 'skip': { + throw new ContractError(`[SkipUnsafeError] Skipping evaluation of the unsafe contract ${contractDefinition.txId}.`, 'unsafeClientSkip'); + } + default: + throw new Error(`Unknown unsafeClient setting ${evaluationOptions.unsafeClient}`); + } + } + if (!evaluationOptions.allowBigInt) { + if (normalizedSource.includes('BigInt')) { + throw new Error('Using BigInt is not allowed by default. Use EvaluationOptions.allowBigInt flag.'); + } + } + if (warp.hasPlugin('vm2')) { + const vm2Plugin = warp.loadPlugin('vm2'); + return vm2Plugin.process({ normalizedSource, swGlobal, logger: this.logger, contractDefinition }); + } + else if (warp.hasPlugin('ivm-handler-api')) { + const ivmPlugin = warp.loadPlugin('ivm-handler-api'); + return ivmPlugin.process({ + contractSource: contractDefinition.src, + evaluationOptions, + arweave: this.arweave, + swGlobal: swGlobal, + contractDefinition + }); + } + else { + const contractFunction = new Function(normalizedSource); + const handler = (0, utils_1.isBrowser)() + ? contractFunction(swGlobal, BigNumber, LoggerFactory_1.LoggerFactory.INST.create(swGlobal.contract.id), warp_isomorphic_1.Buffer, atob, btoa) + : contractFunction(swGlobal, BigNumber, LoggerFactory_1.LoggerFactory.INST.create(swGlobal.contract.id)); + return new JsHandlerApi_1.JsHandlerApi(swGlobal, contractDefinition, handler); + } + } + } + checkWhiteListContractSources(contractDefinition, evaluationOptions) { + if (evaluationOptions && + evaluationOptions.whitelistSources.length > 0 && + !evaluationOptions.whitelistSources.includes(contractDefinition.srcTxId)) { + throw new NonWhitelistedSourceError(`[NonWhitelistedSourceError] Contract source not part of whitelisted sources list: ${contractDefinition.srcTxId}.`); + } + } + async blacklistContracts(warp, contractDefinition) { + const blacklistPlugin = warp.loadPlugin('contract-blacklist'); + let blacklisted = false; + try { + blacklisted = await blacklistPlugin.process(contractDefinition.txId); + } + catch (e) { + this.logger.error(e); + } + if (blacklisted == true) { + throw new ContractError(`[SkipUnsafeError] Skipping evaluation of the blacklisted contract ${contractDefinition.txId}.`, `blacklistedSkip`); + } + } +} +exports.HandlerExecutorFactory = HandlerExecutorFactory; +function generateResponse(wasmBinary) { + const init = { status: 200, statusText: 'OK', headers: { 'Content-Type': 'application/wasm' } }; + return new Response(wasmBinary, init); +} +async function getWasmModule(wasmResponse, binary) { + if (WebAssembly.compileStreaming) { + return await WebAssembly.compileStreaming(wasmResponse); + } + else { + return await WebAssembly.compile(binary); + } +} +//# sourceMappingURL=HandlerExecutorFactory.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/HandlerExecutorFactory.js.map b/lib/cjs/core/modules/impl/HandlerExecutorFactory.js.map new file mode 100644 index 00000000..7cf007e0 --- /dev/null +++ b/lib/cjs/core/modules/impl/HandlerExecutorFactory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"HandlerExecutorFactory.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/HandlerExecutorFactory.ts"],"names":[],"mappings":";;;AACA,gEAAsF;AAItF,yEAAqE;AACrE,0DAAuD;AACvD,kEAA+D;AAG/D,yDAAmE;AACnE,6DAA0D;AAC1D,yDAA6D;AAE7D,gDAAiD;AACjD,qDAAyC;AAIzC,sEAAsE;AACtE,+CAA+C;AAC/C,2BAA2B;AAC3B,MAAM,SAAS,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;AAE1C,MAAa,aAAiB,SAAQ,KAAK;IACzC,YAAqB,KAAQ,EAAW,OAAgB;QACtD,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;QADL,UAAK,GAAL,KAAK,CAAG;QAAW,YAAO,GAAP,OAAO,CAAS;QAEtD,IAAI,CAAC,IAAI,GAAG,0BAAW,CAAC,aAAa,CAAC;IACxC,CAAC;CACF;AALD,sCAKC;AAED,MAAa,yBAA6B,SAAQ,KAAK;IACrD,YAAqB,KAAQ;QAC3B,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;QADL,UAAK,GAAL,KAAK,CAAG;QAE3B,IAAI,CAAC,IAAI,GAAG,0BAAW,CAAC,yBAAyB,CAAC;IACpD,CAAC;CACF;AALD,8DAKC;AAED;;;GAGG;AACH,MAAa,sBAAsB;IAGjC,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;QAF5B,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,CAAC;IAE9B,CAAC;IAEjD,KAAK,CAAC,MAAM,CACV,kBAA6C,EAC7C,iBAAoC,EACpC,IAAU,EACV,gBAAkC;QAElC,IAAI,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC,EAAE;YACxC,MAAM,IAAI,CAAC,kBAAkB,CAAQ,IAAI,EAAE,kBAAkB,CAAC,CAAC;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AAU,EAAE,IAAI,CAAC,CAAC;AACxC,CAAC;AAED,KAAK,UAAU,aAAa,CAAC,YAAsB,EAAE,MAAc;IACjE,IAAI,WAAW,CAAC,gBAAgB,EAAE;QAChC,OAAO,MAAM,WAAW,CAAC,gBAAgB,CAAC,YAAY,CAAC,CAAC;KACzD;SAAM;QACL,OAAO,MAAM,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;KAC1C;AACH,CAAC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/LexicographicalInteractionsSorter.js b/lib/cjs/core/modules/impl/LexicographicalInteractionsSorter.js new file mode 100644 index 00000000..8f4e18be --- /dev/null +++ b/lib/cjs/core/modules/impl/LexicographicalInteractionsSorter.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LexicographicalInteractionsSorter = exports.lastPossibleSortKey = exports.genesisSortKey = exports.sortingLast = exports.sortingFirst = exports.defaultArweaveMs = void 0; +const utils_1 = require("../../../legacy/utils"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +// note: this (i.e. padding to 13 digits) should be safe between years ~1966 and ~2286 +const firstSortKeyMs = ''.padEnd(13, '0'); +const lastSortKeyMs = ''.padEnd(13, '9'); +exports.defaultArweaveMs = ''.padEnd(13, '0'); +exports.sortingFirst = ''.padEnd(64, '0'); +exports.sortingLast = ''.padEnd(64, 'z'); +exports.genesisSortKey = `${''.padStart(12, '0')},${firstSortKeyMs},${exports.sortingFirst}`; +exports.lastPossibleSortKey = `${''.padStart(12, '9')},${lastSortKeyMs},${exports.sortingLast}`; +/** + * implementation that is based on current's SDK sorting alg. + */ +class LexicographicalInteractionsSorter { + constructor(arweave) { + this.arweave = arweave; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('LexicographicalInteractionsSorter'); + } + async sort(transactions) { + const copy = [...transactions]; + const addKeysFuncs = copy.map((tx) => this.addSortKey(tx)); + await Promise.all(addKeysFuncs); + return copy.sort((a, b) => a.node.sortKey.localeCompare(b.node.sortKey)); + } + async createSortKey(blockId, transactionId, blockHeight, dummy = false) { + const blockHashBytes = this.arweave.utils.b64UrlToBuffer(blockId); + const txIdBytes = this.arweave.utils.b64UrlToBuffer(transactionId); + const concatenated = this.arweave.utils.concatBuffers([blockHashBytes, txIdBytes]); + const hashed = (0, utils_1.arrayToHex)(await this.arweave.crypto.hash(concatenated)); + const blockHeightString = `${blockHeight}`.padStart(12, '0'); + const arweaveMs = dummy ? lastSortKeyMs : exports.defaultArweaveMs; + return `${blockHeightString},${arweaveMs},${hashed}`; + } + extractBlockHeight(sortKey) { + // I feel sorry for myself... + return sortKey ? parseInt(sortKey.split(',')[0]) : null; + } + async addSortKey(txInfo) { + const { node } = txInfo; + // might have been already set by the Warp Sequencer + const sortKey = txInfo.node.sortKey; + if (sortKey) { + txInfo.node.sortKey = sortKey; + this.logger.debug('Using sortKey from sequencer', txInfo.node.sortKey); + } + else { + txInfo.node.sortKey = await this.createSortKey(node.block.id, node.id, node.block.height); + } + } + generateLastSortKey(blockHeight) { + const blockHeightString = `${blockHeight}`.padStart(12, '0'); + return `${blockHeightString},${lastSortKeyMs},${exports.sortingLast}`; + } +} +exports.LexicographicalInteractionsSorter = LexicographicalInteractionsSorter; +//# sourceMappingURL=LexicographicalInteractionsSorter.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/LexicographicalInteractionsSorter.js.map b/lib/cjs/core/modules/impl/LexicographicalInteractionsSorter.js.map new file mode 100644 index 00000000..6dec3d5f --- /dev/null +++ b/lib/cjs/core/modules/impl/LexicographicalInteractionsSorter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"LexicographicalInteractionsSorter.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/LexicographicalInteractionsSorter.ts"],"names":[],"mappings":";;;AAEA,iDAAmD;AACnD,kEAA+D;AAG/D,sFAAsF;AACtF,MAAM,cAAc,GAAG,EAAE,CAAC,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;AAC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I,CAAC,OAAO,CAAC,CAAC;SACxE;aAAM;YACL,MAAM,CAAC,IAAI,CAAC,OAAO,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;SAC3F;IACH,CAAC;IAED,mBAAmB,CAAC,WAAmB;QACrC,MAAM,iBAAiB,GAAG,GAAG,WAAW,EAAE,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;QAC7D,OAAO,GAAG,iBAAiB,IAAI,aAAa,IAAI,mBAAW,EAAE,CAAC;IAChE,CAAC;CACF;AAjDD,8EAiDC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/TagsParser.js b/lib/cjs/core/modules/impl/TagsParser.js new file mode 100644 index 00000000..720163ff --- /dev/null +++ b/lib/cjs/core/modules/impl/TagsParser.js @@ -0,0 +1,107 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TagsParser = void 0; +const KnownTags_1 = require("../../KnownTags"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +/** + * A class that is responsible for retrieving "input" tag from the interaction transaction. + * Two tags formats are allowed: + * 1. "multiple interactions in one tx" format - where "Input" tag MUST be next to the "Contract" tag + * See more at https://github.com/ArweaveTeam/SmartWeave/pull/51 + * 2. "traditional" format - one interaction per one transaction - where tags order does not matter. + * + * More on Discord: https://discord.com/channels/357957786904166400/756557551234973696/885388585023463424 + */ +class TagsParser { + constructor() { + this.logger = LoggerFactory_1.LoggerFactory.INST.create('TagsParser'); + } + getInputTag(interactionTransaction, contractTxId) { + // this is the part to retain compatibility with https://github.com/ArweaveTeam/SmartWeave/pull/51 + if (TagsParser.hasMultipleInteractions(interactionTransaction)) { + this.logger.debug('Interaction transaction is using multiple input tx tag format.'); + const contractTagIndex = interactionTransaction.tags.findIndex((tag) => tag.name === KnownTags_1.SMART_WEAVE_TAGS.CONTRACT_TX_ID && tag.value === contractTxId); + // if "Contract" is the last tag + if (interactionTransaction.tags.length - 1 === contractTagIndex) { + this.logger.warn("Wrong tags format: 'Contract' is the last tag"); + return undefined; + } + // in this case the "Input" tag MUST be right after the "Contract" tag + const inputTag = interactionTransaction.tags[contractTagIndex + 1]; + // if the tag after "Contract" tag has wrong name + if (inputTag.name !== KnownTags_1.SMART_WEAVE_TAGS.INPUT) { + this.logger.warn(`No 'Input' tag found after 'Contract' tag. Instead ${inputTag.name} was found`); + return undefined; + } + return inputTag; + } + else { + // the "old way" - i.e. tags ordering does not matter, + // if there is at most one "Contract" tag + // - so returning the first occurrence of "Input" tag. + return interactionTransaction.tags.find((tag) => tag.name === KnownTags_1.SMART_WEAVE_TAGS.INPUT); + } + } + isInteractWrite(interactionTransaction, contractTxId) { + return interactionTransaction.tags.some((tag) => tag.name === KnownTags_1.WARP_TAGS.INTERACT_WRITE && tag.value === contractTxId); + } + getInteractWritesContracts(interactionTransaction) { + return interactionTransaction.tags.filter((tag) => tag.name === KnownTags_1.WARP_TAGS.INTERACT_WRITE).map((t) => t.value); + } + getContractTag(interactionTransaction) { + var _a; + return (_a = interactionTransaction.tags.find((tag) => tag.name === KnownTags_1.SMART_WEAVE_TAGS.CONTRACT_TX_ID)) === null || _a === void 0 ? void 0 : _a.value; + } + getContractsWithInputs(interactionTransaction) { + const result = new Map(); + const contractTags = interactionTransaction.tags.filter((tag) => tag.name === KnownTags_1.SMART_WEAVE_TAGS.CONTRACT_TX_ID); + contractTags.forEach((contractTag) => { + result.set(contractTag.value, this.getInputTag(interactionTransaction, contractTag.value)); + }); + return result; + } + isEvmSigned(interactionTransaction) { + return interactionTransaction.tags.some((tag) => tag.name === KnownTags_1.WARP_TAGS.SIGNATURE_TYPE && tag.value === 'ethereum'); + } + static hasMultipleInteractions(interactionTransaction) { + return interactionTransaction.tags.filter((tag) => tag.name === KnownTags_1.SMART_WEAVE_TAGS.CONTRACT_TX_ID).length > 1; + } + decodeTags(tx) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const tags = tx.get('tags'); + const result = []; + for (const tag of tags) { + try { + const name = tag.get('name', { decode: true, string: true }); + const value = tag.get('value', { decode: true, string: true }); + result.push({ name, value }); + } + catch (e) { + // ignore tags with invalid utf-8 strings in key or value. + } + } + return result; + } + getTag(tx, name) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const tags = tx.get('tags'); + for (const tag of tags) { + try { + if (tag.get('name', { decode: true, string: true }) === name) { + return tag.get('value', { decode: true, string: true }); + } + } + catch (e) { + // ignore tags with invalid utf-8 strings in key or value. + } + } + return false; + } + hasVrfTag(interaction) { + return interaction.tags.some((t) => { + return t.name == KnownTags_1.WARP_TAGS.REQUEST_VRF && t.value === 'true'; + }); + } +} +exports.TagsParser = TagsParser; +//# sourceMappingURL=TagsParser.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/TagsParser.js.map b/lib/cjs/core/modules/impl/TagsParser.js.map new file mode 100644 index 00000000..926d83f0 --- /dev/null +++ b/lib/cjs/core/modules/impl/TagsParser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TagsParser.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/TagsParser.ts"],"names":[],"mappings":";;;AAAA,+CAA8D;AAE9D,kEAA+D;AAG/D;;;;;;;;GAQG;AACH,MAAa,UAAU;IAAvB;QACmB,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IAyGpE,CAAC;IAvGC,WAAW,CAAC,sBAAwC,EAAE,YAAoB;QACxE,kGAAkG;QAClG,IAAI,UAAU,CAAC,uBAAuB,CAAC,sBAAsB,CAAC,EAAE;YAC9D,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gEAAgE,CAAC,CAAC;YACpF,MAAM,gBAAgB,GAAG,sBAAsB,CAAC,IAAI,CAAC,SAAS,CAC5D,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,4BA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IACL,CAAC;CACF;AA1GD,gCA0GC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/WarpGatewayContractDefinitionLoader.js b/lib/cjs/core/modules/impl/WarpGatewayContractDefinitionLoader.js new file mode 100644 index 00000000..5081ada7 --- /dev/null +++ b/lib/cjs/core/modules/impl/WarpGatewayContractDefinitionLoader.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WarpGatewayContractDefinitionLoader = void 0; +const ContractDefinitionLoader_1 = require("./ContractDefinitionLoader"); +const warp_isomorphic_1 = require("warp-isomorphic"); +const ContractDefinition_1 = require("../../../core/ContractDefinition"); +const KnownTags_1 = require("../../KnownTags"); +const Benchmark_1 = require("../../../logging/Benchmark"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +const ArweaveWrapper_1 = require("../../../utils/ArweaveWrapper"); +const WasmSrc_1 = require("./wasm/WasmSrc"); +const TagsParser_1 = require("./TagsParser"); +const SortKeyCache_1 = require("../../../cache/SortKeyCache"); +const arweave_types_1 = require("../../../utils/types/arweave-types"); +const utils_1 = require("../../../utils/utils"); +/** + * An extension to {@link ContractDefinitionLoader} that makes use of + * Warp Gateway ({@link https://github.com/redstone-finance/redstone-sw-gateway}) + * to load Contract Data. + * + * If the contract data is not available on Warp Gateway - it fallbacks to default implementation + * in {@link ContractDefinitionLoader} - i.e. loads the definition from Arweave gateway. + */ +class WarpGatewayContractDefinitionLoader { + constructor(arweave, definitionCache, srcCache, env) { + this.definitionCache = definitionCache; + this.srcCache = srcCache; + this.env = env; + this.rLogger = LoggerFactory_1.LoggerFactory.INST.create('WarpGatewayContractDefinitionLoader'); + this.contractDefinitionLoader = new ContractDefinitionLoader_1.ContractDefinitionLoader(arweave, env); + this.tagsParser = new TagsParser_1.TagsParser(); + } + async load(contractTxId, evolvedSrcTxId) { + const result = await this.getFromCache(contractTxId, evolvedSrcTxId); + if (result) { + this.rLogger.debug('WarpGatewayContractDefinitionLoader: Hit from cache!'); + // LevelDB serializes Buffer to an object with 'type' and 'data' fields + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (result.contractType == 'wasm' && result.srcBinary.data) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + result.srcBinary = warp_isomorphic_1.Buffer.from(result.srcBinary.data); + } + this.verifyEnv(result); + return result; + } + const benchmark = Benchmark_1.Benchmark.measure(); + const contract = await this.doLoad(contractTxId, evolvedSrcTxId); + this.rLogger.info(`Contract definition loaded in: ${benchmark.elapsed()}`); + this.verifyEnv(contract); + await this.putToCache(contractTxId, contract, evolvedSrcTxId); + return contract; + } + async doLoad(contractTxId, forcedSrcTxId) { + try { + const baseUrl = (0, utils_1.stripTrailingSlash)(this._warp.gwUrl()); + const result = await (0, utils_1.getJsonResponse)(fetch(`${baseUrl}/gateway/contract?txId=${contractTxId}${forcedSrcTxId ? `&srcTxId=${forcedSrcTxId}` : ''}`)); + if (result.srcBinary != null && !(result.srcBinary instanceof warp_isomorphic_1.Buffer)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + result.srcBinary = warp_isomorphic_1.Buffer.from(result.srcBinary.data); + } + if (result.srcBinary) { + const wasmSrc = new WasmSrc_1.WasmSrc(result.srcBinary); + result.srcBinary = wasmSrc.wasmBinary(); + let sourceTx; + if (result.srcTx) { + sourceTx = new arweave_types_1.Transaction({ ...result.srcTx }); + } + else { + sourceTx = await this.arweaveWrapper.tx(result.srcTxId); + } + const srcMetaData = JSON.parse(this.tagsParser.getTag(sourceTx, KnownTags_1.WARP_TAGS.WASM_META)); + result.metadata = srcMetaData; + } + result.contractType = result.src ? 'js' : 'wasm'; + return result; + } + catch (e) { + this.rLogger.warn('Falling back to default contracts loader', e); + return await this.contractDefinitionLoader.doLoad(contractTxId, forcedSrcTxId); + } + } + async loadContractSource(contractSrcTxId) { + return await this.contractDefinitionLoader.loadContractSource(contractSrcTxId); + } + type() { + return 'warp'; + } + setCache(cache) { + this.definitionCache = cache; + } + setSrcCache(cacheSrc) { + this.srcCache = cacheSrc; + } + getCache() { + return this.definitionCache; + } + getSrcCache() { + return this.srcCache; + } + verifyEnv(def) { + if (def.testnet && this.env !== 'testnet') { + throw new Error('Trying to use testnet contract in a non-testnet env. Use the "forTestnet" factory method.'); + } + if (!def.testnet && this.env === 'testnet') { + throw new Error('Trying to use non-testnet contract in a testnet env.'); + } + } + // Gets ContractDefinition and ContractSource from two caches and returns a combined structure + async getFromCache(contractTxId, srcTxId) { + const contract = (await this.definitionCache.get(new SortKeyCache_1.CacheKey(contractTxId, 'cd'))); + if (!contract) { + return null; + } + const src = await this.srcCache.get(new SortKeyCache_1.CacheKey(srcTxId || contract.cachedValue.srcTxId, 'src')); + if (!src) { + return null; + } + return { ...contract.cachedValue, ...src.cachedValue }; + } + // Divides ContractDefinition into entries in two caches to avoid duplicates + async putToCache(contractTxId, value, srcTxId) { + const src = new ContractDefinition_1.SrcCache(value); + const contract = new ContractDefinition_1.ContractCache(value); + await this.definitionCache.put({ key: contractTxId, sortKey: 'cd' }, contract); + await this.srcCache.put({ key: srcTxId || contract.srcTxId, sortKey: 'src' }, src); + } + set warp(warp) { + this._warp = warp; + this.arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(warp); + this.contractDefinitionLoader.warp = warp; + } +} +exports.WarpGatewayContractDefinitionLoader = WarpGatewayContractDefinitionLoader; +//# sourceMappingURL=WarpGatewayContractDefinitionLoader.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/WarpGatewayContractDefinitionLoader.js.map b/lib/cjs/core/modules/impl/WarpGatewayContractDefinitionLoader.js.map new file mode 100644 index 00000000..89778c9d --- /dev/null +++ b/lib/cjs/core/modules/impl/WarpGatewayContractDefinitionLoader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpGatewayContractDefinitionLoader.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/WarpGatewayContractDefinitionLoader.ts"],"names":[],"mappings":";;;AACA,yEAAsE;AACtE,qDAAyC;AAEzC,yEAA+G;AAC/G,+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ClB,IAAI,CAAC,cAAc,GAAG,IAAI,+BAAc,CAAC,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,wBAAwB,CAAC,IAAI,GAAG,IAAI,CAAC;IAC5C,CAAC;CACF;AAzID,kFAyIC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/WarpGatewayInteractionsLoader.js b/lib/cjs/core/modules/impl/WarpGatewayInteractionsLoader.js new file mode 100644 index 00000000..7a720555 --- /dev/null +++ b/lib/cjs/core/modules/impl/WarpGatewayInteractionsLoader.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WarpGatewayInteractionsLoader = exports.SourceType = void 0; +const Benchmark_1 = require("../../../logging/Benchmark"); +const LoggerFactory_1 = require("../../../logging/LoggerFactory"); +require("warp-isomorphic"); +const utils_1 = require("../../../utils/utils"); +var SourceType; +(function (SourceType) { + SourceType["ARWEAVE"] = "arweave"; + SourceType["WARP_SEQUENCER"] = "redstone-sequencer"; + SourceType["BOTH"] = "both"; +})(SourceType = exports.SourceType || (exports.SourceType = {})); +/** + * The aim of this implementation of the {@link InteractionsLoader} is to make use of + * Warp Gateway ({@link https://github.com/redstone-finance/redstone-sw-gateway}) + * endpoint and retrieve contracts' interactions. + * + * Optionally - it is possible to pass: + * 1. {@link ConfirmationStatus.confirmed} flag - to receive only confirmed interactions - ie. interactions with + * enough confirmations, whose existence is confirmed by at least 3 Arweave peers. + * 2. {@link ConfirmationStatus.notCorrupted} flag - to receive both already confirmed and not yet confirmed (ie. latest) + * interactions. + * 3. {@link SourceType} - to receive interactions based on their origin ({@link SourceType.ARWEAVE} or {@link SourceType.WARP_SEQUENCER}). + * If not set, by default {@link SourceType.BOTH} is set. + * + * Passing no flag is the "backwards compatible" mode (ie. it will behave like the original Arweave GQL gateway endpoint). + * Note that this may result in returning corrupted and/or forked interactions + * - read more {@link https://github.com/warp-contracts/redstone-sw-gateway#corrupted-transactions}. + */ +class WarpGatewayInteractionsLoader { + constructor(confirmationStatus = null, source = SourceType.BOTH) { + this.confirmationStatus = confirmationStatus; + this.source = source; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('WarpGatewayInteractionsLoader'); + Object.assign(this, confirmationStatus); + this.source = source; + } + async load(contractId, fromSortKey, toSortKey, evaluationOptions) { + this.logger.debug('Loading interactions: for ', { contractId, fromSortKey, toSortKey }); + const interactions = []; + let page = 0; + let limit = 0; + let items = 0; + const effectiveSourceType = evaluationOptions ? evaluationOptions.sourceType : this.source; + const benchmarkTotalTime = Benchmark_1.Benchmark.measure(); + const baseUrl = (0, utils_1.stripTrailingSlash)(this._warp.gwUrl()); + do { + const benchmarkRequestTime = Benchmark_1.Benchmark.measure(); + const url = `${baseUrl}/gateway/v2/interactions-sort-key`; + const response = await (0, utils_1.getJsonResponse)(fetch(`${url}?${new URLSearchParams({ + contractId: contractId, + ...(this._warp.whoAmI ? { client: this._warp.whoAmI } : ''), + ...(fromSortKey ? { from: fromSortKey } : ''), + ...(toSortKey ? { to: toSortKey } : ''), + page: (++page).toString(), + fromSdk: 'true', + ...(this.confirmationStatus && this.confirmationStatus.confirmed + ? { confirmationStatus: 'confirmed' } + : ''), + ...(this.confirmationStatus && this.confirmationStatus.notCorrupted + ? { confirmationStatus: 'not_corrupted' } + : ''), + ...(effectiveSourceType == SourceType.BOTH ? '' : { source: effectiveSourceType }) + })}`)); + this.logger.debug(`Loading interactions: page ${page} loaded in ${benchmarkRequestTime.elapsed()}`); + interactions.push(...response.interactions); + limit = response.paging.limit; + items = response.paging.items; + this.logger.debug(`Loaded interactions length: ${interactions.length}, from: ${fromSortKey}, to: ${toSortKey}`); + } while (items == limit); // note: items < limit means that we're on the last page + this.logger.debug('All loaded interactions:', { + from: fromSortKey, + to: toSortKey, + loaded: interactions.length, + time: benchmarkTotalTime.elapsed() + }); + return interactions; + } + type() { + return 'warp'; + } + clearCache() { + // noop + } + set warp(warp) { + this._warp = warp; + } +} +exports.WarpGatewayInteractionsLoader = WarpGatewayInteractionsLoader; +//# sourceMappingURL=WarpGatewayInteractionsLoader.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/WarpGatewayInteractionsLoader.js.map b/lib/cjs/core/modules/impl/WarpGatewayInteractionsLoader.js.map new file mode 100644 index 00000000..f64bf352 --- /dev/null +++ b/lib/cjs/core/modules/impl/WarpGatewayInteractionsLoader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpGatewayInteractionsLoader.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/WarpGatewayInteractionsLoader.ts"],"names":[],"mappings":";;;AACA,0DAAuD;AACvD,kEAA+D;AAC/D,2BAAyB;AACzB,gDAA2E;AAe3E,IAAkB,UAIjB;AAJD,WAAkB,UAAU;IAC1B,iCAAmB,CAAA;IACnB,mDAAqC,CAAA;IACrC,2BAAa,CAAA;AACf,CAAC,EAJiB,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAI3B;AAUD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,6BAA6B;IAGxC,YACmB,qBAAyC,IAAI,EAC7C,SAAqB,UAAU,CAAC,IAAI;QADpC,uBAAkB,GAAlB,kBAAkB,CAA2B;QAC7C,WAAM,GAAN,MAAM,CAA8B;QAMtC,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,+BAA+B,CAAC,CAAC;QAJnF,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,kBAAkB,CAAC,CAAC;QACxC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAID,KAAK,CAAC,IAAI,CACR,UAAkB,EAClB,WAAoB,EACpB,SAAkB,EAClB,iBAAqC;QAErC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,4BAA4B,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,CAAC,CAAC;QAExF,MAAM,YAAY,GAAuB,EAAE,CAAC;QAC5C,IAAI,IAAI,GAAG,CAAC,CAAC;QACb,IAAI,KAAK,GAAG,CAAC,C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AC,YAAY;oBACjE,CAAC,CAAC,EAAE,kBAAkB,EAAE,eAAe,EAAE;oBACzC,CAAC,CAAC,EAAE,CAAC;gBACP,GAAG,CAAC,mBAAmB,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,mBAAmB,EAAE,CAAC;aACnF,CAAC,EAAE,CACL,CACF,CAAC;YACF,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8BAA8B,IAAI,cAAc,oBAAoB,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;YAEpG,YAAY,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC5C,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC;YAC9B,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC;YAE9B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,YAAY,CAAC,MAAM,WAAW,WAAW,SAAS,SAAS,EAAE,CAAC,CAAC;SACjH,QAAQ,KAAK,IAAI,KAAK,EAAE,CAAC,wDAAwD;QAElF,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,0BAA0B,EAAE;YAC5C,IAAI,EAAE,WAAW;YACjB,EAAE,EAAE,SAAS;YACb,MAAM,EAAE,YAAY,CAAC,MAAM;YAC3B,IAAI,EAAE,kBAAkB,CAAC,OAAO,EAAE;SACnC,CAAC,CAAC;QAEH,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,IAAI;QACF,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,UAAU;QACR,OAAO;IACT,CAAC;IAED,IAAI,IAAI,CAAC,IAAU;QACjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;CACF;AApFD,sEAoFC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/handler/AbstractContractHandler.js b/lib/cjs/core/modules/impl/handler/AbstractContractHandler.js new file mode 100644 index 00000000..db25e812 --- /dev/null +++ b/lib/cjs/core/modules/impl/handler/AbstractContractHandler.js @@ -0,0 +1,133 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AbstractContractHandler = void 0; +const LoggerFactory_1 = require("../../../../logging/LoggerFactory"); +const utils_1 = require("../../../../utils/utils"); +const HandlerExecutorFactory_1 = require("../HandlerExecutorFactory"); +class AbstractContractHandler { + constructor(swGlobal, contractDefinition) { + this.swGlobal = swGlobal; + this.contractDefinition = contractDefinition; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('ContractHandler'); + this.assignReadContractState = this.assignReadContractState.bind(this); + this.assignViewContractState = this.assignViewContractState.bind(this); + this.assignWrite = this.assignWrite.bind(this); + this.assignRefreshState = this.assignRefreshState.bind(this); + } + async dispose() { + // noop by default; + } + assignWrite(executionContext) { + this.swGlobal.contracts.write = async (contractTxId, input, throwOnError) => { + if (!executionContext.evaluationOptions.internalWrites) { + throw new Error("Internal writes feature switched off. Change EvaluationOptions.internalWrites flag to 'true'"); + } + const effectiveThrowOnError = throwOnError == undefined ? executionContext.evaluationOptions.throwOnInternalWriteError : throwOnError; + const debugData = { + from: this.contractDefinition.txId, + to: contractTxId, + input + }; + this.logger.debug('swGlobal.write call:', debugData); + // The contract that we want to call and modify its state + const calleeContract = executionContext.warp.contract(contractTxId, executionContext.contract, { + callingInteraction: this.swGlobal._activeTx, + callType: 'write' + }); + const result = await calleeContract.applyInput(input, this.swGlobal._activeTx); + this.logger.debug('Cache result?:', !this.swGlobal._activeTx.dry); + const shouldAutoThrow = result.type !== 'ok' && + effectiveThrowOnError && + (!this.swGlobal._activeTx.dry || (this.swGlobal._activeTx.dry && this.swGlobal._activeTx.strict)); + const effectiveErrorMessage = shouldAutoThrow + ? `Internal write auto error for call [${JSON.stringify(debugData)}]: ${result.errorMessage}` + : result.errorMessage; + const resultErrorMessages = effectiveErrorMessage + ? { + ...result.originalErrorMessages, + [this.swGlobal._activeTx.id]: effectiveErrorMessage + } + : result.originalErrorMessages; + calleeContract.interactionState().update(calleeContract.txId(), { + state: result.state, + validity: { + ...result.originalValidity, + [this.swGlobal._activeTx.id]: result.type == 'ok' + }, + errorMessages: resultErrorMessages + }, this.swGlobal._activeTx.sortKey); + if (shouldAutoThrow) { + throw new HandlerExecutorFactory_1.ContractError(result.type === 'error' && result.error ? result.error : effectiveErrorMessage); + } + return result; + }; + } + assignViewContractState(executionContext) { + this.swGlobal.contracts.viewContractState = async (contractTxId, input) => { + this.logger.debug('swGlobal.viewContractState call:', { + from: this.contractDefinition.txId, + to: contractTxId, + input + }); + const childContract = executionContext.warp.contract(contractTxId, executionContext.contract, { + callingInteraction: this.swGlobal._activeTx, + callType: 'view' + }); + return await childContract.viewStateForTx(input, this.swGlobal._activeTx); + }; + } + assignReadContractState(executionContext, interactionTx) { + this.swGlobal.contracts.readContractState = async (contractTxId, returnValidity) => { + var _a, _b, _c; + this.logger.debug('swGlobal.readContractState call:', { + from: this.contractDefinition.txId, + to: contractTxId, + sortKey: interactionTx.sortKey, + transaction: this.swGlobal.transaction.id + }); + const { contract, warp } = executionContext; + const childContract = warp.contract(contractTxId, contract, { + callingInteraction: interactionTx, + callType: 'read' + }); + const stateWithValidity = await childContract.readState(interactionTx.sortKey); + if ((_a = stateWithValidity === null || stateWithValidity === void 0 ? void 0 : stateWithValidity.cachedValue) === null || _a === void 0 ? void 0 : _a.errorMessages) { + const errorKeys = Reflect.ownKeys((_b = stateWithValidity === null || stateWithValidity === void 0 ? void 0 : stateWithValidity.cachedValue) === null || _b === void 0 ? void 0 : _b.errorMessages); + if (errorKeys.length) { + const lastErrorKey = errorKeys[errorKeys.length - 1]; + const lastErrorMessage = (_c = stateWithValidity === null || stateWithValidity === void 0 ? void 0 : stateWithValidity.cachedValue) === null || _c === void 0 ? void 0 : _c.errorMessages[lastErrorKey]; + // don't judge me.. + // FIXME: also - '?' is stinky... + if (lastErrorMessage && + lastErrorMessage.startsWith && + (lastErrorMessage.startsWith('[SkipUnsafeError]') || + lastErrorMessage.startsWith('[NonWhitelistedSourceError]'))) { + throw new HandlerExecutorFactory_1.ContractError(lastErrorMessage); + } + } + } + // TODO: it should be up to the client's code to decide which part of the result to use + // (by simply using destructuring operator)... + // but this (i.e. returning always stateWithValidity from here) would break backwards compatibility + // in current contract's source code..:/ + const result = returnValidity + ? { + state: (0, utils_1.deepCopy)(stateWithValidity.cachedValue.state), + validity: stateWithValidity.cachedValue.validity, + errorMessages: stateWithValidity.cachedValue.errorMessages + } + : (0, utils_1.deepCopy)(stateWithValidity.cachedValue.state); + return result; + }; + } + assignRefreshState(executionContext) { + this.swGlobal.contracts.refreshState = async () => { + var _a; + return (_a = executionContext.contract + .interactionState() + .get(this.swGlobal.contract.id, this.swGlobal._activeTx.sortKey)) === null || _a === void 0 ? void 0 : _a.state; + }; + } +} +exports.AbstractContractHandler = AbstractContractHandler; +//# sourceMappingURL=AbstractContractHandler.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/handler/AbstractContractHandler.js.map b/lib/cjs/core/modules/impl/handler/AbstractContractHandler.js.map new file mode 100644 index 00000000..42e31bfb --- /dev/null +++ b/lib/cjs/core/modules/impl/handler/AbstractContractHandler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractContractHandler.js","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/handler/AbstractContractHandler.ts"],"names":[],"mappings":";;;AAKA,qEAAkE;AAClE,mDAAmD;AACnD,sEAA0G;AAE1G,MAAsB,uBAAuB;IAG3C,YACqB,QAA0B,EAC1B,kBAA6C;QAD7C,aAAQ,GAAR,QAAQ,CAAkB;QAC1B,uBAAkB,GAAlB,kBAAkB,CAA2B;QAJxD,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;QAM9D,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACvE,IAAI,CAAC,uBAAuB,GAAG,IA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,aAAa;iBAC3D;gBACH,CAAC,CAAC,IAAA,gBAAQ,EAAC,iBAAiB,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YAElD,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC;IACJ,CAAC;IAES,kBAAkB,CAAC,gBAAyC;QACpE,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,YAAY,GAAG,KAAK,IAAI,EAAE;;YAChD,OAAO,MAAA,gBAAgB,CAAC,QAAQ;iBAC7B,gBAAgB,EAAE;iBAClB,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,0CAAE,KAAK,CAAC;QAC5E,CAAC,CAAC;IACJ,CAAC;CACF;AA7KD,0DA6KC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/handler/JsHandlerApi.js b/lib/cjs/core/modules/impl/handler/JsHandlerApi.js new file mode 100644 index 00000000..b4fe6aad --- /dev/null +++ b/lib/cjs/core/modules/impl/handler/JsHandlerApi.js @@ -0,0 +1,193 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsHandlerApi = exports.KnownErrors = void 0; +const smartweave_global_1 = require("../../../../legacy/smartweave-global"); +const utils_1 = require("../../../../utils/utils"); +const HandlerExecutorFactory_1 = require("../HandlerExecutorFactory"); +const LexicographicalInteractionsSorter_1 = require("../LexicographicalInteractionsSorter"); +const AbstractContractHandler_1 = require("./AbstractContractHandler"); +const INIT_FUNC_NAME = '__init'; +const throwErrorWithName = (name, message) => { + const error = new Error(message); + error.name = name; + throw error; +}; +var KnownErrors; +(function (KnownErrors) { + KnownErrors["ContractError"] = "ContractError"; + KnownErrors["ConstructorError"] = "ConstructorError"; + KnownErrors["NetworkCommunicationError"] = "NetworkCommunicationError"; + KnownErrors["NonWhitelistedSourceError"] = "NonWhitelistedSourceError"; +})(KnownErrors = exports.KnownErrors || (exports.KnownErrors = {})); +class JsHandlerApi extends AbstractContractHandler_1.AbstractContractHandler { + constructor(swGlobal, contractDefinition, + // eslint-disable-next-line + contractFunction) { + super(swGlobal, contractDefinition); + this.contractFunction = contractFunction; + } + async handle(executionContext, currentResult, interactionData) { + const { interaction, interactionTx } = interactionData; + this.setupSwGlobal(interactionData); + this.enableInternalWrites(executionContext, interactionTx); + this.assertNotConstructorCall(interaction); + return await this.runContractFunction(executionContext, interaction, currentResult.state); + } + // eslint-disable-next-line + initState(state) { } + async maybeCallStateConstructor(initialState, executionContext) { + var _a, _b; + if ((_b = (_a = this.contractDefinition.manifest) === null || _a === void 0 ? void 0 : _a.evaluationOptions) === null || _b === void 0 ? void 0 : _b.useConstructor) { + const interaction = { + input: { function: INIT_FUNC_NAME, args: initialState }, + caller: this.contractDefinition.owner, + interactionType: 'write' + }; + const interactionTx = { + owner: { address: executionContext.caller, key: null }, + sortKey: LexicographicalInteractionsSorter_1.genesisSortKey + }; + const interactionData = { interaction, interactionTx }; + this.setupSwGlobal(interactionData); + const cleanUpSwGlobal = this.configureSwGlobalForConstructor(); + const result = await this.runContractFunction(executionContext, interaction, {}); + cleanUpSwGlobal(); + if (result.type !== 'ok') { + if (executionContext.contract.isRoot()) { + throw new Error(`ConstructorError: ${result.errorMessage}`); + } + else { + // note: see comments in 'catch' in 'runContractFunction' + throw new HandlerExecutorFactory_1.ContractError(`ConstructorError [${executionContext.contract.txId()}]: ${result.errorMessage}`, 'constructor'); + } + } + return result.state; + } + else { + return initialState; + } + } + assertNotConstructorCall(interaction) { + var _a, _b; + if (((_b = (_a = this.contractDefinition.manifest) === null || _a === void 0 ? void 0 : _a.evaluationOptions) === null || _b === void 0 ? void 0 : _b.useConstructor) && + interaction.input['function'] === INIT_FUNC_NAME) { + throw new Error(`You have enabled {useConstructor: true} option, so you can't call function ${INIT_FUNC_NAME}`); + } + } + configureSwGlobalForConstructor() { + const handler = (prop) => ({ + get: (target, property) => throwErrorWithName('ConstructorError', `SmartWeave.${prop}.${String(property)} is not accessible in constructor context`) + }); + this.swGlobal.contracts.readContractState = () => throwErrorWithName('ConstructorError', 'Internal writes feature is not available in constructor'); + this.swGlobal.contracts.viewContractState = () => throwErrorWithName('ConstructorError', 'Internal writes feature is not available in constructor'); + this.swGlobal.contracts.refreshState = () => throwErrorWithName('ConstructorError', 'Internal writes feature is not available in constructor'); + this.swGlobal.contracts.write = () => throwErrorWithName('ConstructorError', 'Internal writes feature is not available in constructor'); + const originalBlock = new smartweave_global_1.SWBlock(this.swGlobal); + this.swGlobal.block = new Proxy(this.swGlobal.block, handler('block')); + const originalVrf = new smartweave_global_1.SWVrf(this.swGlobal); + this.swGlobal.vrf = new Proxy(this.swGlobal.vrf, handler('vrf')); + const originalTransaction = new smartweave_global_1.SWTransaction(this.swGlobal); + this.swGlobal.transaction = new Proxy(this.swGlobal.vrf, handler('transaction')); + return () => { + this.swGlobal.block = originalBlock; + this.swGlobal.vrf = originalVrf; + this.swGlobal.transaction = originalTransaction; + }; + } + async runContractFunction(executionContext, interaction, state) { + const stateClone = (0, utils_1.deepCopy)(state); + const { timeoutId, timeoutPromise } = (0, utils_1.timeout)(executionContext.evaluationOptions.maxInteractionEvaluationTimeSeconds); + try { + await this.swGlobal.kv.open(); + await this.swGlobal.kv.begin(); + const handlerResult = await Promise.race([timeoutPromise, this.contractFunction(stateClone, interaction)]); + if (handlerResult && (handlerResult.state !== undefined || handlerResult.result !== undefined)) { + await this.swGlobal.kv.commit(); + let interactionEvent = null; + if (handlerResult.event) { + interactionEvent = { + contractTxId: this.swGlobal.contract.id, + sortKey: this.swGlobal.transaction.sortKey, + transactionId: this.swGlobal.transaction.id, + caller: interaction.caller, + input: interaction.input, + blockTimestamp: this.swGlobal.block.timestamp, + blockHeight: this.swGlobal.block.height, + data: handlerResult.event + }; + } + return { + type: 'ok', + result: handlerResult.result, + state: handlerResult.state || stateClone, + event: interactionEvent + }; + } + // Will be caught below as unexpected exception. + throw new Error(`Unexpected result from contract: ${JSON.stringify(handlerResult)}`); + } + catch (err) { + await this.swGlobal.kv.rollback(); + switch (err.name) { + case KnownErrors.ContractError: + return { + type: 'error', + errorMessage: err.message, + state: state, + result: null, + event: null + }; + case KnownErrors.ConstructorError: + // if that's the contract that we want to evaluate 'directly' - we need to stop evaluation immediately, + // BUT throwing exception in case of inner contract call would stop the base contract evaluation + // (and effectively block it from further evaluation) - https://github.com/warp-contracts/warp/issues/436 + if (executionContext.contract.isRoot()) { + throw Error(`ConstructorError: ${err.message}`); + } + else { + // i.e. if that is an inner contract call + // note: throwing ContractError here (in case of inner contract call) will (from the caller perspective) + // look like a ContractError thrown from the callee contract itself + throw new HandlerExecutorFactory_1.ContractError(`ConstructorError [${executionContext.contract.txId()}]: ${err.message}`, 'constructor'); + } + // any network-based error should result in immediately stop contract evaluation + case KnownErrors.NetworkCommunicationError: + throw err; + case KnownErrors.NonWhitelistedSourceError: + return { + type: 'error', + errorMessage: err.message, + state: state, + result: null, + event: null + }; + default: + return { + type: 'exception', + errorMessage: `${(err && err.stack) || (err && err.message) || err}`, + state: state, + result: null, + event: null + }; + } + } + finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + await this.swGlobal.kv.close(); + } + } + setupSwGlobal({ interaction, interactionTx }) { + this.swGlobal._activeTx = interactionTx; + this.swGlobal.caller = interaction.caller; // either contract tx id (for internal writes) or transaction.owner + } + enableInternalWrites(executionContext, interactionTx) { + this.assignReadContractState(executionContext, interactionTx); + this.assignViewContractState(executionContext); + this.assignWrite(executionContext); + this.assignRefreshState(executionContext); + } +} +exports.JsHandlerApi = JsHandlerApi; +//# sourceMappingURL=JsHandlerApi.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/handler/JsHandlerApi.js.map b/lib/cjs/core/modules/impl/handler/JsHandlerApi.js.map new file mode 100644 index 00000000..28fa26e2 --- /dev/null +++ b/lib/cjs/core/modules/impl/handler/JsHandlerApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"JsHandlerApi.js","sourceRoot":"","sources":["../../../../../../src/core/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CAAC,QAAQ,CAAC,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC,mEAAmE;IAChH,CAAC;IAEO,oBAAoB,CAC1B,gBAAkD,EAClD,aAA+B;QAE/B,IAAI,CAAC,uBAAuB,CAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC;QAC9D,IAAI,CAAC,uBAAuB,CAAQ,gBAAgB,CAAC,CAAC;QACtD,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;QACnC,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;IAC5C,CAAC;CACF;AA/ND,oCA+NC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/handler/WasmHandlerApi.js b/lib/cjs/core/modules/impl/handler/WasmHandlerApi.js new file mode 100644 index 00000000..516779d8 --- /dev/null +++ b/lib/cjs/core/modules/impl/handler/WasmHandlerApi.js @@ -0,0 +1,166 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WasmHandlerApi = void 0; +const HandlerExecutorFactory_1 = require("../HandlerExecutorFactory"); +const AbstractContractHandler_1 = require("./AbstractContractHandler"); +const utils_1 = require("../../../../utils/utils"); +class WasmHandlerApi extends AbstractContractHandler_1.AbstractContractHandler { + constructor(swGlobal, + // eslint-disable-next-line + contractDefinition, wasmExports) { + super(swGlobal, contractDefinition); + this.wasmExports = wasmExports; + } + async handle(executionContext, currentResult, interactionData) { + try { + const { interaction, interactionTx } = interactionData; + this.swGlobal._activeTx = interactionTx; + this.swGlobal.caller = interaction.caller; // either contract tx id (for internal writes) or transaction.owner + this.swGlobal.gasLimit = executionContext.evaluationOptions.gasLimit; + this.swGlobal.gasUsed = 0; + this.assignReadContractState(executionContext, interactionTx); + this.assignViewContractState(executionContext); + this.assignWrite(executionContext); + await this.swGlobal.kv.open(); + await this.swGlobal.kv.begin(); + const handlerResult = await this.doHandle(interaction); + if (interactionData.interaction.interactionType === 'view') { + // view calls are not allowed to perform any KV modifications + await this.swGlobal.kv.rollback(); + } + else { + await this.swGlobal.kv.commit(); + } + return { + type: 'ok', + result: handlerResult, + state: this.doGetCurrentState(), + gasUsed: this.swGlobal.gasUsed, + event: null + }; + } + catch (e) { + await this.swGlobal.kv.rollback(); + const result = { + errorMessage: e.message, + state: currentResult.state, + result: null + }; + if (e instanceof HandlerExecutorFactory_1.ContractError || e instanceof HandlerExecutorFactory_1.NonWhitelistedSourceError) { + return { + ...result, + error: e.error, + type: 'error', + event: null + }; + } + else if (e instanceof utils_1.NetworkCommunicationError) { + throw e; + } + else { + return { + ...result, + type: 'exception', + event: null + }; + } + } + finally { + await this.swGlobal.kv.close(); + } + } + initState(state) { + switch (this.contractDefinition.srcWasmLang) { + case 'rust': { + if ('initStateLegacy' in this.wasmExports) { + this.wasmExports.initStateLegacy(state); + return; + } + const ret = this.wasmExports.initState(state); + if (ret) { + throw new Error(ret); + } + else { + return; + } + } + default: { + throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`); + } + } + } + async doHandleLegacy(action) { + // pre- warp_contract macro contracts + const handleResult = await this.wasmExports.handle(action.input); + if (!handleResult) { + return; + } + if (Object.prototype.hasOwnProperty.call(handleResult, 'Ok')) { + return handleResult.Ok; + } + let errorKey; + let errorArgs = ''; + if (typeof handleResult.Err === 'string' || handleResult.Err instanceof String) { + errorKey = handleResult.Err; + } + else if ('kind' in handleResult.Err) { + throw new HandlerExecutorFactory_1.ContractError(handleResult.Err); + errorKey = handleResult.Err.kind; + errorArgs = 'data' in handleResult.Err ? ' ' + JSON.stringify(handleResult.Err.data, null, 2) : ''; + } + else { + errorKey = Object.keys(handleResult.Err)[0]; + errorArgs = ' ' + handleResult.Err[errorKey]; + } + if (errorKey == 'RuntimeError') { + throw new Error(`[RE:RE]${errorArgs}`); + } + else { + throw new HandlerExecutorFactory_1.ContractError(`[CE:${errorKey}${errorArgs}]`); + } + } + async doHandle(action) { + switch (this.contractDefinition.srcWasmLang) { + case 'rust': { + if ('handle' in this.wasmExports) { + return await this.doHandleLegacy(action); + } + const handleResult = action.interactionType === 'write' + ? await this.wasmExports.warpContractWrite(action.input) + : await this.wasmExports.warpContractView(action.input); + if (!handleResult) { + return; + } + if (handleResult.type === 'ok') { + return handleResult.result; + } + this.logger.error('Error from rust', handleResult); + if (handleResult.type === 'error') + throw new HandlerExecutorFactory_1.ContractError(handleResult.error); + throw new Error(handleResult.errorMessage); + } + default: { + throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`); + } + } + } + async maybeCallStateConstructor(initialState, executionContext) { + var _a, _b; + if ((_b = (_a = this.contractDefinition.manifest) === null || _a === void 0 ? void 0 : _a.evaluationOptions) === null || _b === void 0 ? void 0 : _b.useConstructor) { + throw Error('Constructor is not implemented for wasm'); + } + return initialState; + } + doGetCurrentState() { + switch (this.contractDefinition.srcWasmLang) { + case 'rust': { + return this.wasmExports.currentState(); + } + default: { + throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`); + } + } + } +} +exports.WasmHandlerApi = WasmHandlerApi; +//# sourceMappingURL=WasmHandlerApi.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/handler/WasmHandlerApi.js.map b/lib/cjs/core/modules/impl/handler/WasmHandlerApi.js.map new file mode 100644 index 00000000..4f1d2dc3 --- /dev/null +++ b/lib/cjs/core/modules/impl/handler/WasmHandlerApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WasmHandlerApi.js","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/handler/WasmHandlerApi.ts"],"names":[],"mappings":";;;AAKA,sEAMmC;AACnC,uEAAoE;AACpE,mDAAoE;AAEpE,MAAa,cAAsB,SAAQ,iDAA8B;IACvE,YACE,QAA0B;IAC1B,2BAA2B;IAC3B,kBAA6C,EAC5B,WAAgB;QAEjC,KAAK,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAC;QAFnB,gBAAW,GAAX,WAAW,CAAK;IAGnC,CAAC;IAED,KAAK,CAAC,MAAM,CACV,gBAAyC,EACz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D;QACD,OAAO,YAAY,CAAC;IACtB,CAAC;IAEO,iBAAiB;QACvB,QAAQ,IAAI,CAAC,kBAAkB,CAAC,WAAW,EAAE;YAC3C,KAAK,MAAM,CAAC,CAAC;gBACX,OAAO,IAAI,CAAC,WAAW,CAAC,YAAY,EAAE,CAAC;aACxC;YACD,OAAO,CAAC,CAAC;gBACP,MAAM,IAAI,KAAK,CAAC,eAAe,IAAI,CAAC,kBAAkB,CAAC,WAAW,uBAAuB,CAAC,CAAC;aAC5F;SACF;IACH,CAAC;CACF;AAxKD,wCAwKC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/normalize-source.js b/lib/cjs/core/modules/impl/normalize-source.js new file mode 100644 index 00000000..e0ef2dc0 --- /dev/null +++ b/lib/cjs/core/modules/impl/normalize-source.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkJsSrc = exports.normalizeContractSource = void 0; +const utils_1 = require("../../../utils/utils"); +function normalizeContractSource(contractSrc, useVM2) { + // Convert from ES Module format to something we can run inside a Function. + // Removes the `export` keyword and adds ;return handle to the end of the function. + // Additionally it removes 'IIFE' declarations + // (which may be generated when bundling multiple sources into one output file + // - eg. using esbuild's "IIFE" bundle format). + // We also assign the passed in SmartWeaveGlobal to SmartWeave, and declare + // the ContractError exception. + // We then use `new Function()` which we can call and get back the returned handle function + // which has access to the per-instance globals. + const lines = contractSrc.trim().split('\n'); + const first = lines[0]; + const last = lines[lines.length - 1]; + if ((/\(\s*\(\)\s*=>\s*{/g.test(first) || /\s*\(\s*function\s*\(\)\s*{/g.test(first)) && + /}\s*\)\s*\(\)\s*;/g.test(last)) { + lines.shift(); + lines.pop(); + contractSrc = lines.join('\n'); + } + contractSrc = contractSrc + .replace(/export\s+async\s+function\s+handle/gmu, 'async function handle') + .replace(/export\s+function\s+handle/gmu, 'function handle'); + if (useVM2) { + return ` + ${contractSrc} + module.exports = handle;`; + } + else { + return ` + const window=void 0,document=void 0,eval=void 0,globalThis=void 0; + const [SmartWeave, BigNumber, logger${(0, utils_1.isBrowser)() ? ', Buffer, atob, btoa' : ''}] = arguments; + class ContractError extends Error { constructor(message) { super(message); this.name = 'ContractError' } }; + function ContractAssert(cond, message) { if (!cond) throw new ContractError(message) }; + ${contractSrc}; + return handle; + `; + } +} +exports.normalizeContractSource = normalizeContractSource; +function checkJsSrc(src, logger) { + try { + const normalizedSource = normalizeContractSource(src, false); + new Function(normalizedSource)(); + return true; + } + catch (e) { + logger === null || logger === void 0 ? void 0 : logger.error(e); + return false; + } +} +exports.checkJsSrc = checkJsSrc; +//# sourceMappingURL=normalize-source.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/normalize-source.js.map b/lib/cjs/core/modules/impl/normalize-source.js.map new file mode 100644 index 00000000..857eb6a3 --- /dev/null +++ b/lib/cjs/core/modules/impl/normalize-source.js.map @@ -0,0 +1 @@ +{"version":3,"file":"normalize-source.js","sourceRoot":"","sources":["../../../../../src/core/modules/impl/normalize-source.ts"],"names":[],"mappings":";;;AAAA,gDAAiD;AAGjD,SAAgB,uBAAuB,CAAC,WAAmB,EAAE,MAAe;IAC1E,2EAA2E;IAC3E,mFAAmF;IACnF,8CAA8C;IAC9C,8EAA8E;IAC9E,+CAA+C;IAC/C,2EAA2E;IAC3E,+BAA+B;IAC/B,2FAA2F;IAC3F,gDAAgD;IAEhD,MAAM,KAAK,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC7C,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IACvB,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAErC,IACE,CAAC,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,8BAA8B,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACjF,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,EAC/B;QACA,KAAK,CAAC,KAAK,EAAE,CAAC;QACd,KAAK,CAAC,GAAG,EAAE,CAAC;QACZ,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;KAChC;IAED,WAAW,GAAG,WAAW;SACtB,OAAO,CAAC,uCAAuC,EAAE,uBAAuB,CAAC;SACzE,OAAO,CAAC,+BAA+B,EAAE,iBAAiB,CAAC,CAAC;IAE/D,IAAI,MAAM,EAAE;QACV,OAAO;MACL,WAAW;6BACY,CAAC;KAC3B;SAAM;QACL,OAAO;;0CAE+B,IAAA,iBAAS,GAAE,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,EAAE;;;MAG7E,WAAW;;GAEd,CAAC;KACD;AACH,CAAC;AA1CD,0DA0CC;AAED,SAAgB,UAAU,CAAC,GAAW,EAAE,MAAmB;IACzD,IAAI;QACF,MAAM,gBAAgB,GAAG,uBAAuB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC7D,IAAI,QAAQ,CAAC,gBAAgB,CAAC,EAAE,CAAC;QACjC,OAAO,IAAI,CAAC;KACb;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QACjB,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AATD,gCASC"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/wasm/WasmSrc.js b/lib/cjs/core/modules/impl/wasm/WasmSrc.js new file mode 100644 index 00000000..1e46fe22 --- /dev/null +++ b/lib/cjs/core/modules/impl/wasm/WasmSrc.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WasmSrc = void 0; +const unzipit_1 = require("unzipit"); +const warp_isomorphic_1 = require("warp-isomorphic"); +const LoggerFactory_1 = require("../../../../logging/LoggerFactory"); +class WasmSrc { + constructor(src) { + this.src = src; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('WasmSrc'); + this.splitted = this.splitBuffer(src); + this.logger.debug(`Buffer splitted into ${this.splitted.length} parts`); + } + wasmBinary() { + return this.splitted[0]; + } + async sourceCode() { + const { entries } = await (0, unzipit_1.unzip)(this.splitted[1]); + const result = new Map(); + for (const [name, entry] of Object.entries(entries)) { + if (entry.isDirectory) { + continue; + } + const content = await entry.text(); + result.set(name, content); + } + return result; + } + additionalCode() { + if (this.splitted.length == 2) { + return null; + } + return this.splitted[2].toString(); + } + splitBuffer(inputBuffer) { + let header = ''; + const elements = parseInt(inputBuffer.toString('utf8', 0, 1)); + this.logger.debug(`Number of elements: ${elements}`); + const l = inputBuffer.length; + let delimiters = 0; + let dataStart = 0; + for (let i = 2; i < l; i++) { + const element = inputBuffer.toString('utf8', i, i + 1); + if (element == '|') { + delimiters++; + } + if (delimiters == elements) { + dataStart = i + 1; + break; + } + header += element; + } + this.logger.debug(`Parsed:`, { + header, + dataStart + }); + const lengths = header.split('|').map((l) => parseInt(l)); + this.logger.debug('Lengths', lengths); + const result = []; + for (const length of lengths) { + const buffer = warp_isomorphic_1.Buffer.alloc(length); + const end = dataStart + length; + inputBuffer.copy(buffer, 0, dataStart, end); + dataStart = end; + result.push(buffer); + } + return result; + } +} +exports.WasmSrc = WasmSrc; +//# sourceMappingURL=WasmSrc.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/wasm/WasmSrc.js.map b/lib/cjs/core/modules/impl/wasm/WasmSrc.js.map new file mode 100644 index 00000000..14bd156d --- /dev/null +++ b/lib/cjs/core/modules/impl/wasm/WasmSrc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WasmSrc.js","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/wasm/WasmSrc.ts"],"names":[],"mappings":";;;AAAA,qCAAgC;AAChC,qDAAyC;AACzC,qEAAkE;AAElE,MAAa,OAAO;IAIlB,YAA6B,GAAW;QAAX,QAAG,GAAH,GAAG,CAAQ;QAHvB,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,SAA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newline at end of file diff --git a/lib/cjs/core/modules/impl/wasm/rust-wasm-imports.js b/lib/cjs/core/modules/impl/wasm/rust-wasm-imports.js new file mode 100644 index 00000000..ab44eff1 --- /dev/null +++ b/lib/cjs/core/modules/impl/wasm/rust-wasm-imports.js @@ -0,0 +1,1035 @@ +"use strict"; +/* tslint:disable */ +/* eslint-disable */ +/* a kind of magic */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rustWasmImports = void 0; +const LoggerFactory_1 = require("../../../../logging/LoggerFactory"); +// note: this is (somewhat heavily) modified code +// of the js that is normally generated by the wasm-bindgen +const rustWasmImports = (swGlobal, wbindgenImports, wasmInstance, dtorValue, warpContractsCrateVersion) => { + const wasmLogger = LoggerFactory_1.LoggerFactory.INST.create('WASM:Rust'); + // the raw functions, that we want to make available from the + // wasm module + const rawImports = { + metering: { + usegas: swGlobal.useGas + }, + console: { + log: function (value) { + wasmLogger.debug(`${swGlobal.contract.id}: ${value}`); + } + }, + Block: { + height: function () { + return swGlobal.block.height; + }, + indep_hash: function () { + return swGlobal.block.indep_hash; + }, + timestamp: function () { + return swGlobal.block.timestamp; + } + }, + Transaction: { + id: function () { + return swGlobal.transaction.id; + }, + owner: function () { + return swGlobal.transaction.owner; + }, + target: function () { + return swGlobal.transaction.target; + } + }, + Contract: { + id: function () { + return swGlobal.contract.id; + }, + owner: function () { + return swGlobal.contract.owner; + } + }, + KV: { + get: async function (key) { + return await swGlobal.kv.get(key); + }, + put: async function (key, value) { + await swGlobal.kv.put(key, value); + }, + del: async function (key) { + await swGlobal.kv.del(key); + }, + map: async function (gte, lt, reverse, limit) { + return await swGlobal.kv.kvMap({ + gte, + lt, + reverse, + limit + }); + }, + keys: async function (gte, lt, reverse, limit) { + return await swGlobal.kv.keys({ + gte, + lt, + reverse, + limit + }); + } + }, + SmartWeave: { + caller: function () { + return swGlobal.caller; + }, + readContractState: async function (contractTxId) { + return await swGlobal.contracts.readContractState(contractTxId); + }, + viewContractState: async function (contractTxId, input) { + return await swGlobal.contracts.viewContractState(contractTxId, input); + }, + write: async function (contractId, input) { + return await swGlobal.contracts.write(contractId, input, false); + } + }, + Vrf: { + value: function () { + return swGlobal.vrf.value; + }, + randomInt: function (maxValue) { + return swGlobal.vrf.randomInt(maxValue); + } + } + }; + let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + cachedTextDecoder.decode(); + let cachedUint8Memory0 = null; + function getUint8Memory0() { + if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) { + cachedUint8Memory0 = new Uint8Array(wasmInstance.exports.memory.buffer); + } + return cachedUint8Memory0; + } + function getStringFromWasm0(ptr, len) { + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); + } + const heap = new Array(128).fill(undefined); + heap.push(undefined, null, true, false); + let heap_next = heap.length; + function addHeapObject(obj) { + if (heap_next === heap.length) + heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + if (typeof heap_next !== 'number') + throw new Error('corrupt heap'); + heap[idx] = obj; + return idx; + } + function getObject(idx) { + return heap[idx]; + } + function _assertBoolean(n) { + if (typeof n !== 'boolean') { + throw new Error('expected a boolean argument'); + } + } + function isLikeNone(x) { + return x === undefined || x === null; + } + function _assertNum(n) { + if (typeof n !== 'number') + throw new Error('expected a number argument'); + } + let cachedFloat64Memory0 = null; + function getFloat64Memory0() { + if (cachedFloat64Memory0 === null || cachedFloat64Memory0.byteLength === 0) { + cachedFloat64Memory0 = new Float64Array(wasmInstance.exports.memory.buffer); + } + return cachedFloat64Memory0; + } + let cachedInt32Memory0 = null; + function getInt32Memory0() { + if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) { + cachedInt32Memory0 = new Int32Array(wasmInstance.exports.memory.buffer); + } + return cachedInt32Memory0; + } + let WASM_VECTOR_LEN = 0; + // @ts-ignore + let cachedTextEncoder = new TextEncoder('utf-8'); + const encodeString = typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); + } + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; + }; + function passStringToWasm0(arg, malloc, realloc) { + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length); + getUint8Memory0() + .subarray(ptr, ptr + buf.length) + .set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + let len = arg.length; + let ptr = malloc(len); + const mem = getUint8Memory0(); + let offset = 0; + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7f) + break; + mem[ptr + offset] = code; + } + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, (len = offset + arg.length * 3)); + const view = getUint8Memory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + offset += ret.written; + } + WASM_VECTOR_LEN = offset; + return ptr; + } + function dropObject(idx) { + if (idx < 132) + return; + heap[idx] = heap_next; + heap_next = idx; + } + function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; + } + function debugString(val) { + // primitive types + const type = typeof val; + if (type == 'number' || type == 'boolean' || val == null) { + return `${val}`; + } + if (type == 'string') { + return `"${val}"`; + } + if (type == 'symbol') { + const description = val.description; + if (description == null) { + return 'Symbol'; + } + else { + return `Symbol(${description})`; + } + } + if (type == 'function') { + const name = val.name; + if (typeof name == 'string' && name.length > 0) { + return `Function(${name})`; + } + else { + return 'Function'; + } + } + // objects + if (Array.isArray(val)) { + const length = val.length; + let debug = '['; + if (length > 0) { + debug += debugString(val[0]); + } + for (let i = 1; i < length; i++) { + debug += ', ' + debugString(val[i]); + } + debug += ']'; + return debug; + } + // Test for built-in + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches.length > 1) { + className = builtInMatches[1]; + } + else { + // Failed to match the standard '[object ClassName]' + return toString.call(val); + } + if (className == 'Object') { + // we're a user defined class or Object + // JSON.stringify avoids problems with cycles, and is generally much + // easier than looping through ownProperties of `val`. + try { + return 'Object(' + JSON.stringify(val) + ')'; + } + catch (_) { + return 'Object'; + } + } + // errors + if (val instanceof Error) { + return `${val.name}: ${val.message}\n${val.stack}`; + } + // TODO we could test for more things here, like `Set`s and `Map`s. + return className; + } + function _assertBigInt(n) { + if (typeof n !== 'bigint') + throw new Error('expected a bigint argument'); + } + let cachedBigInt64Memory0 = null; + function getBigInt64Memory0() { + if (cachedBigInt64Memory0 === null || cachedBigInt64Memory0.byteLength === 0) { + cachedBigInt64Memory0 = new BigInt64Array(wasmInstance.exports.memory.buffer); + } + return cachedBigInt64Memory0; + } + function makeMutClosure(arg0, arg1, dtor, f) { + const state = { a: arg0, b: arg1, cnt: 1, dtor }; + const real = (...args) => { + // First up with a closure we increment the internal reference + // count. This ensures that the Rust closure environment won't + // be deallocated while we're invoking it. + state.cnt++; + const a = state.a; + state.a = 0; + try { + return f(a, state.b, ...args); + } + finally { + if (--state.cnt === 0) { + wasmInstance.exports.__wbindgen_export_2.get(state.dtor)(a, state.b); + } + else { + state.a = a; + } + } + }; + real.original = state; + return real; + } + function logError(f, args) { + try { + return f.apply(this, args); + } + catch (e) { + let error = (function () { + try { + return e instanceof Error ? `${e.message}\n\nStack:\n${e.stack}` : e.toString(); + } + catch (_) { + return ''; + } + })(); + console.error('wasm-bindgen: imported JS function that was not marked as `catch` threw an error:', error); + throw e; + } + } + function __wbg_adapter_50(arg0, arg1, arg2) { + wasmInstance.modifiedExports._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__(arg0, arg1, addHeapObject(arg2)); + } + /** + * @param {any} interaction + * @returns {Promise} + */ + function warpContractWrite(interaction) { + const ret = wasmInstance.exports.warpContractWrite(addHeapObject(interaction)); + return takeObject(ret); + } + /** + * @param {any} interaction + * @returns {Promise} + */ + function handle(interaction) { + var ret = wasmInstance.exports.handle(addHeapObject(interaction)); + return takeObject(ret); + } + let stack_pointer = 128; + function addBorrowedObject(obj) { + if (stack_pointer == 1) + throw new Error('out of js stack'); + heap[--stack_pointer] = obj; + return stack_pointer; + } + /** + * @param {any} state + * @returns {boolean} + */ + function initState(state) { + try { + wasmInstance.exports.initState(addBorrowedObject(state)); + } + finally { + heap[stack_pointer++] = undefined; + } + } + function initStateLegacy(state) { + try { + wasmInstance.exports.initState(addBorrowedObject(state)); + } + finally { + heap[stack_pointer++] = undefined; + } + } + /** + * @returns {any} + */ + function currentState() { + const ret = wasmInstance.exports.currentState(); + return takeObject(ret); + } + /** + * @returns {number} + */ + function version() { + const ret = wasmInstance.exports.version(); + return ret; + } + /** + * @returns {number} + */ + function lang() { + const ret = wasmInstance.exports.lang(); + return ret; + } + /** + * @param {any} interaction + * @returns {Promise} + */ + function warpContractView(interaction) { + const ret = wasmInstance.exports.warpContractView(addHeapObject(interaction)); + return takeObject(ret); + } + function handleError(f, args) { + try { + return f.apply(this, args); + } + catch (e) { + wasmInstance.exports.__wbindgen_exn_store(addHeapObject(e)); + } + } + function __wbg_adapter_114(arg0, arg1, arg2, arg3) { + wasmInstance.modifiedExports.wasm_bindgen__convert__closures__invoke2_mut__(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3)); + } + function notDefined(what) { + return () => { + throw new Error(`${what} is not defined`); + }; + } + // mapping from base function names (without mangled suffixes) + // to functions normally generated by the wasm-bindgen + // - the "glue" code between js and wasm. + const baseImports = { + __wbindgen_json_parse: function (arg0, arg1) { + const ret = JSON.parse(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }, + __wbindgen_json_serialize: function (arg0, arg1) { + const obj = getObject(arg1); + const ret = JSON.stringify(obj === undefined ? null : obj); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, + __wbindgen_error_new: function (arg0, arg1) { + const ret = new Error(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }, + __wbindgen_is_undefined: function (arg0) { + const ret = getObject(arg0) === undefined; + return ret; + }, + __wbindgen_in: function (arg0, arg1) { + const ret = getObject(arg0) in getObject(arg1); + return ret; + }, + __wbindgen_number_get: function (arg0, arg1) { + const obj = getObject(arg1); + const ret = typeof obj === 'number' ? obj : undefined; + getFloat64Memory0()[arg0 / 8 + 1] = isLikeNone(ret) ? 0 : ret; + getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret); + }, + __wbindgen_boolean_get: function (arg0) { + const v = getObject(arg0); + const ret = typeof v === 'boolean' ? (v ? 1 : 0) : 2; + _assertNum(ret); + return ret; + }, + __wbindgen_is_null: function (arg0) { + const ret = getObject(arg0) === null; + _assertBoolean(ret); + return ret; + }, + __wbindgen_string_new: function (arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); + return addHeapObject(ret); + }, + __wbindgen_string_get: function (arg0, arg1) { + const obj = getObject(arg1); + const ret = typeof obj === 'string' ? obj : undefined; + var ptr0 = isLikeNone(ret) + ? 0 + : passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + var len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, + __wbindgen_is_bigint: function (arg0) { + const ret = typeof getObject(arg0) === 'bigint'; + return ret; + }, + __wbindgen_is_object: function (arg0) { + const val = getObject(arg0); + const ret = typeof val === 'object' && val !== null; + return ret; + }, + __wbindgen_object_clone_ref: function (arg0) { + const ret = getObject(arg0); + return addHeapObject(ret); + }, + __wbindgen_jsval_eq: function (arg0, arg1) { + const ret = getObject(arg0) === getObject(arg1); + return ret; + }, + __wbindgen_bigint_from_i64: function (arg0) { + const ret = arg0; + return addHeapObject(ret); + }, + __wbindgen_bigint_from_u64: function (arg0) { + const ret = BigInt.asUintN(64, arg0); + return addHeapObject(ret); + }, + __wbg_readContractState: function () { + return handleError(function (arg0, arg1) { + const ret = rawImports.SmartWeave.readContractState(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_viewContractState: function () { + return handleError(function (arg0, arg1, arg2) { + const ret = rawImports.SmartWeave.viewContractState(getStringFromWasm0(arg0, arg1), takeObject(arg2)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_write: function () { + return handleError(function (arg0, arg1, arg2) { + const ret = rawImports.SmartWeave.write(getStringFromWasm0(arg0, arg1), takeObject(arg2)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_refreshState: function (arg0, arg1) { + // TODO + }, + __wbg_kvGet: function () { + return handleError(function (arg0, arg1) { + const ret = rawImports.KV.get(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_kvPut: function () { + return handleError(function (arg0, arg1, arg2) { + const ret = rawImports.KV.put(getStringFromWasm0(arg0, arg1), takeObject(arg2)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_kvDel: function () { + return handleError(function (arg0, arg1) { + const ret = rawImports.KV.del(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_kvMap: function () { + return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6) { + const ret = rawImports.KV.map(arg0 === 0 ? undefined : getStringFromWasm0(arg0, arg1), arg2 === 0 ? undefined : getStringFromWasm0(arg2, arg3), arg4 === 0xffffff ? undefined : arg4 !== 0, arg5 === 0 ? undefined : arg6 >>> 0); + return addHeapObject(ret); + }, arguments); + }, + __wbg_kvKeys: function () { + return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6) { + const ret = rawImports.KV.keys(arg0 === 0 ? undefined : getStringFromWasm0(arg0, arg1), arg2 === 0 ? undefined : getStringFromWasm0(arg2, arg3), arg4 === 0xffffff ? undefined : arg4 !== 0, arg5 === 0 ? undefined : arg6 >>> 0); + return addHeapObject(ret); + }, arguments); + }, + __wbindgen_object_drop_ref: function (arg0) { + takeObject(arg0); + }, + __wbg_error: function () { + return logError(function (arg0, arg1) { + try { + rawImports.console.log(getStringFromWasm0(arg0, arg1)); + } + finally { + wasmInstance.exports.__wbindgen_free(arg0, arg1); + } + }, arguments); + }, + __wbg_new_abda76e883ba8a5f: function () { + return logError(function () { + const ret = new Error(); + return addHeapObject(ret); + }, arguments); + }, + __wbg_stack: function () { + return logError(function (arg0, arg1) { + let limit = Error.stackTraceLimit; + Error.stackTraceLimit = 25; + const ret = getObject(arg1).stack; + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + Error.stackTraceLimit = limit; + }, arguments); + }, + __wbg_indephash: function () { + return logError(function (arg0) { + const ret = rawImports.Block.indep_hash(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, arguments); + }, + __wbg_height: function () { + return logError(function () { + const ret = rawImports.Block.height(); + _assertNum(ret); + return ret; + }, arguments); + }, + __wbg_timestamp: function () { + return logError(function () { + const ret = rawImports.Block.timestamp(); + _assertNum(ret); + return ret; + }, arguments); + }, + __wbg_contractId: function () { + return logError(function (arg0) { + const ret = rawImports.Contract.id(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, arguments); + }, + __wbg_contractOwner: function () { + return logError(function (arg0) { + const ret = rawImports.Contract.owner(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, arguments); + }, + __wbg_id: function (arg0) { + const ret = rawImports.Transaction.id(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, + __wbg_owner: function (arg0) { + const ret = rawImports.Transaction.owner(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, + __wbg_target: function () { + return logError(function (arg0) { + const ret = rawImports.Transaction.target(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, arguments); + }, + __wbg_caller: function (arg0) { + const ret = rawImports.SmartWeave.caller(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, + __wbg_value_b245bf3240b21a48: function () { + return logError(function (arg0) { + const ret = rawImports.Vrf.value(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, arguments); + }, + __wbg_value_7d69ddc3f1ad7876: function () { + return logError(function (arg0) { + const ret = rawImports.Vrf.value(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, arguments); + }, + __wbg_vrfValue: function () { + return logError(function (arg0) { + const ret = rawImports.Vrf.value(); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, arguments); + }, + __wbg_randomInt: function () { + return logError(function (arg0) { + const ret = rawImports.Vrf.randomInt(arg0); + _assertNum(ret); + return ret; + }, arguments); + }, + __wbg_log: function (arg0, arg1) { + console.log(getStringFromWasm0(arg0, arg1)); + }, + __wbindgen_cb_drop: function (arg0) { + const obj = takeObject(arg0).original; + if (obj.cnt-- == 1) { + obj.a = 0; + return true; + } + const ret = false; + return ret; + }, + __wbg_debug: function () { + return logError(function (arg0) { + console.log(getObject(arg0)); + }, arguments); + }, + __wbg_String: function () { + return logError(function (arg0, arg1) { + const ret = String(getObject(arg1)); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, arguments); + }, + __wbg_getwithrefkey: function (arg0, arg1) { + const ret = getObject(arg0)[getObject(arg1)]; + return addHeapObject(ret); + }, + __wbg_set_841ac57cff3d672b: function (arg0, arg1, arg2) { + getObject(arg0)[takeObject(arg1)] = takeObject(arg2); + }, + __wbindgen_number_new: function (arg0) { + const ret = arg0; + return addHeapObject(ret); + }, + __wbindgen_jsval_loose_eq: function (arg0, arg1) { + const ret = getObject(arg0) == getObject(arg1); + return ret; + }, + __wbg_get_27fe3dac1c4d0224: function (arg0, arg1) { + const ret = getObject(arg0)[arg1 >>> 0]; + return addHeapObject(ret); + }, + __wbg_set_17224bc548dd1d7b: function (arg0, arg1, arg2) { + getObject(arg0)[arg1 >>> 0] = takeObject(arg2); + }, + __wbg_isArray: function (arg0) { + const ret = Array.isArray(getObject(arg0)); + return ret; + }, + __wbg_length_e498fbc24f9c1d4f: function (arg0) { + const ret = getObject(arg0).length; + return ret; + }, + __wbg_new_b525de17f44a8943: function () { + const ret = new Array(); + return addHeapObject(ret); + }, + __wbg_instanceof_ArrayBuffer: function (arg0) { + let result; + try { + result = getObject(arg0) instanceof ArrayBuffer; + } + catch { + result = false; + } + const ret = result; + return ret; + }, + __wbg_call_95d1ea488d03e4e8: function () { + return handleError(function (arg0, arg1) { + const ret = getObject(arg0).call(getObject(arg1)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_call_9495de66fdbe016b: function () { + return handleError(function (arg0, arg1, arg2) { + const ret = getObject(arg0).call(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_call_94697a95cb7e239c: function () { + return handleError(function (arg0, arg1, arg2) { + const ret = getObject(arg0).call(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_new_f841cc6f2098f4b5: function () { + const ret = new Map(); + return addHeapObject(ret); + }, + __wbg_set_388c4c6422704173: function (arg0, arg1, arg2) { + const ret = getObject(arg0).set(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); + }, + __wbg_next_88560ec06a094dea: function () { + return handleError(function (arg0) { + const ret = getObject(arg0).next(); + return addHeapObject(ret); + }, arguments); + }, + __wbg_next_b7d530c04fd8b217: function (arg0) { + const ret = getObject(arg0).next; + return addHeapObject(ret); + }, + __wbg_done: function (arg0) { + const ret = getObject(arg0).done; + return ret; + }, + __wbg_value_6ac8da5cc5b3efda: function (arg0) { + const ret = getObject(arg0).value; + return addHeapObject(ret); + }, + __wbg_isSafeInteger: function (arg0) { + const ret = Number.isSafeInteger(getObject(arg0)); + return ret; + }, + __wbg_entries: function (arg0) { + const ret = Object.entries(getObject(arg0)); + return addHeapObject(ret); + }, + __wbg_new_f9876326328f45ed: function () { + const ret = new Object(); + return addHeapObject(ret); + }, + __wbg_iterator: function () { + const ret = Symbol.iterator; + return addHeapObject(ret); + }, + __wbg_new_9d3a9ce4282a18a8: function (arg0, arg1) { + try { + var state0 = { a: arg0, b: arg1 }; + var cb0 = (arg0, arg1) => { + const a = state0.a; + state0.a = 0; + try { + return __wbg_adapter_114(a, state0.b, arg0, arg1); + } + finally { + state0.a = a; + } + }; + const ret = new Promise(cb0); + return addHeapObject(ret); + } + finally { + state0.a = state0.b = 0; + } + }, + __wbg_resolve: function (arg0) { + const ret = Promise.resolve(getObject(arg0)); + return addHeapObject(ret); + }, + __wbg_then_ec5db6d509eb475f: function (arg0, arg1) { + const ret = getObject(arg0).then(getObject(arg1)); + return addHeapObject(ret); + }, + __wbg_then_a6860c82b90816ca: function () { + return logError(function (arg0, arg1) { + const ret = getObject(arg0).then(getObject(arg1)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_then_f753623316e2873a: function (arg0, arg1, arg2) { + const ret = getObject(arg0).then(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); + }, + __wbg_then_58a04e42527f52c6: function () { + return logError(function (arg0, arg1, arg2) { + const ret = getObject(arg0).then(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); + }, arguments); + }, + __wbg_instanceof_Uint8Array: function (arg0) { + let result; + try { + result = getObject(arg0) instanceof Uint8Array; + } + catch { + result = false; + } + const ret = result; + return ret; + }, + __wbg_new_537b7341ce90bb31: function (arg0) { + const ret = new Uint8Array(getObject(arg0)); + return addHeapObject(ret); + }, + __wbg_length_27a2afe8ab42b09f: function (arg0) { + const ret = getObject(arg0).length; + return ret; + }, + __wbg_set_17499e8aa4003ebd: function (arg0, arg1, arg2) { + getObject(arg0).set(getObject(arg1), arg2 >>> 0); + }, + __wbindgen_is_function: function (arg0) { + const ret = typeof getObject(arg0) === 'function'; + return ret; + }, + __wbindgen_is_string: function (arg0) { + const ret = typeof getObject(arg0) === 'string'; + return ret; + }, + __wbg_buffer: function (arg0) { + const ret = getObject(arg0).buffer; + return addHeapObject(ret); + }, + __wbg_get_baf4855f9a986186: function () { + return handleError(function (arg0, arg1) { + const ret = Reflect.get(getObject(arg0), getObject(arg1)); + return addHeapObject(ret); + }, arguments); + }, + __wbindgen_debug_string: function (arg0, arg1) { + const ret = debugString(getObject(arg1)); + const ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }, + __wbindgen_bigint_get_as_i64: function (arg0, arg1) { + const v = getObject(arg1); + const ret = typeof v === 'bigint' ? v : undefined; + getBigInt64Memory0()[arg0 / 8 + 1] = isLikeNone(ret) ? BigInt(0) : ret; + getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret); + }, + __wbindgen_throw: function (arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); + }, + __wbindgen_memory: function () { + const ret = wasmInstance.exports.memory; + return addHeapObject(ret); + }, + __wbindgen_closure_wrapper: function (arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, dtorValue, __wbg_adapter_50); + return addHeapObject(ret); + } + }; + const helpers = { + _assertBoolean, + _assertNum, + addBorrowedObject, + addHeapObject, + getInt32Memory0, + getObject, + getStringFromWasm0, + handleError, + heap: () => heap, + logError, + notDefined, + passStringToWasm0, + takeObject, + wasm: () => wasmInstance.exports, + WASM_VECTOR_LEN: () => WASM_VECTOR_LEN, + __wbg_adapter_1: __wbg_adapter_114, + __wbg_adapter_5: __wbg_adapter_50 + }; + function wrapPluginMethod(f) { + return function () { + return logError(function (arg0) { + const ret = f(takeObject(arg0)); + return addHeapObject(ret); + }, arguments); + }; + } + function extensionsDefinedImports(swGlobal, helpers) { + var _a, _b; + let res = {}; + for (const [_, extension] of Object.entries(swGlobal.extensions)) { + let imports = (_b = (_a = extension.rustImports) === null || _a === void 0 ? void 0 : _a.call(extension, helpers)) !== null && _b !== void 0 ? _b : {}; + for (const [fName, f] of Object.entries(imports)) { + if (fName.startsWith('__wbg_')) { + res[fName] = f; + } + else { + res['__wbg_' + fName] = wrapPluginMethod(f); + } + } + } + return res; + } + const allBaseImports = { ...baseImports, ...extensionsDefinedImports(swGlobal, helpers) }; + const baseImportsKeys = Object.keys(allBaseImports); + // assigning functions to "real" import names from the currently + // compiled wasm module + let module = wbindgenImports.reduce((acc, wbindgenKey) => { + const baseImportsKey = baseImportsKeys.find((key) => wbindgenKey.startsWith(key)); + if (baseImportsKey === undefined) { + throw new Error(`Cannot find import mapping for ${wbindgenKey}. Please file a bug.`); + } + if (baseImportsKeys.filter((key) => wbindgenKey.startsWith(key)).length != 1) { + throw new Error(`Multiple import mappings for ${wbindgenKey}. Please file a bug.`); + } + if (acc.usedKeys.has(baseImportsKey)) { + throw new Error(`Multiple methods maps to ${baseImportsKey}. Please file a bug.`); + } + acc.res[wbindgenKey] = allBaseImports[baseImportsKey]; + acc.usedKeys.add(baseImportsKey); + return acc; + }, { res: {}, usedKeys: new Set() }).res; + if (warpContractsCrateVersion === '__WARP_CONTRACTS_VERSION_LEGACY') { + module.initStateLegacy = initStateLegacy; + module.handle = handle; + } + else { + module.initState = initState; + module.warpContractWrite = warpContractWrite; + module.warpContractView = warpContractView; + } + module.currentState = currentState; + module.version = version; + module.lang = lang; + // the rest of the code is basically left untouched from what + // wasm-bindgen generates + let imports = {}; + imports['__wbindgen_placeholder__'] = module; + /** + */ + class StateWrapper { + __destroy_into_raw() { + // @ts-ignore + const ptr = this.ptr; + // @ts-ignore + this.ptr = 0; + return ptr; + } + free() { + const ptr = this.__destroy_into_raw(); + wasmInstance.exports.__wbg_statewrapper_free(ptr); + } + } + module.StateWrapper = StateWrapper; + imports.metering = rawImports.metering; + return { imports, exports: module }; +}; +exports.rustWasmImports = rustWasmImports; +//# sourceMappingURL=rust-wasm-imports.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/wasm/rust-wasm-imports.js.map b/lib/cjs/core/modules/impl/wasm/rust-wasm-imports.js.map new file mode 100644 index 00000000..065a9583 --- /dev/null +++ b/lib/cjs/core/modules/impl/wasm/rust-wasm-imports.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rust-wasm-imports.js","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/wasm/rust-wasm-imports.ts"],"names":[],"mappings":";AAAA,oBAAoB;AACpB,oBAAoB;AACpB,qBAAqB;;;AAErB,qEAAkE;AAmClE,iDAAiD;AACjD,2DAA2D;AACpD,MAAM,eAAe,GAAG,CAC7B,QAAQ,EACR,eAAe,EACf,YAAY,EACZ,SAAS,EACT,yBAAoD,EAC/C,EAAE;IACP,MAAM,UAAU,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAE1D,6DAA6D;IAC7D,cAAc;IACd,MAAM,UAAU,GAAG;QACjB,QAAQ,EAAE;YACR,MAAM,EAAE,QAAQ,CAAC,MAAM;SACxB;QACD,OAAO,EAAE;YACP,GAAG,EAAE,UAAU,KAAK;gBAClB,UAAU,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,EAAE,KAAK,KAAK,EAAE,CAAC,CAAC;YACxD,CAAC;SACF;QACD,KAAK,EAAE;YACL,MAAM,EAAE;gBACN,OAAO,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC;YAC/B,CAAC;YACD,UAAU,EAAE;gBACV,OAAO,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC;YACnC,CAAC;YACD,SAAS,EAAE;gBACT,OAAO,QAAQ,CAAC,KAAK,CAAC,SAAS,CAAC;YAClC,CAAC;SACF;QACD,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AC;IAEnB,6DAA6D;IAC7D,yBAAyB;IACzB,IAAI,OAAO,GAAQ,EAAE,CAAC;IAEtB,OAAO,CAAC,0BAA0B,CAAC,GAAG,MAAM,CAAC;IAE7C;OACG;IACH,MAAM,YAAY;QAChB,kBAAkB;YAChB,aAAa;YACb,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;YACrB,aAAa;YACb,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;YACb,OAAO,GAAG,CAAC;QACb,CAAC;QAED,IAAI;YACF,MAAM,GAAG,GAAG,IAAI,CAAC,kBAAkB,EAAE,CAAC;YACtC,YAAY,CAAC,OAAO,CAAC,uBAAuB,CAAC,GAAG,CAAC,CAAC;QACpD,CAAC;KACF;IAED,MAAM,CAAC,YAAY,GAAG,YAAY,CAAC;IACnC,OAAO,CAAC,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC;IAEvC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;AACtC,CAAC,CAAC;AArtCW,QAAA,eAAe,mBAqtC1B"} \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/wasm/wasm-bindgen-tools.js b/lib/cjs/core/modules/impl/wasm/wasm-bindgen-tools.js new file mode 100644 index 00000000..e6517601 --- /dev/null +++ b/lib/cjs/core/modules/impl/wasm/wasm-bindgen-tools.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.matchMutClosureDtor = void 0; +function matchMutClosureDtor(source) { + const regexp = /(const|var) ret = makeMutClosure\(arg0, arg1, (\d+?), __wbg_adapter/; + const match = source.match(regexp); + return match[2]; +} +exports.matchMutClosureDtor = matchMutClosureDtor; +//# sourceMappingURL=wasm-bindgen-tools.js.map \ No newline at end of file diff --git a/lib/cjs/core/modules/impl/wasm/wasm-bindgen-tools.js.map b/lib/cjs/core/modules/impl/wasm/wasm-bindgen-tools.js.map new file mode 100644 index 00000000..406bf98b --- /dev/null +++ b/lib/cjs/core/modules/impl/wasm/wasm-bindgen-tools.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wasm-bindgen-tools.js","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/wasm/wasm-bindgen-tools.ts"],"names":[],"mappings":";;;AAAA,SAAgB,mBAAmB,CAAC,MAAc;IAChD,MAAM,MAAM,GAAG,qEAAqE,CAAC;IACrF,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAJD,kDAIC"} \ No newline at end of file diff --git a/lib/cjs/index.js b/lib/cjs/index.js new file mode 100644 index 00000000..bf47b748 --- /dev/null +++ b/lib/cjs/index.js @@ -0,0 +1,79 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./logging/web/ConsoleLogger"), exports); +__exportStar(require("./logging/web/ConsoleLoggerFactory"), exports); +__exportStar(require("./logging/WarpLogger"), exports); +__exportStar(require("./logging/LoggerFactory"), exports); +__exportStar(require("./logging/LoggerSettings"), exports); +__exportStar(require("./logging/Benchmark"), exports); +__exportStar(require("./cache/BasicSortKeyCache"), exports); +__exportStar(require("./cache/SortKeyCache"), exports); +__exportStar(require("./cache/WarpCache"), exports); +__exportStar(require("./cache/impl/LevelDbCache"), exports); +__exportStar(require("./cache/impl/MemCache"), exports); +__exportStar(require("./core/modules/DefinitionLoader"), exports); +__exportStar(require("./core/modules/ExecutorFactory"), exports); +__exportStar(require("./core/modules/InteractionsLoader"), exports); +__exportStar(require("./core/modules/InteractionsSorter"), exports); +__exportStar(require("./core/modules/StateEvaluator"), exports); +__exportStar(require("./core/modules/impl/ContractDefinitionLoader"), exports); +__exportStar(require("./core/modules/impl/WarpGatewayContractDefinitionLoader"), exports); +__exportStar(require("./core/modules/impl/ArweaveGatewayInteractionsLoader"), exports); +__exportStar(require("./core/modules/impl/WarpGatewayInteractionsLoader"), exports); +__exportStar(require("./core/modules/impl/CacheableInteractionsLoader"), exports); +__exportStar(require("./core/modules/impl/DefaultStateEvaluator"), exports); +__exportStar(require("./core/modules/impl/CacheableStateEvaluator"), exports); +__exportStar(require("./core/modules/impl/HandlerExecutorFactory"), exports); +__exportStar(require("./core/modules/impl/LexicographicalInteractionsSorter"), exports); +__exportStar(require("./core/modules/impl/TagsParser"), exports); +__exportStar(require("./core/modules/impl/normalize-source"), exports); +__exportStar(require("./core/modules/impl/handler/AbstractContractHandler"), exports); +__exportStar(require("./core/modules/impl/handler/JsHandlerApi"), exports); +__exportStar(require("./core/modules/impl/handler/WasmHandlerApi"), exports); +__exportStar(require("./core/ExecutionContextModifier"), exports); +__exportStar(require("./core/KnownTags"), exports); +__exportStar(require("./core/ExecutionContext"), exports); +__exportStar(require("./core/ContractDefinition"), exports); +__exportStar(require("./core/ContractCallRecord"), exports); +__exportStar(require("./core/WarpFactory"), exports); +__exportStar(require("./core/Warp"), exports); +__exportStar(require("./core/WarpBuilder"), exports); +__exportStar(require("./core/WarpPlugin"), exports); +__exportStar(require("./core/WarpFetchWrapper"), exports); +__exportStar(require("./contract/Contract"), exports); +__exportStar(require("./contract/HandlerBasedContract"), exports); +__exportStar(require("./contract/PstContract"), exports); +__exportStar(require("./contract/PstContractImpl"), exports); +__exportStar(require("./contract/InnerWritesEvaluator"), exports); +__exportStar(require("./contract/Signature"), exports); +__exportStar(require("./contract/EvaluationOptionsEvaluator"), exports); +__exportStar(require("./contract/deploy/Source"), exports); +__exportStar(require("./contract/deploy/CreateContract"), exports); +__exportStar(require("./legacy/gqlResult"), exports); +__exportStar(require("./legacy/smartweave-global"), exports); +__exportStar(require("./legacy/errors"), exports); +__exportStar(require("./legacy/utils"), exports); +__exportStar(require("./legacy/create-interaction-tx"), exports); +__exportStar(require("./utils/utils"), exports); +__exportStar(require("./utils/ArweaveWrapper"), exports); +__exportStar(require("./utils/types/arweave-types"), exports); +__exportStar(require("./core/modules/impl/wasm/WasmSrc"), exports); +__exportStar(require("./core/modules/impl/wasm/rust-wasm-imports"), exports); +__exportStar(require("./core/modules/impl/wasm/wasm-bindgen-tools"), exports); +__exportStar(require("./core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader"), exports); +__exportStar(require("./core/modules/impl/ArweaveGatewayBundledInteractionLoader"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/cjs/index.js.map b/lib/cjs/index.js.map new file mode 100644 index 00000000..fb5e726f --- /dev/null +++ b/lib/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,8DAA4C;AAC5C,qEAAmD;AACnD,uDAAqC;AACrC,0DAAwC;AACxC,2DAAyC;AACzC,sDAAoC;AAEpC,4DAA0C;AAC1C,uDAAqC;AACrC,oDAAkC;AAClC,4DAA0C;AAC1C,wDAAsC;AAEtC,kEAAgD;AAChD,iEAA+C;AAC/C,oEAAkD;AAClD,oEAAkD;AAClD,gEAA8C;AAE9C,+EAA6D;AAC7D,0FAAwE;AACxE,uFAAqE;AACrE,oFAAkE;AAClE,kFAAgE;AAChE,4EAA0D;AAC1D,8EAA4D;AAC5D,6EAA2D;AAC3D,wFAAsE;AACtE,iEAA+C;AAC/C,uEAAqD;AACrD,sFAAoE;AACpE,2EAAyD;AACzD,6EAA2D;AAE3D,kEAAgD;AAChD,mDAAiC;AACjC,0DAAwC;AACxC,4DAA0C;AAC1C,4DAA0C;AAE1C,qDAAmC;AACnC,8CAA4B;AAC5B,qDAAmC;AACnC,oDAAkC;AAClC,0DAAwC;AAExC,sDAAoC;AACpC,kEAAgD;AAChD,yDAAuC;AACvC,6DAA2C;AAC3C,kEAAgD;AAChD,uDAAqC;AACrC,wEAAsD;AACtD,2DAAyC;AACzC,mEAAiD;AAEjD,qDAAmC;AACnC,6DAA2C;AAC3C,kDAAgC;AAChC,iDAA+B;AAC/B,iEAA+C;AAE/C,gDAA8B;AAC9B,yDAAuC;AACvC,8DAA4C;AAE5C,mEAAiD;AACjD,6EAA2D;AAC3D,8EAA4D;AAE5D,oGAAkF;AAClF,6FAA2E"} \ No newline at end of file diff --git a/lib/cjs/legacy/create-interaction-tx.js b/lib/cjs/legacy/create-interaction-tx.js new file mode 100644 index 00000000..824bfadc --- /dev/null +++ b/lib/cjs/legacy/create-interaction-tx.js @@ -0,0 +1,103 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createInteractionTagsList = exports.createDummyTx = exports.createInteractionTx = void 0; +const KnownTags_1 = require("../core/KnownTags"); +const TagsParser_1 = require("../core/modules/impl/TagsParser"); +const arweave_types_1 = require("../utils/types/arweave-types"); +async function createInteractionTx(arweave, signer, contractId, input, tags, target = '', winstonQty = '0', dummy = false, isTestnet, reward) { + const options = { + data: Math.random().toString().slice(-4) + }; + if (target && target.length) { + options.target = target.toString(); + if (winstonQty && +winstonQty > 0) { + options.quantity = winstonQty.toString(); + } + } + // both reward and last_tx are irrelevant in case of interactions + // that are bundled. So to speed up the process (and prevent the arweave-js + // from calling /tx_anchor and /price endpoints) - we're presetting these + // values here + if (dummy) { + options.reward = '0'; + options.last_tx = 'p7vc1iSP6bvH_fCeUFa9LqoV5qiyW-jdEKouAT0XMoSwrNraB9mgpi29Q10waEpO'; + } + if (reward && reward.length) { + options.reward = reward; + } + const interactionTx = await arweave.createTransaction(options); + const interactionTags = createInteractionTagsList(contractId, input, isTestnet, tags); + interactionTags.forEach((t) => interactionTx.addTag(t.name, t.value)); + if (signer) { + await signer(interactionTx); + } + return interactionTx; +} +exports.createInteractionTx = createInteractionTx; +function createDummyTx(tx, from, block) { + // transactions loaded from gateway (either arweave.net GQL or Warp) have the tags decoded + // - so to be consistent, the "dummy" tx, which is used for viewState and dryWrites, also has to have + // the tags decoded. + const tagsParser = new TagsParser_1.TagsParser(); + const decodedTags = tagsParser.decodeTags(tx); + return { + id: tx.id, + owner: { + address: from, + key: '' + }, + recipient: tx.target, + tags: decodedTags, + fee: { + winston: tx.reward, + ar: '' + }, + quantity: { + winston: tx.quantity, + ar: '' + }, + block: { + id: block.indep_hash, + height: block.height, + timestamp: block.timestamp, + previous: null + }, + // note: calls within dry runs cannot be cached (per block - like the state cache)! + // that's super important, as the block height used for + // the dry-run is the current network block height + // - and not the block height of the real transaction that + // will be mined on Arweave. + // If we start caching results of the dry-runs, we can completely fuck-up + // the consecutive state evaluations. + // - that's why we're setting "dry" flag to true here + // - this prevents the caching layer from saving + // the state evaluated for such interaction in cache. + dry: true, + anchor: null, + signature: null, + data: null, + parent: null, + bundledIn: null + }; +} +exports.createDummyTx = createDummyTx; +function createInteractionTagsList(contractId, input, isTestnet, customTags) { + const interactionTags = []; + if (customTags && customTags.length) { + for (const customTag of customTags) { + interactionTags.push(new arweave_types_1.Tag(customTag.name.toString(), customTag.value.toString())); + } + } + interactionTags.push(new arweave_types_1.Tag(KnownTags_1.SMART_WEAVE_TAGS.APP_NAME, 'SmartWeaveAction')); + // use real SDK version here? + interactionTags.push(new arweave_types_1.Tag(KnownTags_1.SMART_WEAVE_TAGS.APP_VERSION, '0.3.0')); + interactionTags.push(new arweave_types_1.Tag(KnownTags_1.SMART_WEAVE_TAGS.SDK, 'Warp')); + interactionTags.push(new arweave_types_1.Tag(KnownTags_1.SMART_WEAVE_TAGS.CONTRACT_TX_ID, contractId)); + interactionTags.push(new arweave_types_1.Tag(KnownTags_1.SMART_WEAVE_TAGS.INPUT, JSON.stringify(input))); + if (isTestnet) { + interactionTags.push(new arweave_types_1.Tag(KnownTags_1.WARP_TAGS.WARP_TESTNET, '1.0.0')); + } + return interactionTags; +} +exports.createInteractionTagsList = createInteractionTagsList; +//# sourceMappingURL=create-interaction-tx.js.map \ No newline at end of file diff --git a/lib/cjs/legacy/create-interaction-tx.js.map b/lib/cjs/legacy/create-interaction-tx.js.map new file mode 100644 index 00000000..445a59ca --- /dev/null +++ b/lib/cjs/legacy/create-interaction-tx.js.map @@ -0,0 +1 @@ +{"version":3,"file":"create-interaction-tx.js","sourceRoot":"","sources":["../../../src/legacy/create-interaction-tx.ts"],"names":[],"mappings":";;;AACA,iDAAgE;AAEhE,gEAA6D;AAE7D,gEAAuG;AAGhG,KAAK,UAAU,mBAAmB,CACvC,OAAgB,EAChB,MAAuB,EACvB,UAAkB,EAClB,KAAY,EACZ,IAAU,EACV,MAAM,GAAG,EAAE,EACX,UAAU,GAAG,GAAG,EAChB,KAAK,GAAG,KAAK,EACb,SAAkB,EAClB,MAAe;IAEf,MAAM,OAAO,GAAwC;QACnD,IAAI,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KACzC,CAAC;IAEF,IAAI,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE;QAC3B,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;QACnC,IAAI,UAAU,IAAI,CAAC,UAAU,GAAG,CAAC,EAAE;YACjC,OAAO,CAAC,QAAQ,GAAG,UAAU,CAAC,QAAQ,EAAE,CAAC;SAC1C;KACF;IAED,iEAAiE;IACjE,2EAA2E;IAC3E,yEAAyE;IACzE,cAAc;IACd,IAAI,KAAK,EAAE;QACT,OAAO,CAAC,MAAM,GAAG,GAAG,CAAC;QACrB,OAAO,CAAC,OAAO,GAAG,kEAAkE,CAAC;KACtF;IACD,IAAI,MAAM,IAAI,MAAM,CAAC,MAAM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;QACb,eAAe,CAAC,IAAI,CAAC,IAAI,mBAAG,CAAC,qBAAS,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC,CAAC;KAChE;IAED,OAAO,eAAe,CAAC;AACzB,CAAC;AAzBD,8DAyBC"} \ No newline at end of file diff --git a/lib/cjs/legacy/errors.js b/lib/cjs/legacy/errors.js new file mode 100644 index 00000000..142452ac --- /dev/null +++ b/lib/cjs/legacy/errors.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SmartWeaveError = exports.SmartWeaveErrorType = void 0; +var SmartWeaveErrorType; +(function (SmartWeaveErrorType) { + SmartWeaveErrorType["CONTRACT_NOT_FOUND"] = "CONTRACT_NOT_FOUND"; +})(SmartWeaveErrorType = exports.SmartWeaveErrorType || (exports.SmartWeaveErrorType = {})); +class SmartWeaveError extends Error { + constructor(type, optional = {}) { + if (optional.message) { + super(optional.message); + } + else { + super(); + } + this.type = type; + this.otherInfo = optional; + } + getType() { + return this.type; + } +} +exports.SmartWeaveError = SmartWeaveError; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/lib/cjs/legacy/errors.js.map b/lib/cjs/legacy/errors.js.map new file mode 100644 index 00000000..abf205ba --- /dev/null +++ b/lib/cjs/legacy/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/legacy/errors.ts"],"names":[],"mappings":";;;AAAA,IAAkB,mBAEjB;AAFD,WAAkB,mBAAmB;IACnC,gEAAyC,CAAA;AAC3C,CAAC,EAFiB,mBAAmB,GAAnB,2BAAmB,KAAnB,2BAAmB,QAEpC;AAOD,MAAa,eAAgB,SAAQ,KAAK;IAIxC,YAAY,IAAyB,EAAE,WAAgC,EAAE;QACvE,IAAI,QAAQ,CAAC,OAAO,EAAE;YACpB,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;SACzB;aAAM;YACL,KAAK,EAAE,CAAC;SACT;QACD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAEM,OAAO;QACZ,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;CACF;AAjBD,0CAiBC"} \ No newline at end of file diff --git a/lib/cjs/legacy/gqlResult.js b/lib/cjs/legacy/gqlResult.js new file mode 100644 index 00000000..816e8e00 --- /dev/null +++ b/lib/cjs/legacy/gqlResult.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=gqlResult.js.map \ No newline at end of file diff --git a/lib/cjs/legacy/gqlResult.js.map b/lib/cjs/legacy/gqlResult.js.map new file mode 100644 index 00000000..30c25fa1 --- /dev/null +++ b/lib/cjs/legacy/gqlResult.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gqlResult.js","sourceRoot":"","sources":["../../../src/legacy/gqlResult.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/legacy/smartweave-global.js b/lib/cjs/legacy/smartweave-global.js new file mode 100644 index 00000000..09999062 --- /dev/null +++ b/lib/cjs/legacy/smartweave-global.js @@ -0,0 +1,262 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.KV = exports.SWVrf = exports.SWBlock = exports.SWTransaction = exports.SmartWeaveGlobal = void 0; +const SortKeyCache_1 = require("../cache/SortKeyCache"); +const utils_1 = require("../utils/utils"); +class SmartWeaveGlobal { + constructor(arweave, contract, evaluationOptions, interactionState, storage) { + this.gasUsed = 0; + this.gasLimit = Number.MAX_SAFE_INTEGER; + this.unsafeClient = arweave; + this.arweave = { + ar: arweave.ar, + utils: arweave.utils, + wallets: arweave.wallets, + crypto: arweave.crypto + }; + this.baseArweaveUrl = `${arweave.api.config.protocol}://${arweave.api.config.host}:${arweave.api.config.port}`; + this.safeArweaveGet = async function (query) { + return (0, utils_1.safeGet)(`${this.baseArweaveUrl}${query}`); + }; + this.evaluationOptions = evaluationOptions; + this.contract = contract; + this.transaction = new SWTransaction(this); + this.block = new SWBlock(this); + this.contracts = { + readContractState: (contractId, height, returnValidity) => { + throw new Error('Not implemented - should be set by HandlerApi implementor'); + }, + viewContractState: (contractId, input) => { + throw new Error('Not implemented - should be set by HandlerApi implementor'); + }, + write: (contractId, input, throwOnError) => { + throw new Error('Not implemented - should be set by HandlerApi implementor'); + }, + refreshState: () => { + throw new Error('Not implemented - should be set by HandlerApi implementor'); + } + }; + this.vrf = new SWVrf(this); + this.useGas = this.useGas.bind(this); + this.getBalance = this.getBalance.bind(this); + this.extensions = {}; + this.kv = new KV(storage, interactionState, this.transaction, this.contract.id); + } + useGas(gas) { + if (gas < 0) { + throw new Error(`[RE:GNE] Gas number exception - gas < 0.`); + } + this.gasUsed += gas; + if (this.gasUsed > this.gasLimit) { + throw new Error(`[RE:OOG] Out of gas! Used: ${this.gasUsed}, limit: ${this.gasLimit}`); + } + } + async getBalance(address, height) { + if (!this._activeTx) { + throw new Error('Cannot read balance - active tx is not set.'); + } + if (!this.block.height) { + throw new Error('Cannot read balance - block height not set.'); + } + const effectiveHeight = height || this.block.height; + // http://nyc-1.dev.arweave.net:1984/block/height/914387/wallet/M-mpNeJbg9h7mZ-uHaNsa5jwFFRAq0PsTkNWXJ-ojwI/balance + return await fetch(`${this.evaluationOptions.walletBalanceUrl}block/height/${effectiveHeight}/wallet/${address}/balance`) + .then((res) => { + return res.ok ? res.text() : Promise.reject(res); + }) + .catch((error) => { + var _a; + throw new Error(`Unable to read wallet balance. ${error.status}. ${(_a = error.body) === null || _a === void 0 ? void 0 : _a.message}`); + }); + } +} +exports.SmartWeaveGlobal = SmartWeaveGlobal; +// tslint:disable-next-line: max-classes-per-file +class SWTransaction { + constructor(smartWeaveGlobal) { + this.smartWeaveGlobal = smartWeaveGlobal; + } + get id() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.id; + } + get owner() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.owner.address; + } + get target() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.recipient; + } + get tags() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.tags; + } + get sortKey() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.sortKey; + } + get dryRun() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.dry === true; + } + get quantity() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.quantity.winston; + } + get reward() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.fee.winston; + } + get origin() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.source === 'redstone-sequencer' ? 'L2' : 'L1'; + } +} +exports.SWTransaction = SWTransaction; +// tslint:disable-next-line: max-classes-per-file +class SWBlock { + constructor(smartWeaveGlobal) { + this.smartWeaveGlobal = smartWeaveGlobal; + } + get height() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.block.height; + } + get indep_hash() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current Tx'); + } + return this.smartWeaveGlobal._activeTx.block.id; + } + get timestamp() { + if (!this.smartWeaveGlobal._activeTx) { + throw new Error('No current tx'); + } + return this.smartWeaveGlobal._activeTx.block.timestamp; + } +} +exports.SWBlock = SWBlock; +class SWVrf { + constructor(smartWeaveGlobal) { + this.smartWeaveGlobal = smartWeaveGlobal; + } + get data() { + return this.smartWeaveGlobal._activeTx.vrf; + } + // returns the original generated random number as a BigInt string; + get value() { + return this.smartWeaveGlobal._activeTx.vrf.bigint; + } + // returns a random value in a range from 1 to maxValue + randomInt(maxValue) { + if (!Number.isInteger(maxValue)) { + throw new Error('Integer max value required for random integer generation'); + } + const result = (BigInt(this.smartWeaveGlobal._activeTx.vrf.bigint) % BigInt(maxValue)) + BigInt(1); + if (result > Number.MAX_SAFE_INTEGER || result < Number.MIN_SAFE_INTEGER) { + throw new Error('Random int cannot be cast to number'); + } + return Number(result); + } +} +exports.SWVrf = SWVrf; +class KV { + constructor(_storage, _interactionState, _transaction, _contractTxId) { + this._storage = _storage; + this._interactionState = _interactionState; + this._transaction = _transaction; + this._contractTxId = _contractTxId; + } + async put(key, value) { + this.checkStorageAvailable(); + await this._storage.put(new SortKeyCache_1.CacheKey(key, this._transaction.sortKey), value); + } + async get(key) { + var _a; + this.checkStorageAvailable(); + const sortKey = this._transaction.sortKey; + // then we're checking if the values exists in the interactionState + const interactionStateValue = await this._interactionState.getKV(this._contractTxId, new SortKeyCache_1.CacheKey(key, this._transaction.sortKey)); + if (interactionStateValue != null) { + return interactionStateValue; + } + const result = await this._storage.getLessOrEqual(key, this._transaction.sortKey); + return (_a = result === null || result === void 0 ? void 0 : result.cachedValue) !== null && _a !== void 0 ? _a : null; + } + async del(key) { + this.checkStorageAvailable(); + const sortKey = this._transaction.sortKey; + // then we're checking if the values exists in the interactionState + const interactionStateValue = await this._interactionState.delKV(this._contractTxId, new SortKeyCache_1.CacheKey(key, this._transaction.sortKey)); + if (interactionStateValue != null) { + return interactionStateValue; + } + await this._storage.del(new SortKeyCache_1.CacheKey(key, this._transaction.sortKey)); + } + async keys(options) { + const sortKey = this._transaction.sortKey; + return await this._storage.keys(sortKey, options); + } + async kvMap(options) { + const sortKey = this._transaction.sortKey; + return this._storage.kvMap(sortKey, options); + } + async begin() { + if (this._storage) { + return this._storage.begin(); + } + } + async commit() { + if (this._storage) { + if (this._transaction.dryRun) { + await this._storage.rollback(); + } + else { + await this._storage.commit(); + } + } + } + async rollback() { + if (this._storage) { + await this._storage.rollback(); + } + } + open() { + if (this._storage) { + return this._storage.open(); + } + } + close() { + if (this._storage) { + return this._storage.close(); + } + } + checkStorageAvailable() { + if (!this._storage) { + throw new Error('KV Storage not available'); + } + } +} +exports.KV = KV; +//# sourceMappingURL=smartweave-global.js.map \ No newline at end of file diff --git a/lib/cjs/legacy/smartweave-global.js.map b/lib/cjs/legacy/smartweave-global.js.map new file mode 100644 index 00000000..93e56dac --- /dev/null +++ b/lib/cjs/legacy/smartweave-global.js.map @@ -0,0 +1 @@ +{"version":3,"file":"smartweave-global.js","sourceRoot":"","sources":["../../../src/legacy/smartweave-global.ts"],"names":[],"mappings":";;;AAIA,wDAA+D;AAG/D,0CAAyC;AA8BzC,MAAa,gBAAgB;IA+B3B,YACE,OAAgB,EAChB,QAAuC,EACvC,iBAAoC,EACpC,gBAAkC,EAClC,OAAiC;QAEjC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,gBAAgB,CAAC;QACxC,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC;QAC5B,IAAI,CAAC,OAAO,GAAG;YACb,EAAE,EAAE,OAAO,CAAC,EAAE;YACd,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,MAAM,EAAE,OAAO,CAAC,MAAM;SACvB,CAAC;QACF,IAAI,CAAC,cAAc,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,MAAM,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QAC/G,IAAI,CAAC,cAAc,GAAG,KAAK,WAAW,KAAa;YACjD,OAAO,IAAA,eAAO,EAAC,GAAG,IAAI,CAAC,cAAc,GAAG,KAAK,EAAE,CAAC,CAAC;QACnD,CAAC,CAAC;QAEF,IAAI,CAAC,iBAAiB,GAAG,iBAA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I,EAAE,CAAC;SAC7B;IACH,CAAC;IAED,KAAK;QACH,IAAI,IAAI,CAAC,QAAQ,EAAE;YACjB,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;SAC9B;IACH,CAAC;IAEO,qBAAqB;QAC3B,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE;YAClB,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;SAC7C;IACH,CAAC;CACF;AA/FD,gBA+FC"} \ No newline at end of file diff --git a/lib/cjs/legacy/utils.js b/lib/cjs/legacy/utils.js new file mode 100644 index 00000000..d870c491 --- /dev/null +++ b/lib/cjs/legacy/utils.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.arrayToHex = void 0; +function arrayToHex(arr) { + let str = ''; + for (const a of arr) { + str += ('0' + a.toString(16)).slice(-2); + } + return str; +} +exports.arrayToHex = arrayToHex; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib/cjs/legacy/utils.js.map b/lib/cjs/legacy/utils.js.map new file mode 100644 index 00000000..30fd1c4d --- /dev/null +++ b/lib/cjs/legacy/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/legacy/utils.ts"],"names":[],"mappings":";;;AAAA,SAAgB,UAAU,CAAC,GAAe;IACxC,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,KAAK,MAAM,CAAC,IAAI,GAAG,EAAE;QACnB,GAAG,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;KACzC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAND,gCAMC"} \ No newline at end of file diff --git a/lib/cjs/logging/Benchmark.js b/lib/cjs/logging/Benchmark.js new file mode 100644 index 00000000..650486e9 --- /dev/null +++ b/lib/cjs/logging/Benchmark.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Benchmark = void 0; +class Benchmark { + static measure() { + return new Benchmark(); + } + constructor() { + this.start = Date.now(); + this.end = null; + // noop + } + reset() { + this.start = Date.now(); + this.end = null; + } + stop() { + this.end = Date.now(); + } + elapsed(rawValue = false) { + if (this.end === null) { + this.end = Date.now(); + } + const result = this.end - this.start; + return rawValue ? result : `${(this.end - this.start).toFixed(0)}ms`; + } +} +exports.Benchmark = Benchmark; +//# sourceMappingURL=Benchmark.js.map \ No newline at end of file diff --git a/lib/cjs/logging/Benchmark.js.map b/lib/cjs/logging/Benchmark.js.map new file mode 100644 index 00000000..03df62f3 --- /dev/null +++ b/lib/cjs/logging/Benchmark.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Benchmark.js","sourceRoot":"","sources":["../../../src/logging/Benchmark.ts"],"names":[],"mappings":";;;AAAA,MAAa,SAAS;IACb,MAAM,CAAC,OAAO;QACnB,OAAO,IAAI,SAAS,EAAE,CAAC;IACzB,CAAC;IAED;QAIQ,UAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACnB,QAAG,GAAG,IAAI,CAAC;QAJjB,OAAO;IACT,CAAC;IAKM,KAAK;QACV,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACxB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC;IAClB,CAAC;IAEM,IAAI;QACT,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACxB,CAAC;IAEM,OAAO,CAAC,QAAQ,GAAG,KAAK;QAC7B,IAAI,IAAI,CAAC,GAAG,KAAK,IAAI,EAAE;YACrB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;SACvB;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;QACrC,OAAO,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;IACvE,CAAC;CACF;AA7BD,8BA6BC"} \ No newline at end of file diff --git a/lib/cjs/logging/LoggerFactory.js b/lib/cjs/logging/LoggerFactory.js new file mode 100644 index 00000000..5c574556 --- /dev/null +++ b/lib/cjs/logging/LoggerFactory.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LoggerFactory = void 0; +const ConsoleLoggerFactory_1 = require("./web/ConsoleLoggerFactory"); +class LoggerFactory { + constructor() { + // not instantiable from outside + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + setOptions(newOptions, moduleName) { + LoggerFactory.INST.setOptions(newOptions, moduleName); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + getOptions(moduleName) { + return LoggerFactory.INST.getOptions(moduleName); + } + logLevel(level, moduleName) { + LoggerFactory.INST.logLevel(level, moduleName); + } + create(moduleName) { + return LoggerFactory.INST.create(moduleName); + } + static use(logger) { + LoggerFactory.INST = logger; + } +} +exports.LoggerFactory = LoggerFactory; +LoggerFactory.INST = new ConsoleLoggerFactory_1.ConsoleLoggerFactory(); +//# sourceMappingURL=LoggerFactory.js.map \ No newline at end of file diff --git a/lib/cjs/logging/LoggerFactory.js.map b/lib/cjs/logging/LoggerFactory.js.map new file mode 100644 index 00000000..99e0e7b5 --- /dev/null +++ b/lib/cjs/logging/LoggerFactory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"LoggerFactory.js","sourceRoot":"","sources":["../../../src/logging/LoggerFactory.ts"],"names":[],"mappings":";;;AAEA,qEAAkE;AAclE,MAAa,aAAa;IAGxB;QACE,gCAAgC;IAClC,CAAC;IAED,8DAA8D;IAC9D,UAAU,CAAC,UAAe,EAAE,UAAmB;QAC7C,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;IACxD,CAAC;IAED,8DAA8D;IAC9D,UAAU,CAAC,UAAmB;QAC5B,OAAO,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IACnD,CAAC;IAED,QAAQ,CAAC,KAAe,EAAE,UAAmB;QAC3C,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IACjD,CAAC;IAED,MAAM,CAAC,UAAmB;QACxB,OAAO,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAC/C,CAAC;IAED,MAAM,CAAC,GAAG,CAAC,MAAsB;QAC/B,aAAa,CAAC,IAAI,GAAG,MAAM,CAAC;IAC9B,CAAC;;AA3BH,sCA4BC;AA3BQ,kBAAI,GAAmB,IAAI,2CAAoB,EAAE,CAAC"} \ No newline at end of file diff --git a/lib/cjs/logging/LoggerSettings.js b/lib/cjs/logging/LoggerSettings.js new file mode 100644 index 00000000..e0dd99e4 --- /dev/null +++ b/lib/cjs/logging/LoggerSettings.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.lvlToOrder = exports.LogLevelOrder = void 0; +exports.LogLevelOrder = { + silly: 0, + trace: 1, + debug: 2, + info: 3, + warn: 4, + error: 5, + fatal: 6, + none: 7 +}; +function lvlToOrder(logLevel) { + return exports.LogLevelOrder[logLevel]; +} +exports.lvlToOrder = lvlToOrder; +//# sourceMappingURL=LoggerSettings.js.map \ No newline at end of file diff --git a/lib/cjs/logging/LoggerSettings.js.map b/lib/cjs/logging/LoggerSettings.js.map new file mode 100644 index 00000000..62a5de68 --- /dev/null +++ b/lib/cjs/logging/LoggerSettings.js.map @@ -0,0 +1 @@ +{"version":3,"file":"LoggerSettings.js","sourceRoot":"","sources":["../../../src/logging/LoggerSettings.ts"],"names":[],"mappings":";;;AAAa,QAAA,aAAa,GAAG;IAC3B,KAAK,EAAE,CAAC;IACR,KAAK,EAAE,CAAC;IACR,KAAK,EAAE,CAAC;IACR,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,CAAC;IACP,KAAK,EAAE,CAAC;IACR,KAAK,EAAE,CAAC;IACR,IAAI,EAAE,CAAC;CACR,CAAC;AAWF,SAAgB,UAAU,CAAC,QAAkB;IAC3C,OAAO,qBAAa,CAAC,QAAQ,CAAC,CAAC;AACjC,CAAC;AAFD,gCAEC"} \ No newline at end of file diff --git a/lib/cjs/logging/WarpLogger.js b/lib/cjs/logging/WarpLogger.js new file mode 100644 index 00000000..32a1ff06 --- /dev/null +++ b/lib/cjs/logging/WarpLogger.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=WarpLogger.js.map \ No newline at end of file diff --git a/lib/cjs/logging/WarpLogger.js.map b/lib/cjs/logging/WarpLogger.js.map new file mode 100644 index 00000000..225eb09b --- /dev/null +++ b/lib/cjs/logging/WarpLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpLogger.js","sourceRoot":"","sources":["../../../src/logging/WarpLogger.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib/cjs/logging/web/ConsoleLogger.js b/lib/cjs/logging/web/ConsoleLogger.js new file mode 100644 index 00000000..066168a6 --- /dev/null +++ b/lib/cjs/logging/web/ConsoleLogger.js @@ -0,0 +1,64 @@ +"use strict"; +/* eslint-disable */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConsoleLogger = void 0; +const LoggerSettings_1 = require("../../logging/LoggerSettings"); +class ConsoleLogger { + constructor(moduleName, settings) { + this.moduleName = moduleName; + this.settings = settings; + } + trace(message, ...optionalParams) { + if (this.shouldLog('trace')) { + // note: no 'trace' for console logger + console.debug(this.message('trace', message), optionalParams); + } + } + error(message, ...optionalParams) { + if (this.shouldLog('error')) { + console.error(this.message('error', message), optionalParams); + } + } + info(message, ...optionalParams) { + if (this.shouldLog('info')) { + console.info(this.message('info', message), optionalParams); + } + } + silly(message, ...optionalParams) { + if (this.shouldLog('silly')) { + // note: no silly level for console logger + console.debug(this.message('silly', message), optionalParams); + } + } + debug(message, ...optionalParams) { + if (this.shouldLog('debug')) { + console.debug(this.message('debug', message), optionalParams); + } + } + warn(message, ...optionalParams) { + if (this.shouldLog('warn')) { + console.warn(this.message('warn', message), optionalParams); + } + } + log(message, ...optionalParams) { + if (this.shouldLog('info')) { + console.info(this.message('info', message), optionalParams); + } + } + fatal(message, ...optionalParams) { + if (this.shouldLog('fatal')) { + console.error(this.message('fatal', message), optionalParams); + } + } + shouldLog(logLevel) { + return (0, LoggerSettings_1.lvlToOrder)(logLevel) >= (0, LoggerSettings_1.lvlToOrder)(this.settings.minLevel); + } + setSettings(settings) { + this.settings = settings; + } + message(lvl, message) { + return `${new Date().toISOString()} ${lvl.toUpperCase()} [${this.moduleName}] ${message}`; + } +} +exports.ConsoleLogger = ConsoleLogger; +//# sourceMappingURL=ConsoleLogger.js.map \ No newline at end of file diff --git a/lib/cjs/logging/web/ConsoleLogger.js.map b/lib/cjs/logging/web/ConsoleLogger.js.map new file mode 100644 index 00000000..b7db4458 --- /dev/null +++ b/lib/cjs/logging/web/ConsoleLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ConsoleLogger.js","sourceRoot":"","sources":["../../../../src/logging/web/ConsoleLogger.ts"],"names":[],"mappings":";AAAA,oBAAoB;;;AAEpB,iEAAoF;AAGpF,MAAa,aAAa;IACxB,YAA6B,UAAU,EAAS,QAAwB;QAA3C,eAAU,GAAV,UAAU,CAAA;QAAS,aAAQ,GAAR,QAAQ,CAAgB;IAAG,CAAC;IAE5E,KAAK,CAAC,OAAa,EAAE,GAAG,cAAqB;QAC3C,IAAI,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE;YAC3B,sCAAsC;YACtC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC;SAC/D;IACH,CAAC;IAED,KAAK,CA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AAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC;SAC7D;IACH,CAAC;IAED,KAAK,CAAC,OAAa,EAAE,GAAG,cAAqB;QAC3C,IAAI,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE;YAC3B,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC;SAC/D;IACH,CAAC;IAED,SAAS,CAAC,QAAkB;QAC1B,OAAO,IAAA,2BAAU,EAAC,QAAQ,CAAC,IAAI,IAAA,2BAAU,EAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IACpE,CAAC;IAED,WAAW,CAAC,QAAwB;QAClC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED,OAAO,CAAC,GAAa,EAAE,OAAe;QACpC,OAAO,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,IAAI,GAAG,CAAC,WAAW,EAAE,KAAK,IAAI,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;IAC5F,CAAC;CACF;AAhED,sCAgEC"} \ No newline at end of file diff --git a/lib/cjs/logging/web/ConsoleLoggerFactory.js b/lib/cjs/logging/web/ConsoleLoggerFactory.js new file mode 100644 index 00000000..83a38b2e --- /dev/null +++ b/lib/cjs/logging/web/ConsoleLoggerFactory.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConsoleLoggerFactory = void 0; +const ConsoleLogger_1 = require("./ConsoleLogger"); +class ConsoleLoggerFactory { + constructor() { + this.registeredLoggers = {}; + this.registeredOptions = {}; + this.defOptions = { + minLevel: 'info' + }; + this.setOptions = this.setOptions.bind(this); + this.getOptions = this.getOptions.bind(this); + this.create = this.create.bind(this); + this.logLevel = this.logLevel.bind(this); + } + setOptions(newOptions, moduleName) { + // FIXME: c/p from TsLogFactory... + // if moduleName not specified + if (!moduleName) { + // update default options + this.defOptions = newOptions; + // update options for all already registered loggers + Object.keys(this.registeredLoggers).forEach((key) => { + this.registeredLoggers[key].setSettings({ + ...this.registeredLoggers[key].settings, + ...newOptions + }); + }); + } + else { + // if logger already registered + if (this.registeredLoggers[moduleName]) { + // update its options + this.registeredLoggers[moduleName].setSettings({ + ...this.registeredLoggers[moduleName].settings, + ...newOptions + }); + } + else { + // if logger not yet registered - save options that will be used for its creation + this.registeredOptions[moduleName] = { + ...this.defOptions, + ...newOptions + }; + } + } + } + getOptions(moduleName) { + // FIXME: c/p from TsLogFactory... + if (!moduleName) { + return this.defOptions; + } + else { + if (this.registeredLoggers[moduleName]) { + return this.registeredLoggers[moduleName].settings; + } + else if (this.registeredOptions[moduleName]) { + return this.registeredOptions[moduleName]; + } + else { + return this.defOptions; + } + } + } + logLevel(level, moduleName) { + // FIXME: c/p from TsLogFactory... + this.setOptions({ minLevel: level }, moduleName); + } + create(moduleName = 'SWC') { + if (!Object.prototype.hasOwnProperty.call(this.registeredLoggers, moduleName)) { + this.registeredLoggers[moduleName] = new ConsoleLogger_1.ConsoleLogger(moduleName, this.getOptions(moduleName)); + } + return this.registeredLoggers[moduleName]; + } +} +exports.ConsoleLoggerFactory = ConsoleLoggerFactory; +//# sourceMappingURL=ConsoleLoggerFactory.js.map \ No newline at end of file diff --git a/lib/cjs/logging/web/ConsoleLoggerFactory.js.map b/lib/cjs/logging/web/ConsoleLoggerFactory.js.map new file mode 100644 index 00000000..91c1eea4 --- /dev/null +++ b/lib/cjs/logging/web/ConsoleLoggerFactory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ConsoleLoggerFactory.js","sourceRoot":"","sources":["../../../../src/logging/web/ConsoleLoggerFactory.ts"],"names":[],"mappings":";;;AAAA,mDAAgD;AAKhD,MAAa,oBAAoB;IAQ/B;QAPQ,sBAAiB,GAA4C,EAAE,CAAC;QACvD,sBAAiB,GAA6C,EAAE,CAAC;QAE1E,eAAU,GAAmB;YACnC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AG,UAAU;iBACd,CAAC;aACH;SACF;IACH,CAAC;IAED,UAAU,CAAC,UAAmB;QAC5B,kCAAkC;QAClC,IAAI,CAAC,UAAU,EAAE;YACf,OAAO,IAAI,CAAC,UAAU,CAAC;SACxB;aAAM;YACL,IAAI,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,EAAE;gBACtC,OAAO,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC;aACpD;iBAAM,IAAI,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,EAAE;gBAC7C,OAAO,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;aAC3C;iBAAM;gBACL,OAAO,IAAI,CAAC,UAAU,CAAC;aACxB;SACF;IACH,CAAC;IAED,QAAQ,CAAC,KAAe,EAAE,UAAmB;QAC3C,kCAAkC;QAClC,IAAI,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,UAAU,CAAC,CAAC;IACnD,CAAC;IAED,MAAM,CAAC,UAAU,GAAG,KAAK;QACvB,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,UAAU,CAAC,EAAE;YAC7E,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,GAAG,IAAI,6BAAa,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC;SACjG;QAED,OAAO,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;IAC5C,CAAC;CACF;AAzED,oDAyEC"} \ No newline at end of file diff --git a/lib/cjs/plugins/DebuggableExecutorFactor.js b/lib/cjs/plugins/DebuggableExecutorFactor.js new file mode 100644 index 00000000..a340e041 --- /dev/null +++ b/lib/cjs/plugins/DebuggableExecutorFactor.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DebuggableExecutorFactory = void 0; +/** + * An ExecutorFactory that allows to substitute original contract's source code. + * Useful for debugging purposes (e.g. to quickly add some console.logs in contract + * or to test a fix or a new feature - without the need of redeploying a new contract on Arweave); + * + * Not meant to be used in production env! ;-) + */ +class DebuggableExecutorFactory { + constructor(baseImplementation, + // contract source code before default "normalization" + sourceCode) { + this.baseImplementation = baseImplementation; + this.sourceCode = sourceCode; + } + async create(contractDefinition, evaluationOptions, warp, interactionState) { + if (Object.prototype.hasOwnProperty.call(this.sourceCode, contractDefinition.txId)) { + contractDefinition = { + ...contractDefinition, + src: this.sourceCode[contractDefinition.txId] + }; + } + return await this.baseImplementation.create(contractDefinition, evaluationOptions, warp, interactionState); + } + checkWhiteListContractSources(contractDefinition, evaluationOptions) { + return this.baseImplementation.checkWhiteListContractSources(contractDefinition, evaluationOptions); + } +} +exports.DebuggableExecutorFactory = DebuggableExecutorFactory; +//# sourceMappingURL=DebuggableExecutorFactor.js.map \ No newline at end of file diff --git a/lib/cjs/plugins/DebuggableExecutorFactor.js.map b/lib/cjs/plugins/DebuggableExecutorFactor.js.map new file mode 100644 index 00000000..caf1ccec --- /dev/null +++ b/lib/cjs/plugins/DebuggableExecutorFactor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DebuggableExecutorFactor.js","sourceRoot":"","sources":["../../../src/plugins/DebuggableExecutorFactor.ts"],"names":[],"mappings":";;;AAMA;;;;;;GAMG;AACH,MAAa,yBAAyB;IACpC,YACmB,kBAAwC;IACzD,sDAAsD;IACrC,UAAqC;QAFrC,uBAAkB,GAAlB,kBAAkB,CAAsB;QAExC,eAAU,GAAV,UAAU,CAA2B;IACrD,CAAC;IAEJ,KAAK,CAAC,MAAM,CACV,kBAA6C,EAC7C,iBAAoC,EACpC,IAAU,EACV,gBAAkC;QAElC,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,kBAAkB,CAAC,IAAI,CAAC,EAAE;YAClF,kBAAkB,GAAG;gBACnB,GAAG,kBAAkB;gBACrB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,kBAAkB,CAAC,IAAI,CAAC;aAC9C,CAAC;SACH;QAED,OAAO,MAAM,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,kBAAkB,EAAE,iBAAiB,EAAE,IAAI,EAAE,gBAAgB,CAAC,CAAC;IAC7G,CAAC;IAED,6BAA6B,CAC3B,kBAAmD,EACnD,iBAAoC;QAEpC,OAAO,IAAI,CAAC,kBAAkB,CAAC,6BAA6B,CAAC,kBAAkB,EAAE,iBAAiB,CAAC,CAAC;IACtG,CAAC;CACF;AA7BD,8DA6BC"} \ No newline at end of file diff --git a/lib/cjs/plugins/Evolve.js b/lib/cjs/plugins/Evolve.js new file mode 100644 index 00000000..01928728 --- /dev/null +++ b/lib/cjs/plugins/Evolve.js @@ -0,0 +1,106 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Evolve = void 0; +const LoggerFactory_1 = require("../logging/LoggerFactory"); +const errors_1 = require("../legacy/errors"); +const JsHandlerApi_1 = require("../core/modules/impl/handler/JsHandlerApi"); +function isEvolveCompatible(state) { + if (!state) { + return false; + } + const settings = evalSettings(state); + return state.evolve !== undefined || settings.has('evolve'); +} +class Evolve { + constructor() { + this.logger = LoggerFactory_1.LoggerFactory.INST.create('Evolve'); + this.modify = this.modify.bind(this); + } + async modify(state, executionContext) { + const { definitionLoader, executorFactory } = executionContext.warp; + const contractTxId = executionContext.contractDefinition.txId; + const evolvedSrcTxId = Evolve.evolvedSrcTxId(state); + const currentSrcTxId = executionContext.contractDefinition.srcTxId; + if (evolvedSrcTxId) { + if (currentSrcTxId !== evolvedSrcTxId) { + try { + // note: that's really nasty IMO - loading original contract definition, + // but forcing different sourceTxId... + this.logger.info('Evolving to: ', evolvedSrcTxId); + const newContractDefinition = await definitionLoader.load(contractTxId, evolvedSrcTxId); + const newHandler = (await executorFactory.create(newContractDefinition, executionContext.evaluationOptions, executionContext.warp, executionContext.contract.interactionState())); + //FIXME: side-effect... + executionContext.contractDefinition = newContractDefinition; + executionContext.handler = newHandler; + executionContext.handler.initState(state); + this.logger.debug('evolved to:', { + evolve: evolvedSrcTxId, + newSrcTxId: executionContext.contractDefinition.srcTxId, + currentSrcTxId: currentSrcTxId, + contract: executionContext.contractDefinition.txId + }); + return executionContext; + } + catch (e) { + if ((e.name === JsHandlerApi_1.KnownErrors.ContractError && e.subtype === 'unsafeClientSkip') || + e.name == JsHandlerApi_1.KnownErrors.NonWhitelistedSourceError) { + throw e; + } + else { + throw new errors_1.SmartWeaveError(errors_1.SmartWeaveErrorType.CONTRACT_NOT_FOUND, { + message: `Error while evolving ${contractTxId} from ${currentSrcTxId} to ${evolvedSrcTxId}: ${e}`, + requestedTxId: contractTxId + }); + } + } + } + } + return executionContext; + } + static evolvedSrcTxId(state) { + if (!isEvolveCompatible(state)) { + return undefined; + } + const settings = evalSettings(state); + // note: from my understanding - this variable holds the id of the transaction with updated source code. + const evolve = state.evolve || settings.get('evolve'); + let canEvolve = state.canEvolve || settings.get('canEvolve'); + // By default, contracts can evolve if there's not an explicit `false`. + if (canEvolve === undefined || canEvolve === null) { + canEvolve = true; + } + if (evolve && /[a-z0-9_-]{43}/i.test(evolve) && canEvolve) { + return evolve; + } + return undefined; + } +} +exports.Evolve = Evolve; +/* eslint-disable @typescript-eslint/no-explicit-any -- dispatching of any type is done by this function */ +function evalSettings(state) { + // default - empty + let settings = new Map(); + if (state.settings) { + // for Iterable format + if (isIterable(state.settings)) { + settings = new Map(state.settings); + // for Object format + } + else if (isObject(state.settings)) { + settings = new Map(Object.entries(state.settings)); + } + } + return settings; +} +/* eslint-enable @typescript-eslint/no-explicit-any */ +function isIterable(obj) { + // checks for null and undefined + if (obj == null) { + return false; + } + return typeof obj[Symbol.iterator] === 'function'; +} +function isObject(obj) { + return typeof obj === 'object' && obj !== null && !Array.isArray(obj); +} +//# sourceMappingURL=Evolve.js.map \ No newline at end of file diff --git a/lib/cjs/plugins/Evolve.js.map b/lib/cjs/plugins/Evolve.js.map new file mode 100644 index 00000000..33596778 --- /dev/null +++ b/lib/cjs/plugins/Evolve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Evolve.js","sourceRoot":"","sources":["../../../src/plugins/Evolve.ts"],"names":[],"mappings":";;;AACA,4DAAyD;AAGzD,6CAAwE;AAExE,4EAAwE;AAExE,SAAS,kBAAkB,CAAC,KAAc;IACxC,IAAI,CAAC,KAAK,EAAE;QACV,OAAO,KAAK,CAAC;KACd;IACD,MAAM,QAAQ,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;IAErC,OAAQ,KAAqB,CAAC,MAAM,KAAK,SAAS,IAAI,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAC/E,CAAC;AAED,MAAa,MAAM;IAGjB;QAFiB,WAAM,GAAG,6BAAa,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAG5D,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,MAAM,CACV,KAAY,EACZ,gBAA4D;QAE5D,MAAM,EAAE,gBAAgB,EAAE,eAAe,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC;QAEpE,MAAM,YAAY,GAAG,gBAAgB,CAAC,kBAAkB,CAAC,IAAI,CAAC;QAC9D,MAAM,cAAc,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;QACpD,MAAM,cAAc,GAAG,gBAAgB,CAAC,kBAAkB,CAAC,OAAO,CAAC;QAEnE,IAAI,cAAc,EAAE;YAClB,IAAI,cAAc,KAAK,cAAc,EAAE;gBACrC,IAAI;oBACF,wEAAwE;oBACxE,sCAAsC;oBACtC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,EAAE,cAAc,CAAC,CAAC;oBAClD,MAAM,qBAAqB,GAAG,MAAM,gBAAgB,CAAC,IAAI,CA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,CAAC,QAAQ,CAAC,KAAK,UAAU,CAAC;AACpD,CAAC;AAED,SAAS,QAAQ,CAAC,GAAY;IAC5B,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AACxE,CAAC"} \ No newline at end of file diff --git a/lib/cjs/utils/ArweaveWrapper.js b/lib/cjs/utils/ArweaveWrapper.js new file mode 100644 index 00000000..9d37ec64 --- /dev/null +++ b/lib/cjs/utils/ArweaveWrapper.js @@ -0,0 +1,104 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ArweaveWrapper = void 0; +const arweave_1 = __importDefault(require("arweave")); +const warp_isomorphic_1 = require("warp-isomorphic"); +const LoggerFactory_1 = require("../logging/LoggerFactory"); +const arweave_types_1 = require("./types/arweave-types"); +const utils_1 = require("./utils"); +class ArweaveWrapper { + constructor(warp) { + this.warp = warp; + this.logger = LoggerFactory_1.LoggerFactory.INST.create('ArweaveWrapper'); + const { arweave } = warp; + this.baseUrl = `${arweave.api.config.protocol}://${arweave.api.config.host}:${arweave.api.config.port}`; + this.logger.debug('baseurl', this.baseUrl); + } + async warpGwInfo() { + return await this.doFetchInfo(`${(0, utils_1.stripTrailingSlash)(this.warp.gwUrl())}/gateway/arweave/info`); + } + async warpGwBlock() { + this.logger.debug('Calling warp gw block info'); + return await this.doFetchInfo(`${(0, utils_1.stripTrailingSlash)(this.warp.gwUrl())}/gateway/arweave/block`); + } + async info() { + return await this.doFetchInfo(`${this.baseUrl}/info`); + } + /** + * + * @param query graphql query string + * @param variables variables depends on provided query + * @returns axios-like (for backwards compatibility..) response from graphql + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async gql(query, variables) { + try { + const data = JSON.stringify({ + query: query, + variables: variables + }); + const response = await (0, utils_1.getJsonResponse)(fetch(`${this.baseUrl}/graphql`, { + method: 'POST', + body: data, + headers: { + 'Accept-Encoding': 'gzip, deflate, br', + 'Content-Type': 'application/json', + Accept: 'application/json' + } + })); + return { + data: response, + status: 200 + }; + } + catch (e) { + this.logger.error('Error while loading gql', e); + throw e; + } + } + async tx(id) { + const response = await fetch(`${this.baseUrl}/tx/${id}`) + .then((res) => { + return res.ok ? res.json() : Promise.reject(res); + }) + .catch((error) => { + var _a, _b; + if ((_a = error.body) === null || _a === void 0 ? void 0 : _a.message) { + this.logger.error(error.body.message); + } + throw new utils_1.NetworkCommunicationError(`Unable to retrieve tx ${id}. ${error.status}. ${(_b = error.body) === null || _b === void 0 ? void 0 : _b.message}`); + }); + return new arweave_types_1.Transaction({ + ...response + }); + } + async txData(id) { + // note: this is using arweave.net cache - + // not very safe and clever, but fast... + const response = await fetch(`${this.baseUrl}/${id}`); + if (!response.ok) { + this.logger.warn(`Unable to load data from arweave.net/${id} endpoint, falling back to arweave.js`); + // fallback to arweave-js as a last resort.. + const txData = (await this.warp.arweave.transactions.getData(id, { + decode: true + })); + return warp_isomorphic_1.Buffer.from(txData); + } + else { + const buffer = await response.arrayBuffer(); + return warp_isomorphic_1.Buffer.from(buffer); + } + } + async txDataString(id) { + const buffer = await this.txData(id); + return arweave_1.default.utils.bufferToString(buffer); + } + async doFetchInfo(url) { + return await (0, utils_1.getJsonResponse)(fetch(url)); + } +} +exports.ArweaveWrapper = ArweaveWrapper; +//# sourceMappingURL=ArweaveWrapper.js.map \ No newline at end of file diff --git a/lib/cjs/utils/ArweaveWrapper.js.map b/lib/cjs/utils/ArweaveWrapper.js.map new file mode 100644 index 00000000..2cf4498e --- /dev/null +++ b/lib/cjs/utils/ArweaveWrapper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveWrapper.js","sourceRoot":"","sources":["../../../src/utils/ArweaveWrapper.ts"],"names":[],"mappings":";;;;;;AAAA,sDAA8B;AAC9B,qDAA6D;AAC7D,4DAAyD;AACzD,yDAAqF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,KAAK,CAAC,MAAM,CAAC,EAAU;QACrB,0CAA0C;QAC1C,wCAAwC;QACxC,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,OAAO,IAAI,EAAE,EAAE,CAAC,CAAC;QACtD,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;YAChB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,wCAAwC,EAAE,uCAAuC,CAAC,CAAC;YACpG,4CAA4C;YAC5C,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,EAAE;gBAC/D,MAAM,EAAE,IAAI;aACb,CAAC,CAAe,CAAC;YAClB,OAAO,wBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;SACtC;aAAM;YACL,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC;YAC5C,OAAO,wBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;SACtC;IACH,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,EAAU;QAC3B,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACrC,OAAO,iBAAO,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;IAC9C,CAAC;IAEO,KAAK,CAAC,WAAW,CAAI,GAAW;QACtC,OAAO,MAAM,IAAA,uBAAe,EAAI,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9C,CAAC;CACF;AAxGD,wCAwGC"} \ No newline at end of file diff --git a/lib/cjs/utils/types/arweave-types.js b/lib/cjs/utils/types/arweave-types.js new file mode 100644 index 00000000..09351054 --- /dev/null +++ b/lib/cjs/utils/types/arweave-types.js @@ -0,0 +1,149 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Tag = exports.Transaction = void 0; +const ArweaveUtils = __importStar(require("arweave/web/lib/utils")); +class BaseObject { + get(field, options) { + if (!Object.getOwnPropertyNames(this).includes(field)) { + throw new Error(`Field "${field}" is not a property of the Arweave Transaction class.`); + } + // Handle fields that are Uint8Arrays. + // To maintain compat we encode them to b64url + // if decode option is not specificed. + if (this[field] instanceof Uint8Array) { + if (options && options.decode && options.string) { + return ArweaveUtils.bufferToString(this[field]); + } + if (options && options.decode && !options.string) { + return this[field]; + } + return ArweaveUtils.bufferTob64Url(this[field]); + } + if (options && options.decode == true) { + if (options && options.string) { + return ArweaveUtils.b64UrlToString(this[field]); + } + return ArweaveUtils.b64UrlToBuffer(this[field]); + } + return this[field]; + } +} +class Transaction extends BaseObject { + constructor(attributes = {}) { + super(); + this.format = 2; + this.id = ''; + this.last_tx = ''; + this.owner = ''; + this.tags = []; + this.target = ''; + this.quantity = '0'; + this.data_size = '0'; + this.data = new Uint8Array(); + this.data_root = ''; + this.reward = '0'; + this.signature = ''; + Object.assign(this, attributes); + // If something passes in a Tx that has been toJSON'ed and back, + // or where the data was filled in from /tx/data endpoint. + // data will be b64url encoded, so decode it. + if (typeof this.data === 'string') { + this.data = ArweaveUtils.b64UrlToBuffer(this.data); + } + if (attributes.tags) { + this.tags = attributes.tags.map((tag) => { + return new Tag(tag.name, tag.value); + }); + } + } + addTag(name, value) { + this.tags.push(new Tag(ArweaveUtils.stringToB64Url(name), ArweaveUtils.stringToB64Url(value))); + } + toJSON() { + return { + format: this.format, + id: this.id, + last_tx: this.last_tx, + owner: this.owner, + tags: this.tags, + target: this.target, + quantity: this.quantity, + data: ArweaveUtils.bufferTob64Url(this.data), + data_size: this.data_size, + data_root: this.data_root, + data_tree: this.data_tree, + reward: this.reward, + signature: this.signature + }; + } + setOwner(owner) { + this.owner = owner; + } + setSignature({ id, owner, reward, tags, signature }) { + this.id = id; + this.owner = owner; + if (reward) + this.reward = reward; + if (tags) + this.tags = tags; + this.signature = signature; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async prepareChunks(data) { + throw new Error('Should not be called, use arweave-js version.'); + } + // Returns a chunk in a format suitable for posting to /chunk. + // Similar to `prepareChunks()` this does not operate `this.data`, + // instead using the data passed in. + getChunk(idx, data) { + if (!this.chunks) { + throw new Error(`Chunks have not been prepared`); + } + const proof = this.chunks.proofs[idx]; + const chunk = this.chunks.chunks[idx]; + return { + data_root: this.data_root, + data_size: this.data_size, + data_path: ArweaveUtils.bufferTob64Url(proof.proof), + offset: proof.offset.toString(), + chunk: ArweaveUtils.bufferTob64Url(data.slice(chunk.minByteRange, chunk.maxByteRange)) + }; + } + async getSignatureData() { + throw new Error('Should not be called, use arweave-js version.'); + } +} +exports.Transaction = Transaction; +class Tag extends BaseObject { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + constructor(name, value, decode = false) { + super(); + this.name = name; + this.value = value; + } +} +exports.Tag = Tag; +//# sourceMappingURL=arweave-types.js.map \ No newline at end of file diff --git a/lib/cjs/utils/types/arweave-types.js.map b/lib/cjs/utils/types/arweave-types.js.map new file mode 100644 index 00000000..8661a129 --- /dev/null +++ b/lib/cjs/utils/types/arweave-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"arweave-types.js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AS,EAAE,IAAI,CAAC,SAAS;YACzB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,SAAS,EAAE,YAAY,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,CAAC;YACnD,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE;YAC/B,KAAK,EAAE,YAAY,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,YAAY,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;SACvF,CAAC;IACJ,CAAC;IAEM,KAAK,CAAC,gBAAgB;QAC3B,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;CACF;AA/GD,kCA+GC;AAED,MAAa,GAAI,SAAQ,UAAU;IAIjC,6DAA6D;IAC7D,YAAmB,IAAY,EAAE,KAAa,EAAE,MAAM,GAAG,KAAK;QAC5D,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AAVD,kBAUC"} \ No newline at end of file diff --git a/lib/cjs/utils/utils.js b/lib/cjs/utils/utils.js new file mode 100644 index 00000000..28ddc65c --- /dev/null +++ b/lib/cjs/utils/utils.js @@ -0,0 +1,124 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.safeGet = exports.getJsonResponse = exports.NetworkCommunicationError = exports.isBrowser = exports.bufToBn = exports.indent = exports.stripTrailingSlash = exports.timeout = exports.descS = exports.desc = exports.ascS = exports.asc = exports.mapReviver = exports.mapReplacer = exports.deepCopy = exports.safeParseInt = exports.sleep = void 0; +/* eslint-disable */ +const fast_copy_1 = __importDefault(require("fast-copy")); +const JsHandlerApi_1 = require("../core/modules/impl/handler/JsHandlerApi"); +const sleep = (ms) => { + return new Promise((resolve) => setTimeout(resolve, ms)); +}; +exports.sleep = sleep; +const safeParseInt = (str) => { + const maybeInt = Number.parseInt(str); + if (Number.isNaN(maybeInt) && !Number.isSafeInteger(maybeInt)) { + throw Error(`Failed to cast ${str} to integer`); + } + return maybeInt; +}; +exports.safeParseInt = safeParseInt; +const deepCopy = (input) => { + return (0, fast_copy_1.default)(input); +}; +exports.deepCopy = deepCopy; +const mapReplacer = (key, value) => { + if (value instanceof Map) { + return { + dataType: 'Map', + value: Array.from(value.entries()) + }; + } + else { + return value; + } +}; +exports.mapReplacer = mapReplacer; +const mapReviver = (key, value) => { + if (typeof value === 'object' && value !== null) { + if (value.dataType === 'Map') { + return new Map(value.value); + } + } + return value; +}; +exports.mapReviver = mapReviver; +const asc = (a, b) => a - b; +exports.asc = asc; +const ascS = (a, b) => +a - +b; +exports.ascS = ascS; +const desc = (a, b) => b - a; +exports.desc = desc; +const descS = (a, b) => +b - +a; +exports.descS = descS; +function timeout(s) { + let timeoutId = null; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + clearTimeout(timeoutId); + reject('timeout'); + }, s * 1000); + }); + return { + timeoutId, + timeoutPromise + }; +} +exports.timeout = timeout; +function stripTrailingSlash(str) { + return str.endsWith('/') ? str.slice(0, -1) : str; +} +exports.stripTrailingSlash = stripTrailingSlash; +function indent(callDepth) { + return `[d:${callDepth}]`.padEnd(callDepth * 2, '-').concat('> '); +} +exports.indent = indent; +function bufToBn(buf) { + const hex = []; + const u8 = Uint8Array.from(buf); + u8.forEach(function (i) { + let h = i.toString(16); + if (h.length % 2) { + h = '0' + h; + } + hex.push(h); + }); + return BigInt('0x' + hex.join('')); +} +exports.bufToBn = bufToBn; +exports.isBrowser = new Function('try {return this===window;}catch(e){ return false;}'); +class NetworkCommunicationError extends Error { + constructor(error) { + super(error.toString()); + this.error = error; + this.name = JsHandlerApi_1.KnownErrors.NetworkCommunicationError; + } +} +exports.NetworkCommunicationError = NetworkCommunicationError; +async function getJsonResponse(response) { + let r; + try { + r = await response; + } + catch (e) { + throw new NetworkCommunicationError(`Error during network communication: ${JSON.stringify(e)}`); + } + if (!(r === null || r === void 0 ? void 0 : r.ok)) { + const text = await r.text(); + throw new NetworkCommunicationError(`Wrong response code: ${r.status}. ${text}`); + } + try { + const result = await r.json(); + return result; + } + catch (e) { + throw new NetworkCommunicationError(`Error while parsing json response: ${JSON.stringify(e)}`); + } +} +exports.getJsonResponse = getJsonResponse; +async function safeGet(input, init) { + return getJsonResponse(fetch(input, init)); +} +exports.safeGet = safeGet; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib/cjs/utils/utils.js.map b/lib/cjs/utils/utils.js.map new file mode 100644 index 00000000..1b574b4b --- /dev/null +++ b/lib/cjs/utils/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AAAA,oBAAoB;AACpB,0DAA6B;AAE7B,4EAAwE;AAEjE,MAAM,KAAK,GAAG,CAAC,EAAU,EAAiB,EAAE;IACjD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC,CAAC;AAFW,QAAA,KAAK,SAEhB;AAEK,MAAM,YAAY,GAAG,CAAC,GAAW,EAAU,EAAE;IAClD,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAEtC,IAAI,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE;QAC7D,MAAM,KAAK,CAAC,kBAAkB,GAAG,aAAa,CAAC,CAAC;KACjD;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC;AARW,QAAA,YAAY,gBAQvB;AAEK,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAO,EAAE;IAC9C,OAAO,IAAA,mBAAI,EAAC,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index 00000000..f88b1f4e --- /dev/null +++ b/lib/mjs/index.js @@ -0,0 +1,105 @@ +import mod from "../cjs/index.js"; + +export default mod; +export const AbstractContractHandler = mod.AbstractContractHandler; +export const ArweaveGatewayBundledContractDefinitionLoader = mod.ArweaveGatewayBundledContractDefinitionLoader; +export const ArweaveGatewayBundledInteractionLoader = mod.ArweaveGatewayBundledInteractionLoader; +export const ArweaveGatewayInteractionsLoader = mod.ArweaveGatewayInteractionsLoader; +export const ArweaveWrapper = mod.ArweaveWrapper; +export const Benchmark = mod.Benchmark; +export const CacheKey = mod.CacheKey; +export const CacheableInteractionsLoader = mod.CacheableInteractionsLoader; +export const CacheableStateEvaluator = mod.CacheableStateEvaluator; +export const ConsoleLogger = mod.ConsoleLogger; +export const ConsoleLoggerFactory = mod.ConsoleLoggerFactory; +export const ContractCache = mod.ContractCache; +export const ContractCallRecord = mod.ContractCallRecord; +export const ContractDefinitionLoader = mod.ContractDefinitionLoader; +export const ContractError = mod.ContractError; +export const ContractMetadata = mod.ContractMetadata; +export const CustomEvent = mod.CustomEvent; +export const DEFAULT_LEVEL_DB_LOCATION = mod.DEFAULT_LEVEL_DB_LOCATION; +export const DefaultEvaluationOptions = mod.DefaultEvaluationOptions; +export const DefaultStateEvaluator = mod.DefaultStateEvaluator; +export const EvalStateResult = mod.EvalStateResult; +export const EvaluationOptionsEvaluator = mod.EvaluationOptionsEvaluator; +export const HandlerBasedContract = mod.HandlerBasedContract; +export const HandlerExecutorFactory = mod.HandlerExecutorFactory; +export const InnerWritesEvaluator = mod.InnerWritesEvaluator; +export const InteractionCall = mod.InteractionCall; +export const InteractionCompleteEvent = mod.InteractionCompleteEvent; +export const InteractionInput = mod.InteractionInput; +export const InteractionOutput = mod.InteractionOutput; +export const JsHandlerApi = mod.JsHandlerApi; +export const KV = mod.KV; +export const KnownErrors = mod.KnownErrors; +export const LevelDbCache = mod.LevelDbCache; +export const LexicographicalInteractionsSorter = mod.LexicographicalInteractionsSorter; +export const LogLevelOrder = mod.LogLevelOrder; +export const LoggerFactory = mod.LoggerFactory; +export const MemCache = mod.MemCache; +export const NetworkCommunicationError = mod.NetworkCommunicationError; +export const NonWhitelistedSourceError = mod.NonWhitelistedSourceError; +export const PstContractImpl = mod.PstContractImpl; +export const REGISTER_PROVIDER = mod.REGISTER_PROVIDER; +export const SMART_WEAVE_TAGS = mod.SMART_WEAVE_TAGS; +export const SUPPORTED_SRC_CONTENT_TYPES = mod.SUPPORTED_SRC_CONTENT_TYPES; +export const SWBlock = mod.SWBlock; +export const SWTransaction = mod.SWTransaction; +export const SWVrf = mod.SWVrf; +export const Signature = mod.Signature; +export const SmartWeaveError = mod.SmartWeaveError; +export const SmartWeaveErrorType = mod.SmartWeaveErrorType; +export const SmartWeaveGlobal = mod.SmartWeaveGlobal; +export const SortKeyCacheResult = mod.SortKeyCacheResult; +export const SourceType = mod.SourceType; +export const SrcCache = mod.SrcCache; +export const Tag = mod.Tag; +export const TagsParser = mod.TagsParser; +export const Transaction = mod.Transaction; +export const WARP_GW_URL = mod.WARP_GW_URL; +export const WARP_TAGS = mod.WARP_TAGS; +export const Warp = mod.Warp; +export const WarpBuilder = mod.WarpBuilder; +export const WarpFactory = mod.WarpFactory; +export const WarpFetchWrapper = mod.WarpFetchWrapper; +export const WarpGatewayContractDefinitionLoader = mod.WarpGatewayContractDefinitionLoader; +export const WarpGatewayInteractionsLoader = mod.WarpGatewayInteractionsLoader; +export const WasmHandlerApi = mod.WasmHandlerApi; +export const WasmSrc = mod.WasmSrc; +export const arrayToHex = mod.arrayToHex; +export const asc = mod.asc; +export const ascS = mod.ascS; +export const bufToBn = mod.bufToBn; +export const bundledTxsFilter = mod.bundledTxsFilter; +export const checkJsSrc = mod.checkJsSrc; +export const createDummyTx = mod.createDummyTx; +export const createInteractionTagsList = mod.createInteractionTagsList; +export const createInteractionTx = mod.createInteractionTx; +export const deepCopy = mod.deepCopy; +export const defaultArweaveMs = mod.defaultArweaveMs; +export const defaultCacheOptions = mod.defaultCacheOptions; +export const defaultWarpGwOptions = mod.defaultWarpGwOptions; +export const desc = mod.desc; +export const descS = mod.descS; +export const emptyTransfer = mod.emptyTransfer; +export const genesisSortKey = mod.genesisSortKey; +export const getJsonResponse = mod.getJsonResponse; +export const indent = mod.indent; +export const isBrowser = mod.isBrowser; +export const knownWarpPlugins = mod.knownWarpPlugins; +export const knownWarpPluginsPartial = mod.knownWarpPluginsPartial; +export const lastPossibleSortKey = mod.lastPossibleSortKey; +export const lvlToOrder = mod.lvlToOrder; +export const mapReplacer = mod.mapReplacer; +export const mapReviver = mod.mapReviver; +export const matchMutClosureDtor = mod.matchMutClosureDtor; +export const normalizeContractSource = mod.normalizeContractSource; +export const rustWasmImports = mod.rustWasmImports; +export const safeGet = mod.safeGet; +export const safeParseInt = mod.safeParseInt; +export const sleep = mod.sleep; +export const sortingFirst = mod.sortingFirst; +export const sortingLast = mod.sortingLast; +export const stripTrailingSlash = mod.stripTrailingSlash; +export const timeout = mod.timeout; diff --git a/lib/mjs/package.json b/lib/mjs/package.json new file mode 100644 index 00000000..47200257 --- /dev/null +++ b/lib/mjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/lib/types/cache/BasicSortKeyCache.d.ts b/lib/types/cache/BasicSortKeyCache.d.ts new file mode 100644 index 00000000..8d007aff --- /dev/null +++ b/lib/types/cache/BasicSortKeyCache.d.ts @@ -0,0 +1,58 @@ +import { CacheKey, PruneStats, SortKeyCacheResult } from './SortKeyCache'; +/** + * A cache that stores its values per dedicated key and sort key. + * A sort key is a value that the SmartWeave protocol is using + * to sort contract transactions ({@link LexicographicalInteractionsSorter}. + * + * All values should be stored in a lexicographical order (per key) - + * sorted by the sort key. + */ +export interface BasicSortKeyCache { + getLessOrEqual(key: string, sortKey: string): Promise | null>; + /** + * returns value stored for a given key and last sortKey + */ + getLast(key: string): Promise | null>; + /** + * returns last cached sort key - takes all keys into account + */ + getLastSortKey(): Promise; + /** + * returns value for the key and exact sortKey + */ + get(cacheKey: CacheKey): Promise | null>; + /** + * puts new value in cache under given {@link CacheKey.key} and {@link CacheKey.sortKey}. + */ + put(cacheKey: CacheKey, value: V): Promise; + /** + * removes all data stored under a specified key + */ + delete(key: string): Promise; + open(): Promise; + close(): Promise; + begin(): Promise; + rollback(): Promise; + commit(): Promise; + /** + * used mostly for debugging, allows to dump the current content cache + * It's slow. + */ + dump(): Promise; + /** + * returns underlying storage (LevelDB, LMDB, sqlite...) + * - useful for performing low-level operations + */ + storage(): S; + /** + * leaves n-latest (i.e. with latest (in lexicographic order) sort keys) + * entries for each cached key + * + * @param entriesStored - how many latest entries should be left + * for each cached key + * + * @retun PruneStats if getting them doesn't introduce a delay, null otherwise + */ + prune(entriesStored: number): Promise; +} +//# sourceMappingURL=BasicSortKeyCache.d.ts.map \ No newline at end of file diff --git a/lib/types/cache/BasicSortKeyCache.d.ts.map b/lib/types/cache/BasicSortKeyCache.d.ts.map new file mode 100644 index 00000000..81b04d7a --- /dev/null +++ b/lib/types/cache/BasicSortKeyCache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"BasicSortKeyCache.d.ts","sourceRoot":"","sources":["../../../src/cache/BasicSortKeyCache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAE1E;;;;;;;GAOG;AACH,MAAM,WAAW,iBAAiB,CAAC,CAAC;IAClC,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAEpF;;OAEG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAE5D;;OAEG;IACH,cAAc,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAEzC;;OAEG;IACH,GAAG,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAE/D;;OAEG;IACH,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjD;;OAEG;IACH,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnC,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1B,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAExB;;;OAGG;IACH,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC;IAErB;;;OAGG;IACH,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC;IAEhB;;;;;;;;OAQG;IACH,KAAK,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;CAC1D"} \ No newline at end of file diff --git a/lib/types/cache/SortKeyCache.d.ts b/lib/types/cache/SortKeyCache.d.ts new file mode 100644 index 00000000..c4766a6e --- /dev/null +++ b/lib/types/cache/SortKeyCache.d.ts @@ -0,0 +1,56 @@ +import { SortKeyCacheRangeOptions } from './SortKeyCacheRangeOptions'; +import { BasicSortKeyCache } from './BasicSortKeyCache'; +/** + * Key-value cache storage. + * Just as {@link BasicSortKeyCache}, items are stored + * in lexicographical order using by sort key. + * + * In addition, this interface provide functionality related to + * fetching keys and values using range options. {@link SortKeyCacheRangeOptions} + */ +export interface SortKeyCache extends BasicSortKeyCache { + /** + * deletes value in cache under given {@link CacheKey.key} from {@link CacheKey.sortKey}. + * the value will be still available if fetched using a lower sortKey + */ + del(cacheKey: CacheKey): Promise; + /** + * executes a list of stacked operations + */ + batch(opStack: BatchDBOp[]): any; + /** + * Returns keys for a specified range + */ + keys(sortKey: string, options?: SortKeyCacheRangeOptions): Promise; + /** + * Returns a key value map for a specified range + */ + kvMap(sortKey: string, options?: SortKeyCacheRangeOptions): Promise>; +} +export interface PruneStats { + entriesBefore: number; + entriesAfter: number; + sizeBefore: number; + sizeAfter: number; +} +export declare class CacheKey { + readonly key: string; + readonly sortKey: string; + constructor(key: string, sortKey: string); +} +export declare class SortKeyCacheResult { + readonly sortKey: string; + readonly cachedValue: V; + constructor(sortKey: string, cachedValue: V); +} +export declare type BatchDBOp = PutBatch | DelBatch; +export interface PutBatch { + type: 'put'; + key: CacheKey; + value: V; +} +export interface DelBatch { + type: 'del'; + key: string; +} +//# sourceMappingURL=SortKeyCache.d.ts.map \ No newline at end of file diff --git a/lib/types/cache/SortKeyCache.d.ts.map b/lib/types/cache/SortKeyCache.d.ts.map new file mode 100644 index 00000000..02ac7e02 --- /dev/null +++ b/lib/types/cache/SortKeyCache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SortKeyCache.d.ts","sourceRoot":"","sources":["../../../src/cache/SortKeyCache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY,CAAC,CAAC,CAAE,SAAQ,iBAAiB,CAAC,CAAC,CAAC;IAC3D;;;OAGG;IACH,GAAG,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvC;;OAEG;IACH,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,OAAE;IAE/B;;OAEG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAE7E;;OAEG;IACH,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC;CACrF;AAED,MAAM,WAAW,UAAU;IACzB,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,qBAAa,QAAQ;IACP,QAAQ,CAAC,GAAG,EAAE,MAAM;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM;gBAArC,GAAG,EAAE,MAAM,EAAW,OAAO,EAAE,MAAM;CAC3D;AAED,qBAAa,kBAAkB,CAAC,CAAC;IACnB,QAAQ,CAAC,OAAO,EAAE,MAAM;IAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;gBAAxC,OAAO,EAAE,MAAM,EAAW,WAAW,EAAE,CAAC;CAC9D;AAED,MAAM,CAAC,OAAO,MAAM,SAAS,CAAC,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC;AAE1D,MAAM,WAAW,QAAQ,CAAC,CAAC;IACzB,IAAI,EAAE,KAAK,CAAC;IACZ,GAAG,EAAE,QAAQ,CAAC;IACd,KAAK,EAAE,CAAC,CAAC;CACV;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,KAAK,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;CACb"} \ No newline at end of file diff --git a/lib/types/cache/SortKeyCacheRangeOptions.d.ts b/lib/types/cache/SortKeyCacheRangeOptions.d.ts new file mode 100644 index 00000000..0e9db0a0 --- /dev/null +++ b/lib/types/cache/SortKeyCacheRangeOptions.d.ts @@ -0,0 +1,14 @@ +/** + * Range option for fetching items from kv storage {@link SortKeyCache} + * @param gte - greater than equals + * @param lt - less than + * @param reverse - reverses the order + * @param limit - limits output elements + */ +export interface SortKeyCacheRangeOptions { + gte?: string; + lt?: string; + reverse?: boolean | undefined; + limit?: number | undefined; +} +//# sourceMappingURL=SortKeyCacheRangeOptions.d.ts.map \ No newline at end of file diff --git a/lib/types/cache/SortKeyCacheRangeOptions.d.ts.map b/lib/types/cache/SortKeyCacheRangeOptions.d.ts.map new file mode 100644 index 00000000..40de1532 --- /dev/null +++ b/lib/types/cache/SortKeyCacheRangeOptions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SortKeyCacheRangeOptions.d.ts","sourceRoot":"","sources":["../../../src/cache/SortKeyCacheRangeOptions.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,WAAW,wBAAwB;IACvC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC9B,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5B"} \ No newline at end of file diff --git a/lib/types/cache/WarpCache.d.ts b/lib/types/cache/WarpCache.d.ts new file mode 100644 index 00000000..a8c2b2c0 --- /dev/null +++ b/lib/types/cache/WarpCache.d.ts @@ -0,0 +1,32 @@ +/** + * Base interface for Warp Cache implementors. + * Useful for simple, non block-height dependant caches + * - like contract's source code cache. + * See {@link MemCache} for example implementation. + * + * @typeParam K - type of the cache key. + * @typeParam V - type of the cache value. + */ +export interface WarpCache { + /** + * gets value by its key + */ + get(key: K): V; + /** + * checks whether cache contains entry for given key + */ + contains(key: K): boolean; + /** + * puts new value under specified key + */ + put(key: K, value: V): void; + /** + * clears the whole cache + */ + clearAll(): void; + /** + * remove entry in cache for given key + */ + remove(key: K): void; +} +//# sourceMappingURL=WarpCache.d.ts.map \ No newline at end of file diff --git a/lib/types/cache/WarpCache.d.ts.map b/lib/types/cache/WarpCache.d.ts.map new file mode 100644 index 00000000..8d1d07d9 --- /dev/null +++ b/lib/types/cache/WarpCache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpCache.d.ts","sourceRoot":"","sources":["../../../src/cache/WarpCache.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,WAAW,SAAS,CAAC,CAAC,EAAE,CAAC;IAC7B;;OAEG;IACH,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC;IAEf;;OAEG;IACH,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC;IAE1B;;OAEG;IACH,GAAG,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;IAE5B;;OAEG;IACH,QAAQ,IAAI,IAAI,CAAC;IAEjB;;OAEG;IACH,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC;CACtB"} \ No newline at end of file diff --git a/lib/types/cache/impl/LevelDbCache.d.ts b/lib/types/cache/impl/LevelDbCache.d.ts new file mode 100644 index 00000000..efebc309 --- /dev/null +++ b/lib/types/cache/impl/LevelDbCache.d.ts @@ -0,0 +1,74 @@ +import { BatchDBOp, CacheKey, SortKeyCache, SortKeyCacheResult } from '../SortKeyCache'; +import { CacheOptions } from '../../core/WarpFactory'; +import { SortKeyCacheRangeOptions } from '../SortKeyCacheRangeOptions'; +export declare class LevelDbCache implements SortKeyCache { + private readonly cacheOptions; + private readonly ongoingTransactionMark; + private readonly logger; + private readonly subLevelSeparator; + private readonly subLevelOptions; + /** + * not using the Level type, as it is not compatible with MemoryLevel (i.e. has more properties) + * and there doesn't seem to be any public interface/abstract type for all Level implementations + * (the AbstractLevel is not exported from the package...) + */ + private _db; + /** + * Rollback batch is way of recovering kv storage state from before a failed interaction. + * Currently, all operations performed during active transaction are directly saved to kv storage. + * In case the transaction fails the changes will be reverted using the rollback batch. + */ + private _rollbackBatch; + private get db(); + constructor(cacheOptions: CacheOptions); + get(cacheKey: CacheKey, returnDeepCopy?: boolean): Promise | null>; + getLast(key: string): Promise | null>; + getLessOrEqual(key: string, sortKey: string): Promise | null>; + private getValueFromLevel; + put(stateCacheKey: CacheKey, value: V): Promise; + /** + * Delete operation under the hood is a write operation with setting tomb flag to true. + * The idea behind is based on Cassandra Tombstone + * https://www.instaclustr.com/support/documentation/cassandra/using-cassandra/managing-tombstones-in-cassandra/ + * There is a couple of benefits to this approach: + * This allows to use kv storage range operations with ease. + * The value will not be accessible only to the next interactions. Interactions reading state for lower sortKey will be able to access it. + * Revert operation for rollback is much easier to implement + */ + del(cacheKey: CacheKey): Promise; + private setClientValue; + delete(key: string): Promise; + batch(opStack: BatchDBOp[]): Promise; + open(): Promise; + close(): Promise; + begin(): Promise; + rollback(): Promise; + private initRollbackBatch; + private checkPreviousTransactionFinished; + commit(): Promise; + dump(): Promise; + getLastSortKey(): Promise; + keys(sortKey: string, options?: SortKeyCacheRangeOptions): Promise; + validateKey(key: string): void; + extractOriginalKey(joinedKey: string): string; + extractSortKey(joinedKey: string): string; + kvMap(sortKey: string, options?: SortKeyCacheRangeOptions): Promise>; + private levelRangeOptions; + storage(): S; + getNumEntries(): Promise; + /** + Let's assume that given contract cache contains these sortKeys: [a, b, c, d, e, f] + Let's assume entriesStored = 2 + After pruning, the cache should be left with these keys: [e,f]. + + const entries = await contractCache.keys({ reverse: true, limit: entriesStored }).all(); + This would return in this case entries [f, e] (notice the "reverse: true"). + + await contractCache.clear({ lt: entries[entries.length - 1] }); + This effectively means: await contractCache.clear({ lt: e }); + -> hence the entries [a,b,c,d] are removed and left are the [e,f] + */ + prune(entriesStored?: number): Promise; + private allKeys; +} +//# sourceMappingURL=LevelDbCache.d.ts.map \ No newline at end of file diff --git a/lib/types/cache/impl/LevelDbCache.d.ts.map b/lib/types/cache/impl/LevelDbCache.d.ts.map new file mode 100644 index 00000000..904ea476 --- /dev/null +++ b/lib/types/cache/impl/LevelDbCache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"LevelDbCache.d.ts","sourceRoot":"","sources":["../../../../src/cache/impl/LevelDbCache.ts"],"names":[],"mappings":"AAAA,OAAO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M,GAAG,OAAO,CAAC,IAAI,CAAC;IAMlC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE;IAU7B,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAIrB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAItB,QAAQ;YASA,iBAAiB;YAcjB,gCAAgC;IAiBxC,MAAM;IAUN,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC;IAOpB,cAAc,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAiBxC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAIlF,WAAW,CAAC,GAAG,EAAE,MAAM;IASvB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM;IAI7C,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM;IAInC,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAyBzF,OAAO,CAAC,iBAAiB;IAgBzB,OAAO,CAAC,CAAC,KAAK,CAAC;IAIT,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAKtC;;;;;;;;;;;MAWE;IACI,KAAK,CAAC,aAAa,SAAI,GAAG,OAAO,CAAC,IAAI,CAAC;YAwB/B,OAAO;CAKtB"} \ No newline at end of file diff --git a/lib/types/cache/impl/MemCache.d.ts b/lib/types/cache/impl/MemCache.d.ts new file mode 100644 index 00000000..481f28e8 --- /dev/null +++ b/lib/types/cache/impl/MemCache.d.ts @@ -0,0 +1,13 @@ +import { WarpCache } from '../../cache/WarpCache'; +/** + * A simple, in-memory cache, with keys being transaction ids (e.g. contract transaction id). + */ +export declare class MemCache implements WarpCache { + private readonly storage; + clearAll(): void; + contains(key: string): boolean; + get(key: string): V; + put(key: string, value: V): void; + remove(key: string): void; +} +//# sourceMappingURL=MemCache.d.ts.map \ No newline at end of file diff --git a/lib/types/cache/impl/MemCache.d.ts.map b/lib/types/cache/impl/MemCache.d.ts.map new file mode 100644 index 00000000..04745e4c --- /dev/null +++ b/lib/types/cache/impl/MemCache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MemCache.d.ts","sourceRoot":"","sources":["../../../../src/cache/impl/MemCache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElD;;GAEG;AACH,qBAAa,QAAQ,CAAC,CAAC,CAAE,YAAW,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC;IACtD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA4B;IAEpD,QAAQ;IAMR,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAI9B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC;IAInB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IAIzB,MAAM,CAAC,GAAG,EAAE,MAAM;CAGnB"} \ No newline at end of file diff --git a/lib/types/common/SimpleLRUCache.d.ts b/lib/types/common/SimpleLRUCache.d.ts new file mode 100644 index 00000000..960ace2d --- /dev/null +++ b/lib/types/common/SimpleLRUCache.d.ts @@ -0,0 +1,11 @@ +export declare class SimpleLRUCache { + private readonly cache; + private readonly capacity; + constructor(capacity: number); + has(key: K): boolean; + size(): number; + get(key: K): V; + set(key: K, value: V): void; + keys(): K[]; +} +//# sourceMappingURL=SimpleLRUCache.d.ts.map \ No newline at end of file diff --git a/lib/types/common/SimpleLRUCache.d.ts.map b/lib/types/common/SimpleLRUCache.d.ts.map new file mode 100644 index 00000000..ca6d82c1 --- /dev/null +++ b/lib/types/common/SimpleLRUCache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SimpleLRUCache.d.ts","sourceRoot":"","sources":["../../../src/common/SimpleLRUCache.ts"],"names":[],"mappings":"AAAA,qBAAa,cAAc,CAAC,CAAC,EAAE,CAAC;IAC9B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAY;IAClC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;gBACtB,QAAQ,EAAE,MAAM;IAK5B,GAAG,CAAC,GAAG,EAAE,CAAC;IAIV,IAAI,IAAI,MAAM;IAId,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC;IAWd,GAAG,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC;IAWpB,IAAI,IAAI,CAAC,EAAE;CAGZ"} \ No newline at end of file diff --git a/lib/types/contract/Contract.d.ts b/lib/types/contract/Contract.d.ts new file mode 100644 index 00000000..411455ac --- /dev/null +++ b/lib/types/contract/Contract.d.ts @@ -0,0 +1,209 @@ +import { SortKeyCacheResult } from '../cache/SortKeyCache'; +import { ContractCallRecord } from '../core/ContractCallRecord'; +import { InteractionResult } from '../core/modules/impl/HandlerExecutorFactory'; +import { EvaluationOptions, EvalStateResult } from '../core/modules/StateEvaluator'; +import { GQLNodeInterface } from '../legacy/gqlResult'; +import { ArTransfer, Tags, ArWallet } from './deploy/CreateContract'; +import { CustomSignature } from './Signature'; +import { EvaluationOptionsEvaluator } from './EvaluationOptionsEvaluator'; +import { InteractionState } from './states/InteractionState'; +import { DataItem, Signer } from 'warp-arbundles'; +import { Transaction } from '../utils/types/arweave-types'; +export type BenchmarkStats = { + gatewayCommunication: number; + stateEvaluation: number; + total: number; +}; +interface BundlrResponse { + id: string; + public: string; + signature: string; + block: number; +} +export interface WriteInteractionResponse { + bundlrResponse?: BundlrResponse; + originalTxId: string; + interactionTx: Transaction | DataItem; +} +export interface DREContractStatusResponse { + status: string; + contractTxId: string; + state: State; + validity: Record; + errorMessages: Record; + sortKey: string; + timestamp: string; + signature: string; + stateHash: string; +} +export type WarpOptions = { + vrf?: boolean; + disableBundling?: boolean; +}; +export type ArweaveOptions = { + transfer?: ArTransfer; + reward?: string; +}; +export type CommonOptions = { + tags?: Tags; + strict?: boolean; +}; +export type WriteInteractionOptions = WarpOptions & ArweaveOptions & CommonOptions; +/** + * Interface describing state for all Evolve-compatible contracts. + */ +export interface EvolveState { + settings: any[] | unknown | null; + /** + * whether contract is allowed to evolve. + */ + canEvolve: boolean; + /** + * the transaction id of the Arweave transaction with the updated source code. + */ + evolve: string; +} +export type InnerCallType = 'read' | 'view' | 'write'; +export type InnerCallData = { + callingInteraction: GQLNodeInterface; + callType: InnerCallType; +}; +/** + * A base interface to be implemented by SmartWeave Contracts clients + * - contains "low-level" methods that allow to interact with any contract + */ +export interface Contract { + /** + * Returns the Arweave transaction id of this contract. + */ + txId(): string; + /** + * Allows to connect a signer to a contract. + * Connecting a signer MAY be done before "viewState" (depending on contract implementation, + * i.e. whether called contract's function required "caller" info) + * Connecting a signer MUST be done before "writeInteraction" and "bundleInteraction". + * + * @param signer - either {@link ArWallet} that will be connected to this contract, custom {@link SigningFunction} or {@link Signer} + */ + connect(signature: ArWallet | CustomSignature | Signer): Contract; + /** + * Allows to set ({@link EvaluationOptions}) + * + * @param options - a set of {@link EvaluationOptions} that will overwrite current configuration + */ + setEvaluationOptions(options: Partial): Contract; + /** + * Returns state of the contract at required sortKey or blockHeight. + * + * @param sortKeyOrBlockHeight - either a sortKey or block height at which the contract should be read + * + * @param currentTx - a set of currently evaluating interactions, that should + * be skipped during contract inner calls - to prevent the infinite call loop issue + * (mostly related to contract that use the Foreign Call Protocol) + */ + readState(sortKeyOrBlockHeight?: string | number, caller?: string, interactions?: GQLNodeInterface[]): Promise>>; + readStateFor(sortKey: string, interactions: GQLNodeInterface[]): Promise>>; + /** + * Returns the "view" of the state, computed by the SWC - + * i.e. object that is a derivative of a current state and some specific + * smart contract business logic. + * Similar to the "interactRead" from the current SDK version. + * + * This method firstly evaluates the contract state to the requested block height. + * Having the contract state on this block height - it then calls the contract's code + * with specified input. + * + * @param input - the input to the contract - eg. function name and parameters + * @param tags - a set of tags that can be added to the interaction transaction + * @param transfer - additional {@link ArTransfer} data that can be attached to the interaction + * @param caller - caller of the view state operation + * transaction + */ + viewState(input: Input, tags?: Tags, transfer?: ArTransfer, caller?: string): Promise>; + /** + * A version of the viewState method to be used from within the contract's source code. + * The transaction passed as an argument is the currently processed interaction transaction. + * The "caller" will be se to the owner of the interaction transaction, that + * requires to call this method. + * + * note: calling "interactRead" from withing contract's source code was not previously possible - + * this is a new feature. + * + * TODO: this should not be exposed in a public API - as it is supposed + * to be used only by Handler code. + */ + viewStateForTx(input: Input, transaction: GQLNodeInterface): Promise>; + /** + * A dry-write operation on contract. It first loads the contract's state and then + * creates a "dummy" transaction and applies the given Input on top of the current contract's + * state. + * @param input - input to be applied on the current contract's state + * @param tags - additional tags to be added to interaction transaction + * @param transfer - additional {@link ArTransfer} data to be associated with the "dummy" transaction + * @param caller - an option to override the caller - if available, this value will overwrite the caller evaluated + * from the wallet connected to this contract. + * @param vrf - whether a mock VRF data should be generated + */ + dryWrite(input: Input, caller?: string, tags?: Tags, transfer?: ArTransfer, vrf?: boolean): Promise>; + applyInput(input: Input, transaction: GQLNodeInterface): Promise>; + /** + * Writes a new "interaction" transaction - i.e. such transaction that stores input for the contract. + */ + writeInteraction(input: Input, options?: WriteInteractionOptions): Promise; + /** + * Returns the full call tree report the last + * interaction with contract (eg. after reading state) + */ + getCallStack(): ContractCallRecord; + /** + * Gets the parent contract - ie. contract that called THIS contract during the + * state evaluation. + */ + parent(): Contract | null; + /** + * Return the depth of the call to this contract. + * E.g. + * 1. User calls ContractA.readState() - depth = 0 + * 2. ContractA.readState() calls ContractB.readState() - depth = 1 + * 3. ContractB.readState calls ContractC.readState() - depth = 2 + */ + callDepth(): number; + /** + * {@link EvaluationOptions} assigned to this contract. + * The evaluation options for the child contracts are always + * the same as the evaluation options of the root contract. + */ + evaluationOptions(): EvaluationOptions; + /** + * returns benchmark results for the last performed readState call + */ + lastReadStateStats(): BenchmarkStats; + /** + * calculates state hash using stable stringify + */ + stateHash(state: State): Promise; + /** + * this method allows to sync the state of the local SDK state with the state provided by an external endpoint; + * @param externalUrl - external endpoint url + * @param params - by default only query param with `contractId` is set by SDK, any additional ones can be passed + * in the `params` object + */ + syncState(externalUrl: string, params?: any): Promise; + /** + * Evolve is a feature that allows to change contract's source + * code, without having to deploy a new contract. + * This method effectively evolves the contract to the source. + * This requires the {@link save} to be called first + * and its transaction to be confirmed by the network. + * @param newSrcTxId - result of the {@link save} method call. + */ + evolve(newSrcTxId: string, options?: WriteInteractionOptions): Promise; + rootSortKey: string; + getRootEoEvaluator(): EvaluationOptionsEvaluator; + isRoot(): boolean; + getStorageValues(keys: string[]): Promise>>; + interactionState(): InteractionState; + clearChildren(): void; +} +export {}; +//# sourceMappingURL=Contract.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/Contract.d.ts.map b/lib/types/contract/Contract.d.ts.map new file mode 100644 index 00000000..bd88e6df --- /dev/null +++ b/lib/types/contract/Contract.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Contract.d.ts","sourceRoot":"","sources":["../../../src/contract/Contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAChF,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACpF,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,QA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K,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEzC;;;;;OAKG;IAEH,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAEhE;;;;;;;OAOG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC,CAAC;IAExG,WAAW,EAAE,MAAM,CAAC;IAEpB,kBAAkB,IAAI,0BAA0B,CAAC;IAEjD,MAAM,IAAI,OAAO,CAAC;IAElB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IAEpF,gBAAgB,IAAI,gBAAgB,CAAC;IAErC,aAAa,IAAI,IAAI,CAAC;CACvB"} \ No newline at end of file diff --git a/lib/types/contract/EvaluationOptionsEvaluator.d.ts b/lib/types/contract/EvaluationOptionsEvaluator.d.ts new file mode 100644 index 00000000..b5af1599 --- /dev/null +++ b/lib/types/contract/EvaluationOptionsEvaluator.d.ts @@ -0,0 +1,70 @@ +import { EvaluationOptions } from '../core/modules/StateEvaluator'; +export declare class EvaluationOptionsEvaluator { + /** + * The effective evaluation options for the root contract + * i.e. options set via {@link Contract.setEvaluationOptions} + * with values overwritten from contract's manifest + * (if contract manifest was set during contract deployment). + * + * In other words - if certain evaluation options are available in + * contract's manifest - they take precedence over those set via + * {@link Contract.setEvaluationOptions} + */ + readonly rootOptions: EvaluationOptions; + private readonly saferEvaluationOptions; + private readonly notConflictingEvaluationOptions; + /** + * @param userSetOptions evaluation options set via {@link Contract.setEvaluationOptions} + * @param manifestOptions evaluation options from the root contract's manifest (i.e. the contract that + * the user is trying to read - e.g. via warp.contract().readState(); + */ + constructor(userSetOptions: EvaluationOptions, manifestOptions: Partial); + /** + * The idea here is that evaluation of the foreign contract should not be processed with "less secure" + * evaluation options than those set for the main/root contract (i.e. the one that is being read by the User). + * + * Currently, one exception to this rule are the internal writes. + * Consider the examples below: + * + * Example 1: + * 1. The root contract blocks internal writes + * 2. The foreign contract allows for internal writes + * => the internal writes should be allowed during evaluation of the foreign contract + * + * Example 2: + * 1. The root contract has the 'unsafeClient' set to 'skip' + * 2. The foreign contract has the 'unsafeClient' to 'allow' + * => the 'unsafeClient' should be set to 'skip' for foreign contract + * + * Example 3: + * 1. The root contract has the 'vm2' set to 'true' + * 2. The foreign contract has the 'vm2' set to 'false' + * => the 'vm2' for the foreign contract should be set to 'true' + * + * Example 4: + * 1. The root contract has the 'maxCallDepth' set to 3 + * 2. The foreign contract has the 'maxCallDepth' set to 5 + * => the 'maxCallDepth' for the foreign contract should be set to '3' + * NOTE: call depth is always verified from the perspective of the root contract! + * + * Example 5: + * 1. The root contract has the 'maxInteractionEvaluationTimeSeconds' set to 10 + * 2. The foreign contract has the 'maxInteractionEvaluationTimeSeconds' set to 60 + * => the 'maxInteractionEvaluationTimeSeconds' for the foreign contract should be set to '10' + * + * On the other hand - if the root contract has less secure options than the foreign contract - + * the more secure options of the foreign contract should be respected. + * Example: + * 1. Contract "A" with 'unsafeClient' = 'allow' (and unsafeClient used in its source) is performing + * write operation on Contract "B" that has 'unsafeClient' set to 'skip'. + * i.e. Contract A calls SmartWeave.contracts.write on Contract B. + * + * In this case the more secure setting of the Contract B should be reflected - and write itself + * should be blocked (i.e. it should not be even created during the `A.writeInteraction` - when a dry-run + * is being performed, and we're evaluating a list of internal writes for a newly created interaction). + * + * @param foreignContractManifest the manifest of the foreign contract that we want read/write to + */ + forForeignContract(foreignContractOptions?: Partial): EvaluationOptions; +} +//# sourceMappingURL=EvaluationOptionsEvaluator.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/EvaluationOptionsEvaluator.d.ts.map b/lib/types/contract/EvaluationOptionsEvaluator.d.ts.map new file mode 100644 index 00000000..c1f22456 --- /dev/null +++ b/lib/types/contract/EvaluationOptionsEvaluator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"EvaluationOptionsEvaluator.d.ts","sourceRoot":"","sources":["../../../src/contract/EvaluationOptionsEvaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAOnE,qBAAa,0BAA0B;IACrC;;;;;;;;;OASG;IACH,SAAgB,WAAW,EAAE,iBAAiB,CAAC;IAE/C,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CA0FrC;IAEF,OAAO,CAAC,QAAQ,CAAC,+BAA+B,CAI9C;IAEF;;;;OAIG;gBACS,cAAc,EAAE,iBAAiB,EAAE,eAAe,EAAE,OAAO,CAAC,iBAAiB,CAAC;IAiD1F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6CG;IACH,kBAAkB,CAAC,sBAAsB,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,GAAG,iBAAiB;CAW3F"} \ No newline at end of file diff --git a/lib/types/contract/HandlerBasedContract.d.ts b/lib/types/contract/HandlerBasedContract.d.ts new file mode 100644 index 00000000..56ea5a1b --- /dev/null +++ b/lib/types/contract/HandlerBasedContract.d.ts @@ -0,0 +1,90 @@ +import { SortKeyCacheResult } from '../cache/SortKeyCache'; +import { ContractCallRecord } from '../core/ContractCallRecord'; +import { InteractionResult } from '../core/modules/impl/HandlerExecutorFactory'; +import { EvalStateResult, EvaluationOptions } from '../core/modules/StateEvaluator'; +import { Warp } from '../core/Warp'; +import { GQLNodeInterface } from '../legacy/gqlResult'; +import { BenchmarkStats, Contract, DREContractStatusResponse, InnerCallData, WriteInteractionOptions, WriteInteractionResponse } from './Contract'; +import { ArTransfer, ArWallet, Tags } from './deploy/CreateContract'; +import { CustomSignature } from './Signature'; +import { EvaluationOptionsEvaluator } from './EvaluationOptionsEvaluator'; +import { Transaction } from '../utils/types/arweave-types'; +import { InteractionState } from './states/InteractionState'; +import { Signer } from 'warp-arbundles'; +/** + * An implementation of {@link Contract} that is backwards compatible with current style + * of writing SW contracts (ie. using the "handle" function). + * + * It requires {@link ExecutorFactory} that is using {@link HandlerApi} generic type. + */ +export declare class HandlerBasedContract implements Contract { + private readonly _contractTxId; + protected readonly warp: Warp; + private readonly _parentContract; + private readonly _innerCallData; + private readonly logger; + private readonly ecLogger; + private readonly _innerWritesEvaluator; + private readonly _callDepth; + private readonly _arweaveWrapper; + private readonly _mutex; + private _callStack; + private _evaluationOptions; + private _eoEvaluator; + private _benchmarkStats; + private _sorter; + private _rootSortKey; + private _signature; + private _warpFetchWrapper; + private _children; + private _interactionState; + private _dreStates; + constructor(_contractTxId: string, warp: Warp, _parentContract?: Contract, _innerCallData?: InnerCallData); + readState(sortKeyOrBlockHeight?: string | number, caller?: string, interactions?: GQLNodeInterface[]): Promise>>; + readStateFor(sortKey: string, interactions: GQLNodeInterface[]): Promise>>; + viewState(input: Input, tags?: Tags, transfer?: ArTransfer, caller?: string): Promise>; + viewStateForTx(input: Input, interactionTx: GQLNodeInterface): Promise>; + dryWrite(input: Input, caller?: string, tags?: Tags, transfer?: ArTransfer, vrf?: boolean): Promise>; + applyInput(input: Input, transaction: GQLNodeInterface): Promise>; + writeInteraction(input: Input, options?: WriteInteractionOptions): Promise; + private bundleInteraction; + private createInteractionDataItem; + createInteraction(input: Input, tags: Tags, transfer: ArTransfer, strict: boolean, bundle?: boolean, vrf?: boolean, reward?: string): Promise; + private checkInteractionInStrictMode; + txId(): string; + getCallStack(): ContractCallRecord; + connect(signature: ArWallet | CustomSignature | Signer): Contract; + setEvaluationOptions(options: Partial): Contract; + private waitForConfirmation; + private createExecutionContext; + private resolveEvaluationOptions; + private getRemoteContractState; + private fetchRemoteContractState; + private getToSortKey; + private createExecutionContextFromTx; + private maybeResetRootContract; + private callContract; + private doApplyInputOnTx; + private evalInteraction; + parent(): Contract | null; + callDepth(): number; + evaluationOptions(): EvaluationOptions; + lastReadStateStats(): BenchmarkStats; + stateHash(state: State): Promise; + syncState(externalUrl: string, params?: any): Promise; + evolve(newSrcTxId: string, options?: WriteInteractionOptions): Promise; + get rootSortKey(): string; + getRootEoEvaluator(): EvaluationOptionsEvaluator; + isRoot(): boolean; + getStorageValues(keys: string[]): Promise>>; + interactionState(): InteractionState; + getRoot(): HandlerBasedContract; + private maybeSyncStateWithRemoteSource; + private isStateHigherThanAndUpTo; + setDREState(contractTxId: string, result: DREContractStatusResponse): SortKeyCacheResult>; + getDreState(contractTxId: string): SortKeyCacheResult>; + hasDreState(contractTxId: string): boolean; + private discoverInternalWrites; + clearChildren(): void; +} +//# sourceMappingURL=HandlerBasedContract.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/HandlerBasedContract.d.ts.map b/lib/types/contract/HandlerBasedContract.d.ts.map new file mode 100644 index 00000000..e5ba7007 --- /dev/null +++ b/lib/types/contract/HandlerBasedContract.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"HandlerBasedContract.d.ts","sourceRoot":"","sources":["../../../src/contract/HandlerBasedContract.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAmB,MAAM,4BAA4B,CAAC;AAEjF,OAAO,EAKL,iBAAiB,EAElB,MAAM,6CAA6C,CAAC;AAGrD,OAAO,EAA4B,eAAe,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAE9G,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAMvD,OAAO,EACL,cAAc,EACd,QAAQ,EACR,yBAAyB,EACzB,aAAa,EACb,uBAAuB,EACvB,wBAAwB,EACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAiB,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAEpF,OAAO,EAAE,eAAe,EAAa,MAAM,aAAa,CAAC;A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,CAAC,CAAC;IAoBzF,gBAAgB,IAAI,gBAAgB;IAIpC,OAAO,IAAI,oBAAoB,CAAC,OAAO,CAAC;YAS1B,8BAA8B;IAiB5C,OAAO,CAAC,wBAAwB;IAYhC,WAAW,CACT,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,yBAAyB,CAAC,KAAK,CAAC,GACvC,kBAAkB,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAS7C,WAAW,CAAC,YAAY,EAAE,MAAM,GAAG,kBAAkB,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAI7E,WAAW,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO;YAU5B,sBAAsB;IAsCpC,aAAa,IAAI,IAAI;CAMtB"} \ No newline at end of file diff --git a/lib/types/contract/InnerWritesEvaluator.d.ts b/lib/types/contract/InnerWritesEvaluator.d.ts new file mode 100644 index 00000000..47d64444 --- /dev/null +++ b/lib/types/contract/InnerWritesEvaluator.d.ts @@ -0,0 +1,6 @@ +import { ContractCallRecord } from '../core/ContractCallRecord'; +export declare class InnerWritesEvaluator { + eval(callStack: ContractCallRecord): Array; + private evalForeignCalls; +} +//# sourceMappingURL=InnerWritesEvaluator.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/InnerWritesEvaluator.d.ts.map b/lib/types/contract/InnerWritesEvaluator.d.ts.map new file mode 100644 index 00000000..371dff5f --- /dev/null +++ b/lib/types/contract/InnerWritesEvaluator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InnerWritesEvaluator.d.ts","sourceRoot":"","sources":["../../../src/contract/InnerWritesEvaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAmB,MAAM,4BAA4B,CAAC;AAEjF,qBAAa,oBAAoB;IAC/B,IAAI,CAAC,SAAS,EAAE,kBAAkB,GAAG,KAAK,CAAC,MAAM,CAAC;IAUlD,OAAO,CAAC,gBAAgB;CAkBzB"} \ No newline at end of file diff --git a/lib/types/contract/PstContract.d.ts b/lib/types/contract/PstContract.d.ts new file mode 100644 index 00000000..6effd77c --- /dev/null +++ b/lib/types/contract/PstContract.d.ts @@ -0,0 +1,47 @@ +import { Contract, EvolveState, WriteInteractionOptions, WriteInteractionResponse } from './Contract'; +/** + * The result from the "balance" view method on the PST Contract. + */ +export interface BalanceResult { + target: string; + ticker: string; + balance: number; +} +/** + * Interface describing base state for all PST contracts. + */ +export interface PstState extends EvolveState { + ticker: string; + owner: string; + balances: { + [key: string]: number; + }; +} +/** + * Interface describing data required for making a transfer + */ +export interface TransferInput { + target: string; + qty: number; +} +/** + * A type of {@link Contract} designed specifically for the interaction with + * Profit Sharing Token contract. + */ +export interface PstContract extends Contract { + /** + * return the current balance for the given wallet + * @param target - wallet address + */ + currentBalance(target: string): Promise; + /** + * returns the current contract state + */ + currentState(): Promise; + /** + * allows to transfer PSTs between wallets + * @param transfer - data required to perform a transfer, see {@link transfer} + */ + transfer(transfer: TransferInput, options?: WriteInteractionOptions): Promise; +} +//# sourceMappingURL=PstContract.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/PstContract.d.ts.map b/lib/types/contract/PstContract.d.ts.map new file mode 100644 index 00000000..5f93df08 --- /dev/null +++ b/lib/types/contract/PstContract.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PstContract.d.ts","sourceRoot":"","sources":["../../../src/contract/PstContract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAEtG;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,QAAS,SAAQ,WAAW;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;KACvB,CAAC;CACH;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;GAGG;AACH,MAAM,WAAW,WAAY,SAAQ,QAAQ,CAAC,QAAQ,CAAC;IACrD;;;OAGG;IACH,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IAEvD;;OAEG;IACH,YAAY,IAAI,OAAO,CAAC,QAAQ,CAAC,CAAC;IAElC;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC,CAAC;CAChH"} \ No newline at end of file diff --git a/lib/types/contract/PstContractImpl.d.ts b/lib/types/contract/PstContractImpl.d.ts new file mode 100644 index 00000000..17ef573f --- /dev/null +++ b/lib/types/contract/PstContractImpl.d.ts @@ -0,0 +1,9 @@ +import { WriteInteractionOptions, WriteInteractionResponse } from './Contract'; +import { PstState, PstContract, BalanceResult, TransferInput } from './PstContract'; +import { HandlerBasedContract } from './HandlerBasedContract'; +export declare class PstContractImpl extends HandlerBasedContract implements PstContract { + currentBalance(target: string): Promise; + currentState(): Promise; + transfer(transfer: TransferInput, options?: WriteInteractionOptions): Promise; +} +//# sourceMappingURL=PstContractImpl.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/PstContractImpl.d.ts.map b/lib/types/contract/PstContractImpl.d.ts.map new file mode 100644 index 00000000..8d259d14 --- /dev/null +++ b/lib/types/contract/PstContractImpl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PstContractImpl.d.ts","sourceRoot":"","sources":["../../../src/contract/PstContractImpl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAO9D,qBAAa,eAAgB,SAAQ,oBAAoB,CAAC,QAAQ,CAAE,YAAW,WAAW;IAClF,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IAQtD,YAAY,IAAI,OAAO,CAAC,QAAQ,CAAC;IAIjC,QAAQ,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC;CAGrH"} \ No newline at end of file diff --git a/lib/types/contract/Signature.d.ts b/lib/types/contract/Signature.d.ts new file mode 100644 index 00000000..3e2c45b6 --- /dev/null +++ b/lib/types/contract/Signature.d.ts @@ -0,0 +1,38 @@ +import { Warp } from '../core/Warp'; +import { ArWallet } from './deploy/CreateContract'; +import { Transaction } from '../utils/types/arweave-types'; +import { Signer as BundlerSigner } from 'warp-arbundles'; +export type SignatureType = 'arweave' | 'ethereum'; +export type SigningFunction = (tx: Transaction) => Promise; +export type CustomSignature = { + signer: SigningFunction; + type: SignatureType; + getAddress?: () => Promise; +}; +/** +Different types which can be used to sign transaction or data item +- ArWallet - default option for signing Arweave transactions, either JWKInterface or 'use_wallet' +- CustomSignature - object with `signer` field - a custom signing function which takes transaction as a parameter and requires signing it + on the client side and `type` field of type SignatureType which indicates the wallet's chain, either 'arweave' or 'ethereum' +- Signer - arbundles specific class which allows to sign data items (works with data items - when bundling is enabled) +*/ +export type SignatureProvider = ArWallet | CustomSignature | BundlerSigner; +export declare class Signature { + signer: SigningFunction; + bundlerSigner: BundlerSigner; + readonly type: SignatureType; + readonly warp: Warp; + private readonly signatureProviderType; + private readonly wallet; + private cachedAddress?; + constructor(warp: Warp, walletOrSignature: SignatureProvider); + getAddress(): Promise; + private deduceSignerBySigning; + checkNonArweaveSigningAvailability(bundling: boolean): void; + checkBundlerSignerAvailability(bundling: boolean): void; + private assignArweaveSigner; + private assertEnvForCustomSigner; + private isCustomSignature; + private isValidBundlerSignature; +} +//# sourceMappingURL=Signature.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/Signature.d.ts.map b/lib/types/contract/Signature.d.ts.map new file mode 100644 index 00000000..7cbd17be --- /dev/null +++ b/lib/types/contract/Signature.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Signature.d.ts","sourceRoot":"","sources":["../../../src/contract/Signature.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAE3D,OAAO,EAAiB,MAAM,IAAI,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAExE,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,UAAU,CAAC;AACnD,MAAM,MAAM,eAAe,GAAG,CAAC,EAAE,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AACjE,MAAM,MAAM,eAAe,GAAG;IAC5B,MAAM,EAAE,eAAe,CAAC;IACxB,IAAI,EAAE,aAAa,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;CACpC,CAAC;AAEF;;;;;;EAME;AACF,MAAM,MAAM,iBAAiB,GAAG,QAAQ,GAAG,eAAe,GAAG,aAAa,CAAC;AAE3E,qBAAa,SAAS;IACpB,MAAM,EAAE,eAAe,CAAC;IACxB,aAAa,EAAE,aAAa,CAAC;IAC7B,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAC7B,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC;IACpB,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAmD;IACzF,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;IACxB,OAAO,CAAC,aAAa,CAAC,CAAS;gBAEnB,IAAI,EAAE,IAAI,EAAE,iBAAiB,EAAE,iBAAiB;IAsBtD,UAAU,IAAI,OAAO,CAAC,MAAM,CAAC;YA4BrB,qBAAqB;IAsBnC,kCAAkC,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI;IAM3D,8BAA8B,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI;IAQvD,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,wBAAwB;IAUhC,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,uBAAuB;CAehC"} \ No newline at end of file diff --git a/lib/types/contract/deploy/CreateContract.d.ts b/lib/types/contract/deploy/CreateContract.d.ts new file mode 100644 index 00000000..3ee56828 --- /dev/null +++ b/lib/types/contract/deploy/CreateContract.d.ts @@ -0,0 +1,88 @@ +/// +import { JWKInterface } from 'arweave/node/lib/wallet'; +import { WarpPluginType } from '../../core/WarpPlugin'; +import { EvaluationOptions } from '../../core/modules/StateEvaluator'; +import { Source } from './Source'; +import { Signer } from 'warp-arbundles'; +import { CustomSignature } from '../Signature'; +import { Tag } from '../../utils/types/arweave-types'; +export type Tags = Tag[]; +export type ArWallet = JWKInterface | 'use_wallet'; +export type ContractType = 'js' | 'wasm'; +export type ArTransfer = { + target: string; + winstonQty: string; +}; +export declare const emptyTransfer: ArTransfer; +export type EvaluationManifest = { + evaluationOptions?: Partial; + plugins?: WarpPluginType[]; +}; +export declare const REGISTER_PROVIDER: readonly ["node1", "node2", "arweave"]; +export type RegisterProviderType = (typeof REGISTER_PROVIDER)[number]; +export interface CommonContractData { + wallet: ArWallet | CustomSignature | Signer; + initState: string; + tags?: Tags; + transfer?: ArTransfer; + data?: { + 'Content-Type': string; + body: string | Buffer; + }; + evaluationManifest?: EvaluationManifest; +} +export interface ContractData extends CommonContractData { + src: string | Buffer; + wasmSrcCodeDir?: string; + wasmGlueCode?: string; +} +export interface FromSrcTxContractData extends CommonContractData { + srcTxId: string; +} +export interface ContractDeploy { + contractTxId: string; + srcTxId?: string; +} +export interface CreateContract extends Source { + /** + * Allows to deploy contract. By default bundling is enabled. In this case, contract source data item and contract data item are + * created and posted to Warp Gateway where they're uploaded to Bundlr and indexed in the gateway. In case of bundling being disabled + * (or in local environment) contract transaction and contract source transaction are created, signed and posted directly to Arweave. + * @param contractData - contract data {@link ContractData}, + * @param disableBundling - by default bundling is enabled and contract and contract source data item are being created, one can + * manually disable bundling, bundling is also disabled in local environment. + * + * Returns promise of type {@link ContractDeploy} + */ + deploy(contractData: ContractData, disableBundling?: boolean): Promise; + /** + * Allows to deploy contract from already existing source, contract source id is passed in a tag. By default bundling is enabled. + * In this case, contract data item is created and posted to Warp Gateway where it's uploaded to Bundlr and indexed in the gateway. + * In case of bundling being disabled(or in local environment) contract transaction is created, signed and posted directly to Arweave. + * @param contractData - contract data {@link FromSrcTxContractData}, + * @param disableBundling - by default bundling is enabled and contract data item is created, one can manually disable bundling, + * bundling is also disabled in local environment. + * + * Returns promise of type {@link ContractDeploy} + */ + deployFromSourceTx(contractData: FromSrcTxContractData, disableBundling?: boolean): Promise; + /** + * Takes raw contract data item as an argument and posts it to Warp Gateway where it is uploaded to Bundlr and indexed. Only AtomicNFTs + * data items (containing dedicated tags) are accepted. + * @param rawDataItem + * + * Returns promise of type {@link ContractDeploy} + */ + deployBundled(rawDataItem: Buffer): Promise; + /** + * Registers contract transaction in Warp Gateway. One needs to upload contract transaction using e.g. Irys, Turbo + * or arbundles and pass its id in the method along with {@link RegisterProviderType} - 'node1' and 'node2' for contracts + * deployed using Irys and 'arweave' for contracts deployed through other providers (contracts metadata is then queried + * from Arweave gql). + * Contract dedicated tags are verified in the gateway. + * @param id - id of the uploaded contract transaction + * @param registerProvider - {@link RegisterProviderType} + */ + register(id: string, registerProvider: RegisterProviderType): Promise; +} +//# sourceMappingURL=CreateContract.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/deploy/CreateContract.d.ts.map b/lib/types/contract/deploy/CreateContract.d.ts.map new file mode 100644 index 00000000..d46063c0 --- /dev/null +++ b/lib/types/contract/deploy/CreateContract.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"CreateContract.d.ts","sourceRoot":"","sources":["../../../../src/contract/deploy/CreateContract.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,GAAG,EAAE,MAAM,iCAAiC,CAAC;AAEtD,MAAM,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC;AAEzB,MAAM,MAAM,QAAQ,GAAG,YAAY,GAAG,YAAY,CAAC;AAEnD,MAAM,MAAM,YAAY,GAAG,IAAI,GAAG,MAAM,CAAC;AAEzC,MAAM,MAAM,UAAU,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,eAAO,MAAM,aAAa,EAAE,UAG3B,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,iBAAiB,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC/C,OAAO,CAAC,EAAE,cAAc,EAAE,CAAC;CAC5B,CAAC;AAEF,eAAO,MAAM,iBAAiB,wCAAyC,CAAC;AACxE,MAAM,MAAM,oBAAoB,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEtE,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,QAAQ,GAAG,eAAe,GAAG,MAAM,CAAC;IAC5C,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,QAAQ,CAAC,EAAE,UAAU,CAAC;IACtB,IAAI,CAAC,EAAE;QACL,cAAc,EAAE,MAAM,CAAC;QACvB,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;KACvB,CAAC;IACF,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;CACzC;AAED,MAAM,WAAW,YAAa,SAAQ,kBAAkB;IACtD,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,qBAAsB,SAAQ,kBAAkB;IAC/D,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,cAAe,SAAQ,MAAM;IAC5C;;;;;;;;;OASG;IACH,MAAM,CAAC,YAAY,EAAE,YAAY,EAAE,eAAe,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;IAEvF;;;;;;;;;OASG;IACH,kBAAkB,CAAC,YAAY,EAAE,qBAAqB,EAAE,eAAe,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;IAE5G;;;;;;OAMG;IACH,aAAa,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;IAE5D;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,EAAE,oBAAoB,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;CACvF"} \ No newline at end of file diff --git a/lib/types/contract/deploy/Source.d.ts b/lib/types/contract/deploy/Source.d.ts new file mode 100644 index 00000000..6b06d561 --- /dev/null +++ b/lib/types/contract/deploy/Source.d.ts @@ -0,0 +1,34 @@ +/// +import { ArWallet, Tags } from './CreateContract'; +import { CustomSignature } from '../../contract/Signature'; +import { Transaction } from '../../utils/types/arweave-types'; +import { Signer, DataItem } from 'warp-arbundles'; +export interface SourceData { + src: string | Buffer; + wasmSrcCodeDir?: string; + wasmGlueCode?: string; + tags?: Tags; +} +export interface Source { + /** + * Allows to create contract source - either creates a contract source transaction when `disableBundling` is set to `true` or in local + * environment or - creates a contracts source data item when bundling is enabled. It adds contract source specific tags and signs the + * transaction/data item. + * @param sourceData - contract source data {@link SourceData}, + * @param wallet - either Arweave wallet, custom signature or signer {@link SignatureProvider}, + * @param disableBundling - by default bundling is enabled and contract source data item is being created, one can manually disable bundling, + * bundling is also disabled in local environment. + * + * Returns promise of type {@link DataItem} or {@link Transaction} + */ + createSource(sourceData: SourceData, wallet: ArWallet | CustomSignature | Signer, disableBundling?: boolean): Promise; + /** + * Allows to save contract source. It takes contract source created and signed as a data item or transaction and posts it to Warp Gateway + * so it can be uploaded to Bundlr (when bundling is enabled) or posts it directly to Arweave. + * @param source - contract source data item or transaction + * @param disableBundling - by default bundling is enabled and contract source data item is being posted to Warp Gateway and uploaded to + * Bundlr, one can manually disable bundling, bundling is also disabled in local environment. + */ + saveSource(source: DataItem | Transaction, disableBundling?: boolean): Promise; +} +//# sourceMappingURL=Source.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/deploy/Source.d.ts.map b/lib/types/contract/deploy/Source.d.ts.map new file mode 100644 index 00000000..d7016fc0 --- /dev/null +++ b/lib/types/contract/deploy/Source.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Source.d.ts","sourceRoot":"","sources":["../../../../src/contract/deploy/Source.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAElD,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,IAAI,CAAC,EAAE,IAAI,CAAC;CACb;AAED,MAAM,WAAW,MAAM;IACrB;;;;;;;;;;OAUG;IACH,YAAY,CACV,UAAU,EAAE,UAAU,EACtB,MAAM,EAAE,QAAQ,GAAG,eAAe,GAAG,MAAM,EAC3C,eAAe,CAAC,EAAE,OAAO,GACxB,OAAO,CAAC,QAAQ,GAAG,WAAW,CAAC,CAAC;IAEnC;;;;;;OAMG;IACH,UAAU,CAAC,MAAM,EAAE,QAAQ,GAAG,WAAW,EAAE,eAAe,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CACxF"} \ No newline at end of file diff --git a/lib/types/contract/states/ContractInteractionState.d.ts b/lib/types/contract/states/ContractInteractionState.d.ts new file mode 100644 index 00000000..9ffd8369 --- /dev/null +++ b/lib/types/contract/states/ContractInteractionState.d.ts @@ -0,0 +1,32 @@ +import { InteractionState } from './InteractionState'; +import { CacheKey, SortKeyCacheResult } from '../../cache/SortKeyCache'; +import { EvalStateResult } from '../../core/modules/StateEvaluator'; +import { GQLNodeInterface } from '../../legacy/gqlResult'; +import { Warp } from '../../core/Warp'; +import { SortKeyCacheRangeOptions } from '../../cache/SortKeyCacheRangeOptions'; +export declare class ContractInteractionState implements InteractionState { + private readonly _warp; + private readonly _json; + private readonly _initialJson; + private readonly _kv; + constructor(_warp: Warp); + has(contractTx: any, sortKey: string): boolean; + get(contractTxId: string, sortKey: string): EvalStateResult; + getLessOrEqual(contractTxId: string, sortKey?: string): SortKeyCacheResult> | null; + getKV(contractTxId: string, cacheKey: CacheKey): Promise; + delKV(contractTxId: string, cacheKey: CacheKey): Promise; + getKvKeys(contractTxId: string, sortKey?: string, options?: SortKeyCacheRangeOptions): Promise; + getKvRange(contractTxId: string, sortKey?: string, options?: SortKeyCacheRangeOptions): Promise>; + commit(interaction: GQLNodeInterface, forceStore?: boolean): Promise; + commitKV(): Promise; + rollback(interaction: GQLNodeInterface, forceStateStoreToCache: boolean): Promise; + setInitial(contractTxId: string, state: EvalStateResult, sortKey: string): void; + update(contractTxId: string, state: EvalStateResult, sortKey: string): void; + updateKV(contractTxId: string, key: CacheKey, value: unknown): Promise; + private getOrInitKvStorage; + private reset; + private doStoreJson; + private rollbackKVs; + private commitKVs; +} +//# sourceMappingURL=ContractInteractionState.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/states/ContractInteractionState.d.ts.map b/lib/types/contract/states/ContractInteractionState.d.ts.map new file mode 100644 index 00000000..ee02bd4d --- /dev/null +++ b/lib/types/contract/states/ContractInteractionState.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ContractInteractionState.d.ts","sourceRoot":"","sources":["../../../../src/contract/states/ContractInteractionState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAgB,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACtF,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,wBAAwB,EAAE,MAAM,sCAAsC,CAAC;AAGhF,qBAAa,wBAAyB,YAAW,gBAAgB;IAKnD,OAAO,CAAC,QAAQ,CAAC,KAAK;IAJlC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAuE;IAC7F,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA+C;IAC5E,OAAO,CAAC,QAAQ,CAAC,GAAG,CAA4C;gBAEnC,KAAK,EAAE,IAAI;IAExC,GAAG,CAAC,UAAU,KAAA,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO;IAIzC,GAAG,CAAC,YAAY,EAAE,MAAM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,CAAC,IAAI,CAAC;YAIpE,kBAAkB;IAUhC,OAAO,CAAC,KAAK;YAMC,WAAW;YAYX,WAAW;YAUX,SAAS;CASxB"} \ No newline at end of file diff --git a/lib/types/contract/states/InteractionState.d.ts b/lib/types/contract/states/InteractionState.d.ts new file mode 100644 index 00000000..4c472cb1 --- /dev/null +++ b/lib/types/contract/states/InteractionState.d.ts @@ -0,0 +1,43 @@ +import { CacheKey, SortKeyCacheResult } from '../../cache/SortKeyCache'; +import { EvalStateResult } from '../../core/modules/StateEvaluator'; +import { GQLNodeInterface } from '../../legacy/gqlResult'; +import { SortKeyCacheRangeOptions } from '../../cache/SortKeyCacheRangeOptions'; +export interface InteractionState { + /** + * Sets the state for a given contract as it is at the beginning of the interaction evaluation. + * If the interaction evaluation of the root contract will fail (i.e. its result type is != 'ok') + * - this initial state will be committed to the cache for this interaction. + * In other words - all changes made during evaluation of this interaction will be rollbacked. + */ + setInitial(contractTxId: string, state: EvalStateResult, sortKey: string): void; + /** + * Updates the json-state for a given contract during interaction evaluation - e.g. as a result of an internal write + */ + update(contractTxId: string, state: EvalStateResult, sortKey: string): void; + /** + * Updates the kv-state for a given contract during interaction evaluation + */ + updateKV(contractTxId: string, key: CacheKey, value: unknown): Promise; + /** + * commits all the state changes made for all contracts within given interaction evaluation. + * Called by the {@link DefaultStateEvaluator} at the end every root's contract interaction evaluation + * - IFF the result.type == 'ok'. + */ + commit(interaction: GQLNodeInterface, forceStore?: boolean): Promise; + commitKV(): Promise; + /** + * rollbacks all the state changes made for all contracts within given interaction evaluation. + * Called by the {@link DefaultStateEvaluator} at the end every root's contract interaction evaluation + * - IFF the result.type != 'ok'. + * This ensures atomicity of state changes withing any given interaction - also in case of internal contract calls. + */ + rollback(interaction: GQLNodeInterface, forceStateStoreToCache: boolean): Promise; + has(contractTxId: string, sortKey: string): boolean; + get(contractTxId: string, sortKey: string): EvalStateResult | null; + getLessOrEqual(contractTxId: string, sortKey?: string): SortKeyCacheResult> | null; + getKV(contractTxId: string, cacheKey: CacheKey): Promise; + delKV(contractTxId: string, cacheKey: CacheKey): Promise; + getKvKeys(contractTxId: string, sortKey?: string, options?: SortKeyCacheRangeOptions): Promise; + getKvRange(contractTxId: string, sortKey?: string, options?: SortKeyCacheRangeOptions): Promise>; +} +//# sourceMappingURL=InteractionState.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/states/InteractionState.d.ts.map b/lib/types/contract/states/InteractionState.d.ts.map new file mode 100644 index 00000000..1f83129a --- /dev/null +++ b/lib/types/contract/states/InteractionState.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InteractionState.d.ts","sourceRoot":"","sources":["../../../../src/contract/states/InteractionState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,sCAAsC,CAAC;AAGhF,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAEzF;;OAEG;IACH,MAAM,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAErF;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE7E;;;;OAIG;IACH,MAAM,CAAC,WAAW,EAAE,gBAAgB,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE3E,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1B;;;;;OAKG;IACH,QAAQ,CAAC,WAAW,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAExF,GAAG,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;IAEpD,GAAG,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IAE5E,cAAc,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,kBAAkB,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;IAE5G,KAAK,CAAC,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAElE,KAAK,CAAC,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE/D,SAAS,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAEzG,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACvH"} \ No newline at end of file diff --git a/lib/types/contract/testing/Testing.d.ts b/lib/types/contract/testing/Testing.d.ts new file mode 100644 index 00000000..83e246b1 --- /dev/null +++ b/lib/types/contract/testing/Testing.d.ts @@ -0,0 +1,15 @@ +import Arweave from 'arweave'; +import { JWKInterface } from '../../utils/types/arweave-types'; +export type Wallet = { + jwk: JWKInterface; + address: string; +}; +export declare class Testing { + private readonly arweave; + constructor(arweave: Arweave); + mineBlock(): Promise; + addFunds(wallet: JWKInterface): Promise; + isArlocal(): Promise; + private validateEnv; +} +//# sourceMappingURL=Testing.d.ts.map \ No newline at end of file diff --git a/lib/types/contract/testing/Testing.d.ts.map b/lib/types/contract/testing/Testing.d.ts.map new file mode 100644 index 00000000..bb75870c --- /dev/null +++ b/lib/types/contract/testing/Testing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Testing.d.ts","sourceRoot":"","sources":["../../../../src/contract/testing/Testing.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAE/D,MAAM,MAAM,MAAM,GAAG;IACnB,GAAG,EAAE,YAAY,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,qBAAa,OAAO;IACN,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,OAAO;IAEvC,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAK1B,QAAQ,CAAC,MAAM,EAAE,YAAY;IAK7B,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC;YAcrB,WAAW;CAK1B"} \ No newline at end of file diff --git a/lib/types/core/ContractCallRecord.d.ts b/lib/types/core/ContractCallRecord.d.ts new file mode 100644 index 00000000..f06f8959 --- /dev/null +++ b/lib/types/core/ContractCallRecord.d.ts @@ -0,0 +1,48 @@ +import { InteractionData } from './modules/impl/HandlerExecutorFactory'; +import { InnerCallType } from '../contract/Contract'; +export declare class ContractCallRecord { + readonly contractTxId: string; + readonly depth: number; + readonly innerCallType: InnerCallType; + readonly interactions: { + [key: string]: InteractionCall; + }; + readonly id: string; + constructor(contractTxId: string, depth: number, innerCallType?: InnerCallType); + addInteractionData(interactionData: InteractionData): InteractionCall; + getInteraction(txId: string): InteractionCall; + print(): string; +} +export declare class InteractionCall { + readonly interactionInput: InteractionInput; + interactionOutput: InteractionOutput; + private constructor(); + static create(interactionInput: InteractionInput): InteractionCall; + update(interactionOutput: InteractionOutput): void; +} +export declare class InteractionInput { + readonly txId: string; + readonly sortKey: string; + readonly blockHeight: number; + readonly blockTimestamp: number; + readonly caller: string; + readonly functionName: string; + readonly functionArguments: []; + readonly dryWrite: boolean; + readonly foreignContractCalls: { + [key: string]: ContractCallRecord; + }; + constructor(txId: string, sortKey: string, blockHeight: number, blockTimestamp: number, caller: string, functionName: string, functionArguments: [], dryWrite: boolean, foreignContractCalls?: { + [key: string]: ContractCallRecord; + }); +} +export declare class InteractionOutput { + readonly cacheHit: boolean; + readonly outputState: any; + readonly executionTime: number; + readonly valid: boolean; + readonly errorMessage: string; + readonly gasUsed: number; + constructor(cacheHit: boolean, outputState: any, executionTime: number, valid: boolean, errorMessage: string, gasUsed: number); +} +//# sourceMappingURL=ContractCallRecord.d.ts.map \ No newline at end of file diff --git a/lib/types/core/ContractCallRecord.d.ts.map b/lib/types/core/ContractCallRecord.d.ts.map new file mode 100644 index 00000000..d2d814e1 --- /dev/null +++ b/lib/types/core/ContractCallRecord.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ContractCallRecord.d.ts","sourceRoot":"","sources":["../../../src/core/ContractCallRecord.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGrD,qBAAa,kBAAkB;IAIjB,QAAQ,CAAC,YAAY,EAAE,MAAM;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM;IAAE,QAAQ,CAAC,aAAa,EAAE,aAAa;IAHxG,QAAQ,CAAC,YAAY,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,eAAe,CAAA;KAAE,CAAM;IAC/D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;gBAEC,YAAY,EAAE,MAAM,EAAW,KAAK,EAAE,MAAM,EAAW,aAAa,GAAE,aAAoB;IA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AAE,MAAW,EACzB,OAAO,EAAE,MAAM;CAElC"} \ No newline at end of file diff --git a/lib/types/core/ContractDefinition.d.ts b/lib/types/core/ContractDefinition.d.ts new file mode 100644 index 00000000..56a77368 --- /dev/null +++ b/lib/types/core/ContractDefinition.d.ts @@ -0,0 +1,39 @@ +/** + * This type contains all data and meta-data of the given contact. + */ +/// +import { ContractType, EvaluationManifest } from '../contract/deploy/CreateContract'; +export declare const SUPPORTED_SRC_CONTENT_TYPES: string[]; +export declare class ContractMetadata { + dtor: number; +} +export type ContractSource = { + src: string | null; + srcBinary: Buffer | null; + srcWasmLang: string | null; + contractType: ContractType; + srcTx: any; + metadata?: ContractMetadata; +}; +export declare class SrcCache { + src: string | null; + srcBinary: Buffer | null; + srcWasmLang: string | null; + constructor(value: ContractDefinition); +} +export declare class ContractCache { + txId: string; + srcTxId: string; + initState: State; + minFee: string; + owner: string; + contractType: ContractType; + metadata?: ContractMetadata; + manifest?: EvaluationManifest; + contractTx: any; + srcTx: any; + testnet: string | null; + constructor(value: ContractDefinition); +} +export type ContractDefinition = SrcCache & ContractCache; +//# sourceMappingURL=ContractDefinition.d.ts.map \ No newline at end of file diff --git a/lib/types/core/ContractDefinition.d.ts.map b/lib/types/core/ContractDefinition.d.ts.map new file mode 100644 index 00000000..716d38a3 --- /dev/null +++ b/lib/types/core/ContractDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ContractDefinition.d.ts","sourceRoot":"","sources":["../../../src/core/ContractDefinition.ts"],"names":[],"mappings":"AAAA;;GAEG;;AAEH,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AAErF,eAAO,MAAM,2BAA2B,UAAiD,CAAC;AAE1F,qBAAa,gBAAgB;IAC3B,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,MAAM,cAAc,GAAG;IAC3B,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,YAAY,EAAE,YAAY,CAAC;IAC3B,KAAK,EAAE,GAAG,CAAC;IACX,QAAQ,CAAC,EAAE,gBAAgB,CAAC;CAC7B,CAAC;AAEF,qBAAa,QAAQ;IACnB,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;gBAEf,KAAK,EAAE,kBAAkB,CAAC,OAAO,CAAC;CAK/C;AAED,qBAAa,aAAa,CAAC,KAAK;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,KAAK,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,YAAY,CAAC;IAC3B,QAAQ,CAAC,EAAE,gBAAgB,CAAC;IAC5B,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAC9B,UAAU,EAAE,GAAG,CAAC;IAChB,KAAK,EAAE,GAAG,CAAC;IACX,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;gBAEX,KAAK,EAAE,kBAAkB,CAAC,KAAK,CAAC;CAa7C;AAED,MAAM,MAAM,kBAAkB,CAAC,KAAK,IAAI,QAAQ,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC"} \ No newline at end of file diff --git a/lib/types/core/ExecutionContext.d.ts b/lib/types/core/ExecutionContext.d.ts new file mode 100644 index 00000000..4f39f443 --- /dev/null +++ b/lib/types/core/ExecutionContext.d.ts @@ -0,0 +1,46 @@ +import { SortKeyCacheResult } from '../cache/SortKeyCache'; +import { Contract } from '../contract/Contract'; +import { GQLNodeInterface } from '../legacy/gqlResult'; +import { ContractDefinition } from './ContractDefinition'; +import { EvaluationOptions, EvalStateResult } from './modules/StateEvaluator'; +import { Warp } from './Warp'; +/** + * current execution context of the contract - contains all elements + * that are required to call contract's code. + * This has been created to prevent some operations from loading certain data (eg. + * contract's definition - which is very time consuming) multiple times + * (eg. multiple calls to "loadContract" in "interactRead" in the current version of the Arweave's smartweave.js). + */ +export type ExecutionContext = { + /** + * {@link Warp} client currently being used + */ + warp: Warp; + /** + * {@link Contract} related to this execution context + */ + contract: Contract; + /** + * The full {@link ContractDefinition} of the {@link Contract} + */ + contractDefinition: ContractDefinition; + /** + * interaction sorted using either {@link LexicographicalInteractionsSorter} + * - crucial for proper and deterministic state evaluation + */ + sortedInteractions: GQLNodeInterface[]; + /** + * evaluation options currently being used + * TODO: this can be removed, as it should be accessible from the {@link Contract} + */ + evaluationOptions: EvaluationOptions; + /** + * A handle to the contract's "handle" function - ie. main function of the given SWC - that actually + * performs all the computation. + */ + handler?: Api; + caller?: string; + cachedState?: SortKeyCacheResult>; + requestedSortKey?: string; +}; +//# sourceMappingURL=ExecutionContext.d.ts.map \ No newline at end of file diff --git a/lib/types/core/ExecutionContext.d.ts.map b/lib/types/core/ExecutionContext.d.ts.map new file mode 100644 index 00000000..2d6623aa --- /dev/null +++ b/lib/types/core/ExecutionContext.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ExecutionContext.d.ts","sourceRoot":"","sources":["../../../src/core/ExecutionContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAE9B;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,CAAC,KAAK,EAAE,GAAG,GAAG,OAAO,IAAI;IACnD;;OAEG;IACH,IAAI,EAAE,IAAI,CAAC;IACX;;OAEG;IACH,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC1B;;OAEG;IACH,kBAAkB,EAAE,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC9C;;;OAGG;IACH,kBAAkB,EAAE,gBAAgB,EAAE,CAAC;IACvC;;;OAGG;IACH,iBAAiB,EAAE,iBAAiB,CAAC;IACrC;;;OAGG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,kBAAkB,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;IACzD,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,CAAC"} \ No newline at end of file diff --git a/lib/types/core/ExecutionContextModifier.d.ts b/lib/types/core/ExecutionContextModifier.d.ts new file mode 100644 index 00000000..aa7b58f9 --- /dev/null +++ b/lib/types/core/ExecutionContextModifier.d.ts @@ -0,0 +1,10 @@ +import { ExecutionContext } from './ExecutionContext'; +import { HandlerApi } from './modules/impl/HandlerExecutorFactory'; +/** + * This adds ability to modify current execution context based + * on state - example (and currently only) use case is the "evolve" feature. + */ +export interface ExecutionContextModifier { + modify(state: State, executionContext: ExecutionContext>): Promise>>; +} +//# sourceMappingURL=ExecutionContextModifier.d.ts.map \ No newline at end of file diff --git a/lib/types/core/ExecutionContextModifier.d.ts.map b/lib/types/core/ExecutionContextModifier.d.ts.map new file mode 100644 index 00000000..d275852b --- /dev/null +++ b/lib/types/core/ExecutionContextModifier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ExecutionContextModifier.d.ts","sourceRoot":"","sources":["../../../src/core/ExecutionContextModifier.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,uCAAuC,CAAC;AAEnE;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC,MAAM,CAAC,KAAK,EACV,KAAK,EAAE,KAAK,EACZ,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC,GAC3D,OAAO,CAAC,gBAAgB,CAAC,KAAK,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;CACxD"} \ No newline at end of file diff --git a/lib/types/core/KnownTags.d.ts b/lib/types/core/KnownTags.d.ts new file mode 100644 index 00000000..b778e024 --- /dev/null +++ b/lib/types/core/KnownTags.d.ts @@ -0,0 +1,45 @@ +type ObjectValues = T[keyof T]; +/** + * Definition of all transaction tags used by the SmartWeave "protocol" + */ +export declare const SMART_WEAVE_TAGS: { + readonly APP_NAME: "App-Name"; + readonly APP_VERSION: "App-Version"; + readonly CONTRACT_TX_ID: "Contract"; + readonly INPUT: "Input"; + readonly CONTENT_TYPE: "Content-Type"; + readonly CONTRACT_SRC_TX_ID: "Contract-Src"; + readonly SDK: "SDK"; + readonly MIN_FEE: "Min-Fee"; +}; +export type SmartWeaveTags = ObjectValues; +/** + * Definition of all transaction tags specific to Warp platform + */ +export declare const WARP_TAGS: { + readonly SEQUENCER: "Sequencer"; + readonly SEQUENCER_OWNER: "Sequencer-Owner"; + readonly SEQUENCER_MILLIS: "Sequencer-Mills"; + readonly SEQUENCER_SORT_KEY: "Sequencer-Sort-Key"; + readonly SEQUENCER_PREV_SORT_KEY: "Sequencer-Prev-Sort-Key"; + readonly SEQUENCER_LAST_SORT_KEY: "Sequencer-Last-Sort-Key"; + readonly SEQUENCER_TX_ID: "Sequencer-Tx-Id"; + readonly SEQUENCER_BLOCK_HEIGHT: "Sequencer-Block-Height"; + readonly SEQUENCER_BLOCK_ID: "Sequencer-Block-Id"; + readonly SEQUENCER_BLOCK_TIMESTAMP: "Sequencer-Block-Timestamp"; + readonly INIT_STATE: "Init-State"; + readonly INIT_STATE_TX: "Init-State-TX"; + readonly INTERACT_WRITE: "Interact-Write"; + readonly WASM_LANG: "Wasm-Lang"; + readonly WASM_LANG_VERSION: "Wasm-Lang-Version"; + readonly WASM_META: "Wasm-Meta"; + readonly REQUEST_VRF: "Request-Vrf"; + readonly SIGNATURE_TYPE: "Signature-Type"; + readonly UPLOADER_TX_ID: "Uploader-Tx-Id"; + readonly WARP_TESTNET: "Warp-Testnet"; + readonly MANIFEST: "Contract-Manifest"; + readonly NONCE: "Nonce"; +}; +export type WarpTags = ObjectValues; +export {}; +//# sourceMappingURL=KnownTags.d.ts.map \ No newline at end of file diff --git a/lib/types/core/KnownTags.d.ts.map b/lib/types/core/KnownTags.d.ts.map new file mode 100644 index 00000000..2886d71c --- /dev/null +++ b/lib/types/core/KnownTags.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"KnownTags.d.ts","sourceRoot":"","sources":["../../../src/core/KnownTags.ts"],"names":[],"mappings":"AAAA,KAAK,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AAClC;;GAEG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;CASnB,CAAC;AACX,MAAM,MAAM,cAAc,GAAG,YAAY,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEnE;;GAEG;AACH,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;CAuBZ,CAAC;AAEX,MAAM,MAAM,QAAQ,GAAG,YAAY,CAAC,OAAO,SAAS,CAAC,CAAC"} \ No newline at end of file diff --git a/lib/types/core/Warp.d.ts b/lib/types/core/Warp.d.ts new file mode 100644 index 00000000..70a23c6e --- /dev/null +++ b/lib/types/core/Warp.d.ts @@ -0,0 +1,82 @@ +/// +import Arweave from 'arweave'; +import { Contract, InnerCallData } from '../contract/Contract'; +import { ArWallet, RegisterProviderType, ContractData, ContractDeploy, FromSrcTxContractData } from '../contract/deploy/CreateContract'; +import { PstContract } from '../contract/PstContract'; +import { Testing, Wallet } from '../contract/testing/Testing'; +import { DefinitionLoader } from './modules/DefinitionLoader'; +import { ExecutorFactory } from './modules/ExecutorFactory'; +import { HandlerApi } from './modules/impl/HandlerExecutorFactory'; +import { InteractionsLoader } from './modules/InteractionsLoader'; +import { EvalStateResult, StateEvaluator } from './modules/StateEvaluator'; +import { WarpBuilder } from './WarpBuilder'; +import { WarpPluginType, WarpPlugin } from './WarpPlugin'; +import { SortKeyCache } from '../cache/SortKeyCache'; +import { ContractDefinition, SrcCache } from './ContractDefinition'; +import { CustomSignature } from '../contract/Signature'; +import { Transaction } from '../utils/types/arweave-types'; +import { SourceData } from '../contract/deploy/Source'; +import { Signer, DataItem } from 'warp-arbundles'; +import { BasicSortKeyCache } from '../cache/BasicSortKeyCache'; +export type WarpEnvironment = 'local' | 'testnet' | 'mainnet' | 'custom'; +export type KVStorageFactory = (contractTxId: string) => SortKeyCache; +/** + * The Warp "motherboard" ;-). + * This is the base class that supplies the implementation of the SmartWeave protocol + * Allows to plug-in different implementation of all the modules defined in the constructor. + * + * After being fully configured, it allows to "connect" to + * contract and perform operations on them (see {@link Contract}) + */ +export declare class Warp { + readonly arweave: Arweave; + readonly definitionLoader: DefinitionLoader; + readonly interactionsLoader: InteractionsLoader; + readonly executorFactory: ExecutorFactory>; + readonly stateEvaluator: StateEvaluator; + readonly environment: WarpEnvironment; + private _createContract; + private _gwUrl; + private get createContract(); + readonly testing: Testing; + kvStorageFactory: KVStorageFactory; + whoAmI: string; + eventTarget: EventTarget; + private readonly plugins; + constructor(arweave: Arweave, definitionLoader: DefinitionLoader, interactionsLoader: InteractionsLoader, executorFactory: ExecutorFactory>, stateEvaluator: StateEvaluator, environment?: WarpEnvironment); + static builder(arweave: Arweave, stateCache: BasicSortKeyCache>, environment: WarpEnvironment): WarpBuilder; + /** + * Allows to connect to any contract using its transaction id. + * @param contractTxId + * @param callingContract + */ + contract(contractTxId: string, callingContract?: Contract, innerCallData?: InnerCallData): Contract; + deploy(contractData: ContractData, disableBundling?: boolean): Promise; + deployFromSourceTx(contractData: FromSrcTxContractData, disableBundling?: boolean): Promise; + deployBundled(rawDataItem: Buffer): Promise; + register(id: string, registerProvider: RegisterProviderType): Promise; + createSource(sourceData: SourceData, wallet: ArWallet | CustomSignature | Signer, disableBundling?: boolean): Promise; + saveSource(src: Transaction | DataItem, disableBundling?: boolean): Promise; + /** + * Allows to connect to a contract that conforms to the Profit Sharing Token standard + * @param contractTxId + */ + pst(contractTxId: string): PstContract; + useStateCache(stateCache: BasicSortKeyCache>): Warp; + useContractCache(definition: BasicSortKeyCache>, src: SortKeyCache): Warp; + use(plugin: WarpPlugin): Warp; + hasPlugin(type: WarpPluginType): boolean; + matchPlugins(type: string): WarpPluginType[]; + loadPlugin(type: WarpPluginType): WarpPlugin; + maybeLoadPlugin(type: WarpPluginType): WarpPlugin | null; + close(): Promise; + generateWallet(): Promise; + private isPluginType; + useKVStorageFactory(factory: KVStorageFactory): Warp; + useGwUrl(url: string): Warp; + gwUrl(): string; +} +export interface WarpAware { + set warp(warp: Warp); +} +//# sourceMappingURL=Warp.d.ts.map \ No newline at end of file diff --git a/lib/types/core/Warp.d.ts.map b/lib/types/core/Warp.d.ts.map new file mode 100644 index 00000000..36581377 --- /dev/null +++ b/lib/types/core/Warp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Warp.d.ts","sourceRoot":"","sources":["../../../src/core/Warp.ts"],"names":[],"mappings":";AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EACL,QAAQ,EACR,oBAAoB,EACpB,YAAY,EACZ,cAAc,EAEd,qBAAqB,EACtB,MAAM,mCAAmC,CAAC;AAE3C,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAEtD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5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,0 +1,30 @@ +import Arweave from 'arweave'; +import { DefinitionLoader } from './modules/DefinitionLoader'; +import { ExecutorFactory } from './modules/ExecutorFactory'; +import { HandlerApi } from './modules/impl/HandlerExecutorFactory'; +import { InteractionsLoader } from './modules/InteractionsLoader'; +import { StateEvaluator, EvalStateResult } from './modules/StateEvaluator'; +import { WarpEnvironment, Warp } from './Warp'; +import { CacheOptions, GatewayOptions } from './WarpFactory'; +import { BasicSortKeyCache } from '../cache/BasicSortKeyCache'; +export declare class WarpBuilder { + private readonly _arweave; + private readonly _stateCache; + private readonly _environment; + private _definitionLoader?; + private _interactionsLoader?; + private _executorFactory?; + private _stateEvaluator?; + constructor(_arweave: Arweave, _stateCache: BasicSortKeyCache>, _environment?: WarpEnvironment); + setDefinitionLoader(value: DefinitionLoader): WarpBuilder; + setInteractionsLoader(value: InteractionsLoader): WarpBuilder; + setExecutorFactory(value: ExecutorFactory>): WarpBuilder; + setStateEvaluator(value: StateEvaluator): WarpBuilder; + overwriteSource(sourceCode: { + [key: string]: string; + }): Warp; + useWarpGateway(gatewayOptions: GatewayOptions, cacheOptions: CacheOptions): WarpBuilder; + useArweaveGateway(): WarpBuilder; + build(): Warp; +} +//# sourceMappingURL=WarpBuilder.d.ts.map \ No newline at end of file diff --git a/lib/types/core/WarpBuilder.d.ts.map b/lib/types/core/WarpBuilder.d.ts.map new file mode 100644 index 00000000..037c0b81 --- /dev/null +++ b/lib/types/core/WarpBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpBuilder.d.ts","sourceRoot":"","sources":["../../../src/core/WarpBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAI5D,OAAO,EAAE,UAAU,EAAE,MAAM,uCAAuC,CAAC;AAGnE,OAAO,EAAE,kBAAkB,EAAE,MAA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e2c --- /dev/null +++ b/lib/types/core/WarpFactory.d.ts @@ -0,0 +1,65 @@ +import Arweave from 'arweave'; +import { ConfirmationStatus, SourceType } from './modules/impl/WarpGatewayInteractionsLoader'; +import { WarpEnvironment, Warp } from './Warp'; +import { WarpBuilder } from './WarpBuilder'; +export type GatewayOptions = { + confirmationStatus: ConfirmationStatus; + source: SourceType; +}; +export type CacheOptions = { + inMemory: boolean; + dbLocation: string; + subLevelSeparator?: string | undefined; +}; +export declare const defaultWarpGwOptions: GatewayOptions; +/** + * @Deprecated - will be removed soon, left for backwards compatibility with deploy plugin + */ +export declare const WARP_GW_URL = "https://gw.warp.cc"; +export declare const DEFAULT_LEVEL_DB_LOCATION = "./cache/warp"; +export declare const defaultCacheOptions: CacheOptions; +/** + * A factory that simplifies the process of creating different versions of {@link Warp}. + * All versions use the {@link Evolve} plugin. + */ +export declare class WarpFactory { + /** + * creates a Warp instance suitable for testing in a local environment + * (e.g. usually using ArLocal) + * @param arweave - an instance of Arweave + * @param cacheOptions - optional cache options. By default, the in-memory cache is used. + */ + static forLocal(port?: number, arweave?: Arweave, cacheOptions?: { + inMemory: boolean; + dbLocation: string; + subLevelSeparator?: string; + }): Warp; + /** + * creates a Warp instance suitable for testing + * with Warp testnet (https://testnet.redstone.tools/) + */ + static forTestnet(cacheOptions?: CacheOptions, useArweaveGw?: boolean, arweave?: Arweave): Warp; + /** + * creates a Warp instance suitable for use with mainnet. + * By default, the Warp gateway (https://github.com/warp-contracts/gateway#warp-gateway) + * is being used for: + * 1. deploying contracts + * 2. writing new transactions through Warp Sequencer + * 3. loading contract interactions + * + * @param cacheOptions - cache options, defaults {@link defaultCacheOptions} + * @param useArweaveGw - use arweave.net gateway for deploying contracts, + * writing and loading interactions + * @param arweave - custom Arweave instance + */ + static forMainnet(cacheOptions?: CacheOptions, useArweaveGw?: boolean, arweave?: Arweave): Warp; + /** + * returns an instance of {@link WarpBuilder} that allows to fully customize the Warp instance. + * @param arweave + * @param cacheOptions + */ + static custom(arweave: Arweave, cacheOptions: CacheOptions, environment: WarpEnvironment): WarpBuilder; + private static customArweaveGw; + private static customWarpGw; +} +//# sourceMappingURL=WarpFactory.d.ts.map \ No newline at end of file diff --git a/lib/types/core/WarpFactory.d.ts.map b/lib/types/core/WarpFactory.d.ts.map new file mode 100644 index 00000000..d8324579 --- /dev/null +++ b/lib/types/core/WarpFactory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpFactory.d.ts","sourceRoot":"","sources":["../../../src/core/WarpFactory.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAK9B,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,8CAA8C,CAAC;AAE9F,OAAO,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,MAAM,MAAM,cAAc,GAAG;IAC3B,kBAAkB,EAAE,kBAAkB,CAAC;IACvC,MAAM,EAAE,UAAU,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACxC,CAAC;AAEF,eAAO,MAAM,oBAAoB,EAAE,cAGlC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,uBAAuB,CAAC;AAEhD,eAAO,MAAM,yBAAyB,iBAAiB,CAAC;AAExD,eAAO,MAAM,mBAAmB,EAAE,YAGjC,CAAC;AAEF;;;GAGG;AACH,qBAAa,WAAW;IACtB;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CACb,IAAI,SAAO,EACX,OAAO,UAIL,EACF,YAAY;;;;KAGX,GACA,IAAI;IAIP;;;OAGG;IACH,MAAM,CAAC,UAAU,CACf,YAAY,eAAsB,EAClC,YAAY,UAAQ,EACpB,OAAO,UAIL,GACD,IAAI;IAQP;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,UAAU,CACf,YAAY,eAAsB,EAClC,YAAY,UAAQ,EACpB,OAAO,UAIL,GACD,IAAI;IAOP;;;;OAIG;IACH,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,eAAe,GAAG,WAAW;IActG,OAAO,CAAC,MAAM,CAAC,eAAe;IAQ9B,OAAO,CAAC,MAAM,CAAC,YAAY;CAQ5B"} \ No newline at end of file diff --git a/lib/types/core/WarpFetchWrapper.d.ts b/lib/types/core/WarpFetchWrapper.d.ts new file mode 100644 index 00000000..5da12cfd --- /dev/null +++ b/lib/types/core/WarpFetchWrapper.d.ts @@ -0,0 +1,13 @@ +import { Warp } from './Warp'; +export interface FetchRequest { + input: RequestInfo | URL; + init: Partial; +} +export declare class WarpFetchWrapper { + private warp; + private readonly name; + private readonly logger; + constructor(warp: Warp); + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; +} +//# sourceMappingURL=WarpFetchWrapper.d.ts.map \ No newline at end of file diff --git a/lib/types/core/WarpFetchWrapper.d.ts.map b/lib/types/core/WarpFetchWrapper.d.ts.map new file mode 100644 index 00000000..e7f9f8c3 --- /dev/null +++ b/lib/types/core/WarpFetchWrapper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpFetchWrapper.d.ts","sourceRoot":"","sources":["../../../src/core/WarpFetchWrapper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAE9B,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,WAAW,GAAG,GAAG,CAAC;IACzB,IAAI,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;CAC5B;AAED,qBAAa,gBAAgB;IAIf,OAAO,CAAC,IAAI;IAHxB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAsB;IAC3C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAwC;gBAE3C,IAAI,EAAE,IAAI;IAI9B,KAAK,CAAC,KAAK,EAAE,WAAW,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC;CAoBvE"} \ No newline at end of file diff --git a/lib/types/core/WarpPlugin.d.ts b/lib/types/core/WarpPlugin.d.ts new file mode 100644 index 00000000..7ae4c3b9 --- /dev/null +++ b/lib/types/core/WarpPlugin.d.ts @@ -0,0 +1,16 @@ +import { VrfData } from '../legacy/gqlResult'; +export declare const knownWarpPluginsPartial: readonly ["^smartweave-extension-"]; +export declare const knownWarpPlugins: readonly ["evm-signature-verification", "subscription", "ivm-handler-api", "evaluation-progress", "fetch-options", "deploy", "contract-blacklist", "vm2", "vrf"]; +type WarpPluginPartialType = `smartweave-extension-${string}`; +export type WarpKnownPluginType = (typeof knownWarpPlugins)[number]; +export type WarpPluginType = WarpKnownPluginType | WarpPluginPartialType; +export interface WarpPlugin { + type(): WarpPluginType; + process(input: T): R; +} +export type VrfPluginFunctions = { + generateMockVrf(sortKey: string): VrfData; + verify(vrf: VrfData, sortKey: string): boolean; +}; +export {}; +//# sourceMappingURL=WarpPlugin.d.ts.map \ No newline at end of file diff --git a/lib/types/core/WarpPlugin.d.ts.map b/lib/types/core/WarpPlugin.d.ts.map new file mode 100644 index 00000000..fefba0a7 --- /dev/null +++ b/lib/types/core/WarpPlugin.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpPlugin.d.ts","sourceRoot":"","sources":["../../../src/core/WarpPlugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAE9C,eAAO,MAAM,uBAAuB,qCAAsC,CAAC;AAC3E,eAAO,MAAM,gBAAgB,kKAUnB,CAAC;AACX,KAAK,qBAAqB,GAAG,wBAAwB,MAAM,EAAE,CAAC;AAC9D,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AACpE,MAAM,MAAM,cAAc,GAAG,mBAAmB,GAAG,qBAAqB,CAAC;AAEzE,MAAM,WAAW,UAAU,CAAC,CAAC,EAAE,CAAC;IAC9B,IAAI,IAAI,cAAc,CAAC;IAEvB,OAAO,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;CACtB;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;IAC1C,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;CAChD,CAAC"} \ No newline at end of file diff --git a/lib/types/core/modules/DefinitionLoader.d.ts b/lib/types/core/modules/DefinitionLoader.d.ts new file mode 100644 index 00000000..526c2545 --- /dev/null +++ b/lib/types/core/modules/DefinitionLoader.d.ts @@ -0,0 +1,18 @@ +import { ContractCache, ContractDefinition, ContractSource, SrcCache } from '../../core/ContractDefinition'; +import { GwTypeAware } from './InteractionsLoader'; +import { WarpAware } from '../Warp'; +import { BasicSortKeyCache } from '../../cache/BasicSortKeyCache'; +/** + * Implementors of this interface are responsible for loading contract's definitions - + * its source code, info about owner, initial state, etc. + * See ContractDefinition type for more details regarding what data is being loaded. + */ +export interface DefinitionLoader extends GwTypeAware, WarpAware { + load(contractTxId: string, evolvedSrcTxId?: string): Promise>; + loadContractSource(srcTxId: string): Promise; + setCache(cache: BasicSortKeyCache>): void; + setSrcCache(cacheSrc?: BasicSortKeyCache): void; + getCache(): BasicSortKeyCache>; + getSrcCache(): BasicSortKeyCache; +} +//# sourceMappingURL=DefinitionLoader.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/DefinitionLoader.d.ts.map b/lib/types/core/modules/DefinitionLoader.d.ts.map new file mode 100644 index 00000000..e3254981 --- /dev/null +++ b/lib/types/core/modules/DefinitionLoader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"DefinitionLoader.d.ts","sourceRoot":"","sources":["../../../../src/core/modules/DefinitionLoader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAC5G,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAElE;;;;GAIG;AACH,MAAM,WAAW,gBAAiB,SAAQ,WAAW,EAAE,SAAS;IAC9D,IAAI,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;IAE/F,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;IAE7D,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;IAGjE,WAAW,CAAC,QAAQ,CAAC,EAAE,iBAAiB,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC;IAE1D,QAAQ,IAAI,iBAAiB,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC;IAEtD,WAAW,IAAI,iBAAiB,CAAC,QAAQ,CAAC,CAAC;CAC5C"} \ No newline at end of file diff --git a/lib/types/core/modules/ExecutorFactory.d.ts b/lib/types/core/modules/ExecutorFactory.d.ts new file mode 100644 index 00000000..7d3d490e --- /dev/null +++ b/lib/types/core/modules/ExecutorFactory.d.ts @@ -0,0 +1,15 @@ +import { ContractCache, ContractDefinition, SrcCache } from '../../core/ContractDefinition'; +import { EvaluationOptions } from './StateEvaluator'; +import { Warp } from '../Warp'; +import { InteractionState } from '../../contract/states/InteractionState'; +export interface ContractApi { +} +/** + * An interface for all the factories that produce Warp contracts "executors" - + * i.e. objects that are responsible for actually running the contract's code. + */ +export interface ExecutorFactory { + create(contractDefinition: ContractDefinition, evaluationOptions: EvaluationOptions, warp: Warp, interactionState: InteractionState): Promise; + checkWhiteListContractSources(contractDefinition: SrcCache & ContractCache, evaluationOptions: EvaluationOptions): void; +} +//# sourceMappingURL=ExecutorFactory.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/ExecutorFactory.d.ts.map b/lib/types/core/modules/ExecutorFactory.d.ts.map new file mode 100644 index 00000000..b76bd7e9 --- /dev/null +++ b/lib/types/core/modules/ExecutorFactory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ExecutorFactory.d.ts","sourceRoot":"","sources":["../../../../src/core/modules/ExecutorFactory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAC5F,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAG1E,MAAM,WAAW,WAAW;CAAG;AAE/B;;;GAGG;AACH,MAAM,WAAW,eAAe,CAAC,GAAG;IAClC,MAAM,CAAC,KAAK,EACV,kBAAkB,EAAE,kBAAkB,CAAC,KAAK,CAAC,EAC7C,iBAAiB,EAAE,iBAAiB,EACpC,IAAI,EAAE,IAAI,EACV,gBAAgB,EAAE,gBAAgB,GACjC,OAAO,CAAC,GAAG,CAAC,CAAC;IAEhB,6BAA6B,CAAC,KAAK,EACjC,kBAAkB,EAAE,QAAQ,GAAG,aAAa,CAAC,KAAK,CAAC,EACnD,iBAAiB,EAAE,iBAAiB,GACnC,IAAI,CAAC;CACT"} \ No newline at end of file diff --git a/lib/types/core/modules/InteractionsLoader.d.ts b/lib/types/core/modules/InteractionsLoader.d.ts new file mode 100644 index 00000000..88e1fa4d --- /dev/null +++ b/lib/types/core/modules/InteractionsLoader.d.ts @@ -0,0 +1,26 @@ +import { GQLNodeInterface } from '../../legacy/gqlResult'; +import { EvaluationOptions } from './StateEvaluator'; +import { WarpAware } from '../Warp'; +export type GW_TYPE = 'arweave' | 'warp'; +export interface GwTypeAware { + type(): GW_TYPE; +} +/** + * Implementors of this interface add functionality of loading contract's interaction transactions. + * Returned interactions MUST be sorted according to protocol specification ({@link LexicographicalInteractionsSorter} + */ +export interface InteractionsLoader extends GwTypeAware, WarpAware { + /** + * This method loads interactions for a given contract. + * If param fromSortKey and/or param toSortKey are present, the loaded interactions do + * conform the condition: i.sortKey > fromSortKey && i.sortKey <= toSortKey + * + * @param contractTxId - contract tx id to load the interactions + * @param fromSortKey - exclusive, optional - sortKey, from which the interactions should be loaded + * @param toSortKey - inclusive, optional - sortKey, to which the interactions should be loaded + * @param evaluationOptions, optional - {@link EvaluationOptions} + */ + load(contractTxId: string, fromSortKey?: string, toSortKey?: string, evaluationOptions?: EvaluationOptions): Promise; + clearCache(): void; +} +//# sourceMappingURL=InteractionsLoader.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/InteractionsLoader.d.ts.map b/lib/types/core/modules/InteractionsLoader.d.ts.map new file mode 100644 index 00000000..710c43ea --- /dev/null +++ b/lib/types/core/modules/InteractionsLoader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InteractionsLoader.d.ts","sourceRoot":"","sources":["../../../../src/core/modules/InteractionsLoader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEpC,MAAM,MAAM,OAAO,GAAG,SAAS,GAAG,MAAM,CAAC;AAEzC,MAAM,WAAW,WAAW;IAC1B,IAAI,IAAI,OAAO,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAmB,SAAQ,WAAW,EAAE,SAAS;IAChE;;;;;;;;;OASG;IACH,IAAI,CACF,YAAY,EAAE,MAAM,EACpB,WAAW,CAAC,EAAE,MAAM,EACpB,SAAS,CAAC,EAAE,MAAM,EAClB,iBAAiB,CAAC,EAAE,iBAAiB,GACpC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAE/B,UAAU,IAAI,IAAI,CAAC;CACpB"} \ No newline at end of file diff --git a/lib/types/core/modules/InteractionsSorter.d.ts b/lib/types/core/modules/InteractionsSorter.d.ts new file mode 100644 index 00000000..b330c257 --- /dev/null +++ b/lib/types/core/modules/InteractionsSorter.d.ts @@ -0,0 +1,21 @@ +import { GQLEdgeInterface } from '../../legacy/gqlResult'; +/** + * this is probably self-explanatory ;-) + */ +export interface InteractionsSorter { + sort(transactions: GQLEdgeInterface[]): Promise; + /** + * generates a sort key according to protocol specs + */ + createSortKey(blockId: string, transactionId: string, blockHeight: number, dummy?: boolean): Promise; + /** + * retreives the block height from the sort key + */ + extractBlockHeight(sortKey?: string): number | null; + /** + * generates a sort key for given block height - with a guarantee, + * that it will the last possible sort key for a given block height + */ + generateLastSortKey(blockHeight: number): string; +} +//# sourceMappingURL=InteractionsSorter.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/InteractionsSorter.d.ts.map b/lib/types/core/modules/InteractionsSorter.d.ts.map new file mode 100644 index 00000000..6136d652 --- /dev/null +++ b/lib/types/core/modules/InteractionsSorter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InteractionsSorter.d.ts","sourceRoot":"","sources":["../../../../src/core/modules/InteractionsSorter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,YAAY,EAAE,gBAAgB,EAAE,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAEpE;;OAEG;IACH,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAE7G;;OAEG;IACH,kBAAkB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IAEpD;;;OAGG;IACH,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAAC;CAClD"} \ No newline at end of file diff --git a/lib/types/core/modules/StateEvaluator.d.ts b/lib/types/core/modules/StateEvaluator.d.ts new file mode 100644 index 00000000..5744b342 --- /dev/null +++ b/lib/types/core/modules/StateEvaluator.d.ts @@ -0,0 +1,124 @@ +import { SortKeyCacheResult } from '../../cache/SortKeyCache'; +import { ExecutionContext } from '../ExecutionContext'; +import { GQLNodeInterface } from '../../legacy/gqlResult'; +import { SourceType } from './impl/WarpGatewayInteractionsLoader'; +import { BasicSortKeyCache } from '../../cache/BasicSortKeyCache'; +/** + * Implementors of this class are responsible for evaluating contract's state + * - based on the {@link ExecutionContext}. + */ +export interface StateEvaluator { + eval(executionContext: ExecutionContext): Promise>>; + /** + * a hook that is called on each state update (i.e. after evaluating state for each interaction transaction) + */ + onStateUpdate(transaction: GQLNodeInterface, executionContext: ExecutionContext, state: EvalStateResult, force?: boolean): Promise; + /** + * a hook that is called after state has been fully evaluated + */ + onStateEvaluated(transaction: GQLNodeInterface, executionContext: ExecutionContext, state: EvalStateResult): Promise; + /** + * a hook that is called after performing internal write between contracts + */ + onInternalWriteStateUpdate(transaction: GQLNodeInterface, contractTxId: string, state: EvalStateResult): Promise; + /** + * a hook that is called before communicating with other contract. + * note to myself: putting values into cache only "onContractCall" may degrade performance. + * For example: + * 1. block 722317 - contract A calls B + * 2. block 722727 - contract A calls B + * 3. block 722695 - contract B calls A + * If we update cache only on contract call - for the last above call (B->A) + * we would retrieve state cached for 722317. If there are any transactions + * between 722317 and 722695 - the performance will be degraded. + */ + onContractCall(transaction: GQLNodeInterface, executionContext: ExecutionContext, state: EvalStateResult): Promise; + /** + * loads the latest available state for given contract for given sortKey. + */ + latestAvailableState(contractTxId: string, sortKey?: string): Promise> | null>; + putInCache(contractTxId: string, transaction: GQLNodeInterface, state: EvalStateResult): Promise; + /** + * allows to syncState with an external state source (like Warp Distributed Execution Network) + */ + syncState(contractTxId: string, sortKey: string, state: State, validity: Record): Promise>>; + internalWriteState(contractTxId: string, sortKey: string): Promise> | null>; + dumpCache(): Promise; + hasContractCached(contractTxId: string): Promise; + lastCachedSortKey(): Promise; + setCache(cache: BasicSortKeyCache>): void; + getCache(): BasicSortKeyCache>; +} +export declare class EvalStateResult { + readonly state: State; + readonly validity: Record; + readonly errorMessages: Record; + constructor(state: State, validity: Record, errorMessages: Record); +} +export type UnsafeClientOptions = 'allow' | 'skip' | 'throw'; +export declare class DefaultEvaluationOptions implements EvaluationOptions { + ignoreExceptions: boolean; + waitForConfirmation: boolean; + updateCacheForEachInteraction: boolean; + internalWrites: boolean; + maxCallDepth: number; + maxInteractionEvaluationTimeSeconds: number; + stackTrace: { + saveState: boolean; + }; + sequencerUrl: string; + gasLimit: number; + sourceType: SourceType; + unsafeClient: "throw"; + allowBigInt: boolean; + walletBalanceUrl: string; + mineArLocalBlocks: boolean; + throwOnInternalWriteError: boolean; + cacheEveryNInteractions: number; + useKVStorage: boolean; + remoteStateSyncEnabled: boolean; + remoteStateSyncSource: string; + useConstructor: boolean; + whitelistSources: any[]; +} +export interface EvaluationOptions { + ignoreExceptions: boolean; + waitForConfirmation: boolean; + updateCacheForEachInteraction: boolean; + internalWrites: boolean; + maxCallDepth: number; + maxInteractionEvaluationTimeSeconds: number; + stackTrace: { + saveState: boolean; + }; + sequencerUrl: string; + gasLimit: number; + unsafeClient: UnsafeClientOptions; + allowBigInt: boolean; + walletBalanceUrl: string; + sourceType: SourceType; + mineArLocalBlocks: boolean; + throwOnInternalWriteError: boolean; + cacheEveryNInteractions: number; + useKVStorage: boolean; + useConstructor: boolean; + remoteStateSyncEnabled: boolean; + remoteStateSyncSource: string; + whitelistSources: string[]; +} +export declare class CustomEvent extends Event { + readonly detail: T; + constructor(message: any, data: any); +} +export declare class InteractionCompleteEvent { + readonly contractTxId: string; + readonly sortKey: string; + readonly transactionId: string; + readonly caller: string; + readonly input: Input; + readonly blockTimestamp: number; + readonly blockHeight: number; + readonly data: T; + constructor(contractTxId: string, sortKey: string, transactionId: string, caller: string, input: Input, blockTimestamp: number, blockHeight: number, data: T); +} +//# sourceMappingURL=StateEvaluator.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/StateEvaluator.d.ts.map b/lib/types/core/modules/StateEvaluator.d.ts.map new file mode 100644 index 00000000..2d3a2824 --- /dev/null +++ b/lib/types/core/modules/StateEvaluator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"StateEvaluator.d.ts","sourceRoot":"","sources":["../../../../src/core/modules/StateEvaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,sCAAsC,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,IAAI,CAAC,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,kBAAkB,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAE5G;;OAEG;IACH,aAAa,CAAC,KAAK,EACjB,WAAW,EAAE,gBAAgB,EAC7B,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,CAAC,EACzC,KAAK,EAAE,eAAe,CAAC,KAAK,CAAC,EAC7B,KAAK,CAAC,EAAE,OAAO,GACd,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB;;OAEG;IACH,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IACrB,QAAQ,CAAC,cAAc,EAAE,MAAM;IAC/B,QAAQ,CAAC,WAAW,EAAE,MAAM;IAC5B,QAAQ,CAAC,IAAI,EAAE,CAAC;gBAPP,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,MAAM,EACf,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,KAAK,EACZ,cAAc,EAAE,MAAM,EACtB,WAAW,EAAE,MAAM,EACnB,IAAI,EAAE,CAAC;CAEnB"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/ArweaveGQLTxsFetcher.d.ts b/lib/types/core/modules/impl/ArweaveGQLTxsFetcher.d.ts new file mode 100644 index 00000000..dfa4ffa1 --- /dev/null +++ b/lib/types/core/modules/impl/ArweaveGQLTxsFetcher.d.ts @@ -0,0 +1,34 @@ +import { GQLEdgeInterface, GQLTransaction } from 'legacy/gqlResult'; +import { Warp } from '../../Warp'; +interface TagFilter { + name: string; + values: string[]; +} +interface BlockFilter { + min?: number; + max?: number; +} +export interface ArweaveTransactionQuery { + tags?: TagFilter[]; + blockFilter?: BlockFilter; + first?: number; + after?: string; +} +/** + * Query all transactions from arweave gateway + */ +export declare class ArweaveGQLTxsFetcher { + protected readonly warp: Warp; + private readonly arweaveWrapper; + private readonly logger; + constructor(warp: Warp); + transaction(transactionId: string): Promise; + /** + * Fetches transaction stored using legacy bundling format. + */ + transactionUsingUploaderTag(transactionId: string): Promise; + transactions(variables: ArweaveTransactionQuery): Promise; + private fetch; +} +export {}; +//# sourceMappingURL=ArweaveGQLTxsFetcher.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/ArweaveGQLTxsFetcher.d.ts.map b/lib/types/core/modules/impl/ArweaveGQLTxsFetcher.d.ts.map new file mode 100644 index 00000000..0f221a07 --- /dev/null +++ b/lib/types/core/modules/impl/ArweaveGQLTxsFetcher.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveGQLTxsFetcher.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ArweaveGQLTxsFetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAsB,cAAc,EAA0B,MAAM,kBAAkB,CAAC;AAKhH,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAiFlC,UAAU,SAAS;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED,UAAU,WAAW;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,uBAAuB;IACtC,IAAI,CAAC,EAAE,SAAS,EAAE,CAAC;IACnB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAKD;;GAEG;AACH,qBAAa,oBAAoB;IAInB,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI;IAHzC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAiB;IAChD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAwD;gBAEhD,IAAI,EAAE,IAAI;IAInC,WAAW,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;IAMjE;;OAEG;IACG,2BAA2B,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;IAc3E,YAAY,CAAC,SAAS,EAAE,uBAAuB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC;YAiBrE,KAAK;CAwBpB"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.d.ts b/lib/types/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.d.ts new file mode 100644 index 00000000..442acc52 --- /dev/null +++ b/lib/types/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.d.ts @@ -0,0 +1,26 @@ +import { Warp, WarpEnvironment } from '../../Warp'; +import { SortKeyCache } from '../../../cache/SortKeyCache'; +import { ContractCache, ContractDefinition, ContractSource, SrcCache } from '../../../core/ContractDefinition'; +import { GQLTransaction } from '../../../legacy/gqlResult'; +import { DefinitionLoader } from '../DefinitionLoader'; +import { GW_TYPE } from '../InteractionsLoader'; +export declare class ArweaveGatewayBundledContractDefinitionLoader implements DefinitionLoader { + private readonly env; + private arweaveWrapper; + private arweaveTransactions; + private readonly logger; + constructor(env: WarpEnvironment); + load(contractTxId: string, evolvedSrcTxId?: string): Promise>; + fetchContractTx(contractTxId: string): Promise; + private convertToWarpCompatibleContractTx; + loadContractSource(srcTxId: string): Promise; + private contractSource; + private evalInitialState; + setCache(): void; + setSrcCache(): void; + getCache(): SortKeyCache>; + getSrcCache(): SortKeyCache; + type(): GW_TYPE; + set warp(warp: Warp); +} +//# sourceMappingURL=ArweaveGatewayBundledContractDefinitionLoader.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.d.ts.map b/lib/types/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.d.ts.map new file mode 100644 index 00000000..f46b1c2d --- /dev/null +++ b/lib/types/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveGatewayBundledContractDefinitionLoader.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,QAAQ,EAET,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAAmB,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAI5E,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAUhD,qBAAa,6CAA8C,YAAW,gBAAgB;IAKxE,OAAO,CAAC,QAAQ,CAAC,GAAG;IAJhC,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,mBAAmB,CAAuB;IAClD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiF;gBAE3E,GAAG,EAAE,eAAe;IAE3C,IAAI,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAuD9F,eAAe,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;YAQ7D,iCAAiC;IAezC,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;YAuCpD,cAAc;YAgBd,gBAAgB;IAW9B,QAAQ,IAAI,IAAI;IAGhB,WAAW,IAAI,IAAI;IAGnB,QAAQ,IAAI,YAAY,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAGhD,WAAW,IAAI,YAAY,CAAC,QAAQ,CAAC;IAIrC,IAAI,IAAI,OAAO;IAIf,IAAI,IAAI,CAAC,IAAI,EAAE,IAAI,EAGlB;CACF"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/ArweaveGatewayBundledInteractionLoader.d.ts b/lib/types/core/modules/impl/ArweaveGatewayBundledInteractionLoader.d.ts new file mode 100644 index 00000000..7482f28e --- /dev/null +++ b/lib/types/core/modules/impl/ArweaveGatewayBundledInteractionLoader.d.ts @@ -0,0 +1,43 @@ +import Arweave from 'arweave'; +import { GQLNodeInterface } from '../../../legacy/gqlResult'; +import { GW_TYPE, InteractionsLoader } from '../InteractionsLoader'; +import { EvaluationOptions } from '../StateEvaluator'; +import { Warp, WarpEnvironment } from '../../Warp'; +interface TagFilter { + name: string; + values: string[]; +} +interface BlockFilter { + min?: number; + max?: number; +} +export interface GqlReqVariables { + tags: TagFilter[]; + blockFilter: BlockFilter; + first: number; + after?: string; +} +export declare class ArweaveGatewayBundledInteractionLoader implements InteractionsLoader { + protected readonly arweave: Arweave; + private readonly environment; + private readonly logger; + private arweaveFetcher; + private arweaveWrapper; + private _warp; + private readonly sorter; + private readonly tagsParser; + constructor(arweave: Arweave, environment: WarpEnvironment); + load(contractId: string, fromSortKey?: string, toSortKey?: string, evaluationOptions?: EvaluationOptions): Promise; + private verifySortKeyIntegrity; + private isSortKeyInBounds; + private attachSequencerDataToInteraction; + private appendInternalWriteInteractions; + private maybeAddMockVrf; + private isNewerThenSortKeyBlockHeight; + private currentBlockHeight; + type(): GW_TYPE; + clearCache(): void; + set warp(warp: Warp); +} +export {}; +//# sourceMappingURL=ArweaveGatewayBundledInteractionLoader.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/ArweaveGatewayBundledInteractionLoader.d.ts.map b/lib/types/core/modules/impl/ArweaveGatewayBundledInteractionLoader.d.ts.map new file mode 100644 index 00000000..a7f037ab --- /dev/null +++ b/lib/types/core/modules/impl/ArweaveGatewayBundledInteractionLoader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveGatewayBundledInteractionLoader.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ArweaveGatewayBundledInteractionLoader.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAoB,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAI/E,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAEpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtD,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAcnD,UAAU,SAAS;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED,UAAU,WAAW;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,SAAS,EAAE,CAAC;IAClB,WAAW,EAAE,WAAW,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAKD,qBAAa,sCAAuC,YAAW,kBAAkB;IASnE,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO;IAAE,OAAO,CAAC,QAAQ,CAAC,WAAW;IAR7E,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA0E;IAEjG,OAAO,CAAC,cAAc,CAAuB;IAC7C,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,KAAK,CAAO;IACpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAC5C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAoB;gBAEhB,OAAO,EAAE,OAAO,EAAmB,WAAW,EAAE,eAAe;IAIxF,IAAI,CACR,UAAU,EAAE,MAAM,EAClB,WAAW,CAAC,EAAE,MAAM,EACpB,SAAS,CAAC,EAAE,MAAM,EAClB,iBAAiB,CAAC,EAAE,iBAAiB,GACpC,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAoE9B,OAAO,CAAC,sBAAsB;IAgC9B,OAAO,CAAC,iBAAiB;IAczB,OAAO,CAAC,gCAAgC;YAiD1B,+BAA+B;IAyB7C,OAAO,CAAC,eAAe;IAiBvB,OAAO,CAAC,6BAA6B;YAYvB,kBAAkB;IAKhC,IAAI,IAAI,OAAO;IAIf,UAAU,IAAI,IAAI;IAIlB,IAAI,IAAI,CAAC,IAAI,EAAE,IAAI,EAIlB;CACF"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/ArweaveGatewayInteractionsLoader.d.ts b/lib/types/core/modules/impl/ArweaveGatewayInteractionsLoader.d.ts new file mode 100644 index 00000000..5b8ae6ed --- /dev/null +++ b/lib/types/core/modules/impl/ArweaveGatewayInteractionsLoader.d.ts @@ -0,0 +1,21 @@ +import Arweave from 'arweave'; +import { GQLEdgeInterface, GQLNodeInterface } from '../../../legacy/gqlResult'; +import { GW_TYPE, InteractionsLoader } from '../InteractionsLoader'; +import { EvaluationOptions } from '../StateEvaluator'; +import { Warp, WarpEnvironment } from '../../Warp'; +export declare function bundledTxsFilter(tx: GQLEdgeInterface): boolean; +export declare class ArweaveGatewayInteractionsLoader implements InteractionsLoader { + protected readonly arweave: Arweave; + private readonly environment; + private readonly logger; + private readonly sorter; + private arweaveTransactionQuery; + private _warp; + private readonly tagsParser; + constructor(arweave: Arweave, environment: WarpEnvironment); + load(contractId: string, fromSortKey?: string, toSortKey?: string, evaluationOptions?: EvaluationOptions): Promise; + type(): GW_TYPE; + clearCache(): void; + set warp(warp: Warp); +} +//# sourceMappingURL=ArweaveGatewayInteractionsLoader.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/ArweaveGatewayInteractionsLoader.d.ts.map b/lib/types/core/modules/impl/ArweaveGatewayInteractionsLoader.d.ts.map new file mode 100644 index 00000000..65450b87 --- /dev/null +++ b/lib/types/core/modules/impl/ArweaveGatewayInteractionsLoader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveGatewayInteractionsLoader.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ArweaveGatewayInteractionsLoader.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAG/E,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAEpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtD,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAOnD,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,gBAAgB,WAEpD;AAED,qBAAa,gCAAiC,YAAW,kBAAkB;IAQ7D,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO;IAAE,OAAO,CAAC,QAAQ,CAAC,WAAW;IAP7E,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiE;IAExF,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAC5C,OAAO,CAAC,uBAAuB,CAAuB;IACtD,OAAO,CAAC,KAAK,CAAO;IACpB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAoB;gBAEhB,OAAO,EAAE,OAAO,EAAmB,WAAW,EAAE,eAAe;IAIxF,IAAI,CACR,UAAU,EAAE,MAAM,EAClB,WAAW,CAAC,EAAE,MAAM,EACpB,SAAS,CAAC,EAAE,MAAM,EAClB,iBAAiB,CAAC,EAAE,iBAAiB,GACpC,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAsG9B,IAAI,IAAI,OAAO;IAIf,UAAU,IAAI,IAAI;IAIlB,IAAI,IAAI,CAAC,IAAI,EAAE,IAAI,EAGlB;CACF"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/CacheableInteractionsLoader.d.ts b/lib/types/core/modules/impl/CacheableInteractionsLoader.d.ts new file mode 100644 index 00000000..796e5b4b --- /dev/null +++ b/lib/types/core/modules/impl/CacheableInteractionsLoader.d.ts @@ -0,0 +1,15 @@ +import { GQLNodeInterface } from '../../../legacy/gqlResult'; +import { InteractionsLoader, GW_TYPE } from '../InteractionsLoader'; +import { EvaluationOptions } from '../StateEvaluator'; +import { Warp } from '../../Warp'; +export declare class CacheableInteractionsLoader implements InteractionsLoader { + private readonly delegate; + private readonly logger; + private readonly interactionsCache; + constructor(delegate: InteractionsLoader); + load(contractTxId: string, fromSortKey?: string, toSortKey?: string, evaluationOptions?: EvaluationOptions): Promise; + type(): GW_TYPE; + clearCache(): void; + set warp(warp: Warp); +} +//# sourceMappingURL=CacheableInteractionsLoader.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/CacheableInteractionsLoader.d.ts.map b/lib/types/core/modules/impl/CacheableInteractionsLoader.d.ts.map new file mode 100644 index 00000000..cefbb8e3 --- /dev/null +++ b/lib/types/core/modules/impl/CacheableInteractionsLoader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"CacheableInteractionsLoader.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/CacheableInteractionsLoader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE7D,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAElC,qBAAa,2BAA4B,YAAW,kBAAkB;IAIxD,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAHrC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA4D;IACnF,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAA8C;gBAEnD,QAAQ,EAAE,kBAAkB;IAEnD,IAAI,CACR,YAAY,EAAE,MAAM,EACpB,WAAW,CAAC,EAAE,MAAM,EACpB,SAAS,CAAC,EAAE,MAAM,EAClB,iBAAiB,CAAC,EAAE,iBAAiB,GACpC,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAkC9B,IAAI,IAAI,OAAO;IAIf,UAAU,IAAI,IAAI;IAIlB,IAAI,IAAI,CAAC,IAAI,EAAE,IAAI,EAElB;CACF"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/CacheableStateEvaluator.d.ts b/lib/types/core/modules/impl/CacheableStateEvaluator.d.ts new file mode 100644 index 00000000..46c5d8a6 --- /dev/null +++ b/lib/types/core/modules/impl/CacheableStateEvaluator.d.ts @@ -0,0 +1,37 @@ +import Arweave from 'arweave'; +import { SortKeyCacheResult } from '../../../cache/SortKeyCache'; +import { ExecutionContext } from '../../../core/ExecutionContext'; +import { ExecutionContextModifier } from '../../../core/ExecutionContextModifier'; +import { GQLNodeInterface } from '../../../legacy/gqlResult'; +import { EvalStateResult } from '../StateEvaluator'; +import { DefaultStateEvaluator } from './DefaultStateEvaluator'; +import { HandlerApi } from './HandlerExecutorFactory'; +import { BasicSortKeyCache } from '../../../cache/BasicSortKeyCache'; +/** + * An implementation of DefaultStateEvaluator that adds caching capabilities. + * + * The main responsibility of this class is to compute whether there are + * any interaction transactions, for which the state hasn't been evaluated yet - + * if so - it generates a list of such transactions and evaluates the state + * for them - taking as an input state the last cached state. + */ +export declare class CacheableStateEvaluator extends DefaultStateEvaluator { + private cache; + private readonly cLogger; + constructor(arweave: Arweave, cache: BasicSortKeyCache>, executionContextModifiers?: ExecutionContextModifier[]); + eval(executionContext: ExecutionContext>): Promise>>; + onStateEvaluated(transaction: GQLNodeInterface, executionContext: ExecutionContext, state: EvalStateResult): Promise; + onStateUpdate(transaction: GQLNodeInterface, executionContext: ExecutionContext, state: EvalStateResult, force?: boolean): Promise; + latestAvailableState(contractTxId: string, sortKey?: string): Promise> | null>; + onInternalWriteStateUpdate(transaction: GQLNodeInterface, contractTxId: string, state: EvalStateResult): Promise; + onContractCall(transaction: GQLNodeInterface, executionContext: ExecutionContext, state: EvalStateResult): Promise; + putInCache(contractTxId: string, transaction: GQLNodeInterface, state: EvalStateResult): Promise; + syncState(contractTxId: string, sortKey: string, state: State, validity: Record): Promise>>; + dumpCache(): Promise; + internalWriteState(contractTxId: string, sortKey: string): Promise> | null>; + hasContractCached(contractTxId: string): Promise; + lastCachedSortKey(): Promise; + setCache(cache: BasicSortKeyCache>): void; + getCache(): BasicSortKeyCache>; +} +//# sourceMappingURL=CacheableStateEvaluator.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/CacheableStateEvaluator.d.ts.map b/lib/types/core/modules/impl/CacheableStateEvaluator.d.ts.map new file mode 100644 index 00000000..0811f08e --- /dev/null +++ b/lib/types/core/modules/impl/CacheableStateEvaluator.d.ts.map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G,OAAO,CAAC,OAAO,CAAC;IAIzD,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAIjD,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI;IAIlE,QAAQ,IAAI,iBAAiB,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;CAGxD"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/ContractDefinitionLoader.d.ts b/lib/types/core/modules/impl/ContractDefinitionLoader.d.ts new file mode 100644 index 00000000..baab3fa6 --- /dev/null +++ b/lib/types/core/modules/impl/ContractDefinitionLoader.d.ts @@ -0,0 +1,26 @@ +import Arweave from 'arweave'; +import { ContractDefinition, ContractSource, ContractCache, SrcCache } from '../../../core/ContractDefinition'; +import { ArweaveWrapper } from '../../../utils/ArweaveWrapper'; +import { DefinitionLoader } from '../DefinitionLoader'; +import { GW_TYPE } from '../InteractionsLoader'; +import { Warp, WarpEnvironment } from '../../Warp'; +import { BasicSortKeyCache } from '../../../cache/BasicSortKeyCache'; +export declare class ContractDefinitionLoader implements DefinitionLoader { + private readonly arweave; + private readonly env; + private readonly logger; + protected arweaveWrapper: ArweaveWrapper; + private readonly tagsParser; + constructor(arweave: Arweave, env: WarpEnvironment); + load(contractTxId: string, evolvedSrcTxId?: string): Promise>; + doLoad(contractTxId: string, forcedSrcTxId?: string): Promise>; + loadContractSource(contractSrcTxId: string): Promise; + private evalInitialState; + type(): GW_TYPE; + setCache(cache: BasicSortKeyCache>): void; + setSrcCache(cache: BasicSortKeyCache): void; + getCache(): BasicSortKeyCache>; + getSrcCache(): BasicSortKeyCache; + set warp(warp: Warp); +} +//# sourceMappingURL=ContractDefinitionLoader.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/ContractDefinitionLoader.d.ts.map b/lib/types/core/modules/impl/ContractDefinitionLoader.d.ts.map new file mode 100644 index 00000000..61f6dd12 --- /dev/null +++ b/lib/types/core/modules/impl/ContractDefinitionLoader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ContractDefinitionLoader.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/ContractDefinitionLoader.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,aAAa,EACb,QAAQ,EAET,MAAM,kCAAkC,CAAC;AAI1C,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAGhD,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAErE,qBAAa,wBAAyB,YAAW,gBAAgB;IAMnD,OAAO,CAAC,QAAQ,CAAC,OAAO;IAAW,OAAO,CAAC,QAAQ,CAAC,GAAG;IALnE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAyD;IAEhF,SAAS,CAAC,cAAc,EAAE,cAAc,CAAC;IACzC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;gBAEX,OAAO,EAAE,OAAO,EAAmB,GAAG,EAAE,eAAe;IAI9E,IAAI,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAQ9F,MAAM,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAsD/F,kBAAkB,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;YAwC5D,gBAAgB;IAW9B,IAAI,IAAI,OAAO;IAKf,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI;IAKrE,WAAW,CAAC,KAAK,EAAE,iBAAiB,CAAC,QAAQ,CAAC,GAAG,IAAI;IAIrD,QAAQ,IAAI,iBAAiB,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAIrD,WAAW,IAAI,iBAAiB,CAAC,QAAQ,CAAC;IAI1C,IAAI,IAAI,CAAC,IAAI,EAAE,IAAI,EAElB;CACF"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/DefaultStateEvaluator.d.ts b/lib/types/core/modules/impl/DefaultStateEvaluator.d.ts new file mode 100644 index 00000000..2e09739f --- /dev/null +++ b/lib/types/core/modules/impl/DefaultStateEvaluator.d.ts @@ -0,0 +1,40 @@ +import Arweave from 'arweave'; +import { SortKeyCacheResult } from '../../../cache/SortKeyCache'; +import { ExecutionContext } from '../../../core/ExecutionContext'; +import { ExecutionContextModifier } from '../../../core/ExecutionContextModifier'; +import { GQLNodeInterface } from '../../../legacy/gqlResult'; +import { EvalStateResult, StateEvaluator } from '../StateEvaluator'; +import { HandlerApi } from './HandlerExecutorFactory'; +import { BasicSortKeyCache } from '../../../cache/BasicSortKeyCache'; +/** + * This class contains the base functionality of evaluating the contracts state - according + * to the SmartWeave protocol. + * Marked as abstract - as without help of any cache - the evaluation in real-life applications + * would be really slow - so using this class without any caching ({@link CacheableStateEvaluator}) + * mechanism built on top makes no sense. + */ +export declare abstract class DefaultStateEvaluator implements StateEvaluator { + protected readonly arweave: Arweave; + private readonly executionContextModifiers; + private readonly logger; + private readonly tagsParser; + protected constructor(arweave: Arweave, executionContextModifiers?: ExecutionContextModifier[]); + eval(executionContext: ExecutionContext>): Promise>>; + protected doReadState(missingInteractions: GQLNodeInterface[], baseState: EvalStateResult, executionContext: ExecutionContext>): Promise>>; + private logResult; + private parseInput; + abstract latestAvailableState(contractTxId: string, sortKey?: string): Promise> | null>; + abstract onContractCall(transaction: GQLNodeInterface, executionContext: ExecutionContext, state: EvalStateResult): Promise; + abstract onInternalWriteStateUpdate(transaction: GQLNodeInterface, contractTxId: string, state: EvalStateResult): Promise; + abstract onStateEvaluated(transaction: GQLNodeInterface, executionContext: ExecutionContext, state: EvalStateResult): Promise; + abstract onStateUpdate(transaction: GQLNodeInterface, executionContext: ExecutionContext, state: EvalStateResult, force?: boolean): Promise; + abstract putInCache(contractTxId: string, transaction: GQLNodeInterface, state: EvalStateResult): Promise; + abstract syncState(contractTxId: string, sortKey: string, state: State, validity: Record): Promise>>; + abstract dumpCache(): Promise; + abstract internalWriteState(contractTxId: string, sortKey: string): Promise> | null>; + abstract hasContractCached(contractTxId: string): Promise; + abstract lastCachedSortKey(): Promise; + abstract setCache(cache: BasicSortKeyCache>): void; + abstract getCache(): BasicSortKeyCache>; +} +//# sourceMappingURL=DefaultStateEvaluator.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/DefaultStateEvaluator.d.ts.map b/lib/types/core/modules/impl/DefaultStateEvaluator.d.ts.map new file mode 100644 index 00000000..87d474f7 --- /dev/null +++ b/lib/types/core/modules/impl/DefaultStateEvaluator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"DefaultStateEvaluator.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/DefaultStateEvaluator.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,wCAAwC,CAAC;AAClF,OAAO,EAAE,gBAAgB,EAAmB,MAAM,2BAA2B,CAAC;AAI9E,OAAO,EAAE,eAAe,EAAE,cAAc,EAAe,MAAM,mBAAmB,CAAC;AACjF,OAAO,EAAuB,UAAU,EAAqB,MAAM,0BAA0B,CAAC;AAG9F,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,C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AC,MAAM,GAAG,IAAI,CAAC;IAEpD,QAAQ,CAAC,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI;IAE3E,QAAQ,CAAC,QAAQ,IAAI,iBAAiB,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;CACjE"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/HandlerExecutorFactory.d.ts b/lib/types/core/modules/impl/HandlerExecutorFactory.d.ts new file mode 100644 index 00000000..0ed5a403 --- /dev/null +++ b/lib/types/core/modules/impl/HandlerExecutorFactory.d.ts @@ -0,0 +1,81 @@ +import Arweave from 'arweave'; +import { ContractCache, ContractDefinition, SrcCache } from '../../../core/ContractDefinition'; +import { ExecutionContext } from '../../../core/ExecutionContext'; +import { GQLNodeInterface } from '../../../legacy/gqlResult'; +import { SmartWeaveGlobal } from '../../../legacy/smartweave-global'; +import { ExecutorFactory } from '../ExecutorFactory'; +import { EvalStateResult, EvaluationOptions, InteractionCompleteEvent } from '../StateEvaluator'; +import { Warp } from '../../Warp'; +import { InteractionState } from '../../../contract/states/InteractionState'; +import { WarpLogger } from '../../../logging/WarpLogger'; +export declare class ContractError extends Error { + readonly error: T; + readonly subtype?: string; + constructor(error: T, subtype?: string); +} +export declare class NonWhitelistedSourceError extends Error { + readonly error: T; + constructor(error: T); +} +/** + * A factory that produces handlers that are compatible with the "current" style of + * writing SW contracts (i.e. using "handle" function). + */ +export declare class HandlerExecutorFactory implements ExecutorFactory> { + private readonly arweave; + private readonly logger; + constructor(arweave: Arweave); + create(contractDefinition: ContractDefinition, evaluationOptions: EvaluationOptions, warp: Warp, interactionState: InteractionState): Promise>; + checkWhiteListContractSources(contractDefinition: SrcCache & ContractCache, evaluationOptions: EvaluationOptions): void; + private blacklistContracts; +} +export interface InteractionData { + interaction: ContractInteraction; + interactionTx: GQLNodeInterface; +} +/** + * A handle that effectively runs contract's code. + */ +export interface HandlerApi { + handle(executionContext: ExecutionContext, currentResult: EvalStateResult, interactionData: InteractionData): Promise>; + initState(state: State): void; + maybeCallStateConstructor(initialState: State, executionContext: ExecutionContext): Promise; +} +export type HandlerResult = { + result: Result; + state: State; + event: InteractionCompleteEvent; + gasUsed?: number; +}; +export type InteractionResult = HandlerResult & { + type: InteractionResultType; + errorMessage?: string; + error?: unknown; + originalValidity?: Record; + originalErrorMessages?: Record; +}; +export type InteractionType = 'view' | 'write'; +export type ContractInteraction = { + input: Input; + caller: string; + interactionType: InteractionType; +}; +export type InteractionResultType = 'ok' | 'error' | 'exception'; +export interface IvmOptions { + memoryLimit?: number; + timeout?: number; +} +export interface IvmPluginInput { + contractSource: string; + evaluationOptions: EvaluationOptions; + arweave: Arweave; + swGlobal: SmartWeaveGlobal; + contractDefinition: ContractDefinition; +} +export interface VM2PluginInput { + normalizedSource: string; + swGlobal: SmartWeaveGlobal; + logger: WarpLogger; + contractDefinition: ContractDefinition; +} +//# sourceMappingURL=HandlerExecutorFactory.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/HandlerExecutorFactory.d.ts.map b/lib/types/core/modules/impl/HandlerExecutorFactory.d.ts.map new file mode 100644 index 00000000..e823977e --- /dev/null +++ b/lib/types/core/modules/impl/HandlerExecutorFactory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"HandlerExecutorFactory.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/HandlerExecutorFactory.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AAC/F,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAGrE,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OA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AAO,GAAG,WAAW,CAAC;AAEjE,MAAM,WAAW,UAAU;IAIzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,cAAc;IAC7B,cAAc,EAAE,MAAM,CAAC;IACvB,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,kBAAkB,EAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC;CACjD;AAED,MAAM,WAAW,cAAc;IAC7B,gBAAgB,EAAE,MAAM,CAAC;IACzB,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,MAAM,EAAE,UAAU,CAAC;IACnB,kBAAkB,EAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC;CACjD"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/LexicographicalInteractionsSorter.d.ts b/lib/types/core/modules/impl/LexicographicalInteractionsSorter.d.ts new file mode 100644 index 00000000..6c8e7cf7 --- /dev/null +++ b/lib/types/core/modules/impl/LexicographicalInteractionsSorter.d.ts @@ -0,0 +1,22 @@ +import Arweave from 'arweave'; +import { GQLEdgeInterface } from '../../../legacy/gqlResult'; +import { InteractionsSorter } from '../InteractionsSorter'; +export declare const defaultArweaveMs: string; +export declare const sortingFirst: string; +export declare const sortingLast: string; +export declare const genesisSortKey: string; +export declare const lastPossibleSortKey: string; +/** + * implementation that is based on current's SDK sorting alg. + */ +export declare class LexicographicalInteractionsSorter implements InteractionsSorter { + private readonly arweave; + private readonly logger; + constructor(arweave: Arweave); + sort(transactions: GQLEdgeInterface[]): Promise; + createSortKey(blockId: string, transactionId: string, blockHeight: number, dummy?: boolean): Promise; + extractBlockHeight(sortKey?: string): number | null; + private addSortKey; + generateLastSortKey(blockHeight: number): string; +} +//# sourceMappingURL=LexicographicalInteractionsSorter.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/LexicographicalInteractionsSorter.d.ts.map b/lib/types/core/modules/impl/LexicographicalInteractionsSorter.d.ts.map new file mode 100644 index 00000000..234de19b --- /dev/null +++ b/lib/types/core/modules/impl/LexicographicalInteractionsSorter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"LexicographicalInteractionsSorter.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/LexicographicalInteractionsSorter.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAG7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAK3D,eAAO,MAAM,gBAAgB,QAAqB,CAAC;AAEnD,eAAO,MAAM,YAAY,QAAqB,CAAC;AAC/C,eAAO,MAAM,WAAW,QAAqB,CAAC;AAE9C,eAAO,MAAM,cAAc,QAA8D,CAAC;AAC1F,eAAO,MAAM,mBAAmB,QAA4D,CAAC;AAE7F;;GAEG;AACH,qBAAa,iCAAkC,YAAW,kBAAkB;IAG9D,OAAO,CAAC,QAAQ,CAAC,OAAO;IAFpC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkE;gBAE5D,OAAO,EAAE,OAAO;IAEvC,IAAI,CAAC,YAAY,EAAE,gBAAgB,EAAE,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAQ5D,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,UAAQ;IAa9F,kBAAkB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;YAK5C,UAAU;IAcxB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM;CAIjD"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/TagsParser.d.ts b/lib/types/core/modules/impl/TagsParser.d.ts new file mode 100644 index 00000000..b2e253d8 --- /dev/null +++ b/lib/types/core/modules/impl/TagsParser.d.ts @@ -0,0 +1,25 @@ +import { GQLNodeInterface, GQLTagInterface } from '../../../legacy/gqlResult'; +import { Transaction } from '../../../utils/types/arweave-types'; +/** + * A class that is responsible for retrieving "input" tag from the interaction transaction. + * Two tags formats are allowed: + * 1. "multiple interactions in one tx" format - where "Input" tag MUST be next to the "Contract" tag + * See more at https://github.com/ArweaveTeam/SmartWeave/pull/51 + * 2. "traditional" format - one interaction per one transaction - where tags order does not matter. + * + * More on Discord: https://discord.com/channels/357957786904166400/756557551234973696/885388585023463424 + */ +export declare class TagsParser { + private readonly logger; + getInputTag(interactionTransaction: GQLNodeInterface, contractTxId: string): GQLTagInterface; + isInteractWrite(interactionTransaction: GQLNodeInterface, contractTxId: string): boolean; + getInteractWritesContracts(interactionTransaction: GQLNodeInterface): string[]; + getContractTag(interactionTransaction: GQLNodeInterface): string; + getContractsWithInputs(interactionTransaction: GQLNodeInterface): Map; + isEvmSigned(interactionTransaction: GQLNodeInterface): boolean; + static hasMultipleInteractions(interactionTransaction: GQLNodeInterface): boolean; + decodeTags(tx: Transaction): GQLTagInterface[]; + getTag(tx: Transaction, name: string): any; + hasVrfTag(interaction: GQLNodeInterface): boolean; +} +//# sourceMappingURL=TagsParser.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/TagsParser.d.ts.map b/lib/types/core/modules/impl/TagsParser.d.ts.map new file mode 100644 index 00000000..dde39037 --- /dev/null +++ b/lib/types/core/modules/impl/TagsParser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TagsParser.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/TagsParser.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE9E,OAAO,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAC;AAEjE;;;;;;;;GAQG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA2C;IAElE,WAAW,CAAC,sBAAsB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,GAAG,eAAe;IA6B5F,eAAe,CAAC,sBAAsB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO;IAMxF,0BAA0B,CAAC,sBAAsB,EAAE,gBAAgB,GAAG,MAAM,EAAE;IAI9E,cAAc,CAAC,sBAAsB,EAAE,gBAAgB,GAAG,MAAM;IAIhE,sBAAsB,CAAC,sBAAsB,EAAE,gBAAgB,GAAG,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC;IAY9F,WAAW,CAAC,sBAAsB,EAAE,gBAAgB,GAAG,OAAO;IAI9D,MAAM,CAAC,uBAAuB,CAAC,sBAAsB,EAAE,gBAAgB,GAAG,OAAO;IAIjF,UAAU,CAAC,EAAE,EAAE,WAAW,GAAG,eAAe,EAAE;IAkB9C,MAAM,CAAC,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM;IAiBpC,SAAS,CAAC,WAAW,EAAE,gBAAgB;CAKxC"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/WarpGatewayContractDefinitionLoader.d.ts b/lib/types/core/modules/impl/WarpGatewayContractDefinitionLoader.d.ts new file mode 100644 index 00000000..5398caec --- /dev/null +++ b/lib/types/core/modules/impl/WarpGatewayContractDefinitionLoader.d.ts @@ -0,0 +1,38 @@ +import Arweave from 'arweave'; +import { GW_TYPE } from '../InteractionsLoader'; +import { ContractCache, ContractDefinition, ContractSource, SrcCache } from '../../../core/ContractDefinition'; +import { DefinitionLoader } from '../DefinitionLoader'; +import { Warp, WarpEnvironment } from '../../Warp'; +import { BasicSortKeyCache } from '../../../cache/BasicSortKeyCache'; +/** + * An extension to {@link ContractDefinitionLoader} that makes use of + * Warp Gateway ({@link https://github.com/redstone-finance/redstone-sw-gateway}) + * to load Contract Data. + * + * If the contract data is not available on Warp Gateway - it fallbacks to default implementation + * in {@link ContractDefinitionLoader} - i.e. loads the definition from Arweave gateway. + */ +export declare class WarpGatewayContractDefinitionLoader implements DefinitionLoader { + private definitionCache; + private srcCache; + private readonly env; + private readonly rLogger; + private contractDefinitionLoader; + private arweaveWrapper; + private readonly tagsParser; + private _warp; + constructor(arweave: Arweave, definitionCache: BasicSortKeyCache>, srcCache: BasicSortKeyCache, env: WarpEnvironment); + load(contractTxId: string, evolvedSrcTxId?: string): Promise>; + doLoad(contractTxId: string, forcedSrcTxId?: string): Promise>; + loadContractSource(contractSrcTxId: string): Promise; + type(): GW_TYPE; + setCache(cache: BasicSortKeyCache>): void; + setSrcCache(cacheSrc: BasicSortKeyCache): void; + getCache(): BasicSortKeyCache>; + getSrcCache(): BasicSortKeyCache; + private verifyEnv; + private getFromCache; + private putToCache; + set warp(warp: Warp); +} +//# sourceMappingURL=WarpGatewayContractDefinitionLoader.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/WarpGatewayContractDefinitionLoader.d.ts.map b/lib/types/core/modules/impl/WarpGatewayContractDefinitionLoader.d.ts.map new file mode 100644 index 00000000..8aa59247 --- /dev/null +++ b/lib/types/core/modules/impl/WarpGatewayContractDefinitionLoader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpGatewayContractDefinitionLoader.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/WarpGatewayContractDefinitionLoader.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAG9B,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AAK/G,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAKnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAErE;;;;;;;GAOG;AACH,qBAAa,mCAAoC,YAAW,gBAAgB;IASxE,OAAO,CAAC,eAAe;I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teractionsLoader.d.ts new file mode 100644 index 00000000..48516516 --- /dev/null +++ b/lib/types/core/modules/impl/WarpGatewayInteractionsLoader.d.ts @@ -0,0 +1,46 @@ +import { GQLNodeInterface } from '../../../legacy/gqlResult'; +import 'warp-isomorphic'; +import { GW_TYPE, InteractionsLoader } from '../InteractionsLoader'; +import { EvaluationOptions } from '../StateEvaluator'; +import { Warp } from '../../Warp'; +export type ConfirmationStatus = { + notCorrupted?: boolean; + confirmed?: null; +} | { + notCorrupted?: null; + confirmed?: boolean; +}; +export declare const enum SourceType { + ARWEAVE = "arweave", + WARP_SEQUENCER = "redstone-sequencer", + BOTH = "both" +} +/** + * The aim of this implementation of the {@link InteractionsLoader} is to make use of + * Warp Gateway ({@link https://github.com/redstone-finance/redstone-sw-gateway}) + * endpoint and retrieve contracts' interactions. + * + * Optionally - it is possible to pass: + * 1. {@link ConfirmationStatus.confirmed} flag - to receive only confirmed interactions - ie. interactions with + * enough confirmations, whose existence is confirmed by at least 3 Arweave peers. + * 2. {@link ConfirmationStatus.notCorrupted} flag - to receive both already confirmed and not yet confirmed (ie. latest) + * interactions. + * 3. {@link SourceType} - to receive interactions based on their origin ({@link SourceType.ARWEAVE} or {@link SourceType.WARP_SEQUENCER}). + * If not set, by default {@link SourceType.BOTH} is set. + * + * Passing no flag is the "backwards compatible" mode (ie. it will behave like the original Arweave GQL gateway endpoint). + * Note that this may result in returning corrupted and/or forked interactions + * - read more {@link https://github.com/warp-contracts/redstone-sw-gateway#corrupted-transactions}. + */ +export declare class WarpGatewayInteractionsLoader implements InteractionsLoader { + private readonly confirmationStatus; + private readonly source; + private _warp; + constructor(confirmationStatus?: ConfirmationStatus, source?: SourceType); + private readonly logger; + load(contractId: string, fromSortKey?: string, toSortKey?: string, evaluationOptions?: EvaluationOptions): Promise; + type(): GW_TYPE; + clearCache(): void; + set warp(warp: Warp); +} +//# sourceMappingURL=WarpGatewayInteractionsLoader.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/WarpGatewayInteractionsLoader.d.ts.map b/lib/types/core/modules/impl/WarpGatewayInteractionsLoader.d.ts.map new file mode 100644 index 00000000..5bf4658b --- /dev/null +++ b/lib/types/core/modules/impl/WarpGatewayInteractionsLoader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpGatewayInteractionsLoader.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/WarpGatewayInteractionsLoader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAG7D,OAAO,iBAAiB,CAAC;AAEzB,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAElC,MAAM,MAAM,kBAAkB,GAC1B;IACE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,SAAS,CAAC,EAAE,IAAI,CAAC;CAClB,GACD;IACE,YAAY,CAAC,EAAE,IAAI,CAAC;IACpB,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,CAAC;AAEN,0BAAkB,UAAU;IAC1B,OAAO,YAAY;IACnB,cAAc,uBAAuB;IACrC,IAAI,SAAS;CACd;AAUD;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,6BAA8B,YAAW,kBAAkB;IAIpE,OAAO,CAAC,QAAQ,CAAC,kBAAkB;IACnC,OAAO,CAAC,QAAQ,CAAC,MAAM;IAJzB,OAAO,CAAC,KAAK,CAAO;gBAGD,kBAAkB,GAAE,kBAAyB,EAC7C,MAAM,GAAE,UAA4B;IAMvD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA8D;IAE/E,IAAI,CACR,UAAU,EAAE,MAAM,EAClB,WAAW,CAAC,EAAE,MAAM,EACpB,SAAS,CAAC,EAAE,MAAM,EAClB,iBAAiB,CAAC,EAAE,iBAAiB,GACpC,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAuD9B,IAAI,IAAI,OAAO;IAIf,UAAU,IAAI,IAAI;IAIlB,IAAI,IAAI,CAAC,IAAI,EAAE,IAAI,EAElB;CACF"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/handler/AbstractContractHandler.d.ts b/lib/types/core/modules/impl/handler/AbstractContractHandler.d.ts new file mode 100644 index 00000000..98e9e282 --- /dev/null +++ b/lib/types/core/modules/impl/handler/AbstractContractHandler.d.ts @@ -0,0 +1,21 @@ +import { ContractDefinition } from '../../../../core/ContractDefinition'; +import { ExecutionContext } from '../../../../core/ExecutionContext'; +import { EvalStateResult } from '../../../../core/modules/StateEvaluator'; +import { GQLNodeInterface } from '../../../../legacy/gqlResult'; +import { SmartWeaveGlobal } from '../../../../legacy/smartweave-global'; +import { HandlerApi, InteractionData, InteractionResult } from '../HandlerExecutorFactory'; +export declare abstract class AbstractContractHandler implements HandlerApi { + protected readonly swGlobal: SmartWeaveGlobal; + protected readonly contractDefinition: ContractDefinition; + protected logger: import("../../../..").WarpLogger; + protected constructor(swGlobal: SmartWeaveGlobal, contractDefinition: ContractDefinition); + abstract handle(executionContext: ExecutionContext, currentResult: EvalStateResult, interactionData: InteractionData): Promise>; + abstract initState(state: State): any; + abstract maybeCallStateConstructor(initialState: State, executionContext: ExecutionContext): Promise; + dispose(): Promise; + protected assignWrite(executionContext: ExecutionContext): void; + protected assignViewContractState(executionContext: ExecutionContext): void; + protected assignReadContractState(executionContext: ExecutionContext, interactionTx: GQLNodeInterface): void; + protected assignRefreshState(executionContext: ExecutionContext): void; +} +//# sourceMappingURL=AbstractContractHandler.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/handler/AbstractContractHandler.d.ts.map b/lib/types/core/modules/impl/handler/AbstractContractHandler.d.ts.map new file mode 100644 index 00000000..286a8ae0 --- /dev/null +++ b/lib/types/core/modules/impl/handler/AbstractContractHandler.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractContractHandler.d.ts","s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AAW,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,CAAC;IAiE/D,SAAS,CAAC,uBAAuB,CAAC,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,CAAC;IAmBlF,SAAS,CAAC,uBAAuB,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,CAAC,EAAE,aAAa,EAAE,gBAAgB;IAoD5G,SAAS,CAAC,kBAAkB,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,CAAC;CAOvE"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/handler/JsHandlerApi.d.ts b/lib/types/core/modules/impl/handler/JsHandlerApi.d.ts new file mode 100644 index 00000000..c033bc43 --- /dev/null +++ b/lib/types/core/modules/impl/handler/JsHandlerApi.d.ts @@ -0,0 +1,25 @@ +import { ContractDefinition } from '../../../../core/ContractDefinition'; +import { ExecutionContext } from '../../../../core/ExecutionContext'; +import { EvalStateResult } from '../../../../core/modules/StateEvaluator'; +import { SmartWeaveGlobal } from '../../../../legacy/smartweave-global'; +import { InteractionData, InteractionResult } from '../HandlerExecutorFactory'; +import { AbstractContractHandler } from './AbstractContractHandler'; +export declare enum KnownErrors { + ContractError = "ContractError", + ConstructorError = "ConstructorError", + NetworkCommunicationError = "NetworkCommunicationError", + NonWhitelistedSourceError = "NonWhitelistedSourceError" +} +export declare class JsHandlerApi extends AbstractContractHandler { + private readonly contractFunction; + constructor(swGlobal: SmartWeaveGlobal, contractDefinition: ContractDefinition, contractFunction: Function); + handle(executionContext: ExecutionContext, currentResult: EvalStateResult, interactionData: InteractionData): Promise>; + initState(state: State): void; + maybeCallStateConstructor(initialState: State, executionContext: ExecutionContext): Promise; + private assertNotConstructorCall; + private configureSwGlobalForConstructor; + private runContractFunction; + private setupSwGlobal; + private enableInternalWrites; +} +//# sourceMappingURL=JsHandlerApi.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/handler/JsHandlerApi.d.ts.map b/lib/types/core/modules/impl/handler/JsHandlerApi.d.ts.map new file mode 100644 index 00000000..c414f352 --- /dev/null +++ b/lib/types/core/modules/impl/handler/JsHandlerApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"JsHandlerApi.d.ts","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/handler/JsHandlerApi.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACrE,OAAO,EAAE,eAAe,EAA4B,MAAM,yCAAyC,CAAC;AACpG,OAAO,EAAW,gBAAgB,EAAwB,MAAM,sCAAsC,CAAC;AAEvG,OAAO,EAAsC,eAAe,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAEnH,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAQpE,oBAAY,WAAW;IACrB,aAAa,kBAAkB;IAC/B,gBAAgB,qBAAqB;IACrC,yBAAyB,8BAA8B;IACvD,yBAAyB,8BAA8B;CACxD;AAED,qBAAa,YAAY,CAAC,KAAK,CAAE,SAAQ,uBAAuB,CAAC,KAAK,CAAC;IAKnE,OAAO,CAAC,QAAQ,CAAC,gBAAgB;gBAHjC,QAAQ,EAAE,gBAAgB,EAC1B,kBAAkB,EAAE,kBAAkB,CAAC,KAAK,CAAC,EAE5B,gBAAgB,EAAE,QAAQ;IAKvC,MAAM,CAAC,KAAK,EAAE,MAAM,EACxB,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,CAAC,EACzC,aAAa,EAAE,eAAe,CAAC,KAAK,CAAC,EACrC,eAAe,EAAE,eAAe,CAAC,KAAK,CAAC,GACtC,OAAO,CAAC,iBAAiB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAY5C,SAAS,CAAC,KAAK,EAAE,KAAK;IAEhB,yBAAyB,CAAC,KAAK,EACnC,YAAY,EAAE,KAAK,EACnB,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,CAAC,GACxC,OAAO,CAAC,KAAK,CAAC;IAqCjB,OAAO,CAAC,wBAAwB;IAShC,OAAO,CAAC,+BAA+B;YAkCzB,mBAAmB;IAkGjC,OAAO,CAAC,aAAa;IAKrB,OAAO,CAAC,oBAAoB;CAS7B"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/handler/WasmHandlerApi.d.ts b/lib/types/core/modules/impl/handler/WasmHandlerApi.d.ts new file mode 100644 index 00000000..f76627cf --- /dev/null +++ b/lib/types/core/modules/impl/handler/WasmHandlerApi.d.ts @@ -0,0 +1,17 @@ +import { ContractDefinition } from '../../../../core/ContractDefinition'; +import { ExecutionContext } from '../../../../core/ExecutionContext'; +import { EvalStateResult } from '../../../../core/modules/StateEvaluator'; +import { SmartWeaveGlobal } from '../../../../legacy/smartweave-global'; +import { InteractionData, InteractionResult } from '../HandlerExecutorFactory'; +import { AbstractContractHandler } from './AbstractContractHandler'; +export declare class WasmHandlerApi extends AbstractContractHandler { + private readonly wasmExports; + constructor(swGlobal: SmartWeaveGlobal, contractDefinition: ContractDefinition, wasmExports: any); + handle(executionContext: ExecutionContext, currentResult: EvalStateResult, interactionData: InteractionData): Promise>; + initState(state: State): void; + private doHandleLegacy; + private doHandle; + maybeCallStateConstructor(initialState: State, executionContext: ExecutionContext): Promise; + private doGetCurrentState; +} +//# sourceMappingURL=WasmHandlerApi.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/handler/WasmHandlerApi.d.ts.map b/lib/types/core/modules/impl/handler/WasmHandlerApi.d.ts.map new file mode 100644 index 00000000..8d919fa4 --- /dev/null +++ b/lib/types/core/modules/impl/handler/WasmHandlerApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WasmHandlerApi.d.ts","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/handler/WasmHandlerApi.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,yCAAyC,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AACxE,OAAO,EAGL,eAAe,EACf,iBAAiB,EAElB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAGpE,qBAAa,cAAc,CAAC,KAAK,CAAE,SAAQ,uBAAuB,CAAC,KAAK,CAAC;IAKrE,OAAO,CAAC,QAAQ,CAAC,WAAW;gBAH5B,QAAQ,EAAE,gBAAgB,EAE1B,kBAAkB,EAAE,kBAAkB,CAAC,KAAK,CAAC,EAC5B,WAAW,EAAE,GAAG;IAK7B,MAAM,CAAC,KAAK,EAAE,MAAM,EACxB,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,CAAC,EACzC,aAAa,EAAE,eAAe,CAAC,KAAK,CAAC,EACrC,eAAe,EAAE,eAAe,CAAC,KAAK,CAAC,GACtC,OAAO,CAAC,iBAAiB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IA2D5C,SAAS,CAAC,KAAK,EAAE,KAAK;YAoBR,cAAc;YA6Bd,QAAQ;IA0BhB,yBAAyB,CAC7B,YAAY,EAAE,KAAK,EACnB,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,GACjD,OAAO,CAAC,KAAK,CAAC;IAOjB,OAAO,CAAC,iBAAiB;CAU1B"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/normalize-source.d.ts b/lib/types/core/modules/impl/normalize-source.d.ts new file mode 100644 index 00000000..339b430d --- /dev/null +++ b/lib/types/core/modules/impl/normalize-source.d.ts @@ -0,0 +1,4 @@ +import { WarpLogger } from '../../../logging/WarpLogger'; +export declare function normalizeContractSource(contractSrc: string, useVM2: boolean): string; +export declare function checkJsSrc(src: string, logger?: WarpLogger): boolean; +//# sourceMappingURL=normalize-source.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/normalize-source.d.ts.map b/lib/types/core/modules/impl/normalize-source.d.ts.map new file mode 100644 index 00000000..ceda2bda --- /dev/null +++ b/lib/types/core/modules/impl/normalize-source.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"normalize-source.d.ts","sourceRoot":"","sources":["../../../../../src/core/modules/impl/normalize-source.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAEzD,wBAAgB,uBAAuB,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,MAAM,CA0CpF;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,UAAU,GAAG,OAAO,CASpE"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/wasm/WasmSrc.d.ts b/lib/types/core/modules/impl/wasm/WasmSrc.d.ts new file mode 100644 index 00000000..04bc41ed --- /dev/null +++ b/lib/types/core/modules/impl/wasm/WasmSrc.d.ts @@ -0,0 +1,12 @@ +/// +export declare class WasmSrc { + private readonly src; + private readonly logger; + readonly splitted: Buffer[]; + constructor(src: Buffer); + wasmBinary(): Buffer; + sourceCode(): Promise>; + additionalCode(): string | null; + private splitBuffer; +} +//# sourceMappingURL=WasmSrc.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/wasm/WasmSrc.d.ts.map b/lib/types/core/modules/impl/wasm/WasmSrc.d.ts.map new file mode 100644 index 00000000..96676ccd --- /dev/null +++ b/lib/types/core/modules/impl/wasm/WasmSrc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WasmSrc.d.ts","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/wasm/WasmSrc.ts"],"names":[],"mappings":";AAIA,qBAAa,OAAO;IAIN,OAAO,CAAC,QAAQ,CAAC,GAAG;IAHhC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAwC;IAC/D,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,CAAC;gBAEC,GAAG,EAAE,MAAM;IAKxC,UAAU,IAAI,MAAM;IAId,UAAU,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAehD,cAAc,IAAI,MAAM,GAAG,IAAI;IAO/B,OAAO,CAAC,WAAW;CAyCpB"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/wasm/rust-wasm-imports.d.ts b/lib/types/core/modules/impl/wasm/rust-wasm-imports.d.ts new file mode 100644 index 00000000..ff661551 --- /dev/null +++ b/lib/types/core/modules/impl/wasm/rust-wasm-imports.d.ts @@ -0,0 +1,3 @@ +export type WarpContractsCrateVersion = '__WARP_CONTRACTS_VERSION_LEGACY' | '__WARP_CONTRACTS_VERSION_1'; +export declare const rustWasmImports: (swGlobal: any, wbindgenImports: any, wasmInstance: any, dtorValue: any, warpContractsCrateVersion: WarpContractsCrateVersion) => any; +//# sourceMappingURL=rust-wasm-imports.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/wasm/rust-wasm-imports.d.ts.map b/lib/types/core/modules/impl/wasm/rust-wasm-imports.d.ts.map new file mode 100644 index 00000000..b931499f --- /dev/null +++ b/lib/types/core/modules/impl/wasm/rust-wasm-imports.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rust-wasm-imports.d.ts","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/wasm/rust-wasm-imports.ts"],"names":[],"mappings":"AAqCA,MAAM,MAAM,yBAAyB,GAAG,iCAAiC,GAAG,4BAA4B,CAAC;AAIzG,eAAO,MAAM,eAAe,sGAKC,yBAAyB,KACnD,GA+sCF,CAAC"} \ No newline at end of file diff --git a/lib/types/core/modules/impl/wasm/wasm-bindgen-tools.d.ts b/lib/types/core/modules/impl/wasm/wasm-bindgen-tools.d.ts new file mode 100644 index 00000000..ea504765 --- /dev/null +++ b/lib/types/core/modules/impl/wasm/wasm-bindgen-tools.d.ts @@ -0,0 +1,2 @@ +export declare function matchMutClosureDtor(source: string): string; +//# sourceMappingURL=wasm-bindgen-tools.d.ts.map \ No newline at end of file diff --git a/lib/types/core/modules/impl/wasm/wasm-bindgen-tools.d.ts.map b/lib/types/core/modules/impl/wasm/wasm-bindgen-tools.d.ts.map new file mode 100644 index 00000000..70bf8e23 --- /dev/null +++ b/lib/types/core/modules/impl/wasm/wasm-bindgen-tools.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wasm-bindgen-tools.d.ts","sourceRoot":"","sources":["../../../../../../src/core/modules/impl/wasm/wasm-bindgen-tools.ts"],"names":[],"mappings":"AAAA,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,UAIjD"} \ No newline at end of file diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts new file mode 100644 index 00000000..f8ab26d5 --- /dev/null +++ b/lib/types/index.d.ts @@ -0,0 +1,63 @@ +export * from './logging/web/ConsoleLogger'; +export * from './logging/web/ConsoleLoggerFactory'; +export * from './logging/WarpLogger'; +export * from './logging/LoggerFactory'; +export * from './logging/LoggerSettings'; +export * from './logging/Benchmark'; +export * from './cache/BasicSortKeyCache'; +export * from './cache/SortKeyCache'; +export * from './cache/WarpCache'; +export * from './cache/impl/LevelDbCache'; +export * from './cache/impl/MemCache'; +export * from './core/modules/DefinitionLoader'; +export * from './core/modules/ExecutorFactory'; +export * from './core/modules/InteractionsLoader'; +export * from './core/modules/InteractionsSorter'; +export * from './core/modules/StateEvaluator'; +export * from './core/modules/impl/ContractDefinitionLoader'; +export * from './core/modules/impl/WarpGatewayContractDefinitionLoader'; +export * from './core/modules/impl/ArweaveGatewayInteractionsLoader'; +export * from './core/modules/impl/WarpGatewayInteractionsLoader'; +export * from './core/modules/impl/CacheableInteractionsLoader'; +export * from './core/modules/impl/DefaultStateEvaluator'; +export * from './core/modules/impl/CacheableStateEvaluator'; +export * from './core/modules/impl/HandlerExecutorFactory'; +export * from './core/modules/impl/LexicographicalInteractionsSorter'; +export * from './core/modules/impl/TagsParser'; +export * from './core/modules/impl/normalize-source'; +export * from './core/modules/impl/handler/AbstractContractHandler'; +export * from './core/modules/impl/handler/JsHandlerApi'; +export * from './core/modules/impl/handler/WasmHandlerApi'; +export * from './core/ExecutionContextModifier'; +export * from './core/KnownTags'; +export * from './core/ExecutionContext'; +export * from './core/ContractDefinition'; +export * from './core/ContractCallRecord'; +export * from './core/WarpFactory'; +export * from './core/Warp'; +export * from './core/WarpBuilder'; +export * from './core/WarpPlugin'; +export * from './core/WarpFetchWrapper'; +export * from './contract/Contract'; +export * from './contract/HandlerBasedContract'; +export * from './contract/PstContract'; +export * from './contract/PstContractImpl'; +export * from './contract/InnerWritesEvaluator'; +export * from './contract/Signature'; +export * from './contract/EvaluationOptionsEvaluator'; +export * from './contract/deploy/Source'; +export * from './contract/deploy/CreateContract'; +export * from './legacy/gqlResult'; +export * from './legacy/smartweave-global'; +export * from './legacy/errors'; +export * from './legacy/utils'; +export * from './legacy/create-interaction-tx'; +export * from './utils/utils'; +export * from './utils/ArweaveWrapper'; +export * from './utils/types/arweave-types'; +export * from './core/modules/impl/wasm/WasmSrc'; +export * from './core/modules/impl/wasm/rust-wasm-imports'; +export * from './core/modules/impl/wasm/wasm-bindgen-tools'; +export * from './core/modules/impl/ArweaveGatewayBundledContractDefinitionLoader'; +export * from './core/modules/impl/ArweaveGatewayBundledInteractionLoader'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/types/index.d.ts.map b/lib/types/index.d.ts.map new file mode 100644 index 00000000..0f051ed6 --- /dev/null +++ b/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,6BAA6B,CAAC;AAC5C,cAAc,oCAAoC,CAAC;AACnD,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,0BAA0B,CAAC;AACzC,cAAc,qBAAqB,CAAC;AAEpC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,sBAA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CAAgC,CAAC;AAE/C,cAAc,eAAe,CAAC;AAC9B,cAAc,wBAAwB,CAAC;AACvC,cAAc,6BAA6B,CAAC;AAE5C,cAAc,kCAAkC,CAAC;AACjD,cAAc,4CAA4C,CAAC;AAC3D,cAAc,6CAA6C,CAAC;AAE5D,cAAc,mEAAmE,CAAC;AAClF,cAAc,4DAA4D,CAAC"} \ No newline at end of file diff --git a/lib/types/legacy/create-interaction-tx.d.ts b/lib/types/legacy/create-interaction-tx.d.ts new file mode 100644 index 00000000..b6d7557d --- /dev/null +++ b/lib/types/legacy/create-interaction-tx.d.ts @@ -0,0 +1,9 @@ +import Arweave from 'arweave'; +import { GQLNodeInterface } from './gqlResult'; +import { SigningFunction } from '../contract/Signature'; +import { BlockData, Transaction } from '../utils/types/arweave-types'; +import { Tags } from '../contract/deploy/CreateContract'; +export declare function createInteractionTx(arweave: Arweave, signer: SigningFunction, contractId: string, input: Input, tags: Tags, target: string, winstonQty: string, dummy: boolean, isTestnet: boolean, reward?: string): Promise; +export declare function createDummyTx(tx: Transaction, from: string, block: BlockData): GQLNodeInterface; +export declare function createInteractionTagsList(contractId: string, input: Input, isTestnet: boolean, customTags?: Tags): Tags; +//# sourceMappingURL=create-interaction-tx.d.ts.map \ No newline at end of file diff --git a/lib/types/legacy/create-interaction-tx.d.ts.map b/lib/types/legacy/create-interaction-tx.d.ts.map new file mode 100644 index 00000000..2e1d3c23 --- /dev/null +++ b/lib/types/legacy/create-interaction-tx.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"create-interaction-tx.d.ts","sourceRoot":"","sources":["../../../src/legacy/create-interaction-tx.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAmC,WAAW,EAAE,MAAM,8BAA8B,CAAC;AACvG,OAAO,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;AAEzD,wBAAsB,mBAAmB,CAAC,KAAK,EAC7C,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,eAAe,EACvB,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,KAAK,EACZ,IAAI,EAAE,IAAI,EACV,MAAM,QAAK,EACX,UAAU,QAAM,EAChB,KAAK,SAAQ,EACb,SAAS,EAAE,OAAO,EAClB,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,WAAW,CAAC,CAiCtB;AAED,wBAAgB,aAAa,CAAC,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,gBAAgB,CA8C/F;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAC7C,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,KAAK,EACZ,SAAS,EAAE,OAAO,EAClB,UAAU,CAAC,EAAE,IAAI,QAqBlB"} \ No newline at end of file diff --git a/lib/types/legacy/errors.d.ts b/lib/types/legacy/errors.d.ts new file mode 100644 index 00000000..be93f7ac --- /dev/null +++ b/lib/types/legacy/errors.d.ts @@ -0,0 +1,15 @@ +export declare const enum SmartWeaveErrorType { + CONTRACT_NOT_FOUND = "CONTRACT_NOT_FOUND" +} +type SmartWeaveErrorInfo = { + message?: string; + requestedTxId?: string; +}; +export declare class SmartWeaveError extends Error { + readonly type: SmartWeaveErrorType; + readonly otherInfo: SmartWeaveErrorInfo; + constructor(type: SmartWeaveErrorType, optional?: SmartWeaveErrorInfo); + getType(): SmartWeaveErrorType; +} +export {}; +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/lib/types/legacy/errors.d.ts.map b/lib/types/legacy/errors.d.ts.map new file mode 100644 index 00000000..638af8c1 --- /dev/null +++ b/lib/types/legacy/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/legacy/errors.ts"],"names":[],"mappings":"AAAA,0BAAkB,mBAAmB;IACnC,kBAAkB,uBAAuB;CAC1C;AAED,KAAK,mBAAmB,GAAG;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,qBAAa,eAAgB,SAAQ,KAAK;IACxC,SAAgB,IAAI,EAAE,mBAAmB,CAAC;IAC1C,SAAgB,SAAS,EAAE,mBAAmB,CAAC;gBAEnC,IAAI,EAAE,mBAAmB,EAAE,QAAQ,GAAE,mBAAwB;IAUlE,OAAO,IAAI,mBAAmB;CAGtC"} \ No newline at end of file diff --git a/lib/types/legacy/gqlResult.d.ts b/lib/types/legacy/gqlResult.d.ts new file mode 100644 index 00000000..cd766479 --- /dev/null +++ b/lib/types/legacy/gqlResult.d.ts @@ -0,0 +1,92 @@ +export interface GQLPageInfoInterface { + hasNextPage: boolean; +} +export interface GQLOwnerInterface { + address: string; + key: string; +} +export interface GQLAmountInterface { + winston: string; + ar: string; +} +export interface GQLMetaDataInterface { + size: number; + type: string; +} +export interface GQLTagInterface { + name: string; + value: string; +} +export interface GQLBlockInterface { + id: string; + timestamp: number; + height: number; + previous: string; +} +type LastSortKey = 'null' | string; +export interface GQLNodeInterface { + id: string; + anchor: string; + signature: string; + recipient: string; + owner: GQLOwnerInterface; + fee: GQLAmountInterface; + quantity: GQLAmountInterface; + data: GQLMetaDataInterface; + tags: GQLTagInterface[]; + block: GQLBlockInterface; + parent: { + id: string; + }; + bundledIn: { + id: string; + }; + dry?: boolean; + sortKey?: string; + lastSortKey?: LastSortKey; + strict?: boolean; + confirmationStatus?: string; + source?: string; + bundlerTxId?: string; + vrf?: VrfData; +} +export interface VrfData { + index: string; + proof: string; + bigint: string; + pubkey: string; +} +export interface GQLEdgeInterface { + cursor: string; + node: GQLNodeInterface; +} +export interface GQLTransactionsResultInterface { + pageInfo: GQLPageInfoInterface; + edges: GQLEdgeInterface[]; +} +export interface GQLResultInterface { + data: { + transactions: GQLTransactionsResultInterface; + }; +} +export interface GQLTransaction { + id: string; + owner: GQLOwnerInterface; + recipient: string; + tags: GQLTagInterface[]; + block: GQLBlockInterface; + fee: GQLAmountInterface; + quantity: GQLAmountInterface; + bundledIn: { + id: string; + }; + parent: { + id: string; + }; + signature: string; +} +export interface GQLTransactionResponse { + transaction: GQLTransaction; +} +export {}; +//# sourceMappingURL=gqlResult.d.ts.map \ No newline at end of file diff --git a/lib/types/legacy/gqlResult.d.ts.map b/lib/types/legacy/gqlResult.d.ts.map new file mode 100644 index 00000000..28d25426 --- /dev/null +++ b/lib/types/legacy/gqlResult.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"gqlResult.d.ts","sourceRoot":"","sources":["../../../src/legacy/gqlResult.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,oBAAoB;IACnC,WAAW,EAAE,OAAO,CAAC;CACtB;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CAClB;AAGD,KAAK,WAAW,GAAG,MAAM,GAAG,MAAM,CAAC;AAEnC,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,C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AAiB,CAAC;IACzB,GAAG,EAAE,kBAAkB,CAAC;IACxB,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,SAAS,EAAE;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1B,MAAM,EAAE;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,sBAAsB;IACrC,WAAW,EAAE,cAAc,CAAC;CAC7B"} \ No newline at end of file diff --git a/lib/types/legacy/smartweave-global.d.ts b/lib/types/legacy/smartweave-global.d.ts new file mode 100644 index 00000000..73280bb6 --- /dev/null +++ b/lib/types/legacy/smartweave-global.d.ts @@ -0,0 +1,110 @@ +import Arweave from 'arweave'; +import { EvaluationOptions } from '../core/modules/StateEvaluator'; +import { GQLNodeInterface, GQLTagInterface, VrfData } from './gqlResult'; +import { SortKeyCache } from '../cache/SortKeyCache'; +import { SortKeyCacheRangeOptions } from '../cache/SortKeyCacheRangeOptions'; +import { InteractionState } from '../contract/states/InteractionState'; +/** + * + * This class is exposed as a global for contracts + * as 'SmartWeave' and provides an API for getting further + * information or using utility and crypto functions from + * inside the contracts execution. + * + * It provides an api: + * + * - SmartWeave.transaction.id + * - SmartWeave.transaction.reward + * - SmartWeave.block.height + * - SmartWeave.block.timestamp + * - etc + * + * and access to some of the arweave utils: + * - SmartWeave.arweave.utils + * - SmartWeave.arweave.crypto + * - SmartWeave.arweave.wallets + * - SmartWeave.arweave.ar + * + * as well as access to the potentially non-deterministic full client: + * - SmartWeave.unsafeClient + * + */ +export type TransactionOrigin = 'L1' | 'L2'; +export declare class SmartWeaveGlobal { + gasUsed: number; + gasLimit: number; + transaction: SWTransaction; + block: SWBlock; + vrf: SWVrf; + evaluationOptions: EvaluationOptions; + arweave: Pick; + contract: { + id: string; + owner: string; + }; + unsafeClient: Arweave; + baseArweaveUrl: string; + safeArweaveGet: (input: RequestInfo | URL, init?: RequestInit) => Promise; + contracts: { + readContractState: (contractId: string) => Promise; + viewContractState: (contractId: string, input: any) => Promise; + write: (contractId: string, input: any) => Promise; + refreshState: () => Promise; + }; + extensions: any; + _activeTx?: GQLNodeInterface; + caller?: string; + kv: KV; + constructor(arweave: Arweave, contract: { + id: string; + owner: string; + }, evaluationOptions: EvaluationOptions, interactionState: InteractionState, storage: SortKeyCache | null); + useGas(gas: number): void; + getBalance(address: string, height?: number): Promise; +} +export declare class SWTransaction { + private readonly smartWeaveGlobal; + constructor(smartWeaveGlobal: SmartWeaveGlobal); + get id(): string; + get owner(): string; + get target(): string; + get tags(): GQLTagInterface[]; + get sortKey(): string; + get dryRun(): boolean; + get quantity(): string; + get reward(): string; + get origin(): TransactionOrigin; +} +export declare class SWBlock { + private readonly smartWeaveGlobal; + constructor(smartWeaveGlobal: SmartWeaveGlobal); + get height(): number; + get indep_hash(): string; + get timestamp(): number; +} +export declare class SWVrf { + private readonly smartWeaveGlobal; + constructor(smartWeaveGlobal: SmartWeaveGlobal); + get data(): VrfData; + get value(): string; + randomInt(maxValue: number): number; +} +export declare class KV { + private readonly _storage; + private readonly _interactionState; + private readonly _transaction; + private readonly _contractTxId; + constructor(_storage: SortKeyCache | null, _interactionState: InteractionState, _transaction: SWTransaction, _contractTxId: string); + put(key: string, value: any): Promise; + get(key: string): Promise; + del(key: string): Promise; + keys(options?: SortKeyCacheRangeOptions): Promise; + kvMap(options?: SortKeyCacheRangeOptions): Promise>; + begin(): Promise; + commit(): Promise; + rollback(): Promise; + open(): Promise; + close(): Promise; + private checkStorageAvailable; +} +//# sourceMappingURL=smartweave-global.d.ts.map \ No newline at end of file diff --git a/lib/types/legacy/smartweave-global.d.ts.map b/lib/types/legacy/smartweave-global.d.ts.map new file mode 100644 index 00000000..d6fa01d4 --- /dev/null +++ b/lib/types/legacy/smartweave-global.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"smartweave-global.d.ts","sourceRoot":"","sources":["../../../src/legacy/smartweave-global.ts"],"names":[],"mappings":"AACA,OAAO,O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@@ -0,0 +1,2 @@ +export declare function arrayToHex(arr: Uint8Array): string; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/lib/types/legacy/utils.d.ts.map b/lib/types/legacy/utils.d.ts.map new file mode 100644 index 00000000..4d040929 --- /dev/null +++ b/lib/types/legacy/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/legacy/utils.ts"],"names":[],"mappings":"AAAA,wBAAgB,UAAU,CAAC,GAAG,EAAE,UAAU,UAMzC"} \ No newline at end of file diff --git a/lib/types/logging/Benchmark.d.ts b/lib/types/logging/Benchmark.d.ts new file mode 100644 index 00000000..559797f3 --- /dev/null +++ b/lib/types/logging/Benchmark.d.ts @@ -0,0 +1,10 @@ +export declare class Benchmark { + static measure(): Benchmark; + private constructor(); + private start; + private end; + reset(): void; + stop(): void; + elapsed(rawValue?: boolean): string | number; +} +//# sourceMappingURL=Benchmark.d.ts.map \ No newline at end of file diff --git a/lib/types/logging/Benchmark.d.ts.map b/lib/types/logging/Benchmark.d.ts.map new file mode 100644 index 00000000..f2f781be --- /dev/null +++ b/lib/types/logging/Benchmark.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Benchmark.d.ts","sourceRoot":"","sources":["../../../src/logging/Benchmark.ts"],"names":[],"mappings":"AAAA,qBAAa,SAAS;WACN,OAAO,IAAI,SAAS;IAIlC,OAAO;IAIP,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,GAAG,CAAQ;IAEZ,KAAK;IAKL,IAAI;IAIJ,OAAO,CAAC,QAAQ,UAAQ,GAAG,MAAM,GAAG,MAAM;CAQlD"} \ No newline at end of file diff --git a/lib/types/logging/LoggerFactory.d.ts b/lib/types/logging/LoggerFactory.d.ts new file mode 100644 index 00000000..b6289d4c --- /dev/null +++ b/lib/types/logging/LoggerFactory.d.ts @@ -0,0 +1,18 @@ +import { LogLevel } from './LoggerSettings'; +import { WarpLogger } from './WarpLogger'; +export interface ILoggerFactory { + setOptions(newOptions: any, moduleName?: string): void; + getOptions(moduleName?: string): any; + logLevel(level: LogLevel, moduleName?: string): void; + create(moduleName?: string): WarpLogger; +} +export declare class LoggerFactory implements ILoggerFactory { + static INST: ILoggerFactory; + private constructor(); + setOptions(newOptions: any, moduleName?: string): void; + getOptions(moduleName?: string): any; + logLevel(level: LogLevel, moduleName?: string): void; + create(moduleName?: string): WarpLogger; + static use(logger: ILoggerFactory): void; +} +//# sourceMappingURL=LoggerFactory.d.ts.map \ No newline at end of file diff --git a/lib/types/logging/LoggerFactory.d.ts.map b/lib/types/logging/LoggerFactory.d.ts.map new file mode 100644 index 00000000..1d266e7c --- /dev/null +++ b/lib/types/logging/LoggerFactory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"LoggerFactory.d.ts","sourceRoot":"","sources":["../../../src/logging/LoggerFactory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG1C,MAAM,WAAW,cAAc;IAE7B,UAAU,CAAC,UAAU,EAAE,GAAG,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAGvD,UAAU,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;IAErC,QAAQ,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAErD,MAAM,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;CACzC;AAED,qBAAa,aAAc,YAAW,cAAc;IAClD,MAAM,CAAC,IAAI,EAAE,cAAc,CAA8B;IAEzD,OAAO;IAKP,UAAU,CAAC,UAAU,EAAE,GAAG,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;IAKtD,UAAU,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,GAAG;IAIpC,QAAQ,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE,MAAM;IAI7C,MAAM,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,UAAU;IAIvC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,cAAc;CAGlC"} \ No newline at end of file diff --git a/lib/types/logging/LoggerSettings.d.ts b/lib/types/logging/LoggerSettings.d.ts new file mode 100644 index 00000000..15654c6d --- /dev/null +++ b/lib/types/logging/LoggerSettings.d.ts @@ -0,0 +1,19 @@ +export declare const LogLevelOrder: { + silly: number; + trace: number; + debug: number; + info: number; + warn: number; + error: number; + fatal: number; + none: number; +}; +/** + * Log level names (silly - none) + */ +export type LogLevel = 'silly' | 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'none'; +export interface LoggerSettings { + minLevel: LogLevel; +} +export declare function lvlToOrder(logLevel: LogLevel): number; +//# sourceMappingURL=LoggerSettings.d.ts.map \ No newline at end of file diff --git a/lib/types/logging/LoggerSettings.d.ts.map b/lib/types/logging/LoggerSettings.d.ts.map new file mode 100644 index 00000000..ee6d8688 --- /dev/null +++ b/lib/types/logging/LoggerSettings.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"LoggerSettings.d.ts","sourceRoot":"","sources":["../../../src/logging/LoggerSettings.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,aAAa;;;;;;;;;CASzB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;AAElG,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED,wBAAgB,UAAU,CAAC,QAAQ,EAAE,QAAQ,UAE5C"} \ No newline at end of file diff --git a/lib/types/logging/WarpLogger.d.ts b/lib/types/logging/WarpLogger.d.ts new file mode 100644 index 00000000..7bac1d31 --- /dev/null +++ b/lib/types/logging/WarpLogger.d.ts @@ -0,0 +1,10 @@ +export interface WarpLogger { + fatal(message?: any, ...optionalParams: any[]): void; + error(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; + info(message?: any, ...optionalParams: any[]): void; + debug(message?: any, ...optionalParams: any[]): void; + trace(message?: any, ...optionalParams: any[]): void; + silly(message?: any, ...optionalParams: any[]): void; +} +//# sourceMappingURL=WarpLogger.d.ts.map \ No newline at end of file diff --git a/lib/types/logging/WarpLogger.d.ts.map b/lib/types/logging/WarpLogger.d.ts.map new file mode 100644 index 00000000..f5322414 --- /dev/null +++ b/lib/types/logging/WarpLogger.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WarpLogger.d.ts","sourceRoot":"","sources":["../../../src/logging/WarpLogger.ts"],"names":[],"mappings":"AACA,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAErD,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAErD,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAEpD,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAEpD,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAErD,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAErD,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;CACtD"} \ No newline at end of file diff --git a/lib/types/logging/web/ConsoleLogger.d.ts b/lib/types/logging/web/ConsoleLogger.d.ts new file mode 100644 index 00000000..a62efaac --- /dev/null +++ b/lib/types/logging/web/ConsoleLogger.d.ts @@ -0,0 +1,19 @@ +import { LoggerSettings, LogLevel } from '../../logging/LoggerSettings'; +import { WarpLogger } from '../../logging/WarpLogger'; +export declare class ConsoleLogger implements WarpLogger { + private readonly moduleName; + settings: LoggerSettings; + constructor(moduleName: any, settings: LoggerSettings); + trace(message?: any, ...optionalParams: any[]): void; + error(message?: any, ...optionalParams: any[]): void; + info(message?: any, ...optionalParams: any[]): void; + silly(message?: any, ...optionalParams: any[]): void; + debug(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + fatal(message?: any, ...optionalParams: any[]): void; + shouldLog(logLevel: LogLevel): boolean; + setSettings(settings: LoggerSettings): void; + message(lvl: LogLevel, message: string): string; +} +//# sourceMappingURL=ConsoleLogger.d.ts.map \ No newline at end of file diff --git a/lib/types/logging/web/ConsoleLogger.d.ts.map b/lib/types/logging/web/ConsoleLogger.d.ts.map new file mode 100644 index 00000000..d63fbadb --- /dev/null +++ b/lib/types/logging/web/ConsoleLogger.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ConsoleLogger.d.ts","sourceRoot":"","sources":["../../../../src/logging/web/ConsoleLogger.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAc,MAAM,8BAA8B,CAAC;AACpF,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAEtD,qBAAa,aAAc,YAAW,UAAU;IAClC,OAAO,CAAC,QAAQ,CAAC,UAAU;IAAS,QAAQ,EAAE,cAAc;gBAA3C,UAAU,KAAA,EAAS,QAAQ,EAAE,cAAc;IAExE,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI;IAOpD,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI;IAMpD,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI;IAMnD,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI;IAOpD,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI;IAMpD,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI;IAMnD,GAAG,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI;IAMlD,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,EAAE,GAAG,IAAI;IAMpD,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO;IAItC,WAAW,CAAC,QAAQ,EAAE,cAAc,GAAG,IAAI;IAI3C,OAAO,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM;CAGhD"} \ No newline at end of file diff --git a/lib/types/logging/web/ConsoleLoggerFactory.d.ts b/lib/types/logging/web/ConsoleLoggerFactory.d.ts new file mode 100644 index 00000000..80c1adc2 --- /dev/null +++ b/lib/types/logging/web/ConsoleLoggerFactory.d.ts @@ -0,0 +1,14 @@ +import { LoggerSettings, LogLevel } from '../LoggerSettings'; +import { ILoggerFactory } from '../../logging/LoggerFactory'; +import { WarpLogger } from '../../logging/WarpLogger'; +export declare class ConsoleLoggerFactory implements ILoggerFactory { + private registeredLoggers; + private readonly registeredOptions; + private defOptions; + constructor(); + setOptions(newOptions: LoggerSettings, moduleName?: string): void; + getOptions(moduleName?: string): LoggerSettings; + logLevel(level: LogLevel, moduleName?: string): void; + create(moduleName?: string): WarpLogger; +} +//# sourceMappingURL=ConsoleLoggerFactory.d.ts.map \ No newline at end of file diff --git a/lib/types/logging/web/ConsoleLoggerFactory.d.ts.map b/lib/types/logging/web/ConsoleLoggerFactory.d.ts.map new file mode 100644 index 00000000..57f945bc --- /dev/null +++ b/lib/types/logging/web/ConsoleLoggerFactory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ConsoleLoggerFactory.d.ts","sourceRoot":"","sources":["../../../../src/logging/web/ConsoleLoggerFactory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAEtD,qBAAa,oBAAqB,YAAW,cAAc;IACzD,OAAO,CAAC,iBAAiB,CAA+C;IACxE,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAgD;IAElF,OAAO,CAAC,UAAU,CAEhB;;IASF,UAAU,CAAC,UAAU,EAAE,cAAc,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;IA+BjE,UAAU,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,cAAc;IAe/C,QAAQ,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE,MAAM;IAK7C,MAAM,CAAC,UAAU,SAAQ,GAAG,UAAU;CAOvC"} \ No newline at end of file diff --git a/lib/types/plugins/DebuggableExecutorFactor.d.ts b/lib/types/plugins/DebuggableExecutorFactor.d.ts new file mode 100644 index 00000000..388ea037 --- /dev/null +++ b/lib/types/plugins/DebuggableExecutorFactor.d.ts @@ -0,0 +1,22 @@ +import { ContractCache, ContractDefinition, SrcCache } from '../core/ContractDefinition'; +import { ExecutorFactory } from '../core/modules/ExecutorFactory'; +import { EvaluationOptions } from '../core/modules/StateEvaluator'; +import { Warp } from '../core/Warp'; +import { InteractionState } from '../contract/states/InteractionState'; +/** + * An ExecutorFactory that allows to substitute original contract's source code. + * Useful for debugging purposes (e.g. to quickly add some console.logs in contract + * or to test a fix or a new feature - without the need of redeploying a new contract on Arweave); + * + * Not meant to be used in production env! ;-) + */ +export declare class DebuggableExecutorFactory implements ExecutorFactory { + private readonly baseImplementation; + private readonly sourceCode; + constructor(baseImplementation: ExecutorFactory, sourceCode: { + [key: string]: string; + }); + create(contractDefinition: ContractDefinition, evaluationOptions: EvaluationOptions, warp: Warp, interactionState: InteractionState): Promise; + checkWhiteListContractSources(contractDefinition: SrcCache & ContractCache, evaluationOptions: EvaluationOptions): void; +} +//# sourceMappingURL=DebuggableExecutorFactor.d.ts.map \ No newline at end of file diff --git a/lib/types/plugins/DebuggableExecutorFactor.d.ts.map b/lib/types/plugins/DebuggableExecutorFactor.d.ts.map new file mode 100644 index 00000000..bc910aa5 --- /dev/null +++ b/lib/types/plugins/DebuggableExecutorFactor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"DebuggableExecutorFactor.d.ts","sourceRoot":"","sources":["../../../src/plugins/DebuggableExecutorFactor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAEvE;;;;;;GAMG;AACH,qBAAa,yBAAyB,CAAC,GAAG,CAAE,YAAW,eAAe,CAAC,GAAG,CAAC;IAEvE,OAAO,CAAC,QAAQ,CAAC,kBAAkB;IAEnC,OAAO,CAAC,QAAQ,CAAC,UAAU;gBAFV,kBAAkB,EAAE,eAAe,CAAC,GAAG,CAAC,EAExC,UAAU,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE;IAGlD,MAAM,CAAC,KAAK,EAChB,kBAAkB,EAAE,kBAAkB,CAAC,KAAK,CAAC,EAC7C,iBAAiB,EAAE,iBAAiB,EACpC,IAAI,EAAE,IAAI,EACV,gBAAgB,EAAE,gBAAgB,GACjC,OAAO,CAAC,GAAG,CAAC;IAWf,6BAA6B,CAAC,KAAK,EACjC,kBAAkB,EAAE,QAAQ,GAAG,aAAa,CAAC,KAAK,CAAC,EACnD,iBAAiB,EAAE,iBAAiB,GACnC,IAAI;CAGR"} \ No newline at end of file diff --git a/lib/types/plugins/Evolve.d.ts b/lib/types/plugins/Evolve.d.ts new file mode 100644 index 00000000..42facc99 --- /dev/null +++ b/lib/types/plugins/Evolve.d.ts @@ -0,0 +1,10 @@ +import { ExecutionContext } from '../core/ExecutionContext'; +import { ExecutionContextModifier } from '../core/ExecutionContextModifier'; +import { HandlerApi } from '../core/modules/impl/HandlerExecutorFactory'; +export declare class Evolve implements ExecutionContextModifier { + private readonly logger; + constructor(); + modify(state: State, executionContext: ExecutionContext>): Promise>>; + static evolvedSrcTxId(state: unknown): string | undefined; +} +//# sourceMappingURL=Evolve.d.ts.map \ No newline at end of file diff --git a/lib/types/plugins/Evolve.d.ts.map b/lib/types/plugins/Evolve.d.ts.map new file mode 100644 index 00000000..a8be0e6d --- /dev/null +++ b/lib/types/plugins/Evolve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Evolve.d.ts","sourceRoot":"","sources":["../../../src/plugins/Evolve.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAE5E,OAAO,EAAE,UAAU,EAAE,MAAM,6CAA6C,CAAC;AAYzE,qBAAa,MAAO,YAAW,wBAAwB;IACrD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuC;;IAMxD,MAAM,CAAC,KAAK,EAChB,KAAK,EAAE,KAAK,EACZ,gBAAgB,EAAE,gBAAgB,CAAC,KAAK,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC,GAC3D,OAAO,CAAC,gBAAgB,CAAC,KAAK,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAoDtD,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS;CAuB1D"} \ No newline at end of file diff --git a/lib/types/utils/ArweaveWrapper.d.ts b/lib/types/utils/ArweaveWrapper.d.ts new file mode 100644 index 00000000..1faf5ebe --- /dev/null +++ b/lib/types/utils/ArweaveWrapper.d.ts @@ -0,0 +1,27 @@ +/// +import { BlockData, NetworkInfoInterface, Transaction } from './types/arweave-types'; +import { Warp } from '../core/Warp'; +export declare class ArweaveWrapper { + private readonly warp; + private readonly logger; + private readonly baseUrl; + constructor(warp: Warp); + warpGwInfo(): Promise; + warpGwBlock(): Promise; + info(): Promise; + /** + * + * @param query graphql query string + * @param variables variables depends on provided query + * @returns axios-like (for backwards compatibility..) response from graphql + */ + gql(query: string, variables: unknown): Promise<{ + data: any; + status: number; + }>; + tx(id: string): Promise; + txData(id: string): Promise; + txDataString(id: string): Promise; + private doFetchInfo; +} +//# sourceMappingURL=ArweaveWrapper.d.ts.map \ No newline at end of file diff --git a/lib/types/utils/ArweaveWrapper.d.ts.map b/lib/types/utils/ArweaveWrapper.d.ts.map new file mode 100644 index 00000000..994e670f --- /dev/null +++ b/lib/types/utils/ArweaveWrapper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ArweaveWrapper.d.ts","sourceRoot":"","sources":["../../../src/utils/ArweaveWrapper.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAGpC,qBAAa,cAAc;IAKb,OAAO,CAAC,QAAQ,CAAC,IAAI;IAJjC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA+C;IAEtE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;gBAEI,IAAI,EAAE,IAAI;IAMjC,UAAU,IAAI,OAAO,CAAC,oBAAoB,CAAC;IAM3C,WAAW,IAAI,OAAO,CAAC,SAAS,CAAC;IAKjC,IAAI,IAAI,OAAO,CAAC,oBAAoB,CAAC;IAI3C;;;;;OAKG;IAEG,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IA6B9E,EAAE,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAiBpC,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAiBnC,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;YAKjC,WAAW;CAG1B"} \ No newline at end of file diff --git a/lib/types/utils/types/arweave-types.d.ts b/lib/types/utils/types/arweave-types.d.ts new file mode 100644 index 00000000..44907a11 --- /dev/null +++ b/lib/types/utils/types/arweave-types.d.ts @@ -0,0 +1,160 @@ +export interface TransactionConfirmedData { + block_indep_hash: string; + block_height: number; + number_of_confirmations: number; +} +export interface TransactionStatusResponse { + status: number; + confirmed: TransactionConfirmedData | null; +} +export interface TransactionInterface { + format: number; + id: string; + last_tx: string; + owner: string; + tags: Tag[]; + target: string; + quantity: string; + data: Uint8Array; + reward: string; + signature: string; + data_size: string; + data_root: string; +} +export interface Chunk { + dataHash: Uint8Array; + minByteRange: number; + maxByteRange: number; +} +export interface Proof { + offset: number; + proof: Uint8Array; +} +declare class BaseObject { + [key: string]: any; + get(field: string): string; + get(field: string, options: { + decode: true; + string: false; + }): Uint8Array; + get(field: string, options: { + decode: true; + string: true; + }): string; +} +export declare class Transaction extends BaseObject implements TransactionInterface { + readonly format: number; + id: string; + readonly last_tx: string; + owner: string; + tags: Tag[]; + readonly target: string; + readonly quantity: string; + readonly data_size: string; + data: Uint8Array; + data_root: string; + reward: string; + signature: string; + chunks?: { + data_root: Uint8Array; + chunks: Chunk[]; + proofs: Proof[]; + }; + constructor(attributes?: Partial); + addTag(name: string, value: string): void; + toJSON(): { + format: number; + id: string; + last_tx: string; + owner: string; + tags: Tag[]; + target: string; + quantity: string; + data: string; + data_size: string; + data_root: string; + data_tree: any; + reward: string; + signature: string; + }; + setOwner(owner: string): void; + setSignature({ id, owner, reward, tags, signature }: { + id: string; + owner: string; + reward?: string; + tags?: Tag[]; + signature: string; + }): void; + prepareChunks(data: Uint8Array): Promise; + getChunk(idx: number, data: Uint8Array): { + data_root: string; + data_size: string; + data_path: string; + offset: string; + chunk: string; + }; + getSignatureData(): Promise; +} +export declare class Tag extends BaseObject { + readonly name: string; + readonly value: string; + constructor(name: string, value: string, decode?: boolean); +} +export interface JWKPublicInterface { + kty: string; + e: string; + n: string; +} +export interface JWKInterface extends JWKPublicInterface { + d?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; +} +export interface CreateTransactionInterface { + format: number; + last_tx: string; + owner: string; + tags: Tag[]; + target: string; + quantity: string; + data: string | Uint8Array | ArrayBuffer; + data_size: string; + data_root: string; + reward: string; +} +export interface BlockData { + nonce: string; + previous_block: string; + timestamp: number; + last_retarget: number; + diff: string; + height: number; + hash: string; + indep_hash: string; + txs: string[]; + tx_root: string; + wallet_list: string; + reward_addr: string; + tags: Tag[]; + reward_pool: number; + weave_size: number; + block_size: number; + cumulative_diff: string; + hash_list_merkle: string; +} +export interface NetworkInfoInterface { + network: string; + version: number; + release: number; + height: number; + current: string; + blocks: number; + peers: number; + queue_length: number; + node_state_latency: number; +} +export {}; +//# sourceMappingURL=arweave-types.d.ts.map \ No newline at end of file diff --git a/lib/types/utils/types/arweave-types.d.ts.map b/lib/types/utils/types/arweave-types.d.ts.map new file mode 100644 index 00000000..7ee1dad4 --- /dev/null +++ b/lib/types/utils/types/arweave-types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"arweave-types.d.ts","sourceRoot":"","sources":["../../../../src/utils/types/arweave-types.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,wBAAwB;IACvC,gBAAgB,EAAE,MAAM,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,uBAAuB,EAAE,MAAM,CAAC;CACjC;AACD,MAAM,WAAW,yBAAyB;IACxC,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,wBAAwB,GAAG,IAAI,CAAC;CAC5C;AAED,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,UAAU,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,KAAK;IACpB,QAAQ,EAAE,UAAU,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;CACtB;AACD,MAAM,WAAW,KAAK;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,UAAU,CAAC;CACnB;AAED,cAAM,UAAU;IAEd,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;IAEZ,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAC1B,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,MAAM,EAAE,IAAI,CAAC;QAAC,MAAM,EAAE,KAAK,CAAA;KAAE,GAAG,UAAU;IAC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M,EAAE,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,eAAe,EAAE,MAAM,CAAC;IACxB,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AACD,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;IACrB,kBAAkB,EAAE,MAAM,CAAC;CAC5B"} \ No newline at end of file diff --git a/lib/types/utils/utils.d.ts b/lib/types/utils/utils.d.ts new file mode 100644 index 00000000..cd47c60e --- /dev/null +++ b/lib/types/utils/utils.d.ts @@ -0,0 +1,25 @@ +/// +export declare const sleep: (ms: number) => Promise; +export declare const safeParseInt: (str: string) => number; +export declare const deepCopy: (input: unknown) => any; +export declare const mapReplacer: (key: unknown, value: unknown) => unknown; +export declare const mapReviver: (key: unknown, value: any) => any; +export declare const asc: (a: number, b: number) => number; +export declare const ascS: (a: string, b: string) => number; +export declare const desc: (a: number, b: number) => number; +export declare const descS: (a: string, b: string) => number; +export declare function timeout(s: number): { + timeoutId: number; + timeoutPromise: Promise; +}; +export declare function stripTrailingSlash(str: string): string; +export declare function indent(callDepth: number): string; +export declare function bufToBn(buf: Buffer): bigint; +export declare const isBrowser: Function; +export declare class NetworkCommunicationError extends Error { + readonly error: T; + constructor(error: T); +} +export declare function getJsonResponse(response: Promise): Promise; +export declare function safeGet(input: RequestInfo | URL, init?: RequestInit): Promise; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/lib/types/utils/utils.d.ts.map b/lib/types/utils/utils.d.ts.map new file mode 100644 index 00000000..0dab0d86 --- /dev/null +++ b/lib/types/utils/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/utils/utils.ts"],"names":[],"mappings":";AAKA,eAAO,MAAM,KAAK,OAAQ,MAAM,KAAG,QAAQ,IAAI,CAE9C,CAAC;AAEF,eAAO,MAAM,YAAY,QAAS,MAAM,KAAG,MAQ1C,CAAC;AAEF,eAAO,MAAM,QAAQ,UAAW,OAAO,KAAG,GAEzC,CAAC;AAEF,eAAO,MAAM,WAAW,QAAS,OAAO,SAAS,OAAO,YASvD,CAAC;AAEF,eAAO,MAAM,UAAU,QAAS,OAAO,SAAS,GAAG,QAOlD,CAAC;AAEF,eAAO,MAAM,GAAG,MAAO,MAAM,KAAK,MAAM,KAAG,MAAe,CAAC;AAE3D,eAAO,MAAM,IAAI,MAAO,MAAM,KAAK,MAAM,KAAG,MAAiB,CAAC;AAE9D,eAAO,MAAM,IAAI,MAAO,MAAM,KAAK,MAAM,KAAG,MAAe,CAAC;AAE5D,eAAO,MAAM,KAAK,MAAO,MAAM,KAAK,MAAM,KAAG,MAAiB,CAAC;AAE/D,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;CAAE,CAYtF;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,UAE7C;AAED,wBAAgB,MAAM,CAAC,SAAS,EAAE,MAAM,UAEvC;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,UAalC;AAED,eAAO,MAAM,SAAS,UAAsE,CAAC;AAE7F,qBAAa,yBAAyB,CAAC,CAAC,CAAE,SAAQ,KAAK;IACzC,QAAQ,CAAC,KAAK,EAAE,CAAC;gB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