diff --git a/assets/ccip-BUGx8scz.js b/assets/ccip-BD4-E_uZ.js similarity index 99% rename from assets/ccip-BUGx8scz.js rename to assets/ccip-BD4-E_uZ.js index 1a949481..046532ef 100644 --- a/assets/ccip-BUGx8scz.js +++ b/assets/ccip-BD4-E_uZ.js @@ -1,4 +1,4 @@ -import { f as BaseError, h as getUrl, s as stringify, i as decodeErrorResult, j as isAddressEqual, k as call, l as concat, m as encodeAbiParameters, H as HttpRequestError, n as isHex } from "./index-eVNd97lK.js"; +import { f as BaseError, h as getUrl, s as stringify, i as decodeErrorResult, j as isAddressEqual, k as call, l as concat, m as encodeAbiParameters, H as HttpRequestError, n as isHex } from "./index-CaRdSd9P.js"; class OffchainLookupError extends BaseError { constructor({ callbackSelector, cause, data, extraData, sender, urls }) { var _a; diff --git a/assets/hooks.module-D1qE_AJG.js b/assets/hooks.module-BnzzsFhJ.js similarity index 99% rename from assets/hooks.module-D1qE_AJG.js rename to assets/hooks.module-BnzzsFhJ.js index 5211b514..83757b91 100644 --- a/assets/hooks.module-D1qE_AJG.js +++ b/assets/hooks.module-BnzzsFhJ.js @@ -1,5 +1,5 @@ -import { p as process$1, c as commonjsGlobal, B as Buffer$7, a as getAugmentedNamespace } from "./index-eVNd97lK.js"; -import { e as eventsExports, r as require$$0$1, a as require$$0$2, i as inherits_browserExports } from "./inherits_browser-Dwap8BoW.js"; +import { p as process$1, c as commonjsGlobal, B as Buffer$7, a as getAugmentedNamespace } from "./index-CaRdSd9P.js"; +import { e as eventsExports, r as require$$0$1, a as require$$0$2, i as inherits_browserExports } from "./inherits_browser-D3e42oki.js"; var readableBrowser = { exports: {} }; var streamBrowser = eventsExports.EventEmitter; var buffer_list; diff --git a/assets/index-CeEs98iF.js b/assets/index-BT7PrVMP.js similarity index 99% rename from assets/index-CeEs98iF.js rename to assets/index-BT7PrVMP.js index 857137d3..4b78e811 100644 --- a/assets/index-CeEs98iF.js +++ b/assets/index-BT7PrVMP.js @@ -1,6 +1,6 @@ -import { c as commonjsGlobal, B as Buffer, a as getAugmentedNamespace, p as process$1, t as tslib_es6, e as eventemitter3Exports, g as getDefaultExportFromCjs } from "./index-eVNd97lK.js"; -import { r as require$$0$1, e as eventsExports } from "./inherits_browser-Dwap8BoW.js"; -import { s as sha_jsExports, a as require$$1$1, b as require$$2, r as require$$0$2, j as js } from "./hooks.module-D1qE_AJG.js"; +import { c as commonjsGlobal, B as Buffer, a as getAugmentedNamespace, p as process$1, t as tslib_es6, e as eventemitter3Exports, g as getDefaultExportFromCjs } from "./index-CaRdSd9P.js"; +import { r as require$$0$1, e as eventsExports } from "./inherits_browser-D3e42oki.js"; +import { s as sha_jsExports, a as require$$1$1, b as require$$2, r as require$$0$2, j as js } from "./hooks.module-BnzzsFhJ.js"; var dist$5 = {}; var CoinbaseWalletSDK$1 = {}; var walletLogo$1 = {}; diff --git a/assets/index-CN13kjv_.js b/assets/index-C_hKV8dq.js similarity index 99% rename from assets/index-CN13kjv_.js rename to assets/index-C_hKV8dq.js index 9e5449e6..870996b1 100644 --- a/assets/index-CN13kjv_.js +++ b/assets/index-C_hKV8dq.js @@ -1,5 +1,5 @@ -import { n as ne$1, s as se$1, T as T$2, t as te$1, a as a$2, o as oe$1, R as R$1, p as p$1, y as y$1 } from "./index-DjpO9esu.js"; -import "./index-eVNd97lK.js"; +import { n as ne$1, s as se$1, T as T$2, t as te$1, a as a$2, o as oe$1, R as R$1, p as p$1, y as y$1 } from "./index-Dh05DiNn.js"; +import "./index-CaRdSd9P.js"; function addUniqueItem(array, item) { array.indexOf(item) === -1 && array.push(item); } diff --git a/assets/index-eVNd97lK.js b/assets/index-CaRdSd9P.js similarity index 98% rename from assets/index-eVNd97lK.js rename to assets/index-CaRdSd9P.js index 750bf1bc..2efe5232 100644 --- a/assets/index-eVNd97lK.js +++ b/assets/index-CaRdSd9P.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-CnSoKQxV.js","./hooks.module-D1qE_AJG.js","./inherits_browser-Dwap8BoW.js","./index-CeEs98iF.js","./index.es-B9PQPdl4.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-wr_HNsXy.js","./hooks.module-BnzzsFhJ.js","./inherits_browser-D3e42oki.js","./index-BT7PrVMP.js","./index.es-cfKIWXoD.js"])))=>i.map(i=>d[i]); var __defProp = Object.defineProperty; var __typeError = (msg) => { throw TypeError(msg); @@ -18,7 +18,7 @@ var __privateWrapper = (obj, member, setter, getter) => ({ return __privateGet(obj, member, getter); } }); -var _listener, _listeners, _cancelled, _allowInsecure, _gzip, _headers, _method, _timeout, _url, _body, _bodyType, _creds, _preflight, _process, _retry, _signal, _throttle, _getUrlFunc, _FetchRequest_instances, send_fn, _statusCode, _statusMessage, _headers2, _body2, _request, _error, _format, _val, _tens, _FixedNumber_instances, checkFormat_fn, checkValue_fn, add_fn, sub_fn, mul_fn, div_fn, _names, _data2, _dataLength, _Writer_instances, writeData_fn, _data3, _offset, _bytesRead, _parent, _maxInflation, _Reader_instances, incrementBytesRead_fn, peekBytes_fn, _r, _s, _v, _networkV, _privateKey, _options, _type, _to, _data4, _nonce, _gasLimit, _gasPrice, _maxPriorityFeePerGas, _maxFeePerGas, _value, _chainId2, _sig, _accessList, _maxFeePerBlobGas, _blobVersionedHashes, _kzg, _blobs, _Transaction_instances, getSerialized_fn, _types, _fullTypes, _encoderCache, _TypedDataEncoder_instances, getEncoder_fn, _offset2, _tokens, _TokenString_instances, subTokenString_fn, _ParamType_instances, walkAsync_fn, _AbiCoder_instances, getCoder_fn, _errors, _events, _functions, _abiCoder, _Interface_instances, getFunction_fn, getEvent_fn, _transactions, _logs, _startBlock, _iface, _iface2, _filter, _a, _supports2544, _resolver, _EnsResolver_instances, fetch_fn, _EnsResolver_static, getResolver_fn, _feeDataFunc, _url2, _processFunc, _name, _chainId3, _plugins, _provider, _poller, _interval, _blockNumber, _PollingBlockSubscriber_instances, poll_fn, _provider2, _poll, _running, _tag, _lastBlock, _filter2, _hash, _provider3, _filter3, _poller2, _running2, _blockNumber2, _PollingEventSubscriber_instances, poll_fn2, _subs, _plugins2, _pausedState, _destroyed, _networkPromise, _anyNetwork, _performCache, _lastBlockNumber, _nextTimer, _timers, _disableCcipRead, _options2, _AbstractProvider_instances, perform_fn, call_fn, checkNetwork_fn, getAccountValue_fn, getBlock_fn, hasSub_fn, getSub_fn, _VoidSigner_instances, throwUnsupported_fn, _provider4, _filterIdPromise, _poller3, _running3, _network, _hault, _FilterIdSubscriber_instances, poll_fn3, teardown_fn, _event, _options3, _nextId2, _payloads, _drainTimer, _notReady, _network2, _pendingDetectNetwork, _JsonRpcApiProvider_instances, scheduleDrain_fn, _pollingInterval, _connect, _b, _plugin, _provider5, _filter4, _filterId, _paused, _emitPromise, _logFilter, _callbacks, _subs2, _pending, _connect2, _websocket, _configs, _height, _initialSyncPromise, _FallbackProvider_instances, getNextConfig_fn, addRunner_fn, initialSync_fn, checkQuorum_fn, waitForQuorum_fn, _noncePromise, _delta, _request2, _signingKey, _data5, _checksum, _words, _WordlistOwl_instances, loadWords_fn, _HDNodeWallet_instances, account_fn, _HDNodeWallet_static, fromSeed_fn, _Wallet_static, _c, fromAccount_fn, _accent, _focused, _cleanup, _setup, _d, _online, _cleanup2, _setup2, _e, _gcTimeout, _f, _initialState, _revertState, _cache, _retryer, _defaultOptions, _abortSignalConsumed, _Query_instances, dispatch_fn, _g, _queries, _h, _observers, _mutationCache, _retryer2, _Mutation_instances, dispatch_fn2, _i, _mutations, _mutationId, _j, _queryCache, _mutationCache2, _defaultOptions2, _queryDefaults, _mutationDefaults, _mountCount, _unsubscribeFocus, _unsubscribeOnline, _k, _client, _currentQuery, _currentQueryInitialState, _currentResult, _currentResultState, _currentResultOptions, _selectError, _selectFn, _selectResult, _lastQueryWithDefinedData, _staleTimeoutId, _refetchIntervalId, _currentRefetchInterval, _trackedProps, _QueryObserver_instances, executeFetch_fn, updateStaleTimeout_fn, computeRefetchInterval_fn, updateRefetchInterval_fn, updateTimers_fn, clearStaleTimeout_fn, clearRefetchInterval_fn, updateQuery_fn, notify_fn, _l, _client2, _currentResult2, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn2, _m; +var _focused, _cleanup, _setup, _a, _online, _cleanup2, _setup2, _b, _gcTimeout, _c, _initialState, _revertState, _cache, _retryer, _defaultOptions, _abortSignalConsumed, _Query_instances, dispatch_fn, _d, _queries, _e, _observers, _mutationCache, _retryer2, _Mutation_instances, dispatch_fn2, _f, _mutations, _mutationId, _g, _queryCache, _mutationCache2, _defaultOptions2, _queryDefaults, _mutationDefaults, _mountCount, _unsubscribeFocus, _unsubscribeOnline, _h, _client, _currentQuery, _currentQueryInitialState, _currentResult, _currentResultState, _currentResultOptions, _selectError, _selectFn, _selectResult, _lastQueryWithDefinedData, _staleTimeoutId, _refetchIntervalId, _currentRefetchInterval, _trackedProps, _QueryObserver_instances, executeFetch_fn, updateStaleTimeout_fn, computeRefetchInterval_fn, updateRefetchInterval_fn, updateTimers_fn, clearStaleTimeout_fn, clearRefetchInterval_fn, updateQuery_fn, notify_fn, _i, _client2, _currentResult2, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn2, _j, _listener, _listeners, _cancelled, _allowInsecure, _gzip, _headers, _method, _timeout, _url, _body, _bodyType, _creds, _preflight, _process, _retry, _signal, _throttle, _getUrlFunc, _FetchRequest_instances, send_fn, _statusCode, _statusMessage, _headers2, _body2, _request, _error, _format, _val, _tens, _FixedNumber_instances, checkFormat_fn, checkValue_fn, add_fn, sub_fn, mul_fn, div_fn, _names, _data2, _dataLength, _Writer_instances, writeData_fn, _data3, _offset, _bytesRead, _parent, _maxInflation, _Reader_instances, incrementBytesRead_fn, peekBytes_fn, _r, _s, _v, _networkV, _privateKey, _options, _type, _to, _data4, _nonce, _gasLimit, _gasPrice, _maxPriorityFeePerGas, _maxFeePerGas, _value, _chainId2, _sig, _accessList, _maxFeePerBlobGas, _blobVersionedHashes, _kzg, _blobs, _Transaction_instances, getSerialized_fn, _types, _fullTypes, _encoderCache, _TypedDataEncoder_instances, getEncoder_fn, _offset2, _tokens, _TokenString_instances, subTokenString_fn, _ParamType_instances, walkAsync_fn, _AbiCoder_instances, getCoder_fn, _errors, _events, _functions, _abiCoder, _Interface_instances, getFunction_fn, getEvent_fn, _transactions, _logs, _startBlock, _iface, _iface2, _filter, _k, _supports2544, _resolver, _EnsResolver_instances, fetch_fn, _EnsResolver_static, getResolver_fn, _feeDataFunc, _url2, _processFunc, _name, _chainId3, _plugins, _provider, _poller, _interval, _blockNumber, _PollingBlockSubscriber_instances, poll_fn, _provider2, _poll, _running, _tag, _lastBlock, _filter2, _hash, _provider3, _filter3, _poller2, _running2, _blockNumber2, _PollingEventSubscriber_instances, poll_fn2, _subs, _plugins2, _pausedState, _destroyed, _networkPromise, _anyNetwork, _performCache, _lastBlockNumber, _nextTimer, _timers, _disableCcipRead, _options2, _AbstractProvider_instances, perform_fn, call_fn, checkNetwork_fn, getAccountValue_fn, getBlock_fn, hasSub_fn, getSub_fn, _VoidSigner_instances, throwUnsupported_fn, _provider4, _filterIdPromise, _poller3, _running3, _network, _hault, _FilterIdSubscriber_instances, poll_fn3, teardown_fn, _event, _options3, _nextId2, _payloads, _drainTimer, _notReady, _network2, _pendingDetectNetwork, _JsonRpcApiProvider_instances, scheduleDrain_fn, _pollingInterval, _connect, _l, _plugin, _provider5, _filter4, _filterId, _paused, _emitPromise, _logFilter, _callbacks, _subs2, _pending, _connect2, _websocket, _configs, _height, _initialSyncPromise, _FallbackProvider_instances, getNextConfig_fn, addRunner_fn, initialSync_fn, checkQuorum_fn, waitForQuorum_fn, _noncePromise, _delta, _request2, _signingKey, _data5, _checksum, _words, _WordlistOwl_instances, loadWords_fn, _HDNodeWallet_instances, account_fn, _HDNodeWallet_static, fromSeed_fn, _Wallet_static, _m, fromAccount_fn, _accent; function _mergeNamespaces(n2, m2) { for (var i = 0; i < m2.length; i++) { const e2 = m2[i]; @@ -24944,61240 +24944,60936 @@ const useMediaQuery = (queryInput, options = {}) => { }, [query, supportMatchMedia]); return match; }; -const abi$7 = [{ - inputs: [{ - internalType: "bytes32", - type: "bytes32" - }], - name: "getAlternativeSignature", - outputs: [{ - internalType: "string", - type: "string" - }], - stateMutability: "view", - type: "function" -}]; -var erc5719 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - abi: abi$7 -}); -const abi$6 = [{ - type: "function", - name: "isValidSignature", - constant: true, - inputs: [{ - type: "bytes32" - }, { - type: "bytes" - }], - outputs: [{ - type: "bytes4" - }], - payable: false, - stateMutability: "view" -}]; -const returns = { - isValidSignatureBytes32: "0x1626ba7e" +var Subscribable = class { + constructor() { + this.listeners = /* @__PURE__ */ new Set(); + this.subscribe = this.subscribe.bind(this); + } + subscribe(listener) { + this.listeners.add(listener); + this.onSubscribe(); + return () => { + this.listeners.delete(listener); + this.onUnsubscribe(); + }; + } + hasListeners() { + return this.listeners.size > 0; + } + onSubscribe() { + } + onUnsubscribe() { + } }; -var erc1271 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - abi: abi$6, - returns -}); -const abi$5 = [{ - inputs: [{ - internalType: "bytes", - name: "error", - type: "bytes" - }], - name: "ERC1271Revert", - type: "error" -}, { - inputs: [{ - internalType: "bytes", - name: "error", - type: "bytes" - }], - name: "ERC6492DeployFailed", - type: "error" -}, { - inputs: [{ - internalType: "address", - name: "_signer", - type: "address" - }, { - internalType: "bytes32", - name: "_hash", - type: "bytes32" - }, { - internalType: "bytes", - name: "_signature", - type: "bytes" - }], - name: "isValidSig", - outputs: [{ - internalType: "bool", - name: "", - type: "bool" - }], - stateMutability: "nonpayable", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_signer", - type: "address" - }, { - internalType: "bytes32", - name: "_hash", - type: "bytes32" - }, { - internalType: "bytes", - name: "_signature", - type: "bytes" - }, { - internalType: "bool", - name: "allowSideEffects", - type: "bool" - }, { - internalType: "bool", - name: "deployAlreadyDeployed", - type: "bool" - }], - name: "isValidSigImpl", - outputs: [{ - internalType: "bool", - name: "", - type: "bool" - }], - stateMutability: "nonpayable", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_signer", - type: "address" - }, { - internalType: "bytes32", - name: "_hash", - type: "bytes32" - }, { - internalType: "bytes", - name: "_signature", - type: "bytes" - }], - name: "isValidSigNoThrow", - outputs: [{ - internalType: "bool", - name: "", - type: "bool" - }], - stateMutability: "nonpayable", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_signer", - type: "address" - }, { - internalType: "bytes32", - name: "_hash", - type: "bytes32" - }, { - internalType: "bytes", - name: "_signature", - type: "bytes" - }], - name: "isValidSigWithSideEffects", - outputs: [{ - internalType: "bool", - name: "", - type: "bool" - }], - stateMutability: "nonpayable", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_signer", - type: "address" - }, { - internalType: "bytes32", - name: "_hash", - type: "bytes32" - }, { - internalType: "bytes", - name: "_signature", - type: "bytes" - }], - name: "isValidSigWithSideEffectsNoThrow", - outputs: [{ - internalType: "bool", - name: "", - type: "bool" - }], - stateMutability: "nonpayable", - type: "function" -}]; -var erc6492 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - abi: abi$5 -}); -const abi$4 = [{ - type: "function", - name: "deploy", - constant: false, - inputs: [{ - type: "address" - }, { - type: "bytes32" - }], - outputs: [], - payable: true, - stateMutability: "payable" -}]; -var factory = /* @__PURE__ */ Object.freeze({ - __proto__: null, - abi: abi$4 -}); -const abi$3 = [{ - type: "function", - name: "nonce", - constant: true, - inputs: [], - outputs: [{ - type: "uint256" - }], - payable: false, - stateMutability: "view" -}, { - type: "function", - name: "readNonce", - constant: true, - inputs: [{ - type: "uint256" - }], - outputs: [{ - type: "uint256" - }], - payable: false, - stateMutability: "view" -}, { - type: "function", - name: "updateImplementation", - constant: false, - inputs: [{ - type: "address" - }], - outputs: [], - payable: false, - stateMutability: "nonpayable" -}, { - type: "function", - name: "selfExecute", - constant: false, - inputs: [{ - components: [{ - type: "bool", - name: "delegateCall" - }, { - type: "bool", - name: "revertOnError" - }, { - type: "uint256", - name: "gasLimit" - }, { - type: "address", - name: "target" - }, { - type: "uint256", - name: "value" - }, { - type: "bytes", - name: "data" - }], - type: "tuple[]" - }], - outputs: [], - payable: false, - stateMutability: "nonpayable" -}, { - type: "function", - name: "execute", - constant: false, - inputs: [{ - components: [{ - type: "bool", - name: "delegateCall" - }, { - type: "bool", - name: "revertOnError" - }, { - type: "uint256", - name: "gasLimit" - }, { - type: "address", - name: "target" - }, { - type: "uint256", - name: "value" - }, { - type: "bytes", - name: "data" - }], - type: "tuple[]" - }, { - type: "uint256" - }, { - type: "bytes" - }], - outputs: [], - payable: false, - stateMutability: "nonpayable" -}, { - type: "function", - name: "createContract", - inputs: [{ - type: "bytes" - }], - payable: true, - stateMutability: "payable" -}, { - type: "function", - name: "setExtraImageHash", - constant: false, - inputs: [{ - type: "bytes32", - name: "imageHash" - }, { - type: "uint256", - name: "expiration" - }], - outputs: [], - payable: false, - stateMutability: "nonpayable" -}]; -var mainModule = /* @__PURE__ */ Object.freeze({ - __proto__: null, - abi: abi$3 -}); -const abi$2$1 = [{ - type: "function", - name: "updateImageHash", - constant: true, - inputs: [{ - type: "bytes32" - }], - outputs: [], - payable: false, - stateMutability: "view" -}, { - type: "function", - name: "imageHash", - constant: true, - inputs: [], - outputs: [{ - type: "bytes32" - }], - payable: false, - stateMutability: "view" -}]; -var mainModuleUpgradable = /* @__PURE__ */ Object.freeze({ - __proto__: null, - abi: abi$2$1 -}); -const abi$1$1 = [{ - inputs: [{ - internalType: "address", - name: "_factory", - type: "address" - }, { - internalType: "address", - name: "_mainModule", - type: "address" - }], - stateMutability: "nonpayable", - type: "constructor" -}, { - anonymous: false, - inputs: [{ - indexed: true, - internalType: "address", - name: "_wallet", - type: "address" - }, { - indexed: true, - internalType: "bytes32", - name: "_imageHash", - type: "bytes32" - }, { - indexed: false, - internalType: "uint256", - name: "_threshold", - type: "uint256" - }, { - indexed: false, - internalType: "bytes", - name: "_signers", - type: "bytes" - }], - name: "RequiredConfig", - type: "event" -}, { - anonymous: false, - inputs: [{ - indexed: true, - internalType: "address", - name: "_wallet", - type: "address" - }, { - indexed: true, - internalType: "address", - name: "_signer", - type: "address" - }], - name: "RequiredSigner", - type: "event" -}, { - inputs: [{ - internalType: "address", - name: "_addr", - type: "address" - }], - name: "callBalanceOf", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [], - name: "callBlockNumber", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [{ - internalType: "uint256", - name: "_i", - type: "uint256" - }], - name: "callBlockhash", - outputs: [{ - internalType: "bytes32", - name: "", - type: "bytes32" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [], - name: "callChainId", - outputs: [{ - internalType: "uint256", - name: "id", - type: "uint256" - }], - stateMutability: "pure", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_addr", - type: "address" - }], - name: "callCode", - outputs: [{ - internalType: "bytes", - name: "code", - type: "bytes" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_addr", - type: "address" - }], - name: "callCodeHash", - outputs: [{ - internalType: "bytes32", - name: "codeHash", - type: "bytes32" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_addr", - type: "address" - }], - name: "callCodeSize", - outputs: [{ - internalType: "uint256", - name: "size", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [], - name: "callCoinbase", - outputs: [{ - internalType: "address", - name: "", - type: "address" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [], - name: "callDifficulty", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [], - name: "callGasLeft", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [], - name: "callGasLimit", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [], - name: "callGasPrice", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [], - name: "callOrigin", - outputs: [{ - internalType: "address", - name: "", - type: "address" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [], - name: "callTimestamp", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "", - type: "address" - }], - name: "knownImageHashes", - outputs: [{ - internalType: "bytes32", - name: "", - type: "bytes32" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [{ - internalType: "bytes32", - name: "", - type: "bytes32" - }], - name: "lastImageHashUpdate", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "", - type: "address" - }], - name: "lastSignerUpdate", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "", - type: "address" - }], - name: "lastWalletUpdate", - outputs: [{ - internalType: "uint256", - name: "", - type: "uint256" - }], - stateMutability: "view", - type: "function" -}, { - inputs: [{ - components: [{ - internalType: "bool", - name: "delegateCall", - type: "bool" - }, { - internalType: "bool", - name: "revertOnError", - type: "bool" - }, { - internalType: "uint256", - name: "gasLimit", - type: "uint256" - }, { - internalType: "address", - name: "target", - type: "address" - }, { - internalType: "uint256", - name: "value", - type: "uint256" - }, { - internalType: "bytes", - name: "data", - type: "bytes" - }], - internalType: "struct IModuleCalls.Transaction[]", - name: "_txs", - type: "tuple[]" - }], - name: "multiCall", - outputs: [{ - internalType: "bool[]", - name: "_successes", - type: "bool[]" - }, { - internalType: "bytes[]", - name: "_results", - type: "bytes[]" - }], - stateMutability: "payable", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_wallet", - type: "address" - }, { - internalType: "uint256", - name: "_threshold", - type: "uint256" - }, { - components: [{ - internalType: "uint256", - name: "weight", - type: "uint256" - }, { - internalType: "address", - name: "signer", - type: "address" - }], - internalType: "struct RequireUtils.Member[]", - name: "_members", - type: "tuple[]" - }, { - internalType: "bool", - name: "_index", - type: "bool" - }], - name: "publishConfig", - outputs: [], - stateMutability: "nonpayable", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_wallet", - type: "address" - }, { - internalType: "bytes32", - name: "_hash", - type: "bytes32" - }, { - internalType: "uint256", - name: "_sizeMembers", - type: "uint256" - }, { - internalType: "bytes", - name: "_signature", - type: "bytes" - }, { - internalType: "bool", - name: "_index", - type: "bool" - }], - name: "publishInitialSigners", - outputs: [], - stateMutability: "nonpayable", - type: "function" -}, { - inputs: [{ - internalType: "address", - name: "_wallet", - type: "address" - }, { - internalType: "uint256", - name: "_nonce", - type: "uint256" - }], - name: "requireMinNonce", - outputs: [], - stateMutability: "view", - type: "function" -}, { - inputs: [{ - internalType: "uint256", - name: "_expiration", - type: "uint256" - }], - name: "requireNonExpired", - outputs: [], - stateMutability: "view", - type: "function" -}]; -var sequenceUtils = /* @__PURE__ */ Object.freeze({ - __proto__: null, - abi: abi$1$1 -}); -const abi$8 = [{ - inputs: [{ - internalType: "address", - name: "", - type: "address" - }], - name: "requireFreshSigner", - outputs: [], - stateMutability: "nonpayable", - type: "function" -}]; -var requireFreshSigner = /* @__PURE__ */ Object.freeze({ - __proto__: null, - abi: abi$8 -}); -const walletContracts = { - erc6492, - erc5719, - erc1271, - factory, - mainModule, - mainModuleUpgradable, - sequenceUtils, - requireFreshSigner -}; -const abi$1$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - walletContracts -}, Symbol.toStringTag, { value: "Module" })); -function _extends$f() { - _extends$f = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; +var isServer = typeof window === "undefined" || "Deno" in globalThis; +function noop$2() { + return void 0; +} +function functionalUpdate(updater, input2) { + return typeof updater === "function" ? updater(input2) : updater; +} +function isValidTimeout(value) { + return typeof value === "number" && value >= 0 && value !== Infinity; +} +function timeUntilStale(updatedAt, staleTime) { + return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0); +} +function resolveStaleTime(staleTime, query) { + return typeof staleTime === "function" ? staleTime(query) : staleTime; +} +function resolveEnabled(enabled, query) { + return typeof enabled === "function" ? enabled(query) : enabled; +} +function matchQuery(filters, query) { + const { + type = "all", + exact, + fetchStatus, + predicate, + queryKey, + stale + } = filters; + if (queryKey) { + if (exact) { + if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) { + return false; + } + } else if (!partialMatchKey(query.queryKey, queryKey)) { + return false; + } + } + if (type !== "all") { + const isActive = query.isActive(); + if (type === "active" && !isActive) { + return false; + } + if (type === "inactive" && isActive) { + return false; + } + } + if (typeof stale === "boolean" && query.isStale() !== stale) { + return false; + } + if (fetchStatus && fetchStatus !== query.state.fetchStatus) { + return false; + } + if (predicate && !predicate(query)) { + return false; + } + return true; +} +function matchMutation(filters, mutation) { + const { exact, status, predicate, mutationKey } = filters; + if (mutationKey) { + if (!mutation.options.mutationKey) { + return false; + } + if (exact) { + if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) { + return false; + } + } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) { + return false; + } + } + if (status && mutation.state.status !== status) { + return false; + } + if (predicate && !predicate(mutation)) { + return false; + } + return true; +} +function hashQueryKeyByOptions(queryKey, options) { + const hashFn2 = (options == null ? void 0 : options.queryKeyHashFn) || hashKey; + return hashFn2(queryKey); +} +function hashKey(queryKey) { + return JSON.stringify( + queryKey, + (_, val) => isPlainObject$2(val) ? Object.keys(val).sort().reduce((result, key) => { + result[key] = val[key]; + return result; + }, {}) : val + ); +} +function partialMatchKey(a2, b2) { + if (a2 === b2) { + return true; + } + if (typeof a2 !== typeof b2) { + return false; + } + if (a2 && b2 && typeof a2 === "object" && typeof b2 === "object") { + return !Object.keys(b2).some((key) => !partialMatchKey(a2[key], b2[key])); + } + return false; +} +function replaceEqualDeep(a2, b2) { + if (a2 === b2) { + return a2; + } + const array = isPlainArray(a2) && isPlainArray(b2); + if (array || isPlainObject$2(a2) && isPlainObject$2(b2)) { + const aItems = array ? a2 : Object.keys(a2); + const aSize = aItems.length; + const bItems = array ? b2 : Object.keys(b2); + const bSize = bItems.length; + const copy2 = array ? [] : {}; + let equalItems = 0; + for (let i = 0; i < bSize; i++) { + const key = array ? i : bItems[i]; + if ((!array && aItems.includes(key) || array) && a2[key] === void 0 && b2[key] === void 0) { + copy2[key] = void 0; + equalItems++; + } else { + copy2[key] = replaceEqualDeep(a2[key], b2[key]); + if (copy2[key] === a2[key] && a2[key] !== void 0) { + equalItems++; } } } - return target; - }; - return _extends$f.apply(this, arguments); + return aSize === bSize && equalItems === aSize ? a2 : copy2; + } + return b2; } -const WebRPCVersion$3 = "v1"; -const WebRPCSchemaVersion$3 = "v0.4.0"; -const WebRPCSchemaHash$3 = "d3f5f1338693d60d58f87bc408a076218201a097"; -let SortOrder$2 = /* @__PURE__ */ function(SortOrder2) { - SortOrder2["DESC"] = "DESC"; - SortOrder2["ASC"] = "ASC"; - return SortOrder2; -}({}); -let TokenType = /* @__PURE__ */ function(TokenType2) { - TokenType2["ERC20"] = "ERC20"; - TokenType2["ERC721"] = "ERC721"; - TokenType2["ERC1155"] = "ERC1155"; - return TokenType2; -}({}); -class API { - constructor(hostname, fetch2) { - this.hostname = void 0; - this.fetch = void 0; - this.path = "/rpc/API/"; - this.ping = (headers, signal) => { - return this.fetch(this.url("Ping"), createHTTPRequest$7({}, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.version = (headers, signal) => { - return this.fetch(this.url("Version"), createHTTPRequest$7({}, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - version: _data6.version - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.runtimeStatus = (headers, signal) => { - return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$7({}, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.clock = (headers, signal) => { - return this.fetch(this.url("Clock"), createHTTPRequest$7({}, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - serverTime: _data6.serverTime - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getSequenceContext = (headers, signal) => { - return this.fetch(this.url("GetSequenceContext"), createHTTPRequest$7({}, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - data: _data6.data - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getAuthToken = (args, headers, signal) => { - return this.fetch(this.url("GetAuthToken"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status, - jwtToken: _data6.jwtToken, - address: _data6.address, - user: _data6.user - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getAuthToken2 = (args, headers, signal) => { - return this.fetch(this.url("GetAuthToken2"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status, - jwtToken: _data6.jwtToken, - address: _data6.address, - user: _data6.user - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.sendPasswordlessLink = (args, headers, signal) => { - return this.fetch(this.url("SendPasswordlessLink"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.friendList = (args, headers, signal) => { - return this.fetch(this.url("FriendList"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - page: _data6.page, - friends: _data6.friends - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getFriendByAddress = (args, headers, signal) => { - return this.fetch(this.url("GetFriendByAddress"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status, - friend: _data6.friend - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.searchFriends = (args, headers, signal) => { - return this.fetch(this.url("SearchFriends"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - friends: _data6.friends - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.addFriend = (args, headers, signal) => { - return this.fetch(this.url("AddFriend"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status, - friend: _data6.friend - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateFriendNickname = (args, headers, signal) => { - return this.fetch(this.url("UpdateFriendNickname"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status, - friend: _data6.friend - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.removeFriend = (args, headers, signal) => { - return this.fetch(this.url("RemoveFriend"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); +function shallowEqualObjects(a2, b2) { + if (!b2 || Object.keys(a2).length !== Object.keys(b2).length) { + return false; + } + for (const key in a2) { + if (a2[key] !== b2[key]) { + return false; + } + } + return true; +} +function isPlainArray(value) { + return Array.isArray(value) && value.length === Object.keys(value).length; +} +function isPlainObject$2(o2) { + if (!hasObjectPrototype$1(o2)) { + return false; + } + const ctor = o2.constructor; + if (ctor === void 0) { + return true; + } + const prot = ctor.prototype; + if (!hasObjectPrototype$1(prot)) { + return false; + } + if (!prot.hasOwnProperty("isPrototypeOf")) { + return false; + } + if (Object.getPrototypeOf(o2) !== Object.prototype) { + return false; + } + return true; +} +function hasObjectPrototype$1(o2) { + return Object.prototype.toString.call(o2) === "[object Object]"; +} +function sleep$1(timeout) { + return new Promise((resolve) => { + setTimeout(resolve, timeout); + }); +} +function replaceData(prevData, data, options) { + if (typeof options.structuralSharing === "function") { + return options.structuralSharing(prevData, data); + } else if (options.structuralSharing !== false) { + return replaceEqualDeep(prevData, data); + } + return data; +} +function addToEnd(items, item2, max2 = 0) { + const newItems = [...items, item2]; + return max2 && newItems.length > max2 ? newItems.slice(1) : newItems; +} +function addToStart(items, item2, max2 = 0) { + const newItems = [item2, ...items]; + return max2 && newItems.length > max2 ? newItems.slice(0, -1) : newItems; +} +var skipToken = Symbol(); +function ensureQueryFn(options, fetchOptions) { + if (!options.queryFn && (fetchOptions == null ? void 0 : fetchOptions.initialPromise)) { + return () => fetchOptions.initialPromise; + } + if (!options.queryFn || options.queryFn === skipToken) { + return () => Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`)); + } + return options.queryFn; +} +var FocusManager = (_a = class extends Subscribable { + constructor() { + super(); + __privateAdd(this, _focused); + __privateAdd(this, _cleanup); + __privateAdd(this, _setup); + __privateSet(this, _setup, (onFocus) => { + if (!isServer && window.addEventListener) { + const listener = () => onFocus(); + window.addEventListener("visibilitychange", listener, false); + return () => { + window.removeEventListener("visibilitychange", listener); + }; + } + return; + }); + } + onSubscribe() { + if (!__privateGet(this, _cleanup)) { + this.setEventListener(__privateGet(this, _setup)); + } + } + onUnsubscribe() { + var _a2; + if (!this.hasListeners()) { + (_a2 = __privateGet(this, _cleanup)) == null ? void 0 : _a2.call(this); + __privateSet(this, _cleanup, void 0); + } + } + setEventListener(setup) { + var _a2; + __privateSet(this, _setup, setup); + (_a2 = __privateGet(this, _cleanup)) == null ? void 0 : _a2.call(this); + __privateSet(this, _cleanup, setup((focused) => { + if (typeof focused === "boolean") { + this.setFocused(focused); + } else { + this.onFocus(); + } + })); + } + setFocused(focused) { + const changed = __privateGet(this, _focused) !== focused; + if (changed) { + __privateSet(this, _focused, focused); + this.onFocus(); + } + } + onFocus() { + const isFocused = this.isFocused(); + this.listeners.forEach((listener) => { + listener(isFocused); + }); + } + isFocused() { + var _a2; + if (typeof __privateGet(this, _focused) === "boolean") { + return __privateGet(this, _focused); + } + return ((_a2 = globalThis.document) == null ? void 0 : _a2.visibilityState) !== "hidden"; + } +}, _focused = new WeakMap(), _cleanup = new WeakMap(), _setup = new WeakMap(), _a); +var focusManager = new FocusManager(); +var OnlineManager = (_b = class extends Subscribable { + constructor() { + super(); + __privateAdd(this, _online, true); + __privateAdd(this, _cleanup2); + __privateAdd(this, _setup2); + __privateSet(this, _setup2, (onOnline) => { + if (!isServer && window.addEventListener) { + const onlineListener = () => onOnline(true); + const offlineListener = () => onOnline(false); + window.addEventListener("online", onlineListener, false); + window.addEventListener("offline", offlineListener, false); + return () => { + window.removeEventListener("online", onlineListener); + window.removeEventListener("offline", offlineListener); + }; + } + return; + }); + } + onSubscribe() { + if (!__privateGet(this, _cleanup2)) { + this.setEventListener(__privateGet(this, _setup2)); + } + } + onUnsubscribe() { + var _a2; + if (!this.hasListeners()) { + (_a2 = __privateGet(this, _cleanup2)) == null ? void 0 : _a2.call(this); + __privateSet(this, _cleanup2, void 0); + } + } + setEventListener(setup) { + var _a2; + __privateSet(this, _setup2, setup); + (_a2 = __privateGet(this, _cleanup2)) == null ? void 0 : _a2.call(this); + __privateSet(this, _cleanup2, setup(this.setOnline.bind(this))); + } + setOnline(online) { + const changed = __privateGet(this, _online) !== online; + if (changed) { + __privateSet(this, _online, online); + this.listeners.forEach((listener) => { + listener(online); }); - }; - this.contractCall = (args, headers, signal) => { - return this.fetch(this.url("ContractCall"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - returns: _data6.returns - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + } + } + isOnline() { + return __privateGet(this, _online); + } +}, _online = new WeakMap(), _cleanup2 = new WeakMap(), _setup2 = new WeakMap(), _b); +var onlineManager = new OnlineManager(); +function defaultRetryDelay(failureCount) { + return Math.min(1e3 * 2 ** failureCount, 3e4); +} +function canFetch(networkMode) { + return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true; +} +var CancelledError = class extends Error { + constructor(options) { + super("CancelledError"); + this.revert = options == null ? void 0 : options.revert; + this.silent = options == null ? void 0 : options.silent; + } +}; +function isCancelledError(value) { + return value instanceof CancelledError; +} +function createRetryer(config2) { + let isRetryCancelled = false; + let failureCount = 0; + let isResolved = false; + let continueFn; + let promiseResolve; + let promiseReject; + const promise = new Promise((outerResolve, outerReject) => { + promiseResolve = outerResolve; + promiseReject = outerReject; + }); + const cancel = (cancelOptions) => { + var _a2; + if (!isResolved) { + reject(new CancelledError(cancelOptions)); + (_a2 = config2.abort) == null ? void 0 : _a2.call(config2); + } + }; + const cancelRetry = () => { + isRetryCancelled = true; + }; + const continueRetry = () => { + isRetryCancelled = false; + }; + const canContinue = () => focusManager.isFocused() && (config2.networkMode === "always" || onlineManager.isOnline()) && config2.canRun(); + const canStart = () => canFetch(config2.networkMode) && config2.canRun(); + const resolve = (value) => { + var _a2; + if (!isResolved) { + isResolved = true; + (_a2 = config2.onSuccess) == null ? void 0 : _a2.call(config2, value); + continueFn == null ? void 0 : continueFn(); + promiseResolve(value); + } + }; + const reject = (value) => { + var _a2; + if (!isResolved) { + isResolved = true; + (_a2 = config2.onError) == null ? void 0 : _a2.call(config2, value); + continueFn == null ? void 0 : continueFn(); + promiseReject(value); + } + }; + const pause = () => { + return new Promise((continueResolve) => { + var _a2; + continueFn = (value) => { + if (isResolved || canContinue()) { + continueResolve(value); + } + }; + (_a2 = config2.onPause) == null ? void 0 : _a2.call(config2); + }).then(() => { + var _a2; + continueFn = void 0; + if (!isResolved) { + (_a2 = config2.onContinue) == null ? void 0 : _a2.call(config2); + } + }); + }; + const run = () => { + if (isResolved) { + return; + } + let promiseOrValue; + const initialPromise = failureCount === 0 ? config2.initialPromise : void 0; + try { + promiseOrValue = initialPromise ?? config2.fn(); + } catch (error) { + promiseOrValue = Promise.reject(error); + } + Promise.resolve(promiseOrValue).then(resolve).catch((error) => { + var _a2; + if (isResolved) { + return; + } + const retry = config2.retry ?? (isServer ? 0 : 3); + const retryDelay = config2.retryDelay ?? defaultRetryDelay; + const delay2 = typeof retryDelay === "function" ? retryDelay(failureCount, error) : retryDelay; + const shouldRetry2 = retry === true || typeof retry === "number" && failureCount < retry || typeof retry === "function" && retry(failureCount, error); + if (isRetryCancelled || !shouldRetry2) { + reject(error); + return; + } + failureCount++; + (_a2 = config2.onFail) == null ? void 0 : _a2.call(config2, failureCount, error); + sleep$1(delay2).then(() => { + return canContinue() ? void 0 : pause(); + }).then(() => { + if (isRetryCancelled) { + reject(error); + } else { + run(); + } }); - }; - this.decodeContractCall = (args, headers, signal) => { - return this.fetch(this.url("DecodeContractCall"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - call: _data6.call - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + }); + }; + return { + promise, + cancel, + continue: () => { + continueFn == null ? void 0 : continueFn(); + return promise; + }, + cancelRetry, + continueRetry, + canStart, + start: () => { + if (canStart()) { + run(); + } else { + pause().then(run); + } + return promise; + } + }; +} +function createNotifyManager() { + let queue2 = []; + let transactions2 = 0; + let notifyFn = (callback) => { + callback(); + }; + let batchNotifyFn = (callback) => { + callback(); + }; + let scheduleFn = (cb2) => setTimeout(cb2, 0); + const schedule = (callback) => { + if (transactions2) { + queue2.push(callback); + } else { + scheduleFn(() => { + notifyFn(callback); }); - }; - this.lookupContractCallSelectors = (args, headers, signal) => { - return this.fetch(this.url("LookupContractCallSelectors"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - signatures: _data6.signatures - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` + } + }; + const flush = () => { + const originalQueue = queue2; + queue2 = []; + if (originalQueue.length) { + scheduleFn(() => { + batchNotifyFn(() => { + originalQueue.forEach((callback) => { + notifyFn(callback); + }); }); }); - }; - this.userStorageFetch = (args, headers, signal) => { - return this.fetch(this.url("UserStorageFetch"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - object: _data6.object - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.userStorageSave = (args, headers, signal) => { - return this.fetch(this.url("UserStorageSave"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` + } + }; + return { + batch: (callback) => { + let result; + transactions2++; + try { + result = callback(); + } finally { + transactions2--; + if (!transactions2) { + flush(); + } + } + return result; + }, + /** + * All calls to the wrapped function will be batched. + */ + batchCalls: (callback) => { + return (...args) => { + schedule(() => { + callback(...args); }); + }; + }, + schedule, + /** + * Use this method to set a custom notify function. + * This can be used to for example wrap notifications with `React.act` while running tests. + */ + setNotifyFunction: (fn) => { + notifyFn = fn; + }, + /** + * Use this method to set a custom function to batch notifications together into a single tick. + * By default React Query will use the batch function provided by ReactDOM or React Native. + */ + setBatchNotifyFunction: (fn) => { + batchNotifyFn = fn; + }, + setScheduler: (fn) => { + scheduleFn = fn; + } + }; +} +var notifyManager = createNotifyManager(); +var Removable = (_c = class { + constructor() { + __privateAdd(this, _gcTimeout); + } + destroy() { + this.clearGcTimeout(); + } + scheduleGc() { + this.clearGcTimeout(); + if (isValidTimeout(this.gcTime)) { + __privateSet(this, _gcTimeout, setTimeout(() => { + this.optionalRemove(); + }, this.gcTime)); + } + } + updateGcTime(newGcTime) { + this.gcTime = Math.max( + this.gcTime || 0, + newGcTime ?? (isServer ? Infinity : 5 * 60 * 1e3) + ); + } + clearGcTimeout() { + if (__privateGet(this, _gcTimeout)) { + clearTimeout(__privateGet(this, _gcTimeout)); + __privateSet(this, _gcTimeout, void 0); + } + } +}, _gcTimeout = new WeakMap(), _c); +var Query = (_d = class extends Removable { + constructor(config2) { + super(); + __privateAdd(this, _Query_instances); + __privateAdd(this, _initialState); + __privateAdd(this, _revertState); + __privateAdd(this, _cache); + __privateAdd(this, _retryer); + __privateAdd(this, _defaultOptions); + __privateAdd(this, _abortSignalConsumed); + __privateSet(this, _abortSignalConsumed, false); + __privateSet(this, _defaultOptions, config2.defaultOptions); + this.setOptions(config2.options); + this.observers = []; + __privateSet(this, _cache, config2.cache); + this.queryKey = config2.queryKey; + this.queryHash = config2.queryHash; + __privateSet(this, _initialState, getDefaultState$1(this.options)); + this.state = config2.state ?? __privateGet(this, _initialState); + this.scheduleGc(); + } + get meta() { + return this.options.meta; + } + get promise() { + var _a2; + return (_a2 = __privateGet(this, _retryer)) == null ? void 0 : _a2.promise; + } + setOptions(options) { + this.options = { ...__privateGet(this, _defaultOptions), ...options }; + this.updateGcTime(this.options.gcTime); + } + optionalRemove() { + if (!this.observers.length && this.state.fetchStatus === "idle") { + __privateGet(this, _cache).remove(this); + } + } + setData(newData, options) { + const data = replaceData(this.state.data, newData, this.options); + __privateMethod(this, _Query_instances, dispatch_fn).call(this, { + data, + type: "success", + dataUpdatedAt: options == null ? void 0 : options.updatedAt, + manual: options == null ? void 0 : options.manual + }); + return data; + } + setState(state, setStateOptions) { + __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "setState", state, setStateOptions }); + } + cancel(options) { + var _a2, _b2; + const promise = (_a2 = __privateGet(this, _retryer)) == null ? void 0 : _a2.promise; + (_b2 = __privateGet(this, _retryer)) == null ? void 0 : _b2.cancel(options); + return promise ? promise.then(noop$2).catch(noop$2) : Promise.resolve(); + } + destroy() { + super.destroy(); + this.cancel({ silent: true }); + } + reset() { + this.destroy(); + this.setState(__privateGet(this, _initialState)); + } + isActive() { + return this.observers.some( + (observer) => resolveEnabled(observer.options.enabled, this) !== false + ); + } + isDisabled() { + return this.getObserversCount() > 0 && !this.isActive(); + } + isStale() { + if (this.state.isInvalidated) { + return true; + } + if (this.getObserversCount() > 0) { + return this.observers.some( + (observer) => observer.getCurrentResult().isStale + ); + } + return this.state.data === void 0; + } + isStaleByTime(staleTime = 0) { + return this.state.isInvalidated || this.state.data === void 0 || !timeUntilStale(this.state.dataUpdatedAt, staleTime); + } + onFocus() { + var _a2; + const observer = this.observers.find((x2) => x2.shouldFetchOnWindowFocus()); + observer == null ? void 0 : observer.refetch({ cancelRefetch: false }); + (_a2 = __privateGet(this, _retryer)) == null ? void 0 : _a2.continue(); + } + onOnline() { + var _a2; + const observer = this.observers.find((x2) => x2.shouldFetchOnReconnect()); + observer == null ? void 0 : observer.refetch({ cancelRefetch: false }); + (_a2 = __privateGet(this, _retryer)) == null ? void 0 : _a2.continue(); + } + addObserver(observer) { + if (!this.observers.includes(observer)) { + this.observers.push(observer); + this.clearGcTimeout(); + __privateGet(this, _cache).notify({ type: "observerAdded", query: this, observer }); + } + } + removeObserver(observer) { + if (this.observers.includes(observer)) { + this.observers = this.observers.filter((x2) => x2 !== observer); + if (!this.observers.length) { + if (__privateGet(this, _retryer)) { + if (__privateGet(this, _abortSignalConsumed)) { + __privateGet(this, _retryer).cancel({ revert: true }); + } else { + __privateGet(this, _retryer).cancelRetry(); + } + } + this.scheduleGc(); + } + __privateGet(this, _cache).notify({ type: "observerRemoved", query: this, observer }); + } + } + getObserversCount() { + return this.observers.length; + } + invalidate() { + if (!this.state.isInvalidated) { + __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "invalidate" }); + } + } + fetch(options, fetchOptions) { + var _a2, _b2, _c2; + if (this.state.fetchStatus !== "idle") { + if (this.state.data !== void 0 && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) { + this.cancel({ silent: true }); + } else if (__privateGet(this, _retryer)) { + __privateGet(this, _retryer).continueRetry(); + return __privateGet(this, _retryer).promise; + } + } + if (options) { + this.setOptions(options); + } + if (!this.options.queryFn) { + const observer = this.observers.find((x2) => x2.options.queryFn); + if (observer) { + this.setOptions(observer.options); + } + } + const abortController = new AbortController(); + const addSignalProperty = (object2) => { + Object.defineProperty(object2, "signal", { + enumerable: true, + get: () => { + __privateSet(this, _abortSignalConsumed, true); + return abortController.signal; + } }); }; - this.userStorageDelete = (args, headers, signal) => { - return this.fetch(this.url("UserStorageDelete"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); + const fetchFn = () => { + const queryFn = ensureQueryFn(this.options, fetchOptions); + const queryFnContext = { + queryKey: this.queryKey, + meta: this.meta + }; + addSignalProperty(queryFnContext); + __privateSet(this, _abortSignalConsumed, false); + if (this.options.persister) { + return this.options.persister( + queryFn, + queryFnContext, + this + ); + } + return queryFn(queryFnContext); }; - this.userStorageFetchAll = (args, headers, signal) => { - return this.fetch(this.url("UserStorageFetchAll"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - objects: _data6.objects - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); + const context2 = { + fetchOptions, + options: this.options, + queryKey: this.queryKey, + state: this.state, + fetchFn }; - this.getMoonpayLink = (args, headers, signal) => { - return this.fetch(this.url("GetMoonpayLink"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - signedUrl: _data6.signedUrl - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` + addSignalProperty(context2); + (_a2 = this.options.behavior) == null ? void 0 : _a2.onFetch( + context2, + this + ); + __privateSet(this, _revertState, this.state); + if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((_b2 = context2.fetchOptions) == null ? void 0 : _b2.meta)) { + __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "fetch", meta: (_c2 = context2.fetchOptions) == null ? void 0 : _c2.meta }); + } + const onError = (error) => { + var _a3, _b3, _c3, _d2; + if (!(isCancelledError(error) && error.silent)) { + __privateMethod(this, _Query_instances, dispatch_fn).call(this, { + type: "error", + error }); - }); + } + if (!isCancelledError(error)) { + (_b3 = (_a3 = __privateGet(this, _cache).config).onError) == null ? void 0 : _b3.call( + _a3, + error, + this + ); + (_d2 = (_c3 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d2.call( + _c3, + this.state.data, + error, + this + ); + } + if (!this.isFetchingOptimistic) { + this.scheduleGc(); + } + this.isFetchingOptimistic = false; }; - this.getSardineClientToken = (headers, signal) => { - return this.fetch(this.url("GetSardineClientToken"), createHTTPRequest$7({}, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - token: _data6.token - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + __privateSet(this, _retryer, createRetryer({ + initialPromise: fetchOptions == null ? void 0 : fetchOptions.initialPromise, + fn: context2.fetchFn, + abort: abortController.abort.bind(abortController), + onSuccess: (data) => { + var _a3, _b3, _c3, _d2; + if (data === void 0) { + onError(new Error(`${this.queryHash} data is undefined`)); + return; + } + try { + this.setData(data); + } catch (error) { + onError(error); + return; + } + (_b3 = (_a3 = __privateGet(this, _cache).config).onSuccess) == null ? void 0 : _b3.call(_a3, data, this); + (_d2 = (_c3 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d2.call( + _c3, + data, + this.state.error, + this + ); + if (!this.isFetchingOptimistic) { + this.scheduleGc(); + } + this.isFetchingOptimistic = false; + }, + onError, + onFail: (failureCount, error) => { + __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "failed", failureCount, error }); + }, + onPause: () => { + __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "pause" }); + }, + onContinue: () => { + __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "continue" }); + }, + retry: context2.options.retry, + retryDelay: context2.options.retryDelay, + networkMode: context2.options.networkMode, + canRun: () => true + })); + return __privateGet(this, _retryer).start(); + } +}, _initialState = new WeakMap(), _revertState = new WeakMap(), _cache = new WeakMap(), _retryer = new WeakMap(), _defaultOptions = new WeakMap(), _abortSignalConsumed = new WeakMap(), _Query_instances = new WeakSet(), dispatch_fn = function(action) { + const reducer = (state) => { + switch (action.type) { + case "failed": + return { + ...state, + fetchFailureCount: action.failureCount, + fetchFailureReason: action.error + }; + case "pause": + return { + ...state, + fetchStatus: "paused" + }; + case "continue": + return { + ...state, + fetchStatus: "fetching" + }; + case "fetch": + return { + ...state, + ...fetchState(state.data, this.options), + fetchMeta: action.meta ?? null + }; + case "success": + return { + ...state, + data: action.data, + dataUpdateCount: state.dataUpdateCount + 1, + dataUpdatedAt: action.dataUpdatedAt ?? Date.now(), + error: null, + isInvalidated: false, + status: "success", + ...!action.manual && { + fetchStatus: "idle", + fetchFailureCount: 0, + fetchFailureReason: null + } + }; + case "error": + const error = action.error; + if (isCancelledError(error) && error.revert && __privateGet(this, _revertState)) { + return { ...__privateGet(this, _revertState), fetchStatus: "idle" }; + } + return { + ...state, + error, + errorUpdateCount: state.errorUpdateCount + 1, + errorUpdatedAt: Date.now(), + fetchFailureCount: state.fetchFailureCount + 1, + fetchFailureReason: error, + fetchStatus: "idle", + status: "error" + }; + case "invalidate": + return { + ...state, + isInvalidated: true + }; + case "setState": + return { + ...state, + ...action.state + }; + } + }; + this.state = reducer(this.state); + notifyManager.batch(() => { + this.observers.forEach((observer) => { + observer.onQueryUpdate(); + }); + __privateGet(this, _cache).notify({ query: this, type: "updated", action }); + }); +}, _d); +function fetchState(data, options) { + return { + fetchFailureCount: 0, + fetchFailureReason: null, + fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused", + ...data === void 0 && { + error: null, + status: "pending" + } + }; +} +function getDefaultState$1(options) { + const data = typeof options.initialData === "function" ? options.initialData() : options.initialData; + const hasData = data !== void 0; + const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0; + return { + data, + dataUpdateCount: 0, + dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0, + error: null, + errorUpdateCount: 0, + errorUpdatedAt: 0, + fetchFailureCount: 0, + fetchFailureReason: null, + fetchMeta: null, + isInvalidated: false, + status: hasData ? "success" : "pending", + fetchStatus: "idle" + }; +} +var QueryCache = (_e = class extends Subscribable { + constructor(config2 = {}) { + super(); + __privateAdd(this, _queries); + this.config = config2; + __privateSet(this, _queries, /* @__PURE__ */ new Map()); + } + build(client2, options, state) { + const queryKey = options.queryKey; + const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options); + let query = this.get(queryHash); + if (!query) { + query = new Query({ + cache: this, + queryKey, + queryHash, + options: client2.defaultQueryOptions(options), + state, + defaultOptions: client2.getQueryDefaults(queryKey) }); - }; - this.getSardineNFTCheckoutToken = (args, headers, signal) => { - return this.fetch(this.url("GetSardineNFTCheckoutToken"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - resp: _data6.resp - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + this.add(query); + } + return query; + } + add(query) { + if (!__privateGet(this, _queries).has(query.queryHash)) { + __privateGet(this, _queries).set(query.queryHash, query); + this.notify({ + type: "added", + query }); - }; - this.getSardineNFTCheckoutOrderStatus = (args, headers, signal) => { - return this.fetch(this.url("GetSardineNFTCheckoutOrderStatus"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - resp: _data6.resp - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + } + } + remove(query) { + const queryInMap = __privateGet(this, _queries).get(query.queryHash); + if (queryInMap) { + query.destroy(); + if (queryInMap === query) { + __privateGet(this, _queries).delete(query.queryHash); + } + this.notify({ type: "removed", query }); + } + } + clear() { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + this.remove(query); }); - }; - this.resolveENSAddress = (args, headers, signal) => { - return this.fetch(this.url("ResolveENSAddress"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - address: _data6.address, - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + }); + } + get(queryHash) { + return __privateGet(this, _queries).get(queryHash); + } + getAll() { + return [...__privateGet(this, _queries).values()]; + } + find(filters) { + const defaultedFilters = { exact: true, ...filters }; + return this.getAll().find( + (query) => matchQuery(defaultedFilters, query) + ); + } + findAll(filters = {}) { + const queries = this.getAll(); + return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries; + } + notify(event) { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(event); }); - }; - this.isValidSignature = (args, headers, signal) => { - return this.fetch(this.url("IsValidSignature"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - isValid: _data6.isValid - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + }); + } + onFocus() { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onFocus(); }); - }; - this.isValidMessageSignature = (args, headers, signal) => { - return this.fetch(this.url("IsValidMessageSignature"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - isValid: _data6.isValid - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + }); + } + onOnline() { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onOnline(); }); - }; - this.isValidTypedDataSignature = (args, headers, signal) => { - return this.fetch(this.url("IsValidTypedDataSignature"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - isValid: _data6.isValid - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + }); + } +}, _queries = new WeakMap(), _e); +var Mutation = (_f = class extends Removable { + constructor(config2) { + super(); + __privateAdd(this, _Mutation_instances); + __privateAdd(this, _observers); + __privateAdd(this, _mutationCache); + __privateAdd(this, _retryer2); + this.mutationId = config2.mutationId; + __privateSet(this, _mutationCache, config2.mutationCache); + __privateSet(this, _observers, []); + this.state = config2.state || getDefaultState(); + this.setOptions(config2.options); + this.scheduleGc(); + } + setOptions(options) { + this.options = options; + this.updateGcTime(this.options.gcTime); + } + get meta() { + return this.options.meta; + } + addObserver(observer) { + if (!__privateGet(this, _observers).includes(observer)) { + __privateGet(this, _observers).push(observer); + this.clearGcTimeout(); + __privateGet(this, _mutationCache).notify({ + type: "observerAdded", + mutation: this, + observer }); - }; - this.isValidETHAuthProof = (args, headers, signal) => { - return this.fetch(this.url("IsValidETHAuthProof"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - isValid: _data6.isValid - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + } + } + removeObserver(observer) { + __privateSet(this, _observers, __privateGet(this, _observers).filter((x2) => x2 !== observer)); + this.scheduleGc(); + __privateGet(this, _mutationCache).notify({ + type: "observerRemoved", + mutation: this, + observer + }); + } + optionalRemove() { + if (!__privateGet(this, _observers).length) { + if (this.state.status === "pending") { + this.scheduleGc(); + } else { + __privateGet(this, _mutationCache).remove(this); + } + } + } + continue() { + var _a2; + return ((_a2 = __privateGet(this, _retryer2)) == null ? void 0 : _a2.continue()) ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before + this.execute(this.state.variables); + } + async execute(variables) { + var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m2, _n, _o, _p, _q, _r2, _s2, _t; + __privateSet(this, _retryer2, createRetryer({ + fn: () => { + if (!this.options.mutationFn) { + return Promise.reject(new Error("No mutationFn found")); + } + return this.options.mutationFn(variables); + }, + onFail: (failureCount, error) => { + __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "failed", failureCount, error }); + }, + onPause: () => { + __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "pause" }); + }, + onContinue: () => { + __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "continue" }); + }, + retry: this.options.retry ?? 0, + retryDelay: this.options.retryDelay, + networkMode: this.options.networkMode, + canRun: () => __privateGet(this, _mutationCache).canRun(this) + })); + const restored = this.state.status === "pending"; + const isPaused = !__privateGet(this, _retryer2).canStart(); + try { + if (!restored) { + __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "pending", variables, isPaused }); + await ((_b2 = (_a2 = __privateGet(this, _mutationCache).config).onMutate) == null ? void 0 : _b2.call( + _a2, + variables, + this + )); + const context2 = await ((_d2 = (_c2 = this.options).onMutate) == null ? void 0 : _d2.call(_c2, variables)); + if (context2 !== this.state.context) { + __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { + type: "pending", + context: context2, + variables, + isPaused + }); + } + } + const data = await __privateGet(this, _retryer2).start(); + await ((_f2 = (_e2 = __privateGet(this, _mutationCache).config).onSuccess) == null ? void 0 : _f2.call( + _e2, + data, + variables, + this.state.context, + this + )); + await ((_h2 = (_g2 = this.options).onSuccess) == null ? void 0 : _h2.call(_g2, data, variables, this.state.context)); + await ((_j2 = (_i2 = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _j2.call( + _i2, + data, + null, + this.state.variables, + this.state.context, + this + )); + await ((_l2 = (_k2 = this.options).onSettled) == null ? void 0 : _l2.call(_k2, data, null, variables, this.state.context)); + __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "success", data }); + return data; + } catch (error) { + try { + await ((_n = (_m2 = __privateGet(this, _mutationCache).config).onError) == null ? void 0 : _n.call( + _m2, + error, + variables, + this.state.context, + this + )); + await ((_p = (_o = this.options).onError) == null ? void 0 : _p.call( + _o, + error, + variables, + this.state.context + )); + await ((_r2 = (_q = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _r2.call( + _q, + void 0, + error, + this.state.variables, + this.state.context, + this + )); + await ((_t = (_s2 = this.options).onSettled) == null ? void 0 : _t.call( + _s2, + void 0, + error, + variables, + this.state.context + )); + throw error; + } finally { + __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "error", error }); + } + } finally { + __privateGet(this, _mutationCache).runNext(this); + } + } +}, _observers = new WeakMap(), _mutationCache = new WeakMap(), _retryer2 = new WeakMap(), _Mutation_instances = new WeakSet(), dispatch_fn2 = function(action) { + const reducer = (state) => { + switch (action.type) { + case "failed": + return { + ...state, + failureCount: action.failureCount, + failureReason: action.error + }; + case "pause": + return { + ...state, + isPaused: true + }; + case "continue": + return { + ...state, + isPaused: false + }; + case "pending": + return { + ...state, + context: action.context, + data: void 0, + failureCount: 0, + failureReason: null, + error: null, + isPaused: action.isPaused, + status: "pending", + variables: action.variables, + submittedAt: Date.now() + }; + case "success": + return { + ...state, + data: action.data, + failureCount: 0, + failureReason: null, + error: null, + status: "success", + isPaused: false + }; + case "error": + return { + ...state, + data: void 0, + error: action.error, + failureCount: state.failureCount + 1, + failureReason: action.error, + isPaused: false, + status: "error" + }; + } + }; + this.state = reducer(this.state); + notifyManager.batch(() => { + __privateGet(this, _observers).forEach((observer) => { + observer.onMutationUpdate(action); + }); + __privateGet(this, _mutationCache).notify({ + mutation: this, + type: "updated", + action + }); + }); +}, _f); +function getDefaultState() { + return { + context: void 0, + data: void 0, + error: null, + failureCount: 0, + failureReason: null, + isPaused: false, + status: "idle", + variables: void 0, + submittedAt: 0 + }; +} +var MutationCache = (_g = class extends Subscribable { + constructor(config2 = {}) { + super(); + __privateAdd(this, _mutations); + __privateAdd(this, _mutationId); + this.config = config2; + __privateSet(this, _mutations, /* @__PURE__ */ new Map()); + __privateSet(this, _mutationId, Date.now()); + } + build(client2, options, state) { + const mutation = new Mutation({ + mutationCache: this, + mutationId: ++__privateWrapper(this, _mutationId)._, + options: client2.defaultMutationOptions(options), + state + }); + this.add(mutation); + return mutation; + } + add(mutation) { + const scope = scopeFor(mutation); + const mutations = __privateGet(this, _mutations).get(scope) ?? []; + mutations.push(mutation); + __privateGet(this, _mutations).set(scope, mutations); + this.notify({ type: "added", mutation }); + } + remove(mutation) { + var _a2; + const scope = scopeFor(mutation); + if (__privateGet(this, _mutations).has(scope)) { + const mutations = (_a2 = __privateGet(this, _mutations).get(scope)) == null ? void 0 : _a2.filter((x2) => x2 !== mutation); + if (mutations) { + if (mutations.length === 0) { + __privateGet(this, _mutations).delete(scope); + } else { + __privateGet(this, _mutations).set(scope, mutations); + } + } + } + this.notify({ type: "removed", mutation }); + } + canRun(mutation) { + var _a2; + const firstPendingMutation = (_a2 = __privateGet(this, _mutations).get(scopeFor(mutation))) == null ? void 0 : _a2.find((m2) => m2.state.status === "pending"); + return !firstPendingMutation || firstPendingMutation === mutation; + } + runNext(mutation) { + var _a2; + const foundMutation = (_a2 = __privateGet(this, _mutations).get(scopeFor(mutation))) == null ? void 0 : _a2.find((m2) => m2 !== mutation && m2.state.isPaused); + return (foundMutation == null ? void 0 : foundMutation.continue()) ?? Promise.resolve(); + } + clear() { + notifyManager.batch(() => { + this.getAll().forEach((mutation) => { + this.remove(mutation); }); - }; - this.getCoinPrices = (args, headers, signal) => { - return this.fetch(this.url("GetCoinPrices"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - tokenPrices: _data6.tokenPrices - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); + }); + } + getAll() { + return [...__privateGet(this, _mutations).values()].flat(); + } + find(filters) { + const defaultedFilters = { exact: true, ...filters }; + return this.getAll().find( + (mutation) => matchMutation(defaultedFilters, mutation) + ); + } + findAll(filters = {}) { + return this.getAll().filter((mutation) => matchMutation(filters, mutation)); + } + notify(event) { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(event); }); - }; - this.getCollectiblePrices = (args, headers, signal) => { - return this.fetch(this.url("GetCollectiblePrices"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - tokenPrices: _data6.tokenPrices + }); + } + resumePausedMutations() { + const pausedMutations = this.getAll().filter((x2) => x2.state.isPaused); + return notifyManager.batch( + () => Promise.all( + pausedMutations.map((mutation) => mutation.continue().catch(noop$2)) + ) + ); + } +}, _mutations = new WeakMap(), _mutationId = new WeakMap(), _g); +function scopeFor(mutation) { + var _a2; + return ((_a2 = mutation.options.scope) == null ? void 0 : _a2.id) ?? String(mutation.mutationId); +} +function infiniteQueryBehavior(pages) { + return { + onFetch: (context2, query) => { + var _a2, _b2, _c2, _d2, _e2; + const options = context2.options; + const direction = (_c2 = (_b2 = (_a2 = context2.fetchOptions) == null ? void 0 : _a2.meta) == null ? void 0 : _b2.fetchMore) == null ? void 0 : _c2.direction; + const oldPages = ((_d2 = context2.state.data) == null ? void 0 : _d2.pages) || []; + const oldPageParams = ((_e2 = context2.state.data) == null ? void 0 : _e2.pageParams) || []; + let result = { pages: [], pageParams: [] }; + let currentPage = 0; + const fetchFn = async () => { + let cancelled = false; + const addSignalProperty = (object2) => { + Object.defineProperty(object2, "signal", { + enumerable: true, + get: () => { + if (context2.signal.aborted) { + cancelled = true; + } else { + context2.signal.addEventListener("abort", () => { + cancelled = true; + }); + } + return context2.signal; + } + }); + }; + const queryFn = ensureQueryFn(context2.options, context2.fetchOptions); + const fetchPage = async (data, param, previous) => { + if (cancelled) { + return Promise.reject(); + } + if (param == null && data.pages.length) { + return Promise.resolve(data); + } + const queryFnContext = { + queryKey: context2.queryKey, + pageParam: param, + direction: previous ? "backward" : "forward", + meta: context2.options.meta }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getExchangeRate = (args, headers, signal) => { - return this.fetch(this.url("GetExchangeRate"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { + addSignalProperty(queryFnContext); + const page = await queryFn( + queryFnContext + ); + const { maxPages } = context2.options; + const addTo = previous ? addToStart : addToEnd; return { - exchangeRate: _data6.exchangeRate + pages: addTo(data.pages, page, maxPages), + pageParams: addTo(data.pageParams, param, maxPages) }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.memoryStore = (args, headers, signal) => { - return this.fetch(this.url("MemoryStore"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.memoryLoad = (args, headers, signal) => { - return this.fetch(this.url("MemoryLoad"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - value: _data6.value - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getInviteInfo = (headers, signal) => { - return this.fetch(this.url("GetInviteInfo"), createHTTPRequest$7({}, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - inviteInfo: _data6.inviteInfo - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.isValidAccessCode = (args, headers, signal) => { - return this.fetch(this.url("IsValidAccessCode"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.internalClaimAccessCode = (args, headers, signal) => { - return this.fetch(this.url("InternalClaimAccessCode"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.blockNumberAtTime = (args, headers, signal) => { - return this.fetch(this.url("BlockNumberAtTime"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - blocks: _data6.blocks - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.paperSessionSecret = (args, headers, signal) => { - return this.fetch(this.url("PaperSessionSecret"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - secret: _data6.secret - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.paperSessionSecret2 = (args, headers, signal) => { - return this.fetch(this.url("PaperSessionSecret2"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - secret: _data6.secret - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.linkWallet = (args, headers, signal) => { - return this.fetch(this.url("LinkWallet"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status, - linkedWalletAddress: _data6.linkedWalletAddress - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getLinkedWallets = (args, headers, signal) => { - return this.fetch(this.url("GetLinkedWallets"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - linkedWallets: _data6.linkedWallets - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.removeLinkedWallet = (args, headers, signal) => { - return this.fetch(this.url("RemoveLinkedWallet"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.generateWaaSVerificationURL = (args, headers, signal) => { - return this.fetch(this.url("GenerateWaaSVerificationURL"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - nonce: _data6.nonce, - verificationURL: _data6.verificationURL - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.validateWaaSVerificationNonce = (args, headers, signal) => { - return this.fetch(this.url("ValidateWaaSVerificationNonce"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - walletAddress: _data6.walletAddress - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getSwapQuotes = (args, headers, signal) => { - return this.fetch(this.url("GetSwapQuotes"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - swapQuotes: _data6.swapQuotes - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.addCurrencyGroup = (args, headers, signal) => { - return this.fetch(this.url("AddCurrencyGroup"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - groupId: _data6.groupId - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateCurrencyGroup = (args, headers, signal) => { - return this.fetch(this.url("UpdateCurrencyGroup"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.listCurrencyGroups = (headers, signal) => { - return this.fetch(this.url("ListCurrencyGroups"), createHTTPRequest$7({}, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - currencyGroups: _data6.currencyGroups - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.deleteCurrencyGroup = (args, headers, signal) => { - return this.fetch(this.url("DeleteCurrencyGroup"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.addInventoryPaymentConfig = (args, headers, signal) => { - return this.fetch(this.url("AddInventoryPaymentConfig"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - configId: _data6.configId - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getInventoryPaymentConfig = (args, headers, signal) => { - return this.fetch(this.url("GetInventoryPaymentConfig"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - config: _data6.config - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.listInventoryPaymentConfigs = (args, headers, signal) => { - return this.fetch(this.url("ListInventoryPaymentConfigs"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - configs: _data6.configs - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateInventoryPaymentConfig = (args, headers, signal) => { - return this.fetch(this.url("UpdateInventoryPaymentConfig"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.deleteInventoryPaymentConfig = (args, headers, signal) => { - return this.fetch(this.url("DeleteInventoryPaymentConfig"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.requestInventoryPayment = (args, headers, signal) => { - return this.fetch(this.url("RequestInventoryPayment"), createHTTPRequest$7(args, headers, signal)).then((res) => { - return buildResponse$7(res).then((_data6) => { - return { - payment: _data6.payment + }; + if (direction && oldPages.length) { + const previous = direction === "backward"; + const pageParamFn = previous ? getPreviousPageParam : getNextPageParam; + const oldData = { + pages: oldPages, + pageParams: oldPageParams }; - }); - }, (error) => { - throw WebrpcRequestFailedError$7.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.hostname = hostname; - this.fetch = (input2, init2) => fetch2(input2, init2); - } - url(name2) { - return this.hostname + this.path + name2; - } -} -const createHTTPRequest$7 = (body = {}, headers = {}, signal = null) => { - return { - method: "POST", - headers: _extends$f({}, headers, { - "Content-Type": "application/json" - }), - body: JSON.stringify(body || {}), - signal - }; -}; -const buildResponse$7 = (res) => { - return res.text().then((text2) => { - let data; - try { - data = JSON.parse(text2); - } catch (error) { - let message = ""; - if (error instanceof Error) { - message = error.message; + const param = pageParamFn(options, oldData); + result = await fetchPage(oldData, param, previous); + } else { + const remainingPages = pages ?? oldPages.length; + do { + const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result); + if (currentPage > 0 && param == null) { + break; + } + result = await fetchPage(result, param); + currentPage++; + } while (currentPage < remainingPages); + } + return result; + }; + if (context2.options.persister) { + context2.fetchFn = () => { + var _a3, _b3; + return (_b3 = (_a3 = context2.options).persister) == null ? void 0 : _b3.call( + _a3, + fetchFn, + { + queryKey: context2.queryKey, + meta: context2.options.meta, + signal: context2.signal + }, + query + ); + }; + } else { + context2.fetchFn = fetchFn; } - throw WebrpcBadResponseError$7.new({ - status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text2}` - }); - } - if (!res.ok) { - const code2 = typeof data.code === "number" ? data.code : 0; - throw (webrpcErrorByCode$7[code2] || WebrpcError$7).new(data); } - return data; - }); -}; -let WebrpcError$7 = class WebrpcError extends Error { - constructor(name2, code2, message, status, cause) { - super(message); - this.name = void 0; - this.code = void 0; - this.message = void 0; - this.status = void 0; - this.cause = void 0; - this.msg = void 0; - this.name = name2 || "WebrpcError"; - this.code = typeof code2 === "number" ? code2 : 0; - this.message = message || `endpoint error ${this.code}`; - this.msg = this.message; - this.status = typeof status === "number" ? status : 0; - this.cause = cause; - Object.setPrototypeOf(this, WebrpcError.prototype); - } - static new(payload) { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + }; +} +function getNextPageParam(options, { pages, pageParams }) { + const lastIndex = pages.length - 1; + return pages.length > 0 ? options.getNextPageParam( + pages[lastIndex], + pages, + pageParams[lastIndex], + pageParams + ) : void 0; +} +function getPreviousPageParam(options, { pages, pageParams }) { + var _a2; + return pages.length > 0 ? (_a2 = options.getPreviousPageParam) == null ? void 0 : _a2.call(options, pages[0], pages, pageParams[0], pageParams) : void 0; +} +function hasNextPage(options, data) { + if (!data) + return false; + return getNextPageParam(options, data) != null; +} +function hasPreviousPage(options, data) { + if (!data || !options.getPreviousPageParam) + return false; + return getPreviousPageParam(options, data) != null; +} +var QueryClient = (_h = class { + constructor(config2 = {}) { + __privateAdd(this, _queryCache); + __privateAdd(this, _mutationCache2); + __privateAdd(this, _defaultOptions2); + __privateAdd(this, _queryDefaults); + __privateAdd(this, _mutationDefaults); + __privateAdd(this, _mountCount); + __privateAdd(this, _unsubscribeFocus); + __privateAdd(this, _unsubscribeOnline); + __privateSet(this, _queryCache, config2.queryCache || new QueryCache()); + __privateSet(this, _mutationCache2, config2.mutationCache || new MutationCache()); + __privateSet(this, _defaultOptions2, config2.defaultOptions || {}); + __privateSet(this, _queryDefaults, /* @__PURE__ */ new Map()); + __privateSet(this, _mutationDefaults, /* @__PURE__ */ new Map()); + __privateSet(this, _mountCount, 0); } -}; -let WebrpcEndpointError$7 = class WebrpcEndpointError extends WebrpcError$7 { - constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcEndpointError.prototype); + mount() { + __privateWrapper(this, _mountCount)._++; + if (__privateGet(this, _mountCount) !== 1) + return; + __privateSet(this, _unsubscribeFocus, focusManager.subscribe(async (focused) => { + if (focused) { + await this.resumePausedMutations(); + __privateGet(this, _queryCache).onFocus(); + } + })); + __privateSet(this, _unsubscribeOnline, onlineManager.subscribe(async (online) => { + if (online) { + await this.resumePausedMutations(); + __privateGet(this, _queryCache).onOnline(); + } + })); } -}; -let WebrpcRequestFailedError$7 = class WebrpcRequestFailedError extends WebrpcError$7 { - constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcRequestFailedError.prototype); + unmount() { + var _a2, _b2; + __privateWrapper(this, _mountCount)._--; + if (__privateGet(this, _mountCount) !== 0) + return; + (_a2 = __privateGet(this, _unsubscribeFocus)) == null ? void 0 : _a2.call(this); + __privateSet(this, _unsubscribeFocus, void 0); + (_b2 = __privateGet(this, _unsubscribeOnline)) == null ? void 0 : _b2.call(this); + __privateSet(this, _unsubscribeOnline, void 0); } -}; -let WebrpcBadRouteError$7 = class WebrpcBadRouteError extends WebrpcError$7 { - constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRouteError.prototype); + isFetching(filters) { + return __privateGet(this, _queryCache).findAll({ ...filters, fetchStatus: "fetching" }).length; } -}; -let WebrpcBadMethodError$7 = class WebrpcBadMethodError extends WebrpcError$7 { - constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadMethodError.prototype); + isMutating(filters) { + return __privateGet(this, _mutationCache2).findAll({ ...filters, status: "pending" }).length; } -}; -let WebrpcBadRequestError$7 = class WebrpcBadRequestError extends WebrpcError$7 { - constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRequestError.prototype); + getQueryData(queryKey) { + var _a2; + const options = this.defaultQueryOptions({ queryKey }); + return (_a2 = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a2.state.data; } -}; -let WebrpcBadResponseError$7 = class WebrpcBadResponseError extends WebrpcError$7 { - constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadResponseError.prototype); - } -}; -let WebrpcServerPanicError$7 = class WebrpcServerPanicError extends WebrpcError$7 { - constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcServerPanicError.prototype); - } -}; -let WebrpcInternalErrorError$7 = class WebrpcInternalErrorError extends WebrpcError$7 { - constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcInternalErrorError.prototype); - } -}; -let WebrpcClientDisconnectedError$7 = class WebrpcClientDisconnectedError extends WebrpcError$7 { - constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcClientDisconnectedError.prototype); - } -}; -let WebrpcStreamLostError$7 = class WebrpcStreamLostError extends WebrpcError$7 { - constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamLostError.prototype); - } -}; -let WebrpcStreamFinishedError$7 = class WebrpcStreamFinishedError extends WebrpcError$7 { - constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype); - } -}; -let UnauthorizedError$6 = class UnauthorizedError extends WebrpcError$7 { - constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, UnauthorizedError.prototype); - } -}; -let PermissionDeniedError$4 = class PermissionDeniedError extends WebrpcError$7 { - constructor(name2 = "PermissionDenied", code2 = 1001, message = "Permission denied", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, PermissionDeniedError.prototype); + ensureQueryData(options) { + const cachedData = this.getQueryData(options.queryKey); + if (cachedData === void 0) + return this.fetchQuery(options); + else { + const defaultedOptions = this.defaultQueryOptions(options); + const query = __privateGet(this, _queryCache).build(this, defaultedOptions); + if (options.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) { + void this.prefetchQuery(defaultedOptions); + } + return Promise.resolve(cachedData); + } } -}; -let SessionExpiredError$4 = class SessionExpiredError extends WebrpcError$7 { - constructor(name2 = "SessionExpired", code2 = 1002, message = "Session expired", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, SessionExpiredError.prototype); + getQueriesData(filters) { + return __privateGet(this, _queryCache).findAll(filters).map(({ queryKey, state }) => { + const data = state.data; + return [queryKey, data]; + }); } -}; -let AbortedError$3 = class AbortedError extends WebrpcError$7 { - constructor(name2 = "Aborted", code2 = 1005, message = "Request aborted", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, AbortedError.prototype); + setQueryData(queryKey, updater, options) { + const defaultedOptions = this.defaultQueryOptions({ queryKey }); + const query = __privateGet(this, _queryCache).get( + defaultedOptions.queryHash + ); + const prevData = query == null ? void 0 : query.state.data; + const data = functionalUpdate(updater, prevData); + if (data === void 0) { + return void 0; + } + return __privateGet(this, _queryCache).build(this, defaultedOptions).setData(data, { ...options, manual: true }); } -}; -let GeoblockedError$1 = class GeoblockedError extends WebrpcError$7 { - constructor(name2 = "Geoblocked", code2 = 1006, message = "Geoblocked region", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, GeoblockedError.prototype); + setQueriesData(filters, updater, options) { + return notifyManager.batch( + () => __privateGet(this, _queryCache).findAll(filters).map(({ queryKey }) => [ + queryKey, + this.setQueryData(queryKey, updater, options) + ]) + ); } -}; -let InvalidArgumentError$5 = class InvalidArgumentError extends WebrpcError$7 { - constructor(name2 = "InvalidArgument", code2 = 2e3, message = "Invalid argument", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, InvalidArgumentError.prototype); + getQueryState(queryKey) { + var _a2; + const options = this.defaultQueryOptions({ queryKey }); + return (_a2 = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a2.state; } -}; -let UnavailableError$3 = class UnavailableError extends WebrpcError$7 { - constructor(name2 = "Unavailable", code2 = 2002, message = "Unavailable resource", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, UnavailableError.prototype); + removeQueries(filters) { + const queryCache = __privateGet(this, _queryCache); + notifyManager.batch(() => { + queryCache.findAll(filters).forEach((query) => { + queryCache.remove(query); + }); + }); } -}; -let QueryFailedError$5 = class QueryFailedError extends WebrpcError$7 { - constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, QueryFailedError.prototype); + resetQueries(filters, options) { + const queryCache = __privateGet(this, _queryCache); + const refetchFilters = { + type: "active", + ...filters + }; + return notifyManager.batch(() => { + queryCache.findAll(filters).forEach((query) => { + query.reset(); + }); + return this.refetchQueries(refetchFilters, options); + }); } -}; -let NotFoundError$6 = class NotFoundError extends WebrpcError$7 { - constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, NotFoundError.prototype); + cancelQueries(filters = {}, cancelOptions = {}) { + const defaultedCancelOptions = { revert: true, ...cancelOptions }; + const promises = notifyManager.batch( + () => __privateGet(this, _queryCache).findAll(filters).map((query) => query.cancel(defaultedCancelOptions)) + ); + return Promise.all(promises).then(noop$2).catch(noop$2); } -}; -let errors$3 = /* @__PURE__ */ function(errors2) { - errors2["WebrpcEndpoint"] = "WebrpcEndpoint"; - errors2["WebrpcRequestFailed"] = "WebrpcRequestFailed"; - errors2["WebrpcBadRoute"] = "WebrpcBadRoute"; - errors2["WebrpcBadMethod"] = "WebrpcBadMethod"; - errors2["WebrpcBadRequest"] = "WebrpcBadRequest"; - errors2["WebrpcBadResponse"] = "WebrpcBadResponse"; - errors2["WebrpcServerPanic"] = "WebrpcServerPanic"; - errors2["WebrpcInternalError"] = "WebrpcInternalError"; - errors2["WebrpcClientDisconnected"] = "WebrpcClientDisconnected"; - errors2["WebrpcStreamLost"] = "WebrpcStreamLost"; - errors2["WebrpcStreamFinished"] = "WebrpcStreamFinished"; - errors2["Unauthorized"] = "Unauthorized"; - errors2["PermissionDenied"] = "PermissionDenied"; - errors2["SessionExpired"] = "SessionExpired"; - errors2["Aborted"] = "Aborted"; - errors2["Geoblocked"] = "Geoblocked"; - errors2["InvalidArgument"] = "InvalidArgument"; - errors2["Unavailable"] = "Unavailable"; - errors2["QueryFailed"] = "QueryFailed"; - errors2["NotFound"] = "NotFound"; - return errors2; -}({}); -const webrpcErrorByCode$7 = { - [0]: WebrpcEndpointError$7, - [-1]: WebrpcRequestFailedError$7, - [-2]: WebrpcBadRouteError$7, - [-3]: WebrpcBadMethodError$7, - [-4]: WebrpcBadRequestError$7, - [-5]: WebrpcBadResponseError$7, - [-6]: WebrpcServerPanicError$7, - [-7]: WebrpcInternalErrorError$7, - [-8]: WebrpcClientDisconnectedError$7, - [-9]: WebrpcStreamLostError$7, - [-10]: WebrpcStreamFinishedError$7, - [1e3]: UnauthorizedError$6, - [1001]: PermissionDeniedError$4, - [1002]: SessionExpiredError$4, - [1005]: AbortedError$3, - [1006]: GeoblockedError$1, - [2e3]: InvalidArgumentError$5, - [2002]: UnavailableError$3, - [2003]: QueryFailedError$5, - [3e3]: NotFoundError$6 -}; -const fetch$6 = globalThis.fetch; -class SequenceAPIClient extends API { - constructor(hostname, projectAccessKey2, jwtAuth) { - super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, fetch$6); - this.projectAccessKey = projectAccessKey2; - this.jwtAuth = jwtAuth; - this._fetch = (input2, init2) => { - const headers = {}; - const jwtAuth2 = this.jwtAuth; - const projectAccessKey3 = this.projectAccessKey; - if (jwtAuth2 && jwtAuth2.length > 0) { - headers["Authorization"] = `BEARER ${jwtAuth2}`; - } - if (projectAccessKey3 && projectAccessKey3.length > 0) { - headers["X-Access-Key"] = projectAccessKey3; + invalidateQueries(filters = {}, options = {}) { + return notifyManager.batch(() => { + __privateGet(this, _queryCache).findAll(filters).forEach((query) => { + query.invalidate(); + }); + if (filters.refetchType === "none") { + return Promise.resolve(); } - init2.headers = _extends$f({}, init2.headers, headers); - return fetch$6(input2, init2); - }; - this.fetch = this._fetch; + const refetchFilters = { + ...filters, + type: filters.refetchType ?? filters.type ?? "active" + }; + return this.refetchQueries(refetchFilters, options); + }); } -} -const api$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - API, - AbortedError: AbortedError$3, - GeoblockedError: GeoblockedError$1, - InvalidArgumentError: InvalidArgumentError$5, - NotFoundError: NotFoundError$6, - PermissionDeniedError: PermissionDeniedError$4, - QueryFailedError: QueryFailedError$5, - SequenceAPIClient, - SessionExpiredError: SessionExpiredError$4, - SortOrder: SortOrder$2, - TokenType, - UnauthorizedError: UnauthorizedError$6, - UnavailableError: UnavailableError$3, - WebRPCSchemaHash: WebRPCSchemaHash$3, - WebRPCSchemaVersion: WebRPCSchemaVersion$3, - WebRPCVersion: WebRPCVersion$3, - WebrpcBadMethodError: WebrpcBadMethodError$7, - WebrpcBadRequestError: WebrpcBadRequestError$7, - WebrpcBadResponseError: WebrpcBadResponseError$7, - WebrpcBadRouteError: WebrpcBadRouteError$7, - WebrpcClientDisconnectedError: WebrpcClientDisconnectedError$7, - WebrpcEndpointError: WebrpcEndpointError$7, - WebrpcError: WebrpcError$7, - WebrpcInternalErrorError: WebrpcInternalErrorError$7, - WebrpcRequestFailedError: WebrpcRequestFailedError$7, - WebrpcServerPanicError: WebrpcServerPanicError$7, - WebrpcStreamFinishedError: WebrpcStreamFinishedError$7, - WebrpcStreamLostError: WebrpcStreamLostError$7, - errors: errors$3 -}, Symbol.toStringTag, { value: "Module" })); -const version$9 = "6.13.0"; -function checkType(value, type, name2) { - const types2 = type.split("|").map((t2) => t2.trim()); - for (let i = 0; i < types2.length; i++) { - switch (type) { - case "any": - return; - case "bigint": - case "boolean": - case "number": - case "string": - if (typeof value === type) { - return; + refetchQueries(filters = {}, options) { + const fetchOptions = { + ...options, + cancelRefetch: (options == null ? void 0 : options.cancelRefetch) ?? true + }; + const promises = notifyManager.batch( + () => __privateGet(this, _queryCache).findAll(filters).filter((query) => !query.isDisabled()).map((query) => { + let promise = query.fetch(void 0, fetchOptions); + if (!fetchOptions.throwOnError) { + promise = promise.catch(noop$2); } - } + return query.state.fetchStatus === "paused" ? Promise.resolve() : promise; + }) + ); + return Promise.all(promises).then(noop$2); } - const error = new Error(`invalid value for type ${type}`); - error.code = "INVALID_ARGUMENT"; - error.argument = `value.${name2}`; - error.value = value; - throw error; -} -async function resolveProperties$1(value) { - const keys = Object.keys(value); - const results2 = await Promise.all(keys.map((k2) => Promise.resolve(value[k2]))); - return results2.reduce((accum, v3, index2) => { - accum[keys[index2]] = v3; - return accum; - }, {}); -} -function defineProperties$1(target, values, types2) { - for (let key in values) { - let value = values[key]; - const type = types2 ? types2[key] : null; - if (type) { - checkType(value, type, key); + fetchQuery(options) { + const defaultedOptions = this.defaultQueryOptions(options); + if (defaultedOptions.retry === void 0) { + defaultedOptions.retry = false; } - Object.defineProperty(target, key, { enumerable: true, value, writable: false }); - } -} -function stringify$3(value) { - if (value == null) { - return "null"; + const query = __privateGet(this, _queryCache).build(this, defaultedOptions); + return query.isStaleByTime( + resolveStaleTime(defaultedOptions.staleTime, query) + ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data); } - if (Array.isArray(value)) { - return "[ " + value.map(stringify$3).join(", ") + " ]"; + prefetchQuery(options) { + return this.fetchQuery(options).then(noop$2).catch(noop$2); } - if (value instanceof Uint8Array) { - const HEX = "0123456789abcdef"; - let result = "0x"; - for (let i = 0; i < value.length; i++) { - result += HEX[value[i] >> 4]; - result += HEX[value[i] & 15]; - } - return result; + fetchInfiniteQuery(options) { + options.behavior = infiniteQueryBehavior(options.pages); + return this.fetchQuery(options); } - if (typeof value === "object" && typeof value.toJSON === "function") { - return stringify$3(value.toJSON()); + prefetchInfiniteQuery(options) { + return this.fetchInfiniteQuery(options).then(noop$2).catch(noop$2); } - switch (typeof value) { - case "boolean": - case "symbol": - return value.toString(); - case "bigint": - return BigInt(value).toString(); - case "number": - return value.toString(); - case "string": - return JSON.stringify(value); - case "object": { - const keys = Object.keys(value); - keys.sort(); - return "{ " + keys.map((k2) => `${stringify$3(k2)}: ${stringify$3(value[k2])}`).join(", ") + " }"; - } + ensureInfiniteQueryData(options) { + options.behavior = infiniteQueryBehavior(options.pages); + return this.ensureQueryData(options); } - return `[ COULD NOT SERIALIZE ]`; -} -function isError(error, code2) { - return error && error.code === code2; -} -function isCallException(error) { - return isError(error, "CALL_EXCEPTION"); -} -function makeError(message, code2, info) { - let shortMessage = message; - { - const details = []; - if (info) { - if ("message" in info || "code" in info || "name" in info) { - throw new Error(`value will overwrite populated values: ${stringify$3(info)}`); - } - for (const key in info) { - if (key === "shortMessage") { - continue; - } - const value = info[key]; - details.push(key + "=" + stringify$3(value)); - } - } - details.push(`code=${code2}`); - details.push(`version=${version$9}`); - if (details.length) { - message += " (" + details.join(", ") + ")"; + resumePausedMutations() { + if (onlineManager.isOnline()) { + return __privateGet(this, _mutationCache2).resumePausedMutations(); } + return Promise.resolve(); } - let error; - switch (code2) { - case "INVALID_ARGUMENT": - error = new TypeError(message); - break; - case "NUMERIC_FAULT": - case "BUFFER_OVERRUN": - error = new RangeError(message); - break; - default: - error = new Error(message); - } - defineProperties$1(error, { code: code2 }); - if (info) { - Object.assign(error, info); + getQueryCache() { + return __privateGet(this, _queryCache); } - if (error.shortMessage == null) { - defineProperties$1(error, { shortMessage }); + getMutationCache() { + return __privateGet(this, _mutationCache2); } - return error; -} -function assert(check, message, code2, info) { - if (!check) { - throw makeError(message, code2, info); + getDefaultOptions() { + return __privateGet(this, _defaultOptions2); } -} -function assertArgument(check, message, name2, value) { - assert(check, message, "INVALID_ARGUMENT", { argument: name2, value }); -} -function assertArgumentCount(count2, expectedCount, message) { - if (message == null) { - message = ""; + setDefaultOptions(options) { + __privateSet(this, _defaultOptions2, options); } - if (message) { - message = ": " + message; + setQueryDefaults(queryKey, options) { + __privateGet(this, _queryDefaults).set(hashKey(queryKey), { + queryKey, + defaultOptions: options + }); } - assert(count2 >= expectedCount, "missing arguemnt" + message, "MISSING_ARGUMENT", { - count: count2, - expectedCount - }); - assert(count2 <= expectedCount, "too many arguments" + message, "UNEXPECTED_ARGUMENT", { - count: count2, - expectedCount - }); -} -const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => { - try { - if ("test".normalize(form) !== "test") { - throw new Error("bad"); - } - ; - if (form === "NFD") { - const check = String.fromCharCode(233).normalize("NFD"); - const expected = String.fromCharCode(101, 769); - if (check !== expected) { - throw new Error("broken"); + getQueryDefaults(queryKey) { + const defaults2 = [...__privateGet(this, _queryDefaults).values()]; + let result = {}; + defaults2.forEach((queryDefault) => { + if (partialMatchKey(queryKey, queryDefault.queryKey)) { + result = { ...result, ...queryDefault.defaultOptions }; } - } - accum.push(form); - } catch (error) { + }); + return result; } - return accum; -}, []); -function assertNormalize(form) { - assert(_normalizeForms.indexOf(form) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", { - operation: "String.prototype.normalize", - info: { form } - }); -} -function assertPrivate(givenGuard, guard2, className) { - if (className == null) { - className = ""; + setMutationDefaults(mutationKey, options) { + __privateGet(this, _mutationDefaults).set(hashKey(mutationKey), { + mutationKey, + defaultOptions: options + }); } - if (givenGuard !== guard2) { - let method = className, operation = "new"; - if (className) { - method += "."; - operation += " " + className; - } - assert(false, `private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", { - operation + getMutationDefaults(mutationKey) { + const defaults2 = [...__privateGet(this, _mutationDefaults).values()]; + let result = {}; + defaults2.forEach((queryDefault) => { + if (partialMatchKey(mutationKey, queryDefault.mutationKey)) { + result = { ...result, ...queryDefault.defaultOptions }; + } }); + return result; } -} -function _getBytes(value, name2, copy2) { - if (value instanceof Uint8Array) { - if (copy2) { - return new Uint8Array(value); + defaultQueryOptions(options) { + if (options._defaulted) { + return options; } - return value; - } - if (typeof value === "string" && value.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)) { - const result = new Uint8Array((value.length - 2) / 2); - let offset2 = 2; - for (let i = 0; i < result.length; i++) { - result[i] = parseInt(value.substring(offset2, offset2 + 2), 16); - offset2 += 2; + const defaultedOptions = { + ...__privateGet(this, _defaultOptions2).queries, + ...this.getQueryDefaults(options.queryKey), + ...options, + _defaulted: true + }; + if (!defaultedOptions.queryHash) { + defaultedOptions.queryHash = hashQueryKeyByOptions( + defaultedOptions.queryKey, + defaultedOptions + ); } - return result; - } - assertArgument(false, "invalid BytesLike value", name2 || "value", value); -} -function getBytes(value, name2) { - return _getBytes(value, name2, false); -} -function getBytesCopy(value, name2) { - return _getBytes(value, name2, true); -} -function isHexString(value, length) { - if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { - return false; - } - if (typeof length === "number" && value.length !== 2 + 2 * length) { - return false; - } - if (length === true && value.length % 2 !== 0) { - return false; - } - return true; -} -function isBytesLike(value) { - return isHexString(value, true) || value instanceof Uint8Array; -} -const HexCharacters = "0123456789abcdef"; -function hexlify(data) { - const bytes2 = getBytes(data); - let result = "0x"; - for (let i = 0; i < bytes2.length; i++) { - const v3 = bytes2[i]; - result += HexCharacters[(v3 & 240) >> 4] + HexCharacters[v3 & 15]; - } - return result; -} -function concat$1(datas) { - return "0x" + datas.map((d2) => hexlify(d2).substring(2)).join(""); -} -function dataLength(data) { - if (isHexString(data, true)) { - return (data.length - 2) / 2; - } - return getBytes(data).length; -} -function dataSlice(data, start, end) { - const bytes2 = getBytes(data); - if (end != null && end > bytes2.length) { - assert(false, "cannot slice beyond data bounds", "BUFFER_OVERRUN", { - buffer: bytes2, - length: bytes2.length, - offset: end - }); + if (defaultedOptions.refetchOnReconnect === void 0) { + defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always"; + } + if (defaultedOptions.throwOnError === void 0) { + defaultedOptions.throwOnError = !!defaultedOptions.suspense; + } + if (!defaultedOptions.networkMode && defaultedOptions.persister) { + defaultedOptions.networkMode = "offlineFirst"; + } + if (defaultedOptions.enabled !== true && defaultedOptions.queryFn === skipToken) { + defaultedOptions.enabled = false; + } + return defaultedOptions; } - return hexlify(bytes2.slice(start == null ? 0 : start, end == null ? bytes2.length : end)); -} -function stripZerosLeft(data) { - let bytes2 = hexlify(data).substring(2); - while (bytes2.startsWith("00")) { - bytes2 = bytes2.substring(2); + defaultMutationOptions(options) { + if (options == null ? void 0 : options._defaulted) { + return options; + } + return { + ...__privateGet(this, _defaultOptions2).mutations, + ...(options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey), + ...options, + _defaulted: true + }; } - return "0x" + bytes2; -} -function zeroPad(data, length, left) { - const bytes2 = getBytes(data); - assert(length >= bytes2.length, "padding exceeds data length", "BUFFER_OVERRUN", { - buffer: new Uint8Array(bytes2), - length, - offset: length + 1 - }); - const result = new Uint8Array(length); - result.fill(0); - if (left) { - result.set(bytes2, length - bytes2.length); - } else { - result.set(bytes2, 0); + clear() { + __privateGet(this, _queryCache).clear(); + __privateGet(this, _mutationCache2).clear(); } - return hexlify(result); -} -function zeroPadValue(data, length) { - return zeroPad(data, length, true); -} -function zeroPadBytes(data, length) { - return zeroPad(data, length, false); -} -const BN_0$a = BigInt(0); -const BN_1$5 = BigInt(1); -const maxValue = 9007199254740991; -function fromTwos(_value2, _width) { - const value = getUint(_value2, "value"); - const width = BigInt(getNumber(_width, "width")); - assert(value >> width === BN_0$a, "overflow", "NUMERIC_FAULT", { - operation: "fromTwos", - fault: "overflow", - value: _value2 - }); - if (value >> width - BN_1$5) { - const mask2 = (BN_1$5 << width) - BN_1$5; - return -((~value & mask2) + BN_1$5); +}, _queryCache = new WeakMap(), _mutationCache2 = new WeakMap(), _defaultOptions2 = new WeakMap(), _queryDefaults = new WeakMap(), _mutationDefaults = new WeakMap(), _mountCount = new WeakMap(), _unsubscribeFocus = new WeakMap(), _unsubscribeOnline = new WeakMap(), _h); +var QueryObserver = (_i = class extends Subscribable { + constructor(client2, options) { + super(); + __privateAdd(this, _QueryObserver_instances); + __privateAdd(this, _client); + __privateAdd(this, _currentQuery); + __privateAdd(this, _currentQueryInitialState); + __privateAdd(this, _currentResult); + __privateAdd(this, _currentResultState); + __privateAdd(this, _currentResultOptions); + __privateAdd(this, _selectError); + __privateAdd(this, _selectFn); + __privateAdd(this, _selectResult); + // This property keeps track of the last query with defined data. + // It will be used to pass the previous data and query to the placeholder function between renders. + __privateAdd(this, _lastQueryWithDefinedData); + __privateAdd(this, _staleTimeoutId); + __privateAdd(this, _refetchIntervalId); + __privateAdd(this, _currentRefetchInterval); + __privateAdd(this, _trackedProps, /* @__PURE__ */ new Set()); + this.options = options; + __privateSet(this, _client, client2); + __privateSet(this, _selectError, null); + this.bindMethods(); + this.setOptions(options); } - return value; -} -function toTwos(_value2, _width) { - let value = getBigInt(_value2, "value"); - const width = BigInt(getNumber(_width, "width")); - const limit = BN_1$5 << width - BN_1$5; - if (value < BN_0$a) { - value = -value; - assert(value <= limit, "too low", "NUMERIC_FAULT", { - operation: "toTwos", - fault: "overflow", - value: _value2 - }); - const mask2 = (BN_1$5 << width) - BN_1$5; - return (~value & mask2) + BN_1$5; - } else { - assert(value < limit, "too high", "NUMERIC_FAULT", { - operation: "toTwos", - fault: "overflow", - value: _value2 - }); + bindMethods() { + this.refetch = this.refetch.bind(this); } - return value; -} -function mask(_value2, _bits) { - const value = getUint(_value2, "value"); - const bits = BigInt(getNumber(_bits, "bits")); - return value & (BN_1$5 << bits) - BN_1$5; -} -function getBigInt(value, name2) { - switch (typeof value) { - case "bigint": - return value; - case "number": - assertArgument(Number.isInteger(value), "underflow", name2 || "value", value); - assertArgument(value >= -maxValue && value <= maxValue, "overflow", name2 || "value", value); - return BigInt(value); - case "string": - try { - if (value === "") { - throw new Error("empty string"); - } - if (value[0] === "-" && value[1] !== "-") { - return -BigInt(value.substring(1)); - } - return BigInt(value); - } catch (e2) { - assertArgument(false, `invalid BigNumberish string: ${e2.message}`, name2 || "value", value); + onSubscribe() { + if (this.listeners.size === 1) { + __privateGet(this, _currentQuery).addObserver(this); + if (shouldFetchOnMount(__privateGet(this, _currentQuery), this.options)) { + __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this); + } else { + this.updateResult(); } - } - assertArgument(false, "invalid BigNumberish value", name2 || "value", value); -} -function getUint(value, name2) { - const result = getBigInt(value, name2); - assert(result >= BN_0$a, "unsigned value cannot be negative", "NUMERIC_FAULT", { - fault: "overflow", - operation: "getUint", - value - }); - return result; -} -const Nibbles$1 = "0123456789abcdef"; -function toBigInt(value) { - if (value instanceof Uint8Array) { - let result = "0x0"; - for (const v3 of value) { - result += Nibbles$1[v3 >> 4]; - result += Nibbles$1[v3 & 15]; + __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this); } - return BigInt(result); - } - return getBigInt(value); -} -function getNumber(value, name2) { - switch (typeof value) { - case "bigint": - assertArgument(value >= -maxValue && value <= maxValue, "overflow", name2 || "value", value); - return Number(value); - case "number": - assertArgument(Number.isInteger(value), "underflow", name2 || "value", value); - assertArgument(value >= -maxValue && value <= maxValue, "overflow", name2 || "value", value); - return value; - case "string": - try { - if (value === "") { - throw new Error("empty string"); - } - return getNumber(BigInt(value), name2); - } catch (e2) { - assertArgument(false, `invalid numeric string: ${e2.message}`, name2 || "value", value); - } } - assertArgument(false, "invalid numeric value", name2 || "value", value); -} -function toNumber(value) { - return getNumber(toBigInt(value)); -} -function toBeHex(_value2, _width) { - const value = getUint(_value2, "value"); - let result = value.toString(16); - if (_width == null) { - if (result.length % 2) { - result = "0" + result; - } - } else { - const width = getNumber(_width, "width"); - assert(width * 2 >= result.length, `value exceeds width (${width} bytes)`, "NUMERIC_FAULT", { - operation: "toBeHex", - fault: "overflow", - value: _value2 - }); - while (result.length < width * 2) { - result = "0" + result; + onUnsubscribe() { + if (!this.hasListeners()) { + this.destroy(); } } - return "0x" + result; -} -function toBeArray(_value2) { - const value = getUint(_value2, "value"); - if (value === BN_0$a) { - return new Uint8Array([]); - } - let hex2 = value.toString(16); - if (hex2.length % 2) { - hex2 = "0" + hex2; + shouldFetchOnReconnect() { + return shouldFetchOn( + __privateGet(this, _currentQuery), + this.options, + this.options.refetchOnReconnect + ); } - const result = new Uint8Array(hex2.length / 2); - for (let i = 0; i < result.length; i++) { - const offset2 = i * 2; - result[i] = parseInt(hex2.substring(offset2, offset2 + 2), 16); + shouldFetchOnWindowFocus() { + return shouldFetchOn( + __privateGet(this, _currentQuery), + this.options, + this.options.refetchOnWindowFocus + ); } - return result; -} -function toQuantity(value) { - let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2); - while (result.startsWith("0")) { - result = result.substring(1); + destroy() { + this.listeners = /* @__PURE__ */ new Set(); + __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this); + __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this); + __privateGet(this, _currentQuery).removeObserver(this); } - if (result === "") { - result = "0"; + setOptions(options, notifyOptions) { + const prevOptions = this.options; + const prevQuery = __privateGet(this, _currentQuery); + this.options = __privateGet(this, _client).defaultQueryOptions(options); + if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== "boolean") { + throw new Error( + "Expected enabled to be a boolean or a callback that returns a boolean" + ); + } + __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this); + __privateGet(this, _currentQuery).setOptions(this.options); + if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) { + __privateGet(this, _client).getQueryCache().notify({ + type: "observerOptionsUpdated", + query: __privateGet(this, _currentQuery), + observer: this + }); + } + const mounted = this.hasListeners(); + if (mounted && shouldFetchOptionally( + __privateGet(this, _currentQuery), + prevQuery, + this.options, + prevOptions + )) { + __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this); + } + this.updateResult(notifyOptions); + if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || resolveStaleTime(this.options.staleTime, __privateGet(this, _currentQuery)) !== resolveStaleTime(prevOptions.staleTime, __privateGet(this, _currentQuery)))) { + __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this); + } + const nextRefetchInterval = __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this); + if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || nextRefetchInterval !== __privateGet(this, _currentRefetchInterval))) { + __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, nextRefetchInterval); + } } - return "0x" + result; -} -const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; -let Lookup = null; -function getAlpha(letter) { - if (Lookup == null) { - Lookup = {}; - for (let i = 0; i < Alphabet.length; i++) { - Lookup[Alphabet[i]] = BigInt(i); + getOptimisticResult(options) { + const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), options); + const result = this.createResult(query, options); + if (shouldAssignObserverCurrentProperties(this, result)) { + __privateSet(this, _currentResult, result); + __privateSet(this, _currentResultOptions, this.options); + __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state); } + return result; } - const result = Lookup[letter]; - assertArgument(result != null, `invalid base58 value`, "letter", letter); - return result; -} -const BN_0$9 = BigInt(0); -const BN_58 = BigInt(58); -function encodeBase58(_value2) { - const bytes2 = getBytes(_value2); - let value = toBigInt(bytes2); - let result = ""; - while (value) { - result = Alphabet[Number(value % BN_58)] + result; - value /= BN_58; + getCurrentResult() { + return __privateGet(this, _currentResult); } - for (let i = 0; i < bytes2.length; i++) { - if (bytes2[i]) { - break; - } - result = Alphabet[0] + result; + trackResult(result, onPropTracked) { + const trackedResult = {}; + Object.keys(result).forEach((key) => { + Object.defineProperty(trackedResult, key, { + configurable: false, + enumerable: true, + get: () => { + this.trackProp(key); + onPropTracked == null ? void 0 : onPropTracked(key); + return result[key]; + } + }); + }); + return trackedResult; } - return result; -} -function decodeBase58(value) { - let result = BN_0$9; - for (let i = 0; i < value.length; i++) { - result *= BN_58; - result += getAlpha(value[i]); + trackProp(key) { + __privateGet(this, _trackedProps).add(key); } - return result; -} -function decodeBase64(textData) { - textData = atob(textData); - const data = new Uint8Array(textData.length); - for (let i = 0; i < textData.length; i++) { - data[i] = textData.charCodeAt(i); + getCurrentQuery() { + return __privateGet(this, _currentQuery); } - return getBytes(data); -} -function encodeBase64(_data6) { - const data = getBytes(_data6); - let textData = ""; - for (let i = 0; i < data.length; i++) { - textData += String.fromCharCode(data[i]); + refetch({ ...options } = {}) { + return this.fetch({ + ...options + }); } - return btoa(textData); -} -class EventPayload { - /** - * Create a new **EventPayload** for %%emitter%% with - * the %%listener%% and for %%filter%%. - */ - constructor(emitter, listener, filter2) { - /** - * The event filter. - */ - __publicField(this, "filter"); - /** - * The **EventEmitterable**. - */ - __publicField(this, "emitter"); - __privateAdd(this, _listener); - __privateSet(this, _listener, listener); - defineProperties$1(this, { emitter, filter: filter2 }); + fetchOptimistic(options) { + const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options); + const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), defaultedOptions); + query.isFetchingOptimistic = true; + return query.fetch().then(() => this.createResult(query, defaultedOptions)); } - /** - * Unregister the triggered listener for future events. - */ - async removeListener() { - if (__privateGet(this, _listener) == null) { - return; - } - await this.emitter.off(this.filter, __privateGet(this, _listener)); + fetch(fetchOptions) { + return __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this, { + ...fetchOptions, + cancelRefetch: fetchOptions.cancelRefetch ?? true + }).then(() => { + this.updateResult(); + return __privateGet(this, _currentResult); + }); } -} -_listener = new WeakMap(); -function errorFunc(reason, offset2, bytes2, output2, badCodepoint) { - assertArgument(false, `invalid codepoint at offset ${offset2}; ${reason}`, "bytes", bytes2); -} -function ignoreFunc(reason, offset2, bytes2, output2, badCodepoint) { - if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") { - let i = 0; - for (let o2 = offset2 + 1; o2 < bytes2.length; o2++) { - if (bytes2[o2] >> 6 !== 2) { - break; + createResult(query, options) { + var _a2; + const prevQuery = __privateGet(this, _currentQuery); + const prevOptions = this.options; + const prevResult = __privateGet(this, _currentResult); + const prevResultState = __privateGet(this, _currentResultState); + const prevResultOptions = __privateGet(this, _currentResultOptions); + const queryChange = query !== prevQuery; + const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState); + const { state } = query; + let newState = { ...state }; + let isPlaceholderData = false; + let data; + if (options._optimisticResults) { + const mounted = this.hasListeners(); + const fetchOnMount = !mounted && shouldFetchOnMount(query, options); + const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions); + if (fetchOnMount || fetchOptionally) { + newState = { + ...newState, + ...fetchState(state.data, query.options) + }; + } + if (options._optimisticResults === "isRestoring") { + newState.fetchStatus = "idle"; } - i++; } - return i; - } - if (reason === "OVERRUN") { - return bytes2.length - offset2 - 1; - } - return 0; -} -function replaceFunc(reason, offset2, bytes2, output2, badCodepoint) { - if (reason === "OVERLONG") { - assertArgument(typeof badCodepoint === "number", "invalid bad code point for replacement", "badCodepoint", badCodepoint); - output2.push(badCodepoint); - return 0; - } - output2.push(65533); - return ignoreFunc(reason, offset2, bytes2); -} -const Utf8ErrorFuncs = Object.freeze({ - error: errorFunc, - ignore: ignoreFunc, - replace: replaceFunc -}); -function getUtf8CodePoints(_bytes, onError) { - if (onError == null) { - onError = Utf8ErrorFuncs.error; - } - const bytes2 = getBytes(_bytes, "bytes"); - const result = []; - let i = 0; - while (i < bytes2.length) { - const c2 = bytes2[i++]; - if (c2 >> 7 === 0) { - result.push(c2); - continue; - } - let extraLength = null; - let overlongMask = null; - if ((c2 & 224) === 192) { - extraLength = 1; - overlongMask = 127; - } else if ((c2 & 240) === 224) { - extraLength = 2; - overlongMask = 2047; - } else if ((c2 & 248) === 240) { - extraLength = 3; - overlongMask = 65535; - } else { - if ((c2 & 192) === 128) { - i += onError("UNEXPECTED_CONTINUE", i - 1, bytes2, result); + let { error, errorUpdatedAt, status } = newState; + if (options.select && newState.data !== void 0) { + if (prevResult && newState.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === __privateGet(this, _selectFn)) { + data = __privateGet(this, _selectResult); } else { - i += onError("BAD_PREFIX", i - 1, bytes2, result); + try { + __privateSet(this, _selectFn, options.select); + data = options.select(newState.data); + data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options); + __privateSet(this, _selectResult, data); + __privateSet(this, _selectError, null); + } catch (selectError) { + __privateSet(this, _selectError, selectError); + } } - continue; - } - if (i - 1 + extraLength >= bytes2.length) { - i += onError("OVERRUN", i - 1, bytes2, result); - continue; + } else { + data = newState.data; } - let res = c2 & (1 << 8 - extraLength - 1) - 1; - for (let j2 = 0; j2 < extraLength; j2++) { - let nextChar = bytes2[i]; - if ((nextChar & 192) != 128) { - i += onError("MISSING_CONTINUE", i, bytes2, result); - res = null; - break; + if (options.placeholderData !== void 0 && data === void 0 && status === "pending") { + let placeholderData; + if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) { + placeholderData = prevResult.data; + } else { + placeholderData = typeof options.placeholderData === "function" ? options.placeholderData( + (_a2 = __privateGet(this, _lastQueryWithDefinedData)) == null ? void 0 : _a2.state.data, + __privateGet(this, _lastQueryWithDefinedData) + ) : options.placeholderData; + if (options.select && placeholderData !== void 0) { + try { + placeholderData = options.select(placeholderData); + __privateSet(this, _selectError, null); + } catch (selectError) { + __privateSet(this, _selectError, selectError); + } + } + } + if (placeholderData !== void 0) { + status = "success"; + data = replaceData( + prevResult == null ? void 0 : prevResult.data, + placeholderData, + options + ); + isPlaceholderData = true; } - res = res << 6 | nextChar & 63; - i++; } - if (res === null) { - continue; + if (__privateGet(this, _selectError)) { + error = __privateGet(this, _selectError); + data = __privateGet(this, _selectResult); + errorUpdatedAt = Date.now(); + status = "error"; } - if (res > 1114111) { - i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes2, result, res); - continue; + const isFetching = newState.fetchStatus === "fetching"; + const isPending = status === "pending"; + const isError2 = status === "error"; + const isLoading = isPending && isFetching; + const hasData = data !== void 0; + const result = { + status, + fetchStatus: newState.fetchStatus, + isPending, + isSuccess: status === "success", + isError: isError2, + isInitialLoading: isLoading, + isLoading, + data, + dataUpdatedAt: newState.dataUpdatedAt, + error, + errorUpdatedAt, + failureCount: newState.fetchFailureCount, + failureReason: newState.fetchFailureReason, + errorUpdateCount: newState.errorUpdateCount, + isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0, + isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount, + isFetching, + isRefetching: isFetching && !isPending, + isLoadingError: isError2 && !hasData, + isPaused: newState.fetchStatus === "paused", + isPlaceholderData, + isRefetchError: isError2 && hasData, + isStale: isStale(query, options), + refetch: this.refetch + }; + return result; + } + updateResult(notifyOptions) { + const prevResult = __privateGet(this, _currentResult); + const nextResult = this.createResult(__privateGet(this, _currentQuery), this.options); + __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state); + __privateSet(this, _currentResultOptions, this.options); + if (__privateGet(this, _currentResultState).data !== void 0) { + __privateSet(this, _lastQueryWithDefinedData, __privateGet(this, _currentQuery)); } - if (res >= 55296 && res <= 57343) { - i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes2, result, res); - continue; + if (shallowEqualObjects(nextResult, prevResult)) { + return; } - if (res <= overlongMask) { - i += onError("OVERLONG", i - 1 - extraLength, bytes2, result, res); - continue; + __privateSet(this, _currentResult, nextResult); + const defaultNotifyOptions = {}; + const shouldNotifyListeners = () => { + if (!prevResult) { + return true; + } + const { notifyOnChangeProps } = this.options; + const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps; + if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !__privateGet(this, _trackedProps).size) { + return true; + } + const includedProps = new Set( + notifyOnChangePropsValue ?? __privateGet(this, _trackedProps) + ); + if (this.options.throwOnError) { + includedProps.add("error"); + } + return Object.keys(__privateGet(this, _currentResult)).some((key) => { + const typedKey = key; + const changed = __privateGet(this, _currentResult)[typedKey] !== prevResult[typedKey]; + return changed && includedProps.has(typedKey); + }); + }; + if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) { + defaultNotifyOptions.listeners = true; } - result.push(res); + __privateMethod(this, _QueryObserver_instances, notify_fn).call(this, { ...defaultNotifyOptions, ...notifyOptions }); } - return result; -} -function toUtf8Bytes(str, form) { - assertArgument(typeof str === "string", "invalid string value", "str", str); - if (form != null) { - assertNormalize(form); - str = str.normalize(form); + onQueryUpdate() { + this.updateResult(); + if (this.hasListeners()) { + __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this); + } } - let result = []; - for (let i = 0; i < str.length; i++) { - const c2 = str.charCodeAt(i); - if (c2 < 128) { - result.push(c2); - } else if (c2 < 2048) { - result.push(c2 >> 6 | 192); - result.push(c2 & 63 | 128); - } else if ((c2 & 64512) == 55296) { - i++; - const c22 = str.charCodeAt(i); - assertArgument(i < str.length && (c22 & 64512) === 56320, "invalid surrogate pair", "str", str); - const pair = 65536 + ((c2 & 1023) << 10) + (c22 & 1023); - result.push(pair >> 18 | 240); - result.push(pair >> 12 & 63 | 128); - result.push(pair >> 6 & 63 | 128); - result.push(pair & 63 | 128); - } else { - result.push(c2 >> 12 | 224); - result.push(c2 >> 6 & 63 | 128); - result.push(c2 & 63 | 128); +}, _client = new WeakMap(), _currentQuery = new WeakMap(), _currentQueryInitialState = new WeakMap(), _currentResult = new WeakMap(), _currentResultState = new WeakMap(), _currentResultOptions = new WeakMap(), _selectError = new WeakMap(), _selectFn = new WeakMap(), _selectResult = new WeakMap(), _lastQueryWithDefinedData = new WeakMap(), _staleTimeoutId = new WeakMap(), _refetchIntervalId = new WeakMap(), _currentRefetchInterval = new WeakMap(), _trackedProps = new WeakMap(), _QueryObserver_instances = new WeakSet(), executeFetch_fn = function(fetchOptions) { + __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this); + let promise = __privateGet(this, _currentQuery).fetch( + this.options, + fetchOptions + ); + if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) { + promise = promise.catch(noop$2); + } + return promise; +}, updateStaleTimeout_fn = function() { + __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this); + const staleTime = resolveStaleTime( + this.options.staleTime, + __privateGet(this, _currentQuery) + ); + if (isServer || __privateGet(this, _currentResult).isStale || !isValidTimeout(staleTime)) { + return; + } + const time2 = timeUntilStale(__privateGet(this, _currentResult).dataUpdatedAt, staleTime); + const timeout = time2 + 1; + __privateSet(this, _staleTimeoutId, setTimeout(() => { + if (!__privateGet(this, _currentResult).isStale) { + this.updateResult(); } + }, timeout)); +}, computeRefetchInterval_fn = function() { + return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(__privateGet(this, _currentQuery)) : this.options.refetchInterval) ?? false; +}, updateRefetchInterval_fn = function(nextInterval) { + __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this); + __privateSet(this, _currentRefetchInterval, nextInterval); + if (isServer || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) === false || !isValidTimeout(__privateGet(this, _currentRefetchInterval)) || __privateGet(this, _currentRefetchInterval) === 0) { + return; } - return new Uint8Array(result); -} -function _toUtf8String(codePoints) { - return codePoints.map((codePoint) => { - if (codePoint <= 65535) { - return String.fromCharCode(codePoint); + __privateSet(this, _refetchIntervalId, setInterval(() => { + if (this.options.refetchIntervalInBackground || focusManager.isFocused()) { + __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this); } - codePoint -= 65536; - return String.fromCharCode((codePoint >> 10 & 1023) + 55296, (codePoint & 1023) + 56320); - }).join(""); -} -function toUtf8String(bytes2, onError) { - return _toUtf8String(getUtf8CodePoints(bytes2, onError)); -} -function toUtf8CodePoints(str, form) { - return getUtf8CodePoints(toUtf8Bytes(str, form)); -} -function createGetUrl(options) { - async function getUrl2(req, _signal2) { - assert(_signal2 == null || !_signal2.cancelled, "request cancelled before sending", "CANCELLED"); - const protocol = req.url.split(":")[0].toLowerCase(); - assert(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { - info: { protocol }, - operation: "request" - }); - assert(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { - operation: "request" - }); - let error = null; - const controller = new AbortController(); - const timer = setTimeout(() => { - error = makeError("request timeout", "TIMEOUT"); - controller.abort(); - }, req.timeout); - if (_signal2) { - _signal2.addListener(() => { - error = makeError("request cancelled", "CANCELLED"); - controller.abort(); + }, __privateGet(this, _currentRefetchInterval))); +}, updateTimers_fn = function() { + __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this); + __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this)); +}, clearStaleTimeout_fn = function() { + if (__privateGet(this, _staleTimeoutId)) { + clearTimeout(__privateGet(this, _staleTimeoutId)); + __privateSet(this, _staleTimeoutId, void 0); + } +}, clearRefetchInterval_fn = function() { + if (__privateGet(this, _refetchIntervalId)) { + clearInterval(__privateGet(this, _refetchIntervalId)); + __privateSet(this, _refetchIntervalId, void 0); + } +}, updateQuery_fn = function() { + const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), this.options); + if (query === __privateGet(this, _currentQuery)) { + return; + } + const prevQuery = __privateGet(this, _currentQuery); + __privateSet(this, _currentQuery, query); + __privateSet(this, _currentQueryInitialState, query.state); + if (this.hasListeners()) { + prevQuery == null ? void 0 : prevQuery.removeObserver(this); + query.addObserver(this); + } +}, notify_fn = function(notifyOptions) { + notifyManager.batch(() => { + if (notifyOptions.listeners) { + this.listeners.forEach((listener) => { + listener(__privateGet(this, _currentResult)); }); } - const init2 = { - method: req.method, - headers: new Headers(Array.from(req)), - body: req.body || void 0, - signal: controller.signal - }; - let resp; - try { - resp = await fetch(req.url, init2); - } catch (_error2) { - clearTimeout(timer); - if (error) { - throw error; - } - throw _error2; - } - clearTimeout(timer); - const headers = {}; - resp.headers.forEach((value, key) => { - headers[key.toLowerCase()] = value; + __privateGet(this, _client).getQueryCache().notify({ + query: __privateGet(this, _currentQuery), + type: "observerResultsUpdated" }); - const respBody = await resp.arrayBuffer(); - const body = respBody == null ? null : new Uint8Array(respBody); - return { - statusCode: resp.status, - statusMessage: resp.statusText, - headers, - body - }; - } - return getUrl2; + }); +}, _i); +function shouldLoadOnMount(query, options) { + return resolveEnabled(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && options.retryOnMount === false); } -const MAX_ATTEMPTS = 12; -const SLOT_INTERVAL = 250; -let defaultGetUrlFunc = createGetUrl(); -const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); -const reIpfs = new RegExp("^ipfs://(ipfs/)?(.*)$", "i"); -let locked$5 = false; -async function dataGatewayFunc(url, signal) { - try { - const match = url.match(reData); - if (!match) { - throw new Error("invalid data"); - } - return new FetchResponse(200, "OK", { - "content-type": match[1] || "text/plain" - }, match[2] ? decodeBase64(match[3]) : unpercent(match[3])); - } catch (error) { - return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url)); +function shouldFetchOnMount(query, options) { + return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount); +} +function shouldFetchOn(query, options, field) { + if (resolveEnabled(options.enabled, query) !== false) { + const value = typeof field === "function" ? field(query) : field; + return value === "always" || value !== false && isStale(query, options); } + return false; } -function getIpfsGatewayFunc(baseUrl) { - async function gatewayIpfs(url, signal) { - try { - const match = url.match(reIpfs); - if (!match) { - throw new Error("invalid link"); - } - return new FetchRequest(`${baseUrl}${match[2]}`); - } catch (error) { - return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url)); - } +function shouldFetchOptionally(query, prevQuery, options, prevOptions) { + return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options); +} +function isStale(query, options) { + return resolveEnabled(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query)); +} +function shouldAssignObserverCurrentProperties(observer, optimisticResult) { + if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) { + return true; } - return gatewayIpfs; + return false; } -const Gateways = { - "data": dataGatewayFunc, - "ipfs": getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/") -}; -const fetchSignals = /* @__PURE__ */ new WeakMap(); -class FetchCancelSignal { - constructor(request) { - __privateAdd(this, _listeners); - __privateAdd(this, _cancelled); - __privateSet(this, _listeners, []); - __privateSet(this, _cancelled, false); - fetchSignals.set(request, () => { - if (__privateGet(this, _cancelled)) { - return; - } - __privateSet(this, _cancelled, true); - for (const listener of __privateGet(this, _listeners)) { - setTimeout(() => { - listener(); - }, 0); +var InfiniteQueryObserver = class extends QueryObserver { + constructor(client2, options) { + super(client2, options); + } + bindMethods() { + super.bindMethods(); + this.fetchNextPage = this.fetchNextPage.bind(this); + this.fetchPreviousPage = this.fetchPreviousPage.bind(this); + } + setOptions(options, notifyOptions) { + super.setOptions( + { + ...options, + behavior: infiniteQueryBehavior() + }, + notifyOptions + ); + } + getOptimisticResult(options) { + options.behavior = infiniteQueryBehavior(); + return super.getOptimisticResult(options); + } + fetchNextPage(options) { + return this.fetch({ + ...options, + meta: { + fetchMore: { direction: "forward" } } - __privateSet(this, _listeners, []); }); } - addListener(listener) { - assert(!__privateGet(this, _cancelled), "singal already cancelled", "UNSUPPORTED_OPERATION", { - operation: "fetchCancelSignal.addCancelListener" + fetchPreviousPage(options) { + return this.fetch({ + ...options, + meta: { + fetchMore: { direction: "backward" } + } }); - __privateGet(this, _listeners).push(listener); } - get cancelled() { - return __privateGet(this, _cancelled); + createResult(query, options) { + var _a2, _b2; + const { state } = query; + const parentResult = super.createResult(query, options); + const { isFetching, isRefetching, isError: isError2, isRefetchError } = parentResult; + const fetchDirection = (_b2 = (_a2 = state.fetchMeta) == null ? void 0 : _a2.fetchMore) == null ? void 0 : _b2.direction; + const isFetchNextPageError = isError2 && fetchDirection === "forward"; + const isFetchingNextPage = isFetching && fetchDirection === "forward"; + const isFetchPreviousPageError = isError2 && fetchDirection === "backward"; + const isFetchingPreviousPage = isFetching && fetchDirection === "backward"; + const result = { + ...parentResult, + fetchNextPage: this.fetchNextPage, + fetchPreviousPage: this.fetchPreviousPage, + hasNextPage: hasNextPage(options, state.data), + hasPreviousPage: hasPreviousPage(options, state.data), + isFetchNextPageError, + isFetchingNextPage, + isFetchPreviousPageError, + isFetchingPreviousPage, + isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError, + isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage + }; + return result; } - checkSignal() { - assert(!this.cancelled, "cancelled", "CANCELLED", {}); +}; +var MutationObserver$1 = (_j = class extends Subscribable { + constructor(client2, options) { + super(); + __privateAdd(this, _MutationObserver_instances); + __privateAdd(this, _client2); + __privateAdd(this, _currentResult2); + __privateAdd(this, _currentMutation); + __privateAdd(this, _mutateOptions); + __privateSet(this, _client2, client2); + this.setOptions(options); + this.bindMethods(); + __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this); } -} -_listeners = new WeakMap(); -_cancelled = new WeakMap(); -function checkSignal(signal) { - if (signal == null) { - throw new Error("missing signal; should not happen"); + bindMethods() { + this.mutate = this.mutate.bind(this); + this.reset = this.reset.bind(this); } - signal.checkSignal(); - return signal; -} -const _FetchRequest = class _FetchRequest { - /** - * Create a new FetchRequest instance with default values. - * - * Once created, each property may be set before issuing a - * ``.send()`` to make the request. - */ - constructor(url) { - __privateAdd(this, _FetchRequest_instances); - __privateAdd(this, _allowInsecure); - __privateAdd(this, _gzip); - __privateAdd(this, _headers); - __privateAdd(this, _method); - __privateAdd(this, _timeout); - __privateAdd(this, _url); - __privateAdd(this, _body); - __privateAdd(this, _bodyType); - __privateAdd(this, _creds); - // Hooks - __privateAdd(this, _preflight); - __privateAdd(this, _process); - __privateAdd(this, _retry); - __privateAdd(this, _signal); - __privateAdd(this, _throttle); - __privateAdd(this, _getUrlFunc); - __privateSet(this, _url, String(url)); - __privateSet(this, _allowInsecure, false); - __privateSet(this, _gzip, true); - __privateSet(this, _headers, {}); - __privateSet(this, _method, ""); - __privateSet(this, _timeout, 3e5); - __privateSet(this, _throttle, { - slotInterval: SLOT_INTERVAL, - maxAttempts: MAX_ATTEMPTS - }); - __privateSet(this, _getUrlFunc, null); + setOptions(options) { + var _a2; + const prevOptions = this.options; + this.options = __privateGet(this, _client2).defaultMutationOptions(options); + if (!shallowEqualObjects(this.options, prevOptions)) { + __privateGet(this, _client2).getMutationCache().notify({ + type: "observerOptionsUpdated", + mutation: __privateGet(this, _currentMutation), + observer: this + }); + } + if ((prevOptions == null ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) { + this.reset(); + } else if (((_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.state.status) === "pending") { + __privateGet(this, _currentMutation).setOptions(this.options); + } } - /** - * The fetch URL to request. - */ - get url() { - return __privateGet(this, _url); + onUnsubscribe() { + var _a2; + if (!this.hasListeners()) { + (_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.removeObserver(this); + } } - set url(url) { - __privateSet(this, _url, String(url)); + onMutationUpdate(action) { + __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this); + __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this, action); } - /** - * The fetch body, if any, to send as the request body. //(default: null)// - * - * When setting a body, the intrinsic ``Content-Type`` is automatically - * set and will be used if **not overridden** by setting a custom - * header. - * - * If %%body%% is null, the body is cleared (along with the - * intrinsic ``Content-Type``). - * - * If %%body%% is a string, the intrinsic ``Content-Type`` is set to - * ``text/plain``. - * - * If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to - * ``application/octet-stream``. - * - * If %%body%% is any other object, the intrinsic ``Content-Type`` is - * set to ``application/json``. - */ - get body() { - if (__privateGet(this, _body) == null) { - return null; - } - return new Uint8Array(__privateGet(this, _body)); + getCurrentResult() { + return __privateGet(this, _currentResult2); } - set body(body) { - if (body == null) { - __privateSet(this, _body, void 0); - __privateSet(this, _bodyType, void 0); - } else if (typeof body === "string") { - __privateSet(this, _body, toUtf8Bytes(body)); - __privateSet(this, _bodyType, "text/plain"); - } else if (body instanceof Uint8Array) { - __privateSet(this, _body, body); - __privateSet(this, _bodyType, "application/octet-stream"); - } else if (typeof body === "object") { - __privateSet(this, _body, toUtf8Bytes(JSON.stringify(body))); - __privateSet(this, _bodyType, "application/json"); - } else { - throw new Error("invalid body"); - } + reset() { + var _a2; + (_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.removeObserver(this); + __privateSet(this, _currentMutation, void 0); + __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this); + __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this); } - /** - * Returns true if the request has a body. - */ - hasBody() { - return __privateGet(this, _body) != null; + mutate(variables, options) { + var _a2; + __privateSet(this, _mutateOptions, options); + (_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.removeObserver(this); + __privateSet(this, _currentMutation, __privateGet(this, _client2).getMutationCache().build(__privateGet(this, _client2), this.options)); + __privateGet(this, _currentMutation).addObserver(this); + return __privateGet(this, _currentMutation).execute(variables); } - /** - * The HTTP method to use when requesting the URI. If no method - * has been explicitly set, then ``GET`` is used if the body is - * null and ``POST`` otherwise. - */ - get method() { - if (__privateGet(this, _method)) { - return __privateGet(this, _method); - } - if (this.hasBody()) { - return "POST"; +}, _client2 = new WeakMap(), _currentResult2 = new WeakMap(), _currentMutation = new WeakMap(), _mutateOptions = new WeakMap(), _MutationObserver_instances = new WeakSet(), updateResult_fn = function() { + var _a2; + const state = ((_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.state) ?? getDefaultState(); + __privateSet(this, _currentResult2, { + ...state, + isPending: state.status === "pending", + isSuccess: state.status === "success", + isError: state.status === "error", + isIdle: state.status === "idle", + mutate: this.mutate, + reset: this.reset + }); +}, notify_fn2 = function(action) { + notifyManager.batch(() => { + var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2; + if (__privateGet(this, _mutateOptions) && this.hasListeners()) { + const variables = __privateGet(this, _currentResult2).variables; + const context2 = __privateGet(this, _currentResult2).context; + if ((action == null ? void 0 : action.type) === "success") { + (_b2 = (_a2 = __privateGet(this, _mutateOptions)).onSuccess) == null ? void 0 : _b2.call(_a2, action.data, variables, context2); + (_d2 = (_c2 = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _d2.call(_c2, action.data, null, variables, context2); + } else if ((action == null ? void 0 : action.type) === "error") { + (_f2 = (_e2 = __privateGet(this, _mutateOptions)).onError) == null ? void 0 : _f2.call(_e2, action.error, variables, context2); + (_h2 = (_g2 = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _h2.call( + _g2, + void 0, + action.error, + variables, + context2 + ); + } } - return "GET"; + this.listeners.forEach((listener) => { + listener(__privateGet(this, _currentResult2)); + }); + }); +}, _j); +var QueryClientContext = reactExports.createContext( + void 0 +); +var useQueryClient = (queryClient) => { + const client2 = reactExports.useContext(QueryClientContext); + if (!client2) { + throw new Error("No QueryClient set, use QueryClientProvider to set one"); } - set method(method) { - if (method == null) { - method = ""; + return client2; +}; +var QueryClientProvider = ({ + client: client2, + children +}) => { + reactExports.useEffect(() => { + client2.mount(); + return () => { + client2.unmount(); + }; + }, [client2]); + return /* @__PURE__ */ jsxRuntimeExports$1.jsx(QueryClientContext.Provider, { value: client2, children }); +}; +var IsRestoringContext = reactExports.createContext(false); +var useIsRestoring = () => reactExports.useContext(IsRestoringContext); +IsRestoringContext.Provider; +function createValue() { + let isReset = false; + return { + clearReset: () => { + isReset = false; + }, + reset: () => { + isReset = true; + }, + isReset: () => { + return isReset; } - __privateSet(this, _method, String(method).toUpperCase()); + }; +} +var QueryErrorResetBoundaryContext = reactExports.createContext(createValue()); +var useQueryErrorResetBoundary = () => reactExports.useContext(QueryErrorResetBoundaryContext); +function shouldThrowError(throwError2, params) { + if (typeof throwError2 === "function") { + return throwError2(...params); } - /** - * The headers that will be used when requesting the URI. All - * keys are lower-case. - * - * This object is a copy, so any changes will **NOT** be reflected - * in the ``FetchRequest``. - * - * To set a header entry, use the ``setHeader`` method. - */ - get headers() { - const headers = Object.assign({}, __privateGet(this, _headers)); - if (__privateGet(this, _creds)) { - headers["authorization"] = `Basic ${encodeBase64(toUtf8Bytes(__privateGet(this, _creds)))}`; - } - if (this.allowGzip) { - headers["accept-encoding"] = "gzip"; + return !!throwError2; +} +function noop$1() { +} +var ensurePreventErrorBoundaryRetry = (options, errorResetBoundary) => { + if (options.suspense || options.throwOnError) { + if (!errorResetBoundary.isReset()) { + options.retryOnMount = false; } - if (headers["content-type"] == null && __privateGet(this, _bodyType)) { - headers["content-type"] = __privateGet(this, _bodyType); + } +}; +var useClearResetErrorBoundary = (errorResetBoundary) => { + reactExports.useEffect(() => { + errorResetBoundary.clearReset(); + }, [errorResetBoundary]); +}; +var getHasError = ({ + result, + errorResetBoundary, + throwOnError, + query +}) => { + return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && shouldThrowError(throwOnError, [result.error, query]); +}; +var ensureSuspenseTimers = (defaultedOptions) => { + if (defaultedOptions.suspense) { + if (typeof defaultedOptions.staleTime !== "number") { + defaultedOptions.staleTime = 1e3; } - if (this.body) { - headers["content-length"] = String(this.body.length); + if (typeof defaultedOptions.gcTime === "number") { + defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, 1e3); } - return headers; - } - /** - * Get the header for %%key%%, ignoring case. - */ - getHeader(key) { - return this.headers[key.toLowerCase()]; } - /** - * Set the header for %%key%% to %%value%%. All values are coerced - * to a string. - */ - setHeader(key, value) { - __privateGet(this, _headers)[String(key).toLowerCase()] = String(value); +}; +var shouldSuspend = (defaultedOptions, result) => (defaultedOptions == null ? void 0 : defaultedOptions.suspense) && result.isPending; +var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => { + errorResetBoundary.clearReset(); +}); +function useBaseQuery(options, Observer, queryClient) { + var _a2, _b2, _c2, _d2; + const client2 = useQueryClient(); + const isRestoring = useIsRestoring(); + const errorResetBoundary = useQueryErrorResetBoundary(); + const defaultedOptions = client2.defaultQueryOptions(options); + (_b2 = (_a2 = client2.getDefaultOptions().queries) == null ? void 0 : _a2._experimental_beforeQuery) == null ? void 0 : _b2.call( + _a2, + defaultedOptions + ); + defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic"; + ensureSuspenseTimers(defaultedOptions); + ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary); + useClearResetErrorBoundary(errorResetBoundary); + const [observer] = reactExports.useState( + () => new Observer( + client2, + defaultedOptions + ) + ); + const result = observer.getOptimisticResult(defaultedOptions); + reactExports.useSyncExternalStore( + reactExports.useCallback( + (onStoreChange) => { + const unsubscribe = isRestoring ? () => void 0 : observer.subscribe(notifyManager.batchCalls(onStoreChange)); + observer.updateResult(); + return unsubscribe; + }, + [observer, isRestoring] + ), + () => observer.getCurrentResult(), + () => observer.getCurrentResult() + ); + reactExports.useEffect(() => { + observer.setOptions(defaultedOptions, { listeners: false }); + }, [defaultedOptions, observer]); + if (shouldSuspend(defaultedOptions, result)) { + throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary); } - /** - * Clear all headers, resetting all intrinsic headers. - */ - clearHeaders() { - __privateSet(this, _headers, {}); + if (getHasError({ + result, + errorResetBoundary, + throwOnError: defaultedOptions.throwOnError, + query: client2.getQueryCache().get(defaultedOptions.queryHash) + })) { + throw result.error; } - [Symbol.iterator]() { - const headers = this.headers; - const keys = Object.keys(headers); - let index2 = 0; - return { - next: () => { - if (index2 < keys.length) { - const key = keys[index2++]; - return { - value: [key, headers[key]], - done: false - }; - } - return { value: void 0, done: true }; - } - }; + (_d2 = (_c2 = client2.getDefaultOptions().queries) == null ? void 0 : _c2._experimental_afterQuery) == null ? void 0 : _d2.call( + _c2, + defaultedOptions, + result + ); + return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result; +} +function useQuery$1(options, queryClient) { + return useBaseQuery(options, QueryObserver); +} +function useMutation(options, queryClient) { + const client2 = useQueryClient(); + const [observer] = reactExports.useState( + () => new MutationObserver$1( + client2, + options + ) + ); + reactExports.useEffect(() => { + observer.setOptions(options); + }, [observer, options]); + const result = reactExports.useSyncExternalStore( + reactExports.useCallback( + (onStoreChange) => observer.subscribe(notifyManager.batchCalls(onStoreChange)), + [observer] + ), + () => observer.getCurrentResult(), + () => observer.getCurrentResult() + ); + const mutate = reactExports.useCallback( + (variables, mutateOptions) => { + observer.mutate(variables, mutateOptions).catch(noop$1); + }, + [observer] + ); + if (result.error && shouldThrowError(observer.options.throwOnError, [result.error])) { + throw result.error; } - /** - * The value that will be sent for the ``Authorization`` header. - * - * To set the credentials, use the ``setCredentials`` method. - */ - get credentials() { - return __privateGet(this, _creds) || null; + return { ...result, mutate, mutateAsync: result.mutate }; +} +function useInfiniteQuery(options, queryClient) { + return useBaseQuery( + options, + InfiniteQueryObserver + ); +} +const version$9 = "2.21.10"; +let errorConfig = { + getDocsUrl: ({ docsBaseUrl, docsPath: docsPath2 = "", docsSlug }) => docsPath2 ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath2}${docsSlug ? `#${docsSlug}` : ""}` : void 0, + version: version$9 +}; +let BaseError$3 = class BaseError extends Error { + constructor(shortMessage, args = {}) { + var _a2; + const details = (() => { + var _a3; + if (args.cause instanceof BaseError) + return args.cause.details; + if ((_a3 = args.cause) == null ? void 0 : _a3.message) + return args.cause.message; + return args.details; + })(); + const docsPath2 = (() => { + if (args.cause instanceof BaseError) + return args.cause.docsPath || args.docsPath; + return args.docsPath; + })(); + const docsUrl = (_a2 = errorConfig.getDocsUrl) == null ? void 0 : _a2.call(errorConfig, { ...args, docsPath: docsPath2 }); + const message = [ + shortMessage || "An error occurred.", + "", + ...args.metaMessages ? [...args.metaMessages, ""] : [], + ...docsUrl ? [`Docs: ${docsUrl}`] : [], + ...details ? [`Details: ${details}`] : [], + ...[`Version: ${errorConfig.version}`] + ].join("\n"); + super(message, args.cause ? { cause: args.cause } : void 0); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "docsPath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metaMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "version", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "BaseError" + }); + this.details = details; + this.docsPath = docsPath2; + this.metaMessages = args.metaMessages; + this.name = args.name ?? this.name; + this.shortMessage = shortMessage; + this.version = version$9; } - /** - * Sets an ``Authorization`` for %%username%% with %%password%%. - */ - setCredentials(username, password) { - assertArgument(!username.match(/:/), "invalid basic authentication username", "username", "[REDACTED]"); - __privateSet(this, _creds, `${username}:${password}`); + walk(fn) { + return walk(this, fn); } - /** - * Enable and request gzip-encoded responses. The response will - * automatically be decompressed. //(default: true)// - */ - get allowGzip() { - return __privateGet(this, _gzip); +}; +function walk(err, fn) { + if (fn == null ? void 0 : fn(err)) + return err; + if (err && typeof err === "object" && "cause" in err) + return walk(err.cause, fn); + return fn ? null : err; +} +class IntegerOutOfRangeError extends BaseError$3 { + constructor({ max: max2, min: min2, signed: signed2, size: size2, value }) { + super(`Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed2 ? "signed" : "unsigned"} ` : ""}integer range ${max2 ? `(${min2} to ${max2})` : `(above ${min2})`}`, { name: "IntegerOutOfRangeError" }); } - set allowGzip(value) { - __privateSet(this, _gzip, !!value); +} +class InvalidBytesBooleanError extends BaseError$3 { + constructor(bytes2) { + super(`Bytes value "${bytes2}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, { + name: "InvalidBytesBooleanError" + }); } - /** - * Allow ``Authentication`` credentials to be sent over insecure - * channels. //(default: false)// - */ - get allowInsecureAuthentication() { - return !!__privateGet(this, _allowInsecure); +} +class SizeOverflowError extends BaseError$3 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); } - set allowInsecureAuthentication(value) { - __privateSet(this, _allowInsecure, !!value); +} +class SliceOffsetOutOfBoundsError extends BaseError$3 { + constructor({ offset: offset2, position, size: size2 }) { + super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset2}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" }); } - /** - * The timeout (in milliseconds) to wait for a complete response. - * //(default: 5 minutes)// - */ - get timeout() { - return __privateGet(this, _timeout); +} +class SizeExceedsPaddingSizeError extends BaseError$3 { + constructor({ size: size2, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); } - set timeout(timeout) { - assertArgument(timeout >= 0, "timeout must be non-zero", "timeout", timeout); - __privateSet(this, _timeout, timeout); +} +class InvalidBytesLengthError extends BaseError$3 { + constructor({ size: size2, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size2} ${type} long.`, { name: "InvalidBytesLengthError" }); } - /** - * This function is called prior to each request, for example - * during a redirection or retry in case of server throttling. - * - * This offers an opportunity to populate headers or update - * content before sending a request. - */ - get preflightFunc() { - return __privateGet(this, _preflight) || null; +} +function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) { + if (typeof hexOrBytes === "string") + return padHex(hexOrBytes, { dir, size: size2 }); + return padBytes(hexOrBytes, { dir, size: size2 }); +} +function padHex(hex_, { dir, size: size2 = 32 } = {}) { + if (size2 === null) + return hex_; + const hex2 = hex_.replace("0x", ""); + if (hex2.length > size2 * 2) + throw new SizeExceedsPaddingSizeError({ + size: Math.ceil(hex2.length / 2), + targetSize: size2, + type: "hex" + }); + return `0x${hex2[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`; +} +function padBytes(bytes2, { dir, size: size2 = 32 } = {}) { + if (size2 === null) + return bytes2; + if (bytes2.length > size2) + throw new SizeExceedsPaddingSizeError({ + size: bytes2.length, + targetSize: size2, + type: "bytes" + }); + const paddedBytes = new Uint8Array(size2); + for (let i = 0; i < size2; i++) { + const padEnd = dir === "right"; + paddedBytes[padEnd ? i : size2 - i - 1] = bytes2[padEnd ? i : bytes2.length - i - 1]; } - set preflightFunc(preflight) { - __privateSet(this, _preflight, preflight); + return paddedBytes; +} +function isHex(value, { strict = true } = {}) { + if (!value) + return false; + if (typeof value !== "string") + return false; + return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x"); +} +function size$5(value) { + if (isHex(value, { strict: false })) + return Math.ceil((value.length - 2) / 2); + return value.length; +} +function trim(hexOrBytes, { dir = "left" } = {}) { + let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes; + let sliceLength = 0; + for (let i = 0; i < data.length - 1; i++) { + if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") + sliceLength++; + else + break; } - /** - * This function is called after each response, offering an - * opportunity to provide client-level throttling or updating - * response data. - * - * Any error thrown in this causes the ``send()`` to throw. - * - * To schedule a retry attempt (assuming the maximum retry limit - * has not been reached), use [[response.throwThrottleError]]. - */ - get processFunc() { - return __privateGet(this, _process) || null; + data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); + if (typeof hexOrBytes === "string") { + if (data.length === 1 && dir === "right") + data = `${data}0`; + return `0x${data.length % 2 === 1 ? `0${data}` : data}`; } - set processFunc(process2) { - __privateSet(this, _process, process2); + return data; +} +const encoder$1 = /* @__PURE__ */ new TextEncoder(); +function toBytes$3(value, opts = {}) { + if (typeof value === "number" || typeof value === "bigint") + return numberToBytes(value, opts); + if (typeof value === "boolean") + return boolToBytes(value, opts); + if (isHex(value)) + return hexToBytes$2(value, opts); + return stringToBytes(value, opts); +} +function boolToBytes(value, opts = {}) { + const bytes2 = new Uint8Array(1); + bytes2[0] = Number(value); + if (typeof opts.size === "number") { + assertSize(bytes2, { size: opts.size }); + return pad(bytes2, { size: opts.size }); } - /** - * This function is called on each retry attempt. - */ - get retryFunc() { - return __privateGet(this, _retry) || null; + return bytes2; +} +const charCodeMap = { + zero: 48, + nine: 57, + A: 65, + F: 70, + a: 97, + f: 102 +}; +function charCodeToBase16(char) { + if (char >= charCodeMap.zero && char <= charCodeMap.nine) + return char - charCodeMap.zero; + if (char >= charCodeMap.A && char <= charCodeMap.F) + return char - (charCodeMap.A - 10); + if (char >= charCodeMap.a && char <= charCodeMap.f) + return char - (charCodeMap.a - 10); + return void 0; +} +function hexToBytes$2(hex_, opts = {}) { + let hex2 = hex_; + if (opts.size) { + assertSize(hex2, { size: opts.size }); + hex2 = pad(hex2, { dir: "right", size: opts.size }); } - set retryFunc(retry) { - __privateSet(this, _retry, retry); + let hexString = hex2.slice(2); + if (hexString.length % 2) + hexString = `0${hexString}`; + const length = hexString.length / 2; + const bytes2 = new Uint8Array(length); + for (let index2 = 0, j2 = 0; index2 < length; index2++) { + const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j2++)); + const nibbleRight = charCodeToBase16(hexString.charCodeAt(j2++)); + if (nibbleLeft === void 0 || nibbleRight === void 0) { + throw new BaseError$3(`Invalid byte sequence ("${hexString[j2 - 2]}${hexString[j2 - 1]}" in "${hexString}").`); + } + bytes2[index2] = nibbleLeft * 16 + nibbleRight; } - /** - * This function is called to fetch content from HTTP and - * HTTPS URLs and is platform specific (e.g. nodejs vs - * browsers). - * - * This is by default the currently registered global getUrl - * function, which can be changed using [[registerGetUrl]]. - * If this has been set, setting is to ``null`` will cause - * this FetchRequest (and any future clones) to revert back to - * using the currently registered global getUrl function. - * - * Setting this is generally not necessary, but may be useful - * for developers that wish to intercept requests or to - * configurege a proxy or other agent. - */ - get getUrlFunc() { - return __privateGet(this, _getUrlFunc) || defaultGetUrlFunc; + return bytes2; +} +function numberToBytes(value, opts) { + const hex2 = numberToHex(value, opts); + return hexToBytes$2(hex2); +} +function stringToBytes(value, opts = {}) { + const bytes2 = encoder$1.encode(value); + if (typeof opts.size === "number") { + assertSize(bytes2, { size: opts.size }); + return pad(bytes2, { dir: "right", size: opts.size }); } - set getUrlFunc(value) { - __privateSet(this, _getUrlFunc, value); + return bytes2; +} +function assertSize(hexOrBytes, { size: size2 }) { + if (size$5(hexOrBytes) > size2) + throw new SizeOverflowError({ + givenSize: size$5(hexOrBytes), + maxSize: size2 + }); +} +function hexToBigInt(hex2, opts = {}) { + const { signed: signed2 } = opts; + if (opts.size) + assertSize(hex2, { size: opts.size }); + const value = BigInt(hex2); + if (!signed2) + return value; + const size2 = (hex2.length - 2) / 2; + const max2 = (1n << BigInt(size2) * 8n - 1n) - 1n; + if (value <= max2) + return value; + return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n; +} +function hexToNumber$2(hex2, opts = {}) { + return Number(hexToBigInt(hex2, opts)); +} +const hexes$3 = /* @__PURE__ */ Array.from({ length: 256 }, (_v2, i) => i.toString(16).padStart(2, "0")); +function toHex$1(value, opts = {}) { + if (typeof value === "number" || typeof value === "bigint") + return numberToHex(value, opts); + if (typeof value === "string") { + return stringToHex(value, opts); } - toString() { - return ``; + if (typeof value === "boolean") + return boolToHex(value, opts); + return bytesToHex$3(value, opts); +} +function boolToHex(value, opts = {}) { + const hex2 = `0x${Number(value)}`; + if (typeof opts.size === "number") { + assertSize(hex2, { size: opts.size }); + return pad(hex2, { size: opts.size }); } - /** - * Update the throttle parameters used to determine maximum - * attempts and exponential-backoff properties. - */ - setThrottleParams(params) { - if (params.slotInterval != null) { - __privateGet(this, _throttle).slotInterval = params.slotInterval; - } - if (params.maxAttempts != null) { - __privateGet(this, _throttle).maxAttempts = params.maxAttempts; - } + return hex2; +} +function bytesToHex$3(value, opts = {}) { + let string = ""; + for (let i = 0; i < value.length; i++) { + string += hexes$3[value[i]]; } - /** - * Resolves to the response by sending the request. - */ - send() { - assert(__privateGet(this, _signal) == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }); - __privateSet(this, _signal, new FetchCancelSignal(this)); - return __privateMethod(this, _FetchRequest_instances, send_fn).call(this, 0, getTime$2() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this)); + const hex2 = `0x${string}`; + if (typeof opts.size === "number") { + assertSize(hex2, { size: opts.size }); + return pad(hex2, { dir: "right", size: opts.size }); } - /** - * Cancels the inflight response, causing a ``CANCELLED`` - * error to be rejected from the [[send]]. - */ - cancel() { - assert(__privateGet(this, _signal) != null, "request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" }); - const signal = fetchSignals.get(this); - if (!signal) { - throw new Error("missing signal; should not happen"); - } - signal(); + return hex2; +} +function numberToHex(value_, opts = {}) { + const { signed: signed2, size: size2 } = opts; + const value = BigInt(value_); + let maxValue2; + if (size2) { + if (signed2) + maxValue2 = (1n << BigInt(size2) * 8n - 1n) - 1n; + else + maxValue2 = 2n ** (BigInt(size2) * 8n) - 1n; + } else if (typeof value_ === "number") { + maxValue2 = BigInt(Number.MAX_SAFE_INTEGER); } - /** - * Returns a new [[FetchRequest]] that represents the redirection - * to %%location%%. - */ - redirect(location2) { - const current = this.url.split(":")[0].toLowerCase(); - const target = location2.split(":")[0].toLowerCase(); - assert(this.method === "GET" && (current !== "https" || target !== "http") && location2.match(/^https?:/), `unsupported redirect`, "UNSUPPORTED_OPERATION", { - operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location2)})` + const minValue = typeof maxValue2 === "bigint" && signed2 ? -maxValue2 - 1n : 0; + if (maxValue2 && value > maxValue2 || value < minValue) { + const suffix = typeof value_ === "bigint" ? "n" : ""; + throw new IntegerOutOfRangeError({ + max: maxValue2 ? `${maxValue2}${suffix}` : void 0, + min: `${minValue}${suffix}`, + signed: signed2, + size: size2, + value: `${value_}${suffix}` }); - const req = new _FetchRequest(location2); - req.method = "GET"; - req.allowGzip = this.allowGzip; - req.timeout = this.timeout; - __privateSet(req, _headers, Object.assign({}, __privateGet(this, _headers))); - if (__privateGet(this, _body)) { - __privateSet(req, _body, new Uint8Array(__privateGet(this, _body))); - } - __privateSet(req, _bodyType, __privateGet(this, _bodyType)); - return req; } - /** - * Create a new copy of this request. - */ - clone() { - const clone = new _FetchRequest(this.url); - __privateSet(clone, _method, __privateGet(this, _method)); - if (__privateGet(this, _body)) { - __privateSet(clone, _body, __privateGet(this, _body)); - } - __privateSet(clone, _bodyType, __privateGet(this, _bodyType)); - __privateSet(clone, _headers, Object.assign({}, __privateGet(this, _headers))); - __privateSet(clone, _creds, __privateGet(this, _creds)); - if (this.allowGzip) { - clone.allowGzip = true; - } - clone.timeout = this.timeout; - if (this.allowInsecureAuthentication) { - clone.allowInsecureAuthentication = true; - } - __privateSet(clone, _preflight, __privateGet(this, _preflight)); - __privateSet(clone, _process, __privateGet(this, _process)); - __privateSet(clone, _retry, __privateGet(this, _retry)); - __privateSet(clone, _throttle, Object.assign({}, __privateGet(this, _throttle))); - __privateSet(clone, _getUrlFunc, __privateGet(this, _getUrlFunc)); - return clone; + const hex2 = `0x${(signed2 && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`; + if (size2) + return pad(hex2, { size: size2 }); + return hex2; +} +const encoder = /* @__PURE__ */ new TextEncoder(); +function stringToHex(value_, opts = {}) { + const value = encoder.encode(value_); + return bytesToHex$3(value, opts); +} +async function addChain(client2, { chain }) { + const { id: id2, name: name2, nativeCurrency, rpcUrls, blockExplorers } = chain; + await client2.request({ + method: "wallet_addEthereumChain", + params: [ + { + chainId: numberToHex(id2), + chainName: name2, + nativeCurrency, + rpcUrls: rpcUrls.default.http, + blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url }) => url) : void 0 + } + ] + }, { dedupe: true, retryCount: 0 }); +} +function formatAbiItem$1(abiItem, { includeName = false } = {}) { + if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error") + throw new InvalidDefinitionTypeError(abiItem.type); + return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`; +} +function formatAbiParams(params, { includeName = false } = {}) { + if (!params) + return ""; + return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ","); +} +function formatAbiParam(param, { includeName }) { + if (param.type.startsWith("tuple")) { + return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`; } - /** - * Locks all static configuration for gateways and FetchGetUrlFunc - * registration. - */ - static lockConfig() { - locked$5 = true; + return param.type + (includeName && param.name ? ` ${param.name}` : ""); +} +class AbiConstructorNotFoundError extends BaseError$3 { + constructor({ docsPath: docsPath2 }) { + super([ + "A constructor was not found on the ABI.", + "Make sure you are using the correct ABI and that the constructor exists on it." + ].join("\n"), { + docsPath: docsPath2, + name: "AbiConstructorNotFoundError" + }); } - /** - * Get the current Gateway function for %%scheme%%. - */ - static getGateway(scheme) { - return Gateways[scheme.toLowerCase()] || null; +} +class AbiConstructorParamsNotFoundError extends BaseError$3 { + constructor({ docsPath: docsPath2 }) { + super([ + "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.", + "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists." + ].join("\n"), { + docsPath: docsPath2, + name: "AbiConstructorParamsNotFoundError" + }); } - /** - * Use the %%func%% when fetching URIs using %%scheme%%. - * - * This method affects all requests globally. - * - * If [[lockConfig]] has been called, no change is made and this - * throws. - */ - static registerGateway(scheme, func) { - scheme = scheme.toLowerCase(); - if (scheme === "http" || scheme === "https") { - throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); - } - if (locked$5) { - throw new Error("gateways locked"); - } - Gateways[scheme] = func; +} +class AbiDecodingDataSizeTooSmallError extends BaseError$3 { + constructor({ data, params, size: size2 }) { + super([`Data size of ${size2} bytes is too small for given parameters.`].join("\n"), { + metaMessages: [ + `Params: (${formatAbiParams(params, { includeName: true })})`, + `Data: ${data} (${size2} bytes)` + ], + name: "AbiDecodingDataSizeTooSmallError" + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "params", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "size", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = data; + this.params = params; + this.size = size2; } - /** - * Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests. - * - * This method affects all requests globally. - * - * If [[lockConfig]] has been called, no change is made and this - * throws. - */ - static registerGetUrl(getUrl2) { - if (locked$5) { - throw new Error("gateways locked"); - } - defaultGetUrlFunc = getUrl2; +} +class AbiDecodingZeroDataError extends BaseError$3 { + constructor() { + super('Cannot decode zero data ("0x") with ABI parameters.', { + name: "AbiDecodingZeroDataError" + }); } - /** - * Creates a getUrl function that fetches content from HTTP and - * HTTPS URLs. - * - * The available %%options%% are dependent on the platform - * implementation of the default getUrl function. - * - * This is not generally something that is needed, but is useful - * when trying to customize simple behaviour when fetching HTTP - * content. - */ - static createGetUrlFunc(options) { - return createGetUrl(); +} +class AbiEncodingArrayLengthMismatchError extends BaseError$3 { + constructor({ expectedLength, givenLength, type }) { + super([ + `ABI encoding array length mismatch for type ${type}.`, + `Expected length: ${expectedLength}`, + `Given length: ${givenLength}` + ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" }); } - /** - * Creates a function that can "fetch" data URIs. - * - * Note that this is automatically done internally to support - * data URIs, so it is not necessary to register it. - * - * This is not generally something that is needed, but may - * be useful in a wrapper to perfom custom data URI functionality. - */ - static createDataGateway() { - return dataGatewayFunc; +} +class AbiEncodingBytesSizeMismatchError extends BaseError$3 { + constructor({ expectedSize, value }) { + super(`Size of bytes "${value}" (bytes${size$5(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); } - /** - * Creates a function that will fetch IPFS (unvalidated) from - * a custom gateway baseUrl. - * - * The default IPFS gateway used internally is - * ``"https:/\/gateway.ipfs.io/ipfs/"``. - */ - static createIpfsGatewayFunc(baseUrl) { - return getIpfsGatewayFunc(baseUrl); +} +class AbiEncodingLengthMismatchError extends BaseError$3 { + constructor({ expectedLength, givenLength }) { + super([ + "ABI encoding params/values length mismatch.", + `Expected length (params): ${expectedLength}`, + `Given length (values): ${givenLength}` + ].join("\n"), { name: "AbiEncodingLengthMismatchError" }); } -}; -_allowInsecure = new WeakMap(); -_gzip = new WeakMap(); -_headers = new WeakMap(); -_method = new WeakMap(); -_timeout = new WeakMap(); -_url = new WeakMap(); -_body = new WeakMap(); -_bodyType = new WeakMap(); -_creds = new WeakMap(); -_preflight = new WeakMap(); -_process = new WeakMap(); -_retry = new WeakMap(); -_signal = new WeakMap(); -_throttle = new WeakMap(); -_getUrlFunc = new WeakMap(); -_FetchRequest_instances = new WeakSet(); -send_fn = async function(attempt, expires, delay2, _request3, _response) { - var _a2, _b2, _c2; - if (attempt >= __privateGet(this, _throttle).maxAttempts) { - return _response.makeServerError("exceeded maximum retry limit"); - } - assert(getTime$2() <= expires, "timeout", "TIMEOUT", { - operation: "request.send", - reason: "timeout", - request: _request3 - }); - if (delay2 > 0) { - await wait$1(delay2); - } - let req = this.clone(); - const scheme = (req.url.split(":")[0] || "").toLowerCase(); - if (scheme in Gateways) { - const result = await Gateways[scheme](req.url, checkSignal(__privateGet(_request3, _signal))); - if (result instanceof FetchResponse) { - let response2 = result; - if (this.processFunc) { - checkSignal(__privateGet(_request3, _signal)); - try { - response2 = await this.processFunc(req, response2); - } catch (error) { - if (error.throttle == null || typeof error.stall !== "number") { - response2.makeServerError("error in post-processing function", error).assertOk(); - } - } - } - return response2; - } - req = result; - } - if (this.preflightFunc) { - req = await this.preflightFunc(req); +} +class AbiErrorSignatureNotFoundError extends BaseError$3 { + constructor(signature2, { docsPath: docsPath2 }) { + super([ + `Encoded error signature "${signature2}" not found on ABI.`, + "Make sure you are using the correct ABI and that the error exists on it.", + `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature2}.` + ].join("\n"), { + docsPath: docsPath2, + name: "AbiErrorSignatureNotFoundError" + }); + Object.defineProperty(this, "signature", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.signature = signature2; } - const resp = await this.getUrlFunc(req, checkSignal(__privateGet(_request3, _signal))); - let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request3); - if (response.statusCode === 301 || response.statusCode === 302) { - try { - const location2 = response.headers.location || ""; - return __privateMethod(_a2 = req.redirect(location2), _FetchRequest_instances, send_fn).call(_a2, attempt + 1, expires, 0, _request3, response); - } catch (error) { - } - return response; - } else if (response.statusCode === 429) { - if (this.retryFunc == null || await this.retryFunc(req, response, attempt)) { - const retryAfter = response.headers["retry-after"]; - let delay3 = __privateGet(this, _throttle).slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); - if (typeof retryAfter === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { - delay3 = parseInt(retryAfter); - } - return __privateMethod(_b2 = req.clone(), _FetchRequest_instances, send_fn).call(_b2, attempt + 1, expires, delay3, _request3, response); - } +} +class AbiEventSignatureEmptyTopicsError extends BaseError$3 { + constructor({ docsPath: docsPath2 }) { + super("Cannot extract event signature from empty topics.", { + docsPath: docsPath2, + name: "AbiEventSignatureEmptyTopicsError" + }); } - if (this.processFunc) { - checkSignal(__privateGet(_request3, _signal)); - try { - response = await this.processFunc(req, response); - } catch (error) { - if (error.throttle == null || typeof error.stall !== "number") { - response.makeServerError("error in post-processing function", error).assertOk(); - } - let delay3 = __privateGet(this, _throttle).slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); - if (error.stall >= 0) { - delay3 = error.stall; - } - return __privateMethod(_c2 = req.clone(), _FetchRequest_instances, send_fn).call(_c2, attempt + 1, expires, delay3, _request3, response); - } +} +class AbiEventSignatureNotFoundError extends BaseError$3 { + constructor(signature2, { docsPath: docsPath2 }) { + super([ + `Encoded event signature "${signature2}" not found on ABI.`, + "Make sure you are using the correct ABI and that the event exists on it.", + `You can look up the signature here: https://openchain.xyz/signatures?query=${signature2}.` + ].join("\n"), { + docsPath: docsPath2, + name: "AbiEventSignatureNotFoundError" + }); } - return response; -}; -let FetchRequest = _FetchRequest; -const _FetchResponse = class _FetchResponse { - constructor(statusCode, statusMessage, headers, body, request) { - __privateAdd(this, _statusCode); - __privateAdd(this, _statusMessage); - __privateAdd(this, _headers2); - __privateAdd(this, _body2); - __privateAdd(this, _request); - __privateAdd(this, _error); - __privateSet(this, _statusCode, statusCode); - __privateSet(this, _statusMessage, statusMessage); - __privateSet(this, _headers2, Object.keys(headers).reduce((accum, k2) => { - accum[k2.toLowerCase()] = String(headers[k2]); - return accum; - }, {})); - __privateSet(this, _body2, body == null ? null : new Uint8Array(body)); - __privateSet(this, _request, request || null); - __privateSet(this, _error, { message: "" }); +} +class AbiEventNotFoundError extends BaseError$3 { + constructor(eventName, { docsPath: docsPath2 } = {}) { + super([ + `Event ${eventName ? `"${eventName}" ` : ""}not found on ABI.`, + "Make sure you are using the correct ABI and that the event exists on it." + ].join("\n"), { + docsPath: docsPath2, + name: "AbiEventNotFoundError" + }); } - toString() { - return ``; +} +class AbiFunctionNotFoundError extends BaseError$3 { + constructor(functionName, { docsPath: docsPath2 } = {}) { + super([ + `Function ${functionName ? `"${functionName}" ` : ""}not found on ABI.`, + "Make sure you are using the correct ABI and that the function exists on it." + ].join("\n"), { + docsPath: docsPath2, + name: "AbiFunctionNotFoundError" + }); } - /** - * The response status code. - */ - get statusCode() { - return __privateGet(this, _statusCode); +} +class AbiFunctionOutputsNotFoundError extends BaseError$3 { + constructor(functionName, { docsPath: docsPath2 }) { + super([ + `Function "${functionName}" does not contain any \`outputs\` on ABI.`, + "Cannot decode function result without knowing what the parameter types are.", + "Make sure you are using the correct ABI and that the function exists on it." + ].join("\n"), { + docsPath: docsPath2, + name: "AbiFunctionOutputsNotFoundError" + }); } - /** - * The response status message. - */ - get statusMessage() { - return __privateGet(this, _statusMessage); +} +class AbiItemAmbiguityError extends BaseError$3 { + constructor(x2, y2) { + super("Found ambiguous types in overloaded ABI items.", { + metaMessages: [ + `\`${x2.type}\` in \`${formatAbiItem$1(x2.abiItem)}\`, and`, + `\`${y2.type}\` in \`${formatAbiItem$1(y2.abiItem)}\``, + "", + "These types encode differently and cannot be distinguished at runtime.", + "Remove one of the ambiguous items in the ABI." + ], + name: "AbiItemAmbiguityError" + }); } - /** - * The response headers. All keys are lower-case. - */ - get headers() { - return Object.assign({}, __privateGet(this, _headers2)); +} +class BytesSizeMismatchError extends BaseError$3 { + constructor({ expectedSize, givenSize }) { + super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { + name: "BytesSizeMismatchError" + }); } - /** - * The response body, or ``null`` if there was no body. - */ - get body() { - return __privateGet(this, _body2) == null ? null : new Uint8Array(__privateGet(this, _body2)); +} +class DecodeLogDataMismatch extends BaseError$3 { + constructor({ abiItem, data, params, size: size2 }) { + super([ + `Data size of ${size2} bytes is too small for non-indexed event parameters.` + ].join("\n"), { + metaMessages: [ + `Params: (${formatAbiParams(params, { includeName: true })})`, + `Data: ${data} (${size2} bytes)` + ], + name: "DecodeLogDataMismatch" + }); + Object.defineProperty(this, "abiItem", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "params", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "size", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.abiItem = abiItem; + this.data = data; + this.params = params; + this.size = size2; } - /** - * The response body as a UTF-8 encoded string, or the empty - * string (i.e. ``""``) if there was no body. - * - * An error is thrown if the body is invalid UTF-8 data. - */ - get bodyText() { - try { - return __privateGet(this, _body2) == null ? "" : toUtf8String(__privateGet(this, _body2)); - } catch (error) { - assert(false, "response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", { - operation: "bodyText", - info: { response: this } - }); - } +} +class DecodeLogTopicsMismatch extends BaseError$3 { + constructor({ abiItem, param }) { + super([ + `Expected a topic for indexed event parameter${param.name ? ` "${param.name}"` : ""} on event "${formatAbiItem$1(abiItem, { includeName: true })}".` + ].join("\n"), { name: "DecodeLogTopicsMismatch" }); + Object.defineProperty(this, "abiItem", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.abiItem = abiItem; } - /** - * The response body, decoded as JSON. - * - * An error is thrown if the body is invalid JSON-encoded data - * or if there was no body. - */ - get bodyJson() { - try { - return JSON.parse(this.bodyText); - } catch (error) { - assert(false, "response body is not valid JSON", "UNSUPPORTED_OPERATION", { - operation: "bodyJson", - info: { response: this } - }); - } +} +class InvalidAbiEncodingTypeError extends BaseError$3 { + constructor(type, { docsPath: docsPath2 }) { + super([ + `Type "${type}" is not a valid encoding type.`, + "Please provide a valid ABI type." + ].join("\n"), { docsPath: docsPath2, name: "InvalidAbiEncodingType" }); } - [Symbol.iterator]() { - const headers = this.headers; - const keys = Object.keys(headers); - let index2 = 0; - return { - next: () => { - if (index2 < keys.length) { - const key = keys[index2++]; - return { - value: [key, headers[key]], - done: false - }; - } - return { value: void 0, done: true }; - } - }; +} +class InvalidAbiDecodingTypeError extends BaseError$3 { + constructor(type, { docsPath: docsPath2 }) { + super([ + `Type "${type}" is not a valid decoding type.`, + "Please provide a valid ABI type." + ].join("\n"), { docsPath: docsPath2, name: "InvalidAbiDecodingType" }); } - /** - * Return a Response with matching headers and body, but with - * an error status code (i.e. 599) and %%message%% with an - * optional %%error%%. - */ - makeServerError(message, error) { - let statusMessage; - if (!message) { - message = `${this.statusCode} ${this.statusMessage}`; - statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; - } else { - statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; - } - const response = new _FetchResponse(599, statusMessage, this.headers, this.body, __privateGet(this, _request) || void 0); - __privateSet(response, _error, { message, error }); - return response; +} +class InvalidArrayError extends BaseError$3 { + constructor(value) { + super([`Value "${value}" is not a valid array.`].join("\n"), { + name: "InvalidArrayError" + }); } - /** - * If called within a [request.processFunc](FetchRequest-processFunc) - * call, causes the request to retry as if throttled for %%stall%% - * milliseconds. - */ - throwThrottleError(message, stall2) { - if (stall2 == null) { - stall2 = -1; - } else { - assertArgument(Number.isInteger(stall2) && stall2 >= 0, "invalid stall timeout", "stall", stall2); - } - const error = new Error(message || "throttling requests"); - defineProperties$1(error, { stall: stall2, throttle: true }); - throw error; +} +class InvalidDefinitionTypeError extends BaseError$3 { + constructor(type) { + super([ + `"${type}" is not a valid definition type.`, + 'Valid types: "function", "event", "error"' + ].join("\n"), { name: "InvalidDefinitionTypeError" }); } - /** - * Get the header value for %%key%%, ignoring case. - */ - getHeader(key) { - return this.headers[key.toLowerCase()]; +} +function concat$1(values) { + if (typeof values[0] === "string") + return concatHex(values); + return concatBytes$4(values); +} +function concatBytes$4(values) { + let length = 0; + for (const arr of values) { + length += arr.length; } - /** - * Returns true if the response has a body. - */ - hasBody() { - return __privateGet(this, _body2) != null; + const result = new Uint8Array(length); + let offset2 = 0; + for (const arr of values) { + result.set(arr, offset2); + offset2 += arr.length; } - /** - * The request made for this response. - */ - get request() { - return __privateGet(this, _request); + return result; +} +function concatHex(values) { + return `0x${values.reduce((acc, x2) => acc + x2.replace("0x", ""), "")}`; +} +class InvalidAddressError extends BaseError$3 { + constructor({ address }) { + super(`Address "${address}" is invalid.`, { + metaMessages: [ + "- Address must be a hex value of 20 bytes (40 hex characters).", + "- Address must match its checksum counterpart." + ], + name: "InvalidAddressError" + }); } - /** - * Returns true if this response was a success statusCode. - */ - ok() { - return __privateGet(this, _error).message === "" && this.statusCode >= 200 && this.statusCode < 300; +} +class LruMap extends Map { + constructor(size2) { + super(); + Object.defineProperty(this, "maxSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxSize = size2; } - /** - * Throws a ``SERVER_ERROR`` if this response is not ok. - */ - assertOk() { - if (this.ok()) { - return; - } - let { message, error } = __privateGet(this, _error); - if (message === "") { - message = `server response ${this.statusCode} ${this.statusMessage}`; - } - let requestUrl = null; - if (this.request) { - requestUrl = this.request.url; + get(key) { + const value = super.get(key); + if (super.has(key) && value !== void 0) { + this.delete(key); + super.set(key, value); } - let responseBody = null; - try { - if (__privateGet(this, _body2)) { - responseBody = toUtf8String(__privateGet(this, _body2)); - } - } catch (e2) { + return value; + } + set(key, value) { + super.set(key, value); + if (this.maxSize && this.size > this.maxSize) { + const firstKey = this.keys().next().value; + if (firstKey) + this.delete(firstKey); } - assert(false, message, "SERVER_ERROR", { - request: this.request || "unknown request", - response: this, - error, - info: { - requestUrl, - responseBody, - responseStatus: `${this.statusCode} ${this.statusMessage}` - } - }); + return this; } -}; -_statusCode = new WeakMap(); -_statusMessage = new WeakMap(); -_headers2 = new WeakMap(); -_body2 = new WeakMap(); -_request = new WeakMap(); -_error = new WeakMap(); -let FetchResponse = _FetchResponse; -function getTime$2() { - return (/* @__PURE__ */ new Date()).getTime(); } -function unpercent(value) { - return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code2) => { - return String.fromCharCode(parseInt(code2, 16)); - })); +function number$1(n2) { + if (!Number.isSafeInteger(n2) || n2 < 0) + throw new Error(`positive integer expected, not ${n2}`); } -function wait$1(delay2) { - return new Promise((resolve) => setTimeout(resolve, delay2)); +function isBytes$2(a2) { + return a2 instanceof Uint8Array || a2 != null && typeof a2 === "object" && a2.constructor.name === "Uint8Array"; } -const BN_N1 = BigInt(-1); -const BN_0$8 = BigInt(0); -const BN_1$4 = BigInt(1); -const BN_5 = BigInt(5); -const _guard$5 = {}; -let Zeros$1 = "0000"; -while (Zeros$1.length < 80) { - Zeros$1 += Zeros$1; +function bytes$2(b2, ...lengths) { + if (!isBytes$2(b2)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b2.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b2.length}`); } -function getTens(decimals) { - let result = Zeros$1; - while (result.length < decimals) { - result += result; - } - return BigInt("1" + result.substring(0, decimals)); +function hash$2(h2) { + if (typeof h2 !== "function" || typeof h2.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number$1(h2.outputLen); + number$1(h2.blockLen); } -function checkValue(val, format2, safeOp) { - const width = BigInt(format2.width); - if (format2.signed) { - const limit = BN_1$4 << width - BN_1$4; - assert(safeOp == null || val >= -limit && val < limit, "overflow", "NUMERIC_FAULT", { - operation: safeOp, - fault: "overflow", - value: val - }); - if (val > BN_0$8) { - val = fromTwos(mask(val, width), width); - } else { - val = -fromTwos(mask(-val, width), width); - } - } else { - const limit = BN_1$4 << width; - assert(safeOp == null || val >= 0 && val < limit, "overflow", "NUMERIC_FAULT", { - operation: safeOp, - fault: "overflow", - value: val - }); - val = (val % limit + limit) % limit & limit - BN_1$4; - } - return val; +function exists$2(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); } -function getFormat(value) { - if (typeof value === "number") { - value = `fixed128x${value}`; +function output$2(out, instance) { + bytes$2(out); + const min2 = instance.outputLen; + if (out.length < min2) { + throw new Error(`digestInto() expects output buffer of length at least ${min2}`); } - let signed2 = true; - let width = 128; - let decimals = 18; - if (typeof value === "string") { - if (value === "fixed") ; - else if (value === "ufixed") { - signed2 = false; - } else { - const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); - assertArgument(match, "invalid fixed format", "format", value); - signed2 = match[1] !== "u"; - width = parseInt(match[2]); - decimals = parseInt(match[3]); - } - } else if (value) { - const v3 = value; - const check = (key, type, defaultValue) => { - if (v3[key] == null) { - return defaultValue; - } - assertArgument(typeof v3[key] === type, "invalid fixed format (" + key + " not " + type + ")", "format." + key, v3[key]); - return v3[key]; - }; - signed2 = check("signed", "boolean", signed2); - width = check("width", "number", width); - decimals = check("decimals", "number", decimals); +} +const U32_MASK64$1 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n$1 = /* @__PURE__ */ BigInt(32); +function fromBig$1(n2, le2 = false) { + if (le2) + return { h: Number(n2 & U32_MASK64$1), l: Number(n2 >> _32n$1 & U32_MASK64$1) }; + return { h: Number(n2 >> _32n$1 & U32_MASK64$1) | 0, l: Number(n2 & U32_MASK64$1) | 0 }; +} +function split$2(lst, le2 = false) { + let Ah2 = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h: h2, l: l2 } = fromBig$1(lst[i], le2); + [Ah2[i], Al[i]] = [h2, l2]; } - assertArgument(width % 8 === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width); - assertArgument(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals); - const name2 = (signed2 ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); - return { signed: signed2, width, decimals, name: name2 }; + return [Ah2, Al]; } -function toString$1(val, decimals) { - let negative = ""; - if (val < BN_0$8) { - negative = "-"; - val *= BN_N1; +const rotlSH$1 = (h2, l2, s2) => h2 << s2 | l2 >>> 32 - s2; +const rotlSL$1 = (h2, l2, s2) => l2 << s2 | h2 >>> 32 - s2; +const rotlBH$1 = (h2, l2, s2) => l2 << s2 - 32 | h2 >>> 64 - s2; +const rotlBL$1 = (h2, l2, s2) => h2 << s2 - 32 | l2 >>> 64 - s2; +const crypto$3 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const u32$1 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +const createView$2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +const rotr$2 = (word, shift2) => word << 32 - shift2 | word >>> shift2; +const isLE$1 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; +const byteSwap = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); } - let str = val.toString(); - if (decimals === 0) { - return negative + str; +} +function utf8ToBytes$4(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes$2(data) { + if (typeof data === "string") + data = utf8ToBytes$4(data); + bytes$2(data); + return data; +} +function concatBytes$3(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a2 = arrays[i]; + bytes$2(a2); + sum += a2.length; } - while (str.length <= decimals) { - str = Zeros$1 + str; + const res = new Uint8Array(sum); + for (let i = 0, pad2 = 0; i < arrays.length; i++) { + const a2 = arrays[i]; + res.set(a2, pad2); + pad2 += a2.length; } - const index2 = str.length - decimals; - str = str.substring(0, index2) + "." + str.substring(index2); - while (str[0] === "0" && str[1] !== ".") { - str = str.substring(1); + return res; +} +let Hash$2 = class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); } - while (str[str.length - 1] === "0" && str[str.length - 2] !== ".") { - str = str.substring(0, str.length - 1); +}; +function wrapConstructor$2(hashCons) { + const hashC = (msg) => hashCons().update(toBytes$2(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function randomBytes$3(bytesLength = 32) { + if (crypto$3 && typeof crypto$3.getRandomValues === "function") { + return crypto$3.getRandomValues(new Uint8Array(bytesLength)); } - return negative + str; + throw new Error("crypto.getRandomValues must be defined"); } -const _FixedNumber = class _FixedNumber { - // Use this when changing this file to get some typing info, - // but then switch to any to mask the internal type - //constructor(guard: any, value: bigint, format: _FixedFormat) { - /** - * @private - */ - constructor(guard2, value, format2) { - __privateAdd(this, _FixedNumber_instances); - /** - * The specific fixed-point arithmetic field for this value. - */ - __publicField(this, "format"); - __privateAdd(this, _format); - // The actual value (accounting for decimals) - __privateAdd(this, _val); - // A base-10 value to multiple values by to maintain the magnitude - __privateAdd(this, _tens); - /** - * This is a property so console.log shows a human-meaningful value. - * - * @private - */ - __publicField(this, "_value"); - assertPrivate(guard2, _guard$5, "FixedNumber"); - __privateSet(this, _val, value); - __privateSet(this, _format, format2); - const _value2 = toString$1(value, format2.decimals); - defineProperties$1(this, { format: format2.name, _value: _value2 }); - __privateSet(this, _tens, getTens(format2.decimals)); +const SHA3_PI$1 = []; +const SHA3_ROTL$1 = []; +const _SHA3_IOTA$1 = []; +const _0n$9 = /* @__PURE__ */ BigInt(0); +const _1n$b = /* @__PURE__ */ BigInt(1); +const _2n$7 = /* @__PURE__ */ BigInt(2); +const _7n$1 = /* @__PURE__ */ BigInt(7); +const _256n$1 = /* @__PURE__ */ BigInt(256); +const _0x71n$1 = /* @__PURE__ */ BigInt(113); +for (let round2 = 0, R2 = _1n$b, x2 = 1, y2 = 0; round2 < 24; round2++) { + [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; + SHA3_PI$1.push(2 * (5 * y2 + x2)); + SHA3_ROTL$1.push((round2 + 1) * (round2 + 2) / 2 % 64); + let t2 = _0n$9; + for (let j2 = 0; j2 < 7; j2++) { + R2 = (R2 << _1n$b ^ (R2 >> _7n$1) * _0x71n$1) % _256n$1; + if (R2 & _2n$7) + t2 ^= _1n$b << (_1n$b << /* @__PURE__ */ BigInt(j2)) - _1n$b; } - /** - * If true, negative values are permitted, otherwise only - * positive values and zero are allowed. - */ - get signed() { - return __privateGet(this, _format).signed; + _SHA3_IOTA$1.push(t2); +} +const [SHA3_IOTA_H$1, SHA3_IOTA_L$1] = /* @__PURE__ */ split$2(_SHA3_IOTA$1, true); +const rotlH$1 = (h2, l2, s2) => s2 > 32 ? rotlBH$1(h2, l2, s2) : rotlSH$1(h2, l2, s2); +const rotlL$1 = (h2, l2, s2) => s2 > 32 ? rotlBL$1(h2, l2, s2) : rotlSL$1(h2, l2, s2); +function keccakP$1(s2, rounds = 24) { + const B2 = new Uint32Array(5 * 2); + for (let round2 = 24 - rounds; round2 < 24; round2++) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s2[x2] ^ s2[x2 + 10] ^ s2[x2 + 20] ^ s2[x2 + 30] ^ s2[x2 + 40]; + for (let x2 = 0; x2 < 10; x2 += 2) { + const idx1 = (x2 + 8) % 10; + const idx0 = (x2 + 2) % 10; + const B0 = B2[idx0]; + const B1 = B2[idx0 + 1]; + const Th2 = rotlH$1(B0, B1, 1) ^ B2[idx1]; + const Tl = rotlL$1(B0, B1, 1) ^ B2[idx1 + 1]; + for (let y2 = 0; y2 < 50; y2 += 10) { + s2[x2 + y2] ^= Th2; + s2[x2 + y2 + 1] ^= Tl; + } + } + let curH = s2[2]; + let curL = s2[3]; + for (let t2 = 0; t2 < 24; t2++) { + const shift2 = SHA3_ROTL$1[t2]; + const Th2 = rotlH$1(curH, curL, shift2); + const Tl = rotlL$1(curH, curL, shift2); + const PI = SHA3_PI$1[t2]; + curH = s2[PI]; + curL = s2[PI + 1]; + s2[PI] = Th2; + s2[PI + 1] = Tl; + } + for (let y2 = 0; y2 < 50; y2 += 10) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s2[y2 + x2]; + for (let x2 = 0; x2 < 10; x2++) + s2[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; + } + s2[0] ^= SHA3_IOTA_H$1[round2]; + s2[1] ^= SHA3_IOTA_L$1[round2]; } - /** - * The number of bits available to store the value. - */ - get width() { - return __privateGet(this, _format).width; + B2.fill(0); +} +let Keccak$1 = class Keccak extends Hash$2 { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + number$1(outputLen); + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error("Sha3 supports only keccak-f1600 function"); + this.state = new Uint8Array(200); + this.state32 = u32$1(this.state); } - /** - * The number of decimal places in the fixed-point arithment field. - */ - get decimals() { - return __privateGet(this, _format).decimals; + keccak() { + if (!isLE$1) + byteSwap32(this.state32); + keccakP$1(this.state32, this.rounds); + if (!isLE$1) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; } - /** - * The value as an integer, based on the smallest unit the - * [[decimals]] allow. - */ - get value() { - return __privateGet(this, _val); + update(data) { + exists$2(this); + const { blockLen, state } = this; + data = toBytes$2(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; } - /** - * Returns a new [[FixedNumber]] with the result of %%this%% added - * to %%other%%, ignoring overflow. - */ - addUnsafe(other) { - return __privateMethod(this, _FixedNumber_instances, add_fn).call(this, other); + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); } - /** - * Returns a new [[FixedNumber]] with the result of %%this%% added - * to %%other%%. A [[NumericFaultError]] is thrown if overflow - * occurs. - */ - add(other) { - return __privateMethod(this, _FixedNumber_instances, add_fn).call(this, other, "add"); + writeInto(out) { + exists$2(this, false); + bytes$2(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; } - /** - * Returns a new [[FixedNumber]] with the result of %%other%% subtracted - * from %%this%%, ignoring overflow. - */ - subUnsafe(other) { - return __privateMethod(this, _FixedNumber_instances, sub_fn).call(this, other); + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); } - /** - * Returns a new [[FixedNumber]] with the result of %%other%% subtracted - * from %%this%%. A [[NumericFaultError]] is thrown if overflow - * occurs. - */ - sub(other) { - return __privateMethod(this, _FixedNumber_instances, sub_fn).call(this, other, "sub"); + xof(bytes2) { + number$1(bytes2); + return this.xofInto(new Uint8Array(bytes2)); } - /** - * Returns a new [[FixedNumber]] with the result of %%this%% multiplied - * by %%other%%, ignoring overflow and underflow (precision loss). - */ - mulUnsafe(other) { - return __privateMethod(this, _FixedNumber_instances, mul_fn).call(this, other); + digestInto(out) { + output$2(out, this); + if (this.finished) + throw new Error("digest() was already called"); + this.writeInto(out); + this.destroy(); + return out; } - /** - * Returns a new [[FixedNumber]] with the result of %%this%% multiplied - * by %%other%%. A [[NumericFaultError]] is thrown if overflow - * occurs. - */ - mul(other) { - return __privateMethod(this, _FixedNumber_instances, mul_fn).call(this, other, "mul"); + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); } - /** - * Returns a new [[FixedNumber]] with the result of %%this%% multiplied - * by %%other%%. A [[NumericFaultError]] is thrown if overflow - * occurs or if underflow (precision loss) occurs. - */ - mulSignal(other) { - __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, other); - const value = __privateGet(this, _val) * __privateGet(other, _val); - assert(value % __privateGet(this, _tens) === BN_0$8, "precision lost during signalling mul", "NUMERIC_FAULT", { - operation: "mulSignal", - fault: "underflow", - value: this - }); - return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, value / __privateGet(this, _tens), "mulSignal"); + destroy() { + this.destroyed = true; + this.state.fill(0); } - /** - * Returns a new [[FixedNumber]] with the result of %%this%% divided - * by %%other%%, ignoring underflow (precision loss). A - * [[NumericFaultError]] is thrown if overflow occurs. - */ - divUnsafe(other) { - return __privateMethod(this, _FixedNumber_instances, div_fn).call(this, other); + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; } - /** - * Returns a new [[FixedNumber]] with the result of %%this%% divided - * by %%other%%, ignoring underflow (precision loss). A - * [[NumericFaultError]] is thrown if overflow occurs. - */ - div(other) { - return __privateMethod(this, _FixedNumber_instances, div_fn).call(this, other, "div"); +}; +const gen$1 = (suffix, blockLen, outputLen) => wrapConstructor$2(() => new Keccak$1(blockLen, suffix, outputLen)); +const keccak_256$1 = /* @__PURE__ */ gen$1(1, 136, 256 / 8); +function keccak256$1(value, to_) { + const to = to_ || "hex"; + const bytes2 = keccak_256$1(isHex(value, { strict: false }) ? toBytes$3(value) : value); + if (to === "bytes") + return bytes2; + return toHex$1(bytes2); +} +const checksumAddressCache = /* @__PURE__ */ new LruMap(8192); +function checksumAddress(address_, chainId) { + if (checksumAddressCache.has(`${address_}.${chainId}`)) + return checksumAddressCache.get(`${address_}.${chainId}`); + const hexAddress = address_.substring(2).toLowerCase(); + const hash2 = keccak256$1(stringToBytes(hexAddress), "bytes"); + const address = hexAddress.split(""); + for (let i = 0; i < 40; i += 2) { + if (hash2[i >> 1] >> 4 >= 8 && address[i]) { + address[i] = address[i].toUpperCase(); + } + if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) { + address[i + 1] = address[i + 1].toUpperCase(); + } } - /** - * Returns a new [[FixedNumber]] with the result of %%this%% divided - * by %%other%%. A [[NumericFaultError]] is thrown if underflow - * (precision loss) occurs. - */ - divSignal(other) { - assert(__privateGet(other, _val) !== BN_0$8, "division by zero", "NUMERIC_FAULT", { - operation: "div", - fault: "divide-by-zero", - value: this + const result = `0x${address.join("")}`; + checksumAddressCache.set(`${address_}.${chainId}`, result); + return result; +} +function getAddress$1(address, chainId) { + if (!isAddress$1(address, { strict: false })) + throw new InvalidAddressError({ address }); + return checksumAddress(address, chainId); +} +const addressRegex = /^0x[a-fA-F0-9]{40}$/; +const isAddressCache = /* @__PURE__ */ new LruMap(8192); +function isAddress$1(address, options) { + const { strict = true } = options ?? {}; + const cacheKey2 = `${address}.${strict}`; + if (isAddressCache.has(cacheKey2)) + return isAddressCache.get(cacheKey2); + const result = (() => { + if (!addressRegex.test(address)) + return false; + if (address.toLowerCase() === address) + return true; + if (strict) + return checksumAddress(address) === address; + return true; + })(); + isAddressCache.set(cacheKey2, result); + return result; +} +function slice(value, start, end, { strict } = {}) { + if (isHex(value, { strict: false })) + return sliceHex(value, start, end, { + strict }); - __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, other); - const value = __privateGet(this, _val) * __privateGet(this, _tens); - assert(value % __privateGet(other, _val) === BN_0$8, "precision lost during signalling div", "NUMERIC_FAULT", { - operation: "divSignal", - fault: "underflow", - value: this + return sliceBytes(value, start, end, { + strict + }); +} +function assertStartOffset(value, start) { + if (typeof start === "number" && start > 0 && start > size$5(value) - 1) + throw new SliceOffsetOutOfBoundsError({ + offset: start, + position: "start", + size: size$5(value) + }); +} +function assertEndOffset(value, start, end) { + if (typeof start === "number" && typeof end === "number" && size$5(value) !== end - start) { + throw new SliceOffsetOutOfBoundsError({ + offset: end, + position: "end", + size: size$5(value) }); - return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, value / __privateGet(other, _val), "divSignal"); } - /** - * Returns a comparison result between %%this%% and %%other%%. - * - * This is suitable for use in sorting, where ``-1`` implies %%this%% - * is smaller, ``1`` implies %%this%% is larger and ``0`` implies - * both are equal. - */ - cmp(other) { - let a2 = this.value, b2 = other.value; - const delta = this.decimals - other.decimals; - if (delta > 0) { - b2 *= getTens(delta); - } else if (delta < 0) { - a2 *= getTens(-delta); - } - if (a2 < b2) { - return -1; - } - if (a2 > b2) { - return 1; - } - return 0; - } - /** - * Returns true if %%other%% is equal to %%this%%. - */ - eq(other) { - return this.cmp(other) === 0; - } - /** - * Returns true if %%other%% is less than to %%this%%. - */ - lt(other) { - return this.cmp(other) < 0; - } - /** - * Returns true if %%other%% is less than or equal to %%this%%. - */ - lte(other) { - return this.cmp(other) <= 0; - } - /** - * Returns true if %%other%% is greater than to %%this%%. - */ - gt(other) { - return this.cmp(other) > 0; - } - /** - * Returns true if %%other%% is greater than or equal to %%this%%. - */ - gte(other) { - return this.cmp(other) >= 0; +} +function sliceBytes(value_, start, end, { strict } = {}) { + assertStartOffset(value_, start); + const value = value_.slice(start, end); + if (strict) + assertEndOffset(value, start, end); + return value; +} +function sliceHex(value_, start, end, { strict } = {}) { + assertStartOffset(value_, start); + const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`; + if (strict) + assertEndOffset(value, start, end); + return value; +} +function encodeAbiParameters(params, values) { + if (params.length !== values.length) + throw new AbiEncodingLengthMismatchError({ + expectedLength: params.length, + givenLength: values.length + }); + const preparedParams = prepareParams({ + params, + values + }); + const data = encodeParams(preparedParams); + if (data.length === 0) + return "0x"; + return data; +} +function prepareParams({ params, values }) { + const preparedParams = []; + for (let i = 0; i < params.length; i++) { + preparedParams.push(prepareParam({ param: params[i], value: values[i] })); } - /** - * Returns a new [[FixedNumber]] which is the largest **integer** - * that is less than or equal to %%this%%. - * - * The decimal component of the result will always be ``0``. - */ - floor() { - let val = __privateGet(this, _val); - if (__privateGet(this, _val) < BN_0$8) { - val -= __privateGet(this, _tens) - BN_1$4; - } - val = __privateGet(this, _val) / __privateGet(this, _tens) * __privateGet(this, _tens); - return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, val, "floor"); + return preparedParams; +} +function prepareParam({ param, value }) { + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return encodeArray(value, { length, param: { ...param, type } }); } - /** - * Returns a new [[FixedNumber]] which is the smallest **integer** - * that is greater than or equal to %%this%%. - * - * The decimal component of the result will always be ``0``. - */ - ceiling() { - let val = __privateGet(this, _val); - if (__privateGet(this, _val) > BN_0$8) { - val += __privateGet(this, _tens) - BN_1$4; - } - val = __privateGet(this, _val) / __privateGet(this, _tens) * __privateGet(this, _tens); - return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, val, "ceiling"); + if (param.type === "tuple") { + return encodeTuple(value, { + param + }); } - /** - * Returns a new [[FixedNumber]] with the decimal component - * rounded up on ties at %%decimals%% places. - */ - round(decimals) { - if (decimals == null) { - decimals = 0; - } - if (decimals >= this.decimals) { - return this; - } - const delta = this.decimals - decimals; - const bump = BN_5 * getTens(delta - 1); - let value = this.value + bump; - const tens = getTens(delta); - value = value / tens * tens; - checkValue(value, __privateGet(this, _format), "round"); - return new _FixedNumber(_guard$5, value, __privateGet(this, _format)); + if (param.type === "address") { + return encodeAddress(value); } - /** - * Returns true if %%this%% is equal to ``0``. - */ - isZero() { - return __privateGet(this, _val) === BN_0$8; + if (param.type === "bool") { + return encodeBool(value); } - /** - * Returns true if %%this%% is less than ``0``. - */ - isNegative() { - return __privateGet(this, _val) < BN_0$8; + if (param.type.startsWith("uint") || param.type.startsWith("int")) { + const signed2 = param.type.startsWith("int"); + return encodeNumber(value, { signed: signed2 }); } - /** - * Returns the string representation of %%this%%. - */ - toString() { - return this._value; + if (param.type.startsWith("bytes")) { + return encodeBytes$1(value, { param }); } - /** - * Returns a float approximation. - * - * Due to IEEE 754 precission (or lack thereof), this function - * can only return an approximation and most values will contain - * rounding errors. - */ - toUnsafeFloat() { - return parseFloat(this.toString()); + if (param.type === "string") { + return encodeString(value); } - /** - * Return a new [[FixedNumber]] with the same value but has had - * its field set to %%format%%. - * - * This will throw if the value cannot fit into %%format%%. - */ - toFormat(format2) { - return _FixedNumber.fromString(this.toString(), format2); + throw new InvalidAbiEncodingTypeError(param.type, { + docsPath: "/docs/contract/encodeAbiParameters" + }); +} +function encodeParams(preparedParams) { + let staticSize = 0; + for (let i = 0; i < preparedParams.length; i++) { + const { dynamic, encoded } = preparedParams[i]; + if (dynamic) + staticSize += 32; + else + staticSize += size$5(encoded); } - /** - * Creates a new [[FixedNumber]] for %%value%% divided by - * %%decimal%% places with %%format%%. - * - * This will throw a [[NumericFaultError]] if %%value%% (once adjusted - * for %%decimals%%) cannot fit in %%format%%, either due to overflow - * or underflow (precision loss). - */ - static fromValue(_value2, _decimals, _format2) { - const decimals = _decimals == null ? 0 : getNumber(_decimals); - const format2 = getFormat(_format2); - let value = getBigInt(_value2, "value"); - const delta = decimals - format2.decimals; - if (delta > 0) { - const tens = getTens(delta); - assert(value % tens === BN_0$8, "value loses precision for format", "NUMERIC_FAULT", { - operation: "fromValue", - fault: "underflow", - value: _value2 - }); - value /= tens; - } else if (delta < 0) { - value *= getTens(-delta); + const staticParams = []; + const dynamicParams = []; + let dynamicSize = 0; + for (let i = 0; i < preparedParams.length; i++) { + const { dynamic, encoded } = preparedParams[i]; + if (dynamic) { + staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 })); + dynamicParams.push(encoded); + dynamicSize += size$5(encoded); + } else { + staticParams.push(encoded); } - checkValue(value, format2, "fromValue"); - return new _FixedNumber(_guard$5, value, format2); } - /** - * Creates a new [[FixedNumber]] for %%value%% with %%format%%. - * - * This will throw a [[NumericFaultError]] if %%value%% cannot fit - * in %%format%%, either due to overflow or underflow (precision loss). - */ - static fromString(_value2, _format2) { - const match = _value2.match(/^(-?)([0-9]*)\.?([0-9]*)$/); - assertArgument(match && match[2].length + match[3].length > 0, "invalid FixedNumber string value", "value", _value2); - const format2 = getFormat(_format2); - let whole = match[2] || "0", decimal = match[3] || ""; - while (decimal.length < format2.decimals) { - decimal += Zeros$1; - } - assert(decimal.substring(format2.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", { - operation: "fromString", - fault: "underflow", - value: _value2 + return concat$1([...staticParams, ...dynamicParams]); +} +function encodeAddress(value) { + if (!isAddress$1(value)) + throw new InvalidAddressError({ address: value }); + return { dynamic: false, encoded: padHex(value.toLowerCase()) }; +} +function encodeArray(value, { length, param }) { + const dynamic = length === null; + if (!Array.isArray(value)) + throw new InvalidArrayError(value); + if (!dynamic && value.length !== length) + throw new AbiEncodingArrayLengthMismatchError({ + expectedLength: length, + givenLength: value.length, + type: `${param.type}[${length}]` }); - decimal = decimal.substring(0, format2.decimals); - const value = BigInt(match[1] + whole + decimal); - checkValue(value, format2, "fromString"); - return new _FixedNumber(_guard$5, value, format2); + let dynamicChild = false; + const preparedParams = []; + for (let i = 0; i < value.length; i++) { + const preparedParam = prepareParam({ param, value: value[i] }); + if (preparedParam.dynamic) + dynamicChild = true; + preparedParams.push(preparedParam); } - /** - * Creates a new [[FixedNumber]] with the big-endian representation - * %%value%% with %%format%%. - * - * This will throw a [[NumericFaultError]] if %%value%% cannot fit - * in %%format%% due to overflow. - */ - static fromBytes(_value2, _format2) { - let value = toBigInt(getBytes(_value2, "value")); - const format2 = getFormat(_format2); - if (format2.signed) { - value = fromTwos(value, format2.width); + if (dynamic || dynamicChild) { + const data = encodeParams(preparedParams); + if (dynamic) { + const length2 = numberToHex(preparedParams.length, { size: 32 }); + return { + dynamic: true, + encoded: preparedParams.length > 0 ? concat$1([length2, data]) : length2 + }; } - checkValue(value, format2, "fromBytes"); - return new _FixedNumber(_guard$5, value, format2); - } -}; -_format = new WeakMap(); -_val = new WeakMap(); -_tens = new WeakMap(); -_FixedNumber_instances = new WeakSet(); -checkFormat_fn = function(other) { - assertArgument(this.format === other.format, "incompatible format; use fixedNumber.toFormat", "other", other); -}; -checkValue_fn = function(val, safeOp) { - val = checkValue(val, __privateGet(this, _format), safeOp); - return new _FixedNumber(_guard$5, val, __privateGet(this, _format)); -}; -add_fn = function(o2, safeOp) { - __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, o2); - return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, __privateGet(this, _val) + __privateGet(o2, _val), safeOp); -}; -sub_fn = function(o2, safeOp) { - __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, o2); - return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, __privateGet(this, _val) - __privateGet(o2, _val), safeOp); -}; -mul_fn = function(o2, safeOp) { - __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, o2); - return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, __privateGet(this, _val) * __privateGet(o2, _val) / __privateGet(this, _tens), safeOp); -}; -div_fn = function(o2, safeOp) { - assert(__privateGet(o2, _val) !== BN_0$8, "division by zero", "NUMERIC_FAULT", { - operation: "div", - fault: "divide-by-zero", - value: this - }); - __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, o2); - return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, __privateGet(this, _val) * __privateGet(this, _tens) / __privateGet(o2, _val), safeOp); -}; -let FixedNumber = _FixedNumber; -function hexlifyByte(value) { - let result = value.toString(16); - while (result.length < 2) { - result = "0" + result; + if (dynamicChild) + return { dynamic: true, encoded: data }; } - return "0x" + result; + return { + dynamic: false, + encoded: concat$1(preparedParams.map(({ encoded }) => encoded)) + }; } -function unarrayifyInteger(data, offset2, length) { - let result = 0; - for (let i = 0; i < length; i++) { - result = result * 256 + data[offset2 + i]; +function encodeBytes$1(value, { param }) { + const [, paramSize] = param.type.split("bytes"); + const bytesSize = size$5(value); + if (!paramSize) { + let value_ = value; + if (bytesSize % 32 !== 0) + value_ = padHex(value_, { + dir: "right", + size: Math.ceil((value.length - 2) / 2 / 32) * 32 + }); + return { + dynamic: true, + encoded: concat$1([padHex(numberToHex(bytesSize, { size: 32 })), value_]) + }; } - return result; -} -function _decodeChildren(data, offset2, childOffset, length) { - const result = []; - while (childOffset < offset2 + 1 + length) { - const decoded = _decode$1(data, childOffset); - result.push(decoded.result); - childOffset += decoded.consumed; - assert(childOffset <= offset2 + 1 + length, "child data too short", "BUFFER_OVERRUN", { - buffer: data, - length, - offset: offset2 + if (bytesSize !== Number.parseInt(paramSize)) + throw new AbiEncodingBytesSizeMismatchError({ + expectedSize: Number.parseInt(paramSize), + value }); + return { dynamic: false, encoded: padHex(value, { dir: "right" }) }; +} +function encodeBool(value) { + if (typeof value !== "boolean") + throw new BaseError$3(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); + return { dynamic: false, encoded: padHex(boolToHex(value)) }; +} +function encodeNumber(value, { signed: signed2 }) { + return { + dynamic: false, + encoded: numberToHex(value, { + size: 32, + signed: signed2 + }) + }; +} +function encodeString(value) { + const hexValue = stringToHex(value); + const partsLength = Math.ceil(size$5(hexValue) / 32); + const parts = []; + for (let i = 0; i < partsLength; i++) { + parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), { + dir: "right" + })); } - return { consumed: 1 + length, result }; + return { + dynamic: true, + encoded: concat$1([ + padHex(numberToHex(size$5(hexValue), { size: 32 })), + ...parts + ]) + }; } -function _decode$1(data, offset2) { - assert(data.length !== 0, "data too short", "BUFFER_OVERRUN", { - buffer: data, - length: 0, - offset: 1 - }); - const checkOffset = (offset3) => { - assert(offset3 <= data.length, "data short segment too short", "BUFFER_OVERRUN", { - buffer: data, - length: data.length, - offset: offset3 +function encodeTuple(value, { param }) { + let dynamic = false; + const preparedParams = []; + for (let i = 0; i < param.components.length; i++) { + const param_ = param.components[i]; + const index2 = Array.isArray(value) ? i : param_.name; + const preparedParam = prepareParam({ + param: param_, + value: value[index2] }); - }; - if (data[offset2] >= 248) { - const lengthLength = data[offset2] - 247; - checkOffset(offset2 + 1 + lengthLength); - const length = unarrayifyInteger(data, offset2 + 1, lengthLength); - checkOffset(offset2 + 1 + lengthLength + length); - return _decodeChildren(data, offset2, offset2 + 1 + lengthLength, lengthLength + length); - } else if (data[offset2] >= 192) { - const length = data[offset2] - 192; - checkOffset(offset2 + 1 + length); - return _decodeChildren(data, offset2, offset2 + 1, length); - } else if (data[offset2] >= 184) { - const lengthLength = data[offset2] - 183; - checkOffset(offset2 + 1 + lengthLength); - const length = unarrayifyInteger(data, offset2 + 1, lengthLength); - checkOffset(offset2 + 1 + lengthLength + length); - const result = hexlify(data.slice(offset2 + 1 + lengthLength, offset2 + 1 + lengthLength + length)); - return { consumed: 1 + lengthLength + length, result }; - } else if (data[offset2] >= 128) { - const length = data[offset2] - 128; - checkOffset(offset2 + 1 + length); - const result = hexlify(data.slice(offset2 + 1, offset2 + 1 + length)); - return { consumed: 1 + length, result }; + preparedParams.push(preparedParam); + if (preparedParam.dynamic) + dynamic = true; } - return { consumed: 1, result: hexlifyByte(data[offset2]) }; + return { + dynamic, + encoded: dynamic ? encodeParams(preparedParams) : concat$1(preparedParams.map(({ encoded }) => encoded)) + }; } -function decodeRlp(_data6) { - const data = getBytes(_data6, "data"); - const decoded = _decode$1(data, 0); - assertArgument(decoded.consumed === data.length, "unexpected junk after rlp payload", "data", _data6); - return decoded.result; +function getArrayComponents(type) { + const matches = type.match(/^(.*)\[(\d+)?\]$/); + return matches ? ( + // Return `null` if the array is dynamic. + [matches[2] ? Number(matches[2]) : null, matches[1]] + ) : void 0; } -function arrayifyInteger(value) { - const result = []; - while (value) { - result.unshift(value & 255); - value >>= 8; - } - return result; +const docsPath$4 = "/docs/contract/encodeDeployData"; +function encodeDeployData(parameters) { + const { abi: abi2, args, bytecode } = parameters; + if (!args || args.length === 0) + return bytecode; + const description2 = abi2.find((x2) => "type" in x2 && x2.type === "constructor"); + if (!description2) + throw new AbiConstructorNotFoundError({ docsPath: docsPath$4 }); + if (!("inputs" in description2)) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath$4 }); + if (!description2.inputs || description2.inputs.length === 0) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath$4 }); + const data = encodeAbiParameters(description2.inputs, args); + return concatHex([bytecode, data]); } -function _encode$1(object2) { - if (Array.isArray(object2)) { - let payload = []; - object2.forEach(function(child) { - payload = payload.concat(_encode$1(child)); +function parseAccount(account2) { + if (typeof account2 === "string") + return { address: account2, type: "json-rpc" }; + return account2; +} +class AccountNotFoundError extends BaseError$3 { + constructor({ docsPath: docsPath2 } = {}) { + super([ + "Could not find an Account to execute with this Action.", + "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client." + ].join("\n"), { + docsPath: docsPath2, + docsSlug: "account", + name: "AccountNotFoundError" }); - if (payload.length <= 55) { - payload.unshift(192 + payload.length); - return payload; - } - const length2 = arrayifyInteger(payload.length); - length2.unshift(247 + length2.length); - return length2.concat(payload); - } - const data = Array.prototype.slice.call(getBytes(object2, "object")); - if (data.length === 1 && data[0] <= 127) { - return data; - } else if (data.length <= 55) { - data.unshift(128 + data.length); - return data; } - const length = arrayifyInteger(data.length); - length.unshift(183 + length.length); - return length.concat(data); } -const nibbles = "0123456789abcdef"; -function encodeRlp(object2) { - let result = "0x"; - for (const v3 of _encode$1(object2)) { - result += nibbles[v3 >> 4]; - result += nibbles[v3 & 15]; - } - return result; -} -const names = [ - "wei", - "kwei", - "mwei", - "gwei", - "szabo", - "finney", - "ether" -]; -function formatUnits$2(value, unit) { - let decimals = 18; - if (typeof unit === "string") { - const index2 = names.indexOf(unit); - assertArgument(index2 >= 0, "invalid unit", "unit", unit); - decimals = 3 * index2; - } else if (unit != null) { - decimals = getNumber(unit, "unit"); - } - return FixedNumber.fromValue(value, decimals, { decimals, width: 512 }).toString(); -} -function parseUnits$3(value, unit) { - assertArgument(typeof value === "string", "value must be a string", "value", value); - let decimals = 18; - if (typeof unit === "string") { - const index2 = names.indexOf(unit); - assertArgument(index2 >= 0, "invalid unit", "unit", unit); - decimals = 3 * index2; - } else if (unit != null) { - decimals = getNumber(unit, "unit"); - } - return FixedNumber.fromString(value, { decimals, width: 512 }).value; -} -function formatEther$2(wei) { - return formatUnits$2(wei, 18); -} -function parseEther$1(ether) { - return parseUnits$3(ether, 18); -} -function uuidV4(randomBytes2) { - const bytes2 = getBytes(randomBytes2, "randomBytes"); - bytes2[6] = bytes2[6] & 15 | 64; - bytes2[8] = bytes2[8] & 63 | 128; - const value = hexlify(bytes2); - return [ - value.substring(2, 10), - value.substring(10, 14), - value.substring(14, 18), - value.substring(18, 22), - value.substring(22, 34) - ].join("-"); -} -const WordSize = 32; -const Padding = new Uint8Array(WordSize); -const passProperties$1 = ["then"]; -const _guard$4 = {}; -const resultNames = /* @__PURE__ */ new WeakMap(); -function getNames(result) { - return resultNames.get(result); -} -function setNames(result, names2) { - resultNames.set(result, names2); -} -function throwError(name2, error) { - const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name2}`); - wrapped.error = error; - throw wrapped; -} -function toObject(names2, items, deep) { - if (names2.indexOf(null) >= 0) { - return items.map((item2, index2) => { - if (item2 instanceof Result) { - return toObject(getNames(item2), item2, deep); - } - return item2; +class AccountTypeNotSupportedError extends BaseError$3 { + constructor({ docsPath: docsPath2, metaMessages, type }) { + super(`Account type "${type}" is not supported.`, { + docsPath: docsPath2, + metaMessages, + name: "AccountTypeNotSupportedError" }); } - return names2.reduce((accum, name2, index2) => { - let item2 = items.getValue(name2); - if (!(name2 in accum)) { - if (deep && item2 instanceof Result) { - item2 = toObject(getNames(item2), item2, deep); - } - accum[name2] = item2; - } - return accum; - }, {}); } -const _Result = class _Result extends Array { - /** - * @private - */ - constructor(...args) { - const guard2 = args[0]; - let items = args[1]; - let names2 = (args[2] || []).slice(); - let wrap2 = true; - if (guard2 !== _guard$4) { - items = args; - names2 = []; - wrap2 = false; - } - super(items.length); - // No longer used; but cannot be removed as it will remove the - // #private field from the .d.ts which may break backwards - // compatibility - __privateAdd(this, _names); - items.forEach((item2, index2) => { - this[index2] = item2; - }); - const nameCounts = names2.reduce((accum, name2) => { - if (typeof name2 === "string") { - accum.set(name2, (accum.get(name2) || 0) + 1); - } - return accum; - }, /* @__PURE__ */ new Map()); - setNames(this, Object.freeze(items.map((item2, index2) => { - const name2 = names2[index2]; - if (name2 != null && nameCounts.get(name2) === 1) { - return name2; - } - return null; - }))); - __privateSet(this, _names, []); - if (__privateGet(this, _names) == null) { - void __privateGet(this, _names); - } - if (!wrap2) { - return; - } - Object.freeze(this); - const proxy = new Proxy(this, { - get: (target, prop, receiver) => { - if (typeof prop === "string") { - if (prop.match(/^[0-9]+$/)) { - const index2 = getNumber(prop, "%index"); - if (index2 < 0 || index2 >= this.length) { - throw new RangeError("out of result range"); - } - const item2 = target[index2]; - if (item2 instanceof Error) { - throwError(`index ${index2}`, item2); +function publicKeyToAddress(publicKey) { + const address = keccak256$1(`0x${publicKey.substring(4)}`).substring(26); + return checksumAddress(`0x${address}`); +} +const scriptRel = "modulepreload"; +const assetsURL = function(dep, importerUrl) { + return new URL(dep, importerUrl).href; +}; +const seen = {}; +const __vitePreload = function preload(baseModule, deps, importerUrl) { + let promise = Promise.resolve(); + if (deps && deps.length > 0) { + const links = document.getElementsByTagName("link"); + const cspNonceMeta = document.querySelector( + "meta[property=csp-nonce]" + ); + const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce")); + promise = Promise.allSettled( + deps.map((dep) => { + dep = assetsURL(dep, importerUrl); + if (dep in seen) return; + seen[dep] = true; + const isCss = dep.endsWith(".css"); + const cssSelector = isCss ? '[rel="stylesheet"]' : ""; + const isBaseRelative = !!importerUrl; + if (isBaseRelative) { + for (let i = links.length - 1; i >= 0; i--) { + const link2 = links[i]; + if (link2.href === dep && (!isCss || link2.rel === "stylesheet")) { + return; } - return item2; - } - if (passProperties$1.indexOf(prop) >= 0) { - return Reflect.get(target, prop, receiver); - } - const value = target[prop]; - if (value instanceof Function) { - return function(...args2) { - return value.apply(this === receiver ? target : this, args2); - }; - } else if (!(prop in target)) { - return target.getValue.apply(this === receiver ? target : this, [prop]); } + } else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) { + return; } - return Reflect.get(target, prop, receiver); - } - }); - setNames(proxy, getNames(this)); - return proxy; + const link = document.createElement("link"); + link.rel = isCss ? "stylesheet" : scriptRel; + if (!isCss) { + link.as = "script"; + } + link.crossOrigin = ""; + link.href = dep; + if (cspNonce) { + link.setAttribute("nonce", cspNonce); + } + document.head.appendChild(link); + if (isCss) { + return new Promise((res, rej) => { + link.addEventListener("load", res); + link.addEventListener( + "error", + () => rej(new Error(`Unable to preload CSS for ${dep}`)) + ); + }); + } + }) + ); } - /** - * Returns the Result as a normal Array. If %%deep%%, any children - * which are Result objects are also converted to a normal Array. - * - * This will throw if there are any outstanding deferred - * errors. - */ - toArray(deep) { - const result = []; - this.forEach((item2, index2) => { - if (item2 instanceof Error) { - throwError(`index ${index2}`, item2); - } - if (deep && item2 instanceof _Result) { - item2 = item2.toArray(deep); - } - result.push(item2); + function handlePreloadError(err) { + const e2 = new Event("vite:preloadError", { + cancelable: true }); - return result; - } - /** - * Returns the Result as an Object with each name-value pair. If - * %%deep%%, any children which are Result objects are also - * converted to an Object. - * - * This will throw if any value is unnamed, or if there are - * any outstanding deferred errors. - */ - toObject(deep) { - const names2 = getNames(this); - return names2.reduce((accum, name2, index2) => { - assert(name2 != null, `value at index ${index2} unnamed`, "UNSUPPORTED_OPERATION", { - operation: "toObject()" - }); - return toObject(names2, this, deep); - }, {}); - } - /** - * @_ignore - */ - slice(start, end) { - if (start == null) { - start = 0; - } - if (start < 0) { - start += this.length; - if (start < 0) { - start = 0; - } - } - if (end == null) { - end = this.length; - } - if (end < 0) { - end += this.length; - if (end < 0) { - end = 0; - } - } - if (end > this.length) { - end = this.length; - } - const _names2 = getNames(this); - const result = [], names2 = []; - for (let i = start; i < end; i++) { - result.push(this[i]); - names2.push(_names2[i]); - } - return new _Result(_guard$4, result, names2); - } - /** - * @_ignore - */ - filter(callback, thisArg) { - const _names2 = getNames(this); - const result = [], names2 = []; - for (let i = 0; i < this.length; i++) { - const item2 = this[i]; - if (item2 instanceof Error) { - throwError(`index ${i}`, item2); - } - if (callback.call(thisArg, item2, i, this)) { - result.push(item2); - names2.push(_names2[i]); - } - } - return new _Result(_guard$4, result, names2); - } - /** - * @_ignore - */ - map(callback, thisArg) { - const result = []; - for (let i = 0; i < this.length; i++) { - const item2 = this[i]; - if (item2 instanceof Error) { - throwError(`index ${i}`, item2); - } - result.push(callback.call(thisArg, item2, i, this)); + e2.payload = err; + window.dispatchEvent(e2); + if (!e2.defaultPrevented) { + throw err; } - return result; } - /** - * Returns the value for %%name%%. - * - * Since it is possible to have a key whose name conflicts with - * a method on a [[Result]] or its superclass Array, or any - * JavaScript keyword, this ensures all named values are still - * accessible by name. - */ - getValue(name2) { - const index2 = getNames(this).indexOf(name2); - if (index2 === -1) { - return void 0; - } - const value = this[index2]; - if (value instanceof Error) { - throwError(`property ${JSON.stringify(name2)}`, value.error); + return promise.then((res) => { + for (const item2 of res || []) { + if (item2.status !== "rejected") continue; + handlePreloadError(item2.reason); } - return value; - } - /** - * Creates a new [[Result]] for %%items%% with each entry - * also accessible by its corresponding name in %%keys%%. - */ - static fromItems(items, keys) { - return new _Result(_guard$4, items, keys); - } + return baseModule().catch(handlePreloadError); + }); }; -_names = new WeakMap(); -let Result = _Result; -function checkResultErrors(result) { - const errors2 = []; - const checkErrors = function(path, object2) { - if (!Array.isArray(object2)) { - return; - } - for (let key in object2) { - const childPath = path.slice(); - childPath.push(key); - try { - checkErrors(childPath, object2[key]); - } catch (error) { - errors2.push({ path: childPath, error }); - } +async function recoverPublicKey({ hash: hash2, signature: signature2 }) { + const hashHex = isHex(hash2) ? hash2 : toHex$1(hash2); + const { secp256k1: secp256k12 } = await __vitePreload(async () => { + const { secp256k1: secp256k13 } = await Promise.resolve().then(() => secp256k1$2); + return { secp256k1: secp256k13 }; + }, true ? void 0 : void 0, import.meta.url); + const signature_ = (() => { + if (typeof signature2 === "object" && "r" in signature2 && "s" in signature2) { + const { r: r2, s: s2, v: v3, yParity } = signature2; + const yParityOrV2 = Number(yParity ?? v3); + const recoveryBit2 = toRecoveryBit(yParityOrV2); + return new secp256k12.Signature(hexToBigInt(r2), hexToBigInt(s2)).addRecoveryBit(recoveryBit2); } - }; - checkErrors([], result); - return errors2; + const signatureHex = isHex(signature2) ? signature2 : toHex$1(signature2); + const yParityOrV = hexToNumber$2(`0x${signatureHex.slice(130)}`); + const recoveryBit = toRecoveryBit(yParityOrV); + return secp256k12.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit); + })(); + const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false); + return `0x${publicKey}`; } -function getValue$1(value) { - let bytes2 = toBeArray(value); - assert(bytes2.length <= WordSize, "value out-of-bounds", "BUFFER_OVERRUN", { buffer: bytes2, length: WordSize, offset: bytes2.length }); - if (bytes2.length !== WordSize) { - bytes2 = getBytesCopy(concat$1([Padding.slice(bytes2.length % WordSize), bytes2])); - } - return bytes2; +function toRecoveryBit(yParityOrV) { + if (yParityOrV === 0 || yParityOrV === 1) + return yParityOrV; + if (yParityOrV === 27) + return 0; + if (yParityOrV === 28) + return 1; + throw new Error("Invalid yParityOrV value"); } -class Coder { - constructor(name2, type, localName, dynamic) { - // The coder name: - // - address, uint256, tuple, array, etc. - __publicField(this, "name"); - // The fully expanded type, including composite types: - // - address, uint256, tuple(address,bytes), uint256[3][4][], etc. - __publicField(this, "type"); - // The localName bound in the signature, in this example it is "baz": - // - tuple(address foo, uint bar) baz - __publicField(this, "localName"); - // Whether this type is dynamic: - // - Dynamic: bytes, string, address[], tuple(boolean[]), etc. - // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8) - __publicField(this, "dynamic"); - defineProperties$1(this, { name: name2, type, localName, dynamic }, { - name: "string", - type: "string", - localName: "string", - dynamic: "boolean" +async function recoverAddress$1({ hash: hash2, signature: signature2 }) { + return publicKeyToAddress(await recoverPublicKey({ hash: hash2, signature: signature2 })); +} +class NegativeOffsetError extends BaseError$3 { + constructor({ offset: offset2 }) { + super(`Offset \`${offset2}\` cannot be negative.`, { + name: "NegativeOffsetError" }); } - _throwError(message, value) { - assertArgument(false, message, this.localName, value); - } } -class Writer { - constructor() { - __privateAdd(this, _Writer_instances); - // An array of WordSize lengthed objects to concatenation - __privateAdd(this, _data2); - __privateAdd(this, _dataLength); - __privateSet(this, _data2, []); - __privateSet(this, _dataLength, 0); - } - get data() { - return concat$1(__privateGet(this, _data2)); - } - get length() { - return __privateGet(this, _dataLength); - } - appendWriter(writer) { - return __privateMethod(this, _Writer_instances, writeData_fn).call(this, getBytesCopy(writer.data)); - } - // Arrayish item; pad on the right to *nearest* WordSize - writeBytes(value) { - let bytes2 = getBytesCopy(value); - const paddingOffset = bytes2.length % WordSize; - if (paddingOffset) { - bytes2 = getBytesCopy(concat$1([bytes2, Padding.slice(paddingOffset)])); - } - return __privateMethod(this, _Writer_instances, writeData_fn).call(this, bytes2); - } - // Numeric item; pad on the left *to* WordSize - writeValue(value) { - return __privateMethod(this, _Writer_instances, writeData_fn).call(this, getValue$1(value)); - } - // Inserts a numeric place-holder, returning a callback that can - // be used to asjust the value later - writeUpdatableValue() { - const offset2 = __privateGet(this, _data2).length; - __privateGet(this, _data2).push(Padding); - __privateSet(this, _dataLength, __privateGet(this, _dataLength) + WordSize); - return (value) => { - __privateGet(this, _data2)[offset2] = getValue$1(value); - }; +class PositionOutOfBoundsError extends BaseError$3 { + constructor({ length, position }) { + super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); } } -_data2 = new WeakMap(); -_dataLength = new WeakMap(); -_Writer_instances = new WeakSet(); -writeData_fn = function(data) { - __privateGet(this, _data2).push(data); - __privateSet(this, _dataLength, __privateGet(this, _dataLength) + data.length); - return data.length; -}; -const _Reader = class _Reader { - constructor(data, allowLoose, maxInflation) { - __privateAdd(this, _Reader_instances); - // Allows incomplete unpadded data to be read; otherwise an error - // is raised if attempting to overrun the buffer. This is required - // to deal with an old Solidity bug, in which event data for - // external (not public thoguh) was tightly packed. - __publicField(this, "allowLoose"); - __privateAdd(this, _data3); - __privateAdd(this, _offset); - __privateAdd(this, _bytesRead); - __privateAdd(this, _parent); - __privateAdd(this, _maxInflation); - defineProperties$1(this, { allowLoose: !!allowLoose }); - __privateSet(this, _data3, getBytesCopy(data)); - __privateSet(this, _bytesRead, 0); - __privateSet(this, _parent, null); - __privateSet(this, _maxInflation, maxInflation != null ? maxInflation : 1024); - __privateSet(this, _offset, 0); - } - get data() { - return hexlify(__privateGet(this, _data3)); - } - get dataLength() { - return __privateGet(this, _data3).length; +class RecursiveReadLimitExceededError extends BaseError$3 { + constructor({ count: count2, limit }) { + super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count2}\`).`, { name: "RecursiveReadLimitExceededError" }); } - get consumed() { - return __privateGet(this, _offset); - } - get bytes() { - return new Uint8Array(__privateGet(this, _data3)); - } - // Create a sub-reader with the same underlying data, but offset - subReader(offset2) { - const reader2 = new _Reader(__privateGet(this, _data3).slice(__privateGet(this, _offset) + offset2), this.allowLoose, __privateGet(this, _maxInflation)); - __privateSet(reader2, _parent, this); - return reader2; - } - // Read bytes - readBytes(length, loose) { - let bytes2 = __privateMethod(this, _Reader_instances, peekBytes_fn).call(this, 0, length, !!loose); - __privateMethod(this, _Reader_instances, incrementBytesRead_fn).call(this, length); - __privateSet(this, _offset, __privateGet(this, _offset) + bytes2.length); - return bytes2.slice(0, length); - } - // Read a numeric values - readValue() { - return toBigInt(this.readBytes(WordSize)); - } - readIndex() { - return toNumber(this.readBytes(WordSize)); +} +const staticCursor = { + bytes: new Uint8Array(), + dataView: new DataView(new ArrayBuffer(0)), + position: 0, + positionReadCount: /* @__PURE__ */ new Map(), + recursiveReadCount: 0, + recursiveReadLimit: Number.POSITIVE_INFINITY, + assertReadLimit() { + if (this.recursiveReadCount >= this.recursiveReadLimit) + throw new RecursiveReadLimitExceededError({ + count: this.recursiveReadCount + 1, + limit: this.recursiveReadLimit + }); + }, + assertPosition(position) { + if (position < 0 || position > this.bytes.length - 1) + throw new PositionOutOfBoundsError({ + length: this.bytes.length, + position + }); + }, + decrementPosition(offset2) { + if (offset2 < 0) + throw new NegativeOffsetError({ offset: offset2 }); + const position = this.position - offset2; + this.assertPosition(position); + this.position = position; + }, + getReadCount(position) { + return this.positionReadCount.get(position || this.position) || 0; + }, + incrementPosition(offset2) { + if (offset2 < 0) + throw new NegativeOffsetError({ offset: offset2 }); + const position = this.position + offset2; + this.assertPosition(position); + this.position = position; + }, + inspectByte(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectBytes(length, position_) { + const position = position_ ?? this.position; + this.assertPosition(position + length - 1); + return this.bytes.subarray(position, position + length); + }, + inspectUint8(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectUint16(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 1); + return this.dataView.getUint16(position); + }, + inspectUint24(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 2); + return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); + }, + inspectUint32(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 3); + return this.dataView.getUint32(position); + }, + pushByte(byte) { + this.assertPosition(this.position); + this.bytes[this.position] = byte; + this.position++; + }, + pushBytes(bytes2) { + this.assertPosition(this.position + bytes2.length - 1); + this.bytes.set(bytes2, this.position); + this.position += bytes2.length; + }, + pushUint8(value) { + this.assertPosition(this.position); + this.bytes[this.position] = value; + this.position++; + }, + pushUint16(value) { + this.assertPosition(this.position + 1); + this.dataView.setUint16(this.position, value); + this.position += 2; + }, + pushUint24(value) { + this.assertPosition(this.position + 2); + this.dataView.setUint16(this.position, value >> 8); + this.dataView.setUint8(this.position + 2, value & ~4294967040); + this.position += 3; + }, + pushUint32(value) { + this.assertPosition(this.position + 3); + this.dataView.setUint32(this.position, value); + this.position += 4; + }, + readByte() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectByte(); + this.position++; + return value; + }, + readBytes(length, size2) { + this.assertReadLimit(); + this._touch(); + const value = this.inspectBytes(length); + this.position += size2 ?? length; + return value; + }, + readUint8() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint8(); + this.position += 1; + return value; + }, + readUint16() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint16(); + this.position += 2; + return value; + }, + readUint24() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint24(); + this.position += 3; + return value; + }, + readUint32() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint32(); + this.position += 4; + return value; + }, + get remaining() { + return this.bytes.length - this.position; + }, + setPosition(position) { + const oldPosition = this.position; + this.assertPosition(position); + this.position = position; + return () => this.position = oldPosition; + }, + _touch() { + if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) + return; + const count2 = this.getReadCount(); + this.positionReadCount.set(this.position, count2 + 1); + if (count2 > 0) + this.recursiveReadCount++; } }; -_data3 = new WeakMap(); -_offset = new WeakMap(); -_bytesRead = new WeakMap(); -_parent = new WeakMap(); -_maxInflation = new WeakMap(); -_Reader_instances = new WeakSet(); -incrementBytesRead_fn = function(count2) { - var _a2; - if (__privateGet(this, _parent)) { - return __privateMethod(_a2 = __privateGet(this, _parent), _Reader_instances, incrementBytesRead_fn).call(_a2, count2); - } - __privateSet(this, _bytesRead, __privateGet(this, _bytesRead) + count2); - assert(__privateGet(this, _maxInflation) < 1 || __privateGet(this, _bytesRead) <= __privateGet(this, _maxInflation) * this.dataLength, `compressed ABI data exceeds inflation ratio of ${__privateGet(this, _maxInflation)} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`, "BUFFER_OVERRUN", { - buffer: getBytesCopy(__privateGet(this, _data3)), - offset: __privateGet(this, _offset), - length: count2, - info: { - bytesRead: __privateGet(this, _bytesRead), - dataLength: this.dataLength +function createCursor(bytes2, { recursiveReadLimit = 8192 } = {}) { + const cursor = Object.create(staticCursor); + cursor.bytes = bytes2; + cursor.dataView = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength); + cursor.positionReadCount = /* @__PURE__ */ new Map(); + cursor.recursiveReadLimit = recursiveReadLimit; + return cursor; +} +function toRlp(bytes2, to = "hex") { + const encodable = getEncodable(bytes2); + const cursor = createCursor(new Uint8Array(encodable.length)); + encodable.encode(cursor); + if (to === "hex") + return bytesToHex$3(cursor.bytes); + return cursor.bytes; +} +function getEncodable(bytes2) { + if (Array.isArray(bytes2)) + return getEncodableList(bytes2.map((x2) => getEncodable(x2))); + return getEncodableBytes(bytes2); +} +function getEncodableList(list2) { + const bodyLength = list2.reduce((acc, x2) => acc + x2.length, 0); + const sizeOfBodyLength = getSizeOfLength(bodyLength); + const length = (() => { + if (bodyLength <= 55) + return 1 + bodyLength; + return 1 + sizeOfBodyLength + bodyLength; + })(); + return { + length, + encode(cursor) { + if (bodyLength <= 55) { + cursor.pushByte(192 + bodyLength); + } else { + cursor.pushByte(192 + 55 + sizeOfBodyLength); + if (sizeOfBodyLength === 1) + cursor.pushUint8(bodyLength); + else if (sizeOfBodyLength === 2) + cursor.pushUint16(bodyLength); + else if (sizeOfBodyLength === 3) + cursor.pushUint24(bodyLength); + else + cursor.pushUint32(bodyLength); + } + for (const { encode: encode2 } of list2) { + encode2(cursor); + } } - }); -}; -peekBytes_fn = function(offset2, length, loose) { - let alignedLength = Math.ceil(length / WordSize) * WordSize; - if (__privateGet(this, _offset) + alignedLength > __privateGet(this, _data3).length) { - if (this.allowLoose && loose && __privateGet(this, _offset) + length <= __privateGet(this, _data3).length) { - alignedLength = length; - } else { - assert(false, "data out-of-bounds", "BUFFER_OVERRUN", { - buffer: getBytesCopy(__privateGet(this, _data3)), - length: __privateGet(this, _data3).length, - offset: __privateGet(this, _offset) + alignedLength - }); + }; +} +function getEncodableBytes(bytesOrHex) { + const bytes2 = typeof bytesOrHex === "string" ? hexToBytes$2(bytesOrHex) : bytesOrHex; + const sizeOfBytesLength = getSizeOfLength(bytes2.length); + const length = (() => { + if (bytes2.length === 1 && bytes2[0] < 128) + return 1; + if (bytes2.length <= 55) + return 1 + bytes2.length; + return 1 + sizeOfBytesLength + bytes2.length; + })(); + return { + length, + encode(cursor) { + if (bytes2.length === 1 && bytes2[0] < 128) { + cursor.pushBytes(bytes2); + } else if (bytes2.length <= 55) { + cursor.pushByte(128 + bytes2.length); + cursor.pushBytes(bytes2); + } else { + cursor.pushByte(128 + 55 + sizeOfBytesLength); + if (sizeOfBytesLength === 1) + cursor.pushUint8(bytes2.length); + else if (sizeOfBytesLength === 2) + cursor.pushUint16(bytes2.length); + else if (sizeOfBytesLength === 3) + cursor.pushUint24(bytes2.length); + else + cursor.pushUint32(bytes2.length); + cursor.pushBytes(bytes2); + } } - } - return __privateGet(this, _data3).slice(__privateGet(this, _offset), __privateGet(this, _offset) + alignedLength); -}; -let Reader = _Reader; -const global$1 = globalThis || void 0 || self; -function number$1(n2) { - if (!Number.isSafeInteger(n2) || n2 < 0) - throw new Error(`Wrong positive integer: ${n2}`); + }; } -function bytes$2(b2, ...lengths) { - if (!(b2 instanceof Uint8Array)) - throw new Error("Expected Uint8Array"); - if (lengths.length > 0 && !lengths.includes(b2.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b2.length}`); +function getSizeOfLength(length) { + if (length < 2 ** 8) + return 1; + if (length < 2 ** 16) + return 2; + if (length < 2 ** 24) + return 3; + if (length < 2 ** 32) + return 4; + throw new BaseError$3("Length is too large."); } -function hash$2(hash2) { - if (typeof hash2 !== "function" || typeof hash2.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - number$1(hash2.outputLen); - number$1(hash2.blockLen); +function hashAuthorization(parameters) { + const { chainId, contractAddress, nonce, to } = parameters; + const hash2 = keccak256$1(concatHex([ + "0x05", + toRlp([ + numberToHex(chainId), + contractAddress, + nonce ? numberToHex(nonce) : "0x" + ]) + ])); + if (to === "bytes") + return hexToBytes$2(hash2); + return hash2; } -function exists$2(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); +async function recoverAuthorizationAddress(parameters) { + const { authorization, signature: signature2 } = parameters; + return recoverAddress$1({ + hash: hashAuthorization(authorization), + signature: signature2 ?? authorization + }); } -function output$2(out, instance) { - bytes$2(out); - const min2 = instance.outputLen; - if (out.length < min2) { - throw new Error(`digestInto() expects output buffer of length at least ${min2}`); +class ChainDoesNotSupportContract extends BaseError$3 { + constructor({ blockNumber, chain, contract }) { + super(`Chain "${chain.name}" does not support contract "${contract.name}".`, { + metaMessages: [ + "This could be due to any of the following:", + ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [ + `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).` + ] : [ + `- The chain does not have the contract "${contract.name}" configured.` + ] + ], + name: "ChainDoesNotSupportContract" + }); } } -const crypto$3 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; -/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const u8a$1 = (a2) => a2 instanceof Uint8Array; -const u32$1 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -const createView$2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -const rotr$2 = (word, shift2) => word << 32 - shift2 | word >>> shift2; -const isLE$1 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; -if (!isLE$1) - throw new Error("Non little-endian hardware is not supported"); -const nextTick = async () => { +class ChainMismatchError extends BaseError$3 { + constructor({ chain, currentChainId }) { + super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} – ${chain.name}).`, { + metaMessages: [ + `Current Chain ID: ${currentChainId}`, + `Expected Chain ID: ${chain.id} – ${chain.name}` + ], + name: "ChainMismatchError" + }); + } +} +let ChainNotFoundError$1 = class ChainNotFoundError extends BaseError$3 { + constructor() { + super([ + "No chain was provided to the request.", + "Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient." + ].join("\n"), { + name: "ChainNotFoundError" + }); + } }; -async function asyncLoop(iters, tick, cb2) { - let ts = Date.now(); - for (let i = 0; i < iters; i++) { - cb2(i); - const diff = Date.now() - ts; - if (diff >= 0 && diff < tick) - continue; - await nextTick(); - ts += diff; +class ClientChainNotConfiguredError extends BaseError$3 { + constructor() { + super("No chain was provided to the Client.", { + name: "ClientChainNotConfiguredError" + }); } } -function utf8ToBytes$4(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); +function assertCurrentChain({ chain, currentChainId }) { + if (!chain) + throw new ChainNotFoundError$1(); + if (currentChainId !== chain.id) + throw new ChainMismatchError({ chain, currentChainId }); } -function toBytes$3(data) { - if (typeof data === "string") - data = utf8ToBytes$4(data); - if (!u8a$1(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; +const etherUnits = { + gwei: 9, + wei: 18 +}; +const gweiUnits = { + ether: -9, + wei: 9 +}; +function formatUnits$2(value, decimals) { + let display = value.toString(); + const negative = display.startsWith("-"); + if (negative) + display = display.slice(1); + display = display.padStart(decimals, "0"); + let [integer, fraction] = [ + display.slice(0, display.length - decimals), + display.slice(display.length - decimals) + ]; + fraction = fraction.replace(/(0+)$/, ""); + return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`; } -function concatBytes$4(...arrays) { - const r2 = new Uint8Array(arrays.reduce((sum, a2) => sum + a2.length, 0)); - let pad2 = 0; - arrays.forEach((a2) => { - if (!u8a$1(a2)) - throw new Error("Uint8Array expected"); - r2.set(a2, pad2); - pad2 += a2.length; - }); - return r2; +function formatGwei(wei, unit = "wei") { + return formatUnits$2(wei, gweiUnits[unit]); } -let Hash$2 = class Hash { - // Safe version that clones internal state - clone() { - return this._cloneInto(); +class ExecutionRevertedError extends BaseError$3 { + constructor({ cause, message } = {}) { + var _a2; + const reason = (_a2 = message == null ? void 0 : message.replace("execution reverted: ", "")) == null ? void 0 : _a2.replace("execution reverted", ""); + super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { + cause, + name: "ExecutionRevertedError" + }); } -}; -const toStr = {}.toString; -function checkOpts(defaults2, opts) { - if (opts !== void 0 && toStr.call(opts) !== "[object Object]") - throw new Error("Options should be object or undefined"); - const merged = Object.assign(defaults2, opts); - return merged; } -function wrapConstructor$2(hashCons) { - const hashC = (msg) => hashCons().update(toBytes$3(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; +Object.defineProperty(ExecutionRevertedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 3 +}); +Object.defineProperty(ExecutionRevertedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /execution reverted/ +}); +class FeeCapTooHighError extends BaseError$3 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, { + cause, + name: "FeeCapTooHighError" + }); + } } -function randomBytes$3(bytesLength = 32) { - if (crypto$3 && typeof crypto$3.getRandomValues === "function") { - return crypto$3.getRandomValues(new Uint8Array(bytesLength)); +Object.defineProperty(FeeCapTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/ +}); +class FeeCapTooLowError extends BaseError$3 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, { + cause, + name: "FeeCapTooLowError" + }); } - throw new Error("crypto.getRandomValues must be defined"); } -let HMAC$1 = class HMAC extends Hash$2 { - constructor(hash2, _key) { - super(); - this.finished = false; - this.destroyed = false; - hash$2(hash2); - const key = toBytes$3(_key); - this.iHash = hash2.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad2 = new Uint8Array(blockLen); - pad2.set(key.length > blockLen ? hash2.create().update(key).digest() : key); - for (let i = 0; i < pad2.length; i++) - pad2[i] ^= 54; - this.iHash.update(pad2); - this.oHash = hash2.create(); - for (let i = 0; i < pad2.length; i++) - pad2[i] ^= 54 ^ 92; - this.oHash.update(pad2); - pad2.fill(0); - } - update(buf) { - exists$2(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - exists$2(this); - bytes$2(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); +Object.defineProperty(FeeCapTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/ +}); +class NonceTooHighError extends BaseError$3 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" }); } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; +} +Object.defineProperty(NonceTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too high/ +}); +class NonceTooLowError extends BaseError$3 { + constructor({ cause, nonce } = {}) { + super([ + `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`, + "Try increasing the nonce or find the latest nonce with `getTransactionCount`." + ].join("\n"), { cause, name: "NonceTooLowError" }); } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; +} +Object.defineProperty(NonceTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too low|transaction already imported|already known/ +}); +class NonceMaxValueError extends BaseError$3 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" }); } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); +} +Object.defineProperty(NonceMaxValueError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce has max value/ +}); +class InsufficientFundsError extends BaseError$3 { + constructor({ cause } = {}) { + super([ + "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account." + ].join("\n"), { + cause, + metaMessages: [ + "This error could arise when the account does not have enough funds to:", + " - pay for the total gas fee,", + " - pay for the value to send.", + " ", + "The cost of the transaction is calculated as `gas * gas fee + value`, where:", + " - `gas` is the amount of gas needed for transaction to execute,", + " - `gas fee` is the gas fee,", + " - `value` is the amount of ether to send to the recipient." + ], + name: "InsufficientFundsError" + }); } -}; -const hmac$2 = (hash2, key, message) => new HMAC$1(hash2, key).update(message).digest(); -hmac$2.create = (hash2, key) => new HMAC$1(hash2, key); -function pbkdf2Init(hash2, _password, _salt, _opts) { - hash$2(hash2); - const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); - const { c: c2, dkLen, asyncTick } = opts; - number$1(c2); - number$1(dkLen); - number$1(asyncTick); - if (c2 < 1) - throw new Error("PBKDF2: iterations (c) should be >= 1"); - const password = toBytes$3(_password); - const salt = toBytes$3(_salt); - const DK = new Uint8Array(dkLen); - const PRF = hmac$2.create(hash2, password); - const PRFSalt = PRF._cloneInto().update(salt); - return { c: c2, dkLen, asyncTick, DK, PRF, PRFSalt }; } -function pbkdf2Output(PRF, PRFSalt, DK, prfW, u2) { - PRF.destroy(); - PRFSalt.destroy(); - if (prfW) - prfW.destroy(); - u2.fill(0); - return DK; +Object.defineProperty(InsufficientFundsError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /insufficient funds|exceeds transaction sender account balance/ +}); +class IntrinsicGasTooHighError extends BaseError$3 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, { + cause, + name: "IntrinsicGasTooHighError" + }); + } } -function pbkdf2$1(hash2, password, salt, opts) { - const { c: c2, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash2, password, salt, opts); - let prfW; - const arr = new Uint8Array(4); - const view = createView$2(arr); - const u2 = new Uint8Array(PRF.outputLen); - for (let ti2 = 1, pos = 0; pos < dkLen; ti2++, pos += PRF.outputLen) { - const Ti2 = DK.subarray(pos, pos + PRF.outputLen); - view.setInt32(0, ti2, false); - (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u2); - Ti2.set(u2.subarray(0, Ti2.length)); - for (let ui2 = 1; ui2 < c2; ui2++) { - PRF._cloneInto(prfW).update(u2).digestInto(u2); - for (let i = 0; i < Ti2.length; i++) - Ti2[i] ^= u2[i]; - } +Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too high|gas limit reached/ +}); +class IntrinsicGasTooLowError extends BaseError$3 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, { + cause, + name: "IntrinsicGasTooLowError" + }); } - return pbkdf2Output(PRF, PRFSalt, DK, prfW, u2); } -function setBigUint64$2(view, byteOffset, value, isLE2) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE2); - const _32n2 = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh2 = Number(value >> _32n2 & _u32_max); - const wl = Number(value & _u32_max); - const h2 = isLE2 ? 4 : 0; - const l2 = isLE2 ? 0 : 4; - view.setUint32(byteOffset + h2, wh2, isLE2); - view.setUint32(byteOffset + l2, wl, isLE2); +Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too low/ +}); +class TransactionTypeNotSupportedError extends BaseError$3 { + constructor({ cause }) { + super("The transaction type is not supported for this chain.", { + cause, + name: "TransactionTypeNotSupportedError" + }); + } } -class SHA2 extends Hash$2 { - constructor(blockLen, outputLen, padOffset, isLE2) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE2; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView$2(this.buffer); +Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /transaction type not valid/ +}); +class TipAboveFeeCapError extends BaseError$3 { + constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) { + super([ + `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).` + ].join("\n"), { + cause, + name: "TipAboveFeeCapError" + }); } - update(data) { - exists$2(this); - const { view, buffer: buffer2, blockLen } = this; - data = toBytes$3(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView$2(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer2.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; +} +Object.defineProperty(TipAboveFeeCapError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/ +}); +class UnknownNodeError extends BaseError$3 { + constructor({ cause }) { + super(`An error occurred while executing: ${cause == null ? void 0 : cause.shortMessage}`, { + cause, + name: "UnknownNodeError" + }); } - digestInto(out) { - exists$2(this); - output$2(out, this); - this.finished = true; - const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; - let { pos } = this; - buffer2[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos; i < blockLen; i++) - buffer2[i] = 0; - setBigUint64$2(view, blockLen - 8, BigInt(this.length * 8), isLE2); - this.process(view, 0); - const oview = createView$2(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE2); +} +function formatEther$2(wei, unit = "wei") { + return formatUnits$2(wei, etherUnits[unit]); +} +function prettyPrint(args) { + const entries = Object.entries(args).map(([key, value]) => { + if (value === void 0 || value === false) + return null; + return [key, value]; + }).filter(Boolean); + const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0); + return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n"); +} +class FeeConflictError extends BaseError$3 { + constructor() { + super([ + "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.", + "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others." + ].join("\n"), { name: "FeeConflictError" }); } - digest() { - const { buffer: buffer2, outputLen } = this; - this.digestInto(buffer2); - const res = buffer2.slice(0, outputLen); - this.destroy(); - return res; +} +class InvalidSerializableTransactionError extends BaseError$3 { + constructor({ transaction: transaction2 }) { + super("Cannot infer a transaction type from provided transaction.", { + metaMessages: [ + "Provided Transaction:", + "{", + prettyPrint(transaction2), + "}", + "", + "To infer the type, either provide:", + "- a `type` to the Transaction, or", + "- an EIP-1559 Transaction with `maxFeePerGas`, or", + "- an EIP-2930 Transaction with `gasPrice` & `accessList`, or", + "- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or", + "- an EIP-7702 Transaction with `authorizationList`, or", + "- a Legacy Transaction with `gasPrice`" + ], + name: "InvalidSerializableTransactionError" + }); } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer2); - return to; +} +class TransactionExecutionError extends BaseError$3 { + constructor(cause, { account: account2, docsPath: docsPath2, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) { + var _a2; + const prettyArgs = prettyPrint({ + chain: chain && `${chain == null ? void 0 : chain.name} (id: ${chain == null ? void 0 : chain.id})`, + from: account2 == null ? void 0 : account2.address, + to, + value: typeof value !== "undefined" && `${formatEther$2(value)} ${((_a2 = chain == null ? void 0 : chain.nativeCurrency) == null ? void 0 : _a2.symbol) || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, + nonce + }); + super(cause.shortMessage, { + cause, + docsPath: docsPath2, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Request Arguments:", + prettyArgs + ].filter(Boolean), + name: "TransactionExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; } } -const Chi$2 = (a2, b2, c2) => a2 & b2 ^ ~a2 & c2; -const Maj$2 = (a2, b2, c2) => a2 & b2 ^ a2 & c2 ^ b2 & c2; -const SHA256_K$2 = /* @__PURE__ */ new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]); -const IV = /* @__PURE__ */ new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -const SHA256_W$2 = /* @__PURE__ */ new Uint32Array(64); -let SHA256$2 = class SHA256 extends SHA2 { - constructor() { - super(64, 32, 8, false); - this.A = IV[0] | 0; - this.B = IV[1] | 0; - this.C = IV[2] | 0; - this.D = IV[3] | 0; - this.E = IV[4] | 0; - this.F = IV[5] | 0; - this.G = IV[6] | 0; - this.H = IV[7] | 0; +class TransactionNotFoundError extends BaseError$3 { + constructor({ blockHash, blockNumber, blockTag, hash: hash2, index: index2 }) { + let identifier = "Transaction"; + if (blockTag && index2 !== void 0) + identifier = `Transaction at block time "${blockTag}" at index "${index2}"`; + if (blockHash && index2 !== void 0) + identifier = `Transaction at block hash "${blockHash}" at index "${index2}"`; + if (blockNumber && index2 !== void 0) + identifier = `Transaction at block number "${blockNumber}" at index "${index2}"`; + if (hash2) + identifier = `Transaction with hash "${hash2}"`; + super(`${identifier} could not be found.`, { + name: "TransactionNotFoundError" + }); } - get() { - const { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; - return [A2, B2, C2, D2, E2, F2, G2, H2]; +} +class TransactionReceiptNotFoundError extends BaseError$3 { + constructor({ hash: hash2 }) { + super(`Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`, { + name: "TransactionReceiptNotFoundError" + }); } - // prettier-ignore - set(A2, B2, C2, D2, E2, F2, G2, H2) { - this.A = A2 | 0; - this.B = B2 | 0; - this.C = C2 | 0; - this.D = D2 | 0; - this.E = E2 | 0; - this.F = F2 | 0; - this.G = G2 | 0; - this.H = H2 | 0; +} +class WaitForTransactionReceiptTimeoutError extends BaseError$3 { + constructor({ hash: hash2 }) { + super(`Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`, { name: "WaitForTransactionReceiptTimeoutError" }); } - process(view, offset2) { - for (let i = 0; i < 16; i++, offset2 += 4) - SHA256_W$2[i] = view.getUint32(offset2, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W$2[i - 15]; - const W2 = SHA256_W$2[i - 2]; - const s0 = rotr$2(W15, 7) ^ rotr$2(W15, 18) ^ W15 >>> 3; - const s1 = rotr$2(W2, 17) ^ rotr$2(W2, 19) ^ W2 >>> 10; - SHA256_W$2[i] = s1 + SHA256_W$2[i - 7] + s0 + SHA256_W$2[i - 16] | 0; - } - let { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr$2(E2, 6) ^ rotr$2(E2, 11) ^ rotr$2(E2, 25); - const T12 = H2 + sigma1 + Chi$2(E2, F2, G2) + SHA256_K$2[i] + SHA256_W$2[i] | 0; - const sigma0 = rotr$2(A2, 2) ^ rotr$2(A2, 13) ^ rotr$2(A2, 22); - const T22 = sigma0 + Maj$2(A2, B2, C2) | 0; - H2 = G2; - G2 = F2; - F2 = E2; - E2 = D2 + T12 | 0; - D2 = C2; - C2 = B2; - B2 = A2; - A2 = T12 + T22 | 0; - } - A2 = A2 + this.A | 0; - B2 = B2 + this.B | 0; - C2 = C2 + this.C | 0; - D2 = D2 + this.D | 0; - E2 = E2 + this.E | 0; - F2 = F2 + this.F | 0; - G2 = G2 + this.G | 0; - H2 = H2 + this.H | 0; - this.set(A2, B2, C2, D2, E2, F2, G2, H2); - } - roundClean() { - SHA256_W$2.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } -}; -const sha256$4 = /* @__PURE__ */ wrapConstructor$2(() => new SHA256$2()); -const U32_MASK64$1 = /* @__PURE__ */ BigInt(2 ** 32 - 1); -const _32n$1 = /* @__PURE__ */ BigInt(32); -function fromBig$1(n2, le2 = false) { - if (le2) - return { h: Number(n2 & U32_MASK64$1), l: Number(n2 >> _32n$1 & U32_MASK64$1) }; - return { h: Number(n2 >> _32n$1 & U32_MASK64$1) | 0, l: Number(n2 & U32_MASK64$1) | 0 }; } -function split$2(lst, le2 = false) { - let Ah2 = new Uint32Array(lst.length); - let Al = new Uint32Array(lst.length); - for (let i = 0; i < lst.length; i++) { - const { h: h2, l: l2 } = fromBig$1(lst[i], le2); - [Ah2[i], Al[i]] = [h2, l2]; +const stringify$3 = (value, replacer, space) => JSON.stringify(value, (key, value_) => { + const value2 = typeof value_ === "bigint" ? value_.toString() : value_; + return value2; +}, space); +const getContractAddress = (address) => address; +const getUrl = (url) => url; +class HttpRequestError extends BaseError$3 { + constructor({ body, cause, details, headers, status, url }) { + super("HTTP request failed.", { + cause, + details, + metaMessages: [ + status && `Status: ${status}`, + `URL: ${getUrl(url)}`, + body && `Request body: ${stringify$3(body)}` + ].filter(Boolean), + name: "HttpRequestError" + }); + Object.defineProperty(this, "body", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "url", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.body = body; + this.headers = headers; + this.status = status; + this.url = url; } - return [Ah2, Al]; } -const toBig = (h2, l2) => BigInt(h2 >>> 0) << _32n$1 | BigInt(l2 >>> 0); -const shrSH = (h2, _l2, s2) => h2 >>> s2; -const shrSL = (h2, l2, s2) => h2 << 32 - s2 | l2 >>> s2; -const rotrSH = (h2, l2, s2) => h2 >>> s2 | l2 << 32 - s2; -const rotrSL = (h2, l2, s2) => h2 << 32 - s2 | l2 >>> s2; -const rotrBH = (h2, l2, s2) => h2 << 64 - s2 | l2 >>> s2 - 32; -const rotrBL = (h2, l2, s2) => h2 >>> s2 - 32 | l2 << 64 - s2; -const rotr32H = (_h2, l2) => l2; -const rotr32L = (h2, _l2) => h2; -const rotlSH$1 = (h2, l2, s2) => h2 << s2 | l2 >>> 32 - s2; -const rotlSL$1 = (h2, l2, s2) => l2 << s2 | h2 >>> 32 - s2; -const rotlBH$1 = (h2, l2, s2) => l2 << s2 - 32 | h2 >>> 64 - s2; -const rotlBL$1 = (h2, l2, s2) => h2 << s2 - 32 | l2 >>> 64 - s2; -function add(Ah2, Al, Bh2, Bl) { - const l2 = (Al >>> 0) + (Bl >>> 0); - return { h: Ah2 + Bh2 + (l2 / 2 ** 32 | 0) | 0, l: l2 | 0 }; +class RpcRequestError extends BaseError$3 { + constructor({ body, error, url }) { + super("RPC Request failed.", { + cause: error, + details: error.message, + metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify$3(body)}`], + name: "RpcRequestError" + }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.code = error.code; + } } -const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); -const add3H = (low, Ah2, Bh2, Ch2) => Ah2 + Bh2 + Ch2 + (low / 2 ** 32 | 0) | 0; -const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); -const add4H = (low, Ah2, Bh2, Ch2, Dh2) => Ah2 + Bh2 + Ch2 + Dh2 + (low / 2 ** 32 | 0) | 0; -const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); -const add5H = (low, Ah2, Bh2, Ch2, Dh2, Eh2) => Ah2 + Bh2 + Ch2 + Dh2 + Eh2 + (low / 2 ** 32 | 0) | 0; -const u64 = { - fromBig: fromBig$1, - split: split$2, - toBig, - shrSH, - shrSL, - rotrSH, - rotrSL, - rotrBH, - rotrBL, - rotr32H, - rotr32L, - rotlSH: rotlSH$1, - rotlSL: rotlSL$1, - rotlBH: rotlBH$1, - rotlBL: rotlBL$1, - add, - add3L, - add3H, - add4L, - add4H, - add5H, - add5L +let TimeoutError$2 = class TimeoutError extends BaseError$3 { + constructor({ body, url }) { + super("The request took too long to respond.", { + details: "The request timed out.", + metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify$3(body)}`], + name: "TimeoutError" + }); + } }; -const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ - "0x428a2f98d728ae22", - "0x7137449123ef65cd", - "0xb5c0fbcfec4d3b2f", - "0xe9b5dba58189dbbc", - "0x3956c25bf348b538", - "0x59f111f1b605d019", - "0x923f82a4af194f9b", - "0xab1c5ed5da6d8118", - "0xd807aa98a3030242", - "0x12835b0145706fbe", - "0x243185be4ee4b28c", - "0x550c7dc3d5ffb4e2", - "0x72be5d74f27b896f", - "0x80deb1fe3b1696b1", - "0x9bdc06a725c71235", - "0xc19bf174cf692694", - "0xe49b69c19ef14ad2", - "0xefbe4786384f25e3", - "0x0fc19dc68b8cd5b5", - "0x240ca1cc77ac9c65", - "0x2de92c6f592b0275", - "0x4a7484aa6ea6e483", - "0x5cb0a9dcbd41fbd4", - "0x76f988da831153b5", - "0x983e5152ee66dfab", - "0xa831c66d2db43210", - "0xb00327c898fb213f", - "0xbf597fc7beef0ee4", - "0xc6e00bf33da88fc2", - "0xd5a79147930aa725", - "0x06ca6351e003826f", - "0x142929670a0e6e70", - "0x27b70a8546d22ffc", - "0x2e1b21385c26c926", - "0x4d2c6dfc5ac42aed", - "0x53380d139d95b3df", - "0x650a73548baf63de", - "0x766a0abb3c77b2a8", - "0x81c2c92e47edaee6", - "0x92722c851482353b", - "0xa2bfe8a14cf10364", - "0xa81a664bbc423001", - "0xc24b8b70d0f89791", - "0xc76c51a30654be30", - "0xd192e819d6ef5218", - "0xd69906245565a910", - "0xf40e35855771202a", - "0x106aa07032bbd1b8", - "0x19a4c116b8d2d0c8", - "0x1e376c085141ab53", - "0x2748774cdf8eeb99", - "0x34b0bcb5e19b48a8", - "0x391c0cb3c5c95a63", - "0x4ed8aa4ae3418acb", - "0x5b9cca4f7763e373", - "0x682e6ff3d6b2b8a3", - "0x748f82ee5defb2fc", - "0x78a5636f43172f60", - "0x84c87814a1f0ab72", - "0x8cc702081a6439ec", - "0x90befffa23631e28", - "0xa4506cebde82bde9", - "0xbef9a3f7b2c67915", - "0xc67178f2e372532b", - "0xca273eceea26619c", - "0xd186b8c721c0c207", - "0xeada7dd6cde0eb1e", - "0xf57d4f7fee6ed178", - "0x06f067aa72176fba", - "0x0a637dc5a2c898a6", - "0x113f9804bef90dae", - "0x1b710b35131c471b", - "0x28db77f523047d84", - "0x32caab7b40c72493", - "0x3c9ebe0a15c9bebc", - "0x431d67c49c100d4c", - "0x4cc5d4becb3e42b6", - "0x597f299cfc657e2a", - "0x5fcb6fab3ad6faec", - "0x6c44198c4a475817" -].map((n2) => BigInt(n2))))(); -const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); -const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); -class SHA512 extends SHA2 { - constructor() { - super(128, 64, 16, false); - this.Ah = 1779033703 | 0; - this.Al = 4089235720 | 0; - this.Bh = 3144134277 | 0; - this.Bl = 2227873595 | 0; - this.Ch = 1013904242 | 0; - this.Cl = 4271175723 | 0; - this.Dh = 2773480762 | 0; - this.Dl = 1595750129 | 0; - this.Eh = 1359893119 | 0; - this.El = 2917565137 | 0; - this.Fh = 2600822924 | 0; - this.Fl = 725511199 | 0; - this.Gh = 528734635 | 0; - this.Gl = 4215389547 | 0; - this.Hh = 1541459225 | 0; - this.Hl = 327033209 | 0; +const unknownErrorCode = -1; +class RpcError extends BaseError$3 { + constructor(cause, { code: code2, docsPath: docsPath2, metaMessages, name: name2, shortMessage }) { + super(shortMessage, { + cause, + docsPath: docsPath2, + metaMessages: metaMessages || (cause == null ? void 0 : cause.metaMessages), + name: name2 || "RpcError" + }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = name2 || cause.name; + this.code = cause instanceof RpcRequestError ? cause.code : code2 ?? unknownErrorCode; } - // prettier-ignore - get() { - const { Ah: Ah2, Al, Bh: Bh2, Bl, Ch: Ch2, Cl, Dh: Dh2, Dl, Eh: Eh2, El, Fh: Fh2, Fl, Gh: Gh2, Gl, Hh: Hh2, Hl } = this; - return [Ah2, Al, Bh2, Bl, Ch2, Cl, Dh2, Dl, Eh2, El, Fh2, Fl, Gh2, Gl, Hh2, Hl]; +} +class ProviderRpcError extends RpcError { + constructor(cause, options) { + super(cause, options); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = options.data; } - // prettier-ignore - set(Ah2, Al, Bh2, Bl, Ch2, Cl, Dh2, Dl, Eh2, El, Fh2, Fl, Gh2, Gl, Hh2, Hl) { - this.Ah = Ah2 | 0; - this.Al = Al | 0; - this.Bh = Bh2 | 0; - this.Bl = Bl | 0; - this.Ch = Ch2 | 0; - this.Cl = Cl | 0; - this.Dh = Dh2 | 0; - this.Dl = Dl | 0; - this.Eh = Eh2 | 0; - this.El = El | 0; - this.Fh = Fh2 | 0; - this.Fl = Fl | 0; - this.Gh = Gh2 | 0; - this.Gl = Gl | 0; - this.Hh = Hh2 | 0; - this.Hl = Hl | 0; +} +class ParseRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: ParseRpcError.code, + name: "ParseRpcError", + shortMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text." + }); } - process(view, offset2) { - for (let i = 0; i < 16; i++, offset2 += 4) { - SHA512_W_H[i] = view.getUint32(offset2); - SHA512_W_L[i] = view.getUint32(offset2 += 4); - } - for (let i = 16; i < 80; i++) { - const W15h = SHA512_W_H[i - 15] | 0; - const W15l = SHA512_W_L[i - 15] | 0; - const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); - const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); - const W2h = SHA512_W_H[i - 2] | 0; - const W2l = SHA512_W_L[i - 2] | 0; - const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); - const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); - const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); - const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); - SHA512_W_H[i] = SUMh | 0; - SHA512_W_L[i] = SUMl | 0; - } - let { Ah: Ah2, Al, Bh: Bh2, Bl, Ch: Ch2, Cl, Dh: Dh2, Dl, Eh: Eh2, El, Fh: Fh2, Fl, Gh: Gh2, Gl, Hh: Hh2, Hl } = this; - for (let i = 0; i < 80; i++) { - const sigma1h = u64.rotrSH(Eh2, El, 14) ^ u64.rotrSH(Eh2, El, 18) ^ u64.rotrBH(Eh2, El, 41); - const sigma1l = u64.rotrSL(Eh2, El, 14) ^ u64.rotrSL(Eh2, El, 18) ^ u64.rotrBL(Eh2, El, 41); - const CHIh = Eh2 & Fh2 ^ ~Eh2 & Gh2; - const CHIl = El & Fl ^ ~El & Gl; - const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); - const T1h = u64.add5H(T1ll, Hh2, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); - const T1l = T1ll | 0; - const sigma0h = u64.rotrSH(Ah2, Al, 28) ^ u64.rotrBH(Ah2, Al, 34) ^ u64.rotrBH(Ah2, Al, 39); - const sigma0l = u64.rotrSL(Ah2, Al, 28) ^ u64.rotrBL(Ah2, Al, 34) ^ u64.rotrBL(Ah2, Al, 39); - const MAJh = Ah2 & Bh2 ^ Ah2 & Ch2 ^ Bh2 & Ch2; - const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; - Hh2 = Gh2 | 0; - Hl = Gl | 0; - Gh2 = Fh2 | 0; - Gl = Fl | 0; - Fh2 = Eh2 | 0; - Fl = El | 0; - ({ h: Eh2, l: El } = u64.add(Dh2 | 0, Dl | 0, T1h | 0, T1l | 0)); - Dh2 = Ch2 | 0; - Dl = Cl | 0; - Ch2 = Bh2 | 0; - Cl = Bl | 0; - Bh2 = Ah2 | 0; - Bl = Al | 0; - const All = u64.add3L(T1l, sigma0l, MAJl); - Ah2 = u64.add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } - ({ h: Ah2, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah2 | 0, Al | 0)); - ({ h: Bh2, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh2 | 0, Bl | 0)); - ({ h: Ch2, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch2 | 0, Cl | 0)); - ({ h: Dh2, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh2 | 0, Dl | 0)); - ({ h: Eh2, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh2 | 0, El | 0)); - ({ h: Fh2, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh2 | 0, Fl | 0)); - ({ h: Gh2, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh2 | 0, Gl | 0)); - ({ h: Hh2, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh2 | 0, Hl | 0)); - this.set(Ah2, Al, Bh2, Bl, Ch2, Cl, Dh2, Dl, Eh2, El, Fh2, Fl, Gh2, Gl, Hh2, Hl); +} +Object.defineProperty(ParseRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32700 +}); +class InvalidRequestRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: InvalidRequestRpcError.code, + name: "InvalidRequestRpcError", + shortMessage: "JSON is not a valid request object." + }); } - roundClean() { - SHA512_W_H.fill(0); - SHA512_W_L.fill(0); +} +Object.defineProperty(InvalidRequestRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32600 +}); +class MethodNotFoundRpcError extends RpcError { + constructor(cause, { method } = {}) { + super(cause, { + code: MethodNotFoundRpcError.code, + name: "MethodNotFoundRpcError", + shortMessage: `The method${method ? ` "${method}"` : ""} does not exist / is not available.` + }); } - destroy() { - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); +} +Object.defineProperty(MethodNotFoundRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32601 +}); +class InvalidParamsRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: InvalidParamsRpcError.code, + name: "InvalidParamsRpcError", + shortMessage: [ + "Invalid parameters were provided to the RPC method.", + "Double check you have provided the correct parameters." + ].join("\n") + }); } } -const sha512$1 = /* @__PURE__ */ wrapConstructor$2(() => new SHA512()); -function getGlobal$1() { - if (typeof self !== "undefined") { - return self; +Object.defineProperty(InvalidParamsRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32602 +}); +class InternalRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: InternalRpcError.code, + name: "InternalRpcError", + shortMessage: "An internal error was received." + }); } - if (typeof window !== "undefined") { - return window; +} +Object.defineProperty(InternalRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32603 +}); +class InvalidInputRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: InvalidInputRpcError.code, + name: "InvalidInputRpcError", + shortMessage: [ + "Missing or invalid parameters.", + "Double check you have provided the correct parameters." + ].join("\n") + }); } - if (typeof global$1 !== "undefined") { - return global$1; +} +Object.defineProperty(InvalidInputRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32e3 +}); +class ResourceNotFoundRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: ResourceNotFoundRpcError.code, + name: "ResourceNotFoundRpcError", + shortMessage: "Requested resource not found." + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ResourceNotFoundRpcError" + }); } - throw new Error("unable to locate global object"); } -const anyGlobal = getGlobal$1(); -const crypto$2 = anyGlobal.crypto || anyGlobal.msCrypto; -function createHash(algo) { - switch (algo) { - case "sha256": - return sha256$4.create(); - case "sha512": - return sha512$1.create(); +Object.defineProperty(ResourceNotFoundRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32001 +}); +class ResourceUnavailableRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: ResourceUnavailableRpcError.code, + name: "ResourceUnavailableRpcError", + shortMessage: "Requested resource not available." + }); } - assertArgument(false, "invalid hashing algorithm name", "algorithm", algo); } -function createHmac(_algo, key) { - const algo = { sha256: sha256$4, sha512: sha512$1 }[_algo]; - assertArgument(algo != null, "invalid hmac algorithm", "algorithm", _algo); - return hmac$2.create(algo, key); +Object.defineProperty(ResourceUnavailableRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32002 +}); +class TransactionRejectedRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: TransactionRejectedRpcError.code, + name: "TransactionRejectedRpcError", + shortMessage: "Transaction creation failed." + }); + } } -function pbkdf2Sync(password, salt, iterations, keylen, _algo) { - const algo = { sha256: sha256$4, sha512: sha512$1 }[_algo]; - assertArgument(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo); - return pbkdf2$1(algo, password, salt, { c: iterations, dkLen: keylen }); +Object.defineProperty(TransactionRejectedRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32003 +}); +class MethodNotSupportedRpcError extends RpcError { + constructor(cause, { method } = {}) { + super(cause, { + code: MethodNotSupportedRpcError.code, + name: "MethodNotSupportedRpcError", + shortMessage: `Method${method ? ` "${method}"` : ""} is not implemented.` + }); + } } -function randomBytes$2(length) { - assert(crypto$2 != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", { - operation: "randomBytes" - }); - assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length); - const result = new Uint8Array(length); - crypto$2.getRandomValues(result); - return result; +Object.defineProperty(MethodNotSupportedRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32004 +}); +class LimitExceededRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: LimitExceededRpcError.code, + name: "LimitExceededRpcError", + shortMessage: "Request exceeds defined limit." + }); + } } -let locked$4 = false; -const _computeHmac = function(algorithm, key, data) { - return createHmac(algorithm, key).update(data).digest(); -}; -let __computeHmac = _computeHmac; -function computeHmac(algorithm, _key, _data6) { - const key = getBytes(_key, "key"); - const data = getBytes(_data6, "data"); - return hexlify(__computeHmac(algorithm, key, data)); +Object.defineProperty(LimitExceededRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32005 +}); +class JsonRpcVersionUnsupportedError extends RpcError { + constructor(cause) { + super(cause, { + code: JsonRpcVersionUnsupportedError.code, + name: "JsonRpcVersionUnsupportedError", + shortMessage: "Version of JSON-RPC protocol is not supported." + }); + } } -computeHmac._ = _computeHmac; -computeHmac.lock = function() { - locked$4 = true; -}; -computeHmac.register = function(func) { - if (locked$4) { - throw new Error("computeHmac is locked"); +Object.defineProperty(JsonRpcVersionUnsupportedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32006 +}); +class UserRejectedRequestError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: UserRejectedRequestError.code, + name: "UserRejectedRequestError", + shortMessage: "User rejected the request." + }); } - __computeHmac = func; -}; -Object.freeze(computeHmac); -const [SHA3_PI$1, SHA3_ROTL$1, _SHA3_IOTA$1] = [[], [], []]; -const _0n$9 = /* @__PURE__ */ BigInt(0); -const _1n$b = /* @__PURE__ */ BigInt(1); -const _2n$7 = /* @__PURE__ */ BigInt(2); -const _7n$1 = /* @__PURE__ */ BigInt(7); -const _256n$1 = /* @__PURE__ */ BigInt(256); -const _0x71n$1 = /* @__PURE__ */ BigInt(113); -for (let round2 = 0, R2 = _1n$b, x2 = 1, y2 = 0; round2 < 24; round2++) { - [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; - SHA3_PI$1.push(2 * (5 * y2 + x2)); - SHA3_ROTL$1.push((round2 + 1) * (round2 + 2) / 2 % 64); - let t2 = _0n$9; - for (let j2 = 0; j2 < 7; j2++) { - R2 = (R2 << _1n$b ^ (R2 >> _7n$1) * _0x71n$1) % _256n$1; - if (R2 & _2n$7) - t2 ^= _1n$b << (_1n$b << /* @__PURE__ */ BigInt(j2)) - _1n$b; +} +Object.defineProperty(UserRejectedRequestError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4001 +}); +class UnauthorizedProviderError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: UnauthorizedProviderError.code, + name: "UnauthorizedProviderError", + shortMessage: "The requested method and/or account has not been authorized by the user." + }); } - _SHA3_IOTA$1.push(t2); } -const [SHA3_IOTA_H$1, SHA3_IOTA_L$1] = /* @__PURE__ */ split$2(_SHA3_IOTA$1, true); -const rotlH$1 = (h2, l2, s2) => s2 > 32 ? rotlBH$1(h2, l2, s2) : rotlSH$1(h2, l2, s2); -const rotlL$1 = (h2, l2, s2) => s2 > 32 ? rotlBL$1(h2, l2, s2) : rotlSL$1(h2, l2, s2); -function keccakP$1(s2, rounds = 24) { - const B2 = new Uint32Array(5 * 2); - for (let round2 = 24 - rounds; round2 < 24; round2++) { - for (let x2 = 0; x2 < 10; x2++) - B2[x2] = s2[x2] ^ s2[x2 + 10] ^ s2[x2 + 20] ^ s2[x2 + 30] ^ s2[x2 + 40]; - for (let x2 = 0; x2 < 10; x2 += 2) { - const idx1 = (x2 + 8) % 10; - const idx0 = (x2 + 2) % 10; - const B0 = B2[idx0]; - const B1 = B2[idx0 + 1]; - const Th2 = rotlH$1(B0, B1, 1) ^ B2[idx1]; - const Tl = rotlL$1(B0, B1, 1) ^ B2[idx1 + 1]; - for (let y2 = 0; y2 < 50; y2 += 10) { - s2[x2 + y2] ^= Th2; - s2[x2 + y2 + 1] ^= Tl; - } - } - let curH = s2[2]; - let curL = s2[3]; - for (let t2 = 0; t2 < 24; t2++) { - const shift2 = SHA3_ROTL$1[t2]; - const Th2 = rotlH$1(curH, curL, shift2); - const Tl = rotlL$1(curH, curL, shift2); - const PI = SHA3_PI$1[t2]; - curH = s2[PI]; - curL = s2[PI + 1]; - s2[PI] = Th2; - s2[PI + 1] = Tl; - } - for (let y2 = 0; y2 < 50; y2 += 10) { - for (let x2 = 0; x2 < 10; x2++) - B2[x2] = s2[y2 + x2]; - for (let x2 = 0; x2 < 10; x2++) - s2[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; - } - s2[0] ^= SHA3_IOTA_H$1[round2]; - s2[1] ^= SHA3_IOTA_L$1[round2]; +Object.defineProperty(UnauthorizedProviderError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4100 +}); +class UnsupportedProviderMethodError extends ProviderRpcError { + constructor(cause, { method } = {}) { + super(cause, { + code: UnsupportedProviderMethodError.code, + name: "UnsupportedProviderMethodError", + shortMessage: `The Provider does not support the requested method${method ? ` " ${method}"` : ""}.` + }); } - B2.fill(0); } -let Keccak$1 = class Keccak extends Hash$2 { - // NOTE: we accept arguments in bytes instead of bits here. - constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { - super(); - this.blockLen = blockLen; - this.suffix = suffix; - this.outputLen = outputLen; - this.enableXOF = enableXOF; - this.rounds = rounds; - this.pos = 0; - this.posOut = 0; - this.finished = false; - this.destroyed = false; - number$1(outputLen); - if (0 >= this.blockLen || this.blockLen >= 200) - throw new Error("Sha3 supports only keccak-f1600 function"); - this.state = new Uint8Array(200); - this.state32 = u32$1(this.state); +Object.defineProperty(UnsupportedProviderMethodError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4200 +}); +class ProviderDisconnectedError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: ProviderDisconnectedError.code, + name: "ProviderDisconnectedError", + shortMessage: "The Provider is disconnected from all chains." + }); } - keccak() { - keccakP$1(this.state32, this.rounds); - this.posOut = 0; - this.pos = 0; +} +Object.defineProperty(ProviderDisconnectedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4900 +}); +class ChainDisconnectedError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: ChainDisconnectedError.code, + name: "ChainDisconnectedError", + shortMessage: "The Provider is not connected to the requested chain." + }); } - update(data) { - exists$2(this); - const { blockLen, state } = this; - data = toBytes$3(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0; i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); - } - return this; +} +Object.defineProperty(ChainDisconnectedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4901 +}); +class SwitchChainError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: SwitchChainError.code, + name: "SwitchChainError", + shortMessage: "An error occurred when attempting to switch chain." + }); } - finish() { - if (this.finished) - return; - this.finished = true; - const { state, suffix, pos, blockLen } = this; - state[pos] ^= suffix; - if ((suffix & 128) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 128; - this.keccak(); +} +Object.defineProperty(SwitchChainError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4902 +}); +class UnknownRpcError extends RpcError { + constructor(cause) { + super(cause, { + name: "UnknownRpcError", + shortMessage: "An unknown RPC error occurred." + }); } - writeInto(out) { - exists$2(this, false); - bytes$2(out); - this.finish(); - const bufferOut = this.state; - const { blockLen } = this; - for (let pos = 0, len = out.length; pos < len; ) { - if (this.posOut >= blockLen) - this.keccak(); - const take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; +} +function getNodeError(err, args) { + const message = (err.details || "").toLowerCase(); + const executionRevertedError = err instanceof BaseError$3 ? err.walk((e2) => e2.code === ExecutionRevertedError.code) : err; + if (executionRevertedError instanceof BaseError$3) + return new ExecutionRevertedError({ + cause: err, + message: executionRevertedError.details + }); + if (ExecutionRevertedError.nodeMessage.test(message)) + return new ExecutionRevertedError({ + cause: err, + message: err.details + }); + if (FeeCapTooHighError.nodeMessage.test(message)) + return new FeeCapTooHighError({ + cause: err, + maxFeePerGas: args == null ? void 0 : args.maxFeePerGas + }); + if (FeeCapTooLowError.nodeMessage.test(message)) + return new FeeCapTooLowError({ + cause: err, + maxFeePerGas: args == null ? void 0 : args.maxFeePerGas + }); + if (NonceTooHighError.nodeMessage.test(message)) + return new NonceTooHighError({ cause: err, nonce: args == null ? void 0 : args.nonce }); + if (NonceTooLowError.nodeMessage.test(message)) + return new NonceTooLowError({ cause: err, nonce: args == null ? void 0 : args.nonce }); + if (NonceMaxValueError.nodeMessage.test(message)) + return new NonceMaxValueError({ cause: err, nonce: args == null ? void 0 : args.nonce }); + if (InsufficientFundsError.nodeMessage.test(message)) + return new InsufficientFundsError({ cause: err }); + if (IntrinsicGasTooHighError.nodeMessage.test(message)) + return new IntrinsicGasTooHighError({ cause: err, gas: args == null ? void 0 : args.gas }); + if (IntrinsicGasTooLowError.nodeMessage.test(message)) + return new IntrinsicGasTooLowError({ cause: err, gas: args == null ? void 0 : args.gas }); + if (TransactionTypeNotSupportedError.nodeMessage.test(message)) + return new TransactionTypeNotSupportedError({ cause: err }); + if (TipAboveFeeCapError.nodeMessage.test(message)) + return new TipAboveFeeCapError({ + cause: err, + maxFeePerGas: args == null ? void 0 : args.maxFeePerGas, + maxPriorityFeePerGas: args == null ? void 0 : args.maxPriorityFeePerGas + }); + return new UnknownNodeError({ + cause: err + }); +} +function getTransactionError(err, { docsPath: docsPath2, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new TransactionExecutionError(cause, { + docsPath: docsPath2, + ...args + }); +} +function extract(value_, { format: format2 }) { + if (!format2) + return {}; + const value = {}; + function extract_(formatted2) { + const keys = Object.keys(formatted2); + for (const key of keys) { + if (key in value_) + value[key] = value_[key]; + if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key])) + extract_(formatted2[key]); } - return out; - } - xofInto(out) { - if (!this.enableXOF) - throw new Error("XOF is not possible for this instance"); - return this.writeInto(out); } - xof(bytes2) { - number$1(bytes2); - return this.xofInto(new Uint8Array(bytes2)); - } - digestInto(out) { - output$2(out, this); - if (this.finished) - throw new Error("digest() was already called"); - this.writeInto(out); - this.destroy(); - return out; + const formatted = format2(value_ || {}); + extract_(formatted); + return value; +} +const rpcTransactionType = { + legacy: "0x0", + eip2930: "0x1", + eip1559: "0x2", + eip4844: "0x3", + eip7702: "0x4" +}; +function formatTransactionRequest(request) { + const rpcRequest = {}; + if (typeof request.authorizationList !== "undefined") + rpcRequest.authorizationList = formatAuthorizationList$1(request.authorizationList); + if (typeof request.accessList !== "undefined") + rpcRequest.accessList = request.accessList; + if (typeof request.blobVersionedHashes !== "undefined") + rpcRequest.blobVersionedHashes = request.blobVersionedHashes; + if (typeof request.blobs !== "undefined") { + if (typeof request.blobs[0] !== "string") + rpcRequest.blobs = request.blobs.map((x2) => bytesToHex$3(x2)); + else + rpcRequest.blobs = request.blobs; } - digest() { - return this.digestInto(new Uint8Array(this.outputLen)); + if (typeof request.data !== "undefined") + rpcRequest.data = request.data; + if (typeof request.from !== "undefined") + rpcRequest.from = request.from; + if (typeof request.gas !== "undefined") + rpcRequest.gas = numberToHex(request.gas); + if (typeof request.gasPrice !== "undefined") + rpcRequest.gasPrice = numberToHex(request.gasPrice); + if (typeof request.maxFeePerBlobGas !== "undefined") + rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas); + if (typeof request.maxFeePerGas !== "undefined") + rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas); + if (typeof request.maxPriorityFeePerGas !== "undefined") + rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas); + if (typeof request.nonce !== "undefined") + rpcRequest.nonce = numberToHex(request.nonce); + if (typeof request.to !== "undefined") + rpcRequest.to = request.to; + if (typeof request.type !== "undefined") + rpcRequest.type = rpcTransactionType[request.type]; + if (typeof request.value !== "undefined") + rpcRequest.value = numberToHex(request.value); + return rpcRequest; +} +function formatAuthorizationList$1(authorizationList) { + return authorizationList.map((authorization) => ({ + address: authorization.contractAddress, + r: authorization.r, + s: authorization.s, + chainId: numberToHex(authorization.chainId), + nonce: numberToHex(authorization.nonce), + ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {}, + ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {} + })); +} +function getAction$1(client2, actionFn, name2) { + const action_implicit = client2[actionFn.name]; + if (typeof action_implicit === "function") + return action_implicit; + const action_explicit = client2[name2]; + if (typeof action_explicit === "function") + return action_explicit; + return (params) => actionFn(client2, params); +} +const maxUint256 = 2n ** 256n - 1n; +function assertRequest(args) { + const { account: account_, gasPrice, maxFeePerGas, maxPriorityFeePerGas, to } = args; + const account2 = account_ ? parseAccount(account_) : void 0; + if (account2 && !isAddress$1(account2.address)) + throw new InvalidAddressError({ address: account2.address }); + if (to && !isAddress$1(to)) + throw new InvalidAddressError({ address: to }); + if (typeof gasPrice !== "undefined" && (typeof maxFeePerGas !== "undefined" || typeof maxPriorityFeePerGas !== "undefined")) + throw new FeeConflictError(); + if (maxFeePerGas && maxFeePerGas > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas }); + if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) + throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +} +async function getChainId$2(client2) { + const chainIdHex = await client2.request({ + method: "eth_chainId" + }, { dedupe: true }); + return hexToNumber$2(chainIdHex); +} +class BaseFeeScalarError extends BaseError$3 { + constructor() { + super("`baseFeeMultiplier` must be greater than 1.", { + name: "BaseFeeScalarError" + }); } - destroy() { - this.destroyed = true; - this.state.fill(0); +} +class Eip1559FeesNotSupportedError extends BaseError$3 { + constructor() { + super("Chain does not support EIP-1559 fees.", { + name: "Eip1559FeesNotSupportedError" + }); } - _cloneInto(to) { - const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); - to.state32.set(this.state32); - to.pos = this.pos; - to.posOut = this.posOut; - to.finished = this.finished; - to.rounds = rounds; - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.destroyed = this.destroyed; - return to; +} +class MaxFeePerGasTooLowError extends BaseError$3 { + constructor({ maxPriorityFeePerGas }) { + super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" }); } -}; -const gen$1 = (suffix, blockLen, outputLen) => wrapConstructor$2(() => new Keccak$1(blockLen, suffix, outputLen)); -const keccak_256$1 = /* @__PURE__ */ gen$1(1, 136, 256 / 8); -let locked$3 = false; -const _keccak256 = function(data) { - return keccak_256$1(data); -}; -let __keccak256 = _keccak256; -function keccak256$1(_data6) { - const data = getBytes(_data6, "data"); - return hexlify(__keccak256(data)); } -keccak256$1._ = _keccak256; -keccak256$1.lock = function() { - locked$3 = true; -}; -keccak256$1.register = function(func) { - if (locked$3) { - throw new TypeError("keccak256 is locked"); +class BlockNotFoundError extends BaseError$3 { + constructor({ blockHash, blockNumber }) { + let identifier = "Block"; + if (blockHash) + identifier = `Block at hash "${blockHash}"`; + if (blockNumber) + identifier = `Block at number "${blockNumber}"`; + super(`${identifier} could not be found.`, { name: "BlockNotFoundError" }); } - __keccak256 = func; +} +const transactionType = { + "0x0": "legacy", + "0x1": "eip2930", + "0x2": "eip1559", + "0x3": "eip4844", + "0x4": "eip7702" }; -Object.freeze(keccak256$1); -const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); -const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); -const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); -let idxL = [Id]; -let idxR = [Pi]; -for (let i = 0; i < 4; i++) - for (let j2 of [idxL, idxR]) - j2.push(j2[i].map((k2) => Rho[k2])); -const shifts = /* @__PURE__ */ [ - [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], - [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], - [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], - [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], - [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5] -].map((i) => new Uint8Array(i)); -const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j2) => shifts[i][j2])); -const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j2) => shifts[i][j2])); -const Kl = /* @__PURE__ */ new Uint32Array([ - 0, - 1518500249, - 1859775393, - 2400959708, - 2840853838 -]); -const Kr = /* @__PURE__ */ new Uint32Array([ - 1352829926, - 1548603684, - 1836072691, - 2053994217, - 0 -]); -const rotl$1 = (word, shift2) => word << shift2 | word >>> 32 - shift2; -function f$1(group, x2, y2, z2) { - if (group === 0) - return x2 ^ y2 ^ z2; - else if (group === 1) - return x2 & y2 | ~x2 & z2; - else if (group === 2) - return (x2 | ~y2) ^ z2; - else if (group === 3) - return x2 & z2 | y2 & ~z2; - else - return x2 ^ (y2 | ~z2); -} -const BUF = /* @__PURE__ */ new Uint32Array(16); -class RIPEMD160 extends SHA2 { - constructor() { - super(64, 20, 8, true); - this.h0 = 1732584193 | 0; - this.h1 = 4023233417 | 0; - this.h2 = 2562383102 | 0; - this.h3 = 271733878 | 0; - this.h4 = 3285377520 | 0; - } - get() { - const { h0, h1, h2, h3, h4 } = this; - return [h0, h1, h2, h3, h4]; - } - set(h0, h1, h2, h3, h4) { - this.h0 = h0 | 0; - this.h1 = h1 | 0; - this.h2 = h2 | 0; - this.h3 = h3 | 0; - this.h4 = h4 | 0; - } - process(view, offset2) { - for (let i = 0; i < 16; i++, offset2 += 4) - BUF[i] = view.getUint32(offset2, true); - let al2 = this.h0 | 0, ar = al2, bl2 = this.h1 | 0, br = bl2, cl2 = this.h2 | 0, cr = cl2, dl2 = this.h3 | 0, dr = dl2, el2 = this.h4 | 0, er = el2; - for (let group = 0; group < 5; group++) { - const rGroup = 4 - group; - const hbl = Kl[group], hbr = Kr[group]; - const rl2 = idxL[group], rr = idxR[group]; - const sl2 = shiftsL[group], sr = shiftsR[group]; - for (let i = 0; i < 16; i++) { - const tl2 = rotl$1(al2 + f$1(group, bl2, cl2, dl2) + BUF[rl2[i]] + hbl, sl2[i]) + el2 | 0; - al2 = el2, el2 = dl2, dl2 = rotl$1(cl2, 10) | 0, cl2 = bl2, bl2 = tl2; - } - for (let i = 0; i < 16; i++) { - const tr = rotl$1(ar + f$1(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er | 0; - ar = er, er = dr, dr = rotl$1(cr, 10) | 0, cr = br, br = tr; - } +function formatTransaction(transaction2) { + const transaction_ = { + ...transaction2, + blockHash: transaction2.blockHash ? transaction2.blockHash : null, + blockNumber: transaction2.blockNumber ? BigInt(transaction2.blockNumber) : null, + chainId: transaction2.chainId ? hexToNumber$2(transaction2.chainId) : void 0, + gas: transaction2.gas ? BigInt(transaction2.gas) : void 0, + gasPrice: transaction2.gasPrice ? BigInt(transaction2.gasPrice) : void 0, + maxFeePerBlobGas: transaction2.maxFeePerBlobGas ? BigInt(transaction2.maxFeePerBlobGas) : void 0, + maxFeePerGas: transaction2.maxFeePerGas ? BigInt(transaction2.maxFeePerGas) : void 0, + maxPriorityFeePerGas: transaction2.maxPriorityFeePerGas ? BigInt(transaction2.maxPriorityFeePerGas) : void 0, + nonce: transaction2.nonce ? hexToNumber$2(transaction2.nonce) : void 0, + to: transaction2.to ? transaction2.to : null, + transactionIndex: transaction2.transactionIndex ? Number(transaction2.transactionIndex) : null, + type: transaction2.type ? transactionType[transaction2.type] : void 0, + typeHex: transaction2.type ? transaction2.type : void 0, + value: transaction2.value ? BigInt(transaction2.value) : void 0, + v: transaction2.v ? BigInt(transaction2.v) : void 0 + }; + if (transaction2.authorizationList) + transaction_.authorizationList = formatAuthorizationList(transaction2.authorizationList); + transaction_.yParity = (() => { + if (transaction2.yParity) + return Number(transaction2.yParity); + if (typeof transaction_.v === "bigint") { + if (transaction_.v === 0n || transaction_.v === 27n) + return 0; + if (transaction_.v === 1n || transaction_.v === 28n) + return 1; + if (transaction_.v >= 35n) + return transaction_.v % 2n === 0n ? 1 : 0; } - this.set(this.h1 + cl2 + dr | 0, this.h2 + dl2 + er | 0, this.h3 + el2 + ar | 0, this.h4 + al2 + br | 0, this.h0 + bl2 + cr | 0); + return void 0; + })(); + if (transaction_.type === "legacy") { + delete transaction_.accessList; + delete transaction_.maxFeePerBlobGas; + delete transaction_.maxFeePerGas; + delete transaction_.maxPriorityFeePerGas; + delete transaction_.yParity; } - roundClean() { - BUF.fill(0); + if (transaction_.type === "eip2930") { + delete transaction_.maxFeePerBlobGas; + delete transaction_.maxFeePerGas; + delete transaction_.maxPriorityFeePerGas; } - destroy() { - this.destroyed = true; - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0); + if (transaction_.type === "eip1559") { + delete transaction_.maxFeePerBlobGas; } + return transaction_; } -const ripemd160$1 = /* @__PURE__ */ wrapConstructor$2(() => new RIPEMD160()); -let locked$2 = false; -const _ripemd160 = function(data) { - return ripemd160$1(data); -}; -let __ripemd160 = _ripemd160; -function ripemd160(_data6) { - const data = getBytes(_data6, "data"); - return hexlify(__ripemd160(data)); +function formatAuthorizationList(authorizationList) { + return authorizationList.map((authorization) => ({ + contractAddress: authorization.address, + r: authorization.r, + s: authorization.s, + chainId: Number(authorization.chainId), + nonce: Number(authorization.nonce), + ...typeof authorization.yParity !== "undefined" ? { yParity: Number(authorization.yParity) } : {}, + ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: Number(authorization.v) } : {} + })); } -ripemd160._ = _ripemd160; -ripemd160.lock = function() { - locked$2 = true; -}; -ripemd160.register = function(func) { - if (locked$2) { - throw new TypeError("ripemd160 is locked"); - } - __ripemd160 = func; -}; -Object.freeze(ripemd160); -let locked$1 = false; -const _pbkdf2 = function(password, salt, iterations, keylen, algo) { - return pbkdf2Sync(password, salt, iterations, keylen, algo); -}; -let __pbkdf2 = _pbkdf2; -function pbkdf2(_password, _salt, iterations, keylen, algo) { - const password = getBytes(_password, "password"); - const salt = getBytes(_salt, "salt"); - return hexlify(__pbkdf2(password, salt, iterations, keylen, algo)); +function formatBlock$1(block) { + var _a2; + const transactions2 = (_a2 = block.transactions) == null ? void 0 : _a2.map((transaction2) => { + if (typeof transaction2 === "string") + return transaction2; + return formatTransaction(transaction2); + }); + return { + ...block, + baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null, + blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0, + difficulty: block.difficulty ? BigInt(block.difficulty) : void 0, + excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0, + gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0, + gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0, + hash: block.hash ? block.hash : null, + logsBloom: block.logsBloom ? block.logsBloom : null, + nonce: block.nonce ? block.nonce : null, + number: block.number ? BigInt(block.number) : null, + size: block.size ? BigInt(block.size) : void 0, + timestamp: block.timestamp ? BigInt(block.timestamp) : void 0, + transactions: transactions2, + totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null + }; } -pbkdf2._ = _pbkdf2; -pbkdf2.lock = function() { - locked$1 = true; -}; -pbkdf2.register = function(func) { - if (locked$1) { - throw new Error("pbkdf2 is locked"); +async function getBlock(client2, { blockHash, blockNumber, blockTag: blockTag_, includeTransactions: includeTransactions_ } = {}) { + var _a2, _b2, _c2; + const blockTag = blockTag_ ?? "latest"; + const includeTransactions = includeTransactions_ ?? false; + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + let block = null; + if (blockHash) { + block = await client2.request({ + method: "eth_getBlockByHash", + params: [blockHash, includeTransactions] + }, { dedupe: true }); + } else { + block = await client2.request({ + method: "eth_getBlockByNumber", + params: [blockNumberHex || blockTag, includeTransactions] + }, { dedupe: Boolean(blockNumberHex) }); } - __pbkdf2 = func; -}; -Object.freeze(pbkdf2); -let locked = false; -const _randomBytes = function(length) { - return new Uint8Array(randomBytes$2(length)); -}; -let __randomBytes = _randomBytes; -function randomBytes$1(length) { - return __randomBytes(length); + if (!block) + throw new BlockNotFoundError({ blockHash, blockNumber }); + const format2 = ((_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.block) == null ? void 0 : _c2.format) || formatBlock$1; + return format2(block); } -randomBytes$1._ = _randomBytes; -randomBytes$1.lock = function() { - locked = true; -}; -randomBytes$1.register = function(func) { - if (locked) { - throw new Error("randomBytes is locked"); - } - __randomBytes = func; -}; -Object.freeze(randomBytes$1); -const rotl = (a2, b2) => a2 << b2 | a2 >>> 32 - b2; -function XorAndSalsa(prev, pi2, input2, ii2, out, oi2) { - let y00 = prev[pi2++] ^ input2[ii2++], y01 = prev[pi2++] ^ input2[ii2++]; - let y02 = prev[pi2++] ^ input2[ii2++], y03 = prev[pi2++] ^ input2[ii2++]; - let y04 = prev[pi2++] ^ input2[ii2++], y05 = prev[pi2++] ^ input2[ii2++]; - let y06 = prev[pi2++] ^ input2[ii2++], y07 = prev[pi2++] ^ input2[ii2++]; - let y08 = prev[pi2++] ^ input2[ii2++], y09 = prev[pi2++] ^ input2[ii2++]; - let y10 = prev[pi2++] ^ input2[ii2++], y11 = prev[pi2++] ^ input2[ii2++]; - let y12 = prev[pi2++] ^ input2[ii2++], y13 = prev[pi2++] ^ input2[ii2++]; - let y14 = prev[pi2++] ^ input2[ii2++], y15 = prev[pi2++] ^ input2[ii2++]; - let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; - for (let i = 0; i < 8; i += 2) { - x04 ^= rotl(x00 + x12 | 0, 7); - x08 ^= rotl(x04 + x00 | 0, 9); - x12 ^= rotl(x08 + x04 | 0, 13); - x00 ^= rotl(x12 + x08 | 0, 18); - x09 ^= rotl(x05 + x01 | 0, 7); - x13 ^= rotl(x09 + x05 | 0, 9); - x01 ^= rotl(x13 + x09 | 0, 13); - x05 ^= rotl(x01 + x13 | 0, 18); - x14 ^= rotl(x10 + x06 | 0, 7); - x02 ^= rotl(x14 + x10 | 0, 9); - x06 ^= rotl(x02 + x14 | 0, 13); - x10 ^= rotl(x06 + x02 | 0, 18); - x03 ^= rotl(x15 + x11 | 0, 7); - x07 ^= rotl(x03 + x15 | 0, 9); - x11 ^= rotl(x07 + x03 | 0, 13); - x15 ^= rotl(x11 + x07 | 0, 18); - x01 ^= rotl(x00 + x03 | 0, 7); - x02 ^= rotl(x01 + x00 | 0, 9); - x03 ^= rotl(x02 + x01 | 0, 13); - x00 ^= rotl(x03 + x02 | 0, 18); - x06 ^= rotl(x05 + x04 | 0, 7); - x07 ^= rotl(x06 + x05 | 0, 9); - x04 ^= rotl(x07 + x06 | 0, 13); - x05 ^= rotl(x04 + x07 | 0, 18); - x11 ^= rotl(x10 + x09 | 0, 7); - x08 ^= rotl(x11 + x10 | 0, 9); - x09 ^= rotl(x08 + x11 | 0, 13); - x10 ^= rotl(x09 + x08 | 0, 18); - x12 ^= rotl(x15 + x14 | 0, 7); - x13 ^= rotl(x12 + x15 | 0, 9); - x14 ^= rotl(x13 + x12 | 0, 13); - x15 ^= rotl(x14 + x13 | 0, 18); - } - out[oi2++] = y00 + x00 | 0; - out[oi2++] = y01 + x01 | 0; - out[oi2++] = y02 + x02 | 0; - out[oi2++] = y03 + x03 | 0; - out[oi2++] = y04 + x04 | 0; - out[oi2++] = y05 + x05 | 0; - out[oi2++] = y06 + x06 | 0; - out[oi2++] = y07 + x07 | 0; - out[oi2++] = y08 + x08 | 0; - out[oi2++] = y09 + x09 | 0; - out[oi2++] = y10 + x10 | 0; - out[oi2++] = y11 + x11 | 0; - out[oi2++] = y12 + x12 | 0; - out[oi2++] = y13 + x13 | 0; - out[oi2++] = y14 + x14 | 0; - out[oi2++] = y15 + x15 | 0; +async function getGasPrice(client2) { + const gasPrice = await client2.request({ + method: "eth_gasPrice" + }); + return BigInt(gasPrice); } -function BlockMix(input2, ii2, out, oi2, r2) { - let head = oi2 + 0; - let tail = oi2 + 16 * r2; - for (let i = 0; i < 16; i++) - out[tail + i] = input2[ii2 + (2 * r2 - 1) * 16 + i]; - for (let i = 0; i < r2; i++, head += 16, ii2 += 16) { - XorAndSalsa(out, tail, input2, ii2, out, head); - if (i > 0) - tail += 16; - XorAndSalsa(out, head, input2, ii2 += 16, out, tail); - } +async function estimateMaxPriorityFeePerGas(client2, args) { + return internal_estimateMaxPriorityFeePerGas(client2, args); } -function scryptInit(password, salt, _opts) { - const opts = checkOpts({ - dkLen: 32, - asyncTick: 10, - maxmem: 1024 ** 3 + 1024 - }, _opts); - const { N: N2, r: r2, p: p2, dkLen, asyncTick, maxmem, onProgress } = opts; - number$1(N2); - number$1(r2); - number$1(p2); - number$1(dkLen); - number$1(asyncTick); - number$1(maxmem); - if (onProgress !== void 0 && typeof onProgress !== "function") - throw new Error("progressCb should be function"); - const blockSize = 128 * r2; - const blockSize32 = blockSize / 4; - if (N2 <= 1 || (N2 & N2 - 1) !== 0 || N2 >= 2 ** (blockSize / 8) || N2 > 2 ** 32) { - throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32"); - } - if (p2 < 0 || p2 > (2 ** 32 - 1) * 32 / blockSize) { - throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)"); +async function internal_estimateMaxPriorityFeePerGas(client2, args) { + var _a2, _b2; + const { block: block_, chain = client2.chain, request } = args || {}; + try { + const maxPriorityFeePerGas = ((_a2 = chain == null ? void 0 : chain.fees) == null ? void 0 : _a2.maxPriorityFeePerGas) ?? ((_b2 = chain == null ? void 0 : chain.fees) == null ? void 0 : _b2.defaultPriorityFee); + if (typeof maxPriorityFeePerGas === "function") { + const block = block_ || await getAction$1(client2, getBlock, "getBlock")({}); + const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({ + block, + client: client2, + request + }); + if (maxPriorityFeePerGas_ === null) + throw new Error(); + return maxPriorityFeePerGas_; + } + if (typeof maxPriorityFeePerGas !== "undefined") + return maxPriorityFeePerGas; + const maxPriorityFeePerGasHex = await client2.request({ + method: "eth_maxPriorityFeePerGas" + }); + return hexToBigInt(maxPriorityFeePerGasHex); + } catch { + const [block, gasPrice] = await Promise.all([ + block_ ? Promise.resolve(block_) : getAction$1(client2, getBlock, "getBlock")({}), + getAction$1(client2, getGasPrice, "getGasPrice")({}) + ]); + if (typeof block.baseFeePerGas !== "bigint") + throw new Eip1559FeesNotSupportedError(); + const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas; + if (maxPriorityFeePerGas < 0n) + return 0n; + return maxPriorityFeePerGas; } - if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { - throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32"); +} +async function estimateFeesPerGas(client2, args) { + return internal_estimateFeesPerGas(client2, args); +} +async function internal_estimateFeesPerGas(client2, args) { + var _a2, _b2; + const { block: block_, chain = client2.chain, request, type = "eip1559" } = args || {}; + const baseFeeMultiplier = await (async () => { + var _a3, _b3; + if (typeof ((_a3 = chain == null ? void 0 : chain.fees) == null ? void 0 : _a3.baseFeeMultiplier) === "function") + return chain.fees.baseFeeMultiplier({ + block: block_, + client: client2, + request + }); + return ((_b3 = chain == null ? void 0 : chain.fees) == null ? void 0 : _b3.baseFeeMultiplier) ?? 1.2; + })(); + if (baseFeeMultiplier < 1) + throw new BaseFeeScalarError(); + const decimals = ((_a2 = baseFeeMultiplier.toString().split(".")[1]) == null ? void 0 : _a2.length) ?? 0; + const denominator = 10 ** decimals; + const multiply = (base) => base * BigInt(Math.ceil(baseFeeMultiplier * denominator)) / BigInt(denominator); + const block = block_ ? block_ : await getAction$1(client2, getBlock, "getBlock")({}); + if (typeof ((_b2 = chain == null ? void 0 : chain.fees) == null ? void 0 : _b2.estimateFeesPerGas) === "function") { + const fees = await chain.fees.estimateFeesPerGas({ + block: block_, + client: client2, + multiply, + request, + type + }); + if (fees !== null) + return fees; } - const memUsed = blockSize * (N2 + p2); - if (memUsed > maxmem) { - throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + if (type === "eip1559") { + if (typeof block.baseFeePerGas !== "bigint") + throw new Eip1559FeesNotSupportedError(); + const maxPriorityFeePerGas = typeof (request == null ? void 0 : request.maxPriorityFeePerGas) === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client2, { + block, + chain, + request + }); + const baseFeePerGas = multiply(block.baseFeePerGas); + const maxFeePerGas = (request == null ? void 0 : request.maxFeePerGas) ?? baseFeePerGas + maxPriorityFeePerGas; + return { + maxFeePerGas, + maxPriorityFeePerGas + }; } - const B2 = pbkdf2$1(sha256$4, password, salt, { c: 1, dkLen: blockSize * p2 }); - const B32 = u32$1(B2); - const V2 = u32$1(new Uint8Array(blockSize * N2)); - const tmp = u32$1(new Uint8Array(blockSize)); - let blockMixCb = () => { + const gasPrice = (request == null ? void 0 : request.gasPrice) ?? multiply(await getAction$1(client2, getGasPrice, "getGasPrice")({})); + return { + gasPrice }; - if (onProgress) { - const totalBlockMix = 2 * N2 * p2; - const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1); - let blockMixCnt = 0; - blockMixCb = () => { - blockMixCnt++; - if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) - onProgress(blockMixCnt / totalBlockMix); - }; +} +class EstimateGasExecutionError extends BaseError$3 { + constructor(cause, { account: account2, docsPath: docsPath2, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) { + var _a2; + const prettyArgs = prettyPrint({ + from: account2 == null ? void 0 : account2.address, + to, + value: typeof value !== "undefined" && `${formatEther$2(value)} ${((_a2 = chain == null ? void 0 : chain.nativeCurrency) == null ? void 0 : _a2.symbol) || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, + nonce + }); + super(cause.shortMessage, { + cause, + docsPath: docsPath2, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Estimate Gas Arguments:", + prettyArgs + ].filter(Boolean), + name: "EstimateGasExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; } - return { N: N2, r: r2, p: p2, dkLen, blockSize32, V: V2, B32, B: B2, tmp, blockMixCb, asyncTick }; } -function scryptOutput(password, dkLen, B2, V2, tmp) { - const res = pbkdf2$1(sha256$4, password, B2, { c: 1, dkLen }); - B2.fill(0); - V2.fill(0); - tmp.fill(0); - return res; +function getEstimateGasError(err, { docsPath: docsPath2, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new EstimateGasExecutionError(cause, { + docsPath: docsPath2, + ...args + }); } -function scrypt$1(password, salt, opts) { - const { N: N2, r: r2, p: p2, dkLen, blockSize32, V: V2, B32, B: B2, tmp, blockMixCb } = scryptInit(password, salt, opts); - for (let pi2 = 0; pi2 < p2; pi2++) { - const Pi2 = blockSize32 * pi2; - for (let i = 0; i < blockSize32; i++) - V2[i] = B32[Pi2 + i]; - for (let i = 0, pos = 0; i < N2 - 1; i++) { - BlockMix(V2, pos, V2, pos += blockSize32, r2); - blockMixCb(); - } - BlockMix(V2, (N2 - 1) * blockSize32, B32, Pi2, r2); - blockMixCb(); - for (let i = 0; i < N2; i++) { - const j2 = B32[Pi2 + blockSize32 - 16] % N2; - for (let k2 = 0; k2 < blockSize32; k2++) - tmp[k2] = B32[Pi2 + k2] ^ V2[j2 * blockSize32 + k2]; - BlockMix(tmp, 0, B32, Pi2, r2); - blockMixCb(); - } +class AccountStateConflictError extends BaseError$3 { + constructor({ address }) { + super(`State for account "${address}" is set multiple times.`, { + name: "AccountStateConflictError" + }); } - return scryptOutput(password, dkLen, B2, V2, tmp); } -async function scryptAsync(password, salt, opts) { - const { N: N2, r: r2, p: p2, dkLen, blockSize32, V: V2, B32, B: B2, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); - for (let pi2 = 0; pi2 < p2; pi2++) { - const Pi2 = blockSize32 * pi2; - for (let i = 0; i < blockSize32; i++) - V2[i] = B32[Pi2 + i]; - let pos = 0; - await asyncLoop(N2 - 1, asyncTick, () => { - BlockMix(V2, pos, V2, pos += blockSize32, r2); - blockMixCb(); - }); - BlockMix(V2, (N2 - 1) * blockSize32, B32, Pi2, r2); - blockMixCb(); - await asyncLoop(N2, asyncTick, () => { - const j2 = B32[Pi2 + blockSize32 - 16] % N2; - for (let k2 = 0; k2 < blockSize32; k2++) - tmp[k2] = B32[Pi2 + k2] ^ V2[j2 * blockSize32 + k2]; - BlockMix(tmp, 0, B32, Pi2, r2); - blockMixCb(); +class StateAssignmentConflictError extends BaseError$3 { + constructor() { + super("state and stateDiff are set on the same account.", { + name: "StateAssignmentConflictError" }); } - return scryptOutput(password, dkLen, B2, V2, tmp); } -let lockedSync = false, lockedAsync = false; -const _scryptAsync = async function(passwd, salt, N2, r2, p2, dkLen, onProgress) { - return await scryptAsync(passwd, salt, { N: N2, r: r2, p: p2, dkLen, onProgress }); -}; -const _scryptSync = function(passwd, salt, N2, r2, p2, dkLen) { - return scrypt$1(passwd, salt, { N: N2, r: r2, p: p2, dkLen }); -}; -let __scryptAsync = _scryptAsync; -let __scryptSync = _scryptSync; -async function scrypt(_passwd, _salt, N2, r2, p2, dkLen, progress2) { - const passwd = getBytes(_passwd, "passwd"); - const salt = getBytes(_salt, "salt"); - return hexlify(await __scryptAsync(passwd, salt, N2, r2, p2, dkLen, progress2)); +function prettyStateMapping(stateMapping) { + return stateMapping.reduce((pretty, { slot, value }) => { + return `${pretty} ${slot}: ${value} +`; + }, ""); } -scrypt._ = _scryptAsync; -scrypt.lock = function() { - lockedAsync = true; -}; -scrypt.register = function(func) { - if (lockedAsync) { - throw new Error("scrypt is locked"); - } - __scryptAsync = func; -}; -Object.freeze(scrypt); -function scryptSync(_passwd, _salt, N2, r2, p2, dkLen) { - const passwd = getBytes(_passwd, "passwd"); - const salt = getBytes(_salt, "salt"); - return hexlify(__scryptSync(passwd, salt, N2, r2, p2, dkLen)); +function prettyStateOverride(stateOverride) { + return stateOverride.reduce((pretty, { address, ...state }) => { + let val = `${pretty} ${address}: +`; + if (state.nonce) + val += ` nonce: ${state.nonce} +`; + if (state.balance) + val += ` balance: ${state.balance} +`; + if (state.code) + val += ` code: ${state.code} +`; + if (state.state) { + val += " state:\n"; + val += prettyStateMapping(state.state); + } + if (state.stateDiff) { + val += " stateDiff:\n"; + val += prettyStateMapping(state.stateDiff); + } + return val; + }, " State Override:\n").slice(0, -1); } -scryptSync._ = _scryptSync; -scryptSync.lock = function() { - lockedSync = true; -}; -scryptSync.register = function(func) { - if (lockedSync) { - throw new Error("scryptSync is locked"); - } - __scryptSync = func; -}; -Object.freeze(scryptSync); -const _sha256 = function(data) { - return createHash("sha256").update(data).digest(); -}; -const _sha512 = function(data) { - return createHash("sha512").update(data).digest(); -}; -let __sha256 = _sha256; -let __sha512 = _sha512; -let locked256 = false, locked512 = false; -function sha256$3(_data6) { - const data = getBytes(_data6, "data"); - return hexlify(__sha256(data)); +function serializeStateMapping(stateMapping) { + if (!stateMapping || stateMapping.length === 0) + return void 0; + return stateMapping.reduce((acc, { slot, value }) => { + if (slot.length !== 66) + throw new InvalidBytesLengthError({ + size: slot.length, + targetSize: 66, + type: "hex" + }); + if (value.length !== 66) + throw new InvalidBytesLengthError({ + size: value.length, + targetSize: 66, + type: "hex" + }); + acc[slot] = value; + return acc; + }, {}); } -sha256$3._ = _sha256; -sha256$3.lock = function() { - locked256 = true; -}; -sha256$3.register = function(func) { - if (locked256) { - throw new Error("sha256 is locked"); +function serializeAccountStateOverride(parameters) { + const { balance, nonce, state, stateDiff, code: code2 } = parameters; + const rpcAccountStateOverride = {}; + if (code2 !== void 0) + rpcAccountStateOverride.code = code2; + if (balance !== void 0) + rpcAccountStateOverride.balance = numberToHex(balance); + if (nonce !== void 0) + rpcAccountStateOverride.nonce = numberToHex(nonce); + if (state !== void 0) + rpcAccountStateOverride.state = serializeStateMapping(state); + if (stateDiff !== void 0) { + if (rpcAccountStateOverride.state) + throw new StateAssignmentConflictError(); + rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff); } - __sha256 = func; -}; -Object.freeze(sha256$3); -function sha512(_data6) { - const data = getBytes(_data6, "data"); - return hexlify(__sha512(data)); + return rpcAccountStateOverride; } -sha512._ = _sha512; -sha512.lock = function() { - locked512 = true; -}; -sha512.register = function(func) { - if (locked512) { - throw new Error("sha512 is locked"); - } - __sha512 = func; -}; -Object.freeze(sha256$3); -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const _0n$8 = BigInt(0); -const _1n$a = BigInt(1); -const _2n$6 = BigInt(2); -const u8a = (a2) => a2 instanceof Uint8Array; -const hexes$3 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); -function bytesToHex$3(bytes2) { - if (!u8a(bytes2)) - throw new Error("Uint8Array expected"); - let hex2 = ""; - for (let i = 0; i < bytes2.length; i++) { - hex2 += hexes$3[bytes2[i]]; +function serializeStateOverride(parameters) { + if (!parameters) + return void 0; + const rpcStateOverride = {}; + for (const { address, ...accountState } of parameters) { + if (!isAddress$1(address, { strict: false })) + throw new InvalidAddressError({ address }); + if (rpcStateOverride[address]) + throw new AccountStateConflictError({ address }); + rpcStateOverride[address] = serializeAccountStateOverride(accountState); } - return hex2; -} -function numberToHexUnpadded$1(num) { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; + return rpcStateOverride; } -function hexToNumber$2(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - return BigInt(hex2 === "" ? "0" : `0x${hex2}`); +async function getBalance(client2, { address, blockNumber, blockTag = "latest" }) { + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const balance = await client2.request({ + method: "eth_getBalance", + params: [address, blockNumberHex || blockTag] + }); + return BigInt(balance); } -function hexToBytes$2(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - const len = hex2.length; - if (len % 2) - throw new Error("padded hex string expected, got unpadded hex of length " + len); - const array = new Uint8Array(len / 2); - for (let i = 0; i < array.length; i++) { - const j2 = i * 2; - const hexByte = hex2.slice(j2, j2 + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error("Invalid byte sequence"); - array[i] = byte; +async function estimateGas(client2, args) { + var _a2, _b2, _c2; + const account_ = args.account ?? client2.account; + const account2 = account_ ? parseAccount(account_) : void 0; + try { + let estimateGas_rpc = function(parameters) { + const { block: block2, request: request2, rpcStateOverride: rpcStateOverride2 } = parameters; + return client2.request({ + method: "eth_estimateGas", + params: rpcStateOverride2 ? [request2, block2 ?? "latest", rpcStateOverride2] : block2 ? [request2, block2] : [request2] + }); + }; + const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = await prepareTransactionRequest(client2, { + ...args, + parameters: ( + // Some RPC Providers do not compute versioned hashes from blobs. We will need + // to compute them. + (account2 == null ? void 0 : account2.type) === "local" ? void 0 : ["blobVersionedHashes"] + ) + }); + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const rpcStateOverride = serializeStateOverride(stateOverride); + const to = await (async () => { + if (rest.to) + return rest.to; + if (authorizationList && authorizationList.length > 0) + return await recoverAuthorizationAddress({ + authorization: authorizationList[0] + }).catch(() => { + throw new BaseError$3("`to` is required. Could not infer from `authorizationList`"); + }); + return void 0; + })(); + assertRequest(args); + const chainFormat = (_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.transactionRequest) == null ? void 0 : _c2.format; + const format2 = chainFormat || formatTransactionRequest; + const request = format2({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + from: account2 == null ? void 0 : account2.address, + accessList, + authorizationList, + blobs, + blobVersionedHashes, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to, + value + }); + let estimate = BigInt(await estimateGas_rpc({ block, request, rpcStateOverride })); + if (authorizationList) { + const value2 = await getBalance(client2, { address: request.from }); + const estimates = await Promise.all(authorizationList.map(async (authorization) => { + const { contractAddress } = authorization; + const estimate2 = await estimateGas_rpc({ + block, + request: { + authorizationList: void 0, + data, + from: account2 == null ? void 0 : account2.address, + to: contractAddress, + value: numberToHex(value2) + }, + rpcStateOverride + }).catch(() => 100000n); + return 2n * BigInt(estimate2); + })); + estimate += estimates.reduce((acc, curr) => acc + curr, 0n); + } + return estimate; + } catch (err) { + throw getEstimateGasError(err, { + ...args, + account: account2, + chain: client2.chain + }); } - return array; -} -function bytesToNumberBE$1(bytes2) { - return hexToNumber$2(bytesToHex$3(bytes2)); } -function bytesToNumberLE$1(bytes2) { - if (!u8a(bytes2)) - throw new Error("Uint8Array expected"); - return hexToNumber$2(bytesToHex$3(Uint8Array.from(bytes2).reverse())); +async function getTransactionCount(client2, { address, blockTag = "latest", blockNumber }) { + const count2 = await client2.request({ + method: "eth_getTransactionCount", + params: [address, blockNumber ? numberToHex(blockNumber) : blockTag] + }, { dedupe: Boolean(blockNumber) }); + return hexToNumber$2(count2); } -function numberToBytesBE$1(n2, len) { - return hexToBytes$2(n2.toString(16).padStart(len * 2, "0")); +function blobsToCommitments(parameters) { + const { kzg } = parameters; + const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes$2(x2)) : parameters.blobs; + const commitments = []; + for (const blob of blobs) + commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob))); + return to === "bytes" ? commitments : commitments.map((x2) => bytesToHex$3(x2)); } -function numberToBytesLE$1(n2, len) { - return numberToBytesBE$1(n2, len).reverse(); +function blobsToProofs(parameters) { + const { kzg } = parameters; + const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes$2(x2)) : parameters.blobs; + const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x2) => hexToBytes$2(x2)) : parameters.commitments; + const proofs = []; + for (let i = 0; i < blobs.length; i++) { + const blob = blobs[i]; + const commitment = commitments[i]; + proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))); + } + return to === "bytes" ? proofs : proofs.map((x2) => bytesToHex$3(x2)); } -function numberToVarBytesBE$1(n2) { - return hexToBytes$2(numberToHexUnpadded$1(n2)); +function setBigUint64$2(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh2 = Number(value >> _32n2 & _u32_max); + const wl = Number(value & _u32_max); + const h2 = isLE2 ? 4 : 0; + const l2 = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h2, wh2, isLE2); + view.setUint32(byteOffset + l2, wl, isLE2); } -function ensureBytes$1(title, hex2, expectedLength) { - let res; - if (typeof hex2 === "string") { - try { - res = hexToBytes$2(hex2); - } catch (e2) { - throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e2}`); +const Chi$2 = (a2, b2, c2) => a2 & b2 ^ ~a2 & c2; +const Maj$2 = (a2, b2, c2) => a2 & b2 ^ a2 & c2 ^ b2 & c2; +let HashMD$1 = class HashMD extends Hash$2 { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView$2(this.buffer); + } + update(data) { + exists$2(this); + const { view, buffer: buffer2, blockLen } = this; + data = toBytes$2(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView$2(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } } - } else if (u8a(hex2)) { - res = Uint8Array.from(hex2); - } else { - throw new Error(`${title} must be hex string or Uint8Array`); + this.length += data.length; + this.roundClean(); + return this; } - const len = res.length; - if (typeof expectedLength === "number" && len !== expectedLength) - throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); - return res; -} -function concatBytes$3(...arrays) { - const r2 = new Uint8Array(arrays.reduce((sum, a2) => sum + a2.length, 0)); - let pad2 = 0; - arrays.forEach((a2) => { - if (!u8a(a2)) - throw new Error("Uint8Array expected"); - r2.set(a2, pad2); - pad2 += a2.length; - }); - return r2; -} -function equalBytes$1(b1, b2) { - if (b1.length !== b2.length) - return false; - for (let i = 0; i < b1.length; i++) - if (b1[i] !== b2[i]) - return false; - return true; -} -function utf8ToBytes$3(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); -} -function bitLen$1(n2) { - let len; - for (len = 0; n2 > _0n$8; n2 >>= _1n$a, len += 1) - ; - return len; -} -function bitGet$1(n2, pos) { - return n2 >> BigInt(pos) & _1n$a; -} -const bitSet$1 = (n2, pos, value) => { - return n2 | (value ? _1n$a : _0n$8) << BigInt(pos); -}; -const bitMask$1 = (n2) => (_2n$6 << BigInt(n2 - 1)) - _1n$a; -const u8n$1 = (data) => new Uint8Array(data); -const u8fr$1 = (arr) => Uint8Array.from(arr); -function createHmacDrbg$1(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== "number" || hashLen < 2) - throw new Error("hashLen must be a number"); - if (typeof qByteLen !== "number" || qByteLen < 2) - throw new Error("qByteLen must be a number"); - if (typeof hmacFn !== "function") - throw new Error("hmacFn must be a function"); - let v3 = u8n$1(hashLen); - let k2 = u8n$1(hashLen); - let i = 0; - const reset = () => { - v3.fill(1); - k2.fill(0); - i = 0; - }; - const h2 = (...b2) => hmacFn(k2, v3, ...b2); - const reseed = (seed = u8n$1()) => { - k2 = h2(u8fr$1([0]), seed); - v3 = h2(); - if (seed.length === 0) - return; - k2 = h2(u8fr$1([1]), seed); - v3 = h2(); - }; - const gen2 = () => { - if (i++ >= 1e3) - throw new Error("drbg: tried 1000 values"); - let len = 0; - const out = []; - while (len < qByteLen) { - v3 = h2(); - const sl2 = v3.slice(); - out.push(sl2); - len += v3.length; + digestInto(out) { + exists$2(this); + output$2(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer2[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; } - return concatBytes$3(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); - let res = void 0; - while (!(res = pred(gen2()))) - reseed(); - reset(); + for (let i = pos; i < blockLen; i++) + buffer2[i] = 0; + setBigUint64$2(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView$2(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); return res; - }; - return genUntil; -} -const validatorFns$1 = { - bigint: (val) => typeof val === "bigint", - function: (val) => typeof val === "function", - boolean: (val) => typeof val === "boolean", - string: (val) => typeof val === "string", - stringOrUint8Array: (val) => typeof val === "string" || val instanceof Uint8Array, - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object2) => object2.Fp.isValid(val), - hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer2); + return to; + } }; -function validateObject$1(object2, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns$1[type]; - if (typeof checkVal !== "function") - throw new Error(`Invalid validator "${type}", expected function`); - const val = object2[fieldName]; - if (isOptional && val === void 0) - return; - if (!checkVal(val, object2)) { - throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); - } - }; - for (const [fieldName, type] of Object.entries(validators)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object2; -} -const ut$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - bitGet: bitGet$1, - bitLen: bitLen$1, - bitMask: bitMask$1, - bitSet: bitSet$1, - bytesToHex: bytesToHex$3, - bytesToNumberBE: bytesToNumberBE$1, - bytesToNumberLE: bytesToNumberLE$1, - concatBytes: concatBytes$3, - createHmacDrbg: createHmacDrbg$1, - ensureBytes: ensureBytes$1, - equalBytes: equalBytes$1, - hexToBytes: hexToBytes$2, - hexToNumber: hexToNumber$2, - numberToBytesBE: numberToBytesBE$1, - numberToBytesLE: numberToBytesLE$1, - numberToHexUnpadded: numberToHexUnpadded$1, - numberToVarBytesBE: numberToVarBytesBE$1, - utf8ToBytes: utf8ToBytes$3, - validateObject: validateObject$1 -}, Symbol.toStringTag, { value: "Module" })); -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const _0n$7 = BigInt(0), _1n$9 = BigInt(1), _2n$5 = BigInt(2), _3n$3 = BigInt(3); -const _4n$1 = BigInt(4), _5n$1 = BigInt(5), _8n$1 = BigInt(8); -BigInt(9); -BigInt(16); -function mod$1(a2, b2) { - const result = a2 % b2; - return result >= _0n$7 ? result : b2 + result; -} -function pow$1(num, power, modulo) { - if (modulo <= _0n$7 || power < _0n$7) - throw new Error("Expected power/modulo > 0"); - if (modulo === _1n$9) - return _0n$7; - let res = _1n$9; - while (power > _0n$7) { - if (power & _1n$9) - res = res * num % modulo; - num = num * num % modulo; - power >>= _1n$9; - } - return res; -} -function pow2$1(x2, power, modulo) { - let res = x2; - while (power-- > _0n$7) { - res *= res; - res %= modulo; - } - return res; -} -function invert$1(number2, modulo) { - if (number2 === _0n$7 || modulo <= _0n$7) { - throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`); +const SHA256_K$2 = /* @__PURE__ */ new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +const SHA256_IV$1 = /* @__PURE__ */ new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +const SHA256_W$2 = /* @__PURE__ */ new Uint32Array(64); +let SHA256$2 = class SHA256 extends HashMD$1 { + constructor() { + super(64, 32, 8, false); + this.A = SHA256_IV$1[0] | 0; + this.B = SHA256_IV$1[1] | 0; + this.C = SHA256_IV$1[2] | 0; + this.D = SHA256_IV$1[3] | 0; + this.E = SHA256_IV$1[4] | 0; + this.F = SHA256_IV$1[5] | 0; + this.G = SHA256_IV$1[6] | 0; + this.H = SHA256_IV$1[7] | 0; } - let a2 = mod$1(number2, modulo); - let b2 = modulo; - let x2 = _0n$7, u2 = _1n$9; - while (a2 !== _0n$7) { - const q2 = b2 / a2; - const r2 = b2 % a2; - const m2 = x2 - u2 * q2; - b2 = a2, a2 = r2, x2 = u2, u2 = m2; + get() { + const { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; + return [A2, B2, C2, D2, E2, F2, G2, H2]; } - const gcd = b2; - if (gcd !== _1n$9) - throw new Error("invert: does not exist"); - return mod$1(x2, modulo); -} -function tonelliShanks$1(P2) { - const legendreC = (P2 - _1n$9) / _2n$5; - let Q2, S2, Z2; - for (Q2 = P2 - _1n$9, S2 = 0; Q2 % _2n$5 === _0n$7; Q2 /= _2n$5, S2++) - ; - for (Z2 = _2n$5; Z2 < P2 && pow$1(Z2, legendreC, P2) !== P2 - _1n$9; Z2++) - ; - if (S2 === 1) { - const p1div4 = (P2 + _1n$9) / _4n$1; - return function tonelliFast(Fp2, n2) { - const root2 = Fp2.pow(n2, p1div4); - if (!Fp2.eql(Fp2.sqr(root2), n2)) - throw new Error("Cannot find square root"); - return root2; - }; + // prettier-ignore + set(A2, B2, C2, D2, E2, F2, G2, H2) { + this.A = A2 | 0; + this.B = B2 | 0; + this.C = C2 | 0; + this.D = D2 | 0; + this.E = E2 | 0; + this.F = F2 | 0; + this.G = G2 | 0; + this.H = H2 | 0; } - const Q1div2 = (Q2 + _1n$9) / _2n$5; - return function tonelliSlow(Fp2, n2) { - if (Fp2.pow(n2, legendreC) === Fp2.neg(Fp2.ONE)) - throw new Error("Cannot find square root"); - let r2 = S2; - let g2 = Fp2.pow(Fp2.mul(Fp2.ONE, Z2), Q2); - let x2 = Fp2.pow(n2, Q1div2); - let b2 = Fp2.pow(n2, Q2); - while (!Fp2.eql(b2, Fp2.ONE)) { - if (Fp2.eql(b2, Fp2.ZERO)) - return Fp2.ZERO; - let m2 = 1; - for (let t2 = Fp2.sqr(b2); m2 < r2; m2++) { - if (Fp2.eql(t2, Fp2.ONE)) - break; - t2 = Fp2.sqr(t2); - } - const ge2 = Fp2.pow(g2, _1n$9 << BigInt(r2 - m2 - 1)); - g2 = Fp2.sqr(ge2); - x2 = Fp2.mul(x2, ge2); - b2 = Fp2.mul(b2, g2); - r2 = m2; + process(view, offset2) { + for (let i = 0; i < 16; i++, offset2 += 4) + SHA256_W$2[i] = view.getUint32(offset2, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W$2[i - 15]; + const W2 = SHA256_W$2[i - 2]; + const s0 = rotr$2(W15, 7) ^ rotr$2(W15, 18) ^ W15 >>> 3; + const s1 = rotr$2(W2, 17) ^ rotr$2(W2, 19) ^ W2 >>> 10; + SHA256_W$2[i] = s1 + SHA256_W$2[i - 7] + s0 + SHA256_W$2[i - 16] | 0; } - return x2; - }; -} -function FpSqrt$1(P2) { - if (P2 % _4n$1 === _3n$3) { - const p1div4 = (P2 + _1n$9) / _4n$1; - return function sqrt3mod4(Fp2, n2) { - const root2 = Fp2.pow(n2, p1div4); - if (!Fp2.eql(Fp2.sqr(root2), n2)) - throw new Error("Cannot find square root"); - return root2; - }; + let { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr$2(E2, 6) ^ rotr$2(E2, 11) ^ rotr$2(E2, 25); + const T12 = H2 + sigma1 + Chi$2(E2, F2, G2) + SHA256_K$2[i] + SHA256_W$2[i] | 0; + const sigma0 = rotr$2(A2, 2) ^ rotr$2(A2, 13) ^ rotr$2(A2, 22); + const T22 = sigma0 + Maj$2(A2, B2, C2) | 0; + H2 = G2; + G2 = F2; + F2 = E2; + E2 = D2 + T12 | 0; + D2 = C2; + C2 = B2; + B2 = A2; + A2 = T12 + T22 | 0; + } + A2 = A2 + this.A | 0; + B2 = B2 + this.B | 0; + C2 = C2 + this.C | 0; + D2 = D2 + this.D | 0; + E2 = E2 + this.E | 0; + F2 = F2 + this.F | 0; + G2 = G2 + this.G | 0; + H2 = H2 + this.H | 0; + this.set(A2, B2, C2, D2, E2, F2, G2, H2); } - if (P2 % _8n$1 === _5n$1) { - const c1 = (P2 - _5n$1) / _8n$1; - return function sqrt5mod8(Fp2, n2) { - const n22 = Fp2.mul(n2, _2n$5); - const v3 = Fp2.pow(n22, c1); - const nv = Fp2.mul(n2, v3); - const i = Fp2.mul(Fp2.mul(nv, _2n$5), v3); - const root2 = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); - if (!Fp2.eql(Fp2.sqr(root2), n2)) - throw new Error("Cannot find square root"); - return root2; - }; + roundClean() { + SHA256_W$2.fill(0); } - return tonelliShanks$1(P2); + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +}; +const sha256$4 = /* @__PURE__ */ wrapConstructor$2(() => new SHA256$2()); +function sha256$3(value, to_) { + const bytes2 = sha256$4(isHex(value, { strict: false }) ? toBytes$3(value) : value); + return bytes2; } -const FIELD_FIELDS$1 = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" -]; -function validateField$1(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "isSafeInteger", - BITS: "isSafeInteger" - }; - const opts = FIELD_FIELDS$1.reduce((map, val) => { - map[val] = "function"; - return map; - }, initial); - return validateObject$1(field, opts); +function commitmentToVersionedHash(parameters) { + const { commitment, version: version2 = 1 } = parameters; + const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes"); + const versionedHash = sha256$3(commitment); + versionedHash.set([version2], 0); + return to === "bytes" ? versionedHash : bytesToHex$3(versionedHash); } -function FpPow$1(f2, num, power) { - if (power < _0n$7) - throw new Error("Expected power > 0"); - if (power === _0n$7) - return f2.ONE; - if (power === _1n$9) - return num; - let p2 = f2.ONE; - let d2 = num; - while (power > _0n$7) { - if (power & _1n$9) - p2 = f2.mul(p2, d2); - d2 = f2.sqr(d2); - power >>= _1n$9; +function commitmentsToVersionedHashes(parameters) { + const { commitments, version: version2 } = parameters; + const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes"); + const hashes = []; + for (const commitment of commitments) { + hashes.push(commitmentToVersionedHash({ + commitment, + to, + version: version2 + })); } - return p2; + return hashes; } -function FpInvertBatch$1(f2, nums) { - const tmp = new Array(nums.length); - const lastMultiplied = nums.reduce((acc, num, i) => { - if (f2.is0(num)) - return acc; - tmp[i] = acc; - return f2.mul(acc, num); - }, f2.ONE); - const inverted = f2.inv(lastMultiplied); - nums.reduceRight((acc, num, i) => { - if (f2.is0(num)) - return acc; - tmp[i] = f2.mul(acc, tmp[i]); - return f2.mul(acc, num); - }, inverted); - return tmp; +const blobsPerTransaction = 6; +const bytesPerFieldElement = 32; +const fieldElementsPerBlob = 4096; +const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob; +const maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80). +1 - // zero byte (0x00) appended to each field element. +1 * fieldElementsPerBlob * blobsPerTransaction; +class BlobSizeTooLargeError extends BaseError$3 { + constructor({ maxSize, size: size2 }) { + super("Blob size is too large.", { + metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size2} bytes`], + name: "BlobSizeTooLargeError" + }); + } } -function nLength$1(n2, nBitLength) { - const _nBitLength = nBitLength !== void 0 ? nBitLength : n2.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; +class EmptyBlobError extends BaseError$3 { + constructor() { + super("Blob data must not be empty.", { name: "EmptyBlobError" }); + } } -function Field$1(ORDER, bitLen2, isLE2 = false, redef = {}) { - if (ORDER <= _0n$7) - throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); - const { nBitLength: BITS, nByteLength: BYTES } = nLength$1(ORDER, bitLen2); - if (BYTES > 2048) - throw new Error("Field lengths over 2048 bytes are not supported"); - const sqrtP = FpSqrt$1(ORDER); - const f2 = Object.freeze({ - ORDER, - BITS, - BYTES, - MASK: bitMask$1(BITS), - ZERO: _0n$7, - ONE: _1n$9, - create: (num) => mod$1(num, ORDER), - isValid: (num) => { - if (typeof num !== "bigint") - throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); - return _0n$7 <= num && num < ORDER; - }, - is0: (num) => num === _0n$7, - isOdd: (num) => (num & _1n$9) === _1n$9, - neg: (num) => mod$1(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod$1(num * num, ORDER), - add: (lhs, rhs) => mod$1(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod$1(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod$1(lhs * rhs, ORDER), - pow: (num, power) => FpPow$1(f2, num, power), - div: (lhs, rhs) => mod$1(lhs * invert$1(rhs, ORDER), ORDER), - // Same as above, but doesn't normalize - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert$1(num, ORDER), - sqrt: redef.sqrt || ((n2) => sqrtP(f2, n2)), - invertBatch: (lst) => FpInvertBatch$1(f2, lst), - // TODO: do we really need constant cmov? - // We don't have const-time bigints anyway, so probably will be not very useful - cmov: (a2, b2, c2) => c2 ? b2 : a2, - toBytes: (num) => isLE2 ? numberToBytesLE$1(num, BYTES) : numberToBytesBE$1(num, BYTES), - fromBytes: (bytes2) => { - if (bytes2.length !== BYTES) - throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`); - return isLE2 ? bytesToNumberLE$1(bytes2) : bytesToNumberBE$1(bytes2); +function toBlobs(parameters) { + const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes"); + const data = typeof parameters.data === "string" ? hexToBytes$2(parameters.data) : parameters.data; + const size_ = size$5(data); + if (!size_) + throw new EmptyBlobError(); + if (size_ > maxBytesPerTransaction) + throw new BlobSizeTooLargeError({ + maxSize: maxBytesPerTransaction, + size: size_ + }); + const blobs = []; + let active = true; + let position = 0; + while (active) { + const blob = createCursor(new Uint8Array(bytesPerBlob)); + let size2 = 0; + while (size2 < fieldElementsPerBlob) { + const bytes2 = data.slice(position, position + (bytesPerFieldElement - 1)); + blob.pushByte(0); + blob.pushBytes(bytes2); + if (bytes2.length < 31) { + blob.pushByte(128); + active = false; + break; + } + size2++; + position += 31; } - }); - return Object.freeze(f2); -} -function getFieldBytesLength$1(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); + blobs.push(blob); + } + return to === "bytes" ? blobs.map((x2) => x2.bytes) : blobs.map((x2) => bytesToHex$3(x2.bytes)); } -function getMinHashLength$1(fieldOrder) { - const length = getFieldBytesLength$1(fieldOrder); - return length + Math.ceil(length / 2); +function toBlobSidecars(parameters) { + const { data, kzg, to } = parameters; + const blobs = parameters.blobs ?? toBlobs({ data, to }); + const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to }); + const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to }); + const sidecars = []; + for (let i = 0; i < blobs.length; i++) + sidecars.push({ + blob: blobs[i], + commitment: commitments[i], + proof: proofs[i] + }); + return sidecars; } -function mapHashToField$1(key, fieldOrder, isLE2 = false) { - const len = key.length; - const fieldLen = getFieldBytesLength$1(fieldOrder); - const minLen = getMinHashLength$1(fieldOrder); - if (len < 16 || len < minLen || len > 1024) - throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); - const num = isLE2 ? bytesToNumberBE$1(key) : bytesToNumberLE$1(key); - const reduced = mod$1(num, fieldOrder - _1n$9) + _1n$9; - return isLE2 ? numberToBytesLE$1(reduced, fieldLen) : numberToBytesBE$1(reduced, fieldLen); +function getTransactionType(transaction2) { + if (transaction2.type) + return transaction2.type; + if (typeof transaction2.authorizationList !== "undefined") + return "eip7702"; + if (typeof transaction2.blobs !== "undefined" || typeof transaction2.blobVersionedHashes !== "undefined" || typeof transaction2.maxFeePerBlobGas !== "undefined" || typeof transaction2.sidecars !== "undefined") + return "eip4844"; + if (typeof transaction2.maxFeePerGas !== "undefined" || typeof transaction2.maxPriorityFeePerGas !== "undefined") { + return "eip1559"; + } + if (typeof transaction2.gasPrice !== "undefined") { + if (typeof transaction2.accessList !== "undefined") + return "eip2930"; + return "legacy"; + } + throw new InvalidSerializableTransactionError({ transaction: transaction2 }); } -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const _0n$6 = BigInt(0); -const _1n$8 = BigInt(1); -function wNAF$1(c2, bits) { - const constTimeNegate = (condition, item2) => { - const neg = item2.negate(); - return condition ? neg : item2; - }; - const opts = (W2) => { - const windows = Math.ceil(bits / W2) + 1; - const windowSize = 2 ** (W2 - 1); - return { windows, windowSize }; - }; - return { - constTimeNegate, - // non-const time multiplication ladder - unsafeLadder(elm, n2) { - let p2 = c2.ZERO; - let d2 = elm; - while (n2 > _0n$6) { - if (n2 & _1n$8) - p2 = p2.add(d2); - d2 = d2.double(); - n2 >>= _1n$8; - } - return p2; - }, - /** - * Creates a wNAF precomputation window. Used for caching. - * Default window size is set by `utils.precompute()` and is equal to 8. - * Number of precomputed points depends on the curve size: - * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: - * - 𝑊 is the window size - * - 𝑛 is the bitlength of the curve order. - * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. - * @returns precomputed point tables flattened to a single array - */ - precomputeWindow(elm, W2) { - const { windows, windowSize } = opts(W2); - const points = []; - let p2 = elm; - let base = p2; - for (let window2 = 0; window2 < windows; window2++) { - base = p2; - points.push(base); - for (let i = 1; i < windowSize; i++) { - base = base.add(p2); - points.push(base); - } - p2 = base.double(); - } - return points; - }, - /** - * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. - * @param W window size - * @param precomputes precomputed tables - * @param n scalar (we don't check here, but should be less than curve order) - * @returns real and fake (for const-time) points - */ - wNAF(W2, precomputes, n2) { - const { windows, windowSize } = opts(W2); - let p2 = c2.ZERO; - let f2 = c2.BASE; - const mask2 = BigInt(2 ** W2 - 1); - const maxNumber = 2 ** W2; - const shiftBy = BigInt(W2); - for (let window2 = 0; window2 < windows; window2++) { - const offset2 = window2 * windowSize; - let wbits = Number(n2 & mask2); - n2 >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n2 += _1n$8; - } - const offset1 = offset2; - const offset22 = offset2 + Math.abs(wbits) - 1; - const cond1 = window2 % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - f2 = f2.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p2 = p2.add(constTimeNegate(cond2, precomputes[offset22])); - } - } - return { p: p2, f: f2 }; - }, - wNAFCached(P2, precomputesMap, n2, transform) { - const W2 = P2._WINDOW_SIZE || 1; - let comp = precomputesMap.get(P2); - if (!comp) { - comp = this.precomputeWindow(P2, W2); - if (W2 !== 1) { - precomputesMap.set(P2, transform(comp)); - } - } - return this.wNAF(W2, comp, n2); - } - }; -} -function validateBasic$1(curve) { - validateField$1(curve.Fp); - validateObject$1(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...nLength$1(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); -} -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -function validatePointOpts$1(curve) { - const opts = validateBasic$1(curve); - validateObject$1(opts, { - a: "field", - b: "field" - }, { - allowedPrivateKeyLengths: "array", - wrapPrivateKey: "boolean", - isTorsionFree: "function", - clearCofactor: "function", - allowInfinityPoint: "boolean", - fromBytes: "function", - toBytes: "function" - }); - const { endo, Fp: Fp2, a: a2 } = opts; - if (endo) { - if (!Fp2.eql(a2, Fp2.ZERO)) { - throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); +const defaultParameters = [ + "blobVersionedHashes", + "chainId", + "fees", + "gas", + "nonce", + "type" +]; +async function prepareTransactionRequest(client2, args) { + const { account: account_ = client2.account, blobs, chain, gas, kzg, nonce, nonceManager, parameters = defaultParameters, type } = args; + const account2 = account_ ? parseAccount(account_) : void 0; + const request = { ...args, ...account2 ? { from: account2 == null ? void 0 : account2.address } : {} }; + let block; + async function getBlock$1() { + if (block) + return block; + block = await getAction$1(client2, getBlock, "getBlock")({ blockTag: "latest" }); + return block; + } + let chainId; + async function getChainId2() { + if (chainId) + return chainId; + if (chain) + return chain.id; + if (typeof args.chainId !== "undefined") + return args.chainId; + const chainId_ = await getAction$1(client2, getChainId$2, "getChainId")({}); + chainId = chainId_; + return chainId; + } + if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) { + const commitments = blobsToCommitments({ blobs, kzg }); + if (parameters.includes("blobVersionedHashes")) { + const versionedHashes = commitmentsToVersionedHashes({ + commitments, + to: "hex" + }); + request.blobVersionedHashes = versionedHashes; } - if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { - throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); + if (parameters.includes("sidecars")) { + const proofs = blobsToProofs({ blobs, commitments, kzg }); + const sidecars = toBlobSidecars({ + blobs, + commitments, + proofs, + to: "hex" + }); + request.sidecars = sidecars; } } - return Object.freeze({ ...opts }); -} -const { bytesToNumberBE: b2n$1, hexToBytes: h2b$1 } = ut$1; -const DER$1 = { - // asn.1 DER encoding utils - Err: class DERErr extends Error { - constructor(m2 = "") { - super(m2); + if (parameters.includes("chainId")) + request.chainId = await getChainId2(); + if (parameters.includes("nonce") && typeof nonce === "undefined" && account2) { + if (nonceManager) { + const chainId2 = await getChainId2(); + request.nonce = await nonceManager.consume({ + address: account2.address, + chainId: chainId2, + client: client2 + }); + } else { + request.nonce = await getAction$1(client2, getTransactionCount, "getTransactionCount")({ + address: account2.address, + blockTag: "pending" + }); } - }, - _parseInt(data) { - const { Err: E2 } = DER$1; - if (data.length < 2 || data[0] !== 2) - throw new E2("Invalid signature integer tag"); - const len = data[1]; - const res = data.subarray(2, len + 2); - if (!len || res.length !== len) - throw new E2("Invalid signature integer: wrong length"); - if (res[0] & 128) - throw new E2("Invalid signature integer: negative"); - if (res[0] === 0 && !(res[1] & 128)) - throw new E2("Invalid signature integer: unnecessary leading zero"); - return { d: b2n$1(res), l: data.subarray(len + 2) }; - }, - toSig(hex2) { - const { Err: E2 } = DER$1; - const data = typeof hex2 === "string" ? h2b$1(hex2) : hex2; - if (!(data instanceof Uint8Array)) - throw new Error("ui8a expected"); - let l2 = data.length; - if (l2 < 2 || data[0] != 48) - throw new E2("Invalid signature tag"); - if (data[1] !== l2 - 2) - throw new E2("Invalid signature: incorrect length"); - const { d: r2, l: sBytes } = DER$1._parseInt(data.subarray(2)); - const { d: s2, l: rBytesLeft } = DER$1._parseInt(sBytes); - if (rBytesLeft.length) - throw new E2("Invalid signature: left bytes after parsing"); - return { r: r2, s: s2 }; - }, - hexFromSig(sig) { - const slice2 = (s3) => Number.parseInt(s3[0], 16) & 8 ? "00" + s3 : s3; - const h2 = (num) => { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; - }; - const s2 = slice2(h2(sig.s)); - const r2 = slice2(h2(sig.r)); - const shl = s2.length / 2; - const rhl = r2.length / 2; - const sl2 = h2(shl); - const rl2 = h2(rhl); - return `30${h2(rhl + shl + 4)}02${rl2}${r2}02${sl2}${s2}`; - } -}; -const _0n$5 = BigInt(0), _1n$7 = BigInt(1); -BigInt(2); -const _3n$2 = BigInt(3); -BigInt(4); -function weierstrassPoints$1(opts) { - const CURVE = validatePointOpts$1(opts); - const { Fp: Fp2 } = CURVE; - const toBytes2 = CURVE.toBytes || ((_c2, point, _isCompressed) => { - const a2 = point.toAffine(); - return concatBytes$3(Uint8Array.from([4]), Fp2.toBytes(a2.x), Fp2.toBytes(a2.y)); - }); - const fromBytes = CURVE.fromBytes || ((bytes2) => { - const tail = bytes2.subarray(1); - const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x: x2, y: y2 }; - }); - function weierstrassEquation(x2) { - const { a: a2, b: b2 } = CURVE; - const x22 = Fp2.sqr(x2); - const x3 = Fp2.mul(x22, x2); - return Fp2.add(Fp2.add(x3, Fp2.mul(x2, a2)), b2); - } - if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error("bad generator point: equation left != right"); - function isWithinCurveOrder(num) { - return typeof num === "bigint" && _0n$5 < num && num < CURVE.n; - } - function assertGE(num) { - if (!isWithinCurveOrder(num)) - throw new Error("Expected valid bigint: 0 < bigint < curve.n"); } - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: n2 } = CURVE; - if (lengths && typeof key !== "bigint") { - if (key instanceof Uint8Array) - key = bytesToHex$3(key); - if (typeof key !== "string" || !lengths.includes(key.length)) - throw new Error("Invalid key"); - key = key.padStart(nByteLength * 2, "0"); - } - let num; + if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") { try { - num = typeof key === "bigint" ? key : bytesToNumberBE$1(ensureBytes$1("private key", key, nByteLength)); - } catch (error) { - throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + request.type = getTransactionType(request); + } catch { + const block2 = await getBlock$1(); + request.type = typeof (block2 == null ? void 0 : block2.baseFeePerGas) === "bigint" ? "eip1559" : "legacy"; } - if (wrapPrivateKey) - num = mod$1(num, n2); - assertGE(num); - return num; - } - const pointPrecomputes = /* @__PURE__ */ new Map(); - function assertPrjPoint(other) { - if (!(other instanceof Point)) - throw new Error("ProjectivePoint expected"); } - class Point { - constructor(px2, py, pz) { - this.px = px2; - this.py = py; - this.pz = pz; - if (px2 == null || !Fp2.isValid(px2)) - throw new Error("x required"); - if (py == null || !Fp2.isValid(py)) - throw new Error("y required"); - if (pz == null || !Fp2.isValid(pz)) - throw new Error("z required"); - } - // Does not validate if the point is on-curve. - // Use fromHex instead, or call assertValidity() later. - static fromAffine(p2) { - const { x: x2, y: y2 } = p2 || {}; - if (!p2 || !Fp2.isValid(x2) || !Fp2.isValid(y2)) - throw new Error("invalid affine point"); - if (p2 instanceof Point) - throw new Error("projective point not allowed"); - const is0 = (i) => Fp2.eql(i, Fp2.ZERO); - if (is0(x2) && is0(y2)) - return Point.ZERO; - return new Point(x2, y2, Fp2.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - /** - * Takes a bunch of Projective Points but executes only one - * inversion on all of them. Inversion is very slow operation, - * so this improves performance massively. - * Optimization: converts a list of projective points to a list of identical points with Z=1. - */ - static normalizeZ(points) { - const toInv = Fp2.invertBatch(points.map((p2) => p2.pz)); - return points.map((p2, i) => p2.toAffine(toInv[i])).map(Point.fromAffine); - } - /** - * Converts hash string or Uint8Array to Point. - * @param hex short/long ECDSA hex - */ - static fromHex(hex2) { - const P2 = Point.fromAffine(fromBytes(ensureBytes$1("pointHex", hex2))); - P2.assertValidity(); - return P2; - } - // Multiplies generator point by privateKey. - static fromPrivateKey(privateKey) { - return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - // "Private method", don't use it directly - _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes.delete(this); - } - // A point on curve is valid if it conforms to equation. - assertValidity() { - if (this.is0()) { - if (CURVE.allowInfinityPoint && !Fp2.is0(this.py)) - return; - throw new Error("bad point: ZERO"); + if (parameters.includes("fees")) { + if (request.type !== "legacy" && request.type !== "eip2930") { + if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") { + const block2 = await getBlock$1(); + const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client2, { + block: block2, + chain, + request + }); + if (typeof args.maxPriorityFeePerGas === "undefined" && args.maxFeePerGas && args.maxFeePerGas < maxPriorityFeePerGas) + throw new MaxFeePerGasTooLowError({ + maxPriorityFeePerGas + }); + request.maxPriorityFeePerGas = maxPriorityFeePerGas; + request.maxFeePerGas = maxFeePerGas; } - const { x: x2, y: y2 } = this.toAffine(); - if (!Fp2.isValid(x2) || !Fp2.isValid(y2)) - throw new Error("bad point: x or y not FE"); - const left = Fp2.sqr(y2); - const right = weierstrassEquation(x2); - if (!Fp2.eql(left, right)) - throw new Error("bad point: equation left != right"); - if (!this.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - } - hasEvenY() { - const { y: y2 } = this.toAffine(); - if (Fp2.isOdd) - return !Fp2.isOdd(y2); - throw new Error("Field doesn't support isOdd"); + } else { + if (typeof args.maxFeePerGas !== "undefined" || typeof args.maxPriorityFeePerGas !== "undefined") + throw new Eip1559FeesNotSupportedError(); + const block2 = await getBlock$1(); + const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client2, { + block: block2, + chain, + request, + type: "legacy" + }); + request.gasPrice = gasPrice_; } - /** - * Compare one point to another. - */ - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U12 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); - const U22 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); - return U12 && U22; + } + if (parameters.includes("gas") && typeof gas === "undefined") + request.gas = await getAction$1(client2, estimateGas, "estimateGas")({ + ...request, + account: account2 ? { address: account2.address, type: "json-rpc" } : void 0 + }); + assertRequest(request); + delete request.parameters; + return request; +} +async function sendRawTransaction(client2, { serializedTransaction }) { + return client2.request({ + method: "eth_sendRawTransaction", + params: [serializedTransaction] + }, { retryCount: 0 }); +} +async function sendTransaction$1(client2, parameters) { + var _a2, _b2, _c2, _d2; + const { account: account_ = client2.account, chain = client2.chain, accessList, authorizationList, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, ...rest } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/sendTransaction" + }); + const account2 = parseAccount(account_); + try { + assertRequest(parameters); + const to = await (async () => { + if (parameters.to) + return parameters.to; + if (authorizationList && authorizationList.length > 0) + return await recoverAuthorizationAddress({ + authorization: authorizationList[0] + }).catch(() => { + throw new BaseError$3("`to` is required. Could not infer from `authorizationList`."); + }); + return void 0; + })(); + if (account2.type === "json-rpc") { + let chainId; + if (chain !== null) { + chainId = await getAction$1(client2, getChainId$2, "getChainId")({}); + assertCurrentChain({ + currentChainId: chainId, + chain + }); + } + const chainFormat = (_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.transactionRequest) == null ? void 0 : _c2.format; + const format2 = chainFormat || formatTransactionRequest; + const request = format2({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + accessList, + authorizationList, + blobs, + chainId, + data, + from: account2.address, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to, + value + }); + return await client2.request({ + method: "eth_sendTransaction", + params: [request] + }, { retryCount: 0 }); } - /** - * Flips point to one corresponding to (x, -y) in Affine coordinates. - */ - negate() { - return new Point(this.px, Fp2.neg(this.py), this.pz); + if (account2.type === "local") { + const request = await getAction$1(client2, prepareTransactionRequest, "prepareTransactionRequest")({ + account: account2, + accessList, + authorizationList, + blobs, + chain, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + nonceManager: account2.nonceManager, + parameters: [...defaultParameters, "sidecars"], + value, + ...rest, + to + }); + const serializer = (_d2 = chain == null ? void 0 : chain.serializers) == null ? void 0 : _d2.transaction; + const serializedTransaction = await account2.signTransaction(request, { + serializer + }); + return await getAction$1(client2, sendRawTransaction, "sendRawTransaction")({ + serializedTransaction + }); } - // Renes-Costello-Batina exception-free doubling formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 3 - // Cost: 8M + 3S + 3*a + 2*b3 + 15add. - double() { - const { a: a2, b: b2 } = CURVE; - const b3 = Fp2.mul(b2, _3n$2); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - let t0 = Fp2.mul(X1, X1); - let t1 = Fp2.mul(Y1, Y1); - let t2 = Fp2.mul(Z1, Z1); - let t3 = Fp2.mul(X1, Y1); - t3 = Fp2.add(t3, t3); - Z3 = Fp2.mul(X1, Z1); - Z3 = Fp2.add(Z3, Z3); - X3 = Fp2.mul(a2, Z3); - Y3 = Fp2.mul(b3, t2); - Y3 = Fp2.add(X3, Y3); - X3 = Fp2.sub(t1, Y3); - Y3 = Fp2.add(t1, Y3); - Y3 = Fp2.mul(X3, Y3); - X3 = Fp2.mul(t3, X3); - Z3 = Fp2.mul(b3, Z3); - t2 = Fp2.mul(a2, t2); - t3 = Fp2.sub(t0, t2); - t3 = Fp2.mul(a2, t3); - t3 = Fp2.add(t3, Z3); - Z3 = Fp2.add(t0, t0); - t0 = Fp2.add(Z3, t0); - t0 = Fp2.add(t0, t2); - t0 = Fp2.mul(t0, t3); - Y3 = Fp2.add(Y3, t0); - t2 = Fp2.mul(Y1, Z1); - t2 = Fp2.add(t2, t2); - t0 = Fp2.mul(t2, t3); - X3 = Fp2.sub(X3, t0); - Z3 = Fp2.mul(t2, t1); - Z3 = Fp2.add(Z3, Z3); - Z3 = Fp2.add(Z3, Z3); - return new Point(X3, Y3, Z3); - } - // Renes-Costello-Batina exception-free addition formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 1 - // Cost: 12M + 0S + 3*a + 3*b3 + 23add. - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - const a2 = CURVE.a; - const b3 = Fp2.mul(CURVE.b, _3n$2); - let t0 = Fp2.mul(X1, X2); - let t1 = Fp2.mul(Y1, Y2); - let t2 = Fp2.mul(Z1, Z2); - let t3 = Fp2.add(X1, Y1); - let t4 = Fp2.add(X2, Y2); - t3 = Fp2.mul(t3, t4); - t4 = Fp2.add(t0, t1); - t3 = Fp2.sub(t3, t4); - t4 = Fp2.add(X1, Z1); - let t5 = Fp2.add(X2, Z2); - t4 = Fp2.mul(t4, t5); - t5 = Fp2.add(t0, t2); - t4 = Fp2.sub(t4, t5); - t5 = Fp2.add(Y1, Z1); - X3 = Fp2.add(Y2, Z2); - t5 = Fp2.mul(t5, X3); - X3 = Fp2.add(t1, t2); - t5 = Fp2.sub(t5, X3); - Z3 = Fp2.mul(a2, t4); - X3 = Fp2.mul(b3, t2); - Z3 = Fp2.add(X3, Z3); - X3 = Fp2.sub(t1, Z3); - Z3 = Fp2.add(t1, Z3); - Y3 = Fp2.mul(X3, Z3); - t1 = Fp2.add(t0, t0); - t1 = Fp2.add(t1, t0); - t2 = Fp2.mul(a2, t2); - t4 = Fp2.mul(b3, t4); - t1 = Fp2.add(t1, t2); - t2 = Fp2.sub(t0, t2); - t2 = Fp2.mul(a2, t2); - t4 = Fp2.add(t4, t2); - t0 = Fp2.mul(t1, t4); - Y3 = Fp2.add(Y3, t0); - t0 = Fp2.mul(t5, t4); - X3 = Fp2.mul(t3, X3); - X3 = Fp2.sub(X3, t0); - t0 = Fp2.mul(t3, t1); - Z3 = Fp2.mul(t5, Z3); - Z3 = Fp2.add(Z3, t0); - return new Point(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point.ZERO); - } - wNAF(n2) { - return wnaf.wNAFCached(this, pointPrecomputes, n2, (comp) => { - const toInv = Fp2.invertBatch(comp.map((p2) => p2.pz)); - return comp.map((p2, i) => p2.toAffine(toInv[i])).map(Point.fromAffine); + if (account2.type === "smart") + throw new AccountTypeNotSupportedError({ + metaMessages: [ + "Consider using the `sendUserOperation` Action instead." + ], + docsPath: "/docs/actions/bundler/sendUserOperation", + type: "smart" }); - } - /** - * Non-constant-time multiplication. Uses double-and-add algorithm. - * It's faster, but should only be used when you don't care about - * an exposed private key e.g. sig verification, which works over *public* keys. - */ - multiplyUnsafe(n2) { - const I2 = Point.ZERO; - if (n2 === _0n$5) - return I2; - assertGE(n2); - if (n2 === _1n$7) - return this; - const { endo } = CURVE; - if (!endo) - return wnaf.unsafeLadder(this, n2); - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n2); - let k1p = I2; - let k2p = I2; - let d2 = this; - while (k1 > _0n$5 || k2 > _0n$5) { - if (k1 & _1n$7) - k1p = k1p.add(d2); - if (k2 & _1n$7) - k2p = k2p.add(d2); - d2 = d2.double(); - k1 >>= _1n$7; - k2 >>= _1n$7; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - /** - * Constant time multiplication. - * Uses wNAF method. Windowed method may be 10% faster, - * but takes 2x longer to generate and consumes 2x memory. - * Uses precomputes when available. - * Uses endomorphism for Koblitz curves. - * @param scalar by which the point would be multiplied - * @returns New point - */ - multiply(scalar) { - assertGE(scalar); - let n2 = scalar; - let point, fake; - const { endo } = CURVE; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n2); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - const { p: p2, f: f2 } = this.wNAF(n2); - point = p2; - fake = f2; - } - return Point.normalizeZ([point, fake])[0]; - } - /** - * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. - * Not using Strauss-Shamir trick: precomputation tables are faster. - * The trick could be useful if both P and Q are not G (not in our case). - * @returns non-zero affine point - */ - multiplyAndAddUnsafe(Q2, a2, b2) { - const G2 = Point.BASE; - const mul = (P2, a3) => a3 === _0n$5 || a3 === _1n$7 || !P2.equals(G2) ? P2.multiplyUnsafe(a3) : P2.multiply(a3); - const sum = mul(this, a2).add(mul(Q2, b2)); - return sum.is0() ? void 0 : sum; - } - // Converts Projective point to affine (x, y) coordinates. - // Can accept precomputed Z^-1 - for example, from invertBatch. - // (x, y, z) ∋ (x=x/z, y=y/z) - toAffine(iz) { - const { px: x2, py: y2, pz: z2 } = this; - const is0 = this.is0(); - if (iz == null) - iz = is0 ? Fp2.ONE : Fp2.inv(z2); - const ax = Fp2.mul(x2, iz); - const ay = Fp2.mul(y2, iz); - const zz = Fp2.mul(z2, iz); - if (is0) - return { x: Fp2.ZERO, y: Fp2.ZERO }; - if (!Fp2.eql(zz, Fp2.ONE)) - throw new Error("invZ was invalid"); - return { x: ax, y: ay }; - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n$7) - return true; - if (isTorsionFree) - return isTorsionFree(Point, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n$7) - return this; - if (clearCofactor) - return clearCofactor(Point, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - this.assertValidity(); - return toBytes2(Point, this, isCompressed); - } - toHex(isCompressed = true) { - return bytesToHex$3(this.toRawBytes(isCompressed)); - } + throw new AccountTypeNotSupportedError({ + docsPath: "/docs/actions/wallet/sendTransaction", + type: account2.type + }); + } catch (err) { + if (err instanceof AccountTypeNotSupportedError) + throw err; + throw getTransactionError(err, { + ...parameters, + account: account2, + chain: parameters.chain || void 0 + }); } - Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE); - Point.ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF$1(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); - return { - CURVE, - ProjectivePoint: Point, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder - }; } -function validateOpts$1(curve) { - const opts = validateBasic$1(curve); - validateObject$1(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" +function deployContract(walletClient, parameters) { + const { abi: abi2, args, bytecode, ...request } = parameters; + const calldata = encodeDeployData({ abi: abi2, args, bytecode }); + return sendTransaction$1(walletClient, { + ...request, + data: calldata }); - return Object.freeze({ lowS: true, ...opts }); } -function weierstrass$1(curveDef) { - const CURVE = validateOpts$1(curveDef); - const { Fp: Fp2, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp2.BYTES + 1; - const uncompressedLen = 2 * Fp2.BYTES + 1; - function isValidFieldElement(num) { - return _0n$5 < num && num < Fp2.ORDER; +const multicall3Abi = [ + { + inputs: [ + { + components: [ + { + name: "target", + type: "address" + }, + { + name: "allowFailure", + type: "bool" + }, + { + name: "callData", + type: "bytes" + } + ], + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3", + outputs: [ + { + components: [ + { + name: "success", + type: "bool" + }, + { + name: "returnData", + type: "bytes" + } + ], + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "view", + type: "function" } - function modN(a2) { - return mod$1(a2, CURVE_ORDER); +]; +const universalResolverErrors = [ + { + inputs: [], + name: "ResolverNotFound", + type: "error" + }, + { + inputs: [], + name: "ResolverWildcardNotSupported", + type: "error" + }, + { + inputs: [], + name: "ResolverNotContract", + type: "error" + }, + { + inputs: [ + { + name: "returnData", + type: "bytes" + } + ], + name: "ResolverError", + type: "error" + }, + { + inputs: [ + { + components: [ + { + name: "status", + type: "uint16" + }, + { + name: "message", + type: "string" + } + ], + name: "errors", + type: "tuple[]" + } + ], + name: "HttpError", + type: "error" } - function invN(a2) { - return invert$1(a2, CURVE_ORDER); +]; +const universalResolverResolveAbi = [ + ...universalResolverErrors, + { + name: "resolve", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes" }, + { name: "data", type: "bytes" } + ], + outputs: [ + { name: "", type: "bytes" }, + { name: "address", type: "address" } + ] + }, + { + name: "resolve", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes" }, + { name: "data", type: "bytes" }, + { name: "gateways", type: "string[]" } + ], + outputs: [ + { name: "", type: "bytes" }, + { name: "address", type: "address" } + ] } - const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints$1({ - ...CURVE, - toBytes(_c2, point, isCompressed) { - const a2 = point.toAffine(); - const x2 = Fp2.toBytes(a2.x); - const cat = concatBytes$3; - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x2); - } else { - return cat(Uint8Array.from([4]), x2, Fp2.toBytes(a2.y)); - } - }, - fromBytes(bytes2) { - const len = bytes2.length; - const head = bytes2[0]; - const tail = bytes2.subarray(1); - if (len === compressedLen && (head === 2 || head === 3)) { - const x2 = bytesToNumberBE$1(tail); - if (!isValidFieldElement(x2)) - throw new Error("Point is not on curve"); - const y2 = weierstrassEquation(x2); - let y3 = Fp2.sqrt(y2); - const isYOdd = (y3 & _1n$7) === _1n$7; - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y3 = Fp2.neg(y3); - return { x: x2, y: y3 }; - } else if (len === uncompressedLen && head === 4) { - const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x: x2, y: y2 }; - } else { - throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); +]; +const universalResolverReverseAbi = [ + ...universalResolverErrors, + { + name: "reverse", + type: "function", + stateMutability: "view", + inputs: [{ type: "bytes", name: "reverseName" }], + outputs: [ + { type: "string", name: "resolvedName" }, + { type: "address", name: "resolvedAddress" }, + { type: "address", name: "reverseResolver" }, + { type: "address", name: "resolver" } + ] + }, + { + name: "reverse", + type: "function", + stateMutability: "view", + inputs: [ + { type: "bytes", name: "reverseName" }, + { type: "string[]", name: "gateways" } + ], + outputs: [ + { type: "string", name: "resolvedName" }, + { type: "address", name: "resolvedAddress" }, + { type: "address", name: "reverseResolver" }, + { type: "address", name: "resolver" } + ] + } +]; +const textResolverAbi = [ + { + name: "text", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes32" }, + { name: "key", type: "string" } + ], + outputs: [{ name: "", type: "string" }] + } +]; +const addressResolverAbi = [ + { + name: "addr", + type: "function", + stateMutability: "view", + inputs: [{ name: "name", type: "bytes32" }], + outputs: [{ name: "", type: "address" }] + }, + { + name: "addr", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes32" }, + { name: "coinType", type: "uint256" } + ], + outputs: [{ name: "", type: "bytes" }] + } +]; +const universalSignatureValidatorAbi = [ + { + inputs: [ + { + name: "_signer", + type: "address" + }, + { + name: "_hash", + type: "bytes32" + }, + { + name: "_signature", + type: "bytes" } - } - }); - const numToNByteStr = (num) => bytesToHex$3(numberToBytesBE$1(num, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number2) { - const HALF = CURVE_ORDER >> _1n$7; - return number2 > HALF; + ], + stateMutability: "nonpayable", + type: "constructor" } - function normalizeS(s2) { - return isBiggerThanHalfOrder(s2) ? modN(-s2) : s2; +]; +function bytesToBigInt(bytes2, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes2, { size: opts.size }); + const hex2 = bytesToHex$3(bytes2, opts); + return hexToBigInt(hex2, opts); +} +function bytesToBool(bytes_, opts = {}) { + let bytes2 = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes2, { size: opts.size }); + bytes2 = trim(bytes2); } - const slcNum = (b2, from, to) => bytesToNumberBE$1(b2.slice(from, to)); - class Signature2 { - constructor(r2, s2, recovery) { - this.r = r2; - this.s = s2; - this.recovery = recovery; - this.assertValidity(); - } - // pair (bytes of r, bytes of s) - static fromCompact(hex2) { - const l2 = CURVE.nByteLength; - hex2 = ensureBytes$1("compactSignature", hex2, l2 * 2); - return new Signature2(slcNum(hex2, 0, l2), slcNum(hex2, l2, 2 * l2)); - } - // DER encoded ECDSA signature - // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script - static fromDER(hex2) { - const { r: r2, s: s2 } = DER$1.toSig(ensureBytes$1("DER", hex2)); - return new Signature2(r2, s2); - } - assertValidity() { - if (!isWithinCurveOrder(this.r)) - throw new Error("r must be 0 < r < CURVE.n"); - if (!isWithinCurveOrder(this.s)) - throw new Error("s must be 0 < s < CURVE.n"); - } - addRecoveryBit(recovery) { - return new Signature2(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r: r2, s: s2, recovery: rec } = this; - const h2 = bits2int_modN(ensureBytes$1("msgHash", msgHash)); - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const radj = rec === 2 || rec === 3 ? r2 + CURVE.n : r2; - if (radj >= Fp2.ORDER) - throw new Error("recovery id 2 or 3 invalid"); - const prefix = (rec & 1) === 0 ? "02" : "03"; - const R2 = Point.fromHex(prefix + numToNByteStr(radj)); - const ir = invN(radj); - const u1 = modN(-h2 * ir); - const u2 = modN(s2 * ir); - const Q2 = Point.BASE.multiplyAndAddUnsafe(R2, u1, u2); - if (!Q2) - throw new Error("point at infinify"); - Q2.assertValidity(); - return Q2; - } - // Signatures should be low-s, to prevent malleability. - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature2(this.r, modN(-this.s), this.recovery) : this; - } - // DER-encoded - toDERRawBytes() { - return hexToBytes$2(this.toDERHex()); - } - toDERHex() { - return DER$1.hexFromSig({ r: this.r, s: this.s }); - } - // padded bytes of r, then padded bytes of s - toCompactRawBytes() { - return hexToBytes$2(this.toCompactHex()); - } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); - } - } - const utils2 = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } catch (error) { - return false; - } - }, - normPrivateKeyToScalar, - /** - * Produces cryptographically secure private key from random of size - * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. - */ - randomPrivateKey: () => { - const length = getMinHashLength$1(CURVE.n); - return mapHashToField$1(CURVE.randomBytes(length), CURVE.n); - }, - /** - * Creates precompute table for an arbitrary EC point. Makes point "cached". - * Allows to massively speed-up `point.multiply(scalar)`. - * @returns cached point - * @example - * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); - * fast.multiply(privKey); // much faster ECDH now - */ - precompute(windowSize = 8, point = Point.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); - return point; - } - }; - function getPublicKey(privateKey, isCompressed = true) { - return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - function isProbPub(item2) { - const arr = item2 instanceof Uint8Array; - const str = typeof item2 === "string"; - const len = (arr || str) && item2.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item2 instanceof Point) - return true; - return false; + if (bytes2.length > 1 || bytes2[0] > 1) + throw new InvalidBytesBooleanError(bytes2); + return Boolean(bytes2[0]); +} +function bytesToNumber(bytes2, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes2, { size: opts.size }); + const hex2 = bytesToHex$3(bytes2, opts); + return hexToNumber$2(hex2, opts); +} +function bytesToString(bytes_, opts = {}) { + let bytes2 = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes2, { size: opts.size }); + bytes2 = trim(bytes2, { dir: "right" }); } - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error("first arg must be private key"); - if (!isProbPub(publicB)) - throw new Error("second arg must be public key"); - const b2 = Point.fromHex(publicB); - return b2.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + return new TextDecoder().decode(bytes2); +} +function decodeAbiParameters(params, data) { + const bytes2 = typeof data === "string" ? hexToBytes$2(data) : data; + const cursor = createCursor(bytes2); + if (size$5(bytes2) === 0 && params.length > 0) + throw new AbiDecodingZeroDataError(); + if (size$5(data) && size$5(data) < 32) + throw new AbiDecodingDataSizeTooSmallError({ + data: typeof data === "string" ? data : bytesToHex$3(data), + params, + size: size$5(data) + }); + let consumed = 0; + const values = []; + for (let i = 0; i < params.length; ++i) { + const param = params[i]; + cursor.setPosition(consumed); + const [data2, consumed_] = decodeParameter(cursor, param, { + staticPosition: 0 + }); + consumed += consumed_; + values.push(data2); } - const bits2int = CURVE.bits2int || function(bytes2) { - const num = bytesToNumberBE$1(bytes2); - const delta = bytes2.length * 8 - CURVE.nBitLength; - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE.bits2int_modN || function(bytes2) { - return modN(bits2int(bytes2)); - }; - const ORDER_MASK = bitMask$1(CURVE.nBitLength); - function int2octets(num) { - if (typeof num !== "bigint") - throw new Error("bigint expected"); - if (!(_0n$5 <= num && num < ORDER_MASK)) - throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); - return numberToBytesBE$1(num, CURVE.nByteLength); + return values; +} +function decodeParameter(cursor, param, { staticPosition }) { + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return decodeArray(cursor, { ...param, type }, { length, staticPosition }); } - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (["recovered", "canonical"].some((k2) => k2 in opts)) - throw new Error("sign() legacy options not supported"); - const { hash: hash2, randomBytes: randomBytes2 } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; - msgHash = ensureBytes$1("msgHash", msgHash); - if (prehash) - msgHash = ensureBytes$1("prehashed msgHash", hash2(msgHash)); - const h1int = bits2int_modN(msgHash); - const d2 = normPrivateKeyToScalar(privateKey); - const seedArgs = [int2octets(d2), int2octets(h1int)]; - if (ent != null) { - const e2 = ent === true ? randomBytes2(Fp2.BYTES) : ent; - seedArgs.push(ensureBytes$1("extraEntropy", e2)); - } - const seed = concatBytes$3(...seedArgs); - const m2 = h1int; - function k2sig(kBytes) { - const k2 = bits2int(kBytes); - if (!isWithinCurveOrder(k2)) - return; - const ik2 = invN(k2); - const q2 = Point.BASE.multiply(k2).toAffine(); - const r2 = modN(q2.x); - if (r2 === _0n$5) - return; - const s2 = modN(ik2 * modN(m2 + r2 * d2)); - if (s2 === _0n$5) - return; - let recovery = (q2.x === r2 ? 0 : 2) | Number(q2.y & _1n$7); - let normS = s2; - if (lowS && isBiggerThanHalfOrder(s2)) { - normS = normalizeS(s2); - recovery ^= 1; - } - return new Signature2(r2, normS, recovery); + if (param.type === "tuple") + return decodeTuple(cursor, param, { staticPosition }); + if (param.type === "address") + return decodeAddress(cursor); + if (param.type === "bool") + return decodeBool(cursor); + if (param.type.startsWith("bytes")) + return decodeBytes(cursor, param, { staticPosition }); + if (param.type.startsWith("uint") || param.type.startsWith("int")) + return decodeNumber(cursor, param); + if (param.type === "string") + return decodeString(cursor, { staticPosition }); + throw new InvalidAbiDecodingTypeError(param.type, { + docsPath: "/docs/contract/decodeAbiParameters" + }); +} +const sizeOfLength = 32; +const sizeOfOffset = 32; +function decodeAddress(cursor) { + const value = cursor.readBytes(32); + return [checksumAddress(bytesToHex$3(sliceBytes(value, -20))), 32]; +} +function decodeArray(cursor, param, { length, staticPosition }) { + if (!length) { + const offset2 = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset2; + const startOfData = start + sizeOfLength; + cursor.setPosition(start); + const length2 = bytesToNumber(cursor.readBytes(sizeOfLength)); + const dynamicChild = hasDynamicChild(param); + let consumed2 = 0; + const value2 = []; + for (let i = 0; i < length2; ++i) { + cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: startOfData + }); + consumed2 += consumed_; + value2.push(data); } - return { seed, k2sig }; - } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); - const C2 = CURVE; - const drbg = createHmacDrbg$1(C2.hash.outputLen, C2.nByteLength, C2.hmac); - return drbg(seed, k2sig); + cursor.setPosition(staticPosition + 32); + return [value2, 32]; } - Point.BASE._setWindowSize(8); - function verify(signature2, msgHash, publicKey, opts = defaultVerOpts) { - var _a2; - const sg2 = signature2; - msgHash = ensureBytes$1("msgHash", msgHash); - publicKey = ensureBytes$1("publicKey", publicKey); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - const { lowS, prehash } = opts; - let _sig2 = void 0; - let P2; - try { - if (typeof sg2 === "string" || sg2 instanceof Uint8Array) { - try { - _sig2 = Signature2.fromDER(sg2); - } catch (derError) { - if (!(derError instanceof DER$1.Err)) - throw derError; - _sig2 = Signature2.fromCompact(sg2); - } - } else if (typeof sg2 === "object" && typeof sg2.r === "bigint" && typeof sg2.s === "bigint") { - const { r: r3, s: s3 } = sg2; - _sig2 = new Signature2(r3, s3); - } else { - throw new Error("PARSE"); - } - P2 = Point.fromHex(publicKey); - } catch (error) { - if (error.message === "PARSE") - throw new Error(`signature must be Signature instance, Uint8Array or hex string`); - return false; + if (hasDynamicChild(param)) { + const offset2 = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset2; + const value2 = []; + for (let i = 0; i < length; ++i) { + cursor.setPosition(start + i * 32); + const [data] = decodeParameter(cursor, param, { + staticPosition: start + }); + value2.push(data); } - if (lowS && _sig2.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r: r2, s: s2 } = _sig2; - const h2 = bits2int_modN(msgHash); - const is = invN(s2); - const u1 = modN(h2 * is); - const u2 = modN(r2 * is); - const R2 = (_a2 = Point.BASE.multiplyAndAddUnsafe(P2, u1, u2)) == null ? void 0 : _a2.toAffine(); - if (!R2) - return false; - const v3 = modN(R2.x); - return v3 === r2; + cursor.setPosition(staticPosition + 32); + return [value2, 32]; } - return { - CURVE, - getPublicKey, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point, - Signature: Signature2, - utils: utils2 - }; + let consumed = 0; + const value = []; + for (let i = 0; i < length; ++i) { + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: staticPosition + consumed + }); + consumed += consumed_; + value.push(data); + } + return [value, consumed]; } -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -function getHash$1(hash2) { - return { - hash: hash2, - hmac: (key, ...msgs) => hmac$2(hash2, key, concatBytes$4(...msgs)), - randomBytes: randomBytes$3 - }; +function decodeBool(cursor) { + return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]; } -function createCurve$1(curveDef, defHash) { - const create = (hash2) => weierstrass$1({ ...curveDef, ...getHash$1(hash2) }); - return Object.freeze({ ...create(defHash), create }); +function decodeBytes(cursor, param, { staticPosition }) { + const [_, size2] = param.type.split("bytes"); + if (!size2) { + const offset2 = bytesToNumber(cursor.readBytes(32)); + cursor.setPosition(staticPosition + offset2); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["0x", 32]; + } + const data = cursor.readBytes(length); + cursor.setPosition(staticPosition + 32); + return [bytesToHex$3(data), 32]; + } + const value = bytesToHex$3(cursor.readBytes(Number.parseInt(size2), 32)); + return [value, 32]; } -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const secp256k1P$1 = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); -const secp256k1N$1 = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); -const _1n$6 = BigInt(1); -const _2n$4 = BigInt(2); -const divNearest$1 = (a2, b2) => (a2 + b2 / _2n$4) / b2; -function sqrtMod$1(y2) { - const P2 = secp256k1P$1; - const _3n2 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y2 * y2 * y2 % P2; - const b3 = b2 * b2 * y2 % P2; - const b6 = pow2$1(b3, _3n2, P2) * b3 % P2; - const b9 = pow2$1(b6, _3n2, P2) * b3 % P2; - const b11 = pow2$1(b9, _2n$4, P2) * b2 % P2; - const b22 = pow2$1(b11, _11n, P2) * b11 % P2; - const b44 = pow2$1(b22, _22n, P2) * b22 % P2; - const b88 = pow2$1(b44, _44n, P2) * b44 % P2; - const b176 = pow2$1(b88, _88n, P2) * b88 % P2; - const b220 = pow2$1(b176, _44n, P2) * b44 % P2; - const b223 = pow2$1(b220, _3n2, P2) * b3 % P2; - const t1 = pow2$1(b223, _23n, P2) * b22 % P2; - const t2 = pow2$1(t1, _6n, P2) * b2 % P2; - const root2 = pow2$1(t2, _2n$4, P2); - if (!Fp$1.eql(Fp$1.sqr(root2), y2)) - throw new Error("Cannot find square root"); - return root2; +function decodeNumber(cursor, param) { + const signed2 = param.type.startsWith("int"); + const size2 = Number.parseInt(param.type.split("int")[1] || "256"); + const value = cursor.readBytes(32); + return [ + size2 > 48 ? bytesToBigInt(value, { signed: signed2 }) : bytesToNumber(value, { signed: signed2 }), + 32 + ]; } -const Fp$1 = Field$1(secp256k1P$1, void 0, void 0, { sqrt: sqrtMod$1 }); -const secp256k1$2 = createCurve$1({ - a: BigInt(0), - b: BigInt(7), - Fp: Fp$1, - n: secp256k1N$1, - // Base point (x, y) aka generator point - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - lowS: true, - /** - * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. - * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. - * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. - * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 - */ - endo: { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k2) => { - const n2 = secp256k1N$1; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n$6 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest$1(b2 * k2, n2); - const c2 = divNearest$1(-b1 * k2, n2); - let k1 = mod$1(k2 - c1 * a1 - c2 * a2, n2); - let k22 = mod$1(-c1 * b1 - c2 * b2, n2); - const k1neg = k1 > POW_2_128; - const k2neg = k22 > POW_2_128; - if (k1neg) - k1 = n2 - k1; - if (k2neg) - k22 = n2 - k22; - if (k1 > POW_2_128 || k22 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k2); - } - return { k1neg, k1, k2neg, k2: k22 }; +function decodeTuple(cursor, param, { staticPosition }) { + const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name: name2 }) => !name2); + const value = hasUnnamedChild ? [] : {}; + let consumed = 0; + if (hasDynamicChild(param)) { + const offset2 = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset2; + for (let i = 0; i < param.components.length; ++i) { + const component = param.components[i]; + cursor.setPosition(start + consumed); + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition: start + }); + consumed += consumed_; + value[hasUnnamedChild ? i : component == null ? void 0 : component.name] = data; } + cursor.setPosition(staticPosition + 32); + return [value, 32]; } -}, sha256$4); -BigInt(0); -secp256k1$2.ProjectivePoint; -const ZeroAddress = "0x0000000000000000000000000000000000000000"; -const ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"; -const N$1 = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); -const WeiPerEther = BigInt("1000000000000000000"); -const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -const MinInt256 = BigInt("0x8000000000000000000000000000000000000000000000000000000000000000") * BigInt(-1); -const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -const EtherSymbol = "Ξ"; -const MessagePrefix = "Ethereum Signed Message:\n"; -const BN_0$7 = BigInt(0); -const BN_1$3 = BigInt(1); -const BN_2$3 = BigInt(2); -const BN_27$1 = BigInt(27); -const BN_28$1 = BigInt(28); -const BN_35$1 = BigInt(35); -const _guard$3 = {}; -function toUint256(value) { - return zeroPadValue(toBeArray(value), 32); + for (let i = 0; i < param.components.length; ++i) { + const component = param.components[i]; + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition + }); + value[hasUnnamedChild ? i : component == null ? void 0 : component.name] = data; + consumed += consumed_; + } + return [value, consumed]; } -const _Signature = class _Signature { - /** - * @private - */ - constructor(guard2, r2, s2, v3) { - __privateAdd(this, _r); - __privateAdd(this, _s); - __privateAdd(this, _v); - __privateAdd(this, _networkV); - assertPrivate(guard2, _guard$3, "Signature"); - __privateSet(this, _r, r2); - __privateSet(this, _s, s2); - __privateSet(this, _v, v3); - __privateSet(this, _networkV, null); +function decodeString(cursor, { staticPosition }) { + const offset2 = bytesToNumber(cursor.readBytes(32)); + const start = staticPosition + offset2; + cursor.setPosition(start); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["", 32]; } - /** - * The ``r`` value for a signautre. - * - * This represents the ``x`` coordinate of a "reference" or - * challenge point, from which the ``y`` can be computed. - */ - get r() { - return __privateGet(this, _r); - } - set r(value) { - assertArgument(dataLength(value) === 32, "invalid r", "value", value); - __privateSet(this, _r, hexlify(value)); - } - /** - * The ``s`` value for a signature. - */ - get s() { - return __privateGet(this, _s); - } - set s(_value2) { - assertArgument(dataLength(_value2) === 32, "invalid s", "value", _value2); - const value = hexlify(_value2); - assertArgument(parseInt(value.substring(0, 3)) < 8, "non-canonical s", "value", value); - __privateSet(this, _s, value); + const data = cursor.readBytes(length, 32); + const value = bytesToString(trim(data)); + cursor.setPosition(staticPosition + 32); + return [value, 32]; +} +function hasDynamicChild(param) { + var _a2; + const { type } = param; + if (type === "string") + return true; + if (type === "bytes") + return true; + if (type.endsWith("[]")) + return true; + if (type === "tuple") + return (_a2 = param.components) == null ? void 0 : _a2.some(hasDynamicChild); + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] })) + return true; + return false; +} +const hash$1 = (value) => keccak256$1(toBytes$3(value)); +function hashSignature(sig) { + return hash$1(sig); +} +const version$8 = "1.0.5"; +let BaseError$2 = class BaseError2 extends Error { + constructor(shortMessage, args = {}) { + var _a2; + const details = args.cause instanceof BaseError2 ? args.cause.details : ((_a2 = args.cause) == null ? void 0 : _a2.message) ? args.cause.message : args.details; + const docsPath2 = args.cause instanceof BaseError2 ? args.cause.docsPath || args.docsPath : args.docsPath; + const message = [ + shortMessage || "An error occurred.", + "", + ...args.metaMessages ? [...args.metaMessages, ""] : [], + ...docsPath2 ? [`Docs: https://abitype.dev${docsPath2}`] : [], + ...details ? [`Details: ${details}`] : [], + `Version: abitype@${version$8}` + ].join("\n"); + super(message); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "docsPath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metaMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiTypeError" + }); + if (args.cause) + this.cause = args.cause; + this.details = details; + this.docsPath = docsPath2; + this.metaMessages = args.metaMessages; + this.shortMessage = shortMessage; } - /** - * The ``v`` value for a signature. - * - * Since a given ``x`` value for ``r`` has two possible values for - * its correspondin ``y``, the ``v`` indicates which of the two ``y`` - * values to use. - * - * It is normalized to the values ``27`` or ``28`` for legacy - * purposes. - */ - get v() { - return __privateGet(this, _v); +}; +function execTyped(regex, string) { + const match = regex.exec(string); + return match == null ? void 0 : match.groups; +} +const bytesRegex$1 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; +const integerRegex$1 = /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; +const isTupleRegex = /^\(.+?\).*?$/; +const tupleRegex = /^tuple(?(\[(\d*)\])*)$/; +function formatAbiParameter(abiParameter) { + let type = abiParameter.type; + if (tupleRegex.test(abiParameter.type) && "components" in abiParameter) { + type = "("; + const length = abiParameter.components.length; + for (let i = 0; i < length; i++) { + const component = abiParameter.components[i]; + type += formatAbiParameter(component); + if (i < length - 1) + type += ", "; + } + const result = execTyped(tupleRegex, abiParameter.type); + type += `)${(result == null ? void 0 : result.array) ?? ""}`; + return formatAbiParameter({ + ...abiParameter, + type + }); } - set v(value) { - const v3 = getNumber(value, "value"); - assertArgument(v3 === 27 || v3 === 28, "invalid v", "v", value); - __privateSet(this, _v, v3); + if ("indexed" in abiParameter && abiParameter.indexed) + type = `${type} indexed`; + if (abiParameter.name) + return `${type} ${abiParameter.name}`; + return type; +} +function formatAbiParameters(abiParameters) { + let params = ""; + const length = abiParameters.length; + for (let i = 0; i < length; i++) { + const abiParameter = abiParameters[i]; + params += formatAbiParameter(abiParameter); + if (i !== length - 1) + params += ", "; } - /** - * The EIP-155 ``v`` for legacy transactions. For non-legacy - * transactions, this value is ``null``. - */ - get networkV() { - return __privateGet(this, _networkV); + return params; +} +function formatAbiItem(abiItem) { + if (abiItem.type === "function") + return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== "nonpayable" ? ` ${abiItem.stateMutability}` : ""}${abiItem.outputs.length ? ` returns (${formatAbiParameters(abiItem.outputs)})` : ""}`; + if (abiItem.type === "event") + return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; + if (abiItem.type === "error") + return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; + if (abiItem.type === "constructor") + return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === "payable" ? " payable" : ""}`; + if (abiItem.type === "fallback") + return "fallback()"; + return "receive() external payable"; +} +const errorSignatureRegex = /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; +function isErrorSignature(signature2) { + return errorSignatureRegex.test(signature2); +} +function execErrorSignature(signature2) { + return execTyped(errorSignatureRegex, signature2); +} +const eventSignatureRegex = /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; +function isEventSignature(signature2) { + return eventSignatureRegex.test(signature2); +} +function execEventSignature(signature2) { + return execTyped(eventSignatureRegex, signature2); +} +const functionSignatureRegex = /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/; +function isFunctionSignature(signature2) { + return functionSignatureRegex.test(signature2); +} +function execFunctionSignature(signature2) { + return execTyped(functionSignatureRegex, signature2); +} +const structSignatureRegex = /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/; +function isStructSignature(signature2) { + return structSignatureRegex.test(signature2); +} +function execStructSignature(signature2) { + return execTyped(structSignatureRegex, signature2); +} +const constructorSignatureRegex = /^constructor\((?.*?)\)(?:\s(?payable{1}))?$/; +function isConstructorSignature(signature2) { + return constructorSignatureRegex.test(signature2); +} +function execConstructorSignature(signature2) { + return execTyped(constructorSignatureRegex, signature2); +} +const fallbackSignatureRegex = /^fallback\(\) external(?:\s(?payable{1}))?$/; +function isFallbackSignature(signature2) { + return fallbackSignatureRegex.test(signature2); +} +const receiveSignatureRegex = /^receive\(\) external payable$/; +function isReceiveSignature(signature2) { + return receiveSignatureRegex.test(signature2); +} +const eventModifiers = /* @__PURE__ */ new Set(["indexed"]); +const functionModifiers = /* @__PURE__ */ new Set([ + "calldata", + "memory", + "storage" +]); +class UnknownTypeError extends BaseError$2 { + constructor({ type }) { + super("Unknown type.", { + metaMessages: [ + `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownTypeError" + }); } - /** - * The chain ID for EIP-155 legacy transactions. For non-legacy - * transactions, this value is ``null``. - */ - get legacyChainId() { - const v3 = this.networkV; - if (v3 == null) { - return null; - } - return _Signature.getChainId(v3); +} +class UnknownSolidityTypeError extends BaseError$2 { + constructor({ type }) { + super("Unknown type.", { + metaMessages: [`Type "${type}" is not a valid ABI type.`] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownSolidityTypeError" + }); } - /** - * The ``yParity`` for the signature. - * - * See ``v`` for more details on how this value is used. - */ - get yParity() { - return this.v === 27 ? 0 : 1; +} +class InvalidParameterError extends BaseError$2 { + constructor({ param }) { + super("Invalid ABI parameter.", { + details: param + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidParameterError" + }); } - /** - * The [[link-eip-2098]] compact representation of the ``yParity`` - * and ``s`` compacted into a single ``bytes32``. - */ - get yParityAndS() { - const yParityAndS = getBytes(this.s); - if (this.yParity) { - yParityAndS[0] |= 128; - } - return hexlify(yParityAndS); +} +class SolidityProtectedKeywordError extends BaseError$2 { + constructor({ param, name: name2 }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `"${name2}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "SolidityProtectedKeywordError" + }); } - /** - * The [[link-eip-2098]] compact representation. - */ - get compactSerialized() { - return concat$1([this.r, this.yParityAndS]); +} +class InvalidModifierError extends BaseError$2 { + constructor({ param, type, modifier }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidModifierError" + }); } - /** - * The serialized representation. - */ - get serialized() { - return concat$1([this.r, this.s, this.yParity ? "0x1c" : "0x1b"]); +} +class InvalidFunctionModifierError extends BaseError$2 { + constructor({ param, type, modifier }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.`, + `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidFunctionModifierError" + }); } - [Symbol.for("nodejs.util.inspect.custom")]() { - return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`; +} +class InvalidAbiTypeParameterError extends BaseError$2 { + constructor({ abiParameter }) { + super("Invalid ABI parameter.", { + details: JSON.stringify(abiParameter, null, 2), + metaMessages: ["ABI parameter type is invalid."] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidAbiTypeParameterError" + }); } - /** - * Returns a new identical [[Signature]]. - */ - clone() { - const clone = new _Signature(_guard$3, this.r, this.s, this.v); - if (this.networkV) { - __privateSet(clone, _networkV, this.networkV); - } - return clone; +} +class InvalidSignatureError extends BaseError$2 { + constructor({ signature: signature2, type }) { + super(`Invalid ${type} signature.`, { + details: signature2 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidSignatureError" + }); } - /** - * Returns a representation that is compatible with ``JSON.stringify``. - */ - toJSON() { - const networkV = this.networkV; - return { - _type: "signature", - networkV: networkV != null ? networkV.toString() : null, - r: this.r, - s: this.s, - v: this.v - }; +} +class UnknownSignatureError extends BaseError$2 { + constructor({ signature: signature2 }) { + super("Unknown signature.", { + details: signature2 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownSignatureError" + }); } - /** - * Compute the chain ID from the ``v`` in a legacy EIP-155 transactions. - * - * @example: - * Signature.getChainId(45) - * //_result: - * - * Signature.getChainId(46) - * //_result: - */ - static getChainId(v3) { - const bv = getBigInt(v3, "v"); - if (bv == BN_27$1 || bv == BN_28$1) { - return BN_0$7; - } - assertArgument(bv >= BN_35$1, "invalid EIP-155 v", "v", v3); - return (bv - BN_35$1) / BN_2$3; +} +class InvalidStructSignatureError extends BaseError$2 { + constructor({ signature: signature2 }) { + super("Invalid struct signature.", { + details: signature2, + metaMessages: ["No properties exist."] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidStructSignatureError" + }); } - /** - * Compute the ``v`` for a chain ID for a legacy EIP-155 transactions. - * - * Legacy transactions which use [[link-eip-155]] hijack the ``v`` - * property to include the chain ID. - * - * @example: - * Signature.getChainIdV(5, 27) - * //_result: - * - * Signature.getChainIdV(5, 28) - * //_result: - * - */ - static getChainIdV(chainId, v3) { - return getBigInt(chainId) * BN_2$3 + BigInt(35 + v3 - 27); +} +class CircularReferenceError extends BaseError$2 { + constructor({ type }) { + super("Circular reference detected.", { + metaMessages: [`Struct "${type}" is a circular reference.`] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "CircularReferenceError" + }); } - /** - * Compute the normalized legacy transaction ``v`` from a ``yParirty``, - * a legacy transaction ``v`` or a legacy [[link-eip-155]] transaction. - * - * @example: - * // The values 0 and 1 imply v is actually yParity - * Signature.getNormalizedV(0) - * //_result: - * - * // Legacy non-EIP-1559 transaction (i.e. 27 or 28) - * Signature.getNormalizedV(27) - * //_result: - * - * // Legacy EIP-155 transaction (i.e. >= 35) - * Signature.getNormalizedV(46) - * //_result: - * - * // Invalid values throw - * Signature.getNormalizedV(5) - * //_error: - */ - static getNormalizedV(v3) { - const bv = getBigInt(v3); - if (bv === BN_0$7 || bv === BN_27$1) { - return 27; - } - if (bv === BN_1$3 || bv === BN_28$1) { - return 28; - } - assertArgument(bv >= BN_35$1, "invalid v", "v", v3); - return bv & BN_1$3 ? 27 : 28; +} +class InvalidParenthesisError extends BaseError$2 { + constructor({ current, depth }) { + super("Unbalanced parentheses.", { + metaMessages: [ + `"${current.trim()}" has too many ${depth > 0 ? "opening" : "closing"} parentheses.` + ], + details: `Depth "${depth}"` + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidParenthesisError" + }); } - /** - * Creates a new [[Signature]]. - * - * If no %%sig%% is provided, a new [[Signature]] is created - * with default values. - * - * If %%sig%% is a string, it is parsed. - */ - static from(sig) { - function assertError(check, message) { - assertArgument(check, message, "signature", sig); - } - if (sig == null) { - return new _Signature(_guard$3, ZeroHash, ZeroHash, 27); - } - if (typeof sig === "string") { - const bytes2 = getBytes(sig, "signature"); - if (bytes2.length === 64) { - const r3 = hexlify(bytes2.slice(0, 32)); - const s3 = bytes2.slice(32, 64); - const v5 = s3[0] & 128 ? 28 : 27; - s3[0] &= 127; - return new _Signature(_guard$3, r3, hexlify(s3), v5); - } - if (bytes2.length === 65) { - const r3 = hexlify(bytes2.slice(0, 32)); - const s3 = bytes2.slice(32, 64); - assertError((s3[0] & 128) === 0, "non-canonical s"); - const v5 = _Signature.getNormalizedV(bytes2[64]); - return new _Signature(_guard$3, r3, hexlify(s3), v5); - } - assertError(false, "invalid raw signature length"); - } - if (sig instanceof _Signature) { - return sig.clone(); +} +function getParameterCacheKey(param, type) { + if (type) + return `${type}:${param}`; + return param; +} +const parameterCache = /* @__PURE__ */ new Map([ + // Unnamed + ["address", { type: "address" }], + ["bool", { type: "bool" }], + ["bytes", { type: "bytes" }], + ["bytes32", { type: "bytes32" }], + ["int", { type: "int256" }], + ["int256", { type: "int256" }], + ["string", { type: "string" }], + ["uint", { type: "uint256" }], + ["uint8", { type: "uint8" }], + ["uint16", { type: "uint16" }], + ["uint24", { type: "uint24" }], + ["uint32", { type: "uint32" }], + ["uint64", { type: "uint64" }], + ["uint96", { type: "uint96" }], + ["uint112", { type: "uint112" }], + ["uint160", { type: "uint160" }], + ["uint192", { type: "uint192" }], + ["uint256", { type: "uint256" }], + // Named + ["address owner", { type: "address", name: "owner" }], + ["address to", { type: "address", name: "to" }], + ["bool approved", { type: "bool", name: "approved" }], + ["bytes _data", { type: "bytes", name: "_data" }], + ["bytes data", { type: "bytes", name: "data" }], + ["bytes signature", { type: "bytes", name: "signature" }], + ["bytes32 hash", { type: "bytes32", name: "hash" }], + ["bytes32 r", { type: "bytes32", name: "r" }], + ["bytes32 root", { type: "bytes32", name: "root" }], + ["bytes32 s", { type: "bytes32", name: "s" }], + ["string name", { type: "string", name: "name" }], + ["string symbol", { type: "string", name: "symbol" }], + ["string tokenURI", { type: "string", name: "tokenURI" }], + ["uint tokenId", { type: "uint256", name: "tokenId" }], + ["uint8 v", { type: "uint8", name: "v" }], + ["uint256 balance", { type: "uint256", name: "balance" }], + ["uint256 tokenId", { type: "uint256", name: "tokenId" }], + ["uint256 value", { type: "uint256", name: "value" }], + // Indexed + [ + "event:address indexed from", + { type: "address", name: "from", indexed: true } + ], + ["event:address indexed to", { type: "address", name: "to", indexed: true }], + [ + "event:uint indexed tokenId", + { type: "uint256", name: "tokenId", indexed: true } + ], + [ + "event:uint256 indexed tokenId", + { type: "uint256", name: "tokenId", indexed: true } + ] +]); +function parseSignature(signature2, structs = {}) { + if (isFunctionSignature(signature2)) { + const match = execFunctionSignature(signature2); + if (!match) + throw new InvalidSignatureError({ signature: signature2, type: "function" }); + const inputParams = splitParameters(match.parameters); + const inputs = []; + const inputLength = inputParams.length; + for (let i = 0; i < inputLength; i++) { + inputs.push(parseAbiParameter(inputParams[i], { + modifiers: functionModifiers, + structs, + type: "function" + })); } - const _r2 = sig.r; - assertError(_r2 != null, "missing r"); - const r2 = toUint256(_r2); - const s2 = function(s3, yParityAndS) { - if (s3 != null) { - return toUint256(s3); - } - if (yParityAndS != null) { - assertError(isHexString(yParityAndS, 32), "invalid yParityAndS"); - const bytes2 = getBytes(yParityAndS); - bytes2[0] &= 127; - return hexlify(bytes2); - } - assertError(false, "missing s"); - }(sig.s, sig.yParityAndS); - assertError((getBytes(s2)[0] & 128) == 0, "non-canonical s"); - const { networkV, v: v3 } = function(_v2, yParityAndS, yParity) { - if (_v2 != null) { - const v5 = getBigInt(_v2); - return { - networkV: v5 >= BN_35$1 ? v5 : void 0, - v: _Signature.getNormalizedV(v5) - }; - } - if (yParityAndS != null) { - assertError(isHexString(yParityAndS, 32), "invalid yParityAndS"); - return { v: getBytes(yParityAndS)[0] & 128 ? 28 : 27 }; - } - if (yParity != null) { - switch (getNumber(yParity, "sig.yParity")) { - case 0: - return { v: 27 }; - case 1: - return { v: 28 }; - } - assertError(false, "invalid yParity"); + const outputs = []; + if (match.returns) { + const outputParams = splitParameters(match.returns); + const outputLength = outputParams.length; + for (let i = 0; i < outputLength; i++) { + outputs.push(parseAbiParameter(outputParams[i], { + modifiers: functionModifiers, + structs, + type: "function" + })); } - assertError(false, "missing v"); - }(sig.v, sig.yParityAndS, sig.yParity); - const result = new _Signature(_guard$3, r2, s2, v3); - if (networkV) { - __privateSet(result, _networkV, networkV); } - assertError(sig.yParity == null || getNumber(sig.yParity, "sig.yParity") === result.yParity, "yParity mismatch"); - assertError(sig.yParityAndS == null || sig.yParityAndS === result.yParityAndS, "yParityAndS mismatch"); - return result; - } -}; -_r = new WeakMap(); -_s = new WeakMap(); -_v = new WeakMap(); -_networkV = new WeakMap(); -let Signature = _Signature; -const _SigningKey = class _SigningKey { - /** - * Creates a new **SigningKey** for %%privateKey%%. - */ - constructor(privateKey) { - __privateAdd(this, _privateKey); - assertArgument(dataLength(privateKey) === 32, "invalid private key", "privateKey", "[REDACTED]"); - __privateSet(this, _privateKey, hexlify(privateKey)); - } - /** - * The private key. - */ - get privateKey() { - return __privateGet(this, _privateKey); - } - /** - * The uncompressed public key. - * - * This will always begin with the prefix ``0x04`` and be 132 - * characters long (the ``0x`` prefix and 130 hexadecimal nibbles). - */ - get publicKey() { - return _SigningKey.computePublicKey(__privateGet(this, _privateKey)); - } - /** - * The compressed public key. - * - * This will always begin with either the prefix ``0x02`` or ``0x03`` - * and be 68 characters long (the ``0x`` prefix and 33 hexadecimal - * nibbles) - */ - get compressedPublicKey() { - return _SigningKey.computePublicKey(__privateGet(this, _privateKey), true); - } - /** - * Return the signature of the signed %%digest%%. - */ - sign(digest) { - assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest); - const sig = secp256k1$2.sign(getBytesCopy(digest), getBytesCopy(__privateGet(this, _privateKey)), { - lowS: true - }); - return Signature.from({ - r: toBeHex(sig.r, 32), - s: toBeHex(sig.s, 32), - v: sig.recovery ? 28 : 27 - }); + return { + name: match.name, + type: "function", + stateMutability: match.stateMutability ?? "nonpayable", + inputs, + outputs + }; } - /** - * Returns the [[link-wiki-ecdh]] shared secret between this - * private key and the %%other%% key. - * - * The %%other%% key may be any type of key, a raw public key, - * a compressed/uncompressed pubic key or aprivate key. - * - * Best practice is usually to use a cryptographic hash on the - * returned value before using it as a symetric secret. - * - * @example: - * sign1 = new SigningKey(id("some-secret-1")) - * sign2 = new SigningKey(id("some-secret-2")) - * - * // Notice that privA.computeSharedSecret(pubB)... - * sign1.computeSharedSecret(sign2.publicKey) - * //_result: - * - * // ...is equal to privB.computeSharedSecret(pubA). - * sign2.computeSharedSecret(sign1.publicKey) - * //_result: - */ - computeSharedSecret(other) { - const pubKey = _SigningKey.computePublicKey(other); - return hexlify(secp256k1$2.getSharedSecret(getBytesCopy(__privateGet(this, _privateKey)), getBytes(pubKey), false)); + if (isEventSignature(signature2)) { + const match = execEventSignature(signature2); + if (!match) + throw new InvalidSignatureError({ signature: signature2, type: "event" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) { + abiParameters.push(parseAbiParameter(params[i], { + modifiers: eventModifiers, + structs, + type: "event" + })); + } + return { name: match.name, type: "event", inputs: abiParameters }; } - /** - * Compute the public key for %%key%%, optionally %%compressed%%. - * - * The %%key%% may be any type of key, a raw public key, a - * compressed/uncompressed public key or private key. - * - * @example: - * sign = new SigningKey(id("some-secret")); - * - * // Compute the uncompressed public key for a private key - * SigningKey.computePublicKey(sign.privateKey) - * //_result: - * - * // Compute the compressed public key for a private key - * SigningKey.computePublicKey(sign.privateKey, true) - * //_result: - * - * // Compute the uncompressed public key - * SigningKey.computePublicKey(sign.publicKey, false); - * //_result: - * - * // Compute the Compressed a public key - * SigningKey.computePublicKey(sign.publicKey, true); - * //_result: - */ - static computePublicKey(key, compressed) { - let bytes2 = getBytes(key, "key"); - if (bytes2.length === 32) { - const pubKey = secp256k1$2.getPublicKey(bytes2, !!compressed); - return hexlify(pubKey); + if (isErrorSignature(signature2)) { + const match = execErrorSignature(signature2); + if (!match) + throw new InvalidSignatureError({ signature: signature2, type: "error" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) { + abiParameters.push(parseAbiParameter(params[i], { structs, type: "error" })); } - if (bytes2.length === 64) { - const pub = new Uint8Array(65); - pub[0] = 4; - pub.set(bytes2, 1); - bytes2 = pub; + return { name: match.name, type: "error", inputs: abiParameters }; + } + if (isConstructorSignature(signature2)) { + const match = execConstructorSignature(signature2); + if (!match) + throw new InvalidSignatureError({ signature: signature2, type: "constructor" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) { + abiParameters.push(parseAbiParameter(params[i], { structs, type: "constructor" })); } - const point = secp256k1$2.ProjectivePoint.fromHex(bytes2); - return hexlify(point.toRawBytes(compressed)); + return { + type: "constructor", + stateMutability: match.stateMutability ?? "nonpayable", + inputs: abiParameters + }; } - /** - * Returns the public key for the private key which produced the - * %%signature%% for the given %%digest%%. - * - * @example: - * key = new SigningKey(id("some-secret")) - * digest = id("hello world") - * sig = key.sign(digest) - * - * // Notice the signer public key... - * key.publicKey - * //_result: - * - * // ...is equal to the recovered public key - * SigningKey.recoverPublicKey(digest, sig) - * //_result: - * - */ - static recoverPublicKey(digest, signature2) { - assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest); - const sig = Signature.from(signature2); - let secpSig = secp256k1$2.Signature.fromCompact(getBytesCopy(concat$1([sig.r, sig.s]))); - secpSig = secpSig.addRecoveryBit(sig.yParity); - const pubKey = secpSig.recoverPublicKey(getBytesCopy(digest)); - assertArgument(pubKey != null, "invalid signautre for digest", "signature", signature2); - return "0x" + pubKey.toHex(false); + if (isFallbackSignature(signature2)) + return { type: "fallback" }; + if (isReceiveSignature(signature2)) + return { + type: "receive", + stateMutability: "payable" + }; + throw new UnknownSignatureError({ signature: signature2 }); +} +const abiParameterWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; +const abiParameterWithTupleRegex = /^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; +const dynamicIntegerRegex = /^u?int$/; +function parseAbiParameter(param, options) { + var _a2, _b2; + const parameterCacheKey = getParameterCacheKey(param, options == null ? void 0 : options.type); + if (parameterCache.has(parameterCacheKey)) + return parameterCache.get(parameterCacheKey); + const isTuple = isTupleRegex.test(param); + const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param); + if (!match) + throw new InvalidParameterError({ param }); + if (match.name && isSolidityKeyword(match.name)) + throw new SolidityProtectedKeywordError({ param, name: match.name }); + const name2 = match.name ? { name: match.name } : {}; + const indexed = match.modifier === "indexed" ? { indexed: true } : {}; + const structs = (options == null ? void 0 : options.structs) ?? {}; + let type; + let components = {}; + if (isTuple) { + type = "tuple"; + const params = splitParameters(match.type); + const components_ = []; + const length = params.length; + for (let i = 0; i < length; i++) { + components_.push(parseAbiParameter(params[i], { structs })); + } + components = { components: components_ }; + } else if (match.type in structs) { + type = "tuple"; + components = { components: structs[match.type] }; + } else if (dynamicIntegerRegex.test(match.type)) { + type = `${match.type}256`; + } else { + type = match.type; + if (!((options == null ? void 0 : options.type) === "struct") && !isSolidityType(type)) + throw new UnknownSolidityTypeError({ type }); } - /** - * Returns the point resulting from adding the ellipic curve points - * %%p0%% and %%p1%%. - * - * This is not a common function most developers should require, but - * can be useful for certain privacy-specific techniques. - * - * For example, it is used by [[HDNodeWallet]] to compute child - * addresses from parent public keys and chain codes. - */ - static addPoints(p0, p1, compressed) { - const pub0 = secp256k1$2.ProjectivePoint.fromHex(_SigningKey.computePublicKey(p0).substring(2)); - const pub1 = secp256k1$2.ProjectivePoint.fromHex(_SigningKey.computePublicKey(p1).substring(2)); - return "0x" + pub0.add(pub1).toHex(!!compressed); + if (match.modifier) { + if (!((_b2 = (_a2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _a2.has) == null ? void 0 : _b2.call(_a2, match.modifier))) + throw new InvalidModifierError({ + param, + type: options == null ? void 0 : options.type, + modifier: match.modifier + }); + if (functionModifiers.has(match.modifier) && !isValidDataLocation(type, !!match.array)) + throw new InvalidFunctionModifierError({ + param, + type: options == null ? void 0 : options.type, + modifier: match.modifier + }); } -}; -_privateKey = new WeakMap(); -let SigningKey = _SigningKey; -function lock() { - computeHmac.lock(); - keccak256$1.lock(); - pbkdf2.lock(); - randomBytes$1.lock(); - ripemd160.lock(); - scrypt.lock(); - scryptSync.lock(); - sha256$3.lock(); - sha512.lock(); - randomBytes$1.lock(); + const abiParameter = { + type: `${type}${match.array ?? ""}`, + ...name2, + ...indexed, + ...components + }; + parameterCache.set(parameterCacheKey, abiParameter); + return abiParameter; } -const BN_0$6 = BigInt(0); -const BN_36 = BigInt(36); -function getChecksumAddress(address) { - address = address.toLowerCase(); - const chars = address.substring(2).split(""); - const expanded = new Uint8Array(40); - for (let i = 0; i < 40; i++) { - expanded[i] = chars[i].charCodeAt(0); - } - const hashed = getBytes(keccak256$1(expanded)); - for (let i = 0; i < 40; i += 2) { - if (hashed[i >> 1] >> 4 >= 8) { - chars[i] = chars[i].toUpperCase(); - } - if ((hashed[i >> 1] & 15) >= 8) { - chars[i + 1] = chars[i + 1].toUpperCase(); +function splitParameters(params, result = [], current = "", depth = 0) { + const length = params.trim().length; + for (let i = 0; i < length; i++) { + const char = params[i]; + const tail = params.slice(i + 1); + switch (char) { + case ",": + return depth === 0 ? splitParameters(tail, [...result, current.trim()]) : splitParameters(tail, result, `${current}${char}`, depth); + case "(": + return splitParameters(tail, result, `${current}${char}`, depth + 1); + case ")": + return splitParameters(tail, result, `${current}${char}`, depth - 1); + default: + return splitParameters(tail, result, `${current}${char}`, depth); } } - return "0x" + chars.join(""); -} -const ibanLookup = {}; -for (let i = 0; i < 10; i++) { - ibanLookup[String(i)] = String(i); + if (current === "") + return result; + if (depth !== 0) + throw new InvalidParenthesisError({ current, depth }); + result.push(current.trim()); + return result; } -for (let i = 0; i < 26; i++) { - ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); +function isSolidityType(type) { + return type === "address" || type === "bool" || type === "function" || type === "string" || bytesRegex$1.test(type) || integerRegex$1.test(type); } -const safeDigits = 15; -function ibanChecksum(address) { - address = address.toUpperCase(); - address = address.substring(4) + address.substring(0, 2) + "00"; - let expanded = address.split("").map((c2) => { - return ibanLookup[c2]; - }).join(""); - while (expanded.length >= safeDigits) { - let block = expanded.substring(0, safeDigits); - expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); - } - let checksum2 = String(98 - parseInt(expanded, 10) % 97); - while (checksum2.length < 2) { - checksum2 = "0" + checksum2; - } - return checksum2; +const protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/; +function isSolidityKeyword(name2) { + return name2 === "address" || name2 === "bool" || name2 === "function" || name2 === "string" || name2 === "tuple" || bytesRegex$1.test(name2) || integerRegex$1.test(name2) || protectedKeywordsRegex.test(name2); } -const Base36 = function() { - const result = {}; - for (let i = 0; i < 36; i++) { - const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i]; - result[key] = BigInt(i); - } - return result; -}(); -function fromBase36(value) { - value = value.toLowerCase(); - let result = BN_0$6; - for (let i = 0; i < value.length; i++) { - result = result * BN_36 + Base36[value[i]]; - } - return result; +function isValidDataLocation(type, isArray2) { + return isArray2 || type === "bytes" || type === "string" || type === "tuple"; } -function getAddress$1(address) { - assertArgument(typeof address === "string", "invalid address", "address", address); - if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { - if (!address.startsWith("0x")) { - address = "0x" + address; - } - const result = getChecksumAddress(address); - assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, "bad address checksum", "address", address); - return result; - } - if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { - assertArgument(address.substring(2, 4) === ibanChecksum(address), "bad icap checksum", "address", address); - let result = fromBase36(address.substring(4)).toString(16); - while (result.length < 40) { - result = "0" + result; +function parseStructs(signatures) { + const shallowStructs = {}; + const signaturesLength = signatures.length; + for (let i = 0; i < signaturesLength; i++) { + const signature2 = signatures[i]; + if (!isStructSignature(signature2)) + continue; + const match = execStructSignature(signature2); + if (!match) + throw new InvalidSignatureError({ signature: signature2, type: "struct" }); + const properties = match.properties.split(";"); + const components = []; + const propertiesLength = properties.length; + for (let k2 = 0; k2 < propertiesLength; k2++) { + const property = properties[k2]; + const trimmed = property.trim(); + if (!trimmed) + continue; + const abiParameter = parseAbiParameter(trimmed, { + type: "struct" + }); + components.push(abiParameter); } - return getChecksumAddress("0x" + result); - } - assertArgument(false, "invalid address", "address", address); -} -function getIcapAddress(address) { - let base36 = BigInt(getAddress$1(address)).toString(36).toUpperCase(); - while (base36.length < 30) { - base36 = "0" + base36; + if (!components.length) + throw new InvalidStructSignatureError({ signature: signature2 }); + shallowStructs[match.name] = components; } - return "XE" + ibanChecksum("XE00" + base36) + base36; -} -function getCreateAddress(tx) { - const from = getAddress$1(tx.from); - const nonce = getBigInt(tx.nonce, "tx.nonce"); - let nonceHex = nonce.toString(16); - if (nonceHex === "0") { - nonceHex = "0x"; - } else if (nonceHex.length % 2) { - nonceHex = "0x0" + nonceHex; - } else { - nonceHex = "0x" + nonceHex; + const resolvedStructs = {}; + const entries = Object.entries(shallowStructs); + const entriesLength = entries.length; + for (let i = 0; i < entriesLength; i++) { + const [name2, parameters] = entries[i]; + resolvedStructs[name2] = resolveStructs(parameters, shallowStructs); } - return getAddress$1(dataSlice(keccak256$1(encodeRlp([from, nonceHex])), 12)); -} -function getCreate2Address(_from, _salt, _initCodeHash) { - const from = getAddress$1(_from); - const salt = getBytes(_salt, "salt"); - const initCodeHash = getBytes(_initCodeHash, "initCodeHash"); - assertArgument(salt.length === 32, "salt must be 32 bytes", "salt", _salt); - assertArgument(initCodeHash.length === 32, "initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash); - return getAddress$1(dataSlice(keccak256$1(concat$1(["0xff", from, salt, initCodeHash])), 12)); -} -function isAddressable(value) { - return value && typeof value.getAddress === "function"; + return resolvedStructs; } -function isAddress$1(value) { - try { - getAddress$1(value); - return true; - } catch (error) { +const typeWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/; +function resolveStructs(abiParameters, structs, ancestors = /* @__PURE__ */ new Set()) { + const components = []; + const length = abiParameters.length; + for (let i = 0; i < length; i++) { + const abiParameter = abiParameters[i]; + const isTuple = isTupleRegex.test(abiParameter.type); + if (isTuple) + components.push(abiParameter); + else { + const match = execTyped(typeWithoutTupleRegex, abiParameter.type); + if (!(match == null ? void 0 : match.type)) + throw new InvalidAbiTypeParameterError({ abiParameter }); + const { array, type } = match; + if (type in structs) { + if (ancestors.has(type)) + throw new CircularReferenceError({ type }); + components.push({ + ...abiParameter, + type: `tuple${array ?? ""}`, + components: resolveStructs(structs[type] ?? [], structs, /* @__PURE__ */ new Set([...ancestors, type])) + }); + } else { + if (isSolidityType(type)) + components.push(abiParameter); + else + throw new UnknownTypeError({ type }); + } + } } - return false; + return components; } -async function checkAddress(target, promise) { - const result = await promise; - if (result == null || result === "0x0000000000000000000000000000000000000000") { - assert(typeof target !== "string", "unconfigured name", "UNCONFIGURED_NAME", { value: target }); - assertArgument(false, "invalid AddressLike value; did not resolve to a value address", "target", target); +function parseAbi(signatures) { + const structs = parseStructs(signatures); + const abi2 = []; + const length = signatures.length; + for (let i = 0; i < length; i++) { + const signature2 = signatures[i]; + if (isStructSignature(signature2)) + continue; + abi2.push(parseSignature(signature2, structs)); } - return getAddress$1(result); + return abi2; } -function resolveAddress(target, resolver) { - if (typeof target === "string") { - if (target.match(/^0x[0-9a-f]{40}$/i)) { - return getAddress$1(target); +function normalizeSignature(signature2) { + let active = true; + let current = ""; + let level = 0; + let result = ""; + let valid = false; + for (let i = 0; i < signature2.length; i++) { + const char = signature2[i]; + if (["(", ")", ","].includes(char)) + active = true; + if (char === "(") + level++; + if (char === ")") + level--; + if (!active) + continue; + if (level === 0) { + if (char === " " && ["event", "function", ""].includes(result)) + result = ""; + else { + result += char; + if (char === ")") { + valid = true; + break; + } + } + continue; } - assert(resolver != null, "ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { operation: "resolveName" }); - return checkAddress(target, resolver.resolveName(target)); - } else if (isAddressable(target)) { - return checkAddress(target, target.getAddress()); - } else if (target && typeof target.then === "function") { - return checkAddress(target, target); - } - assertArgument(false, "unsupported addressable value", "target", target); -} -const _gaurd = {}; -function n$3(value, width) { - let signed2 = false; - if (width < 0) { - signed2 = true; - width *= -1; + if (char === " ") { + if (signature2[i - 1] !== "," && current !== "," && current !== ",(") { + current = ""; + active = false; + } + continue; + } + result += char; + current += char; } - return new Typed(_gaurd, `${signed2 ? "" : "u"}int${width}`, value, { signed: signed2, width }); + if (!valid) + throw new BaseError$3("Unable to normalize signature."); + return result; } -function b$1(value, size2) { - return new Typed(_gaurd, `bytes${size2 ? size2 : ""}`, value, { size: size2 }); +const toSignature = (def) => { + const def_ = (() => { + if (typeof def === "string") + return def; + return formatAbiItem(def); + })(); + return normalizeSignature(def_); +}; +function toSignatureHash(fn) { + return hashSignature(toSignature(fn)); } -const _typedSymbol = Symbol.for("_ethers_typed"); -const _Typed = class _Typed { - /** - * @_ignore: - */ - constructor(gaurd, type, value, options) { - /** - * The type, as a Solidity-compatible type. - */ - __publicField(this, "type"); - /** - * The actual value. - */ - __publicField(this, "value"); - __privateAdd(this, _options); - /** - * @_ignore: - */ - __publicField(this, "_typedSymbol"); - if (options == null) { - options = null; +const toEventSelector = toSignatureHash; +const toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4); +function getAbiItem(parameters) { + const { abi: abi2, args = [], name: name2 } = parameters; + const isSelector = isHex(name2, { strict: false }); + const abiItems = abi2.filter((abiItem) => { + if (isSelector) { + if (abiItem.type === "function") + return toFunctionSelector(abiItem) === name2; + if (abiItem.type === "event") + return toEventSelector(abiItem) === name2; + return false; } - assertPrivate(_gaurd, gaurd, "Typed"); - defineProperties$1(this, { _typedSymbol, type, value }); - __privateSet(this, _options, options); - this.format(); - } - /** - * Format the type as a Human-Readable type. - */ - format() { - if (this.type === "array") { - throw new Error(""); - } else if (this.type === "dynamicArray") { - throw new Error(""); - } else if (this.type === "tuple") { - return `tuple(${this.value.map((v3) => v3.format()).join(",")})`; + return "name" in abiItem && abiItem.name === name2; + }); + if (abiItems.length === 0) + return void 0; + if (abiItems.length === 1) + return abiItems[0]; + let matchedAbiItem = void 0; + for (const abiItem of abiItems) { + if (!("inputs" in abiItem)) + continue; + if (!args || args.length === 0) { + if (!abiItem.inputs || abiItem.inputs.length === 0) + return abiItem; + continue; } - return this.type; - } - /** - * The default value returned by this type. - */ - defaultValue() { - return 0; - } - /** - * The minimum value for numeric types. - */ - minValue() { - return 0; - } - /** - * The maximum value for numeric types. - */ - maxValue() { - return 0; - } - /** - * Returns ``true`` and provides a type guard is this is a [[TypedBigInt]]. - */ - isBigInt() { - return !!this.type.match(/^u?int[0-9]+$/); - } - /** - * Returns ``true`` and provides a type guard is this is a [[TypedData]]. - */ - isData() { - return this.type.startsWith("bytes"); - } - /** - * Returns ``true`` and provides a type guard is this is a [[TypedString]]. - */ - isString() { - return this.type === "string"; - } - /** - * Returns the tuple name, if this is a tuple. Throws otherwise. - */ - get tupleName() { - if (this.type !== "tuple") { - throw TypeError("not a tuple"); + if (!abiItem.inputs) + continue; + if (abiItem.inputs.length === 0) + continue; + if (abiItem.inputs.length !== args.length) + continue; + const matched = args.every((arg, index2) => { + const abiParameter = "inputs" in abiItem && abiItem.inputs[index2]; + if (!abiParameter) + return false; + return isArgOfType(arg, abiParameter); + }); + if (matched) { + if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { + const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args); + if (ambiguousTypes) + throw new AbiItemAmbiguityError({ + abiItem, + type: ambiguousTypes[0] + }, { + abiItem: matchedAbiItem, + type: ambiguousTypes[1] + }); + } + matchedAbiItem = abiItem; } - return __privateGet(this, _options); } - // Returns the length of this type as an array - // - `null` indicates the length is unforced, it could be dynamic - // - `-1` indicates the length is dynamic - // - any other value indicates it is a static array and is its length - /** - * Returns the length of the array type or ``-1`` if it is dynamic. - * - * Throws if the type is not an array. - */ - get arrayLength() { - if (this.type !== "array") { - throw TypeError("not an array"); - } - if (__privateGet(this, _options) === true) { - return -1; - } - if (__privateGet(this, _options) === false) { - return this.value.length; + if (matchedAbiItem) + return matchedAbiItem; + return abiItems[0]; +} +function isArgOfType(arg, abiParameter) { + const argType = typeof arg; + const abiParameterType = abiParameter.type; + switch (abiParameterType) { + case "address": + return isAddress$1(arg, { strict: false }); + case "bool": + return argType === "boolean"; + case "function": + return argType === "string"; + case "string": + return argType === "string"; + default: { + if (abiParameterType === "tuple" && "components" in abiParameter) + return Object.values(abiParameter.components).every((component, index2) => { + return isArgOfType(Object.values(arg)[index2], component); + }); + if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) + return argType === "number" || argType === "bigint"; + if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) + return argType === "string" || arg instanceof Uint8Array; + if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { + return Array.isArray(arg) && arg.every((x2) => isArgOfType(x2, { + ...abiParameter, + // Pop off `[]` or `[M]` from end of type + type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") + })); + } + return false; } - return null; - } - /** - * Returns a new **Typed** of %%type%% with the %%value%%. - */ - static from(type, value) { - return new _Typed(_gaurd, type, value); - } - /** - * Return a new ``uint8`` type for %%v%%. - */ - static uint8(v3) { - return n$3(v3, 8); - } - /** - * Return a new ``uint16`` type for %%v%%. - */ - static uint16(v3) { - return n$3(v3, 16); - } - /** - * Return a new ``uint24`` type for %%v%%. - */ - static uint24(v3) { - return n$3(v3, 24); - } - /** - * Return a new ``uint32`` type for %%v%%. - */ - static uint32(v3) { - return n$3(v3, 32); - } - /** - * Return a new ``uint40`` type for %%v%%. - */ - static uint40(v3) { - return n$3(v3, 40); - } - /** - * Return a new ``uint48`` type for %%v%%. - */ - static uint48(v3) { - return n$3(v3, 48); - } - /** - * Return a new ``uint56`` type for %%v%%. - */ - static uint56(v3) { - return n$3(v3, 56); - } - /** - * Return a new ``uint64`` type for %%v%%. - */ - static uint64(v3) { - return n$3(v3, 64); - } - /** - * Return a new ``uint72`` type for %%v%%. - */ - static uint72(v3) { - return n$3(v3, 72); } - /** - * Return a new ``uint80`` type for %%v%%. - */ - static uint80(v3) { - return n$3(v3, 80); - } - /** - * Return a new ``uint88`` type for %%v%%. - */ - static uint88(v3) { - return n$3(v3, 88); - } - /** - * Return a new ``uint96`` type for %%v%%. - */ - static uint96(v3) { - return n$3(v3, 96); - } - /** - * Return a new ``uint104`` type for %%v%%. - */ - static uint104(v3) { - return n$3(v3, 104); - } - /** - * Return a new ``uint112`` type for %%v%%. - */ - static uint112(v3) { - return n$3(v3, 112); - } - /** - * Return a new ``uint120`` type for %%v%%. - */ - static uint120(v3) { - return n$3(v3, 120); - } - /** - * Return a new ``uint128`` type for %%v%%. - */ - static uint128(v3) { - return n$3(v3, 128); +} +function getAmbiguousTypes(sourceParameters, targetParameters, args) { + for (const parameterIndex in sourceParameters) { + const sourceParameter = sourceParameters[parameterIndex]; + const targetParameter = targetParameters[parameterIndex]; + if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) + return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]); + const types2 = [sourceParameter.type, targetParameter.type]; + const ambiguous = (() => { + if (types2.includes("address") && types2.includes("bytes20")) + return true; + if (types2.includes("address") && types2.includes("string")) + return isAddress$1(args[parameterIndex], { strict: false }); + if (types2.includes("address") && types2.includes("bytes")) + return isAddress$1(args[parameterIndex], { strict: false }); + return false; + })(); + if (ambiguous) + return types2; } - /** - * Return a new ``uint136`` type for %%v%%. - */ - static uint136(v3) { - return n$3(v3, 136); + return; +} +const docsPath$3 = "/docs/contract/decodeFunctionResult"; +function decodeFunctionResult(parameters) { + const { abi: abi2, args, functionName, data } = parameters; + let abiItem = abi2[0]; + if (functionName) { + const item2 = getAbiItem({ abi: abi2, args, name: functionName }); + if (!item2) + throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath$3 }); + abiItem = item2; } - /** - * Return a new ``uint144`` type for %%v%%. - */ - static uint144(v3) { - return n$3(v3, 144); + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath$3 }); + if (!abiItem.outputs) + throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath$3 }); + const values = decodeAbiParameters(abiItem.outputs, data); + if (values && values.length > 1) + return values; + if (values && values.length === 1) + return values[0]; + return void 0; +} +const docsPath$2 = "/docs/contract/encodeFunctionData"; +function prepareEncodeFunctionData(parameters) { + const { abi: abi2, args, functionName } = parameters; + let abiItem = abi2[0]; + if (functionName) { + const item2 = getAbiItem({ + abi: abi2, + args, + name: functionName + }); + if (!item2) + throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath$2 }); + abiItem = item2; } - /** - * Return a new ``uint152`` type for %%v%%. - */ - static uint152(v3) { - return n$3(v3, 152); - } - /** - * Return a new ``uint160`` type for %%v%%. - */ - static uint160(v3) { - return n$3(v3, 160); - } - /** - * Return a new ``uint168`` type for %%v%%. - */ - static uint168(v3) { - return n$3(v3, 168); - } - /** - * Return a new ``uint176`` type for %%v%%. - */ - static uint176(v3) { - return n$3(v3, 176); - } - /** - * Return a new ``uint184`` type for %%v%%. - */ - static uint184(v3) { - return n$3(v3, 184); - } - /** - * Return a new ``uint192`` type for %%v%%. - */ - static uint192(v3) { - return n$3(v3, 192); - } - /** - * Return a new ``uint200`` type for %%v%%. - */ - static uint200(v3) { - return n$3(v3, 200); - } - /** - * Return a new ``uint208`` type for %%v%%. - */ - static uint208(v3) { - return n$3(v3, 208); - } - /** - * Return a new ``uint216`` type for %%v%%. - */ - static uint216(v3) { - return n$3(v3, 216); - } - /** - * Return a new ``uint224`` type for %%v%%. - */ - static uint224(v3) { - return n$3(v3, 224); - } - /** - * Return a new ``uint232`` type for %%v%%. - */ - static uint232(v3) { - return n$3(v3, 232); - } - /** - * Return a new ``uint240`` type for %%v%%. - */ - static uint240(v3) { - return n$3(v3, 240); - } - /** - * Return a new ``uint248`` type for %%v%%. - */ - static uint248(v3) { - return n$3(v3, 248); - } - /** - * Return a new ``uint256`` type for %%v%%. - */ - static uint256(v3) { - return n$3(v3, 256); - } - /** - * Return a new ``uint256`` type for %%v%%. - */ - static uint(v3) { - return n$3(v3, 256); - } - /** - * Return a new ``int8`` type for %%v%%. - */ - static int8(v3) { - return n$3(v3, -8); - } - /** - * Return a new ``int16`` type for %%v%%. - */ - static int16(v3) { - return n$3(v3, -16); - } - /** - * Return a new ``int24`` type for %%v%%. - */ - static int24(v3) { - return n$3(v3, -24); - } - /** - * Return a new ``int32`` type for %%v%%. - */ - static int32(v3) { - return n$3(v3, -32); - } - /** - * Return a new ``int40`` type for %%v%%. - */ - static int40(v3) { - return n$3(v3, -40); - } - /** - * Return a new ``int48`` type for %%v%%. - */ - static int48(v3) { - return n$3(v3, -48); + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath$2 }); + return { + abi: [abiItem], + functionName: toFunctionSelector(formatAbiItem$1(abiItem)) + }; +} +function encodeFunctionData(parameters) { + const { args } = parameters; + const { abi: abi2, functionName } = (() => { + var _a2; + if (parameters.abi.length === 1 && ((_a2 = parameters.functionName) == null ? void 0 : _a2.startsWith("0x"))) + return parameters; + return prepareEncodeFunctionData(parameters); + })(); + const abiItem = abi2[0]; + const signature2 = functionName; + const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : void 0; + return concatHex([signature2, data ?? "0x"]); +} +function getChainContractAddress({ blockNumber, chain, contract: name2 }) { + var _a2; + const contract = (_a2 = chain == null ? void 0 : chain.contracts) == null ? void 0 : _a2[name2]; + if (!contract) + throw new ChainDoesNotSupportContract({ + chain, + contract: { name: name2 } + }); + if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber) + throw new ChainDoesNotSupportContract({ + blockNumber, + chain, + contract: { + name: name2, + blockCreated: contract.blockCreated + } + }); + return contract.address; +} +const panicReasons = { + 1: "An `assert` condition failed.", + 17: "Arithmetic operation resulted in underflow or overflow.", + 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).", + 33: "Attempted to convert to an invalid type.", + 34: "Attempted to access a storage byte array that is incorrectly encoded.", + 49: "Performed `.pop()` on an empty array", + 50: "Array index is out of bounds.", + 65: "Allocated too much memory or created an array which is too large.", + 81: "Attempted to call a zero-initialized variable of internal function type." +}; +const solidityError = { + inputs: [ + { + name: "message", + type: "string" + } + ], + name: "Error", + type: "error" +}; +const solidityPanic = { + inputs: [ + { + name: "reason", + type: "uint256" + } + ], + name: "Panic", + type: "error" +}; +function decodeErrorResult(parameters) { + const { abi: abi2, data } = parameters; + const signature2 = slice(data, 0, 4); + if (signature2 === "0x") + throw new AbiDecodingZeroDataError(); + const abi_ = [...abi2 || [], solidityError, solidityPanic]; + const abiItem = abi_.find((x2) => x2.type === "error" && signature2 === toFunctionSelector(formatAbiItem$1(x2))); + if (!abiItem) + throw new AbiErrorSignatureNotFoundError(signature2, { + docsPath: "/docs/contract/decodeErrorResult" + }); + return { + abiItem, + args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : void 0, + errorName: abiItem.name + }; +} +function formatAbiItemWithArgs({ abiItem, args, includeFunctionName = true, includeName = false }) { + if (!("name" in abiItem)) + return; + if (!("inputs" in abiItem)) + return; + if (!abiItem.inputs) + return; + return `${includeFunctionName ? abiItem.name : ""}(${abiItem.inputs.map((input2, i) => `${includeName && input2.name ? `${input2.name}: ` : ""}${typeof args[i] === "object" ? stringify$3(args[i]) : args[i]}`).join(", ")})`; +} +class CallExecutionError extends BaseError$3 { + constructor(cause, { account: account_, docsPath: docsPath2, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride }) { + var _a2; + const account2 = account_ ? parseAccount(account_) : void 0; + let prettyArgs = prettyPrint({ + from: account2 == null ? void 0 : account2.address, + to, + value: typeof value !== "undefined" && `${formatEther$2(value)} ${((_a2 = chain == null ? void 0 : chain.nativeCurrency) == null ? void 0 : _a2.symbol) || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, + nonce + }); + if (stateOverride) { + prettyArgs += ` +${prettyStateOverride(stateOverride)}`; + } + super(cause.shortMessage, { + cause, + docsPath: docsPath2, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Raw Call Arguments:", + prettyArgs + ].filter(Boolean), + name: "CallExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; } - /** - * Return a new ``int56`` type for %%v%%. - */ - static int56(v3) { - return n$3(v3, -56); +} +class ContractFunctionExecutionError extends BaseError$3 { + constructor(cause, { abi: abi2, args, contractAddress, docsPath: docsPath2, functionName, sender }) { + const abiItem = getAbiItem({ abi: abi2, args, name: functionName }); + const formattedArgs = abiItem ? formatAbiItemWithArgs({ + abiItem, + args, + includeFunctionName: false, + includeName: false + }) : void 0; + const functionWithParams = abiItem ? formatAbiItem$1(abiItem, { includeName: true }) : void 0; + const prettyArgs = prettyPrint({ + address: contractAddress && getContractAddress(contractAddress), + function: functionWithParams, + args: formattedArgs && formattedArgs !== "()" && `${[...Array((functionName == null ? void 0 : functionName.length) ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`, + sender + }); + super(cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`, { + cause, + docsPath: docsPath2, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + prettyArgs && "Contract Call:", + prettyArgs + ].filter(Boolean), + name: "ContractFunctionExecutionError" + }); + Object.defineProperty(this, "abi", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "args", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "contractAddress", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "formattedArgs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "functionName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sender", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.abi = abi2; + this.args = args; + this.cause = cause; + this.contractAddress = contractAddress; + this.functionName = functionName; + this.sender = sender; } - /** - * Return a new ``int64`` type for %%v%%. - */ - static int64(v3) { - return n$3(v3, -64); +} +class ContractFunctionRevertedError extends BaseError$3 { + constructor({ abi: abi2, data, functionName, message }) { + let cause; + let decodedData = void 0; + let metaMessages; + let reason; + if (data && data !== "0x") { + try { + decodedData = decodeErrorResult({ abi: abi2, data }); + const { abiItem, errorName, args: errorArgs } = decodedData; + if (errorName === "Error") { + reason = errorArgs[0]; + } else if (errorName === "Panic") { + const [firstArg] = errorArgs; + reason = panicReasons[firstArg]; + } else { + const errorWithParams = abiItem ? formatAbiItem$1(abiItem, { includeName: true }) : void 0; + const formattedArgs = abiItem && errorArgs ? formatAbiItemWithArgs({ + abiItem, + args: errorArgs, + includeFunctionName: false, + includeName: false + }) : void 0; + metaMessages = [ + errorWithParams ? `Error: ${errorWithParams}` : "", + formattedArgs && formattedArgs !== "()" ? ` ${[...Array((errorName == null ? void 0 : errorName.length) ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : "" + ]; + } + } catch (err) { + cause = err; + } + } else if (message) + reason = message; + let signature2; + if (cause instanceof AbiErrorSignatureNotFoundError) { + signature2 = cause.signature; + metaMessages = [ + `Unable to decode signature "${signature2}" as it was not found on the provided ABI.`, + "Make sure you are using the correct ABI and that the error exists on it.", + `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature2}.` + ]; + } + super(reason && reason !== "execution reverted" || signature2 ? [ + `The contract function "${functionName}" reverted with the following ${signature2 ? "signature" : "reason"}:`, + reason || signature2 + ].join("\n") : `The contract function "${functionName}" reverted.`, { + cause, + metaMessages, + name: "ContractFunctionRevertedError" + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reason", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "signature", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = decodedData; + this.reason = reason; + this.signature = signature2; } - /** - * Return a new ``int72`` type for %%v%%. - */ - static int72(v3) { - return n$3(v3, -72); +} +class ContractFunctionZeroDataError extends BaseError$3 { + constructor({ functionName }) { + super(`The contract function "${functionName}" returned no data ("0x").`, { + metaMessages: [ + "This could be due to any of the following:", + ` - The contract does not have the function "${functionName}",`, + " - The parameters passed to the contract function may be invalid, or", + " - The address is not a contract." + ], + name: "ContractFunctionZeroDataError" + }); } - /** - * Return a new ``int80`` type for %%v%%. - */ - static int80(v3) { - return n$3(v3, -80); +} +class CounterfactualDeploymentFailedError extends BaseError$3 { + constructor({ factory: factory2 }) { + super(`Deployment for counterfactual contract call failed${factory2 ? ` for factory "${factory2}".` : ""}`, { + metaMessages: [ + "Please ensure:", + "- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).", + "- The `factoryData` is a valid encoded function call for contract deployment function on the factory." + ], + name: "CounterfactualDeploymentFailedError" + }); } - /** - * Return a new ``int88`` type for %%v%%. - */ - static int88(v3) { - return n$3(v3, -88); +} +class RawContractError extends BaseError$3 { + constructor({ data, message }) { + super(message || "", { name: "RawContractError" }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = data; } - /** - * Return a new ``int96`` type for %%v%%. - */ - static int96(v3) { - return n$3(v3, -96); +} +function isNullUniversalResolverError(err, callType) { + var _a2, _b2, _c2, _d2, _e2, _f2; + if (!(err instanceof BaseError$3)) + return false; + const cause = err.walk((e2) => e2 instanceof ContractFunctionRevertedError); + if (!(cause instanceof ContractFunctionRevertedError)) + return false; + if (((_a2 = cause.data) == null ? void 0 : _a2.errorName) === "ResolverNotFound") + return true; + if (((_b2 = cause.data) == null ? void 0 : _b2.errorName) === "ResolverWildcardNotSupported") + return true; + if (((_c2 = cause.data) == null ? void 0 : _c2.errorName) === "ResolverNotContract") + return true; + if (((_d2 = cause.data) == null ? void 0 : _d2.errorName) === "ResolverError") + return true; + if (((_e2 = cause.data) == null ? void 0 : _e2.errorName) === "HttpError") + return true; + if ((_f2 = cause.reason) == null ? void 0 : _f2.includes("Wildcard on non-extended resolvers is not supported")) + return true; + if (callType === "reverse" && cause.reason === panicReasons[50]) + return true; + return false; +} +function encodedLabelToLabelhash(label) { + if (label.length !== 66) + return null; + if (label.indexOf("[") !== 0) + return null; + if (label.indexOf("]") !== 65) + return null; + const hash2 = `0x${label.slice(1, 65)}`; + if (!isHex(hash2)) + return null; + return hash2; +} +function namehash$1(name2) { + let result = new Uint8Array(32).fill(0); + if (!name2) + return bytesToHex$3(result); + const labels = name2.split("."); + for (let i = labels.length - 1; i >= 0; i -= 1) { + const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]); + const hashed = hashFromEncodedLabel ? toBytes$3(hashFromEncodedLabel) : keccak256$1(stringToBytes(labels[i]), "bytes"); + result = keccak256$1(concat$1([result, hashed]), "bytes"); } - /** - * Return a new ``int104`` type for %%v%%. - */ - static int104(v3) { - return n$3(v3, -104); + return bytesToHex$3(result); +} +function encodeLabelhash(hash2) { + return `[${hash2.slice(2)}]`; +} +function labelhash(label) { + const result = new Uint8Array(32).fill(0); + if (!label) + return bytesToHex$3(result); + return encodedLabelToLabelhash(label) || keccak256$1(stringToBytes(label)); +} +function packetToBytes(packet) { + const value = packet.replace(/^\.|\.$/gm, ""); + if (value.length === 0) + return new Uint8Array(1); + const bytes2 = new Uint8Array(stringToBytes(value).byteLength + 2); + let offset2 = 0; + const list2 = value.split("."); + for (let i = 0; i < list2.length; i++) { + let encoded = stringToBytes(list2[i]); + if (encoded.byteLength > 255) + encoded = stringToBytes(encodeLabelhash(labelhash(list2[i]))); + bytes2[offset2] = encoded.length; + bytes2.set(encoded, offset2 + 1); + offset2 += encoded.length + 1; } - /** - * Return a new ``int112`` type for %%v%%. - */ - static int112(v3) { - return n$3(v3, -112); - } - /** - * Return a new ``int120`` type for %%v%%. - */ - static int120(v3) { - return n$3(v3, -120); + if (bytes2.byteLength !== offset2 + 1) + return bytes2.slice(0, offset2 + 1); + return bytes2; +} +const EXECUTION_REVERTED_ERROR_CODE = 3; +function getContractError(err, { abi: abi2, address, args, docsPath: docsPath2, functionName, sender }) { + const { code: code2, data, message, shortMessage } = err instanceof RawContractError ? err : err instanceof BaseError$3 ? err.walk((err2) => "data" in err2) || err.walk() : {}; + const cause = (() => { + if (err instanceof AbiDecodingZeroDataError) + return new ContractFunctionZeroDataError({ functionName }); + if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code2) && (data || message || shortMessage)) { + return new ContractFunctionRevertedError({ + abi: abi2, + data: typeof data === "object" ? data.data : data, + functionName, + message: shortMessage ?? message + }); + } + return err; + })(); + return new ContractFunctionExecutionError(cause, { + abi: abi2, + args, + contractAddress: address, + docsPath: docsPath2, + functionName, + sender + }); +} +const aggregate3Signature = "0x82ad56cb"; +const deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe"; +const deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe"; +const universalSignatureValidatorByteCode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572"; +function getCallError(err, { docsPath: docsPath2, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new CallExecutionError(cause, { + docsPath: docsPath2, + ...args + }); +} +const schedulerCache = /* @__PURE__ */ new Map(); +function createBatchScheduler({ fn, id: id2, shouldSplitBatch, wait: wait2 = 0, sort }) { + const exec = async () => { + const scheduler2 = getScheduler(); + flush(); + const args = scheduler2.map(({ args: args2 }) => args2); + if (args.length === 0) + return; + fn(args).then((data) => { + var _a2; + if (sort && Array.isArray(data)) + data.sort(sort); + for (let i = 0; i < scheduler2.length; i++) { + const { pendingPromise } = scheduler2[i]; + (_a2 = pendingPromise.resolve) == null ? void 0 : _a2.call(pendingPromise, [data[i], data]); + } + }).catch((err) => { + var _a2; + for (let i = 0; i < scheduler2.length; i++) { + const { pendingPromise } = scheduler2[i]; + (_a2 = pendingPromise.reject) == null ? void 0 : _a2.call(pendingPromise, err); + } + }); + }; + const flush = () => schedulerCache.delete(id2); + const getBatchedArgs = () => getScheduler().map(({ args }) => args); + const getScheduler = () => schedulerCache.get(id2) || []; + const setScheduler = (item2) => schedulerCache.set(id2, [...getScheduler(), item2]); + return { + flush, + async schedule(args) { + const pendingPromise = {}; + const promise = new Promise((resolve, reject) => { + pendingPromise.resolve = resolve; + pendingPromise.reject = reject; + }); + const split2 = shouldSplitBatch == null ? void 0 : shouldSplitBatch([...getBatchedArgs(), args]); + if (split2) + exec(); + const hasActiveScheduler = getScheduler().length > 0; + if (hasActiveScheduler) { + setScheduler({ args, pendingPromise }); + return promise; + } + setScheduler({ args, pendingPromise }); + setTimeout(exec, wait2); + return promise; + } + }; +} +async function call(client2, args) { + var _a2, _b2, _c2, _d2; + const { account: account_ = client2.account, batch = Boolean((_a2 = client2.batch) == null ? void 0 : _a2.multicall), blockNumber, blockTag = "latest", accessList, blobs, code: code2, data: data_, factory: factory2, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride, ...rest } = args; + const account2 = account_ ? parseAccount(account_) : void 0; + if (code2 && (factory2 || factoryData)) + throw new BaseError$3("Cannot provide both `code` & `factory`/`factoryData` as parameters."); + if (code2 && to) + throw new BaseError$3("Cannot provide both `code` & `to` as parameters."); + const deploylessCallViaBytecode = code2 && data_; + const deploylessCallViaFactory = factory2 && factoryData && to && data_; + const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory; + const data = (() => { + if (deploylessCallViaBytecode) + return toDeploylessCallViaBytecodeData({ + code: code2, + data: data_ + }); + if (deploylessCallViaFactory) + return toDeploylessCallViaFactoryData({ + data: data_, + factory: factory2, + factoryData, + to + }); + return data_; + })(); + try { + assertRequest(args); + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const rpcStateOverride = serializeStateOverride(stateOverride); + const chainFormat = (_d2 = (_c2 = (_b2 = client2.chain) == null ? void 0 : _b2.formatters) == null ? void 0 : _c2.transactionRequest) == null ? void 0 : _d2.format; + const format2 = chainFormat || formatTransactionRequest; + const request = format2({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + from: account2 == null ? void 0 : account2.address, + accessList, + blobs, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to: deploylessCall ? void 0 : to, + value + }); + if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) { + try { + return await scheduleMulticall(client2, { + ...request, + blockNumber, + blockTag + }); + } catch (err) { + if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract)) + throw err; + } + } + const response = await client2.request({ + method: "eth_call", + params: rpcStateOverride ? [ + request, + block, + rpcStateOverride + ] : [request, block] + }); + if (response === "0x") + return { data: void 0 }; + return { data: response }; + } catch (err) { + const data2 = getRevertErrorData(err); + const { offchainLookup, offchainLookupSignature } = await __vitePreload(async () => { + const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-BD4-E_uZ.js"); + return { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 }; + }, true ? [] : void 0, import.meta.url); + if (client2.ccipRead !== false && (data2 == null ? void 0 : data2.slice(0, 10)) === offchainLookupSignature && to) + return { data: await offchainLookup(client2, { data: data2, to }) }; + if (deploylessCall && (data2 == null ? void 0 : data2.slice(0, 10)) === "0x101bb98d") + throw new CounterfactualDeploymentFailedError({ factory: factory2 }); + throw getCallError(err, { + ...args, + account: account2, + chain: client2.chain + }); } - /** - * Return a new ``int128`` type for %%v%%. - */ - static int128(v3) { - return n$3(v3, -128); +} +function shouldPerformMulticall({ request }) { + const { data, to, ...request_ } = request; + if (!data) + return false; + if (data.startsWith(aggregate3Signature)) + return false; + if (!to) + return false; + if (Object.values(request_).filter((x2) => typeof x2 !== "undefined").length > 0) + return false; + return true; +} +async function scheduleMulticall(client2, args) { + var _a2; + const { batchSize = 1024, wait: wait2 = 0 } = typeof ((_a2 = client2.batch) == null ? void 0 : _a2.multicall) === "object" ? client2.batch.multicall : {}; + const { blockNumber, blockTag = "latest", data, multicallAddress: multicallAddress_, to } = args; + let multicallAddress = multicallAddress_; + if (!multicallAddress) { + if (!client2.chain) + throw new ClientChainNotConfiguredError(); + multicallAddress = getChainContractAddress({ + blockNumber, + chain: client2.chain, + contract: "multicall3" + }); } - /** - * Return a new ``int136`` type for %%v%%. - */ - static int136(v3) { - return n$3(v3, -136); + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const { schedule } = createBatchScheduler({ + id: `${client2.uid}.${block}`, + wait: wait2, + shouldSplitBatch(args2) { + const size2 = args2.reduce((size3, { data: data2 }) => size3 + (data2.length - 2), 0); + return size2 > batchSize * 2; + }, + fn: async (requests) => { + const calls = requests.map((request) => ({ + allowFailure: true, + callData: request.data, + target: request.to + })); + const calldata = encodeFunctionData({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3" + }); + const data2 = await client2.request({ + method: "eth_call", + params: [ + { + data: calldata, + to: multicallAddress + }, + block + ] + }); + return decodeFunctionResult({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3", + data: data2 || "0x" + }); + } + }); + const [{ returnData, success }] = await schedule({ data, to }); + if (!success) + throw new RawContractError({ data: returnData }); + if (returnData === "0x") + return { data: void 0 }; + return { data: returnData }; +} +function toDeploylessCallViaBytecodeData(parameters) { + const { code: code2, data } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(bytes, bytes)"]), + bytecode: deploylessCallViaBytecodeBytecode, + args: [code2, data] + }); +} +function toDeploylessCallViaFactoryData(parameters) { + const { data, factory: factory2, factoryData, to } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(address, bytes, address, bytes)"]), + bytecode: deploylessCallViaFactoryBytecode, + args: [to, data, factory2, factoryData] + }); +} +function getRevertErrorData(err) { + var _a2; + if (!(err instanceof BaseError$3)) + return void 0; + const error = err.walk(); + return typeof (error == null ? void 0 : error.data) === "object" ? (_a2 = error.data) == null ? void 0 : _a2.data : error.data; +} +async function readContract$1(client2, parameters) { + const { abi: abi2, address, args, functionName, ...rest } = parameters; + const calldata = encodeFunctionData({ + abi: abi2, + args, + functionName + }); + try { + const { data } = await getAction$1(client2, call, "call")({ + ...rest, + data: calldata, + to: address + }); + return decodeFunctionResult({ + abi: abi2, + args, + functionName, + data: data || "0x" + }); + } catch (error) { + throw getContractError(error, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/readContract", + functionName + }); } - /** - * Return a new ``int144`` type for %%v%%. - */ - static int144(v3) { - return n$3(v3, -144); +} +async function getEnsAddress(client2, { blockNumber, blockTag, coinType, name: name2, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client2.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client2.chain, + contract: "ensUniversalResolver" + }); } - /** - * Return a new ``int52`` type for %%v%%. - */ - static int152(v3) { - return n$3(v3, -152); + try { + const functionData = encodeFunctionData({ + abi: addressResolverAbi, + functionName: "addr", + ...coinType != null ? { args: [namehash$1(name2), BigInt(coinType)] } : { args: [namehash$1(name2)] } + }); + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverResolveAbi, + functionName: "resolve", + args: [toHex$1(packetToBytes(name2)), functionData], + blockNumber, + blockTag + }; + const readContractAction = getAction$1(client2, readContract$1, "readContract"); + const res = gatewayUrls ? await readContractAction({ + ...readContractParameters, + args: [...readContractParameters.args, gatewayUrls] + }) : await readContractAction(readContractParameters); + if (res[0] === "0x") + return null; + const address = decodeFunctionResult({ + abi: addressResolverAbi, + args: coinType != null ? [namehash$1(name2), BigInt(coinType)] : void 0, + functionName: "addr", + data: res[0] + }); + if (address === "0x") + return null; + if (trim(address) === "0x00") + return null; + return address; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err, "resolve")) + return null; + throw err; } - /** - * Return a new ``int160`` type for %%v%%. - */ - static int160(v3) { - return n$3(v3, -160); +} +class EnsAvatarInvalidMetadataError extends BaseError$3 { + constructor({ data }) { + super("Unable to extract image from metadata. The metadata may be malformed or invalid.", { + metaMessages: [ + "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.", + "", + `Provided data: ${JSON.stringify(data)}` + ], + name: "EnsAvatarInvalidMetadataError" + }); } - /** - * Return a new ``int168`` type for %%v%%. - */ - static int168(v3) { - return n$3(v3, -168); +} +class EnsAvatarInvalidNftUriError extends BaseError$3 { + constructor({ reason }) { + super(`ENS NFT avatar URI is invalid. ${reason}`, { + name: "EnsAvatarInvalidNftUriError" + }); } - /** - * Return a new ``int176`` type for %%v%%. - */ - static int176(v3) { - return n$3(v3, -176); +} +class EnsAvatarUriResolutionError extends BaseError$3 { + constructor({ uri }) { + super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" }); } - /** - * Return a new ``int184`` type for %%v%%. - */ - static int184(v3) { - return n$3(v3, -184); +} +class EnsAvatarUnsupportedNamespaceError extends BaseError$3 { + constructor({ namespace }) { + super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" }); } - /** - * Return a new ``int92`` type for %%v%%. - */ - static int192(v3) { - return n$3(v3, -192); +} +const networkRegex = /(?https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/; +const ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/; +const base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/; +const dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/; +async function isImageUri(uri) { + try { + const res = await fetch(uri, { method: "HEAD" }); + if (res.status === 200) { + const contentType = res.headers.get("content-type"); + return contentType == null ? void 0 : contentType.startsWith("image/"); + } + return false; + } catch (error) { + if (typeof error === "object" && typeof error.response !== "undefined") { + return false; + } + if (!globalThis.hasOwnProperty("Image")) + return false; + return new Promise((resolve) => { + const img2 = new Image(); + img2.onload = () => { + resolve(true); + }; + img2.onerror = () => { + resolve(false); + }; + img2.src = uri; + }); } - /** - * Return a new ``int200`` type for %%v%%. - */ - static int200(v3) { - return n$3(v3, -200); +} +function getGateway(custom2, defaultGateway) { + if (!custom2) + return defaultGateway; + if (custom2.endsWith("/")) + return custom2.slice(0, -1); + return custom2; +} +function resolveAvatarUri({ uri, gatewayUrls }) { + const isEncoded = base64Regex.test(uri); + if (isEncoded) + return { uri, isOnChain: true, isEncoded }; + const ipfsGateway = getGateway(gatewayUrls == null ? void 0 : gatewayUrls.ipfs, "https://ipfs.io"); + const arweaveGateway = getGateway(gatewayUrls == null ? void 0 : gatewayUrls.arweave, "https://arweave.net"); + const networkRegexMatch = uri.match(networkRegex); + const { protocol, subpath, target, subtarget = "" } = (networkRegexMatch == null ? void 0 : networkRegexMatch.groups) || {}; + const isIPNS = protocol === "ipns:/" || subpath === "ipns/"; + const isIPFS2 = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri); + if (uri.startsWith("http") && !isIPNS && !isIPFS2) { + let replacedUri = uri; + if (gatewayUrls == null ? void 0 : gatewayUrls.arweave) + replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls == null ? void 0 : gatewayUrls.arweave); + return { uri: replacedUri, isOnChain: false, isEncoded: false }; } - /** - * Return a new ``int208`` type for %%v%%. - */ - static int208(v3) { - return n$3(v3, -208); + if ((isIPNS || isIPFS2) && target) { + return { + uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`, + isOnChain: false, + isEncoded: false + }; } - /** - * Return a new ``int216`` type for %%v%%. - */ - static int216(v3) { - return n$3(v3, -216); + if (protocol === "ar:/" && target) { + return { + uri: `${arweaveGateway}/${target}${subtarget || ""}`, + isOnChain: false, + isEncoded: false + }; } - /** - * Return a new ``int224`` type for %%v%%. - */ - static int224(v3) { - return n$3(v3, -224); + let parsedUri = uri.replace(dataURIRegex, ""); + if (parsedUri.startsWith(" res2.json()); + const image = await parseAvatarUri({ + gatewayUrls, + uri: getJsonImage(res) + }); + return image; + } catch { + throw new EnsAvatarUriResolutionError({ uri }); } - /** - * Return a new ``bytes4`` type for %%v%%. - */ - static bytes4(v3) { - return b$1(v3, 4); +} +async function parseAvatarUri({ gatewayUrls, uri }) { + const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls }); + if (isOnChain) + return resolvedURI; + const isImage = await isImageUri(resolvedURI); + if (isImage) + return resolvedURI; + throw new EnsAvatarUriResolutionError({ uri }); +} +function parseNftUri(uri_) { + let uri = uri_; + if (uri.startsWith("did:nft:")) { + uri = uri.replace("did:nft:", "").replace(/_/g, "/"); } - /** - * Return a new ``bytes5`` type for %%v%%. - */ - static bytes5(v3) { - return b$1(v3, 5); + const [reference, asset_namespace, tokenID] = uri.split("/"); + const [eip_namespace, chainID] = reference.split(":"); + const [erc_namespace, contractAddress] = asset_namespace.split(":"); + if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155") + throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" }); + if (!chainID) + throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" }); + if (!contractAddress) + throw new EnsAvatarInvalidNftUriError({ + reason: "Contract address not found" + }); + if (!tokenID) + throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" }); + if (!erc_namespace) + throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" }); + return { + chainID: Number.parseInt(chainID), + namespace: erc_namespace.toLowerCase(), + contractAddress, + tokenID + }; +} +async function getNftTokenUri(client2, { nft }) { + if (nft.namespace === "erc721") { + return readContract$1(client2, { + address: nft.contractAddress, + abi: [ + { + name: "tokenURI", + type: "function", + stateMutability: "view", + inputs: [{ name: "tokenId", type: "uint256" }], + outputs: [{ name: "", type: "string" }] + } + ], + functionName: "tokenURI", + args: [BigInt(nft.tokenID)] + }); } - /** - * Return a new ``bytes6`` type for %%v%%. - */ - static bytes6(v3) { - return b$1(v3, 6); + if (nft.namespace === "erc1155") { + return readContract$1(client2, { + address: nft.contractAddress, + abi: [ + { + name: "uri", + type: "function", + stateMutability: "view", + inputs: [{ name: "_id", type: "uint256" }], + outputs: [{ name: "", type: "string" }] + } + ], + functionName: "uri", + args: [BigInt(nft.tokenID)] + }); } - /** - * Return a new ``bytes7`` type for %%v%%. - */ - static bytes7(v3) { - return b$1(v3, 7); + throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace }); +} +async function parseAvatarRecord(client2, { gatewayUrls, record }) { + if (/eip155:/i.test(record)) + return parseNftAvatarUri(client2, { gatewayUrls, record }); + return parseAvatarUri({ uri: record, gatewayUrls }); +} +async function parseNftAvatarUri(client2, { gatewayUrls, record }) { + const nft = parseNftUri(record); + const nftUri = await getNftTokenUri(client2, { nft }); + const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls }); + if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) { + const encodedJson = isEncoded ? ( + // if it is encoded, decode it + atob(resolvedNftUri.replace("data:application/json;base64,", "")) + ) : ( + // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is) + resolvedNftUri + ); + const decoded = JSON.parse(encodedJson); + return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls }); } - /** - * Return a new ``bytes8`` type for %%v%%. - */ - static bytes8(v3) { - return b$1(v3, 8); + let uriTokenId = nft.tokenID; + if (nft.namespace === "erc1155") + uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0"); + return getMetadataAvatarUri({ + gatewayUrls, + uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId) + }); +} +async function getEnsText(client2, { blockNumber, blockTag, name: name2, key, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client2.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client2.chain, + contract: "ensUniversalResolver" + }); } - /** - * Return a new ``bytes9`` type for %%v%%. - */ - static bytes9(v3) { - return b$1(v3, 9); + try { + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverResolveAbi, + functionName: "resolve", + args: [ + toHex$1(packetToBytes(name2)), + encodeFunctionData({ + abi: textResolverAbi, + functionName: "text", + args: [namehash$1(name2), key] + }) + ], + blockNumber, + blockTag + }; + const readContractAction = getAction$1(client2, readContract$1, "readContract"); + const res = gatewayUrls ? await readContractAction({ + ...readContractParameters, + args: [...readContractParameters.args, gatewayUrls] + }) : await readContractAction(readContractParameters); + if (res[0] === "0x") + return null; + const record = decodeFunctionResult({ + abi: textResolverAbi, + functionName: "text", + data: res[0] + }); + return record === "" ? null : record; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err, "resolve")) + return null; + throw err; } - /** - * Return a new ``bytes10`` type for %%v%%. - */ - static bytes10(v3) { - return b$1(v3, 10); +} +async function getEnsAvatar(client2, { blockNumber, blockTag, assetGatewayUrls, name: name2, gatewayUrls, strict, universalResolverAddress }) { + const record = await getAction$1(client2, getEnsText, "getEnsText")({ + blockNumber, + blockTag, + key: "avatar", + name: name2, + universalResolverAddress, + gatewayUrls, + strict + }); + if (!record) + return null; + try { + return await parseAvatarRecord(client2, { + record, + gatewayUrls: assetGatewayUrls + }); + } catch { + return null; } - /** - * Return a new ``bytes11`` type for %%v%%. - */ - static bytes11(v3) { - return b$1(v3, 11); +} +async function getEnsName(client2, { address, blockNumber, blockTag, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client2.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client2.chain, + contract: "ensUniversalResolver" + }); } - /** - * Return a new ``bytes12`` type for %%v%%. - */ - static bytes12(v3) { - return b$1(v3, 12); + const reverseNode = `${address.toLowerCase().substring(2)}.addr.reverse`; + try { + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverReverseAbi, + functionName: "reverse", + args: [toHex$1(packetToBytes(reverseNode))], + blockNumber, + blockTag + }; + const readContractAction = getAction$1(client2, readContract$1, "readContract"); + const [name2, resolvedAddress] = gatewayUrls ? await readContractAction({ + ...readContractParameters, + args: [...readContractParameters.args, gatewayUrls] + }) : await readContractAction(readContractParameters); + if (address.toLowerCase() !== resolvedAddress.toLowerCase()) + return null; + return name2; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err, "reverse")) + return null; + throw err; } - /** - * Return a new ``bytes13`` type for %%v%%. - */ - static bytes13(v3) { - return b$1(v3, 13); +} +async function getEnsResolver(client2, { blockNumber, blockTag, name: name2, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client2.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client2.chain, + contract: "ensUniversalResolver" + }); } - /** - * Return a new ``bytes14`` type for %%v%%. - */ - static bytes14(v3) { - return b$1(v3, 14); + const [resolverAddress] = await getAction$1(client2, readContract$1, "readContract")({ + address: universalResolverAddress, + abi: [ + { + inputs: [{ type: "bytes" }], + name: "findResolver", + outputs: [{ type: "address" }, { type: "bytes32" }], + stateMutability: "view", + type: "function" + } + ], + functionName: "findResolver", + args: [toHex$1(packetToBytes(name2))], + blockNumber, + blockTag + }); + return resolverAddress; +} +function createFilterRequestScope(client2, { method }) { + var _a2, _b2; + const requestMap = {}; + if (client2.transport.type === "fallback") + (_b2 = (_a2 = client2.transport).onResponse) == null ? void 0 : _b2.call(_a2, ({ method: method_, response: id2, status, transport }) => { + if (status === "success" && method === method_) + requestMap[id2] = transport.request; + }); + return (id2) => requestMap[id2] || client2.request; +} +async function createBlockFilter(client2) { + const getRequest = createFilterRequestScope(client2, { + method: "eth_newBlockFilter" + }); + const id2 = await client2.request({ + method: "eth_newBlockFilter" + }); + return { id: id2, request: getRequest(id2), type: "block" }; +} +class FilterTypeNotSupportedError extends BaseError$3 { + constructor(type) { + super(`Filter type "${type}" is not supported.`, { + name: "FilterTypeNotSupportedError" + }); } - /** - * Return a new ``bytes15`` type for %%v%%. - */ - static bytes15(v3) { - return b$1(v3, 15); +} +const docsPath$1 = "/docs/contract/encodeEventTopics"; +function encodeEventTopics(parameters) { + var _a2; + const { abi: abi2, eventName, args } = parameters; + let abiItem = abi2[0]; + if (eventName) { + const item2 = getAbiItem({ abi: abi2, name: eventName }); + if (!item2) + throw new AbiEventNotFoundError(eventName, { docsPath: docsPath$1 }); + abiItem = item2; } - /** - * Return a new ``bytes16`` type for %%v%%. - */ - static bytes16(v3) { - return b$1(v3, 16); + if (abiItem.type !== "event") + throw new AbiEventNotFoundError(void 0, { docsPath: docsPath$1 }); + const definition = formatAbiItem$1(abiItem); + const signature2 = toEventSelector(definition); + let topics = []; + if (args && "inputs" in abiItem) { + const indexedInputs = (_a2 = abiItem.inputs) == null ? void 0 : _a2.filter((param) => "indexed" in param && param.indexed); + const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? (indexedInputs == null ? void 0 : indexedInputs.map((x2) => args[x2.name])) ?? [] : []; + if (args_.length > 0) { + topics = (indexedInputs == null ? void 0 : indexedInputs.map((param, i) => { + if (Array.isArray(args_[i])) + return args_[i].map((_, j2) => encodeArg({ param, value: args_[i][j2] })); + return args_[i] ? encodeArg({ param, value: args_[i] }) : null; + })) ?? []; + } } - /** - * Return a new ``bytes17`` type for %%v%%. - */ - static bytes17(v3) { - return b$1(v3, 17); + return [signature2, ...topics]; +} +function encodeArg({ param, value }) { + if (param.type === "string" || param.type === "bytes") + return keccak256$1(toBytes$3(value)); + if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) + throw new FilterTypeNotSupportedError(param.type); + return encodeAbiParameters([param], [value]); +} +async function createContractEventFilter(client2, parameters) { + const { address, abi: abi2, args, eventName, fromBlock, strict, toBlock } = parameters; + const getRequest = createFilterRequestScope(client2, { + method: "eth_newFilter" + }); + const topics = eventName ? encodeEventTopics({ + abi: abi2, + args, + eventName + }) : void 0; + const id2 = await client2.request({ + method: "eth_newFilter", + params: [ + { + address, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, + topics + } + ] + }); + return { + abi: abi2, + args, + eventName, + id: id2, + request: getRequest(id2), + strict: Boolean(strict), + type: "event" + }; +} +async function createEventFilter(client2, { address, args, event, events: events_, fromBlock, strict, toBlock } = {}) { + const events = events_ ?? (event ? [event] : void 0); + const getRequest = createFilterRequestScope(client2, { + method: "eth_newFilter" + }); + let topics = []; + if (events) { + const encoded = events.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args + })); + topics = [encoded]; + if (event) + topics = topics[0]; } - /** - * Return a new ``bytes18`` type for %%v%%. - */ - static bytes18(v3) { - return b$1(v3, 18); + const id2 = await client2.request({ + method: "eth_newFilter", + params: [ + { + address, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, + ...topics.length ? { topics } : {} + } + ] + }); + return { + abi: events, + args, + eventName: event ? event.name : void 0, + fromBlock, + id: id2, + request: getRequest(id2), + strict: Boolean(strict), + toBlock, + type: "event" + }; +} +async function createPendingTransactionFilter(client2) { + const getRequest = createFilterRequestScope(client2, { + method: "eth_newPendingTransactionFilter" + }); + const id2 = await client2.request({ + method: "eth_newPendingTransactionFilter" + }); + return { id: id2, request: getRequest(id2), type: "transaction" }; +} +async function estimateContractGas(client2, parameters) { + const { abi: abi2, address, args, functionName, ...request } = parameters; + const data = encodeFunctionData({ + abi: abi2, + args, + functionName + }); + try { + const gas = await getAction$1(client2, estimateGas, "estimateGas")({ + data, + to: address, + ...request + }); + return gas; + } catch (error) { + const account2 = request.account ? parseAccount(request.account) : void 0; + throw getContractError(error, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/estimateContractGas", + functionName, + sender: account2 == null ? void 0 : account2.address + }); } - /** - * Return a new ``bytes19`` type for %%v%%. - */ - static bytes19(v3) { - return b$1(v3, 19); - } - /** - * Return a new ``bytes20`` type for %%v%%. - */ - static bytes20(v3) { - return b$1(v3, 20); - } - /** - * Return a new ``bytes21`` type for %%v%%. - */ - static bytes21(v3) { - return b$1(v3, 21); - } - /** - * Return a new ``bytes22`` type for %%v%%. - */ - static bytes22(v3) { - return b$1(v3, 22); - } - /** - * Return a new ``bytes23`` type for %%v%%. - */ - static bytes23(v3) { - return b$1(v3, 23); - } - /** - * Return a new ``bytes24`` type for %%v%%. - */ - static bytes24(v3) { - return b$1(v3, 24); - } - /** - * Return a new ``bytes25`` type for %%v%%. - */ - static bytes25(v3) { - return b$1(v3, 25); - } - /** - * Return a new ``bytes26`` type for %%v%%. - */ - static bytes26(v3) { - return b$1(v3, 26); - } - /** - * Return a new ``bytes27`` type for %%v%%. - */ - static bytes27(v3) { - return b$1(v3, 27); - } - /** - * Return a new ``bytes28`` type for %%v%%. - */ - static bytes28(v3) { - return b$1(v3, 28); - } - /** - * Return a new ``bytes29`` type for %%v%%. - */ - static bytes29(v3) { - return b$1(v3, 29); - } - /** - * Return a new ``bytes30`` type for %%v%%. - */ - static bytes30(v3) { - return b$1(v3, 30); - } - /** - * Return a new ``bytes31`` type for %%v%%. - */ - static bytes31(v3) { - return b$1(v3, 31); - } - /** - * Return a new ``bytes32`` type for %%v%%. - */ - static bytes32(v3) { - return b$1(v3, 32); - } - /** - * Return a new ``address`` type for %%v%%. - */ - static address(v3) { - return new _Typed(_gaurd, "address", v3); - } - /** - * Return a new ``bool`` type for %%v%%. - */ - static bool(v3) { - return new _Typed(_gaurd, "bool", !!v3); - } - /** - * Return a new ``bytes`` type for %%v%%. - */ - static bytes(v3) { - return new _Typed(_gaurd, "bytes", v3); - } - /** - * Return a new ``string`` type for %%v%%. - */ - static string(v3) { - return new _Typed(_gaurd, "string", v3); +} +async function getBlobBaseFee(client2) { + const baseFee = await client2.request({ + method: "eth_blobBaseFee" + }); + return BigInt(baseFee); +} +const promiseCache$1 = /* @__PURE__ */ new Map(); +const responseCache = /* @__PURE__ */ new Map(); +function getCache(cacheKey2) { + const buildCache = (cacheKey3, cache2) => ({ + clear: () => cache2.delete(cacheKey3), + get: () => cache2.get(cacheKey3), + set: (data) => cache2.set(cacheKey3, data) + }); + const promise = buildCache(cacheKey2, promiseCache$1); + const response = buildCache(cacheKey2, responseCache); + return { + clear: () => { + promise.clear(); + response.clear(); + }, + promise, + response + }; +} +async function withCache(fn, { cacheKey: cacheKey2, cacheTime = Number.POSITIVE_INFINITY }) { + const cache2 = getCache(cacheKey2); + const response = cache2.response.get(); + if (response && cacheTime > 0) { + const age = (/* @__PURE__ */ new Date()).getTime() - response.created.getTime(); + if (age < cacheTime) + return response.data; } - /** - * Return a new ``array`` type for %%v%%, allowing %%dynamic%% length. - */ - static array(v3, dynamic) { - throw new Error("not implemented yet"); + let promise = cache2.promise.get(); + if (!promise) { + promise = fn(); + cache2.promise.set(promise); } - /** - * Return a new ``tuple`` type for %%v%%, with the optional %%name%%. - */ - static tuple(v3, name2) { - throw new Error("not implemented yet"); + try { + const data = await promise; + cache2.response.set({ created: /* @__PURE__ */ new Date(), data }); + return data; + } finally { + cache2.promise.clear(); } - /** - * Return a new ``uint8`` type for %%v%%. - */ - static overrides(v3) { - return new _Typed(_gaurd, "overrides", Object.assign({}, v3)); +} +const cacheKey = (id2) => `blockNumber.${id2}`; +async function getBlockNumber(client2, { cacheTime = client2.cacheTime } = {}) { + const blockNumberHex = await withCache(() => client2.request({ + method: "eth_blockNumber" + }), { cacheKey: cacheKey(client2.uid), cacheTime }); + return BigInt(blockNumberHex); +} +async function getBlockTransactionCount(client2, { blockHash, blockNumber, blockTag = "latest" } = {}) { + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + let count2; + if (blockHash) { + count2 = await client2.request({ + method: "eth_getBlockTransactionCountByHash", + params: [blockHash] + }, { dedupe: true }); + } else { + count2 = await client2.request({ + method: "eth_getBlockTransactionCountByNumber", + params: [blockNumberHex || blockTag] + }, { dedupe: Boolean(blockNumberHex) }); } - /** - * Returns true only if %%value%% is a [[Typed]] instance. - */ - static isTyped(value) { - return value && typeof value === "object" && "_typedSymbol" in value && value._typedSymbol === _typedSymbol; + return hexToNumber$2(count2); +} +async function getCode(client2, { address, blockNumber, blockTag = "latest" }) { + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + const hex2 = await client2.request({ + method: "eth_getCode", + params: [address, blockNumberHex || blockTag] + }, { dedupe: Boolean(blockNumberHex) }); + if (hex2 === "0x") + return void 0; + return hex2; +} +function isAddressEqual(a2, b2) { + if (!isAddress$1(a2, { strict: false })) + throw new InvalidAddressError({ address: a2 }); + if (!isAddress$1(b2, { strict: false })) + throw new InvalidAddressError({ address: b2 }); + return a2.toLowerCase() === b2.toLowerCase(); +} +const docsPath = "/docs/contract/decodeEventLog"; +function decodeEventLog(parameters) { + const { abi: abi2, data, strict: strict_, topics } = parameters; + const strict = strict_ ?? true; + const [signature2, ...argTopics] = topics; + if (!signature2) + throw new AbiEventSignatureEmptyTopicsError({ docsPath }); + const abiItem = (() => { + if (abi2.length === 1) + return abi2[0]; + return abi2.find((x2) => x2.type === "event" && signature2 === toEventSelector(formatAbiItem$1(x2))); + })(); + if (!(abiItem && "name" in abiItem) || abiItem.type !== "event") + throw new AbiEventSignatureNotFoundError(signature2, { docsPath }); + const { name: name2, inputs } = abiItem; + const isUnnamed = inputs == null ? void 0 : inputs.some((x2) => !("name" in x2 && x2.name)); + let args = isUnnamed ? [] : {}; + const indexedInputs = inputs.filter((x2) => "indexed" in x2 && x2.indexed); + for (let i = 0; i < indexedInputs.length; i++) { + const param = indexedInputs[i]; + const topic = argTopics[i]; + if (!topic) + throw new DecodeLogTopicsMismatch({ + abiItem, + param + }); + args[isUnnamed ? i : param.name || i] = decodeTopic({ param, value: topic }); } - /** - * If the value is a [[Typed]] instance, validates the underlying value - * and returns it, otherwise returns value directly. - * - * This is useful for functions that with to accept either a [[Typed]] - * object or values. - */ - static dereference(value, type) { - if (_Typed.isTyped(value)) { - if (value.type !== type) { - throw new Error(`invalid type: expecetd ${type}, got ${value.type}`); + const nonIndexedInputs = inputs.filter((x2) => !("indexed" in x2 && x2.indexed)); + if (nonIndexedInputs.length > 0) { + if (data && data !== "0x") { + try { + const decodedData = decodeAbiParameters(nonIndexedInputs, data); + if (decodedData) { + if (isUnnamed) + args = [...args, ...decodedData]; + else { + for (let i = 0; i < nonIndexedInputs.length; i++) { + args[nonIndexedInputs[i].name] = decodedData[i]; + } + } + } + } catch (err) { + if (strict) { + if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError) + throw new DecodeLogDataMismatch({ + abiItem, + data, + params: nonIndexedInputs, + size: size$5(data) + }); + throw err; + } } - return value.value; + } else if (strict) { + throw new DecodeLogDataMismatch({ + abiItem, + data: "0x", + params: nonIndexedInputs, + size: 0 + }); } - return value; - } -}; -_options = new WeakMap(); -let Typed = _Typed; -class AddressCoder extends Coder { - constructor(localName) { - super("address", "address", localName, false); - } - defaultValue() { - return "0x0000000000000000000000000000000000000000"; } - encode(writer, _value2) { - let value = Typed.dereference(_value2, "string"); + return { + eventName: name2, + args: Object.values(args).length > 0 ? args : void 0 + }; +} +function decodeTopic({ param, value }) { + if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) + return value; + const decodedArg = decodeAbiParameters([param], value) || []; + return decodedArg[0]; +} +function parseEventLogs(parameters) { + const { abi: abi2, args, logs, strict = true } = parameters; + const eventName = (() => { + if (!parameters.eventName) + return void 0; + if (Array.isArray(parameters.eventName)) + return parameters.eventName; + return [parameters.eventName]; + })(); + return logs.map((log) => { + var _a2; try { - value = getAddress$1(value); - } catch (error) { - return this._throwError(error.message, _value2); + const abiItem = abi2.find((abiItem2) => abiItem2.type === "event" && log.topics[0] === toEventSelector(abiItem2)); + if (!abiItem) + return null; + const event = decodeEventLog({ + ...log, + abi: [abiItem], + strict + }); + if (eventName && !eventName.includes(event.eventName)) + return null; + if (!includesArgs({ + args: event.args, + inputs: abiItem.inputs, + matchArgs: args + })) + return null; + return { ...event, ...log }; + } catch (err) { + let eventName2; + let isUnnamed; + if (err instanceof AbiEventSignatureNotFoundError) + return null; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict) + return null; + eventName2 = err.abiItem.name; + isUnnamed = (_a2 = err.abiItem.inputs) == null ? void 0 : _a2.some((x2) => !("name" in x2 && x2.name)); + } + return { ...log, args: isUnnamed ? [] : {}, eventName: eventName2 }; } - return writer.writeValue(value); - } - decode(reader2) { - return getAddress$1(toBeHex(reader2.readValue(), 20)); - } + }).filter(Boolean); } -class AnonymousCoder extends Coder { - constructor(coder) { - super(coder.name, coder.type, "_", coder.dynamic); - __publicField(this, "coder"); - this.coder = coder; - } - defaultValue() { - return this.coder.defaultValue(); - } - encode(writer, value) { - return this.coder.encode(writer, value); +function includesArgs(parameters) { + const { args, inputs, matchArgs } = parameters; + if (!matchArgs) + return true; + if (!args) + return false; + function isEqual(input2, value, arg) { + try { + if (input2.type === "address") + return isAddressEqual(value, arg); + if (input2.type === "string" || input2.type === "bytes") + return keccak256$1(toBytes$3(value)) === arg; + return value === arg; + } catch { + return false; + } } - decode(reader2) { - return this.coder.decode(reader2); + if (Array.isArray(args) && Array.isArray(matchArgs)) { + return matchArgs.every((value, index2) => { + if (value === null) + return true; + const input2 = inputs[index2]; + if (!input2) + return false; + const value_ = Array.isArray(value) ? value : [value]; + return value_.some((value2) => isEqual(input2, value2, args[index2])); + }); } + if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs)) + return Object.entries(matchArgs).every(([key, value]) => { + if (value === null) + return true; + const input2 = inputs.find((input3) => input3.name === key); + if (!input2) + return false; + const value_ = Array.isArray(value) ? value : [value]; + return value_.some((value2) => isEqual(input2, value2, args[key])); + }); + return false; } -function pack(writer, coders2, values) { - let arrayValues = []; - if (Array.isArray(values)) { - arrayValues = values; - } else if (values && typeof values === "object") { - let unique = {}; - arrayValues = coders2.map((coder) => { - const name2 = coder.localName; - assert(name2, "cannot encode object for signature with missing names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); - assert(!unique[name2], "cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); - unique[name2] = true; - return values[name2]; +function formatLog$1(log, { args, eventName } = {}) { + return { + ...log, + blockHash: log.blockHash ? log.blockHash : null, + blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null, + logIndex: log.logIndex ? Number(log.logIndex) : null, + transactionHash: log.transactionHash ? log.transactionHash : null, + transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null, + ...eventName ? { args, eventName } : {} + }; +} +async function getLogs(client2, { address, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) { + const strict = strict_ ?? false; + const events = events_ ?? (event ? [event] : void 0); + let topics = []; + if (events) { + const encoded = events.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args: events_ ? void 0 : args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + let logs; + if (blockHash) { + logs = await client2.request({ + method: "eth_getLogs", + params: [{ address, topics, blockHash }] }); } else { - assertArgument(false, "invalid tuple value", "tuple", values); + logs = await client2.request({ + method: "eth_getLogs", + params: [ + { + address, + topics, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock + } + ] + }); } - assertArgument(coders2.length === arrayValues.length, "types/value length mismatch", "tuple", values); - let staticWriter = new Writer(); - let dynamicWriter = new Writer(); - let updateFuncs = []; - coders2.forEach((coder, index2) => { - let value = arrayValues[index2]; - if (coder.dynamic) { - let dynamicOffset = dynamicWriter.length; - coder.encode(dynamicWriter, value); - let updateFunc = staticWriter.writeUpdatableValue(); - updateFuncs.push((baseOffset) => { - updateFunc(baseOffset + dynamicOffset); - }); - } else { - coder.encode(staticWriter, value); - } + const formattedLogs = logs.map((log) => formatLog$1(log)); + if (!events) + return formattedLogs; + return parseEventLogs({ + abi: events, + args, + logs: formattedLogs, + strict }); - updateFuncs.forEach((func) => { - func(staticWriter.length); +} +async function getContractEvents(client2, parameters) { + const { abi: abi2, address, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters; + const event = eventName ? getAbiItem({ abi: abi2, name: eventName }) : void 0; + const events = !event ? abi2.filter((x2) => x2.type === "event") : void 0; + return getAction$1(client2, getLogs, "getLogs")({ + address, + args, + blockHash, + event, + events, + fromBlock, + toBlock, + strict }); - let length = writer.appendWriter(staticWriter); - length += writer.appendWriter(dynamicWriter); - return length; } -function unpack(reader2, coders2) { - let values = []; - let keys = []; - let baseReader = reader2.subReader(0); - coders2.forEach((coder) => { - let value = null; - if (coder.dynamic) { - let offset2 = reader2.readIndex(); - let offsetReader = baseReader.subReader(offset2); - try { - value = coder.decode(offsetReader); - } catch (error) { - if (isError(error, "BUFFER_OVERRUN")) { - throw error; - } - value = error; - value.baseType = coder.name; - value.name = coder.localName; - value.type = coder.type; - } - } else { - try { - value = coder.decode(reader2); - } catch (error) { - if (isError(error, "BUFFER_OVERRUN")) { - throw error; - } - value = error; - value.baseType = coder.name; - value.name = coder.localName; - value.type = coder.type; - } - } - if (value == void 0) { - throw new Error("investigate"); - } - values.push(value); - keys.push(coder.localName || null); - }); - return Result.fromItems(values, keys); -} -class ArrayCoder extends Coder { - constructor(coder, length, localName) { - const type = coder.type + "[" + (length >= 0 ? length : "") + "]"; - const dynamic = length === -1 || coder.dynamic; - super("array", type, localName, dynamic); - __publicField(this, "coder"); - __publicField(this, "length"); - defineProperties$1(this, { coder, length }); - } - defaultValue() { - const defaultChild = this.coder.defaultValue(); - const result = []; - for (let i = 0; i < this.length; i++) { - result.push(defaultChild); - } - return result; - } - encode(writer, _value2) { - const value = Typed.dereference(_value2, "array"); - if (!Array.isArray(value)) { - this._throwError("expected array value", value); - } - let count2 = this.length; - if (count2 === -1) { - count2 = value.length; - writer.writeValue(value.length); - } - assertArgumentCount(value.length, count2, "coder array" + (this.localName ? " " + this.localName : "")); - let coders2 = []; - for (let i = 0; i < value.length; i++) { - coders2.push(this.coder); - } - return pack(writer, coders2, value); +class Eip712DomainNotFoundError extends BaseError$3 { + constructor({ address }) { + super(`No EIP-712 domain found on contract "${address}".`, { + metaMessages: [ + "Ensure that:", + `- The contract is deployed at the address "${address}".`, + "- `eip712Domain()` function exists on the contract.", + "- `eip712Domain()` function matches signature to ERC-5267 specification." + ], + name: "Eip712DomainNotFoundError" + }); } - decode(reader2) { - let count2 = this.length; - if (count2 === -1) { - count2 = reader2.readIndex(); - assert(count2 * WordSize <= reader2.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: reader2.bytes, offset: count2 * WordSize, length: reader2.dataLength }); - } - let coders2 = []; - for (let i = 0; i < count2; i++) { - coders2.push(new AnonymousCoder(this.coder)); +} +async function getEip712Domain(client2, parameters) { + const { address, factory: factory2, factoryData } = parameters; + try { + const [fields, name2, version2, chainId, verifyingContract, salt, extensions] = await getAction$1(client2, readContract$1, "readContract")({ + abi: abi$9, + address, + functionName: "eip712Domain", + factory: factory2, + factoryData + }); + return { + domain: { + name: name2, + version: version2, + chainId: Number(chainId), + verifyingContract, + salt + }, + extensions, + fields + }; + } catch (e2) { + const error = e2; + if (error.name === "ContractFunctionExecutionError" && error.cause.name === "ContractFunctionZeroDataError") { + throw new Eip712DomainNotFoundError({ address }); } - return unpack(reader2, coders2); + throw error; } } -class BooleanCoder extends Coder { - constructor(localName) { - super("bool", "bool", localName, false); - } - defaultValue() { - return false; - } - encode(writer, _value2) { - const value = Typed.dereference(_value2, "bool"); - return writer.writeValue(value ? 1 : 0); - } - decode(reader2) { - return !!reader2.readValue(); +const abi$9 = [ + { + inputs: [], + name: "eip712Domain", + outputs: [ + { name: "fields", type: "bytes1" }, + { name: "name", type: "string" }, + { name: "version", type: "string" }, + { name: "chainId", type: "uint256" }, + { name: "verifyingContract", type: "address" }, + { name: "salt", type: "bytes32" }, + { name: "extensions", type: "uint256[]" } + ], + stateMutability: "view", + type: "function" } +]; +function formatFeeHistory(feeHistory) { + var _a2; + return { + baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)), + gasUsedRatio: feeHistory.gasUsedRatio, + oldestBlock: BigInt(feeHistory.oldestBlock), + reward: (_a2 = feeHistory.reward) == null ? void 0 : _a2.map((reward) => reward.map((value) => BigInt(value))) + }; } -class DynamicBytesCoder extends Coder { - constructor(type, localName) { - super(type, type, localName, true); - } - defaultValue() { - return "0x"; - } - encode(writer, value) { - value = getBytesCopy(value); - let length = writer.writeValue(value.length); - length += writer.writeBytes(value); - return length; - } - decode(reader2) { - return reader2.readBytes(reader2.readIndex(), true); - } +async function getFeeHistory(client2, { blockCount, blockNumber, blockTag = "latest", rewardPercentiles }) { + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const feeHistory = await client2.request({ + method: "eth_feeHistory", + params: [ + numberToHex(blockCount), + blockNumberHex || blockTag, + rewardPercentiles + ] + }, { dedupe: Boolean(blockNumberHex) }); + return formatFeeHistory(feeHistory); } -class BytesCoder extends DynamicBytesCoder { - constructor(localName) { - super("bytes", localName); - } - decode(reader2) { - return hexlify(super.decode(reader2)); - } +async function getFilterChanges(_client3, { filter: filter2 }) { + const strict = "strict" in filter2 && filter2.strict; + const logs = await filter2.request({ + method: "eth_getFilterChanges", + params: [filter2.id] + }); + if (typeof logs[0] === "string") + return logs; + const formattedLogs = logs.map((log) => formatLog$1(log)); + if (!("abi" in filter2) || !filter2.abi) + return formattedLogs; + return parseEventLogs({ + abi: filter2.abi, + logs: formattedLogs, + strict + }); } -class FixedBytesCoder extends Coder { - constructor(size2, localName) { - let name2 = "bytes" + String(size2); - super(name2, name2, localName, false); - __publicField(this, "size"); - defineProperties$1(this, { size: size2 }, { size: "number" }); - } - defaultValue() { - return "0x0000000000000000000000000000000000000000000000000000000000000000".substring(0, 2 + this.size * 2); - } - encode(writer, _value2) { - let data = getBytesCopy(Typed.dereference(_value2, this.type)); - if (data.length !== this.size) { - this._throwError("incorrect data length", _value2); - } - return writer.writeBytes(data); - } - decode(reader2) { - return hexlify(reader2.readBytes(this.size)); - } +async function getFilterLogs(_client3, { filter: filter2 }) { + const strict = filter2.strict ?? false; + const logs = await filter2.request({ + method: "eth_getFilterLogs", + params: [filter2.id] + }); + const formattedLogs = logs.map((log) => formatLog$1(log)); + if (!filter2.abi) + return formattedLogs; + return parseEventLogs({ + abi: filter2.abi, + logs: formattedLogs, + strict + }); } -const Empty = new Uint8Array([]); -class NullCoder extends Coder { - constructor(localName) { - super("null", "", localName, false); - } - defaultValue() { - return null; - } - encode(writer, value) { - if (value != null) { - this._throwError("not null", value); - } - return writer.writeBytes(Empty); - } - decode(reader2) { - reader2.readBytes(0); - return null; - } +async function getStorageAt(client2, { address, blockNumber, blockTag = "latest", slot }) { + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + const data = await client2.request({ + method: "eth_getStorageAt", + params: [address, slot, blockNumberHex || blockTag] + }); + return data; } -const BN_0$5 = BigInt(0); -const BN_1$2 = BigInt(1); -const BN_MAX_UINT256$1 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -class NumberCoder extends Coder { - constructor(size2, signed2, localName) { - const name2 = (signed2 ? "int" : "uint") + size2 * 8; - super(name2, name2, localName, false); - __publicField(this, "size"); - __publicField(this, "signed"); - defineProperties$1(this, { size: size2, signed: signed2 }, { size: "number", signed: "boolean" }); +async function getTransaction(client2, { blockHash, blockNumber, blockTag: blockTag_, hash: hash2, index: index2 }) { + var _a2, _b2, _c2; + const blockTag = blockTag_ || "latest"; + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + let transaction2 = null; + if (hash2) { + transaction2 = await client2.request({ + method: "eth_getTransactionByHash", + params: [hash2] + }, { dedupe: true }); + } else if (blockHash) { + transaction2 = await client2.request({ + method: "eth_getTransactionByBlockHashAndIndex", + params: [blockHash, numberToHex(index2)] + }, { dedupe: true }); + } else if (blockNumberHex || blockTag) { + transaction2 = await client2.request({ + method: "eth_getTransactionByBlockNumberAndIndex", + params: [blockNumberHex || blockTag, numberToHex(index2)] + }, { dedupe: Boolean(blockNumberHex) }); } - defaultValue() { - return 0; + if (!transaction2) + throw new TransactionNotFoundError({ + blockHash, + blockNumber, + blockTag, + hash: hash2, + index: index2 + }); + const format2 = ((_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.transaction) == null ? void 0 : _c2.format) || formatTransaction; + return format2(transaction2); +} +async function getTransactionConfirmations(client2, { hash: hash2, transactionReceipt }) { + const [blockNumber, transaction2] = await Promise.all([ + getAction$1(client2, getBlockNumber, "getBlockNumber")({}), + hash2 ? getAction$1(client2, getTransaction, "getTransaction")({ hash: hash2 }) : void 0 + ]); + const transactionBlockNumber = (transactionReceipt == null ? void 0 : transactionReceipt.blockNumber) || (transaction2 == null ? void 0 : transaction2.blockNumber); + if (!transactionBlockNumber) + return 0n; + return blockNumber - transactionBlockNumber + 1n; +} +const receiptStatuses = { + "0x0": "reverted", + "0x1": "success" +}; +function formatTransactionReceipt$1(transactionReceipt) { + const receipt = { + ...transactionReceipt, + blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null, + contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null, + cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null, + effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null, + gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null, + logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog$1(log)) : null, + to: transactionReceipt.to ? transactionReceipt.to : null, + transactionIndex: transactionReceipt.transactionIndex ? hexToNumber$2(transactionReceipt.transactionIndex) : null, + status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null, + type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null + }; + if (transactionReceipt.blobGasPrice) + receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice); + if (transactionReceipt.blobGasUsed) + receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed); + return receipt; +} +async function getTransactionReceipt$1(client2, { hash: hash2 }) { + var _a2, _b2, _c2; + const receipt = await client2.request({ + method: "eth_getTransactionReceipt", + params: [hash2] + }, { dedupe: true }); + if (!receipt) + throw new TransactionReceiptNotFoundError({ hash: hash2 }); + const format2 = ((_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.transactionReceipt) == null ? void 0 : _c2.format) || formatTransactionReceipt$1; + return format2(receipt); +} +async function multicall(client2, parameters) { + var _a2; + const { allowFailure = true, batchSize: batchSize_, blockNumber, blockTag, multicallAddress: multicallAddress_, stateOverride } = parameters; + const contracts = parameters.contracts; + const batchSize = batchSize_ ?? (typeof ((_a2 = client2.batch) == null ? void 0 : _a2.multicall) === "object" && client2.batch.multicall.batchSize || 1024); + let multicallAddress = multicallAddress_; + if (!multicallAddress) { + if (!client2.chain) + throw new Error("client chain not configured. multicallAddress is required."); + multicallAddress = getChainContractAddress({ + blockNumber, + chain: client2.chain, + contract: "multicall3" + }); } - encode(writer, _value2) { - let value = getBigInt(Typed.dereference(_value2, this.type)); - let maxUintValue = mask(BN_MAX_UINT256$1, WordSize * 8); - if (this.signed) { - let bounds = mask(maxUintValue, this.size * 8 - 1); - if (value > bounds || value < -(bounds + BN_1$2)) { - this._throwError("value out-of-bounds", _value2); + const chunkedCalls = [[]]; + let currentChunk = 0; + let currentChunkSize = 0; + for (let i = 0; i < contracts.length; i++) { + const { abi: abi2, address, args, functionName } = contracts[i]; + try { + const callData = encodeFunctionData({ abi: abi2, args, functionName }); + currentChunkSize += (callData.length - 2) / 2; + if ( + // Check if batching is enabled. + batchSize > 0 && // Check if the current size of the batch exceeds the size limit. + currentChunkSize > batchSize && // Check if the current chunk is not already empty. + chunkedCalls[currentChunk].length > 0 + ) { + currentChunk++; + currentChunkSize = (callData.length - 2) / 2; + chunkedCalls[currentChunk] = []; } - value = toTwos(value, 8 * WordSize); - } else if (value < BN_0$5 || value > mask(maxUintValue, this.size * 8)) { - this._throwError("value out-of-bounds", _value2); + chunkedCalls[currentChunk] = [ + ...chunkedCalls[currentChunk], + { + allowFailure: true, + callData, + target: address + } + ]; + } catch (err) { + const error = getContractError(err, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/multicall", + functionName + }); + if (!allowFailure) + throw error; + chunkedCalls[currentChunk] = [ + ...chunkedCalls[currentChunk], + { + allowFailure: true, + callData: "0x", + target: address + } + ]; } - return writer.writeValue(value); } - decode(reader2) { - let value = mask(reader2.readValue(), this.size * 8); - if (this.signed) { - value = fromTwos(value, this.size * 8); + const aggregate3Results = await Promise.allSettled(chunkedCalls.map((calls) => getAction$1(client2, readContract$1, "readContract")({ + abi: multicall3Abi, + address: multicallAddress, + args: [calls], + blockNumber, + blockTag, + functionName: "aggregate3", + stateOverride + }))); + const results2 = []; + for (let i = 0; i < aggregate3Results.length; i++) { + const result = aggregate3Results[i]; + if (result.status === "rejected") { + if (!allowFailure) + throw result.reason; + for (let j2 = 0; j2 < chunkedCalls[i].length; j2++) { + results2.push({ + status: "failure", + error: result.reason, + result: void 0 + }); + } + continue; + } + const aggregate3Result = result.value; + for (let j2 = 0; j2 < aggregate3Result.length; j2++) { + const { returnData, success } = aggregate3Result[j2]; + const { callData } = chunkedCalls[i][j2]; + const { abi: abi2, address, functionName, args } = contracts[results2.length]; + try { + if (callData === "0x") + throw new AbiDecodingZeroDataError(); + if (!success) + throw new RawContractError({ data: returnData }); + const result2 = decodeFunctionResult({ + abi: abi2, + args, + data: returnData, + functionName + }); + results2.push(allowFailure ? { result: result2, status: "success" } : result2); + } catch (err) { + const error = getContractError(err, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/multicall", + functionName + }); + if (!allowFailure) + throw error; + results2.push({ error, result: void 0, status: "failure" }); + } } - return value; } + if (results2.length !== contracts.length) + throw new BaseError$3("multicall results mismatch"); + return results2; } -class StringCoder extends DynamicBytesCoder { - constructor(localName) { - super("string", localName); - } - defaultValue() { - return ""; - } - encode(writer, _value2) { - return super.encode(writer, toUtf8Bytes(Typed.dereference(_value2, "string"))); - } - decode(reader2) { - return toUtf8String(super.decode(reader2)); +const listenersCache = /* @__PURE__ */ new Map(); +const cleanupCache = /* @__PURE__ */ new Map(); +let callbackCount = 0; +function observe(observerId, callbacks, fn) { + const callbackId = ++callbackCount; + const getListeners = () => listenersCache.get(observerId) || []; + const unsubscribe = () => { + const listeners2 = getListeners(); + listenersCache.set(observerId, listeners2.filter((cb2) => cb2.id !== callbackId)); + }; + const unwatch = () => { + const cleanup2 = cleanupCache.get(observerId); + if (getListeners().length === 1 && cleanup2) + cleanup2(); + unsubscribe(); + }; + const listeners = getListeners(); + listenersCache.set(observerId, [ + ...listeners, + { id: callbackId, fns: callbacks } + ]); + if (listeners && listeners.length > 0) + return unwatch; + const emit2 = {}; + for (const key in callbacks) { + emit2[key] = (...args) => { + var _a2, _b2; + const listeners2 = getListeners(); + if (listeners2.length === 0) + return; + for (const listener of listeners2) + (_b2 = (_a2 = listener.fns)[key]) == null ? void 0 : _b2.call(_a2, ...args); + }; } + const cleanup = fn(emit2); + if (typeof cleanup === "function") + cleanupCache.set(observerId, cleanup); + return unwatch; } -class TupleCoder extends Coder { - constructor(coders2, localName) { - let dynamic = false; - const types2 = []; - coders2.forEach((coder) => { - if (coder.dynamic) { - dynamic = true; - } - types2.push(coder.type); - }); - const type = "tuple(" + types2.join(",") + ")"; - super("tuple", type, localName, dynamic); - __publicField(this, "coders"); - defineProperties$1(this, { coders: Object.freeze(coders2.slice()) }); - } - defaultValue() { - const values = []; - this.coders.forEach((coder) => { - values.push(coder.defaultValue()); - }); - const uniqueNames = this.coders.reduce((accum, coder) => { - const name2 = coder.localName; - if (name2) { - if (!accum[name2]) { - accum[name2] = 0; - } - accum[name2]++; - } - return accum; - }, {}); - this.coders.forEach((coder, index2) => { - let name2 = coder.localName; - if (!name2 || uniqueNames[name2] !== 1) { +async function wait$1(time2) { + return new Promise((res) => setTimeout(res, time2)); +} +function poll(fn, { emitOnBegin, initialWaitTime, interval }) { + let active = true; + const unwatch = () => active = false; + const watch = async () => { + let data = void 0; + if (emitOnBegin) + data = await fn({ unpoll: unwatch }); + const initialWait = await (initialWaitTime == null ? void 0 : initialWaitTime(data)) ?? interval; + await wait$1(initialWait); + const poll2 = async () => { + if (!active) return; + await fn({ unpoll: unwatch }); + await wait$1(interval); + poll2(); + }; + poll2(); + }; + watch(); + return unwatch; +} +function watchBlocks(client2, { blockTag = "latest", emitMissed = false, emitOnBegin = false, onBlock, onError, includeTransactions: includeTransactions_, poll: poll_, pollingInterval = client2.pollingInterval }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (client2.transport.type === "webSocket") + return false; + if (client2.transport.type === "fallback" && client2.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + const includeTransactions = includeTransactions_ ?? false; + let prevBlock; + const pollBlocks = () => { + const observerId = stringify$3([ + "watchBlocks", + client2.uid, + blockTag, + emitMissed, + emitOnBegin, + includeTransactions, + pollingInterval + ]); + return observe(observerId, { onBlock, onError }, (emit2) => poll(async () => { + var _a2; + try { + const block = await getAction$1(client2, getBlock, "getBlock")({ + blockTag, + includeTransactions + }); + if (block.number && (prevBlock == null ? void 0 : prevBlock.number)) { + if (block.number === prevBlock.number) + return; + if (block.number - prevBlock.number > 1 && emitMissed) { + for (let i = (prevBlock == null ? void 0 : prevBlock.number) + 1n; i < block.number; i++) { + const block2 = await getAction$1(client2, getBlock, "getBlock")({ + blockNumber: i, + includeTransactions + }); + emit2.onBlock(block2, prevBlock); + prevBlock = block2; + } + } + } + if ( + // If no previous block exists, emit. + !(prevBlock == null ? void 0 : prevBlock.number) || // If the block tag is "pending" with no block number, emit. + blockTag === "pending" && !(block == null ? void 0 : block.number) || // If the next block number is greater than the previous block number, emit. + // We don't want to emit blocks in the past. + block.number && block.number > prevBlock.number + ) { + emit2.onBlock(block, prevBlock); + prevBlock = block; + } + } catch (err) { + (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); } - if (name2 === "length") { - name2 = "_length"; + }, { + emitOnBegin, + interval: pollingInterval + })); + }; + const subscribeBlocks = () => { + let active = true; + let emitFetched = true; + let unsubscribe = () => active = false; + (async () => { + try { + if (emitOnBegin) { + getAction$1(client2, getBlock, "getBlock")({ + blockTag, + includeTransactions + }).then((block) => { + if (!active) + return; + if (!emitFetched) + return; + onBlock(block, void 0); + emitFetched = false; + }); + } + const transport = (() => { + if (client2.transport.type === "fallback") { + const transport2 = client2.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client2.transport; + return transport2.value; + } + return client2.transport; + })(); + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["newHeads"], + onData(data) { + var _a2, _b2, _c2; + if (!active) + return; + const format2 = ((_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.block) == null ? void 0 : _c2.format) || formatBlock$1; + const block = format2(data.result); + onBlock(block, prevBlock); + emitFetched = false; + prevBlock = block; + }, + onError(error) { + onError == null ? void 0 : onError(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError == null ? void 0 : onError(err); } - if (values[name2] != null) { - return; + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollBlocks() : subscribeBlocks(); +} +function watchBlockNumber(client2, { emitOnBegin = false, emitMissed = false, onBlockNumber, onError, poll: poll_, pollingInterval = client2.pollingInterval }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (client2.transport.type === "webSocket") + return false; + if (client2.transport.type === "fallback" && client2.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + let prevBlockNumber; + const pollBlockNumber = () => { + const observerId = stringify$3([ + "watchBlockNumber", + client2.uid, + emitOnBegin, + emitMissed, + pollingInterval + ]); + return observe(observerId, { onBlockNumber, onError }, (emit2) => poll(async () => { + var _a2; + try { + const blockNumber = await getAction$1(client2, getBlockNumber, "getBlockNumber")({ cacheTime: 0 }); + if (prevBlockNumber) { + if (blockNumber === prevBlockNumber) + return; + if (blockNumber - prevBlockNumber > 1 && emitMissed) { + for (let i = prevBlockNumber + 1n; i < blockNumber; i++) { + emit2.onBlockNumber(i, prevBlockNumber); + prevBlockNumber = i; + } + } + } + if (!prevBlockNumber || blockNumber > prevBlockNumber) { + emit2.onBlockNumber(blockNumber, prevBlockNumber); + prevBlockNumber = blockNumber; + } + } catch (err) { + (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); } - values[name2] = values[index2]; + }, { + emitOnBegin, + interval: pollingInterval + })); + }; + const subscribeBlockNumber = () => { + const observerId = stringify$3([ + "watchBlockNumber", + client2.uid, + emitOnBegin, + emitMissed + ]); + return observe(observerId, { onBlockNumber, onError }, (emit2) => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const transport = (() => { + if (client2.transport.type === "fallback") { + const transport2 = client2.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client2.transport; + return transport2.value; + } + return client2.transport; + })(); + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["newHeads"], + onData(data) { + var _a2; + if (!active) + return; + const blockNumber = hexToBigInt((_a2 = data.result) == null ? void 0 : _a2.number); + emit2.onBlockNumber(blockNumber, prevBlockNumber); + prevBlockNumber = blockNumber; + }, + onError(error) { + var _a2; + (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError == null ? void 0 : onError(err); + } + })(); + return () => unsubscribe(); }); - return Object.freeze(values); - } - encode(writer, _value2) { - const value = Typed.dereference(_value2, "tuple"); - return pack(writer, this.coders, value); - } - decode(reader2) { - return unpack(reader2, this.coders); - } -} -function id$1(value) { - return keccak256$1(toUtf8Bytes(value)); + }; + return enablePolling ? pollBlockNumber() : subscribeBlockNumber(); } -var COMPRESSED$1 = "AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQCuhzc3NzcBP68NEfMABQdHBuw5BV8FYAA9MzkI9r4ZBg7QyQAWA9CeOwLNCjcCjqkChuA/lm+RAsXTAoP6ASfnEQDytQFJAjWVCkeXAOsA6godAB/cwdAUE0WlBCN/AQUCQRjFD/MRBjHxDQSJbw0jBzUAswBxme+tnIcAYwabAysG8QAjAEMMmxcDqgPKQyDXCMMxA7kUQwD3NXOrAKmFIAAfBC0D3x4BJQDBGdUFAhEgVD8JnwmQJiNWYUzrg0oAGwAUAB0AFnNcACkAFgBP9h3gPfsDOWDKneY2ChglX1UDYD30ABsAFAAdABZzIGRAnwDD8wAjAEEMzRbDqgMB2sAFYwXqAtCnAsS4AwpUJKRtFHsadUz9AMMVbwLpABM1NJEX0ZkCgYMBEyMAxRVvAukAEzUBUFAtmUwSAy4DBTER33EftQHfSwB5MxJ/AjkWKQLzL8E/cwBB6QH9LQDPDtO9ASNriQC5DQANAwCK21EFI91zHwCoL9kBqQcHBwcHKzUDowBvAQohPvU3fAQgHwCyAc8CKQMA5zMSezr7ULgFmDp/LzVQBgEGAi8FYQVgt8AFcTtlQhpCWEmfe5tmZ6IAExsDzQ8t+X8rBKtTAltbAn0jsy8Bl6utPWMDTR8Ei2kRANkDBrNHNysDBzECQWUAcwFpJ3kAiyUhAJ0BUb8AL3EfAbfNAz81KUsFWwF3YQZtAm0A+VEfAzEJDQBRSQCzAQBlAHsAM70GD/v3IZWHBwARKQAxALsjTwHZAeMPEzmXgIHwABIAGQA8AEUAQDt3gdvIEGcQZAkGTRFMdEIVEwK0D64L7REdDNkq09PgADSxB/MDWwfzA1sDWwfzB/MDWwfzA1sDWwNbA1scEvAi28gQZw9QBHUFlgWTBN4IiyZREYkHMAjaVBV0JhxPA00BBCMtSSQ7mzMTJUpMFE0LCAQ2SmyvfUADTzGzVP2QqgPTMlc5dAkGHnkSqAAyD3skNb1OhnpPcagKU0+2tYdJak5vAsY6sEAACikJm2/Dd1YGRRAfJ6kQ+ww3AbkBPw3xS9wE9QY/BM0fgRkdD9GVoAipLeEM8SbnLqWAXiP5KocF8Uv4POELUVFsD10LaQnnOmeBUgMlAREijwrhDT0IcRD3Cs1vDekRSQc9A9lJngCpBwULFR05FbkmFGKwCw05ewb/GvoLkyazEy17AAXXGiUGUQEtGwMA0y7rhbRaNVwgT2MGBwspI8sUrFAkDSlAu3hMGh8HGSWtApVDdEqLUToelyH6PEENai4XUYAH+TwJGVMLhTyiRq9FEhHWPpE9TCJNTDAEOYMsMyePCdMPiQy9fHYBXQklCbUMdRM1ERs3yQg9Bx0xlygnGQglRplgngT7owP3E9UDDwVDCUUHFwO5HDETMhUtBRGBKNsC9zbZLrcCk1aEARsFzw8pH+MQVEfkDu0InwJpA4cl7wAxFSUAGyKfCEdnAGOP3FMJLs8Iy2pwI3gDaxTrZRF3B5UOWwerHDcVwxzlcMxeD4YMKKezCV8BeQmdAWME5wgNNV+MpCBFZ1eLXBifIGVBQ14AAjUMaRWjRMGHfAKPD28SHwE5AXcHPQ0FAnsR8RFvEJkI74YINbkz/DopBFMhhyAVCisDU2zSCysm/Qz8bQGnEmYDEDRBd/Jnr2C6KBgBBx0yyUFkIfULlk/RDKAaxRhGVDIZ6AfDA/ca9yfuQVsGAwOnBxc6UTPyBMELbQiPCUMATQ6nGwfbGG4KdYzUATWPAbudA1uVhwJzkwY7Bw8Aaw+LBX3pACECqwinAAkA0wNbAD0CsQehAB0AiUUBQQMrMwEl6QKTA5cINc8BmTMB9y0EH8cMGQD7O25OAsO1AoBuZqYF4VwCkgJNOQFRKQQJUktVA7N15QDfAE8GF+NLARmvTs8e50cB43MvAMsA/wAJOQcJRQHRAfdxALsBYws1Caa3uQFR7S0AhwAZbwHbAo0A4QA5AIP1AVcAUQVd/QXXAlNNARU1HC9bZQG/AyMBNwERAH0Gz5GpzQsjBHEH1wIQHxXlAu8yB7kFAyLjE9FCyQK94lkAMhoKPAqrCqpgX2Q3CjV2PVQAEh+sPss/UgVVO1c7XDtXO1w7VztcO1c7XDtXO1wDm8Pmw+YKcF9JYe8Mqg3YRMw6TRPfYFVgNhPMLbsUxRXSJVoZQRrAJwkl6FUNDwgt12Y0CDA0eRfAAEMpbINFY4oeNApPHOtTlVT8LR8AtUumM7MNsBsZREQFS3XxYi4WEgomAmSFAmJGX1GzAV83JAKh+wJonAJmDQKfiDgfDwJmPwJmKgRyBIMDfxcDfpY5Cjl7GzmGOicnAmwhAjI6OA4CbcsCbbLzjgM3a0kvAWsA4gDlAE4JB5wMkQECD8YAEbkCdzMCdqZDAnlPRwJ4viFg30WyRvcCfEMCeswCfQ0CfPRIBEiBZygALxlJXEpfGRtK0ALRBQLQ0EsrA4hTA4fqRMmRNgLypV0HAwOyS9JMMSkH001QTbMCi0MCitzFHwshR2sJuwKOOwKOYESbhQKO3QKOYHxRuFM5AQ5S2FSJApP/ApMQAO0AIFUiVbNV1AosHymZijLleGpFPz0Cl6MC77ZYJawAXSkClpMCloCgAK1ZsFoNhVEAPwKWuQKWUlxIXNUCmc8CmWhczl0LHQKcnznGOqECnBoCn58CnryOACETNS4TAp31Ap6WALlBYThh8wKe1wKgcgGtAp6jIwKeUqljzGQrKS8CJ7MCJoICoP8CoFDbAqYzAqXSAqgDAIECp/ZogGi1AAdNaiBq1QKs5wKssgKtawKtBgJXIQJV4AKx5dsDH1JsmwKywRECsuwbbORtZ21MYwMl0QK2YD9DbpQDKUkCuGICuUsZArkue3A6cOUCvR0DLbYDMhUCvoxyBgMzdQK+HnMmc1MCw88CwwhzhnRPOUl05AM8qwEDPJ4DPcMCxYACxksCxhSNAshtVQLISALJUwLJMgJkoQLd1nh9ZXiyeSlL1AMYp2cGAmH4GfeVKHsPXpZevxUCz28Cz3AzT1fW9xejAMqxAs93AS3uA04Wfk8JAtwrAtuOAtJTA1JgA1NjAQUDVZCAjUMEzxrxZEl5A4LSg5EC2ssC2eKEFIRNp0ADhqkAMwNkEoZ1Xf0AWQLfaQLevHd7AuIz7RgB8zQrAfSfAfLWiwLr9wLpdH0DAur9AuroAP1LAb0C7o0C66CWrpcHAu5DA4XkmH1w5HGlAvMHAG0DjhqZlwL3FwORcgOSiwL3nAL53QL4apogmq+/O5siA52HAv7+AR8APZ8gAZ+3AwWRA6ZuA6bdANXJAwZuoYyiCQ0DDE0BEwEjB3EGZb1rCQC/BG/DFY8etxEAG3k9ACcDNxJRA42DAWcrJQCM8wAlAOanC6OVCLsGI6fJBgCvBRnDBvElRUYFFoAFcD9GSDNCKUK8X3kZX8QAls0FOgCQVCGbwTsuYDoZutcONxjOGJHJ/gVfBWAFXwVgBWsFYAVfBWAFXwVgBV8FYAVfBWBOHQjfjW8KCgoKbF7xMwTRA7kGN8PDAMMEr8MA70gxFroFTj5xPnhCR0K+X30/X/AAWBkzswCNBsxzzASm70aCRS4rDDMeLz49fnXfcsH5GcoscQFz13Y4HwVnBXLJycnACNdRYwgICAqEXoWTxgA7P4kACxbZBu21Kw0AjMsTAwkVAOVtJUUsJ1JCuULESUArXy9gPi9AKwnJRQYKTD9LPoA+iT54PnkCkULEUUpDX9NWV3JVEjQAc1w3A3IBE3YnX+g7QiMJb6MKaiszRCUuQrNCxDPMCcwEX9EWJzYREBEEBwIHKn6l33JCNVIfybPJtAltydPUCmhBZw/tEKsZAJOVJU1CLRuxbUHOQAo7P0s+eEJHHA8SJVRPdGM0NVrpvBoKhfUlM0JHHGUQUhEWO1xLSj8MO0ucNAqJIzVCRxv9EFsqKyA4OQgNj2nwZgp5ZNFgE2A1K3YHS2AhQQojJmC7DgpzGG1WYFUZCQYHZO9gHWCdYIVgu2BTYJlwFh8GvRbcXbG8YgtDHrMBwzPVyQonHQgkCyYBgQJ0Ajc4nVqIAwGSCsBPIgDsK3SWEtIVBa5N8gGjAo+kVwVIZwD/AEUSCDweX4ITrRQsJ8K3TwBXFDwEAB0TvzVcAtoTS20RIwDgVgZ9BBImYgA5AL4Coi8LFnezOkCnIQFjAY4KBAPh9RcGsgZSBsEAJctdsWIRu2kTkQstRw7DAcMBKgpPBGIGMDAwKCYnKTQaLg4AKRSVAFwCdl+YUZ0JdicFD3lPAdt1F9ZZKCGxuE3yBxkFVGcA/wBFEgiCBwAOLHQSjxOtQDg1z7deFRMAZ8QTAGtKb1ApIiPHADkAvgKiLy1DFtYCmBiDAlDDWNB0eo7fpaMO/aEVRRv0ATEQZBIODyMEAc8JQhCbDRgzFD4TAEMAu9YBCgCsAOkAm5I3ABwAYxvONnR+MhXJAxgKQyxL2+kkJhMbhQKDBMkSsvF0AD9BNQ6uQC7WqSQHwxEAEEIu1hkhAH2z4iQPwyJPHNWpdyYBRSpnJALzoBAEVPPsH20MxA0CCEQKRgAFyAtFAlMNwwjEDUQJRArELtapMg7DDZgJIw+TGukEIwvDFkMAqAtDEMMMBhioe+QAO3MMRAACrgnEBSPY9Q0FDnbSBoMAB8MSYxkSxAEJAPIJAAB8FWMOFtMc/HcXwxhDAC7DAvOowwAewwJdKDKHAAHDAALrFUQVwwAbwyvzpWMWv8wA/ABpAy++bcYDUKPD0KhDCwKmJ1MAAmMA5+UZwxAagwipBRL/eADfw6fDGOMCGsOjk3l6BwOpo4sAEsMOGxMAA5sAbcMOAAvDp0MJGkMDwgipnNIPAwfIqUMGAOGDAAPzABXDAAcDAAnDAGmTABrDAA7DChjDjnEWAwABYwAOcwAuUyYABsMAF8MIKQANUgC6wy4AA8MADqMq8wCyYgAcIwAB8wqpAAXOCx0V4wAHowBCwwEKAGnDAAuDAB3DAAjDCakABdIAbqcZ3QCZCCkABdIAAAFDAAfjAB2jCCkABqIACYMAGzMAbSMA5sOIAAhjAAhDABTDBAkpAAbSAOOTAAlDC6kOzPtnAAdDAG6kQFAATwAKwwwAA0MACbUDPwAHIwAZgwACE6cDAAojAApDAAoDp/MGwwAJIwADEwAQQwgAFEMAEXMAD5MADfMADcMAGRMOFiMAFUMAbqMWuwHDAMIAE0MLAGkzEgDhUwACQwAEWgAXgwUjAAbYABjDBSYBgzBaAEFNALcQBxUMegAwMngBrA0IZgJ0KxQHBREPd1N0ZzKRJwaIHAZqNT4DqQq8BwngAB4DAwt2AX56T1ocKQNXAh1GATQGC3tOxYNagkgAMQA5CQADAQEAWxLjAIOYNAEzAH7tFRk6TglSAF8NAAlYAQ+S1ACAQwQorQBiAN4dAJ1wPyeTANVzuQDX3AIeEMp9eyMgXiUAEdkBkJizKltbVVAaRMqRAAEAhyQ/SDEz6BmfVwB6ATEsOClKIRcDOF0E/832AFNt5AByAnkCRxGCOs94NjXdAwINGBonDBwPALW2AwICAgAAAAAAAAYDBQMDARrUAwAtAAAAAgEGBgYGBgYFBQUFBQUEBQYHCAkEBQUFBQQAAAICAAAAIgCNAJAAlT0A6gC7ANwApEQAwgCyAK0AqADuAKYA2gCjAOcBCAEDAMcAgQBiANIA1AEDAN4A8gCQAKkBMQDqAN8A3AsBCQ8yO9ra2tq8xuLT1tRJOB0BUgFcNU0BWgFpAWgBWwFMUUlLbhMBUxsNEAs6PhMOACcUKy0vMj5AQENDQ0RFFEYGJFdXV1dZWVhZL1pbXVxcI2NnZ2ZoZypsbnZ1eHh4eHh4enp6enp6enp6enp8fH18e2IARPIASQCaAHgAMgBm+ACOAFcAVwA3AnbvAIsABfj4AGQAk/IAnwBPAGIAZP//sACFAIUAaQBWALEAJAC2AIMCQAJDAPwA5wD+AP4A6AD/AOkA6QDoAOYALwJ7AVEBQAE+AVQBPgE+AT4BOQE4ATgBOAEcAVgXADEQCAEAUx8SHgsdHhYAjgCWAKYAUQBqIAIxAHYAbwCXAxUDJzIDIUlGTzEAkQJPAMcCVwKkAMAClgKWApYClgKWApYCiwKWApYClgKWApYClgKVApUCmAKgApcClgKWApQClAKUApQCkgKVAnUB1AKXAp8ClgKWApUeAIETBQD+DQOfAmECOh8BVBg9AuIZEjMbAU4/G1WZAXusRAFpYQEFA0FPAQYAmTEeIJdyADFoAHEANgCRA5zMk/C2jGINwjMWygIZCaXdfDILBCs5dAE7YnQBugDlhoiHhoiGiYqKhouOjIaNkI6Ij4qQipGGkoaThpSSlYaWhpeKmIaZhpqGm4aci52QnoqfhuIC4XTpAt90AIp0LHSoAIsAdHQEQwRABEIERQRDBEkERgRBBEcESQRIBEQERgRJAJ5udACrA490ALxuAQ10ANFZdHQA13QCFHQA/mJ0AP4BIQD+APwA/AD9APwDhGZ03ASMK23HAP4A/AD8AP0A/CR0dACRYnQA/gCRASEA/gCRAvQA/gCRA4RmdNwEjCttxyR0AP9idAEhAP4A/gD8APwA/QD8AP8A/AD8AP0A/AOEZnTcBIwrbcckdHQAkWJ0ASEA/gCRAP4AkQL0AP4AkQOEZnTcBIwrbcckdAJLAT50AlIBQXQCU8l0dAJfdHQDpgL0A6YDpgOnA6cDpwOnA4RmdNwEjCttxyR0dACRYnQBIQOmAJEDpgCRAvQDpgCRA4RmdNwEjCttxyR0BDh0AJEEOQCRDpU5dSgCADR03gV2CwArdAEFAM5iCnR0AF1iAAYcOgp0dACRCnQAXAEIwWZ0CnRmdHQAkWZ0CnRmdEXgAFF03gp0dEY0tlT2u3SOAQTwscwhjZZKrhYcBSfFp9XNbKiVDOD2b+cpe4/Z17mQnbtzzhaeQtE2GGj0IDNTjRUSyTxxw/RPHW/+vS7d1NfRt9z9QPZg4X7QFfhCnkvgNPIItOsC2eV6hPannZNHlZ9xrwZXIMOlu3jSoQSq78WEjwLjw1ELSlF1aBvfzwk5ZX7AUvQzjPQKbDuQ+sm4wNOp4A6AdVuRS0t1y/DZpg4R6m7FNjM9HgvW7Bi88zaMjOo6lM8wtBBdj8LP4ylv3zCXPhebMKJc066o9sF71oFW/8JXu86HJbwDID5lzw5GWLR/LhT0Qqnp2JQxNZNfcbLIzPy+YypqRm/lBmGmex+82+PisxUumSeJkALIT6rJezxMH+CTJmQtt5uwTVbL3ptmjDUQzlSIvWi8Tl7ng1NpuRn1Ng4n14Qc+3Iil7OwkvNWogLSPkn3pihIFytyIGmMhOe3n1tWsuMy9BdKyqF4Z3v2SgggTL9KVvMXPnCbRe+oOuFFP3HejBG/w9gvmfNYvg6JuWia2lcSSN1uIjBktzoIazOHPJZ7kKHPz8mRWVdW3lA8WGF9dQF6Bm673boov3BUWDU2JNcahR23GtfHKLOz/viZ+rYnZFaIznXO67CYEJ1fXuTRpZhYZkKe54xeoagkNGLs+NTZHE0rX45/XvQ2RGADX6vcAvdxIUBV27wxGm2zjZo4X3ILgAlrOFheuZ6wtsvaIj4yLY7qqawlliaIcrz2G+c3vscAnCkCuMzMmZvMfu9lLwTvfX+3cVSyPdN9ZwgDZhfjRgNJcLiJ67b9xx8JHswprbiE3v9UphotAPIgnXVIN5KmMc0piXhc6cChPnN+MRhG9adtdttQTTwSIpl8I4/j//d3sz1326qTBTpPRM/Hgh3kzqEXs8ZAk4ErQhNO8hzrQ0DLkWMA/N+91tn2MdOJnWC2FCZehkQrwzwbKOjhvZsbM95QoeL9skYyMf4srVPVJSgg7pOLUtr/n9eT99oe9nLtFRpjA9okV2Kj8h9k5HaC0oivRD8VyXkJ81tcd4fHNXPCfloIQasxsuO18/46dR2jgul/UIet2G0kRvnyONMKhHs6J26FEoqSqd+rfYjeEGwHWVDpX1fh1jBBcKGMqRepju9Y00mDVHC+Xdij/j44rKfvfjGinNs1jO/0F3jB83XCDINN/HB84axlP+3E/klktRo+vl3U/aiyMJbIodE1XSsDn6UAzIoMtUObY2+k/4gY/l+AkZJ5Sj2vQrkyLm3FoxjhDX+31UXBFf9XrAH31fFqoBmDEZvhvvpnZ87N+oZEu7U9O/nnk+QWj3x8uyoRbEnf+O5UMr9i0nHP38IF5AvzrBW8YWBUR0mIAzIvndQq9N3v/Jto3aPjPXUPl8ASdPPyAp7jENf8bk7VMM9ol9XGmlBmeDMuGqt+WzuL6CXAxXjIhCPM5vACchgMJ/8XBGLO/D1isVvGhwwHHr1DLaI5mn2Jr/b1pUD90uciDaS8cXNDzCWvNmT/PhQe5e8nTnnnkt8Ds/SIjibcum/fqDhKopxAY8AkSrPn+IGDEKOO+U3XOP6djFs2H5N9+orhOahiQk5KnEUWa+CzkVzhp8bMHRbg81qhjjXuIKbHjSLSIBKWqockGtKinY+z4/RdBUF6pcc3JmnlxVcNgrI4SEzKUZSwcD2QCyxzKve+gAmg6ZuSRkpPFa6mfThu7LJNu3H5K42uCpNvPAsoedolKV/LHe/eJ+BbaG5MG0NaSGVPRUmNFMFFSSpXEcXwbVh7UETOZZtoVNRGOIbbkig3McEtR68cG0RZAoJevWYo7Dg/lZ1CQzblWeUvVHmr8fY4Nqd9JJiH/zEX24mJviH60fAyFr0A3c4bC1j3yZU60VgJxXn8JgJXLUIsiBnmKmMYz+7yBQFBvqb2eYnuW59joZBf56/wXvWIR4R8wTmV80i1mZy+S4+BUES+hzjk0uXpC///z/IlqHZ1monzlXp8aCfhGKMti73FI1KbL1q6IKO4fuBuZ59gagjn5xU79muMpHXg6S+e+gDM/U9BKLHbl9l6o8czQKl4RUkJJiqftQG2i3BMg/TQlUYFkJDYBOOvAugYuzYSDnZbDDd/aSd9x0Oe6F+bJcHfl9+gp6L5/TgA+BdFFovbfCrQ40s5vMPw8866pNX8zyFGeFWdxIpPVp9Rg1UPOVFbFZrvaFq/YAzHQgqMWpahMYfqHpmwXfHL1/kpYmGuHFwT55mQu0dylfNuq2Oq0hTMCPwqfxnuBIPLXfci4Y1ANy+1CUipQxld/izVh16WyG2Q0CQQ9NqtAnx1HCHwDj7sYxOSB0wopZSnOzxQOcExmxrVTF2BkOthVpGfuhaGECfCJpJKpjnihY+xOT2QJxN61+9K6QSqtv2Shr82I3jgJrqBg0wELFZPjvHpvzTtaJnLK6Vb97Yn933koO/saN7fsjwNKzp4l2lJVx2orjCGzC/4ZL4zCver6aQYtC5sdoychuFE6ufOiog+VWi5UDkbmvmtah/3aArEBIi39s5ILUnlFLgilcGuz9CQshEY7fw2ouoILAYPVT/gyAIq3TFAIwVsl+ktkRz/qGfnCDGrm5gsl/l9QdvCWGsjPz3dU7XuqKfdUrr/6XIgjp4rey6AJBmCmUJMjITHVdFb5m1p+dLMCL8t55zD42cmftmLEJC0Da04YiRCVUBLLa8D071/N5UBNBXDh0LFsmhV/5B5ExOB4j3WVG/S3lfK5o+V6ELHvy6RR9n4ac+VsK4VE4yphPvV+kG9FegTBH4ZRXL2HytUHCduJazB/KykjfetYxOXTLws267aGOd+I+JhKP//+VnXmS90OD/jvLcVu0asyqcuYN1mSb6XTlCkqv1vigZPIYwNF/zpWcT1GR/6aEIRjkh0yhg4LXJfaGobYJTY4JI58KiAKgmmgAKWdl5nYCeLqavRJGQNuYuZtZFGx+IkI4w4NS2xwbetNMunOjBu/hmKCI/w7tfiiyUd//4rbTeWt4izBY8YvGIN6vyKYmP/8X8wHKCeN+WRcKM70+tXKNGyevU9H2Dg5BsljnTf8YbsJ1TmMs74Ce2XlHisleguhyeg44rQOHZuw/6HTkhnnurK2d62q6yS7210SsAIaR+jXMQA+svkrLpsUY+F30Uw89uOdGAR6vo4FIME0EfVVeHTu6eKicfhSqOeXJhbftcd08sWEnNUL1C9fnprTgd83IMut8onVUF0hvqzZfHduPjbjwEXIcoYmy+P6tcJZHmeOv6VrvEdkHDJecjHuHeWANe79VG662qTjA/HCvumVv3qL+LrOcpqGps2ZGwQdFJ7PU4iuyRlBrwfO+xnPyr47s2cXVbWzAyznDiBGjCM3ksxjjqM62GE9C8f5U38kB3VjtabKp/nRdvMESPGDG90bWRLAt1Qk5DyLuazRR1YzdC1c+hZXvAWV8xA72S4A8B67vjVhbba3MMop293FeEXpe7zItMWrJG/LOH9ByOXmYnNJfjmfuX9KbrpgLOba4nZ+fl8Gbdv/ihv+6wFGKHCYrVwmhFC0J3V2bn2tIB1wCc1CST3d3X2OyxhguXcs4sm679UngzofuSeBewMFJboIQHbUh/m2JhW2hG9DIvG2t7yZIzKBTz9wBtnNC+2pCRYhSIuQ1j8xsz5VvqnyUIthvuoyyu7fNIrg/KQUVmGQaqkqZk/Vx5b33/gsEs8yX7SC1J+NV4icz6bvIE7C5G6McBaI8rVg56q5QBJWxn/87Q1sPK4+sQa8fLU5gXo4paaq4cOcQ4wR0VBHPGjKh+UlPCbA1nLXyEUX45qZ8J7/Ln4FPJE2TdzD0Z8MLSNQiykMMmSyOCiFfy84Rq60emYB2vD09KjYwsoIpeDcBDTElBbXxND72yhd9pC/1CMid/5HUMvAL27OtcIJDzNKpRPNqPOpyt2aPGz9QWIs9hQ9LiX5s8m9hjTUu/f7MyIatjjd+tSfQ3ufZxPpmJhTaBtZtKLUcfOCUqADuO+QoH8B9v6U+P0HV1GLQmtoNFTb3s74ivZgjES0qfK+8RdGgBbcCMSy8eBvh98+et1KIFqSe1KQPyXULBMTsIYnysIwiZBJYdI20vseV+wuJkcqGemehKjaAb9L57xZm3g2zX0bZ2xk/fU+bCo7TlnbW7JuF1YdURo/2Gw7VclDG1W7LOtas2LX4upifZ/23rzpsnY/ALfRgrcWP5hYmV9VxVOQA1fZvp9F2UNU+7d7xRyVm5wiLp3/0dlV7vdw1PMiZrbDAYzIVqEjRY2YU03sJhPnlwIPcZUG5ltL6S8XCxU1eYS5cjr34veBmXAvy7yN4ZjArIG0dfD/5UpBNlX1ZPoxJOwyqRi3wQWtOzd4oNKh0LkoTm8cwqgIfKhqqGOhwo71I+zXnMemTv2B2AUzABWyFztGgGULjDDzWYwJUVBTjKCn5K2QGMK1CQT7SzziOjo+BhAmqBjzuc3xYym2eedGeOIRJVyTwDw37iCMe4g5Vbnsb5ZBdxOAnMT7HU4DHpxWGuQ7GeiY30Cpbvzss55+5Km1YsbD5ea3NI9QNYIXol5apgSu9dZ8f8xS5dtHpido5BclDuLWY4lhik0tbJa07yJhH0BOyEut/GRbYTS6RfiTYWGMCkNpfSHi7HvdiTglEVHKZXaVhezH4kkXiIvKopYAlPusftpE4a5IZwvw1x/eLvoDIh/zpo9FiQInsTb2SAkKHV42XYBjpJDg4374XiVb3ws4qM0s9eSQ5HzsMU4OZJKuopFjBM+dAZEl8RUMx5uU2N486Kr141tVsGQfGjORYMCJAMsxELeNT4RmWjRcpdTGBwcx6XN9drWqPmJzcrGrH4+DRc7+n1w3kPZwu0BkNr6hQrqgo7JTB9A5kdJ/H7P4cWBMwsmuixAzJB3yrQpnGIq90lxAXLzDCdn1LPibsRt7rHNjgQBklRgPZ8vTbjXdgXrTWQsK5MdrXXQVPp0Rinq3frzZKJ0qD6Qhc40VzAraUXlob1gvkhK3vpmHgI6FRlQZNx6eRqkp0zy4AQlX813fAPtL3jMRaitGFFjo0zmErloC+h+YYdVQ6k4F/epxAoF0BmqEoKNTt6j4vQZNQ2BoqF9Vj53TOIoNmDiu9Xp15RkIgQIGcoLpfoIbenzpGUAtqFJp5W+LLnx38jHeECTJ/navKY1NWfN0sY1T8/pB8kIH3DU3DX+u6W3YwpypBMYOhbSxGjq84RZ84fWJow8pyHqn4S/9J15EcCMsXqrfwyd9mhiu3+rEo9pPpoJkdZqHjra4NvzFwuThNKy6hao/SlLw3ZADUcUp3w3SRVfW2rhl80zOgTYnKE0Hs2qp1J6H3xqPqIkvUDRMFDYyRbsFI3M9MEyovPk8rlw7/0a81cDVLmBsR2ze2pBuKb23fbeZC0uXoIvDppfTwIDxk1Oq2dGesGc+oJXWJLGkOha3CX+DUnzgAp9HGH9RsPZN63Hn4RMA5eSVhPHO+9RcRb/IOgtW31V1Q5IPGtoxPjC+MEJbVlIMYADd9aHYWUIQKopuPOHmoqSkubnAKnzgKHqgIOfW5RdAgotN6BN+O2ZYHkuemLnvQ8U9THVrS1RtLmKbcC7PeeDsYznvqzeg6VCNwmr0Yyx1wnLjyT84BZz3EJyCptD3yeueAyDWIs0L2qs/VQ3HUyqfrja0V1LdDzqAikeWuV4sc7RLIB69jEIBjCkyZedoUHqCrOvShVzyd73OdrJW0hPOuQv2qOoHDc9xVb6Yu6uq3Xqp2ZaH46A7lzevbxQEmfrzvAYSJuZ4WDk1Hz3QX1LVdiUK0EvlAGAYlG3Md30r7dcPN63yqBCIj25prpvZP0nI4+EgWoFG95V596CurXpKRBGRjQlHCvy5Ib/iW8nZJWwrET3mgd6mEhfP4KCuaLjopWs7h+MdXFdIv8dHQJgg1xi1eYqB0uDYjxwVmri0Sv5XKut/onqapC+FQiC2C1lvYJ9MVco6yDYsS3AANUfMtvtbYI2hfwZatiSsnoUeMZd34GVjkMMKA+XnjJpXgRW2SHTZplVowPmJsvXy6w3cfO1AK2dvtZEKTkC/TY9LFiKHCG0DnrMQdGm2lzlBHM9iEYynH2UcVMhUEjsc0oDBTgo2ZSQ1gzkAHeWeBXYFjYLuuf8yzTCy7/RFR81WDjXMbq2BOH5dURnxo6oivmxL3cKzKInlZkD31nvpHB9Kk7GfcfE1t+1V64b9LtgeJGlpRFxQCAqWJ5DoY77ski8gsOEOr2uywZaoO/NGa0X0y1pNQHBi3b2SUGNpcZxDT7rLbBf1FSnQ8guxGW3W+36BW0gBje4DOz6Ba6SVk0xiKgt+q2JOFyr4SYfnu+Ic1QZYIuwHBrgzr6UvOcSCzPTOo7D6IC4ISeS7zkl4h+2VoeHpnG/uWR3+ysNgPcOIXQbv0n4mr3BwQcdKJxgPSeyuP/z1Jjg4e9nUvoXegqQVIE30EHx5GHv+FAVUNTowYDJgyFhf5IvlYmEqRif6+WN1MkEJmDcQITx9FX23a4mxy1AQRsOHO/+eImX9l8EMJI3oPWzVXxSOeHU1dUWYr2uAA7AMb+vAEZSbU3qob9ibCyXeypEMpZ6863o6QPqlqGHZkuWABSTVNd4cOh9hv3qEpSx2Zy/DJMP6cItEmiBJ5PFqQnDEIt3NrA3COlOSgz43D7gpNFNJ5MBh4oFzhDPiglC2ypsNU4ISywY2erkyb1NC3Qh/IfWj0eDgZI4/ln8WPfBsT3meTjq1Uqt1E7Zl/qftqkx6aM9KueMCekSnMrcHj1CqTWWzEzPsZGcDe3Ue4Ws+XFYVxNbOFF8ezkvQGR6ZOtOLU2lQEnMBStx47vE6Pb7AYMBRj2OOfZXfisjJnpTfSNjo6sZ6qSvNxZNmDeS7Gk3yYyCk1HtKN2UnhMIjOXUzAqDv90lx9O/q/AT1ZMnit5XQe9wmQxnE/WSH0CqZ9/2Hy+Sfmpeg8RwsHI5Z8kC8H293m/LHVVM/BA7HaTJYg5Enk7M/xWpq0192ACfBai2LA/qrCjCr6Dh1BIMzMXINBmX96MJ5Hn2nxln/RXPFhwHxUmSV0EV2V0jm86/dxxuYSU1W7sVkEbN9EzkG0QFwPhyHKyb3t+Fj5WoUUTErcazE/N6EW6Lvp0d//SDPj7EV9UdJN+Amnf3Wwk3A0SlJ9Z00yvXZ7n3z70G47Hfsow8Wq1JXcfwnA+Yxa5mFsgV464KKP4T31wqIgzFPd3eCe3j5ory5fBF2hgCFyVFrLzI9eetNXvM7oQqyFgDo4CTp/hDV9NMX9JDHQ/nyHTLvZLNLF6ftn2OxjGm8+PqOwhxnPHWipkE/8wbtyri80Sr7pMNkQGMfo4ZYK9OcCC4ESVFFbLMIvlxSoRqWie0wxqnLfcLSXMSpMMQEJYDVObYsXIQNv4TGNwjq1kvT1UOkicTrG3IaBZ3XdScS3u8sgeZPVpOLkbiF940FjbCeNRINNvDbd01EPBrTCPpm12m43ze1bBB59Ia6Ovhnur/Nvx3IxwSWol+3H2qfCJR8df6aQf4v6WiONxkK+IqT4pKQrZK/LplgDI/PJZbOep8dtbV7oCr6CgfpWa8NczOkPx81iSHbsNhVSJBOtrLIMrL31LK9TqHqAbAHe0RLmmV806kRLDLNEhUEJfm9u0sxpkL93Zgd6rw+tqBfTMi59xqXHLXSHwSbSBl0EK0+loECOPtrl+/nsaFe197di4yUgoe4jKoAJDXc6DGDjrQOoFDWZJ9HXwt8xDrQP+7aRwWKWI1GF8s8O4KzxWBBcwnl3vnl1Oez3oh6Ea1vjR7/z7DDTrFtqU2W/KAEzAuXDNZ7MY73MF216dzdSbWmUp4lcm7keJfWaMHgut9x5C9mj66Z0lJ+yhsjVvyiWrfk1lzPOTdhG15Y7gQlXtacvI7qv/XNSscDwqkgwHT/gUsD5yB7LdRRvJxQGYINn9hTpodKFVSTPrtGvyQw+HlRFXIkodErAGu9Iy1YpfSPc3jkFh5CX3lPxv7aqjE/JAfTIpEjGb/H7MO0e2vsViSW1qa/Lmi4/n4DEI3g7lYrcanspDfEpKkdV1OjSLOy0BCUqVoECaB55vs06rXl4jqmLsPsFM/7vYJ0vrBhDCm/00A/H81l1uekJ/6Lml3Hb9+NKiLqATJmDpyzfYZFHumEjC662L0Bwkxi7E9U4cQA0XMVDuMYAIeLMPgQaMVOd8fmt5SflFIfuBoszeAw7ow5gXPE2Y/yBc/7jExARUf/BxIHQBF5Sn3i61w4z5xJdCyO1F1X3+3ax+JSvMeZ7S6QSKp1Fp/sjYz6Z+VgCZzibGeEoujryfMulH7Rai5kAft9ebcW50DyJr2uo2z97mTWIu45YsSnNSMrrNUuG1XsYBtD9TDYzQffKB87vWbkM4EbPAFgoBV4GQS+vtFDUqOFAoi1nTtmIOvg38N4hT2Sn8r8clmBCXspBlMBYTnrqFJGBT3wZOzAyJDre9dHH7+x7qaaKDOB4UQALD5ecS0DE4obubQEiuJZ0EpBVpLuYcce8Aa4PYd/V4DLDAJBYKQPCWTcrEaZ5HYbJi11Gd6hjGom1ii18VHYnG28NKpkz2UKVPxlhYSp8uZr367iOmoy7zsxehW9wzcy2zG0a80PBMCRQMb32hnaHeOR8fnNDzZhaNYhkOdDsBUZ3loDMa1YP0uS0cjUP3b/6DBlqmZOeNABDsLl5BI5QJups8uxAuWJdkUB/pO6Zax6tsg7fN5mjjDgMGngO+DPcKqiHIDbFIGudxtPTIyDi9SFMKBDcfdGQRv41q1AqmxgkVfJMnP8w/Bc7N9/TR6C7mGObFqFkIEom8sKi2xYqJLTCHK7cxzaZvqODo22c3wisBCP4HeAgcRbNPAsBkNRhSmD48dHupdBRw4mIvtS5oeF6zeT1KMCyhMnmhpkFAGWnGscoNkwvQ8ZM5lE/vgTHFYL99OuNxdFBxTEDd5v2qLR8y9WkXsWgG6kZNndFG+pO/UAkOCipqIhL3hq7cRSdrCq7YhUsTocEcnaFa6nVkhnSeRYUA1YO0z5itF9Sly3VlxYDw239TJJH6f3EUfYO5lb7bcFcz8Bp7Oo8QmnsUHOz/fagVUBtKEw1iT88j+aKkv8cscKNkMxjYr8344D1kFoZ7/td1W6LCNYN594301tUGRmFjAzeRg5vyoM1F6+bJZ/Q54jN/k8SFd3DxPTYaAUsivsBfgTn7Mx8H2SpPt4GOdYRnEJOH6jHM2p6SgB0gzIRq6fHxGMmSmqaPCmlfwxiuloaVIitLGN8wie2CDWhkzLoCJcODh7KIOAqbHEvXdUxaS4TTTs07Clzj/6GmVs9kiZDerMxEnhUB6QQPlcfqkG9882RqHoLiHGBoHfQuXIsAG8GTAtao2KVwRnvvam8jo1e312GQAKWEa4sUVEAMG4G6ckcONDwRcg1e2D3+ohXgY4UAWF8wHKQMrSnzCgfFpsxh+aHXMGtPQroQasRY4U6UdG0rz1Vjbka0MekOGRZQEvqQFlxseFor8zWFgHek3v29+WqN6gaK5gZOTOMZzpQIC1201LkMCXild3vWXSc5UX9xcFYfbRPzGFa1FDcPfPB/jUEq/FeGt419CI3YmBlVoHsa4KdcwQP5ZSwHHhFJ7/Ph/Rap/4vmG91eDwPP0lDfCDRCLszTqfzM71xpmiKi2HwS4WlqvGNwtvwF5Dqpn6KTq8ax00UMPkxDcZrEEEsIvHiUXXEphdb4GB4FymlPwBz4Gperqq5pW7TQ6/yNRhW8VT5NhuP0udlxo4gILq5ZxAZk8ZGh3g4CqxJlPKY7AQxupfUcVpWT5VItp1+30UqoyP4wWsRo3olRRgkWZZ2ZN6VC3OZFeXB8NbnUrSdikNptD1QiGuKkr8EmSR/AK9Rw+FF3s5uwuPbvHGiPeFOViltMK7AUaOsq9+x9cndk3iJEE5LKZRlWJbKOZweROzmPNVPkjE3K/TyA57Rs68TkZ3MR8akKpm7cFjnjPd/DdkWjgYoKHSr5Wu5ssoBYU4acRs5g2DHxUmdq8VXOXRbunD8QN0LhgkssgahcdoYsNvuXGUK/KXD/7oFb+VGdhqIn02veuM5bLudJOc2Ky0GMaG4W/xWBxIJcL7yliJOXOpx0AkBqUgzlDczmLT4iILXDxxtRR1oZa2JWFgiAb43obrJnG/TZC2KSK2wqOzRZTXavZZFMb1f3bXvVaNaK828w9TO610gk8JNf3gMfETzXXsbcvRGCG9JWQZ6+cDPqc4466Yo2RcKH+PILeKOqtnlbInR3MmBeGG3FH10yzkybuqEC2HSQwpA0An7d9+73BkDUTm30bZmoP/RGbgFN+GrCOfADgqr0WbI1a1okpFms8iHYw9hm0zUvlEMivBRxModrbJJ+9/p3jUdQQ9BCtQdxnOGrT5dzRUmw0593/mbRSdBg0nRvRZM5/E16m7ZHmDEtWhwvfdZCZ8J8M12W0yRMszXamWfQTwIZ4ayYktrnscQuWr8idp3PjT2eF/jmtdhIfcpMnb+IfZY2FebW6UY/AK3jP4u3Tu4zE4qlnQgLFbM19EBIsNf7KhjdbqQ/D6yiDb+NlEi2SKD+ivXVUK8ib0oBo366gXkR8ZxGjpJIDcEgZPa9TcYe0TIbiPl/rPUQDu3XBJ9X/GNq3FAUsKsll57DzaGMrjcT+gctp+9MLYXCq+sqP81eVQ0r9lt+gcQfZbACRbEjvlMskztZG8gbC8Qn9tt26Q7y7nDrbZq/LEz7kR6Jc6pg3N9rVX8Y5MJrGlML9p9lU4jbTkKqCveeZUJjHB03m2KRKR2TytoFkTXOLg7keU1s1lrPMQJpoOKLuAAC+y1HlJucU6ysB5hsXhvSPPLq5J7JtnqHKZ4vYjC4Vy8153QY+6780xDuGARsGbOs1WqzH0QS765rnSKEbbKlkO8oI/VDwUd0is13tKpqILu1mDJFNy/iJAWcvDgjxvusIT+PGz3ST/J9r9Mtfd0jpaGeiLYIqXc7DiHSS8TcjFVksi66PEkxW1z6ujbLLUGNNYnzOWpH8BZGK4bCK7iR+MbIv8ncDAz1u4StN3vTTzewr9IQjk9wxFxn+6N1ddKs0vffJiS08N3a4G1SVrlZ97Q/M+8G9fe5AP6d9/Qq4WRnORVhofPIKEdCr3llspUfE0oKIIYoByBRPh+bX1HLS3JWGJRhIvE1aW4NTd8ePi4Z+kXb+Z8snYfSNcqijhAgVsx4RCM54cXUiYkjeBmmC4ajOHrChoELscJJC7+9jjMjw5BagZKlgRMiSNYz7h7vvZIoQqbtQmspc0cUk1G/73iXtSpROl5wtLgQi0mW2Ex8i3WULhcggx6E1LMVHUsdc9GHI1PH3U2Ko0PyGdn9KdVOLm7FPBui0i9a0HpA60MsewVE4z8CAt5d401Gv6zXlIT5Ybit1VIA0FCs7wtvYreru1fUyW3oLAZ/+aTnZrOcYRNVA8spoRtlRoWflsRClFcgzkqiHOrf0/SVw+EpVaFlJ0g4Kxq1MMOmiQdpMNpte8lMMQqm6cIFXlnGbfJllysKDi+0JJMotkqgIxOSQgU9dn/lWkeVf8nUm3iwX2Nl3WDw9i6AUK3vBAbZZrcJpDQ/N64AVwjT07Jef30GSSmtNu2WlW7YoyW2FlWfZFQUwk867EdLYKk9VG6JgEnBiBxkY7LMo4YLQJJlAo9l/oTvJkSARDF/XtyAzM8O2t3eT/iXa6wDN3WewNmQHdPfsxChU/KtLG2Mn8i4ZqKdSlIaBZadxJmRzVS/o4yA65RTSViq60oa395Lqw0pzY4SipwE0SXXsKV+GZraGSkr/RW08wPRvqvSUkYBMA9lPx4m24az+IHmCbXA+0faxTRE9wuGeO06DIXa6QlKJ3puIyiuAVfPr736vzo2pBirS+Vxel3TMm3JKhz9o2ZoRvaFVpIkykb0Hcm4oHFBMcNSNj7/4GJt43ogonY2Vg4nsDQIWxAcorpXACzgBqQPjYsE/VUpXpwNManEru4NwMCFPkXvMoqvoeLN3qyu/N1eWEHttMD65v19l/0kH2mR35iv/FI+yjoHJ9gPMz67af3Mq/BoWXqu3rphiWMXVkmnPSEkpGpUI2h1MThideGFEOK6YZHPwYzMBvpNC7+ZHxPb7epfefGyIB4JzO9DTNEYnDLVVHdQyvOEVefrk6Uv5kTQYVYWWdqrdcIl7yljwwIWdfQ/y+2QB3eR/qxYObuYyB4gTbo2in4PzarU1sO9nETkmj9/AoxDA+JM3GMqQtJR4jtduHtnoCLxd1gQUscHRB/MoRYIEsP2pDZ9KvHgtlk1iTbWWbHhohwFEYX7y51fUV2nuUmnoUcqnWIQAAgl9LTVX+Bc0QGNEhChxHR4YjfE51PUdGfsSFE6ck7BL3/hTf9jLq4G1IafINxOLKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI"; -const FENCED = /* @__PURE__ */ new Map([[8217, "apostrophe"], [8260, "fraction slash"], [12539, "middle dot"]]); -const NSM_MAX = 4; -function decode_arithmetic(bytes2) { - let pos = 0; - function u16() { - return bytes2[pos++] << 8 | bytes2[pos++]; - } - let symbol_count = u16(); - let total = 1; - let acc = [0, 1]; - for (let i = 1; i < symbol_count; i++) { - acc.push(total += u16()); - } - let skip = u16(); - let pos_payload = pos; - pos += skip; - let read_width = 0; - let read_buffer = 0; - function read_bit() { - if (read_width == 0) { - read_buffer = read_buffer << 8 | bytes2[pos++]; - read_width = 8; - } - return read_buffer >> --read_width & 1; - } - const N2 = 31; - const FULL = 2 ** N2; - const HALF = FULL >>> 1; - const QRTR = HALF >> 1; - const MASK = FULL - 1; - let register2 = 0; - for (let i = 0; i < N2; i++) register2 = register2 << 1 | read_bit(); - let symbols = []; - let low = 0; - let range2 = FULL; - while (true) { - let value = Math.floor(((register2 - low + 1) * total - 1) / range2); - let start = 0; - let end = symbol_count; - while (end - start > 1) { - let mid = start + end >>> 1; - if (value < acc[mid]) { - end = mid; - } else { - start = mid; - } - } - if (start == 0) break; - symbols.push(start); - let a2 = low + Math.floor(range2 * acc[start] / total); - let b2 = low + Math.floor(range2 * acc[start + 1] / total) - 1; - while (((a2 ^ b2) & HALF) == 0) { - register2 = register2 << 1 & MASK | read_bit(); - a2 = a2 << 1 & MASK; - b2 = b2 << 1 & MASK | 1; - } - while (a2 & ~b2 & QRTR) { - register2 = register2 & HALF | register2 << 1 & MASK >>> 1 | read_bit(); - a2 = a2 << 1 ^ HALF; - b2 = (b2 ^ HALF) << 1 | HALF | 1; - } - low = a2; - range2 = 1 + b2 - a2; - } - let offset2 = symbol_count - 4; - return symbols.map((x2) => { - switch (x2 - offset2) { - case 3: - return offset2 + 65792 + (bytes2[pos_payload++] << 16 | bytes2[pos_payload++] << 8 | bytes2[pos_payload++]); - case 2: - return offset2 + 256 + (bytes2[pos_payload++] << 8 | bytes2[pos_payload++]); - case 1: - return offset2 + bytes2[pos_payload++]; - default: - return x2 - 1; - } +async function uninstallFilter(_client3, { filter: filter2 }) { + return filter2.request({ + method: "eth_uninstallFilter", + params: [filter2.id] }); } -function read_payload(v3) { - let pos = 0; - return () => v3[pos++]; -} -function read_compressed_payload(s2) { - return read_payload(decode_arithmetic(unsafe_atob(s2))); +function watchEvent(client2, { address, args, batch = true, event, events, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client2.pollingInterval, strict: strict_ }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (typeof fromBlock === "bigint") + return true; + if (client2.transport.type === "webSocket") + return false; + if (client2.transport.type === "fallback" && client2.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + const strict = strict_ ?? false; + const pollEvent = () => { + const observerId = stringify$3([ + "watchEvent", + address, + args, + batch, + client2.uid, + event, + pollingInterval, + fromBlock + ]); + return observe(observerId, { onLogs, onError }, (emit2) => { + let previousBlockNumber; + if (fromBlock !== void 0) + previousBlockNumber = fromBlock - 1n; + let filter2; + let initialized = false; + const unwatch = poll(async () => { + var _a2; + if (!initialized) { + try { + filter2 = await getAction$1(client2, createEventFilter, "createEventFilter")({ + address, + args, + event, + events, + strict, + fromBlock + }); + } catch { + } + initialized = true; + return; + } + try { + let logs; + if (filter2) { + logs = await getAction$1(client2, getFilterChanges, "getFilterChanges")({ filter: filter2 }); + } else { + const blockNumber = await getAction$1(client2, getBlockNumber, "getBlockNumber")({}); + if (previousBlockNumber && previousBlockNumber !== blockNumber) { + logs = await getAction$1(client2, getLogs, "getLogs")({ + address, + args, + event, + events, + fromBlock: previousBlockNumber + 1n, + toBlock: blockNumber + }); + } else { + logs = []; + } + previousBlockNumber = blockNumber; + } + if (logs.length === 0) + return; + if (batch) + emit2.onLogs(logs); + else + for (const log of logs) + emit2.onLogs([log]); + } catch (err) { + if (filter2 && err instanceof InvalidInputRpcError) + initialized = false; + (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter2) + await getAction$1(client2, uninstallFilter, "uninstallFilter")({ filter: filter2 }); + unwatch(); + }; + }); + }; + const subscribeEvent = () => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const transport = (() => { + if (client2.transport.type === "fallback") { + const transport2 = client2.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client2.transport; + return transport2.value; + } + return client2.transport; + })(); + const events_ = events ?? (event ? [event] : void 0); + let topics = []; + if (events_) { + const encoded = events_.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["logs", { address, topics }], + onData(data) { + var _a2; + if (!active) + return; + const log = data.result; + try { + const { eventName, args: args2 } = decodeEventLog({ + abi: events_ ?? [], + data: log.data, + topics: log.topics, + strict + }); + const formatted = formatLog$1(log, { args: args2, eventName }); + onLogs([formatted]); + } catch (err) { + let eventName; + let isUnnamed; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict_) + return; + eventName = err.abiItem.name; + isUnnamed = (_a2 = err.abiItem.inputs) == null ? void 0 : _a2.some((x2) => !("name" in x2 && x2.name)); + } + const formatted = formatLog$1(log, { + args: isUnnamed ? [] : {}, + eventName + }); + onLogs([formatted]); + } + }, + onError(error) { + onError == null ? void 0 : onError(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError == null ? void 0 : onError(err); + } + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollEvent() : subscribeEvent(); } -function unsafe_atob(s2) { - let lookup2 = []; - [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach((c2, i) => lookup2[c2.charCodeAt(0)] = i); - let n2 = s2.length; - let ret = new Uint8Array(6 * n2 >> 3); - for (let i = 0, pos = 0, width = 0, carry = 0; i < n2; i++) { - carry = carry << 6 | lookup2[s2.charCodeAt(i)]; - width += 6; - if (width >= 8) { - ret[pos++] = carry >> (width -= 8); - } - } - return ret; +function watchPendingTransactions(client2, { batch = true, onError, onTransactions, poll: poll_, pollingInterval = client2.pollingInterval }) { + const enablePolling = typeof poll_ !== "undefined" ? poll_ : client2.transport.type !== "webSocket"; + const pollPendingTransactions = () => { + const observerId = stringify$3([ + "watchPendingTransactions", + client2.uid, + batch, + pollingInterval + ]); + return observe(observerId, { onTransactions, onError }, (emit2) => { + let filter2; + const unwatch = poll(async () => { + var _a2; + try { + if (!filter2) { + try { + filter2 = await getAction$1(client2, createPendingTransactionFilter, "createPendingTransactionFilter")({}); + return; + } catch (err) { + unwatch(); + throw err; + } + } + const hashes = await getAction$1(client2, getFilterChanges, "getFilterChanges")({ filter: filter2 }); + if (hashes.length === 0) + return; + if (batch) + emit2.onTransactions(hashes); + else + for (const hash2 of hashes) + emit2.onTransactions([hash2]); + } catch (err) { + (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter2) + await getAction$1(client2, uninstallFilter, "uninstallFilter")({ filter: filter2 }); + unwatch(); + }; + }); + }; + const subscribePendingTransactions = () => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const { unsubscribe: unsubscribe_ } = await client2.transport.subscribe({ + params: ["newPendingTransactions"], + onData(data) { + if (!active) + return; + const transaction2 = data.result; + onTransactions([transaction2]); + }, + onError(error) { + onError == null ? void 0 : onError(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError == null ? void 0 : onError(err); + } + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollPendingTransactions() : subscribePendingTransactions(); } -function signed(i) { - return i & 1 ? ~i >> 1 : i >> 1; +async function getAddresses(client2) { + var _a2; + if (((_a2 = client2.account) == null ? void 0 : _a2.type) === "local") + return [client2.account.address]; + const addresses = await client2.request({ method: "eth_accounts" }, { dedupe: true }); + return addresses.map((address) => checksumAddress(address)); } -function read_deltas(n2, next) { - let v3 = Array(n2); - for (let i = 0, x2 = 0; i < n2; i++) v3[i] = x2 += signed(next()); - return v3; +async function getPermissions(client2) { + const permissions = await client2.request({ method: "wallet_getPermissions" }, { dedupe: true }); + return permissions; } -function read_sorted(next, prev = 0) { - let ret = []; - while (true) { - let x2 = next(); - let n2 = next(); - if (!n2) break; - prev += x2; - for (let i = 0; i < n2; i++) { - ret.push(prev + i); - } - prev += n2 + 1; - } - return ret; +const promiseCache = /* @__PURE__ */ new LruMap(8192); +function withDedupe(fn, { enabled = true, id: id2 }) { + if (!enabled || !id2) + return fn(); + if (promiseCache.get(id2)) + return promiseCache.get(id2); + const promise = fn().finally(() => promiseCache.delete(id2)); + promiseCache.set(id2, promise); + return promise; } -function read_sorted_arrays(next) { - return read_array_while(() => { - let v3 = read_sorted(next); - if (v3.length) return v3; +function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) { + return new Promise((resolve, reject) => { + const attemptRetry = async ({ count: count2 = 0 } = {}) => { + const retry = async ({ error }) => { + const delay2 = typeof delay_ === "function" ? delay_({ count: count2, error }) : delay_; + if (delay2) + await wait$1(delay2); + attemptRetry({ count: count2 + 1 }); + }; + try { + const data = await fn(); + resolve(data); + } catch (err) { + if (count2 < retryCount && await shouldRetry2({ count: count2, error: err })) + return retry({ error: err }); + reject(err); + } + }; + attemptRetry(); }); } -function read_mapped(next) { - let ret = []; - while (true) { - let w2 = next(); - if (w2 == 0) break; - ret.push(read_linear_table(w2, next)); - } - while (true) { - let w2 = next() - 1; - if (w2 < 0) break; - ret.push(read_replacement_table(w2, next)); - } - return ret.flat(); +function buildRequest(request, options = {}) { + return async (args, overrideOptions = {}) => { + const { dedupe = false, retryDelay = 150, retryCount = 3, uid: uid2 } = { + ...options, + ...overrideOptions + }; + const requestId = dedupe ? keccak256$1(stringToHex(`${uid2}.${stringify$3(args)}`)) : void 0; + return withDedupe(() => withRetry(async () => { + try { + return await request(args); + } catch (err_) { + const err = err_; + switch (err.code) { + case ParseRpcError.code: + throw new ParseRpcError(err); + case InvalidRequestRpcError.code: + throw new InvalidRequestRpcError(err); + case MethodNotFoundRpcError.code: + throw new MethodNotFoundRpcError(err, { method: args.method }); + case InvalidParamsRpcError.code: + throw new InvalidParamsRpcError(err); + case InternalRpcError.code: + throw new InternalRpcError(err); + case InvalidInputRpcError.code: + throw new InvalidInputRpcError(err); + case ResourceNotFoundRpcError.code: + throw new ResourceNotFoundRpcError(err); + case ResourceUnavailableRpcError.code: + throw new ResourceUnavailableRpcError(err); + case TransactionRejectedRpcError.code: + throw new TransactionRejectedRpcError(err); + case MethodNotSupportedRpcError.code: + throw new MethodNotSupportedRpcError(err, { + method: args.method + }); + case LimitExceededRpcError.code: + throw new LimitExceededRpcError(err); + case JsonRpcVersionUnsupportedError.code: + throw new JsonRpcVersionUnsupportedError(err); + case UserRejectedRequestError.code: + throw new UserRejectedRequestError(err); + case UnauthorizedProviderError.code: + throw new UnauthorizedProviderError(err); + case UnsupportedProviderMethodError.code: + throw new UnsupportedProviderMethodError(err); + case ProviderDisconnectedError.code: + throw new ProviderDisconnectedError(err); + case ChainDisconnectedError.code: + throw new ChainDisconnectedError(err); + case SwitchChainError.code: + throw new SwitchChainError(err); + case 5e3: + throw new UserRejectedRequestError(err); + default: + if (err_ instanceof BaseError$3) + throw err_; + throw new UnknownRpcError(err); + } + } + }, { + delay: ({ count: count2, error }) => { + var _a2; + if (error && error instanceof HttpRequestError) { + const retryAfter = (_a2 = error == null ? void 0 : error.headers) == null ? void 0 : _a2.get("Retry-After"); + if (retryAfter == null ? void 0 : retryAfter.match(/\d/)) + return Number.parseInt(retryAfter) * 1e3; + } + return ~~(1 << count2) * retryDelay; + }, + retryCount, + shouldRetry: ({ error }) => shouldRetry(error) + }), { enabled: dedupe, id: requestId }); + }; } -function read_array_while(next) { - let v3 = []; - while (true) { - let x2 = next(v3.length); - if (!x2) break; - v3.push(x2); +function shouldRetry(error) { + if ("code" in error && typeof error.code === "number") { + if (error.code === -1) + return true; + if (error.code === LimitExceededRpcError.code) + return true; + if (error.code === InternalRpcError.code) + return true; + return false; } - return v3; -} -function read_transposed(n2, w2, next) { - let m2 = Array(n2).fill().map(() => []); - for (let i = 0; i < w2; i++) { - read_deltas(n2, next).forEach((x2, j2) => m2[j2].push(x2)); + if (error instanceof HttpRequestError && error.status) { + if (error.status === 403) + return true; + if (error.status === 408) + return true; + if (error.status === 413) + return true; + if (error.status === 429) + return true; + if (error.status === 500) + return true; + if (error.status === 502) + return true; + if (error.status === 503) + return true; + if (error.status === 504) + return true; + return false; } - return m2; + return true; } -function read_linear_table(w2, next) { - let dx = 1 + next(); - let dy = next(); - let vN = read_array_while(next); - let m2 = read_transposed(vN.length, 1 + w2, next); - return m2.flatMap((v3, i) => { - let [x2, ...ys] = v3; - return Array(vN[i]).fill().map((_, j2) => { - let j_dy = j2 * dy; - return [x2 + j2 * dx, ys.map((y2) => y2 + j_dy)]; - }); +function defineChain(chain) { + return { + formatters: void 0, + fees: void 0, + serializers: void 0, + ...chain + }; +} +const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; +const integerRegex = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; +function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, signal }) { + return new Promise((resolve, reject) => { + (async () => { + let timeoutId; + try { + const controller = new AbortController(); + if (timeout > 0) { + timeoutId = setTimeout(() => { + if (signal) { + controller.abort(); + } else { + reject(errorInstance); + } + }, timeout); + } + resolve(await fn({ signal: (controller == null ? void 0 : controller.signal) || null })); + } catch (err) { + if ((err == null ? void 0 : err.name) === "AbortError") + reject(errorInstance); + reject(err); + } finally { + clearTimeout(timeoutId); + } + })(); }); } -function read_replacement_table(w2, next) { - let n2 = 1 + next(); - let m2 = read_transposed(n2, 1 + w2, next); - return m2.map((v3) => [v3[0], v3.slice(1)]); +function createIdStore() { + return { + current: 0, + take() { + return this.current++; + }, + reset() { + this.current = 0; + } + }; } -function read_trie(next) { - let ret = []; - let sorted = read_sorted(next); - expand(decode2([]), []); - return ret; - function decode2(Q2) { - let S2 = next(); - let B2 = read_array_while(() => { - let cps = read_sorted(next).map((i) => sorted[i]); - if (cps.length) return decode2(cps); - }); - return { S: S2, B: B2, Q: Q2 }; - } - function expand({ S: S2, B: B2 }, cps, saved) { - if (S2 & 4 && saved === cps[cps.length - 1]) return; - if (S2 & 2) saved = cps[cps.length - 1]; - if (S2 & 1) ret.push(cps); - for (let br of B2) { - for (let cp of br.Q) { - expand(br, [...cps, cp], saved); +const idCache = /* @__PURE__ */ createIdStore(); +function getHttpRpcClient(url, options = {}) { + return { + async request(params) { + var _a2; + const { body, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params; + const fetchOptions = { + ...options.fetchOptions ?? {}, + ...params.fetchOptions ?? {} + }; + const { headers, method, signal: signal_ } = fetchOptions; + try { + const response = await withTimeout(async ({ signal }) => { + const init2 = { + ...fetchOptions, + body: Array.isArray(body) ? stringify$3(body.map((body2) => ({ + jsonrpc: "2.0", + id: body2.id ?? idCache.take(), + ...body2 + }))) : stringify$3({ + jsonrpc: "2.0", + id: body.id ?? idCache.take(), + ...body + }), + headers: { + "Content-Type": "application/json", + ...headers + }, + method: method || "POST", + signal: signal_ || (timeout > 0 ? signal : null) + }; + const request = new Request(url, init2); + if (onRequest) + await onRequest(request); + const response2 = await fetch(url, init2); + return response2; + }, { + errorInstance: new TimeoutError$2({ body, url }), + timeout, + signal: true + }); + if (onResponse) + await onResponse(response); + let data; + if ((_a2 = response.headers.get("Content-Type")) == null ? void 0 : _a2.startsWith("application/json")) + data = await response.json(); + else { + data = await response.text(); + data = JSON.parse(data || "{}"); + } + if (!response.ok) { + throw new HttpRequestError({ + body, + details: stringify$3(data.error) || response.statusText, + headers: response.headers, + status: response.status, + url + }); + } + return data; + } catch (err) { + if (err instanceof HttpRequestError) + throw err; + if (err instanceof TimeoutError$2) + throw err; + throw new HttpRequestError({ + body, + cause: err, + url + }); } } - } + }; } -function hex_cp(cp) { - return cp.toString(16).toUpperCase().padStart(2, "0"); +function hashTypedData(parameters) { + const { domain: domain2 = {}, message, primaryType } = parameters; + const types2 = { + EIP712Domain: getTypesForEIP712Domain({ domain: domain2 }), + ...parameters.types + }; + validateTypedData({ + domain: domain2, + message, + primaryType, + types: types2 + }); + const parts = ["0x1901"]; + if (domain2) + parts.push(hashDomain({ + domain: domain2, + types: types2 + })); + if (primaryType !== "EIP712Domain") + parts.push(hashStruct({ + data: message, + primaryType, + types: types2 + })); + return keccak256$1(concat$1(parts)); } -function quote_cp(cp) { - return `{${hex_cp(cp)}}`; +function hashDomain({ domain: domain2, types: types2 }) { + return hashStruct({ + data: domain2, + primaryType: "EIP712Domain", + types: types2 + }); } -function explode_cp(s2) { - let cps = []; - for (let pos = 0, len = s2.length; pos < len; ) { - let cp = s2.codePointAt(pos); - pos += cp < 65536 ? 1 : 2; - cps.push(cp); - } - return cps; +function hashStruct({ data, primaryType, types: types2 }) { + const encoded = encodeData({ + data, + primaryType, + types: types2 + }); + return keccak256$1(encoded); } -function str_from_cps(cps) { - const chunk = 4096; - let len = cps.length; - if (len < chunk) return String.fromCodePoint(...cps); - let buf = []; - for (let i = 0; i < len; ) { - buf.push(String.fromCodePoint(...cps.slice(i, i += chunk))); +function encodeData({ data, primaryType, types: types2 }) { + const encodedTypes = [{ type: "bytes32" }]; + const encodedValues = [hashType({ primaryType, types: types2 })]; + for (const field of types2[primaryType]) { + const [type, value] = encodeField({ + types: types2, + name: field.name, + type: field.type, + value: data[field.name] + }); + encodedTypes.push(type); + encodedValues.push(value); } - return buf.join(""); + return encodeAbiParameters(encodedTypes, encodedValues); } -function compare_arrays(a2, b2) { - let n2 = a2.length; - let c2 = n2 - b2.length; - for (let i = 0; c2 == 0 && i < n2; i++) c2 = a2[i] - b2[i]; - return c2; +function hashType({ primaryType, types: types2 }) { + const encodedHashType = toHex$1(encodeType$1({ primaryType, types: types2 })); + return keccak256$1(encodedHashType); } -var COMPRESSED = "AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSMEEEl5RFVMKvO0XQ8ExDdJMnIgsj26PTQyy8FfEQ8AY8IPAGcEbwRwBHEEcgRzBHQEdQR2BHcEeAR6BHsEfAR+BIAEgfndBQoBYgULAWIFDAFiBNcE2ATZBRAFEQUvBdALFAsVDPcNBw13DYcOMA4xDjMB4BllHI0B2grbAMDpHLkQ7QHVAPRNQQFnGRUEg0yEB2uaJF8AJpIBpob5AERSMAKNoAXqaQLUBMCzEiACnwRZEkkVsS7tANAsBG0RuAQLEPABv9HICTUBXigPZwRBApMDOwAamhtaABqEAY8KvKx3LQ4ArAB8UhwEBAVSagD8AEFZADkBIadVj2UMUgx5Il4ANQC9AxIB1BlbEPMAs30CGxlXAhwZKQIECBc6EbsCoxngzv7UzRQA8M0BawL6ZwkN7wABAD33OQRcsgLJCjMCjqUChtw/km+NAsXPAoP2BT84PwURAK0RAvptb6cApQS/OMMey5HJS84UdxpxTPkCogVFITaTOwERAK5pAvkNBOVyA7q3BKlOJSALAgUIBRcEdASpBXqzABXFSWZOawLCOqw//AolCZdvv3dSBkEQGyelEPcMMwG1ATsN7UvYBPEGOwTJH30ZGQ/NlZwIpS3dDO0m4y6hgFoj9SqDBe1L9DzdC01RaA9ZC2UJ4zpjgU4DIQENIosK3Q05CG0Q8wrJaw3lEUUHOQPVSZoApQcBCxEdNRW1JhBirAsJOXcG+xr2C48mrxMpevwF0xohBk0BKRr/AM8u54WwWjFcHE9fBgMLJSPHFKhQIA0lQLd4SBobBxUlqQKRQ3BKh1E2HpMh9jw9DWYuE1F8B/U8BRlPC4E8nkarRQ4R0j6NPUgiSUwsBDV/LC8niwnPD4UMuXxyAVkJIQmxDHETMREXN8UIOQcZLZckJxUIIUaVYJoE958D8xPRAwsFPwlBBxMDtRwtEy4VKQUNgSTXAvM21S6zAo9WgAEXBcsPJR/fEFBH4A7pCJsCZQODJesALRUhABcimwhDYwBfj9hTBS7LCMdqbCN0A2cU52ERcweRDlcHpxwzFb8c4XDIXguGCCijrwlbAXUJmQFfBOMICTVbjKAgQWdTi1gYmyBhQT9d/AIxDGUVn0S9h3gCiw9rEhsBNQFzBzkNAQJ3Ee0RaxCVCOuGBDW1M/g6JQRPIYMgEQonA09szgsnJvkM+GkBoxJiAww0PXfuZ6tgtiQX/QcZMsVBYCHxC5JPzQycGsEYQlQuGeQHvwPzGvMn6kFXBf8DowMTOk0z7gS9C2kIiwk/AEkOoxcH1xhqCnGM0AExiwG3mQNXkYMCb48GNwcLAGcLhwV55QAdAqcIowAFAM8DVwA5Aq0HnQAZAIVBAT0DJy8BIeUCjwOTCDHLAZUvAfMpBBvDDBUA9zduSgLDsQKAamaiBd1YAo4CSTUBTSUEBU5HUQOvceEA2wBLBhPfRwEVq0rLGuNDAd9vKwDHAPsABTUHBUEBzQHzbQC3AV8LMQmis7UBTekpAIMAFWsB1wKJAN0ANQB/8QFTAE0FWfkF0wJPSQERMRgrV2EBuwMfATMBDQB5BsuNpckHHwRtB9MCEBsV4QLvLge1AQMi3xPNQsUCvd5VoWACZIECYkJbTa9bNyACofcCaJgCZgkCn4Q4GwsCZjsCZiYEbgR/A38TA36SOQY5dxc5gjojIwJsHQIyNjgKAm3HAm2u74ozZ0UrAWcA3gDhAEoFB5gMjQD+C8IADbUCdy8CdqI/AnlLQwJ4uh1c20WuRtcCfD8CesgCfQkCfPAFWQUgSABIfWMkAoFtAoAAAoAFAn+uSVhKWxUXSswC0QEC0MxLJwOITwOH5kTFkTIC8qFdAwMDrkvOTC0lA89NTE2vAos/AorYwRsHHUNnBbcCjjcCjlxAl4ECjtkCjlx4UbRTNQpS1FSFApP7ApMMAOkAHFUeVa9V0AYsGymVhjLheGZFOzkCl58C77JYIagAWSUClo8ClnycAKlZrFoJgU0AOwKWtQKWTlxEXNECmcsCmWRcyl0HGQKcmznCOp0CnBYCn5sCnriKAB0PMSoPAp3xAp6SALU9YTRh7wKe0wKgbgGpAp6fHwKeTqVjyGQnJSsCJ68CJn4CoPsCoEwCot0CocQCpi8Cpc4Cp/8AfQKn8mh8aLEAA0lqHGrRAqzjAqyuAq1nAq0CAlcdAlXcArHh1wMfTmyXArK9DQKy6Bds4G1jbUhfAyXNArZcOz9ukAMpRQK4XgK5RxUCuSp3cDZw4QK9GQK72nCWAzIRAr6IcgIDM3ECvhpzInNPAsPLAsMEc4J0SzVFdOADPKcDPJoDPb8CxXwCxkcCxhCJAshpUQLIRALJTwLJLgJknQLd0nh5YXiueSVL0AMYo2cCAmH0GfOVJHsLXpJeuxECz2sCz2wvS1PS8xOfAMatAs9zASnqA04SfksFAtwnAtuKAtJPA1JcA1NfAQEDVYyAiT8AyxbtYEWCHILTgs6DjQLaxwLZ3oQQhEmnPAOGpQAvA2QOhnFZ+QBVAt9lAt64c3cC4i/tFAHzMCcB9JsB8tKHAuvzAulweQLq+QLq5AD5RwG5Au6JAuuclqqXAwLuPwOF4Jh5cOBxoQLzAwBpA44WmZMC9xMDkW4DkocC95gC+dkC+GaaHJqruzebHgOdgwL++gEbADmfHJ+zAwWNA6ZqA6bZANHFAwZqoYiiBQkDDEkCwAA/AwDhQRdTARHzA2sHl2cFAJMtK7evvdsBiZkUfxEEOQH7KQUhDp0JnwCS/SlXxQL3AZ0AtwW5AG8LbUEuFCaNLgFDAYD8AbUmAHUDDgRtACwCFgyhAAAKAj0CagPdA34EkQEgRQUhfAoABQBEABMANhICdwEABdUDa+8KxQIA9wqfJ7+xt+UBkSFBQgHpFH8RNMCJAAQAGwBaAkUChIsABjpTOpSNbQC4Oo860ACNOME63AClAOgAywE6gTo7Ofw5+Tt2iTpbO56JOm85GAFWATMBbAUvNV01njWtNWY1dTW2NcU1gjWRNdI14TWeNa017jX9NbI1wTYCNhE1xjXVNhY2JzXeNe02LjY9Ni41LSE2OjY9Njw2yTcIBJA8VzY4Nt03IDcPNsogN4k3MAoEsDxnNiQ3GTdsOo03IULUQwdC4EMLHA8PCZsobShRVQYA6X8A6bABFCnXAukBowC9BbcAbwNzBL8MDAMMAQgDAAkKCwsLCQoGBAVVBI/DvwDz9b29kaUCb0QtsRTNLt4eGBcSHAMZFhYZEhYEARAEBUEcQRxBHEEcQRxBHEEaQRxBHEFCSTxBPElISUhBNkM2QTYbNklISVmBVIgBFLWZAu0BhQCjBcEAbykBvwGJAaQcEZ0ePCklMAAhMvAIMAL54gC7Bm8EescjzQMpARQpKgDUABavAj626xQAJP0A3etzuf4NNRA7efy2Z9NQrCnC0OSyANz5BBIbJ5IFDR6miIavYS6tprjjmuKebxm5C74Q225X1pkaYYPb6f1DK4k3xMEBb9S2WMjEibTNWhsRJIA+vwNVEiXTE5iXs/wezV66oFLfp9NZGYW+Gk19J2+bCT6Ye2w6LDYdgzKMUabk595eLBCXANz9HUpWbATq9vqXVx9XDg+Pc9Xp4+bsS005SVM/BJBM4687WUuf+Uj9dEi8aDNaPxtpbDxcG1THTImUMZq4UCaaNYpsVqraNyKLJXDYsFZ/5jl7bLRtO88t7P3xZaAxhb5OdPMXqsSkp1WCieG8jXm1U99+blvLlXzPCS+M93VnJCiK+09LfaSaBAVBomyDgJua8dfUzR7ga34IvR2Nvj+A9heJ6lsl1KG4NkI1032Cnff1m1wof2B9oHJK4bi6JkEdSqeNeiuo6QoZZincoc73/TH9SXF8sCE7XyuYyW8WSgbGFCjPV0ihLKhdPs08Tx82fYAkLLc4I2wdl4apY7GU5lHRFzRWJep7Ww3wbeA3qmd59/86P4xuNaqDpygXt6M85glSBHOCGgJDnt+pN9bK7HApMguX6+06RZNjzVmcZJ+wcUrJ9//bpRNxNuKpNl9uFds+S9tdx7LaM5ZkIrPj6nIU9mnbFtVbs9s/uLgl8MVczAwet+iOEzzBlYW7RCMgE6gyNLeq6+1tIx4dpgZnd0DksJS5f+JNDpwwcPNXaaVspq1fbQajOrJgK0ofKtJ1Ne90L6VO4MOl5S886p7u6xo7OLjG8TGL+HU1JXGJgppg4nNbNJ5nlzSpuPYy21JUEcUA94PoFiZfjZue+QnyQ80ekOuZVkxx4g+cvhJfHgNl4hy1/a6+RKcKlar/J29y//EztlbVPHVUeQ1zX86eQVAjR/M3dA9w4W8LfaXp4EgM85wOWasli837PzVMOnsLzR+k3o75/lRPAJSE1xAKQzEi5v10ke+VBvRt1cwQRMd+U5mLCTGVd6XiZtgBG5cDi0w22GKcVNvHiu5LQbZEDVtz0onn7k5+heuKXVsZtSzilkLRAUmjMXEMB3J9YC50XBxPiz53SC+EhnPl9WsKCv92SM/OFFIMJZYfl0WW8tIO3UxYcwdMAj7FSmgrsZ2aAZO03BOhP1bNNZItyXYQFTpC3SG1VuPDqH9GkiCDmE+JwxyIVSO5siDErAOpEXFgjy6PQtOVDj+s6e1r8heWVvmZnTciuf4EiNZzCAd7SOMhXERIOlsHIMG399i9aLTy3m2hRLZjJVDNLS53iGIK11dPqQt0zBDyg6qc7YqkDm2M5Ve6dCWCaCbTXX2rToaIgz6+zh4lYUi/+6nqcFMAkQJKHYLK0wYk5N9szV6xihDbDDFr45lN1K4aCXBq/FitPSud9gLt5ZVn+ZqGX7cwm2z5EGMgfFpIFyhGGuDPmso6TItTMwny+7uPnLCf4W6goFQFV0oQSsc9VfMmVLcLr6ZetDZbaSFTLqnSO/bIPjA3/zAUoqgGFAEQS4IhuMzEp2I3jJzbzkk/IEmyax+rhZTwd6f+CGtwPixu8IvzACquPWPREu9ZvGkUzpRwvRRuaNN6cr0W1wWits9ICdYJ7ltbgMiSL3sTPeufgNcVqMVWFkCPDH4jG2jA0XcVgQj62Cb29v9f/z/+2KbYvIv/zzjpQAPkliaVDzNrW57TZ/ZOyZD0nlfMmAIBIAGAI0D3k/mdN4xr9v85ZbZbbqfH2jGd5hUqNZWwl5SPfoGmfElmazUIeNL1j/mkF7VNAzTq4jNt8JoQ11NQOcmhprXoxSxfRGJ9LDEOAQ+dmxAQH90iti9e2u/MoeuaGcDTHoC+xsmEeWmxEKefQuIzHbpw5Tc5cEocboAD09oipWQhtTO1wivf/O+DRe2rpl/E9wlrzBorjJsOeG1B/XPW4EaJEFdNlECEZga5ZoGRHXgYouGRuVkm8tDESiEyFNo+3s5M5puSdTyUL2llnINVHEt91XUNW4ewdMgJ4boJfEyt/iY5WXqbA+A2Fkt5Z0lutiWhe9nZIyIUjyXDC3UsaG1t+eNx6z4W/OYoTB7A6x+dNSTOi9AInctbESqm5gvOLww7OWXPrmHwVZasrl4eD113pm+JtT7JVOvnCXqdzzdTRHgJ0PiGTFYW5Gvt9R9LD6Lzfs0v/TZZHSmyVNq7viIHE6DBK7Qp07Iz55EM8SYtQvZf/obBniTWi5C2/ovHfw4VndkE5XYdjOhCMRjDeOEfXeN/CwfGduiUIfsoFeUxXeQXba7c7972XNv8w+dTjjUM0QeNAReW+J014dKAD/McQYXT7c0GQPIkn3Ll6R7gGjuiQoZD0TEeEqQpKoZ15g/0OPQI17QiSv9AUROa/V/TQN3dvLArec3RrsYlvBm1b8LWzltdugsC50lNKYLEp2a+ZZYqPejULRlOJh5zj/LVMyTDvwKhMxxwuDkxJ1QpoNI0OTWLom4Z71SNzI9TV1iXJrIu9Wcnd+MCaAw8o1jSXd94YU/1gnkrC9BUEOtQvEIQ7g0i6h+KL2JKk8Ydl7HruvgWMSAmNe+LshGhV4qnWHhO9/RIPQzY1tHRj2VqOyNsDpK0cww+56AdDC4gsWwY0XxoucIWIqs/GcwnWqlaT0KPr8mbK5U94/301i1WLt4YINTVvCFBrFZbIbY8eycOdeJ2teD5IfPLCRg7jjcFTwlMFNl9zdh/o3E/hHPwj7BWg0MU09pPrBLbrCgm54A6H+I6v27+jL5gkjWg/iYdks9jbfVP5y/n0dlgWEMlKasl7JvFZd56LfybW1eeaVO0gxTfXZwD8G4SI116yx7UKVRgui6Ya1YpixqXeNLc8IxtAwCU5IhwQgn+NqHnRaDv61CxKhOq4pOX7M6pkA+Pmpd4j1vn6ACUALoLLc4vpXci8VidLxzm7qFBe7s+quuJs6ETYmnpgS3LwSZxPIltgBDXz8M1k/W2ySNv2f9/NPhxLGK2D21dkHeSGmenRT3Yqcdl0m/h3OYr8V+lXNYGf8aCCpd4bWjE4QIPj7vUKN4Nrfs7ML6Y2OyS830JCnofg/k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g"; -const S0 = 44032; -const L0 = 4352; -const V0 = 4449; -const T0 = 4519; -const L_COUNT = 19; -const V_COUNT = 21; -const T_COUNT = 28; -const N_COUNT = V_COUNT * T_COUNT; -const S_COUNT = L_COUNT * N_COUNT; -const S1 = S0 + S_COUNT; -const L1 = L0 + L_COUNT; -const V1 = V0 + V_COUNT; -const T1$1 = T0 + T_COUNT; -function unpack_cc(packed) { - return packed >> 24 & 255; +function encodeType$1({ primaryType, types: types2 }) { + let result = ""; + const unsortedDeps = findTypeDependencies({ primaryType, types: types2 }); + unsortedDeps.delete(primaryType); + const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; + for (const type of deps) { + result += `${type}(${types2[type].map(({ name: name2, type: t2 }) => `${t2} ${name2}`).join(",")})`; + } + return result; } -function unpack_cp(packed) { - return packed & 16777215; -} -let SHIFTED_RANK, EXCLUSIONS, DECOMP, RECOMP; -function init$1() { - let r2 = read_compressed_payload(COMPRESSED); - SHIFTED_RANK = new Map(read_sorted_arrays(r2).flatMap((v3, i) => v3.map((x2) => [x2, i + 1 << 24]))); - EXCLUSIONS = new Set(read_sorted(r2)); - DECOMP = /* @__PURE__ */ new Map(); - RECOMP = /* @__PURE__ */ new Map(); - for (let [cp, cps] of read_mapped(r2)) { - if (!EXCLUSIONS.has(cp) && cps.length == 2) { - let [a2, b2] = cps; - let bucket = RECOMP.get(a2); - if (!bucket) { - bucket = /* @__PURE__ */ new Map(); - RECOMP.set(a2, bucket); - } - bucket.set(b2, cp); - } - DECOMP.set(cp, cps.reverse()); +function findTypeDependencies({ primaryType: primaryType_, types: types2 }, results2 = /* @__PURE__ */ new Set()) { + const match = primaryType_.match(/^\w*/u); + const primaryType = match == null ? void 0 : match[0]; + if (results2.has(primaryType) || types2[primaryType] === void 0) { + return results2; } -} -function is_hangul(cp) { - return cp >= S0 && cp < S1; -} -function compose_pair(a2, b2) { - if (a2 >= L0 && a2 < L1 && b2 >= V0 && b2 < V1) { - return S0 + (a2 - L0) * N_COUNT + (b2 - V0) * T_COUNT; - } else if (is_hangul(a2) && b2 > T0 && b2 < T1$1 && (a2 - S0) % T_COUNT == 0) { - return a2 + (b2 - T0); - } else { - let recomp = RECOMP.get(a2); - if (recomp) { - recomp = recomp.get(b2); - if (recomp) { - return recomp; - } - } - return -1; + results2.add(primaryType); + for (const field of types2[primaryType]) { + findTypeDependencies({ primaryType: field.type, types: types2 }, results2); } + return results2; } -function decomposed(cps) { - if (!SHIFTED_RANK) init$1(); - let ret = []; - let buf = []; - let check_order = false; - function add2(cp) { - let cc2 = SHIFTED_RANK.get(cp); - if (cc2) { - check_order = true; - cp |= cc2; - } - ret.push(cp); +function encodeField({ types: types2, name: name2, type, value }) { + if (types2[type] !== void 0) { + return [ + { type: "bytes32" }, + keccak256$1(encodeData({ data: value, primaryType: type, types: types2 })) + ]; } - for (let cp of cps) { - while (true) { - if (cp < 128) { - ret.push(cp); - } else if (is_hangul(cp)) { - let s_index = cp - S0; - let l_index = s_index / N_COUNT | 0; - let v_index = s_index % N_COUNT / T_COUNT | 0; - let t_index = s_index % T_COUNT; - add2(L0 + l_index); - add2(V0 + v_index); - if (t_index > 0) add2(T0 + t_index); - } else { - let mapped = DECOMP.get(cp); - if (mapped) { - buf.push(...mapped); - } else { - add2(cp); - } - } - if (!buf.length) break; - cp = buf.pop(); - } + if (type === "bytes") { + const prepend = value.length % 2 ? "0" : ""; + value = `0x${prepend + value.slice(2)}`; + return [{ type: "bytes32" }, keccak256$1(value)]; } - if (check_order && ret.length > 1) { - let prev_cc = unpack_cc(ret[0]); - for (let i = 1; i < ret.length; i++) { - let cc2 = unpack_cc(ret[i]); - if (cc2 == 0 || prev_cc <= cc2) { - prev_cc = cc2; - continue; - } - let j2 = i - 1; - while (true) { - let tmp = ret[j2 + 1]; - ret[j2 + 1] = ret[j2]; - ret[j2] = tmp; - if (!j2) break; - prev_cc = unpack_cc(ret[--j2]); - if (prev_cc <= cc2) break; - } - prev_cc = unpack_cc(ret[i]); - } + if (type === "string") + return [{ type: "bytes32" }, keccak256$1(toHex$1(value))]; + if (type.lastIndexOf("]") === type.length - 1) { + const parsedType = type.slice(0, type.lastIndexOf("[")); + const typeValuePairs = value.map((item2) => encodeField({ + name: name2, + type: parsedType, + types: types2, + value: item2 + })); + return [ + { type: "bytes32" }, + keccak256$1(encodeAbiParameters(typeValuePairs.map(([t2]) => t2), typeValuePairs.map(([, v3]) => v3))) + ]; } - return ret; + return [{ type }, value]; } -function composed_from_decomposed(v3) { - let ret = []; - let stack = []; - let prev_cp = -1; - let prev_cc = 0; - for (let packed of v3) { - let cc2 = unpack_cc(packed); - let cp = unpack_cp(packed); - if (prev_cp == -1) { - if (cc2 == 0) { - prev_cp = cp; - } else { - ret.push(cp); - } - } else if (prev_cc > 0 && prev_cc >= cc2) { - if (cc2 == 0) { - ret.push(prev_cp, ...stack); - stack.length = 0; - prev_cp = cp; - } else { - stack.push(cp); - } - prev_cc = cc2; - } else { - let composed = compose_pair(prev_cp, cp); - if (composed >= 0) { - prev_cp = composed; - } else if (prev_cc == 0 && cc2 == 0) { - ret.push(prev_cp); - prev_cp = cp; - } else { - stack.push(cp); - prev_cc = cc2; - } +function serializeTypedData(parameters) { + const { domain: domain_, message: message_, primaryType, types: types2 } = parameters; + const normalizeData = (struct, data_) => { + const data = { ...data_ }; + for (const param of struct) { + const { name: name2, type } = param; + if (type === "address") + data[name2] = data[name2].toLowerCase(); } - } - if (prev_cp >= 0) { - ret.push(prev_cp, ...stack); - } - return ret; -} -function nfd(cps) { - return decomposed(cps).map(unpack_cp); -} -function nfc(cps) { - return composed_from_decomposed(decomposed(cps)); -} -const HYPHEN = 45; -const STOP_CH = "."; -const FE0F = 65039; -const UNIQUE_PH = 1; -const Array_from = (x2) => Array.from(x2); -function group_has_cp(g2, cp) { - return g2.P.has(cp) || g2.Q.has(cp); -} -class Emoji extends Array { - get is_emoji() { - return true; - } - // free tagging system -} -let MAPPED, IGNORED, CM, NSM, ESCAPE, GROUPS, WHOLE_VALID, WHOLE_MAP, VALID, EMOJI_LIST, EMOJI_ROOT; -function init() { - if (MAPPED) return; - let r2 = read_compressed_payload(COMPRESSED$1); - const read_sorted_array = () => read_sorted(r2); - const read_sorted_set = () => new Set(read_sorted_array()); - const set_add_many = (set, v3) => v3.forEach((x2) => set.add(x2)); - MAPPED = new Map(read_mapped(r2)); - IGNORED = read_sorted_set(); - CM = read_sorted_array(); - NSM = new Set(read_sorted_array().map((i) => CM[i])); - CM = new Set(CM); - ESCAPE = read_sorted_set(); - read_sorted_set(); - let chunks = read_sorted_arrays(r2); - let unrestricted = r2(); - const read_chunked = () => { - let set = /* @__PURE__ */ new Set(); - read_sorted_array().forEach((i) => set_add_many(set, chunks[i])); - set_add_many(set, read_sorted_array()); - return set; + return data; }; - GROUPS = read_array_while((i) => { - let N2 = read_array_while(r2).map((x2) => x2 + 96); - if (N2.length) { - let R2 = i >= unrestricted; - N2[0] -= 32; - N2 = str_from_cps(N2); - if (R2) N2 = `Restricted[${N2}]`; - let P2 = read_chunked(); - let Q2 = read_chunked(); - let M2 = !r2(); - return { N: N2, P: P2, Q: Q2, M: M2, R: R2 }; - } - }); - WHOLE_VALID = read_sorted_set(); - WHOLE_MAP = /* @__PURE__ */ new Map(); - let wholes = read_sorted_array().concat(Array_from(WHOLE_VALID)).sort((a2, b2) => a2 - b2); - wholes.forEach((cp, i) => { - let d2 = r2(); - let w2 = wholes[i] = d2 ? wholes[i - d2] : { V: [], M: /* @__PURE__ */ new Map() }; - w2.V.push(cp); - if (!WHOLE_VALID.has(cp)) { - WHOLE_MAP.set(cp, w2); - } - }); - for (let { V: V2, M: M2 } of new Set(WHOLE_MAP.values())) { - let recs = []; - for (let cp of V2) { - let gs = GROUPS.filter((g2) => group_has_cp(g2, cp)); - let rec = recs.find(({ G: G2 }) => gs.some((g2) => G2.has(g2))); - if (!rec) { - rec = { G: /* @__PURE__ */ new Set(), V: [] }; - recs.push(rec); - } - rec.V.push(cp); - set_add_many(rec.G, gs); - } - let union = recs.flatMap((x2) => Array_from(x2.G)); - for (let { G: G2, V: V3 } of recs) { - let complement = new Set(union.filter((g2) => !G2.has(g2))); - for (let cp of V3) { - M2.set(cp, complement); + const domain2 = (() => { + if (!types2.EIP712Domain) + return {}; + if (!domain_) + return {}; + return normalizeData(types2.EIP712Domain, domain_); + })(); + const message = (() => { + if (primaryType === "EIP712Domain") + return void 0; + return normalizeData(types2[primaryType], message_); + })(); + return stringify$3({ domain: domain2, message, primaryType, types: types2 }); +} +function validateTypedData(parameters) { + const { domain: domain2, message, primaryType, types: types2 } = parameters; + const validateData = (struct, data) => { + for (const param of struct) { + const { name: name2, type } = param; + const value = data[name2]; + const integerMatch = type.match(integerRegex); + if (integerMatch && (typeof value === "number" || typeof value === "bigint")) { + const [_type2, base, size_] = integerMatch; + numberToHex(value, { + signed: base === "int", + size: Number.parseInt(size_) / 8 + }); } - } - } - VALID = /* @__PURE__ */ new Set(); - let multi = /* @__PURE__ */ new Set(); - const add_to_union = (cp) => VALID.has(cp) ? multi.add(cp) : VALID.add(cp); - for (let g2 of GROUPS) { - for (let cp of g2.P) add_to_union(cp); - for (let cp of g2.Q) add_to_union(cp); - } - for (let cp of VALID) { - if (!WHOLE_MAP.has(cp) && !multi.has(cp)) { - WHOLE_MAP.set(cp, UNIQUE_PH); - } - } - set_add_many(VALID, nfd(VALID)); - EMOJI_LIST = read_trie(r2).map((v3) => Emoji.from(v3)).sort(compare_arrays); - EMOJI_ROOT = /* @__PURE__ */ new Map(); - for (let cps of EMOJI_LIST) { - let prev = [EMOJI_ROOT]; - for (let cp of cps) { - let next = prev.map((node) => { - let child = node.get(cp); - if (!child) { - child = /* @__PURE__ */ new Map(); - node.set(cp, child); - } - return child; - }); - if (cp === FE0F) { - prev.push(...next); - } else { - prev = next; + if (type === "address" && typeof value === "string" && !isAddress$1(value)) + throw new InvalidAddressError({ address: value }); + const bytesMatch = type.match(bytesRegex); + if (bytesMatch) { + const [_type2, size_] = bytesMatch; + if (size_ && size$5(value) !== Number.parseInt(size_)) + throw new BytesSizeMismatchError({ + expectedSize: Number.parseInt(size_), + givenSize: size$5(value) + }); } + const struct2 = types2[type]; + if (struct2) + validateData(struct2, value); } - for (let x2 of prev) { - x2.V = cps; - } - } + }; + if (types2.EIP712Domain && domain2) + validateData(types2.EIP712Domain, domain2); + if (primaryType !== "EIP712Domain") + validateData(types2[primaryType], message); } -function quoted_cp(cp) { - return (should_escape(cp) ? "" : `${bidi_qq(safe_str_from_cps([cp]))} `) + quote_cp(cp); +function getTypesForEIP712Domain({ domain: domain2 }) { + return [ + typeof (domain2 == null ? void 0 : domain2.name) === "string" && { name: "name", type: "string" }, + (domain2 == null ? void 0 : domain2.version) && { name: "version", type: "string" }, + typeof (domain2 == null ? void 0 : domain2.chainId) === "number" && { + name: "chainId", + type: "uint256" + }, + (domain2 == null ? void 0 : domain2.verifyingContract) && { + name: "verifyingContract", + type: "address" + }, + (domain2 == null ? void 0 : domain2.salt) && { name: "salt", type: "bytes32" } + ].filter(Boolean); } -function bidi_qq(s2) { - return `"${s2}"‎`; +const presignMessagePrefix = "Ethereum Signed Message:\n"; +function toPrefixedMessage(message_) { + const message = (() => { + if (typeof message_ === "string") + return stringToHex(message_); + if (typeof message_.raw === "string") + return message_.raw; + return bytesToHex$3(message_.raw); + })(); + const prefix = stringToHex(`${presignMessagePrefix}${size$5(message)}`); + return concat$1([prefix, message]); } -function check_label_extension(cps) { - if (cps.length >= 4 && cps[2] == HYPHEN && cps[3] == HYPHEN) { - throw new Error(`invalid label extension: "${str_from_cps(cps.slice(0, 4))}"`); - } +function hashMessage$1(message, to_) { + return keccak256$1(toPrefixedMessage(message), to_); } -function check_leading_underscore(cps) { - const UNDERSCORE = 95; - for (let i = cps.lastIndexOf(UNDERSCORE); i > 0; ) { - if (cps[--i] !== UNDERSCORE) { - throw new Error("underscore allowed only at start"); - } - } +const erc6492MagicBytes = "0x6492649264926492649264926492649264926492649264926492649264926492"; +function isErc6492Signature(signature2) { + return sliceHex(signature2, -32) === erc6492MagicBytes; } -function check_fenced(cps) { - let cp = cps[0]; - let prev = FENCED.get(cp); - if (prev) throw error_placement(`leading ${prev}`); - let n2 = cps.length; - let last = -1; - for (let i = 1; i < n2; i++) { - cp = cps[i]; - let match = FENCED.get(cp); - if (match) { - if (last == i) throw error_placement(`${prev} + ${match}`); - last = i + 1; - prev = match; - } - } - if (last == n2) throw error_placement(`trailing ${prev}`); +function serializeErc6492Signature(parameters) { + const { address, data, signature: signature2, to = "hex" } = parameters; + const signature_ = concatHex([ + encodeAbiParameters([{ type: "address" }, { type: "bytes" }, { type: "bytes" }], [address, data, signature2]), + erc6492MagicBytes + ]); + if (to === "hex") + return signature_; + return hexToBytes$2(signature_); } -function safe_str_from_cps(cps, max2 = Infinity, quoter = quote_cp) { - let buf = []; - if (is_combining_mark(cps[0])) buf.push("◌"); - if (cps.length > max2) { - max2 >>= 1; - cps = [...cps.slice(0, max2), 8230, ...cps.slice(-max2)]; +class InvalidDecimalNumberError extends BaseError$3 { + constructor({ value }) { + super(`Number \`${value}\` is not a valid decimal number.`, { + name: "InvalidDecimalNumberError" + }); } - let prev = 0; - let n2 = cps.length; - for (let i = 0; i < n2; i++) { - let cp = cps[i]; - if (should_escape(cp)) { - buf.push(str_from_cps(cps.slice(prev, i))); - buf.push(quoter(cp)); - prev = i + 1; +} +function parseUnits$3(value, decimals) { + if (!/^(-?)([0-9]*)\.?([0-9]*)$/.test(value)) + throw new InvalidDecimalNumberError({ value }); + let [integer, fraction = "0"] = value.split("."); + const negative = integer.startsWith("-"); + if (negative) + integer = integer.slice(1); + fraction = fraction.replace(/(0+)$/, ""); + if (decimals === 0) { + if (Math.round(Number(`.${fraction}`)) === 1) + integer = `${BigInt(integer) + 1n}`; + fraction = ""; + } else if (fraction.length > decimals) { + const [left, unit, right] = [ + fraction.slice(0, decimals - 1), + fraction.slice(decimals - 1, decimals), + fraction.slice(decimals) + ]; + const rounded = Math.round(Number(`${unit}.${right}`)); + if (rounded > 9) + fraction = `${BigInt(left) + BigInt(1)}0`.padStart(left.length + 1, "0"); + else + fraction = `${left}${rounded}`; + if (fraction.length > decimals) { + fraction = fraction.slice(1); + integer = `${BigInt(integer) + 1n}`; } + fraction = fraction.slice(0, decimals); + } else { + fraction = fraction.padEnd(decimals, "0"); } - buf.push(str_from_cps(cps.slice(prev, n2))); - return buf.join(""); + return BigInt(`${negative ? "-" : ""}${integer}${fraction}`); } -function is_combining_mark(cp) { - init(); - return CM.has(cp); +function formatStorageProof(storageProof) { + return storageProof.map((proof) => ({ + ...proof, + value: BigInt(proof.value) + })); } -function should_escape(cp) { - init(); - return ESCAPE.has(cp); +function formatProof(proof) { + return { + ...proof, + balance: proof.balance ? BigInt(proof.balance) : void 0, + nonce: proof.nonce ? hexToNumber$2(proof.nonce) : void 0, + storageProof: proof.storageProof ? formatStorageProof(proof.storageProof) : void 0 + }; } -function ens_normalize(name2) { - return flatten(split$1(name2, nfc, filter_fe0f)); +async function getProof(client2, { address, blockNumber, blockTag: blockTag_, storageKeys }) { + const blockTag = blockTag_ ?? "latest"; + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + const proof = await client2.request({ + method: "eth_getProof", + params: [address, storageKeys, blockNumberHex || blockTag] + }); + return formatProof(proof); } -function split$1(name2, nf2, ef2) { - if (!name2) return []; - init(); - let offset2 = 0; - return name2.split(STOP_CH).map((label) => { - let input2 = explode_cp(label); - let info = { - input: input2, - offset: offset2 - // codepoint, not substring! - }; - offset2 += input2.length + 1; - try { - let tokens = info.tokens = tokens_from_str(input2, nf2, ef2); - let token_count = tokens.length; - let type; - if (!token_count) { - throw new Error(`empty label`); - } - let norm2 = info.output = tokens.flat(); - check_leading_underscore(norm2); - let emoji = info.emoji = token_count > 1 || tokens[0].is_emoji; - if (!emoji && norm2.every((cp) => cp < 128)) { - check_label_extension(norm2); - type = "ASCII"; - } else { - let chars = tokens.flatMap((x2) => x2.is_emoji ? [] : x2); - if (!chars.length) { - type = "Emoji"; - } else { - if (CM.has(norm2[0])) throw error_placement("leading combining mark"); - for (let i = 1; i < token_count; i++) { - let cps = tokens[i]; - if (!cps.is_emoji && CM.has(cps[0])) { - throw error_placement(`emoji + combining mark: "${str_from_cps(tokens[i - 1])} + ${safe_str_from_cps([cps[0]])}"`); - } - } - check_fenced(norm2); - let unique = Array_from(new Set(chars)); - let [g2] = determine_group(unique); - check_group(g2, chars); - check_whole(g2, unique); - type = g2.N; +async function waitForTransactionReceipt(client2, { + confirmations = 1, + hash: hash2, + onReplaced, + pollingInterval = client2.pollingInterval, + retryCount = 6, + retryDelay = ({ count: count2 }) => ~~(1 << count2) * 200, + // exponential backoff + timeout +}) { + const observerId = stringify$3(["waitForTransactionReceipt", client2.uid, hash2]); + let count2 = 0; + let transaction2; + let replacedTransaction; + let receipt; + let retrying = false; + return new Promise((resolve, reject) => { + if (timeout) + setTimeout(() => reject(new WaitForTransactionReceiptTimeoutError({ hash: hash2 })), timeout); + const _unobserve = observe(observerId, { onReplaced, resolve, reject }, (emit2) => { + const _unwatch = getAction$1(client2, watchBlockNumber, "watchBlockNumber")({ + emitMissed: true, + emitOnBegin: true, + poll: true, + pollingInterval, + async onBlockNumber(blockNumber_) { + const done = (fn) => { + _unwatch(); + fn(); + _unobserve(); + }; + let blockNumber = blockNumber_; + if (retrying) + return; + if (count2 > retryCount) + done(() => emit2.reject(new WaitForTransactionReceiptTimeoutError({ hash: hash2 }))); + try { + if (receipt) { + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + done(() => emit2.resolve(receipt)); + return; + } + if (!transaction2) { + retrying = true; + await withRetry(async () => { + transaction2 = await getAction$1(client2, getTransaction, "getTransaction")({ hash: hash2 }); + if (transaction2.blockNumber) + blockNumber = transaction2.blockNumber; + }, { + delay: retryDelay, + retryCount + }); + retrying = false; + } + receipt = await getAction$1(client2, getTransactionReceipt$1, "getTransactionReceipt")({ hash: hash2 }); + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + done(() => emit2.resolve(receipt)); + } catch (err) { + if (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError) { + if (!transaction2) { + retrying = false; + return; + } + try { + replacedTransaction = transaction2; + retrying = true; + const block = await withRetry(() => getAction$1(client2, getBlock, "getBlock")({ + blockNumber, + includeTransactions: true + }), { + delay: retryDelay, + retryCount, + shouldRetry: ({ error }) => error instanceof BlockNotFoundError + }); + retrying = false; + const replacementTransaction = block.transactions.find(({ from, nonce }) => from === replacedTransaction.from && nonce === replacedTransaction.nonce); + if (!replacementTransaction) + return; + receipt = await getAction$1(client2, getTransactionReceipt$1, "getTransactionReceipt")({ + hash: replacementTransaction.hash + }); + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + let reason = "replaced"; + if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value) { + reason = "repriced"; + } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) { + reason = "cancelled"; + } + done(() => { + var _a2; + (_a2 = emit2.onReplaced) == null ? void 0 : _a2.call(emit2, { + reason, + replacedTransaction, + transaction: replacementTransaction, + transactionReceipt: receipt + }); + emit2.resolve(receipt); + }); + } catch (err_) { + done(() => emit2.reject(err_)); + } + } else { + done(() => emit2.reject(err)); + } + } finally { + count2++; + } } - } - info.type = type; - } catch (err) { - info.error = err; - } - return info; + }); + }); }); } -function check_whole(group, unique) { - let maker; - let shared = []; - for (let cp of unique) { - let whole = WHOLE_MAP.get(cp); - if (whole === UNIQUE_PH) return; - if (whole) { - let set = whole.M.get(cp); - maker = maker ? maker.filter((g2) => set.has(g2)) : Array_from(set); - if (!maker.length) return; - } else { - shared.push(cp); - } - } - if (maker) { - for (let g2 of maker) { - if (shared.every((cp) => group_has_cp(g2, cp))) { - throw new Error(`whole-script confusable: ${group.N}/${g2.N}`); +async function requestAddresses(client2) { + const addresses = await client2.request({ method: "eth_requestAccounts" }, { dedupe: true, retryCount: 0 }); + return addresses.map((address) => getAddress$1(address)); +} +async function requestPermissions(client2, permissions) { + return client2.request({ + method: "wallet_requestPermissions", + params: [permissions] + }, { retryCount: 0 }); +} +async function signTransaction(client2, parameters) { + var _a2, _b2, _c2, _d2; + const { account: account_ = client2.account, chain = client2.chain, ...transaction2 } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signTransaction" + }); + const account2 = parseAccount(account_); + assertRequest({ + account: account2, + ...parameters + }); + const chainId = await getAction$1(client2, getChainId$2, "getChainId")({}); + if (chain !== null) + assertCurrentChain({ + currentChainId: chainId, + chain + }); + const formatters = (chain == null ? void 0 : chain.formatters) || ((_a2 = client2.chain) == null ? void 0 : _a2.formatters); + const format2 = ((_b2 = formatters == null ? void 0 : formatters.transactionRequest) == null ? void 0 : _b2.format) || formatTransactionRequest; + if (account2.signTransaction) + return account2.signTransaction({ + ...transaction2, + chainId + }, { serializer: (_d2 = (_c2 = client2.chain) == null ? void 0 : _c2.serializers) == null ? void 0 : _d2.transaction }); + return await client2.request({ + method: "eth_signTransaction", + params: [ + { + ...format2(transaction2), + chainId: numberToHex(chainId), + from: account2.address } - } - } + ] + }, { retryCount: 0 }); } -function determine_group(unique) { - let groups = GROUPS; - for (let cp of unique) { - let gs = groups.filter((g2) => group_has_cp(g2, cp)); - if (!gs.length) { - if (!GROUPS.some((g2) => group_has_cp(g2, cp))) { - throw error_disallowed(cp); - } else { - throw error_group_member(groups[0], cp); +async function signMessage$1(client2, { account: account_ = client2.account, message }) { + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signMessage" + }); + const account2 = parseAccount(account_); + if (account2.signMessage) + return account2.signMessage({ message }); + const message_ = (() => { + if (typeof message === "string") + return stringToHex(message); + if (message.raw instanceof Uint8Array) + return toHex$1(message.raw); + return message.raw; + })(); + return client2.request({ + method: "personal_sign", + params: [message_, account2.address] + }, { retryCount: 0 }); +} +async function signTypedData(client2, parameters) { + const { account: account_ = client2.account, domain: domain2, message, primaryType } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signTypedData" + }); + const account2 = parseAccount(account_); + const types2 = { + EIP712Domain: getTypesForEIP712Domain({ domain: domain2 }), + ...parameters.types + }; + validateTypedData({ domain: domain2, message, primaryType, types: types2 }); + if (account2.signTypedData) + return account2.signTypedData({ domain: domain2, message, primaryType, types: types2 }); + const typedData = serializeTypedData({ domain: domain2, message, primaryType, types: types2 }); + return client2.request({ + method: "eth_signTypedData_v4", + params: [account2.address, typedData] + }, { retryCount: 0 }); +} +async function simulateContract$1(client2, parameters) { + const { abi: abi2, address, args, dataSuffix, functionName, ...callRequest } = parameters; + const account2 = callRequest.account ? parseAccount(callRequest.account) : client2.account; + const calldata = encodeFunctionData({ abi: abi2, args, functionName }); + try { + const { data } = await getAction$1(client2, call, "call")({ + batch: false, + data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + ...callRequest, + account: account2 + }); + const result = decodeFunctionResult({ + abi: abi2, + args, + functionName, + data: data || "0x" + }); + const minimizedAbi = abi2.filter((abiItem) => "name" in abiItem && abiItem.name === parameters.functionName); + return { + result, + request: { + abi: minimizedAbi, + address, + args, + dataSuffix, + functionName, + ...callRequest, + account: account2 } - } - groups = gs; - if (gs.length == 1) break; + }; + } catch (error) { + throw getContractError(error, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/simulateContract", + functionName, + sender: account2 == null ? void 0 : account2.address + }); } - return groups; } -function flatten(split2) { - return split2.map(({ input: input2, error, output: output2 }) => { - if (error) { - let msg = error.message; - throw new Error(split2.length == 1 ? msg : `Invalid label ${bidi_qq(safe_str_from_cps(input2, 63))}: ${msg}`); - } - return str_from_cps(output2); - }).join(STOP_CH); +async function switchChain$1(client2, { id: id2 }) { + await client2.request({ + method: "wallet_switchEthereumChain", + params: [ + { + chainId: numberToHex(id2) + } + ] + }, { retryCount: 0 }); } -function error_disallowed(cp) { - return new Error(`disallowed character: ${quoted_cp(cp)}`); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n$8 = BigInt(0); +const _1n$a = BigInt(1); +const _2n$6 = BigInt(2); +function isBytes$1(a2) { + return a2 instanceof Uint8Array || a2 != null && typeof a2 === "object" && a2.constructor.name === "Uint8Array"; } -function error_group_member(g2, cp) { - let quoted = quoted_cp(cp); - let gg2 = GROUPS.find((g3) => g3.P.has(cp)); - if (gg2) { - quoted = `${gg2.N} ${quoted}`; +function abytes(item2) { + if (!isBytes$1(item2)) + throw new Error("Uint8Array expected"); +} +const hexes$2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +function bytesToHex$2(bytes2) { + abytes(bytes2); + let hex2 = ""; + for (let i = 0; i < bytes2.length; i++) { + hex2 += hexes$2[bytes2[i]]; } - return new Error(`illegal mixture: ${g2.N} + ${quoted}`); + return hex2; } -function error_placement(where) { - return new Error(`illegal placement: ${where}`); +function numberToHexUnpadded$1(num) { + const hex2 = num.toString(16); + return hex2.length & 1 ? `0${hex2}` : hex2; } -function check_group(g2, cps) { - for (let cp of cps) { - if (!group_has_cp(g2, cp)) { - throw error_group_member(g2, cp); - } - } - if (g2.M) { - let decomposed2 = nfd(cps); - for (let i = 1, e2 = decomposed2.length; i < e2; i++) { - if (NSM.has(decomposed2[i])) { - let j2 = i + 1; - for (let cp; j2 < e2 && NSM.has(cp = decomposed2[j2]); j2++) { - for (let k2 = i; k2 < j2; k2++) { - if (decomposed2[k2] == cp) { - throw new Error(`duplicate non-spacing marks: ${quoted_cp(cp)}`); - } - } - } - if (j2 - i > NSM_MAX) { - throw new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(decomposed2.slice(i - 1, j2)))} (${j2 - i}/${NSM_MAX})`); - } - i = j2; - } - } - } +function hexToNumber$1(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + return BigInt(hex2 === "" ? "0" : `0x${hex2}`); } -function tokens_from_str(input2, nf2, ef2) { - let ret = []; - let chars = []; - input2 = input2.slice().reverse(); - while (input2.length) { - let emoji = consume_emoji_reversed(input2); - if (emoji) { - if (chars.length) { - ret.push(nf2(chars)); - chars = []; - } - ret.push(ef2(emoji)); - } else { - let cp = input2.pop(); - if (VALID.has(cp)) { - chars.push(cp); - } else { - let cps = MAPPED.get(cp); - if (cps) { - chars.push(...cps); - } else if (!IGNORED.has(cp)) { - throw error_disallowed(cp); - } - } +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +function hexToBytes$1(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + const hl2 = hex2.length; + const al2 = hl2 / 2; + if (hl2 % 2) + throw new Error("padded hex string expected, got unpadded hex of length " + hl2); + const array = new Uint8Array(al2); + for (let ai2 = 0, hi2 = 0; ai2 < al2; ai2++, hi2 += 2) { + const n1 = asciiToBase16(hex2.charCodeAt(hi2)); + const n2 = asciiToBase16(hex2.charCodeAt(hi2 + 1)); + if (n1 === void 0 || n2 === void 0) { + const char = hex2[hi2] + hex2[hi2 + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi2); } + array[ai2] = n1 * 16 + n2; } - if (chars.length) { - ret.push(nf2(chars)); - } - return ret; + return array; } -function filter_fe0f(cps) { - return cps.filter((cp) => cp != FE0F); +function bytesToNumberBE$1(bytes2) { + return hexToNumber$1(bytesToHex$2(bytes2)); } -function consume_emoji_reversed(cps, eaten) { - let node = EMOJI_ROOT; - let emoji; - let pos = cps.length; - while (pos) { - node = node.get(cps[--pos]); - if (!node) break; - let { V: V2 } = node; - if (V2) { - emoji = V2; - cps.length = pos; - } - } - return emoji; +function bytesToNumberLE$1(bytes2) { + abytes(bytes2); + return hexToNumber$1(bytesToHex$2(Uint8Array.from(bytes2).reverse())); } -const Zeros = new Uint8Array(32); -Zeros.fill(0); -function checkComponent(comp) { - assertArgument(comp.length !== 0, "invalid ENS name; empty component", "comp", comp); - return comp; +function numberToBytesBE$1(n2, len) { + return hexToBytes$1(n2.toString(16).padStart(len * 2, "0")); } -function ensNameSplit(name2) { - const bytes2 = toUtf8Bytes(ensNormalize(name2)); - const comps = []; - if (name2.length === 0) { - return comps; - } - let last = 0; - for (let i = 0; i < bytes2.length; i++) { - const d2 = bytes2[i]; - if (d2 === 46) { - comps.push(checkComponent(bytes2.slice(last, i))); - last = i + 1; - } - } - assertArgument(last < bytes2.length, "invalid ENS name; empty component", "name", name2); - comps.push(checkComponent(bytes2.slice(last))); - return comps; +function numberToBytesLE$1(n2, len) { + return numberToBytesBE$1(n2, len).reverse(); } -function ensNormalize(name2) { - try { - if (name2.length === 0) { - throw new Error("empty label"); +function numberToVarBytesBE$1(n2) { + return hexToBytes$1(numberToHexUnpadded$1(n2)); +} +function ensureBytes$1(title, hex2, expectedLength) { + let res; + if (typeof hex2 === "string") { + try { + res = hexToBytes$1(hex2); + } catch (e2) { + throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e2}`); } - return ens_normalize(name2); - } catch (error) { - assertArgument(false, `invalid ENS name (${error.message})`, "name", name2); + } else if (isBytes$1(hex2)) { + res = Uint8Array.from(hex2); + } else { + throw new Error(`${title} must be hex string or Uint8Array`); } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; } -function isValidName(name2) { - try { - return ensNameSplit(name2).length !== 0; - } catch (error) { +function concatBytes$2(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a2 = arrays[i]; + abytes(a2); + sum += a2.length; } - return false; -} -function namehash$1(name2) { - assertArgument(typeof name2 === "string", "invalid ENS name; not a string", "name", name2); - assertArgument(name2.length, `invalid ENS name (empty label)`, "name", name2); - let result = Zeros; - const comps = ensNameSplit(name2); - while (comps.length) { - result = keccak256$1(concat$1([result, keccak256$1(comps.pop())])); + const res = new Uint8Array(sum); + for (let i = 0, pad2 = 0; i < arrays.length; i++) { + const a2 = arrays[i]; + res.set(a2, pad2); + pad2 += a2.length; } - return hexlify(result); + return res; } -function dnsEncode(name2, _maxLength) { - const length = _maxLength != null ? _maxLength : 63; - assertArgument(length <= 255, "DNS encoded label cannot exceed 255", "length", length); - return hexlify(concat$1(ensNameSplit(name2).map((comp) => { - assertArgument(comp.length <= length, `label ${JSON.stringify(name2)} exceeds ${length} bytes`, "name", name2); - const bytes2 = new Uint8Array(comp.length + 1); - bytes2.set(comp, 1); - bytes2[0] = bytes2.length - 1; - return bytes2; - }))) + "00"; +function equalBytes$1(a2, b2) { + if (a2.length !== b2.length) + return false; + let diff = 0; + for (let i = 0; i < a2.length; i++) + diff |= a2[i] ^ b2[i]; + return diff === 0; } -function accessSetify(addr, storageKeys) { - return { - address: getAddress$1(addr), - storageKeys: storageKeys.map((storageKey2, index2) => { - assertArgument(isHexString(storageKey2, 32), "invalid slot", `storageKeys[${index2}]`, storageKey2); - return storageKey2.toLowerCase(); - }) - }; +function utf8ToBytes$3(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); } -function accessListify(value) { - if (Array.isArray(value)) { - return value.map((set, index2) => { - if (Array.isArray(set)) { - assertArgument(set.length === 2, "invalid slot set", `value[${index2}]`, set); - return accessSetify(set[0], set[1]); - } - assertArgument(set != null && typeof set === "object", "invalid address-slot set", "value", value); - return accessSetify(set.address, set.storageKeys); - }); - } - assertArgument(value != null && typeof value === "object", "invalid access list", "value", value); - const result = Object.keys(value).map((addr) => { - const storageKeys = value[addr].reduce((accum, storageKey2) => { - accum[storageKey2] = true; - return accum; - }, {}); - return accessSetify(addr, Object.keys(storageKeys).sort()); - }); - result.sort((a2, b2) => a2.address.localeCompare(b2.address)); - return result; +function bitLen$1(n2) { + let len; + for (len = 0; n2 > _0n$8; n2 >>= _1n$a, len += 1) + ; + return len; } -function computeAddress(key) { - let pubkey; - if (typeof key === "string") { - pubkey = SigningKey.computePublicKey(key, false); - } else { - pubkey = key.publicKey; - } - return getAddress$1(keccak256$1("0x" + pubkey.substring(4)).substring(26)); +function bitGet$1(n2, pos) { + return n2 >> BigInt(pos) & _1n$a; } -function recoverAddress$1(digest, signature2) { - return computeAddress(SigningKey.recoverPublicKey(digest, signature2)); +function bitSet$1(n2, pos, value) { + return n2 | (value ? _1n$a : _0n$8) << BigInt(pos); } -const BN_0$4 = BigInt(0); -const BN_2$2 = BigInt(2); -const BN_27 = BigInt(27); -const BN_28 = BigInt(28); -const BN_35 = BigInt(35); -const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -const BLOB_SIZE = 4096 * 32; -function getVersionedHash(version2, hash2) { - let versioned = version2.toString(16); - while (versioned.length < 2) { - versioned = "0" + versioned; - } - versioned += sha256$3(hash2).substring(4); - return "0x" + versioned; +const bitMask$1 = (n2) => (_2n$6 << BigInt(n2 - 1)) - _1n$a; +const u8n$1 = (data) => new Uint8Array(data); +const u8fr$1 = (arr) => Uint8Array.from(arr); +function createHmacDrbg$1(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + let v3 = u8n$1(hashLen); + let k2 = u8n$1(hashLen); + let i = 0; + const reset = () => { + v3.fill(1); + k2.fill(0); + i = 0; + }; + const h2 = (...b2) => hmacFn(k2, v3, ...b2); + const reseed = (seed = u8n$1()) => { + k2 = h2(u8fr$1([0]), seed); + v3 = h2(); + if (seed.length === 0) + return; + k2 = h2(u8fr$1([1]), seed); + v3 = h2(); + }; + const gen2 = () => { + if (i++ >= 1e3) + throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v3 = h2(); + const sl2 = v3.slice(); + out.push(sl2); + len += v3.length; + } + return concatBytes$2(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while (!(res = pred(gen2()))) + reseed(); + reset(); + return res; + }; + return genUntil; } -function handleAddress(value) { - if (value === "0x") { - return null; - } - return getAddress$1(value); +const validatorFns$1 = { + bigint: (val) => typeof val === "bigint", + function: (val) => typeof val === "function", + boolean: (val) => typeof val === "boolean", + string: (val) => typeof val === "string", + stringOrUint8Array: (val) => typeof val === "string" || isBytes$1(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object2) => object2.Fp.isValid(val), + hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) +}; +function validateObject$1(object2, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns$1[type]; + if (typeof checkVal !== "function") + throw new Error(`Invalid validator "${type}", expected function`); + const val = object2[fieldName]; + if (isOptional && val === void 0) + return; + if (!checkVal(val, object2)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object2; } -function handleAccessList(value, param) { - try { - return accessListify(value); - } catch (error) { - assertArgument(false, error.message, param, value); - } +const ut$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + abytes, + bitGet: bitGet$1, + bitLen: bitLen$1, + bitMask: bitMask$1, + bitSet: bitSet$1, + bytesToHex: bytesToHex$2, + bytesToNumberBE: bytesToNumberBE$1, + bytesToNumberLE: bytesToNumberLE$1, + concatBytes: concatBytes$2, + createHmacDrbg: createHmacDrbg$1, + ensureBytes: ensureBytes$1, + equalBytes: equalBytes$1, + hexToBytes: hexToBytes$1, + hexToNumber: hexToNumber$1, + isBytes: isBytes$1, + numberToBytesBE: numberToBytesBE$1, + numberToBytesLE: numberToBytesLE$1, + numberToHexUnpadded: numberToHexUnpadded$1, + numberToVarBytesBE: numberToVarBytesBE$1, + utf8ToBytes: utf8ToBytes$3, + validateObject: validateObject$1 +}, Symbol.toStringTag, { value: "Module" })); +function isBytesEqual(a_, b_) { + const a2 = isHex(a_) ? toBytes$3(a_) : a_; + const b2 = isHex(b_) ? toBytes$3(b_) : b_; + return equalBytes$1(a2, b2); } -function handleNumber(_value2, param) { - if (_value2 === "0x") { - return 0; - } - return getNumber(_value2, param); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n$7 = BigInt(0), _1n$9 = BigInt(1), _2n$5 = BigInt(2), _3n$3 = BigInt(3); +const _4n$1 = BigInt(4), _5n$1 = BigInt(5), _8n$1 = BigInt(8); +BigInt(9); +BigInt(16); +function mod$1(a2, b2) { + const result = a2 % b2; + return result >= _0n$7 ? result : b2 + result; } -function handleUint(_value2, param) { - if (_value2 === "0x") { - return BN_0$4; +function pow$1(num, power, modulo) { + if (modulo <= _0n$7 || power < _0n$7) + throw new Error("Expected power/modulo > 0"); + if (modulo === _1n$9) + return _0n$7; + let res = _1n$9; + while (power > _0n$7) { + if (power & _1n$9) + res = res * num % modulo; + num = num * num % modulo; + power >>= _1n$9; } - const value = getBigInt(_value2, param); - assertArgument(value <= BN_MAX_UINT, "value exceeds uint size", param, value); - return value; -} -function formatNumber(_value2, name2) { - const value = getBigInt(_value2, "value"); - const result = toBeArray(value); - assertArgument(result.length <= 32, `value too large`, `tx.${name2}`, value); - return result; -} -function formatAccessList(value) { - return accessListify(value).map((set) => [set.address, set.storageKeys]); + return res; } -function formatHashes(value, param) { - assertArgument(Array.isArray(value), `invalid ${param}`, "value", value); - for (let i = 0; i < value.length; i++) { - assertArgument(isHexString(value[i], 32), "invalid ${ param } hash", `value[${i}]`, value[i]); +function pow2$1(x2, power, modulo) { + let res = x2; + while (power-- > _0n$7) { + res *= res; + res %= modulo; } - return value; + return res; } -function _parseLegacy(data) { - const fields = decodeRlp(data); - assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 6), "invalid field count for legacy transaction", "data", data); - const tx = { - type: 0, - nonce: handleNumber(fields[0], "nonce"), - gasPrice: handleUint(fields[1], "gasPrice"), - gasLimit: handleUint(fields[2], "gasLimit"), - to: handleAddress(fields[3]), - value: handleUint(fields[4], "value"), - data: hexlify(fields[5]), - chainId: BN_0$4 - }; - if (fields.length === 6) { - return tx; +function invert$1(number2, modulo) { + if (number2 === _0n$7 || modulo <= _0n$7) { + throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`); } - const v3 = handleUint(fields[6], "v"); - const r2 = handleUint(fields[7], "r"); - const s2 = handleUint(fields[8], "s"); - if (r2 === BN_0$4 && s2 === BN_0$4) { - tx.chainId = v3; - } else { - let chainId = (v3 - BN_35) / BN_2$2; - if (chainId < BN_0$4) { - chainId = BN_0$4; - } - tx.chainId = chainId; - assertArgument(chainId !== BN_0$4 || (v3 === BN_27 || v3 === BN_28), "non-canonical legacy v", "v", fields[6]); - tx.signature = Signature.from({ - r: zeroPadValue(fields[7], 32), - s: zeroPadValue(fields[8], 32), - v: v3 - }); + let a2 = mod$1(number2, modulo); + let b2 = modulo; + let x2 = _0n$7, u2 = _1n$9; + while (a2 !== _0n$7) { + const q2 = b2 / a2; + const r2 = b2 % a2; + const m2 = x2 - u2 * q2; + b2 = a2, a2 = r2, x2 = u2, u2 = m2; } - return tx; + const gcd = b2; + if (gcd !== _1n$9) + throw new Error("invert: does not exist"); + return mod$1(x2, modulo); } -function _serializeLegacy(tx, sig) { - const fields = [ - formatNumber(tx.nonce, "nonce"), - formatNumber(tx.gasPrice || 0, "gasPrice"), - formatNumber(tx.gasLimit, "gasLimit"), - tx.to || "0x", - formatNumber(tx.value, "value"), - tx.data - ]; - let chainId = BN_0$4; - if (tx.chainId != BN_0$4) { - chainId = getBigInt(tx.chainId, "tx.chainId"); - assertArgument(!sig || sig.networkV == null || sig.legacyChainId === chainId, "tx.chainId/sig.v mismatch", "sig", sig); - } else if (tx.signature) { - const legacy = tx.signature.legacyChainId; - if (legacy != null) { - chainId = legacy; - } +function tonelliShanks$1(P2) { + const legendreC = (P2 - _1n$9) / _2n$5; + let Q2, S2, Z2; + for (Q2 = P2 - _1n$9, S2 = 0; Q2 % _2n$5 === _0n$7; Q2 /= _2n$5, S2++) + ; + for (Z2 = _2n$5; Z2 < P2 && pow$1(Z2, legendreC, P2) !== P2 - _1n$9; Z2++) + ; + if (S2 === 1) { + const p1div4 = (P2 + _1n$9) / _4n$1; + return function tonelliFast(Fp2, n2) { + const root2 = Fp2.pow(n2, p1div4); + if (!Fp2.eql(Fp2.sqr(root2), n2)) + throw new Error("Cannot find square root"); + return root2; + }; } - if (!sig) { - if (chainId !== BN_0$4) { - fields.push(toBeArray(chainId)); - fields.push("0x"); - fields.push("0x"); + const Q1div2 = (Q2 + _1n$9) / _2n$5; + return function tonelliSlow(Fp2, n2) { + if (Fp2.pow(n2, legendreC) === Fp2.neg(Fp2.ONE)) + throw new Error("Cannot find square root"); + let r2 = S2; + let g2 = Fp2.pow(Fp2.mul(Fp2.ONE, Z2), Q2); + let x2 = Fp2.pow(n2, Q1div2); + let b2 = Fp2.pow(n2, Q2); + while (!Fp2.eql(b2, Fp2.ONE)) { + if (Fp2.eql(b2, Fp2.ZERO)) + return Fp2.ZERO; + let m2 = 1; + for (let t2 = Fp2.sqr(b2); m2 < r2; m2++) { + if (Fp2.eql(t2, Fp2.ONE)) + break; + t2 = Fp2.sqr(t2); + } + const ge2 = Fp2.pow(g2, _1n$9 << BigInt(r2 - m2 - 1)); + g2 = Fp2.sqr(ge2); + x2 = Fp2.mul(x2, ge2); + b2 = Fp2.mul(b2, g2); + r2 = m2; } - return encodeRlp(fields); - } - let v3 = BigInt(27 + sig.yParity); - if (chainId !== BN_0$4) { - v3 = Signature.getChainIdV(chainId, sig.v); - } else if (BigInt(sig.v) !== v3) { - assertArgument(false, "tx.chainId/sig.v mismatch", "sig", sig); - } - fields.push(toBeArray(v3)); - fields.push(toBeArray(sig.r)); - fields.push(toBeArray(sig.s)); - return encodeRlp(fields); + return x2; + }; } -function _parseEipSignature(tx, fields) { - let yParity; - try { - yParity = handleNumber(fields[0], "yParity"); - if (yParity !== 0 && yParity !== 1) { - throw new Error("bad yParity"); - } - } catch (error) { - assertArgument(false, "invalid yParity", "yParity", fields[0]); +function FpSqrt$1(P2) { + if (P2 % _4n$1 === _3n$3) { + const p1div4 = (P2 + _1n$9) / _4n$1; + return function sqrt3mod4(Fp2, n2) { + const root2 = Fp2.pow(n2, p1div4); + if (!Fp2.eql(Fp2.sqr(root2), n2)) + throw new Error("Cannot find square root"); + return root2; + }; } - const r2 = zeroPadValue(fields[1], 32); - const s2 = zeroPadValue(fields[2], 32); - const signature2 = Signature.from({ r: r2, s: s2, yParity }); - tx.signature = signature2; + if (P2 % _8n$1 === _5n$1) { + const c1 = (P2 - _5n$1) / _8n$1; + return function sqrt5mod8(Fp2, n2) { + const n22 = Fp2.mul(n2, _2n$5); + const v3 = Fp2.pow(n22, c1); + const nv = Fp2.mul(n2, v3); + const i = Fp2.mul(Fp2.mul(nv, _2n$5), v3); + const root2 = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); + if (!Fp2.eql(Fp2.sqr(root2), n2)) + throw new Error("Cannot find square root"); + return root2; + }; + } + return tonelliShanks$1(P2); } -function _parseEip1559(data) { - const fields = decodeRlp(getBytes(data).slice(1)); - assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 12), "invalid field count for transaction type: 2", "data", hexlify(data)); - const tx = { - type: 2, - chainId: handleUint(fields[0], "chainId"), - nonce: handleNumber(fields[1], "nonce"), - maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"), - maxFeePerGas: handleUint(fields[3], "maxFeePerGas"), - gasPrice: null, - gasLimit: handleUint(fields[4], "gasLimit"), - to: handleAddress(fields[5]), - value: handleUint(fields[6], "value"), - data: hexlify(fields[7]), - accessList: handleAccessList(fields[8], "accessList") +const FIELD_FIELDS$1 = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" +]; +function validateField$1(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger" }; - if (fields.length === 9) { - return tx; - } - _parseEipSignature(tx, fields.slice(9)); - return tx; + const opts = FIELD_FIELDS$1.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + return validateObject$1(field, opts); } -function _serializeEip1559(tx, sig) { - const fields = [ - formatNumber(tx.chainId, "chainId"), - formatNumber(tx.nonce, "nonce"), - formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), - formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), - formatNumber(tx.gasLimit, "gasLimit"), - tx.to || "0x", - formatNumber(tx.value, "value"), - tx.data, - formatAccessList(tx.accessList || []) - ]; - if (sig) { - fields.push(formatNumber(sig.yParity, "yParity")); - fields.push(toBeArray(sig.r)); - fields.push(toBeArray(sig.s)); +function FpPow$1(f2, num, power) { + if (power < _0n$7) + throw new Error("Expected power > 0"); + if (power === _0n$7) + return f2.ONE; + if (power === _1n$9) + return num; + let p2 = f2.ONE; + let d2 = num; + while (power > _0n$7) { + if (power & _1n$9) + p2 = f2.mul(p2, d2); + d2 = f2.sqr(d2); + power >>= _1n$9; } - return concat$1(["0x02", encodeRlp(fields)]); + return p2; } -function _parseEip2930(data) { - const fields = decodeRlp(getBytes(data).slice(1)); - assertArgument(Array.isArray(fields) && (fields.length === 8 || fields.length === 11), "invalid field count for transaction type: 1", "data", hexlify(data)); - const tx = { - type: 1, - chainId: handleUint(fields[0], "chainId"), - nonce: handleNumber(fields[1], "nonce"), - gasPrice: handleUint(fields[2], "gasPrice"), - gasLimit: handleUint(fields[3], "gasLimit"), - to: handleAddress(fields[4]), - value: handleUint(fields[5], "value"), - data: hexlify(fields[6]), - accessList: handleAccessList(fields[7], "accessList") - }; - if (fields.length === 8) { - return tx; - } - _parseEipSignature(tx, fields.slice(8)); - return tx; +function FpInvertBatch$1(f2, nums) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f2.is0(num)) + return acc; + tmp[i] = acc; + return f2.mul(acc, num); + }, f2.ONE); + const inverted = f2.inv(lastMultiplied); + nums.reduceRight((acc, num, i) => { + if (f2.is0(num)) + return acc; + tmp[i] = f2.mul(acc, tmp[i]); + return f2.mul(acc, num); + }, inverted); + return tmp; } -function _serializeEip2930(tx, sig) { - const fields = [ - formatNumber(tx.chainId, "chainId"), - formatNumber(tx.nonce, "nonce"), - formatNumber(tx.gasPrice || 0, "gasPrice"), - formatNumber(tx.gasLimit, "gasLimit"), - tx.to || "0x", - formatNumber(tx.value, "value"), - tx.data, - formatAccessList(tx.accessList || []) - ]; - if (sig) { - fields.push(formatNumber(sig.yParity, "recoveryParam")); - fields.push(toBeArray(sig.r)); - fields.push(toBeArray(sig.s)); - } - return concat$1(["0x01", encodeRlp(fields)]); +function nLength$1(n2, nBitLength) { + const _nBitLength = nBitLength !== void 0 ? nBitLength : n2.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; } -function _parseEip4844(data) { - let fields = decodeRlp(getBytes(data).slice(1)); - let typeName = "3"; - let blobs = null; - if (fields.length === 4 && Array.isArray(fields[0])) { - typeName = "3 (network format)"; - const fBlobs = fields[1], fCommits = fields[2], fProofs = fields[3]; - assertArgument(Array.isArray(fBlobs), "invalid network format: blobs not an array", "fields[1]", fBlobs); - assertArgument(Array.isArray(fCommits), "invalid network format: commitments not an array", "fields[2]", fCommits); - assertArgument(Array.isArray(fProofs), "invalid network format: proofs not an array", "fields[3]", fProofs); - assertArgument(fBlobs.length === fCommits.length, "invalid network format: blobs/commitments length mismatch", "fields", fields); - assertArgument(fBlobs.length === fProofs.length, "invalid network format: blobs/proofs length mismatch", "fields", fields); - blobs = []; - for (let i = 0; i < fields[1].length; i++) { - blobs.push({ - data: fBlobs[i], - commitment: fCommits[i], - proof: fProofs[i] - }); +function Field$1(ORDER, bitLen2, isLE2 = false, redef = {}) { + if (ORDER <= _0n$7) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength$1(ORDER, bitLen2); + if (BYTES > 2048) + throw new Error("Field lengths over 2048 bytes are not supported"); + const sqrtP = FpSqrt$1(ORDER); + const f2 = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask$1(BITS), + ZERO: _0n$7, + ONE: _1n$9, + create: (num) => mod$1(num, ORDER), + isValid: (num) => { + if (typeof num !== "bigint") + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n$7 <= num && num < ORDER; + }, + is0: (num) => num === _0n$7, + isOdd: (num) => (num & _1n$9) === _1n$9, + neg: (num) => mod$1(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod$1(num * num, ORDER), + add: (lhs, rhs) => mod$1(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod$1(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod$1(lhs * rhs, ORDER), + pow: (num, power) => FpPow$1(f2, num, power), + div: (lhs, rhs) => mod$1(lhs * invert$1(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert$1(num, ORDER), + sqrt: redef.sqrt || ((n2) => sqrtP(f2, n2)), + invertBatch: (lst) => FpInvertBatch$1(f2, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a2, b2, c2) => c2 ? b2 : a2, + toBytes: (num) => isLE2 ? numberToBytesLE$1(num, BYTES) : numberToBytesBE$1(num, BYTES), + fromBytes: (bytes2) => { + if (bytes2.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`); + return isLE2 ? bytesToNumberLE$1(bytes2) : bytesToNumberBE$1(bytes2); } - fields = fields[0]; - } - assertArgument(Array.isArray(fields) && (fields.length === 11 || fields.length === 14), `invalid field count for transaction type: ${typeName}`, "data", hexlify(data)); - const tx = { - type: 3, - chainId: handleUint(fields[0], "chainId"), - nonce: handleNumber(fields[1], "nonce"), - maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"), - maxFeePerGas: handleUint(fields[3], "maxFeePerGas"), - gasPrice: null, - gasLimit: handleUint(fields[4], "gasLimit"), - to: handleAddress(fields[5]), - value: handleUint(fields[6], "value"), - data: hexlify(fields[7]), - accessList: handleAccessList(fields[8], "accessList"), - maxFeePerBlobGas: handleUint(fields[9], "maxFeePerBlobGas"), - blobVersionedHashes: fields[10] - }; - if (blobs) { - tx.blobs = blobs; - } - assertArgument(tx.to != null, `invalid address for transaction type: ${typeName}`, "data", data); - assertArgument(Array.isArray(tx.blobVersionedHashes), "invalid blobVersionedHashes: must be an array", "data", data); - for (let i = 0; i < tx.blobVersionedHashes.length; i++) { - assertArgument(isHexString(tx.blobVersionedHashes[i], 32), `invalid blobVersionedHash at index ${i}: must be length 32`, "data", data); - } - if (fields.length === 11) { - return tx; - } - _parseEipSignature(tx, fields.slice(11)); - return tx; + }); + return Object.freeze(f2); } -function _serializeEip4844(tx, sig, blobs) { - const fields = [ - formatNumber(tx.chainId, "chainId"), - formatNumber(tx.nonce, "nonce"), - formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), - formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), - formatNumber(tx.gasLimit, "gasLimit"), - tx.to || ZeroAddress, - formatNumber(tx.value, "value"), - tx.data, - formatAccessList(tx.accessList || []), - formatNumber(tx.maxFeePerBlobGas || 0, "maxFeePerBlobGas"), - formatHashes(tx.blobVersionedHashes || [], "blobVersionedHashes") - ]; - if (sig) { - fields.push(formatNumber(sig.yParity, "yParity")); - fields.push(toBeArray(sig.r)); - fields.push(toBeArray(sig.s)); - if (blobs) { - return concat$1([ - "0x03", - encodeRlp([ - fields, - blobs.map((b2) => b2.data), - blobs.map((b2) => b2.commitment), - blobs.map((b2) => b2.proof) - ]) - ]); +function getFieldBytesLength$1(fieldOrder) { + if (typeof fieldOrder !== "bigint") + throw new Error("field order must be bigint"); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +function getMinHashLength$1(fieldOrder) { + const length = getFieldBytesLength$1(fieldOrder); + return length + Math.ceil(length / 2); +} +function mapHashToField$1(key, fieldOrder, isLE2 = false) { + const len = key.length; + const fieldLen = getFieldBytesLength$1(fieldOrder); + const minLen = getMinHashLength$1(fieldOrder); + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE2 ? bytesToNumberBE$1(key) : bytesToNumberLE$1(key); + const reduced = mod$1(num, fieldOrder - _1n$9) + _1n$9; + return isLE2 ? numberToBytesLE$1(reduced, fieldLen) : numberToBytesBE$1(reduced, fieldLen); +} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n$6 = BigInt(0); +const _1n$8 = BigInt(1); +function wNAF$1(c2, bits) { + const constTimeNegate = (condition, item2) => { + const neg = item2.negate(); + return condition ? neg : item2; + }; + const opts = (W2) => { + const windows = Math.ceil(bits / W2) + 1; + const windowSize = 2 ** (W2 - 1); + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n2) { + let p2 = c2.ZERO; + let d2 = elm; + while (n2 > _0n$6) { + if (n2 & _1n$8) + p2 = p2.add(d2); + d2 = d2.double(); + n2 >>= _1n$8; + } + return p2; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W2) { + const { windows, windowSize } = opts(W2); + const points = []; + let p2 = elm; + let base = p2; + for (let window2 = 0; window2 < windows; window2++) { + base = p2; + points.push(base); + for (let i = 1; i < windowSize; i++) { + base = base.add(p2); + points.push(base); + } + p2 = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W2, precomputes, n2) { + const { windows, windowSize } = opts(W2); + let p2 = c2.ZERO; + let f2 = c2.BASE; + const mask2 = BigInt(2 ** W2 - 1); + const maxNumber = 2 ** W2; + const shiftBy = BigInt(W2); + for (let window2 = 0; window2 < windows; window2++) { + const offset2 = window2 * windowSize; + let wbits = Number(n2 & mask2); + n2 >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n2 += _1n$8; + } + const offset1 = offset2; + const offset22 = offset2 + Math.abs(wbits) - 1; + const cond1 = window2 % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f2 = f2.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p2 = p2.add(constTimeNegate(cond2, precomputes[offset22])); + } + } + return { p: p2, f: f2 }; + }, + wNAFCached(P2, precomputesMap, n2, transform) { + const W2 = P2._WINDOW_SIZE || 1; + let comp = precomputesMap.get(P2); + if (!comp) { + comp = this.precomputeWindow(P2, W2); + if (W2 !== 1) { + precomputesMap.set(P2, transform(comp)); + } + } + return this.wNAF(W2, comp, n2); } - } - return concat$1(["0x03", encodeRlp(fields)]); + }; } -const _Transaction = class _Transaction { - /** - * Creates a new Transaction with default values. - */ - constructor() { - __privateAdd(this, _Transaction_instances); - __privateAdd(this, _type); - __privateAdd(this, _to); - __privateAdd(this, _data4); - __privateAdd(this, _nonce); - __privateAdd(this, _gasLimit); - __privateAdd(this, _gasPrice); - __privateAdd(this, _maxPriorityFeePerGas); - __privateAdd(this, _maxFeePerGas); - __privateAdd(this, _value); - __privateAdd(this, _chainId2); - __privateAdd(this, _sig); - __privateAdd(this, _accessList); - __privateAdd(this, _maxFeePerBlobGas); - __privateAdd(this, _blobVersionedHashes); - __privateAdd(this, _kzg); - __privateAdd(this, _blobs); - __privateSet(this, _type, null); - __privateSet(this, _to, null); - __privateSet(this, _nonce, 0); - __privateSet(this, _gasLimit, BN_0$4); - __privateSet(this, _gasPrice, null); - __privateSet(this, _maxPriorityFeePerGas, null); - __privateSet(this, _maxFeePerGas, null); - __privateSet(this, _data4, "0x"); - __privateSet(this, _value, BN_0$4); - __privateSet(this, _chainId2, BN_0$4); - __privateSet(this, _sig, null); - __privateSet(this, _accessList, null); - __privateSet(this, _maxFeePerBlobGas, null); - __privateSet(this, _blobVersionedHashes, null); - __privateSet(this, _blobs, null); - __privateSet(this, _kzg, null); - } - /** - * The transaction type. - * - * If null, the type will be automatically inferred based on - * explicit properties. - */ - get type() { - return __privateGet(this, _type); - } - set type(value) { - switch (value) { - case null: - __privateSet(this, _type, null); - break; - case 0: - case "legacy": - __privateSet(this, _type, 0); - break; - case 1: - case "berlin": - case "eip-2930": - __privateSet(this, _type, 1); - break; - case 2: - case "london": - case "eip-1559": - __privateSet(this, _type, 2); - break; - case 3: - case "cancun": - case "eip-4844": - __privateSet(this, _type, 3); - break; - default: - assertArgument(false, "unsupported transaction type", "type", value); +function validateBasic$1(curve) { + validateField$1(curve.Fp); + validateObject$1(curve, { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field" + }, { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger" + }); + return Object.freeze({ + ...nLength$1(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER } + }); +} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +function validatePointOpts$1(curve) { + const opts = validateBasic$1(curve); + validateObject$1(opts, { + a: "field", + b: "field" + }, { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function" + }); + const { endo, Fp: Fp2, a: a2 } = opts; + if (endo) { + if (!Fp2.eql(a2, Fp2.ZERO)) { + throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); } - } - /** - * The name of the transaction type. - */ - get typeName() { - switch (this.type) { - case 0: - return "legacy"; - case 1: - return "eip-2930"; - case 2: - return "eip-1559"; - case 3: - return "eip-4844"; + if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { + throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); } - return null; } - /** - * The ``to`` address for the transaction or ``null`` if the - * transaction is an ``init`` transaction. - */ - get to() { - const value = __privateGet(this, _to); - if (value == null && this.type === 3) { - return ZeroAddress; + return Object.freeze({ ...opts }); +} +const { bytesToNumberBE: b2n$1, hexToBytes: h2b$1 } = ut$1; +const DER$1 = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m2 = "") { + super(m2); } - return value; - } - set to(value) { - __privateSet(this, _to, value == null ? null : getAddress$1(value)); - } - /** - * The transaction nonce. - */ - get nonce() { - return __privateGet(this, _nonce); + }, + _parseInt(data) { + const { Err: E2 } = DER$1; + if (data.length < 2 || data[0] !== 2) + throw new E2("Invalid signature integer tag"); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E2("Invalid signature integer: wrong length"); + if (res[0] & 128) + throw new E2("Invalid signature integer: negative"); + if (res[0] === 0 && !(res[1] & 128)) + throw new E2("Invalid signature integer: unnecessary leading zero"); + return { d: b2n$1(res), l: data.subarray(len + 2) }; + }, + toSig(hex2) { + const { Err: E2 } = DER$1; + const data = typeof hex2 === "string" ? h2b$1(hex2) : hex2; + abytes(data); + let l2 = data.length; + if (l2 < 2 || data[0] != 48) + throw new E2("Invalid signature tag"); + if (data[1] !== l2 - 2) + throw new E2("Invalid signature: incorrect length"); + const { d: r2, l: sBytes } = DER$1._parseInt(data.subarray(2)); + const { d: s2, l: rBytesLeft } = DER$1._parseInt(sBytes); + if (rBytesLeft.length) + throw new E2("Invalid signature: left bytes after parsing"); + return { r: r2, s: s2 }; + }, + hexFromSig(sig) { + const slice2 = (s3) => Number.parseInt(s3[0], 16) & 8 ? "00" + s3 : s3; + const h2 = (num) => { + const hex2 = num.toString(16); + return hex2.length & 1 ? `0${hex2}` : hex2; + }; + const s2 = slice2(h2(sig.s)); + const r2 = slice2(h2(sig.r)); + const shl = s2.length / 2; + const rhl = r2.length / 2; + const sl2 = h2(shl); + const rl2 = h2(rhl); + return `30${h2(rhl + shl + 4)}02${rl2}${r2}02${sl2}${s2}`; } - set nonce(value) { - __privateSet(this, _nonce, getNumber(value, "value")); +}; +const _0n$5 = BigInt(0), _1n$7 = BigInt(1); +BigInt(2); +const _3n$2 = BigInt(3); +BigInt(4); +function weierstrassPoints$1(opts) { + const CURVE = validatePointOpts$1(opts); + const { Fp: Fp2 } = CURVE; + const toBytes2 = CURVE.toBytes || ((_c2, point, _isCompressed) => { + const a2 = point.toAffine(); + return concatBytes$2(Uint8Array.from([4]), Fp2.toBytes(a2.x), Fp2.toBytes(a2.y)); + }); + const fromBytes = CURVE.fromBytes || ((bytes2) => { + const tail = bytes2.subarray(1); + const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x: x2, y: y2 }; + }); + function weierstrassEquation(x2) { + const { a: a2, b: b2 } = CURVE; + const x22 = Fp2.sqr(x2); + const x3 = Fp2.mul(x22, x2); + return Fp2.add(Fp2.add(x3, Fp2.mul(x2, a2)), b2); } - /** - * The gas limit. - */ - get gasLimit() { - return __privateGet(this, _gasLimit); + if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error("bad generator point: equation left != right"); + function isWithinCurveOrder(num) { + return typeof num === "bigint" && _0n$5 < num && num < CURVE.n; } - set gasLimit(value) { - __privateSet(this, _gasLimit, getBigInt(value)); + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error("Expected valid bigint: 0 < bigint < curve.n"); } - /** - * The gas price. - * - * On legacy networks this defines the fee that will be paid. On - * EIP-1559 networks, this should be ``null``. - */ - get gasPrice() { - const value = __privateGet(this, _gasPrice); - if (value == null && (this.type === 0 || this.type === 1)) { - return BN_0$4; + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: n2 } = CURVE; + if (lengths && typeof key !== "bigint") { + if (isBytes$1(key)) + key = bytesToHex$2(key); + if (typeof key !== "string" || !lengths.includes(key.length)) + throw new Error("Invalid key"); + key = key.padStart(nByteLength * 2, "0"); } - return value; + let num; + try { + num = typeof key === "bigint" ? key : bytesToNumberBE$1(ensureBytes$1("private key", key, nByteLength)); + } catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod$1(num, n2); + assertGE(num); + return num; } - set gasPrice(value) { - __privateSet(this, _gasPrice, value == null ? null : getBigInt(value, "gasPrice")); + const pointPrecomputes = /* @__PURE__ */ new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error("ProjectivePoint expected"); } - /** - * The maximum priority fee per unit of gas to pay. On legacy - * networks this should be ``null``. - */ - get maxPriorityFeePerGas() { - const value = __privateGet(this, _maxPriorityFeePerGas); - if (value == null) { - if (this.type === 2 || this.type === 3) { - return BN_0$4; - } - return null; + class Point { + constructor(px2, py, pz) { + this.px = px2; + this.py = py; + this.pz = pz; + if (px2 == null || !Fp2.isValid(px2)) + throw new Error("x required"); + if (py == null || !Fp2.isValid(py)) + throw new Error("y required"); + if (pz == null || !Fp2.isValid(pz)) + throw new Error("z required"); } - return value; - } - set maxPriorityFeePerGas(value) { - __privateSet(this, _maxPriorityFeePerGas, value == null ? null : getBigInt(value, "maxPriorityFeePerGas")); - } - /** - * The maximum total fee per unit of gas to pay. On legacy - * networks this should be ``null``. - */ - get maxFeePerGas() { - const value = __privateGet(this, _maxFeePerGas); - if (value == null) { - if (this.type === 2 || this.type === 3) { - return BN_0$4; - } - return null; + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p2) { + const { x: x2, y: y2 } = p2 || {}; + if (!p2 || !Fp2.isValid(x2) || !Fp2.isValid(y2)) + throw new Error("invalid affine point"); + if (p2 instanceof Point) + throw new Error("projective point not allowed"); + const is0 = (i) => Fp2.eql(i, Fp2.ZERO); + if (is0(x2) && is0(y2)) + return Point.ZERO; + return new Point(x2, y2, Fp2.ONE); } - return value; - } - set maxFeePerGas(value) { - __privateSet(this, _maxFeePerGas, value == null ? null : getBigInt(value, "maxFeePerGas")); - } - /** - * The transaction data. For ``init`` transactions this is the - * deployment code. - */ - get data() { - return __privateGet(this, _data4); - } - set data(value) { - __privateSet(this, _data4, hexlify(value)); - } - /** - * The amount of ether (in wei) to send in this transactions. - */ - get value() { - return __privateGet(this, _value); - } - set value(value) { - __privateSet(this, _value, getBigInt(value, "value")); - } - /** - * The chain ID this transaction is valid on. - */ - get chainId() { - return __privateGet(this, _chainId2); - } - set chainId(value) { - __privateSet(this, _chainId2, getBigInt(value)); - } - /** - * If signed, the signature for this transaction. - */ - get signature() { - return __privateGet(this, _sig) || null; - } - set signature(value) { - __privateSet(this, _sig, value == null ? null : Signature.from(value)); - } - /** - * The access list. - * - * An access list permits discounted (but pre-paid) access to - * bytecode and state variable access within contract execution. - */ - get accessList() { - const value = __privateGet(this, _accessList) || null; - if (value == null) { - if (this.type === 1 || this.type === 2 || this.type === 3) { - return []; - } - return null; + get x() { + return this.toAffine().x; } - return value; - } - set accessList(value) { - __privateSet(this, _accessList, value == null ? null : accessListify(value)); - } - /** - * The max fee per blob gas for Cancun transactions. - */ - get maxFeePerBlobGas() { - const value = __privateGet(this, _maxFeePerBlobGas); - if (value == null && this.type === 3) { - return BN_0$4; + get y() { + return this.toAffine().y; } - return value; - } - set maxFeePerBlobGas(value) { - __privateSet(this, _maxFeePerBlobGas, value == null ? null : getBigInt(value, "maxFeePerBlobGas")); - } - /** - * The BLOb versioned hashes for Cancun transactions. - */ - get blobVersionedHashes() { - let value = __privateGet(this, _blobVersionedHashes); - if (value == null && this.type === 3) { - return []; + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp2.invertBatch(points.map((p2) => p2.pz)); + return points.map((p2, i) => p2.toAffine(toInv[i])).map(Point.fromAffine); } - return value; - } - set blobVersionedHashes(value) { - if (value != null) { - assertArgument(Array.isArray(value), "blobVersionedHashes must be an Array", "value", value); - value = value.slice(); - for (let i = 0; i < value.length; i++) { - assertArgument(isHexString(value[i], 32), "invalid blobVersionedHash", `value[${i}]`, value[i]); - } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex2) { + const P2 = Point.fromAffine(fromBytes(ensureBytes$1("pointHex", hex2))); + P2.assertValidity(); + return P2; } - __privateSet(this, _blobVersionedHashes, value); - } - /** - * The BLObs for the Transaction, if any. - * - * If ``blobs`` is non-``null``, then the [[seriailized]] - * will return the network formatted sidecar, otherwise it - * will return the standard [[link-eip-2718]] payload. The - * [[unsignedSerialized]] is unaffected regardless. - * - * When setting ``blobs``, either fully valid [[Blob]] objects - * may be specified (i.e. correctly padded, with correct - * committments and proofs) or a raw [[BytesLike]] may - * be provided. - * - * If raw [[BytesLike]] are provided, the [[kzg]] property **must** - * be already set. The blob will be correctly padded and the - * [[KzgLibrary]] will be used to compute the committment and - * proof for the blob. - * - * A BLOb is a sequence of field elements, each of which must - * be within the BLS field modulo, so some additional processing - * may be required to encode arbitrary data to ensure each 32 byte - * field is within the valid range. - * - * Setting this automatically populates [[blobVersionedHashes]], - * overwriting any existing values. Setting this to ``null`` - * does **not** remove the [[blobVersionedHashes]], leaving them - * present. - */ - get blobs() { - if (__privateGet(this, _blobs) == null) { - return null; + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); } - return __privateGet(this, _blobs).map((b2) => Object.assign({}, b2)); - } - set blobs(_blobs2) { - if (_blobs2 == null) { - __privateSet(this, _blobs, null); - return; + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); } - const blobs = []; - const versionedHashes = []; - for (let i = 0; i < _blobs2.length; i++) { - const blob = _blobs2[i]; - if (isBytesLike(blob)) { - assert(__privateGet(this, _kzg), "adding a raw blob requires a KZG library", "UNSUPPORTED_OPERATION", { - operation: "set blobs()" - }); - let data = getBytes(blob); - assertArgument(data.length <= BLOB_SIZE, "blob is too large", `blobs[${i}]`, blob); - if (data.length !== BLOB_SIZE) { - const padded = new Uint8Array(BLOB_SIZE); - padded.set(data); - data = padded; - } - const commit = __privateGet(this, _kzg).blobToKzgCommitment(data); - const proof = hexlify(__privateGet(this, _kzg).computeBlobKzgProof(data, commit)); - blobs.push({ - data: hexlify(data), - commitment: hexlify(commit), - proof - }); - versionedHashes.push(getVersionedHash(1, commit)); - } else { - const commit = hexlify(blob.commitment); - blobs.push({ - data: hexlify(blob.data), - commitment: commit, - proof: hexlify(blob.proof) - }); - versionedHashes.push(getVersionedHash(1, commit)); + // A point on curve is valid if it conforms to equation. + assertValidity() { + if (this.is0()) { + if (CURVE.allowInfinityPoint && !Fp2.is0(this.py)) + return; + throw new Error("bad point: ZERO"); } + const { x: x2, y: y2 } = this.toAffine(); + if (!Fp2.isValid(x2) || !Fp2.isValid(y2)) + throw new Error("bad point: x or y not FE"); + const left = Fp2.sqr(y2); + const right = weierstrassEquation(x2); + if (!Fp2.eql(left, right)) + throw new Error("bad point: equation left != right"); + if (!this.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); } - __privateSet(this, _blobs, blobs); - __privateSet(this, _blobVersionedHashes, versionedHashes); - } - get kzg() { - return __privateGet(this, _kzg); - } - set kzg(kzg) { - __privateSet(this, _kzg, kzg); - } - /** - * The transaction hash, if signed. Otherwise, ``null``. - */ - get hash() { - if (this.signature == null) { - return null; + hasEvenY() { + const { y: y2 } = this.toAffine(); + if (Fp2.isOdd) + return !Fp2.isOdd(y2); + throw new Error("Field doesn't support isOdd"); } - return keccak256$1(__privateMethod(this, _Transaction_instances, getSerialized_fn).call(this, true, false)); - } - /** - * The pre-image hash of this transaction. - * - * This is the digest that a [[Signer]] must sign to authorize - * this transaction. - */ - get unsignedHash() { - return keccak256$1(this.unsignedSerialized); - } - /** - * The sending address, if signed. Otherwise, ``null``. - */ - get from() { - if (this.signature == null) { - return null; + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U12 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); + const U22 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); + return U12 && U22; } - return recoverAddress$1(this.unsignedHash, this.signature); - } - /** - * The public key of the sender, if signed. Otherwise, ``null``. - */ - get fromPublicKey() { - if (this.signature == null) { - return null; + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp2.neg(this.py), this.pz); } - return SigningKey.recoverPublicKey(this.unsignedHash, this.signature); - } - /** - * Returns true if signed. - * - * This provides a Type Guard that properties requiring a signed - * transaction are non-null. - */ - isSigned() { - return this.signature != null; - } - /** - * The serialized transaction. - * - * This throws if the transaction is unsigned. For the pre-image, - * use [[unsignedSerialized]]. - */ - get serialized() { - return __privateMethod(this, _Transaction_instances, getSerialized_fn).call(this, true, true); - } - /** - * The transaction pre-image. - * - * The hash of this is the digest which needs to be signed to - * authorize this transaction. - */ - get unsignedSerialized() { - return __privateMethod(this, _Transaction_instances, getSerialized_fn).call(this, false, false); - } - /** - * Return the most "likely" type; currently the highest - * supported transaction type. - */ - inferType() { - const types2 = this.inferTypes(); - if (types2.indexOf(2) >= 0) { - return 2; + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a: a2, b: b2 } = CURVE; + const b3 = Fp2.mul(b2, _3n$2); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + let t0 = Fp2.mul(X1, X1); + let t1 = Fp2.mul(Y1, Y1); + let t2 = Fp2.mul(Z1, Z1); + let t3 = Fp2.mul(X1, Y1); + t3 = Fp2.add(t3, t3); + Z3 = Fp2.mul(X1, Z1); + Z3 = Fp2.add(Z3, Z3); + X3 = Fp2.mul(a2, Z3); + Y3 = Fp2.mul(b3, t2); + Y3 = Fp2.add(X3, Y3); + X3 = Fp2.sub(t1, Y3); + Y3 = Fp2.add(t1, Y3); + Y3 = Fp2.mul(X3, Y3); + X3 = Fp2.mul(t3, X3); + Z3 = Fp2.mul(b3, Z3); + t2 = Fp2.mul(a2, t2); + t3 = Fp2.sub(t0, t2); + t3 = Fp2.mul(a2, t3); + t3 = Fp2.add(t3, Z3); + Z3 = Fp2.add(t0, t0); + t0 = Fp2.add(Z3, t0); + t0 = Fp2.add(t0, t2); + t0 = Fp2.mul(t0, t3); + Y3 = Fp2.add(Y3, t0); + t2 = Fp2.mul(Y1, Z1); + t2 = Fp2.add(t2, t2); + t0 = Fp2.mul(t2, t3); + X3 = Fp2.sub(X3, t0); + Z3 = Fp2.mul(t2, t1); + Z3 = Fp2.add(Z3, Z3); + Z3 = Fp2.add(Z3, Z3); + return new Point(X3, Y3, Z3); } - return types2.pop(); - } - /** - * Validates the explicit properties and returns a list of compatible - * transaction types. - */ - inferTypes() { - const hasGasPrice = this.gasPrice != null; - const hasFee = this.maxFeePerGas != null || this.maxPriorityFeePerGas != null; - const hasAccessList = this.accessList != null; - const hasBlob = __privateGet(this, _maxFeePerBlobGas) != null || __privateGet(this, _blobVersionedHashes); - if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) { - assert(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { value: this }); + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + const a2 = CURVE.a; + const b3 = Fp2.mul(CURVE.b, _3n$2); + let t0 = Fp2.mul(X1, X2); + let t1 = Fp2.mul(Y1, Y2); + let t2 = Fp2.mul(Z1, Z2); + let t3 = Fp2.add(X1, Y1); + let t4 = Fp2.add(X2, Y2); + t3 = Fp2.mul(t3, t4); + t4 = Fp2.add(t0, t1); + t3 = Fp2.sub(t3, t4); + t4 = Fp2.add(X1, Z1); + let t5 = Fp2.add(X2, Z2); + t4 = Fp2.mul(t4, t5); + t5 = Fp2.add(t0, t2); + t4 = Fp2.sub(t4, t5); + t5 = Fp2.add(Y1, Z1); + X3 = Fp2.add(Y2, Z2); + t5 = Fp2.mul(t5, X3); + X3 = Fp2.add(t1, t2); + t5 = Fp2.sub(t5, X3); + Z3 = Fp2.mul(a2, t4); + X3 = Fp2.mul(b3, t2); + Z3 = Fp2.add(X3, Z3); + X3 = Fp2.sub(t1, Z3); + Z3 = Fp2.add(t1, Z3); + Y3 = Fp2.mul(X3, Z3); + t1 = Fp2.add(t0, t0); + t1 = Fp2.add(t1, t0); + t2 = Fp2.mul(a2, t2); + t4 = Fp2.mul(b3, t4); + t1 = Fp2.add(t1, t2); + t2 = Fp2.sub(t0, t2); + t2 = Fp2.mul(a2, t2); + t4 = Fp2.add(t4, t2); + t0 = Fp2.mul(t1, t4); + Y3 = Fp2.add(Y3, t0); + t0 = Fp2.mul(t5, t4); + X3 = Fp2.mul(t3, X3); + X3 = Fp2.sub(X3, t0); + t0 = Fp2.mul(t3, t1); + Z3 = Fp2.mul(t5, Z3); + Z3 = Fp2.add(Z3, t0); + return new Point(X3, Y3, Z3); } - assert(!hasFee || this.type !== 0 && this.type !== 1, "transaction type cannot have maxFeePerGas or maxPriorityFeePerGas", "BAD_DATA", { value: this }); - assert(this.type !== 0 || !hasAccessList, "legacy transaction cannot have accessList", "BAD_DATA", { value: this }); - const types2 = []; - if (this.type != null) { - types2.push(this.type); - } else { - if (hasFee) { - types2.push(2); - } else if (hasGasPrice) { - types2.push(1); - if (!hasAccessList) { - types2.push(0); - } - } else if (hasAccessList) { - types2.push(1); - types2.push(2); - } else if (hasBlob && this.to) { - types2.push(3); - } else { - types2.push(0); - types2.push(1); - types2.push(2); - types2.push(3); - } + subtract(other) { + return this.add(other.negate()); } - types2.sort(); - return types2; - } - /** - * Returns true if this transaction is a legacy transaction (i.e. - * ``type === 0``). - * - * This provides a Type Guard that the related properties are - * non-null. - */ - isLegacy() { - return this.type === 0; - } - /** - * Returns true if this transaction is berlin hardform transaction (i.e. - * ``type === 1``). - * - * This provides a Type Guard that the related properties are - * non-null. - */ - isBerlin() { - return this.type === 1; - } - /** - * Returns true if this transaction is london hardform transaction (i.e. - * ``type === 2``). - * - * This provides a Type Guard that the related properties are - * non-null. - */ - isLondon() { - return this.type === 2; - } - /** - * Returns true if this transaction is an [[link-eip-4844]] BLOB - * transaction. - * - * This provides a Type Guard that the related properties are - * non-null. - */ - isCancun() { - return this.type === 3; - } - /** - * Create a copy of this transaciton. - */ - clone() { - return _Transaction.from(this); - } - /** - * Return a JSON-friendly object. - */ - toJSON() { - const s2 = (v3) => { - if (v3 == null) { - return null; - } - return v3.toString(); - }; - return { - type: this.type, - to: this.to, - // from: this.from, - data: this.data, - nonce: this.nonce, - gasLimit: s2(this.gasLimit), - gasPrice: s2(this.gasPrice), - maxPriorityFeePerGas: s2(this.maxPriorityFeePerGas), - maxFeePerGas: s2(this.maxFeePerGas), - value: s2(this.value), - chainId: s2(this.chainId), - sig: this.signature ? this.signature.toJSON() : null, - accessList: this.accessList - }; - } - /** - * Create a **Transaction** from a serialized transaction or a - * Transaction-like object. - */ - static from(tx) { - if (tx == null) { - return new _Transaction(); + is0() { + return this.equals(Point.ZERO); } - if (typeof tx === "string") { - const payload = getBytes(tx); - if (payload[0] >= 127) { - return _Transaction.from(_parseLegacy(payload)); + wNAF(n2) { + return wnaf.wNAFCached(this, pointPrecomputes, n2, (comp) => { + const toInv = Fp2.invertBatch(comp.map((p2) => p2.pz)); + return comp.map((p2, i) => p2.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n2) { + const I2 = Point.ZERO; + if (n2 === _0n$5) + return I2; + assertGE(n2); + if (n2 === _1n$7) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n2); + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n2); + let k1p = I2; + let k2p = I2; + let d2 = this; + while (k1 > _0n$5 || k2 > _0n$5) { + if (k1 & _1n$7) + k1p = k1p.add(d2); + if (k2 & _1n$7) + k2p = k2p.add(d2); + d2 = d2.double(); + k1 >>= _1n$7; + k2 >>= _1n$7; } - switch (payload[0]) { - case 1: - return _Transaction.from(_parseEip2930(payload)); - case 2: - return _Transaction.from(_parseEip1559(payload)); - case 3: - return _Transaction.from(_parseEip4844(payload)); + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n2 = scalar; + let point, fake; + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n2); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p: p2, f: f2 } = this.wNAF(n2); + point = p2; + fake = f2; } - assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: "from" }); + return Point.normalizeZ([point, fake])[0]; } - const result = new _Transaction(); - if (tx.type != null) { - result.type = tx.type; + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q2, a2, b2) { + const G2 = Point.BASE; + const mul = (P2, a3) => a3 === _0n$5 || a3 === _1n$7 || !P2.equals(G2) ? P2.multiplyUnsafe(a3) : P2.multiply(a3); + const sum = mul(this, a2).add(mul(Q2, b2)); + return sum.is0() ? void 0 : sum; } - if (tx.to != null) { - result.to = tx.to; + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x2, py: y2, pz: z2 } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? Fp2.ONE : Fp2.inv(z2); + const ax = Fp2.mul(x2, iz); + const ay = Fp2.mul(y2, iz); + const zz = Fp2.mul(z2, iz); + if (is0) + return { x: Fp2.ZERO, y: Fp2.ZERO }; + if (!Fp2.eql(zz, Fp2.ONE)) + throw new Error("invZ was invalid"); + return { x: ax, y: ay }; } - if (tx.nonce != null) { - result.nonce = tx.nonce; + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n$7) + return true; + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error("isTorsionFree() has not been declared for the elliptic curve"); } - if (tx.gasLimit != null) { - result.gasLimit = tx.gasLimit; + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n$7) + return this; + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); } - if (tx.gasPrice != null) { - result.gasPrice = tx.gasPrice; + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes2(Point, this, isCompressed); } - if (tx.maxPriorityFeePerGas != null) { - result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas; + toHex(isCompressed = true) { + return bytesToHex$2(this.toRawBytes(isCompressed)); } - if (tx.maxFeePerGas != null) { - result.maxFeePerGas = tx.maxFeePerGas; + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE); + Point.ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF$1(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder + }; +} +function validateOpts$1(curve) { + const opts = validateBasic$1(curve); + validateObject$1(opts, { + hash: "hash", + hmac: "function", + randomBytes: "function" + }, { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean" + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass$1(curveDef) { + const CURVE = validateOpts$1(curveDef); + const { Fp: Fp2, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp2.BYTES + 1; + const uncompressedLen = 2 * Fp2.BYTES + 1; + function isValidFieldElement(num) { + return _0n$5 < num && num < Fp2.ORDER; + } + function modN(a2) { + return mod$1(a2, CURVE_ORDER); + } + function invN(a2) { + return invert$1(a2, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints$1({ + ...CURVE, + toBytes(_c2, point, isCompressed) { + const a2 = point.toAffine(); + const x2 = Fp2.toBytes(a2.x); + const cat = concatBytes$2; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x2); + } else { + return cat(Uint8Array.from([4]), x2, Fp2.toBytes(a2.y)); + } + }, + fromBytes(bytes2) { + const len = bytes2.length; + const head = bytes2[0]; + const tail = bytes2.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x2 = bytesToNumberBE$1(tail); + if (!isValidFieldElement(x2)) + throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x2); + let y3; + try { + y3 = Fp2.sqrt(y2); + } catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; + throw new Error("Point is not on curve" + suffix); + } + const isYOdd = (y3 & _1n$7) === _1n$7; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y3 = Fp2.neg(y3); + return { x: x2, y: y3 }; + } else if (len === uncompressedLen && head === 4) { + const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x: x2, y: y2 }; + } else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } } - if (tx.maxFeePerBlobGas != null) { - result.maxFeePerBlobGas = tx.maxFeePerBlobGas; + }); + const numToNByteStr = (num) => bytesToHex$2(numberToBytesBE$1(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number2) { + const HALF = CURVE_ORDER >> _1n$7; + return number2 > HALF; + } + function normalizeS(s2) { + return isBiggerThanHalfOrder(s2) ? modN(-s2) : s2; + } + const slcNum = (b2, from, to) => bytesToNumberBE$1(b2.slice(from, to)); + class Signature2 { + constructor(r2, s2, recovery) { + this.r = r2; + this.s = s2; + this.recovery = recovery; + this.assertValidity(); } - if (tx.data != null) { - result.data = tx.data; + // pair (bytes of r, bytes of s) + static fromCompact(hex2) { + const l2 = CURVE.nByteLength; + hex2 = ensureBytes$1("compactSignature", hex2, l2 * 2); + return new Signature2(slcNum(hex2, 0, l2), slcNum(hex2, l2, 2 * l2)); } - if (tx.value != null) { - result.value = tx.value; + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex2) { + const { r: r2, s: s2 } = DER$1.toSig(ensureBytes$1("DER", hex2)); + return new Signature2(r2, s2); } - if (tx.chainId != null) { - result.chainId = tx.chainId; + assertValidity() { + if (!isWithinCurveOrder(this.r)) + throw new Error("r must be 0 < r < CURVE.n"); + if (!isWithinCurveOrder(this.s)) + throw new Error("s must be 0 < s < CURVE.n"); } - if (tx.signature != null) { - result.signature = Signature.from(tx.signature); + addRecoveryBit(recovery) { + return new Signature2(this.r, this.s, recovery); } - if (tx.accessList != null) { - result.accessList = tx.accessList; + recoverPublicKey(msgHash) { + const { r: r2, s: s2, recovery: rec } = this; + const h2 = bits2int_modN(ensureBytes$1("msgHash", msgHash)); + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r2 + CURVE.n : r2; + if (radj >= Fp2.ORDER) + throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R2 = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); + const u1 = modN(-h2 * ir); + const u2 = modN(s2 * ir); + const Q2 = Point.BASE.multiplyAndAddUnsafe(R2, u1, u2); + if (!Q2) + throw new Error("point at infinify"); + Q2.assertValidity(); + return Q2; } - if (tx.blobVersionedHashes != null) { - result.blobVersionedHashes = tx.blobVersionedHashes; + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); } - if (tx.kzg != null) { - result.kzg = tx.kzg; + normalizeS() { + return this.hasHighS() ? new Signature2(this.r, modN(-this.s), this.recovery) : this; } - if (tx.blobs != null) { - result.blobs = tx.blobs; + // DER-encoded + toDERRawBytes() { + return hexToBytes$1(this.toDERHex()); } - if (tx.hash != null) { - assertArgument(result.isSigned(), "unsigned transaction cannot define '.hash'", "tx", tx); - assertArgument(result.hash === tx.hash, "hash mismatch", "tx", tx); + toDERHex() { + return DER$1.hexFromSig({ r: this.r, s: this.s }); } - if (tx.from != null) { - assertArgument(result.isSigned(), "unsigned transaction cannot define '.from'", "tx", tx); - assertArgument(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx); + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes$1(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); } - return result; - } -}; -_type = new WeakMap(); -_to = new WeakMap(); -_data4 = new WeakMap(); -_nonce = new WeakMap(); -_gasLimit = new WeakMap(); -_gasPrice = new WeakMap(); -_maxPriorityFeePerGas = new WeakMap(); -_maxFeePerGas = new WeakMap(); -_value = new WeakMap(); -_chainId2 = new WeakMap(); -_sig = new WeakMap(); -_accessList = new WeakMap(); -_maxFeePerBlobGas = new WeakMap(); -_blobVersionedHashes = new WeakMap(); -_kzg = new WeakMap(); -_blobs = new WeakMap(); -_Transaction_instances = new WeakSet(); -getSerialized_fn = function(signed2, sidecar) { - assert(!signed2 || this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { operation: ".serialized" }); - const sig = signed2 ? this.signature : null; - switch (this.inferType()) { - case 0: - return _serializeLegacy(this, sig); - case 1: - return _serializeEip2930(this, sig); - case 2: - return _serializeEip1559(this, sig); - case 3: - return _serializeEip4844(this, sig, sidecar ? this.blobs : null); - } - assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: ".serialized" }); -}; -let Transaction = _Transaction; -function hashMessage$1(message) { - if (typeof message === "string") { - message = toUtf8Bytes(message); } - return keccak256$1(concat$1([ - toUtf8Bytes(MessagePrefix), - toUtf8Bytes(String(message.length)), - message - ])); -} -function verifyMessage$1(message, sig) { - const digest = hashMessage$1(message); - return recoverAddress$1(digest, sig); -} -const regexBytes = new RegExp("^bytes([0-9]+)$"); -const regexNumber = new RegExp("^(u?int)([0-9]*)$"); -const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$"); -function _pack(type, value, isArray2) { - switch (type) { - case "address": - if (isArray2) { - return getBytes(zeroPadValue(value, 32)); - } - return getBytes(getAddress$1(value)); - case "string": - return toUtf8Bytes(value); - case "bytes": - return getBytes(value); - case "bool": - value = !!value ? "0x01" : "0x00"; - if (isArray2) { - return getBytes(zeroPadValue(value, 32)); + const utils2 = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; } - return getBytes(value); - } - let match = type.match(regexNumber); - if (match) { - let signed2 = match[1] === "int"; - let size2 = parseInt(match[2] || "256"); - assertArgument((!match[2] || match[2] === String(size2)) && size2 % 8 === 0 && size2 !== 0 && size2 <= 256, "invalid number type", "type", type); - if (isArray2) { - size2 = 256; - } - if (signed2) { - value = toTwos(value, size2); + }, + normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength$1(CURVE.n); + return mapHashToField$1(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; } - return getBytes(zeroPadValue(toBeArray(value), size2 / 8)); + }; + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); } - match = type.match(regexBytes); - if (match) { - const size2 = parseInt(match[1]); - assertArgument(String(size2) === match[1] && size2 !== 0 && size2 <= 32, "invalid bytes type", "type", type); - assertArgument(dataLength(value) === size2, `invalid value for ${type}`, "value", value); - if (isArray2) { - return getBytes(zeroPadBytes(value, 32)); - } - return value; + function isProbPub(item2) { + const arr = isBytes$1(item2); + const str = typeof item2 === "string"; + const len = (arr || str) && item2.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item2 instanceof Point) + return true; + return false; } - match = type.match(regexArray); - if (match && Array.isArray(value)) { - const baseType = match[1]; - const count2 = parseInt(match[2] || String(value.length)); - assertArgument(count2 === value.length, `invalid array length for ${type}`, "value", value); - const result = []; - value.forEach(function(value2) { - result.push(_pack(baseType, value2, true)); - }); - return getBytes(concat$1(result)); + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) + throw new Error("second arg must be public key"); + const b2 = Point.fromHex(publicB); + return b2.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); } - assertArgument(false, "invalid type", "type", type); -} -function solidityPacked(types2, values) { - assertArgument(types2.length === values.length, "wrong number of values; expected ${ types.length }", "values", values); - const tight = []; - types2.forEach(function(type, index2) { - tight.push(_pack(type, values[index2])); - }); - return hexlify(concat$1(tight)); -} -function solidityPackedKeccak256(types2, values) { - return keccak256$1(solidityPacked(types2, values)); -} -function solidityPackedSha256(types2, values) { - return sha256$3(solidityPacked(types2, values)); -} -const padding = new Uint8Array(32); -padding.fill(0); -const BN__1 = BigInt(-1); -const BN_0$3 = BigInt(0); -const BN_1$1 = BigInt(1); -const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -function hexPadRight(value) { - const bytes2 = getBytes(value); - const padOffset = bytes2.length % 32; - if (padOffset) { - return concat$1([bytes2, padding.slice(padOffset)]); - } - return hexlify(bytes2); -} -const hexTrue = toBeHex(BN_1$1, 32); -const hexFalse = toBeHex(BN_0$3, 32); -const domainFieldTypes = { - name: "string", - version: "string", - chainId: "uint256", - verifyingContract: "address", - salt: "bytes32" -}; -const domainFieldNames = [ - "name", - "version", - "chainId", - "verifyingContract", - "salt" -]; -function checkString(key) { - return function(value) { - assertArgument(typeof value === "string", `invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); - return value; + const bits2int = CURVE.bits2int || function(bytes2) { + const num = bytesToNumberBE$1(bytes2); + const delta = bytes2.length * 8 - CURVE.nBitLength; + return delta > 0 ? num >> BigInt(delta) : num; }; -} -const domainChecks = { - name: checkString("name"), - version: checkString("version"), - chainId: function(_value2) { - const value = getBigInt(_value2, "domain.chainId"); - assertArgument(value >= 0, "invalid chain ID", "domain.chainId", _value2); - if (Number.isSafeInteger(value)) { - return Number(value); - } - return toQuantity(value); - }, - verifyingContract: function(value) { - try { - return getAddress$1(value).toLowerCase(); - } catch (error) { - } - assertArgument(false, `invalid domain value "verifyingContract"`, "domain.verifyingContract", value); - }, - salt: function(value) { - const bytes2 = getBytes(value, "domain.salt"); - assertArgument(bytes2.length === 32, `invalid domain value "salt"`, "domain.salt", value); - return hexlify(bytes2); + const bits2int_modN = CURVE.bits2int_modN || function(bytes2) { + return modN(bits2int(bytes2)); + }; + const ORDER_MASK = bitMask$1(CURVE.nBitLength); + function int2octets(num) { + if (typeof num !== "bigint") + throw new Error("bigint expected"); + if (!(_0n$5 <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + return numberToBytesBE$1(num, CURVE.nByteLength); } -}; -function getBaseEncoder(type) { - { - const match = type.match(/^(u?)int(\d+)$/); - if (match) { - const signed2 = match[1] === ""; - const width = parseInt(match[2]); - assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && match[2] === String(width), "invalid numeric width", "type", type); - const boundsUpper = mask(BN_MAX_UINT256, signed2 ? width - 1 : width); - const boundsLower = signed2 ? (boundsUpper + BN_1$1) * BN__1 : BN_0$3; - return function(_value2) { - const value = getBigInt(_value2, "value"); - assertArgument(value >= boundsLower && value <= boundsUpper, `value out-of-bounds for ${type}`, "value", value); - return toBeHex(signed2 ? toTwos(value, 256) : value, 32); - }; + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (["recovered", "canonical"].some((k2) => k2 in opts)) + throw new Error("sign() legacy options not supported"); + const { hash: hash2, randomBytes: randomBytes2 } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) + lowS = true; + msgHash = ensureBytes$1("msgHash", msgHash); + if (prehash) + msgHash = ensureBytes$1("prehashed msgHash", hash2(msgHash)); + const h1int = bits2int_modN(msgHash); + const d2 = normPrivateKeyToScalar(privateKey); + const seedArgs = [int2octets(d2), int2octets(h1int)]; + if (ent != null && ent !== false) { + const e2 = ent === true ? randomBytes2(Fp2.BYTES) : ent; + seedArgs.push(ensureBytes$1("extraEntropy", e2)); } - } - { - const match = type.match(/^bytes(\d+)$/); - if (match) { - const width = parseInt(match[1]); - assertArgument(width !== 0 && width <= 32 && match[1] === String(width), "invalid bytes width", "type", type); - return function(value) { - const bytes2 = getBytes(value); - assertArgument(bytes2.length === width, `invalid length for ${type}`, "value", value); - return hexPadRight(value); - }; + const seed = concatBytes$2(...seedArgs); + const m2 = h1int; + function k2sig(kBytes) { + const k2 = bits2int(kBytes); + if (!isWithinCurveOrder(k2)) + return; + const ik2 = invN(k2); + const q2 = Point.BASE.multiply(k2).toAffine(); + const r2 = modN(q2.x); + if (r2 === _0n$5) + return; + const s2 = modN(ik2 * modN(m2 + r2 * d2)); + if (s2 === _0n$5) + return; + let recovery = (q2.x === r2 ? 0 : 2) | Number(q2.y & _1n$7); + let normS = s2; + if (lowS && isBiggerThanHalfOrder(s2)) { + normS = normalizeS(s2); + recovery ^= 1; + } + return new Signature2(r2, normS, recovery); } + return { seed, k2sig }; } - switch (type) { - case "address": - return function(value) { - return zeroPadValue(getAddress$1(value), 32); - }; - case "bool": - return function(value) { - return !value ? hexFalse : hexTrue; - }; - case "bytes": - return function(value) { - return keccak256$1(value); - }; - case "string": - return function(value) { - return id$1(value); - }; - } - return null; -} -function encodeType$1(name2, fields) { - return `${name2}(${fields.map(({ name: name3, type }) => type + " " + name3).join(",")})`; -} -function splitArray(type) { - const match = type.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/); - if (match) { - return { - base: match[1], - index: match[2] + match[4], - array: { - base: match[1], - prefix: match[1] + match[2], - count: match[5] ? parseInt(match[5]) : -1 - } - }; + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const C2 = CURVE; + const drbg = createHmacDrbg$1(C2.hash.outputLen, C2.nByteLength, C2.hmac); + return drbg(seed, k2sig); } - return { base: type }; -} -const _TypedDataEncoder = class _TypedDataEncoder { - /** - * Create a new **TypedDataEncoder** for %%types%%. - * - * This performs all necessary checking that types are valid and - * do not violate the [[link-eip-712]] structural constraints as - * well as computes the [[primaryType]]. - */ - constructor(_types2) { - __privateAdd(this, _TypedDataEncoder_instances); - /** - * The primary type for the structured [[types]]. - * - * This is derived automatically from the [[types]], since no - * recursion is possible, once the DAG for the types is consturcted - * internally, the primary type must be the only remaining type with - * no parent nodes. - */ - __publicField(this, "primaryType"); - __privateAdd(this, _types); - __privateAdd(this, _fullTypes); - __privateAdd(this, _encoderCache); - __privateSet(this, _fullTypes, /* @__PURE__ */ new Map()); - __privateSet(this, _encoderCache, /* @__PURE__ */ new Map()); - const links = /* @__PURE__ */ new Map(); - const parents = /* @__PURE__ */ new Map(); - const subtypes = /* @__PURE__ */ new Map(); - const types2 = {}; - Object.keys(_types2).forEach((type) => { - types2[type] = _types2[type].map(({ name: name2, type: type2 }) => { - let { base, index: index2 } = splitArray(type2); - if (base === "int" && !_types2["int"]) { - base = "int256"; - } - if (base === "uint" && !_types2["uint"]) { - base = "uint256"; - } - return { name: name2, type: base + (index2 || "") }; - }); - links.set(type, /* @__PURE__ */ new Set()); - parents.set(type, []); - subtypes.set(type, /* @__PURE__ */ new Set()); - }); - __privateSet(this, _types, JSON.stringify(types2)); - for (const name2 in types2) { - const uniqueNames = /* @__PURE__ */ new Set(); - for (const field of types2[name2]) { - assertArgument(!uniqueNames.has(field.name), `duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name2)}`, "types", _types2); - uniqueNames.add(field.name); - const baseType = splitArray(field.type).base; - assertArgument(baseType !== name2, `circular type reference to ${JSON.stringify(baseType)}`, "types", _types2); - const encoder2 = getBaseEncoder(baseType); - if (encoder2) { - continue; - } - assertArgument(parents.has(baseType), `unknown type ${JSON.stringify(baseType)}`, "types", _types2); - parents.get(baseType).push(name2); - links.get(name2).add(baseType); - } - } - const primaryTypes = Array.from(parents.keys()).filter((n2) => parents.get(n2).length === 0); - assertArgument(primaryTypes.length !== 0, "missing primary type", "types", _types2); - assertArgument(primaryTypes.length === 1, `ambiguous primary types or unused types: ${primaryTypes.map((t2) => JSON.stringify(t2)).join(", ")}`, "types", _types2); - defineProperties$1(this, { primaryType: primaryTypes[0] }); - function checkCircular(type, found) { - assertArgument(!found.has(type), `circular type reference to ${JSON.stringify(type)}`, "types", _types2); - found.add(type); - for (const child of links.get(type)) { - if (!parents.has(child)) { - continue; - } - checkCircular(child, found); - for (const subtype of found) { - subtypes.get(subtype).add(child); + Point.BASE._setWindowSize(8); + function verify(signature2, msgHash, publicKey, opts = defaultVerOpts) { + var _a2; + const sg2 = signature2; + msgHash = ensureBytes$1("msgHash", msgHash); + publicKey = ensureBytes$1("publicKey", publicKey); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + const { lowS, prehash } = opts; + let _sig2 = void 0; + let P2; + try { + if (typeof sg2 === "string" || isBytes$1(sg2)) { + try { + _sig2 = Signature2.fromDER(sg2); + } catch (derError) { + if (!(derError instanceof DER$1.Err)) + throw derError; + _sig2 = Signature2.fromCompact(sg2); } + } else if (typeof sg2 === "object" && typeof sg2.r === "bigint" && typeof sg2.s === "bigint") { + const { r: r3, s: s3 } = sg2; + _sig2 = new Signature2(r3, s3); + } else { + throw new Error("PARSE"); } - found.delete(type); - } - checkCircular(this.primaryType, /* @__PURE__ */ new Set()); - for (const [name2, set] of subtypes) { - const st = Array.from(set); - st.sort(); - __privateGet(this, _fullTypes).set(name2, encodeType$1(name2, types2[name2]) + st.map((t2) => encodeType$1(t2, types2[t2])).join("")); + P2 = Point.fromHex(publicKey); + } catch (error) { + if (error.message === "PARSE") + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; } + if (lowS && _sig2.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r: r2, s: s2 } = _sig2; + const h2 = bits2int_modN(msgHash); + const is = invN(s2); + const u1 = modN(h2 * is); + const u2 = modN(r2 * is); + const R2 = (_a2 = Point.BASE.multiplyAndAddUnsafe(P2, u1, u2)) == null ? void 0 : _a2.toAffine(); + if (!R2) + return false; + const v3 = modN(R2.x); + return v3 === r2; } - /** - * The types. - */ - get types() { - return JSON.parse(__privateGet(this, _types)); - } - /** - * Returnthe encoder for the specific %%type%%. - */ - getEncoder(type) { - let encoder2 = __privateGet(this, _encoderCache).get(type); - if (!encoder2) { - encoder2 = __privateMethod(this, _TypedDataEncoder_instances, getEncoder_fn).call(this, type); - __privateGet(this, _encoderCache).set(type, encoder2); - } - return encoder2; + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature: Signature2, + utils: utils2 + }; +} +let HMAC$1 = class HMAC extends Hash$2 { + constructor(hash2, _key) { + super(); + this.finished = false; + this.destroyed = false; + hash$2(hash2); + const key = toBytes$2(_key); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad2 = new Uint8Array(blockLen); + pad2.set(key.length > blockLen ? hash2.create().update(key).digest() : key); + for (let i = 0; i < pad2.length; i++) + pad2[i] ^= 54; + this.iHash.update(pad2); + this.oHash = hash2.create(); + for (let i = 0; i < pad2.length; i++) + pad2[i] ^= 54 ^ 92; + this.oHash.update(pad2); + pad2.fill(0); } - /** - * Return the full type for %%name%%. - */ - encodeType(name2) { - const result = __privateGet(this, _fullTypes).get(name2); - assertArgument(result, `unknown type: ${JSON.stringify(name2)}`, "name", name2); - return result; + update(buf) { + exists$2(this); + this.iHash.update(buf); + return this; } - /** - * Return the encoded %%value%% for the %%type%%. - */ - encodeData(type, value) { - return this.getEncoder(type)(value); + digestInto(out) { + exists$2(this); + bytes$2(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); } - /** - * Returns the hash of %%value%% for the type of %%name%%. - */ - hashStruct(name2, value) { - return keccak256$1(this.encodeData(name2, value)); + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; } - /** - * Return the fulled encoded %%value%% for the [[types]]. - */ - encode(value) { - return this.encodeData(this.primaryType, value); + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; } - /** - * Return the hash of the fully encoded %%value%% for the [[types]]. - */ - hash(value) { - return this.hashStruct(this.primaryType, value); + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); } +}; +const hmac$2 = (hash2, key, message) => new HMAC$1(hash2, key).update(message).digest(); +hmac$2.create = (hash2, key) => new HMAC$1(hash2, key); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +function getHash$1(hash2) { + return { + hash: hash2, + hmac: (key, ...msgs) => hmac$2(hash2, key, concatBytes$3(...msgs)), + randomBytes: randomBytes$3 + }; +} +function createCurve$1(curveDef, defHash) { + const create = (hash2) => weierstrass$1({ ...curveDef, ...getHash$1(hash2) }); + return Object.freeze({ ...create(defHash), create }); +} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const secp256k1P$1 = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); +const secp256k1N$1 = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const _1n$6 = BigInt(1); +const _2n$4 = BigInt(2); +const divNearest$1 = (a2, b2) => (a2 + b2 / _2n$4) / b2; +function sqrtMod$1(y2) { + const P2 = secp256k1P$1; + const _3n2 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = y2 * y2 * y2 % P2; + const b3 = b2 * b2 * y2 % P2; + const b6 = pow2$1(b3, _3n2, P2) * b3 % P2; + const b9 = pow2$1(b6, _3n2, P2) * b3 % P2; + const b11 = pow2$1(b9, _2n$4, P2) * b2 % P2; + const b22 = pow2$1(b11, _11n, P2) * b11 % P2; + const b44 = pow2$1(b22, _22n, P2) * b22 % P2; + const b88 = pow2$1(b44, _44n, P2) * b44 % P2; + const b176 = pow2$1(b88, _88n, P2) * b88 % P2; + const b220 = pow2$1(b176, _44n, P2) * b44 % P2; + const b223 = pow2$1(b220, _3n2, P2) * b3 % P2; + const t1 = pow2$1(b223, _23n, P2) * b22 % P2; + const t2 = pow2$1(t1, _6n, P2) * b2 % P2; + const root2 = pow2$1(t2, _2n$4, P2); + if (!Fp$1.eql(Fp$1.sqr(root2), y2)) + throw new Error("Cannot find square root"); + return root2; +} +const Fp$1 = Field$1(secp256k1P$1, void 0, void 0, { sqrt: sqrtMod$1 }); +const secp256k1$1 = createCurve$1({ + a: BigInt(0), + // equation params: a, b + b: BigInt(7), + // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp: Fp$1, + // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N$1, + // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), + Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), + h: BigInt(1), + // Cofactor + lowS: true, + // Allow only low-S signatures by default in sign() and verify() /** - * @_ignore: + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 */ - _visit(type, value, callback) { - { - const encoder2 = getBaseEncoder(type); - if (encoder2) { - return callback(type, value); + endo: { + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + splitScalar: (k2) => { + const n2 = secp256k1N$1; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n$6 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest$1(b2 * k2, n2); + const c2 = divNearest$1(-b1 * k2, n2); + let k1 = mod$1(k2 - c1 * a1 - c2 * a2, n2); + let k22 = mod$1(-c1 * b1 - c2 * b2, n2); + const k1neg = k1 > POW_2_128; + const k2neg = k22 > POW_2_128; + if (k1neg) + k1 = n2 - k1; + if (k2neg) + k22 = n2 - k22; + if (k1 > POW_2_128 || k22 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k2); } + return { k1neg, k1, k2neg, k2: k22 }; } - const array = splitArray(type).array; - if (array) { - assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value); - return value.map((v3) => this._visit(array.prefix, v3, callback)); - } - const fields = this.types[type]; - if (fields) { - return fields.reduce((accum, { name: name2, type: type2 }) => { - accum[name2] = this._visit(type2, value[name2], callback); - return accum; - }, {}); - } - assertArgument(false, `unknown type: ${type}`, "type", type); - } - /** - * Call %%calback%% for each value in %%value%%, passing the type and - * component within %%value%%. - * - * This is useful for replacing addresses or other transformation that - * may be desired on each component, based on its type. - */ - visit(value, callback) { - return this._visit(this.primaryType, value, callback); - } - /** - * Create a new **TypedDataEncoder** for %%types%%. - */ - static from(types2) { - return new _TypedDataEncoder(types2); } - /** - * Return the primary type for %%types%%. - */ - static getPrimaryType(types2) { - return _TypedDataEncoder.from(types2).primaryType; - } - /** - * Return the hashed struct for %%value%% using %%types%% and %%name%%. - */ - static hashStruct(name2, types2, value) { - return _TypedDataEncoder.from(types2).hashStruct(name2, value); - } - /** - * Return the domain hash for %%domain%%. - */ - static hashDomain(domain2) { - const domainFields = []; - for (const name2 in domain2) { - if (domain2[name2] == null) { - continue; - } - const type = domainFieldTypes[name2]; - assertArgument(type, `invalid typed-data domain key: ${JSON.stringify(name2)}`, "domain", domain2); - domainFields.push({ name: name2, type }); - } - domainFields.sort((a2, b2) => { - return domainFieldNames.indexOf(a2.name) - domainFieldNames.indexOf(b2.name); +}, sha256$4); +BigInt(0); +secp256k1$1.ProjectivePoint; +const secp256k1$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + secp256k1: secp256k1$1 +}, Symbol.toStringTag, { value: "Module" })); +function serializeSignature({ r: r2, s: s2, to = "hex", v: v3, yParity }) { + const yParity_ = (() => { + if (yParity === 0 || yParity === 1) + return yParity; + if (v3 && (v3 === 27n || v3 === 28n || v3 >= 35n)) + return v3 % 2n === 0n ? 1 : 0; + throw new Error("Invalid `v` or `yParity` value"); + })(); + const signature2 = `0x${new secp256k1$1.Signature(hexToBigInt(r2), hexToBigInt(s2)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`; + if (to === "hex") + return signature2; + return hexToBytes$2(signature2); +} +async function verifyHash(client2, parameters) { + const { address, factory: factory2, factoryData, hash: hash2, signature: signature2, ...rest } = parameters; + const signatureHex = (() => { + if (isHex(signature2)) + return signature2; + if (typeof signature2 === "object" && "r" in signature2 && "s" in signature2) + return serializeSignature(signature2); + return bytesToHex$3(signature2); + })(); + const wrappedSignature = await (async () => { + if (!factory2 && !factoryData) + return signatureHex; + if (isErc6492Signature(signatureHex)) + return signatureHex; + return serializeErc6492Signature({ + address: factory2, + data: factoryData, + signature: signatureHex }); - return _TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain2); - } - /** - * Return the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%. - */ - static encode(domain2, types2, value) { - return concat$1([ - "0x1901", - _TypedDataEncoder.hashDomain(domain2), - _TypedDataEncoder.from(types2).hash(value) - ]); - } - /** - * Return the hash of the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%. - */ - static hash(domain2, types2, value) { - return keccak256$1(_TypedDataEncoder.encode(domain2, types2, value)); - } - // Replaces all address types with ENS names with their looked up address - /** - * Resolves to the value from resolving all addresses in %%value%% for - * %%types%% and the %%domain%%. - */ - static async resolveNames(domain2, types2, value, resolveName) { - domain2 = Object.assign({}, domain2); - for (const key in domain2) { - if (domain2[key] == null) { - delete domain2[key]; - } - } - const ensCache = {}; - if (domain2.verifyingContract && !isHexString(domain2.verifyingContract, 20)) { - ensCache[domain2.verifyingContract] = "0x"; - } - const encoder2 = _TypedDataEncoder.from(types2); - encoder2.visit(value, (type, value2) => { - if (type === "address" && !isHexString(value2, 20)) { - ensCache[value2] = "0x"; - } - return value2; + })(); + try { + const { data } = await getAction$1(client2, call, "call")({ + data: encodeDeployData({ + abi: universalSignatureValidatorAbi, + args: [address, hash2, wrappedSignature], + bytecode: universalSignatureValidatorByteCode + }), + ...rest }); - for (const name2 in ensCache) { - ensCache[name2] = await resolveName(name2); + return isBytesEqual(data ?? "0x0", "0x1"); + } catch (error) { + try { + const verified = isAddressEqual(getAddress$1(address), await recoverAddress$1({ hash: hash2, signature: signature2 })); + if (verified) + return true; + } catch { } - if (domain2.verifyingContract && ensCache[domain2.verifyingContract]) { - domain2.verifyingContract = ensCache[domain2.verifyingContract]; + if (error instanceof CallExecutionError) { + return false; } - value = encoder2.visit(value, (type, value2) => { - if (type === "address" && ensCache[value2]) { - return ensCache[value2]; - } - return value2; - }); - return { domain: domain2, value }; + throw error; } - /** - * Returns the JSON-encoded payload expected by nodes which implement - * the JSON-RPC [[link-eip-712]] method. - */ - static getPayload(domain2, types2, value) { - _TypedDataEncoder.hashDomain(domain2); - const domainValues = {}; - const domainTypes = []; - domainFieldNames.forEach((name2) => { - const value2 = domain2[name2]; - if (value2 == null) { - return; - } - domainValues[name2] = domainChecks[name2](value2); - domainTypes.push({ name: name2, type: domainFieldTypes[name2] }); - }); - const encoder2 = _TypedDataEncoder.from(types2); - types2 = encoder2.types; - const typesWithDomain = Object.assign({}, types2); - assertArgument(typesWithDomain.EIP712Domain == null, "types must not contain EIP712Domain type", "types.EIP712Domain", types2); - typesWithDomain.EIP712Domain = domainTypes; - encoder2.encode(value); - return { - types: typesWithDomain, - domain: domainValues, - primaryType: encoder2.primaryType, - message: encoder2.visit(value, (type, value2) => { - if (type.match(/^bytes(\d*)/)) { - return hexlify(getBytes(value2)); - } - if (type.match(/^u?int/)) { - return getBigInt(value2).toString(); - } - switch (type) { - case "address": - return value2.toLowerCase(); - case "bool": - return !!value2; - case "string": - assertArgument(typeof value2 === "string", "invalid string", "value", value2); - return value2; +} +async function verifyMessage$1(client2, { address, message, factory: factory2, factoryData, signature: signature2, ...callRequest }) { + const hash2 = hashMessage$1(message); + return verifyHash(client2, { + address, + factory: factory2, + factoryData, + hash: hash2, + signature: signature2, + ...callRequest + }); +} +async function verifyTypedData$1(client2, parameters) { + const { address, factory: factory2, factoryData, signature: signature2, message, primaryType, types: types2, domain: domain2, ...callRequest } = parameters; + const hash2 = hashTypedData({ message, primaryType, types: types2, domain: domain2 }); + return verifyHash(client2, { + address, + factory: factory2, + factoryData, + hash: hash2, + signature: signature2, + ...callRequest + }); +} +async function watchAsset(client2, params) { + const added = await client2.request({ + method: "wallet_watchAsset", + params + }, { retryCount: 0 }); + return added; +} +function watchContractEvent(client2, parameters) { + const { abi: abi2, address, args, batch = true, eventName, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client2.pollingInterval, strict: strict_ } = parameters; + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (typeof fromBlock === "bigint") + return true; + if (client2.transport.type === "webSocket") + return false; + if (client2.transport.type === "fallback" && client2.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + const pollContractEvent = () => { + const strict = strict_ ?? false; + const observerId = stringify$3([ + "watchContractEvent", + address, + args, + batch, + client2.uid, + eventName, + pollingInterval, + strict, + fromBlock + ]); + return observe(observerId, { onLogs, onError }, (emit2) => { + let previousBlockNumber; + if (fromBlock !== void 0) + previousBlockNumber = fromBlock - 1n; + let filter2; + let initialized = false; + const unwatch = poll(async () => { + var _a2; + if (!initialized) { + try { + filter2 = await getAction$1(client2, createContractEventFilter, "createContractEventFilter")({ + abi: abi2, + address, + args, + eventName, + strict, + fromBlock + }); + } catch { + } + initialized = true; + return; } - assertArgument(false, "unsupported type", "type", type); - }) - }; - } -}; -_types = new WeakMap(); -_fullTypes = new WeakMap(); -_encoderCache = new WeakMap(); -_TypedDataEncoder_instances = new WeakSet(); -getEncoder_fn = function(type) { - { - const encoder2 = getBaseEncoder(type); - if (encoder2) { - return encoder2; - } - } - const array = splitArray(type).array; - if (array) { - const subtype = array.prefix; - const subEncoder = this.getEncoder(subtype); - return (value) => { - assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value); - let result = value.map(subEncoder); - if (__privateGet(this, _fullTypes).has(subtype)) { - result = result.map(keccak256$1); - } - return keccak256$1(concat$1(result)); - }; - } - const fields = this.types[type]; - if (fields) { - const encodedType = id$1(__privateGet(this, _fullTypes).get(type)); - return (value) => { - const values = fields.map(({ name: name2, type: type2 }) => { - const result = this.getEncoder(type2)(value[name2]); - if (__privateGet(this, _fullTypes).has(type2)) { - return keccak256$1(result); + try { + let logs; + if (filter2) { + logs = await getAction$1(client2, getFilterChanges, "getFilterChanges")({ filter: filter2 }); + } else { + const blockNumber = await getAction$1(client2, getBlockNumber, "getBlockNumber")({}); + if (previousBlockNumber && previousBlockNumber < blockNumber) { + logs = await getAction$1(client2, getContractEvents, "getContractEvents")({ + abi: abi2, + address, + args, + eventName, + fromBlock: previousBlockNumber + 1n, + toBlock: blockNumber, + strict + }); + } else { + logs = []; + } + previousBlockNumber = blockNumber; + } + if (logs.length === 0) + return; + if (batch) + emit2.onLogs(logs); + else + for (const log of logs) + emit2.onLogs([log]); + } catch (err) { + if (filter2 && err instanceof InvalidInputRpcError) + initialized = false; + (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); } - return result; + }, { + emitOnBegin: true, + interval: pollingInterval }); - values.unshift(encodedType); - return concat$1(values); - }; + return async () => { + if (filter2) + await getAction$1(client2, uninstallFilter, "uninstallFilter")({ filter: filter2 }); + unwatch(); + }; + }); + }; + const subscribeContractEvent = () => { + const strict = strict_ ?? false; + const observerId = stringify$3([ + "watchContractEvent", + address, + args, + batch, + client2.uid, + eventName, + pollingInterval, + strict + ]); + let active = true; + let unsubscribe = () => active = false; + return observe(observerId, { onLogs, onError }, (emit2) => { + (async () => { + try { + const transport = (() => { + if (client2.transport.type === "fallback") { + const transport2 = client2.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client2.transport; + return transport2.value; + } + return client2.transport; + })(); + const topics = eventName ? encodeEventTopics({ + abi: abi2, + eventName, + args + }) : []; + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["logs", { address, topics }], + onData(data) { + var _a2; + if (!active) + return; + const log = data.result; + try { + const { eventName: eventName2, args: args2 } = decodeEventLog({ + abi: abi2, + data: log.data, + topics: log.topics, + strict: strict_ + }); + const formatted = formatLog$1(log, { + args: args2, + eventName: eventName2 + }); + emit2.onLogs([formatted]); + } catch (err) { + let eventName2; + let isUnnamed; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict_) + return; + eventName2 = err.abiItem.name; + isUnnamed = (_a2 = err.abiItem.inputs) == null ? void 0 : _a2.some((x2) => !("name" in x2 && x2.name)); + } + const formatted = formatLog$1(log, { + args: isUnnamed ? [] : {}, + eventName: eventName2 + }); + emit2.onLogs([formatted]); + } + }, + onError(error) { + var _a2; + (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError == null ? void 0 : onError(err); + } + })(); + return () => unsubscribe(); + }); + }; + return enablePolling ? pollContractEvent() : subscribeContractEvent(); +} +async function writeContract$1(client2, parameters) { + const { abi: abi2, account: account_ = client2.account, address, args, dataSuffix, functionName, ...request } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/contract/writeContract" + }); + const account2 = parseAccount(account_); + const data = encodeFunctionData({ + abi: abi2, + args, + functionName + }); + try { + return await getAction$1(client2, sendTransaction$1, "sendTransaction")({ + data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + account: account2, + ...request + }); + } catch (error) { + throw getContractError(error, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/writeContract", + functionName, + sender: account2.address + }); } - assertArgument(false, `unknown type: ${type}`, "type", type); -}; -let TypedDataEncoder = _TypedDataEncoder; -function verifyTypedData$1(domain2, types2, value, signature2) { - return recoverAddress$1(TypedDataEncoder.hash(domain2, types2, value), signature2); } -function setify(items) { - const result = /* @__PURE__ */ new Set(); - items.forEach((k2) => result.add(k2)); - return Object.freeze(result); +function getAction(client2, actionFn, name2) { + const action_implicit = client2[actionFn.name]; + if (typeof action_implicit === "function") + return action_implicit; + const action_explicit = client2[name2]; + if (typeof action_explicit === "function") + return action_explicit; + return (params) => actionFn(client2, params); } -const _kwVisibDeploy = "external public payable override"; -const KwVisibDeploy = setify(_kwVisibDeploy.split(" ")); -const _kwVisib = "constant external internal payable private public pure view override"; -const KwVisib = setify(_kwVisib.split(" ")); -const _kwTypes = "constructor error event fallback function receive struct"; -const KwTypes = setify(_kwTypes.split(" ")); -const _kwModifiers = "calldata memory storage payable indexed"; -const KwModifiers = setify(_kwModifiers.split(" ")); -const _kwOther = "tuple returns"; -const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(" "); -const Keywords = setify(_keywords.split(" ")); -const SimpleTokens = { - "(": "OPEN_PAREN", - ")": "CLOSE_PAREN", - "[": "OPEN_BRACKET", - "]": "CLOSE_BRACKET", - ",": "COMMA", - "@": "AT" +const version$7 = "2.13.5"; +const getVersion$1 = () => `@wagmi/core@${version$7}`; +var __classPrivateFieldGet$3 = function(receiver, state, kind, f2) { + if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver); }; -const regexWhitespacePrefix = new RegExp("^(\\s*)"); -const regexNumberPrefix = new RegExp("^([0-9]+)"); -const regexIdPrefix = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"); -const regexId = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"); -const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"); -const _TokenString = class _TokenString { - constructor(tokens) { - __privateAdd(this, _TokenString_instances); - __privateAdd(this, _offset2); - __privateAdd(this, _tokens); - __privateSet(this, _offset2, 0); - __privateSet(this, _tokens, tokens.slice()); - } - get offset() { - return __privateGet(this, _offset2); - } - get length() { - return __privateGet(this, _tokens).length - __privateGet(this, _offset2); - } - clone() { - return new _TokenString(__privateGet(this, _tokens)); - } - reset() { - __privateSet(this, _offset2, 0); - } - // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens - popKeyword(allowed) { - const top = this.peek(); - if (top.type !== "KEYWORD" || !allowed.has(top.text)) { - throw new Error(`expected keyword ${top.text}`); - } - return this.pop().text; +var _BaseError_instances, _BaseError_walk; +let BaseError$1 = class BaseError3 extends Error { + get docsBaseUrl() { + return "https://wagmi.sh/core"; } - // Pops and returns the value of the next token if it is `type`; throws if out of tokens - popType(type) { - if (this.peek().type !== type) { - const top = this.peek(); - throw new Error(`expected ${type}; got ${top.type} ${JSON.stringify(top.text)}`); - } - return this.pop().text; + get version() { + return getVersion$1(); } - // Pops and returns a "(" TOKENS ")" - popParen() { - const top = this.peek(); - if (top.type !== "OPEN_PAREN") { - throw new Error("bad start"); - } - const result = __privateMethod(this, _TokenString_instances, subTokenString_fn).call(this, __privateGet(this, _offset2) + 1, top.match + 1); - __privateSet(this, _offset2, top.match + 1); - return result; - } - // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")" - popParams() { - const top = this.peek(); - if (top.type !== "OPEN_PAREN") { - throw new Error("bad start"); - } - const result = []; - while (__privateGet(this, _offset2) < top.match - 1) { - const link = this.peek().linkNext; - result.push(__privateMethod(this, _TokenString_instances, subTokenString_fn).call(this, __privateGet(this, _offset2) + 1, link)); - __privateSet(this, _offset2, link); - } - __privateSet(this, _offset2, top.match + 1); - return result; - } - // Returns the top Token, throwing if out of tokens - peek() { - if (__privateGet(this, _offset2) >= __privateGet(this, _tokens).length) { - throw new Error("out-of-bounds"); - } - return __privateGet(this, _tokens)[__privateGet(this, _offset2)]; - } - // Returns the next value, if it is a keyword in `allowed` - peekKeyword(allowed) { - const top = this.peekType("KEYWORD"); - return top != null && allowed.has(top) ? top : null; - } - // Returns the value of the next token if it is `type` - peekType(type) { - if (this.length === 0) { - return null; - } - const top = this.peek(); - return top.type === type ? top.text : null; - } - // Returns the next token; throws if out of tokens - pop() { - const result = this.peek(); - __privateWrapper(this, _offset2)._++; - return result; + constructor(shortMessage, options = {}) { + var _a2; + super(); + _BaseError_instances.add(this); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "docsPath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metaMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "WagmiCoreError" + }); + const details = options.cause instanceof BaseError3 ? options.cause.details : ((_a2 = options.cause) == null ? void 0 : _a2.message) ? options.cause.message : options.details; + const docsPath2 = options.cause instanceof BaseError3 ? options.cause.docsPath || options.docsPath : options.docsPath; + this.message = [ + shortMessage || "An error occurred.", + "", + ...options.metaMessages ? [...options.metaMessages, ""] : [], + ...docsPath2 ? [ + `Docs: ${this.docsBaseUrl}${docsPath2}.html${options.docsSlug ? `#${options.docsSlug}` : ""}` + ] : [], + ...details ? [`Details: ${details}`] : [], + `Version: ${this.version}` + ].join("\n"); + if (options.cause) + this.cause = options.cause; + this.details = details; + this.docsPath = docsPath2; + this.metaMessages = options.metaMessages; + this.shortMessage = shortMessage; } - toString() { - const tokens = []; - for (let i = __privateGet(this, _offset2); i < __privateGet(this, _tokens).length; i++) { - const token = __privateGet(this, _tokens)[i]; - tokens.push(`${token.type}:${token.text}`); - } - return ``; + walk(fn) { + return __classPrivateFieldGet$3(this, _BaseError_instances, "m", _BaseError_walk).call(this, this, fn); } }; -_offset2 = new WeakMap(); -_tokens = new WeakMap(); -_TokenString_instances = new WeakSet(); -subTokenString_fn = function(from = 0, to = 0) { - return new _TokenString(__privateGet(this, _tokens).slice(from, to).map((t2) => { - return Object.freeze(Object.assign({}, t2, { - match: t2.match - from, - linkBack: t2.linkBack - from, - linkNext: t2.linkNext - from - })); - })); +_BaseError_instances = /* @__PURE__ */ new WeakSet(), _BaseError_walk = function _BaseError_walk2(err, fn) { + if (fn == null ? void 0 : fn(err)) + return err; + if (err.cause) + return __classPrivateFieldGet$3(this, _BaseError_instances, "m", _BaseError_walk2).call(this, err.cause, fn); + return err; }; -let TokenString = _TokenString; -function lex(text2) { - const tokens = []; - const throwError2 = (message) => { - const token = offset2 < text2.length ? JSON.stringify(text2[offset2]) : "$EOI"; - throw new Error(`invalid token ${token} at ${offset2}: ${message}`); - }; - let brackets = []; - let commas = []; - let offset2 = 0; - while (offset2 < text2.length) { - let cur = text2.substring(offset2); - let match = cur.match(regexWhitespacePrefix); - if (match) { - offset2 += match[1].length; - cur = text2.substring(offset2); - } - const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset: offset2, value: -1 }; - tokens.push(token); - let type = SimpleTokens[cur[0]] || ""; - if (type) { - token.type = type; - token.text = cur[0]; - offset2++; - if (type === "OPEN_PAREN") { - brackets.push(tokens.length - 1); - commas.push(tokens.length - 1); - } else if (type == "CLOSE_PAREN") { - if (brackets.length === 0) { - throwError2("no matching open bracket"); - } - token.match = brackets.pop(); - tokens[token.match].match = tokens.length - 1; - token.depth--; - token.linkBack = commas.pop(); - tokens[token.linkBack].linkNext = tokens.length - 1; - } else if (type === "COMMA") { - token.linkBack = commas.pop(); - tokens[token.linkBack].linkNext = tokens.length - 1; - commas.push(tokens.length - 1); - } else if (type === "OPEN_BRACKET") { - token.type = "BRACKET"; - } else if (type === "CLOSE_BRACKET") { - let suffix = tokens.pop().text; - if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") { - const value = tokens.pop().text; - suffix = value + suffix; - tokens[tokens.length - 1].value = getNumber(value); - } - if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") { - throw new Error("missing opening bracket"); - } - tokens[tokens.length - 1].text += suffix; - } - continue; - } - match = cur.match(regexIdPrefix); - if (match) { - token.text = match[1]; - offset2 += token.text.length; - if (Keywords.has(token.text)) { - token.type = "KEYWORD"; - continue; - } - if (token.text.match(regexType)) { - token.type = "TYPE"; - continue; - } - token.type = "ID"; - continue; - } - match = cur.match(regexNumberPrefix); - if (match) { - token.text = match[1]; - token.type = "NUMBER"; - offset2 += token.text.length; - continue; - } - throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset2}`); +class ChainNotConfiguredError extends BaseError$1 { + constructor() { + super("Chain not configured."); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ChainNotConfiguredError" + }); } - return new TokenString(tokens.map((t2) => Object.freeze(t2))); } -function allowSingle(set, allowed) { - let included = []; - for (const key in allowed.keys()) { - if (set.has(key)) { - included.push(key); - } - } - if (included.length > 1) { - throw new Error(`conflicting types: ${included.join(", ")}`); +class ConnectorAlreadyConnectedError extends BaseError$1 { + constructor() { + super("Connector already connected."); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ConnectorAlreadyConnectedError" + }); } } -function consumeName(type, tokens) { - if (tokens.peekKeyword(KwTypes)) { - const keyword = tokens.pop().text; - if (keyword !== type) { - throw new Error(`expected ${type}, got ${keyword}`); - } +class ConnectorNotConnectedError extends BaseError$1 { + constructor() { + super("Connector not connected."); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ConnectorNotConnectedError" + }); } - return tokens.popType("ID"); } -function consumeKeywords(tokens, allowed) { - const keywords = /* @__PURE__ */ new Set(); - while (true) { - const keyword = tokens.peekType("KEYWORD"); - if (keyword == null || allowed && !allowed.has(keyword)) { - break; - } - tokens.pop(); - if (keywords.has(keyword)) { - throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`); - } - keywords.add(keyword); +class ConnectorAccountNotFoundError extends BaseError$1 { + constructor({ address, connector }) { + super(`Account "${address}" not found for connector "${connector.name}".`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ConnectorAccountNotFoundError" + }); } - return Object.freeze(keywords); } -function consumeMutability(tokens) { - let modifiers = consumeKeywords(tokens, KwVisib); - allowSingle(modifiers, setify("constant payable nonpayable".split(" "))); - allowSingle(modifiers, setify("pure view payable nonpayable".split(" "))); - if (modifiers.has("view")) { - return "view"; - } - if (modifiers.has("pure")) { - return "pure"; - } - if (modifiers.has("payable")) { - return "payable"; - } - if (modifiers.has("nonpayable")) { - return "nonpayable"; +class ConnectorChainMismatchError extends BaseError$1 { + constructor({ connectionChainId, connectorChainId }) { + super(`The current chain of the connector (id: ${connectorChainId}) does not match the connection's chain (id: ${connectionChainId}).`, { + metaMessages: [ + `Current Chain ID: ${connectorChainId}`, + `Expected Chain ID: ${connectionChainId}` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ConnectorChainMismatchError" + }); } - if (modifiers.has("constant")) { - return "view"; +} +class ConnectorUnavailableReconnectingError extends BaseError$1 { + constructor({ connector }) { + super(`Connector "${connector.name}" unavailable while reconnecting.`, { + details: [ + "During the reconnection step, the only connector methods guaranteed to be available are: `id`, `name`, `type`, `uuid`.", + "All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored.", + "This error commonly occurs for connectors that asynchronously inject after reconnection has already started." + ].join(" ") + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ConnectorUnavailableReconnectingError" + }); } - return "nonpayable"; } -function consumeParams(tokens, allowIndexed) { - return tokens.popParams().map((t2) => ParamType.from(t2, allowIndexed)); +async function connect(config2, parameters) { + var _a2; + let connector; + if (typeof parameters.connector === "function") { + connector = config2._internal.connectors.setup(parameters.connector); + } else + connector = parameters.connector; + if (connector.uid === config2.state.current) + throw new ConnectorAlreadyConnectedError(); + try { + config2.setState((x2) => ({ ...x2, status: "connecting" })); + connector.emitter.emit("message", { type: "connecting" }); + const data = await connector.connect({ chainId: parameters.chainId }); + const accounts = data.accounts; + connector.emitter.off("connect", config2._internal.events.connect); + connector.emitter.on("change", config2._internal.events.change); + connector.emitter.on("disconnect", config2._internal.events.disconnect); + await ((_a2 = config2.storage) == null ? void 0 : _a2.setItem("recentConnectorId", connector.id)); + config2.setState((x2) => ({ + ...x2, + connections: new Map(x2.connections).set(connector.uid, { + accounts, + chainId: data.chainId, + connector + }), + current: connector.uid, + status: "connected" + })); + return { accounts, chainId: data.chainId }; + } catch (error) { + config2.setState((x2) => ({ + ...x2, + // Keep existing connector connected in case of error + status: x2.current ? "connected" : "disconnected" + })); + throw error; + } } -function consumeGas(tokens) { - if (tokens.peekType("AT")) { - tokens.pop(); - if (tokens.peekType("NUMBER")) { - return getBigInt(tokens.pop().text); +const size$4 = 256; +let index$8 = size$4; +let buffer$2; +function uid$1(length = 11) { + if (!buffer$2 || index$8 + length > size$4 * 2) { + buffer$2 = ""; + index$8 = 0; + for (let i = 0; i < size$4; i++) { + buffer$2 += (256 + Math.random() * 256 | 0).toString(16).substring(1); } - throw new Error("invalid gas"); } - return null; + return buffer$2.substring(index$8, index$8++ + length); } -function consumeEoi(tokens) { - if (tokens.length) { - throw new Error(`unexpected tokens at offset ${tokens.offset}: ${tokens.toString()}`); +function createClient(parameters) { + const { batch, cacheTime = parameters.pollingInterval ?? 4e3, ccipRead, key = "base", name: name2 = "Base Client", pollingInterval = 4e3, type = "base" } = parameters; + const chain = parameters.chain; + const account2 = parameters.account ? parseAccount(parameters.account) : void 0; + const { config: config2, request, value } = parameters.transport({ + chain, + pollingInterval + }); + const transport = { ...config2, ...value }; + const client2 = { + account: account2, + batch, + cacheTime, + ccipRead, + chain, + key, + name: name2, + pollingInterval, + request, + transport, + type, + uid: uid$1() + }; + function extend(base) { + return (extendFn) => { + const extended = extendFn(base); + for (const key2 in client2) + delete extended[key2]; + const combined = { ...base, ...extended }; + return Object.assign(combined, { extend: extend(combined) }); + }; } + return Object.assign(client2, { extend: extend(client2) }); } -const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/); -function verifyBasicType(type) { - const match = type.match(regexType); - assertArgument(match, "invalid type", "type", type); - if (type === "uint") { - return "uint256"; - } - if (type === "int") { - return "int256"; - } - if (match[2]) { - const length = parseInt(match[2]); - assertArgument(length !== 0 && length <= 32, "invalid bytes length", "type", type); - } else if (match[3]) { - const size2 = parseInt(match[3]); - assertArgument(size2 !== 0 && size2 <= 256 && size2 % 8 === 0, "invalid numeric width", "type", type); +function createTransport({ key, name: name2, request, retryCount = 3, retryDelay = 150, timeout, type }, value) { + const uid2 = uid$1(); + return { + config: { + key, + name: name2, + request, + retryCount, + retryDelay, + timeout, + type + }, + request: buildRequest(request, { retryCount, retryDelay, uid: uid2 }), + value + }; +} +function custom(provider2, config2 = {}) { + const { key = "custom", name: name2 = "Custom Provider", retryDelay } = config2; + return ({ retryCount: defaultRetryCount }) => createTransport({ + key, + name: name2, + request: provider2.request.bind(provider2), + retryCount: config2.retryCount ?? defaultRetryCount, + retryDelay, + type: "custom" + }); +} +class UrlRequiredError extends BaseError$3 { + constructor() { + super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", { + docsPath: "/docs/clients/intro", + name: "UrlRequiredError" + }); } - return type; } -const _guard$2 = {}; -const internal$1 = Symbol.for("_ethers_internal"); -const ParamTypeInternal = "_ParamTypeInternal"; -const ErrorFragmentInternal = "_ErrorInternal"; -const EventFragmentInternal = "_EventInternal"; -const ConstructorFragmentInternal = "_ConstructorInternal"; -const FallbackFragmentInternal = "_FallbackInternal"; -const FunctionFragmentInternal = "_FunctionInternal"; -const StructFragmentInternal = "_StructInternal"; -const _ParamType = class _ParamType { - /** - * @private - */ - constructor(guard2, name2, type, baseType, indexed, components, arrayLength, arrayChildren) { - __privateAdd(this, _ParamType_instances); - /** - * The local name of the parameter (or ``""`` if unbound) - */ - __publicField(this, "name"); - /** - * The fully qualified type (e.g. ``"address"``, ``"tuple(address)"``, - * ``"uint256[3][]"``) - */ - __publicField(this, "type"); - /** - * The base type (e.g. ``"address"``, ``"tuple"``, ``"array"``) - */ - __publicField(this, "baseType"); - /** - * True if the parameters is indexed. - * - * For non-indexable types this is ``null``. - */ - __publicField(this, "indexed"); - /** - * The components for the tuple. - * - * For non-tuple types this is ``null``. - */ - __publicField(this, "components"); - /** - * The array length, or ``-1`` for dynamic-lengthed arrays. - * - * For non-array types this is ``null``. - */ - __publicField(this, "arrayLength"); - /** - * The type of each child in the array. - * - * For non-array types this is ``null``. - */ - __publicField(this, "arrayChildren"); - assertPrivate(guard2, _guard$2, "ParamType"); - Object.defineProperty(this, internal$1, { value: ParamTypeInternal }); - if (components) { - components = Object.freeze(components.slice()); - } - if (baseType === "array") { - if (arrayLength == null || arrayChildren == null) { - throw new Error(""); - } - } else if (arrayLength != null || arrayChildren != null) { - throw new Error(""); - } - if (baseType === "tuple") { - if (components == null) { - throw new Error(""); - } - } else if (components != null) { - throw new Error(""); - } - defineProperties$1(this, { +function http(url, config2 = {}) { + const { batch, fetchOptions, key = "http", name: name2 = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay } = config2; + return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => { + const { batchSize = 1e3, wait: wait2 = 0 } = typeof batch === "object" ? batch : {}; + const retryCount = config2.retryCount ?? retryCount_; + const timeout = timeout_ ?? config2.timeout ?? 1e4; + const url_ = chain == null ? void 0 : chain.rpcUrls.default.http[0]; + if (!url_) + throw new UrlRequiredError(); + const rpcClient = getHttpRpcClient(url_, { + fetchOptions, + onRequest: onFetchRequest, + onResponse: onFetchResponse, + timeout + }); + return createTransport({ + key, name: name2, - type, - baseType, - indexed, - components, - arrayLength, - arrayChildren + async request({ method, params }) { + const body = { method, params }; + const { schedule } = createBatchScheduler({ + id: url_, + wait: wait2, + shouldSplitBatch(requests) { + return requests.length > batchSize; + }, + fn: (body2) => rpcClient.request({ + body: body2 + }), + sort: (a2, b2) => a2.id - b2.id + }); + const fn = async (body2) => batch ? schedule(body2) : [ + await rpcClient.request({ + body: body2 + }) + ]; + const [{ error, result }] = await fn(body); + if (error) + throw new RpcRequestError({ + body, + error, + url: url_ + }); + return result; + }, + retryCount, + retryDelay, + timeout, + type: "http" + }, { + fetchOptions, + url: url_ }); + }; +} +function parseSiweMessage(message) { + var _a2, _b2, _c2; + const { scheme, statement, ...prefix } = ((_a2 = message.match(prefixRegex)) == null ? void 0 : _a2.groups) ?? {}; + const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = ((_b2 = message.match(suffixRegex)) == null ? void 0 : _b2.groups) ?? {}; + const resources = (_c2 = message.split("Resources:")[1]) == null ? void 0 : _c2.split("\n- ").slice(1); + return { + ...prefix, + ...suffix, + ...chainId ? { chainId: Number(chainId) } : {}, + ...expirationTime ? { expirationTime: new Date(expirationTime) } : {}, + ...issuedAt ? { issuedAt: new Date(issuedAt) } : {}, + ...notBefore ? { notBefore: new Date(notBefore) } : {}, + ...requestId ? { requestId } : {}, + ...resources ? { resources } : {}, + ...scheme ? { scheme } : {}, + ...statement ? { statement } : {} + }; +} +const prefixRegex = /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/; +const suffixRegex = /(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/; +function validateSiweMessage(parameters) { + const { address, domain: domain2, message, nonce, scheme, time: time2 = /* @__PURE__ */ new Date() } = parameters; + if (domain2 && message.domain !== domain2) + return false; + if (nonce && message.nonce !== nonce) + return false; + if (scheme && message.scheme !== scheme) + return false; + if (message.expirationTime && time2 >= message.expirationTime) + return false; + if (message.notBefore && time2 < message.notBefore) + return false; + try { + if (!message.address) + return false; + if (address && !isAddressEqual(message.address, address)) + return false; + } catch { + return false; } - /** - * Return a string representation of this type. - * - * For example, - * - * ``sighash" => "(uint256,address)"`` - * - * ``"minimal" => "tuple(uint256,address) indexed"`` - * - * ``"full" => "tuple(uint256 foo, address bar) indexed baz"`` - */ - format(format2) { - if (format2 == null) { - format2 = "sighash"; - } - if (format2 === "json") { - const name2 = this.name || ""; - if (this.isArray()) { - const result3 = JSON.parse(this.arrayChildren.format("json")); - result3.name = name2; - result3.type += `[${this.arrayLength < 0 ? "" : String(this.arrayLength)}]`; - return JSON.stringify(result3); - } - const result2 = { - type: this.baseType === "tuple" ? "tuple" : this.type, - name: name2 - }; - if (typeof this.indexed === "boolean") { - result2.indexed = this.indexed; - } - if (this.isTuple()) { - result2.components = this.components.map((c2) => JSON.parse(c2.format(format2))); - } - return JSON.stringify(result2); - } - let result = ""; - if (this.isArray()) { - result += this.arrayChildren.format(format2); - result += `[${this.arrayLength < 0 ? "" : String(this.arrayLength)}]`; - } else { - if (this.isTuple()) { - result += "(" + this.components.map((comp) => comp.format(format2)).join(format2 === "full" ? ", " : ",") + ")"; - } else { - result += this.type; - } - } - if (format2 !== "sighash") { - if (this.indexed === true) { - result += " indexed"; - } - if (format2 === "full" && this.name) { - result += " " + this.name; - } - } - return result; + return true; +} +async function verifySiweMessage(client2, parameters) { + const { address, domain: domain2, message, nonce, scheme, signature: signature2, time: time2 = /* @__PURE__ */ new Date(), ...callRequest } = parameters; + const parsed = parseSiweMessage(message); + if (!parsed.address) + return false; + const isValid2 = validateSiweMessage({ + address, + domain: domain2, + message: parsed, + nonce, + scheme, + time: time2 + }); + if (!isValid2) + return false; + const hash2 = hashMessage$1(message); + return verifyHash(client2, { + address: parsed.address, + hash: hash2, + signature: signature2, + ...callRequest + }); +} +function publicActions(client2) { + return { + call: (args) => call(client2, args), + createBlockFilter: () => createBlockFilter(client2), + createContractEventFilter: (args) => createContractEventFilter(client2, args), + createEventFilter: (args) => createEventFilter(client2, args), + createPendingTransactionFilter: () => createPendingTransactionFilter(client2), + estimateContractGas: (args) => estimateContractGas(client2, args), + estimateGas: (args) => estimateGas(client2, args), + getBalance: (args) => getBalance(client2, args), + getBlobBaseFee: () => getBlobBaseFee(client2), + getBlock: (args) => getBlock(client2, args), + getBlockNumber: (args) => getBlockNumber(client2, args), + getBlockTransactionCount: (args) => getBlockTransactionCount(client2, args), + getBytecode: (args) => getCode(client2, args), + getChainId: () => getChainId$2(client2), + getCode: (args) => getCode(client2, args), + getContractEvents: (args) => getContractEvents(client2, args), + getEip712Domain: (args) => getEip712Domain(client2, args), + getEnsAddress: (args) => getEnsAddress(client2, args), + getEnsAvatar: (args) => getEnsAvatar(client2, args), + getEnsName: (args) => getEnsName(client2, args), + getEnsResolver: (args) => getEnsResolver(client2, args), + getEnsText: (args) => getEnsText(client2, args), + getFeeHistory: (args) => getFeeHistory(client2, args), + estimateFeesPerGas: (args) => estimateFeesPerGas(client2, args), + getFilterChanges: (args) => getFilterChanges(client2, args), + getFilterLogs: (args) => getFilterLogs(client2, args), + getGasPrice: () => getGasPrice(client2), + getLogs: (args) => getLogs(client2, args), + getProof: (args) => getProof(client2, args), + estimateMaxPriorityFeePerGas: (args) => estimateMaxPriorityFeePerGas(client2, args), + getStorageAt: (args) => getStorageAt(client2, args), + getTransaction: (args) => getTransaction(client2, args), + getTransactionConfirmations: (args) => getTransactionConfirmations(client2, args), + getTransactionCount: (args) => getTransactionCount(client2, args), + getTransactionReceipt: (args) => getTransactionReceipt$1(client2, args), + multicall: (args) => multicall(client2, args), + prepareTransactionRequest: (args) => prepareTransactionRequest(client2, args), + readContract: (args) => readContract$1(client2, args), + sendRawTransaction: (args) => sendRawTransaction(client2, args), + simulateContract: (args) => simulateContract$1(client2, args), + verifyMessage: (args) => verifyMessage$1(client2, args), + verifySiweMessage: (args) => verifySiweMessage(client2, args), + verifyTypedData: (args) => verifyTypedData$1(client2, args), + uninstallFilter: (args) => uninstallFilter(client2, args), + waitForTransactionReceipt: (args) => waitForTransactionReceipt(client2, args), + watchBlocks: (args) => watchBlocks(client2, args), + watchBlockNumber: (args) => watchBlockNumber(client2, args), + watchContractEvent: (args) => watchContractEvent(client2, args), + watchEvent: (args) => watchEvent(client2, args), + watchPendingTransactions: (args) => watchPendingTransactions(client2, args) + }; +} +function walletActions(client2) { + return { + addChain: (args) => addChain(client2, args), + deployContract: (args) => deployContract(client2, args), + getAddresses: () => getAddresses(client2), + getChainId: () => getChainId$2(client2), + getPermissions: () => getPermissions(client2), + prepareTransactionRequest: (args) => prepareTransactionRequest(client2, args), + requestAddresses: () => requestAddresses(client2), + requestPermissions: (args) => requestPermissions(client2, args), + sendRawTransaction: (args) => sendRawTransaction(client2, args), + sendTransaction: (args) => sendTransaction$1(client2, args), + signMessage: (args) => signMessage$1(client2, args), + signTransaction: (args) => signTransaction(client2, args), + signTypedData: (args) => signTypedData(client2, args), + switchChain: (args) => switchChain$1(client2, args), + watchAsset: (args) => watchAsset(client2, args), + writeContract: (args) => writeContract$1(client2, args) + }; +} +const zeroAddress = "0x0000000000000000000000000000000000000000"; +async function getConnectorClient(config2, parameters = {}) { + let connection; + if (parameters.connector) { + const { connector: connector2 } = parameters; + if (config2.state.status === "reconnecting" && !connector2.getAccounts && !connector2.getChainId) + throw new ConnectorUnavailableReconnectingError({ connector: connector2 }); + const [accounts, chainId2] = await Promise.all([ + connector2.getAccounts(), + connector2.getChainId() + ]); + connection = { + accounts, + chainId: chainId2, + connector: connector2 + }; + } else + connection = config2.state.connections.get(config2.state.current); + if (!connection) + throw new ConnectorNotConnectedError(); + const chainId = parameters.chainId ?? connection.chainId; + const connectorChainId = await connection.connector.getChainId(); + if (connectorChainId !== connection.chainId) + throw new ConnectorChainMismatchError({ + connectionChainId: connection.chainId, + connectorChainId + }); + const connector = connection.connector; + if (connector.getClient) + return connector.getClient({ chainId }); + const account2 = parseAccount(parameters.account ?? connection.accounts[0]); + account2.address = getAddress$1(account2.address); + if (parameters.account && !connection.accounts.some((x2) => x2.toLowerCase() === account2.address.toLowerCase())) + throw new ConnectorAccountNotFoundError({ + address: account2.address, + connector + }); + const chain = config2.chains.find((chain2) => chain2.id === chainId); + const provider2 = await connection.connector.getProvider({ chainId }); + return createClient({ + account: account2, + chain, + name: "Connector Client", + transport: (opts) => custom(provider2)({ ...opts, retryCount: 0 }) + }); +} +async function disconnect(config2, parameters = {}) { + var _a2, _b2; + let connector; + if (parameters.connector) + connector = parameters.connector; + else { + const { connections: connections2, current } = config2.state; + const connection = connections2.get(current); + connector = connection == null ? void 0 : connection.connector; } - /** - * Returns true if %%this%% is an Array type. - * - * This provides a type gaurd ensuring that [[arrayChildren]] - * and [[arrayLength]] are non-null. - */ - isArray() { - return this.baseType === "array"; + const connections = config2.state.connections; + if (connector) { + await connector.disconnect(); + connector.emitter.off("change", config2._internal.events.change); + connector.emitter.off("disconnect", config2._internal.events.disconnect); + connector.emitter.on("connect", config2._internal.events.connect); + connections.delete(connector.uid); } - /** - * Returns true if %%this%% is a Tuple type. - * - * This provides a type gaurd ensuring that [[components]] - * is non-null. - */ - isTuple() { - return this.baseType === "tuple"; + config2.setState((x2) => { + if (connections.size === 0) + return { + ...x2, + connections: /* @__PURE__ */ new Map(), + current: null, + status: "disconnected" + }; + const nextConnection = connections.values().next().value; + return { + ...x2, + connections: new Map(connections), + current: nextConnection.connector.uid + }; + }); + { + const current = config2.state.current; + if (!current) + return; + const connector2 = (_a2 = config2.state.connections.get(current)) == null ? void 0 : _a2.connector; + if (!connector2) + return; + await ((_b2 = config2.storage) == null ? void 0 : _b2.setItem("recentConnectorId", connector2.id)); } - /** - * Returns true if %%this%% is an Indexable type. - * - * This provides a type gaurd ensuring that [[indexed]] - * is non-null. - */ - isIndexable() { - return this.indexed != null; +} +function getAccount$1(config2) { + const uid2 = config2.state.current; + const connection = config2.state.connections.get(uid2); + const addresses = connection == null ? void 0 : connection.accounts; + const address = addresses == null ? void 0 : addresses[0]; + const chain = config2.chains.find((chain2) => chain2.id === (connection == null ? void 0 : connection.chainId)); + const status = config2.state.status; + switch (status) { + case "connected": + return { + address, + addresses, + chain, + chainId: connection == null ? void 0 : connection.chainId, + connector: connection == null ? void 0 : connection.connector, + isConnected: true, + isConnecting: false, + isDisconnected: false, + isReconnecting: false, + status + }; + case "reconnecting": + return { + address, + addresses, + chain, + chainId: connection == null ? void 0 : connection.chainId, + connector: connection == null ? void 0 : connection.connector, + isConnected: !!address, + isConnecting: false, + isDisconnected: false, + isReconnecting: true, + status + }; + case "connecting": + return { + address, + addresses, + chain, + chainId: connection == null ? void 0 : connection.chainId, + connector: connection == null ? void 0 : connection.connector, + isConnected: false, + isConnecting: true, + isDisconnected: false, + isReconnecting: false, + status + }; + case "disconnected": + return { + address: void 0, + addresses: void 0, + chain: void 0, + chainId: void 0, + connector: void 0, + isConnected: false, + isConnecting: false, + isDisconnected: true, + isReconnecting: false, + status + }; } - /** - * Walks the **ParamType** with %%value%%, calling %%process%% - * on each type, destructing the %%value%% recursively. - */ - walk(value, process2) { - if (this.isArray()) { - if (!Array.isArray(value)) { - throw new Error("invalid array value"); - } - if (this.arrayLength !== -1 && value.length !== this.arrayLength) { - throw new Error("array is wrong length"); - } - const _this = this; - return value.map((v3) => _this.arrayChildren.walk(v3, process2)); - } - if (this.isTuple()) { - if (!Array.isArray(value)) { - throw new Error("invalid tuple value"); - } - if (value.length !== this.components.length) { - throw new Error("array is wrong length"); - } - const _this = this; - return value.map((v3, i) => _this.components[i].walk(v3, process2)); +} +function readContract(config2, parameters) { + const { chainId, ...rest } = parameters; + const client2 = config2.getClient({ chainId }); + const action = getAction(client2, readContract$1, "readContract"); + return action(rest); +} +function getChainId$1(config2) { + return config2.state.chainId; +} +function deepEqual$1(a2, b2) { + if (a2 === b2) + return true; + if (a2 && b2 && typeof a2 === "object" && typeof b2 === "object") { + if (a2.constructor !== b2.constructor) + return false; + let length; + let i; + if (Array.isArray(a2) && Array.isArray(b2)) { + length = a2.length; + if (length !== b2.length) + return false; + for (i = length; i-- !== 0; ) + if (!deepEqual$1(a2[i], b2[i])) + return false; + return true; } - return process2(this.type, value); - } - /** - * Walks the **ParamType** with %%value%%, asynchronously calling - * %%process%% on each type, destructing the %%value%% recursively. - * - * This can be used to resolve ENS names by walking and resolving each - * ``"address"`` type. - */ - async walkAsync(value, process2) { - const promises = []; - const result = [value]; - __privateMethod(this, _ParamType_instances, walkAsync_fn).call(this, promises, value, process2, (value2) => { - result[0] = value2; - }); - if (promises.length) { - await Promise.all(promises); + if (a2.valueOf !== Object.prototype.valueOf) + return a2.valueOf() === b2.valueOf(); + if (a2.toString !== Object.prototype.toString) + return a2.toString() === b2.toString(); + const keys = Object.keys(a2); + length = keys.length; + if (length !== Object.keys(b2).length) + return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b2, keys[i])) + return false; + for (i = length; i-- !== 0; ) { + const key = keys[i]; + if (key && !deepEqual$1(a2[key], b2[key])) + return false; } - return result[0]; + return true; } - /** - * Creates a new **ParamType** for %%obj%%. - * - * If %%allowIndexed%% then the ``indexed`` keyword is permitted, - * otherwise the ``indexed`` keyword will throw an error. - */ - static from(obj, allowIndexed) { - if (_ParamType.isParamType(obj)) { - return obj; - } - if (typeof obj === "string") { - try { - return _ParamType.from(lex(obj), allowIndexed); - } catch (error) { - assertArgument(false, "invalid param type", "obj", obj); - } - } else if (obj instanceof TokenString) { - let type2 = "", baseType = ""; - let comps = null; - if (consumeKeywords(obj, setify(["tuple"])).has("tuple") || obj.peekType("OPEN_PAREN")) { - baseType = "tuple"; - comps = obj.popParams().map((t2) => _ParamType.from(t2)); - type2 = `tuple(${comps.map((c2) => c2.format()).join(",")})`; - } else { - type2 = verifyBasicType(obj.popType("TYPE")); - baseType = type2; - } - let arrayChildren = null; - let arrayLength = null; - while (obj.length && obj.peekType("BRACKET")) { - const bracket = obj.pop(); - arrayChildren = new _ParamType(_guard$2, "", type2, baseType, null, comps, arrayLength, arrayChildren); - arrayLength = bracket.value; - type2 += bracket.text; - baseType = "array"; - comps = null; - } - let indexed2 = null; - const keywords = consumeKeywords(obj, KwModifiers); - if (keywords.has("indexed")) { - if (!allowIndexed) { - throw new Error(""); - } - indexed2 = true; - } - const name3 = obj.peekType("ID") ? obj.pop().text : ""; - if (obj.length) { - throw new Error("leftover tokens"); - } - return new _ParamType(_guard$2, name3, type2, baseType, indexed2, comps, arrayLength, arrayChildren); - } - const name2 = obj.name; - assertArgument(!name2 || typeof name2 === "string" && name2.match(regexId), "invalid name", "obj.name", name2); - let indexed = obj.indexed; - if (indexed != null) { - assertArgument(allowIndexed, "parameter cannot be indexed", "obj.indexed", obj.indexed); - indexed = !!indexed; - } - let type = obj.type; - let arrayMatch = type.match(regexArrayType); - if (arrayMatch) { - const arrayLength = parseInt(arrayMatch[2] || "-1"); - const arrayChildren = _ParamType.from({ - type: arrayMatch[1], - components: obj.components - }); - return new _ParamType(_guard$2, name2 || "", type, "array", indexed, null, arrayLength, arrayChildren); - } - if (type === "tuple" || type.startsWith( - "tuple(" - /* fix: ) */ - ) || type.startsWith( - "(" - /* fix: ) */ - )) { - const comps = obj.components != null ? obj.components.map((c2) => _ParamType.from(c2)) : null; - const tuple = new _ParamType(_guard$2, name2 || "", type, "tuple", indexed, comps, null, null); - return tuple; + return a2 !== a2 && b2 !== b2; +} +let previousChains = []; +function getChains(config2) { + const chains2 = config2.chains; + if (deepEqual$1(previousChains, chains2)) + return previousChains; + previousChains = chains2; + return chains2; +} +function getClient(config2, parameters = {}) { + let client2 = void 0; + try { + client2 = config2.getClient(parameters); + } catch { + } + return client2; +} +let previousConnections = []; +function getConnections(config2) { + const connections = [...config2.state.connections.values()]; + if (config2.state.status === "reconnecting") + return previousConnections; + if (deepEqual$1(previousConnections, connections)) + return previousConnections; + previousConnections = connections; + return connections; +} +let previousConnectors = []; +function getConnectors(config2) { + const connectors = config2.connectors; + if (deepEqual$1(previousConnectors, connectors)) + return previousConnectors; + previousConnectors = connectors; + return connectors; +} +function getPublicClient(config2, parameters = {}) { + const client2 = getClient(config2, parameters); + return client2 == null ? void 0 : client2.extend(publicActions); +} +async function getWalletClient(config2, parameters = {}) { + const client2 = await getConnectorClient(config2, parameters); + client2.extend(walletActions); + return client2.extend(walletActions); +} +let isReconnecting = false; +async function reconnect(config2, parameters = {}) { + var _a2, _b2; + if (isReconnecting) + return []; + isReconnecting = true; + config2.setState((x2) => ({ + ...x2, + status: x2.current ? "reconnecting" : "connecting" + })); + const connectors = []; + if ((_a2 = parameters.connectors) == null ? void 0 : _a2.length) { + for (const connector_ of parameters.connectors) { + let connector; + if (typeof connector_ === "function") + connector = config2._internal.connectors.setup(connector_); + else + connector = connector_; + connectors.push(connector); } - type = verifyBasicType(obj.type); - return new _ParamType(_guard$2, name2 || "", type, type, indexed, null, null, null); + } else + connectors.push(...config2.connectors); + let recentConnectorId; + try { + recentConnectorId = await ((_b2 = config2.storage) == null ? void 0 : _b2.getItem("recentConnectorId")); + } catch { } - /** - * Returns true if %%value%% is a **ParamType**. - */ - static isParamType(value) { - return value && value[internal$1] === ParamTypeInternal; + const scores = {}; + for (const [, connection] of config2.state.connections) { + scores[connection.connector.id] = 1; } -}; -_ParamType_instances = new WeakSet(); -walkAsync_fn = function(promises, value, process2, setValue) { - if (this.isArray()) { - if (!Array.isArray(value)) { - throw new Error("invalid array value"); - } - if (this.arrayLength !== -1 && value.length !== this.arrayLength) { - throw new Error("array is wrong length"); - } - const childType = this.arrayChildren; - const result2 = value.slice(); - result2.forEach((value2, index2) => { - var _a2; - __privateMethod(_a2 = childType, _ParamType_instances, walkAsync_fn).call(_a2, promises, value2, process2, (value3) => { - result2[index2] = value3; - }); + if (recentConnectorId) + scores[recentConnectorId] = 0; + const sorted = Object.keys(scores).length > 0 ? ( + // .toSorted() + [...connectors].sort((a2, b2) => (scores[a2.id] ?? 10) - (scores[b2.id] ?? 10)) + ) : connectors; + let connected = false; + const connections = []; + const providers = []; + for (const connector of sorted) { + const provider2 = await connector.getProvider().catch(() => void 0); + if (!provider2) + continue; + if (providers.some((x2) => x2 === provider2)) + continue; + const isAuthorized = await connector.isAuthorized(); + if (!isAuthorized) + continue; + const data = await connector.connect({ isReconnecting: true }).catch(() => null); + if (!data) + continue; + connector.emitter.off("connect", config2._internal.events.connect); + connector.emitter.on("change", config2._internal.events.change); + connector.emitter.on("disconnect", config2._internal.events.disconnect); + config2.setState((x2) => { + const connections2 = new Map(connected ? x2.connections : /* @__PURE__ */ new Map()).set(connector.uid, { accounts: data.accounts, chainId: data.chainId, connector }); + return { + ...x2, + current: connected ? x2.current : connector.uid, + connections: connections2 + }; }); - setValue(result2); - return; - } - if (this.isTuple()) { - const components = this.components; - let result2; - if (Array.isArray(value)) { - result2 = value.slice(); - } else { - if (value == null || typeof value !== "object") { - throw new Error("invalid tuple value"); - } - result2 = components.map((param) => { - if (!param.name) { - throw new Error("cannot use object value with unnamed components"); - } - if (!(param.name in value)) { - throw new Error(`missing value for component ${param.name}`); - } - return value[param.name]; - }); - } - if (result2.length !== this.components.length) { - throw new Error("array is wrong length"); - } - result2.forEach((value2, index2) => { - var _a2; - __privateMethod(_a2 = components[index2], _ParamType_instances, walkAsync_fn).call(_a2, promises, value2, process2, (value3) => { - result2[index2] = value3; - }); + connections.push({ + accounts: data.accounts, + chainId: data.chainId, + connector }); - setValue(result2); - return; - } - const result = process2(this.type, value); - if (result.then) { - promises.push(async function() { - setValue(await result); - }()); - } else { - setValue(result); + providers.push(provider2); + connected = true; } -}; -let ParamType = _ParamType; -class Fragment { - /** - * @private - */ - constructor(guard2, type, inputs) { - /** - * The type of the fragment. - */ - __publicField(this, "type"); - /** - * The inputs for the fragment. - */ - __publicField(this, "inputs"); - assertPrivate(guard2, _guard$2, "Fragment"); - inputs = Object.freeze(inputs.slice()); - defineProperties$1(this, { type, inputs }); + if (config2.state.status === "reconnecting" || config2.state.status === "connecting") { + if (!connected) + config2.setState((x2) => ({ + ...x2, + connections: /* @__PURE__ */ new Map(), + current: null, + status: "disconnected" + })); + else + config2.setState((x2) => ({ ...x2, status: "connected" })); } - /** - * Creates a new **Fragment** for %%obj%%, wich can be any supported - * ABI frgament type. - */ - static from(obj) { - if (typeof obj === "string") { - try { - Fragment.from(JSON.parse(obj)); - } catch (e2) { - } - return Fragment.from(lex(obj)); - } - if (obj instanceof TokenString) { - const type = obj.peekKeyword(KwTypes); - switch (type) { - case "constructor": - return ConstructorFragment.from(obj); - case "error": - return ErrorFragment.from(obj); - case "event": - return EventFragment.from(obj); - case "fallback": - case "receive": - return FallbackFragment.from(obj); - case "function": - return FunctionFragment.from(obj); - case "struct": - return StructFragment.from(obj); - } - } else if (typeof obj === "object") { - switch (obj.type) { - case "constructor": - return ConstructorFragment.from(obj); - case "error": - return ErrorFragment.from(obj); - case "event": - return EventFragment.from(obj); - case "fallback": - case "receive": - return FallbackFragment.from(obj); - case "function": - return FunctionFragment.from(obj); - case "struct": - return StructFragment.from(obj); - } - assert(false, `unsupported type: ${obj.type}`, "UNSUPPORTED_OPERATION", { - operation: "Fragment.from" + isReconnecting = false; + return connections; +} +async function sendTransaction(config2, parameters) { + const { account: account2, chainId, connector, gas: gas_, ...rest } = parameters; + let client2; + if (typeof account2 === "object" && account2.type === "local") + client2 = config2.getClient({ chainId }); + else + client2 = await getConnectorClient(config2, { account: account2, chainId, connector }); + const { connector: activeConnector } = getAccount$1(config2); + const gas = await (async () => { + var _a2; + if (!("data" in parameters) || !parameters.data) + return void 0; + if ((_a2 = connector ?? activeConnector) == null ? void 0 : _a2.supportsSimulation) + return void 0; + if (gas_ === null) + return void 0; + if (gas_ === void 0) { + const action2 = getAction(client2, estimateGas, "estimateGas"); + return action2({ + ...rest, + account: account2, + chain: chainId ? { id: chainId } : null }); } - assertArgument(false, "unsupported frgament object", "obj", obj); - } - /** - * Returns true if %%value%% is a [[ConstructorFragment]]. - */ - static isConstructor(value) { - return ConstructorFragment.isFragment(value); - } - /** - * Returns true if %%value%% is an [[ErrorFragment]]. - */ - static isError(value) { - return ErrorFragment.isFragment(value); - } - /** - * Returns true if %%value%% is an [[EventFragment]]. - */ - static isEvent(value) { - return EventFragment.isFragment(value); + return gas_; + })(); + const action = getAction(client2, sendTransaction$1, "sendTransaction"); + const hash2 = await action({ + ...rest, + ...account2 ? { account: account2 } : {}, + gas, + chain: chainId ? { id: chainId } : null + }); + return hash2; +} +async function simulateContract(config2, parameters) { + const { abi: abi2, chainId, connector, ...rest } = parameters; + let account2; + if (parameters.account) + account2 = parameters.account; + else { + const connectorClient = await getConnectorClient(config2, { + chainId, + connector + }); + account2 = connectorClient.account; } - /** - * Returns true if %%value%% is a [[FunctionFragment]]. - */ - static isFunction(value) { - return FunctionFragment.isFragment(value); + const client2 = config2.getClient({ chainId }); + const action = getAction(client2, simulateContract$1, "simulateContract"); + const { result, request } = await action({ ...rest, abi: abi2, account: account2 }); + return { + chainId: client2.chain.id, + result, + request: { __mode: "prepared", ...request, chainId } + }; +} +class ProviderNotFoundError extends BaseError$1 { + constructor() { + super("Provider not found."); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ProviderNotFoundError" + }); } - /** - * Returns true if %%value%% is a [[StructFragment]]. - */ - static isStruct(value) { - return StructFragment.isFragment(value); +} +class SwitchChainNotSupportedError extends BaseError$1 { + constructor({ connector }) { + super(`"${connector.name}" does not support programmatic chain switching.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "SwitchChainNotSupportedError" + }); } } -class NamedFragment extends Fragment { - /** - * @private - */ - constructor(guard2, type, name2, inputs) { - super(guard2, type, inputs); - /** - * The name of the fragment. - */ - __publicField(this, "name"); - assertArgument(typeof name2 === "string" && name2.match(regexId), "invalid identifier", "name", name2); - inputs = Object.freeze(inputs.slice()); - defineProperties$1(this, { name: name2 }); +async function switchChain(config2, parameters) { + var _a2; + const { addEthereumChainParameter, chainId } = parameters; + const connection = config2.state.connections.get(((_a2 = parameters.connector) == null ? void 0 : _a2.uid) ?? config2.state.current); + if (connection) { + const connector = connection.connector; + if (!connector.switchChain) + throw new SwitchChainNotSupportedError({ connector }); + const chain2 = await connector.switchChain({ + addEthereumChainParameter, + chainId + }); + return chain2; } + const chain = config2.chains.find((x2) => x2.id === chainId); + if (!chain) + throw new ChainNotConfiguredError(); + config2.setState((x2) => ({ ...x2, chainId })); + return chain; } -function joinParams(format2, params) { - return "(" + params.map((p2) => p2.format(format2)).join(format2 === "full" ? ", " : ",") + ")"; +function watchAccount(config2, parameters) { + const { onChange } = parameters; + return config2.subscribe(() => getAccount$1(config2), onChange, { + equalityFn(a2, b2) { + const { connector: aConnector, ...aRest } = a2; + const { connector: bConnector, ...bRest } = b2; + return deepEqual$1(aRest, bRest) && // check connector separately + (aConnector == null ? void 0 : aConnector.id) === (bConnector == null ? void 0 : bConnector.id) && (aConnector == null ? void 0 : aConnector.uid) === (bConnector == null ? void 0 : bConnector.uid); + } + }); } -class ErrorFragment extends NamedFragment { - /** - * @private - */ - constructor(guard2, name2, inputs) { - super(guard2, "error", name2, inputs); - Object.defineProperty(this, internal$1, { value: ErrorFragmentInternal }); - } - /** - * The Custom Error selector. - */ - get selector() { - return id$1(this.format("sighash")).substring(0, 10); - } - /** - * Returns a string representation of this fragment as %%format%%. - */ - format(format2) { - if (format2 == null) { - format2 = "sighash"; +function watchChainId(config2, parameters) { + const { onChange } = parameters; + return config2.subscribe((state) => state.chainId, onChange); +} +function watchConnections(config2, parameters) { + const { onChange } = parameters; + return config2.subscribe(() => getConnections(config2), onChange, { + equalityFn: deepEqual$1 + }); +} +function watchConnectors(config2, parameters) { + const { onChange } = parameters; + return config2._internal.connectors.subscribe((connectors, prevConnectors) => { + onChange(Object.values(connectors), prevConnectors); + }); +} +function watchPublicClient(config2, parameters) { + const { onChange } = parameters; + return config2.subscribe(() => getPublicClient(config2), onChange, { + equalityFn(a2, b2) { + return (a2 == null ? void 0 : a2.uid) === (b2 == null ? void 0 : b2.uid); } - if (format2 === "json") { - return JSON.stringify({ - type: "error", - name: this.name, - inputs: this.inputs.map((input2) => JSON.parse(input2.format(format2))) - }); - } - const result = []; - if (format2 !== "sighash") { - result.push("error"); - } - result.push(this.name + joinParams(format2, this.inputs)); - return result.join(" "); - } - /** - * Returns a new **ErrorFragment** for %%obj%%. - */ - static from(obj) { - if (ErrorFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === "string") { - return ErrorFragment.from(lex(obj)); - } else if (obj instanceof TokenString) { - const name2 = consumeName("error", obj); - const inputs = consumeParams(obj); - consumeEoi(obj); - return new ErrorFragment(_guard$2, name2, inputs); - } - return new ErrorFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); - } - /** - * Returns ``true`` and provides a type guard if %%value%% is an - * **ErrorFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === ErrorFragmentInternal; - } + }); } -class EventFragment extends NamedFragment { - /** - * @private - */ - constructor(guard2, name2, inputs, anonymous) { - super(guard2, "event", name2, inputs); - /** - * Whether this event is anonymous. - */ - __publicField(this, "anonymous"); - Object.defineProperty(this, internal$1, { value: EventFragmentInternal }); - defineProperties$1(this, { anonymous }); - } - /** - * The Event topic hash. - */ - get topicHash() { - return id$1(this.format("sighash")); +async function writeContract(config2, parameters) { + const { account: account2, chainId, connector, __mode, ...rest } = parameters; + let client2; + if (typeof account2 === "object" && account2.type === "local") + client2 = config2.getClient({ chainId }); + else + client2 = await getConnectorClient(config2, { account: account2, chainId, connector }); + const { connector: activeConnector } = getAccount$1(config2); + let request; + if (__mode === "prepared" || (activeConnector == null ? void 0 : activeConnector.supportsSimulation)) + request = rest; + else { + const { request: simulateRequest } = await simulateContract(config2, { + ...rest, + account: account2, + chainId + }); + request = simulateRequest; } - /** - * Returns a string representation of this event as %%format%%. - */ - format(format2) { - if (format2 == null) { - format2 = "sighash"; + const action = getAction(client2, writeContract$1, "writeContract"); + const hash2 = await action({ + ...request, + ...account2 ? { account: account2 } : {}, + chain: chainId ? { id: chainId } : null + }); + return hash2; +} +function createConnector(createConnectorFn) { + return createConnectorFn; +} +const supportsSimulationIdRegex = /(rabby|trustwallet)/; +const targetMap = { + coinbaseWallet: { + id: "coinbaseWallet", + name: "Coinbase Wallet", + provider(window2) { + if (window2 == null ? void 0 : window2.coinbaseWalletExtension) + return window2.coinbaseWalletExtension; + return findProvider(window2, "isCoinbaseWallet"); } - if (format2 === "json") { - return JSON.stringify({ - type: "event", - anonymous: this.anonymous, - name: this.name, - inputs: this.inputs.map((i) => JSON.parse(i.format(format2))) + }, + metaMask: { + id: "metaMask", + name: "MetaMask", + provider(window2) { + return findProvider(window2, (provider2) => { + if (!provider2.isMetaMask) + return false; + if (provider2.isBraveWallet && !provider2._events && !provider2._state) + return false; + const flags = [ + "isApexWallet", + "isAvalanche", + "isBitKeep", + "isBlockWallet", + "isKuCoinWallet", + "isMathWallet", + "isOkxWallet", + "isOKExWallet", + "isOneInchIOSWallet", + "isOneInchAndroidWallet", + "isOpera", + "isPortal", + "isRabby", + "isTokenPocket", + "isTokenary", + "isZerion" + ]; + for (const flag of flags) + if (provider2[flag]) + return false; + return true; }); } - const result = []; - if (format2 !== "sighash") { - result.push("event"); - } - result.push(this.name + joinParams(format2, this.inputs)); - if (format2 !== "sighash" && this.anonymous) { - result.push("anonymous"); + }, + phantom: { + id: "phantom", + name: "Phantom", + provider(window2) { + var _a2, _b2; + if ((_a2 = window2 == null ? void 0 : window2.phantom) == null ? void 0 : _a2.ethereum) + return (_b2 = window2.phantom) == null ? void 0 : _b2.ethereum; + return findProvider(window2, "isPhantom"); } - return result.join(" "); - } - /** - * Return the topic hash for an event with %%name%% and %%params%%. - */ - static getTopicHash(name2, params) { - params = (params || []).map((p2) => ParamType.from(p2)); - const fragment = new EventFragment(_guard$2, name2, params, false); - return fragment.topicHash; } - /** - * Returns a new **EventFragment** for %%obj%%. - */ - static from(obj) { - if (EventFragment.isFragment(obj)) { - return obj; +}; +injected$1.type = "injected"; +function injected$1(parameters = {}) { + const { shimDisconnect = true, unstable_shimAsyncInject } = parameters; + function getTarget() { + const target = parameters.target; + if (typeof target === "function") { + const result = target(); + if (result) + return result; } - if (typeof obj === "string") { - try { - return EventFragment.from(lex(obj)); - } catch (error) { - assertArgument(false, "invalid event fragment", "obj", obj); + if (typeof target === "object") + return target; + if (typeof target === "string") + return { + ...targetMap[target] ?? { + id: target, + name: `${target[0].toUpperCase()}${target.slice(1)}`, + provider: `is${target[0].toUpperCase()}${target.slice(1)}` + } + }; + return { + id: "injected", + name: "Injected", + provider(window2) { + return window2 == null ? void 0 : window2.ethereum; } - } else if (obj instanceof TokenString) { - const name2 = consumeName("event", obj); - const inputs = consumeParams(obj, true); - const anonymous = !!consumeKeywords(obj, setify(["anonymous"])).has("anonymous"); - consumeEoi(obj); - return new EventFragment(_guard$2, name2, inputs, anonymous); - } - return new EventFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map((p2) => ParamType.from(p2, true)) : [], !!obj.anonymous); - } - /** - * Returns ``true`` and provides a type guard if %%value%% is an - * **EventFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === EventFragmentInternal; - } -} -class ConstructorFragment extends Fragment { - /** - * @private - */ - constructor(guard2, type, inputs, payable, gas) { - super(guard2, type, inputs); - /** - * Whether the constructor can receive an endowment. - */ - __publicField(this, "payable"); - /** - * The recommended gas limit for deployment or ``null``. - */ - __publicField(this, "gas"); - Object.defineProperty(this, internal$1, { value: ConstructorFragmentInternal }); - defineProperties$1(this, { payable, gas }); - } - /** - * Returns a string representation of this constructor as %%format%%. - */ - format(format2) { - assert(format2 != null && format2 !== "sighash", "cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { operation: "format(sighash)" }); - if (format2 === "json") { - return JSON.stringify({ - type: "constructor", - stateMutability: this.payable ? "payable" : "undefined", - payable: this.payable, - gas: this.gas != null ? this.gas : void 0, - inputs: this.inputs.map((i) => JSON.parse(i.format(format2))) - }); - } - const result = [`constructor${joinParams(format2, this.inputs)}`]; - if (this.payable) { - result.push("payable"); - } - if (this.gas != null) { - result.push(`@${this.gas.toString()}`); - } - return result.join(" "); + }; } - /** - * Returns a new **ConstructorFragment** for %%obj%%. - */ - static from(obj) { - if (ConstructorFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === "string") { - try { - return ConstructorFragment.from(lex(obj)); - } catch (error) { - assertArgument(false, "invalid constuctor fragment", "obj", obj); + let accountsChanged; + let chainChanged; + let connect2; + let disconnect2; + return createConnector((config2) => ({ + get icon() { + return getTarget().icon; + }, + get id() { + return getTarget().id; + }, + get name() { + return getTarget().name; + }, + get supportsSimulation() { + return supportsSimulationIdRegex.test(this.id.toLowerCase()); + }, + type: injected$1.type, + async setup() { + const provider2 = await this.getProvider(); + if (provider2 && parameters.target) { + if (!connect2) { + connect2 = this.onConnect.bind(this); + provider2.on("connect", connect2); + } + if (!accountsChanged) { + accountsChanged = this.onAccountsChanged.bind(this); + provider2.on("accountsChanged", accountsChanged); + } + } + }, + async connect({ chainId, isReconnecting: isReconnecting2 } = {}) { + var _a2, _b2, _c2, _d2, _e2, _f2; + const provider2 = await this.getProvider(); + if (!provider2) + throw new ProviderNotFoundError(); + let accounts = []; + if (isReconnecting2) + accounts = await this.getAccounts().catch(() => []); + else if (shimDisconnect) { + try { + const permissions = await provider2.request({ + method: "wallet_requestPermissions", + params: [{ eth_accounts: {} }] + }); + accounts = (_d2 = (_c2 = (_b2 = (_a2 = permissions[0]) == null ? void 0 : _a2.caveats) == null ? void 0 : _b2[0]) == null ? void 0 : _c2.value) == null ? void 0 : _d2.map((x2) => getAddress$1(x2)); + if (accounts.length > 0) { + const sortedAccounts = await this.getAccounts(); + accounts = sortedAccounts; + } + } catch (err) { + const error = err; + if (error.code === UserRejectedRequestError.code) + throw new UserRejectedRequestError(error); + if (error.code === ResourceUnavailableRpcError.code) + throw error; + } } - } else if (obj instanceof TokenString) { - consumeKeywords(obj, setify(["constructor"])); - const inputs = consumeParams(obj); - const payable = !!consumeKeywords(obj, KwVisibDeploy).has("payable"); - const gas = consumeGas(obj); - consumeEoi(obj); - return new ConstructorFragment(_guard$2, "constructor", inputs, payable, gas); - } - return new ConstructorFragment(_guard$2, "constructor", obj.inputs ? obj.inputs.map(ParamType.from) : [], !!obj.payable, obj.gas != null ? obj.gas : null); - } - /** - * Returns ``true`` and provides a type guard if %%value%% is a - * **ConstructorFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === ConstructorFragmentInternal; - } -} -class FallbackFragment extends Fragment { - constructor(guard2, inputs, payable) { - super(guard2, "fallback", inputs); - /** - * If the function can be sent value during invocation. - */ - __publicField(this, "payable"); - Object.defineProperty(this, internal$1, { value: FallbackFragmentInternal }); - defineProperties$1(this, { payable }); - } - /** - * Returns a string representation of this fallback as %%format%%. - */ - format(format2) { - const type = this.inputs.length === 0 ? "receive" : "fallback"; - if (format2 === "json") { - const stateMutability = this.payable ? "payable" : "nonpayable"; - return JSON.stringify({ type, stateMutability }); - } - return `${type}()${this.payable ? " payable" : ""}`; - } - /** - * Returns a new **FallbackFragment** for %%obj%%. - */ - static from(obj) { - if (FallbackFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === "string") { try { - return FallbackFragment.from(lex(obj)); - } catch (error) { - assertArgument(false, "invalid fallback fragment", "obj", obj); + if (!(accounts == null ? void 0 : accounts.length) && !isReconnecting2) { + const requestedAccounts = await provider2.request({ + method: "eth_requestAccounts" + }); + accounts = requestedAccounts.map((x2) => getAddress$1(x2)); + } + if (connect2) { + provider2.removeListener("connect", connect2); + connect2 = void 0; + } + if (!accountsChanged) { + accountsChanged = this.onAccountsChanged.bind(this); + provider2.on("accountsChanged", accountsChanged); + } + if (!chainChanged) { + chainChanged = this.onChainChanged.bind(this); + provider2.on("chainChanged", chainChanged); + } + if (!disconnect2) { + disconnect2 = this.onDisconnect.bind(this); + provider2.on("disconnect", disconnect2); + } + let currentChainId = await this.getChainId(); + if (chainId && currentChainId !== chainId) { + const chain = await this.switchChain({ chainId }).catch((error) => { + if (error.code === UserRejectedRequestError.code) + throw error; + return { id: currentChainId }; + }); + currentChainId = (chain == null ? void 0 : chain.id) ?? currentChainId; + } + if (shimDisconnect) + await ((_e2 = config2.storage) == null ? void 0 : _e2.removeItem(`${this.id}.disconnected`)); + if (!parameters.target) + await ((_f2 = config2.storage) == null ? void 0 : _f2.setItem("injected.connected", true)); + return { accounts, chainId: currentChainId }; + } catch (err) { + const error = err; + if (error.code === UserRejectedRequestError.code) + throw new UserRejectedRequestError(error); + if (error.code === ResourceUnavailableRpcError.code) + throw new ResourceUnavailableRpcError(error); + throw error; } - } else if (obj instanceof TokenString) { - const errorObj = obj.toString(); - const topIsValid = obj.peekKeyword(setify(["fallback", "receive"])); - assertArgument(topIsValid, "type must be fallback or receive", "obj", errorObj); - const type = obj.popKeyword(setify(["fallback", "receive"])); - if (type === "receive") { - const inputs2 = consumeParams(obj); - assertArgument(inputs2.length === 0, `receive cannot have arguments`, "obj.inputs", inputs2); - consumeKeywords(obj, setify(["payable"])); - consumeEoi(obj); - return new FallbackFragment(_guard$2, [], true); + }, + async disconnect() { + var _a2, _b2; + const provider2 = await this.getProvider(); + if (!provider2) + throw new ProviderNotFoundError(); + if (chainChanged) { + provider2.removeListener("chainChanged", chainChanged); + chainChanged = void 0; } - let inputs = consumeParams(obj); - if (inputs.length) { - assertArgument(inputs.length === 1 && inputs[0].type === "bytes", "invalid fallback inputs", "obj.inputs", inputs.map((i) => i.format("minimal")).join(", ")); - } else { - inputs = [ParamType.from("bytes")]; + if (disconnect2) { + provider2.removeListener("disconnect", disconnect2); + disconnect2 = void 0; } - const mutability = consumeMutability(obj); - assertArgument(mutability === "nonpayable" || mutability === "payable", "fallback cannot be constants", "obj.stateMutability", mutability); - if (consumeKeywords(obj, setify(["returns"])).has("returns")) { - const outputs = consumeParams(obj); - assertArgument(outputs.length === 1 && outputs[0].type === "bytes", "invalid fallback outputs", "obj.outputs", outputs.map((i) => i.format("minimal")).join(", ")); + if (!connect2) { + connect2 = this.onConnect.bind(this); + provider2.on("connect", connect2); } - consumeEoi(obj); - return new FallbackFragment(_guard$2, inputs, mutability === "payable"); - } - if (obj.type === "receive") { - return new FallbackFragment(_guard$2, [], true); - } - if (obj.type === "fallback") { - const inputs = [ParamType.from("bytes")]; - const payable = obj.stateMutability === "payable"; - return new FallbackFragment(_guard$2, inputs, payable); - } - assertArgument(false, "invalid fallback description", "obj", obj); - } - /** - * Returns ``true`` and provides a type guard if %%value%% is a - * **FallbackFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === FallbackFragmentInternal; - } -} -class FunctionFragment extends NamedFragment { - /** - * @private - */ - constructor(guard2, name2, stateMutability, inputs, outputs, gas) { - super(guard2, "function", name2, inputs); - /** - * If the function is constant (e.g. ``pure`` or ``view`` functions). - */ - __publicField(this, "constant"); - /** - * The returned types for the result of calling this function. - */ - __publicField(this, "outputs"); - /** - * The state mutability (e.g. ``payable``, ``nonpayable``, ``view`` - * or ``pure``) - */ - __publicField(this, "stateMutability"); - /** - * If the function can be sent value during invocation. - */ - __publicField(this, "payable"); - /** - * The recommended gas limit to send when calling this function. - */ - __publicField(this, "gas"); - Object.defineProperty(this, internal$1, { value: FunctionFragmentInternal }); - outputs = Object.freeze(outputs.slice()); - const constant = stateMutability === "view" || stateMutability === "pure"; - const payable = stateMutability === "payable"; - defineProperties$1(this, { constant, gas, outputs, payable, stateMutability }); - } - /** - * The Function selector. - */ - get selector() { - return id$1(this.format("sighash")).substring(0, 10); - } - /** - * Returns a string representation of this function as %%format%%. - */ - format(format2) { - if (format2 == null) { - format2 = "sighash"; - } - if (format2 === "json") { - return JSON.stringify({ - type: "function", - name: this.name, - constant: this.constant, - stateMutability: this.stateMutability !== "nonpayable" ? this.stateMutability : void 0, - payable: this.payable, - gas: this.gas != null ? this.gas : void 0, - inputs: this.inputs.map((i) => JSON.parse(i.format(format2))), - outputs: this.outputs.map((o2) => JSON.parse(o2.format(format2))) - }); - } - const result = []; - if (format2 !== "sighash") { - result.push("function"); - } - result.push(this.name + joinParams(format2, this.inputs)); - if (format2 !== "sighash") { - if (this.stateMutability !== "nonpayable") { - result.push(this.stateMutability); + try { + await withTimeout(() => ( + // TODO: Remove explicit type for viem@3 + provider2.request({ + // `'wallet_revokePermissions'` added in `viem@2.10.3` + method: "wallet_revokePermissions", + params: [{ eth_accounts: {} }] + }) + ), { timeout: 100 }); + } catch { } - if (this.outputs && this.outputs.length) { - result.push("returns"); - result.push(joinParams(format2, this.outputs)); + if (shimDisconnect) { + await ((_a2 = config2.storage) == null ? void 0 : _a2.setItem(`${this.id}.disconnected`, true)); } - if (this.gas != null) { - result.push(`@${this.gas.toString()}`); + if (!parameters.target) + await ((_b2 = config2.storage) == null ? void 0 : _b2.removeItem("injected.connected")); + }, + async getAccounts() { + const provider2 = await this.getProvider(); + if (!provider2) + throw new ProviderNotFoundError(); + const accounts = await provider2.request({ method: "eth_accounts" }); + return accounts.map((x2) => getAddress$1(x2)); + }, + async getChainId() { + const provider2 = await this.getProvider(); + if (!provider2) + throw new ProviderNotFoundError(); + const hexChainId = await provider2.request({ method: "eth_chainId" }); + return Number(hexChainId); + }, + async getProvider() { + if (typeof window === "undefined") + return void 0; + let provider2; + const target = getTarget(); + if (typeof target.provider === "function") + provider2 = target.provider(window); + else if (typeof target.provider === "string") + provider2 = findProvider(window, target.provider); + else + provider2 = target.provider; + if (provider2 && !provider2.removeListener) { + if ("off" in provider2 && typeof provider2.off === "function") + provider2.removeListener = provider2.off; + else + provider2.removeListener = () => { + }; } - } - return result.join(" "); - } - /** - * Return the selector for a function with %%name%% and %%params%%. - */ - static getSelector(name2, params) { - params = (params || []).map((p2) => ParamType.from(p2)); - const fragment = new FunctionFragment(_guard$2, name2, "view", params, [], null); - return fragment.selector; - } - /** - * Returns a new **FunctionFragment** for %%obj%%. - */ - static from(obj) { - if (FunctionFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === "string") { + return provider2; + }, + async isAuthorized() { + var _a2, _b2; try { - return FunctionFragment.from(lex(obj)); - } catch (error) { - assertArgument(false, "invalid function fragment", "obj", obj); - } - } else if (obj instanceof TokenString) { - const name2 = consumeName("function", obj); - const inputs = consumeParams(obj); - const mutability = consumeMutability(obj); - let outputs = []; - if (consumeKeywords(obj, setify(["returns"])).has("returns")) { - outputs = consumeParams(obj); + const isDisconnected = shimDisconnect && // If shim exists in storage, connector is disconnected + await ((_a2 = config2.storage) == null ? void 0 : _a2.getItem(`${this.id}.disconnected`)); + if (isDisconnected) + return false; + if (!parameters.target) { + const connected = await ((_b2 = config2.storage) == null ? void 0 : _b2.getItem("injected.connected")); + if (!connected) + return false; + } + const provider2 = await this.getProvider(); + if (!provider2) { + if (unstable_shimAsyncInject !== void 0 && unstable_shimAsyncInject !== false) { + const handleEthereum = async () => { + if (typeof window !== "undefined") + window.removeEventListener("ethereum#initialized", handleEthereum); + const provider3 = await this.getProvider(); + return !!provider3; + }; + const timeout = typeof unstable_shimAsyncInject === "number" ? unstable_shimAsyncInject : 1e3; + const res = await Promise.race([ + ...typeof window !== "undefined" ? [ + new Promise((resolve) => window.addEventListener("ethereum#initialized", () => resolve(handleEthereum()), { once: true })) + ] : [], + new Promise((resolve) => setTimeout(() => resolve(handleEthereum()), timeout)) + ]); + if (res) + return true; + } + throw new ProviderNotFoundError(); + } + const accounts = await withRetry(() => this.getAccounts()); + return !!accounts.length; + } catch { + return false; } - const gas = consumeGas(obj); - consumeEoi(obj); - return new FunctionFragment(_guard$2, name2, mutability, inputs, outputs, gas); - } - let stateMutability = obj.stateMutability; - if (stateMutability == null) { - stateMutability = "payable"; - if (typeof obj.constant === "boolean") { - stateMutability = "view"; - if (!obj.constant) { - stateMutability = "payable"; - if (typeof obj.payable === "boolean" && !obj.payable) { - stateMutability = "nonpayable"; + }, + async switchChain({ addEthereumChainParameter, chainId }) { + var _a2, _b2, _c2, _d2; + const provider2 = await this.getProvider(); + if (!provider2) + throw new ProviderNotFoundError(); + const chain = config2.chains.find((x2) => x2.id === chainId); + if (!chain) + throw new SwitchChainError(new ChainNotConfiguredError()); + try { + await Promise.all([ + provider2.request({ + method: "wallet_switchEthereumChain", + params: [{ chainId: numberToHex(chainId) }] + }).then(async () => { + const currentChainId = await this.getChainId(); + if (currentChainId === chainId) + config2.emitter.emit("change", { chainId }); + }), + new Promise((resolve) => config2.emitter.once("change", ({ chainId: currentChainId }) => { + if (currentChainId === chainId) + resolve(); + })) + ]); + return chain; + } catch (err) { + const error = err; + if (error.code === 4902 || // Unwrapping for MetaMask Mobile + // https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719 + ((_b2 = (_a2 = error == null ? void 0 : error.data) == null ? void 0 : _a2.originalError) == null ? void 0 : _b2.code) === 4902) { + try { + const { default: blockExplorer, ...blockExplorers } = chain.blockExplorers ?? {}; + let blockExplorerUrls; + if (addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.blockExplorerUrls) + blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls; + else if (blockExplorer) + blockExplorerUrls = [ + blockExplorer.url, + ...Object.values(blockExplorers).map((x2) => x2.url) + ]; + let rpcUrls; + if ((_c2 = addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.rpcUrls) == null ? void 0 : _c2.length) + rpcUrls = addEthereumChainParameter.rpcUrls; + else + rpcUrls = [((_d2 = chain.rpcUrls.default) == null ? void 0 : _d2.http[0]) ?? ""]; + const addEthereumChain = { + blockExplorerUrls, + chainId: numberToHex(chainId), + chainName: (addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.chainName) ?? chain.name, + iconUrls: addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.iconUrls, + nativeCurrency: (addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.nativeCurrency) ?? chain.nativeCurrency, + rpcUrls + }; + await provider2.request({ + method: "wallet_addEthereumChain", + params: [addEthereumChain] + }); + const currentChainId = await this.getChainId(); + if (currentChainId !== chainId) + throw new UserRejectedRequestError(new Error("User rejected switch after adding network.")); + return chain; + } catch (error2) { + throw new UserRejectedRequestError(error2); } } - } else if (typeof obj.payable === "boolean" && !obj.payable) { - stateMutability = "nonpayable"; + if (error.code === UserRejectedRequestError.code) + throw new UserRejectedRequestError(error); + throw new SwitchChainError(error); + } + }, + async onAccountsChanged(accounts) { + var _a2; + if (accounts.length === 0) + this.onDisconnect(); + else if (config2.emitter.listenerCount("connect")) { + const chainId = (await this.getChainId()).toString(); + this.onConnect({ chainId }); + if (shimDisconnect) + await ((_a2 = config2.storage) == null ? void 0 : _a2.removeItem(`${this.id}.disconnected`)); + } else + config2.emitter.emit("change", { + accounts: accounts.map((x2) => getAddress$1(x2)) + }); + }, + onChainChanged(chain) { + const chainId = Number(chain); + config2.emitter.emit("change", { chainId }); + }, + async onConnect(connectInfo) { + const accounts = await this.getAccounts(); + if (accounts.length === 0) + return; + const chainId = Number(connectInfo.chainId); + config2.emitter.emit("connect", { accounts, chainId }); + const provider2 = await this.getProvider(); + if (provider2) { + if (connect2) { + provider2.removeListener("connect", connect2); + connect2 = void 0; + } + if (!accountsChanged) { + accountsChanged = this.onAccountsChanged.bind(this); + provider2.on("accountsChanged", accountsChanged); + } + if (!chainChanged) { + chainChanged = this.onChainChanged.bind(this); + provider2.on("chainChanged", chainChanged); + } + if (!disconnect2) { + disconnect2 = this.onDisconnect.bind(this); + provider2.on("disconnect", disconnect2); + } + } + }, + async onDisconnect(error) { + const provider2 = await this.getProvider(); + if (error && error.code === 1013) { + if (provider2 && !!(await this.getAccounts()).length) + return; + } + config2.emitter.emit("disconnect"); + if (provider2) { + if (chainChanged) { + provider2.removeListener("chainChanged", chainChanged); + chainChanged = void 0; + } + if (disconnect2) { + provider2.removeListener("disconnect", disconnect2); + disconnect2 = void 0; + } + if (!connect2) { + connect2 = this.onConnect.bind(this); + provider2.on("connect", connect2); + } } } - return new FunctionFragment(_guard$2, obj.name, stateMutability, obj.inputs ? obj.inputs.map(ParamType.from) : [], obj.outputs ? obj.outputs.map(ParamType.from) : [], obj.gas != null ? obj.gas : null); - } - /** - * Returns ``true`` and provides a type guard if %%value%% is a - * **FunctionFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === FunctionFragmentInternal; - } + })); } -class StructFragment extends NamedFragment { - /** - * @private - */ - constructor(guard2, name2, inputs) { - super(guard2, "struct", name2, inputs); - Object.defineProperty(this, internal$1, { value: StructFragmentInternal }); - } - /** - * Returns a string representation of this struct as %%format%%. - */ - format() { - throw new Error("@TODO"); +function findProvider(window2, select) { + function isProvider(provider2) { + if (typeof select === "function") + return select(provider2); + if (typeof select === "string") + return provider2[select]; + return true; } - /** - * Returns a new **StructFragment** for %%obj%%. - */ - static from(obj) { - if (typeof obj === "string") { - try { - return StructFragment.from(lex(obj)); - } catch (error) { - assertArgument(false, "invalid struct fragment", "obj", obj); - } - } else if (obj instanceof TokenString) { - const name2 = consumeName("struct", obj); - const inputs = consumeParams(obj); - consumeEoi(obj); - return new StructFragment(_guard$2, name2, inputs); + const ethereum = window2.ethereum; + if (ethereum == null ? void 0 : ethereum.providers) + return ethereum.providers.find((provider2) => isProvider(provider2)); + if (ethereum && isProvider(ethereum)) + return ethereum; + return void 0; +} +function requestProviders(listener) { + if (typeof window === "undefined") + return; + const handler = (event) => listener(event.detail); + window.addEventListener("eip6963:announceProvider", handler); + window.dispatchEvent(new CustomEvent("eip6963:requestProvider")); + return () => window.removeEventListener("eip6963:announceProvider", handler); +} +function createStore$1() { + const listeners = /* @__PURE__ */ new Set(); + let providerDetails = []; + const request = () => requestProviders((providerDetail) => { + if (providerDetails.some(({ info }) => info.uuid === providerDetail.info.uuid)) + return; + providerDetails = [...providerDetails, providerDetail]; + listeners.forEach((listener) => listener(providerDetails, { added: [providerDetail] })); + }); + let unwatch = request(); + return { + _listeners() { + return listeners; + }, + clear() { + listeners.forEach((listener) => listener([], { removed: [...providerDetails] })); + providerDetails = []; + }, + destroy() { + this.clear(); + listeners.clear(); + unwatch == null ? void 0 : unwatch(); + }, + findProvider({ rdns }) { + return providerDetails.find((providerDetail) => providerDetail.info.rdns === rdns); + }, + getProviders() { + return providerDetails; + }, + reset() { + this.clear(); + unwatch == null ? void 0 : unwatch(); + unwatch = request(); + }, + subscribe(listener, { emitImmediately } = {}) { + listeners.add(listener); + if (emitImmediately) + listener(providerDetails, { added: providerDetails }); + return () => listeners.delete(listener); } - return new StructFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); - } - // @TODO: fix this return type - /** - * Returns ``true`` and provides a type guard if %%value%% is a - * **StructFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === StructFragmentInternal; - } + }; } -const PanicReasons$1 = /* @__PURE__ */ new Map(); -PanicReasons$1.set(0, "GENERIC_PANIC"); -PanicReasons$1.set(1, "ASSERT_FALSE"); -PanicReasons$1.set(17, "OVERFLOW"); -PanicReasons$1.set(18, "DIVIDE_BY_ZERO"); -PanicReasons$1.set(33, "ENUM_RANGE_ERROR"); -PanicReasons$1.set(34, "BAD_STORAGE_DATA"); -PanicReasons$1.set(49, "STACK_UNDERFLOW"); -PanicReasons$1.set(50, "ARRAY_RANGE_ERROR"); -PanicReasons$1.set(65, "OUT_OF_MEMORY"); -PanicReasons$1.set(81, "UNINITIALIZED_FUNCTION_CALL"); -const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); -const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); -let defaultCoder = null; -let defaultMaxInflation = 1024; -function getBuiltinCallException(action, tx, data, abiCoder) { - let message = "missing revert data"; - let reason = null; - const invocation = null; - let revert = null; - if (data) { - message = "execution reverted"; - const bytes2 = getBytes(data); - data = hexlify(data); - if (bytes2.length === 0) { - message += " (no data present; likely require(false) occurred"; - reason = "require(false)"; - } else if (bytes2.length % 32 !== 4) { - message += " (could not decode reason; invalid data length)"; - } else if (hexlify(bytes2.slice(0, 4)) === "0x08c379a0") { - try { - reason = abiCoder.decode(["string"], bytes2.slice(4))[0]; - revert = { - signature: "Error(string)", - name: "Error", - args: [reason] - }; - message += `: ${JSON.stringify(reason)}`; - } catch (error) { - message += " (could not decode reason; invalid string data)"; - } - } else if (hexlify(bytes2.slice(0, 4)) === "0x4e487b71") { - try { - const code2 = Number(abiCoder.decode(["uint256"], bytes2.slice(4))[0]); - revert = { - signature: "Panic(uint256)", - name: "Panic", - args: [code2] - }; - reason = `Panic due to ${PanicReasons$1.get(code2) || "UNKNOWN"}(${code2})`; - message += `: ${reason}`; - } catch (error) { - message += " (could not decode panic code)"; +const __vite_import_meta_env__$1 = { "BASE_URL": "./", "DEV": false, "MODE": "production", "PROD": true, "SSR": false }; +const subscribeWithSelectorImpl = (fn) => (set, get2, api2) => { + const origSubscribe = api2.subscribe; + api2.subscribe = (selector2, optListener, options) => { + let listener = selector2; + if (optListener) { + const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is; + let currentSlice = selector2(api2.getState()); + listener = (state) => { + const nextSlice = selector2(state); + if (!equalityFn(currentSlice, nextSlice)) { + const previousSlice = currentSlice; + optListener(currentSlice = nextSlice, previousSlice); + } + }; + if (options == null ? void 0 : options.fireImmediately) { + optListener(currentSlice, currentSlice); } - } else { - message += " (unknown custom error)"; } - } - const transaction2 = { - to: tx.to ? getAddress$1(tx.to) : null, - data: tx.data || "0x" + return origSubscribe(listener); }; - if (tx.from) { - transaction2.from = getAddress$1(tx.from); - } - return makeError(message, "CALL_EXCEPTION", { - action, - data, - reason, - transaction: transaction2, - invocation, - revert - }); -} -const _AbiCoder = class _AbiCoder { - constructor() { - __privateAdd(this, _AbiCoder_instances); - } - /** - * Get the default values for the given %%types%%. - * - * For example, a ``uint`` is by default ``0`` and ``bool`` - * is by default ``false``. - */ - getDefaultValue(types2) { - const coders2 = types2.map((type) => __privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, ParamType.from(type))); - const coder = new TupleCoder(coders2, "_"); - return coder.defaultValue(); + const initialState = fn(set, get2, api2); + return initialState; +}; +const subscribeWithSelector = subscribeWithSelectorImpl; +function createJSONStorage(getStorage, options) { + let storage; + try { + storage = getStorage(); + } catch (e2) { + return; } - /** - * Encode the %%values%% as the %%types%% into ABI data. - * - * @returns DataHexstring - */ - encode(types2, values) { - assertArgumentCount(values.length, types2.length, "types/values length mismatch"); - const coders2 = types2.map((type) => __privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, ParamType.from(type))); - const coder = new TupleCoder(coders2, "_"); - const writer = new Writer(); - coder.encode(writer, values); - return writer.data; - } - /** - * Decode the ABI %%data%% as the %%types%% into values. - * - * If %%loose%% decoding is enabled, then strict padding is - * not enforced. Some older versions of Solidity incorrectly - * padded event data emitted from ``external`` functions. - */ - decode(types2, data, loose) { - const coders2 = types2.map((type) => __privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, ParamType.from(type))); - const coder = new TupleCoder(coders2, "_"); - return coder.decode(new Reader(data, loose, defaultMaxInflation)); - } - static _setDefaultMaxInflation(value) { - assertArgument(typeof value === "number" && Number.isInteger(value), "invalid defaultMaxInflation factor", "value", value); - defaultMaxInflation = value; - } - /** - * Returns the shared singleton instance of a default [[AbiCoder]]. - * - * On the first call, the instance is created internally. - */ - static defaultAbiCoder() { - if (defaultCoder == null) { - defaultCoder = new _AbiCoder(); + const persistStorage = { + getItem: (name2) => { + var _a2; + const parse2 = (str2) => { + if (str2 === null) { + return null; + } + return JSON.parse(str2, void 0); + }; + const str = (_a2 = storage.getItem(name2)) != null ? _a2 : null; + if (str instanceof Promise) { + return str.then(parse2); + } + return parse2(str); + }, + setItem: (name2, newValue) => storage.setItem( + name2, + JSON.stringify(newValue, void 0) + ), + removeItem: (name2) => storage.removeItem(name2) + }; + return persistStorage; +} +const toThenable = (fn) => (input2) => { + try { + const result = fn(input2); + if (result instanceof Promise) { + return result; } - return defaultCoder; - } - /** - * Returns an ethers-compatible [[CallExceptionError]] Error for the given - * result %%data%% for the [[CallExceptionAction]] %%action%% against - * the Transaction %%tx%%. - */ - static getBuiltinCallException(action, tx, data) { - return getBuiltinCallException(action, tx, data, _AbiCoder.defaultAbiCoder()); + return { + then(onFulfilled) { + return toThenable(onFulfilled)(result); + }, + catch(_onRejected) { + return this; + } + }; + } catch (e2) { + return { + then(_onFulfilled) { + return this; + }, + catch(onRejected) { + return toThenable(onRejected)(e2); + } + }; } }; -_AbiCoder_instances = new WeakSet(); -getCoder_fn = function(param) { - if (param.isArray()) { - return new ArrayCoder(__privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, param.arrayChildren), param.arrayLength, param.name); +const oldImpl = (config2, baseOptions) => (set, get2, api2) => { + let options = { + getStorage: () => localStorage, + serialize: JSON.stringify, + deserialize: JSON.parse, + partialize: (state) => state, + version: 0, + merge: (persistedState, currentState) => ({ + ...currentState, + ...persistedState + }), + ...baseOptions + }; + let hasHydrated = false; + const hydrationListeners = /* @__PURE__ */ new Set(); + const finishHydrationListeners = /* @__PURE__ */ new Set(); + let storage; + try { + storage = options.getStorage(); + } catch (e2) { } - if (param.isTuple()) { - return new TupleCoder(param.components.map((c2) => __privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, c2)), param.name); + if (!storage) { + return config2( + (...args) => { + console.warn( + `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.` + ); + set(...args); + }, + get2, + api2 + ); } - switch (param.baseType) { - case "address": - return new AddressCoder(param.name); - case "bool": - return new BooleanCoder(param.name); - case "string": - return new StringCoder(param.name); - case "bytes": - return new BytesCoder(param.name); - case "": - return new NullCoder(param.name); + const thenableSerialize = toThenable(options.serialize); + const setItem = () => { + const state = options.partialize({ ...get2() }); + let errorInSync; + const thenable = thenableSerialize({ state, version: options.version }).then( + (serializedValue) => storage.setItem(options.name, serializedValue) + ).catch((e2) => { + errorInSync = e2; + }); + if (errorInSync) { + throw errorInSync; + } + return thenable; + }; + const savedSetState = api2.setState; + api2.setState = (state, replace) => { + savedSetState(state, replace); + void setItem(); + }; + const configResult = config2( + (...args) => { + set(...args); + void setItem(); + }, + get2, + api2 + ); + let stateFromStorage; + const hydrate2 = () => { + var _a2; + if (!storage) + return; + hasHydrated = false; + hydrationListeners.forEach((cb2) => cb2(get2())); + const postRehydrationCallback = ((_a2 = options.onRehydrateStorage) == null ? void 0 : _a2.call(options, get2())) || void 0; + return toThenable(storage.getItem.bind(storage))(options.name).then((storageValue) => { + if (storageValue) { + return options.deserialize(storageValue); + } + }).then((deserializedStorageValue) => { + if (deserializedStorageValue) { + if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) { + if (options.migrate) { + return options.migrate( + deserializedStorageValue.state, + deserializedStorageValue.version + ); + } + console.error( + `State loaded from storage couldn't be migrated since no migrate function was provided` + ); + } else { + return deserializedStorageValue.state; + } + } + }).then((migratedState) => { + var _a22; + stateFromStorage = options.merge( + migratedState, + (_a22 = get2()) != null ? _a22 : configResult + ); + set(stateFromStorage, true); + return setItem(); + }).then(() => { + postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0); + hasHydrated = true; + finishHydrationListeners.forEach((cb2) => cb2(stateFromStorage)); + }).catch((e2) => { + postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e2); + }); + }; + api2.persist = { + setOptions: (newOptions) => { + options = { + ...options, + ...newOptions + }; + if (newOptions.getStorage) { + storage = newOptions.getStorage(); + } + }, + clearStorage: () => { + storage == null ? void 0 : storage.removeItem(options.name); + }, + getOptions: () => options, + rehydrate: () => hydrate2(), + hasHydrated: () => hasHydrated, + onHydrate: (cb2) => { + hydrationListeners.add(cb2); + return () => { + hydrationListeners.delete(cb2); + }; + }, + onFinishHydration: (cb2) => { + finishHydrationListeners.add(cb2); + return () => { + finishHydrationListeners.delete(cb2); + }; + } + }; + hydrate2(); + return stateFromStorage || configResult; +}; +const newImpl = (config2, baseOptions) => (set, get2, api2) => { + let options = { + storage: createJSONStorage(() => localStorage), + partialize: (state) => state, + version: 0, + merge: (persistedState, currentState) => ({ + ...currentState, + ...persistedState + }), + ...baseOptions + }; + let hasHydrated = false; + const hydrationListeners = /* @__PURE__ */ new Set(); + const finishHydrationListeners = /* @__PURE__ */ new Set(); + let storage = options.storage; + if (!storage) { + return config2( + (...args) => { + console.warn( + `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.` + ); + set(...args); + }, + get2, + api2 + ); } - let match = param.type.match(paramTypeNumber); - if (match) { - let size2 = parseInt(match[2] || "256"); - assertArgument(size2 !== 0 && size2 <= 256 && size2 % 8 === 0, "invalid " + match[1] + " bit length", "param", param); - return new NumberCoder(size2 / 8, match[1] === "int", param.name); + const setItem = () => { + const state = options.partialize({ ...get2() }); + return storage.setItem(options.name, { + state, + version: options.version + }); + }; + const savedSetState = api2.setState; + api2.setState = (state, replace) => { + savedSetState(state, replace); + void setItem(); + }; + const configResult = config2( + (...args) => { + set(...args); + void setItem(); + }, + get2, + api2 + ); + let stateFromStorage; + const hydrate2 = () => { + var _a2, _b2; + if (!storage) + return; + hasHydrated = false; + hydrationListeners.forEach((cb2) => { + var _a22; + return cb2((_a22 = get2()) != null ? _a22 : configResult); + }); + const postRehydrationCallback = ((_b2 = options.onRehydrateStorage) == null ? void 0 : _b2.call(options, (_a2 = get2()) != null ? _a2 : configResult)) || void 0; + return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => { + if (deserializedStorageValue) { + if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) { + if (options.migrate) { + return options.migrate( + deserializedStorageValue.state, + deserializedStorageValue.version + ); + } + console.error( + `State loaded from storage couldn't be migrated since no migrate function was provided` + ); + } else { + return deserializedStorageValue.state; + } + } + }).then((migratedState) => { + var _a22; + stateFromStorage = options.merge( + migratedState, + (_a22 = get2()) != null ? _a22 : configResult + ); + set(stateFromStorage, true); + return setItem(); + }).then(() => { + postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0); + stateFromStorage = get2(); + hasHydrated = true; + finishHydrationListeners.forEach((cb2) => cb2(stateFromStorage)); + }).catch((e2) => { + postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e2); + }); + }; + api2.persist = { + setOptions: (newOptions) => { + options = { + ...options, + ...newOptions + }; + if (newOptions.storage) { + storage = newOptions.storage; + } + }, + clearStorage: () => { + storage == null ? void 0 : storage.removeItem(options.name); + }, + getOptions: () => options, + rehydrate: () => hydrate2(), + hasHydrated: () => hasHydrated, + onHydrate: (cb2) => { + hydrationListeners.add(cb2); + return () => { + hydrationListeners.delete(cb2); + }; + }, + onFinishHydration: (cb2) => { + finishHydrationListeners.add(cb2); + return () => { + finishHydrationListeners.delete(cb2); + }; + } + }; + if (!options.skipHydration) { + hydrate2(); } - match = param.type.match(paramTypeBytes); - if (match) { - let size2 = parseInt(match[1]); - assertArgument(size2 !== 0 && size2 <= 32, "invalid bytes length", "param", param); - return new FixedBytesCoder(size2, param.name); + return stateFromStorage || configResult; +}; +const persistImpl = (config2, baseOptions) => { + if ("getStorage" in baseOptions || "serialize" in baseOptions || "deserialize" in baseOptions) { + if ((__vite_import_meta_env__$1 ? "production" : void 0) !== "production") { + console.warn( + "[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead." + ); + } + return oldImpl(config2, baseOptions); } - assertArgument(false, "invalid type", "type", param.type); + return newImpl(config2, baseOptions); }; -let AbiCoder = _AbiCoder; -function encodeBytes32String(text2) { - const bytes2 = toUtf8Bytes(text2); - if (bytes2.length > 31) { - throw new Error("bytes32 string must be less than 32 bytes"); +const persist = persistImpl; +const __vite_import_meta_env__ = { "BASE_URL": "./", "DEV": false, "MODE": "production", "PROD": true, "SSR": false }; +const createStoreImpl = (createState2) => { + let state; + const listeners = /* @__PURE__ */ new Set(); + const setState = (partial, replace) => { + const nextState = typeof partial === "function" ? partial(state) : partial; + if (!Object.is(nextState, state)) { + const previousState = state; + state = (replace != null ? replace : typeof nextState !== "object") ? nextState : Object.assign({}, state, nextState); + listeners.forEach((listener) => listener(state, previousState)); + } + }; + const getState2 = () => state; + const subscribe = (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }; + const destroy = () => { + if ((__vite_import_meta_env__ ? "production" : void 0) !== "production") { + console.warn( + "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected." + ); + } + listeners.clear(); + }; + const api2 = { setState, getState: getState2, subscribe, destroy }; + state = createState2(setState, getState2, api2); + return api2; +}; +const createStore = (createState2) => createState2 ? createStoreImpl(createState2) : createStoreImpl; +var eventemitter3 = { exports: {} }; +(function(module2) { + var has = Object.prototype.hasOwnProperty, prefix = "~"; + function Events() { } - return zeroPadBytes(bytes2, 32); -} -function decodeBytes32String(_bytes) { - const data = getBytes(_bytes, "bytes"); - if (data.length !== 32) { - throw new Error("invalid bytes32 - not 32 bytes long"); + if (Object.create) { + Events.prototype = /* @__PURE__ */ Object.create(null); + if (!new Events().__proto__) prefix = false; } - if (data[31] !== 0) { - throw new Error("invalid bytes32 string - no null terminator"); + function EE(fn, context2, once) { + this.fn = fn; + this.context = context2; + this.once = once || false; } - let length = 31; - while (data[length - 1] === 0) { - length--; + function addListener(emitter, event, fn, context2, once) { + if (typeof fn !== "function") { + throw new TypeError("The listener must be a function"); + } + var listener = new EE(fn, context2 || emitter, once), evt = prefix ? prefix + event : event; + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + return emitter; } - return toUtf8String(data.slice(0, length)); -} -class LogDescription { - /** - * @_ignore: - */ - constructor(fragment, topic, args) { - /** - * The matching fragment for the ``topic0``. - */ - __publicField(this, "fragment"); - /** - * The name of the Event. - */ - __publicField(this, "name"); - /** - * The full Event signature. - */ - __publicField(this, "signature"); - /** - * The topic hash for the Event. - */ - __publicField(this, "topic"); - /** - * The arguments passed into the Event with ``emit``. - */ - __publicField(this, "args"); - const name2 = fragment.name, signature2 = fragment.format(); - defineProperties$1(this, { - fragment, - name: name2, - signature: signature2, - topic, - args - }); + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; } -} -class TransactionDescription { - /** - * @_ignore: - */ - constructor(fragment, selector2, args, value) { - /** - * The matching fragment from the transaction ``data``. - */ - __publicField(this, "fragment"); - /** - * The name of the Function from the transaction ``data``. - */ - __publicField(this, "name"); - /** - * The arguments passed to the Function from the transaction ``data``. - */ - __publicField(this, "args"); - /** - * The full Function signature from the transaction ``data``. - */ - __publicField(this, "signature"); - /** - * The selector for the Function from the transaction ``data``. - */ - __publicField(this, "selector"); - /** - * The ``value`` (in wei) from the transaction. - */ - __publicField(this, "value"); - const name2 = fragment.name, signature2 = fragment.format(); - defineProperties$1(this, { - fragment, - name: name2, - args, - signature: signature2, - selector: selector2, - value - }); - } -} -class ErrorDescription { - /** - * @_ignore: - */ - constructor(fragment, selector2, args) { - /** - * The matching fragment. - */ - __publicField(this, "fragment"); - /** - * The name of the Error. - */ - __publicField(this, "name"); - /** - * The arguments passed to the Error with ``revert``. - */ - __publicField(this, "args"); - /** - * The full Error signature. - */ - __publicField(this, "signature"); - /** - * The selector for the Error. - */ - __publicField(this, "selector"); - const name2 = fragment.name, signature2 = fragment.format(); - defineProperties$1(this, { - fragment, - name: name2, - args, - signature: signature2, - selector: selector2 - }); - } -} -class Indexed { - /** - * @_ignore: - */ - constructor(hash2) { - /** - * The ``keccak256`` of the value logged. - */ - __publicField(this, "hash"); - /** - * @_ignore: - */ - __publicField(this, "_isIndexed"); - defineProperties$1(this, { hash: hash2, _isIndexed: true }); - } - /** - * Returns ``true`` if %%value%% is an **Indexed**. - * - * This provides a Type Guard for property access. - */ - static isIndexed(value) { - return !!(value && value._isIndexed); + function EventEmitter2() { + this._events = new Events(); + this._eventsCount = 0; } -} -const PanicReasons = { - "0": "generic panic", - "1": "assert(false)", - "17": "arithmetic overflow", - "18": "division or modulo by zero", - "33": "enum overflow", - "34": "invalid encoded storage byte array accessed", - "49": "out-of-bounds array access; popping on an empty array", - "50": "out-of-bounds access of an array or bytesN", - "65": "out of memory", - "81": "uninitialized function" -}; -const BuiltinErrors = { - "0x08c379a0": { - signature: "Error(string)", - name: "Error", - inputs: ["string"], - reason: (message) => { - return `reverted with reason string ${JSON.stringify(message)}`; + EventEmitter2.prototype.eventNames = function eventNames() { + var names2 = [], events, name2; + if (this._eventsCount === 0) return names2; + for (name2 in events = this._events) { + if (has.call(events, name2)) names2.push(prefix ? name2.slice(1) : name2); } - }, - "0x4e487b71": { - signature: "Panic(uint256)", - name: "Panic", - inputs: ["uint256"], - reason: (code2) => { - let reason = "unknown panic code"; - if (code2 >= 0 && code2 <= 255 && PanicReasons[code2.toString()]) { - reason = PanicReasons[code2.toString()]; - } - return `reverted with panic code 0x${code2.toString(16)} (${reason})`; + if (Object.getOwnPropertySymbols) { + return names2.concat(Object.getOwnPropertySymbols(events)); } - } -}; -const _Interface = class _Interface { - /** - * Create a new Interface for the %%fragments%%. - */ - constructor(fragments) { - __privateAdd(this, _Interface_instances); - /** - * All the Contract ABI members (i.e. methods, events, errors, etc). - */ - __publicField(this, "fragments"); - /** - * The Contract constructor. - */ - __publicField(this, "deploy"); - /** - * The Fallback method, if any. - */ - __publicField(this, "fallback"); - /** - * If receiving ether is supported. - */ - __publicField(this, "receive"); - __privateAdd(this, _errors); - __privateAdd(this, _events); - __privateAdd(this, _functions); - // #structs: Map; - __privateAdd(this, _abiCoder); - let abi2 = []; - if (typeof fragments === "string") { - abi2 = JSON.parse(fragments); - } else { - abi2 = fragments; + return names2; + }; + EventEmitter2.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + for (var i = 0, l2 = handlers.length, ee2 = new Array(l2); i < l2; i++) { + ee2[i] = handlers[i].fn; } - __privateSet(this, _functions, /* @__PURE__ */ new Map()); - __privateSet(this, _errors, /* @__PURE__ */ new Map()); - __privateSet(this, _events, /* @__PURE__ */ new Map()); - const frags = []; - for (const a2 of abi2) { - try { - frags.push(Fragment.from(a2)); - } catch (error) { - console.log(`[Warning] Invalid Fragment ${JSON.stringify(a2)}:`, error.message); + return ee2; + }; + EventEmitter2.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + EventEmitter2.prototype.emit = function emit2(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt], len = arguments.length, args, i; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); + switch (len) { + case 1: + return listeners.fn.call(listeners.context), true; + case 2: + return listeners.fn.call(listeners.context, a1), true; + case 3: + return listeners.fn.call(listeners.context, a1, a2), true; + case 4: + return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: + return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: + return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + for (i = 1, args = new Array(len - 1); i < len; i++) { + args[i - 1] = arguments[i]; + } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j2; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); + switch (len) { + case 1: + listeners[i].fn.call(listeners[i].context); + break; + case 2: + listeners[i].fn.call(listeners[i].context, a1); + break; + case 3: + listeners[i].fn.call(listeners[i].context, a1, a2); + break; + case 4: + listeners[i].fn.call(listeners[i].context, a1, a2, a3); + break; + default: + if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) { + args[j2 - 1] = arguments[j2]; + } + listeners[i].fn.apply(listeners[i].context, args); + } } } - defineProperties$1(this, { - fragments: Object.freeze(frags) - }); - let fallback2 = null; - let receive = false; - __privateSet(this, _abiCoder, this.getAbiCoder()); - this.fragments.forEach((fragment, index2) => { - let bucket; - switch (fragment.type) { - case "constructor": - if (this.deploy) { - console.log("duplicate definition - constructor"); - return; - } - defineProperties$1(this, { deploy: fragment }); - return; - case "fallback": - if (fragment.inputs.length === 0) { - receive = true; - } else { - assertArgument(!fallback2 || fragment.payable !== fallback2.payable, "conflicting fallback fragments", `fragments[${index2}]`, fragment); - fallback2 = fragment; - receive = fallback2.payable; - } - return; - case "function": - bucket = __privateGet(this, _functions); - break; - case "event": - bucket = __privateGet(this, _events); - break; - case "error": - bucket = __privateGet(this, _errors); - break; - default: - return; + return true; + }; + EventEmitter2.prototype.on = function on(event, fn, context2) { + return addListener(this, event, fn, context2, false); + }; + EventEmitter2.prototype.once = function once(event, fn, context2) { + return addListener(this, event, fn, context2, true); + }; + EventEmitter2.prototype.removeListener = function removeListener(event, fn, context2, once) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + var listeners = this._events[evt]; + if (listeners.fn) { + if (listeners.fn === fn && (!once || listeners.once) && (!context2 || listeners.context === context2)) { + clearEvent(this, evt); } - const signature2 = fragment.format(); - if (bucket.has(signature2)) { - return; + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if (listeners[i].fn !== fn || once && !listeners[i].once || context2 && listeners[i].context !== context2) { + events.push(listeners[i]); + } } - bucket.set(signature2, fragment); - }); - if (!this.deploy) { - defineProperties$1(this, { - deploy: ConstructorFragment.from("constructor()") - }); + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); } - defineProperties$1(this, { fallback: fallback2, receive }); - } - /** - * Returns the entire Human-Readable ABI, as an array of - * signatures, optionally as %%minimal%% strings, which - * removes parameter names and unneceesary spaces. - */ - format(minimal) { - const format2 = minimal ? "minimal" : "full"; - const abi2 = this.fragments.map((f2) => f2.format(format2)); - return abi2; - } - /** - * Return the JSON-encoded ABI. This is the format Solidiy - * returns. - */ - formatJson() { - const abi2 = this.fragments.map((f2) => f2.format("json")); - return JSON.stringify(abi2.map((j2) => JSON.parse(j2))); - } - /** - * The ABI coder that will be used to encode and decode binary - * data. - */ - getAbiCoder() { - return AbiCoder.defaultAbiCoder(); - } - /** - * Get the function name for %%key%%, which may be a function selector, - * function name or function signature that belongs to the ABI. - */ - getFunctionName(key) { - const fragment = __privateMethod(this, _Interface_instances, getFunction_fn).call(this, key, null, false); - assertArgument(fragment, "no matching function", "key", key); - return fragment.name; + return this; + }; + EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + return this; + }; + EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; + EventEmitter2.prototype.addListener = EventEmitter2.prototype.on; + EventEmitter2.prefixed = prefix; + EventEmitter2.EventEmitter = EventEmitter2; + { + module2.exports = EventEmitter2; } - /** - * Returns true if %%key%% (a function selector, function name or - * function signature) is present in the ABI. - * - * In the case of a function name, the name may be ambiguous, so - * accessing the [[FunctionFragment]] may require refinement. - */ - hasFunction(key) { - return !!__privateMethod(this, _Interface_instances, getFunction_fn).call(this, key, null, false); +})(eventemitter3); +var eventemitter3Exports = eventemitter3.exports; +const EventEmitter = /* @__PURE__ */ getDefaultExportFromCjs$1(eventemitter3Exports); +class Emitter { + constructor(uid2) { + Object.defineProperty(this, "uid", { + enumerable: true, + configurable: true, + writable: true, + value: uid2 + }); + Object.defineProperty(this, "_emitter", { + enumerable: true, + configurable: true, + writable: true, + value: new EventEmitter() + }); } - /** - * Get the [[FunctionFragment]] for %%key%%, which may be a function - * selector, function name or function signature that belongs to the ABI. - * - * If %%values%% is provided, it will use the Typed API to handle - * ambiguous cases where multiple functions match by name. - * - * If the %%key%% and %%values%% do not refine to a single function in - * the ABI, this will throw. - */ - getFunction(key, values) { - return __privateMethod(this, _Interface_instances, getFunction_fn).call(this, key, values || null, true); + on(eventName, fn) { + this._emitter.on(eventName, fn); } - /** - * Iterate over all functions, calling %%callback%%, sorted by their name. - */ - forEachFunction(callback) { - const names2 = Array.from(__privateGet(this, _functions).keys()); - names2.sort((a2, b2) => a2.localeCompare(b2)); - for (let i = 0; i < names2.length; i++) { - const name2 = names2[i]; - callback(__privateGet(this, _functions).get(name2), i); - } + once(eventName, fn) { + this._emitter.once(eventName, fn); } - /** - * Get the event name for %%key%%, which may be a topic hash, - * event name or event signature that belongs to the ABI. - */ - getEventName(key) { - const fragment = __privateMethod(this, _Interface_instances, getEvent_fn).call(this, key, null, false); - assertArgument(fragment, "no matching event", "key", key); - return fragment.name; + off(eventName, fn) { + this._emitter.off(eventName, fn); } - /** - * Returns true if %%key%% (an event topic hash, event name or - * event signature) is present in the ABI. - * - * In the case of an event name, the name may be ambiguous, so - * accessing the [[EventFragment]] may require refinement. - */ - hasEvent(key) { - return !!__privateMethod(this, _Interface_instances, getEvent_fn).call(this, key, null, false); + emit(eventName, ...params) { + const data = params[0]; + this._emitter.emit(eventName, { uid: this.uid, ...data }); } - /** - * Get the [[EventFragment]] for %%key%%, which may be a topic hash, - * event name or event signature that belongs to the ABI. - * - * If %%values%% is provided, it will use the Typed API to handle - * ambiguous cases where multiple events match by name. - * - * If the %%key%% and %%values%% do not refine to a single event in - * the ABI, this will throw. - */ - getEvent(key, values) { - return __privateMethod(this, _Interface_instances, getEvent_fn).call(this, key, values || null, true); + listenerCount(eventName) { + return this._emitter.listenerCount(eventName); } - /** - * Iterate over all events, calling %%callback%%, sorted by their name. - */ - forEachEvent(callback) { - const names2 = Array.from(__privateGet(this, _events).keys()); - names2.sort((a2, b2) => a2.localeCompare(b2)); - for (let i = 0; i < names2.length; i++) { - const name2 = names2[i]; - callback(__privateGet(this, _events).get(name2), i); +} +function createEmitter(uid2) { + return new Emitter(uid2); +} +function deserialize(value, reviver) { + return JSON.parse(value, (key, value_) => { + let value2 = value_; + if ((value2 == null ? void 0 : value2.__type) === "bigint") + value2 = BigInt(value2.value); + if ((value2 == null ? void 0 : value2.__type) === "Map") + value2 = new Map(value2.value); + return (reviver == null ? void 0 : reviver(key, value2)) ?? value2; + }); +} +function getReferenceKey(keys, cutoff) { + return keys.slice(0, cutoff).join(".") || "."; +} +function getCutoff(array, value) { + const { length } = array; + for (let index2 = 0; index2 < length; ++index2) { + if (array[index2] === value) { + return index2 + 1; } } - /** - * Get the [[ErrorFragment]] for %%key%%, which may be an error - * selector, error name or error signature that belongs to the ABI. - * - * If %%values%% is provided, it will use the Typed API to handle - * ambiguous cases where multiple errors match by name. - * - * If the %%key%% and %%values%% do not refine to a single error in - * the ABI, this will throw. - */ - getError(key, values) { - if (isHexString(key)) { - const selector2 = key.toLowerCase(); - if (BuiltinErrors[selector2]) { - return ErrorFragment.from(BuiltinErrors[selector2].signature); - } - for (const fragment of __privateGet(this, _errors).values()) { - if (selector2 === fragment.selector) { - return fragment; + return 0; +} +function createReplacer(replacer, circularReplacer) { + const hasReplacer = typeof replacer === "function"; + const hasCircularReplacer = typeof circularReplacer === "function"; + const cache2 = []; + const keys = []; + return function replace(key, value) { + if (typeof value === "object") { + if (cache2.length) { + const thisCutoff = getCutoff(cache2, this); + if (thisCutoff === 0) { + cache2[cache2.length] = this; + } else { + cache2.splice(thisCutoff); + keys.splice(thisCutoff); + } + keys[keys.length] = key; + const valueCutoff = getCutoff(cache2, value); + if (valueCutoff !== 0) { + return hasCircularReplacer ? circularReplacer.call(this, key, value, getReferenceKey(keys, valueCutoff)) : `[ref=${getReferenceKey(keys, valueCutoff)}]`; } + } else { + cache2[0] = value; + keys[0] = key; } - return null; } - if (key.indexOf("(") === -1) { - const matching = []; - for (const [name2, fragment] of __privateGet(this, _errors)) { - if (name2.split( - "(" - /* fix:) */ - )[0] === key) { - matching.push(fragment); - } - } - if (matching.length === 0) { - if (key === "Error") { - return ErrorFragment.from("error Error(string)"); - } - if (key === "Panic") { - return ErrorFragment.from("error Panic(uint256)"); - } - return null; - } else if (matching.length > 1) { - const matchStr = matching.map((m2) => JSON.stringify(m2.format())).join(", "); - assertArgument(false, `ambiguous error description (i.e. ${matchStr})`, "name", key); - } - return matching[0]; - } - key = ErrorFragment.from(key).format(); - if (key === "Error(string)") { - return ErrorFragment.from("error Error(string)"); - } - if (key === "Panic(uint256)") { - return ErrorFragment.from("error Panic(uint256)"); - } - const result = __privateGet(this, _errors).get(key); - if (result) { - return result; - } - return null; + return hasReplacer ? replacer.call(this, key, value) : value; + }; +} +function serialize(value, replacer, indent, circularReplacer) { + return JSON.stringify(value, createReplacer((key, value_) => { + let value2 = value_; + if (typeof value2 === "bigint") + value2 = { __type: "bigint", value: value_.toString() }; + if (value2 instanceof Map) + value2 = { __type: "Map", value: Array.from(value_.entries()) }; + return (replacer == null ? void 0 : replacer(key, value2)) ?? value2; + }, circularReplacer), indent ?? void 0); +} +function createStorage(parameters) { + const { deserialize: deserialize$1 = deserialize, key: prefix = "wagmi", serialize: serialize$1 = serialize, storage = noopStorage } = parameters; + function unwrap2(value) { + if (value instanceof Promise) + return value.then((x2) => x2).catch(() => null); + return value; } - /** - * Iterate over all errors, calling %%callback%%, sorted by their name. - */ - forEachError(callback) { - const names2 = Array.from(__privateGet(this, _errors).keys()); - names2.sort((a2, b2) => a2.localeCompare(b2)); - for (let i = 0; i < names2.length; i++) { - const name2 = names2[i]; - callback(__privateGet(this, _errors).get(name2), i); + return { + ...storage, + key: prefix, + async getItem(key, defaultValue) { + const value = storage.getItem(`${prefix}.${key}`); + const unwrapped = await unwrap2(value); + if (unwrapped) + return deserialize$1(unwrapped) ?? null; + return defaultValue ?? null; + }, + async setItem(key, value) { + const storageKey2 = `${prefix}.${key}`; + if (value === null) + await unwrap2(storage.removeItem(storageKey2)); + else + await unwrap2(storage.setItem(storageKey2, serialize$1(value))); + }, + async removeItem(key) { + await unwrap2(storage.removeItem(`${prefix}.${key}`)); } + }; +} +const noopStorage = { + getItem: () => null, + setItem: () => { + }, + removeItem: () => { } - // Get the 4-byte selector used by Solidity to identify a function - /* - getSelector(fragment: ErrorFragment | FunctionFragment): string { - if (typeof(fragment) === "string") { - const matches: Array = [ ]; - - try { matches.push(this.getFunction(fragment)); } catch (error) { } - try { matches.push(this.getError(fragment)); } catch (_) { } - - if (matches.length === 0) { - logger.throwArgumentError("unknown fragment", "key", fragment); - } else if (matches.length > 1) { - logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment); - } - - fragment = matches[0]; - } - - return dataSlice(id(fragment.format()), 0, 4); - } - */ - // Get the 32-byte topic hash used by Solidity to identify an event - /* - getEventTopic(fragment: EventFragment): string { - //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); } - return id(fragment.format()); - } - */ - _decodeParams(params, data) { - return __privateGet(this, _abiCoder).decode(params, data); - } - _encodeParams(params, values) { - return __privateGet(this, _abiCoder).encode(params, values); - } - /** - * Encodes a ``tx.data`` object for deploying the Contract with - * the %%values%% as the constructor arguments. - */ - encodeDeploy(values) { - return this._encodeParams(this.deploy.inputs, values || []); - } - /** - * Decodes the result %%data%% (e.g. from an ``eth_call``) for the - * specified error (see [[getError]] for valid values for - * %%key%%). - * - * Most developers should prefer the [[parseCallResult]] method instead, - * which will automatically detect a ``CALL_EXCEPTION`` and throw the - * corresponding error. - */ - decodeErrorResult(fragment, data) { - if (typeof fragment === "string") { - const f2 = this.getError(fragment); - assertArgument(f2, "unknown error", "fragment", fragment); - fragment = f2; +}; +const size$3 = 256; +let index$7 = size$3; +let buffer$1; +function uid(length = 11) { + if (!buffer$1 || index$7 + length > size$3 * 2) { + buffer$1 = ""; + index$7 = 0; + for (let i = 0; i < size$3; i++) { + buffer$1 += (256 + Math.random() * 256 | 0).toString(16).substring(1); } - assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match error ${fragment.name}.`, "data", data); - return this._decodeParams(fragment.inputs, dataSlice(data, 4)); } - /** - * Encodes the transaction revert data for a call result that - * reverted from the the Contract with the sepcified %%error%% - * (see [[getError]] for valid values for %%fragment%%) with the %%values%%. - * - * This is generally not used by most developers, unless trying to mock - * a result from a Contract. - */ - encodeErrorResult(fragment, values) { - if (typeof fragment === "string") { - const f2 = this.getError(fragment); - assertArgument(f2, "unknown error", "fragment", fragment); - fragment = f2; - } - return concat$1([ - fragment.selector, - this._encodeParams(fragment.inputs, values || []) - ]); + return buffer$1.substring(index$7, index$7++ + length); +} +function createConfig$1(parameters) { + const { multiInjectedProviderDiscovery = true, storage = createStorage({ + storage: typeof window !== "undefined" && window.localStorage ? window.localStorage : noopStorage + }), syncConnectedChain = true, ssr = false, ...rest } = parameters; + const mipd = typeof window !== "undefined" && multiInjectedProviderDiscovery ? createStore$1() : void 0; + const chains2 = createStore(() => rest.chains); + const connectors = createStore(() => [ + ...rest.connectors ?? [], + ...!ssr ? (mipd == null ? void 0 : mipd.getProviders().map(providerDetailToConnector)) ?? [] : [] + ].map(setup)); + function setup(connectorFn) { + var _a2; + const emitter = createEmitter(uid()); + const connector = { + ...connectorFn({ + emitter, + chains: chains2.getState(), + storage, + transports: rest.transports + }), + emitter, + uid: emitter.uid + }; + emitter.on("connect", connect2); + (_a2 = connector.setup) == null ? void 0 : _a2.call(connector); + return connector; } - /** - * Decodes the %%data%% from a transaction ``tx.data`` for - * the function specified (see [[getFunction]] for valid values - * for %%fragment%%). - * - * Most developers should prefer the [[parseTransaction]] method - * instead, which will automatically detect the fragment. - */ - decodeFunctionData(fragment, data) { - if (typeof fragment === "string") { - const f2 = this.getFunction(fragment); - assertArgument(f2, "unknown function", "fragment", fragment); - fragment = f2; - } - assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match function ${fragment.name}.`, "data", data); - return this._decodeParams(fragment.inputs, dataSlice(data, 4)); + function providerDetailToConnector(providerDetail) { + const { info } = providerDetail; + const provider2 = providerDetail.provider; + return injected$1({ target: { ...info, id: info.rdns, provider: provider2 } }); } - /** - * Encodes the ``tx.data`` for a transaction that calls the function - * specified (see [[getFunction]] for valid values for %%fragment%%) with - * the %%values%%. - */ - encodeFunctionData(fragment, values) { - if (typeof fragment === "string") { - const f2 = this.getFunction(fragment); - assertArgument(f2, "unknown function", "fragment", fragment); - fragment = f2; + const clients = /* @__PURE__ */ new Map(); + function getClient2(config2 = {}) { + const chainId = config2.chainId ?? store.getState().chainId; + const chain = chains2.getState().find((x2) => x2.id === chainId); + if (config2.chainId && !chain) + throw new ChainNotConfiguredError(); + { + const client3 = clients.get(store.getState().chainId); + if (client3 && !chain) + return client3; + if (!chain) + throw new ChainNotConfiguredError(); } - return concat$1([ - fragment.selector, - this._encodeParams(fragment.inputs, values || []) - ]); - } - /** - * Decodes the result %%data%% (e.g. from an ``eth_call``) for the - * specified function (see [[getFunction]] for valid values for - * %%key%%). - * - * Most developers should prefer the [[parseCallResult]] method instead, - * which will automatically detect a ``CALL_EXCEPTION`` and throw the - * corresponding error. - */ - decodeFunctionResult(fragment, data) { - if (typeof fragment === "string") { - const f2 = this.getFunction(fragment); - assertArgument(f2, "unknown function", "fragment", fragment); - fragment = f2; + { + const client3 = clients.get(chainId); + if (client3) + return client3; } - let message = "invalid length for result data"; - const bytes2 = getBytesCopy(data); - if (bytes2.length % 32 === 0) { - try { - return __privateGet(this, _abiCoder).decode(fragment.outputs, bytes2); - } catch (error) { - message = "could not decode result data"; + let client2; + if (rest.client) + client2 = rest.client({ chain }); + else { + const chainId2 = chain.id; + const chainIds = chains2.getState().map((x2) => x2.id); + const properties = {}; + const entries = Object.entries(rest); + for (const [key, value] of entries) { + if (key === "chains" || key === "client" || key === "connectors" || key === "transports") + continue; + if (typeof value === "object") { + if (chainId2 in value) + properties[key] = value[chainId2]; + else { + const hasChainSpecificValue = chainIds.some((x2) => x2 in value); + if (hasChainSpecificValue) + continue; + properties[key] = value; + } + } else + properties[key] = value; } + client2 = createClient({ + ...properties, + chain, + batch: properties.batch ?? { multicall: true }, + transport: (parameters2) => rest.transports[chainId2]({ ...parameters2, connectors }) + }); } - assert(false, message, "BAD_DATA", { - value: hexlify(bytes2), - info: { method: fragment.name, signature: fragment.format() } - }); + clients.set(chainId, client2); + return client2; } - makeError(_data6, tx) { - const data = getBytes(_data6, "data"); - const error = AbiCoder.getBuiltinCallException("call", tx, data); - const customPrefix = "execution reverted (unknown custom error)"; - if (error.message.startsWith(customPrefix)) { - const selector2 = hexlify(data.slice(0, 4)); - const ef2 = this.getError(selector2); - if (ef2) { - try { - const args = __privateGet(this, _abiCoder).decode(ef2.inputs, data.slice(4)); - error.revert = { - name: ef2.name, - signature: ef2.format(), - args - }; - error.reason = error.revert.signature; - error.message = `execution reverted: ${error.reason}`; - } catch (e2) { - error.message = `execution reverted (coult not decode custom error)`; - } - } - } - const parsed = this.parseTransaction(tx); - if (parsed) { - error.invocation = { - method: parsed.name, - signature: parsed.signature, - args: parsed.args - }; - } - return error; + function getInitialState() { + return { + chainId: chains2.getState()[0].id, + connections: /* @__PURE__ */ new Map(), + current: null, + status: "disconnected" + }; } - /** - * Encodes the result data (e.g. from an ``eth_call``) for the - * specified function (see [[getFunction]] for valid values - * for %%fragment%%) with %%values%%. - * - * This is generally not used by most developers, unless trying to mock - * a result from a Contract. - */ - encodeFunctionResult(fragment, values) { - if (typeof fragment === "string") { - const f2 = this.getFunction(fragment); - assertArgument(f2, "unknown function", "fragment", fragment); - fragment = f2; - } - return hexlify(__privateGet(this, _abiCoder).encode(fragment.outputs, values || [])); + let currentVersion; + const prefix = "0.0.0-canary-"; + if (version$7.startsWith(prefix)) + currentVersion = Number.parseInt(version$7.replace(prefix, "")); + else + currentVersion = Number.parseInt(version$7.split(".")[0] ?? "0"); + const store = createStore(subscribeWithSelector( + // only use persist middleware if storage exists + storage ? persist(getInitialState, { + migrate(persistedState, version2) { + if (version2 === currentVersion) + return persistedState; + const initialState = getInitialState(); + const chainId = validatePersistedChainId(persistedState, initialState.chainId); + return { ...initialState, chainId }; + }, + name: "store", + partialize(state) { + return { + connections: { + __type: "Map", + value: Array.from(state.connections.entries()).map(([key, connection]) => { + const { id: id2, name: name2, type, uid: uid2 } = connection.connector; + const connector = { id: id2, name: name2, type, uid: uid2 }; + return [key, { ...connection, connector }]; + }) + }, + chainId: state.chainId, + current: state.current + }; + }, + merge(persistedState, currentState) { + if (typeof persistedState === "object" && persistedState && "status" in persistedState) + delete persistedState.status; + const chainId = validatePersistedChainId(persistedState, currentState.chainId); + return { + ...currentState, + ...persistedState, + chainId + }; + }, + skipHydration: ssr, + storage, + version: currentVersion + }) : getInitialState + )); + function validatePersistedChainId(persistedState, defaultChainId) { + return persistedState && typeof persistedState === "object" && "chainId" in persistedState && typeof persistedState.chainId === "number" && chains2.getState().some((x2) => x2.id === persistedState.chainId) ? persistedState.chainId : defaultChainId; } - /* - spelunk(inputs: Array, values: ReadonlyArray, processfunc: (type: string, value: any) => Promise): Promise> { - const promises: Array> = [ ]; - const process = function(type: ParamType, value: any): any { - if (type.baseType === "array") { - return descend(type.child - } - if (type. === "address") { - } - }; - - const descend = function (inputs: Array, values: ReadonlyArray) { - if (inputs.length !== values.length) { throw new Error("length mismatch"); } - - }; - - const result: Array = [ ]; - values.forEach((value, index) => { - if (value == null) { - topics.push(null); - } else if (param.baseType === "array" || param.baseType === "tuple") { - logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); - } else if (Array.isArray(value)) { - topics.push(value.map((value) => encodeTopic(param, value))); - } else { - topics.push(encodeTopic(param, value)); - } - }); - } - */ - // Create the filter for the event with search criteria (e.g. for eth_filterLog) - encodeFilterTopics(fragment, values) { - if (typeof fragment === "string") { - const f2 = this.getEvent(fragment); - assertArgument(f2, "unknown event", "eventFragment", fragment); - fragment = f2; - } - assert(values.length <= fragment.inputs.length, `too many arguments for ${fragment.format()}`, "UNEXPECTED_ARGUMENT", { count: values.length, expectedCount: fragment.inputs.length }); - const topics = []; - if (!fragment.anonymous) { - topics.push(fragment.topicHash); - } - const encodeTopic = (param, value) => { - if (param.type === "string") { - return id$1(value); - } else if (param.type === "bytes") { - return keccak256$1(hexlify(value)); - } - if (param.type === "bool" && typeof value === "boolean") { - value = value ? "0x01" : "0x00"; - } else if (param.type.match(/^u?int/)) { - value = toBeHex(value); - } else if (param.type.match(/^bytes/)) { - value = zeroPadBytes(value, 32); - } else if (param.type === "address") { - __privateGet(this, _abiCoder).encode(["address"], [value]); - } - return zeroPadValue(hexlify(value), 32); - }; - values.forEach((value, index2) => { - const param = fragment.inputs[index2]; - if (!param.indexed) { - assertArgument(value == null, "cannot filter non-indexed parameters; must be null", "contract." + param.name, value); + if (syncConnectedChain) + store.subscribe(({ connections, current }) => { + var _a2; + return current ? (_a2 = connections.get(current)) == null ? void 0 : _a2.chainId : void 0; + }, (chainId) => { + const isChainConfigured = chains2.getState().some((x2) => x2.id === chainId); + if (!isChainConfigured) return; - } - if (value == null) { - topics.push(null); - } else if (param.baseType === "array" || param.baseType === "tuple") { - assertArgument(false, "filtering with tuples or arrays not supported", "contract." + param.name, value); - } else if (Array.isArray(value)) { - topics.push(value.map((value2) => encodeTopic(param, value2))); - } else { - topics.push(encodeTopic(param, value)); - } + return store.setState((x2) => ({ + ...x2, + chainId: chainId ?? x2.chainId + })); }); - while (topics.length && topics[topics.length - 1] === null) { - topics.pop(); - } - return topics; - } - encodeEventLog(fragment, values) { - if (typeof fragment === "string") { - const f2 = this.getEvent(fragment); - assertArgument(f2, "unknown event", "eventFragment", fragment); - fragment = f2; + mipd == null ? void 0 : mipd.subscribe((providerDetails) => { + const currentConnectorIds = /* @__PURE__ */ new Map(); + for (const connector of connectors.getState()) { + currentConnectorIds.set(connector.id, true); } - const topics = []; - const dataTypes = []; - const dataValues = []; - if (!fragment.anonymous) { - topics.push(fragment.topicHash); + const newConnectors = []; + for (const providerDetail of providerDetails) { + const connector = setup(providerDetailToConnector(providerDetail)); + if (currentConnectorIds.has(connector.id)) + continue; + newConnectors.push(connector); } - assertArgument(values.length === fragment.inputs.length, "event arguments/values mismatch", "values", values); - fragment.inputs.forEach((param, index2) => { - const value = values[index2]; - if (param.indexed) { - if (param.type === "string") { - topics.push(id$1(value)); - } else if (param.type === "bytes") { - topics.push(keccak256$1(value)); - } else if (param.baseType === "tuple" || param.baseType === "array") { - throw new Error("not implemented"); - } else { - topics.push(__privateGet(this, _abiCoder).encode([param.type], [value])); - } - } else { - dataTypes.push(param); - dataValues.push(value); - } + if (storage && !store.persist.hasHydrated()) + return; + connectors.setState((x2) => [...x2, ...newConnectors], true); + }); + function change(data) { + store.setState((x2) => { + const connection = x2.connections.get(data.uid); + if (!connection) + return x2; + return { + ...x2, + connections: new Map(x2.connections).set(data.uid, { + accounts: data.accounts ?? connection.accounts, + chainId: data.chainId ?? connection.chainId, + connector: connection.connector + }) + }; }); - return { - data: __privateGet(this, _abiCoder).encode(dataTypes, dataValues), - topics - }; } - // Decode a filter for the event and the search criteria - decodeEventLog(fragment, data, topics) { - if (typeof fragment === "string") { - const f2 = this.getEvent(fragment); - assertArgument(f2, "unknown event", "eventFragment", fragment); - fragment = f2; - } - if (topics != null && !fragment.anonymous) { - const eventTopic = fragment.topicHash; - assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic, "fragment/topic mismatch", "topics[0]", topics[0]); - topics = topics.slice(1); - } - const indexed = []; - const nonIndexed = []; - const dynamic = []; - fragment.inputs.forEach((param, index2) => { - if (param.indexed) { - if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") { - indexed.push(ParamType.from({ type: "bytes32", name: param.name })); - dynamic.push(true); - } else { - indexed.push(param); - dynamic.push(false); - } - } else { - nonIndexed.push(param); - dynamic.push(false); + function connect2(data) { + if (store.getState().status === "connecting" || store.getState().status === "reconnecting") + return; + store.setState((x2) => { + const connector = connectors.getState().find((x3) => x3.uid === data.uid); + if (!connector) + return x2; + if (connector.emitter.listenerCount("connect")) + connector.emitter.off("connect", change); + if (!connector.emitter.listenerCount("change")) + connector.emitter.on("change", change); + if (!connector.emitter.listenerCount("disconnect")) + connector.emitter.on("disconnect", disconnect2); + return { + ...x2, + connections: new Map(x2.connections).set(data.uid, { + accounts: data.accounts, + chainId: data.chainId, + connector + }), + current: data.uid, + status: "connected" + }; + }); + } + function disconnect2(data) { + store.setState((x2) => { + const connection = x2.connections.get(data.uid); + if (connection) { + const connector = connection.connector; + if (connector.emitter.listenerCount("change")) + connection.connector.emitter.off("change", change); + if (connector.emitter.listenerCount("disconnect")) + connection.connector.emitter.off("disconnect", disconnect2); + if (!connector.emitter.listenerCount("connect")) + connection.connector.emitter.on("connect", connect2); } + x2.connections.delete(data.uid); + if (x2.connections.size === 0) + return { + ...x2, + connections: /* @__PURE__ */ new Map(), + current: null, + status: "disconnected" + }; + const nextConnection = x2.connections.values().next().value; + return { + ...x2, + connections: new Map(x2.connections), + current: nextConnection.connector.uid + }; }); - const resultIndexed = topics != null ? __privateGet(this, _abiCoder).decode(indexed, concat$1(topics)) : null; - const resultNonIndexed = __privateGet(this, _abiCoder).decode(nonIndexed, data, true); - const values = []; - const keys = []; - let nonIndexedIndex = 0, indexedIndex = 0; - fragment.inputs.forEach((param, index2) => { - let value = null; - if (param.indexed) { - if (resultIndexed == null) { - value = new Indexed(null); - } else if (dynamic[index2]) { - value = new Indexed(resultIndexed[indexedIndex++]); - } else { - try { - value = resultIndexed[indexedIndex++]; - } catch (error) { - value = error; - } + } + return { + get chains() { + return chains2.getState(); + }, + get connectors() { + return connectors.getState(); + }, + storage, + getClient: getClient2, + get state() { + return store.getState(); + }, + setState(value) { + let newState; + if (typeof value === "function") + newState = value(store.getState()); + else + newState = value; + const initialState = getInitialState(); + if (typeof newState !== "object") + newState = initialState; + const isCorrupt = Object.keys(initialState).some((x2) => !(x2 in newState)); + if (isCorrupt) + newState = initialState; + store.setState(newState, true); + }, + subscribe(selector2, listener, options) { + return store.subscribe(selector2, listener, options ? { + ...options, + fireImmediately: options.emitImmediately + // Workaround cast since Zustand does not support `'exactOptionalPropertyTypes'` + } : void 0); + }, + _internal: { + mipd, + store, + ssr: Boolean(ssr), + syncConnectedChain, + transports: rest.transports, + chains: { + setState(value) { + const nextChains = typeof value === "function" ? value(chains2.getState()) : value; + if (nextChains.length === 0) + return; + return chains2.setState(nextChains, true); + }, + subscribe(listener) { + return chains2.subscribe(listener); } - } else { - try { - value = resultNonIndexed[nonIndexedIndex++]; - } catch (error) { - value = error; + }, + connectors: { + providerDetailToConnector, + setup, + setState(value) { + return connectors.setState(typeof value === "function" ? value(connectors.getState()) : value, true); + }, + subscribe(listener) { + return connectors.subscribe(listener); } + }, + events: { change, connect: connect2, disconnect: disconnect2 } + } + }; +} +function hydrate(config2, parameters) { + const { initialState, reconnectOnMount } = parameters; + if (initialState && !config2._internal.store.persist.hasHydrated()) + config2.setState({ + ...initialState, + chainId: config2.chains.some((x2) => x2.id === initialState.chainId) ? initialState.chainId : config2.chains[0].id, + connections: reconnectOnMount ? initialState.connections : /* @__PURE__ */ new Map(), + status: reconnectOnMount ? "reconnecting" : "disconnected" + }); + return { + async onMount() { + var _a2; + if (config2._internal.ssr) { + await config2._internal.store.persist.rehydrate(); + const mipdConnectors = (_a2 = config2._internal.mipd) == null ? void 0 : _a2.getProviders().map(config2._internal.connectors.providerDetailToConnector).map(config2._internal.connectors.setup); + config2._internal.connectors.setState((connectors) => [ + ...connectors, + ...mipdConnectors ?? [] + ]); } - values.push(value); - keys.push(param.name || null); + if (reconnectOnMount) + reconnect(config2); + else if (config2.storage) + config2.setState((x2) => ({ + ...x2, + connections: /* @__PURE__ */ new Map() + })); + } + }; +} +function extractRpcUrls(parameters) { + var _a2, _b2, _c2; + const { chain } = parameters; + const fallbackUrl = chain.rpcUrls.default.http[0]; + if (!parameters.transports) + return [fallbackUrl]; + const transport = (_b2 = (_a2 = parameters.transports) == null ? void 0 : _a2[chain.id]) == null ? void 0 : _b2.call(_a2, { chain }); + const transports = ((_c2 = transport == null ? void 0 : transport.value) == null ? void 0 : _c2.transports) || [transport]; + return transports.map(({ value }) => (value == null ? void 0 : value.url) || fallbackUrl); +} +function Hydrate(parameters) { + const { children, config: config2, initialState, reconnectOnMount = true } = parameters; + const { onMount } = hydrate(config2, { + initialState, + reconnectOnMount + }); + if (!config2._internal.ssr) + onMount(); + const active = reactExports.useRef(true); + reactExports.useEffect(() => { + if (!active.current) + return; + if (!config2._internal.ssr) + return; + onMount(); + return () => { + active.current = false; + }; + }, []); + return children; +} +const WagmiContext = reactExports.createContext(void 0); +function WagmiProvider(parameters) { + const { children, config: config2 } = parameters; + const props = { value: config2 }; + return reactExports.createElement(Hydrate, parameters, reactExports.createElement(WagmiContext.Provider, props, children)); +} +const version$6 = "2.12.12"; +const getVersion = () => `wagmi@${version$6}`; +class BaseError4 extends BaseError$1 { + constructor() { + super(...arguments); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "WagmiError" }); - return Result.fromItems(values, keys); } - /** - * Parses a transaction, finding the matching function and extracts - * the parameter values along with other useful function details. - * - * If the matching function cannot be found, return null. - */ - parseTransaction(tx) { - const data = getBytes(tx.data, "tx.data"); - const value = getBigInt(tx.value != null ? tx.value : 0, "tx.value"); - const fragment = this.getFunction(hexlify(data.slice(0, 4))); - if (!fragment) { - return null; - } - const args = __privateGet(this, _abiCoder).decode(fragment.inputs, data.slice(4)); - return new TransactionDescription(fragment, fragment.selector, args, value); + get docsBaseUrl() { + return "https://wagmi.sh/react"; } - parseCallResult(data) { - throw new Error("@TODO"); + get version() { + return getVersion(); } - /** - * Parses a receipt log, finding the matching event and extracts - * the parameter values along with other useful event details. - * - * If the matching event cannot be found, returns null. - */ - parseLog(log) { - const fragment = this.getEvent(log.topics[0]); - if (!fragment || fragment.anonymous) { - return null; - } - return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics)); +} +class WagmiProviderNotFoundError extends BaseError4 { + constructor() { + super("`useConfig` must be used within `WagmiProvider`.", { + docsPath: "/api/WagmiProvider" + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "WagmiProviderNotFoundError" + }); } - /** - * Parses a revert data, finding the matching error and extracts - * the parameter values along with other useful error details. - * - * If the matching error cannot be found, returns null. - */ - parseError(data) { - const hexData = hexlify(data); - const fragment = this.getError(dataSlice(hexData, 0, 4)); - if (!fragment) { - return null; - } - const args = __privateGet(this, _abiCoder).decode(fragment.inputs, dataSlice(hexData, 4)); - return new ErrorDescription(fragment, fragment.selector, args); +} +function useConfig(parameters = {}) { + const config2 = parameters.config ?? reactExports.useContext(WagmiContext); + if (!config2) + throw new WagmiProviderNotFoundError(); + return config2; +} +function watchChains(config2, parameters) { + const { onChange } = parameters; + return config2._internal.chains.subscribe((chains2, prevChains) => { + onChange(chains2, prevChains); + }); +} +var withSelector = { exports: {} }; +var withSelector_production_min = {}; +var shim = { exports: {} }; +var useSyncExternalStoreShim_production_min = {}; +/** + * @license React + * use-sync-external-store-shim.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var e$1 = reactExports; +function h$2(a2, b2) { + return a2 === b2 && (0 !== a2 || 1 / a2 === 1 / b2) || a2 !== a2 && b2 !== b2; +} +var k$1 = "function" === typeof Object.is ? Object.is : h$2, l$1 = e$1.useState, m$1 = e$1.useEffect, n$3 = e$1.useLayoutEffect, p$2 = e$1.useDebugValue; +function q$2(a2, b2) { + var d2 = b2(), f2 = l$1({ inst: { value: d2, getSnapshot: b2 } }), c2 = f2[0].inst, g2 = f2[1]; + n$3(function() { + c2.value = d2; + c2.getSnapshot = b2; + r$2(c2) && g2({ inst: c2 }); + }, [a2, d2, b2]); + m$1(function() { + r$2(c2) && g2({ inst: c2 }); + return a2(function() { + r$2(c2) && g2({ inst: c2 }); + }); + }, [a2]); + p$2(d2); + return d2; +} +function r$2(a2) { + var b2 = a2.getSnapshot; + a2 = a2.value; + try { + var d2 = b2(); + return !k$1(a2, d2); + } catch (f2) { + return true; } - /** - * Creates a new [[Interface]] from the ABI %%value%%. - * - * The %%value%% may be provided as an existing [[Interface]] object, - * a JSON-encoded ABI or any Human-Readable ABI format. - */ - static from(value) { - if (value instanceof _Interface) { - return value; - } - if (typeof value === "string") { - return new _Interface(JSON.parse(value)); - } - if (typeof value.formatJson === "function") { - return new _Interface(value.formatJson()); - } - if (typeof value.format === "function") { - return new _Interface(value.format("json")); +} +function t$2(a2, b2) { + return b2(); +} +var u$2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? t$2 : q$2; +useSyncExternalStoreShim_production_min.useSyncExternalStore = void 0 !== e$1.useSyncExternalStore ? e$1.useSyncExternalStore : u$2; +{ + shim.exports = useSyncExternalStoreShim_production_min; +} +var shimExports = shim.exports; +/** + * @license React + * use-sync-external-store-shim/with-selector.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var h$1 = reactExports, n$2 = shimExports; +function p$1(a2, b2) { + return a2 === b2 && (0 !== a2 || 1 / a2 === 1 / b2) || a2 !== a2 && b2 !== b2; +} +var q$1 = "function" === typeof Object.is ? Object.is : p$1, r$1 = n$2.useSyncExternalStore, t$1 = h$1.useRef, u$1 = h$1.useEffect, v$1 = h$1.useMemo, w = h$1.useDebugValue; +withSelector_production_min.useSyncExternalStoreWithSelector = function(a2, b2, e2, l2, g2) { + var c2 = t$1(null); + if (null === c2.current) { + var f2 = { hasValue: false, value: null }; + c2.current = f2; + } else f2 = c2.current; + c2 = v$1(function() { + function a3(a4) { + if (!c3) { + c3 = true; + d3 = a4; + a4 = l2(a4); + if (void 0 !== g2 && f2.hasValue) { + var b3 = f2.value; + if (g2(b3, a4)) return k2 = b3; + } + return k2 = a4; + } + b3 = k2; + if (q$1(d3, a4)) return b3; + var e3 = l2(a4); + if (void 0 !== g2 && g2(b3, e3)) return b3; + d3 = a4; + return k2 = e3; } - return new _Interface(value); - } + var c3 = false, d3, k2, m2 = void 0 === e2 ? null : e2; + return [function() { + return a3(b2()); + }, null === m2 ? void 0 : function() { + return a3(m2()); + }]; + }, [b2, e2, l2, g2]); + var d2 = r$1(a2, c2[0], c2[1]); + u$1(function() { + f2.hasValue = true; + f2.value = d2; + }, [d2]); + w(d2); + return d2; }; -_errors = new WeakMap(); -_events = new WeakMap(); -_functions = new WeakMap(); -_abiCoder = new WeakMap(); -_Interface_instances = new WeakSet(); -// Find a function definition by any means necessary (unless it is ambiguous) -getFunction_fn = function(key, values, forceUnique) { - if (isHexString(key)) { - const selector2 = key.toLowerCase(); - for (const fragment of __privateGet(this, _functions).values()) { - if (selector2 === fragment.selector) { - return fragment; +{ + withSelector.exports = withSelector_production_min; +} +var withSelectorExports = withSelector.exports; +const isPlainObject$1 = (obj) => typeof obj === "object" && !Array.isArray(obj); +function useSyncExternalStoreWithTracked(subscribe, getSnapshot, getServerSnapshot = getSnapshot, isEqual = deepEqual$1) { + const trackedKeys = reactExports.useRef([]); + const result = withSelectorExports.useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, (x2) => x2, (a2, b2) => { + if (isPlainObject$1(a2) && isPlainObject$1(b2) && trackedKeys.current.length) { + for (const key of trackedKeys.current) { + const equal = isEqual(a2[key], b2[key]); + if (!equal) + return false; } + return true; } - return null; - } - if (key.indexOf("(") === -1) { - const matching = []; - for (const [name2, fragment] of __privateGet(this, _functions)) { - if (name2.split( - "(" - /* fix:) */ - )[0] === key) { - matching.push(fragment); - } + return isEqual(a2, b2); + }); + if (isPlainObject$1(result)) { + const trackedResult = { ...result }; + let properties = {}; + for (const [key, value] of Object.entries(trackedResult)) { + properties = { + ...properties, + [key]: { + configurable: false, + enumerable: true, + get: () => { + if (!trackedKeys.current.includes(key)) { + trackedKeys.current.push(key); + } + return value; + } + } + }; } - if (values) { - const lastValue = values.length > 0 ? values[values.length - 1] : null; - let valueLength = values.length; - let allowOptions = true; - if (Typed.isTyped(lastValue) && lastValue.type === "overrides") { - allowOptions = false; - valueLength--; - } - for (let i = matching.length - 1; i >= 0; i--) { - const inputs = matching[i].inputs.length; - if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) { - matching.splice(i, 1); - } - } - for (let i = matching.length - 1; i >= 0; i--) { - const inputs = matching[i].inputs; - for (let j2 = 0; j2 < values.length; j2++) { - if (!Typed.isTyped(values[j2])) { - continue; - } - if (j2 >= inputs.length) { - if (values[j2].type === "overrides") { - continue; - } - matching.splice(i, 1); - break; - } - if (values[j2].type !== inputs[j2].baseType) { - matching.splice(i, 1); - break; - } - } - } - } - if (matching.length === 1 && values && values.length !== matching[0].inputs.length) { - const lastArg = values[values.length - 1]; - if (lastArg == null || Array.isArray(lastArg) || typeof lastArg !== "object") { - matching.splice(0, 1); - } - } - if (matching.length === 0) { - return null; - } - if (matching.length > 1 && forceUnique) { - const matchStr = matching.map((m2) => JSON.stringify(m2.format())).join(", "); - assertArgument(false, `ambiguous function description (i.e. matches ${matchStr})`, "key", key); - } - return matching[0]; - } - const result = __privateGet(this, _functions).get(FunctionFragment.from(key).format()); - if (result) { - return result; - } - return null; -}; -// Find an event definition by any means necessary (unless it is ambiguous) -getEvent_fn = function(key, values, forceUnique) { - if (isHexString(key)) { - const eventTopic = key.toLowerCase(); - for (const fragment of __privateGet(this, _events).values()) { - if (eventTopic === fragment.topicHash) { - return fragment; - } - } - return null; - } - if (key.indexOf("(") === -1) { - const matching = []; - for (const [name2, fragment] of __privateGet(this, _events)) { - if (name2.split( - "(" - /* fix:) */ - )[0] === key) { - matching.push(fragment); - } - } - if (values) { - for (let i = matching.length - 1; i >= 0; i--) { - if (matching[i].inputs.length < values.length) { - matching.splice(i, 1); - } - } - for (let i = matching.length - 1; i >= 0; i--) { - const inputs = matching[i].inputs; - for (let j2 = 0; j2 < values.length; j2++) { - if (!Typed.isTyped(values[j2])) { - continue; - } - if (values[j2].type !== inputs[j2].baseType) { - matching.splice(i, 1); - break; - } - } - } - } - if (matching.length === 0) { - return null; - } - if (matching.length > 1 && forceUnique) { - const matchStr = matching.map((m2) => JSON.stringify(m2.format())).join(", "); - assertArgument(false, `ambiguous event description (i.e. matches ${matchStr})`, "key", key); - } - return matching[0]; - } - const result = __privateGet(this, _events).get(EventFragment.from(key).format()); - if (result) { - return result; - } - return null; -}; -let Interface = _Interface; -const BN_0$2 = BigInt(0); -function getValue(value) { - if (value == null) { - return null; + Object.defineProperties(trackedResult, properties); + return trackedResult; } - return value; + return result; } -function toJson(value) { - if (value == null) { - return null; - } - return value.toString(); +function useAccount(parameters = {}) { + const config2 = useConfig(parameters); + return useSyncExternalStoreWithTracked((onChange) => watchAccount(config2, { onChange }), () => getAccount$1(config2)); } -class FeeData { - /** - * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and - * %%maxPriorityFeePerGas%%. - */ - constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { - /** - * The gas price for legacy networks. - */ - __publicField(this, "gasPrice"); - /** - * The maximum fee to pay per gas. - * - * The base fee per gas is defined by the network and based on - * congestion, increasing the cost during times of heavy load - * and lowering when less busy. - * - * The actual fee per gas will be the base fee for the block - * and the priority fee, up to the max fee per gas. - * - * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) - */ - __publicField(this, "maxFeePerGas"); - /** - * The additional amout to pay per gas to encourage a validator - * to include the transaction. - * - * The purpose of this is to compensate the validator for the - * adjusted risk for including a given transaction. - * - * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) - */ - __publicField(this, "maxPriorityFeePerGas"); - defineProperties$1(this, { - gasPrice: getValue(gasPrice), - maxFeePerGas: getValue(maxFeePerGas), - maxPriorityFeePerGas: getValue(maxPriorityFeePerGas) - }); - } - /** - * Returns a JSON-friendly value. - */ - toJSON() { - const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; - return { - _type: "FeeData", - gasPrice: toJson(gasPrice), - maxFeePerGas: toJson(maxFeePerGas), - maxPriorityFeePerGas: toJson(maxPriorityFeePerGas) - }; - } +function structuralSharing(oldData, newData) { + if (deepEqual$1(oldData, newData)) + return oldData; + return replaceEqualDeep(oldData, newData); } -function copyRequest(req) { - const result = {}; - if (req.to) { - result.to = req.to; - } - if (req.from) { - result.from = req.from; - } - if (req.data) { - result.data = hexlify(req.data); - } - const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/); - for (const key of bigIntKeys) { - if (!(key in req) || req[key] == null) { - continue; - } - result[key] = getBigInt(req[key], `request.${key}`); - } - const numberKeys = "type,nonce".split(/,/); - for (const key of numberKeys) { - if (!(key in req) || req[key] == null) { - continue; - } - result[key] = getNumber(req[key], `request.${key}`); - } - if (req.accessList) { - result.accessList = accessListify(req.accessList); - } - if ("blockTag" in req) { - result.blockTag = req.blockTag; - } - if ("enableCcipRead" in req) { - result.enableCcipRead = !!req.enableCcipRead; - } - if ("customData" in req) { - result.customData = req.customData; - } - if ("blobVersionedHashes" in req && req.blobVersionedHashes) { - result.blobVersionedHashes = req.blobVersionedHashes.slice(); - } - if ("kzg" in req) { - result.kzg = req.kzg; - } - if ("blobs" in req && req.blobs) { - result.blobs = req.blobs.map((b2) => { - if (isBytesLike(b2)) { - return hexlify(b2); - } - return Object.assign({}, b2); - }); +function hashFn(queryKey) { + return JSON.stringify(queryKey, (_, value) => { + if (isPlainObject(value)) + return Object.keys(value).sort().reduce((result, key) => { + result[key] = value[key]; + return result; + }, {}); + if (typeof value === "bigint") + return value.toString(); + return value; + }); +} +function isPlainObject(value) { + if (!hasObjectPrototype(value)) { + return false; } + const ctor = value.constructor; + if (typeof ctor === "undefined") + return true; + const prot = ctor.prototype; + if (!hasObjectPrototype(prot)) + return false; + if (!prot.hasOwnProperty("isPrototypeOf")) + return false; + return true; +} +function hasObjectPrototype(o2) { + return Object.prototype.toString.call(o2) === "[object Object]"; +} +function filterQueryOptions(options) { + const { + // import('@tanstack/query-core').QueryOptions + _defaulted, + behavior, + gcTime, + initialData, + initialDataUpdatedAt, + maxPages, + meta, + networkMode, + queryFn, + queryHash, + queryKey, + queryKeyHashFn, + retry, + retryDelay, + structuralSharing: structuralSharing2, + // import('@tanstack/query-core').InfiniteQueryObserverOptions + getPreviousPageParam: getPreviousPageParam2, + getNextPageParam: getNextPageParam2, + initialPageParam, + // import('@tanstack/react-query').UseQueryOptions + _optimisticResults, + enabled, + notifyOnChangeProps, + placeholderData, + refetchInterval, + refetchIntervalInBackground, + refetchOnMount, + refetchOnReconnect, + refetchOnWindowFocus, + retryOnMount, + select, + staleTime, + suspense, + throwOnError, + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // wagmi + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + config: config2, + connector, + query, + ...rest + } = options; + return rest; +} +function connectMutationOptions(config2) { + return { + mutationFn(variables) { + return connect(config2, variables); + }, + mutationKey: ["connect"] + }; +} +function disconnectMutationOptions(config2) { + return { + mutationFn(variables) { + return disconnect(config2, variables); + }, + mutationKey: ["disconnect"] + }; +} +function getWalletClientQueryOptions(config2, options = {}) { + return { + gcTime: 0, + async queryFn({ queryKey }) { + const { connector } = options; + const { connectorUid: _, scopeKey: _s2, ...parameters } = queryKey[1]; + return getWalletClient(config2, { ...parameters, connector }); + }, + queryKey: getWalletClientQueryKey(options) + }; +} +function getWalletClientQueryKey(options = {}) { + const { connector, ...parameters } = options; + return [ + "walletClient", + { ...filterQueryOptions(parameters), connectorUid: connector == null ? void 0 : connector.uid } + ]; +} +function readContractQueryOptions(config2, options = {}) { + return { + // TODO: Support `signal` once Viem actions allow passthrough + // https://tkdodo.eu/blog/why-you-want-react-query#bonus-cancellation + async queryFn({ queryKey }) { + const abi2 = options.abi; + if (!abi2) + throw new Error("abi is required"); + const { functionName, scopeKey: _, ...parameters } = queryKey[1]; + const addressOrCodeParams = (() => { + const params = queryKey[1]; + if (params.address) + return { address: params.address }; + if (params.code) + return { code: params.code }; + throw new Error("address or code is required"); + })(); + if (!functionName) + throw new Error("functionName is required"); + return readContract(config2, { + abi: abi2, + functionName, + args: parameters.args, + ...addressOrCodeParams, + ...parameters + }); + }, + queryKey: readContractQueryKey(options) + }; +} +function readContractQueryKey(options = {}) { + const { abi: _, ...rest } = options; + return ["readContract", filterQueryOptions(rest)]; +} +function sendTransactionMutationOptions(config2) { + return { + mutationFn(variables) { + return sendTransaction(config2, variables); + }, + mutationKey: ["sendTransaction"] + }; +} +function switchChainMutationOptions(config2) { + return { + mutationFn(variables) { + return switchChain(config2, variables); + }, + mutationKey: ["switchChain"] + }; +} +function writeContractMutationOptions(config2) { + return { + mutationFn(variables) { + return writeContract(config2, variables); + }, + mutationKey: ["writeContract"] + }; +} +function useQuery(parameters) { + const result = useQuery$1({ + ...parameters, + queryKeyHashFn: hashFn + // for bigint support + }); + result.queryKey = parameters.queryKey; return result; } -class Block { - /** - * Create a new **Block** object. - * - * This should generally not be necessary as the unless implementing a - * low-level library. - */ - constructor(block, provider2) { - /** - * The provider connected to the block used to fetch additional details - * if necessary. - */ - __publicField(this, "provider"); - /** - * The block number, sometimes called the block height. This is a - * sequential number that is one higher than the parent block. - */ - __publicField(this, "number"); - /** - * The block hash. - * - * This hash includes all properties, so can be safely used to identify - * an exact set of block properties. - */ - __publicField(this, "hash"); - /** - * The timestamp for this block, which is the number of seconds since - * epoch that this block was included. - */ - __publicField(this, "timestamp"); - /** - * The block hash of the parent block. - */ - __publicField(this, "parentHash"); - /** - * The hash tree root of the parent beacon block for the given - * execution block. See [[link-eip-4788]]. - */ - __publicField(this, "parentBeaconBlockRoot"); - /** - * The nonce. - * - * On legacy networks, this is the random number inserted which - * permitted the difficulty target to be reached. - */ - __publicField(this, "nonce"); - /** - * The difficulty target. - * - * On legacy networks, this is the proof-of-work target required - * for a block to meet the protocol rules to be included. - * - * On modern networks, this is a random number arrived at using - * randao. @TODO: Find links? - */ - __publicField(this, "difficulty"); - /** - * The total gas limit for this block. - */ - __publicField(this, "gasLimit"); - /** - * The total gas used in this block. - */ - __publicField(this, "gasUsed"); - /** - * The root hash for the global state after applying changes - * in this block. - */ - __publicField(this, "stateRoot"); - /** - * The hash of the transaction receipts trie. - */ - __publicField(this, "receiptsRoot"); - /** - * The total amount of blob gas consumed by the transactions - * within the block. See [[link-eip-4844]]. - */ - __publicField(this, "blobGasUsed"); - /** - * The running total of blob gas consumed in excess of the - * target, prior to the block. See [[link-eip-4844]]. - */ - __publicField(this, "excessBlobGas"); - /** - * The miner coinbase address, wihch receives any subsidies for - * including this block. - */ - __publicField(this, "miner"); - /** - * The latest RANDAO mix of the post beacon state of - * the previous block. - */ - __publicField(this, "prevRandao"); - /** - * Any extra data the validator wished to include. - */ - __publicField(this, "extraData"); - /** - * The base fee per gas that all transactions in this block were - * charged. - * - * This adjusts after each block, depending on how congested the network - * is. - */ - __publicField(this, "baseFeePerGas"); - __privateAdd(this, _transactions); - __privateSet(this, _transactions, block.transactions.map((tx) => { - if (typeof tx !== "string") { - return new TransactionResponse(tx, provider2); - } - return tx; - })); - defineProperties$1(this, { - provider: provider2, - hash: getValue(block.hash), - number: block.number, - timestamp: block.timestamp, - parentHash: block.parentHash, - parentBeaconBlockRoot: block.parentBeaconBlockRoot, - nonce: block.nonce, - difficulty: block.difficulty, - gasLimit: block.gasLimit, - gasUsed: block.gasUsed, - blobGasUsed: block.blobGasUsed, - excessBlobGas: block.excessBlobGas, - miner: block.miner, - prevRandao: getValue(block.prevRandao), - extraData: block.extraData, - baseFeePerGas: getValue(block.baseFeePerGas), - stateRoot: block.stateRoot, - receiptsRoot: block.receiptsRoot - }); - } - /** - * Returns the list of transaction hashes, in the order - * they were executed within the block. - */ - get transactions() { - return __privateGet(this, _transactions).map((tx) => { - if (typeof tx === "string") { - return tx; - } - return tx.hash; - }); - } - /** - * Returns the complete transactions, in the order they - * were executed within the block. - * - * This is only available for blocks which prefetched - * transactions, by passing ``true`` to %%prefetchTxs%% - * into [[Provider-getBlock]]. - */ - get prefetchedTransactions() { - const txs = __privateGet(this, _transactions).slice(); - if (txs.length === 0) { - return []; - } - assert(typeof txs[0] === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", { - operation: "transactionResponses()" +function useChainId(parameters = {}) { + const config2 = useConfig(parameters); + return reactExports.useSyncExternalStore((onChange) => watchChainId(config2, { onChange }), () => getChainId$1(config2), () => getChainId$1(config2)); +} +function useChains(parameters = {}) { + const config2 = useConfig(parameters); + return reactExports.useSyncExternalStore((onChange) => watchChains(config2, { onChange }), () => getChains(config2), () => getChains(config2)); +} +function useConnectors(parameters = {}) { + const config2 = useConfig(parameters); + return reactExports.useSyncExternalStore((onChange) => watchConnectors(config2, { onChange }), () => getConnectors(config2), () => getConnectors(config2)); +} +function useConnect(parameters = {}) { + const { mutation } = parameters; + const config2 = useConfig(parameters); + const mutationOptions = connectMutationOptions(config2); + const { mutate, mutateAsync, ...result } = useMutation({ + ...mutation, + ...mutationOptions + }); + reactExports.useEffect(() => { + return config2.subscribe(({ status }) => status, (status, previousStatus) => { + if (previousStatus === "connected" && status === "disconnected") + result.reset(); }); - return txs; - } - /** - * Returns a JSON-friendly value. - */ - toJSON() { - const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash: hash2, miner, prevRandao, nonce, number: number2, parentHash, parentBeaconBlockRoot, stateRoot, receiptsRoot, timestamp, transactions: transactions2 } = this; - return { - _type: "Block", - baseFeePerGas: toJson(baseFeePerGas), - difficulty: toJson(difficulty), - extraData, - gasLimit: toJson(gasLimit), - gasUsed: toJson(gasUsed), - blobGasUsed: toJson(this.blobGasUsed), - excessBlobGas: toJson(this.excessBlobGas), - hash: hash2, - miner, - prevRandao, - nonce, - number: number2, - parentHash, - timestamp, - parentBeaconBlockRoot, - stateRoot, - receiptsRoot, - transactions: transactions2 - }; - } - [Symbol.iterator]() { - let index2 = 0; - const txs = this.transactions; - return { - next: () => { - if (index2 < this.length) { - return { - value: txs[index2++], - done: false - }; - } - return { value: void 0, done: true }; - } - }; - } - /** - * The number of transactions in this block. - */ - get length() { - return __privateGet(this, _transactions).length; - } - /** - * The [[link-js-date]] this block was included at. - */ - get date() { - if (this.timestamp == null) { - return null; - } - return new Date(this.timestamp * 1e3); - } - /** - * Get the transaction at %%indexe%% within this block. - */ - async getTransaction(indexOrHash) { - let tx = void 0; - if (typeof indexOrHash === "number") { - tx = __privateGet(this, _transactions)[indexOrHash]; - } else { - const hash2 = indexOrHash.toLowerCase(); - for (const v3 of __privateGet(this, _transactions)) { - if (typeof v3 === "string") { - if (v3 !== hash2) { - continue; - } - tx = v3; - break; - } else { - if (v3.hash === hash2) { - continue; - } - tx = v3; - break; - } - } - } - if (tx == null) { - throw new Error("no such tx"); - } - if (typeof tx === "string") { - return await this.provider.getTransaction(tx); - } else { - return tx; - } - } - /** - * If a **Block** was fetched with a request to include the transactions - * this will allow synchronous access to those transactions. - * - * If the transactions were not prefetched, this will throw. - */ - getPrefetchedTransaction(indexOrHash) { - const txs = this.prefetchedTransactions; - if (typeof indexOrHash === "number") { - return txs[indexOrHash]; - } - indexOrHash = indexOrHash.toLowerCase(); - for (const tx of txs) { - if (tx.hash === indexOrHash) { - return tx; - } - } - assertArgument(false, "no matching transaction", "indexOrHash", indexOrHash); - } - /** - * Returns true if this block been mined. This provides a type guard - * for all properties on a [[MinedBlock]]. - */ - isMined() { - return !!this.hash; - } - /** - * Returns true if this block is an [[link-eip-2930]] block. - */ - isLondon() { - return !!this.baseFeePerGas; - } - /** - * @_ignore: - */ - orphanedEvent() { - if (!this.isMined()) { - throw new Error(""); + }, [config2, result.reset]); + return { + ...result, + connect: mutate, + connectAsync: mutateAsync, + connectors: useConnectors({ config: config2 }) + }; +} +function useConnections(parameters = {}) { + const config2 = useConfig(parameters); + return reactExports.useSyncExternalStore((onChange) => watchConnections(config2, { onChange }), () => getConnections(config2), () => getConnections(config2)); +} +function useDisconnect(parameters = {}) { + const { mutation } = parameters; + const config2 = useConfig(parameters); + const mutationOptions = disconnectMutationOptions(config2); + const { mutate, mutateAsync, ...result } = useMutation({ + ...mutation, + ...mutationOptions + }); + return { + ...result, + connectors: useConnections({ config: config2 }).map((connection) => connection.connector), + disconnect: mutate, + disconnectAsync: mutateAsync + }; +} +function usePublicClient(parameters = {}) { + const config2 = useConfig(parameters); + return withSelectorExports.useSyncExternalStoreWithSelector((onChange) => watchPublicClient(config2, { onChange }), () => getPublicClient(config2, parameters), () => getPublicClient(config2, parameters), (x2) => x2, (a2, b2) => (a2 == null ? void 0 : a2.uid) === (b2 == null ? void 0 : b2.uid)); +} +function useReadContract(parameters = {}) { + const { abi: abi2, address, functionName, query = {} } = parameters; + const code2 = parameters.code; + const config2 = useConfig(parameters); + const chainId = useChainId({ config: config2 }); + const options = readContractQueryOptions(config2, { ...parameters, chainId: parameters.chainId ?? chainId }); + const enabled = Boolean((address || code2) && abi2 && functionName && (query.enabled ?? true)); + return useQuery({ + ...query, + ...options, + enabled, + structuralSharing: query.structuralSharing ?? structuralSharing + }); +} +function useSendTransaction(parameters = {}) { + const { mutation } = parameters; + const config2 = useConfig(parameters); + const mutationOptions = sendTransactionMutationOptions(config2); + const { mutate, mutateAsync, ...result } = useMutation({ + ...mutation, + ...mutationOptions + }); + return { + ...result, + sendTransaction: mutate, + sendTransactionAsync: mutateAsync + }; +} +function useSwitchChain(parameters = {}) { + const { mutation } = parameters; + const config2 = useConfig(parameters); + const mutationOptions = switchChainMutationOptions(config2); + const { mutate, mutateAsync, ...result } = useMutation({ + ...mutation, + ...mutationOptions + }); + return { + ...result, + chains: useChains({ config: config2 }), + switchChain: mutate, + switchChainAsync: mutateAsync + }; +} +function useWalletClient(parameters = {}) { + const { query = {}, ...rest } = parameters; + const config2 = useConfig(rest); + const queryClient = useQueryClient(); + const { address, connector, status } = useAccount({ config: config2 }); + const chainId = useChainId({ config: config2 }); + const activeConnector = parameters.connector ?? connector; + const { queryKey, ...options } = getWalletClientQueryOptions(config2, { + ...parameters, + chainId: parameters.chainId ?? chainId, + connector: parameters.connector ?? connector + }); + const enabled = Boolean((status === "connected" || status === "reconnecting" && (activeConnector == null ? void 0 : activeConnector.getProvider)) && (query.enabled ?? true)); + const addressRef = reactExports.useRef(address); + reactExports.useEffect(() => { + const previousAddress = addressRef.current; + if (!address && previousAddress) { + queryClient.removeQueries({ queryKey }); + addressRef.current = void 0; + } else if (address !== previousAddress) { + queryClient.invalidateQueries({ queryKey }); + addressRef.current = address; } - return createOrphanedBlockFilter(this); - } + }, [address, queryClient]); + return useQuery({ + ...query, + ...options, + queryKey, + enabled, + staleTime: Number.POSITIVE_INFINITY + }); } -_transactions = new WeakMap(); -class Log { - /** - * @_ignore: - */ - constructor(log, provider2) { - /** - * The provider connected to the log used to fetch additional details - * if necessary. - */ - __publicField(this, "provider"); - /** - * The transaction hash of the transaction this log occurred in. Use the - * [[Log-getTransaction]] to get the [[TransactionResponse]]. - */ - __publicField(this, "transactionHash"); - /** - * The block hash of the block this log occurred in. Use the - * [[Log-getBlock]] to get the [[Block]]. - */ - __publicField(this, "blockHash"); - /** - * The block number of the block this log occurred in. It is preferred - * to use the [[Block-hash]] when fetching the related [[Block]], - * since in the case of an orphaned block, the block at that height may - * have changed. - */ - __publicField(this, "blockNumber"); - /** - * If the **Log** represents a block that was removed due to an orphaned - * block, this will be true. - * - * This can only happen within an orphan event listener. - */ - __publicField(this, "removed"); - /** - * The address of the contract that emitted this log. - */ - __publicField(this, "address"); - /** - * The data included in this log when it was emitted. - */ - __publicField(this, "data"); - /** - * The indexed topics included in this log when it was emitted. - * - * All topics are included in the bloom filters, so they can be - * efficiently filtered using the [[Provider-getLogs]] method. - */ - __publicField(this, "topics"); - /** - * The index within the block this log occurred at. This is generally - * not useful to developers, but can be used with the various roots - * to proof inclusion within a block. - */ - __publicField(this, "index"); - /** - * The index within the transaction of this log. - */ - __publicField(this, "transactionIndex"); - this.provider = provider2; - const topics = Object.freeze(log.topics.slice()); - defineProperties$1(this, { - transactionHash: log.transactionHash, - blockHash: log.blockHash, - blockNumber: log.blockNumber, - removed: log.removed, - address: log.address, - data: log.data, - topics, - index: log.index, - transactionIndex: log.transactionIndex - }); - } - /** - * Returns a JSON-compatible object. - */ - toJSON() { - const { address, blockHash, blockNumber, data, index: index2, removed, topics, transactionHash, transactionIndex } = this; - return { - _type: "log", - address, - blockHash, - blockNumber, - data, - index: index2, - removed, - topics, - transactionHash, - transactionIndex - }; - } - /** - * Returns the block that this log occurred in. - */ - async getBlock() { - const block = await this.provider.getBlock(this.blockHash); - assert(!!block, "failed to find transaction", "UNKNOWN_ERROR", {}); - return block; - } - /** - * Returns the transaction that this log occurred in. - */ - async getTransaction() { - const tx = await this.provider.getTransaction(this.transactionHash); - assert(!!tx, "failed to find transaction", "UNKNOWN_ERROR", {}); - return tx; - } - /** - * Returns the transaction receipt fot the transaction that this - * log occurred in. - */ - async getTransactionReceipt() { - const receipt = await this.provider.getTransactionReceipt(this.transactionHash); - assert(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", {}); - return receipt; - } - /** - * @_ignore: - */ - removedEvent() { - return createRemovedLogFilter(this); - } +function useWriteContract(parameters = {}) { + const { mutation } = parameters; + const config2 = useConfig(parameters); + const mutationOptions = writeContractMutationOptions(config2); + const { mutate, mutateAsync, ...result } = useMutation({ + ...mutation, + ...mutationOptions + }); + return { + ...result, + writeContract: mutate, + writeContractAsync: mutateAsync + }; } -class TransactionReceipt { - /** - * @_ignore: - */ - constructor(tx, provider2) { - /** - * The provider connected to the log used to fetch additional details - * if necessary. - */ - __publicField(this, "provider"); - /** - * The address the transaction was sent to. - */ - __publicField(this, "to"); - /** - * The sender of the transaction. - */ - __publicField(this, "from"); - /** - * The address of the contract if the transaction was directly - * responsible for deploying one. - * - * This is non-null **only** if the ``to`` is empty and the ``data`` - * was successfully executed as initcode. - */ - __publicField(this, "contractAddress"); - /** - * The transaction hash. - */ - __publicField(this, "hash"); - /** - * The index of this transaction within the block transactions. - */ - __publicField(this, "index"); - /** - * The block hash of the [[Block]] this transaction was included in. - */ - __publicField(this, "blockHash"); - /** - * The block number of the [[Block]] this transaction was included in. - */ - __publicField(this, "blockNumber"); - /** - * The bloom filter bytes that represent all logs that occurred within - * this transaction. This is generally not useful for most developers, - * but can be used to validate the included logs. - */ - __publicField(this, "logsBloom"); - /** - * The actual amount of gas used by this transaction. - * - * When creating a transaction, the amount of gas that will be used can - * only be approximated, but the sender must pay the gas fee for the - * entire gas limit. After the transaction, the difference is refunded. - */ - __publicField(this, "gasUsed"); - /** - * The gas used for BLObs. See [[link-eip-4844]]. - */ - __publicField(this, "blobGasUsed"); - /** - * The amount of gas used by all transactions within the block for this - * and all transactions with a lower ``index``. - * - * This is generally not useful for developers but can be used to - * validate certain aspects of execution. - */ - __publicField(this, "cumulativeGasUsed"); - /** - * The actual gas price used during execution. - * - * Due to the complexity of [[link-eip-1559]] this value can only - * be caluclated after the transaction has been mined, snce the base - * fee is protocol-enforced. - */ - __publicField(this, "gasPrice"); - /** - * The price paid per BLOB in gas. See [[link-eip-4844]]. - */ - __publicField(this, "blobGasPrice"); - /** - * The [[link-eip-2718]] transaction type. - */ - __publicField(this, "type"); - //readonly byzantium!: boolean; - /** - * The status of this transaction, indicating success (i.e. ``1``) or - * a revert (i.e. ``0``). - * - * This is available in post-byzantium blocks, but some backends may - * backfill this value. - */ - __publicField(this, "status"); - /** - * The root hash of this transaction. - * - * This is no present and was only included in pre-byzantium blocks, but - * could be used to validate certain parts of the receipt. - */ - __publicField(this, "root"); - __privateAdd(this, _logs); - __privateSet(this, _logs, Object.freeze(tx.logs.map((log) => { - return new Log(log, provider2); - }))); - let gasPrice = BN_0$2; - if (tx.effectiveGasPrice != null) { - gasPrice = tx.effectiveGasPrice; - } else if (tx.gasPrice != null) { - gasPrice = tx.gasPrice; - } - defineProperties$1(this, { - provider: provider2, - to: tx.to, - from: tx.from, - contractAddress: tx.contractAddress, - hash: tx.hash, - index: tx.index, - blockHash: tx.blockHash, - blockNumber: tx.blockNumber, - logsBloom: tx.logsBloom, - gasUsed: tx.gasUsed, - cumulativeGasUsed: tx.cumulativeGasUsed, - blobGasUsed: tx.blobGasUsed, - gasPrice, - blobGasPrice: tx.blobGasPrice, - type: tx.type, - //byzantium: tx.byzantium, - status: tx.status, - root: tx.root - }); - } - /** - * The logs for this transaction. - */ - get logs() { - return __privateGet(this, _logs); - } - /** - * Returns a JSON-compatible representation. - */ - toJSON() { - const { - to, - from, - contractAddress, - hash: hash2, - index: index2, - blockHash, - blockNumber, - logsBloom, - logs, - //byzantium, - status, - root: root2 - } = this; - return { - _type: "TransactionReceipt", - blockHash, - blockNumber, - //byzantium, - contractAddress, - cumulativeGasUsed: toJson(this.cumulativeGasUsed), - from, - gasPrice: toJson(this.gasPrice), - blobGasUsed: toJson(this.blobGasUsed), - blobGasPrice: toJson(this.blobGasPrice), - gasUsed: toJson(this.gasUsed), - hash: hash2, - index: index2, - logs, - logsBloom, - root: root2, - status, - to - }; - } - /** - * @_ignore: - */ - get length() { - return this.logs.length; - } - [Symbol.iterator]() { - let index2 = 0; - return { - next: () => { - if (index2 < this.length) { - return { value: this.logs[index2++], done: false }; - } - return { value: void 0, done: true }; - } - }; - } - /** - * The total fee for this transaction, in wei. - */ - get fee() { - return this.gasUsed * this.gasPrice; - } - /** - * Resolves to the block this transaction occurred in. - */ - async getBlock() { - const block = await this.provider.getBlock(this.blockHash); - if (block == null) { - throw new Error("TODO"); - } - return block; - } - /** - * Resolves to the transaction this transaction occurred in. - */ - async getTransaction() { - const tx = await this.provider.getTransaction(this.hash); - if (tx == null) { - throw new Error("TODO"); - } - return tx; - } - /** - * Resolves to the return value of the execution of this transaction. - * - * Support for this feature is limited, as it requires an archive node - * with the ``debug_`` or ``trace_`` API enabled. - */ - async getResult() { - return await this.provider.getTransactionResult(this.hash); - } - /** - * Resolves to the number of confirmations this transaction has. - */ - async confirmations() { - return await this.provider.getBlockNumber() - this.blockNumber + 1; - } - /** - * @_ignore: - */ - removedEvent() { - return createRemovedTransactionFilter(this); - } - /** - * @_ignore: - */ - reorderedEvent(other) { - assert(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" }); - return createReorderedTransactionFilter(this, other); - } -} -_logs = new WeakMap(); -const _TransactionResponse = class _TransactionResponse { - /** - * @_ignore: - */ - constructor(tx, provider2) { - /** - * The provider this is connected to, which will influence how its - * methods will resolve its async inspection methods. - */ - __publicField(this, "provider"); - /** - * The block number of the block that this transaction was included in. - * - * This is ``null`` for pending transactions. - */ - __publicField(this, "blockNumber"); - /** - * The blockHash of the block that this transaction was included in. - * - * This is ``null`` for pending transactions. - */ - __publicField(this, "blockHash"); - /** - * The index within the block that this transaction resides at. - */ - __publicField(this, "index"); - /** - * The transaction hash. - */ - __publicField(this, "hash"); - /** - * The [[link-eip-2718]] transaction envelope type. This is - * ``0`` for legacy transactions types. - */ - __publicField(this, "type"); - /** - * The receiver of this transaction. - * - * If ``null``, then the transaction is an initcode transaction. - * This means the result of executing the [[data]] will be deployed - * as a new contract on chain (assuming it does not revert) and the - * address may be computed using [[getCreateAddress]]. - */ - __publicField(this, "to"); - /** - * The sender of this transaction. It is implicitly computed - * from the transaction pre-image hash (as the digest) and the - * [[signature]] using ecrecover. - */ - __publicField(this, "from"); - /** - * The nonce, which is used to prevent replay attacks and offer - * a method to ensure transactions from a given sender are explicitly - * ordered. - * - * When sending a transaction, this must be equal to the number of - * transactions ever sent by [[from]]. - */ - __publicField(this, "nonce"); - /** - * The maximum units of gas this transaction can consume. If execution - * exceeds this, the entries transaction is reverted and the sender - * is charged for the full amount, despite not state changes being made. - */ - __publicField(this, "gasLimit"); - /** - * The gas price can have various values, depending on the network. - * - * In modern networks, for transactions that are included this is - * the //effective gas price// (the fee per gas that was actually - * charged), while for transactions that have not been included yet - * is the [[maxFeePerGas]]. - * - * For legacy transactions, or transactions on legacy networks, this - * is the fee that will be charged per unit of gas the transaction - * consumes. - */ - __publicField(this, "gasPrice"); - /** - * The maximum priority fee (per unit of gas) to allow a - * validator to charge the sender. This is inclusive of the - * [[maxFeeFeePerGas]]. - */ - __publicField(this, "maxPriorityFeePerGas"); - /** - * The maximum fee (per unit of gas) to allow this transaction - * to charge the sender. - */ - __publicField(this, "maxFeePerGas"); - /** - * The [[link-eip-4844]] max fee per BLOb gas. - */ - __publicField(this, "maxFeePerBlobGas"); - /** - * The data. - */ - __publicField(this, "data"); - /** - * The value, in wei. Use [[formatEther]] to format this value - * as ether. - */ - __publicField(this, "value"); - /** - * The chain ID. - */ - __publicField(this, "chainId"); - /** - * The signature. - */ - __publicField(this, "signature"); - /** - * The [[link-eip-2930]] access list for transaction types that - * support it, otherwise ``null``. - */ - __publicField(this, "accessList"); - /** - * The [[link-eip-4844]] BLOb versioned hashes. - */ - __publicField(this, "blobVersionedHashes"); - __privateAdd(this, _startBlock); - this.provider = provider2; - this.blockNumber = tx.blockNumber != null ? tx.blockNumber : null; - this.blockHash = tx.blockHash != null ? tx.blockHash : null; - this.hash = tx.hash; - this.index = tx.index; - this.type = tx.type; - this.from = tx.from; - this.to = tx.to || null; - this.gasLimit = tx.gasLimit; - this.nonce = tx.nonce; - this.data = tx.data; - this.value = tx.value; - this.gasPrice = tx.gasPrice; - this.maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? tx.maxPriorityFeePerGas : null; - this.maxFeePerGas = tx.maxFeePerGas != null ? tx.maxFeePerGas : null; - this.maxFeePerBlobGas = tx.maxFeePerBlobGas != null ? tx.maxFeePerBlobGas : null; - this.chainId = tx.chainId; - this.signature = tx.signature; - this.accessList = tx.accessList != null ? tx.accessList : null; - this.blobVersionedHashes = tx.blobVersionedHashes != null ? tx.blobVersionedHashes : null; - __privateSet(this, _startBlock, -1); - } - /** - * Returns a JSON-compatible representation of this transaction. - */ - toJSON() { - const { blockNumber, blockHash, index: index2, hash: hash2, type, to, from, nonce, data, signature: signature2, accessList, blobVersionedHashes } = this; - return { - _type: "TransactionResponse", - accessList, - blockNumber, - blockHash, - blobVersionedHashes, - chainId: toJson(this.chainId), - data, - from, - gasLimit: toJson(this.gasLimit), - gasPrice: toJson(this.gasPrice), - hash: hash2, - maxFeePerGas: toJson(this.maxFeePerGas), - maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), - maxFeePerBlobGas: toJson(this.maxFeePerBlobGas), - nonce, - signature: signature2, - to, - index: index2, - type, - value: toJson(this.value) - }; - } - /** - * Resolves to the Block that this transaction was included in. - * - * This will return null if the transaction has not been included yet. - */ - async getBlock() { - let blockNumber = this.blockNumber; - if (blockNumber == null) { - const tx = await this.getTransaction(); - if (tx) { - blockNumber = tx.blockNumber; - } - } - if (blockNumber == null) { - return null; - } - const block = this.provider.getBlock(blockNumber); - if (block == null) { - throw new Error("TODO"); - } - return block; - } - /** - * Resolves to this transaction being re-requested from the - * provider. This can be used if you have an unmined transaction - * and wish to get an up-to-date populated instance. - */ - async getTransaction() { - return this.provider.getTransaction(this.hash); - } - /** - * Resolve to the number of confirmations this transaction has. - */ - async confirmations() { - if (this.blockNumber == null) { - const { tx, blockNumber: blockNumber2 } = await resolveProperties$1({ - tx: this.getTransaction(), - blockNumber: this.provider.getBlockNumber() - }); - if (tx == null || tx.blockNumber == null) { - return 0; - } - return blockNumber2 - tx.blockNumber + 1; - } - const blockNumber = await this.provider.getBlockNumber(); - return blockNumber - this.blockNumber + 1; - } - /** - * Resolves once this transaction has been mined and has - * %%confirms%% blocks including it (default: ``1``) with an - * optional %%timeout%%. - * - * This can resolve to ``null`` only if %%confirms%% is ``0`` - * and the transaction has not been mined, otherwise this will - * wait until enough confirmations have completed. - */ - async wait(_confirms, _timeout2) { - const confirms = _confirms == null ? 1 : _confirms; - const timeout = _timeout2 == null ? 0 : _timeout2; - let startBlock = __privateGet(this, _startBlock); - let nextScan = -1; - let stopScanning = startBlock === -1 ? true : false; - const checkReplacement = async () => { - if (stopScanning) { - return null; - } - const { blockNumber, nonce } = await resolveProperties$1({ - blockNumber: this.provider.getBlockNumber(), - nonce: this.provider.getTransactionCount(this.from) - }); - if (nonce < this.nonce) { - startBlock = blockNumber; - return; - } - if (stopScanning) { - return null; - } - const mined = await this.getTransaction(); - if (mined && mined.blockNumber != null) { - return; - } - if (nextScan === -1) { - nextScan = startBlock - 3; - if (nextScan < __privateGet(this, _startBlock)) { - nextScan = __privateGet(this, _startBlock); - } - } - while (nextScan <= blockNumber) { - if (stopScanning) { - return null; - } - const block = await this.provider.getBlock(nextScan, true); - if (block == null) { - return; - } - for (const hash2 of block) { - if (hash2 === this.hash) { - return; - } - } - for (let i = 0; i < block.length; i++) { - const tx = await block.getTransaction(i); - if (tx.from === this.from && tx.nonce === this.nonce) { - if (stopScanning) { - return null; - } - const receipt2 = await this.provider.getTransactionReceipt(tx.hash); - if (receipt2 == null) { - return; - } - if (blockNumber - receipt2.blockNumber + 1 < confirms) { - return; - } - let reason = "replaced"; - if (tx.data === this.data && tx.to === this.to && tx.value === this.value) { - reason = "repriced"; - } else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0$2) { - reason = "cancelled"; - } - assert(false, "transaction was replaced", "TRANSACTION_REPLACED", { - cancelled: reason === "replaced" || reason === "cancelled", - reason, - replacement: tx.replaceableTransaction(startBlock), - hash: tx.hash, - receipt: receipt2 - }); - } - } - nextScan++; - } - return; - }; - const checkReceipt = (receipt2) => { - if (receipt2 == null || receipt2.status !== 0) { - return receipt2; - } - assert(false, "transaction execution reverted", "CALL_EXCEPTION", { - action: "sendTransaction", - data: null, - reason: null, - invocation: null, - revert: null, - transaction: { - to: receipt2.to, - from: receipt2.from, - data: "" - // @TODO: in v7, split out sendTransaction properties - }, - receipt: receipt2 - }); - }; - const receipt = await this.provider.getTransactionReceipt(this.hash); - if (confirms === 0) { - return checkReceipt(receipt); - } - if (receipt) { - if (await receipt.confirmations() >= confirms) { - return checkReceipt(receipt); - } - } else { - await checkReplacement(); - if (confirms === 0) { - return null; - } - } - const waiter = new Promise((resolve, reject) => { - const cancellers = []; - const cancel = () => { - cancellers.forEach((c2) => c2()); - }; - cancellers.push(() => { - stopScanning = true; - }); - if (timeout > 0) { - const timer = setTimeout(() => { - cancel(); - reject(makeError("wait for transaction timeout", "TIMEOUT")); - }, timeout); - cancellers.push(() => { - clearTimeout(timer); - }); - } - const txListener = async (receipt2) => { - if (await receipt2.confirmations() >= confirms) { - cancel(); - try { - resolve(checkReceipt(receipt2)); - } catch (error) { - reject(error); - } - } - }; - cancellers.push(() => { - this.provider.off(this.hash, txListener); - }); - this.provider.on(this.hash, txListener); - if (startBlock >= 0) { - const replaceListener = async () => { - try { - await checkReplacement(); - } catch (error) { - if (isError(error, "TRANSACTION_REPLACED")) { - cancel(); - reject(error); - return; - } - } - if (!stopScanning) { - this.provider.once("block", replaceListener); - } - }; - cancellers.push(() => { - this.provider.off("block", replaceListener); - }); - this.provider.once("block", replaceListener); - } - }); - return await waiter; - } - /** - * Returns ``true`` if this transaction has been included. - * - * This is effective only as of the time the TransactionResponse - * was instantiated. To get up-to-date information, use - * [[getTransaction]]. - * - * This provides a Type Guard that this transaction will have - * non-null property values for properties that are null for - * unmined transactions. - */ - isMined() { - return this.blockHash != null; - } - /** - * Returns true if the transaction is a legacy (i.e. ``type == 0``) - * transaction. - * - * This provides a Type Guard that this transaction will have - * the ``null``-ness for hardfork-specific properties set correctly. - */ - isLegacy() { - return this.type === 0; - } - /** - * Returns true if the transaction is a Berlin (i.e. ``type == 1``) - * transaction. See [[link-eip-2070]]. - * - * This provides a Type Guard that this transaction will have - * the ``null``-ness for hardfork-specific properties set correctly. - */ - isBerlin() { - return this.type === 1; - } - /** - * Returns true if the transaction is a London (i.e. ``type == 2``) - * transaction. See [[link-eip-1559]]. - * - * This provides a Type Guard that this transaction will have - * the ``null``-ness for hardfork-specific properties set correctly. - */ - isLondon() { - return this.type === 2; - } - /** - * Returns true if hte transaction is a Cancun (i.e. ``type == 3``) - * transaction. See [[link-eip-4844]]. - */ - isCancun() { - return this.type === 3; - } - /** - * Returns a filter which can be used to listen for orphan events - * that evict this transaction. - */ - removedEvent() { - assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); - return createRemovedTransactionFilter(this); - } - /** - * Returns a filter which can be used to listen for orphan events - * that re-order this event against %%other%%. - */ - reorderedEvent(other) { - assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); - assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); - return createReorderedTransactionFilter(this, other); - } - /** - * Returns a new TransactionResponse instance which has the ability to - * detect (and throw an error) if the transaction is replaced, which - * will begin scanning at %%startBlock%%. - * - * This should generally not be used by developers and is intended - * primarily for internal use. Setting an incorrect %%startBlock%% can - * have devastating performance consequences if used incorrectly. - */ - replaceableTransaction(startBlock) { - assertArgument(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock); - const tx = new _TransactionResponse(this, this.provider); - __privateSet(tx, _startBlock, startBlock); - return tx; - } -}; -_startBlock = new WeakMap(); -let TransactionResponse = _TransactionResponse; -function createOrphanedBlockFilter(block) { - return { orphan: "drop-block", hash: block.hash, number: block.number }; -} -function createReorderedTransactionFilter(tx, other) { - return { orphan: "reorder-transaction", tx, other }; -} -function createRemovedTransactionFilter(tx) { - return { orphan: "drop-transaction", tx }; -} -function createRemovedLogFilter(log) { - return { orphan: "drop-log", log: { - transactionHash: log.transactionHash, - blockHash: log.blockHash, - blockNumber: log.blockNumber, - address: log.address, - data: log.data, - topics: Object.freeze(log.topics.slice()), - index: log.index - } }; -} -class EventLog extends Log { - /** - * @_ignore: - */ - constructor(log, iface, fragment) { - super(log, log.provider); - /** - * The Contract Interface. - */ - __publicField(this, "interface"); - /** - * The matching event. - */ - __publicField(this, "fragment"); - /** - * The parsed arguments passed to the event by ``emit``. - */ - __publicField(this, "args"); - const args = iface.decodeEventLog(fragment, log.data, log.topics); - defineProperties$1(this, { args, fragment, interface: iface }); - } - /** - * The name of the event. - */ - get eventName() { - return this.fragment.name; - } - /** - * The signature of the event. - */ - get eventSignature() { - return this.fragment.format(); - } -} -class UndecodedEventLog extends Log { - /** - * @_ignore: - */ - constructor(log, error) { - super(log, log.provider); - /** - * The error encounted when trying to decode the log. - */ - __publicField(this, "error"); - defineProperties$1(this, { error }); - } -} -class ContractTransactionReceipt extends TransactionReceipt { - /** - * @_ignore: - */ - constructor(iface, provider2, tx) { - super(tx, provider2); - __privateAdd(this, _iface); - __privateSet(this, _iface, iface); - } - /** - * The parsed logs for any [[Log]] which has a matching event in the - * Contract ABI. - */ - get logs() { - return super.logs.map((log) => { - const fragment = log.topics.length ? __privateGet(this, _iface).getEvent(log.topics[0]) : null; - if (fragment) { - try { - return new EventLog(log, __privateGet(this, _iface), fragment); - } catch (error) { - return new UndecodedEventLog(log, error); - } - } - return log; - }); - } -} -_iface = new WeakMap(); -class ContractTransactionResponse extends TransactionResponse { - /** - * @_ignore: - */ - constructor(iface, provider2, tx) { - super(tx, provider2); - __privateAdd(this, _iface2); - __privateSet(this, _iface2, iface); - } - /** - * Resolves once this transaction has been mined and has - * %%confirms%% blocks including it (default: ``1``) with an - * optional %%timeout%%. - * - * This can resolve to ``null`` only if %%confirms%% is ``0`` - * and the transaction has not been mined, otherwise this will - * wait until enough confirmations have completed. - */ - async wait(confirms, timeout) { - const receipt = await super.wait(confirms, timeout); - if (receipt == null) { - return null; - } - return new ContractTransactionReceipt(__privateGet(this, _iface2), this.provider, receipt); - } -} -_iface2 = new WeakMap(); -class ContractUnknownEventPayload extends EventPayload { - /** - * @_event: - */ - constructor(contract, listener, filter2, log) { - super(contract, listener, filter2); - /** - * The log with no matching events. - */ - __publicField(this, "log"); - defineProperties$1(this, { log }); - } - /** - * Resolves to the block the event occured in. - */ - async getBlock() { - return await this.log.getBlock(); - } - /** - * Resolves to the transaction the event occured in. - */ - async getTransaction() { - return await this.log.getTransaction(); - } - /** - * Resolves to the transaction receipt the event occured in. - */ - async getTransactionReceipt() { - return await this.log.getTransactionReceipt(); - } -} -class ContractEventPayload extends ContractUnknownEventPayload { - /** - * @_ignore: - */ - constructor(contract, listener, filter2, fragment, _log) { - super(contract, listener, filter2, new EventLog(_log, contract.interface, fragment)); - const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics); - defineProperties$1(this, { args, fragment }); - } - /** - * The event name. - */ - get eventName() { - return this.fragment.name; - } - /** - * The event signature. - */ - get eventSignature() { - return this.fragment.format(); - } -} -const BN_0$1 = BigInt(0); -function canCall(value) { - return value && typeof value.call === "function"; -} -function canEstimate(value) { - return value && typeof value.estimateGas === "function"; -} -function canResolve(value) { - return value && typeof value.resolveName === "function"; -} -function canSend(value) { - return value && typeof value.sendTransaction === "function"; -} -function getResolver(value) { - if (value != null) { - if (canResolve(value)) { - return value; - } - if (value.provider) { - return value.provider; - } - } - return void 0; -} -class PreparedTopicFilter { - constructor(contract, fragment, args) { - __privateAdd(this, _filter); - __publicField(this, "fragment"); - defineProperties$1(this, { fragment }); - if (fragment.inputs.length < args.length) { - throw new Error("too many arguments"); - } - const runner = getRunner(contract.runner, "resolveName"); - const resolver = canResolve(runner) ? runner : null; - __privateSet(this, _filter, async function() { - const resolvedArgs = await Promise.all(fragment.inputs.map((param, index2) => { - const arg = args[index2]; - if (arg == null) { - return null; - } - return param.walkAsync(args[index2], (type, value) => { - if (type === "address") { - if (Array.isArray(value)) { - return Promise.all(value.map((v3) => resolveAddress(v3, resolver))); - } - return resolveAddress(value, resolver); - } - return value; - }); - })); - return contract.interface.encodeFilterTopics(fragment, resolvedArgs); - }()); - } - getTopicFilter() { - return __privateGet(this, _filter); - } -} -_filter = new WeakMap(); -function getRunner(value, feature) { - if (value == null) { - return null; - } - if (typeof value[feature] === "function") { - return value; - } - if (value.provider && typeof value.provider[feature] === "function") { - return value.provider; - } - return null; -} -function getProvider(value) { - if (value == null) { - return null; - } - return value.provider || null; -} -async function copyOverrides(arg, allowed) { - const _overrides = Typed.dereference(arg, "overrides"); - assertArgument(typeof _overrides === "object", "invalid overrides parameter", "overrides", arg); - const overrides = copyRequest(_overrides); - assertArgument(overrides.to == null || (allowed || []).indexOf("to") >= 0, "cannot override to", "overrides.to", overrides.to); - assertArgument(overrides.data == null || (allowed || []).indexOf("data") >= 0, "cannot override data", "overrides.data", overrides.data); - if (overrides.from) { - overrides.from = overrides.from; - } - return overrides; -} -async function resolveArgs(_runner, inputs, args) { - const runner = getRunner(_runner, "resolveName"); - const resolver = canResolve(runner) ? runner : null; - return await Promise.all(inputs.map((param, index2) => { - return param.walkAsync(args[index2], (type, value) => { - value = Typed.dereference(value, type); - if (type === "address") { - return resolveAddress(value, resolver); - } - return value; - }); - })); -} -function buildWrappedFallback(contract) { - const populateTransaction = async function(overrides) { - const tx = await copyOverrides(overrides, ["data"]); - tx.to = await contract.getAddress(); - if (tx.from) { - tx.from = await resolveAddress(tx.from, getResolver(contract.runner)); - } - const iface = contract.interface; - const noValue = getBigInt(tx.value || BN_0$1, "overrides.value") === BN_0$1; - const noData = (tx.data || "0x") === "0x"; - if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) { - assertArgument(false, "cannot send data to receive or send value to non-payable fallback", "overrides", overrides); - } - assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); - const payable = iface.receive || iface.fallback && iface.fallback.payable; - assertArgument(payable || noValue, "cannot send value to non-payable fallback", "overrides.value", tx.value); - assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); - return tx; - }; - const staticCall = async function(overrides) { - const runner = getRunner(contract.runner, "call"); - assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); - const tx = await populateTransaction(overrides); - try { - return await runner.call(tx); - } catch (error) { - if (isCallException(error) && error.data) { - throw contract.interface.makeError(error.data, tx); - } - throw error; - } - }; - const send = async function(overrides) { - const runner = contract.runner; - assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); - const tx = await runner.sendTransaction(await populateTransaction(overrides)); - const provider2 = getProvider(contract.runner); - return new ContractTransactionResponse(contract.interface, provider2, tx); - }; - const estimateGas2 = async function(overrides) { - const runner = getRunner(contract.runner, "estimateGas"); - assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); - return await runner.estimateGas(await populateTransaction(overrides)); - }; - const method = async (overrides) => { - return await send(overrides); - }; - defineProperties$1(method, { - _contract: contract, - estimateGas: estimateGas2, - populateTransaction, - send, - staticCall - }); - return method; -} -function buildWrappedMethod(contract, key) { - const getFragment = function(...args) { - const fragment = contract.interface.getFunction(key, args); - assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { - operation: "fragment", - info: { key, args } - }); - return fragment; - }; - const populateTransaction = async function(...args) { - const fragment = getFragment(...args); - let overrides = {}; - if (fragment.inputs.length + 1 === args.length) { - overrides = await copyOverrides(args.pop()); - if (overrides.from) { - overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner)); - } - } - if (fragment.inputs.length !== args.length) { - throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); - } - const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); - return Object.assign({}, overrides, await resolveProperties$1({ - to: contract.getAddress(), - data: contract.interface.encodeFunctionData(fragment, resolvedArgs) - })); - }; - const staticCall = async function(...args) { - const result = await staticCallResult(...args); - if (result.length === 1) { - return result[0]; - } - return result; - }; - const send = async function(...args) { - const runner = contract.runner; - assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); - const tx = await runner.sendTransaction(await populateTransaction(...args)); - const provider2 = getProvider(contract.runner); - return new ContractTransactionResponse(contract.interface, provider2, tx); - }; - const estimateGas2 = async function(...args) { - const runner = getRunner(contract.runner, "estimateGas"); - assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); - return await runner.estimateGas(await populateTransaction(...args)); - }; - const staticCallResult = async function(...args) { - const runner = getRunner(contract.runner, "call"); - assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); - const tx = await populateTransaction(...args); - let result = "0x"; - try { - result = await runner.call(tx); - } catch (error) { - if (isCallException(error) && error.data) { - throw contract.interface.makeError(error.data, tx); - } - throw error; - } - const fragment = getFragment(...args); - return contract.interface.decodeFunctionResult(fragment, result); - }; - const method = async (...args) => { - const fragment = getFragment(...args); - if (fragment.constant) { - return await staticCall(...args); - } - return await send(...args); - }; - defineProperties$1(method, { - name: contract.interface.getFunctionName(key), - _contract: contract, - _key: key, - getFragment, - estimateGas: estimateGas2, - populateTransaction, - send, - staticCall, - staticCallResult - }); - Object.defineProperty(method, "fragment", { - configurable: false, - enumerable: true, - get: () => { - const fragment = contract.interface.getFunction(key); - assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { - operation: "fragment", - info: { key } - }); - return fragment; - } - }); - return method; -} -function buildWrappedEvent(contract, key) { - const getFragment = function(...args) { - const fragment = contract.interface.getEvent(key, args); - assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { - operation: "fragment", - info: { key, args } - }); - return fragment; - }; - const method = function(...args) { - return new PreparedTopicFilter(contract, getFragment(...args), args); - }; - defineProperties$1(method, { - name: contract.interface.getEventName(key), - _contract: contract, - _key: key, - getFragment - }); - Object.defineProperty(method, "fragment", { - configurable: false, - enumerable: true, - get: () => { - const fragment = contract.interface.getEvent(key); - assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { - operation: "fragment", - info: { key } - }); - return fragment; - } - }); - return method; -} -const internal = Symbol.for("_ethersInternal_contract"); -const internalValues = /* @__PURE__ */ new WeakMap(); -function setInternal(contract, values) { - internalValues.set(contract[internal], values); -} -function getInternal(contract) { - return internalValues.get(contract[internal]); -} -function isDeferred(value) { - return value && typeof value === "object" && "getTopicFilter" in value && typeof value.getTopicFilter === "function" && value.fragment; -} -async function getSubInfo(contract, event) { - let topics; - let fragment = null; - if (Array.isArray(event)) { - const topicHashify = function(name2) { - if (isHexString(name2, 32)) { - return name2; - } - const fragment2 = contract.interface.getEvent(name2); - assertArgument(fragment2, "unknown fragment", "name", name2); - return fragment2.topicHash; - }; - topics = event.map((e2) => { - if (e2 == null) { - return null; - } - if (Array.isArray(e2)) { - return e2.map(topicHashify); - } - return topicHashify(e2); - }); - } else if (event === "*") { - topics = [null]; - } else if (typeof event === "string") { - if (isHexString(event, 32)) { - topics = [event]; - } else { - fragment = contract.interface.getEvent(event); - assertArgument(fragment, "unknown fragment", "event", event); - topics = [fragment.topicHash]; - } - } else if (isDeferred(event)) { - topics = await event.getTopicFilter(); - } else if ("fragment" in event) { - fragment = event.fragment; - topics = [fragment.topicHash]; - } else { - assertArgument(false, "unknown event name", "event", event); - } - topics = topics.map((t2) => { - if (t2 == null) { - return null; - } - if (Array.isArray(t2)) { - const items = Array.from(new Set(t2.map((t3) => t3.toLowerCase())).values()); - if (items.length === 1) { - return items[0]; - } - items.sort(); - return items; - } - return t2.toLowerCase(); - }); - const tag = topics.map((t2) => { - if (t2 == null) { - return "null"; - } - if (Array.isArray(t2)) { - return t2.join("|"); - } - return t2; - }).join("&"); - return { fragment, tag, topics }; -} -async function hasSub(contract, event) { - const { subs } = getInternal(contract); - return subs.get((await getSubInfo(contract, event)).tag) || null; -} -async function getSub(contract, operation, event) { - const provider2 = getProvider(contract.runner); - assert(provider2, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { operation }); - const { fragment, tag, topics } = await getSubInfo(contract, event); - const { addr, subs } = getInternal(contract); - let sub = subs.get(tag); - if (!sub) { - const address = addr ? addr : contract; - const filter2 = { address, topics }; - const listener = (log) => { - let foundFragment = fragment; - if (foundFragment == null) { - try { - foundFragment = contract.interface.getEvent(log.topics[0]); - } catch (error) { - } - } - if (foundFragment) { - const _foundFragment = foundFragment; - const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : []; - emit(contract, event, args, (listener2) => { - return new ContractEventPayload(contract, listener2, event, _foundFragment, log); - }); - } else { - emit(contract, event, [], (listener2) => { - return new ContractUnknownEventPayload(contract, listener2, event, log); - }); - } - }; - let starting = []; - const start = () => { - if (starting.length) { - return; - } - starting.push(provider2.on(filter2, listener)); - }; - const stop = async () => { - if (starting.length == 0) { - return; - } - let started = starting; - starting = []; - await Promise.all(started); - provider2.off(filter2, listener); - }; - sub = { tag, listeners: [], start, stop }; - subs.set(tag, sub); - } - return sub; -} -let lastEmit = Promise.resolve(); -async function _emit(contract, event, args, payloadFunc) { - await lastEmit; - const sub = await hasSub(contract, event); - if (!sub) { - return false; - } - const count2 = sub.listeners.length; - sub.listeners = sub.listeners.filter(({ listener, once }) => { - const passArgs = Array.from(args); - if (payloadFunc) { - passArgs.push(payloadFunc(once ? null : listener)); - } - try { - listener.call(contract, ...passArgs); - } catch (error) { - } - return !once; - }); - if (sub.listeners.length === 0) { - sub.stop(); - getInternal(contract).subs.delete(sub.tag); - } - return count2 > 0; -} -async function emit(contract, event, args, payloadFunc) { - try { - await lastEmit; - } catch (error) { - } - const resultPromise = _emit(contract, event, args, payloadFunc); - lastEmit = resultPromise; - return await resultPromise; -} -const passProperties = ["then"]; -_a = internal; -const _BaseContract = class _BaseContract { - /** - * Creates a new contract connected to %%target%% with the %%abi%% and - * optionally connected to a %%runner%% to perform operations on behalf - * of. - */ - constructor(target, abi2, runner, _deployTx) { - /** - * The target to connect to. - * - * This can be an address, ENS name or any [[Addressable]], such as - * another contract. To get the resovled address, use the ``getAddress`` - * method. - */ - __publicField(this, "target"); - /** - * The contract Interface. - */ - __publicField(this, "interface"); - /** - * The connected runner. This is generally a [[Provider]] or a - * [[Signer]], which dictates what operations are supported. - * - * For example, a **Contract** connected to a [[Provider]] may - * only execute read-only operations. - */ - __publicField(this, "runner"); - /** - * All the Events available on this contract. - */ - __publicField(this, "filters"); - /** - * @_ignore: - */ - __publicField(this, _a); - /** - * The fallback or receive function if any. - */ - __publicField(this, "fallback"); - assertArgument(typeof target === "string" || isAddressable(target), "invalid value for Contract target", "target", target); - if (runner == null) { - runner = null; - } - const iface = Interface.from(abi2); - defineProperties$1(this, { target, runner, interface: iface }); - Object.defineProperty(this, internal, { value: {} }); - let addrPromise; - let addr = null; - let deployTx = null; - if (_deployTx) { - const provider2 = getProvider(runner); - deployTx = new ContractTransactionResponse(this.interface, provider2, _deployTx); - } - let subs = /* @__PURE__ */ new Map(); - if (typeof target === "string") { - if (isHexString(target)) { - addr = target; - addrPromise = Promise.resolve(target); - } else { - const resolver = getRunner(runner, "resolveName"); - if (!canResolve(resolver)) { - throw makeError("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { - operation: "resolveName" - }); - } - addrPromise = resolver.resolveName(target).then((addr2) => { - if (addr2 == null) { - throw makeError("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", { - value: target - }); - } - getInternal(this).addr = addr2; - return addr2; - }); - } - } else { - addrPromise = target.getAddress().then((addr2) => { - if (addr2 == null) { - throw new Error("TODO"); - } - getInternal(this).addr = addr2; - return addr2; - }); - } - setInternal(this, { addrPromise, addr, deployTx, subs }); - const filters = new Proxy({}, { - get: (target2, prop, receiver) => { - if (typeof prop === "symbol" || passProperties.indexOf(prop) >= 0) { - return Reflect.get(target2, prop, receiver); - } - try { - return this.getEvent(prop); - } catch (error) { - if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { - throw error; - } - } - return void 0; - }, - has: (target2, prop) => { - if (passProperties.indexOf(prop) >= 0) { - return Reflect.has(target2, prop); - } - return Reflect.has(target2, prop) || this.interface.hasEvent(String(prop)); - } - }); - defineProperties$1(this, { filters }); - defineProperties$1(this, { - fallback: iface.receive || iface.fallback ? buildWrappedFallback(this) : null - }); - return new Proxy(this, { - get: (target2, prop, receiver) => { - if (typeof prop === "symbol" || prop in target2 || passProperties.indexOf(prop) >= 0) { - return Reflect.get(target2, prop, receiver); - } - try { - return target2.getFunction(prop); - } catch (error) { - if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { - throw error; - } - } - return void 0; - }, - has: (target2, prop) => { - if (typeof prop === "symbol" || prop in target2 || passProperties.indexOf(prop) >= 0) { - return Reflect.has(target2, prop); - } - return target2.interface.hasFunction(prop); - } - }); - } - /** - * Return a new Contract instance with the same target and ABI, but - * a different %%runner%%. - */ - connect(runner) { - return new _BaseContract(this.target, this.interface, runner); - } - /** - * Return a new Contract instance with the same ABI and runner, but - * a different %%target%%. - */ - attach(target) { - return new _BaseContract(target, this.interface, this.runner); - } - /** - * Return the resolved address of this Contract. - */ - async getAddress() { - return await getInternal(this).addrPromise; - } - /** - * Return the deployed bytecode or null if no bytecode is found. - */ - async getDeployedCode() { - const provider2 = getProvider(this.runner); - assert(provider2, "runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "getDeployedCode" }); - const code2 = await provider2.getCode(await this.getAddress()); - if (code2 === "0x") { - return null; - } - return code2; - } - /** - * Resolve to this Contract once the bytecode has been deployed, or - * resolve immediately if already deployed. - */ - async waitForDeployment() { - const deployTx = this.deploymentTransaction(); - if (deployTx) { - await deployTx.wait(); - return this; - } - const code2 = await this.getDeployedCode(); - if (code2 != null) { - return this; - } - const provider2 = getProvider(this.runner); - assert(provider2 != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "waitForDeployment" }); - return new Promise((resolve, reject) => { - const checkCode = async () => { - try { - const code3 = await this.getDeployedCode(); - if (code3 != null) { - return resolve(this); - } - provider2.once("block", checkCode); - } catch (error) { - reject(error); - } - }; - checkCode(); - }); - } - /** - * Return the transaction used to deploy this contract. - * - * This is only available if this instance was returned from a - * [[ContractFactory]]. - */ - deploymentTransaction() { - return getInternal(this).deployTx; - } - /** - * Return the function for a given name. This is useful when a contract - * method name conflicts with a JavaScript name such as ``prototype`` or - * when using a Contract programatically. - */ - getFunction(key) { - if (typeof key !== "string") { - key = key.format(); - } - const func = buildWrappedMethod(this, key); - return func; - } - /** - * Return the event for a given name. This is useful when a contract - * event name conflicts with a JavaScript name such as ``prototype`` or - * when using a Contract programatically. - */ - getEvent(key) { - if (typeof key !== "string") { - key = key.format(); - } - return buildWrappedEvent(this, key); - } - /** - * @_ignore: - */ - async queryTransaction(hash2) { - throw new Error("@TODO"); - } - /* - // @TODO: this is a non-backwards compatible change, but will be added - // in v7 and in a potential SmartContract class in an upcoming - // v6 release - async getTransactionReceipt(hash: string): Promise { - const provider = getProvider(this.runner); - assert(provider, "contract runner does not have a provider", - "UNSUPPORTED_OPERATION", { operation: "queryTransaction" }); - - const receipt = await provider.getTransactionReceipt(hash); - if (receipt == null) { return null; } - - return new ContractTransactionReceipt(this.interface, provider, receipt); - } - */ - /** - * Provide historic access to event data for %%event%% in the range - * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``) - * inclusive. - */ - async queryFilter(event, fromBlock, toBlock) { - if (fromBlock == null) { - fromBlock = 0; - } - if (toBlock == null) { - toBlock = "latest"; - } - const { addr, addrPromise } = getInternal(this); - const address = addr ? addr : await addrPromise; - const { fragment, topics } = await getSubInfo(this, event); - const filter2 = { address, topics, fromBlock, toBlock }; - const provider2 = getProvider(this.runner); - assert(provider2, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { operation: "queryFilter" }); - return (await provider2.getLogs(filter2)).map((log) => { - let foundFragment = fragment; - if (foundFragment == null) { - try { - foundFragment = this.interface.getEvent(log.topics[0]); - } catch (error) { - } - } - if (foundFragment) { - try { - return new EventLog(log, this.interface, foundFragment); - } catch (error) { - return new UndecodedEventLog(log, error); - } - } - return new Log(log, provider2); - }); - } - /** - * Add an event %%listener%% for the %%event%%. - */ - async on(event, listener) { - const sub = await getSub(this, "on", event); - sub.listeners.push({ listener, once: false }); - sub.start(); - return this; - } - /** - * Add an event %%listener%% for the %%event%%, but remove the listener - * after it is fired once. - */ - async once(event, listener) { - const sub = await getSub(this, "once", event); - sub.listeners.push({ listener, once: true }); - sub.start(); - return this; - } - /** - * Emit an %%event%% calling all listeners with %%args%%. - * - * Resolves to ``true`` if any listeners were called. - */ - async emit(event, ...args) { - return await emit(this, event, args, null); - } - /** - * Resolves to the number of listeners of %%event%% or the total number - * of listeners if unspecified. - */ - async listenerCount(event) { - if (event) { - const sub = await hasSub(this, event); - if (!sub) { - return 0; - } - return sub.listeners.length; - } - const { subs } = getInternal(this); - let total = 0; - for (const { listeners } of subs.values()) { - total += listeners.length; - } - return total; - } - /** - * Resolves to the listeners subscribed to %%event%% or all listeners - * if unspecified. - */ - async listeners(event) { - if (event) { - const sub = await hasSub(this, event); - if (!sub) { - return []; - } - return sub.listeners.map(({ listener }) => listener); - } - const { subs } = getInternal(this); - let result = []; - for (const { listeners } of subs.values()) { - result = result.concat(listeners.map(({ listener }) => listener)); - } - return result; - } - /** - * Remove the %%listener%% from the listeners for %%event%% or remove - * all listeners if unspecified. - */ - async off(event, listener) { - const sub = await hasSub(this, event); - if (!sub) { - return this; - } - if (listener) { - const index2 = sub.listeners.map(({ listener: listener2 }) => listener2).indexOf(listener); - if (index2 >= 0) { - sub.listeners.splice(index2, 1); - } - } - if (listener == null || sub.listeners.length === 0) { - sub.stop(); - getInternal(this).subs.delete(sub.tag); - } - return this; - } - /** - * Remove all the listeners for %%event%% or remove all listeners if - * unspecified. - */ - async removeAllListeners(event) { - if (event) { - const sub = await hasSub(this, event); - if (!sub) { - return this; - } - sub.stop(); - getInternal(this).subs.delete(sub.tag); - } else { - const { subs } = getInternal(this); - for (const { tag, stop } of subs.values()) { - stop(); - subs.delete(tag); - } - } - return this; - } - /** - * Alias for [on]. - */ - async addListener(event, listener) { - return await this.on(event, listener); - } - /** - * Alias for [off]. - */ - async removeListener(event, listener) { - return await this.off(event, listener); - } - /** - * Create a new Class for the %%abi%%. - */ - static buildClass(abi2) { - class CustomContract extends _BaseContract { - constructor(address, runner = null) { - super(address, abi2, runner); - } - } - return CustomContract; - } - /** - * Create a new BaseContract with a specified Interface. - */ - static from(target, abi2, runner) { - if (runner == null) { - runner = null; - } - const contract = new this(target, abi2, runner); - return contract; - } -}; -let BaseContract = _BaseContract; -function _ContractBase() { - return BaseContract; -} -class Contract extends _ContractBase() { -} -class ContractFactory { - /** - * Create a new **ContractFactory** with %%abi%% and %%bytecode%%, - * optionally connected to %%runner%%. - * - * The %%bytecode%% may be the ``bytecode`` property within the - * standard Solidity JSON output. - */ - constructor(abi2, bytecode, runner) { - /** - * The Contract Interface. - */ - __publicField(this, "interface"); - /** - * The Contract deployment bytecode. Often called the initcode. - */ - __publicField(this, "bytecode"); - /** - * The ContractRunner to deploy the Contract as. - */ - __publicField(this, "runner"); - const iface = Interface.from(abi2); - if (bytecode instanceof Uint8Array) { - bytecode = hexlify(getBytes(bytecode)); - } else { - if (typeof bytecode === "object") { - bytecode = bytecode.object; - } - if (!bytecode.startsWith("0x")) { - bytecode = "0x" + bytecode; - } - bytecode = hexlify(getBytes(bytecode)); - } - defineProperties$1(this, { - bytecode, - interface: iface, - runner: runner || null - }); - } - attach(target) { - return new BaseContract(target, this.interface, this.runner); - } - /** - * Resolves to the transaction to deploy the contract, passing %%args%% - * into the constructor. - */ - async getDeployTransaction(...args) { - let overrides = {}; - const fragment = this.interface.deploy; - if (fragment.inputs.length + 1 === args.length) { - overrides = await copyOverrides(args.pop()); - } - if (fragment.inputs.length !== args.length) { - throw new Error("incorrect number of arguments to constructor"); - } - const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); - const data = concat$1([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); - return Object.assign({}, overrides, { data }); - } - /** - * Resolves to the Contract deployed by passing %%args%% into the - * constructor. - * - * This will resolve to the Contract before it has been deployed to the - * network, so the [[BaseContract-waitForDeployment]] should be used before - * sending any transactions to it. - */ - async deploy(...args) { - const tx = await this.getDeployTransaction(...args); - assert(this.runner && typeof this.runner.sendTransaction === "function", "factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", { - operation: "sendTransaction" - }); - const sentTx = await this.runner.sendTransaction(tx); - const address = getCreateAddress(sentTx); - return new BaseContract(address, this.interface, this.runner, sentTx); - } - /** - * Return a new **ContractFactory** with the same ABI and bytecode, - * but connected to %%runner%%. - */ - connect(runner) { - return new ContractFactory(this.interface, this.bytecode, runner); - } - /** - * Create a new **ContractFactory** from the standard Solidity JSON output. - */ - static fromSolidity(output2, runner) { - assertArgument(output2 != null, "bad compiler output", "output", output2); - if (typeof output2 === "string") { - output2 = JSON.parse(output2); - } - const abi2 = output2.abi; - let bytecode = ""; - if (output2.bytecode) { - bytecode = output2.bytecode; - } else if (output2.evm && output2.evm.bytecode) { - bytecode = output2.evm.bytecode; - } - return new this(abi2, bytecode, runner); - } -} -function getIpfsLink(link) { - if (link.match(/^ipfs:\/\/ipfs\//i)) { - link = link.substring(12); - } else if (link.match(/^ipfs:\/\//i)) { - link = link.substring(7); - } else { - assertArgument(false, "unsupported IPFS format", "link", link); - } - return `https://gateway.ipfs.io/ipfs/${link}`; -} -class MulticoinProviderPlugin { - /** - * Creates a new **MulticoinProviderPluing** for %%name%%. - */ - constructor(name2) { - /** - * The name. - */ - __publicField(this, "name"); - defineProperties$1(this, { name: name2 }); - } - connect(proivder) { - return this; - } - /** - * Returns ``true`` if %%coinType%% is supported by this plugin. - */ - supportsCoinType(coinType) { - return false; - } - /** - * Resolves to the encoded %%address%% for %%coinType%%. - */ - async encodeAddress(coinType, address) { - throw new Error("unsupported coin"); - } - /** - * Resolves to the decoded %%data%% for %%coinType%%. - */ - async decodeAddress(coinType, data) { - throw new Error("unsupported coin"); - } -} -const matcherIpfs = new RegExp("^(ipfs)://(.*)$", "i"); -const matchers = [ - new RegExp("^(https)://(.*)$", "i"), - new RegExp("^(data):(.*)$", "i"), - matcherIpfs, - new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i") -]; -const _EnsResolver = class _EnsResolver { - constructor(provider2, address, name2) { - __privateAdd(this, _EnsResolver_instances); - /** - * The connected provider. - */ - __publicField(this, "provider"); - /** - * The address of the resolver. - */ - __publicField(this, "address"); - /** - * The name this resolver was resolved against. - */ - __publicField(this, "name"); - // For EIP-2544 names, the ancestor that provided the resolver - __privateAdd(this, _supports2544); - __privateAdd(this, _resolver); - defineProperties$1(this, { provider: provider2, address, name: name2 }); - __privateSet(this, _supports2544, null); - __privateSet(this, _resolver, new Contract(address, [ - "function supportsInterface(bytes4) view returns (bool)", - "function resolve(bytes, bytes) view returns (bytes)", - "function addr(bytes32) view returns (address)", - "function addr(bytes32, uint) view returns (bytes)", - "function text(bytes32, string) view returns (string)", - "function contenthash(bytes32) view returns (bytes)" - ], provider2)); - } - /** - * Resolves to true if the resolver supports wildcard resolution. - */ - async supportsWildcard() { - if (__privateGet(this, _supports2544) == null) { - __privateSet(this, _supports2544, (async () => { - try { - return await __privateGet(this, _resolver).supportsInterface("0x9061b923"); - } catch (error) { - if (isError(error, "CALL_EXCEPTION")) { - return false; - } - __privateSet(this, _supports2544, null); - throw error; - } - })()); - } - return await __privateGet(this, _supports2544); - } - /** - * Resolves to the address for %%coinType%% or null if the - * provided %%coinType%% has not been configured. - */ - async getAddress(coinType) { - if (coinType == null) { - coinType = 60; - } - if (coinType === 60) { - try { - const result = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "addr(bytes32)"); - if (result == null || result === ZeroAddress) { - return null; - } - return result; - } catch (error) { - if (isError(error, "CALL_EXCEPTION")) { - return null; - } - throw error; - } - } - if (coinType >= 0 && coinType < 2147483648) { - let ethCoinType = coinType + 2147483648; - const data2 = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "addr(bytes32,uint)", [ethCoinType]); - if (isHexString(data2, 20)) { - return getAddress$1(data2); - } - } - let coinPlugin = null; - for (const plugin of this.provider.plugins) { - if (!(plugin instanceof MulticoinProviderPlugin)) { - continue; - } - if (plugin.supportsCoinType(coinType)) { - coinPlugin = plugin; - break; - } - } - if (coinPlugin == null) { - return null; - } - const data = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "addr(bytes32,uint)", [coinType]); - if (data == null || data === "0x") { - return null; - } - const address = await coinPlugin.decodeAddress(coinType, data); - if (address != null) { - return address; - } - assert(false, `invalid coin data`, "UNSUPPORTED_OPERATION", { - operation: `getAddress(${coinType})`, - info: { coinType, data } - }); - } - /** - * Resolves to the EIP-634 text record for %%key%%, or ``null`` - * if unconfigured. - */ - async getText(key) { - const data = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "text(bytes32,string)", [key]); - if (data == null || data === "0x") { - return null; - } - return data; - } - /** - * Rsolves to the content-hash or ``null`` if unconfigured. - */ - async getContentHash() { - const data = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "contenthash(bytes32)"); - if (data == null || data === "0x") { - return null; - } - const ipfs = data.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); - if (ipfs) { - const scheme = ipfs[1] === "e3010170" ? "ipfs" : "ipns"; - const length = parseInt(ipfs[4], 16); - if (ipfs[5].length === length * 2) { - return `${scheme}://${encodeBase58("0x" + ipfs[2])}`; - } - } - const swarm = data.match(/^0xe40101fa011b20([0-9a-f]*)$/); - if (swarm && swarm[1].length === 64) { - return `bzz://${swarm[1]}`; - } - assert(false, `invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", { - operation: "getContentHash()", - info: { data } - }); - } - /** - * Resolves to the avatar url or ``null`` if the avatar is either - * unconfigured or incorrectly configured (e.g. references an NFT - * not owned by the address). - * - * If diagnosing issues with configurations, the [[_getAvatar]] - * method may be useful. - */ - async getAvatar() { - const avatar2 = await this._getAvatar(); - return avatar2.url; - } - /** - * When resolving an avatar, there are many steps involved, such - * fetching metadata and possibly validating ownership of an - * NFT. - * - * This method can be used to examine each step and the value it - * was working from. - */ - async _getAvatar() { - const linkage = [{ type: "name", value: this.name }]; - try { - const avatar2 = await this.getText("avatar"); - if (avatar2 == null) { - linkage.push({ type: "!avatar", value: "" }); - return { url: null, linkage }; - } - linkage.push({ type: "avatar", value: avatar2 }); - for (let i = 0; i < matchers.length; i++) { - const match = avatar2.match(matchers[i]); - if (match == null) { - continue; - } - const scheme = match[1].toLowerCase(); - switch (scheme) { - case "https": - case "data": - linkage.push({ type: "url", value: avatar2 }); - return { linkage, url: avatar2 }; - case "ipfs": { - const url = getIpfsLink(avatar2); - linkage.push({ type: "ipfs", value: avatar2 }); - linkage.push({ type: "url", value: url }); - return { linkage, url }; - } - case "erc721": - case "erc1155": { - const selector2 = scheme === "erc721" ? "tokenURI(uint256)" : "uri(uint256)"; - linkage.push({ type: scheme, value: avatar2 }); - const owner = await this.getAddress(); - if (owner == null) { - linkage.push({ type: "!owner", value: "" }); - return { url: null, linkage }; - } - const comps = (match[2] || "").split("/"); - if (comps.length !== 2) { - linkage.push({ type: `!${scheme}caip`, value: match[2] || "" }); - return { url: null, linkage }; - } - const tokenId = comps[1]; - const contract = new Contract(comps[0], [ - // ERC-721 - "function tokenURI(uint) view returns (string)", - "function ownerOf(uint) view returns (address)", - // ERC-1155 - "function uri(uint) view returns (string)", - "function balanceOf(address, uint256) view returns (uint)" - ], this.provider); - if (scheme === "erc721") { - const tokenOwner = await contract.ownerOf(tokenId); - if (owner !== tokenOwner) { - linkage.push({ type: "!owner", value: tokenOwner }); - return { url: null, linkage }; - } - linkage.push({ type: "owner", value: tokenOwner }); - } else if (scheme === "erc1155") { - const balance = await contract.balanceOf(owner, tokenId); - if (!balance) { - linkage.push({ type: "!balance", value: "0" }); - return { url: null, linkage }; - } - linkage.push({ type: "balance", value: balance.toString() }); - } - let metadataUrl = await contract[selector2](tokenId); - if (metadataUrl == null || metadataUrl === "0x") { - linkage.push({ type: "!metadata-url", value: "" }); - return { url: null, linkage }; - } - linkage.push({ type: "metadata-url-base", value: metadataUrl }); - if (scheme === "erc1155") { - metadataUrl = metadataUrl.replace("{id}", toBeHex(tokenId, 32).substring(2)); - linkage.push({ type: "metadata-url-expanded", value: metadataUrl }); - } - if (metadataUrl.match(/^ipfs:/i)) { - metadataUrl = getIpfsLink(metadataUrl); - } - linkage.push({ type: "metadata-url", value: metadataUrl }); - let metadata2 = {}; - const response = await new FetchRequest(metadataUrl).send(); - response.assertOk(); - try { - metadata2 = response.bodyJson; - } catch (error) { - try { - linkage.push({ type: "!metadata", value: response.bodyText }); - } catch (error2) { - const bytes2 = response.body; - if (bytes2) { - linkage.push({ type: "!metadata", value: hexlify(bytes2) }); - } - return { url: null, linkage }; - } - return { url: null, linkage }; - } - if (!metadata2) { - linkage.push({ type: "!metadata", value: "" }); - return { url: null, linkage }; - } - linkage.push({ type: "metadata", value: JSON.stringify(metadata2) }); - let imageUrl = metadata2.image; - if (typeof imageUrl !== "string") { - linkage.push({ type: "!imageUrl", value: "" }); - return { url: null, linkage }; - } - if (imageUrl.match(/^(https:\/\/|data:)/i)) { - } else { - const ipfs = imageUrl.match(matcherIpfs); - if (ipfs == null) { - linkage.push({ type: "!imageUrl-ipfs", value: imageUrl }); - return { url: null, linkage }; - } - linkage.push({ type: "imageUrl-ipfs", value: imageUrl }); - imageUrl = getIpfsLink(imageUrl); - } - linkage.push({ type: "url", value: imageUrl }); - return { linkage, url: imageUrl }; - } - } - } - } catch (error) { - } - return { linkage, url: null }; - } - static async getEnsAddress(provider2) { - const network2 = await provider2.getNetwork(); - const ensPlugin = network2.getPlugin("org.ethers.plugins.network.Ens"); - assert(ensPlugin, "network does not support ENS", "UNSUPPORTED_OPERATION", { - operation: "getEnsAddress", - info: { network: network2 } - }); - return ensPlugin.address; - } - /** - * Resolve to the ENS resolver for %%name%% using %%provider%% or - * ``null`` if unconfigured. - */ - static async fromName(provider2, name2) { - var _a2; - let currentName = name2; - while (true) { - if (currentName === "" || currentName === ".") { - return null; - } - if (name2 !== "eth" && currentName === "eth") { - return null; - } - const addr = await __privateMethod(_a2 = _EnsResolver, _EnsResolver_static, getResolver_fn).call(_a2, provider2, currentName); - if (addr != null) { - const resolver = new _EnsResolver(provider2, addr, name2); - if (currentName !== name2 && !await resolver.supportsWildcard()) { - return null; - } - return resolver; - } - currentName = currentName.split(".").slice(1).join("."); - } - } -}; -_supports2544 = new WeakMap(); -_resolver = new WeakMap(); -_EnsResolver_instances = new WeakSet(); -fetch_fn = async function(funcName, params) { - params = (params || []).slice(); - const iface = __privateGet(this, _resolver).interface; - params.unshift(namehash$1(this.name)); - let fragment = null; - if (await this.supportsWildcard()) { - fragment = iface.getFunction(funcName); - assert(fragment, "missing fragment", "UNKNOWN_ERROR", { - info: { funcName } - }); - params = [ - dnsEncode(this.name, 255), - iface.encodeFunctionData(fragment, params) - ]; - funcName = "resolve(bytes,bytes)"; - } - params.push({ - enableCcipRead: true - }); - try { - const result = await __privateGet(this, _resolver)[funcName](...params); - if (fragment) { - return iface.decodeFunctionResult(fragment, result)[0]; - } - return result; - } catch (error) { - if (!isError(error, "CALL_EXCEPTION")) { - throw error; - } - } - return null; -}; -_EnsResolver_static = new WeakSet(); -getResolver_fn = async function(provider2, name2) { - const ensAddr = await _EnsResolver.getEnsAddress(provider2); - try { - const contract = new Contract(ensAddr, [ - "function resolver(bytes32) view returns (address)" - ], provider2); - const addr = await contract.resolver(namehash$1(name2), { - enableCcipRead: true - }); - if (addr === ZeroAddress) { - return null; - } - return addr; - } catch (error) { - throw error; - } - return null; -}; -__privateAdd(_EnsResolver, _EnsResolver_static); -let EnsResolver = _EnsResolver; -const BN_0 = BigInt(0); -function allowNull(format2, nullValue) { - return function(value) { - if (value == null) { - return nullValue; - } - return format2(value); - }; -} -function arrayOf(format2, allowNull2) { - return (array) => { - if (allowNull2 && array == null) { - return null; - } - if (!Array.isArray(array)) { - throw new Error("not an array"); - } - return array.map((i) => format2(i)); - }; -} -function object(format2, altNames) { - return (value) => { - const result = {}; - for (const key in format2) { - let srcKey = key; - if (altNames && key in altNames && !(srcKey in value)) { - for (const altKey of altNames[key]) { - if (altKey in value) { - srcKey = altKey; - break; - } - } - } - try { - const nv = format2[key](value[srcKey]); - if (nv !== void 0) { - result[key] = nv; - } - } catch (error) { - const message = error instanceof Error ? error.message : "not-an-error"; - assert(false, `invalid value for value.${key} (${message})`, "BAD_DATA", { value }); - } - } - return result; - }; -} -function formatBoolean(value) { - switch (value) { - case true: - case "true": - return true; - case false: - case "false": - return false; - } - assertArgument(false, `invalid boolean; ${JSON.stringify(value)}`, "value", value); -} -function formatData(value) { - assertArgument(isHexString(value, true), "invalid data", "value", value); - return value; -} -function formatHash(value) { - assertArgument(isHexString(value, 32), "invalid hash", "value", value); - return value; -} -const _formatLog = object({ - address: getAddress$1, - blockHash: formatHash, - blockNumber: getNumber, - data: formatData, - index: getNumber, - removed: allowNull(formatBoolean, false), - topics: arrayOf(formatHash), - transactionHash: formatHash, - transactionIndex: getNumber -}, { - index: ["logIndex"] -}); -function formatLog$1(value) { - return _formatLog(value); -} -const _formatBlock = object({ - hash: allowNull(formatHash), - parentHash: formatHash, - parentBeaconBlockRoot: allowNull(formatHash, null), - number: getNumber, - timestamp: getNumber, - nonce: allowNull(formatData), - difficulty: getBigInt, - gasLimit: getBigInt, - gasUsed: getBigInt, - stateRoot: allowNull(formatHash, null), - receiptsRoot: allowNull(formatHash, null), - blobGasUsed: allowNull(getBigInt, null), - excessBlobGas: allowNull(getBigInt, null), - miner: allowNull(getAddress$1), - prevRandao: allowNull(formatHash, null), - extraData: formatData, - baseFeePerGas: allowNull(getBigInt) -}, { - prevRandao: ["mixHash"] -}); -function formatBlock$1(value) { - const result = _formatBlock(value); - result.transactions = value.transactions.map((tx) => { - if (typeof tx === "string") { - return tx; - } - return formatTransactionResponse(tx); - }); - return result; -} -const _formatReceiptLog = object({ - transactionIndex: getNumber, - blockNumber: getNumber, - transactionHash: formatHash, - address: getAddress$1, - topics: arrayOf(formatHash), - data: formatData, - index: getNumber, - blockHash: formatHash -}, { - index: ["logIndex"] -}); -function formatReceiptLog(value) { - return _formatReceiptLog(value); -} -const _formatTransactionReceipt = object({ - to: allowNull(getAddress$1, null), - from: allowNull(getAddress$1, null), - contractAddress: allowNull(getAddress$1, null), - // should be allowNull(hash), but broken-EIP-658 support is handled in receipt - index: getNumber, - root: allowNull(hexlify), - gasUsed: getBigInt, - blobGasUsed: allowNull(getBigInt, null), - logsBloom: allowNull(formatData), - blockHash: formatHash, - hash: formatHash, - logs: arrayOf(formatReceiptLog), - blockNumber: getNumber, - //confirmations: allowNull(getNumber, null), - cumulativeGasUsed: getBigInt, - effectiveGasPrice: allowNull(getBigInt), - blobGasPrice: allowNull(getBigInt, null), - status: allowNull(getNumber), - type: allowNull(getNumber, 0) -}, { - effectiveGasPrice: ["gasPrice"], - hash: ["transactionHash"], - index: ["transactionIndex"] -}); -function formatTransactionReceipt$1(value) { - return _formatTransactionReceipt(value); -} -function formatTransactionResponse(value) { - if (value.to && getBigInt(value.to) === BN_0) { - value.to = "0x0000000000000000000000000000000000000000"; - } - const result = object({ - hash: formatHash, - // Some nodes do not return this, usually test nodes (like Ganache) - index: allowNull(getNumber, void 0), - type: (value2) => { - if (value2 === "0x" || value2 == null) { - return 0; - } - return getNumber(value2); - }, - accessList: allowNull(accessListify, null), - blobVersionedHashes: allowNull(arrayOf(formatHash, true), null), - blockHash: allowNull(formatHash, null), - blockNumber: allowNull(getNumber, null), - transactionIndex: allowNull(getNumber, null), - from: getAddress$1, - // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas) must be set - gasPrice: allowNull(getBigInt), - maxPriorityFeePerGas: allowNull(getBigInt), - maxFeePerGas: allowNull(getBigInt), - maxFeePerBlobGas: allowNull(getBigInt, null), - gasLimit: getBigInt, - to: allowNull(getAddress$1, null), - value: getBigInt, - nonce: getNumber, - data: formatData, - creates: allowNull(getAddress$1, null), - chainId: allowNull(getBigInt, null) - }, { - data: ["input"], - gasLimit: ["gas"], - index: ["transactionIndex"] - })(value); - if (result.to == null && result.creates == null) { - result.creates = getCreateAddress(result); - } - if ((value.type === 1 || value.type === 2) && value.accessList == null) { - result.accessList = []; - } - if (value.signature) { - result.signature = Signature.from(value.signature); - } else { - result.signature = Signature.from(value); - } - if (result.chainId == null) { - const chainId = result.signature.legacyChainId; - if (chainId != null) { - result.chainId = chainId; - } - } - if (result.blockHash && getBigInt(result.blockHash) === BN_0) { - result.blockHash = null; - } - return result; -} -const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"; -class NetworkPlugin { - /** - * Creates a new **NetworkPlugin**. - */ - constructor(name2) { - /** - * The name of the plugin. - * - * It is recommended to use reverse-domain-notation, which permits - * unique names with a known authority as well as hierarchal entries. - */ - __publicField(this, "name"); - defineProperties$1(this, { name: name2 }); - } - /** - * Creates a copy of this plugin. - */ - clone() { - return new NetworkPlugin(this.name); - } -} -class GasCostPlugin extends NetworkPlugin { - /** - * Creates a new GasCostPlugin from %%effectiveBlock%% until the - * latest block or another GasCostPlugin supercedes that block number, - * with the associated %%costs%%. - */ - constructor(effectiveBlock, costs) { - if (effectiveBlock == null) { - effectiveBlock = 0; - } - super(`org.ethers.network.plugins.GasCost#${effectiveBlock || 0}`); - /** - * The block number to treat these values as valid from. - * - * This allows a hardfork to have updated values included as well as - * mulutiple hardforks to be supported. - */ - __publicField(this, "effectiveBlock"); - /** - * The transactions base fee. - */ - __publicField(this, "txBase"); - /** - * The fee for creating a new account. - */ - __publicField(this, "txCreate"); - /** - * The fee per zero-byte in the data. - */ - __publicField(this, "txDataZero"); - /** - * The fee per non-zero-byte in the data. - */ - __publicField(this, "txDataNonzero"); - /** - * The fee per storage key in the [[link-eip-2930]] access list. - */ - __publicField(this, "txAccessListStorageKey"); - /** - * The fee per address in the [[link-eip-2930]] access list. - */ - __publicField(this, "txAccessListAddress"); - const props = { effectiveBlock }; - function set(name2, nullish) { - let value = (costs || {})[name2]; - if (value == null) { - value = nullish; - } - assertArgument(typeof value === "number", `invalud value for ${name2}`, "costs", costs); - props[name2] = value; - } - set("txBase", 21e3); - set("txCreate", 32e3); - set("txDataZero", 4); - set("txDataNonzero", 16); - set("txAccessListStorageKey", 1900); - set("txAccessListAddress", 2400); - defineProperties$1(this, props); - } - clone() { - return new GasCostPlugin(this.effectiveBlock, this); - } -} -class EnsPlugin extends NetworkPlugin { - /** - * Creates a new **EnsPlugin** connected to %%address%% on the - * %%targetNetwork%%. The default ENS address and mainnet is used - * if unspecified. - */ - constructor(address, targetNetwork) { - super("org.ethers.plugins.network.Ens"); - /** - * The ENS Registrty Contract address. - */ - __publicField(this, "address"); - /** - * The chain ID that the ENS contract lives on. - */ - __publicField(this, "targetNetwork"); - defineProperties$1(this, { - address: address || EnsAddress, - targetNetwork: targetNetwork == null ? 1 : targetNetwork - }); - } - clone() { - return new EnsPlugin(this.address, this.targetNetwork); - } -} -const _FeeDataNetworkPlugin = class _FeeDataNetworkPlugin extends NetworkPlugin { - /** - * Creates a new **FeeDataNetworkPlugin**. - */ - constructor(feeDataFunc) { - super("org.ethers.plugins.network.FeeData"); - __privateAdd(this, _feeDataFunc); - __privateSet(this, _feeDataFunc, feeDataFunc); - } - /** - * The fee data function provided to the constructor. - */ - get feeDataFunc() { - return __privateGet(this, _feeDataFunc); - } - /** - * Resolves to the fee data. - */ - async getFeeData(provider2) { - return await __privateGet(this, _feeDataFunc).call(this, provider2); - } - clone() { - return new _FeeDataNetworkPlugin(__privateGet(this, _feeDataFunc)); - } -}; -_feeDataFunc = new WeakMap(); -let FeeDataNetworkPlugin = _FeeDataNetworkPlugin; -class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin { - /** - * Creates a new **FetchUrlFeeDataNetworkPlugin** which will - * be used when computing the fee data for the network. - */ - constructor(url, processFunc) { - super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); - __privateAdd(this, _url2); - __privateAdd(this, _processFunc); - __privateSet(this, _url2, url); - __privateSet(this, _processFunc, processFunc); - } - /** - * The URL to initialize the FetchRequest with in %%processFunc%%. - */ - get url() { - return __privateGet(this, _url2); - } - /** - * The callback to use when computing the FeeData. - */ - get processFunc() { - return __privateGet(this, _processFunc); - } - // We are immutable, so we can serve as our own clone - clone() { - return this; - } -} -_url2 = new WeakMap(); -_processFunc = new WeakMap(); -const Networks = /* @__PURE__ */ new Map(); -const _Network = class _Network { - /** - * Creates a new **Network** for %%name%% and %%chainId%%. - */ - constructor(name2, chainId) { - __privateAdd(this, _name); - __privateAdd(this, _chainId3); - __privateAdd(this, _plugins); - __privateSet(this, _name, name2); - __privateSet(this, _chainId3, getBigInt(chainId)); - __privateSet(this, _plugins, /* @__PURE__ */ new Map()); - } - /** - * Returns a JSON-compatible representation of a Network. - */ - toJSON() { - return { name: this.name, chainId: String(this.chainId) }; - } - /** - * The network common name. - * - * This is the canonical name, as networks migh have multiple - * names. - */ - get name() { - return __privateGet(this, _name); - } - set name(value) { - __privateSet(this, _name, value); - } - /** - * The network chain ID. - */ - get chainId() { - return __privateGet(this, _chainId3); - } - set chainId(value) { - __privateSet(this, _chainId3, getBigInt(value, "chainId")); - } - /** - * Returns true if %%other%% matches this network. Any chain ID - * must match, and if no chain ID is present, the name must match. - * - * This method does not currently check for additional properties, - * such as ENS address or plug-in compatibility. - */ - matches(other) { - if (other == null) { - return false; - } - if (typeof other === "string") { - try { - return this.chainId === getBigInt(other); - } catch (error) { - } - return this.name === other; - } - if (typeof other === "number" || typeof other === "bigint") { - try { - return this.chainId === getBigInt(other); - } catch (error) { - } - return false; - } - if (typeof other === "object") { - if (other.chainId != null) { - try { - return this.chainId === getBigInt(other.chainId); - } catch (error) { - } - return false; - } - if (other.name != null) { - return this.name === other.name; - } - return false; - } - return false; - } - /** - * Returns the list of plugins currently attached to this Network. - */ - get plugins() { - return Array.from(__privateGet(this, _plugins).values()); - } - /** - * Attach a new %%plugin%% to this Network. The network name - * must be unique, excluding any fragment. - */ - attachPlugin(plugin) { - if (__privateGet(this, _plugins).get(plugin.name)) { - throw new Error(`cannot replace existing plugin: ${plugin.name} `); - } - __privateGet(this, _plugins).set(plugin.name, plugin.clone()); - return this; - } - /** - * Return the plugin, if any, matching %%name%% exactly. Plugins - * with fragments will not be returned unless %%name%% includes - * a fragment. - */ - getPlugin(name2) { - return __privateGet(this, _plugins).get(name2) || null; - } - /** - * Gets a list of all plugins that match %%name%%, with otr without - * a fragment. - */ - getPlugins(basename) { - return this.plugins.filter((p2) => p2.name.split("#")[0] === basename); - } - /** - * Create a copy of this Network. - */ - clone() { - const clone = new _Network(this.name, this.chainId); - this.plugins.forEach((plugin) => { - clone.attachPlugin(plugin.clone()); - }); - return clone; - } - /** - * Compute the intrinsic gas required for a transaction. - * - * A GasCostPlugin can be attached to override the default - * values. - */ - computeIntrinsicGas(tx) { - const costs = this.getPlugin("org.ethers.plugins.network.GasCost") || new GasCostPlugin(); - let gas = costs.txBase; - if (tx.to == null) { - gas += costs.txCreate; - } - if (tx.data) { - for (let i = 2; i < tx.data.length; i += 2) { - if (tx.data.substring(i, i + 2) === "00") { - gas += costs.txDataZero; - } else { - gas += costs.txDataNonzero; - } - } - } - if (tx.accessList) { - const accessList = accessListify(tx.accessList); - for (const addr in accessList) { - gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length; - } - } - return gas; - } - /** - * Returns a new Network for the %%network%% name or chainId. - */ - static from(network2) { - injectCommonNetworks(); - if (network2 == null) { - return _Network.from("mainnet"); - } - if (typeof network2 === "number") { - network2 = BigInt(network2); - } - if (typeof network2 === "string" || typeof network2 === "bigint") { - const networkFunc = Networks.get(network2); - if (networkFunc) { - return networkFunc(); - } - if (typeof network2 === "bigint") { - return new _Network("unknown", network2); - } - assertArgument(false, "unknown network", "network", network2); - } - if (typeof network2.clone === "function") { - const clone = network2.clone(); - return clone; - } - if (typeof network2 === "object") { - assertArgument(typeof network2.name === "string" && typeof network2.chainId === "number", "invalid network object name or chainId", "network", network2); - const custom2 = new _Network(network2.name, network2.chainId); - if (network2.ensAddress || network2.ensNetwork != null) { - custom2.attachPlugin(new EnsPlugin(network2.ensAddress, network2.ensNetwork)); - } - return custom2; - } - assertArgument(false, "invalid network", "network", network2); - } - /** - * Register %%nameOrChainId%% with a function which returns - * an instance of a Network representing that chain. - */ - static register(nameOrChainId, networkFunc) { - if (typeof nameOrChainId === "number") { - nameOrChainId = BigInt(nameOrChainId); - } - const existing = Networks.get(nameOrChainId); - if (existing) { - assertArgument(false, `conflicting network for ${JSON.stringify(existing.name)}`, "nameOrChainId", nameOrChainId); - } - Networks.set(nameOrChainId, networkFunc); - } -}; -_name = new WeakMap(); -_chainId3 = new WeakMap(); -_plugins = new WeakMap(); -let Network = _Network; -function parseUnits$2(_value2, decimals) { - const value = String(_value2); - if (!value.match(/^[0-9.]+$/)) { - throw new Error(`invalid gwei value: ${_value2}`); - } - const comps = value.split("."); - if (comps.length === 1) { - comps.push(""); - } - if (comps.length !== 2) { - throw new Error(`invalid gwei value: ${_value2}`); - } - while (comps[1].length < decimals) { - comps[1] += "0"; - } - if (comps[1].length > 9) { - let frac = BigInt(comps[1].substring(0, 9)); - if (!comps[1].substring(9).match(/^0+$/)) { - frac++; - } - comps[1] = frac.toString(); - } - return BigInt(comps[0] + comps[1]); -} -function getGasStationPlugin(url) { - return new FetchUrlFeeDataNetworkPlugin(url, async (fetchFeeData, provider2, request) => { - request.setHeader("User-Agent", "ethers"); - let response; - try { - const [_response, _feeData] = await Promise.all([ - request.send(), - fetchFeeData() - ]); - response = _response; - const payload = response.bodyJson.standard; - const feeData = { - gasPrice: _feeData.gasPrice, - maxFeePerGas: parseUnits$2(payload.maxFee, 9), - maxPriorityFeePerGas: parseUnits$2(payload.maxPriorityFee, 9) - }; - return feeData; - } catch (error) { - assert(false, `error encountered with polygon gas station (${JSON.stringify(request.url)})`, "SERVER_ERROR", { request, response, error }); - } - }); -} -let injected$1 = false; -function injectCommonNetworks() { - if (injected$1) { - return; - } - injected$1 = true; - function registerEth(name2, chainId, options) { - const func = function() { - const network2 = new Network(name2, chainId); - if (options.ensNetwork != null) { - network2.attachPlugin(new EnsPlugin(null, options.ensNetwork)); - } - network2.attachPlugin(new GasCostPlugin()); - (options.plugins || []).forEach((plugin) => { - network2.attachPlugin(plugin); - }); - return network2; - }; - Network.register(name2, func); - Network.register(chainId, func); - if (options.altNames) { - options.altNames.forEach((name3) => { - Network.register(name3, func); - }); - } - } - registerEth("mainnet", 1, { ensNetwork: 1, altNames: ["homestead"] }); - registerEth("ropsten", 3, { ensNetwork: 3 }); - registerEth("rinkeby", 4, { ensNetwork: 4 }); - registerEth("goerli", 5, { ensNetwork: 5 }); - registerEth("kovan", 42, { ensNetwork: 42 }); - registerEth("sepolia", 11155111, { ensNetwork: 11155111 }); - registerEth("holesky", 17e3, { ensNetwork: 17e3 }); - registerEth("classic", 61, {}); - registerEth("classicKotti", 6, {}); - registerEth("arbitrum", 42161, { - ensNetwork: 1 - }); - registerEth("arbitrum-goerli", 421613, {}); - registerEth("arbitrum-sepolia", 421614, {}); - registerEth("base", 8453, { ensNetwork: 1 }); - registerEth("base-goerli", 84531, {}); - registerEth("base-sepolia", 84532, {}); - registerEth("bnb", 56, { ensNetwork: 1 }); - registerEth("bnbt", 97, {}); - registerEth("linea", 59144, { ensNetwork: 1 }); - registerEth("linea-goerli", 59140, {}); - registerEth("linea-sepolia", 59141, {}); - registerEth("matic", 137, { - ensNetwork: 1, - plugins: [ - getGasStationPlugin("https://gasstation.polygon.technology/v2") - ] - }); - registerEth("matic-amoy", 80002, {}); - registerEth("matic-mumbai", 80001, { - altNames: ["maticMumbai", "maticmum"], - plugins: [ - getGasStationPlugin("https://gasstation-testnet.polygon.technology/v2") - ] - }); - registerEth("optimism", 10, { - ensNetwork: 1, - plugins: [] - }); - registerEth("optimism-goerli", 420, {}); - registerEth("optimism-sepolia", 11155420, {}); - registerEth("xdai", 100, { ensNetwork: 1 }); -} -function copy$3(obj) { - return JSON.parse(JSON.stringify(obj)); -} -class PollingBlockSubscriber { - /** - * Create a new **PollingBlockSubscriber** attached to %%provider%%. - */ - constructor(provider2) { - __privateAdd(this, _PollingBlockSubscriber_instances); - __privateAdd(this, _provider); - __privateAdd(this, _poller); - __privateAdd(this, _interval); - // The most recent block we have scanned for events. The value -2 - // indicates we still need to fetch an initial block number - __privateAdd(this, _blockNumber); - __privateSet(this, _provider, provider2); - __privateSet(this, _poller, null); - __privateSet(this, _interval, 4e3); - __privateSet(this, _blockNumber, -2); - } - /** - * The polling interval. - */ - get pollingInterval() { - return __privateGet(this, _interval); - } - set pollingInterval(value) { - __privateSet(this, _interval, value); - } - start() { - if (__privateGet(this, _poller)) { - return; - } - __privateSet(this, _poller, __privateGet(this, _provider)._setTimeout(__privateMethod(this, _PollingBlockSubscriber_instances, poll_fn).bind(this), __privateGet(this, _interval))); - __privateMethod(this, _PollingBlockSubscriber_instances, poll_fn).call(this); - } - stop() { - if (!__privateGet(this, _poller)) { - return; - } - __privateGet(this, _provider)._clearTimeout(__privateGet(this, _poller)); - __privateSet(this, _poller, null); - } - pause(dropWhilePaused) { - this.stop(); - if (dropWhilePaused) { - __privateSet(this, _blockNumber, -2); - } - } - resume() { - this.start(); - } -} -_provider = new WeakMap(); -_poller = new WeakMap(); -_interval = new WeakMap(); -_blockNumber = new WeakMap(); -_PollingBlockSubscriber_instances = new WeakSet(); -poll_fn = async function() { - try { - const blockNumber = await __privateGet(this, _provider).getBlockNumber(); - if (__privateGet(this, _blockNumber) === -2) { - __privateSet(this, _blockNumber, blockNumber); - return; - } - if (blockNumber !== __privateGet(this, _blockNumber)) { - for (let b2 = __privateGet(this, _blockNumber) + 1; b2 <= blockNumber; b2++) { - if (__privateGet(this, _poller) == null) { - return; - } - await __privateGet(this, _provider).emit("block", b2); - } - __privateSet(this, _blockNumber, blockNumber); - } - } catch (error) { - } - if (__privateGet(this, _poller) == null) { - return; - } - __privateSet(this, _poller, __privateGet(this, _provider)._setTimeout(__privateMethod(this, _PollingBlockSubscriber_instances, poll_fn).bind(this), __privateGet(this, _interval))); -}; -class OnBlockSubscriber { - /** - * Create a new **OnBlockSubscriber** attached to %%provider%%. - */ - constructor(provider2) { - __privateAdd(this, _provider2); - __privateAdd(this, _poll); - __privateAdd(this, _running); - __privateSet(this, _provider2, provider2); - __privateSet(this, _running, false); - __privateSet(this, _poll, (blockNumber) => { - this._poll(blockNumber, __privateGet(this, _provider2)); - }); - } - /** - * Called on every new block. - */ - async _poll(blockNumber, provider2) { - throw new Error("sub-classes must override this"); - } - start() { - if (__privateGet(this, _running)) { - return; - } - __privateSet(this, _running, true); - __privateGet(this, _poll).call(this, -2); - __privateGet(this, _provider2).on("block", __privateGet(this, _poll)); - } - stop() { - if (!__privateGet(this, _running)) { - return; - } - __privateSet(this, _running, false); - __privateGet(this, _provider2).off("block", __privateGet(this, _poll)); - } - pause(dropWhilePaused) { - this.stop(); - } - resume() { - this.start(); - } -} -_provider2 = new WeakMap(); -_poll = new WeakMap(); -_running = new WeakMap(); -class PollingBlockTagSubscriber extends OnBlockSubscriber { - constructor(provider2, tag) { - super(provider2); - __privateAdd(this, _tag); - __privateAdd(this, _lastBlock); - __privateSet(this, _tag, tag); - __privateSet(this, _lastBlock, -2); - } - pause(dropWhilePaused) { - if (dropWhilePaused) { - __privateSet(this, _lastBlock, -2); - } - super.pause(dropWhilePaused); - } - async _poll(blockNumber, provider2) { - const block = await provider2.getBlock(__privateGet(this, _tag)); - if (block == null) { - return; - } - if (__privateGet(this, _lastBlock) === -2) { - __privateSet(this, _lastBlock, block.number); - } else if (block.number > __privateGet(this, _lastBlock)) { - provider2.emit(__privateGet(this, _tag), block.number); - __privateSet(this, _lastBlock, block.number); - } - } -} -_tag = new WeakMap(); -_lastBlock = new WeakMap(); -class PollingOrphanSubscriber extends OnBlockSubscriber { - constructor(provider2, filter2) { - super(provider2); - __privateAdd(this, _filter2); - __privateSet(this, _filter2, copy$3(filter2)); - } - async _poll(blockNumber, provider2) { - throw new Error("@TODO"); - } -} -_filter2 = new WeakMap(); -class PollingTransactionSubscriber extends OnBlockSubscriber { - /** - * Create a new **PollingTransactionSubscriber** attached to - * %%provider%%, listening for %%hash%%. - */ - constructor(provider2, hash2) { - super(provider2); - __privateAdd(this, _hash); - __privateSet(this, _hash, hash2); - } - async _poll(blockNumber, provider2) { - const tx = await provider2.getTransactionReceipt(__privateGet(this, _hash)); - if (tx) { - provider2.emit(__privateGet(this, _hash), tx); - } - } -} -_hash = new WeakMap(); -class PollingEventSubscriber { - /** - * Create a new **PollingTransactionSubscriber** attached to - * %%provider%%, listening for %%filter%%. - */ - constructor(provider2, filter2) { - __privateAdd(this, _PollingEventSubscriber_instances); - __privateAdd(this, _provider3); - __privateAdd(this, _filter3); - __privateAdd(this, _poller2); - __privateAdd(this, _running2); - // The most recent block we have scanned for events. The value -2 - // indicates we still need to fetch an initial block number - __privateAdd(this, _blockNumber2); - __privateSet(this, _provider3, provider2); - __privateSet(this, _filter3, copy$3(filter2)); - __privateSet(this, _poller2, __privateMethod(this, _PollingEventSubscriber_instances, poll_fn2).bind(this)); - __privateSet(this, _running2, false); - __privateSet(this, _blockNumber2, -2); - } - start() { - if (__privateGet(this, _running2)) { - return; - } - __privateSet(this, _running2, true); - if (__privateGet(this, _blockNumber2) === -2) { - __privateGet(this, _provider3).getBlockNumber().then((blockNumber) => { - __privateSet(this, _blockNumber2, blockNumber); - }); - } - __privateGet(this, _provider3).on("block", __privateGet(this, _poller2)); - } - stop() { - if (!__privateGet(this, _running2)) { - return; - } - __privateSet(this, _running2, false); - __privateGet(this, _provider3).off("block", __privateGet(this, _poller2)); - } - pause(dropWhilePaused) { - this.stop(); - if (dropWhilePaused) { - __privateSet(this, _blockNumber2, -2); - } - } - resume() { - this.start(); - } -} -_provider3 = new WeakMap(); -_filter3 = new WeakMap(); -_poller2 = new WeakMap(); -_running2 = new WeakMap(); -_blockNumber2 = new WeakMap(); -_PollingEventSubscriber_instances = new WeakSet(); -poll_fn2 = async function(blockNumber) { - if (__privateGet(this, _blockNumber2) === -2) { - return; - } - const filter2 = copy$3(__privateGet(this, _filter3)); - filter2.fromBlock = __privateGet(this, _blockNumber2) + 1; - filter2.toBlock = blockNumber; - const logs = await __privateGet(this, _provider3).getLogs(filter2); - if (logs.length === 0) { - if (__privateGet(this, _blockNumber2) < blockNumber - 60) { - __privateSet(this, _blockNumber2, blockNumber - 60); - } - return; - } - for (const log of logs) { - __privateGet(this, _provider3).emit(__privateGet(this, _filter3), log); - __privateSet(this, _blockNumber2, log.blockNumber); - } -}; -const BN_2$1 = BigInt(2); -const MAX_CCIP_REDIRECTS = 10; -function isPromise$1(value) { - return value && typeof value.then === "function"; -} -function getTag$1(prefix, value) { - return prefix + ":" + JSON.stringify(value, (k2, v3) => { - if (v3 == null) { - return "null"; - } - if (typeof v3 === "bigint") { - return `bigint:${v3.toString()}`; - } - if (typeof v3 === "string") { - return v3.toLowerCase(); - } - if (typeof v3 === "object" && !Array.isArray(v3)) { - const keys = Object.keys(v3); - keys.sort(); - return keys.reduce((accum, key) => { - accum[key] = v3[key]; - return accum; - }, {}); - } - return v3; - }); -} -class UnmanagedSubscriber { - /** - * Create a new UnmanagedSubscriber with %%name%%. - */ - constructor(name2) { - /** - * The name fof the event. - */ - __publicField(this, "name"); - defineProperties$1(this, { name: name2 }); - } - start() { - } - stop() { - } - pause(dropWhilePaused) { - } - resume() { - } -} -function copy$2(value) { - return JSON.parse(JSON.stringify(value)); -} -function concisify(items) { - items = Array.from(new Set(items).values()); - items.sort(); - return items; -} -async function getSubscription(_event2, provider2) { - if (_event2 == null) { - throw new Error("invalid event"); - } - if (Array.isArray(_event2)) { - _event2 = { topics: _event2 }; - } - if (typeof _event2 === "string") { - switch (_event2) { - case "block": - case "debug": - case "error": - case "finalized": - case "network": - case "pending": - case "safe": { - return { type: _event2, tag: _event2 }; - } - } - } - if (isHexString(_event2, 32)) { - const hash2 = _event2.toLowerCase(); - return { type: "transaction", tag: getTag$1("tx", { hash: hash2 }), hash: hash2 }; - } - if (_event2.orphan) { - const event = _event2; - return { type: "orphan", tag: getTag$1("orphan", event), filter: copy$2(event) }; - } - if (_event2.address || _event2.topics) { - const event = _event2; - const filter2 = { - topics: (event.topics || []).map((t2) => { - if (t2 == null) { - return null; - } - if (Array.isArray(t2)) { - return concisify(t2.map((t3) => t3.toLowerCase())); - } - return t2.toLowerCase(); - }) - }; - if (event.address) { - const addresses = []; - const promises = []; - const addAddress = (addr) => { - if (isHexString(addr)) { - addresses.push(addr); - } else { - promises.push((async () => { - addresses.push(await resolveAddress(addr, provider2)); - })()); - } - }; - if (Array.isArray(event.address)) { - event.address.forEach(addAddress); - } else { - addAddress(event.address); - } - if (promises.length) { - await Promise.all(promises); - } - filter2.address = concisify(addresses.map((a2) => a2.toLowerCase())); - } - return { filter: filter2, tag: getTag$1("event", filter2), type: "event" }; - } - assertArgument(false, "unknown ProviderEvent", "event", _event2); -} -function getTime$1() { - return (/* @__PURE__ */ new Date()).getTime(); -} -const defaultOptions$1 = { - cacheTimeout: 250, - pollingInterval: 4e3 -}; -class AbstractProvider { - /** - * Create a new **AbstractProvider** connected to %%network%%, or - * use the various network detection capabilities to discover the - * [[Network]] if necessary. - */ - constructor(_network3, options) { - __privateAdd(this, _AbstractProvider_instances); - __privateAdd(this, _subs); - __privateAdd(this, _plugins2); - // null=unpaused, true=paused+dropWhilePaused, false=paused - __privateAdd(this, _pausedState); - __privateAdd(this, _destroyed); - __privateAdd(this, _networkPromise); - __privateAdd(this, _anyNetwork); - __privateAdd(this, _performCache); - // The most recent block number if running an event or -1 if no "block" event - __privateAdd(this, _lastBlockNumber); - __privateAdd(this, _nextTimer); - __privateAdd(this, _timers); - __privateAdd(this, _disableCcipRead); - __privateAdd(this, _options2); - __privateSet(this, _options2, Object.assign({}, defaultOptions$1, options || {})); - if (_network3 === "any") { - __privateSet(this, _anyNetwork, true); - __privateSet(this, _networkPromise, null); - } else if (_network3) { - const network2 = Network.from(_network3); - __privateSet(this, _anyNetwork, false); - __privateSet(this, _networkPromise, Promise.resolve(network2)); - setTimeout(() => { - this.emit("network", network2, null); - }, 0); - } else { - __privateSet(this, _anyNetwork, false); - __privateSet(this, _networkPromise, null); - } - __privateSet(this, _lastBlockNumber, -1); - __privateSet(this, _performCache, /* @__PURE__ */ new Map()); - __privateSet(this, _subs, /* @__PURE__ */ new Map()); - __privateSet(this, _plugins2, /* @__PURE__ */ new Map()); - __privateSet(this, _pausedState, null); - __privateSet(this, _destroyed, false); - __privateSet(this, _nextTimer, 1); - __privateSet(this, _timers, /* @__PURE__ */ new Map()); - __privateSet(this, _disableCcipRead, false); - } - get pollingInterval() { - return __privateGet(this, _options2).pollingInterval; - } - /** - * Returns ``this``, to allow an **AbstractProvider** to implement - * the [[ContractRunner]] interface. - */ - get provider() { - return this; - } - /** - * Returns all the registered plug-ins. - */ - get plugins() { - return Array.from(__privateGet(this, _plugins2).values()); - } - /** - * Attach a new plug-in. - */ - attachPlugin(plugin) { - if (__privateGet(this, _plugins2).get(plugin.name)) { - throw new Error(`cannot replace existing plugin: ${plugin.name} `); - } - __privateGet(this, _plugins2).set(plugin.name, plugin.connect(this)); - return this; - } - /** - * Get a plugin by name. - */ - getPlugin(name2) { - return __privateGet(this, _plugins2).get(name2) || null; - } - /** - * Prevent any CCIP-read operation, regardless of whether requested - * in a [[call]] using ``enableCcipRead``. - */ - get disableCcipRead() { - return __privateGet(this, _disableCcipRead); - } - set disableCcipRead(value) { - __privateSet(this, _disableCcipRead, !!value); - } - /** - * Resolves to the data for executing the CCIP-read operations. - */ - async ccipReadFetch(tx, calldata, urls) { - if (this.disableCcipRead || urls.length === 0 || tx.to == null) { - return null; - } - const sender = tx.to.toLowerCase(); - const data = calldata.toLowerCase(); - const errorMessages = []; - for (let i = 0; i < urls.length; i++) { - const url = urls[i]; - const href = url.replace("{sender}", sender).replace("{data}", data); - const request = new FetchRequest(href); - if (url.indexOf("{data}") === -1) { - request.body = { data, sender }; - } - this.emit("debug", { action: "sendCcipReadFetchRequest", request, index: i, urls }); - let errorMessage = "unknown error"; - const resp = await request.send(); - try { - const result = resp.bodyJson; - if (result.data) { - this.emit("debug", { action: "receiveCcipReadFetchResult", request, result }); - return result.data; - } - if (result.message) { - errorMessage = result.message; - } - this.emit("debug", { action: "receiveCcipReadFetchError", request, result }); - } catch (error) { - } - assert(resp.statusCode < 400 || resp.statusCode >= 500, `response not found during CCIP fetch: ${errorMessage}`, "OFFCHAIN_FAULT", { reason: "404_MISSING_RESOURCE", transaction: tx, info: { url, errorMessage } }); - errorMessages.push(errorMessage); - } - assert(false, `error encountered during CCIP fetch: ${errorMessages.map((m2) => JSON.stringify(m2)).join(", ")}`, "OFFCHAIN_FAULT", { - reason: "500_SERVER_ERROR", - transaction: tx, - info: { urls, errorMessages } - }); - } - /** - * Provides the opportunity for a sub-class to wrap a block before - * returning it, to add additional properties or an alternate - * sub-class of [[Block]]. - */ - _wrapBlock(value, network2) { - return new Block(formatBlock$1(value), this); - } - /** - * Provides the opportunity for a sub-class to wrap a log before - * returning it, to add additional properties or an alternate - * sub-class of [[Log]]. - */ - _wrapLog(value, network2) { - return new Log(formatLog$1(value), this); - } - /** - * Provides the opportunity for a sub-class to wrap a transaction - * receipt before returning it, to add additional properties or an - * alternate sub-class of [[TransactionReceipt]]. - */ - _wrapTransactionReceipt(value, network2) { - return new TransactionReceipt(formatTransactionReceipt$1(value), this); - } - /** - * Provides the opportunity for a sub-class to wrap a transaction - * response before returning it, to add additional properties or an - * alternate sub-class of [[TransactionResponse]]. - */ - _wrapTransactionResponse(tx, network2) { - return new TransactionResponse(formatTransactionResponse(tx), this); - } - /** - * Resolves to the Network, forcing a network detection using whatever - * technique the sub-class requires. - * - * Sub-classes **must** override this. - */ - _detectNetwork() { - assert(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", { - operation: "_detectNetwork" - }); - } - /** - * Sub-classes should use this to perform all built-in operations. All - * methods sanitizes and normalizes the values passed into this. - * - * Sub-classes **must** override this. - */ - async _perform(req) { - assert(false, `unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", { - operation: req.method, - info: req - }); - } - // State - async getBlockNumber() { - const blockNumber = getNumber(await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getBlockNumber" }), "%response"); - if (__privateGet(this, _lastBlockNumber) >= 0) { - __privateSet(this, _lastBlockNumber, blockNumber); - } - return blockNumber; - } - /** - * Returns or resolves to the address for %%address%%, resolving ENS - * names and [[Addressable]] objects and returning if already an - * address. - */ - _getAddress(address) { - return resolveAddress(address, this); - } - /** - * Returns or resolves to a valid block tag for %%blockTag%%, resolving - * negative values and returning if already a valid block tag. - */ - _getBlockTag(blockTag) { - if (blockTag == null) { - return "latest"; - } - switch (blockTag) { - case "earliest": - return "0x0"; - case "finalized": - case "latest": - case "pending": - case "safe": - return blockTag; - } - if (isHexString(blockTag)) { - if (isHexString(blockTag, 32)) { - return blockTag; - } - return toQuantity(blockTag); - } - if (typeof blockTag === "bigint") { - blockTag = getNumber(blockTag, "blockTag"); - } - if (typeof blockTag === "number") { - if (blockTag >= 0) { - return toQuantity(blockTag); - } - if (__privateGet(this, _lastBlockNumber) >= 0) { - return toQuantity(__privateGet(this, _lastBlockNumber) + blockTag); - } - return this.getBlockNumber().then((b2) => toQuantity(b2 + blockTag)); - } - assertArgument(false, "invalid blockTag", "blockTag", blockTag); - } - /** - * Returns or resolves to a filter for %%filter%%, resolving any ENS - * names or [[Addressable]] object and returning if already a valid - * filter. - */ - _getFilter(filter2) { - const topics = (filter2.topics || []).map((t2) => { - if (t2 == null) { - return null; - } - if (Array.isArray(t2)) { - return concisify(t2.map((t3) => t3.toLowerCase())); - } - return t2.toLowerCase(); - }); - const blockHash = "blockHash" in filter2 ? filter2.blockHash : void 0; - const resolve = (_address, fromBlock2, toBlock2) => { - let address2 = void 0; - switch (_address.length) { - case 0: - break; - case 1: - address2 = _address[0]; - break; - default: - _address.sort(); - address2 = _address; - } - if (blockHash) { - if (fromBlock2 != null || toBlock2 != null) { - throw new Error("invalid filter"); - } - } - const filter3 = {}; - if (address2) { - filter3.address = address2; - } - if (topics.length) { - filter3.topics = topics; - } - if (fromBlock2) { - filter3.fromBlock = fromBlock2; - } - if (toBlock2) { - filter3.toBlock = toBlock2; - } - if (blockHash) { - filter3.blockHash = blockHash; - } - return filter3; - }; - let address = []; - if (filter2.address) { - if (Array.isArray(filter2.address)) { - for (const addr of filter2.address) { - address.push(this._getAddress(addr)); - } - } else { - address.push(this._getAddress(filter2.address)); - } - } - let fromBlock = void 0; - if ("fromBlock" in filter2) { - fromBlock = this._getBlockTag(filter2.fromBlock); - } - let toBlock = void 0; - if ("toBlock" in filter2) { - toBlock = this._getBlockTag(filter2.toBlock); - } - if (address.filter((a2) => typeof a2 !== "string").length || fromBlock != null && typeof fromBlock !== "string" || toBlock != null && typeof toBlock !== "string") { - return Promise.all([Promise.all(address), fromBlock, toBlock]).then((result) => { - return resolve(result[0], result[1], result[2]); - }); - } - return resolve(address, fromBlock, toBlock); - } - /** - * Returns or resolves to a transaction for %%request%%, resolving - * any ENS names or [[Addressable]] and returning if already a valid - * transaction. - */ - _getTransactionRequest(_request3) { - const request = copyRequest(_request3); - const promises = []; - ["to", "from"].forEach((key) => { - if (request[key] == null) { - return; - } - const addr = resolveAddress(request[key], this); - if (isPromise$1(addr)) { - promises.push(async function() { - request[key] = await addr; - }()); - } else { - request[key] = addr; - } - }); - if (request.blockTag != null) { - const blockTag = this._getBlockTag(request.blockTag); - if (isPromise$1(blockTag)) { - promises.push(async function() { - request.blockTag = await blockTag; - }()); - } else { - request.blockTag = blockTag; - } - } - if (promises.length) { - return async function() { - await Promise.all(promises); - return request; - }(); - } - return request; - } - async getNetwork() { - if (__privateGet(this, _networkPromise) == null) { - const detectNetwork = (async () => { - try { - const network2 = await this._detectNetwork(); - this.emit("network", network2, null); - return network2; - } catch (error) { - if (__privateGet(this, _networkPromise) === detectNetwork) { - __privateSet(this, _networkPromise, null); - } - throw error; - } - })(); - __privateSet(this, _networkPromise, detectNetwork); - return (await detectNetwork).clone(); - } - const networkPromise = __privateGet(this, _networkPromise); - const [expected, actual] = await Promise.all([ - networkPromise, - this._detectNetwork() - // The actual connected network - ]); - if (expected.chainId !== actual.chainId) { - if (__privateGet(this, _anyNetwork)) { - this.emit("network", actual, expected); - if (__privateGet(this, _networkPromise) === networkPromise) { - __privateSet(this, _networkPromise, Promise.resolve(actual)); - } - } else { - assert(false, `network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", { - event: "changed" - }); - } - } - return expected.clone(); - } - async getFeeData() { - const network2 = await this.getNetwork(); - const getFeeDataFunc = async () => { - const { _block, gasPrice, priorityFee } = await resolveProperties$1({ - _block: __privateMethod(this, _AbstractProvider_instances, getBlock_fn).call(this, "latest", false), - gasPrice: (async () => { - try { - const value = await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getGasPrice" }); - return getBigInt(value, "%response"); - } catch (error) { - } - return null; - })(), - priorityFee: (async () => { - try { - const value = await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getPriorityFee" }); - return getBigInt(value, "%response"); - } catch (error) { - } - return null; - })() - }); - let maxFeePerGas = null; - let maxPriorityFeePerGas = null; - const block = this._wrapBlock(_block, network2); - if (block && block.baseFeePerGas) { - maxPriorityFeePerGas = priorityFee != null ? priorityFee : BigInt("1000000000"); - maxFeePerGas = block.baseFeePerGas * BN_2$1 + maxPriorityFeePerGas; - } - return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); - }; - const plugin = network2.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); - if (plugin) { - const req = new FetchRequest(plugin.url); - const feeData = await plugin.processFunc(getFeeDataFunc, this, req); - return new FeeData(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas); - } - return await getFeeDataFunc(); - } - async estimateGas(_tx) { - let tx = this._getTransactionRequest(_tx); - if (isPromise$1(tx)) { - tx = await tx; - } - return getBigInt(await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { - method: "estimateGas", - transaction: tx - }), "%response"); - } - async call(_tx) { - const { tx, blockTag } = await resolveProperties$1({ - tx: this._getTransactionRequest(_tx), - blockTag: this._getBlockTag(_tx.blockTag) - }); - return await __privateMethod(this, _AbstractProvider_instances, checkNetwork_fn).call(this, __privateMethod(this, _AbstractProvider_instances, call_fn).call(this, tx, blockTag, _tx.enableCcipRead ? 0 : -1)); - } - async getBalance(address, blockTag) { - return getBigInt(await __privateMethod(this, _AbstractProvider_instances, getAccountValue_fn).call(this, { method: "getBalance" }, address, blockTag), "%response"); - } - async getTransactionCount(address, blockTag) { - return getNumber(await __privateMethod(this, _AbstractProvider_instances, getAccountValue_fn).call(this, { method: "getTransactionCount" }, address, blockTag), "%response"); - } - async getCode(address, blockTag) { - return hexlify(await __privateMethod(this, _AbstractProvider_instances, getAccountValue_fn).call(this, { method: "getCode" }, address, blockTag)); - } - async getStorage(address, _position, blockTag) { - const position = getBigInt(_position, "position"); - return hexlify(await __privateMethod(this, _AbstractProvider_instances, getAccountValue_fn).call(this, { method: "getStorage", position }, address, blockTag)); - } - // Write - async broadcastTransaction(signedTx) { - const { blockNumber, hash: hash2, network: network2 } = await resolveProperties$1({ - blockNumber: this.getBlockNumber(), - hash: this._perform({ - method: "broadcastTransaction", - signedTransaction: signedTx - }), - network: this.getNetwork() - }); - const tx = Transaction.from(signedTx); - if (tx.hash !== hash2) { - throw new Error("@TODO: the returned hash did not match"); - } - return this._wrapTransactionResponse(tx, network2).replaceableTransaction(blockNumber); - } - // Queries - async getBlock(block, prefetchTxs) { - const { network: network2, params } = await resolveProperties$1({ - network: this.getNetwork(), - params: __privateMethod(this, _AbstractProvider_instances, getBlock_fn).call(this, block, !!prefetchTxs) - }); - if (params == null) { - return null; - } - return this._wrapBlock(params, network2); - } - async getTransaction(hash2) { - const { network: network2, params } = await resolveProperties$1({ - network: this.getNetwork(), - params: __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getTransaction", hash: hash2 }) - }); - if (params == null) { - return null; - } - return this._wrapTransactionResponse(params, network2); - } - async getTransactionReceipt(hash2) { - const { network: network2, params } = await resolveProperties$1({ - network: this.getNetwork(), - params: __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getTransactionReceipt", hash: hash2 }) - }); - if (params == null) { - return null; - } - if (params.gasPrice == null && params.effectiveGasPrice == null) { - const tx = await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getTransaction", hash: hash2 }); - if (tx == null) { - throw new Error("report this; could not find tx or effectiveGasPrice"); - } - params.effectiveGasPrice = tx.gasPrice; - } - return this._wrapTransactionReceipt(params, network2); - } - async getTransactionResult(hash2) { - const { result } = await resolveProperties$1({ - network: this.getNetwork(), - result: __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getTransactionResult", hash: hash2 }) - }); - if (result == null) { - return null; - } - return hexlify(result); - } - // Bloom-filter Queries - async getLogs(_filter5) { - let filter2 = this._getFilter(_filter5); - if (isPromise$1(filter2)) { - filter2 = await filter2; - } - const { network: network2, params } = await resolveProperties$1({ - network: this.getNetwork(), - params: __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getLogs", filter: filter2 }) - }); - return params.map((p2) => this._wrapLog(p2, network2)); - } - // ENS - _getProvider(chainId) { - assert(false, "provider cannot connect to target network", "UNSUPPORTED_OPERATION", { - operation: "_getProvider()" - }); - } - async getResolver(name2) { - return await EnsResolver.fromName(this, name2); - } - async getAvatar(name2) { - const resolver = await this.getResolver(name2); - if (resolver) { - return await resolver.getAvatar(); - } - return null; - } - async resolveName(name2) { - const resolver = await this.getResolver(name2); - if (resolver) { - return await resolver.getAddress(); - } - return null; - } - async lookupAddress(address) { - address = getAddress$1(address); - const node = namehash$1(address.substring(2).toLowerCase() + ".addr.reverse"); - try { - const ensAddr = await EnsResolver.getEnsAddress(this); - const ensContract = new Contract(ensAddr, [ - "function resolver(bytes32) view returns (address)" - ], this); - const resolver = await ensContract.resolver(node); - if (resolver == null || resolver === ZeroAddress) { - return null; - } - const resolverContract = new Contract(resolver, [ - "function name(bytes32) view returns (string)" - ], this); - const name2 = await resolverContract.name(node); - const check = await this.resolveName(name2); - if (check !== address) { - return null; - } - return name2; - } catch (error) { - if (isError(error, "BAD_DATA") && error.value === "0x") { - return null; - } - if (isError(error, "CALL_EXCEPTION")) { - return null; - } - throw error; - } - return null; - } - async waitForTransaction(hash2, _confirms, timeout) { - const confirms = _confirms != null ? _confirms : 1; - if (confirms === 0) { - return this.getTransactionReceipt(hash2); - } - return new Promise(async (resolve, reject) => { - let timer = null; - const listener = async (blockNumber) => { - try { - const receipt = await this.getTransactionReceipt(hash2); - if (receipt != null) { - if (blockNumber - receipt.blockNumber + 1 >= confirms) { - resolve(receipt); - if (timer) { - clearTimeout(timer); - timer = null; - } - return; - } - } - } catch (error) { - console.log("EEE", error); - } - this.once("block", listener); - }; - if (timeout != null) { - timer = setTimeout(() => { - if (timer == null) { - return; - } - timer = null; - this.off("block", listener); - reject(makeError("timeout", "TIMEOUT", { reason: "timeout" })); - }, timeout); - } - listener(await this.getBlockNumber()); - }); - } - async waitForBlock(blockTag) { - assert(false, "not implemented yet", "NOT_IMPLEMENTED", { - operation: "waitForBlock" - }); - } - /** - * Clear a timer created using the [[_setTimeout]] method. - */ - _clearTimeout(timerId) { - const timer = __privateGet(this, _timers).get(timerId); - if (!timer) { - return; - } - if (timer.timer) { - clearTimeout(timer.timer); - } - __privateGet(this, _timers).delete(timerId); - } - /** - * Create a timer that will execute %%func%% after at least %%timeout%% - * (in ms). If %%timeout%% is unspecified, then %%func%% will execute - * in the next event loop. - * - * [Pausing](AbstractProvider-paused) the provider will pause any - * associated timers. - */ - _setTimeout(_func, timeout) { - if (timeout == null) { - timeout = 0; - } - const timerId = __privateWrapper(this, _nextTimer)._++; - const func = () => { - __privateGet(this, _timers).delete(timerId); - _func(); - }; - if (this.paused) { - __privateGet(this, _timers).set(timerId, { timer: null, func, time: timeout }); - } else { - const timer = setTimeout(func, timeout); - __privateGet(this, _timers).set(timerId, { timer, func, time: getTime$1() }); - } - return timerId; - } - /** - * Perform %%func%% on each subscriber. - */ - _forEachSubscriber(func) { - for (const sub of __privateGet(this, _subs).values()) { - func(sub.subscriber); - } - } - /** - * Sub-classes may override this to customize subscription - * implementations. - */ - _getSubscriber(sub) { - switch (sub.type) { - case "debug": - case "error": - case "network": - return new UnmanagedSubscriber(sub.type); - case "block": { - const subscriber = new PollingBlockSubscriber(this); - subscriber.pollingInterval = this.pollingInterval; - return subscriber; - } - case "safe": - case "finalized": - return new PollingBlockTagSubscriber(this, sub.type); - case "event": - return new PollingEventSubscriber(this, sub.filter); - case "transaction": - return new PollingTransactionSubscriber(this, sub.hash); - case "orphan": - return new PollingOrphanSubscriber(this, sub.filter); - } - throw new Error(`unsupported event: ${sub.type}`); - } - /** - * If a [[Subscriber]] fails and needs to replace itself, this - * method may be used. - * - * For example, this is used for providers when using the - * ``eth_getFilterChanges`` method, which can return null if state - * filters are not supported by the backend, allowing the Subscriber - * to swap in a [[PollingEventSubscriber]]. - */ - _recoverSubscriber(oldSub, newSub) { - for (const sub of __privateGet(this, _subs).values()) { - if (sub.subscriber === oldSub) { - if (sub.started) { - sub.subscriber.stop(); - } - sub.subscriber = newSub; - if (sub.started) { - newSub.start(); - } - if (__privateGet(this, _pausedState) != null) { - newSub.pause(__privateGet(this, _pausedState)); - } - break; - } - } - } - async on(event, listener) { - const sub = await __privateMethod(this, _AbstractProvider_instances, getSub_fn).call(this, event); - sub.listeners.push({ listener, once: false }); - if (!sub.started) { - sub.subscriber.start(); - sub.started = true; - if (__privateGet(this, _pausedState) != null) { - sub.subscriber.pause(__privateGet(this, _pausedState)); - } - } - return this; - } - async once(event, listener) { - const sub = await __privateMethod(this, _AbstractProvider_instances, getSub_fn).call(this, event); - sub.listeners.push({ listener, once: true }); - if (!sub.started) { - sub.subscriber.start(); - sub.started = true; - if (__privateGet(this, _pausedState) != null) { - sub.subscriber.pause(__privateGet(this, _pausedState)); - } - } - return this; - } - async emit(event, ...args) { - const sub = await __privateMethod(this, _AbstractProvider_instances, hasSub_fn).call(this, event, args); - if (!sub || sub.listeners.length === 0) { - return false; - } - const count2 = sub.listeners.length; - sub.listeners = sub.listeners.filter(({ listener, once }) => { - const payload = new EventPayload(this, once ? null : listener, event); - try { - listener.call(this, ...args, payload); - } catch (error) { - } - return !once; - }); - if (sub.listeners.length === 0) { - if (sub.started) { - sub.subscriber.stop(); - } - __privateGet(this, _subs).delete(sub.tag); - } - return count2 > 0; - } - async listenerCount(event) { - if (event) { - const sub = await __privateMethod(this, _AbstractProvider_instances, hasSub_fn).call(this, event); - if (!sub) { - return 0; - } - return sub.listeners.length; - } - let total = 0; - for (const { listeners } of __privateGet(this, _subs).values()) { - total += listeners.length; - } - return total; - } - async listeners(event) { - if (event) { - const sub = await __privateMethod(this, _AbstractProvider_instances, hasSub_fn).call(this, event); - if (!sub) { - return []; - } - return sub.listeners.map(({ listener }) => listener); - } - let result = []; - for (const { listeners } of __privateGet(this, _subs).values()) { - result = result.concat(listeners.map(({ listener }) => listener)); - } - return result; - } - async off(event, listener) { - const sub = await __privateMethod(this, _AbstractProvider_instances, hasSub_fn).call(this, event); - if (!sub) { - return this; - } - if (listener) { - const index2 = sub.listeners.map(({ listener: listener2 }) => listener2).indexOf(listener); - if (index2 >= 0) { - sub.listeners.splice(index2, 1); - } - } - if (!listener || sub.listeners.length === 0) { - if (sub.started) { - sub.subscriber.stop(); - } - __privateGet(this, _subs).delete(sub.tag); - } - return this; - } - async removeAllListeners(event) { - if (event) { - const { tag, started, subscriber } = await __privateMethod(this, _AbstractProvider_instances, getSub_fn).call(this, event); - if (started) { - subscriber.stop(); - } - __privateGet(this, _subs).delete(tag); - } else { - for (const [tag, { started, subscriber }] of __privateGet(this, _subs)) { - if (started) { - subscriber.stop(); - } - __privateGet(this, _subs).delete(tag); - } - } - return this; - } - // Alias for "on" - async addListener(event, listener) { - return await this.on(event, listener); - } - // Alias for "off" - async removeListener(event, listener) { - return this.off(event, listener); - } - /** - * If this provider has been destroyed using the [[destroy]] method. - * - * Once destroyed, all resources are reclaimed, internal event loops - * and timers are cleaned up and no further requests may be sent to - * the provider. - */ - get destroyed() { - return __privateGet(this, _destroyed); - } - /** - * Sub-classes may use this to shutdown any sockets or release their - * resources and reject any pending requests. - * - * Sub-classes **must** call ``super.destroy()``. - */ - destroy() { - this.removeAllListeners(); - for (const timerId of __privateGet(this, _timers).keys()) { - this._clearTimeout(timerId); - } - __privateSet(this, _destroyed, true); - } - /** - * Whether the provider is currently paused. - * - * A paused provider will not emit any events, and generally should - * not make any requests to the network, but that is up to sub-classes - * to manage. - * - * Setting ``paused = true`` is identical to calling ``.pause(false)``, - * which will buffer any events that occur while paused until the - * provider is unpaused. - */ - get paused() { - return __privateGet(this, _pausedState) != null; - } - set paused(pause) { - if (!!pause === this.paused) { - return; - } - if (this.paused) { - this.resume(); - } else { - this.pause(false); - } - } - /** - * Pause the provider. If %%dropWhilePaused%%, any events that occur - * while paused are dropped, otherwise all events will be emitted once - * the provider is unpaused. - */ - pause(dropWhilePaused) { - __privateSet(this, _lastBlockNumber, -1); - if (__privateGet(this, _pausedState) != null) { - if (__privateGet(this, _pausedState) == !!dropWhilePaused) { - return; - } - assert(false, "cannot change pause type; resume first", "UNSUPPORTED_OPERATION", { - operation: "pause" - }); - } - this._forEachSubscriber((s2) => s2.pause(dropWhilePaused)); - __privateSet(this, _pausedState, !!dropWhilePaused); - for (const timer of __privateGet(this, _timers).values()) { - if (timer.timer) { - clearTimeout(timer.timer); - } - timer.time = getTime$1() - timer.time; - } - } - /** - * Resume the provider. - */ - resume() { - if (__privateGet(this, _pausedState) == null) { - return; - } - this._forEachSubscriber((s2) => s2.resume()); - __privateSet(this, _pausedState, null); - for (const timer of __privateGet(this, _timers).values()) { - let timeout = timer.time; - if (timeout < 0) { - timeout = 0; - } - timer.time = getTime$1(); - setTimeout(timer.func, timeout); - } - } -} -_subs = new WeakMap(); -_plugins2 = new WeakMap(); -_pausedState = new WeakMap(); -_destroyed = new WeakMap(); -_networkPromise = new WeakMap(); -_anyNetwork = new WeakMap(); -_performCache = new WeakMap(); -_lastBlockNumber = new WeakMap(); -_nextTimer = new WeakMap(); -_timers = new WeakMap(); -_disableCcipRead = new WeakMap(); -_options2 = new WeakMap(); -_AbstractProvider_instances = new WeakSet(); -perform_fn = async function(req) { - const timeout = __privateGet(this, _options2).cacheTimeout; - if (timeout < 0) { - return await this._perform(req); - } - const tag = getTag$1(req.method, req); - let perform = __privateGet(this, _performCache).get(tag); - if (!perform) { - perform = this._perform(req); - __privateGet(this, _performCache).set(tag, perform); - setTimeout(() => { - if (__privateGet(this, _performCache).get(tag) === perform) { - __privateGet(this, _performCache).delete(tag); - } - }, timeout); - } - return await perform; -}; -call_fn = async function(tx, blockTag, attempt) { - assert(attempt < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", { - reason: "TOO_MANY_REDIRECTS", - transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true }) - }); - const transaction2 = copyRequest(tx); - try { - return hexlify(await this._perform({ method: "call", transaction: transaction2, blockTag })); - } catch (error) { - if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction2.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") { - const data = error.data; - const txSender = await resolveAddress(transaction2.to, this); - let ccipArgs; - try { - ccipArgs = parseOffchainLookup(dataSlice(error.data, 4)); - } catch (error2) { - assert(false, error2.message, "OFFCHAIN_FAULT", { - reason: "BAD_DATA", - transaction: transaction2, - info: { data } - }); - } - assert(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), "CCIP Read sender mismatch", "CALL_EXCEPTION", { - action: "call", - data, - reason: "OffchainLookup", - transaction: transaction2, - invocation: null, - revert: { - signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", - name: "OffchainLookup", - args: ccipArgs.errorArgs - } - }); - const ccipResult = await this.ccipReadFetch(transaction2, ccipArgs.calldata, ccipArgs.urls); - assert(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { - reason: "FETCH_FAILED", - transaction: transaction2, - info: { data: error.data, errorArgs: ccipArgs.errorArgs } - }); - const tx2 = { - to: txSender, - data: concat$1([ccipArgs.selector, encodeBytes$1([ccipResult, ccipArgs.extraData])]) - }; - this.emit("debug", { action: "sendCcipReadCall", transaction: tx2 }); - try { - const result = await __privateMethod(this, _AbstractProvider_instances, call_fn).call(this, tx2, blockTag, attempt + 1); - this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({}, tx2), result }); - return result; - } catch (error2) { - this.emit("debug", { action: "receiveCcipReadCallError", transaction: Object.assign({}, tx2), error: error2 }); - throw error2; - } - } - throw error; - } -}; -checkNetwork_fn = async function(promise) { - const { value } = await resolveProperties$1({ - network: this.getNetwork(), - value: promise - }); - return value; -}; -getAccountValue_fn = async function(request, _address, _blockTag) { - let address = this._getAddress(_address); - let blockTag = this._getBlockTag(_blockTag); - if (typeof address !== "string" || typeof blockTag !== "string") { - [address, blockTag] = await Promise.all([address, blockTag]); - } - return await __privateMethod(this, _AbstractProvider_instances, checkNetwork_fn).call(this, __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, Object.assign(request, { address, blockTag }))); -}; -getBlock_fn = async function(block, includeTransactions) { - if (isHexString(block, 32)) { - return await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { - method: "getBlock", - blockHash: block, - includeTransactions - }); - } - let blockTag = this._getBlockTag(block); - if (typeof blockTag !== "string") { - blockTag = await blockTag; - } - return await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { - method: "getBlock", - blockTag, - includeTransactions - }); -}; -hasSub_fn = async function(event, emitArgs) { - let sub = await getSubscription(event, this); - if (sub.type === "event" && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) { - sub = await getSubscription({ orphan: "drop-log", log: emitArgs[0] }, this); - } - return __privateGet(this, _subs).get(sub.tag) || null; -}; -getSub_fn = async function(event) { - const subscription = await getSubscription(event, this); - const tag = subscription.tag; - let sub = __privateGet(this, _subs).get(tag); - if (!sub) { - const subscriber = this._getSubscriber(subscription); - const addressableMap = /* @__PURE__ */ new WeakMap(); - const nameMap = /* @__PURE__ */ new Map(); - sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [] }; - __privateGet(this, _subs).set(tag, sub); - } - return sub; -}; -function _parseString(result, start) { - try { - const bytes2 = _parseBytes(result, start); - if (bytes2) { - return toUtf8String(bytes2); - } - } catch (error) { - } - return null; -} -function _parseBytes(result, start) { - if (result === "0x") { - return null; - } - try { - const offset2 = getNumber(dataSlice(result, start, start + 32)); - const length = getNumber(dataSlice(result, offset2, offset2 + 32)); - return dataSlice(result, offset2 + 32, offset2 + 32 + length); - } catch (error) { - } - return null; -} -function numPad(value) { - const result = toBeArray(value); - if (result.length > 32) { - throw new Error("internal; should not happen"); - } - const padded = new Uint8Array(32); - padded.set(result, 32 - result.length); - return padded; -} -function bytesPad(value) { - if (value.length % 32 === 0) { - return value; - } - const result = new Uint8Array(Math.ceil(value.length / 32) * 32); - result.set(value); - return result; -} -const empty = new Uint8Array([]); -function encodeBytes$1(datas) { - const result = []; - let byteCount = 0; - for (let i = 0; i < datas.length; i++) { - result.push(empty); - byteCount += 32; - } - for (let i = 0; i < datas.length; i++) { - const data = getBytes(datas[i]); - result[i] = numPad(byteCount); - result.push(numPad(data.length)); - result.push(bytesPad(data)); - byteCount += 32 + Math.ceil(data.length / 32) * 32; - } - return concat$1(result); -} -const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000"; -function parseOffchainLookup(data) { - const result = { - sender: "", - urls: [], - calldata: "", - selector: "", - extraData: "", - errorArgs: [] - }; - assert(dataLength(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", { - reason: "insufficient OffchainLookup data" - }); - const sender = dataSlice(data, 0, 32); - assert(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup sender" - }); - result.sender = dataSlice(sender, 12); - try { - const urls = []; - const urlsOffset = getNumber(dataSlice(data, 32, 64)); - const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32)); - const urlsData = dataSlice(data, urlsOffset + 32); - for (let u2 = 0; u2 < urlsLength; u2++) { - const url = _parseString(urlsData, u2 * 32); - if (url == null) { - throw new Error("abort"); - } - urls.push(url); - } - result.urls = urls; - } catch (error) { - assert(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup urls" - }); - } - try { - const calldata = _parseBytes(data, 64); - if (calldata == null) { - throw new Error("abort"); - } - result.calldata = calldata; - } catch (error) { - assert(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup calldata" - }); - } - assert(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup callbaackSelector" - }); - result.selector = dataSlice(data, 96, 100); - try { - const extraData = _parseBytes(data, 128); - if (extraData == null) { - throw new Error("abort"); - } - result.extraData = extraData; - } catch (error) { - assert(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup extraData" - }); - } - result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k2) => result[k2]); - return result; -} -function checkProvider(signer2, operation) { - if (signer2.provider) { - return signer2.provider; - } - assert(false, "missing provider", "UNSUPPORTED_OPERATION", { operation }); -} -async function populate(signer2, tx) { - let pop = copyRequest(tx); - if (pop.to != null) { - pop.to = resolveAddress(pop.to, signer2); - } - if (pop.from != null) { - const from = pop.from; - pop.from = Promise.all([ - signer2.getAddress(), - resolveAddress(from, signer2) - ]).then(([address, from2]) => { - assertArgument(address.toLowerCase() === from2.toLowerCase(), "transaction from mismatch", "tx.from", from2); - return address; - }); - } else { - pop.from = signer2.getAddress(); - } - return await resolveProperties$1(pop); -} -class AbstractSigner { - /** - * Creates a new Signer connected to %%provider%%. - */ - constructor(provider2) { - /** - * The provider this signer is connected to. - */ - __publicField(this, "provider"); - defineProperties$1(this, { provider: provider2 || null }); - } - async getNonce(blockTag) { - return checkProvider(this, "getTransactionCount").getTransactionCount(await this.getAddress(), blockTag); - } - async populateCall(tx) { - const pop = await populate(this, tx); - return pop; - } - async populateTransaction(tx) { - const provider2 = checkProvider(this, "populateTransaction"); - const pop = await populate(this, tx); - if (pop.nonce == null) { - pop.nonce = await this.getNonce("pending"); - } - if (pop.gasLimit == null) { - pop.gasLimit = await this.estimateGas(pop); - } - const network2 = await this.provider.getNetwork(); - if (pop.chainId != null) { - const chainId = getBigInt(pop.chainId); - assertArgument(chainId === network2.chainId, "transaction chainId mismatch", "tx.chainId", tx.chainId); - } else { - pop.chainId = network2.chainId; - } - const hasEip1559 = pop.maxFeePerGas != null || pop.maxPriorityFeePerGas != null; - if (pop.gasPrice != null && (pop.type === 2 || hasEip1559)) { - assertArgument(false, "eip-1559 transaction do not support gasPrice", "tx", tx); - } else if ((pop.type === 0 || pop.type === 1) && hasEip1559) { - assertArgument(false, "pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "tx", tx); - } - if ((pop.type === 2 || pop.type == null) && (pop.maxFeePerGas != null && pop.maxPriorityFeePerGas != null)) { - pop.type = 2; - } else if (pop.type === 0 || pop.type === 1) { - const feeData = await provider2.getFeeData(); - assert(feeData.gasPrice != null, "network does not support gasPrice", "UNSUPPORTED_OPERATION", { - operation: "getGasPrice" - }); - if (pop.gasPrice == null) { - pop.gasPrice = feeData.gasPrice; - } - } else { - const feeData = await provider2.getFeeData(); - if (pop.type == null) { - if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) { - pop.type = 2; - if (pop.gasPrice != null) { - const gasPrice = pop.gasPrice; - delete pop.gasPrice; - pop.maxFeePerGas = gasPrice; - pop.maxPriorityFeePerGas = gasPrice; - } else { - if (pop.maxFeePerGas == null) { - pop.maxFeePerGas = feeData.maxFeePerGas; - } - if (pop.maxPriorityFeePerGas == null) { - pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; - } - } - } else if (feeData.gasPrice != null) { - assert(!hasEip1559, "network does not support EIP-1559", "UNSUPPORTED_OPERATION", { - operation: "populateTransaction" - }); - if (pop.gasPrice == null) { - pop.gasPrice = feeData.gasPrice; - } - pop.type = 0; - } else { - assert(false, "failed to get consistent fee data", "UNSUPPORTED_OPERATION", { - operation: "signer.getFeeData" - }); - } - } else if (pop.type === 2 || pop.type === 3) { - if (pop.maxFeePerGas == null) { - pop.maxFeePerGas = feeData.maxFeePerGas; - } - if (pop.maxPriorityFeePerGas == null) { - pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; - } - } - } - return await resolveProperties$1(pop); - } - async estimateGas(tx) { - return checkProvider(this, "estimateGas").estimateGas(await this.populateCall(tx)); - } - async call(tx) { - return checkProvider(this, "call").call(await this.populateCall(tx)); - } - async resolveName(name2) { - const provider2 = checkProvider(this, "resolveName"); - return await provider2.resolveName(name2); - } - async sendTransaction(tx) { - const provider2 = checkProvider(this, "sendTransaction"); - const pop = await this.populateTransaction(tx); - delete pop.from; - const txObj = Transaction.from(pop); - return await provider2.broadcastTransaction(await this.signTransaction(txObj)); - } -} -const _VoidSigner = class _VoidSigner extends AbstractSigner { - /** - * Creates a new **VoidSigner** with %%address%% attached to - * %%provider%%. - */ - constructor(address, provider2) { - super(provider2); - __privateAdd(this, _VoidSigner_instances); - /** - * The signer address. - */ - __publicField(this, "address"); - defineProperties$1(this, { address }); - } - async getAddress() { - return this.address; - } - connect(provider2) { - return new _VoidSigner(this.address, provider2); - } - async signTransaction(tx) { - __privateMethod(this, _VoidSigner_instances, throwUnsupported_fn).call(this, "transactions", "signTransaction"); - } - async signMessage(message) { - __privateMethod(this, _VoidSigner_instances, throwUnsupported_fn).call(this, "messages", "signMessage"); - } - async signTypedData(domain2, types2, value) { - __privateMethod(this, _VoidSigner_instances, throwUnsupported_fn).call(this, "typed-data", "signTypedData"); - } -}; -_VoidSigner_instances = new WeakSet(); -throwUnsupported_fn = function(suffix, operation) { - assert(false, `VoidSigner cannot sign ${suffix}`, "UNSUPPORTED_OPERATION", { operation }); -}; -let VoidSigner = _VoidSigner; -const shown = /* @__PURE__ */ new Set(); -function showThrottleMessage(service) { - if (shown.has(service)) { - return; - } - shown.add(service); - console.log("========= NOTICE ========="); - console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`); - console.log(""); - console.log("The default API keys for each service are provided as a highly-throttled,"); - console.log("community resource for low-traffic projects and early prototyping."); - console.log(""); - console.log("While your application will continue to function, we highly recommended"); - console.log("signing up for your own API keys to improve performance, increase your"); - console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."); - console.log(""); - console.log("For more details: https://docs.ethers.org/api-keys/"); - console.log("=========================="); -} -function copy$1(obj) { - return JSON.parse(JSON.stringify(obj)); -} -class FilterIdSubscriber { - /** - * Creates a new **FilterIdSubscriber** which will used [[_subscribe]] - * and [[_emitResults]] to setup the subscription and provide the event - * to the %%provider%%. - */ - constructor(provider2) { - __privateAdd(this, _FilterIdSubscriber_instances); - __privateAdd(this, _provider4); - __privateAdd(this, _filterIdPromise); - __privateAdd(this, _poller3); - __privateAdd(this, _running3); - __privateAdd(this, _network); - __privateAdd(this, _hault); - __privateSet(this, _provider4, provider2); - __privateSet(this, _filterIdPromise, null); - __privateSet(this, _poller3, __privateMethod(this, _FilterIdSubscriber_instances, poll_fn3).bind(this)); - __privateSet(this, _running3, false); - __privateSet(this, _network, null); - __privateSet(this, _hault, false); - } - /** - * Sub-classes **must** override this to begin the subscription. - */ - _subscribe(provider2) { - throw new Error("subclasses must override this"); - } - /** - * Sub-classes **must** override this handle the events. - */ - _emitResults(provider2, result) { - throw new Error("subclasses must override this"); - } - /** - * Sub-classes **must** override this handle recovery on errors. - */ - _recover(provider2) { - throw new Error("subclasses must override this"); - } - start() { - if (__privateGet(this, _running3)) { - return; - } - __privateSet(this, _running3, true); - __privateMethod(this, _FilterIdSubscriber_instances, poll_fn3).call(this, -2); - } - stop() { - if (!__privateGet(this, _running3)) { - return; - } - __privateSet(this, _running3, false); - __privateSet(this, _hault, true); - __privateMethod(this, _FilterIdSubscriber_instances, teardown_fn).call(this); - __privateGet(this, _provider4).off("block", __privateGet(this, _poller3)); - } - pause(dropWhilePaused) { - if (dropWhilePaused) { - __privateMethod(this, _FilterIdSubscriber_instances, teardown_fn).call(this); - } - __privateGet(this, _provider4).off("block", __privateGet(this, _poller3)); - } - resume() { - this.start(); - } -} -_provider4 = new WeakMap(); -_filterIdPromise = new WeakMap(); -_poller3 = new WeakMap(); -_running3 = new WeakMap(); -_network = new WeakMap(); -_hault = new WeakMap(); -_FilterIdSubscriber_instances = new WeakSet(); -poll_fn3 = async function(blockNumber) { - try { - if (__privateGet(this, _filterIdPromise) == null) { - __privateSet(this, _filterIdPromise, this._subscribe(__privateGet(this, _provider4))); - } - let filterId = null; - try { - filterId = await __privateGet(this, _filterIdPromise); - } catch (error) { - if (!isError(error, "UNSUPPORTED_OPERATION") || error.operation !== "eth_newFilter") { - throw error; - } - } - if (filterId == null) { - __privateSet(this, _filterIdPromise, null); - __privateGet(this, _provider4)._recoverSubscriber(this, this._recover(__privateGet(this, _provider4))); - return; - } - const network2 = await __privateGet(this, _provider4).getNetwork(); - if (!__privateGet(this, _network)) { - __privateSet(this, _network, network2); - } - if (__privateGet(this, _network).chainId !== network2.chainId) { - throw new Error("chaid changed"); - } - if (__privateGet(this, _hault)) { - return; - } - const result = await __privateGet(this, _provider4).send("eth_getFilterChanges", [filterId]); - await this._emitResults(__privateGet(this, _provider4), result); - } catch (error) { - console.log("@TODO", error); - } - __privateGet(this, _provider4).once("block", __privateGet(this, _poller3)); -}; -teardown_fn = function() { - const filterIdPromise = __privateGet(this, _filterIdPromise); - if (filterIdPromise) { - __privateSet(this, _filterIdPromise, null); - filterIdPromise.then((filterId) => { - if (__privateGet(this, _provider4).destroyed) { - return; - } - __privateGet(this, _provider4).send("eth_uninstallFilter", [filterId]); - }); - } -}; -class FilterIdEventSubscriber extends FilterIdSubscriber { - /** - * Creates a new **FilterIdEventSubscriber** attached to %%provider%% - * listening for %%filter%%. - */ - constructor(provider2, filter2) { - super(provider2); - __privateAdd(this, _event); - __privateSet(this, _event, copy$1(filter2)); - } - _recover(provider2) { - return new PollingEventSubscriber(provider2, __privateGet(this, _event)); - } - async _subscribe(provider2) { - const filterId = await provider2.send("eth_newFilter", [__privateGet(this, _event)]); - return filterId; - } - async _emitResults(provider2, results2) { - for (const result of results2) { - provider2.emit(__privateGet(this, _event), provider2._wrapLog(result, provider2._network)); - } - } -} -_event = new WeakMap(); -class FilterIdPendingSubscriber extends FilterIdSubscriber { - async _subscribe(provider2) { - return await provider2.send("eth_newPendingTransactionFilter", []); - } - async _emitResults(provider2, results2) { - for (const result of results2) { - provider2.emit("pending", result); - } - } -} -const Primitive$1 = "bigint,boolean,function,number,string,symbol".split(/,/g); -function deepCopy(value) { - if (value == null || Primitive$1.indexOf(typeof value) >= 0) { - return value; - } - if (typeof value.getAddress === "function") { - return value; - } - if (Array.isArray(value)) { - return value.map(deepCopy); - } - if (typeof value === "object") { - return Object.keys(value).reduce((accum, key) => { - accum[key] = value[key]; - return accum; - }, {}); - } - throw new Error(`should not happen: ${value} (${typeof value})`); -} -function stall$3(duration) { - return new Promise((resolve) => { - setTimeout(resolve, duration); - }); -} -function getLowerCase(value) { - if (value) { - return value.toLowerCase(); - } - return value; -} -function isPollable(value) { - return value && typeof value.pollingInterval === "number"; -} -const defaultOptions = { - polling: false, - staticNetwork: null, - batchStallTime: 10, - batchMaxSize: 1 << 20, - batchMaxCount: 100, - cacheTimeout: 250, - pollingInterval: 4e3 +const abi$7 = [{ + inputs: [{ + internalType: "bytes32", + type: "bytes32" + }], + name: "getAlternativeSignature", + outputs: [{ + internalType: "string", + type: "string" + }], + stateMutability: "view", + type: "function" +}]; +var erc5719 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + abi: abi$7 +}); +const abi$6 = [{ + type: "function", + name: "isValidSignature", + constant: true, + inputs: [{ + type: "bytes32" + }, { + type: "bytes" + }], + outputs: [{ + type: "bytes4" + }], + payable: false, + stateMutability: "view" +}]; +const returns = { + isValidSignatureBytes32: "0x1626ba7e" }; -class JsonRpcSigner extends AbstractSigner { - constructor(provider2, address) { - super(provider2); - __publicField(this, "address"); - address = getAddress$1(address); - defineProperties$1(this, { address }); - } - connect(provider2) { - assert(false, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", { - operation: "signer.connect" - }); - } - async getAddress() { - return this.address; - } - // JSON-RPC will automatially fill in nonce, etc. so we just check from - async populateTransaction(tx) { - return await this.populateCall(tx); - } - // Returns just the hash of the transaction after sent, which is what - // the bare JSON-RPC API does; - async sendUncheckedTransaction(_tx) { - const tx = deepCopy(_tx); - const promises = []; - if (tx.from) { - const _from = tx.from; - promises.push((async () => { - const from = await resolveAddress(_from, this.provider); - assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); - tx.from = from; - })()); - } else { - tx.from = this.address; - } - if (tx.gasLimit == null) { - promises.push((async () => { - tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address }); - })()); - } - if (tx.to != null) { - const _to2 = tx.to; - promises.push((async () => { - tx.to = await resolveAddress(_to2, this.provider); - })()); - } - if (promises.length) { - await Promise.all(promises); - } - const hexTx = this.provider.getRpcTransaction(tx); - return this.provider.send("eth_sendTransaction", [hexTx]); - } - async sendTransaction(tx) { - const blockNumber = await this.provider.getBlockNumber(); - const hash2 = await this.sendUncheckedTransaction(tx); - return await new Promise((resolve, reject) => { - const timeouts = [1e3, 100]; - let invalids = 0; - const checkTx = async () => { - try { - const tx2 = await this.provider.getTransaction(hash2); - if (tx2 != null) { - resolve(tx2.replaceableTransaction(blockNumber)); - return; - } - } catch (error) { - if (isError(error, "CANCELLED") || isError(error, "BAD_DATA") || isError(error, "NETWORK_ERROR")) { - if (error.info == null) { - error.info = {}; - } - error.info.sendTransactionHash = hash2; - reject(error); - return; - } - if (isError(error, "INVALID_ARGUMENT")) { - invalids++; - if (error.info == null) { - error.info = {}; - } - error.info.sendTransactionHash = hash2; - if (invalids > 10) { - reject(error); - return; - } - } - this.provider.emit("error", makeError("failed to fetch transation after sending (will try again)", "UNKNOWN_ERROR", { error })); +var erc1271 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + abi: abi$6, + returns +}); +const abi$5 = [{ + inputs: [{ + internalType: "bytes", + name: "error", + type: "bytes" + }], + name: "ERC1271Revert", + type: "error" +}, { + inputs: [{ + internalType: "bytes", + name: "error", + type: "bytes" + }], + name: "ERC6492DeployFailed", + type: "error" +}, { + inputs: [{ + internalType: "address", + name: "_signer", + type: "address" + }, { + internalType: "bytes32", + name: "_hash", + type: "bytes32" + }, { + internalType: "bytes", + name: "_signature", + type: "bytes" + }], + name: "isValidSig", + outputs: [{ + internalType: "bool", + name: "", + type: "bool" + }], + stateMutability: "nonpayable", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_signer", + type: "address" + }, { + internalType: "bytes32", + name: "_hash", + type: "bytes32" + }, { + internalType: "bytes", + name: "_signature", + type: "bytes" + }, { + internalType: "bool", + name: "allowSideEffects", + type: "bool" + }, { + internalType: "bool", + name: "deployAlreadyDeployed", + type: "bool" + }], + name: "isValidSigImpl", + outputs: [{ + internalType: "bool", + name: "", + type: "bool" + }], + stateMutability: "nonpayable", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_signer", + type: "address" + }, { + internalType: "bytes32", + name: "_hash", + type: "bytes32" + }, { + internalType: "bytes", + name: "_signature", + type: "bytes" + }], + name: "isValidSigNoThrow", + outputs: [{ + internalType: "bool", + name: "", + type: "bool" + }], + stateMutability: "nonpayable", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_signer", + type: "address" + }, { + internalType: "bytes32", + name: "_hash", + type: "bytes32" + }, { + internalType: "bytes", + name: "_signature", + type: "bytes" + }], + name: "isValidSigWithSideEffects", + outputs: [{ + internalType: "bool", + name: "", + type: "bool" + }], + stateMutability: "nonpayable", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_signer", + type: "address" + }, { + internalType: "bytes32", + name: "_hash", + type: "bytes32" + }, { + internalType: "bytes", + name: "_signature", + type: "bytes" + }], + name: "isValidSigWithSideEffectsNoThrow", + outputs: [{ + internalType: "bool", + name: "", + type: "bool" + }], + stateMutability: "nonpayable", + type: "function" +}]; +var erc6492 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + abi: abi$5 +}); +const abi$4 = [{ + type: "function", + name: "deploy", + constant: false, + inputs: [{ + type: "address" + }, { + type: "bytes32" + }], + outputs: [], + payable: true, + stateMutability: "payable" +}]; +var factory = /* @__PURE__ */ Object.freeze({ + __proto__: null, + abi: abi$4 +}); +const abi$3 = [{ + type: "function", + name: "nonce", + constant: true, + inputs: [], + outputs: [{ + type: "uint256" + }], + payable: false, + stateMutability: "view" +}, { + type: "function", + name: "readNonce", + constant: true, + inputs: [{ + type: "uint256" + }], + outputs: [{ + type: "uint256" + }], + payable: false, + stateMutability: "view" +}, { + type: "function", + name: "updateImplementation", + constant: false, + inputs: [{ + type: "address" + }], + outputs: [], + payable: false, + stateMutability: "nonpayable" +}, { + type: "function", + name: "selfExecute", + constant: false, + inputs: [{ + components: [{ + type: "bool", + name: "delegateCall" + }, { + type: "bool", + name: "revertOnError" + }, { + type: "uint256", + name: "gasLimit" + }, { + type: "address", + name: "target" + }, { + type: "uint256", + name: "value" + }, { + type: "bytes", + name: "data" + }], + type: "tuple[]" + }], + outputs: [], + payable: false, + stateMutability: "nonpayable" +}, { + type: "function", + name: "execute", + constant: false, + inputs: [{ + components: [{ + type: "bool", + name: "delegateCall" + }, { + type: "bool", + name: "revertOnError" + }, { + type: "uint256", + name: "gasLimit" + }, { + type: "address", + name: "target" + }, { + type: "uint256", + name: "value" + }, { + type: "bytes", + name: "data" + }], + type: "tuple[]" + }, { + type: "uint256" + }, { + type: "bytes" + }], + outputs: [], + payable: false, + stateMutability: "nonpayable" +}, { + type: "function", + name: "createContract", + inputs: [{ + type: "bytes" + }], + payable: true, + stateMutability: "payable" +}, { + type: "function", + name: "setExtraImageHash", + constant: false, + inputs: [{ + type: "bytes32", + name: "imageHash" + }, { + type: "uint256", + name: "expiration" + }], + outputs: [], + payable: false, + stateMutability: "nonpayable" +}]; +var mainModule = /* @__PURE__ */ Object.freeze({ + __proto__: null, + abi: abi$3 +}); +const abi$2 = [{ + type: "function", + name: "updateImageHash", + constant: true, + inputs: [{ + type: "bytes32" + }], + outputs: [], + payable: false, + stateMutability: "view" +}, { + type: "function", + name: "imageHash", + constant: true, + inputs: [], + outputs: [{ + type: "bytes32" + }], + payable: false, + stateMutability: "view" +}]; +var mainModuleUpgradable = /* @__PURE__ */ Object.freeze({ + __proto__: null, + abi: abi$2 +}); +const abi$1$1 = [{ + inputs: [{ + internalType: "address", + name: "_factory", + type: "address" + }, { + internalType: "address", + name: "_mainModule", + type: "address" + }], + stateMutability: "nonpayable", + type: "constructor" +}, { + anonymous: false, + inputs: [{ + indexed: true, + internalType: "address", + name: "_wallet", + type: "address" + }, { + indexed: true, + internalType: "bytes32", + name: "_imageHash", + type: "bytes32" + }, { + indexed: false, + internalType: "uint256", + name: "_threshold", + type: "uint256" + }, { + indexed: false, + internalType: "bytes", + name: "_signers", + type: "bytes" + }], + name: "RequiredConfig", + type: "event" +}, { + anonymous: false, + inputs: [{ + indexed: true, + internalType: "address", + name: "_wallet", + type: "address" + }, { + indexed: true, + internalType: "address", + name: "_signer", + type: "address" + }], + name: "RequiredSigner", + type: "event" +}, { + inputs: [{ + internalType: "address", + name: "_addr", + type: "address" + }], + name: "callBalanceOf", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [], + name: "callBlockNumber", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [{ + internalType: "uint256", + name: "_i", + type: "uint256" + }], + name: "callBlockhash", + outputs: [{ + internalType: "bytes32", + name: "", + type: "bytes32" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [], + name: "callChainId", + outputs: [{ + internalType: "uint256", + name: "id", + type: "uint256" + }], + stateMutability: "pure", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_addr", + type: "address" + }], + name: "callCode", + outputs: [{ + internalType: "bytes", + name: "code", + type: "bytes" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_addr", + type: "address" + }], + name: "callCodeHash", + outputs: [{ + internalType: "bytes32", + name: "codeHash", + type: "bytes32" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_addr", + type: "address" + }], + name: "callCodeSize", + outputs: [{ + internalType: "uint256", + name: "size", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [], + name: "callCoinbase", + outputs: [{ + internalType: "address", + name: "", + type: "address" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [], + name: "callDifficulty", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [], + name: "callGasLeft", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [], + name: "callGasLimit", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [], + name: "callGasPrice", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [], + name: "callOrigin", + outputs: [{ + internalType: "address", + name: "", + type: "address" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [], + name: "callTimestamp", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "", + type: "address" + }], + name: "knownImageHashes", + outputs: [{ + internalType: "bytes32", + name: "", + type: "bytes32" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [{ + internalType: "bytes32", + name: "", + type: "bytes32" + }], + name: "lastImageHashUpdate", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "", + type: "address" + }], + name: "lastSignerUpdate", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "", + type: "address" + }], + name: "lastWalletUpdate", + outputs: [{ + internalType: "uint256", + name: "", + type: "uint256" + }], + stateMutability: "view", + type: "function" +}, { + inputs: [{ + components: [{ + internalType: "bool", + name: "delegateCall", + type: "bool" + }, { + internalType: "bool", + name: "revertOnError", + type: "bool" + }, { + internalType: "uint256", + name: "gasLimit", + type: "uint256" + }, { + internalType: "address", + name: "target", + type: "address" + }, { + internalType: "uint256", + name: "value", + type: "uint256" + }, { + internalType: "bytes", + name: "data", + type: "bytes" + }], + internalType: "struct IModuleCalls.Transaction[]", + name: "_txs", + type: "tuple[]" + }], + name: "multiCall", + outputs: [{ + internalType: "bool[]", + name: "_successes", + type: "bool[]" + }, { + internalType: "bytes[]", + name: "_results", + type: "bytes[]" + }], + stateMutability: "payable", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_wallet", + type: "address" + }, { + internalType: "uint256", + name: "_threshold", + type: "uint256" + }, { + components: [{ + internalType: "uint256", + name: "weight", + type: "uint256" + }, { + internalType: "address", + name: "signer", + type: "address" + }], + internalType: "struct RequireUtils.Member[]", + name: "_members", + type: "tuple[]" + }, { + internalType: "bool", + name: "_index", + type: "bool" + }], + name: "publishConfig", + outputs: [], + stateMutability: "nonpayable", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_wallet", + type: "address" + }, { + internalType: "bytes32", + name: "_hash", + type: "bytes32" + }, { + internalType: "uint256", + name: "_sizeMembers", + type: "uint256" + }, { + internalType: "bytes", + name: "_signature", + type: "bytes" + }, { + internalType: "bool", + name: "_index", + type: "bool" + }], + name: "publishInitialSigners", + outputs: [], + stateMutability: "nonpayable", + type: "function" +}, { + inputs: [{ + internalType: "address", + name: "_wallet", + type: "address" + }, { + internalType: "uint256", + name: "_nonce", + type: "uint256" + }], + name: "requireMinNonce", + outputs: [], + stateMutability: "view", + type: "function" +}, { + inputs: [{ + internalType: "uint256", + name: "_expiration", + type: "uint256" + }], + name: "requireNonExpired", + outputs: [], + stateMutability: "view", + type: "function" +}]; +var sequenceUtils = /* @__PURE__ */ Object.freeze({ + __proto__: null, + abi: abi$1$1 +}); +const abi$8 = [{ + inputs: [{ + internalType: "address", + name: "", + type: "address" + }], + name: "requireFreshSigner", + outputs: [], + stateMutability: "nonpayable", + type: "function" +}]; +var requireFreshSigner = /* @__PURE__ */ Object.freeze({ + __proto__: null, + abi: abi$8 +}); +const walletContracts = { + erc6492, + erc5719, + erc1271, + factory, + mainModule, + mainModuleUpgradable, + sequenceUtils, + requireFreshSigner +}; +const abi$1$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + walletContracts +}, Symbol.toStringTag, { value: "Module" })); +function _extends$f() { + _extends$f = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; } - this.provider._setTimeout(() => { - checkTx(); - }, timeouts.pop() || 4e3); - }; - checkTx(); - }); - } - async signTransaction(_tx) { - const tx = deepCopy(_tx); - if (tx.from) { - const from = await resolveAddress(tx.from, this.provider); - assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); - tx.from = from; - } else { - tx.from = this.address; + } } - const hexTx = this.provider.getRpcTransaction(tx); - return await this.provider.send("eth_signTransaction", [hexTx]); - } - async signMessage(_message) { - const message = typeof _message === "string" ? toUtf8Bytes(_message) : _message; - return await this.provider.send("personal_sign", [ - hexlify(message), - this.address.toLowerCase() - ]); - } - async signTypedData(domain2, types2, _value2) { - const value = deepCopy(_value2); - const populated = await TypedDataEncoder.resolveNames(domain2, types2, value, async (value2) => { - const address = await resolveAddress(value2); - assertArgument(address != null, "TypedData does not support null address", "value", value2); - return address; - }); - return await this.provider.send("eth_signTypedData_v4", [ - this.address.toLowerCase(), - JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types2, populated.value)) - ]); - } - async unlock(password) { - return this.provider.send("personal_unlockAccount", [ - this.address.toLowerCase(), - password, - null - ]); - } - // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign - async _legacySignMessage(_message) { - const message = typeof _message === "string" ? toUtf8Bytes(_message) : _message; - return await this.provider.send("eth_sign", [ - this.address.toLowerCase(), - hexlify(message) - ]); - } + return target; + }; + return _extends$f.apply(this, arguments); } -class JsonRpcApiProvider extends AbstractProvider { - constructor(network2, options) { - super(network2, options); - __privateAdd(this, _JsonRpcApiProvider_instances); - __privateAdd(this, _options3); - // The next ID to use for the JSON-RPC ID field - __privateAdd(this, _nextId2); - // Payloads are queued and triggered in batches using the drainTimer - __privateAdd(this, _payloads); - __privateAdd(this, _drainTimer); - __privateAdd(this, _notReady); - __privateAdd(this, _network2); - __privateAdd(this, _pendingDetectNetwork); - __privateSet(this, _nextId2, 1); - __privateSet(this, _options3, Object.assign({}, defaultOptions, options || {})); - __privateSet(this, _payloads, []); - __privateSet(this, _drainTimer, null); - __privateSet(this, _network2, null); - __privateSet(this, _pendingDetectNetwork, null); - { - let resolve = null; - const promise = new Promise((_resolve) => { - resolve = _resolve; +const WebRPCVersion$3 = "v1"; +const WebRPCSchemaVersion$3 = "v0.4.0"; +const WebRPCSchemaHash$3 = "d3f5f1338693d60d58f87bc408a076218201a097"; +let SortOrder$2 = /* @__PURE__ */ function(SortOrder2) { + SortOrder2["DESC"] = "DESC"; + SortOrder2["ASC"] = "ASC"; + return SortOrder2; +}({}); +let TokenType = /* @__PURE__ */ function(TokenType2) { + TokenType2["ERC20"] = "ERC20"; + TokenType2["ERC721"] = "ERC721"; + TokenType2["ERC1155"] = "ERC1155"; + return TokenType2; +}({}); +class API { + constructor(hostname, fetch2) { + this.hostname = void 0; + this.fetch = void 0; + this.path = "/rpc/API/"; + this.ping = (headers, signal) => { + return this.fetch(this.url("Ping"), createHTTPRequest$7({}, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.version = (headers, signal) => { + return this.fetch(this.url("Version"), createHTTPRequest$7({}, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + version: _data6.version + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.runtimeStatus = (headers, signal) => { + return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$7({}, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.clock = (headers, signal) => { + return this.fetch(this.url("Clock"), createHTTPRequest$7({}, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + serverTime: _data6.serverTime + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getSequenceContext = (headers, signal) => { + return this.fetch(this.url("GetSequenceContext"), createHTTPRequest$7({}, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + data: _data6.data + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getAuthToken = (args, headers, signal) => { + return this.fetch(this.url("GetAuthToken"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status, + jwtToken: _data6.jwtToken, + address: _data6.address, + user: _data6.user + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getAuthToken2 = (args, headers, signal) => { + return this.fetch(this.url("GetAuthToken2"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status, + jwtToken: _data6.jwtToken, + address: _data6.address, + user: _data6.user + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.sendPasswordlessLink = (args, headers, signal) => { + return this.fetch(this.url("SendPasswordlessLink"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.friendList = (args, headers, signal) => { + return this.fetch(this.url("FriendList"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + page: _data6.page, + friends: _data6.friends + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getFriendByAddress = (args, headers, signal) => { + return this.fetch(this.url("GetFriendByAddress"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status, + friend: _data6.friend + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.searchFriends = (args, headers, signal) => { + return this.fetch(this.url("SearchFriends"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + friends: _data6.friends + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.addFriend = (args, headers, signal) => { + return this.fetch(this.url("AddFriend"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status, + friend: _data6.friend + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.updateFriendNickname = (args, headers, signal) => { + return this.fetch(this.url("UpdateFriendNickname"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status, + friend: _data6.friend + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.removeFriend = (args, headers, signal) => { + return this.fetch(this.url("RemoveFriend"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.contractCall = (args, headers, signal) => { + return this.fetch(this.url("ContractCall"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + returns: _data6.returns + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.decodeContractCall = (args, headers, signal) => { + return this.fetch(this.url("DecodeContractCall"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + call: _data6.call + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.lookupContractCallSelectors = (args, headers, signal) => { + return this.fetch(this.url("LookupContractCallSelectors"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + signatures: _data6.signatures + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.userStorageFetch = (args, headers, signal) => { + return this.fetch(this.url("UserStorageFetch"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + object: _data6.object + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.userStorageSave = (args, headers, signal) => { + return this.fetch(this.url("UserStorageSave"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.userStorageDelete = (args, headers, signal) => { + return this.fetch(this.url("UserStorageDelete"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.userStorageFetchAll = (args, headers, signal) => { + return this.fetch(this.url("UserStorageFetchAll"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + objects: _data6.objects + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getMoonpayLink = (args, headers, signal) => { + return this.fetch(this.url("GetMoonpayLink"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + signedUrl: _data6.signedUrl + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getSardineClientToken = (headers, signal) => { + return this.fetch(this.url("GetSardineClientToken"), createHTTPRequest$7({}, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + token: _data6.token + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getSardineNFTCheckoutToken = (args, headers, signal) => { + return this.fetch(this.url("GetSardineNFTCheckoutToken"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + resp: _data6.resp + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getSardineNFTCheckoutOrderStatus = (args, headers, signal) => { + return this.fetch(this.url("GetSardineNFTCheckoutOrderStatus"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + resp: _data6.resp + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.resolveENSAddress = (args, headers, signal) => { + return this.fetch(this.url("ResolveENSAddress"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + address: _data6.address, + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.isValidSignature = (args, headers, signal) => { + return this.fetch(this.url("IsValidSignature"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + isValid: _data6.isValid + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.isValidMessageSignature = (args, headers, signal) => { + return this.fetch(this.url("IsValidMessageSignature"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + isValid: _data6.isValid + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - __privateSet(this, _notReady, { promise, resolve }); - } - const staticNetwork = this._getOption("staticNetwork"); - if (typeof staticNetwork === "boolean") { - assertArgument(!staticNetwork || network2 !== "any", "staticNetwork cannot be used on special network 'any'", "options", options); - if (staticNetwork && network2 != null) { - __privateSet(this, _network2, Network.from(network2)); - } - } else if (staticNetwork) { - assertArgument(network2 == null || staticNetwork.matches(network2), "staticNetwork MUST match network object", "options", options); - __privateSet(this, _network2, staticNetwork); - } - } - /** - * Returns the value associated with the option %%key%%. - * - * Sub-classes can use this to inquire about configuration options. - */ - _getOption(key) { - return __privateGet(this, _options3)[key]; - } - /** - * Gets the [[Network]] this provider has committed to. On each call, the network - * is detected, and if it has changed, the call will reject. - */ - get _network() { - assert(__privateGet(this, _network2), "network is not available yet", "NETWORK_ERROR"); - return __privateGet(this, _network2); - } - /** - * Resolves to the non-normalized value by performing %%req%%. - * - * Sub-classes may override this to modify behavior of actions, - * and should generally call ``super._perform`` as a fallback. - */ - async _perform(req) { - if (req.method === "call" || req.method === "estimateGas") { - let tx = req.transaction; - if (tx && tx.type != null && getBigInt(tx.type)) { - if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { - const feeData = await this.getFeeData(); - if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { - req = Object.assign({}, req, { - transaction: Object.assign({}, tx, { type: void 0 }) - }); - } - } - } - } - const request = this.getRpcRequest(req); - if (request != null) { - return await this.send(request.method, request.args); - } - return super._perform(req); - } - /** - * Sub-classes may override this; it detects the *actual* network that - * we are **currently** connected to. - * - * Keep in mind that [[send]] may only be used once [[ready]], otherwise the - * _send primitive must be used instead. - */ - async _detectNetwork() { - const network2 = this._getOption("staticNetwork"); - if (network2) { - if (network2 === true) { - if (__privateGet(this, _network2)) { - return __privateGet(this, _network2); - } - } else { - return network2; - } - } - if (__privateGet(this, _pendingDetectNetwork)) { - return await __privateGet(this, _pendingDetectNetwork); - } - if (this.ready) { - __privateSet(this, _pendingDetectNetwork, (async () => { - try { - const result = Network.from(getBigInt(await this.send("eth_chainId", []))); - __privateSet(this, _pendingDetectNetwork, null); - return result; - } catch (error) { - __privateSet(this, _pendingDetectNetwork, null); - throw error; - } - })()); - return await __privateGet(this, _pendingDetectNetwork); - } - __privateSet(this, _pendingDetectNetwork, (async () => { - const payload = { - id: __privateWrapper(this, _nextId2)._++, - method: "eth_chainId", - params: [], - jsonrpc: "2.0" - }; - this.emit("debug", { action: "sendRpcPayload", payload }); - let result; - try { - result = (await this._send(payload))[0]; - __privateSet(this, _pendingDetectNetwork, null); - } catch (error) { - __privateSet(this, _pendingDetectNetwork, null); - this.emit("debug", { action: "receiveRpcError", error }); - throw error; - } - this.emit("debug", { action: "receiveRpcResult", result }); - if ("result" in result) { - return Network.from(getBigInt(result.result)); - } - throw this.getRpcError(payload, result); - })()); - return await __privateGet(this, _pendingDetectNetwork); - } - /** - * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls - * will be passed to [[_send]] from [[send]]. If it is overridden, then - * ``super._start()`` **MUST** be called. - * - * Calling it multiple times is safe and has no effect. - */ - _start() { - if (__privateGet(this, _notReady) == null || __privateGet(this, _notReady).resolve == null) { - return; - } - __privateGet(this, _notReady).resolve(); - __privateSet(this, _notReady, null); - (async () => { - while (__privateGet(this, _network2) == null && !this.destroyed) { - try { - __privateSet(this, _network2, await this._detectNetwork()); - } catch (error) { - if (this.destroyed) { - break; - } - console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"); - this.emit("error", makeError("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error } })); - await stall$3(1e3); - } - } - __privateMethod(this, _JsonRpcApiProvider_instances, scheduleDrain_fn).call(this); - })(); - } - /** - * Resolves once the [[_start]] has been called. This can be used in - * sub-classes to defer sending data until the connection has been - * established. - */ - async _waitUntilReady() { - if (__privateGet(this, _notReady) == null) { - return; - } - return await __privateGet(this, _notReady).promise; - } - /** - * Return a Subscriber that will manage the %%sub%%. - * - * Sub-classes may override this to modify the behavior of - * subscription management. - */ - _getSubscriber(sub) { - if (sub.type === "pending") { - return new FilterIdPendingSubscriber(this); - } - if (sub.type === "event") { - if (this._getOption("polling")) { - return new PollingEventSubscriber(this, sub.filter); - } - return new FilterIdEventSubscriber(this, sub.filter); - } - if (sub.type === "orphan" && sub.filter.orphan === "drop-log") { - return new UnmanagedSubscriber("orphan"); - } - return super._getSubscriber(sub); - } - /** - * Returns true only if the [[_start]] has been called. - */ - get ready() { - return __privateGet(this, _notReady) == null; - } - /** - * Returns %%tx%% as a normalized JSON-RPC transaction request, - * which has all values hexlified and any numeric values converted - * to Quantity values. - */ - getRpcTransaction(tx) { - const result = {}; - ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach((key) => { - if (tx[key] == null) { - return; - } - let dstKey = key; - if (key === "gasLimit") { - dstKey = "gas"; - } - result[dstKey] = toQuantity(getBigInt(tx[key], `tx.${key}`)); - }); - ["from", "to", "data"].forEach((key) => { - if (tx[key] == null) { - return; - } - result[key] = hexlify(tx[key]); - }); - if (tx.accessList) { - result["accessList"] = accessListify(tx.accessList); - } - if (tx.blobVersionedHashes) { - result["blobVersionedHashes"] = tx.blobVersionedHashes.map((h2) => h2.toLowerCase()); - } - return result; - } - /** - * Returns the request method and arguments required to perform - * %%req%%. - */ - getRpcRequest(req) { - switch (req.method) { - case "chainId": - return { method: "eth_chainId", args: [] }; - case "getBlockNumber": - return { method: "eth_blockNumber", args: [] }; - case "getGasPrice": - return { method: "eth_gasPrice", args: [] }; - case "getPriorityFee": - return { method: "eth_maxPriorityFeePerGas", args: [] }; - case "getBalance": - return { - method: "eth_getBalance", - args: [getLowerCase(req.address), req.blockTag] - }; - case "getTransactionCount": - return { - method: "eth_getTransactionCount", - args: [getLowerCase(req.address), req.blockTag] - }; - case "getCode": - return { - method: "eth_getCode", - args: [getLowerCase(req.address), req.blockTag] - }; - case "getStorage": - return { - method: "eth_getStorageAt", - args: [ - getLowerCase(req.address), - "0x" + req.position.toString(16), - req.blockTag - ] - }; - case "broadcastTransaction": - return { - method: "eth_sendRawTransaction", - args: [req.signedTransaction] - }; - case "getBlock": - if ("blockTag" in req) { + }; + this.isValidTypedDataSignature = (args, headers, signal) => { + return this.fetch(this.url("IsValidTypedDataSignature"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { return { - method: "eth_getBlockByNumber", - args: [req.blockTag, !!req.includeTransactions] + isValid: _data6.isValid }; - } else if ("blockHash" in req) { + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.isValidETHAuthProof = (args, headers, signal) => { + return this.fetch(this.url("IsValidETHAuthProof"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { return { - method: "eth_getBlockByHash", - args: [req.blockHash, !!req.includeTransactions] + isValid: _data6.isValid }; - } - break; - case "getTransaction": - return { - method: "eth_getTransactionByHash", - args: [req.hash] - }; - case "getTransactionReceipt": - return { - method: "eth_getTransactionReceipt", - args: [req.hash] - }; - case "call": - return { - method: "eth_call", - args: [this.getRpcTransaction(req.transaction), req.blockTag] - }; - case "estimateGas": { - return { - method: "eth_estimateGas", - args: [this.getRpcTransaction(req.transaction)] - }; - } - case "getLogs": - if (req.filter && req.filter.address != null) { - if (Array.isArray(req.filter.address)) { - req.filter.address = req.filter.address.map(getLowerCase); - } else { - req.filter.address = getLowerCase(req.filter.address); - } - } - return { method: "eth_getLogs", args: [req.filter] }; - } - return null; - } - /** - * Returns an ethers-style Error for the given JSON-RPC error - * %%payload%%, coalescing the various strings and error shapes - * that different nodes return, coercing them into a machine-readable - * standardized error. - */ - getRpcError(payload, _error2) { - const { method } = payload; - const { error } = _error2; - if (method === "eth_estimateGas" && error.message) { - const msg = error.message; - if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) { - return makeError("insufficient funds", "INSUFFICIENT_FUNDS", { - transaction: payload.params[0], - info: { payload, error } }); - } - } - if (method === "eth_call" || method === "eth_estimateGas") { - const result = spelunkData(error); - const e2 = AbiCoder.getBuiltinCallException(method === "eth_call" ? "call" : "estimateGas", payload.params[0], result ? result.data : null); - e2.info = { error, payload }; - return e2; - } - const message = JSON.stringify(spelunkMessage(error)); - if (typeof error.message === "string" && error.message.match(/user denied|ethers-user-denied/i)) { - const actionMap = { - eth_sign: "signMessage", - personal_sign: "signMessage", - eth_signTypedData_v4: "signTypedData", - eth_signTransaction: "signTransaction", - eth_sendTransaction: "sendTransaction", - eth_requestAccounts: "requestAccess", - wallet_requestAccounts: "requestAccess" - }; - return makeError(`user rejected action`, "ACTION_REJECTED", { - action: actionMap[method] || "unknown", - reason: "rejected", - info: { payload, error } + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getCoinPrices = (args, headers, signal) => { + return this.fetch(this.url("GetCoinPrices"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + tokenPrices: _data6.tokenPrices + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getCollectiblePrices = (args, headers, signal) => { + return this.fetch(this.url("GetCollectiblePrices"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + tokenPrices: _data6.tokenPrices + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getExchangeRate = (args, headers, signal) => { + return this.fetch(this.url("GetExchangeRate"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + exchangeRate: _data6.exchangeRate + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.memoryStore = (args, headers, signal) => { + return this.fetch(this.url("MemoryStore"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.memoryLoad = (args, headers, signal) => { + return this.fetch(this.url("MemoryLoad"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + value: _data6.value + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getInviteInfo = (headers, signal) => { + return this.fetch(this.url("GetInviteInfo"), createHTTPRequest$7({}, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + inviteInfo: _data6.inviteInfo + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.isValidAccessCode = (args, headers, signal) => { + return this.fetch(this.url("IsValidAccessCode"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.internalClaimAccessCode = (args, headers, signal) => { + return this.fetch(this.url("InternalClaimAccessCode"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.blockNumberAtTime = (args, headers, signal) => { + return this.fetch(this.url("BlockNumberAtTime"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + blocks: _data6.blocks + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.paperSessionSecret = (args, headers, signal) => { + return this.fetch(this.url("PaperSessionSecret"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + secret: _data6.secret + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.paperSessionSecret2 = (args, headers, signal) => { + return this.fetch(this.url("PaperSessionSecret2"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + secret: _data6.secret + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.linkWallet = (args, headers, signal) => { + return this.fetch(this.url("LinkWallet"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status, + linkedWalletAddress: _data6.linkedWalletAddress + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getLinkedWallets = (args, headers, signal) => { + return this.fetch(this.url("GetLinkedWallets"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + linkedWallets: _data6.linkedWallets + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - } - if (method === "eth_sendRawTransaction" || method === "eth_sendTransaction") { - const transaction2 = payload.params[0]; - if (message.match(/insufficient funds|base fee exceeds gas limit/i)) { - return makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { - transaction: transaction2, - info: { error } + }; + this.removeLinkedWallet = (args, headers, signal) => { + return this.fetch(this.url("RemoveLinkedWallet"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + status: _data6.status + }; }); - } - if (message.match(/nonce/i) && message.match(/too low/i)) { - return makeError("nonce has already been used", "NONCE_EXPIRED", { transaction: transaction2, info: { error } }); - } - if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) { - return makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { transaction: transaction2, info: { error } }); - } - if (message.match(/only replay-protected/i)) { - return makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", { - operation: method, - info: { transaction: transaction2, info: { error } } + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` }); - } - } - let unsupported = !!message.match(/the method .* does not exist/i); - if (!unsupported) { - if (error && error.details && error.details.startsWith("Unauthorized method:")) { - unsupported = true; - } - } - if (unsupported) { - return makeError("unsupported operation", "UNSUPPORTED_OPERATION", { - operation: payload.method, - info: { error, payload } }); - } - return makeError("could not coalesce error", "UNKNOWN_ERROR", { error, payload }); - } - /** - * Requests the %%method%% with %%params%% via the JSON-RPC protocol - * over the underlying channel. This can be used to call methods - * on the backend that do not have a high-level API within the Provider - * API. - * - * This method queues requests according to the batch constraints - * in the options, assigns the request a unique ID. - * - * **Do NOT override** this method in sub-classes; instead - * override [[_send]] or force the options values in the - * call to the constructor to modify this method's behavior. - */ - send(method, params) { - if (this.destroyed) { - return Promise.reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: method })); - } - const id2 = __privateWrapper(this, _nextId2)._++; - const promise = new Promise((resolve, reject) => { - __privateGet(this, _payloads).push({ - resolve, - reject, - payload: { method, params, id: id2, jsonrpc: "2.0" } + }; + this.generateWaaSVerificationURL = (args, headers, signal) => { + return this.fetch(this.url("GenerateWaaSVerificationURL"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + nonce: _data6.nonce, + verificationURL: _data6.verificationURL + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - }); - __privateMethod(this, _JsonRpcApiProvider_instances, scheduleDrain_fn).call(this); - return promise; - } - /** - * Resolves to the [[Signer]] account for %%address%% managed by - * the client. - * - * If the %%address%% is a number, it is used as an index in the - * the accounts from [[listAccounts]]. - * - * This can only be used on clients which manage accounts (such as - * Geth with imported account or MetaMask). - * - * Throws if the account doesn't exist. - */ - async getSigner(address) { - if (address == null) { - address = 0; - } - const accountsPromise = this.send("eth_accounts", []); - if (typeof address === "number") { - const accounts2 = await accountsPromise; - if (address >= accounts2.length) { - throw new Error("no such account"); - } - return new JsonRpcSigner(this, accounts2[address]); - } - const { accounts } = await resolveProperties$1({ - network: this.getNetwork(), - accounts: accountsPromise - }); - address = getAddress$1(address); - for (const account2 of accounts) { - if (getAddress$1(account2) === address) { - return new JsonRpcSigner(this, address); - } - } - throw new Error("invalid account"); - } - async listAccounts() { - const accounts = await this.send("eth_accounts", []); - return accounts.map((a2) => new JsonRpcSigner(this, a2)); - } - destroy() { - if (__privateGet(this, _drainTimer)) { - clearTimeout(__privateGet(this, _drainTimer)); - __privateSet(this, _drainTimer, null); - } - for (const { payload, reject } of __privateGet(this, _payloads)) { - reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method })); - } - __privateSet(this, _payloads, []); - super.destroy(); - } -} -_options3 = new WeakMap(); -_nextId2 = new WeakMap(); -_payloads = new WeakMap(); -_drainTimer = new WeakMap(); -_notReady = new WeakMap(); -_network2 = new WeakMap(); -_pendingDetectNetwork = new WeakMap(); -_JsonRpcApiProvider_instances = new WeakSet(); -scheduleDrain_fn = function() { - if (__privateGet(this, _drainTimer)) { - return; - } - const stallTime = this._getOption("batchMaxCount") === 1 ? 0 : this._getOption("batchStallTime"); - __privateSet(this, _drainTimer, setTimeout(() => { - __privateSet(this, _drainTimer, null); - const payloads = __privateGet(this, _payloads); - __privateSet(this, _payloads, []); - while (payloads.length) { - const batch = [payloads.shift()]; - while (payloads.length) { - if (batch.length === __privateGet(this, _options3).batchMaxCount) { - break; - } - batch.push(payloads.shift()); - const bytes2 = JSON.stringify(batch.map((p2) => p2.payload)); - if (bytes2.length > __privateGet(this, _options3).batchMaxSize) { - payloads.unshift(batch.pop()); - break; - } - } - (async () => { - const payload = batch.length === 1 ? batch[0].payload : batch.map((p2) => p2.payload); - this.emit("debug", { action: "sendRpcPayload", payload }); - try { - const result = await this._send(payload); - this.emit("debug", { action: "receiveRpcResult", result }); - for (const { resolve, reject, payload: payload2 } of batch) { - if (this.destroyed) { - reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload2.method })); - continue; - } - const resp = result.filter((r2) => r2.id === payload2.id)[0]; - if (resp == null) { - const error = makeError("missing response for request", "BAD_DATA", { - value: result, - info: { payload: payload2 } - }); - this.emit("error", error); - reject(error); - continue; - } - if ("error" in resp) { - reject(this.getRpcError(payload2, resp)); - continue; - } - resolve(resp.result); - } - } catch (error) { - this.emit("debug", { action: "receiveRpcError", error }); - for (const { reject } of batch) { - reject(error); - } - } - })(); - } - }, stallTime)); -}; -class JsonRpcApiPollingProvider extends JsonRpcApiProvider { - constructor(network2, options) { - super(network2, options); - __privateAdd(this, _pollingInterval); - let pollingInterval = this._getOption("pollingInterval"); - if (pollingInterval == null) { - pollingInterval = defaultOptions.pollingInterval; - } - __privateSet(this, _pollingInterval, pollingInterval); - } - _getSubscriber(sub) { - const subscriber = super._getSubscriber(sub); - if (isPollable(subscriber)) { - subscriber.pollingInterval = __privateGet(this, _pollingInterval); - } - return subscriber; - } - /** - * The polling interval (default: 4000 ms) - */ - get pollingInterval() { - return __privateGet(this, _pollingInterval); - } - set pollingInterval(value) { - if (!Number.isInteger(value) || value < 0) { - throw new Error("invalid interval"); - } - __privateSet(this, _pollingInterval, value); - this._forEachSubscriber((sub) => { - if (isPollable(sub)) { - sub.pollingInterval = __privateGet(this, _pollingInterval); - } - }); - } -} -_pollingInterval = new WeakMap(); -let JsonRpcProvider$1 = (_b = class extends JsonRpcApiPollingProvider { - constructor(url, network2, options) { - if (url == null) { - url = "http://localhost:8545"; - } - super(network2, options); - __privateAdd(this, _connect); - if (typeof url === "string") { - __privateSet(this, _connect, new FetchRequest(url)); - } else { - __privateSet(this, _connect, url.clone()); - } - } - _getConnection() { - return __privateGet(this, _connect).clone(); - } - async send(method, params) { - await this._start(); - return await super.send(method, params); - } - async _send(payload) { - const request = this._getConnection(); - request.body = JSON.stringify(payload); - request.setHeader("content-type", "application/json"); - const response = await request.send(); - response.assertOk(); - let resp = response.bodyJson; - if (!Array.isArray(resp)) { - resp = [resp]; - } - return resp; - } -}, _connect = new WeakMap(), _b); -function spelunkData(value) { - if (value == null) { - return null; - } - if (typeof value.message === "string" && value.message.match(/revert/i) && isHexString(value.data)) { - return { message: value.message, data: value.data }; - } - if (typeof value === "object") { - for (const key in value) { - const result = spelunkData(value[key]); - if (result) { - return result; - } - } - return null; - } - if (typeof value === "string") { - try { - return spelunkData(JSON.parse(value)); - } catch (error) { - } - } - return null; -} -function _spelunkMessage(value, result) { - if (value == null) { - return; - } - if (typeof value.message === "string") { - result.push(value.message); - } - if (typeof value === "object") { - for (const key in value) { - _spelunkMessage(value[key], result); - } - } - if (typeof value === "string") { - try { - return _spelunkMessage(JSON.parse(value), result); - } catch (error) { - } - } -} -function spelunkMessage(value) { - const result = []; - _spelunkMessage(value, result); - return result; -} -const defaultApiKey$1 = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972"; -function getHost$5(name2) { - switch (name2) { - case "mainnet": - return "rpc.ankr.com/eth"; - case "goerli": - return "rpc.ankr.com/eth_goerli"; - case "sepolia": - return "rpc.ankr.com/eth_sepolia"; - case "arbitrum": - return "rpc.ankr.com/arbitrum"; - case "base": - return "rpc.ankr.com/base"; - case "base-goerli": - return "rpc.ankr.com/base_goerli"; - case "base-sepolia": - return "rpc.ankr.com/base_sepolia"; - case "bnb": - return "rpc.ankr.com/bsc"; - case "bnbt": - return "rpc.ankr.com/bsc_testnet_chapel"; - case "matic": - return "rpc.ankr.com/polygon"; - case "matic-mumbai": - return "rpc.ankr.com/polygon_mumbai"; - case "optimism": - return "rpc.ankr.com/optimism"; - case "optimism-goerli": - return "rpc.ankr.com/optimism_testnet"; - case "optimism-sepolia": - return "rpc.ankr.com/optimism_sepolia"; - } - assertArgument(false, "unsupported network", "network", name2); -} -class AnkrProvider extends JsonRpcProvider$1 { - /** - * Create a new **AnkrProvider**. - * - * By default connecting to ``mainnet`` with a highly throttled - * API key. - */ - constructor(_network3, apiKey) { - if (_network3 == null) { - _network3 = "mainnet"; - } - const network2 = Network.from(_network3); - if (apiKey == null) { - apiKey = defaultApiKey$1; - } - const options = { polling: true, staticNetwork: network2 }; - const request = AnkrProvider.getRequest(network2, apiKey); - super(request, network2, options); - /** - * The API key for the Ankr connection. - */ - __publicField(this, "apiKey"); - defineProperties$1(this, { apiKey }); - } - _getProvider(chainId) { - try { - return new AnkrProvider(chainId, this.apiKey); - } catch (error) { - } - return super._getProvider(chainId); - } - /** - * Returns a prepared request for connecting to %%network%% with - * %%apiKey%%. - */ - static getRequest(network2, apiKey) { - if (apiKey == null) { - apiKey = defaultApiKey$1; - } - const request = new FetchRequest(`https://${getHost$5(network2.name)}/${apiKey}`); - request.allowGzip = true; - if (apiKey === defaultApiKey$1) { - request.retryFunc = async (request2, response, attempt) => { - showThrottleMessage("AnkrProvider"); - return true; - }; - } - return request; - } - getRpcError(payload, error) { - if (payload.method === "eth_sendRawTransaction") { - if (error && error.error && error.error.message === "INTERNAL_ERROR: could not replace existing tx") { - error.error.message = "replacement transaction underpriced"; - } - } - return super.getRpcError(payload, error); - } - isCommunityResource() { - return this.apiKey === defaultApiKey$1; - } -} -const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC"; -function getHost$4(name2) { - switch (name2) { - case "mainnet": - return "eth-mainnet.alchemyapi.io"; - case "goerli": - return "eth-goerli.g.alchemy.com"; - case "sepolia": - return "eth-sepolia.g.alchemy.com"; - case "arbitrum": - return "arb-mainnet.g.alchemy.com"; - case "arbitrum-goerli": - return "arb-goerli.g.alchemy.com"; - case "arbitrum-sepolia": - return "arb-sepolia.g.alchemy.com"; - case "base": - return "base-mainnet.g.alchemy.com"; - case "base-goerli": - return "base-goerli.g.alchemy.com"; - case "base-sepolia": - return "base-sepolia.g.alchemy.com"; - case "matic": - return "polygon-mainnet.g.alchemy.com"; - case "matic-amoy": - return "polygon-amoy.g.alchemy.com"; - case "matic-mumbai": - return "polygon-mumbai.g.alchemy.com"; - case "optimism": - return "opt-mainnet.g.alchemy.com"; - case "optimism-goerli": - return "opt-goerli.g.alchemy.com"; - case "optimism-sepolia": - return "opt-sepolia.g.alchemy.com"; - } - assertArgument(false, "unsupported network", "network", name2); -} -class AlchemyProvider extends JsonRpcProvider$1 { - constructor(_network3, apiKey) { - if (_network3 == null) { - _network3 = "mainnet"; - } - const network2 = Network.from(_network3); - if (apiKey == null) { - apiKey = defaultApiKey; - } - const request = AlchemyProvider.getRequest(network2, apiKey); - super(request, network2, { staticNetwork: network2 }); - __publicField(this, "apiKey"); - defineProperties$1(this, { apiKey }); - } - _getProvider(chainId) { - try { - return new AlchemyProvider(chainId, this.apiKey); - } catch (error) { - } - return super._getProvider(chainId); - } - async _perform(req) { - if (req.method === "getTransactionResult") { - const { trace, tx } = await resolveProperties$1({ - trace: this.send("trace_transaction", [req.hash]), - tx: this.getTransaction(req.hash) + }; + this.validateWaaSVerificationNonce = (args, headers, signal) => { + return this.fetch(this.url("ValidateWaaSVerificationNonce"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + walletAddress: _data6.walletAddress + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getSwapQuotes = (args, headers, signal) => { + return this.fetch(this.url("GetSwapQuotes"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + swapQuotes: _data6.swapQuotes + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - if (trace == null || tx == null) { - return null; - } - let data; - let error = false; - try { - data = trace[0].result.output; - error = trace[0].error === "Reverted"; - } catch (error2) { - } - if (data) { - assert(!error, "an error occurred during transaction executions", "CALL_EXCEPTION", { - action: "getTransactionResult", - data, - reason: null, - transaction: tx, - invocation: null, - revert: null - // @TODO + }; + this.addCurrencyGroup = (args, headers, signal) => { + return this.fetch(this.url("AddCurrencyGroup"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + groupId: _data6.groupId + }; }); - return data; - } - assert(false, "could not parse trace result", "BAD_DATA", { value: trace }); - } - return await super._perform(req); - } - isCommunityResource() { - return this.apiKey === defaultApiKey; - } - static getRequest(network2, apiKey) { - if (apiKey == null) { - apiKey = defaultApiKey; - } - const request = new FetchRequest(`https://${getHost$4(network2.name)}/v2/${apiKey}`); - request.allowGzip = true; - if (apiKey === defaultApiKey) { - request.retryFunc = async (request2, response, attempt) => { - showThrottleMessage("alchemy"); - return true; - }; - } - return request; - } -} -function getApiKey(name2) { - switch (name2) { - case "mainnet": - return "39f1d67cedf8b7831010a665328c9197"; - case "arbitrum": - return "0550c209db33c3abf4cc927e1e18cea1"; - case "bnb": - return "98b5a77e531614387366f6fc5da097f8"; - case "matic": - return "cd9d4d70377471aa7c142ec4a4205249"; - } - assertArgument(false, "unsupported network", "network", name2); -} -function getHost$3(name2) { - switch (name2) { - case "mainnet": - return "ethereum-mainnet.core.chainstack.com"; - case "arbitrum": - return "arbitrum-mainnet.core.chainstack.com"; - case "bnb": - return "bsc-mainnet.core.chainstack.com"; - case "matic": - return "polygon-mainnet.core.chainstack.com"; - } - assertArgument(false, "unsupported network", "network", name2); -} -class ChainstackProvider extends JsonRpcProvider$1 { - /** - * Creates a new **ChainstackProvider**. - */ - constructor(_network3, apiKey) { - if (_network3 == null) { - _network3 = "mainnet"; - } - const network2 = Network.from(_network3); - if (apiKey == null) { - apiKey = getApiKey(network2.name); - } - const request = ChainstackProvider.getRequest(network2, apiKey); - super(request, network2, { staticNetwork: network2 }); - /** - * The API key for the Chainstack connection. - */ - __publicField(this, "apiKey"); - defineProperties$1(this, { apiKey }); - } - _getProvider(chainId) { - try { - return new ChainstackProvider(chainId, this.apiKey); - } catch (error) { - } - return super._getProvider(chainId); - } - isCommunityResource() { - return this.apiKey === getApiKey(this._network.name); - } - /** - * Returns a prepared request for connecting to %%network%% - * with %%apiKey%% and %%projectSecret%%. - */ - static getRequest(network2, apiKey) { - if (apiKey == null) { - apiKey = getApiKey(network2.name); - } - const request = new FetchRequest(`https://${getHost$3(network2.name)}/${apiKey}`); - request.allowGzip = true; - if (apiKey === getApiKey(network2.name)) { - request.retryFunc = async (request2, response, attempt) => { - showThrottleMessage("ChainstackProvider"); - return true; - }; - } - return request; - } -} -class CloudflareProvider extends JsonRpcProvider$1 { - constructor(_network3) { - if (_network3 == null) { - _network3 = "mainnet"; - } - const network2 = Network.from(_network3); - assertArgument(network2.name === "mainnet", "unsupported network", "network", _network3); - super("https://cloudflare-eth.com/", network2, { staticNetwork: network2 }); - } -} -const THROTTLE = 2e3; -function isPromise(value) { - return value && typeof value.then === "function"; -} -const EtherscanPluginId = "org.ethers.plugins.provider.Etherscan"; -class EtherscanPlugin extends NetworkPlugin { - /** - * Creates a new **EtherscanProvider** which will use - * %%baseUrl%%. - */ - constructor(baseUrl) { - super(EtherscanPluginId); - /** - * The Etherscan API base URL. - */ - __publicField(this, "baseUrl"); - defineProperties$1(this, { baseUrl }); - } - clone() { - return new EtherscanPlugin(this.baseUrl); - } -} -const skipKeys = ["enableCcipRead"]; -let nextId = 1; -class EtherscanProvider extends AbstractProvider { - /** - * Creates a new **EtherscanBaseProvider**. - */ - constructor(_network3, _apiKey) { - const apiKey = _apiKey != null ? _apiKey : null; - super(); - /** - * The connected network. - */ - __publicField(this, "network"); - /** - * The API key or null if using the community provided bandwidth. - */ - __publicField(this, "apiKey"); - __privateAdd(this, _plugin); - const network2 = Network.from(_network3); - __privateSet(this, _plugin, network2.getPlugin(EtherscanPluginId)); - defineProperties$1(this, { apiKey, network: network2 }); - this.getBaseUrl(); - } - /** - * Returns the base URL. - * - * If an [[EtherscanPlugin]] is configured on the - * [[EtherscanBaseProvider_network]], returns the plugin's - * baseUrl. - */ - getBaseUrl() { - if (__privateGet(this, _plugin)) { - return __privateGet(this, _plugin).baseUrl; - } - switch (this.network.name) { - case "mainnet": - return "https://api.etherscan.io"; - case "goerli": - return "https://api-goerli.etherscan.io"; - case "sepolia": - return "https://api-sepolia.etherscan.io"; - case "holesky": - return "https://api-holesky.etherscan.io"; - case "arbitrum": - return "https://api.arbiscan.io"; - case "arbitrum-goerli": - return "https://api-goerli.arbiscan.io"; - case "base": - return "https://api.basescan.org"; - case "base-sepolia": - return "https://api-sepolia.basescan.org"; - case "bnb": - return "https://api.bscscan.com"; - case "bnbt": - return "https://api-testnet.bscscan.com"; - case "matic": - return "https://api.polygonscan.com"; - case "matic-amoy": - return "https://api-amoy.polygonscan.com"; - case "matic-mumbai": - return "https://api-testnet.polygonscan.com"; - case "optimism": - return "https://api-optimistic.etherscan.io"; - case "optimism-goerli": - return "https://api-goerli-optimistic.etherscan.io"; - } - assertArgument(false, "unsupported network", "network", this.network); - } - /** - * Returns the URL for the %%module%% and %%params%%. - */ - getUrl(module2, params) { - const query = Object.keys(params).reduce((accum, key) => { - const value = params[key]; - if (value != null) { - accum += `&${key}=${value}`; - } - return accum; - }, ""); - const apiKey = this.apiKey ? `&apikey=${this.apiKey}` : ""; - return `${this.getBaseUrl()}/api?module=${module2}${query}${apiKey}`; - } - /** - * Returns the URL for using POST requests. - */ - getPostUrl() { - return `${this.getBaseUrl()}/api`; - } - /** - * Returns the parameters for using POST requests. - */ - getPostData(module2, params) { - params.module = module2; - params.apikey = this.apiKey; - return params; - } - async detectNetwork() { - return this.network; - } - /** - * Resolves to the result of calling %%module%% with %%params%%. - * - * If %%post%%, the request is made as a POST request. - */ - async fetch(module2, params, post) { - const id2 = nextId++; - const url = post ? this.getPostUrl() : this.getUrl(module2, params); - const payload = post ? this.getPostData(module2, params) : null; - this.emit("debug", { action: "sendRequest", id: id2, url, payload }); - const request = new FetchRequest(url); - request.setThrottleParams({ slotInterval: 1e3 }); - request.retryFunc = (req, resp, attempt) => { - if (this.isCommunityResource()) { - showThrottleMessage("Etherscan"); - } - return Promise.resolve(true); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); }; - request.processFunc = async (request2, response2) => { - const result2 = response2.hasBody() ? JSON.parse(toUtf8String(response2.body)) : {}; - const throttle = (typeof result2.result === "string" ? result2.result : "").toLowerCase().indexOf("rate limit") >= 0; - if (module2 === "proxy") { - if (result2 && result2.status == 0 && result2.message == "NOTOK" && throttle) { - this.emit("debug", { action: "receiveError", id: id2, reason: "proxy-NOTOK", error: result2 }); - response2.throwThrottleError(result2.result, THROTTLE); - } - } else { - if (throttle) { - this.emit("debug", { action: "receiveError", id: id2, reason: "null result", error: result2.result }); - response2.throwThrottleError(result2.result, THROTTLE); - } - } - return response2; + this.updateCurrencyGroup = (args, headers, signal) => { + return this.fetch(this.url("UpdateCurrencyGroup"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); }; - if (payload) { - request.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8"); - request.body = Object.keys(payload).map((k2) => `${k2}=${payload[k2]}`).join("&"); - } - const response = await request.send(); - try { - response.assertOk(); - } catch (error) { - this.emit("debug", { action: "receiveError", id: id2, error, reason: "assertOk" }); - assert(false, "response error", "SERVER_ERROR", { request, response }); - } - if (!response.hasBody()) { - this.emit("debug", { action: "receiveError", id: id2, error: "missing body", reason: "null body" }); - assert(false, "missing response", "SERVER_ERROR", { request, response }); - } - const result = JSON.parse(toUtf8String(response.body)); - if (module2 === "proxy") { - if (result.jsonrpc != "2.0") { - this.emit("debug", { action: "receiveError", id: id2, result, reason: "invalid JSON-RPC" }); - assert(false, "invalid JSON-RPC response (missing jsonrpc='2.0')", "SERVER_ERROR", { request, response, info: { result } }); - } - if (result.error) { - this.emit("debug", { action: "receiveError", id: id2, result, reason: "JSON-RPC error" }); - assert(false, "error response", "SERVER_ERROR", { request, response, info: { result } }); - } - this.emit("debug", { action: "receiveRequest", id: id2, result }); - return result.result; - } else { - if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) { - this.emit("debug", { action: "receiveRequest", id: id2, result }); - return result.result; - } - if (result.status != 1 || typeof result.message === "string" && !result.message.match(/^OK/)) { - this.emit("debug", { action: "receiveError", id: id2, result }); - assert(false, "error response", "SERVER_ERROR", { request, response, info: { result } }); - } - this.emit("debug", { action: "receiveRequest", id: id2, result }); - return result.result; - } - } - /** - * Returns %%transaction%% normalized for the Etherscan API. - */ - _getTransactionPostData(transaction2) { - const result = {}; - for (let key in transaction2) { - if (skipKeys.indexOf(key) >= 0) { - continue; - } - if (transaction2[key] == null) { - continue; - } - let value = transaction2[key]; - if (key === "type" && value === 0) { - continue; - } - if (key === "blockTag" && value === "latest") { - continue; - } - if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) { - value = toQuantity(value); - } else if (key === "accessList") { - value = "[" + accessListify(value).map((set) => { - return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`; - }).join(",") + "]"; - } else if (key === "blobVersionedHashes") { - if (value.length === 0) { - continue; - } - assert(false, "Etherscan API does not support blobVersionedHashes", "UNSUPPORTED_OPERATION", { - operation: "_getTransactionPostData", - info: { transaction: transaction2 } + this.listCurrencyGroups = (headers, signal) => { + return this.fetch(this.url("ListCurrencyGroups"), createHTTPRequest$7({}, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + currencyGroups: _data6.currencyGroups + }; }); - } else { - value = hexlify(value); - } - result[key] = value; - } - return result; - } - /** - * Throws the normalized Etherscan error. - */ - _checkError(req, error, transaction2) { - let message = ""; - if (isError(error, "SERVER_ERROR")) { - try { - message = error.info.result.error.message; - } catch (e2) { - } - if (!message) { - try { - message = error.info.message; - } catch (e2) { - } - } - } - if (req.method === "estimateGas") { - if (!message.match(/revert/i) && message.match(/insufficient funds/i)) { - assert(false, "insufficient funds", "INSUFFICIENT_FUNDS", { - transaction: req.transaction + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` }); - } - } - if (req.method === "call" || req.method === "estimateGas") { - if (message.match(/execution reverted/i)) { - let data = ""; - try { - data = error.info.result.error.data; - } catch (error2) { - } - const e2 = AbiCoder.getBuiltinCallException(req.method, req.transaction, data); - e2.info = { request: req, error }; - throw e2; - } - } - if (message) { - if (req.method === "broadcastTransaction") { - const transaction3 = Transaction.from(req.signedTransaction); - if (message.match(/replacement/i) && message.match(/underpriced/i)) { - assert(false, "replacement fee too low", "REPLACEMENT_UNDERPRICED", { - transaction: transaction3 - }); - } - if (message.match(/insufficient funds/)) { - assert(false, "insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { - transaction: transaction3 - }); - } - if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) { - assert(false, "nonce has already been used", "NONCE_EXPIRED", { - transaction: transaction3 - }); - } - } - } - throw error; - } - async _detectNetwork() { - return this.network; - } - async _perform(req) { - switch (req.method) { - case "chainId": - return this.network.chainId; - case "getBlockNumber": - return this.fetch("proxy", { action: "eth_blockNumber" }); - case "getGasPrice": - return this.fetch("proxy", { action: "eth_gasPrice" }); - case "getPriorityFee": - if (this.network.name === "mainnet") { - return "1000000000"; - } else if (this.network.name === "optimism") { - return "1000000"; - } else { - throw new Error("fallback onto the AbstractProvider default"); - } - case "getBalance": - return this.fetch("account", { - action: "balance", - address: req.address, - tag: req.blockTag + }); + }; + this.deleteCurrencyGroup = (args, headers, signal) => { + return this.fetch(this.url("DeleteCurrencyGroup"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.addInventoryPaymentConfig = (args, headers, signal) => { + return this.fetch(this.url("AddInventoryPaymentConfig"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + configId: _data6.configId + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getInventoryPaymentConfig = (args, headers, signal) => { + return this.fetch(this.url("GetInventoryPaymentConfig"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + config: _data6.config + }; }); - case "getTransactionCount": - return this.fetch("proxy", { - action: "eth_getTransactionCount", - address: req.address, - tag: req.blockTag + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` }); - case "getCode": - return this.fetch("proxy", { - action: "eth_getCode", - address: req.address, - tag: req.blockTag + }); + }; + this.listInventoryPaymentConfigs = (args, headers, signal) => { + return this.fetch(this.url("ListInventoryPaymentConfigs"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + configs: _data6.configs + }; }); - case "getStorage": - return this.fetch("proxy", { - action: "eth_getStorageAt", - address: req.address, - position: req.position, - tag: req.blockTag + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` }); - case "broadcastTransaction": - return this.fetch("proxy", { - action: "eth_sendRawTransaction", - hex: req.signedTransaction - }, true).catch((error) => { - return this._checkError(req, error, req.signedTransaction); + }); + }; + this.updateInventoryPaymentConfig = (args, headers, signal) => { + return this.fetch(this.url("UpdateInventoryPaymentConfig"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return {}; }); - case "getBlock": - if ("blockTag" in req) { - return this.fetch("proxy", { - action: "eth_getBlockByNumber", - tag: req.blockTag, - boolean: req.includeTransactions ? "true" : "false" - }); - } - assert(false, "getBlock by blockHash not supported by Etherscan", "UNSUPPORTED_OPERATION", { - operation: "getBlock(blockHash)" + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` }); - case "getTransaction": - return this.fetch("proxy", { - action: "eth_getTransactionByHash", - txhash: req.hash + }); + }; + this.deleteInventoryPaymentConfig = (args, headers, signal) => { + return this.fetch(this.url("DeleteInventoryPaymentConfig"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + ok: _data6.ok + }; }); - case "getTransactionReceipt": - return this.fetch("proxy", { - action: "eth_getTransactionReceipt", - txhash: req.hash + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` }); - case "call": { - if (req.blockTag !== "latest") { - throw new Error("EtherscanProvider does not support blockTag for call"); - } - const postData = this._getTransactionPostData(req.transaction); - postData.module = "proxy"; - postData.action = "eth_call"; - try { - return await this.fetch("proxy", postData, true); - } catch (error) { - return this._checkError(req, error, req.transaction); - } - } - case "estimateGas": { - const postData = this._getTransactionPostData(req.transaction); - postData.module = "proxy"; - postData.action = "eth_estimateGas"; - try { - return await this.fetch("proxy", postData, true); - } catch (error) { - return this._checkError(req, error, req.transaction); - } - } - } - return super._perform(req); - } - async getNetwork() { - return this.network; + }); + }; + this.requestInventoryPayment = (args, headers, signal) => { + return this.fetch(this.url("RequestInventoryPayment"), createHTTPRequest$7(args, headers, signal)).then((res) => { + return buildResponse$7(res).then((_data6) => { + return { + payment: _data6.payment + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$7.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.hostname = hostname; + this.fetch = (input2, init2) => fetch2(input2, init2); } - /** - * Resolves to the current price of ether. - * - * This returns ``0`` on any network other than ``mainnet``. - */ - async getEtherPrice() { - if (this.network.name !== "mainnet") { - return 0; - } - return parseFloat((await this.fetch("stats", { action: "ethprice" })).ethusd); + url(name2) { + return this.hostname + this.path + name2; } - /** - * Resolves to a [Contract]] for %%address%%, using the - * Etherscan API to retreive the Contract ABI. - */ - async getContract(_address) { - let address = this._getAddress(_address); - if (isPromise(address)) { - address = await address; - } +} +const createHTTPRequest$7 = (body = {}, headers = {}, signal = null) => { + return { + method: "POST", + headers: _extends$f({}, headers, { + "Content-Type": "application/json" + }), + body: JSON.stringify(body || {}), + signal + }; +}; +const buildResponse$7 = (res) => { + return res.text().then((text2) => { + let data; try { - const resp = await this.fetch("contract", { - action: "getabi", - address - }); - const abi2 = JSON.parse(resp); - return new Contract(address, abi2, this); + data = JSON.parse(text2); } catch (error) { - return null; + let message = ""; + if (error instanceof Error) { + message = error.message; + } + throw WebrpcBadResponseError$7.new({ + status: res.status, + cause: `JSON.parse(): ${message}: response text: ${text2}` + }); } + if (!res.ok) { + const code2 = typeof data.code === "number" ? data.code : 0; + throw (webrpcErrorByCode$7[code2] || WebrpcError$7).new(data); + } + return data; + }); +}; +let WebrpcError$7 = class WebrpcError extends Error { + constructor(name2, code2, message, status, cause) { + super(message); + this.name = void 0; + this.code = void 0; + this.message = void 0; + this.status = void 0; + this.cause = void 0; + this.msg = void 0; + this.name = name2 || "WebrpcError"; + this.code = typeof code2 === "number" ? code2 : 0; + this.message = message || `endpoint error ${this.code}`; + this.msg = this.message; + this.status = typeof status === "number" ? status : 0; + this.cause = cause; + Object.setPrototypeOf(this, WebrpcError.prototype); } - isCommunityResource() { - return this.apiKey == null; - } -} -_plugin = new WeakMap(); -function getGlobal() { - if (typeof self !== "undefined") { - return self; + static new(payload) { + return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); } - if (typeof window !== "undefined") { - return window; +}; +let WebrpcEndpointError$7 = class WebrpcEndpointError extends WebrpcError$7 { + constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcEndpointError.prototype); } - if (typeof global$1 !== "undefined") { - return global$1; +}; +let WebrpcRequestFailedError$7 = class WebrpcRequestFailedError extends WebrpcError$7 { + constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcRequestFailedError.prototype); } - throw new Error("unable to locate global object"); -} -const _WebSocket = getGlobal().WebSocket; -class SocketSubscriber { - /** - * Creates a new **SocketSubscriber** attached to %%provider%% listening - * to %%filter%%. - */ - constructor(provider2, filter2) { - __privateAdd(this, _provider5); - __privateAdd(this, _filter4); - __privateAdd(this, _filterId); - __privateAdd(this, _paused); - __privateAdd(this, _emitPromise); - __privateSet(this, _provider5, provider2); - __privateSet(this, _filter4, JSON.stringify(filter2)); - __privateSet(this, _filterId, null); - __privateSet(this, _paused, null); - __privateSet(this, _emitPromise, null); +}; +let WebrpcBadRouteError$7 = class WebrpcBadRouteError extends WebrpcError$7 { + constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRouteError.prototype); } - /** - * The filter. - */ - get filter() { - return JSON.parse(__privateGet(this, _filter4)); +}; +let WebrpcBadMethodError$7 = class WebrpcBadMethodError extends WebrpcError$7 { + constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadMethodError.prototype); } - start() { - __privateSet(this, _filterId, __privateGet(this, _provider5).send("eth_subscribe", this.filter).then((filterId) => { - __privateGet(this, _provider5)._register(filterId, this); - return filterId; - })); +}; +let WebrpcBadRequestError$7 = class WebrpcBadRequestError extends WebrpcError$7 { + constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRequestError.prototype); } - stop() { - __privateGet(this, _filterId).then((filterId) => { - if (__privateGet(this, _provider5).destroyed) { - return; - } - __privateGet(this, _provider5).send("eth_unsubscribe", [filterId]); - }); - __privateSet(this, _filterId, null); +}; +let WebrpcBadResponseError$7 = class WebrpcBadResponseError extends WebrpcError$7 { + constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadResponseError.prototype); } - // @TODO: pause should trap the current blockNumber, unsub, and on resume use getLogs - // and resume - pause(dropWhilePaused) { - assert(dropWhilePaused, "preserve logs while paused not supported by SocketSubscriber yet", "UNSUPPORTED_OPERATION", { operation: "pause(false)" }); - __privateSet(this, _paused, !!dropWhilePaused); +}; +let WebrpcServerPanicError$7 = class WebrpcServerPanicError extends WebrpcError$7 { + constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcServerPanicError.prototype); } - resume() { - __privateSet(this, _paused, null); +}; +let WebrpcInternalErrorError$7 = class WebrpcInternalErrorError extends WebrpcError$7 { + constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcInternalErrorError.prototype); } - /** - * @_ignore: - */ - _handleMessage(message) { - if (__privateGet(this, _filterId) == null) { - return; - } - if (__privateGet(this, _paused) === null) { - let emitPromise = __privateGet(this, _emitPromise); - if (emitPromise == null) { - emitPromise = this._emit(__privateGet(this, _provider5), message); - } else { - emitPromise = emitPromise.then(async () => { - await this._emit(__privateGet(this, _provider5), message); - }); - } - __privateSet(this, _emitPromise, emitPromise.then(() => { - if (__privateGet(this, _emitPromise) === emitPromise) { - __privateSet(this, _emitPromise, null); - } - })); - } +}; +let WebrpcClientDisconnectedError$7 = class WebrpcClientDisconnectedError extends WebrpcError$7 { + constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcClientDisconnectedError.prototype); } - /** - * Sub-classes **must** override this to emit the events on the - * provider. - */ - async _emit(provider2, message) { - throw new Error("sub-classes must implemente this; _emit"); +}; +let WebrpcStreamLostError$7 = class WebrpcStreamLostError extends WebrpcError$7 { + constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamLostError.prototype); } -} -_provider5 = new WeakMap(); -_filter4 = new WeakMap(); -_filterId = new WeakMap(); -_paused = new WeakMap(); -_emitPromise = new WeakMap(); -class SocketBlockSubscriber extends SocketSubscriber { - /** - * @_ignore: - */ - constructor(provider2) { - super(provider2, ["newHeads"]); +}; +let WebrpcStreamFinishedError$7 = class WebrpcStreamFinishedError extends WebrpcError$7 { + constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamFinishedError.prototype); } - async _emit(provider2, message) { - provider2.emit("block", parseInt(message.number)); +}; +let UnauthorizedError$6 = class UnauthorizedError extends WebrpcError$7 { + constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, UnauthorizedError.prototype); } -} -class SocketPendingSubscriber extends SocketSubscriber { - /** - * @_ignore: - */ - constructor(provider2) { - super(provider2, ["newPendingTransactions"]); +}; +let PermissionDeniedError$4 = class PermissionDeniedError extends WebrpcError$7 { + constructor(name2 = "PermissionDenied", code2 = 1001, message = "Permission denied", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, PermissionDeniedError.prototype); } - async _emit(provider2, message) { - provider2.emit("pending", message); +}; +let SessionExpiredError$4 = class SessionExpiredError extends WebrpcError$7 { + constructor(name2 = "SessionExpired", code2 = 1002, message = "Session expired", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, SessionExpiredError.prototype); } -} -class SocketEventSubscriber extends SocketSubscriber { - /** - * @_ignore: - */ - constructor(provider2, filter2) { - super(provider2, ["logs", filter2]); - __privateAdd(this, _logFilter); - __privateSet(this, _logFilter, JSON.stringify(filter2)); +}; +let AbortedError$3 = class AbortedError extends WebrpcError$7 { + constructor(name2 = "Aborted", code2 = 1005, message = "Request aborted", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, AbortedError.prototype); } - /** - * The filter. - */ - get logFilter() { - return JSON.parse(__privateGet(this, _logFilter)); +}; +let GeoblockedError$1 = class GeoblockedError extends WebrpcError$7 { + constructor(name2 = "Geoblocked", code2 = 1006, message = "Geoblocked region", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, GeoblockedError.prototype); } - async _emit(provider2, message) { - provider2.emit(this.logFilter, provider2._wrapLog(message, provider2._network)); +}; +let InvalidArgumentError$5 = class InvalidArgumentError extends WebrpcError$7 { + constructor(name2 = "InvalidArgument", code2 = 2e3, message = "Invalid argument", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, InvalidArgumentError.prototype); } -} -_logFilter = new WeakMap(); -class SocketProvider extends JsonRpcApiProvider { - /** - * Creates a new **SocketProvider** connected to %%network%%. - * - * If unspecified, the network will be discovered. - */ - constructor(network2, _options4) { - const options = Object.assign({}, _options4 != null ? _options4 : {}); - assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1, "sockets-based providers do not support batches", "options.batchMaxCount", _options4); - options.batchMaxCount = 1; - if (options.staticNetwork == null) { - options.staticNetwork = true; - } - super(network2, options); - __privateAdd(this, _callbacks); - // Maps each filterId to its subscriber - __privateAdd(this, _subs2); - // If any events come in before a subscriber has finished - // registering, queue them - __privateAdd(this, _pending); - __privateSet(this, _callbacks, /* @__PURE__ */ new Map()); - __privateSet(this, _subs2, /* @__PURE__ */ new Map()); - __privateSet(this, _pending, /* @__PURE__ */ new Map()); +}; +let UnavailableError$3 = class UnavailableError extends WebrpcError$7 { + constructor(name2 = "Unavailable", code2 = 2002, message = "Unavailable resource", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, UnavailableError.prototype); } - // This value is only valid after _start has been called - /* - get _network(): Network { - if (this.#network == null) { - throw new Error("this shouldn't happen"); - } - return this.#network.clone(); +}; +let QueryFailedError$5 = class QueryFailedError extends WebrpcError$7 { + constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, QueryFailedError.prototype); } - */ - _getSubscriber(sub) { - switch (sub.type) { - case "close": - return new UnmanagedSubscriber("close"); - case "block": - return new SocketBlockSubscriber(this); - case "pending": - return new SocketPendingSubscriber(this); - case "event": - return new SocketEventSubscriber(this, sub.filter); - case "orphan": - if (sub.filter.orphan === "drop-log") { - return new UnmanagedSubscriber("drop-log"); - } - } - return super._getSubscriber(sub); +}; +let NotFoundError$6 = class NotFoundError extends WebrpcError$7 { + constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, NotFoundError.prototype); } - /** - * Register a new subscriber. This is used internalled by Subscribers - * and generally is unecessary unless extending capabilities. - */ - _register(filterId, subscriber) { - __privateGet(this, _subs2).set(filterId, subscriber); - const pending = __privateGet(this, _pending).get(filterId); - if (pending) { - for (const message of pending) { - subscriber._handleMessage(message); +}; +let errors$3 = /* @__PURE__ */ function(errors2) { + errors2["WebrpcEndpoint"] = "WebrpcEndpoint"; + errors2["WebrpcRequestFailed"] = "WebrpcRequestFailed"; + errors2["WebrpcBadRoute"] = "WebrpcBadRoute"; + errors2["WebrpcBadMethod"] = "WebrpcBadMethod"; + errors2["WebrpcBadRequest"] = "WebrpcBadRequest"; + errors2["WebrpcBadResponse"] = "WebrpcBadResponse"; + errors2["WebrpcServerPanic"] = "WebrpcServerPanic"; + errors2["WebrpcInternalError"] = "WebrpcInternalError"; + errors2["WebrpcClientDisconnected"] = "WebrpcClientDisconnected"; + errors2["WebrpcStreamLost"] = "WebrpcStreamLost"; + errors2["WebrpcStreamFinished"] = "WebrpcStreamFinished"; + errors2["Unauthorized"] = "Unauthorized"; + errors2["PermissionDenied"] = "PermissionDenied"; + errors2["SessionExpired"] = "SessionExpired"; + errors2["Aborted"] = "Aborted"; + errors2["Geoblocked"] = "Geoblocked"; + errors2["InvalidArgument"] = "InvalidArgument"; + errors2["Unavailable"] = "Unavailable"; + errors2["QueryFailed"] = "QueryFailed"; + errors2["NotFound"] = "NotFound"; + return errors2; +}({}); +const webrpcErrorByCode$7 = { + [0]: WebrpcEndpointError$7, + [-1]: WebrpcRequestFailedError$7, + [-2]: WebrpcBadRouteError$7, + [-3]: WebrpcBadMethodError$7, + [-4]: WebrpcBadRequestError$7, + [-5]: WebrpcBadResponseError$7, + [-6]: WebrpcServerPanicError$7, + [-7]: WebrpcInternalErrorError$7, + [-8]: WebrpcClientDisconnectedError$7, + [-9]: WebrpcStreamLostError$7, + [-10]: WebrpcStreamFinishedError$7, + [1e3]: UnauthorizedError$6, + [1001]: PermissionDeniedError$4, + [1002]: SessionExpiredError$4, + [1005]: AbortedError$3, + [1006]: GeoblockedError$1, + [2e3]: InvalidArgumentError$5, + [2002]: UnavailableError$3, + [2003]: QueryFailedError$5, + [3e3]: NotFoundError$6 +}; +const fetch$6 = globalThis.fetch; +class SequenceAPIClient extends API { + constructor(hostname, projectAccessKey2, jwtAuth) { + super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, fetch$6); + this.projectAccessKey = projectAccessKey2; + this.jwtAuth = jwtAuth; + this._fetch = (input2, init2) => { + const headers = {}; + const jwtAuth2 = this.jwtAuth; + const projectAccessKey3 = this.projectAccessKey; + if (jwtAuth2 && jwtAuth2.length > 0) { + headers["Authorization"] = `BEARER ${jwtAuth2}`; } - __privateGet(this, _pending).delete(filterId); - } - } - async _send(payload) { - assertArgument(!Array.isArray(payload), "WebSocket does not support batch send", "payload", payload); - const promise = new Promise((resolve, reject) => { - __privateGet(this, _callbacks).set(payload.id, { payload, resolve, reject }); - }); - await this._waitUntilReady(); - await this._write(JSON.stringify(payload)); - return [await promise]; - } - // Sub-classes must call this once they are connected - /* - async _start(): Promise { - if (this.#ready) { return; } - - for (const { payload } of this.#callbacks.values()) { - await this._write(JSON.stringify(payload)); - } - - this.#ready = (async function() { - await super._start(); - })(); + if (projectAccessKey3 && projectAccessKey3.length > 0) { + headers["X-Access-Key"] = projectAccessKey3; } - */ - /** - * Sub-classes **must** call this with messages received over their - * transport to be processed and dispatched. - */ - async _processMessage(message) { - const result = JSON.parse(message); - if (result && typeof result === "object" && "id" in result) { - const callback = __privateGet(this, _callbacks).get(result.id); - if (callback == null) { - this.emit("error", makeError("received result for unknown id", "UNKNOWN_ERROR", { - reasonCode: "UNKNOWN_ID", - result - })); + init2.headers = _extends$f({}, init2.headers, headers); + return fetch$6(input2, init2); + }; + this.fetch = this._fetch; + } +} +const api$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + API, + AbortedError: AbortedError$3, + GeoblockedError: GeoblockedError$1, + InvalidArgumentError: InvalidArgumentError$5, + NotFoundError: NotFoundError$6, + PermissionDeniedError: PermissionDeniedError$4, + QueryFailedError: QueryFailedError$5, + SequenceAPIClient, + SessionExpiredError: SessionExpiredError$4, + SortOrder: SortOrder$2, + TokenType, + UnauthorizedError: UnauthorizedError$6, + UnavailableError: UnavailableError$3, + WebRPCSchemaHash: WebRPCSchemaHash$3, + WebRPCSchemaVersion: WebRPCSchemaVersion$3, + WebRPCVersion: WebRPCVersion$3, + WebrpcBadMethodError: WebrpcBadMethodError$7, + WebrpcBadRequestError: WebrpcBadRequestError$7, + WebrpcBadResponseError: WebrpcBadResponseError$7, + WebrpcBadRouteError: WebrpcBadRouteError$7, + WebrpcClientDisconnectedError: WebrpcClientDisconnectedError$7, + WebrpcEndpointError: WebrpcEndpointError$7, + WebrpcError: WebrpcError$7, + WebrpcInternalErrorError: WebrpcInternalErrorError$7, + WebrpcRequestFailedError: WebrpcRequestFailedError$7, + WebrpcServerPanicError: WebrpcServerPanicError$7, + WebrpcStreamFinishedError: WebrpcStreamFinishedError$7, + WebrpcStreamLostError: WebrpcStreamLostError$7, + errors: errors$3 +}, Symbol.toStringTag, { value: "Module" })); +const version$5 = "6.13.0"; +function checkType(value, type, name2) { + const types2 = type.split("|").map((t2) => t2.trim()); + for (let i = 0; i < types2.length; i++) { + switch (type) { + case "any": return; - } - __privateGet(this, _callbacks).delete(result.id); - callback.resolve(result); - } else if (result && result.method === "eth_subscription") { - const filterId = result.params.subscription; - const subscriber = __privateGet(this, _subs2).get(filterId); - if (subscriber) { - subscriber._handleMessage(result.params.result); - } else { - let pending = __privateGet(this, _pending).get(filterId); - if (pending == null) { - pending = []; - __privateGet(this, _pending).set(filterId, pending); + case "bigint": + case "boolean": + case "number": + case "string": + if (typeof value === type) { + return; } - pending.push(result.params.result); - } - } else { - this.emit("error", makeError("received unexpected message", "UNKNOWN_ERROR", { - reasonCode: "UNEXPECTED_MESSAGE", - result - })); - return; } } - /** - * Sub-classes **must** override this to send %%message%% over their - * transport. - */ - async _write(message) { - throw new Error("sub-classes must override this"); - } + const error = new Error(`invalid value for type ${type}`); + error.code = "INVALID_ARGUMENT"; + error.argument = `value.${name2}`; + error.value = value; + throw error; } -_callbacks = new WeakMap(); -_subs2 = new WeakMap(); -_pending = new WeakMap(); -class WebSocketProvider extends SocketProvider { - constructor(url, network2, options) { - super(network2, options); - __privateAdd(this, _connect2); - __privateAdd(this, _websocket); - if (typeof url === "string") { - __privateSet(this, _connect2, () => { - return new _WebSocket(url); - }); - __privateSet(this, _websocket, __privateGet(this, _connect2).call(this)); - } else if (typeof url === "function") { - __privateSet(this, _connect2, url); - __privateSet(this, _websocket, url()); - } else { - __privateSet(this, _connect2, null); - __privateSet(this, _websocket, url); +async function resolveProperties$1(value) { + const keys = Object.keys(value); + const results2 = await Promise.all(keys.map((k2) => Promise.resolve(value[k2]))); + return results2.reduce((accum, v3, index2) => { + accum[keys[index2]] = v3; + return accum; + }, {}); +} +function defineProperties$1(target, values, types2) { + for (let key in values) { + let value = values[key]; + const type = types2 ? types2[key] : null; + if (type) { + checkType(value, type, key); } - this.websocket.onopen = async () => { - try { - await this._start(); - this.resume(); - } catch (error) { - console.log("failed to start WebsocketProvider", error); - } - }; - this.websocket.onmessage = (message) => { - this._processMessage(message.data); - }; + Object.defineProperty(target, key, { enumerable: true, value, writable: false }); } - get websocket() { - if (__privateGet(this, _websocket) == null) { - throw new Error("websocket closed"); +} +function stringify$2(value) { + if (value == null) { + return "null"; + } + if (Array.isArray(value)) { + return "[ " + value.map(stringify$2).join(", ") + " ]"; + } + if (value instanceof Uint8Array) { + const HEX = "0123456789abcdef"; + let result = "0x"; + for (let i = 0; i < value.length; i++) { + result += HEX[value[i] >> 4]; + result += HEX[value[i] & 15]; } - return __privateGet(this, _websocket); + return result; } - async _write(message) { - this.websocket.send(message); + if (typeof value === "object" && typeof value.toJSON === "function") { + return stringify$2(value.toJSON()); } - async destroy() { - if (__privateGet(this, _websocket) != null) { - __privateGet(this, _websocket).close(); - __privateSet(this, _websocket, null); + switch (typeof value) { + case "boolean": + case "symbol": + return value.toString(); + case "bigint": + return BigInt(value).toString(); + case "number": + return value.toString(); + case "string": + return JSON.stringify(value); + case "object": { + const keys = Object.keys(value); + keys.sort(); + return "{ " + keys.map((k2) => `${stringify$2(k2)}: ${stringify$2(value[k2])}`).join(", ") + " }"; } - super.destroy(); } + return `[ COULD NOT SERIALIZE ]`; } -_connect2 = new WeakMap(); -_websocket = new WeakMap(); -const defaultProjectId = "84842078b09946638c03157f83405213"; -function getHost$2(name2) { - switch (name2) { - case "mainnet": - return "mainnet.infura.io"; - case "goerli": - return "goerli.infura.io"; - case "sepolia": - return "sepolia.infura.io"; - case "arbitrum": - return "arbitrum-mainnet.infura.io"; - case "arbitrum-goerli": - return "arbitrum-goerli.infura.io"; - case "arbitrum-sepolia": - return "arbitrum-sepolia.infura.io"; - case "base": - return "base-mainnet.infura.io"; - case "base-goerlia": - return "base-goerli.infura.io"; - case "base-sepolia": - return "base-sepolia.infura.io"; - case "bnb": - return "bnbsmartchain-mainnet.infura.io"; - case "bnbt": - return "bnbsmartchain-testnet.infura.io"; - case "linea": - return "linea-mainnet.infura.io"; - case "linea-goerli": - return "linea-goerli.infura.io"; - case "linea-sepolia": - return "linea-sepolia.infura.io"; - case "matic": - return "polygon-mainnet.infura.io"; - case "matic-amoy": - return "polygon-amoy.infura.io"; - case "matic-mumbai": - return "polygon-mumbai.infura.io"; - case "optimism": - return "optimism-mainnet.infura.io"; - case "optimism-goerli": - return "optimism-goerli.infura.io"; - case "optimism-sepolia": - return "optimism-sepolia.infura.io"; - } - assertArgument(false, "unsupported network", "network", name2); +function isError(error, code2) { + return error && error.code === code2; } -class InfuraWebSocketProvider extends WebSocketProvider { - /** - * Creates a new **InfuraWebSocketProvider**. - */ - constructor(network2, projectId) { - const provider2 = new InfuraProvider(network2, projectId); - const req = provider2._getConnection(); - assert(!req.credentials, "INFURA WebSocket project secrets unsupported", "UNSUPPORTED_OPERATION", { operation: "InfuraProvider.getWebSocketProvider()" }); - const url = req.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/"); - super(url, provider2._network); - /** - * The Project ID for the INFURA connection. - */ - __publicField(this, "projectId"); - /** - * The Project Secret. - * - * If null, no authenticated requests are made. This should not - * be used outside of private contexts. - */ - __publicField(this, "projectSecret"); - defineProperties$1(this, { - projectId: provider2.projectId, - projectSecret: provider2.projectSecret - }); - } - isCommunityResource() { - return this.projectId === defaultProjectId; - } +function isCallException(error) { + return isError(error, "CALL_EXCEPTION"); } -class InfuraProvider extends JsonRpcProvider$1 { - /** - * Creates a new **InfuraProvider**. - */ - constructor(_network3, projectId, projectSecret) { - if (_network3 == null) { - _network3 = "mainnet"; - } - const network2 = Network.from(_network3); - if (projectId == null) { - projectId = defaultProjectId; +function makeError(message, code2, info) { + let shortMessage = message; + { + const details = []; + if (info) { + if ("message" in info || "code" in info || "name" in info) { + throw new Error(`value will overwrite populated values: ${stringify$2(info)}`); + } + for (const key in info) { + if (key === "shortMessage") { + continue; + } + const value = info[key]; + details.push(key + "=" + stringify$2(value)); + } } - if (projectSecret == null) { - projectSecret = null; + details.push(`code=${code2}`); + details.push(`version=${version$5}`); + if (details.length) { + message += " (" + details.join(", ") + ")"; } - const request = InfuraProvider.getRequest(network2, projectId, projectSecret); - super(request, network2, { staticNetwork: network2 }); - /** - * The Project ID for the INFURA connection. - */ - __publicField(this, "projectId"); - /** - * The Project Secret. - * - * If null, no authenticated requests are made. This should not - * be used outside of private contexts. - */ - __publicField(this, "projectSecret"); - defineProperties$1(this, { projectId, projectSecret }); } - _getProvider(chainId) { - try { - return new InfuraProvider(chainId, this.projectId, this.projectSecret); - } catch (error) { - } - return super._getProvider(chainId); + let error; + switch (code2) { + case "INVALID_ARGUMENT": + error = new TypeError(message); + break; + case "NUMERIC_FAULT": + case "BUFFER_OVERRUN": + error = new RangeError(message); + break; + default: + error = new Error(message); } - isCommunityResource() { - return this.projectId === defaultProjectId; + defineProperties$1(error, { code: code2 }); + if (info) { + Object.assign(error, info); } - /** - * Creates a new **InfuraWebSocketProvider**. - */ - static getWebSocketProvider(network2, projectId) { - return new InfuraWebSocketProvider(network2, projectId); + if (error.shortMessage == null) { + defineProperties$1(error, { shortMessage }); } - /** - * Returns a prepared request for connecting to %%network%% - * with %%projectId%% and %%projectSecret%%. - */ - static getRequest(network2, projectId, projectSecret) { - if (projectId == null) { - projectId = defaultProjectId; - } - if (projectSecret == null) { - projectSecret = null; - } - const request = new FetchRequest(`https://${getHost$2(network2.name)}/v3/${projectId}`); - request.allowGzip = true; - if (projectSecret) { - request.setCredentials("", projectSecret); - } - if (projectId === defaultProjectId) { - request.retryFunc = async (request2, response, attempt) => { - showThrottleMessage("InfuraProvider"); - return true; - }; - } - return request; + return error; +} +function assert(check, message, code2, info) { + if (!check) { + throw makeError(message, code2, info); } } -const defaultToken = "919b412a057b5e9c9b6dce193c5a60242d6efadb"; -function getHost$1(name2) { - switch (name2) { - case "mainnet": - return "ethers.quiknode.pro"; - case "goerli": - return "ethers.ethereum-goerli.quiknode.pro"; - case "sepolia": - return "ethers.ethereum-sepolia.quiknode.pro"; - case "holesky": - return "ethers.ethereum-holesky.quiknode.pro"; - case "arbitrum": - return "ethers.arbitrum-mainnet.quiknode.pro"; - case "arbitrum-goerli": - return "ethers.arbitrum-goerli.quiknode.pro"; - case "arbitrum-sepolia": - return "ethers.arbitrum-sepolia.quiknode.pro"; - case "base": - return "ethers.base-mainnet.quiknode.pro"; - case "base-goerli": - return "ethers.base-goerli.quiknode.pro"; - case "base-spolia": - return "ethers.base-sepolia.quiknode.pro"; - case "bnb": - return "ethers.bsc.quiknode.pro"; - case "bnbt": - return "ethers.bsc-testnet.quiknode.pro"; - case "matic": - return "ethers.matic.quiknode.pro"; - case "matic-mumbai": - return "ethers.matic-testnet.quiknode.pro"; - case "optimism": - return "ethers.optimism.quiknode.pro"; - case "optimism-goerli": - return "ethers.optimism-goerli.quiknode.pro"; - case "optimism-sepolia": - return "ethers.optimism-sepolia.quiknode.pro"; - case "xdai": - return "ethers.xdai.quiknode.pro"; +function assertArgument(check, message, name2, value) { + assert(check, message, "INVALID_ARGUMENT", { argument: name2, value }); +} +function assertArgumentCount(count2, expectedCount, message) { + if (message == null) { + message = ""; } - assertArgument(false, "unsupported network", "network", name2); + if (message) { + message = ": " + message; + } + assert(count2 >= expectedCount, "missing arguemnt" + message, "MISSING_ARGUMENT", { + count: count2, + expectedCount + }); + assert(count2 <= expectedCount, "too many arguments" + message, "UNEXPECTED_ARGUMENT", { + count: count2, + expectedCount + }); } -class QuickNodeProvider extends JsonRpcProvider$1 { - /** - * Creates a new **QuickNodeProvider**. - */ - constructor(_network3, token) { - if (_network3 == null) { - _network3 = "mainnet"; +const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => { + try { + if ("test".normalize(form) !== "test") { + throw new Error("bad"); } - const network2 = Network.from(_network3); - if (token == null) { - token = defaultToken; + ; + if (form === "NFD") { + const check = String.fromCharCode(233).normalize("NFD"); + const expected = String.fromCharCode(101, 769); + if (check !== expected) { + throw new Error("broken"); + } } - const request = QuickNodeProvider.getRequest(network2, token); - super(request, network2, { staticNetwork: network2 }); - /** - * The API token. - */ - __publicField(this, "token"); - defineProperties$1(this, { token }); + accum.push(form); + } catch (error) { + } + return accum; +}, []); +function assertNormalize(form) { + assert(_normalizeForms.indexOf(form) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", { + operation: "String.prototype.normalize", + info: { form } + }); +} +function assertPrivate(givenGuard, guard2, className) { + if (className == null) { + className = ""; } - _getProvider(chainId) { - try { - return new QuickNodeProvider(chainId, this.token); - } catch (error) { + if (givenGuard !== guard2) { + let method = className, operation = "new"; + if (className) { + method += "."; + operation += " " + className; } - return super._getProvider(chainId); - } - isCommunityResource() { - return this.token === defaultToken; + assert(false, `private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", { + operation + }); } - /** - * Returns a new request prepared for %%network%% and the - * %%token%%. - */ - static getRequest(network2, token) { - if (token == null) { - token = defaultToken; +} +function _getBytes(value, name2, copy2) { + if (value instanceof Uint8Array) { + if (copy2) { + return new Uint8Array(value); } - const request = new FetchRequest(`https://${getHost$1(network2.name)}/${token}`); - request.allowGzip = true; - if (token === defaultToken) { - request.retryFunc = async (request2, response, attempt) => { - showThrottleMessage("QuickNodeProvider"); - return true; - }; + return value; + } + if (typeof value === "string" && value.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)) { + const result = new Uint8Array((value.length - 2) / 2); + let offset2 = 2; + for (let i = 0; i < result.length; i++) { + result[i] = parseInt(value.substring(offset2, offset2 + 2), 16); + offset2 += 2; } - return request; + return result; } + assertArgument(false, "invalid BytesLike value", name2 || "value", value); } -const BN_1 = BigInt("1"); -const BN_2 = BigInt("2"); -function shuffle(array) { - for (let i = array.length - 1; i > 0; i--) { - const j2 = Math.floor(Math.random() * (i + 1)); - const tmp = array[i]; - array[i] = array[j2]; - array[j2] = tmp; +function getBytes(value, name2) { + return _getBytes(value, name2, false); +} +function getBytesCopy(value, name2) { + return _getBytes(value, name2, true); +} +function isHexString(value, length) { + if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (typeof length === "number" && value.length !== 2 + 2 * length) { + return false; + } + if (length === true && value.length % 2 !== 0) { + return false; } + return true; } -function stall$2(duration) { - return new Promise((resolve) => { - setTimeout(resolve, duration); - }); +function isBytesLike(value) { + return isHexString(value, true) || value instanceof Uint8Array; } -function getTime() { - return (/* @__PURE__ */ new Date()).getTime(); +const HexCharacters = "0123456789abcdef"; +function hexlify(data) { + const bytes2 = getBytes(data); + let result = "0x"; + for (let i = 0; i < bytes2.length; i++) { + const v3 = bytes2[i]; + result += HexCharacters[(v3 & 240) >> 4] + HexCharacters[v3 & 15]; + } + return result; } -function stringify$2(value) { - return JSON.stringify(value, (key, value2) => { - if (typeof value2 === "bigint") { - return { type: "bigint", value: value2.toString() }; - } - return value2; - }); +function concat(datas) { + return "0x" + datas.map((d2) => hexlify(d2).substring(2)).join(""); } -const defaultConfig = { stallTimeout: 400, priority: 1, weight: 1 }; -const defaultState = { - blockNumber: -2, - requests: 0, - lateResponses: 0, - errorResponses: 0, - outOfSync: -1, - unsupportedEvents: 0, - rollingDuration: 0, - score: 0, - _network: null, - _updateNumber: null, - _totalTime: 0, - _lastFatalError: null, - _lastFatalErrorTimestamp: 0 -}; -async function waitForSync(config2, blockNumber) { - while (config2.blockNumber < 0 || config2.blockNumber < blockNumber) { - if (!config2._updateNumber) { - config2._updateNumber = (async () => { - try { - const blockNumber2 = await config2.provider.getBlockNumber(); - if (blockNumber2 > config2.blockNumber) { - config2.blockNumber = blockNumber2; - } - } catch (error) { - config2.blockNumber = -2; - config2._lastFatalError = error; - config2._lastFatalErrorTimestamp = getTime(); - } - config2._updateNumber = null; - })(); - } - await config2._updateNumber; - config2.outOfSync++; - if (config2._lastFatalError) { - break; - } +function dataLength(data) { + if (isHexString(data, true)) { + return (data.length - 2) / 2; } + return getBytes(data).length; } -function _normalize(value) { - if (value == null) { - return "null"; +function dataSlice(data, start, end) { + const bytes2 = getBytes(data); + if (end != null && end > bytes2.length) { + assert(false, "cannot slice beyond data bounds", "BUFFER_OVERRUN", { + buffer: bytes2, + length: bytes2.length, + offset: end + }); } - if (Array.isArray(value)) { - return "[" + value.map(_normalize).join(",") + "]"; + return hexlify(bytes2.slice(start == null ? 0 : start, end == null ? bytes2.length : end)); +} +function stripZerosLeft(data) { + let bytes2 = hexlify(data).substring(2); + while (bytes2.startsWith("00")) { + bytes2 = bytes2.substring(2); } - if (typeof value === "object" && typeof value.toJSON === "function") { - return _normalize(value.toJSON()); + return "0x" + bytes2; +} +function zeroPad(data, length, left) { + const bytes2 = getBytes(data); + assert(length >= bytes2.length, "padding exceeds data length", "BUFFER_OVERRUN", { + buffer: new Uint8Array(bytes2), + length, + offset: length + 1 + }); + const result = new Uint8Array(length); + result.fill(0); + if (left) { + result.set(bytes2, length - bytes2.length); + } else { + result.set(bytes2, 0); + } + return hexlify(result); +} +function zeroPadValue(data, length) { + return zeroPad(data, length, true); +} +function zeroPadBytes(data, length) { + return zeroPad(data, length, false); +} +const BN_0$a = BigInt(0); +const BN_1$5 = BigInt(1); +const maxValue = 9007199254740991; +function fromTwos(_value2, _width) { + const value = getUint(_value2, "value"); + const width = BigInt(getNumber(_width, "width")); + assert(value >> width === BN_0$a, "overflow", "NUMERIC_FAULT", { + operation: "fromTwos", + fault: "overflow", + value: _value2 + }); + if (value >> width - BN_1$5) { + const mask2 = (BN_1$5 << width) - BN_1$5; + return -((~value & mask2) + BN_1$5); + } + return value; +} +function toTwos(_value2, _width) { + let value = getBigInt(_value2, "value"); + const width = BigInt(getNumber(_width, "width")); + const limit = BN_1$5 << width - BN_1$5; + if (value < BN_0$a) { + value = -value; + assert(value <= limit, "too low", "NUMERIC_FAULT", { + operation: "toTwos", + fault: "overflow", + value: _value2 + }); + const mask2 = (BN_1$5 << width) - BN_1$5; + return (~value & mask2) + BN_1$5; + } else { + assert(value < limit, "too high", "NUMERIC_FAULT", { + operation: "toTwos", + fault: "overflow", + value: _value2 + }); } + return value; +} +function mask(_value2, _bits) { + const value = getUint(_value2, "value"); + const bits = BigInt(getNumber(_bits, "bits")); + return value & (BN_1$5 << bits) - BN_1$5; +} +function getBigInt(value, name2) { switch (typeof value) { - case "boolean": - case "symbol": - return value.toString(); case "bigint": + return value; case "number": - return BigInt(value).toString(); + assertArgument(Number.isInteger(value), "underflow", name2 || "value", value); + assertArgument(value >= -maxValue && value <= maxValue, "overflow", name2 || "value", value); + return BigInt(value); case "string": - return JSON.stringify(value); - case "object": { - const keys = Object.keys(value); - keys.sort(); - return "{" + keys.map((k2) => `${JSON.stringify(k2)}:${_normalize(value[k2])}`).join(",") + "}"; - } + try { + if (value === "") { + throw new Error("empty string"); + } + if (value[0] === "-" && value[1] !== "-") { + return -BigInt(value.substring(1)); + } + return BigInt(value); + } catch (e2) { + assertArgument(false, `invalid BigNumberish string: ${e2.message}`, name2 || "value", value); + } } - console.log("Could not serialize", value); - throw new Error("Hmm..."); + assertArgument(false, "invalid BigNumberish value", name2 || "value", value); } -function normalizeResult(value) { - if ("error" in value) { - const error = value.error; - return { tag: _normalize(error), value: error }; - } - const result = value.result; - return { tag: _normalize(result), value: result }; +function getUint(value, name2) { + const result = getBigInt(value, name2); + assert(result >= BN_0$a, "unsigned value cannot be negative", "NUMERIC_FAULT", { + fault: "overflow", + operation: "getUint", + value + }); + return result; } -function checkQuorum(quorum, results2) { - const tally = /* @__PURE__ */ new Map(); - for (const { value, tag, weight } of results2) { - const t2 = tally.get(tag) || { value, weight: 0 }; - t2.weight += weight; - tally.set(tag, t2); - } - let best = null; - for (const r2 of tally.values()) { - if (r2.weight >= quorum && (!best || r2.weight > best.weight)) { - best = r2; +const Nibbles$1 = "0123456789abcdef"; +function toBigInt(value) { + if (value instanceof Uint8Array) { + let result = "0x0"; + for (const v3 of value) { + result += Nibbles$1[v3 >> 4]; + result += Nibbles$1[v3 & 15]; } + return BigInt(result); } - if (best) { - return best.value; - } - return void 0; + return getBigInt(value); } -function getMedian(quorum, results2) { - let resultWeight = 0; - const errorMap = /* @__PURE__ */ new Map(); - let bestError = null; - const values = []; - for (const { value, tag, weight } of results2) { - if (value instanceof Error) { - const e2 = errorMap.get(tag) || { value, weight: 0 }; - e2.weight += weight; - errorMap.set(tag, e2); - if (bestError == null || e2.weight > bestError.weight) { - bestError = e2; +function getNumber(value, name2) { + switch (typeof value) { + case "bigint": + assertArgument(value >= -maxValue && value <= maxValue, "overflow", name2 || "value", value); + return Number(value); + case "number": + assertArgument(Number.isInteger(value), "underflow", name2 || "value", value); + assertArgument(value >= -maxValue && value <= maxValue, "overflow", name2 || "value", value); + return value; + case "string": + try { + if (value === "") { + throw new Error("empty string"); + } + return getNumber(BigInt(value), name2); + } catch (e2) { + assertArgument(false, `invalid numeric string: ${e2.message}`, name2 || "value", value); } - } else { - values.push(BigInt(value)); - resultWeight += weight; - } } - if (resultWeight < quorum) { - if (bestError && bestError.weight >= quorum) { - return bestError.value; + assertArgument(false, "invalid numeric value", name2 || "value", value); +} +function toNumber(value) { + return getNumber(toBigInt(value)); +} +function toBeHex(_value2, _width) { + const value = getUint(_value2, "value"); + let result = value.toString(16); + if (_width == null) { + if (result.length % 2) { + result = "0" + result; + } + } else { + const width = getNumber(_width, "width"); + assert(width * 2 >= result.length, `value exceeds width (${width} bytes)`, "NUMERIC_FAULT", { + operation: "toBeHex", + fault: "overflow", + value: _value2 + }); + while (result.length < width * 2) { + result = "0" + result; } - return void 0; - } - values.sort((a2, b2) => a2 < b2 ? -1 : b2 > a2 ? 1 : 0); - const mid = Math.floor(values.length / 2); - if (values.length % 2) { - return values[mid]; } - return (values[mid - 1] + values[mid] + BN_1) / BN_2; + return "0x" + result; } -function getAnyResult(quorum, results2) { - const result = checkQuorum(quorum, results2); - if (result !== void 0) { - return result; +function toBeArray(_value2) { + const value = getUint(_value2, "value"); + if (value === BN_0$a) { + return new Uint8Array([]); } - for (const r2 of results2) { - if (r2.value) { - return r2.value; - } + let hex2 = value.toString(16); + if (hex2.length % 2) { + hex2 = "0" + hex2; } - return void 0; + const result = new Uint8Array(hex2.length / 2); + for (let i = 0; i < result.length; i++) { + const offset2 = i * 2; + result[i] = parseInt(hex2.substring(offset2, offset2 + 2), 16); + } + return result; } -function getFuzzyMode(quorum, results2) { - if (quorum === 1) { - return getNumber(getMedian(quorum, results2), "%internal"); +function toQuantity(value) { + let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2); + while (result.startsWith("0")) { + result = result.substring(1); } - const tally = /* @__PURE__ */ new Map(); - const add2 = (result, weight) => { - const t2 = tally.get(result) || { result, weight: 0 }; - t2.weight += weight; - tally.set(result, t2); - }; - for (const { weight, value } of results2) { - const r2 = getNumber(value); - add2(r2 - 1, weight); - add2(r2, weight); - add2(r2 + 1, weight); + if (result === "") { + result = "0"; } - let bestWeight = 0; - let bestResult = void 0; - for (const { weight, result } of tally.values()) { - if (weight >= quorum && (weight > bestWeight || bestResult != null && weight === bestWeight && result > bestResult)) { - bestWeight = weight; - bestResult = result; + return "0x" + result; +} +const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; +let Lookup = null; +function getAlpha(letter) { + if (Lookup == null) { + Lookup = {}; + for (let i = 0; i < Alphabet.length; i++) { + Lookup[Alphabet[i]] = BigInt(i); } } - return bestResult; + const result = Lookup[letter]; + assertArgument(result != null, `invalid base58 value`, "letter", letter); + return result; } -class FallbackProvider extends AbstractProvider { - /** - * Creates a new **FallbackProvider** with %%providers%% connected to - * %%network%%. - * - * If a [[Provider]] is included in %%providers%%, defaults are used - * for the configuration. - */ - constructor(providers, network2, options) { - super(network2, options); - __privateAdd(this, _FallbackProvider_instances); - /** - * The number of backends that must agree on a value before it is - * accpeted. - */ - __publicField(this, "quorum"); - /** - * @_ignore: - */ - __publicField(this, "eventQuorum"); - /** - * @_ignore: - */ - __publicField(this, "eventWorkers"); - __privateAdd(this, _configs); - __privateAdd(this, _height); - __privateAdd(this, _initialSyncPromise); - __privateSet(this, _configs, providers.map((p2) => { - if (p2 instanceof AbstractProvider) { - return Object.assign({ provider: p2 }, defaultConfig, defaultState); - } else { - return Object.assign({}, defaultConfig, p2, defaultState); - } - })); - __privateSet(this, _height, -2); - __privateSet(this, _initialSyncPromise, null); - if (options && options.quorum != null) { - this.quorum = options.quorum; - } else { - this.quorum = Math.ceil(__privateGet(this, _configs).reduce((accum, config2) => { - accum += config2.weight; - return accum; - }, 0) / 2); +const BN_0$9 = BigInt(0); +const BN_58 = BigInt(58); +function encodeBase58(_value2) { + const bytes2 = getBytes(_value2); + let value = toBigInt(bytes2); + let result = ""; + while (value) { + result = Alphabet[Number(value % BN_58)] + result; + value /= BN_58; + } + for (let i = 0; i < bytes2.length; i++) { + if (bytes2[i]) { + break; } - this.eventQuorum = 1; - this.eventWorkers = 1; - assertArgument(this.quorum <= __privateGet(this, _configs).reduce((a2, c2) => a2 + c2.weight, 0), "quorum exceed provider weight", "quorum", this.quorum); + result = Alphabet[0] + result; } - get providerConfigs() { - return __privateGet(this, _configs).map((c2) => { - const result = Object.assign({}, c2); - for (const key in result) { - if (key[0] === "_") { - delete result[key]; - } - } - return result; - }); + return result; +} +function decodeBase58(value) { + let result = BN_0$9; + for (let i = 0; i < value.length; i++) { + result *= BN_58; + result += getAlpha(value[i]); + } + return result; +} +function decodeBase64(textData) { + textData = atob(textData); + const data = new Uint8Array(textData.length); + for (let i = 0; i < textData.length; i++) { + data[i] = textData.charCodeAt(i); + } + return getBytes(data); +} +function encodeBase64(_data6) { + const data = getBytes(_data6); + let textData = ""; + for (let i = 0; i < data.length; i++) { + textData += String.fromCharCode(data[i]); } - async _detectNetwork() { - return Network.from(getBigInt(await this._perform({ method: "chainId" }))); + return btoa(textData); +} +class EventPayload { + /** + * Create a new **EventPayload** for %%emitter%% with + * the %%listener%% and for %%filter%%. + */ + constructor(emitter, listener, filter2) { + /** + * The event filter. + */ + __publicField(this, "filter"); + /** + * The **EventEmitterable**. + */ + __publicField(this, "emitter"); + __privateAdd(this, _listener); + __privateSet(this, _listener, listener); + defineProperties$1(this, { emitter, filter: filter2 }); } - // @TODO: Add support to select providers to be the event subscriber - //_getSubscriber(sub: Subscription): Subscriber { - // throw new Error("@TODO"); - //} /** - * Transforms a %%req%% into the correct method call on %%provider%%. + * Unregister the triggered listener for future events. */ - async _translatePerform(provider2, req) { - switch (req.method) { - case "broadcastTransaction": - return await provider2.broadcastTransaction(req.signedTransaction); - case "call": - return await provider2.call(Object.assign({}, req.transaction, { blockTag: req.blockTag })); - case "chainId": - return (await provider2.getNetwork()).chainId; - case "estimateGas": - return await provider2.estimateGas(req.transaction); - case "getBalance": - return await provider2.getBalance(req.address, req.blockTag); - case "getBlock": { - const block = "blockHash" in req ? req.blockHash : req.blockTag; - return await provider2.getBlock(block, req.includeTransactions); - } - case "getBlockNumber": - return await provider2.getBlockNumber(); - case "getCode": - return await provider2.getCode(req.address, req.blockTag); - case "getGasPrice": - return (await provider2.getFeeData()).gasPrice; - case "getPriorityFee": - return (await provider2.getFeeData()).maxPriorityFeePerGas; - case "getLogs": - return await provider2.getLogs(req.filter); - case "getStorage": - return await provider2.getStorage(req.address, req.position, req.blockTag); - case "getTransaction": - return await provider2.getTransaction(req.hash); - case "getTransactionCount": - return await provider2.getTransactionCount(req.address, req.blockTag); - case "getTransactionReceipt": - return await provider2.getTransactionReceipt(req.hash); - case "getTransactionResult": - return await provider2.getTransactionResult(req.hash); + async removeListener() { + if (__privateGet(this, _listener) == null) { + return; } + await this.emitter.off(this.filter, __privateGet(this, _listener)); } - async _perform(req) { - if (req.method === "broadcastTransaction") { - const results2 = __privateGet(this, _configs).map((c2) => null); - const broadcasts = __privateGet(this, _configs).map(async ({ provider: provider2, weight }, index2) => { - try { - const result3 = await provider2._perform(req); - results2[index2] = Object.assign(normalizeResult({ result: result3 }), { weight }); - } catch (error) { - results2[index2] = Object.assign(normalizeResult({ error }), { weight }); - } - }); - while (true) { - const done = results2.filter((r2) => r2 != null); - for (const { value } of done) { - if (!(value instanceof Error)) { - return value; - } - } - const result3 = checkQuorum(this.quorum, results2.filter((r2) => r2 != null)); - if (isError(result3, "INSUFFICIENT_FUNDS")) { - throw result3; - } - const waiting = broadcasts.filter((b2, i) => results2[i] == null); - if (waiting.length === 0) { - break; - } - await Promise.race(waiting); - } - const result2 = getAnyResult(this.quorum, results2); - assert(result2 !== void 0, "problem multi-broadcasting", "SERVER_ERROR", { - request: "%sub-requests", - info: { request: req, results: results2.map(stringify$2) } - }); - if (result2 instanceof Error) { - throw result2; +} +_listener = new WeakMap(); +function errorFunc(reason, offset2, bytes2, output2, badCodepoint) { + assertArgument(false, `invalid codepoint at offset ${offset2}; ${reason}`, "bytes", bytes2); +} +function ignoreFunc(reason, offset2, bytes2, output2, badCodepoint) { + if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") { + let i = 0; + for (let o2 = offset2 + 1; o2 < bytes2.length; o2++) { + if (bytes2[o2] >> 6 !== 2) { + break; } - return result2; + i++; } - await __privateMethod(this, _FallbackProvider_instances, initialSync_fn).call(this); - const running = /* @__PURE__ */ new Set(); - let inflightQuorum = 0; - while (true) { - const runner = __privateMethod(this, _FallbackProvider_instances, addRunner_fn).call(this, running, req); - if (runner == null) { - break; + return i; + } + if (reason === "OVERRUN") { + return bytes2.length - offset2 - 1; + } + return 0; +} +function replaceFunc(reason, offset2, bytes2, output2, badCodepoint) { + if (reason === "OVERLONG") { + assertArgument(typeof badCodepoint === "number", "invalid bad code point for replacement", "badCodepoint", badCodepoint); + output2.push(badCodepoint); + return 0; + } + output2.push(65533); + return ignoreFunc(reason, offset2, bytes2); +} +const Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +function getUtf8CodePoints(_bytes, onError) { + if (onError == null) { + onError = Utf8ErrorFuncs.error; + } + const bytes2 = getBytes(_bytes, "bytes"); + const result = []; + let i = 0; + while (i < bytes2.length) { + const c2 = bytes2[i++]; + if (c2 >> 7 === 0) { + result.push(c2); + continue; + } + let extraLength = null; + let overlongMask = null; + if ((c2 & 224) === 192) { + extraLength = 1; + overlongMask = 127; + } else if ((c2 & 240) === 224) { + extraLength = 2; + overlongMask = 2047; + } else if ((c2 & 248) === 240) { + extraLength = 3; + overlongMask = 65535; + } else { + if ((c2 & 192) === 128) { + i += onError("UNEXPECTED_CONTINUE", i - 1, bytes2, result); + } else { + i += onError("BAD_PREFIX", i - 1, bytes2, result); } - inflightQuorum += runner.config.weight; - if (inflightQuorum >= this.quorum) { + continue; + } + if (i - 1 + extraLength >= bytes2.length) { + i += onError("OVERRUN", i - 1, bytes2, result); + continue; + } + let res = c2 & (1 << 8 - extraLength - 1) - 1; + for (let j2 = 0; j2 < extraLength; j2++) { + let nextChar = bytes2[i]; + if ((nextChar & 192) != 128) { + i += onError("MISSING_CONTINUE", i, bytes2, result); + res = null; break; } + res = res << 6 | nextChar & 63; + i++; } - const result = await __privateMethod(this, _FallbackProvider_instances, waitForQuorum_fn).call(this, running, req); - for (const runner of running) { - if (runner.perform && runner.result == null) { - runner.config.lateResponses++; - } + if (res === null) { + continue; } - return result; - } - async destroy() { - for (const { provider: provider2 } of __privateGet(this, _configs)) { - provider2.destroy(); + if (res > 1114111) { + i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes2, result, res); + continue; } - super.destroy(); - } -} -_configs = new WeakMap(); -_height = new WeakMap(); -_initialSyncPromise = new WeakMap(); -_FallbackProvider_instances = new WeakSet(); -// Grab the next (random) config that is not already part of -// the running set -getNextConfig_fn = function(running) { - const configs = Array.from(running).map((r2) => r2.config); - const allConfigs = __privateGet(this, _configs).slice(); - shuffle(allConfigs); - allConfigs.sort((a2, b2) => a2.priority - b2.priority); - for (const config2 of allConfigs) { - if (config2._lastFatalError) { + if (res >= 55296 && res <= 57343) { + i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes2, result, res); continue; } - if (configs.indexOf(config2) === -1) { - return config2; + if (res <= overlongMask) { + i += onError("OVERLONG", i - 1 - extraLength, bytes2, result, res); + continue; } + result.push(res); } - return null; -}; -// Adds a new runner (if available) to running. -addRunner_fn = function(running, req) { - const config2 = __privateMethod(this, _FallbackProvider_instances, getNextConfig_fn).call(this, running); - if (config2 == null) { - return null; + return result; +} +function toUtf8Bytes(str, form) { + assertArgument(typeof str === "string", "invalid string value", "str", str); + if (form != null) { + assertNormalize(form); + str = str.normalize(form); } - const runner = { - config: config2, - result: null, - didBump: false, - perform: null, - staller: null - }; - const now = getTime(); - runner.perform = (async () => { - try { - config2.requests++; - const result = await this._translatePerform(config2.provider, req); - runner.result = { result }; - } catch (error) { - config2.errorResponses++; - runner.result = { error }; + let result = []; + for (let i = 0; i < str.length; i++) { + const c2 = str.charCodeAt(i); + if (c2 < 128) { + result.push(c2); + } else if (c2 < 2048) { + result.push(c2 >> 6 | 192); + result.push(c2 & 63 | 128); + } else if ((c2 & 64512) == 55296) { + i++; + const c22 = str.charCodeAt(i); + assertArgument(i < str.length && (c22 & 64512) === 56320, "invalid surrogate pair", "str", str); + const pair = 65536 + ((c2 & 1023) << 10) + (c22 & 1023); + result.push(pair >> 18 | 240); + result.push(pair >> 12 & 63 | 128); + result.push(pair >> 6 & 63 | 128); + result.push(pair & 63 | 128); + } else { + result.push(c2 >> 12 | 224); + result.push(c2 >> 6 & 63 | 128); + result.push(c2 & 63 | 128); } - const dt = getTime() - now; - config2._totalTime += dt; - config2.rollingDuration = 0.95 * config2.rollingDuration + 0.05 * dt; - runner.perform = null; - })(); - runner.staller = (async () => { - await stall$2(config2.stallTimeout); - runner.staller = null; - })(); - running.add(runner); - return runner; -}; -initialSync_fn = async function() { - let initialSync = __privateGet(this, _initialSyncPromise); - if (!initialSync) { - const promises = []; - __privateGet(this, _configs).forEach((config2) => { - promises.push((async () => { - await waitForSync(config2, 0); - if (!config2._lastFatalError) { - config2._network = await config2.provider.getNetwork(); - } - })()); + } + return new Uint8Array(result); +} +function _toUtf8String(codePoints) { + return codePoints.map((codePoint) => { + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + codePoint -= 65536; + return String.fromCharCode((codePoint >> 10 & 1023) + 55296, (codePoint & 1023) + 56320); + }).join(""); +} +function toUtf8String(bytes2, onError) { + return _toUtf8String(getUtf8CodePoints(bytes2, onError)); +} +function toUtf8CodePoints(str, form) { + return getUtf8CodePoints(toUtf8Bytes(str, form)); +} +function createGetUrl(options) { + async function getUrl2(req, _signal2) { + assert(_signal2 == null || !_signal2.cancelled, "request cancelled before sending", "CANCELLED"); + const protocol = req.url.split(":")[0].toLowerCase(); + assert(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { + info: { protocol }, + operation: "request" }); - __privateSet(this, _initialSyncPromise, initialSync = (async () => { - await Promise.all(promises); - let chainId = null; - for (const config2 of __privateGet(this, _configs)) { - if (config2._lastFatalError) { - continue; - } - const network2 = config2._network; - if (chainId == null) { - chainId = network2.chainId; - } else if (network2.chainId !== chainId) { - assert(false, "cannot mix providers on different networks", "UNSUPPORTED_OPERATION", { - operation: "new FallbackProvider" - }); - } + assert(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { + operation: "request" + }); + let error = null; + const controller = new AbortController(); + const timer = setTimeout(() => { + error = makeError("request timeout", "TIMEOUT"); + controller.abort(); + }, req.timeout); + if (_signal2) { + _signal2.addListener(() => { + error = makeError("request cancelled", "CANCELLED"); + controller.abort(); + }); + } + const init2 = { + method: req.method, + headers: new Headers(Array.from(req)), + body: req.body || void 0, + signal: controller.signal + }; + let resp; + try { + resp = await fetch(req.url, init2); + } catch (_error2) { + clearTimeout(timer); + if (error) { + throw error; } - })()); - } - await initialSync; -}; -checkQuorum_fn = async function(running, req) { - const results2 = []; - for (const runner of running) { - if (runner.result != null) { - const { tag, value } = normalizeResult(runner.result); - results2.push({ tag, value, weight: runner.config.weight }); + throw _error2; } + clearTimeout(timer); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = await resp.arrayBuffer(); + const body = respBody == null ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, + body + }; } - if (results2.reduce((a2, r2) => a2 + r2.weight, 0) < this.quorum) { - return void 0; + return getUrl2; +} +const MAX_ATTEMPTS = 12; +const SLOT_INTERVAL = 250; +let defaultGetUrlFunc = createGetUrl(); +const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); +const reIpfs = new RegExp("^ipfs://(ipfs/)?(.*)$", "i"); +let locked$5 = false; +async function dataGatewayFunc(url, signal) { + try { + const match = url.match(reData); + if (!match) { + throw new Error("invalid data"); + } + return new FetchResponse(200, "OK", { + "content-type": match[1] || "text/plain" + }, match[2] ? decodeBase64(match[3]) : unpercent(match[3])); + } catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url)); } - switch (req.method) { - case "getBlockNumber": { - if (__privateGet(this, _height) === -2) { - __privateSet(this, _height, Math.ceil(getNumber(getMedian(this.quorum, __privateGet(this, _configs).filter((c2) => !c2._lastFatalError).map((c2) => ({ - value: c2.blockNumber, - tag: getNumber(c2.blockNumber).toString(), - weight: c2.weight - })))))); - } - const mode = getFuzzyMode(this.quorum, results2); - if (mode === void 0) { - return void 0; - } - if (mode > __privateGet(this, _height)) { - __privateSet(this, _height, mode); +} +function getIpfsGatewayFunc(baseUrl) { + async function gatewayIpfs(url, signal) { + try { + const match = url.match(reIpfs); + if (!match) { + throw new Error("invalid link"); } - return __privateGet(this, _height); + return new FetchRequest(`${baseUrl}${match[2]}`); + } catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url)); } - case "getGasPrice": - case "getPriorityFee": - case "estimateGas": - return getMedian(this.quorum, results2); - case "getBlock": - if ("blockTag" in req && req.blockTag === "pending") { - return getAnyResult(this.quorum, results2); - } - return checkQuorum(this.quorum, results2); - case "call": - case "chainId": - case "getBalance": - case "getTransactionCount": - case "getCode": - case "getStorage": - case "getTransaction": - case "getTransactionReceipt": - case "getLogs": - return checkQuorum(this.quorum, results2); - case "broadcastTransaction": - return getAnyResult(this.quorum, results2); } - assert(false, "unsupported method", "UNSUPPORTED_OPERATION", { - operation: `_perform(${stringify$2(req.method)})` - }); + return gatewayIpfs; +} +const Gateways = { + "data": dataGatewayFunc, + "ipfs": getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/") }; -waitForQuorum_fn = async function(running, req) { - if (running.size === 0) { - throw new Error("no runners?!"); - } - const interesting = []; - let newRunners = 0; - for (const runner of running) { - if (runner.perform) { - interesting.push(runner.perform); - } - if (runner.staller) { - interesting.push(runner.staller); - continue; - } - if (runner.didBump) { - continue; - } - runner.didBump = true; - newRunners++; +const fetchSignals = /* @__PURE__ */ new WeakMap(); +class FetchCancelSignal { + constructor(request) { + __privateAdd(this, _listeners); + __privateAdd(this, _cancelled); + __privateSet(this, _listeners, []); + __privateSet(this, _cancelled, false); + fetchSignals.set(request, () => { + if (__privateGet(this, _cancelled)) { + return; + } + __privateSet(this, _cancelled, true); + for (const listener of __privateGet(this, _listeners)) { + setTimeout(() => { + listener(); + }, 0); + } + __privateSet(this, _listeners, []); + }); } - const value = await __privateMethod(this, _FallbackProvider_instances, checkQuorum_fn).call(this, running, req); - if (value !== void 0) { - if (value instanceof Error) { - throw value; - } - return value; + addListener(listener) { + assert(!__privateGet(this, _cancelled), "singal already cancelled", "UNSUPPORTED_OPERATION", { + operation: "fetchCancelSignal.addCancelListener" + }); + __privateGet(this, _listeners).push(listener); } - for (let i = 0; i < newRunners; i++) { - __privateMethod(this, _FallbackProvider_instances, addRunner_fn).call(this, running, req); + get cancelled() { + return __privateGet(this, _cancelled); + } + checkSignal() { + assert(!this.cancelled, "cancelled", "CANCELLED", {}); } - assert(interesting.length > 0, "quorum not met", "SERVER_ERROR", { - request: "%sub-requests", - info: { request: req, results: Array.from(running).map((r2) => stringify$2(r2.result)) } - }); - await Promise.race(interesting); - return await __privateMethod(this, _FallbackProvider_instances, waitForQuorum_fn).call(this, running, req); -}; -function isWebSocketLike(value) { - return value && typeof value.send === "function" && typeof value.close === "function"; } -const Testnets = "goerli kovan sepolia classicKotti optimism-goerli arbitrum-goerli matic-mumbai bnbt".split(" "); -function getDefaultProvider(network2, options) { - if (options == null) { - options = {}; +_listeners = new WeakMap(); +_cancelled = new WeakMap(); +function checkSignal(signal) { + if (signal == null) { + throw new Error("missing signal; should not happen"); } - const allowService = (name2) => { - if (options[name2] === "-") { - return false; - } - if (typeof options.exclusive === "string") { - return name2 === options.exclusive; - } - if (Array.isArray(options.exclusive)) { - return options.exclusive.indexOf(name2) !== -1; - } - return true; - }; - if (typeof network2 === "string" && network2.match(/^https?:/)) { - return new JsonRpcProvider$1(network2); + signal.checkSignal(); + return signal; +} +const _FetchRequest = class _FetchRequest { + /** + * Create a new FetchRequest instance with default values. + * + * Once created, each property may be set before issuing a + * ``.send()`` to make the request. + */ + constructor(url) { + __privateAdd(this, _FetchRequest_instances); + __privateAdd(this, _allowInsecure); + __privateAdd(this, _gzip); + __privateAdd(this, _headers); + __privateAdd(this, _method); + __privateAdd(this, _timeout); + __privateAdd(this, _url); + __privateAdd(this, _body); + __privateAdd(this, _bodyType); + __privateAdd(this, _creds); + // Hooks + __privateAdd(this, _preflight); + __privateAdd(this, _process); + __privateAdd(this, _retry); + __privateAdd(this, _signal); + __privateAdd(this, _throttle); + __privateAdd(this, _getUrlFunc); + __privateSet(this, _url, String(url)); + __privateSet(this, _allowInsecure, false); + __privateSet(this, _gzip, true); + __privateSet(this, _headers, {}); + __privateSet(this, _method, ""); + __privateSet(this, _timeout, 3e5); + __privateSet(this, _throttle, { + slotInterval: SLOT_INTERVAL, + maxAttempts: MAX_ATTEMPTS + }); + __privateSet(this, _getUrlFunc, null); } - if (typeof network2 === "string" && network2.match(/^wss?:/) || isWebSocketLike(network2)) { - return new WebSocketProvider(network2); + /** + * The fetch URL to request. + */ + get url() { + return __privateGet(this, _url); } - let staticNetwork = null; - try { - staticNetwork = Network.from(network2); - } catch (error) { + set url(url) { + __privateSet(this, _url, String(url)); } - const providers = []; - if (allowService("publicPolygon") && staticNetwork) { - if (staticNetwork.name === "matic") { - providers.push(new JsonRpcProvider$1("https://polygon-rpc.com/", staticNetwork, { staticNetwork })); - } else if (staticNetwork.name === "matic-amoy") { - providers.push(new JsonRpcProvider$1("https://rpc-amoy.polygon.technology/", staticNetwork, { staticNetwork })); + /** + * The fetch body, if any, to send as the request body. //(default: null)// + * + * When setting a body, the intrinsic ``Content-Type`` is automatically + * set and will be used if **not overridden** by setting a custom + * header. + * + * If %%body%% is null, the body is cleared (along with the + * intrinsic ``Content-Type``). + * + * If %%body%% is a string, the intrinsic ``Content-Type`` is set to + * ``text/plain``. + * + * If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to + * ``application/octet-stream``. + * + * If %%body%% is any other object, the intrinsic ``Content-Type`` is + * set to ``application/json``. + */ + get body() { + if (__privateGet(this, _body) == null) { + return null; } + return new Uint8Array(__privateGet(this, _body)); } - if (allowService("alchemy")) { - try { - providers.push(new AlchemyProvider(network2, options.alchemy)); - } catch (error) { + set body(body) { + if (body == null) { + __privateSet(this, _body, void 0); + __privateSet(this, _bodyType, void 0); + } else if (typeof body === "string") { + __privateSet(this, _body, toUtf8Bytes(body)); + __privateSet(this, _bodyType, "text/plain"); + } else if (body instanceof Uint8Array) { + __privateSet(this, _body, body); + __privateSet(this, _bodyType, "application/octet-stream"); + } else if (typeof body === "object") { + __privateSet(this, _body, toUtf8Bytes(JSON.stringify(body))); + __privateSet(this, _bodyType, "application/json"); + } else { + throw new Error("invalid body"); } } - if (allowService("ankr") && options.ankr != null) { - try { - providers.push(new AnkrProvider(network2, options.ankr)); - } catch (error) { - } + /** + * Returns true if the request has a body. + */ + hasBody() { + return __privateGet(this, _body) != null; } - if (allowService("chainstack")) { - try { - providers.push(new ChainstackProvider(network2, options.chainstack)); - } catch (error) { + /** + * The HTTP method to use when requesting the URI. If no method + * has been explicitly set, then ``GET`` is used if the body is + * null and ``POST`` otherwise. + */ + get method() { + if (__privateGet(this, _method)) { + return __privateGet(this, _method); } - } - if (allowService("cloudflare")) { - try { - providers.push(new CloudflareProvider(network2)); - } catch (error) { + if (this.hasBody()) { + return "POST"; } + return "GET"; } - if (allowService("etherscan")) { - try { - providers.push(new EtherscanProvider(network2, options.etherscan)); - } catch (error) { + set method(method) { + if (method == null) { + method = ""; } + __privateSet(this, _method, String(method).toUpperCase()); } - if (allowService("infura")) { - try { - let projectId = options.infura; - let projectSecret = void 0; - if (typeof projectId === "object") { - projectSecret = projectId.projectSecret; - projectId = projectId.projectId; - } - providers.push(new InfuraProvider(network2, projectId, projectSecret)); - } catch (error) { + /** + * The headers that will be used when requesting the URI. All + * keys are lower-case. + * + * This object is a copy, so any changes will **NOT** be reflected + * in the ``FetchRequest``. + * + * To set a header entry, use the ``setHeader`` method. + */ + get headers() { + const headers = Object.assign({}, __privateGet(this, _headers)); + if (__privateGet(this, _creds)) { + headers["authorization"] = `Basic ${encodeBase64(toUtf8Bytes(__privateGet(this, _creds)))}`; } - } - if (allowService("quicknode")) { - try { - let token = options.quicknode; - providers.push(new QuickNodeProvider(network2, token)); - } catch (error) { + if (this.allowGzip) { + headers["accept-encoding"] = "gzip"; + } + if (headers["content-type"] == null && __privateGet(this, _bodyType)) { + headers["content-type"] = __privateGet(this, _bodyType); + } + if (this.body) { + headers["content-length"] = String(this.body.length); } + return headers; } - assert(providers.length, "unsupported default network", "UNSUPPORTED_OPERATION", { - operation: "getDefaultProvider" - }); - if (providers.length === 1) { - return providers[0]; + /** + * Get the header for %%key%%, ignoring case. + */ + getHeader(key) { + return this.headers[key.toLowerCase()]; } - let quorum = Math.floor(providers.length / 2); - if (quorum > 2) { - quorum = 2; + /** + * Set the header for %%key%% to %%value%%. All values are coerced + * to a string. + */ + setHeader(key, value) { + __privateGet(this, _headers)[String(key).toLowerCase()] = String(value); } - if (staticNetwork && Testnets.indexOf(staticNetwork.name) !== -1) { - quorum = 1; + /** + * Clear all headers, resetting all intrinsic headers. + */ + clearHeaders() { + __privateSet(this, _headers, {}); } - if (options && options.quorum) { - quorum = options.quorum; + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index2 = 0; + return { + next: () => { + if (index2 < keys.length) { + const key = keys[index2++]; + return { + value: [key, headers[key]], + done: false + }; + } + return { value: void 0, done: true }; + } + }; } - return new FallbackProvider(providers, void 0, { quorum }); -} -const _NonceManager = class _NonceManager extends AbstractSigner { /** - * Creates a new **NonceManager** to manage %%signer%%. + * The value that will be sent for the ``Authorization`` header. + * + * To set the credentials, use the ``setCredentials`` method. */ - constructor(signer2) { - super(signer2.provider); - /** - * The Signer being managed. - */ - __publicField(this, "signer"); - __privateAdd(this, _noncePromise); - __privateAdd(this, _delta); - defineProperties$1(this, { signer: signer2 }); - __privateSet(this, _noncePromise, null); - __privateSet(this, _delta, 0); + get credentials() { + return __privateGet(this, _creds) || null; } - async getAddress() { - return this.signer.getAddress(); + /** + * Sets an ``Authorization`` for %%username%% with %%password%%. + */ + setCredentials(username, password) { + assertArgument(!username.match(/:/), "invalid basic authentication username", "username", "[REDACTED]"); + __privateSet(this, _creds, `${username}:${password}`); } - connect(provider2) { - return new _NonceManager(this.signer.connect(provider2)); + /** + * Enable and request gzip-encoded responses. The response will + * automatically be decompressed. //(default: true)// + */ + get allowGzip() { + return __privateGet(this, _gzip); } - async getNonce(blockTag) { - if (blockTag === "pending") { - if (__privateGet(this, _noncePromise) == null) { - __privateSet(this, _noncePromise, super.getNonce("pending")); - } - const delta = __privateGet(this, _delta); - return await __privateGet(this, _noncePromise) + delta; - } - return super.getNonce(blockTag); + set allowGzip(value) { + __privateSet(this, _gzip, !!value); } /** - * Manually increment the nonce. This may be useful when managng - * offline transactions. + * Allow ``Authentication`` credentials to be sent over insecure + * channels. //(default: false)// */ - increment() { - __privateWrapper(this, _delta)._++; + get allowInsecureAuthentication() { + return !!__privateGet(this, _allowInsecure); + } + set allowInsecureAuthentication(value) { + __privateSet(this, _allowInsecure, !!value); } /** - * Resets the nonce, causing the **NonceManager** to reload the current - * nonce from the blockchain on the next transaction. + * The timeout (in milliseconds) to wait for a complete response. + * //(default: 5 minutes)// */ - reset() { - __privateSet(this, _delta, 0); - __privateSet(this, _noncePromise, null); + get timeout() { + return __privateGet(this, _timeout); } - async sendTransaction(tx) { - const noncePromise = this.getNonce("pending"); - this.increment(); - tx = await this.signer.populateTransaction(tx); - tx.nonce = await noncePromise; - return await this.signer.sendTransaction(tx); + set timeout(timeout) { + assertArgument(timeout >= 0, "timeout must be non-zero", "timeout", timeout); + __privateSet(this, _timeout, timeout); } - signTransaction(tx) { - return this.signer.signTransaction(tx); + /** + * This function is called prior to each request, for example + * during a redirection or retry in case of server throttling. + * + * This offers an opportunity to populate headers or update + * content before sending a request. + */ + get preflightFunc() { + return __privateGet(this, _preflight) || null; } - signMessage(message) { - return this.signer.signMessage(message); + set preflightFunc(preflight) { + __privateSet(this, _preflight, preflight); } - signTypedData(domain2, types2, value) { - return this.signer.signTypedData(domain2, types2, value); + /** + * This function is called after each response, offering an + * opportunity to provide client-level throttling or updating + * response data. + * + * Any error thrown in this causes the ``send()`` to throw. + * + * To schedule a retry attempt (assuming the maximum retry limit + * has not been reached), use [[response.throwThrottleError]]. + */ + get processFunc() { + return __privateGet(this, _process) || null; + } + set processFunc(process2) { + __privateSet(this, _process, process2); } -}; -_noncePromise = new WeakMap(); -_delta = new WeakMap(); -let NonceManager = _NonceManager; -class BrowserProvider extends JsonRpcApiPollingProvider { /** - * Connnect to the %%ethereum%% provider, optionally forcing the - * %%network%%. + * This function is called on each retry attempt. */ - constructor(ethereum, network2, _options4) { - const options = Object.assign({}, _options4 != null ? _options4 : {}, { batchMaxCount: 1 }); - assertArgument(ethereum && ethereum.request, "invalid EIP-1193 provider", "ethereum", ethereum); - super(network2, options); - __privateAdd(this, _request2); - __privateSet(this, _request2, async (method, params) => { - const payload = { method, params }; - this.emit("debug", { action: "sendEip1193Request", payload }); - try { - const result = await ethereum.request(payload); - this.emit("debug", { action: "receiveEip1193Result", result }); - return result; - } catch (e2) { - const error = new Error(e2.message); - error.code = e2.code; - error.data = e2.data; - error.payload = payload; - this.emit("debug", { action: "receiveEip1193Error", error }); - throw error; - } - }); + get retryFunc() { + return __privateGet(this, _retry) || null; } - async send(method, params) { - await this._start(); - return await super.send(method, params); + set retryFunc(retry) { + __privateSet(this, _retry, retry); } - async _send(payload) { - assertArgument(!Array.isArray(payload), "EIP-1193 does not support batch request", "payload", payload); - try { - const result = await __privateGet(this, _request2).call(this, payload.method, payload.params || []); - return [{ id: payload.id, result }]; - } catch (e2) { - return [{ - id: payload.id, - error: { code: e2.code, data: e2.data, message: e2.message } - }]; - } + /** + * This function is called to fetch content from HTTP and + * HTTPS URLs and is platform specific (e.g. nodejs vs + * browsers). + * + * This is by default the currently registered global getUrl + * function, which can be changed using [[registerGetUrl]]. + * If this has been set, setting is to ``null`` will cause + * this FetchRequest (and any future clones) to revert back to + * using the currently registered global getUrl function. + * + * Setting this is generally not necessary, but may be useful + * for developers that wish to intercept requests or to + * configurege a proxy or other agent. + */ + get getUrlFunc() { + return __privateGet(this, _getUrlFunc) || defaultGetUrlFunc; } - getRpcError(payload, error) { - error = JSON.parse(JSON.stringify(error)); - switch (error.error.code || -1) { - case 4001: - error.error.message = `ethers-user-denied: ${error.error.message}`; - break; - case 4200: - error.error.message = `ethers-unsupported: ${error.error.message}`; - break; - } - return super.getRpcError(payload, error); + set getUrlFunc(value) { + __privateSet(this, _getUrlFunc, value); + } + toString() { + return ``; } /** - * Resolves to ``true`` if the provider manages the %%address%%. + * Update the throttle parameters used to determine maximum + * attempts and exponential-backoff properties. */ - async hasSigner(address) { - if (address == null) { - address = 0; + setThrottleParams(params) { + if (params.slotInterval != null) { + __privateGet(this, _throttle).slotInterval = params.slotInterval; } - const accounts = await this.send("eth_accounts", []); - if (typeof address === "number") { - return accounts.length > address; + if (params.maxAttempts != null) { + __privateGet(this, _throttle).maxAttempts = params.maxAttempts; } - address = address.toLowerCase(); - return accounts.filter((a2) => a2.toLowerCase() === address).length !== 0; } - async getSigner(address) { - if (address == null) { - address = 0; + /** + * Resolves to the response by sending the request. + */ + send() { + assert(__privateGet(this, _signal) == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }); + __privateSet(this, _signal, new FetchCancelSignal(this)); + return __privateMethod(this, _FetchRequest_instances, send_fn).call(this, 0, getTime$2() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this)); + } + /** + * Cancels the inflight response, causing a ``CANCELLED`` + * error to be rejected from the [[send]]. + */ + cancel() { + assert(__privateGet(this, _signal) != null, "request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" }); + const signal = fetchSignals.get(this); + if (!signal) { + throw new Error("missing signal; should not happen"); } - if (!await this.hasSigner(address)) { - try { - await __privateGet(this, _request2).call(this, "eth_requestAccounts", []); - } catch (error) { - const payload = error.payload; - throw this.getRpcError(payload, { id: payload.id, error }); - } + signal(); + } + /** + * Returns a new [[FetchRequest]] that represents the redirection + * to %%location%%. + */ + redirect(location2) { + const current = this.url.split(":")[0].toLowerCase(); + const target = location2.split(":")[0].toLowerCase(); + assert(this.method === "GET" && (current !== "https" || target !== "http") && location2.match(/^https?:/), `unsupported redirect`, "UNSUPPORTED_OPERATION", { + operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location2)})` + }); + const req = new _FetchRequest(location2); + req.method = "GET"; + req.allowGzip = this.allowGzip; + req.timeout = this.timeout; + __privateSet(req, _headers, Object.assign({}, __privateGet(this, _headers))); + if (__privateGet(this, _body)) { + __privateSet(req, _body, new Uint8Array(__privateGet(this, _body))); } - return await super.getSigner(address); - } -} -_request2 = new WeakMap(); -const defaultApplicationId = "62e1ad51b37b8e00394bda3b"; -function getHost(name2) { - switch (name2) { - case "mainnet": - return "eth-mainnet.gateway.pokt.network"; - case "goerli": - return "eth-goerli.gateway.pokt.network"; - case "matic": - return "poly-mainnet.gateway.pokt.network"; - case "matic-mumbai": - return "polygon-mumbai-rpc.gateway.pokt.network"; + __privateSet(req, _bodyType, __privateGet(this, _bodyType)); + return req; } - assertArgument(false, "unsupported network", "network", name2); -} -class PocketProvider extends JsonRpcProvider$1 { /** - * Create a new **PocketProvider**. - * - * By default connecting to ``mainnet`` with a highly throttled - * API key. + * Create a new copy of this request. */ - constructor(_network3, applicationId, applicationSecret) { - if (_network3 == null) { - _network3 = "mainnet"; + clone() { + const clone = new _FetchRequest(this.url); + __privateSet(clone, _method, __privateGet(this, _method)); + if (__privateGet(this, _body)) { + __privateSet(clone, _body, __privateGet(this, _body)); } - const network2 = Network.from(_network3); - if (applicationId == null) { - applicationId = defaultApplicationId; + __privateSet(clone, _bodyType, __privateGet(this, _bodyType)); + __privateSet(clone, _headers, Object.assign({}, __privateGet(this, _headers))); + __privateSet(clone, _creds, __privateGet(this, _creds)); + if (this.allowGzip) { + clone.allowGzip = true; } - if (applicationSecret == null) { - applicationSecret = null; + clone.timeout = this.timeout; + if (this.allowInsecureAuthentication) { + clone.allowInsecureAuthentication = true; } - const options = { staticNetwork: network2 }; - const request = PocketProvider.getRequest(network2, applicationId, applicationSecret); - super(request, network2, options); - /** - * The Application ID for the Pocket connection. - */ - __publicField(this, "applicationId"); - /** - * The Application Secret for making authenticated requests - * to the Pocket connection. - */ - __publicField(this, "applicationSecret"); - defineProperties$1(this, { applicationId, applicationSecret }); + __privateSet(clone, _preflight, __privateGet(this, _preflight)); + __privateSet(clone, _process, __privateGet(this, _process)); + __privateSet(clone, _retry, __privateGet(this, _retry)); + __privateSet(clone, _throttle, Object.assign({}, __privateGet(this, _throttle))); + __privateSet(clone, _getUrlFunc, __privateGet(this, _getUrlFunc)); + return clone; } - _getProvider(chainId) { - try { - return new PocketProvider(chainId, this.applicationId, this.applicationSecret); - } catch (error) { - } - return super._getProvider(chainId); + /** + * Locks all static configuration for gateways and FetchGetUrlFunc + * registration. + */ + static lockConfig() { + locked$5 = true; } /** - * Returns a prepared request for connecting to %%network%% with - * %%applicationId%%. + * Get the current Gateway function for %%scheme%%. */ - static getRequest(network2, applicationId, applicationSecret) { - if (applicationId == null) { - applicationId = defaultApplicationId; - } - const request = new FetchRequest(`https://${getHost(network2.name)}/v1/lb/${applicationId}`); - request.allowGzip = true; - if (applicationSecret) { - request.setCredentials("", applicationSecret); + static getGateway(scheme) { + return Gateways[scheme.toLowerCase()] || null; + } + /** + * Use the %%func%% when fetching URIs using %%scheme%%. + * + * This method affects all requests globally. + * + * If [[lockConfig]] has been called, no change is made and this + * throws. + */ + static registerGateway(scheme, func) { + scheme = scheme.toLowerCase(); + if (scheme === "http" || scheme === "https") { + throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); } - if (applicationId === defaultApplicationId) { - request.retryFunc = async (request2, response, attempt) => { - showThrottleMessage("PocketProvider"); - return true; - }; + if (locked$5) { + throw new Error("gateways locked"); } - return request; + Gateways[scheme] = func; } - isCommunityResource() { - return this.applicationId === defaultApplicationId; + /** + * Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests. + * + * This method affects all requests globally. + * + * If [[lockConfig]] has been called, no change is made and this + * throws. + */ + static registerGetUrl(getUrl2) { + if (locked$5) { + throw new Error("gateways locked"); + } + defaultGetUrlFunc = getUrl2; } -} -const IpcSocketProvider = void 0; -const _BaseWallet = class _BaseWallet extends AbstractSigner { /** - * Creates a new BaseWallet for %%privateKey%%, optionally - * connected to %%provider%%. + * Creates a getUrl function that fetches content from HTTP and + * HTTPS URLs. * - * If %%provider%% is not specified, only offline methods can - * be used. + * The available %%options%% are dependent on the platform + * implementation of the default getUrl function. + * + * This is not generally something that is needed, but is useful + * when trying to customize simple behaviour when fetching HTTP + * content. */ - constructor(privateKey, provider2) { - super(provider2); - /** - * The wallet address. - */ - __publicField(this, "address"); - __privateAdd(this, _signingKey); - assertArgument(privateKey && typeof privateKey.sign === "function", "invalid private key", "privateKey", "[ REDACTED ]"); - __privateSet(this, _signingKey, privateKey); - const address = computeAddress(this.signingKey.publicKey); - defineProperties$1(this, { address }); + static createGetUrlFunc(options) { + return createGetUrl(); } - // Store private values behind getters to reduce visibility - // in console.log /** - * The [[SigningKey]] used for signing payloads. + * Creates a function that can "fetch" data URIs. + * + * Note that this is automatically done internally to support + * data URIs, so it is not necessary to register it. + * + * This is not generally something that is needed, but may + * be useful in a wrapper to perfom custom data URI functionality. */ - get signingKey() { - return __privateGet(this, _signingKey); + static createDataGateway() { + return dataGatewayFunc; } /** - * The private key for this wallet. + * Creates a function that will fetch IPFS (unvalidated) from + * a custom gateway baseUrl. + * + * The default IPFS gateway used internally is + * ``"https:/\/gateway.ipfs.io/ipfs/"``. */ - get privateKey() { - return this.signingKey.privateKey; + static createIpfsGatewayFunc(baseUrl) { + return getIpfsGatewayFunc(baseUrl); } - async getAddress() { - return this.address; +}; +_allowInsecure = new WeakMap(); +_gzip = new WeakMap(); +_headers = new WeakMap(); +_method = new WeakMap(); +_timeout = new WeakMap(); +_url = new WeakMap(); +_body = new WeakMap(); +_bodyType = new WeakMap(); +_creds = new WeakMap(); +_preflight = new WeakMap(); +_process = new WeakMap(); +_retry = new WeakMap(); +_signal = new WeakMap(); +_throttle = new WeakMap(); +_getUrlFunc = new WeakMap(); +_FetchRequest_instances = new WeakSet(); +send_fn = async function(attempt, expires, delay2, _request3, _response) { + var _a2, _b2, _c2; + if (attempt >= __privateGet(this, _throttle).maxAttempts) { + return _response.makeServerError("exceeded maximum retry limit"); } - connect(provider2) { - return new _BaseWallet(__privateGet(this, _signingKey), provider2); + assert(getTime$2() <= expires, "timeout", "TIMEOUT", { + operation: "request.send", + reason: "timeout", + request: _request3 + }); + if (delay2 > 0) { + await wait(delay2); } - async signTransaction(tx) { - const { to, from } = await resolveProperties$1({ - to: tx.to ? resolveAddress(tx.to, this.provider) : void 0, - from: tx.from ? resolveAddress(tx.from, this.provider) : void 0 - }); - if (to != null) { - tx.to = to; + let req = this.clone(); + const scheme = (req.url.split(":")[0] || "").toLowerCase(); + if (scheme in Gateways) { + const result = await Gateways[scheme](req.url, checkSignal(__privateGet(_request3, _signal))); + if (result instanceof FetchResponse) { + let response2 = result; + if (this.processFunc) { + checkSignal(__privateGet(_request3, _signal)); + try { + response2 = await this.processFunc(req, response2); + } catch (error) { + if (error.throttle == null || typeof error.stall !== "number") { + response2.makeServerError("error in post-processing function", error).assertOk(); + } + } + } + return response2; } - if (from != null) { - tx.from = from; + req = result; + } + if (this.preflightFunc) { + req = await this.preflightFunc(req); + } + const resp = await this.getUrlFunc(req, checkSignal(__privateGet(_request3, _signal))); + let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request3); + if (response.statusCode === 301 || response.statusCode === 302) { + try { + const location2 = response.headers.location || ""; + return __privateMethod(_a2 = req.redirect(location2), _FetchRequest_instances, send_fn).call(_a2, attempt + 1, expires, 0, _request3, response); + } catch (error) { } - if (tx.from != null) { - assertArgument(getAddress$1(tx.from) === this.address, "transaction from address mismatch", "tx.from", tx.from); - delete tx.from; + return response; + } else if (response.statusCode === 429) { + if (this.retryFunc == null || await this.retryFunc(req, response, attempt)) { + const retryAfter = response.headers["retry-after"]; + let delay3 = __privateGet(this, _throttle).slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); + if (typeof retryAfter === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { + delay3 = parseInt(retryAfter); + } + return __privateMethod(_b2 = req.clone(), _FetchRequest_instances, send_fn).call(_b2, attempt + 1, expires, delay3, _request3, response); } - const btx = Transaction.from(tx); - btx.signature = this.signingKey.sign(btx.unsignedHash); - return btx.serialized; } - async signMessage(message) { - return this.signMessageSync(message); + if (this.processFunc) { + checkSignal(__privateGet(_request3, _signal)); + try { + response = await this.processFunc(req, response); + } catch (error) { + if (error.throttle == null || typeof error.stall !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } + let delay3 = __privateGet(this, _throttle).slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); + if (error.stall >= 0) { + delay3 = error.stall; + } + return __privateMethod(_c2 = req.clone(), _FetchRequest_instances, send_fn).call(_c2, attempt + 1, expires, delay3, _request3, response); + } + } + return response; +}; +let FetchRequest = _FetchRequest; +const _FetchResponse = class _FetchResponse { + constructor(statusCode, statusMessage, headers, body, request) { + __privateAdd(this, _statusCode); + __privateAdd(this, _statusMessage); + __privateAdd(this, _headers2); + __privateAdd(this, _body2); + __privateAdd(this, _request); + __privateAdd(this, _error); + __privateSet(this, _statusCode, statusCode); + __privateSet(this, _statusMessage, statusMessage); + __privateSet(this, _headers2, Object.keys(headers).reduce((accum, k2) => { + accum[k2.toLowerCase()] = String(headers[k2]); + return accum; + }, {})); + __privateSet(this, _body2, body == null ? null : new Uint8Array(body)); + __privateSet(this, _request, request || null); + __privateSet(this, _error, { message: "" }); + } + toString() { + return ``; } - // @TODO: Add a secialized signTx and signTyped sync that enforces - // all parameters are known? /** - * Returns the signature for %%message%% signed with this wallet. + * The response status code. */ - signMessageSync(message) { - return this.signingKey.sign(hashMessage$1(message)).serialized; - } - async signTypedData(domain2, types2, value) { - const populated = await TypedDataEncoder.resolveNames(domain2, types2, value, async (name2) => { - assert(this.provider != null, "cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", { - operation: "resolveName", - info: { name: name2 } - }); - const address = await this.provider.resolveName(name2); - assert(address != null, "unconfigured ENS name", "UNCONFIGURED_NAME", { - value: name2 - }); - return address; - }); - return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types2, populated.value)).serialized; + get statusCode() { + return __privateGet(this, _statusCode); } -}; -_signingKey = new WeakMap(); -let BaseWallet = _BaseWallet; -const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; -const Word = /^[a-z]*$/i; -function unfold(words2, sep) { - let initial = 97; - return words2.reduce((accum, word) => { - if (word === sep) { - initial++; - } else if (word.match(Word)) { - accum.push(String.fromCharCode(initial) + word); - } else { - initial = 97; - accum.push(word); - } - return accum; - }, []); -} -function decode$1(data, subs) { - for (let i = subsChrs.length - 1; i >= 0; i--) { - data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); + /** + * The response status message. + */ + get statusMessage() { + return __privateGet(this, _statusMessage); } - const clumps = []; - const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item2, semi, word) => { - if (semi) { - for (let i = parseInt(semi); i >= 0; i--) { - clumps.push(";"); - } - } else { - clumps.push(item2.toLowerCase()); - } - return ""; - }); - if (leftover) { - throw new Error(`leftovers: ${JSON.stringify(leftover)}`); + /** + * The response headers. All keys are lower-case. + */ + get headers() { + return Object.assign({}, __privateGet(this, _headers2)); } - return unfold(unfold(clumps, ";"), ":"); -} -function decodeOwl(data) { - assertArgument(data[0] === "0", "unsupported auwl data", "data", data); - return decode$1(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); -} -class Wordlist { /** - * Creates a new Wordlist instance. - * - * Sub-classes MUST call this if they provide their own constructor, - * passing in the locale string of the language. - * - * Generally there is no need to create instances of a Wordlist, - * since each language-specific Wordlist creates an instance and - * there is no state kept internally, so they are safe to share. + * The response body, or ``null`` if there was no body. */ - constructor(locale) { - __publicField(this, "locale"); - defineProperties$1(this, { locale }); + get body() { + return __privateGet(this, _body2) == null ? null : new Uint8Array(__privateGet(this, _body2)); } /** - * Sub-classes may override this to provide a language-specific - * method for spliting %%phrase%% into individual words. + * The response body as a UTF-8 encoded string, or the empty + * string (i.e. ``""``) if there was no body. * - * By default, %%phrase%% is split using any sequences of - * white-space as defined by regular expressions (i.e. ``/\s+/``). + * An error is thrown if the body is invalid UTF-8 data. */ - split(phrase) { - return phrase.toLowerCase().split(/\s+/g); + get bodyText() { + try { + return __privateGet(this, _body2) == null ? "" : toUtf8String(__privateGet(this, _body2)); + } catch (error) { + assert(false, "response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", { + operation: "bodyText", + info: { response: this } + }); + } } /** - * Sub-classes may override this to provider a language-specific - * method for joining %%words%% into a phrase. + * The response body, decoded as JSON. * - * By default, %%words%% are joined by a single space. + * An error is thrown if the body is invalid JSON-encoded data + * or if there was no body. */ - join(words2) { - return words2.join(" "); + get bodyJson() { + try { + return JSON.parse(this.bodyText); + } catch (error) { + assert(false, "response body is not valid JSON", "UNSUPPORTED_OPERATION", { + operation: "bodyJson", + info: { response: this } + }); + } + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index2 = 0; + return { + next: () => { + if (index2 < keys.length) { + const key = keys[index2++]; + return { + value: [key, headers[key]], + done: false + }; + } + return { value: void 0, done: true }; + } + }; } -} -class WordlistOwl extends Wordlist { /** - * Creates a new Wordlist for %%locale%% using the OWL %%data%% - * and validated against the %%checksum%%. + * Return a Response with matching headers and body, but with + * an error status code (i.e. 599) and %%message%% with an + * optional %%error%%. */ - constructor(locale, data, checksum2) { - super(locale); - __privateAdd(this, _WordlistOwl_instances); - __privateAdd(this, _data5); - __privateAdd(this, _checksum); - __privateAdd(this, _words); - __privateSet(this, _data5, data); - __privateSet(this, _checksum, checksum2); - __privateSet(this, _words, null); + makeServerError(message, error) { + let statusMessage; + if (!message) { + message = `${this.statusCode} ${this.statusMessage}`; + statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; + } else { + statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; + } + const response = new _FetchResponse(599, statusMessage, this.headers, this.body, __privateGet(this, _request) || void 0); + __privateSet(response, _error, { message, error }); + return response; } /** - * The OWL-encoded data. + * If called within a [request.processFunc](FetchRequest-processFunc) + * call, causes the request to retry as if throttled for %%stall%% + * milliseconds. */ - get _data() { - return __privateGet(this, _data5); + throwThrottleError(message, stall2) { + if (stall2 == null) { + stall2 = -1; + } else { + assertArgument(Number.isInteger(stall2) && stall2 >= 0, "invalid stall timeout", "stall", stall2); + } + const error = new Error(message || "throttling requests"); + defineProperties$1(error, { stall: stall2, throttle: true }); + throw error; } /** - * Decode all the words for the wordlist. + * Get the header value for %%key%%, ignoring case. */ - _decodeWords() { - return decodeOwl(__privateGet(this, _data5)); - } - getWord(index2) { - const words2 = __privateMethod(this, _WordlistOwl_instances, loadWords_fn).call(this); - assertArgument(index2 >= 0 && index2 < words2.length, `invalid word index: ${index2}`, "index", index2); - return words2[index2]; - } - getWordIndex(word) { - return __privateMethod(this, _WordlistOwl_instances, loadWords_fn).call(this).indexOf(word); + getHeader(key) { + return this.headers[key.toLowerCase()]; } -} -_data5 = new WeakMap(); -_checksum = new WeakMap(); -_words = new WeakMap(); -_WordlistOwl_instances = new WeakSet(); -loadWords_fn = function() { - if (__privateGet(this, _words) == null) { - const words2 = this._decodeWords(); - const checksum2 = id$1(words2.join("\n") + "\n"); - if (checksum2 !== __privateGet(this, _checksum)) { - throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); - } - __privateSet(this, _words, words2); + /** + * Returns true if the response has a body. + */ + hasBody() { + return __privateGet(this, _body2) != null; } - return __privateGet(this, _words); -}; -const words = "0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-PM&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryFN Noc|PutQuirySSue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOgAyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO"; -const checksum = "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60"; -let wordlist = null; -class LangEn extends WordlistOwl { /** - * Creates a new instance of the English language Wordlist. - * - * This should be unnecessary most of the time as the exported - * [[langEn]] should suffice. - * - * @_ignore: + * The request made for this response. */ - constructor() { - super("en", words, checksum); + get request() { + return __privateGet(this, _request); } /** - * Returns a singleton instance of a ``LangEn``, creating it - * if this is the first time being called. + * Returns true if this response was a success statusCode. */ - static wordlist() { - if (wordlist == null) { - wordlist = new LangEn(); + ok() { + return __privateGet(this, _error).message === "" && this.statusCode >= 200 && this.statusCode < 300; + } + /** + * Throws a ``SERVER_ERROR`` if this response is not ok. + */ + assertOk() { + if (this.ok()) { + return; } - return wordlist; + let { message, error } = __privateGet(this, _error); + if (message === "") { + message = `server response ${this.statusCode} ${this.statusMessage}`; + } + let requestUrl = null; + if (this.request) { + requestUrl = this.request.url; + } + let responseBody = null; + try { + if (__privateGet(this, _body2)) { + responseBody = toUtf8String(__privateGet(this, _body2)); + } + } catch (e2) { + } + assert(false, message, "SERVER_ERROR", { + request: this.request || "unknown request", + response: this, + error, + info: { + requestUrl, + responseBody, + responseStatus: `${this.statusCode} ${this.statusMessage}` + } + }); } +}; +_statusCode = new WeakMap(); +_statusMessage = new WeakMap(); +_headers2 = new WeakMap(); +_body2 = new WeakMap(); +_request = new WeakMap(); +_error = new WeakMap(); +let FetchResponse = _FetchResponse; +function getTime$2() { + return (/* @__PURE__ */ new Date()).getTime(); } -function getUpperMask(bits) { - return (1 << bits) - 1 << 8 - bits & 255; +function unpercent(value) { + return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code2) => { + return String.fromCharCode(parseInt(code2, 16)); + })); } -function getLowerMask(bits) { - return (1 << bits) - 1 & 255; +function wait(delay2) { + return new Promise((resolve) => setTimeout(resolve, delay2)); } -function mnemonicToEntropy(mnemonic, wordlist2) { - assertNormalize("NFKD"); - if (wordlist2 == null) { - wordlist2 = LangEn.wordlist(); +const BN_N1 = BigInt(-1); +const BN_0$8 = BigInt(0); +const BN_1$4 = BigInt(1); +const BN_5 = BigInt(5); +const _guard$5 = {}; +let Zeros$1 = "0000"; +while (Zeros$1.length < 80) { + Zeros$1 += Zeros$1; +} +function getTens(decimals) { + let result = Zeros$1; + while (result.length < decimals) { + result += result; } - const words2 = wordlist2.split(mnemonic); - assertArgument(words2.length % 3 === 0 && words2.length >= 12 && words2.length <= 24, "invalid mnemonic length", "mnemonic", "[ REDACTED ]"); - const entropy = new Uint8Array(Math.ceil(11 * words2.length / 8)); - let offset2 = 0; - for (let i = 0; i < words2.length; i++) { - let index2 = wordlist2.getWordIndex(words2[i].normalize("NFKD")); - assertArgument(index2 >= 0, `invalid mnemonic word at index ${i}`, "mnemonic", "[ REDACTED ]"); - for (let bit = 0; bit < 11; bit++) { - if (index2 & 1 << 10 - bit) { - entropy[offset2 >> 3] |= 1 << 7 - offset2 % 8; - } - offset2++; + return BigInt("1" + result.substring(0, decimals)); +} +function checkValue(val, format2, safeOp) { + const width = BigInt(format2.width); + if (format2.signed) { + const limit = BN_1$4 << width - BN_1$4; + assert(safeOp == null || val >= -limit && val < limit, "overflow", "NUMERIC_FAULT", { + operation: safeOp, + fault: "overflow", + value: val + }); + if (val > BN_0$8) { + val = fromTwos(mask(val, width), width); + } else { + val = -fromTwos(mask(-val, width), width); } + } else { + const limit = BN_1$4 << width; + assert(safeOp == null || val >= 0 && val < limit, "overflow", "NUMERIC_FAULT", { + operation: safeOp, + fault: "overflow", + value: val + }); + val = (val % limit + limit) % limit & limit - BN_1$4; } - const entropyBits = 32 * words2.length / 3; - const checksumBits = words2.length / 3; - const checksumMask = getUpperMask(checksumBits); - const checksum2 = getBytes(sha256$3(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; - assertArgument(checksum2 === (entropy[entropy.length - 1] & checksumMask), "invalid mnemonic checksum", "mnemonic", "[ REDACTED ]"); - return hexlify(entropy.slice(0, entropyBits / 8)); + return val; } -function entropyToMnemonic(entropy, wordlist2) { - assertArgument(entropy.length % 4 === 0 && entropy.length >= 16 && entropy.length <= 32, "invalid entropy size", "entropy", "[ REDACTED ]"); - if (wordlist2 == null) { - wordlist2 = LangEn.wordlist(); +function getFormat(value) { + if (typeof value === "number") { + value = `fixed128x${value}`; } - const indices = [0]; - let remainingBits = 11; - for (let i = 0; i < entropy.length; i++) { - if (remainingBits > 8) { - indices[indices.length - 1] <<= 8; - indices[indices.length - 1] |= entropy[i]; - remainingBits -= 8; + let signed2 = true; + let width = 128; + let decimals = 18; + if (typeof value === "string") { + if (value === "fixed") ; + else if (value === "ufixed") { + signed2 = false; } else { - indices[indices.length - 1] <<= remainingBits; - indices[indices.length - 1] |= entropy[i] >> 8 - remainingBits; - indices.push(entropy[i] & getLowerMask(8 - remainingBits)); - remainingBits += 3; + const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); + assertArgument(match, "invalid fixed format", "format", value); + signed2 = match[1] !== "u"; + width = parseInt(match[2]); + decimals = parseInt(match[3]); } + } else if (value) { + const v3 = value; + const check = (key, type, defaultValue) => { + if (v3[key] == null) { + return defaultValue; + } + assertArgument(typeof v3[key] === type, "invalid fixed format (" + key + " not " + type + ")", "format." + key, v3[key]); + return v3[key]; + }; + signed2 = check("signed", "boolean", signed2); + width = check("width", "number", width); + decimals = check("decimals", "number", decimals); } - const checksumBits = entropy.length / 4; - const checksum2 = parseInt(sha256$3(entropy).substring(2, 4), 16) & getUpperMask(checksumBits); - indices[indices.length - 1] <<= checksumBits; - indices[indices.length - 1] |= checksum2 >> 8 - checksumBits; - return wordlist2.join(indices.map((index2) => wordlist2.getWord(index2))); + assertArgument(width % 8 === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width); + assertArgument(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals); + const name2 = (signed2 ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); + return { signed: signed2, width, decimals, name: name2 }; } -const _guard$1 = {}; -class Mnemonic { +function toString$1(val, decimals) { + let negative = ""; + if (val < BN_0$8) { + negative = "-"; + val *= BN_N1; + } + let str = val.toString(); + if (decimals === 0) { + return negative + str; + } + while (str.length <= decimals) { + str = Zeros$1 + str; + } + const index2 = str.length - decimals; + str = str.substring(0, index2) + "." + str.substring(index2); + while (str[0] === "0" && str[1] !== ".") { + str = str.substring(1); + } + while (str[str.length - 1] === "0" && str[str.length - 2] !== ".") { + str = str.substring(0, str.length - 1); + } + return negative + str; +} +const _FixedNumber = class _FixedNumber { + // Use this when changing this file to get some typing info, + // but then switch to any to mask the internal type + //constructor(guard: any, value: bigint, format: _FixedFormat) { /** * @private */ - constructor(guard2, entropy, phrase, password, wordlist2) { - /** - * The mnemonic phrase of 12, 15, 18, 21 or 24 words. - * - * Use the [[wordlist]] ``split`` method to get the individual words. - */ - __publicField(this, "phrase"); - /** - * The password used for this mnemonic. If no password is used this - * is the empty string (i.e. ``""``) as per the specification. - */ - __publicField(this, "password"); + constructor(guard2, value, format2) { + __privateAdd(this, _FixedNumber_instances); /** - * The wordlist for this mnemonic. + * The specific fixed-point arithmetic field for this value. */ - __publicField(this, "wordlist"); + __publicField(this, "format"); + __privateAdd(this, _format); + // The actual value (accounting for decimals) + __privateAdd(this, _val); + // A base-10 value to multiple values by to maintain the magnitude + __privateAdd(this, _tens); /** - * The underlying entropy which the mnemonic encodes. + * This is a property so console.log shows a human-meaningful value. + * + * @private */ - __publicField(this, "entropy"); - if (password == null) { - password = ""; - } - if (wordlist2 == null) { - wordlist2 = LangEn.wordlist(); - } - assertPrivate(guard2, _guard$1, "Mnemonic"); - defineProperties$1(this, { phrase, password, wordlist: wordlist2, entropy }); + __publicField(this, "_value"); + assertPrivate(guard2, _guard$5, "FixedNumber"); + __privateSet(this, _val, value); + __privateSet(this, _format, format2); + const _value2 = toString$1(value, format2.decimals); + defineProperties$1(this, { format: format2.name, _value: _value2 }); + __privateSet(this, _tens, getTens(format2.decimals)); } /** - * Returns the seed for the mnemonic. + * If true, negative values are permitted, otherwise only + * positive values and zero are allowed. */ - computeSeed() { - const salt = toUtf8Bytes("mnemonic" + this.password, "NFKD"); - return pbkdf2(toUtf8Bytes(this.phrase, "NFKD"), salt, 2048, 64, "sha512"); + get signed() { + return __privateGet(this, _format).signed; } /** - * Creates a new Mnemonic for the %%phrase%%. - * - * The default %%password%% is the empty string and the default - * wordlist is the [English wordlists](LangEn). + * The number of bits available to store the value. */ - static fromPhrase(phrase, password, wordlist2) { - const entropy = mnemonicToEntropy(phrase, wordlist2); - phrase = entropyToMnemonic(getBytes(entropy), wordlist2); - return new Mnemonic(_guard$1, entropy, phrase, password, wordlist2); + get width() { + return __privateGet(this, _format).width; } /** - * Create a new **Mnemonic** from the %%entropy%%. - * - * The default %%password%% is the empty string and the default - * wordlist is the [English wordlists](LangEn). + * The number of decimal places in the fixed-point arithment field. */ - static fromEntropy(_entropy, password, wordlist2) { - const entropy = getBytes(_entropy, "entropy"); - const phrase = entropyToMnemonic(entropy, wordlist2); - return new Mnemonic(_guard$1, hexlify(entropy), phrase, password, wordlist2); + get decimals() { + return __privateGet(this, _format).decimals; } /** - * Returns the phrase for %%mnemonic%%. + * The value as an integer, based on the smallest unit the + * [[decimals]] allow. */ - static entropyToPhrase(_entropy, wordlist2) { - const entropy = getBytes(_entropy, "entropy"); - return entropyToMnemonic(entropy, wordlist2); + get value() { + return __privateGet(this, _val); } /** - * Returns the entropy for %%phrase%%. + * Returns a new [[FixedNumber]] with the result of %%this%% added + * to %%other%%, ignoring overflow. */ - static phraseToEntropy(phrase, wordlist2) { - return mnemonicToEntropy(phrase, wordlist2); + addUnsafe(other) { + return __privateMethod(this, _FixedNumber_instances, add_fn).call(this, other); } /** - * Returns true if %%phrase%% is a valid [[link-bip-39]] phrase. - * - * This checks all the provided words belong to the %%wordlist%%, - * that the length is valid and the checksum is correct. + * Returns a new [[FixedNumber]] with the result of %%this%% added + * to %%other%%. A [[NumericFaultError]] is thrown if overflow + * occurs. */ - static isValidMnemonic(phrase, wordlist2) { - try { - mnemonicToEntropy(phrase, wordlist2); - return true; - } catch (error) { - } - return false; + add(other) { + return __privateMethod(this, _FixedNumber_instances, add_fn).call(this, other, "add"); } -} -/*! MIT License. Copyright 2015-2022 Richard Moore . See LICENSE.txt. */ -var __classPrivateFieldGet$3 = function(receiver, state, kind, f2) { - if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver); -}; -var __classPrivateFieldSet$2 = function(receiver, state, value, kind, f2) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value; -}; -var _AES_key, _AES_Kd, _AES_Ke; -const numberOfRounds = { 16: 10, 24: 12, 32: 14 }; -const rcon = [1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145]; -const S = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22]; -const Si = [82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125]; -const T1 = [3328402341, 4168907908, 4000806809, 4135287693, 4294111757, 3597364157, 3731845041, 2445657428, 1613770832, 33620227, 3462883241, 1445669757, 3892248089, 3050821474, 1303096294, 3967186586, 2412431941, 528646813, 2311702848, 4202528135, 4026202645, 2992200171, 2387036105, 4226871307, 1101901292, 3017069671, 1604494077, 1169141738, 597466303, 1403299063, 3832705686, 2613100635, 1974974402, 3791519004, 1033081774, 1277568618, 1815492186, 2118074177, 4126668546, 2211236943, 1748251740, 1369810420, 3521504564, 4193382664, 3799085459, 2883115123, 1647391059, 706024767, 134480908, 2512897874, 1176707941, 2646852446, 806885416, 932615841, 168101135, 798661301, 235341577, 605164086, 461406363, 3756188221, 3454790438, 1311188841, 2142417613, 3933566367, 302582043, 495158174, 1479289972, 874125870, 907746093, 3698224818, 3025820398, 1537253627, 2756858614, 1983593293, 3084310113, 2108928974, 1378429307, 3722699582, 1580150641, 327451799, 2790478837, 3117535592, 0, 3253595436, 1075847264, 3825007647, 2041688520, 3059440621, 3563743934, 2378943302, 1740553945, 1916352843, 2487896798, 2555137236, 2958579944, 2244988746, 3151024235, 3320835882, 1336584933, 3992714006, 2252555205, 2588757463, 1714631509, 293963156, 2319795663, 3925473552, 67240454, 4269768577, 2689618160, 2017213508, 631218106, 1269344483, 2723238387, 1571005438, 2151694528, 93294474, 1066570413, 563977660, 1882732616, 4059428100, 1673313503, 2008463041, 2950355573, 1109467491, 537923632, 3858759450, 4260623118, 3218264685, 2177748300, 403442708, 638784309, 3287084079, 3193921505, 899127202, 2286175436, 773265209, 2479146071, 1437050866, 4236148354, 2050833735, 3362022572, 3126681063, 840505643, 3866325909, 3227541664, 427917720, 2655997905, 2749160575, 1143087718, 1412049534, 999329963, 193497219, 2353415882, 3354324521, 1807268051, 672404540, 2816401017, 3160301282, 369822493, 2916866934, 3688947771, 1681011286, 1949973070, 336202270, 2454276571, 201721354, 1210328172, 3093060836, 2680341085, 3184776046, 1135389935, 3294782118, 965841320, 831886756, 3554993207, 4068047243, 3588745010, 2345191491, 1849112409, 3664604599, 26054028, 2983581028, 2622377682, 1235855840, 3630984372, 2891339514, 4092916743, 3488279077, 3395642799, 4101667470, 1202630377, 268961816, 1874508501, 4034427016, 1243948399, 1546530418, 941366308, 1470539505, 1941222599, 2546386513, 3421038627, 2715671932, 3899946140, 1042226977, 2521517021, 1639824860, 227249030, 260737669, 3765465232, 2084453954, 1907733956, 3429263018, 2420656344, 100860677, 4160157185, 470683154, 3261161891, 1781871967, 2924959737, 1773779408, 394692241, 2579611992, 974986535, 664706745, 3655459128, 3958962195, 731420851, 571543859, 3530123707, 2849626480, 126783113, 865375399, 765172662, 1008606754, 361203602, 3387549984, 2278477385, 2857719295, 1344809080, 2782912378, 59542671, 1503764984, 160008576, 437062935, 1707065306, 3622233649, 2218934982, 3496503480, 2185314755, 697932208, 1512910199, 504303377, 2075177163, 2824099068, 1841019862, 739644986]; -const T2 = [2781242211, 2230877308, 2582542199, 2381740923, 234877682, 3184946027, 2984144751, 1418839493, 1348481072, 50462977, 2848876391, 2102799147, 434634494, 1656084439, 3863849899, 2599188086, 1167051466, 2636087938, 1082771913, 2281340285, 368048890, 3954334041, 3381544775, 201060592, 3963727277, 1739838676, 4250903202, 3930435503, 3206782108, 4149453988, 2531553906, 1536934080, 3262494647, 484572669, 2923271059, 1783375398, 1517041206, 1098792767, 49674231, 1334037708, 1550332980, 4098991525, 886171109, 150598129, 2481090929, 1940642008, 1398944049, 1059722517, 201851908, 1385547719, 1699095331, 1587397571, 674240536, 2704774806, 252314885, 3039795866, 151914247, 908333586, 2602270848, 1038082786, 651029483, 1766729511, 3447698098, 2682942837, 454166793, 2652734339, 1951935532, 775166490, 758520603, 3000790638, 4004797018, 4217086112, 4137964114, 1299594043, 1639438038, 3464344499, 2068982057, 1054729187, 1901997871, 2534638724, 4121318227, 1757008337, 0, 750906861, 1614815264, 535035132, 3363418545, 3988151131, 3201591914, 1183697867, 3647454910, 1265776953, 3734260298, 3566750796, 3903871064, 1250283471, 1807470800, 717615087, 3847203498, 384695291, 3313910595, 3617213773, 1432761139, 2484176261, 3481945413, 283769337, 100925954, 2180939647, 4037038160, 1148730428, 3123027871, 3813386408, 4087501137, 4267549603, 3229630528, 2315620239, 2906624658, 3156319645, 1215313976, 82966005, 3747855548, 3245848246, 1974459098, 1665278241, 807407632, 451280895, 251524083, 1841287890, 1283575245, 337120268, 891687699, 801369324, 3787349855, 2721421207, 3431482436, 959321879, 1469301956, 4065699751, 2197585534, 1199193405, 2898814052, 3887750493, 724703513, 2514908019, 2696962144, 2551808385, 3516813135, 2141445340, 1715741218, 2119445034, 2872807568, 2198571144, 3398190662, 700968686, 3547052216, 1009259540, 2041044702, 3803995742, 487983883, 1991105499, 1004265696, 1449407026, 1316239930, 504629770, 3683797321, 168560134, 1816667172, 3837287516, 1570751170, 1857934291, 4014189740, 2797888098, 2822345105, 2754712981, 936633572, 2347923833, 852879335, 1133234376, 1500395319, 3084545389, 2348912013, 1689376213, 3533459022, 3762923945, 3034082412, 4205598294, 133428468, 634383082, 2949277029, 2398386810, 3913789102, 403703816, 3580869306, 2297460856, 1867130149, 1918643758, 607656988, 4049053350, 3346248884, 1368901318, 600565992, 2090982877, 2632479860, 557719327, 3717614411, 3697393085, 2249034635, 2232388234, 2430627952, 1115438654, 3295786421, 2865522278, 3633334344, 84280067, 33027830, 303828494, 2747425121, 1600795957, 4188952407, 3496589753, 2434238086, 1486471617, 658119965, 3106381470, 953803233, 334231800, 3005978776, 857870609, 3151128937, 1890179545, 2298973838, 2805175444, 3056442267, 574365214, 2450884487, 550103529, 1233637070, 4289353045, 2018519080, 2057691103, 2399374476, 4166623649, 2148108681, 387583245, 3664101311, 836232934, 3330556482, 3100665960, 3280093505, 2955516313, 2002398509, 287182607, 3413881008, 4238890068, 3597515707, 975967766]; -const T3 = [1671808611, 2089089148, 2006576759, 2072901243, 4061003762, 1807603307, 1873927791, 3310653893, 810573872, 16974337, 1739181671, 729634347, 4263110654, 3613570519, 2883997099, 1989864566, 3393556426, 2191335298, 3376449993, 2106063485, 4195741690, 1508618841, 1204391495, 4027317232, 2917941677, 3563566036, 2734514082, 2951366063, 2629772188, 2767672228, 1922491506, 3227229120, 3082974647, 4246528509, 2477669779, 644500518, 911895606, 1061256767, 4144166391, 3427763148, 878471220, 2784252325, 3845444069, 4043897329, 1905517169, 3631459288, 827548209, 356461077, 67897348, 3344078279, 593839651, 3277757891, 405286936, 2527147926, 84871685, 2595565466, 118033927, 305538066, 2157648768, 3795705826, 3945188843, 661212711, 2999812018, 1973414517, 152769033, 2208177539, 745822252, 439235610, 455947803, 1857215598, 1525593178, 2700827552, 1391895634, 994932283, 3596728278, 3016654259, 695947817, 3812548067, 795958831, 2224493444, 1408607827, 3513301457, 0, 3979133421, 543178784, 4229948412, 2982705585, 1542305371, 1790891114, 3410398667, 3201918910, 961245753, 1256100938, 1289001036, 1491644504, 3477767631, 3496721360, 4012557807, 2867154858, 4212583931, 1137018435, 1305975373, 861234739, 2241073541, 1171229253, 4178635257, 33948674, 2139225727, 1357946960, 1011120188, 2679776671, 2833468328, 1374921297, 2751356323, 1086357568, 2408187279, 2460827538, 2646352285, 944271416, 4110742005, 3168756668, 3066132406, 3665145818, 560153121, 271589392, 4279952895, 4077846003, 3530407890, 3444343245, 202643468, 322250259, 3962553324, 1608629855, 2543990167, 1154254916, 389623319, 3294073796, 2817676711, 2122513534, 1028094525, 1689045092, 1575467613, 422261273, 1939203699, 1621147744, 2174228865, 1339137615, 3699352540, 577127458, 712922154, 2427141008, 2290289544, 1187679302, 3995715566, 3100863416, 339486740, 3732514782, 1591917662, 186455563, 3681988059, 3762019296, 844522546, 978220090, 169743370, 1239126601, 101321734, 611076132, 1558493276, 3260915650, 3547250131, 2901361580, 1655096418, 2443721105, 2510565781, 3828863972, 2039214713, 3878868455, 3359869896, 928607799, 1840765549, 2374762893, 3580146133, 1322425422, 2850048425, 1823791212, 1459268694, 4094161908, 3928346602, 1706019429, 2056189050, 2934523822, 135794696, 3134549946, 2022240376, 628050469, 779246638, 472135708, 2800834470, 3032970164, 3327236038, 3894660072, 3715932637, 1956440180, 522272287, 1272813131, 3185336765, 2340818315, 2323976074, 1888542832, 1044544574, 3049550261, 1722469478, 1222152264, 50660867, 4127324150, 236067854, 1638122081, 895445557, 1475980887, 3117443513, 2257655686, 3243809217, 489110045, 2662934430, 3778599393, 4162055160, 2561878936, 288563729, 1773916777, 3648039385, 2391345038, 2493985684, 2612407707, 505560094, 2274497927, 3911240169, 3460925390, 1442818645, 678973480, 3749357023, 2358182796, 2717407649, 2306869641, 219617805, 3218761151, 3862026214, 1120306242, 1756942440, 1103331905, 2578459033, 762796589, 252780047, 2966125488, 1425844308, 3151392187, 372911126]; -const T4 = [1667474886, 2088535288, 2004326894, 2071694838, 4075949567, 1802223062, 1869591006, 3318043793, 808472672, 16843522, 1734846926, 724270422, 4278065639, 3621216949, 2880169549, 1987484396, 3402253711, 2189597983, 3385409673, 2105378810, 4210693615, 1499065266, 1195886990, 4042263547, 2913856577, 3570689971, 2728590687, 2947541573, 2627518243, 2762274643, 1920112356, 3233831835, 3082273397, 4261223649, 2475929149, 640051788, 909531756, 1061110142, 4160160501, 3435941763, 875846760, 2779116625, 3857003729, 4059105529, 1903268834, 3638064043, 825316194, 353713962, 67374088, 3351728789, 589522246, 3284360861, 404236336, 2526454071, 84217610, 2593830191, 117901582, 303183396, 2155911963, 3806477791, 3958056653, 656894286, 2998062463, 1970642922, 151591698, 2206440989, 741110872, 437923380, 454765878, 1852748508, 1515908788, 2694904667, 1381168804, 993742198, 3604373943, 3014905469, 690584402, 3823320797, 791638366, 2223281939, 1398011302, 3520161977, 0, 3991743681, 538992704, 4244381667, 2981218425, 1532751286, 1785380564, 3419096717, 3200178535, 960056178, 1246420628, 1280103576, 1482221744, 3486468741, 3503319995, 4025428677, 2863326543, 4227536621, 1128514950, 1296947098, 859002214, 2240123921, 1162203018, 4193849577, 33687044, 2139062782, 1347481760, 1010582648, 2678045221, 2829640523, 1364325282, 2745433693, 1077985408, 2408548869, 2459086143, 2644360225, 943212656, 4126475505, 3166494563, 3065430391, 3671750063, 555836226, 269496352, 4294908645, 4092792573, 3537006015, 3452783745, 202118168, 320025894, 3974901699, 1600119230, 2543297077, 1145359496, 387397934, 3301201811, 2812801621, 2122220284, 1027426170, 1684319432, 1566435258, 421079858, 1936954854, 1616945344, 2172753945, 1330631070, 3705438115, 572679748, 707427924, 2425400123, 2290647819, 1179044492, 4008585671, 3099120491, 336870440, 3739122087, 1583276732, 185277718, 3688593069, 3772791771, 842159716, 976899700, 168435220, 1229577106, 101059084, 606366792, 1549591736, 3267517855, 3553849021, 2897014595, 1650632388, 2442242105, 2509612081, 3840161747, 2038008818, 3890688725, 3368567691, 926374254, 1835907034, 2374863873, 3587531953, 1313788572, 2846482505, 1819063512, 1448540844, 4109633523, 3941213647, 1701162954, 2054852340, 2930698567, 134748176, 3132806511, 2021165296, 623210314, 774795868, 471606328, 2795958615, 3031746419, 3334885783, 3907527627, 3722280097, 1953799400, 522133822, 1263263126, 3183336545, 2341176845, 2324333839, 1886425312, 1044267644, 3048588401, 1718004428, 1212733584, 50529542, 4143317495, 235803164, 1633788866, 892690282, 1465383342, 3115962473, 2256965911, 3250673817, 488449850, 2661202215, 3789633753, 4177007595, 2560144171, 286339874, 1768537042, 3654906025, 2391705863, 2492770099, 2610673197, 505291324, 2273808917, 3924369609, 3469625735, 1431699370, 673740880, 3755965093, 2358021891, 2711746649, 2307489801, 218961690, 3217021541, 3873845719, 1111672452, 1751693520, 1094828930, 2576986153, 757954394, 252645662, 2964376443, 1414855848, 3149649517, 370555436]; -const T5 = [1374988112, 2118214995, 437757123, 975658646, 1001089995, 530400753, 2902087851, 1273168787, 540080725, 2910219766, 2295101073, 4110568485, 1340463100, 3307916247, 641025152, 3043140495, 3736164937, 632953703, 1172967064, 1576976609, 3274667266, 2169303058, 2370213795, 1809054150, 59727847, 361929877, 3211623147, 2505202138, 3569255213, 1484005843, 1239443753, 2395588676, 1975683434, 4102977912, 2572697195, 666464733, 3202437046, 4035489047, 3374361702, 2110667444, 1675577880, 3843699074, 2538681184, 1649639237, 2976151520, 3144396420, 4269907996, 4178062228, 1883793496, 2403728665, 2497604743, 1383856311, 2876494627, 1917518562, 3810496343, 1716890410, 3001755655, 800440835, 2261089178, 3543599269, 807962610, 599762354, 33778362, 3977675356, 2328828971, 2809771154, 4077384432, 1315562145, 1708848333, 101039829, 3509871135, 3299278474, 875451293, 2733856160, 92987698, 2767645557, 193195065, 1080094634, 1584504582, 3178106961, 1042385657, 2531067453, 3711829422, 1306967366, 2438237621, 1908694277, 67556463, 1615861247, 429456164, 3602770327, 2302690252, 1742315127, 2968011453, 126454664, 3877198648, 2043211483, 2709260871, 2084704233, 4169408201, 0, 159417987, 841739592, 504459436, 1817866830, 4245618683, 260388950, 1034867998, 908933415, 168810852, 1750902305, 2606453969, 607530554, 202008497, 2472011535, 3035535058, 463180190, 2160117071, 1641816226, 1517767529, 470948374, 3801332234, 3231722213, 1008918595, 303765277, 235474187, 4069246893, 766945465, 337553864, 1475418501, 2943682380, 4003061179, 2743034109, 4144047775, 1551037884, 1147550661, 1543208500, 2336434550, 3408119516, 3069049960, 3102011747, 3610369226, 1113818384, 328671808, 2227573024, 2236228733, 3535486456, 2935566865, 3341394285, 496906059, 3702665459, 226906860, 2009195472, 733156972, 2842737049, 294930682, 1206477858, 2835123396, 2700099354, 1451044056, 573804783, 2269728455, 3644379585, 2362090238, 2564033334, 2801107407, 2776292904, 3669462566, 1068351396, 742039012, 1350078989, 1784663195, 1417561698, 4136440770, 2430122216, 775550814, 2193862645, 2673705150, 1775276924, 1876241833, 3475313331, 3366754619, 270040487, 3902563182, 3678124923, 3441850377, 1851332852, 3969562369, 2203032232, 3868552805, 2868897406, 566021896, 4011190502, 3135740889, 1248802510, 3936291284, 699432150, 832877231, 708780849, 3332740144, 899835584, 1951317047, 4236429990, 3767586992, 866637845, 4043610186, 1106041591, 2144161806, 395441711, 1984812685, 1139781709, 3433712980, 3835036895, 2664543715, 1282050075, 3240894392, 1181045119, 2640243204, 25965917, 4203181171, 4211818798, 3009879386, 2463879762, 3910161971, 1842759443, 2597806476, 933301370, 1509430414, 3943906441, 3467192302, 3076639029, 3776767469, 2051518780, 2631065433, 1441952575, 404016761, 1942435775, 1408749034, 1610459739, 3745345300, 2017778566, 3400528769, 3110650942, 941896748, 3265478751, 371049330, 3168937228, 675039627, 4279080257, 967311729, 135050206, 3635733660, 1683407248, 2076935265, 3576870512, 1215061108, 3501741890]; -const T6 = [1347548327, 1400783205, 3273267108, 2520393566, 3409685355, 4045380933, 2880240216, 2471224067, 1428173050, 4138563181, 2441661558, 636813900, 4233094615, 3620022987, 2149987652, 2411029155, 1239331162, 1730525723, 2554718734, 3781033664, 46346101, 310463728, 2743944855, 3328955385, 3875770207, 2501218972, 3955191162, 3667219033, 768917123, 3545789473, 692707433, 1150208456, 1786102409, 2029293177, 1805211710, 3710368113, 3065962831, 401639597, 1724457132, 3028143674, 409198410, 2196052529, 1620529459, 1164071807, 3769721975, 2226875310, 486441376, 2499348523, 1483753576, 428819965, 2274680428, 3075636216, 598438867, 3799141122, 1474502543, 711349675, 129166120, 53458370, 2592523643, 2782082824, 4063242375, 2988687269, 3120694122, 1559041666, 730517276, 2460449204, 4042459122, 2706270690, 3446004468, 3573941694, 533804130, 2328143614, 2637442643, 2695033685, 839224033, 1973745387, 957055980, 2856345839, 106852767, 1371368976, 4181598602, 1033297158, 2933734917, 1179510461, 3046200461, 91341917, 1862534868, 4284502037, 605657339, 2547432937, 3431546947, 2003294622, 3182487618, 2282195339, 954669403, 3682191598, 1201765386, 3917234703, 3388507166, 0, 2198438022, 1211247597, 2887651696, 1315723890, 4227665663, 1443857720, 507358933, 657861945, 1678381017, 560487590, 3516619604, 975451694, 2970356327, 261314535, 3535072918, 2652609425, 1333838021, 2724322336, 1767536459, 370938394, 182621114, 3854606378, 1128014560, 487725847, 185469197, 2918353863, 3106780840, 3356761769, 2237133081, 1286567175, 3152976349, 4255350624, 2683765030, 3160175349, 3309594171, 878443390, 1988838185, 3704300486, 1756818940, 1673061617, 3403100636, 272786309, 1075025698, 545572369, 2105887268, 4174560061, 296679730, 1841768865, 1260232239, 4091327024, 3960309330, 3497509347, 1814803222, 2578018489, 4195456072, 575138148, 3299409036, 446754879, 3629546796, 4011996048, 3347532110, 3252238545, 4270639778, 915985419, 3483825537, 681933534, 651868046, 2755636671, 3828103837, 223377554, 2607439820, 1649704518, 3270937875, 3901806776, 1580087799, 4118987695, 3198115200, 2087309459, 2842678573, 3016697106, 1003007129, 2802849917, 1860738147, 2077965243, 164439672, 4100872472, 32283319, 2827177882, 1709610350, 2125135846, 136428751, 3874428392, 3652904859, 3460984630, 3572145929, 3593056380, 2939266226, 824852259, 818324884, 3224740454, 930369212, 2801566410, 2967507152, 355706840, 1257309336, 4148292826, 243256656, 790073846, 2373340630, 1296297904, 1422699085, 3756299780, 3818836405, 457992840, 3099667487, 2135319889, 77422314, 1560382517, 1945798516, 788204353, 1521706781, 1385356242, 870912086, 325965383, 2358957921, 2050466060, 2388260884, 2313884476, 4006521127, 901210569, 3990953189, 1014646705, 1503449823, 1062597235, 2031621326, 3212035895, 3931371469, 1533017514, 350174575, 2256028891, 2177544179, 1052338372, 741876788, 1606591296, 1914052035, 213705253, 2334669897, 1107234197, 1899603969, 3725069491, 2631447780, 2422494913, 1635502980, 1893020342, 1950903388, 1120974935]; -const T7 = [2807058932, 1699970625, 2764249623, 1586903591, 1808481195, 1173430173, 1487645946, 59984867, 4199882800, 1844882806, 1989249228, 1277555970, 3623636965, 3419915562, 1149249077, 2744104290, 1514790577, 459744698, 244860394, 3235995134, 1963115311, 4027744588, 2544078150, 4190530515, 1608975247, 2627016082, 2062270317, 1507497298, 2200818878, 567498868, 1764313568, 3359936201, 2305455554, 2037970062, 1047239e3, 1910319033, 1337376481, 2904027272, 2892417312, 984907214, 1243112415, 830661914, 861968209, 2135253587, 2011214180, 2927934315, 2686254721, 731183368, 1750626376, 4246310725, 1820824798, 4172763771, 3542330227, 48394827, 2404901663, 2871682645, 671593195, 3254988725, 2073724613, 145085239, 2280796200, 2779915199, 1790575107, 2187128086, 472615631, 3029510009, 4075877127, 3802222185, 4107101658, 3201631749, 1646252340, 4270507174, 1402811438, 1436590835, 3778151818, 3950355702, 3963161475, 4020912224, 2667994737, 273792366, 2331590177, 104699613, 95345982, 3175501286, 2377486676, 1560637892, 3564045318, 369057872, 4213447064, 3919042237, 1137477952, 2658625497, 1119727848, 2340947849, 1530455833, 4007360968, 172466556, 266959938, 516552836, 0, 2256734592, 3980931627, 1890328081, 1917742170, 4294704398, 945164165, 3575528878, 958871085, 3647212047, 2787207260, 1423022939, 775562294, 1739656202, 3876557655, 2530391278, 2443058075, 3310321856, 547512796, 1265195639, 437656594, 3121275539, 719700128, 3762502690, 387781147, 218828297, 3350065803, 2830708150, 2848461854, 428169201, 122466165, 3720081049, 1627235199, 648017665, 4122762354, 1002783846, 2117360635, 695634755, 3336358691, 4234721005, 4049844452, 3704280881, 2232435299, 574624663, 287343814, 612205898, 1039717051, 840019705, 2708326185, 793451934, 821288114, 1391201670, 3822090177, 376187827, 3113855344, 1224348052, 1679968233, 2361698556, 1058709744, 752375421, 2431590963, 1321699145, 3519142200, 2734591178, 188127444, 2177869557, 3727205754, 2384911031, 3215212461, 2648976442, 2450346104, 3432737375, 1180849278, 331544205, 3102249176, 4150144569, 2952102595, 2159976285, 2474404304, 766078933, 313773861, 2570832044, 2108100632, 1668212892, 3145456443, 2013908262, 418672217, 3070356634, 2594734927, 1852171925, 3867060991, 3473416636, 3907448597, 2614737639, 919489135, 164948639, 2094410160, 2997825956, 590424639, 2486224549, 1723872674, 3157750862, 3399941250, 3501252752, 3625268135, 2555048196, 3673637356, 1343127501, 4130281361, 3599595085, 2957853679, 1297403050, 81781910, 3051593425, 2283490410, 532201772, 1367295589, 3926170974, 895287692, 1953757831, 1093597963, 492483431, 3528626907, 1446242576, 1192455638, 1636604631, 209336225, 344873464, 1015671571, 669961897, 3375740769, 3857572124, 2973530695, 3747192018, 1933530610, 3464042516, 935293895, 3454686199, 2858115069, 1863638845, 3683022916, 4085369519, 3292445032, 875313188, 1080017571, 3279033885, 621591778, 1233856572, 2504130317, 24197544, 3017672716, 3835484340, 3247465558, 2220981195, 3060847922, 1551124588, 1463996600]; -const T8 = [4104605777, 1097159550, 396673818, 660510266, 2875968315, 2638606623, 4200115116, 3808662347, 821712160, 1986918061, 3430322568, 38544885, 3856137295, 718002117, 893681702, 1654886325, 2975484382, 3122358053, 3926825029, 4274053469, 796197571, 1290801793, 1184342925, 3556361835, 2405426947, 2459735317, 1836772287, 1381620373, 3196267988, 1948373848, 3764988233, 3385345166, 3263785589, 2390325492, 1480485785, 3111247143, 3780097726, 2293045232, 548169417, 3459953789, 3746175075, 439452389, 1362321559, 1400849762, 1685577905, 1806599355, 2174754046, 137073913, 1214797936, 1174215055, 3731654548, 2079897426, 1943217067, 1258480242, 529487843, 1437280870, 3945269170, 3049390895, 3313212038, 923313619, 679998e3, 3215307299, 57326082, 377642221, 3474729866, 2041877159, 133361907, 1776460110, 3673476453, 96392454, 878845905, 2801699524, 777231668, 4082475170, 2330014213, 4142626212, 2213296395, 1626319424, 1906247262, 1846563261, 562755902, 3708173718, 1040559837, 3871163981, 1418573201, 3294430577, 114585348, 1343618912, 2566595609, 3186202582, 1078185097, 3651041127, 3896688048, 2307622919, 425408743, 3371096953, 2081048481, 1108339068, 2216610296, 0, 2156299017, 736970802, 292596766, 1517440620, 251657213, 2235061775, 2933202493, 758720310, 265905162, 1554391400, 1532285339, 908999204, 174567692, 1474760595, 4002861748, 2610011675, 3234156416, 3693126241, 2001430874, 303699484, 2478443234, 2687165888, 585122620, 454499602, 151849742, 2345119218, 3064510765, 514443284, 4044981591, 1963412655, 2581445614, 2137062819, 19308535, 1928707164, 1715193156, 4219352155, 1126790795, 600235211, 3992742070, 3841024952, 836553431, 1669664834, 2535604243, 3323011204, 1243905413, 3141400786, 4180808110, 698445255, 2653899549, 2989552604, 2253581325, 3252932727, 3004591147, 1891211689, 2487810577, 3915653703, 4237083816, 4030667424, 2100090966, 865136418, 1229899655, 953270745, 3399679628, 3557504664, 4118925222, 2061379749, 3079546586, 2915017791, 983426092, 2022837584, 1607244650, 2118541908, 2366882550, 3635996816, 972512814, 3283088770, 1568718495, 3499326569, 3576539503, 621982671, 2895723464, 410887952, 2623762152, 1002142683, 645401037, 1494807662, 2595684844, 1335535747, 2507040230, 4293295786, 3167684641, 367585007, 3885750714, 1865862730, 2668221674, 2960971305, 2763173681, 1059270954, 2777952454, 2724642869, 1320957812, 2194319100, 2429595872, 2815956275, 77089521, 3973773121, 3444575871, 2448830231, 1305906550, 4021308739, 2857194700, 2516901860, 3518358430, 1787304780, 740276417, 1699839814, 1592394909, 2352307457, 2272556026, 188821243, 1729977011, 3687994002, 274084841, 3594982253, 3613494426, 2701949495, 4162096729, 322734571, 2837966542, 1640576439, 484830689, 1202797690, 3537852828, 4067639125, 349075736, 3342319475, 4157467219, 4255800159, 1030690015, 1155237496, 2951971274, 1757691577, 607398968, 2738905026, 499347990, 3794078908, 1011452712, 227885567, 2818666809, 213114376, 3034881240, 1455525988, 3414450555, 850817237, 1817998408, 3092726480]; -const U1 = [0, 235474187, 470948374, 303765277, 941896748, 908933415, 607530554, 708780849, 1883793496, 2118214995, 1817866830, 1649639237, 1215061108, 1181045119, 1417561698, 1517767529, 3767586992, 4003061179, 4236429990, 4069246893, 3635733660, 3602770327, 3299278474, 3400528769, 2430122216, 2664543715, 2362090238, 2193862645, 2835123396, 2801107407, 3035535058, 3135740889, 3678124923, 3576870512, 3341394285, 3374361702, 3810496343, 3977675356, 4279080257, 4043610186, 2876494627, 2776292904, 3076639029, 3110650942, 2472011535, 2640243204, 2403728665, 2169303058, 1001089995, 899835584, 666464733, 699432150, 59727847, 226906860, 530400753, 294930682, 1273168787, 1172967064, 1475418501, 1509430414, 1942435775, 2110667444, 1876241833, 1641816226, 2910219766, 2743034109, 2976151520, 3211623147, 2505202138, 2606453969, 2302690252, 2269728455, 3711829422, 3543599269, 3240894392, 3475313331, 3843699074, 3943906441, 4178062228, 4144047775, 1306967366, 1139781709, 1374988112, 1610459739, 1975683434, 2076935265, 1775276924, 1742315127, 1034867998, 866637845, 566021896, 800440835, 92987698, 193195065, 429456164, 395441711, 1984812685, 2017778566, 1784663195, 1683407248, 1315562145, 1080094634, 1383856311, 1551037884, 101039829, 135050206, 437757123, 337553864, 1042385657, 807962610, 573804783, 742039012, 2531067453, 2564033334, 2328828971, 2227573024, 2935566865, 2700099354, 3001755655, 3168937228, 3868552805, 3902563182, 4203181171, 4102977912, 3736164937, 3501741890, 3265478751, 3433712980, 1106041591, 1340463100, 1576976609, 1408749034, 2043211483, 2009195472, 1708848333, 1809054150, 832877231, 1068351396, 766945465, 599762354, 159417987, 126454664, 361929877, 463180190, 2709260871, 2943682380, 3178106961, 3009879386, 2572697195, 2538681184, 2236228733, 2336434550, 3509871135, 3745345300, 3441850377, 3274667266, 3910161971, 3877198648, 4110568485, 4211818798, 2597806476, 2497604743, 2261089178, 2295101073, 2733856160, 2902087851, 3202437046, 2968011453, 3936291284, 3835036895, 4136440770, 4169408201, 3535486456, 3702665459, 3467192302, 3231722213, 2051518780, 1951317047, 1716890410, 1750902305, 1113818384, 1282050075, 1584504582, 1350078989, 168810852, 67556463, 371049330, 404016761, 841739592, 1008918595, 775550814, 540080725, 3969562369, 3801332234, 4035489047, 4269907996, 3569255213, 3669462566, 3366754619, 3332740144, 2631065433, 2463879762, 2160117071, 2395588676, 2767645557, 2868897406, 3102011747, 3069049960, 202008497, 33778362, 270040487, 504459436, 875451293, 975658646, 675039627, 641025152, 2084704233, 1917518562, 1615861247, 1851332852, 1147550661, 1248802510, 1484005843, 1451044056, 933301370, 967311729, 733156972, 632953703, 260388950, 25965917, 328671808, 496906059, 1206477858, 1239443753, 1543208500, 1441952575, 2144161806, 1908694277, 1675577880, 1842759443, 3610369226, 3644379585, 3408119516, 3307916247, 4011190502, 3776767469, 4077384432, 4245618683, 2809771154, 2842737049, 3144396420, 3043140495, 2673705150, 2438237621, 2203032232, 2370213795]; -const U2 = [0, 185469197, 370938394, 487725847, 741876788, 657861945, 975451694, 824852259, 1483753576, 1400783205, 1315723890, 1164071807, 1950903388, 2135319889, 1649704518, 1767536459, 2967507152, 3152976349, 2801566410, 2918353863, 2631447780, 2547432937, 2328143614, 2177544179, 3901806776, 3818836405, 4270639778, 4118987695, 3299409036, 3483825537, 3535072918, 3652904859, 2077965243, 1893020342, 1841768865, 1724457132, 1474502543, 1559041666, 1107234197, 1257309336, 598438867, 681933534, 901210569, 1052338372, 261314535, 77422314, 428819965, 310463728, 3409685355, 3224740454, 3710368113, 3593056380, 3875770207, 3960309330, 4045380933, 4195456072, 2471224067, 2554718734, 2237133081, 2388260884, 3212035895, 3028143674, 2842678573, 2724322336, 4138563181, 4255350624, 3769721975, 3955191162, 3667219033, 3516619604, 3431546947, 3347532110, 2933734917, 2782082824, 3099667487, 3016697106, 2196052529, 2313884476, 2499348523, 2683765030, 1179510461, 1296297904, 1347548327, 1533017514, 1786102409, 1635502980, 2087309459, 2003294622, 507358933, 355706840, 136428751, 53458370, 839224033, 957055980, 605657339, 790073846, 2373340630, 2256028891, 2607439820, 2422494913, 2706270690, 2856345839, 3075636216, 3160175349, 3573941694, 3725069491, 3273267108, 3356761769, 4181598602, 4063242375, 4011996048, 3828103837, 1033297158, 915985419, 730517276, 545572369, 296679730, 446754879, 129166120, 213705253, 1709610350, 1860738147, 1945798516, 2029293177, 1239331162, 1120974935, 1606591296, 1422699085, 4148292826, 4233094615, 3781033664, 3931371469, 3682191598, 3497509347, 3446004468, 3328955385, 2939266226, 2755636671, 3106780840, 2988687269, 2198438022, 2282195339, 2501218972, 2652609425, 1201765386, 1286567175, 1371368976, 1521706781, 1805211710, 1620529459, 2105887268, 1988838185, 533804130, 350174575, 164439672, 46346101, 870912086, 954669403, 636813900, 788204353, 2358957921, 2274680428, 2592523643, 2441661558, 2695033685, 2880240216, 3065962831, 3182487618, 3572145929, 3756299780, 3270937875, 3388507166, 4174560061, 4091327024, 4006521127, 3854606378, 1014646705, 930369212, 711349675, 560487590, 272786309, 457992840, 106852767, 223377554, 1678381017, 1862534868, 1914052035, 2031621326, 1211247597, 1128014560, 1580087799, 1428173050, 32283319, 182621114, 401639597, 486441376, 768917123, 651868046, 1003007129, 818324884, 1503449823, 1385356242, 1333838021, 1150208456, 1973745387, 2125135846, 1673061617, 1756818940, 2970356327, 3120694122, 2802849917, 2887651696, 2637442643, 2520393566, 2334669897, 2149987652, 3917234703, 3799141122, 4284502037, 4100872472, 3309594171, 3460984630, 3545789473, 3629546796, 2050466060, 1899603969, 1814803222, 1730525723, 1443857720, 1560382517, 1075025698, 1260232239, 575138148, 692707433, 878443390, 1062597235, 243256656, 91341917, 409198410, 325965383, 3403100636, 3252238545, 3704300486, 3620022987, 3874428392, 3990953189, 4042459122, 4227665663, 2460449204, 2578018489, 2226875310, 2411029155, 3198115200, 3046200461, 2827177882, 2743944855]; -const U3 = [0, 218828297, 437656594, 387781147, 875313188, 958871085, 775562294, 590424639, 1750626376, 1699970625, 1917742170, 2135253587, 1551124588, 1367295589, 1180849278, 1265195639, 3501252752, 3720081049, 3399941250, 3350065803, 3835484340, 3919042237, 4270507174, 4085369519, 3102249176, 3051593425, 2734591178, 2952102595, 2361698556, 2177869557, 2530391278, 2614737639, 3145456443, 3060847922, 2708326185, 2892417312, 2404901663, 2187128086, 2504130317, 2555048196, 3542330227, 3727205754, 3375740769, 3292445032, 3876557655, 3926170974, 4246310725, 4027744588, 1808481195, 1723872674, 1910319033, 2094410160, 1608975247, 1391201670, 1173430173, 1224348052, 59984867, 244860394, 428169201, 344873464, 935293895, 984907214, 766078933, 547512796, 1844882806, 1627235199, 2011214180, 2062270317, 1507497298, 1423022939, 1137477952, 1321699145, 95345982, 145085239, 532201772, 313773861, 830661914, 1015671571, 731183368, 648017665, 3175501286, 2957853679, 2807058932, 2858115069, 2305455554, 2220981195, 2474404304, 2658625497, 3575528878, 3625268135, 3473416636, 3254988725, 3778151818, 3963161475, 4213447064, 4130281361, 3599595085, 3683022916, 3432737375, 3247465558, 3802222185, 4020912224, 4172763771, 4122762354, 3201631749, 3017672716, 2764249623, 2848461854, 2331590177, 2280796200, 2431590963, 2648976442, 104699613, 188127444, 472615631, 287343814, 840019705, 1058709744, 671593195, 621591778, 1852171925, 1668212892, 1953757831, 2037970062, 1514790577, 1463996600, 1080017571, 1297403050, 3673637356, 3623636965, 3235995134, 3454686199, 4007360968, 3822090177, 4107101658, 4190530515, 2997825956, 3215212461, 2830708150, 2779915199, 2256734592, 2340947849, 2627016082, 2443058075, 172466556, 122466165, 273792366, 492483431, 1047239e3, 861968209, 612205898, 695634755, 1646252340, 1863638845, 2013908262, 1963115311, 1446242576, 1530455833, 1277555970, 1093597963, 1636604631, 1820824798, 2073724613, 1989249228, 1436590835, 1487645946, 1337376481, 1119727848, 164948639, 81781910, 331544205, 516552836, 1039717051, 821288114, 669961897, 719700128, 2973530695, 3157750862, 2871682645, 2787207260, 2232435299, 2283490410, 2667994737, 2450346104, 3647212047, 3564045318, 3279033885, 3464042516, 3980931627, 3762502690, 4150144569, 4199882800, 3070356634, 3121275539, 2904027272, 2686254721, 2200818878, 2384911031, 2570832044, 2486224549, 3747192018, 3528626907, 3310321856, 3359936201, 3950355702, 3867060991, 4049844452, 4234721005, 1739656202, 1790575107, 2108100632, 1890328081, 1402811438, 1586903591, 1233856572, 1149249077, 266959938, 48394827, 369057872, 418672217, 1002783846, 919489135, 567498868, 752375421, 209336225, 24197544, 376187827, 459744698, 945164165, 895287692, 574624663, 793451934, 1679968233, 1764313568, 2117360635, 1933530610, 1343127501, 1560637892, 1243112415, 1192455638, 3704280881, 3519142200, 3336358691, 3419915562, 3907448597, 3857572124, 4075877127, 4294704398, 3029510009, 3113855344, 2927934315, 2744104290, 2159976285, 2377486676, 2594734927, 2544078150]; -const U4 = [0, 151849742, 303699484, 454499602, 607398968, 758720310, 908999204, 1059270954, 1214797936, 1097159550, 1517440620, 1400849762, 1817998408, 1699839814, 2118541908, 2001430874, 2429595872, 2581445614, 2194319100, 2345119218, 3034881240, 3186202582, 2801699524, 2951971274, 3635996816, 3518358430, 3399679628, 3283088770, 4237083816, 4118925222, 4002861748, 3885750714, 1002142683, 850817237, 698445255, 548169417, 529487843, 377642221, 227885567, 77089521, 1943217067, 2061379749, 1640576439, 1757691577, 1474760595, 1592394909, 1174215055, 1290801793, 2875968315, 2724642869, 3111247143, 2960971305, 2405426947, 2253581325, 2638606623, 2487810577, 3808662347, 3926825029, 4044981591, 4162096729, 3342319475, 3459953789, 3576539503, 3693126241, 1986918061, 2137062819, 1685577905, 1836772287, 1381620373, 1532285339, 1078185097, 1229899655, 1040559837, 923313619, 740276417, 621982671, 439452389, 322734571, 137073913, 19308535, 3871163981, 4021308739, 4104605777, 4255800159, 3263785589, 3414450555, 3499326569, 3651041127, 2933202493, 2815956275, 3167684641, 3049390895, 2330014213, 2213296395, 2566595609, 2448830231, 1305906550, 1155237496, 1607244650, 1455525988, 1776460110, 1626319424, 2079897426, 1928707164, 96392454, 213114376, 396673818, 514443284, 562755902, 679998e3, 865136418, 983426092, 3708173718, 3557504664, 3474729866, 3323011204, 4180808110, 4030667424, 3945269170, 3794078908, 2507040230, 2623762152, 2272556026, 2390325492, 2975484382, 3092726480, 2738905026, 2857194700, 3973773121, 3856137295, 4274053469, 4157467219, 3371096953, 3252932727, 3673476453, 3556361835, 2763173681, 2915017791, 3064510765, 3215307299, 2156299017, 2307622919, 2459735317, 2610011675, 2081048481, 1963412655, 1846563261, 1729977011, 1480485785, 1362321559, 1243905413, 1126790795, 878845905, 1030690015, 645401037, 796197571, 274084841, 425408743, 38544885, 188821243, 3613494426, 3731654548, 3313212038, 3430322568, 4082475170, 4200115116, 3780097726, 3896688048, 2668221674, 2516901860, 2366882550, 2216610296, 3141400786, 2989552604, 2837966542, 2687165888, 1202797690, 1320957812, 1437280870, 1554391400, 1669664834, 1787304780, 1906247262, 2022837584, 265905162, 114585348, 499347990, 349075736, 736970802, 585122620, 972512814, 821712160, 2595684844, 2478443234, 2293045232, 2174754046, 3196267988, 3079546586, 2895723464, 2777952454, 3537852828, 3687994002, 3234156416, 3385345166, 4142626212, 4293295786, 3841024952, 3992742070, 174567692, 57326082, 410887952, 292596766, 777231668, 660510266, 1011452712, 893681702, 1108339068, 1258480242, 1343618912, 1494807662, 1715193156, 1865862730, 1948373848, 2100090966, 2701949495, 2818666809, 3004591147, 3122358053, 2235061775, 2352307457, 2535604243, 2653899549, 3915653703, 3764988233, 4219352155, 4067639125, 3444575871, 3294430577, 3746175075, 3594982253, 836553431, 953270745, 600235211, 718002117, 367585007, 484830689, 133361907, 251657213, 2041877159, 1891211689, 1806599355, 1654886325, 1568718495, 1418573201, 1335535747, 1184342925]; -function convertToInt32(bytes2) { - const result = []; - for (let i = 0; i < bytes2.length; i += 4) { - result.push(bytes2[i] << 24 | bytes2[i + 1] << 16 | bytes2[i + 2] << 8 | bytes2[i + 3]); + /** + * Returns a new [[FixedNumber]] with the result of %%other%% subtracted + * from %%this%%, ignoring overflow. + */ + subUnsafe(other) { + return __privateMethod(this, _FixedNumber_instances, sub_fn).call(this, other); } - return result; -} -class AES { - get key() { - return __classPrivateFieldGet$3(this, _AES_key, "f").slice(); + /** + * Returns a new [[FixedNumber]] with the result of %%other%% subtracted + * from %%this%%. A [[NumericFaultError]] is thrown if overflow + * occurs. + */ + sub(other) { + return __privateMethod(this, _FixedNumber_instances, sub_fn).call(this, other, "sub"); } - constructor(key) { - _AES_key.set(this, void 0); - _AES_Kd.set(this, void 0); - _AES_Ke.set(this, void 0); - if (!(this instanceof AES)) { - throw Error("AES must be instanitated with `new`"); - } - __classPrivateFieldSet$2(this, _AES_key, new Uint8Array(key), "f"); - const rounds = numberOfRounds[this.key.length]; - if (rounds == null) { - throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)"); - } - __classPrivateFieldSet$2(this, _AES_Ke, [], "f"); - __classPrivateFieldSet$2(this, _AES_Kd, [], "f"); - for (let i = 0; i <= rounds; i++) { - __classPrivateFieldGet$3(this, _AES_Ke, "f").push([0, 0, 0, 0]); - __classPrivateFieldGet$3(this, _AES_Kd, "f").push([0, 0, 0, 0]); - } - const roundKeyCount = (rounds + 1) * 4; - const KC = this.key.length / 4; - const tk2 = convertToInt32(this.key); - let index2; - for (let i = 0; i < KC; i++) { - index2 = i >> 2; - __classPrivateFieldGet$3(this, _AES_Ke, "f")[index2][i % 4] = tk2[i]; - __classPrivateFieldGet$3(this, _AES_Kd, "f")[rounds - index2][i % 4] = tk2[i]; - } - let rconpointer = 0; - let t2 = KC, tt; - while (t2 < roundKeyCount) { - tt = tk2[KC - 1]; - tk2[0] ^= S[tt >> 16 & 255] << 24 ^ S[tt >> 8 & 255] << 16 ^ S[tt & 255] << 8 ^ S[tt >> 24 & 255] ^ rcon[rconpointer] << 24; - rconpointer += 1; - if (KC != 8) { - for (let i2 = 1; i2 < KC; i2++) { - tk2[i2] ^= tk2[i2 - 1]; - } - } else { - for (let i2 = 1; i2 < KC / 2; i2++) { - tk2[i2] ^= tk2[i2 - 1]; - } - tt = tk2[KC / 2 - 1]; - tk2[KC / 2] ^= S[tt & 255] ^ S[tt >> 8 & 255] << 8 ^ S[tt >> 16 & 255] << 16 ^ S[tt >> 24 & 255] << 24; - for (let i2 = KC / 2 + 1; i2 < KC; i2++) { - tk2[i2] ^= tk2[i2 - 1]; - } - } - let i = 0, r2, c2; - while (i < KC && t2 < roundKeyCount) { - r2 = t2 >> 2; - c2 = t2 % 4; - __classPrivateFieldGet$3(this, _AES_Ke, "f")[r2][c2] = tk2[i]; - __classPrivateFieldGet$3(this, _AES_Kd, "f")[rounds - r2][c2] = tk2[i++]; - t2++; - } - } - for (let r2 = 1; r2 < rounds; r2++) { - for (let c2 = 0; c2 < 4; c2++) { - tt = __classPrivateFieldGet$3(this, _AES_Kd, "f")[r2][c2]; - __classPrivateFieldGet$3(this, _AES_Kd, "f")[r2][c2] = U1[tt >> 24 & 255] ^ U2[tt >> 16 & 255] ^ U3[tt >> 8 & 255] ^ U4[tt & 255]; - } - } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% multiplied + * by %%other%%, ignoring overflow and underflow (precision loss). + */ + mulUnsafe(other) { + return __privateMethod(this, _FixedNumber_instances, mul_fn).call(this, other); } - encrypt(plaintext) { - if (plaintext.length != 16) { - throw new TypeError("invalid plaintext size (must be 16 bytes)"); - } - const rounds = __classPrivateFieldGet$3(this, _AES_Ke, "f").length - 1; - const a2 = [0, 0, 0, 0]; - let t2 = convertToInt32(plaintext); - for (let i = 0; i < 4; i++) { - t2[i] ^= __classPrivateFieldGet$3(this, _AES_Ke, "f")[0][i]; - } - for (let r2 = 1; r2 < rounds; r2++) { - for (let i = 0; i < 4; i++) { - a2[i] = T1[t2[i] >> 24 & 255] ^ T2[t2[(i + 1) % 4] >> 16 & 255] ^ T3[t2[(i + 2) % 4] >> 8 & 255] ^ T4[t2[(i + 3) % 4] & 255] ^ __classPrivateFieldGet$3(this, _AES_Ke, "f")[r2][i]; - } - t2 = a2.slice(); - } - const result = new Uint8Array(16); - let tt = 0; - for (let i = 0; i < 4; i++) { - tt = __classPrivateFieldGet$3(this, _AES_Ke, "f")[rounds][i]; - result[4 * i] = (S[t2[i] >> 24 & 255] ^ tt >> 24) & 255; - result[4 * i + 1] = (S[t2[(i + 1) % 4] >> 16 & 255] ^ tt >> 16) & 255; - result[4 * i + 2] = (S[t2[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; - result[4 * i + 3] = (S[t2[(i + 3) % 4] & 255] ^ tt) & 255; - } - return result; + /** + * Returns a new [[FixedNumber]] with the result of %%this%% multiplied + * by %%other%%. A [[NumericFaultError]] is thrown if overflow + * occurs. + */ + mul(other) { + return __privateMethod(this, _FixedNumber_instances, mul_fn).call(this, other, "mul"); } - decrypt(ciphertext) { - if (ciphertext.length != 16) { - throw new TypeError("invalid ciphertext size (must be 16 bytes)"); - } - const rounds = __classPrivateFieldGet$3(this, _AES_Kd, "f").length - 1; - const a2 = [0, 0, 0, 0]; - let t2 = convertToInt32(ciphertext); - for (let i = 0; i < 4; i++) { - t2[i] ^= __classPrivateFieldGet$3(this, _AES_Kd, "f")[0][i]; - } - for (let r2 = 1; r2 < rounds; r2++) { - for (let i = 0; i < 4; i++) { - a2[i] = T5[t2[i] >> 24 & 255] ^ T6[t2[(i + 3) % 4] >> 16 & 255] ^ T7[t2[(i + 2) % 4] >> 8 & 255] ^ T8[t2[(i + 1) % 4] & 255] ^ __classPrivateFieldGet$3(this, _AES_Kd, "f")[r2][i]; - } - t2 = a2.slice(); - } - const result = new Uint8Array(16); - let tt = 0; - for (let i = 0; i < 4; i++) { - tt = __classPrivateFieldGet$3(this, _AES_Kd, "f")[rounds][i]; - result[4 * i] = (Si[t2[i] >> 24 & 255] ^ tt >> 24) & 255; - result[4 * i + 1] = (Si[t2[(i + 3) % 4] >> 16 & 255] ^ tt >> 16) & 255; - result[4 * i + 2] = (Si[t2[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; - result[4 * i + 3] = (Si[t2[(i + 1) % 4] & 255] ^ tt) & 255; - } - return result; + /** + * Returns a new [[FixedNumber]] with the result of %%this%% multiplied + * by %%other%%. A [[NumericFaultError]] is thrown if overflow + * occurs or if underflow (precision loss) occurs. + */ + mulSignal(other) { + __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, other); + const value = __privateGet(this, _val) * __privateGet(other, _val); + assert(value % __privateGet(this, _tens) === BN_0$8, "precision lost during signalling mul", "NUMERIC_FAULT", { + operation: "mulSignal", + fault: "underflow", + value: this + }); + return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, value / __privateGet(this, _tens), "mulSignal"); + } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% divided + * by %%other%%, ignoring underflow (precision loss). A + * [[NumericFaultError]] is thrown if overflow occurs. + */ + divUnsafe(other) { + return __privateMethod(this, _FixedNumber_instances, div_fn).call(this, other); + } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% divided + * by %%other%%, ignoring underflow (precision loss). A + * [[NumericFaultError]] is thrown if overflow occurs. + */ + div(other) { + return __privateMethod(this, _FixedNumber_instances, div_fn).call(this, other, "div"); } -} -_AES_key = /* @__PURE__ */ new WeakMap(), _AES_Kd = /* @__PURE__ */ new WeakMap(), _AES_Ke = /* @__PURE__ */ new WeakMap(); -class ModeOfOperation { - constructor(name2, key, cls) { - if (cls && !(this instanceof cls)) { - throw new Error(`${name2} must be instantiated with "new"`); - } - Object.defineProperties(this, { - aes: { enumerable: true, value: new AES(key) }, - name: { enumerable: true, value: name2 } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% divided + * by %%other%%. A [[NumericFaultError]] is thrown if underflow + * (precision loss) occurs. + */ + divSignal(other) { + assert(__privateGet(other, _val) !== BN_0$8, "division by zero", "NUMERIC_FAULT", { + operation: "div", + fault: "divide-by-zero", + value: this + }); + __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, other); + const value = __privateGet(this, _val) * __privateGet(this, _tens); + assert(value % __privateGet(other, _val) === BN_0$8, "precision lost during signalling div", "NUMERIC_FAULT", { + operation: "divSignal", + fault: "underflow", + value: this }); + return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, value / __privateGet(other, _val), "divSignal"); } -} -var __classPrivateFieldSet$1 = function(receiver, state, value, kind, f2) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value; -}; -var __classPrivateFieldGet$2 = function(receiver, state, kind, f2) { - if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver); -}; -var _CBC_iv, _CBC_lastBlock; -class CBC extends ModeOfOperation { - constructor(key, iv) { - super("ECC", key, CBC); - _CBC_iv.set(this, void 0); - _CBC_lastBlock.set(this, void 0); - if (iv) { - if (iv.length % 16) { - throw new TypeError("invalid iv size (must be 16 bytes)"); - } - __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(iv), "f"); - } else { - __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(16), "f"); + /** + * Returns a comparison result between %%this%% and %%other%%. + * + * This is suitable for use in sorting, where ``-1`` implies %%this%% + * is smaller, ``1`` implies %%this%% is larger and ``0`` implies + * both are equal. + */ + cmp(other) { + let a2 = this.value, b2 = other.value; + const delta = this.decimals - other.decimals; + if (delta > 0) { + b2 *= getTens(delta); + } else if (delta < 0) { + a2 *= getTens(-delta); } - __classPrivateFieldSet$1(this, _CBC_lastBlock, this.iv, "f"); - } - get iv() { - return new Uint8Array(__classPrivateFieldGet$2(this, _CBC_iv, "f")); - } - encrypt(plaintext) { - if (plaintext.length % 16) { - throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)"); + if (a2 < b2) { + return -1; } - const ciphertext = new Uint8Array(plaintext.length); - for (let i = 0; i < plaintext.length; i += 16) { - for (let j2 = 0; j2 < 16; j2++) { - __classPrivateFieldGet$2(this, _CBC_lastBlock, "f")[j2] ^= plaintext[i + j2]; - } - __classPrivateFieldSet$1(this, _CBC_lastBlock, this.aes.encrypt(__classPrivateFieldGet$2(this, _CBC_lastBlock, "f")), "f"); - ciphertext.set(__classPrivateFieldGet$2(this, _CBC_lastBlock, "f"), i); + if (a2 > b2) { + return 1; } - return ciphertext; + return 0; } - decrypt(ciphertext) { - if (ciphertext.length % 16) { - throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)"); - } - const plaintext = new Uint8Array(ciphertext.length); - for (let i = 0; i < ciphertext.length; i += 16) { - const block = this.aes.decrypt(ciphertext.subarray(i, i + 16)); - for (let j2 = 0; j2 < 16; j2++) { - plaintext[i + j2] = block[j2] ^ __classPrivateFieldGet$2(this, _CBC_lastBlock, "f")[j2]; - __classPrivateFieldGet$2(this, _CBC_lastBlock, "f")[j2] = ciphertext[i + j2]; - } - } - return plaintext; + /** + * Returns true if %%other%% is equal to %%this%%. + */ + eq(other) { + return this.cmp(other) === 0; } -} -_CBC_iv = /* @__PURE__ */ new WeakMap(), _CBC_lastBlock = /* @__PURE__ */ new WeakMap(); -var __classPrivateFieldSet = function(receiver, state, value, kind, f2) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value; -}; -var __classPrivateFieldGet$1 = function(receiver, state, kind, f2) { - if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver); -}; -var _CTR_remaining, _CTR_remainingIndex, _CTR_counter; -class CTR extends ModeOfOperation { - constructor(key, initialValue) { - super("CTR", key, CTR); - _CTR_remaining.set(this, void 0); - _CTR_remainingIndex.set(this, void 0); - _CTR_counter.set(this, void 0); - __classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), "f"); - __classPrivateFieldGet$1(this, _CTR_counter, "f").fill(0); - __classPrivateFieldSet(this, _CTR_remaining, __classPrivateFieldGet$1(this, _CTR_counter, "f"), "f"); - __classPrivateFieldSet(this, _CTR_remainingIndex, 16, "f"); - if (initialValue == null) { - initialValue = 1; - } - if (typeof initialValue === "number") { - this.setCounterValue(initialValue); - } else { - this.setCounterBytes(initialValue); - } + /** + * Returns true if %%other%% is less than to %%this%%. + */ + lt(other) { + return this.cmp(other) < 0; } - get counter() { - return new Uint8Array(__classPrivateFieldGet$1(this, _CTR_counter, "f")); + /** + * Returns true if %%other%% is less than or equal to %%this%%. + */ + lte(other) { + return this.cmp(other) <= 0; } - setCounterValue(value) { - if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) { - throw new TypeError("invalid counter initial integer value"); - } - for (let index2 = 15; index2 >= 0; --index2) { - __classPrivateFieldGet$1(this, _CTR_counter, "f")[index2] = value % 256; - value = Math.floor(value / 256); - } + /** + * Returns true if %%other%% is greater than to %%this%%. + */ + gt(other) { + return this.cmp(other) > 0; } - setCounterBytes(value) { - if (value.length !== 16) { - throw new TypeError("invalid counter initial Uint8Array value length"); - } - __classPrivateFieldGet$1(this, _CTR_counter, "f").set(value); + /** + * Returns true if %%other%% is greater than or equal to %%this%%. + */ + gte(other) { + return this.cmp(other) >= 0; } - increment() { - for (let i = 15; i >= 0; i--) { - if (__classPrivateFieldGet$1(this, _CTR_counter, "f")[i] === 255) { - __classPrivateFieldGet$1(this, _CTR_counter, "f")[i] = 0; - } else { - __classPrivateFieldGet$1(this, _CTR_counter, "f")[i]++; - break; - } + /** + * Returns a new [[FixedNumber]] which is the largest **integer** + * that is less than or equal to %%this%%. + * + * The decimal component of the result will always be ``0``. + */ + floor() { + let val = __privateGet(this, _val); + if (__privateGet(this, _val) < BN_0$8) { + val -= __privateGet(this, _tens) - BN_1$4; } + val = __privateGet(this, _val) / __privateGet(this, _tens) * __privateGet(this, _tens); + return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, val, "floor"); } - encrypt(plaintext) { - var _a2, _b2; - const crypttext = new Uint8Array(plaintext); - for (let i = 0; i < crypttext.length; i++) { - if (__classPrivateFieldGet$1(this, _CTR_remainingIndex, "f") === 16) { - __classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet$1(this, _CTR_counter, "f")), "f"); - __classPrivateFieldSet(this, _CTR_remainingIndex, 0, "f"); - this.increment(); - } - crypttext[i] ^= __classPrivateFieldGet$1(this, _CTR_remaining, "f")[__classPrivateFieldSet(this, _CTR_remainingIndex, (_b2 = __classPrivateFieldGet$1(this, _CTR_remainingIndex, "f"), _a2 = _b2++, _b2), "f"), _a2]; + /** + * Returns a new [[FixedNumber]] which is the smallest **integer** + * that is greater than or equal to %%this%%. + * + * The decimal component of the result will always be ``0``. + */ + ceiling() { + let val = __privateGet(this, _val); + if (__privateGet(this, _val) > BN_0$8) { + val += __privateGet(this, _tens) - BN_1$4; } - return crypttext; - } - decrypt(ciphertext) { - return this.encrypt(ciphertext); + val = __privateGet(this, _val) / __privateGet(this, _tens) * __privateGet(this, _tens); + return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, val, "ceiling"); } -} -_CTR_remaining = /* @__PURE__ */ new WeakMap(), _CTR_remainingIndex = /* @__PURE__ */ new WeakMap(), _CTR_counter = /* @__PURE__ */ new WeakMap(); -function pkcs7Strip(data) { - if (data.length < 16) { - throw new TypeError("PKCS#7 invalid length"); + /** + * Returns a new [[FixedNumber]] with the decimal component + * rounded up on ties at %%decimals%% places. + */ + round(decimals) { + if (decimals == null) { + decimals = 0; + } + if (decimals >= this.decimals) { + return this; + } + const delta = this.decimals - decimals; + const bump = BN_5 * getTens(delta - 1); + let value = this.value + bump; + const tens = getTens(delta); + value = value / tens * tens; + checkValue(value, __privateGet(this, _format), "round"); + return new _FixedNumber(_guard$5, value, __privateGet(this, _format)); } - const padder = data[data.length - 1]; - if (padder > 16) { - throw new TypeError("PKCS#7 padding byte out of range"); + /** + * Returns true if %%this%% is equal to ``0``. + */ + isZero() { + return __privateGet(this, _val) === BN_0$8; } - const length = data.length - padder; - for (let i = 0; i < padder; i++) { - if (data[length + i] !== padder) { - throw new TypeError("PKCS#7 invalid padding byte"); - } + /** + * Returns true if %%this%% is less than ``0``. + */ + isNegative() { + return __privateGet(this, _val) < BN_0$8; } - return new Uint8Array(data.subarray(0, length)); -} -function looseArrayify(hexString) { - if (typeof hexString === "string" && !hexString.startsWith("0x")) { - hexString = "0x" + hexString; + /** + * Returns the string representation of %%this%%. + */ + toString() { + return this._value; } - return getBytesCopy(hexString); -} -function zpad$1(value, length) { - value = String(value); - while (value.length < length) { - value = "0" + value; + /** + * Returns a float approximation. + * + * Due to IEEE 754 precission (or lack thereof), this function + * can only return an approximation and most values will contain + * rounding errors. + */ + toUnsafeFloat() { + return parseFloat(this.toString()); } - return value; -} -function getPassword(password) { - if (typeof password === "string") { - return toUtf8Bytes(password, "NFKC"); + /** + * Return a new [[FixedNumber]] with the same value but has had + * its field set to %%format%%. + * + * This will throw if the value cannot fit into %%format%%. + */ + toFormat(format2) { + return _FixedNumber.fromString(this.toString(), format2); } - return getBytesCopy(password); -} -function spelunk(object2, _path) { - const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i); - assertArgument(match != null, "invalid path", "path", _path); - const path = match[1]; - const type = match[3]; - const reqd = match[4] === "!"; - let cur = object2; - for (const comp of path.toLowerCase().split(".")) { - if (Array.isArray(cur)) { - if (!comp.match(/^[0-9]+$/)) { - break; - } - cur = cur[parseInt(comp)]; - } else if (typeof cur === "object") { - let found = null; - for (const key in cur) { - if (key.toLowerCase() === comp) { - found = cur[key]; - break; - } - } - cur = found; - } else { - cur = null; - } - if (cur == null) { - break; + /** + * Creates a new [[FixedNumber]] for %%value%% divided by + * %%decimal%% places with %%format%%. + * + * This will throw a [[NumericFaultError]] if %%value%% (once adjusted + * for %%decimals%%) cannot fit in %%format%%, either due to overflow + * or underflow (precision loss). + */ + static fromValue(_value2, _decimals, _format2) { + const decimals = _decimals == null ? 0 : getNumber(_decimals); + const format2 = getFormat(_format2); + let value = getBigInt(_value2, "value"); + const delta = decimals - format2.decimals; + if (delta > 0) { + const tens = getTens(delta); + assert(value % tens === BN_0$8, "value loses precision for format", "NUMERIC_FAULT", { + operation: "fromValue", + fault: "underflow", + value: _value2 + }); + value /= tens; + } else if (delta < 0) { + value *= getTens(-delta); } + checkValue(value, format2, "fromValue"); + return new _FixedNumber(_guard$5, value, format2); } - assertArgument(!reqd || cur != null, "missing required value", "path", path); - if (type && cur != null) { - if (type === "int") { - if (typeof cur === "string" && cur.match(/^-?[0-9]+$/)) { - return parseInt(cur); - } else if (Number.isSafeInteger(cur)) { - return cur; - } - } - if (type === "number") { - if (typeof cur === "string" && cur.match(/^-?[0-9.]*$/)) { - return parseFloat(cur); - } - } - if (type === "data") { - if (typeof cur === "string") { - return looseArrayify(cur); - } - } - if (type === "array" && Array.isArray(cur)) { - return cur; - } - if (type === typeof cur) { - return cur; + /** + * Creates a new [[FixedNumber]] for %%value%% with %%format%%. + * + * This will throw a [[NumericFaultError]] if %%value%% cannot fit + * in %%format%%, either due to overflow or underflow (precision loss). + */ + static fromString(_value2, _format2) { + const match = _value2.match(/^(-?)([0-9]*)\.?([0-9]*)$/); + assertArgument(match && match[2].length + match[3].length > 0, "invalid FixedNumber string value", "value", _value2); + const format2 = getFormat(_format2); + let whole = match[2] || "0", decimal = match[3] || ""; + while (decimal.length < format2.decimals) { + decimal += Zeros$1; } - assertArgument(false, `wrong type found for ${type} `, "path", path); + assert(decimal.substring(format2.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", { + operation: "fromString", + fault: "underflow", + value: _value2 + }); + decimal = decimal.substring(0, format2.decimals); + const value = BigInt(match[1] + whole + decimal); + checkValue(value, format2, "fromString"); + return new _FixedNumber(_guard$5, value, format2); } - return cur; -} -const defaultPath$1 = "m/44'/60'/0'/0/0"; -function isKeystoreJson(json) { - try { - const data = JSON.parse(json); - const version2 = data.version != null ? parseInt(data.version) : 0; - if (version2 === 3) { - return true; + /** + * Creates a new [[FixedNumber]] with the big-endian representation + * %%value%% with %%format%%. + * + * This will throw a [[NumericFaultError]] if %%value%% cannot fit + * in %%format%% due to overflow. + */ + static fromBytes(_value2, _format2) { + let value = toBigInt(getBytes(_value2, "value")); + const format2 = getFormat(_format2); + if (format2.signed) { + value = fromTwos(value, format2.width); } - } catch (error) { - } - return false; -} -function decrypt(data, key, ciphertext) { - const cipher = spelunk(data, "crypto.cipher:string"); - if (cipher === "aes-128-ctr") { - const iv = spelunk(data, "crypto.cipherparams.iv:data!"); - const aesCtr = new CTR(key, iv); - return hexlify(aesCtr.decrypt(ciphertext)); + checkValue(value, format2, "fromBytes"); + return new _FixedNumber(_guard$5, value, format2); } - assert(false, "unsupported cipher", "UNSUPPORTED_OPERATION", { - operation: "decrypt" +}; +_format = new WeakMap(); +_val = new WeakMap(); +_tens = new WeakMap(); +_FixedNumber_instances = new WeakSet(); +checkFormat_fn = function(other) { + assertArgument(this.format === other.format, "incompatible format; use fixedNumber.toFormat", "other", other); +}; +checkValue_fn = function(val, safeOp) { + val = checkValue(val, __privateGet(this, _format), safeOp); + return new _FixedNumber(_guard$5, val, __privateGet(this, _format)); +}; +add_fn = function(o2, safeOp) { + __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, o2); + return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, __privateGet(this, _val) + __privateGet(o2, _val), safeOp); +}; +sub_fn = function(o2, safeOp) { + __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, o2); + return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, __privateGet(this, _val) - __privateGet(o2, _val), safeOp); +}; +mul_fn = function(o2, safeOp) { + __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, o2); + return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, __privateGet(this, _val) * __privateGet(o2, _val) / __privateGet(this, _tens), safeOp); +}; +div_fn = function(o2, safeOp) { + assert(__privateGet(o2, _val) !== BN_0$8, "division by zero", "NUMERIC_FAULT", { + operation: "div", + fault: "divide-by-zero", + value: this }); -} -function getAccount$1(data, _key) { - const key = getBytes(_key); - const ciphertext = spelunk(data, "crypto.ciphertext:data!"); - const computedMAC = hexlify(keccak256$1(concat$1([key.slice(16, 32), ciphertext]))).substring(2); - assertArgument(computedMAC === spelunk(data, "crypto.mac:string!").toLowerCase(), "incorrect password", "password", "[ REDACTED ]"); - const privateKey = decrypt(data, key.slice(0, 16), ciphertext); - const address = computeAddress(privateKey); - if (data.address) { - let check = data.address.toLowerCase(); - if (!check.startsWith("0x")) { - check = "0x" + check; - } - assertArgument(getAddress$1(check) === address, "keystore address/privateKey mismatch", "address", data.address); + __privateMethod(this, _FixedNumber_instances, checkFormat_fn).call(this, o2); + return __privateMethod(this, _FixedNumber_instances, checkValue_fn).call(this, __privateGet(this, _val) * __privateGet(this, _tens) / __privateGet(o2, _val), safeOp); +}; +let FixedNumber = _FixedNumber; +function hexlifyByte(value) { + let result = value.toString(16); + while (result.length < 2) { + result = "0" + result; } - const account2 = { address, privateKey }; - const version2 = spelunk(data, "x-ethers.version:string"); - if (version2 === "0.1") { - const mnemonicKey = key.slice(32, 64); - const mnemonicCiphertext = spelunk(data, "x-ethers.mnemonicCiphertext:data!"); - const mnemonicIv = spelunk(data, "x-ethers.mnemonicCounter:data!"); - const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); - account2.mnemonic = { - path: spelunk(data, "x-ethers.path:string") || defaultPath$1, - locale: spelunk(data, "x-ethers.locale:string") || "en", - entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))) - }; + return "0x" + result; +} +function unarrayifyInteger(data, offset2, length) { + let result = 0; + for (let i = 0; i < length; i++) { + result = result * 256 + data[offset2 + i]; } - return account2; + return result; } -function getDecryptKdfParams(data) { - const kdf = spelunk(data, "crypto.kdf:string"); - if (kdf && typeof kdf === "string") { - if (kdf.toLowerCase() === "scrypt") { - const salt = spelunk(data, "crypto.kdfparams.salt:data!"); - const N2 = spelunk(data, "crypto.kdfparams.n:int!"); - const r2 = spelunk(data, "crypto.kdfparams.r:int!"); - const p2 = spelunk(data, "crypto.kdfparams.p:int!"); - assertArgument(N2 > 0 && (N2 & N2 - 1) === 0, "invalid kdf.N", "kdf.N", N2); - assertArgument(r2 > 0 && p2 > 0, "invalid kdf", "kdf", kdf); - const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); - assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dflen", dkLen); - return { name: "scrypt", salt, N: N2, r: r2, p: p2, dkLen: 64 }; - } else if (kdf.toLowerCase() === "pbkdf2") { - const salt = spelunk(data, "crypto.kdfparams.salt:data!"); - const prf = spelunk(data, "crypto.kdfparams.prf:string!"); - const algorithm = prf.split("-").pop(); - assertArgument(algorithm === "sha256" || algorithm === "sha512", "invalid kdf.pdf", "kdf.pdf", prf); - const count2 = spelunk(data, "crypto.kdfparams.c:int!"); - const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); - assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dklen", dkLen); - return { name: "pbkdf2", salt, count: count2, dkLen, algorithm }; - } +function _decodeChildren(data, offset2, childOffset, length) { + const result = []; + while (childOffset < offset2 + 1 + length) { + const decoded = _decode$1(data, childOffset); + result.push(decoded.result); + childOffset += decoded.consumed; + assert(childOffset <= offset2 + 1 + length, "child data too short", "BUFFER_OVERRUN", { + buffer: data, + length, + offset: offset2 + }); } - assertArgument(false, "unsupported key-derivation function", "kdf", kdf); + return { consumed: 1 + length, result }; } -function decryptKeystoreJsonSync(json, _password) { - const data = JSON.parse(json); - const password = getPassword(_password); - const params = getDecryptKdfParams(data); - if (params.name === "pbkdf2") { - const { salt: salt2, count: count2, dkLen: dkLen2, algorithm } = params; - const key2 = pbkdf2(password, salt2, count2, dkLen2, algorithm); - return getAccount$1(data, key2); +function _decode$1(data, offset2) { + assert(data.length !== 0, "data too short", "BUFFER_OVERRUN", { + buffer: data, + length: 0, + offset: 1 + }); + const checkOffset = (offset3) => { + assert(offset3 <= data.length, "data short segment too short", "BUFFER_OVERRUN", { + buffer: data, + length: data.length, + offset: offset3 + }); + }; + if (data[offset2] >= 248) { + const lengthLength = data[offset2] - 247; + checkOffset(offset2 + 1 + lengthLength); + const length = unarrayifyInteger(data, offset2 + 1, lengthLength); + checkOffset(offset2 + 1 + lengthLength + length); + return _decodeChildren(data, offset2, offset2 + 1 + lengthLength, lengthLength + length); + } else if (data[offset2] >= 192) { + const length = data[offset2] - 192; + checkOffset(offset2 + 1 + length); + return _decodeChildren(data, offset2, offset2 + 1, length); + } else if (data[offset2] >= 184) { + const lengthLength = data[offset2] - 183; + checkOffset(offset2 + 1 + lengthLength); + const length = unarrayifyInteger(data, offset2 + 1, lengthLength); + checkOffset(offset2 + 1 + lengthLength + length); + const result = hexlify(data.slice(offset2 + 1 + lengthLength, offset2 + 1 + lengthLength + length)); + return { consumed: 1 + lengthLength + length, result }; + } else if (data[offset2] >= 128) { + const length = data[offset2] - 128; + checkOffset(offset2 + 1 + length); + const result = hexlify(data.slice(offset2 + 1, offset2 + 1 + length)); + return { consumed: 1 + length, result }; } - assert(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params }); - const { salt, N: N2, r: r2, p: p2, dkLen } = params; - const key = scryptSync(password, salt, N2, r2, p2, dkLen); - return getAccount$1(data, key); + return { consumed: 1, result: hexlifyByte(data[offset2]) }; } -function stall$1(duration) { - return new Promise((resolve) => { - setTimeout(() => { - resolve(); - }, duration); - }); +function decodeRlp(_data6) { + const data = getBytes(_data6, "data"); + const decoded = _decode$1(data, 0); + assertArgument(decoded.consumed === data.length, "unexpected junk after rlp payload", "data", _data6); + return decoded.result; } -async function decryptKeystoreJson(json, _password, progress2) { - const data = JSON.parse(json); - const password = getPassword(_password); - const params = getDecryptKdfParams(data); - if (params.name === "pbkdf2") { - if (progress2) { - progress2(0); - await stall$1(0); - } - const { salt: salt2, count: count2, dkLen: dkLen2, algorithm } = params; - const key2 = pbkdf2(password, salt2, count2, dkLen2, algorithm); - if (progress2) { - progress2(1); - await stall$1(0); - } - return getAccount$1(data, key2); +function arrayifyInteger(value) { + const result = []; + while (value) { + result.unshift(value & 255); + value >>= 8; } - assert(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params }); - const { salt, N: N2, r: r2, p: p2, dkLen } = params; - const key = await scrypt(password, salt, N2, r2, p2, dkLen, progress2); - return getAccount$1(data, key); + return result; } -function getEncryptKdfParams(options) { - const salt = options.salt != null ? getBytes(options.salt, "options.salt") : randomBytes$1(32); - let N2 = 1 << 17, r2 = 8, p2 = 1; - if (options.scrypt) { - if (options.scrypt.N) { - N2 = options.scrypt.N; - } - if (options.scrypt.r) { - r2 = options.scrypt.r; - } - if (options.scrypt.p) { - p2 = options.scrypt.p; +function _encode$1(object2) { + if (Array.isArray(object2)) { + let payload = []; + object2.forEach(function(child) { + payload = payload.concat(_encode$1(child)); + }); + if (payload.length <= 55) { + payload.unshift(192 + payload.length); + return payload; } + const length2 = arrayifyInteger(payload.length); + length2.unshift(247 + length2.length); + return length2.concat(payload); } - assertArgument(typeof N2 === "number" && N2 > 0 && Number.isSafeInteger(N2) && (BigInt(N2) & BigInt(N2 - 1)) === BigInt(0), "invalid scrypt N parameter", "options.N", N2); - assertArgument(typeof r2 === "number" && r2 > 0 && Number.isSafeInteger(r2), "invalid scrypt r parameter", "options.r", r2); - assertArgument(typeof p2 === "number" && p2 > 0 && Number.isSafeInteger(p2), "invalid scrypt p parameter", "options.p", p2); - return { name: "scrypt", dkLen: 32, salt, N: N2, r: r2, p: p2 }; -} -function _encryptKeystore(key, kdf, account2, options) { - const privateKey = getBytes(account2.privateKey, "privateKey"); - const iv = options.iv != null ? getBytes(options.iv, "options.iv") : randomBytes$1(16); - assertArgument(iv.length === 16, "invalid options.iv length", "options.iv", options.iv); - const uuidRandom = options.uuid != null ? getBytes(options.uuid, "options.uuid") : randomBytes$1(16); - assertArgument(uuidRandom.length === 16, "invalid options.uuid length", "options.uuid", options.iv); - const derivedKey = key.slice(0, 16); - const macPrefix = key.slice(16, 32); - const aesCtr = new CTR(derivedKey, iv); - const ciphertext = getBytes(aesCtr.encrypt(privateKey)); - const mac = keccak256$1(concat$1([macPrefix, ciphertext])); - const data = { - address: account2.address.substring(2).toLowerCase(), - id: uuidV4(uuidRandom), - version: 3, - Crypto: { - cipher: "aes-128-ctr", - cipherparams: { - iv: hexlify(iv).substring(2) - }, - ciphertext: hexlify(ciphertext).substring(2), - kdf: "scrypt", - kdfparams: { - salt: hexlify(kdf.salt).substring(2), - n: kdf.N, - dklen: 32, - p: kdf.p, - r: kdf.r - }, - mac: mac.substring(2) - } - }; - if (account2.mnemonic) { - const client2 = options.client != null ? options.client : `ethers/${version$9}`; - const path = account2.mnemonic.path || defaultPath$1; - const locale = account2.mnemonic.locale || "en"; - const mnemonicKey = key.slice(32, 64); - const entropy = getBytes(account2.mnemonic.entropy, "account.mnemonic.entropy"); - const mnemonicIv = randomBytes$1(16); - const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); - const mnemonicCiphertext = getBytes(mnemonicAesCtr.encrypt(entropy)); - const now = /* @__PURE__ */ new Date(); - const timestamp = now.getUTCFullYear() + "-" + zpad$1(now.getUTCMonth() + 1, 2) + "-" + zpad$1(now.getUTCDate(), 2) + "T" + zpad$1(now.getUTCHours(), 2) + "-" + zpad$1(now.getUTCMinutes(), 2) + "-" + zpad$1(now.getUTCSeconds(), 2) + ".0Z"; - const gethFilename = "UTC--" + timestamp + "--" + data.address; - data["x-ethers"] = { - client: client2, - gethFilename, - path, - locale, - mnemonicCounter: hexlify(mnemonicIv).substring(2), - mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2), - version: "0.1" - }; + const data = Array.prototype.slice.call(getBytes(object2, "object")); + if (data.length === 1 && data[0] <= 127) { + return data; + } else if (data.length <= 55) { + data.unshift(128 + data.length); + return data; } - return JSON.stringify(data); + const length = arrayifyInteger(data.length); + length.unshift(183 + length.length); + return length.concat(data); } -function encryptKeystoreJsonSync(account2, password, options) { - if (options == null) { - options = {}; +const nibbles = "0123456789abcdef"; +function encodeRlp(object2) { + let result = "0x"; + for (const v3 of _encode$1(object2)) { + result += nibbles[v3 >> 4]; + result += nibbles[v3 & 15]; } - const passwordBytes = getPassword(password); - const kdf = getEncryptKdfParams(options); - const key = scryptSync(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64); - return _encryptKeystore(getBytes(key), kdf, account2, options); + return result; } -async function encryptKeystoreJson(account2, password, options) { - if (options == null) { - options = {}; +const names = [ + "wei", + "kwei", + "mwei", + "gwei", + "szabo", + "finney", + "ether" +]; +function formatUnits$1(value, unit) { + let decimals = 18; + if (typeof unit === "string") { + const index2 = names.indexOf(unit); + assertArgument(index2 >= 0, "invalid unit", "unit", unit); + decimals = 3 * index2; + } else if (unit != null) { + decimals = getNumber(unit, "unit"); } - const passwordBytes = getPassword(password); - const kdf = getEncryptKdfParams(options); - const key = await scrypt(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64, options.progressCallback); - return _encryptKeystore(getBytes(key), kdf, account2, options); + return FixedNumber.fromValue(value, decimals, { decimals, width: 512 }).toString(); } -const defaultPath = "m/44'/60'/0'/0/0"; -const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]); -const HardenedBit = 2147483648; -const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); -const Nibbles = "0123456789abcdef"; -function zpad(value, length) { - let result = ""; - while (value) { - result = Nibbles[value % 16] + result; - value = Math.trunc(value / 16); - } - while (result.length < length * 2) { - result = "0" + result; +function parseUnits$2(value, unit) { + assertArgument(typeof value === "string", "value must be a string", "value", value); + let decimals = 18; + if (typeof unit === "string") { + const index2 = names.indexOf(unit); + assertArgument(index2 >= 0, "invalid unit", "unit", unit); + decimals = 3 * index2; + } else if (unit != null) { + decimals = getNumber(unit, "unit"); } - return "0x" + result; + return FixedNumber.fromString(value, { decimals, width: 512 }).value; } -function encodeBase58Check(_value2) { - const value = getBytes(_value2); - const check = dataSlice(sha256$3(sha256$3(value)), 0, 4); - const bytes2 = concat$1([value, check]); - return encodeBase58(bytes2); +function formatEther$1(wei) { + return formatUnits$1(wei, 18); } -const _guard = {}; -function ser_I(index2, chainCode, publicKey, privateKey) { - const data = new Uint8Array(37); - if (index2 & HardenedBit) { - assert(privateKey != null, "cannot derive child of neutered node", "UNSUPPORTED_OPERATION", { - operation: "deriveChild" - }); - data.set(getBytes(privateKey), 1); - } else { - data.set(getBytes(publicKey)); - } - for (let i = 24; i >= 0; i -= 8) { - data[33 + (i >> 3)] = index2 >> 24 - i & 255; - } - const I2 = getBytes(computeHmac("sha512", chainCode, data)); - return { IL: I2.slice(0, 32), IR: I2.slice(32) }; +function parseEther$1(ether) { + return parseUnits$2(ether, 18); } -function derivePath(node, path) { - const components = path.split("/"); - assertArgument(components.length > 0, "invalid path", "path", path); - if (components[0] === "m") { - assertArgument(node.depth === 0, `cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${node.depth}`, "path", path); - components.shift(); +function uuidV4(randomBytes2) { + const bytes2 = getBytes(randomBytes2, "randomBytes"); + bytes2[6] = bytes2[6] & 15 | 64; + bytes2[8] = bytes2[8] & 63 | 128; + const value = hexlify(bytes2); + return [ + value.substring(2, 10), + value.substring(10, 14), + value.substring(14, 18), + value.substring(18, 22), + value.substring(22, 34) + ].join("-"); +} +const WordSize = 32; +const Padding = new Uint8Array(WordSize); +const passProperties$1 = ["then"]; +const _guard$4 = {}; +const resultNames = /* @__PURE__ */ new WeakMap(); +function getNames(result) { + return resultNames.get(result); +} +function setNames(result, names2) { + resultNames.set(result, names2); +} +function throwError(name2, error) { + const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name2}`); + wrapped.error = error; + throw wrapped; +} +function toObject(names2, items, deep) { + if (names2.indexOf(null) >= 0) { + return items.map((item2, index2) => { + if (item2 instanceof Result) { + return toObject(getNames(item2), item2, deep); + } + return item2; + }); } - let result = node; - for (let i = 0; i < components.length; i++) { - const component = components[i]; - if (component.match(/^[0-9]+'$/)) { - const index2 = parseInt(component.substring(0, component.length - 1)); - assertArgument(index2 < HardenedBit, "invalid path index", `path[${i}]`, component); - result = result.deriveChild(HardenedBit + index2); - } else if (component.match(/^[0-9]+$/)) { - const index2 = parseInt(component); - assertArgument(index2 < HardenedBit, "invalid path index", `path[${i}]`, component); - result = result.deriveChild(index2); - } else { - assertArgument(false, "invalid path component", `path[${i}]`, component); + return names2.reduce((accum, name2, index2) => { + let item2 = items.getValue(name2); + if (!(name2 in accum)) { + if (deep && item2 instanceof Result) { + item2 = toObject(getNames(item2), item2, deep); + } + accum[name2] = item2; } - } - return result; + return accum; + }, {}); } -const _HDNodeWallet = class _HDNodeWallet extends BaseWallet { +const _Result = class _Result extends Array { /** * @private */ - constructor(guard2, signingKey, parentFingerprint, chainCode, path, index2, depth, mnemonic, provider2) { - super(signingKey, provider2); - __privateAdd(this, _HDNodeWallet_instances); - /** - * The compressed public key. - */ - __publicField(this, "publicKey"); - /** - * The fingerprint. - * - * A fingerprint allows quick qay to detect parent and child nodes, - * but developers should be prepared to deal with collisions as it - * is only 4 bytes. - */ - __publicField(this, "fingerprint"); - /** - * The parent fingerprint. - */ - __publicField(this, "parentFingerprint"); - /** - * The mnemonic used to create this HD Node, if available. - * - * Sources such as extended keys do not encode the mnemonic, in - * which case this will be ``null``. - */ - __publicField(this, "mnemonic"); - /** - * The chaincode, which is effectively a public key used - * to derive children. - */ - __publicField(this, "chainCode"); - /** - * The derivation path of this wallet. - * - * Since extended keys do not provide full path details, this - * may be ``null``, if instantiated from a source that does not - * encode it. - */ - __publicField(this, "path"); - /** - * The child index of this wallet. Values over ``2 *\* 31`` indicate - * the node is hardened. - */ - __publicField(this, "index"); - /** - * The depth of this wallet, which is the number of components - * in its path. - */ - __publicField(this, "depth"); - assertPrivate(guard2, _guard, "HDNodeWallet"); - defineProperties$1(this, { publicKey: signingKey.compressedPublicKey }); - const fingerprint = dataSlice(ripemd160(sha256$3(this.publicKey)), 0, 4); - defineProperties$1(this, { - parentFingerprint, - fingerprint, - chainCode, - path, - index: index2, - depth + constructor(...args) { + const guard2 = args[0]; + let items = args[1]; + let names2 = (args[2] || []).slice(); + let wrap2 = true; + if (guard2 !== _guard$4) { + items = args; + names2 = []; + wrap2 = false; + } + super(items.length); + // No longer used; but cannot be removed as it will remove the + // #private field from the .d.ts which may break backwards + // compatibility + __privateAdd(this, _names); + items.forEach((item2, index2) => { + this[index2] = item2; }); - defineProperties$1(this, { mnemonic }); - } - connect(provider2) { - return new _HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider2); - } - /** - * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with - * %%password%%. - * - * If %%progressCallback%% is specified, it will receive periodic - * updates as the encryption process progreses. - */ - async encrypt(password, progressCallback) { - return await encryptKeystoreJson(__privateMethod(this, _HDNodeWallet_instances, account_fn).call(this), password, { progressCallback }); - } - /** - * Returns a [JSON Keystore Wallet](json-wallets) encryped with - * %%password%%. - * - * It is preferred to use the [async version](encrypt) instead, - * which allows a [[ProgressCallback]] to keep the user informed. - * - * This method will block the event loop (freezing all UI) until - * it is complete, which may be a non-trivial duration. - */ - encryptSync(password) { - return encryptKeystoreJsonSync(__privateMethod(this, _HDNodeWallet_instances, account_fn).call(this), password); - } - /** - * The extended key. - * - * This key will begin with the prefix ``xpriv`` and can be used to - * reconstruct this HD Node to derive its children. - */ - get extendedKey() { - assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" }); - return encodeBase58Check(concat$1([ - "0x0488ADE4", - zpad(this.depth, 1), - this.parentFingerprint, - zpad(this.index, 4), - this.chainCode, - concat$1(["0x00", this.privateKey]) - ])); - } - /** - * Returns true if this wallet has a path, providing a Type Guard - * that the path is non-null. - */ - hasPath() { - return this.path != null; - } - /** - * Returns a neutered HD Node, which removes the private details - * of an HD Node. - * - * A neutered node has no private key, but can be used to derive - * child addresses and other public data about the HD Node. - */ - neuter() { - return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider); + const nameCounts = names2.reduce((accum, name2) => { + if (typeof name2 === "string") { + accum.set(name2, (accum.get(name2) || 0) + 1); + } + return accum; + }, /* @__PURE__ */ new Map()); + setNames(this, Object.freeze(items.map((item2, index2) => { + const name2 = names2[index2]; + if (name2 != null && nameCounts.get(name2) === 1) { + return name2; + } + return null; + }))); + __privateSet(this, _names, []); + if (__privateGet(this, _names) == null) { + void __privateGet(this, _names); + } + if (!wrap2) { + return; + } + Object.freeze(this); + const proxy = new Proxy(this, { + get: (target, prop, receiver) => { + if (typeof prop === "string") { + if (prop.match(/^[0-9]+$/)) { + const index2 = getNumber(prop, "%index"); + if (index2 < 0 || index2 >= this.length) { + throw new RangeError("out of result range"); + } + const item2 = target[index2]; + if (item2 instanceof Error) { + throwError(`index ${index2}`, item2); + } + return item2; + } + if (passProperties$1.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + const value = target[prop]; + if (value instanceof Function) { + return function(...args2) { + return value.apply(this === receiver ? target : this, args2); + }; + } else if (!(prop in target)) { + return target.getValue.apply(this === receiver ? target : this, [prop]); + } + } + return Reflect.get(target, prop, receiver); + } + }); + setNames(proxy, getNames(this)); + return proxy; } /** - * Return the child for %%index%%. + * Returns the Result as a normal Array. If %%deep%%, any children + * which are Result objects are also converted to a normal Array. + * + * This will throw if there are any outstanding deferred + * errors. */ - deriveChild(_index) { - const index2 = getNumber(_index, "index"); - assertArgument(index2 <= 4294967295, "invalid index", "index", index2); - let path = this.path; - if (path) { - path += "/" + (index2 & ~HardenedBit); - if (index2 & HardenedBit) { - path += "'"; + toArray(deep) { + const result = []; + this.forEach((item2, index2) => { + if (item2 instanceof Error) { + throwError(`index ${index2}`, item2); } - } - const { IR, IL } = ser_I(index2, this.chainCode, this.publicKey, this.privateKey); - const ki2 = new SigningKey(toBeHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32)); - return new _HDNodeWallet(_guard, ki2, this.fingerprint, hexlify(IR), path, index2, this.depth + 1, this.mnemonic, this.provider); + if (deep && item2 instanceof _Result) { + item2 = item2.toArray(deep); + } + result.push(item2); + }); + return result; } /** - * Return the HDNode for %%path%% from this node. + * Returns the Result as an Object with each name-value pair. If + * %%deep%%, any children which are Result objects are also + * converted to an Object. + * + * This will throw if any value is unnamed, or if there are + * any outstanding deferred errors. */ - derivePath(path) { - return derivePath(this, path); + toObject(deep) { + const names2 = getNames(this); + return names2.reduce((accum, name2, index2) => { + assert(name2 != null, `value at index ${index2} unnamed`, "UNSUPPORTED_OPERATION", { + operation: "toObject()" + }); + return toObject(names2, this, deep); + }, {}); } /** - * Creates a new HD Node from %%extendedKey%%. - * - * If the %%extendedKey%% will either have a prefix or ``xpub`` or - * ``xpriv``, returning a neutered HD Node ([[HDNodeVoidWallet]]) - * or full HD Node ([[HDNodeWallet) respectively. + * @_ignore */ - static fromExtendedKey(extendedKey) { - const bytes2 = toBeArray(decodeBase58(extendedKey)); - assertArgument(bytes2.length === 82 || encodeBase58Check(bytes2.slice(0, 78)) === extendedKey, "invalid extended key", "extendedKey", "[ REDACTED ]"); - const depth = bytes2[4]; - const parentFingerprint = hexlify(bytes2.slice(5, 9)); - const index2 = parseInt(hexlify(bytes2.slice(9, 13)).substring(2), 16); - const chainCode = hexlify(bytes2.slice(13, 45)); - const key = bytes2.slice(45, 78); - switch (hexlify(bytes2.slice(0, 4))) { - case "0x0488b21e": - case "0x043587cf": { - const publicKey = hexlify(key); - return new HDNodeVoidWallet(_guard, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index2, depth, null); + slice(start, end) { + if (start == null) { + start = 0; + } + if (start < 0) { + start += this.length; + if (start < 0) { + start = 0; } - case "0x0488ade4": - case "0x04358394 ": - if (key[0] !== 0) { - break; - } - return new _HDNodeWallet(_guard, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index2, depth, null, null); } - assertArgument(false, "invalid extended key prefix", "extendedKey", "[ REDACTED ]"); - } - /** - * Creates a new random HDNode. - */ - static createRandom(password, path, wordlist2) { - var _a2; - if (password == null) { - password = ""; + if (end == null) { + end = this.length; } - if (path == null) { - path = defaultPath; + if (end < 0) { + end += this.length; + if (end < 0) { + end = 0; + } } - if (wordlist2 == null) { - wordlist2 = LangEn.wordlist(); + if (end > this.length) { + end = this.length; } - const mnemonic = Mnemonic.fromEntropy(randomBytes$1(16), password, wordlist2); - return __privateMethod(_a2 = _HDNodeWallet, _HDNodeWallet_static, fromSeed_fn).call(_a2, mnemonic.computeSeed(), mnemonic).derivePath(path); + const _names2 = getNames(this); + const result = [], names2 = []; + for (let i = start; i < end; i++) { + result.push(this[i]); + names2.push(_names2[i]); + } + return new _Result(_guard$4, result, names2); } /** - * Create an HD Node from %%mnemonic%%. + * @_ignore */ - static fromMnemonic(mnemonic, path) { - var _a2; - if (!path) { - path = defaultPath; + filter(callback, thisArg) { + const _names2 = getNames(this); + const result = [], names2 = []; + for (let i = 0; i < this.length; i++) { + const item2 = this[i]; + if (item2 instanceof Error) { + throwError(`index ${i}`, item2); + } + if (callback.call(thisArg, item2, i, this)) { + result.push(item2); + names2.push(_names2[i]); + } } - return __privateMethod(_a2 = _HDNodeWallet, _HDNodeWallet_static, fromSeed_fn).call(_a2, mnemonic.computeSeed(), mnemonic).derivePath(path); + return new _Result(_guard$4, result, names2); } /** - * Creates an HD Node from a mnemonic %%phrase%%. + * @_ignore */ - static fromPhrase(phrase, password, path, wordlist2) { - var _a2; - if (password == null) { - password = ""; + map(callback, thisArg) { + const result = []; + for (let i = 0; i < this.length; i++) { + const item2 = this[i]; + if (item2 instanceof Error) { + throwError(`index ${i}`, item2); + } + result.push(callback.call(thisArg, item2, i, this)); } - if (path == null) { - path = defaultPath; + return result; + } + /** + * Returns the value for %%name%%. + * + * Since it is possible to have a key whose name conflicts with + * a method on a [[Result]] or its superclass Array, or any + * JavaScript keyword, this ensures all named values are still + * accessible by name. + */ + getValue(name2) { + const index2 = getNames(this).indexOf(name2); + if (index2 === -1) { + return void 0; } - if (wordlist2 == null) { - wordlist2 = LangEn.wordlist(); + const value = this[index2]; + if (value instanceof Error) { + throwError(`property ${JSON.stringify(name2)}`, value.error); } - const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist2); - return __privateMethod(_a2 = _HDNodeWallet, _HDNodeWallet_static, fromSeed_fn).call(_a2, mnemonic.computeSeed(), mnemonic).derivePath(path); + return value; } /** - * Creates an HD Node from a %%seed%%. + * Creates a new [[Result]] for %%items%% with each entry + * also accessible by its corresponding name in %%keys%%. */ - static fromSeed(seed) { - var _a2; - return __privateMethod(_a2 = _HDNodeWallet, _HDNodeWallet_static, fromSeed_fn).call(_a2, seed, null); + static fromItems(items, keys) { + return new _Result(_guard$4, items, keys); } }; -_HDNodeWallet_instances = new WeakSet(); -account_fn = function() { - const account2 = { address: this.address, privateKey: this.privateKey }; - const m2 = this.mnemonic; - if (this.path && m2 && m2.wordlist.locale === "en" && m2.password === "") { - account2.mnemonic = { - path: this.path, - locale: "en", - entropy: m2.entropy - }; +_names = new WeakMap(); +let Result = _Result; +function checkResultErrors(result) { + const errors2 = []; + const checkErrors = function(path, object2) { + if (!Array.isArray(object2)) { + return; + } + for (let key in object2) { + const childPath = path.slice(); + childPath.push(key); + try { + checkErrors(childPath, object2[key]); + } catch (error) { + errors2.push({ path: childPath, error }); + } + } + }; + checkErrors([], result); + return errors2; +} +function getValue$1(value) { + let bytes2 = toBeArray(value); + assert(bytes2.length <= WordSize, "value out-of-bounds", "BUFFER_OVERRUN", { buffer: bytes2, length: WordSize, offset: bytes2.length }); + if (bytes2.length !== WordSize) { + bytes2 = getBytesCopy(concat([Padding.slice(bytes2.length % WordSize), bytes2])); } - return account2; -}; -_HDNodeWallet_static = new WeakSet(); -fromSeed_fn = function(_seed, mnemonic) { - assertArgument(isBytesLike(_seed), "invalid seed", "seed", "[REDACTED]"); - const seed = getBytes(_seed, "seed"); - assertArgument(seed.length >= 16 && seed.length <= 64, "invalid seed", "seed", "[REDACTED]"); - const I2 = getBytes(computeHmac("sha512", MasterSecret, seed)); - const signingKey = new SigningKey(hexlify(I2.slice(0, 32))); - return new _HDNodeWallet(_guard, signingKey, "0x00000000", hexlify(I2.slice(32)), "m", 0, 0, mnemonic, null); -}; -__privateAdd(_HDNodeWallet, _HDNodeWallet_static); -let HDNodeWallet = _HDNodeWallet; -class HDNodeVoidWallet extends VoidSigner { - /** - * @private - */ - constructor(guard2, address, publicKey, parentFingerprint, chainCode, path, index2, depth, provider2) { - super(address, provider2); - /** - * The compressed public key. - */ - __publicField(this, "publicKey"); - /** - * The fingerprint. - * - * A fingerprint allows quick qay to detect parent and child nodes, - * but developers should be prepared to deal with collisions as it - * is only 4 bytes. - */ - __publicField(this, "fingerprint"); - /** - * The parent node fingerprint. - */ - __publicField(this, "parentFingerprint"); - /** - * The chaincode, which is effectively a public key used - * to derive children. - */ - __publicField(this, "chainCode"); - /** - * The derivation path of this wallet. - * - * Since extended keys do not provider full path details, this - * may be ``null``, if instantiated from a source that does not - * enocde it. - */ - __publicField(this, "path"); - /** - * The child index of this wallet. Values over ``2 *\* 31`` indicate - * the node is hardened. - */ - __publicField(this, "index"); - /** - * The depth of this wallet, which is the number of components - * in its path. - */ - __publicField(this, "depth"); - assertPrivate(guard2, _guard, "HDNodeVoidWallet"); - defineProperties$1(this, { publicKey }); - const fingerprint = dataSlice(ripemd160(sha256$3(publicKey)), 0, 4); - defineProperties$1(this, { - publicKey, - fingerprint, - parentFingerprint, - chainCode, - path, - index: index2, - depth + return bytes2; +} +class Coder { + constructor(name2, type, localName, dynamic) { + // The coder name: + // - address, uint256, tuple, array, etc. + __publicField(this, "name"); + // The fully expanded type, including composite types: + // - address, uint256, tuple(address,bytes), uint256[3][4][], etc. + __publicField(this, "type"); + // The localName bound in the signature, in this example it is "baz": + // - tuple(address foo, uint bar) baz + __publicField(this, "localName"); + // Whether this type is dynamic: + // - Dynamic: bytes, string, address[], tuple(boolean[]), etc. + // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8) + __publicField(this, "dynamic"); + defineProperties$1(this, { name: name2, type, localName, dynamic }, { + name: "string", + type: "string", + localName: "string", + dynamic: "boolean" }); } - connect(provider2) { - return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider2); + _throwError(message, value) { + assertArgument(false, message, this.localName, value); } - /** - * The extended key. - * - * This key will begin with the prefix ``xpub`` and can be used to - * reconstruct this neutered key to derive its children addresses. - */ - get extendedKey() { - assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" }); - return encodeBase58Check(concat$1([ - "0x0488B21E", - zpad(this.depth, 1), - this.parentFingerprint, - zpad(this.index, 4), - this.chainCode, - this.publicKey - ])); +} +class Writer { + constructor() { + __privateAdd(this, _Writer_instances); + // An array of WordSize lengthed objects to concatenation + __privateAdd(this, _data2); + __privateAdd(this, _dataLength); + __privateSet(this, _data2, []); + __privateSet(this, _dataLength, 0); } - /** - * Returns true if this wallet has a path, providing a Type Guard - * that the path is non-null. - */ - hasPath() { - return this.path != null; + get data() { + return concat(__privateGet(this, _data2)); } - /** - * Return the child for %%index%%. - */ - deriveChild(_index) { - const index2 = getNumber(_index, "index"); - assertArgument(index2 <= 4294967295, "invalid index", "index", index2); - let path = this.path; - if (path) { - path += "/" + (index2 & ~HardenedBit); - if (index2 & HardenedBit) { - path += "'"; - } - } - const { IR, IL } = ser_I(index2, this.chainCode, this.publicKey, null); - const Ki2 = SigningKey.addPoints(IL, this.publicKey, true); - const address = computeAddress(Ki2); - return new HDNodeVoidWallet(_guard, address, Ki2, this.fingerprint, hexlify(IR), path, index2, this.depth + 1, this.provider); + get length() { + return __privateGet(this, _dataLength); } - /** - * Return the signer for %%path%% from this node. - */ - derivePath(path) { - return derivePath(this, path); + appendWriter(writer) { + return __privateMethod(this, _Writer_instances, writeData_fn).call(this, getBytesCopy(writer.data)); } -} -function getAccountPath(_index) { - const index2 = getNumber(_index, "index"); - assertArgument(index2 >= 0 && index2 < HardenedBit, "invalid account index", "index", index2); - return `m/44'/60'/${index2}'/0/0`; -} -function getIndexedAccountPath(_index) { - const index2 = getNumber(_index, "index"); - assertArgument(index2 >= 0 && index2 < HardenedBit, "invalid account index", "index", index2); - return `m/44'/60'/0'/0/${index2}`; -} -function isCrowdsaleJson(json) { - try { - const data = JSON.parse(json); - if (data.encseed) { - return true; + // Arrayish item; pad on the right to *nearest* WordSize + writeBytes(value) { + let bytes2 = getBytesCopy(value); + const paddingOffset = bytes2.length % WordSize; + if (paddingOffset) { + bytes2 = getBytesCopy(concat([bytes2, Padding.slice(paddingOffset)])); } - } catch (error) { + return __privateMethod(this, _Writer_instances, writeData_fn).call(this, bytes2); } - return false; -} -function decryptCrowdsaleJson(json, _password) { - const data = JSON.parse(json); - const password = getPassword(_password); - const address = getAddress$1(spelunk(data, "ethaddr:string!")); - const encseed = looseArrayify(spelunk(data, "encseed:string!")); - assertArgument(encseed && encseed.length % 16 === 0, "invalid encseed", "json", json); - const key = getBytes(pbkdf2(password, password, 2e3, 32, "sha256")).slice(0, 16); - const iv = encseed.slice(0, 16); - const encryptedSeed = encseed.slice(16); - const aesCbc = new CBC(key, iv); - const seed = pkcs7Strip(getBytes(aesCbc.decrypt(encryptedSeed))); - let seedHex = ""; - for (let i = 0; i < seed.length; i++) { - seedHex += String.fromCharCode(seed[i]); + // Numeric item; pad on the left *to* WordSize + writeValue(value) { + return __privateMethod(this, _Writer_instances, writeData_fn).call(this, getValue$1(value)); } - return { address, privateKey: id$1(seedHex) }; -} -function stall(duration) { - return new Promise((resolve) => { - setTimeout(() => { - resolve(); - }, duration); - }); -} -let Wallet$1 = (_c = class extends BaseWallet { - /** - * Create a new wallet for the private %%key%%, optionally connected - * to %%provider%%. - */ - constructor(key, provider2) { - if (typeof key === "string" && !key.startsWith("0x")) { - key = "0x" + key; - } - let signingKey = typeof key === "string" ? new SigningKey(key) : key; - super(signingKey, provider2); + // Inserts a numeric place-holder, returning a callback that can + // be used to asjust the value later + writeUpdatableValue() { + const offset2 = __privateGet(this, _data2).length; + __privateGet(this, _data2).push(Padding); + __privateSet(this, _dataLength, __privateGet(this, _dataLength) + WordSize); + return (value) => { + __privateGet(this, _data2)[offset2] = getValue$1(value); + }; } - connect(provider2) { - return new _c(this.signingKey, provider2); +} +_data2 = new WeakMap(); +_dataLength = new WeakMap(); +_Writer_instances = new WeakSet(); +writeData_fn = function(data) { + __privateGet(this, _data2).push(data); + __privateSet(this, _dataLength, __privateGet(this, _dataLength) + data.length); + return data.length; +}; +const _Reader = class _Reader { + constructor(data, allowLoose, maxInflation) { + __privateAdd(this, _Reader_instances); + // Allows incomplete unpadded data to be read; otherwise an error + // is raised if attempting to overrun the buffer. This is required + // to deal with an old Solidity bug, in which event data for + // external (not public thoguh) was tightly packed. + __publicField(this, "allowLoose"); + __privateAdd(this, _data3); + __privateAdd(this, _offset); + __privateAdd(this, _bytesRead); + __privateAdd(this, _parent); + __privateAdd(this, _maxInflation); + defineProperties$1(this, { allowLoose: !!allowLoose }); + __privateSet(this, _data3, getBytesCopy(data)); + __privateSet(this, _bytesRead, 0); + __privateSet(this, _parent, null); + __privateSet(this, _maxInflation, maxInflation != null ? maxInflation : 1024); + __privateSet(this, _offset, 0); } - /** - * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with - * %%password%%. - * - * If %%progressCallback%% is specified, it will receive periodic - * updates as the encryption process progreses. - */ - async encrypt(password, progressCallback) { - const account2 = { address: this.address, privateKey: this.privateKey }; - return await encryptKeystoreJson(account2, password, { progressCallback }); + get data() { + return hexlify(__privateGet(this, _data3)); } - /** - * Returns a [JSON Keystore Wallet](json-wallets) encryped with - * %%password%%. - * - * It is preferred to use the [async version](encrypt) instead, - * which allows a [[ProgressCallback]] to keep the user informed. - * - * This method will block the event loop (freezing all UI) until - * it is complete, which may be a non-trivial duration. - */ - encryptSync(password) { - const account2 = { address: this.address, privateKey: this.privateKey }; - return encryptKeystoreJsonSync(account2, password); + get dataLength() { + return __privateGet(this, _data3).length; } - /** - * Creates (asynchronously) a **Wallet** by decrypting the %%json%% - * with %%password%%. - * - * If %%progress%% is provided, it is called periodically during - * decryption so that any UI can be updated. - */ - static async fromEncryptedJson(json, password, progress2) { - var _a2; - let account2 = null; - if (isKeystoreJson(json)) { - account2 = await decryptKeystoreJson(json, password, progress2); - } else if (isCrowdsaleJson(json)) { - if (progress2) { - progress2(0); - await stall(0); - } - account2 = decryptCrowdsaleJson(json, password); - if (progress2) { - progress2(1); - await stall(0); - } - } - return __privateMethod(_a2 = _c, _Wallet_static, fromAccount_fn).call(_a2, account2); + get consumed() { + return __privateGet(this, _offset); } - /** - * Creates a **Wallet** by decrypting the %%json%% with %%password%%. - * - * The [[fromEncryptedJson]] method is preferred, as this method - * will lock up and freeze the UI during decryption, which may take - * some time. - */ - static fromEncryptedJsonSync(json, password) { - var _a2; - let account2 = null; - if (isKeystoreJson(json)) { - account2 = decryptKeystoreJsonSync(json, password); - } else if (isCrowdsaleJson(json)) { - account2 = decryptCrowdsaleJson(json, password); - } else { - assertArgument(false, "invalid JSON wallet", "json", "[ REDACTED ]"); - } - return __privateMethod(_a2 = _c, _Wallet_static, fromAccount_fn).call(_a2, account2); + get bytes() { + return new Uint8Array(__privateGet(this, _data3)); } - /** - * Creates a new random [[HDNodeWallet]] using the available - * [cryptographic random source](randomBytes). - * - * If there is no crytographic random source, this will throw. - */ - static createRandom(provider2) { - const wallet = HDNodeWallet.createRandom(); - if (provider2) { - return wallet.connect(provider2); - } - return wallet; + // Create a sub-reader with the same underlying data, but offset + subReader(offset2) { + const reader2 = new _Reader(__privateGet(this, _data3).slice(__privateGet(this, _offset) + offset2), this.allowLoose, __privateGet(this, _maxInflation)); + __privateSet(reader2, _parent, this); + return reader2; } - /** - * Creates a [[HDNodeWallet]] for %%phrase%%. - */ - static fromPhrase(phrase, provider2) { - const wallet = HDNodeWallet.fromPhrase(phrase); - if (provider2) { - return wallet.connect(provider2); - } - return wallet; + // Read bytes + readBytes(length, loose) { + let bytes2 = __privateMethod(this, _Reader_instances, peekBytes_fn).call(this, 0, length, !!loose); + __privateMethod(this, _Reader_instances, incrementBytesRead_fn).call(this, length); + __privateSet(this, _offset, __privateGet(this, _offset) + bytes2.length); + return bytes2.slice(0, length); } -}, _Wallet_static = new WeakSet(), fromAccount_fn = function(account2) { - assertArgument(account2, "invalid JSON wallet", "json", "[ REDACTED ]"); - if ("mnemonic" in account2 && account2.mnemonic && account2.mnemonic.locale === "en") { - const mnemonic = Mnemonic.fromEntropy(account2.mnemonic.entropy); - const wallet2 = HDNodeWallet.fromMnemonic(mnemonic, account2.mnemonic.path); - if (wallet2.address === account2.address && wallet2.privateKey === account2.privateKey) { - return wallet2; - } - console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key"); + // Read a numeric values + readValue() { + return toBigInt(this.readBytes(WordSize)); } - const wallet = new _c(account2.privateKey); - assertArgument(wallet.address === account2.address, "address/privateKey mismatch", "json", "[ REDACTED ]"); - return wallet; -}, __privateAdd(_c, _Wallet_static), _c); -const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; -function decodeBits(width, data) { - const maxValue2 = (1 << width) - 1; - const result = []; - let accum = 0, bits = 0, flood = 0; - for (let i = 0; i < data.length; i++) { - accum = accum << 6 | Base64.indexOf(data[i]); - bits += 6; - while (bits >= width) { - const value = accum >> bits - width; - accum &= (1 << bits - width) - 1; - bits -= width; - if (value === 0) { - flood += maxValue2; - } else { - result.push(value + flood); - flood = 0; - } + readIndex() { + return toNumber(this.readBytes(WordSize)); + } +}; +_data3 = new WeakMap(); +_offset = new WeakMap(); +_bytesRead = new WeakMap(); +_parent = new WeakMap(); +_maxInflation = new WeakMap(); +_Reader_instances = new WeakSet(); +incrementBytesRead_fn = function(count2) { + var _a2; + if (__privateGet(this, _parent)) { + return __privateMethod(_a2 = __privateGet(this, _parent), _Reader_instances, incrementBytesRead_fn).call(_a2, count2); + } + __privateSet(this, _bytesRead, __privateGet(this, _bytesRead) + count2); + assert(__privateGet(this, _maxInflation) < 1 || __privateGet(this, _bytesRead) <= __privateGet(this, _maxInflation) * this.dataLength, `compressed ABI data exceeds inflation ratio of ${__privateGet(this, _maxInflation)} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`, "BUFFER_OVERRUN", { + buffer: getBytesCopy(__privateGet(this, _data3)), + offset: __privateGet(this, _offset), + length: count2, + info: { + bytesRead: __privateGet(this, _bytesRead), + dataLength: this.dataLength + } + }); +}; +peekBytes_fn = function(offset2, length, loose) { + let alignedLength = Math.ceil(length / WordSize) * WordSize; + if (__privateGet(this, _offset) + alignedLength > __privateGet(this, _data3).length) { + if (this.allowLoose && loose && __privateGet(this, _offset) + length <= __privateGet(this, _data3).length) { + alignedLength = length; + } else { + assert(false, "data out-of-bounds", "BUFFER_OVERRUN", { + buffer: getBytesCopy(__privateGet(this, _data3)), + length: __privateGet(this, _data3).length, + offset: __privateGet(this, _offset) + alignedLength + }); } } - return result; + return __privateGet(this, _data3).slice(__privateGet(this, _offset), __privateGet(this, _offset) + alignedLength); +}; +let Reader = _Reader; +const global$1 = globalThis || void 0 || self; +function number(n2) { + if (!Number.isSafeInteger(n2) || n2 < 0) + throw new Error(`Wrong positive integer: ${n2}`); } -function decodeOwlA(data, accents) { - let words2 = decodeOwl(data).join(","); - accents.split(/,/g).forEach((accent) => { - const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); - assertArgument(match !== null, "internal error parsing accents", "accents", accents); - let posOffset = 0; - const positions = decodeBits(parseInt(match[3]), match[4]); - const charCode = parseInt(match[2]); - const regex = new RegExp(`([${match[1]}])`, "g"); - words2 = words2.replace(regex, (all, letter) => { - const rem = --positions[posOffset]; - if (rem === 0) { - letter = String.fromCharCode(letter.charCodeAt(0), charCode); - posOffset++; - } - return letter; - }); - }); - return words2.split(","); +function bytes$1(b2, ...lengths) { + if (!(b2 instanceof Uint8Array)) + throw new Error("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b2.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b2.length}`); } -class WordlistOwlA extends WordlistOwl { - /** - * Creates a new Wordlist for %%locale%% using the OWLA %%data%% - * and %%accent%% data and validated against the %%checksum%%. - */ - constructor(locale, data, accent, checksum2) { - super(locale, data, checksum2); - __privateAdd(this, _accent); - __privateSet(this, _accent, accent); - } - /** - * The OWLA-encoded accent data. - */ - get _accent() { - return __privateGet(this, _accent); - } - /** - * Decode all the words for the wordlist. - */ - _decodeWords() { - return decodeOwlA(this._data, this._accent); +function hash(hash2) { + if (typeof hash2 !== "function" || typeof hash2.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number(hash2.outputLen); + number(hash2.blockLen); +} +function exists$1(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function output$1(out, instance) { + bytes$1(out); + const min2 = instance.outputLen; + if (out.length < min2) { + throw new Error(`digestInto() expects output buffer of length at least ${min2}`); } } -_accent = new WeakMap(); -const wordlists = { - en: LangEn.wordlist() +const crypto$2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const u8a$1 = (a2) => a2 instanceof Uint8Array; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +const createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +const rotr$1 = (word, shift2) => word << 32 - shift2 | word >>> shift2; +const isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; +if (!isLE) + throw new Error("Non little-endian hardware is not supported"); +const nextTick = async () => { }; -const ethers = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - AbiCoder, - AbstractProvider, - AbstractSigner, - AlchemyProvider, - AnkrProvider, - BaseContract, - BaseWallet, - Block, - BrowserProvider, - ChainstackProvider, - CloudflareProvider, - ConstructorFragment, - Contract, - ContractEventPayload, - ContractFactory, - ContractTransactionReceipt, - ContractTransactionResponse, - ContractUnknownEventPayload, - EnsPlugin, - EnsResolver, - ErrorDescription, - ErrorFragment, - EtherSymbol, - EtherscanPlugin, - EtherscanProvider, - EventFragment, - EventLog, - EventPayload, - FallbackFragment, - FallbackProvider, - FeeData, - FeeDataNetworkPlugin, - FetchCancelSignal, - FetchRequest, - FetchResponse, - FetchUrlFeeDataNetworkPlugin, - FixedNumber, - Fragment, - FunctionFragment, - GasCostPlugin, - HDNodeVoidWallet, - HDNodeWallet, - Indexed, - InfuraProvider, - InfuraWebSocketProvider, - Interface, - IpcSocketProvider, - JsonRpcApiProvider, - JsonRpcProvider: JsonRpcProvider$1, - JsonRpcSigner, - LangEn, - Log, - LogDescription, - MaxInt256, - MaxUint256, - MessagePrefix, - MinInt256, - Mnemonic, - MulticoinProviderPlugin, - N: N$1, - NamedFragment, - Network, - NetworkPlugin, - NonceManager, - ParamType, - PocketProvider, - QuickNodeProvider, - Result, - Signature, - SigningKey, - SocketBlockSubscriber, - SocketEventSubscriber, - SocketPendingSubscriber, - SocketProvider, - SocketSubscriber, - StructFragment, - Transaction, - TransactionDescription, - TransactionReceipt, - TransactionResponse, - Typed, - TypedDataEncoder, - UndecodedEventLog, - UnmanagedSubscriber, - Utf8ErrorFuncs, - VoidSigner, - Wallet: Wallet$1, - WebSocketProvider, - WeiPerEther, - Wordlist, - WordlistOwl, - WordlistOwlA, - ZeroAddress, - ZeroHash, - accessListify, - assert, - assertArgument, - assertArgumentCount, - assertNormalize, - assertPrivate, - checkResultErrors, - computeAddress, - computeHmac, - concat: concat$1, - copyRequest, - dataLength, - dataSlice, - decodeBase58, - decodeBase64, - decodeBytes32String, - decodeRlp, - decryptCrowdsaleJson, - decryptKeystoreJson, - decryptKeystoreJsonSync, - defaultPath, - defineProperties: defineProperties$1, - dnsEncode, - encodeBase58, - encodeBase64, - encodeBytes32String, - encodeRlp, - encryptKeystoreJson, - encryptKeystoreJsonSync, - ensNormalize, - formatEther: formatEther$2, - formatUnits: formatUnits$2, - fromTwos, - getAccountPath, - getAddress: getAddress$1, - getBigInt, - getBytes, - getBytesCopy, - getCreate2Address, - getCreateAddress, - getDefaultProvider, - getIcapAddress, - getIndexedAccountPath, - getNumber, - getUint, - hashMessage: hashMessage$1, - hexlify, - id: id$1, - isAddress: isAddress$1, - isAddressable, - isBytesLike, - isCallException, - isCrowdsaleJson, - isError, - isHexString, - isKeystoreJson, - isValidName, - keccak256: keccak256$1, - lock, - makeError, - mask, - namehash: namehash$1, - parseEther: parseEther$1, - parseUnits: parseUnits$3, - pbkdf2, - randomBytes: randomBytes$1, - recoverAddress: recoverAddress$1, - resolveAddress, - resolveProperties: resolveProperties$1, - ripemd160, - scrypt, - scryptSync, - sha256: sha256$3, - sha512, - showThrottleMessage, - solidityPacked, - solidityPackedKeccak256, - solidityPackedSha256, - stripZerosLeft, - toBeArray, - toBeHex, - toBigInt, - toNumber, - toQuantity, - toTwos, - toUtf8Bytes, - toUtf8CodePoints, - toUtf8String, - uuidV4, - verifyMessage: verifyMessage$1, - verifyTypedData: verifyTypedData$1, - version: version$9, - wordlists, - zeroPadBytes, - zeroPadValue -}, Symbol.toStringTag, { value: "Module" })); -var buffer$2 = {}; -var base64Js = {}; -base64Js.byteLength = byteLength; -base64Js.toByteArray = toByteArray; -base64Js.fromByteArray = fromByteArray; -var lookup = []; -var revLookup = []; -var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; -var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -for (var i$2 = 0, len = code.length; i$2 < len; ++i$2) { - lookup[i$2] = code[i$2]; - revLookup[code.charCodeAt(i$2)] = i$2; +async function asyncLoop(iters, tick, cb2) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb2(i); + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } } -revLookup["-".charCodeAt(0)] = 62; -revLookup["_".charCodeAt(0)] = 63; -function getLens(b64) { - var len = b64.length; - if (len % 4 > 0) { - throw new Error("Invalid string. Length must be a multiple of 4"); +function utf8ToBytes$2(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes$1(data) { + if (typeof data === "string") + data = utf8ToBytes$2(data); + if (!u8a$1(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +function concatBytes$1(...arrays) { + const r2 = new Uint8Array(arrays.reduce((sum, a2) => sum + a2.length, 0)); + let pad2 = 0; + arrays.forEach((a2) => { + if (!u8a$1(a2)) + throw new Error("Uint8Array expected"); + r2.set(a2, pad2); + pad2 += a2.length; + }); + return r2; +} +let Hash$1 = class Hash2 { + // Safe version that clones internal state + clone() { + return this._cloneInto(); } - var validLen = b64.indexOf("="); - if (validLen === -1) validLen = len; - var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; +}; +const toStr = {}.toString; +function checkOpts(defaults2, opts) { + if (opts !== void 0 && toStr.call(opts) !== "[object Object]") + throw new Error("Options should be object or undefined"); + const merged = Object.assign(defaults2, opts); + return merged; } -function byteLength(b64) { - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +function wrapConstructor$1(hashCons) { + const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; } -function _byteLength(b64, validLen, placeHoldersLen) { - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +function randomBytes$2(bytesLength = 32) { + if (crypto$2 && typeof crypto$2.getRandomValues === "function") { + return crypto$2.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error("crypto.getRandomValues must be defined"); } -function toByteArray(b64) { - var tmp; - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - var curByte = 0; - var len = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i; - for (i = 0; i < len; i += 4) { - tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; - arr[curByte++] = tmp >> 16 & 255; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; +class HMAC2 extends Hash$1 { + constructor(hash$12, _key) { + super(); + this.finished = false; + this.destroyed = false; + hash(hash$12); + const key = toBytes$1(_key); + this.iHash = hash$12.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad2 = new Uint8Array(blockLen); + pad2.set(key.length > blockLen ? hash$12.create().update(key).digest() : key); + for (let i = 0; i < pad2.length; i++) + pad2[i] ^= 54; + this.iHash.update(pad2); + this.oHash = hash$12.create(); + for (let i = 0; i < pad2.length; i++) + pad2[i] ^= 54 ^ 92; + this.oHash.update(pad2); + pad2.fill(0); } - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; - arr[curByte++] = tmp & 255; + update(buf) { + exists$1(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + exists$1(this); + bytes$1(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; } - if (placeHoldersLen === 1) { - tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); } - return arr; } -function tripletToBase64(num) { - return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; +const hmac$1 = (hash2, key, message) => new HMAC2(hash2, key).update(message).digest(); +hmac$1.create = (hash2, key) => new HMAC2(hash2, key); +function pbkdf2Init(hash$12, _password, _salt, _opts) { + hash(hash$12); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c: c2, dkLen, asyncTick } = opts; + number(c2); + number(dkLen); + number(asyncTick); + if (c2 < 1) + throw new Error("PBKDF2: iterations (c) should be >= 1"); + const password = toBytes$1(_password); + const salt = toBytes$1(_salt); + const DK = new Uint8Array(dkLen); + const PRF = hmac$1.create(hash$12, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c: c2, dkLen, asyncTick, DK, PRF, PRFSalt }; } -function encodeChunk(uint8, start, end) { - var tmp; - var output2 = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255); - output2.push(tripletToBase64(tmp)); +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u2) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u2.fill(0); + return DK; +} +function pbkdf2$1(hash2, password, salt, opts) { + const { c: c2, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash2, password, salt, opts); + let prfW; + const arr = new Uint8Array(4); + const view = createView$1(arr); + const u2 = new Uint8Array(PRF.outputLen); + for (let ti2 = 1, pos = 0; pos < dkLen; ti2++, pos += PRF.outputLen) { + const Ti2 = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti2, false); + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u2); + Ti2.set(u2.subarray(0, Ti2.length)); + for (let ui2 = 1; ui2 < c2; ui2++) { + PRF._cloneInto(prfW).update(u2).digestInto(u2); + for (let i = 0; i < Ti2.length; i++) + Ti2[i] ^= u2[i]; + } } - return output2.join(""); + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u2); } -function fromByteArray(uint8) { - var tmp; - var len = uint8.length; - var extraBytes = len % 3; - var parts = []; - var maxChunkLength = 16383; - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); +function setBigUint64$1(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh2 = Number(value >> _32n2 & _u32_max); + const wl = Number(value & _u32_max); + const h2 = isLE2 ? 4 : 0; + const l2 = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h2, wh2, isLE2); + view.setUint32(byteOffset + l2, wl, isLE2); +} +class SHA2 extends Hash$1 { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView$1(this.buffer); } - if (extraBytes === 1) { - tmp = uint8[len - 1]; - parts.push( - lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" - ); - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1]; - parts.push( - lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" - ); + update(data) { + exists$1(this); + const { view, buffer: buffer2, blockLen } = this; + data = toBytes$1(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView$1(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists$1(this); + output$1(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer2[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer2[i] = 0; + setBigUint64$1(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView$1(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer2); + return to; } - return parts.join(""); } -var ieee754 = {}; -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -ieee754.read = function(buffer2, offset2, isLE2, mLen, nBytes) { - var e2, m2; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE2 ? nBytes - 1 : 0; - var d2 = isLE2 ? -1 : 1; - var s2 = buffer2[offset2 + i]; - i += d2; - e2 = s2 & (1 << -nBits) - 1; - s2 >>= -nBits; - nBits += eLen; - for (; nBits > 0; e2 = e2 * 256 + buffer2[offset2 + i], i += d2, nBits -= 8) { +const Chi$1 = (a2, b2, c2) => a2 & b2 ^ ~a2 & c2; +const Maj$1 = (a2, b2, c2) => a2 & b2 ^ a2 & c2 ^ b2 & c2; +const SHA256_K$1 = /* @__PURE__ */ new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +const IV = /* @__PURE__ */ new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +const SHA256_W$1 = /* @__PURE__ */ new Uint32Array(64); +let SHA256$1 = class SHA2562 extends SHA2 { + constructor() { + super(64, 32, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; } - m2 = e2 & (1 << -nBits) - 1; - e2 >>= -nBits; - nBits += mLen; - for (; nBits > 0; m2 = m2 * 256 + buffer2[offset2 + i], i += d2, nBits -= 8) { + get() { + const { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; + return [A2, B2, C2, D2, E2, F2, G2, H2]; } - if (e2 === 0) { - e2 = 1 - eBias; - } else if (e2 === eMax) { - return m2 ? NaN : (s2 ? -1 : 1) * Infinity; - } else { - m2 = m2 + Math.pow(2, mLen); - e2 = e2 - eBias; + // prettier-ignore + set(A2, B2, C2, D2, E2, F2, G2, H2) { + this.A = A2 | 0; + this.B = B2 | 0; + this.C = C2 | 0; + this.D = D2 | 0; + this.E = E2 | 0; + this.F = F2 | 0; + this.G = G2 | 0; + this.H = H2 | 0; } - return (s2 ? -1 : 1) * m2 * Math.pow(2, e2 - mLen); -}; -ieee754.write = function(buffer2, value, offset2, isLE2, mLen, nBytes) { - var e2, m2, c2; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = isLE2 ? 0 : nBytes - 1; - var d2 = isLE2 ? 1 : -1; - var s2 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - value = Math.abs(value); - if (isNaN(value) || value === Infinity) { - m2 = isNaN(value) ? 1 : 0; - e2 = eMax; - } else { - e2 = Math.floor(Math.log(value) / Math.LN2); - if (value * (c2 = Math.pow(2, -e2)) < 1) { - e2--; - c2 *= 2; - } - if (e2 + eBias >= 1) { - value += rt / c2; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c2 >= 2) { - e2++; - c2 /= 2; + process(view, offset2) { + for (let i = 0; i < 16; i++, offset2 += 4) + SHA256_W$1[i] = view.getUint32(offset2, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W$1[i - 15]; + const W2 = SHA256_W$1[i - 2]; + const s0 = rotr$1(W15, 7) ^ rotr$1(W15, 18) ^ W15 >>> 3; + const s1 = rotr$1(W2, 17) ^ rotr$1(W2, 19) ^ W2 >>> 10; + SHA256_W$1[i] = s1 + SHA256_W$1[i - 7] + s0 + SHA256_W$1[i - 16] | 0; } - if (e2 + eBias >= eMax) { - m2 = 0; - e2 = eMax; - } else if (e2 + eBias >= 1) { - m2 = (value * c2 - 1) * Math.pow(2, mLen); - e2 = e2 + eBias; - } else { - m2 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e2 = 0; + let { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr$1(E2, 6) ^ rotr$1(E2, 11) ^ rotr$1(E2, 25); + const T12 = H2 + sigma1 + Chi$1(E2, F2, G2) + SHA256_K$1[i] + SHA256_W$1[i] | 0; + const sigma0 = rotr$1(A2, 2) ^ rotr$1(A2, 13) ^ rotr$1(A2, 22); + const T22 = sigma0 + Maj$1(A2, B2, C2) | 0; + H2 = G2; + G2 = F2; + F2 = E2; + E2 = D2 + T12 | 0; + D2 = C2; + C2 = B2; + B2 = A2; + A2 = T12 + T22 | 0; } + A2 = A2 + this.A | 0; + B2 = B2 + this.B | 0; + C2 = C2 + this.C | 0; + D2 = D2 + this.D | 0; + E2 = E2 + this.E | 0; + F2 = F2 + this.F | 0; + G2 = G2 + this.G | 0; + H2 = H2 + this.H | 0; + this.set(A2, B2, C2, D2, E2, F2, G2, H2); } - for (; mLen >= 8; buffer2[offset2 + i] = m2 & 255, i += d2, m2 /= 256, mLen -= 8) { + roundClean() { + SHA256_W$1.fill(0); } - e2 = e2 << mLen | m2; - eLen += mLen; - for (; eLen > 0; buffer2[offset2 + i] = e2 & 255, i += d2, e2 /= 256, eLen -= 8) { + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); } - buffer2[offset2 + i - d2] |= s2 * 128; }; -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -(function(exports) { - const base64 = base64Js; - const ieee754$1 = ieee754; - const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; - exports.Buffer = Buffer3; - exports.SlowBuffer = SlowBuffer2; - exports.INSPECT_MAX_BYTES = 50; - const K_MAX_LENGTH = 2147483647; - exports.kMaxLength = K_MAX_LENGTH; - const { Uint8Array: GlobalUint8Array, ArrayBuffer: GlobalArrayBuffer, SharedArrayBuffer: GlobalSharedArrayBuffer } = globalThis; - Buffer3.TYPED_ARRAY_SUPPORT = typedArraySupport(); - if (!Buffer3.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { - try { - const arr = new GlobalUint8Array(1); - const proto = { foo: function() { - return 42; - } }; - Object.setPrototypeOf(proto, GlobalUint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e2) { - return false; - } +const sha256$2 = /* @__PURE__ */ wrapConstructor$1(() => new SHA256$1()); +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +function fromBig(n2, le2 = false) { + if (le2) + return { h: Number(n2 & U32_MASK64), l: Number(n2 >> _32n & U32_MASK64) }; + return { h: Number(n2 >> _32n & U32_MASK64) | 0, l: Number(n2 & U32_MASK64) | 0 }; +} +function split$1(lst, le2 = false) { + let Ah2 = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h: h2, l: l2 } = fromBig(lst[i], le2); + [Ah2[i], Al[i]] = [h2, l2]; } - Object.defineProperty(Buffer3.prototype, "parent", { - enumerable: true, - get: function() { - if (!Buffer3.isBuffer(this)) return void 0; - return this.buffer; - } - }); - Object.defineProperty(Buffer3.prototype, "offset", { - enumerable: true, - get: function() { - if (!Buffer3.isBuffer(this)) return void 0; - return this.byteOffset; - } - }); - function createBuffer(length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"'); - } - const buf = new GlobalUint8Array(length); - Object.setPrototypeOf(buf, Buffer3.prototype); - return buf; + return [Ah2, Al]; +} +const toBig = (h2, l2) => BigInt(h2 >>> 0) << _32n | BigInt(l2 >>> 0); +const shrSH = (h2, _l2, s2) => h2 >>> s2; +const shrSL = (h2, l2, s2) => h2 << 32 - s2 | l2 >>> s2; +const rotrSH = (h2, l2, s2) => h2 >>> s2 | l2 << 32 - s2; +const rotrSL = (h2, l2, s2) => h2 << 32 - s2 | l2 >>> s2; +const rotrBH = (h2, l2, s2) => h2 << 64 - s2 | l2 >>> s2 - 32; +const rotrBL = (h2, l2, s2) => h2 >>> s2 - 32 | l2 << 64 - s2; +const rotr32H = (_h2, l2) => l2; +const rotr32L = (h2, _l2) => h2; +const rotlSH = (h2, l2, s2) => h2 << s2 | l2 >>> 32 - s2; +const rotlSL = (h2, l2, s2) => l2 << s2 | h2 >>> 32 - s2; +const rotlBH = (h2, l2, s2) => l2 << s2 - 32 | h2 >>> 64 - s2; +const rotlBL = (h2, l2, s2) => h2 << s2 - 32 | l2 >>> 64 - s2; +function add(Ah2, Al, Bh2, Bl) { + const l2 = (Al >>> 0) + (Bl >>> 0); + return { h: Ah2 + Bh2 + (l2 / 2 ** 32 | 0) | 0, l: l2 | 0 }; +} +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah2, Bh2, Ch2) => Ah2 + Bh2 + Ch2 + (low / 2 ** 32 | 0) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah2, Bh2, Ch2, Dh2) => Ah2 + Bh2 + Ch2 + Dh2 + (low / 2 ** 32 | 0) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah2, Bh2, Ch2, Dh2, Eh2) => Ah2 + Bh2 + Ch2 + Dh2 + Eh2 + (low / 2 ** 32 | 0) | 0; +const u64 = { + fromBig, + split: split$1, + toBig, + shrSH, + shrSL, + rotrSH, + rotrSL, + rotrBH, + rotrBL, + rotr32H, + rotr32L, + rotlSH, + rotlSL, + rotlBH, + rotlBL, + add, + add3L, + add3H, + add4L, + add4H, + add5H, + add5L +}; +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + "0x428a2f98d728ae22", + "0x7137449123ef65cd", + "0xb5c0fbcfec4d3b2f", + "0xe9b5dba58189dbbc", + "0x3956c25bf348b538", + "0x59f111f1b605d019", + "0x923f82a4af194f9b", + "0xab1c5ed5da6d8118", + "0xd807aa98a3030242", + "0x12835b0145706fbe", + "0x243185be4ee4b28c", + "0x550c7dc3d5ffb4e2", + "0x72be5d74f27b896f", + "0x80deb1fe3b1696b1", + "0x9bdc06a725c71235", + "0xc19bf174cf692694", + "0xe49b69c19ef14ad2", + "0xefbe4786384f25e3", + "0x0fc19dc68b8cd5b5", + "0x240ca1cc77ac9c65", + "0x2de92c6f592b0275", + "0x4a7484aa6ea6e483", + "0x5cb0a9dcbd41fbd4", + "0x76f988da831153b5", + "0x983e5152ee66dfab", + "0xa831c66d2db43210", + "0xb00327c898fb213f", + "0xbf597fc7beef0ee4", + "0xc6e00bf33da88fc2", + "0xd5a79147930aa725", + "0x06ca6351e003826f", + "0x142929670a0e6e70", + "0x27b70a8546d22ffc", + "0x2e1b21385c26c926", + "0x4d2c6dfc5ac42aed", + "0x53380d139d95b3df", + "0x650a73548baf63de", + "0x766a0abb3c77b2a8", + "0x81c2c92e47edaee6", + "0x92722c851482353b", + "0xa2bfe8a14cf10364", + "0xa81a664bbc423001", + "0xc24b8b70d0f89791", + "0xc76c51a30654be30", + "0xd192e819d6ef5218", + "0xd69906245565a910", + "0xf40e35855771202a", + "0x106aa07032bbd1b8", + "0x19a4c116b8d2d0c8", + "0x1e376c085141ab53", + "0x2748774cdf8eeb99", + "0x34b0bcb5e19b48a8", + "0x391c0cb3c5c95a63", + "0x4ed8aa4ae3418acb", + "0x5b9cca4f7763e373", + "0x682e6ff3d6b2b8a3", + "0x748f82ee5defb2fc", + "0x78a5636f43172f60", + "0x84c87814a1f0ab72", + "0x8cc702081a6439ec", + "0x90befffa23631e28", + "0xa4506cebde82bde9", + "0xbef9a3f7b2c67915", + "0xc67178f2e372532b", + "0xca273eceea26619c", + "0xd186b8c721c0c207", + "0xeada7dd6cde0eb1e", + "0xf57d4f7fee6ed178", + "0x06f067aa72176fba", + "0x0a637dc5a2c898a6", + "0x113f9804bef90dae", + "0x1b710b35131c471b", + "0x28db77f523047d84", + "0x32caab7b40c72493", + "0x3c9ebe0a15c9bebc", + "0x431d67c49c100d4c", + "0x4cc5d4becb3e42b6", + "0x597f299cfc657e2a", + "0x5fcb6fab3ad6faec", + "0x6c44198c4a475817" +].map((n2) => BigInt(n2))))(); +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends SHA2 { + constructor() { + super(128, 64, 16, false); + this.Ah = 1779033703 | 0; + this.Al = 4089235720 | 0; + this.Bh = 3144134277 | 0; + this.Bl = 2227873595 | 0; + this.Ch = 1013904242 | 0; + this.Cl = 4271175723 | 0; + this.Dh = 2773480762 | 0; + this.Dl = 1595750129 | 0; + this.Eh = 1359893119 | 0; + this.El = 2917565137 | 0; + this.Fh = 2600822924 | 0; + this.Fl = 725511199 | 0; + this.Gh = 528734635 | 0; + this.Gl = 4215389547 | 0; + this.Hh = 1541459225 | 0; + this.Hl = 327033209 | 0; } - function Buffer3(arg, encodingOrOffset, length) { - if (typeof arg === "number") { - if (typeof encodingOrOffset === "string") { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ); - } - return allocUnsafe(arg); - } - return from(arg, encodingOrOffset, length); + // prettier-ignore + get() { + const { Ah: Ah2, Al, Bh: Bh2, Bl, Ch: Ch2, Cl, Dh: Dh2, Dl, Eh: Eh2, El, Fh: Fh2, Fl, Gh: Gh2, Gl, Hh: Hh2, Hl } = this; + return [Ah2, Al, Bh2, Bl, Ch2, Cl, Dh2, Dl, Eh2, El, Fh2, Fl, Gh2, Gl, Hh2, Hl]; } - Buffer3.poolSize = 8192; - function from(value, encodingOrOffset, length) { - if (typeof value === "string") { - return fromString(value, encodingOrOffset); - } - if (GlobalArrayBuffer.isView(value)) { - return fromArrayView(value); - } - if (value == null) { - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - if (isInstance(value, GlobalArrayBuffer) || value && isInstance(value.buffer, GlobalArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - if (typeof GlobalSharedArrayBuffer !== "undefined" && (isInstance(value, GlobalSharedArrayBuffer) || value && isInstance(value.buffer, GlobalSharedArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - if (typeof value === "number") { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ); - } - const valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) { - return Buffer3.from(valueOf, encodingOrOffset, length); - } - const b2 = fromObject(value); - if (b2) return b2; - if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { - return Buffer3.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); - } - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); + // prettier-ignore + set(Ah2, Al, Bh2, Bl, Ch2, Cl, Dh2, Dl, Eh2, El, Fh2, Fl, Gh2, Gl, Hh2, Hl) { + this.Ah = Ah2 | 0; + this.Al = Al | 0; + this.Bh = Bh2 | 0; + this.Bl = Bl | 0; + this.Ch = Ch2 | 0; + this.Cl = Cl | 0; + this.Dh = Dh2 | 0; + this.Dl = Dl | 0; + this.Eh = Eh2 | 0; + this.El = El | 0; + this.Fh = Fh2 | 0; + this.Fl = Fl | 0; + this.Gh = Gh2 | 0; + this.Gl = Gl | 0; + this.Hh = Hh2 | 0; + this.Hl = Hl | 0; } - Buffer3.from = function(value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length); - }; - Object.setPrototypeOf(Buffer3.prototype, GlobalUint8Array.prototype); - Object.setPrototypeOf(Buffer3, GlobalUint8Array); - function assertSize2(size2) { - if (typeof size2 !== "number") { - throw new TypeError('"size" argument must be of type number'); - } else if (size2 < 0) { - throw new RangeError('The value "' + size2 + '" is invalid for option "size"'); + process(view, offset2) { + for (let i = 0; i < 16; i++, offset2 += 4) { + SHA512_W_H[i] = view.getUint32(offset2); + SHA512_W_L[i] = view.getUint32(offset2 += 4); } - } - function alloc(size2, fill, encoding) { - assertSize2(size2); - if (size2 <= 0) { - return createBuffer(size2); + for (let i = 16; i < 80; i++) { + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; } - if (fill !== void 0) { - return typeof encoding === "string" ? createBuffer(size2).fill(fill, encoding) : createBuffer(size2).fill(fill); + let { Ah: Ah2, Al, Bh: Bh2, Bl, Ch: Ch2, Cl, Dh: Dh2, Dl, Eh: Eh2, El, Fh: Fh2, Fl, Gh: Gh2, Gl, Hh: Hh2, Hl } = this; + for (let i = 0; i < 80; i++) { + const sigma1h = u64.rotrSH(Eh2, El, 14) ^ u64.rotrSH(Eh2, El, 18) ^ u64.rotrBH(Eh2, El, 41); + const sigma1l = u64.rotrSL(Eh2, El, 14) ^ u64.rotrSL(Eh2, El, 18) ^ u64.rotrBL(Eh2, El, 41); + const CHIh = Eh2 & Fh2 ^ ~Eh2 & Gh2; + const CHIl = El & Fl ^ ~El & Gl; + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh2, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + const sigma0h = u64.rotrSH(Ah2, Al, 28) ^ u64.rotrBH(Ah2, Al, 34) ^ u64.rotrBH(Ah2, Al, 39); + const sigma0l = u64.rotrSL(Ah2, Al, 28) ^ u64.rotrBL(Ah2, Al, 34) ^ u64.rotrBL(Ah2, Al, 39); + const MAJh = Ah2 & Bh2 ^ Ah2 & Ch2 ^ Bh2 & Ch2; + const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; + Hh2 = Gh2 | 0; + Hl = Gl | 0; + Gh2 = Fh2 | 0; + Gl = Fl | 0; + Fh2 = Eh2 | 0; + Fl = El | 0; + ({ h: Eh2, l: El } = u64.add(Dh2 | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh2 = Ch2 | 0; + Dl = Cl | 0; + Ch2 = Bh2 | 0; + Cl = Bl | 0; + Bh2 = Ah2 | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah2 = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; } - return createBuffer(size2); + ({ h: Ah2, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah2 | 0, Al | 0)); + ({ h: Bh2, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh2 | 0, Bl | 0)); + ({ h: Ch2, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch2 | 0, Cl | 0)); + ({ h: Dh2, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh2 | 0, Dl | 0)); + ({ h: Eh2, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh2 | 0, El | 0)); + ({ h: Fh2, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh2 | 0, Fl | 0)); + ({ h: Gh2, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh2 | 0, Gl | 0)); + ({ h: Hh2, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh2 | 0, Hl | 0)); + this.set(Ah2, Al, Bh2, Bl, Ch2, Cl, Dh2, Dl, Eh2, El, Fh2, Fl, Gh2, Gl, Hh2, Hl); } - Buffer3.alloc = function(size2, fill, encoding) { - return alloc(size2, fill, encoding); - }; - function allocUnsafe(size2) { - assertSize2(size2); - return createBuffer(size2 < 0 ? 0 : checked(size2) | 0); + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); } - Buffer3.allocUnsafe = function(size2) { - return allocUnsafe(size2); - }; - Buffer3.allocUnsafeSlow = function(size2) { - return allocUnsafe(size2); - }; - function fromString(string, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - if (!Buffer3.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - const length = byteLength2(string, encoding) | 0; - let buf = createBuffer(length); - const actual = buf.write(string, encoding); - if (actual !== length) { - buf = buf.slice(0, actual); - } - return buf; + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } - function fromArrayLike(array) { - const length = array.length < 0 ? 0 : checked(array.length) | 0; - const buf = createBuffer(length); - for (let i = 0; i < length; i += 1) { - buf[i] = array[i] & 255; - } - return buf; +} +const sha512$1 = /* @__PURE__ */ wrapConstructor$1(() => new SHA512()); +function getGlobal$1() { + if (typeof self !== "undefined") { + return self; } - function fromArrayView(arrayView) { - if (isInstance(arrayView, GlobalUint8Array)) { - const copy2 = new GlobalUint8Array(arrayView); - return fromArrayBuffer(copy2.buffer, copy2.byteOffset, copy2.byteLength); - } - return fromArrayLike(arrayView); + if (typeof window !== "undefined") { + return window; } - function fromArrayBuffer(array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - let buf; - if (byteOffset === void 0 && length === void 0) { - buf = new GlobalUint8Array(array); - } else if (length === void 0) { - buf = new GlobalUint8Array(array, byteOffset); - } else { - buf = new GlobalUint8Array(array, byteOffset, length); - } - Object.setPrototypeOf(buf, Buffer3.prototype); - return buf; + if (typeof global$1 !== "undefined") { + return global$1; } - function fromObject(obj) { - if (Buffer3.isBuffer(obj)) { - const len = checked(obj.length) | 0; - const buf = createBuffer(len); - if (buf.length === 0) { - return buf; - } - obj.copy(buf, 0, 0, len); - return buf; - } - if (obj.length !== void 0) { - if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { - return createBuffer(0); - } - return fromArrayLike(obj); - } - if (obj.type === "Buffer" && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } + throw new Error("unable to locate global object"); +} +const anyGlobal = getGlobal$1(); +const crypto$1 = anyGlobal.crypto || anyGlobal.msCrypto; +function createHash(algo) { + switch (algo) { + case "sha256": + return sha256$2.create(); + case "sha512": + return sha512$1.create(); } - function checked(length) { - if (length >= K_MAX_LENGTH) { - throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); - } - return length | 0; + assertArgument(false, "invalid hashing algorithm name", "algorithm", algo); +} +function createHmac(_algo, key) { + const algo = { sha256: sha256$2, sha512: sha512$1 }[_algo]; + assertArgument(algo != null, "invalid hmac algorithm", "algorithm", _algo); + return hmac$1.create(algo, key); +} +function pbkdf2Sync(password, salt, iterations, keylen, _algo) { + const algo = { sha256: sha256$2, sha512: sha512$1 }[_algo]; + assertArgument(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo); + return pbkdf2$1(algo, password, salt, { c: iterations, dkLen: keylen }); +} +function randomBytes$1(length) { + assert(crypto$1 != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", { + operation: "randomBytes" + }); + assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length); + const result = new Uint8Array(length); + crypto$1.getRandomValues(result); + return result; +} +let locked$4 = false; +const _computeHmac = function(algorithm, key, data) { + return createHmac(algorithm, key).update(data).digest(); +}; +let __computeHmac = _computeHmac; +function computeHmac(algorithm, _key, _data6) { + const key = getBytes(_key, "key"); + const data = getBytes(_data6, "data"); + return hexlify(__computeHmac(algorithm, key, data)); +} +computeHmac._ = _computeHmac; +computeHmac.lock = function() { + locked$4 = true; +}; +computeHmac.register = function(func) { + if (locked$4) { + throw new Error("computeHmac is locked"); } - function SlowBuffer2(length) { - if (+length != length) { - length = 0; - } - return Buffer3.alloc(+length); + __computeHmac = func; +}; +Object.freeze(computeHmac); +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n$4 = /* @__PURE__ */ BigInt(0); +const _1n$5 = /* @__PURE__ */ BigInt(1); +const _2n$3 = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(113); +for (let round2 = 0, R2 = _1n$5, x2 = 1, y2 = 0; round2 < 24; round2++) { + [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; + SHA3_PI.push(2 * (5 * y2 + x2)); + SHA3_ROTL.push((round2 + 1) * (round2 + 2) / 2 % 64); + let t2 = _0n$4; + for (let j2 = 0; j2 < 7; j2++) { + R2 = (R2 << _1n$5 ^ (R2 >> _7n) * _0x71n) % _256n; + if (R2 & _2n$3) + t2 ^= _1n$5 << (_1n$5 << /* @__PURE__ */ BigInt(j2)) - _1n$5; } - Buffer3.isBuffer = function isBuffer(b2) { - return b2 != null && b2._isBuffer === true && b2 !== Buffer3.prototype; - }; - Buffer3.compare = function compare(a2, b2) { - if (isInstance(a2, GlobalUint8Array)) a2 = Buffer3.from(a2, a2.offset, a2.byteLength); - if (isInstance(b2, GlobalUint8Array)) b2 = Buffer3.from(b2, b2.offset, b2.byteLength); - if (!Buffer3.isBuffer(a2) || !Buffer3.isBuffer(b2)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ); - } - if (a2 === b2) return 0; - let x2 = a2.length; - let y2 = b2.length; - for (let i = 0, len = Math.min(x2, y2); i < len; ++i) { - if (a2[i] !== b2[i]) { - x2 = a2[i]; - y2 = b2[i]; - break; - } - } - if (x2 < y2) return -1; - if (y2 < x2) return 1; - return 0; - }; - Buffer3.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "latin1": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return true; - default: - return false; - } - }; - Buffer3.concat = function concat2(list2, length) { - if (!Array.isArray(list2)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - if (list2.length === 0) { - return Buffer3.alloc(0); - } - let i; - if (length === void 0) { - length = 0; - for (i = 0; i < list2.length; ++i) { - length += list2[i].length; - } - } - const buffer2 = Buffer3.allocUnsafe(length); - let pos = 0; - for (i = 0; i < list2.length; ++i) { - let buf = list2[i]; - if (isInstance(buf, GlobalUint8Array)) { - if (pos + buf.length > buffer2.length) { - if (!Buffer3.isBuffer(buf)) buf = Buffer3.from(buf); - buf.copy(buffer2, pos); - } else { - GlobalUint8Array.prototype.set.call( - buffer2, - buf, - pos - ); - } - } else if (!Buffer3.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer2, pos); - } - pos += buf.length; - } - return buffer2; - }; - function byteLength2(string, encoding) { - if (Buffer3.isBuffer(string)) { - return string.length; - } - if (GlobalArrayBuffer.isView(string) || isInstance(string, GlobalArrayBuffer)) { - return string.byteLength; - } - if (typeof string !== "string") { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string - ); - } - const len = string.length; - const mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) return 0; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "ascii": - case "latin1": - case "binary": - return len; - case "utf8": - case "utf-8": - return utf8ToBytes2(string).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return len * 2; - case "hex": - return len >>> 1; - case "base64": - return base64ToBytes(string).length; - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes2(string).length; - } - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; + _SHA3_IOTA.push(t2); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split$1(_SHA3_IOTA, true); +const rotlH = (h2, l2, s2) => s2 > 32 ? rotlBH(h2, l2, s2) : rotlSH(h2, l2, s2); +const rotlL = (h2, l2, s2) => s2 > 32 ? rotlBL(h2, l2, s2) : rotlSL(h2, l2, s2); +function keccakP(s2, rounds = 24) { + const B2 = new Uint32Array(5 * 2); + for (let round2 = 24 - rounds; round2 < 24; round2++) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s2[x2] ^ s2[x2 + 10] ^ s2[x2 + 20] ^ s2[x2 + 30] ^ s2[x2 + 40]; + for (let x2 = 0; x2 < 10; x2 += 2) { + const idx1 = (x2 + 8) % 10; + const idx0 = (x2 + 2) % 10; + const B0 = B2[idx0]; + const B1 = B2[idx0 + 1]; + const Th2 = rotlH(B0, B1, 1) ^ B2[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B2[idx1 + 1]; + for (let y2 = 0; y2 < 50; y2 += 10) { + s2[x2 + y2] ^= Th2; + s2[x2 + y2 + 1] ^= Tl; } } - } - Buffer3.byteLength = byteLength2; - function slowToString(encoding, start, end) { - let loweredCase = false; - if (start === void 0 || start < 0) { - start = 0; - } - if (start > this.length) { - return ""; - } - if (end === void 0 || end > this.length) { - end = this.length; - } - if (end <= 0) { - return ""; - } - end >>>= 0; - start >>>= 0; - if (end <= start) { - return ""; + let curH = s2[2]; + let curL = s2[3]; + for (let t2 = 0; t2 < 24; t2++) { + const shift2 = SHA3_ROTL[t2]; + const Th2 = rotlH(curH, curL, shift2); + const Tl = rotlL(curH, curL, shift2); + const PI = SHA3_PI[t2]; + curH = s2[PI]; + curL = s2[PI + 1]; + s2[PI] = Th2; + s2[PI + 1] = Tl; } - if (!encoding) encoding = "utf8"; - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); - case "ascii": - return asciiSlice(this, start, end); - case "latin1": - case "binary": - return latin1Slice(this, start, end); - case "base64": - return base64Slice(this, start, end); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); - default: - if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } + for (let y2 = 0; y2 < 50; y2 += 10) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s2[y2 + x2]; + for (let x2 = 0; x2 < 10; x2++) + s2[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; } + s2[0] ^= SHA3_IOTA_H[round2]; + s2[1] ^= SHA3_IOTA_L[round2]; } - Buffer3.prototype._isBuffer = true; - function swap(b2, n2, m2) { - const i = b2[n2]; - b2[n2] = b2[m2]; - b2[m2] = i; + B2.fill(0); +} +class Keccak2 extends Hash$1 { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + number(outputLen); + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error("Sha3 supports only keccak-f1600 function"); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); } - Buffer3.prototype.swap16 = function swap16() { - const len = this.length; - if (len % 2 !== 0) { - throw new RangeError("Buffer size must be a multiple of 16-bits"); - } - for (let i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this; - }; - Buffer3.prototype.swap32 = function swap32() { - const len = this.length; - if (len % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (let i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this; - }; - Buffer3.prototype.swap64 = function swap64() { - const len = this.length; - if (len % 8 !== 0) { - throw new RangeError("Buffer size must be a multiple of 64-bits"); - } - for (let i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists$1(this); + const { blockLen, state } = this; + data = toBytes$1(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); } return this; - }; - Buffer3.prototype.toString = function toString2() { - const length = this.length; - if (length === 0) return ""; - if (arguments.length === 0) return utf8Slice(this, 0, length); - return slowToString.apply(this, arguments); - }; - Buffer3.prototype.toLocaleString = Buffer3.prototype.toString; - Buffer3.prototype.equals = function equals(b2) { - if (!Buffer3.isBuffer(b2)) throw new TypeError("Argument must be a Buffer"); - if (this === b2) return true; - return Buffer3.compare(this, b2) === 0; - }; - Buffer3.prototype.inspect = function inspect() { - let str = ""; - const max2 = exports.INSPECT_MAX_BYTES; - str = this.toString("hex", 0, max2).replace(/(.{2})/g, "$1 ").trim(); - if (this.length > max2) str += " ... "; - return ""; - }; - if (customInspectSymbol) { - Buffer3.prototype[customInspectSymbol] = Buffer3.prototype.inspect; } - Buffer3.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { - if (isInstance(target, GlobalUint8Array)) { - target = Buffer3.from(target, target.offset, target.byteLength); - } - if (!Buffer3.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target - ); - } - if (start === void 0) { - start = 0; - } - if (end === void 0) { - end = target ? target.length : 0; - } - if (thisStart === void 0) { - thisStart = 0; - } - if (thisEnd === void 0) { - thisEnd = this.length; - } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError("out of range index"); - } - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) return 0; - let x2 = thisEnd - thisStart; - let y2 = end - start; - const len = Math.min(x2, y2); - const thisCopy = this.slice(thisStart, thisEnd); - const targetCopy = target.slice(start, end); - for (let i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x2 = thisCopy[i]; - y2 = targetCopy[i]; - break; - } - } - if (x2 < y2) return -1; - if (y2 < x2) return 1; - return 0; - }; - function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) { - if (buffer2.length === 0) return -1; - if (typeof byteOffset === "string") { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 2147483647) { - byteOffset = 2147483647; - } else if (byteOffset < -2147483648) { - byteOffset = -2147483648; - } - byteOffset = +byteOffset; - if (numberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer2.length - 1; - } - if (byteOffset < 0) byteOffset = buffer2.length + byteOffset; - if (byteOffset >= buffer2.length) { - if (dir) return -1; - else byteOffset = buffer2.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1; - } - if (typeof val === "string") { - val = Buffer3.from(val, encoding); - } - if (Buffer3.isBuffer(val)) { - if (val.length === 0) { - return -1; - } - return arrayIndexOf(buffer2, val, byteOffset, encoding, dir); - } else if (typeof val === "number") { - val = val & 255; - if (typeof GlobalUint8Array.prototype.indexOf === "function") { - if (dir) { - return GlobalUint8Array.prototype.indexOf.call(buffer2, val, byteOffset); - } else { - return GlobalUint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset); - } - } - return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir); - } - throw new TypeError("val must be string, number or Buffer"); + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); } - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - let indexSize = 1; - let arrLength = arr.length; - let valLength = val.length; - if (encoding !== void 0) { - encoding = String(encoding).toLowerCase(); - if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { - if (arr.length < 2 || val.length < 2) { - return -1; - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - function read(buf, i2) { - if (indexSize === 1) { - return buf[i2]; - } else { - return buf.readUInt16BE(i2 * indexSize); - } + writeInto(out) { + exists$1(this, false); + bytes$1(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; } - let i; - if (dir) { - let foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes2) { + number(bytes2); + return this.xofInto(new Uint8Array(bytes2)); + } + digestInto(out) { + output$1(out, this); + if (this.finished) + throw new Error("digest() was already called"); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak2(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor$1(() => new Keccak2(blockLen, suffix, outputLen)); +const keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); +let locked$3 = false; +const _keccak256 = function(data) { + return keccak_256(data); +}; +let __keccak256 = _keccak256; +function keccak256(_data6) { + const data = getBytes(_data6, "data"); + return hexlify(__keccak256(data)); +} +keccak256._ = _keccak256; +keccak256.lock = function() { + locked$3 = true; +}; +keccak256.register = function(func) { + if (locked$3) { + throw new TypeError("keccak256 is locked"); + } + __keccak256 = func; +}; +Object.freeze(keccak256); +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j2 of [idxL, idxR]) + j2.push(j2[i].map((k2) => Rho[k2])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5] +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j2) => shifts[i][j2])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j2) => shifts[i][j2])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0, + 1518500249, + 1859775393, + 2400959708, + 2840853838 +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 1352829926, + 1548603684, + 1836072691, + 2053994217, + 0 +]); +const rotl$1 = (word, shift2) => word << shift2 | word >>> 32 - shift2; +function f$1(group, x2, y2, z2) { + if (group === 0) + return x2 ^ y2 ^ z2; + else if (group === 1) + return x2 & y2 | ~x2 & z2; + else if (group === 2) + return (x2 | ~y2) ^ z2; + else if (group === 3) + return x2 & z2 | y2 & ~z2; + else + return x2 ^ (y2 | ~z2); +} +const BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 1732584193 | 0; + this.h1 = 4023233417 | 0; + this.h2 = 2562383102 | 0; + this.h3 = 271733878 | 0; + this.h4 = 3285377520 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset2) { + for (let i = 0; i < 16; i++, offset2 += 4) + BUF[i] = view.getUint32(offset2, true); + let al2 = this.h0 | 0, ar = al2, bl2 = this.h1 | 0, br = bl2, cl2 = this.h2 | 0, cr = cl2, dl2 = this.h3 | 0, dr = dl2, el2 = this.h4 | 0, er = el2; + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; + const rl2 = idxL[group], rr = idxR[group]; + const sl2 = shiftsL[group], sr = shiftsR[group]; + for (let i = 0; i < 16; i++) { + const tl2 = rotl$1(al2 + f$1(group, bl2, cl2, dl2) + BUF[rl2[i]] + hbl, sl2[i]) + el2 | 0; + al2 = el2, el2 = dl2, dl2 = rotl$1(cl2, 10) | 0, cl2 = bl2, bl2 = tl2; } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - let found = true; - for (let j2 = 0; j2 < valLength; j2++) { - if (read(arr, i + j2) !== read(val, j2)) { - found = false; - break; - } - } - if (found) return i; + for (let i = 0; i < 16; i++) { + const tr = rotl$1(ar + f$1(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er | 0; + ar = er, er = dr, dr = rotl$1(cr, 10) | 0, cr = br, br = tr; } } - return -1; + this.set(this.h1 + cl2 + dr | 0, this.h2 + dl2 + er | 0, this.h3 + el2 + ar | 0, this.h4 + al2 + br | 0, this.h0 + bl2 + cr | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +const ripemd160$1 = /* @__PURE__ */ wrapConstructor$1(() => new RIPEMD160()); +let locked$2 = false; +const _ripemd160 = function(data) { + return ripemd160$1(data); +}; +let __ripemd160 = _ripemd160; +function ripemd160(_data6) { + const data = getBytes(_data6, "data"); + return hexlify(__ripemd160(data)); +} +ripemd160._ = _ripemd160; +ripemd160.lock = function() { + locked$2 = true; +}; +ripemd160.register = function(func) { + if (locked$2) { + throw new TypeError("ripemd160 is locked"); + } + __ripemd160 = func; +}; +Object.freeze(ripemd160); +let locked$1 = false; +const _pbkdf2 = function(password, salt, iterations, keylen, algo) { + return pbkdf2Sync(password, salt, iterations, keylen, algo); +}; +let __pbkdf2 = _pbkdf2; +function pbkdf2(_password, _salt, iterations, keylen, algo) { + const password = getBytes(_password, "password"); + const salt = getBytes(_salt, "salt"); + return hexlify(__pbkdf2(password, salt, iterations, keylen, algo)); +} +pbkdf2._ = _pbkdf2; +pbkdf2.lock = function() { + locked$1 = true; +}; +pbkdf2.register = function(func) { + if (locked$1) { + throw new Error("pbkdf2 is locked"); + } + __pbkdf2 = func; +}; +Object.freeze(pbkdf2); +let locked = false; +const _randomBytes = function(length) { + return new Uint8Array(randomBytes$1(length)); +}; +let __randomBytes = _randomBytes; +function randomBytes(length) { + return __randomBytes(length); +} +randomBytes._ = _randomBytes; +randomBytes.lock = function() { + locked = true; +}; +randomBytes.register = function(func) { + if (locked) { + throw new Error("randomBytes is locked"); } - Buffer3.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - Buffer3.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - function hexWrite(buf, string, offset2, length) { - offset2 = Number(offset2) || 0; - const remaining = buf.length - offset2; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - const strLen = string.length; - if (length > strLen / 2) { - length = strLen / 2; - } - let i; - for (i = 0; i < length; ++i) { - const parsed = parseInt(string.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) return i; - buf[offset2 + i] = parsed; - } - return i; + __randomBytes = func; +}; +Object.freeze(randomBytes); +const rotl = (a2, b2) => a2 << b2 | a2 >>> 32 - b2; +function XorAndSalsa(prev, pi2, input2, ii2, out, oi2) { + let y00 = prev[pi2++] ^ input2[ii2++], y01 = prev[pi2++] ^ input2[ii2++]; + let y02 = prev[pi2++] ^ input2[ii2++], y03 = prev[pi2++] ^ input2[ii2++]; + let y04 = prev[pi2++] ^ input2[ii2++], y05 = prev[pi2++] ^ input2[ii2++]; + let y06 = prev[pi2++] ^ input2[ii2++], y07 = prev[pi2++] ^ input2[ii2++]; + let y08 = prev[pi2++] ^ input2[ii2++], y09 = prev[pi2++] ^ input2[ii2++]; + let y10 = prev[pi2++] ^ input2[ii2++], y11 = prev[pi2++] ^ input2[ii2++]; + let y12 = prev[pi2++] ^ input2[ii2++], y13 = prev[pi2++] ^ input2[ii2++]; + let y14 = prev[pi2++] ^ input2[ii2++], y15 = prev[pi2++] ^ input2[ii2++]; + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); } - function utf8Write(buf, string, offset2, length) { - return blitBuffer(utf8ToBytes2(string, buf.length - offset2), buf, offset2, length); + out[oi2++] = y00 + x00 | 0; + out[oi2++] = y01 + x01 | 0; + out[oi2++] = y02 + x02 | 0; + out[oi2++] = y03 + x03 | 0; + out[oi2++] = y04 + x04 | 0; + out[oi2++] = y05 + x05 | 0; + out[oi2++] = y06 + x06 | 0; + out[oi2++] = y07 + x07 | 0; + out[oi2++] = y08 + x08 | 0; + out[oi2++] = y09 + x09 | 0; + out[oi2++] = y10 + x10 | 0; + out[oi2++] = y11 + x11 | 0; + out[oi2++] = y12 + x12 | 0; + out[oi2++] = y13 + x13 | 0; + out[oi2++] = y14 + x14 | 0; + out[oi2++] = y15 + x15 | 0; +} +function BlockMix(input2, ii2, out, oi2, r2) { + let head = oi2 + 0; + let tail = oi2 + 16 * r2; + for (let i = 0; i < 16; i++) + out[tail + i] = input2[ii2 + (2 * r2 - 1) * 16 + i]; + for (let i = 0; i < r2; i++, head += 16, ii2 += 16) { + XorAndSalsa(out, tail, input2, ii2, out, head); + if (i > 0) + tail += 16; + XorAndSalsa(out, head, input2, ii2 += 16, out, tail); } - function asciiWrite(buf, string, offset2, length) { - return blitBuffer(asciiToBytes(string), buf, offset2, length); +} +function scryptInit(password, salt, _opts) { + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024 + }, _opts); + const { N: N2, r: r2, p: p2, dkLen, asyncTick, maxmem, onProgress } = opts; + number(N2); + number(r2); + number(p2); + number(dkLen); + number(asyncTick); + number(maxmem); + if (onProgress !== void 0 && typeof onProgress !== "function") + throw new Error("progressCb should be function"); + const blockSize = 128 * r2; + const blockSize32 = blockSize / 4; + if (N2 <= 1 || (N2 & N2 - 1) !== 0 || N2 >= 2 ** (blockSize / 8) || N2 > 2 ** 32) { + throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32"); } - function base64Write(buf, string, offset2, length) { - return blitBuffer(base64ToBytes(string), buf, offset2, length); + if (p2 < 0 || p2 > (2 ** 32 - 1) * 32 / blockSize) { + throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)"); } - function ucs2Write(buf, string, offset2, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset2), buf, offset2, length); + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32"); } - Buffer3.prototype.write = function write(string, offset2, length, encoding) { - if (offset2 === void 0) { - encoding = "utf8"; - length = this.length; - offset2 = 0; - } else if (length === void 0 && typeof offset2 === "string") { - encoding = offset2; - length = this.length; - offset2 = 0; - } else if (isFinite(offset2)) { - offset2 = offset2 >>> 0; - if (isFinite(length)) { - length = length >>> 0; - if (encoding === void 0) encoding = "utf8"; - } else { - encoding = length; - length = void 0; - } - } else { - throw new Error( - "Buffer.write(string, encoding, offset[, length]) is no longer supported" - ); - } - const remaining = this.length - offset2; - if (length === void 0 || length > remaining) length = remaining; - if (string.length > 0 && (length < 0 || offset2 < 0) || offset2 > this.length) { - throw new RangeError("Attempt to write outside buffer bounds"); - } - if (!encoding) encoding = "utf8"; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "hex": - return hexWrite(this, string, offset2, length); - case "utf8": - case "utf-8": - return utf8Write(this, string, offset2, length); - case "ascii": - case "latin1": - case "binary": - return asciiWrite(this, string, offset2, length); - case "base64": - return base64Write(this, string, offset2, length); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string, offset2, length); - default: - if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } + const memUsed = blockSize * (N2 + p2); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + const B2 = pbkdf2$1(sha256$2, password, salt, { c: 1, dkLen: blockSize * p2 }); + const B32 = u32(B2); + const V2 = u32(new Uint8Array(blockSize * N2)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => { }; - Buffer3.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0) + if (onProgress) { + const totalBlockMix = 2 * N2 * p2; + const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); }; - }; - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf); - } else { - return base64.fromByteArray(buf.slice(start, end)); - } - } - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - const res = []; - let i = start; - while (i < end) { - const firstByte = buf[i]; - let codePoint = null; - let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (i + bytesPerSequence <= end) { - let secondByte, thirdByte, fourthByte, tempCodePoint; - switch (bytesPerSequence) { - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; - if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { - codePoint = tempCodePoint; - } - } - break; - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; - if (tempCodePoint > 65535 && tempCodePoint < 1114112) { - codePoint = tempCodePoint; - } - } - } - } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - res.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - res.push(codePoint); - i += bytesPerSequence; - } - return decodeCodePointsArray(res); } - const MAX_ARGUMENTS_LENGTH = 4096; - function decodeCodePointsArray(codePoints) { - const len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); + return { N: N2, r: r2, p: p2, dkLen, blockSize32, V: V2, B32, B: B2, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B2, V2, tmp) { + const res = pbkdf2$1(sha256$2, password, B2, { c: 1, dkLen }); + B2.fill(0); + V2.fill(0); + tmp.fill(0); + return res; +} +function scrypt$1(password, salt, opts) { + const { N: N2, r: r2, p: p2, dkLen, blockSize32, V: V2, B32, B: B2, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi2 = 0; pi2 < p2; pi2++) { + const Pi2 = blockSize32 * pi2; + for (let i = 0; i < blockSize32; i++) + V2[i] = B32[Pi2 + i]; + for (let i = 0, pos = 0; i < N2 - 1; i++) { + BlockMix(V2, pos, V2, pos += blockSize32, r2); + blockMixCb(); } - let res = ""; - let i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); + BlockMix(V2, (N2 - 1) * blockSize32, B32, Pi2, r2); + blockMixCb(); + for (let i = 0; i < N2; i++) { + const j2 = B32[Pi2 + blockSize32 - 16] % N2; + for (let k2 = 0; k2 < blockSize32; k2++) + tmp[k2] = B32[Pi2 + k2] ^ V2[j2 * blockSize32 + k2]; + BlockMix(tmp, 0, B32, Pi2, r2); + blockMixCb(); } - return res; } - function asciiSlice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 127); - } - return ret; + return scryptOutput(password, dkLen, B2, V2, tmp); +} +async function scryptAsync(password, salt, opts) { + const { N: N2, r: r2, p: p2, dkLen, blockSize32, V: V2, B32, B: B2, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi2 = 0; pi2 < p2; pi2++) { + const Pi2 = blockSize32 * pi2; + for (let i = 0; i < blockSize32; i++) + V2[i] = B32[Pi2 + i]; + let pos = 0; + await asyncLoop(N2 - 1, asyncTick, () => { + BlockMix(V2, pos, V2, pos += blockSize32, r2); + blockMixCb(); + }); + BlockMix(V2, (N2 - 1) * blockSize32, B32, Pi2, r2); + blockMixCb(); + await asyncLoop(N2, asyncTick, () => { + const j2 = B32[Pi2 + blockSize32 - 16] % N2; + for (let k2 = 0; k2 < blockSize32; k2++) + tmp[k2] = B32[Pi2 + k2] ^ V2[j2 * blockSize32 + k2]; + BlockMix(tmp, 0, B32, Pi2, r2); + blockMixCb(); + }); } - function latin1Slice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret; + return scryptOutput(password, dkLen, B2, V2, tmp); +} +let lockedSync = false, lockedAsync = false; +const _scryptAsync = async function(passwd, salt, N2, r2, p2, dkLen, onProgress) { + return await scryptAsync(passwd, salt, { N: N2, r: r2, p: p2, dkLen, onProgress }); +}; +const _scryptSync = function(passwd, salt, N2, r2, p2, dkLen) { + return scrypt$1(passwd, salt, { N: N2, r: r2, p: p2, dkLen }); +}; +let __scryptAsync = _scryptAsync; +let __scryptSync = _scryptSync; +async function scrypt(_passwd, _salt, N2, r2, p2, dkLen, progress2) { + const passwd = getBytes(_passwd, "passwd"); + const salt = getBytes(_salt, "salt"); + return hexlify(await __scryptAsync(passwd, salt, N2, r2, p2, dkLen, progress2)); +} +scrypt._ = _scryptAsync; +scrypt.lock = function() { + lockedAsync = true; +}; +scrypt.register = function(func) { + if (lockedAsync) { + throw new Error("scrypt is locked"); } - function hexSlice(buf, start, end) { - const len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - let out = ""; - for (let i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]]; - } - return out; + __scryptAsync = func; +}; +Object.freeze(scrypt); +function scryptSync(_passwd, _salt, N2, r2, p2, dkLen) { + const passwd = getBytes(_passwd, "passwd"); + const salt = getBytes(_salt, "salt"); + return hexlify(__scryptSync(passwd, salt, N2, r2, p2, dkLen)); +} +scryptSync._ = _scryptSync; +scryptSync.lock = function() { + lockedSync = true; +}; +scryptSync.register = function(func) { + if (lockedSync) { + throw new Error("scryptSync is locked"); } - function utf16leSlice(buf, start, end) { - const bytes2 = buf.slice(start, end); - let res = ""; - for (let i = 0; i < bytes2.length - 1; i += 2) { - res += String.fromCharCode(bytes2[i] + bytes2[i + 1] * 256); - } - return res; + __scryptSync = func; +}; +Object.freeze(scryptSync); +const _sha256 = function(data) { + return createHash("sha256").update(data).digest(); +}; +const _sha512 = function(data) { + return createHash("sha512").update(data).digest(); +}; +let __sha256 = _sha256; +let __sha512 = _sha512; +let locked256 = false, locked512 = false; +function sha256$1(_data6) { + const data = getBytes(_data6, "data"); + return hexlify(__sha256(data)); +} +sha256$1._ = _sha256; +sha256$1.lock = function() { + locked256 = true; +}; +sha256$1.register = function(func) { + if (locked256) { + throw new Error("sha256 is locked"); } - Buffer3.prototype.slice = function slice2(start, end) { - const len = this.length; - start = ~~start; - end = end === void 0 ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; + __sha256 = func; +}; +Object.freeze(sha256$1); +function sha512(_data6) { + const data = getBytes(_data6, "data"); + return hexlify(__sha512(data)); +} +sha512._ = _sha512; +sha512.lock = function() { + locked512 = true; +}; +sha512.register = function(func) { + if (locked512) { + throw new Error("sha512 is locked"); + } + __sha512 = func; +}; +Object.freeze(sha256$1); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n$3 = BigInt(0); +const _1n$4 = BigInt(1); +const _2n$2 = BigInt(2); +const u8a = (a2) => a2 instanceof Uint8Array; +const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +function bytesToHex$1(bytes2) { + if (!u8a(bytes2)) + throw new Error("Uint8Array expected"); + let hex2 = ""; + for (let i = 0; i < bytes2.length; i++) { + hex2 += hexes$1[bytes2[i]]; + } + return hex2; +} +function numberToHexUnpadded(num) { + const hex2 = num.toString(16); + return hex2.length & 1 ? `0${hex2}` : hex2; +} +function hexToNumber(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + return BigInt(hex2 === "" ? "0" : `0x${hex2}`); +} +function hexToBytes(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + const len = hex2.length; + if (len % 2) + throw new Error("padded hex string expected, got unpadded hex of length " + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j2 = i * 2; + const hexByte = hex2.slice(j2, j2 + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error("Invalid byte sequence"); + array[i] = byte; + } + return array; +} +function bytesToNumberBE(bytes2) { + return hexToNumber(bytesToHex$1(bytes2)); +} +function bytesToNumberLE(bytes2) { + if (!u8a(bytes2)) + throw new Error("Uint8Array expected"); + return hexToNumber(bytesToHex$1(Uint8Array.from(bytes2).reverse())); +} +function numberToBytesBE(n2, len) { + return hexToBytes(n2.toString(16).padStart(len * 2, "0")); +} +function numberToBytesLE(n2, len) { + return numberToBytesBE(n2, len).reverse(); +} +function numberToVarBytesBE(n2) { + return hexToBytes(numberToHexUnpadded(n2)); +} +function ensureBytes(title, hex2, expectedLength) { + let res; + if (typeof hex2 === "string") { + try { + res = hexToBytes(hex2); + } catch (e2) { + throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e2}`); } - if (end < start) end = start; - const newBuf = this.subarray(start, end); - Object.setPrototypeOf(newBuf, Buffer3.prototype); - return newBuf; - }; - function checkOffset(offset2, ext, length) { - if (offset2 % 1 !== 0 || offset2 < 0) throw new RangeError("offset is not uint"); - if (offset2 + ext > length) throw new RangeError("Trying to access beyond buffer length"); + } else if (u8a(hex2)) { + res = Uint8Array.from(hex2); + } else { + throw new Error(`${title} must be hex string or Uint8Array`); } - Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset2, byteLength3, noAssert) { - offset2 = offset2 >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) checkOffset(offset2, byteLength3, this.length); - let val = this[offset2]; - let mul = 1; - let i = 0; - while (++i < byteLength3 && (mul *= 256)) { - val += this[offset2 + i] * mul; - } - return val; - }; - Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset2, byteLength3, noAssert) { - offset2 = offset2 >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) { - checkOffset(offset2, byteLength3, this.length); - } - let val = this[offset2 + --byteLength3]; - let mul = 1; - while (byteLength3 > 0 && (mul *= 256)) { - val += this[offset2 + --byteLength3] * mul; - } - return val; - }; - Buffer3.prototype.readUint8 = Buffer3.prototype.readUInt8 = function readUInt8(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 1, this.length); - return this[offset2]; - }; - Buffer3.prototype.readUint16LE = Buffer3.prototype.readUInt16LE = function readUInt16LE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 2, this.length); - return this[offset2] | this[offset2 + 1] << 8; - }; - Buffer3.prototype.readUint16BE = Buffer3.prototype.readUInt16BE = function readUInt16BE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 2, this.length); - return this[offset2] << 8 | this[offset2 + 1]; - }; - Buffer3.prototype.readUint32LE = Buffer3.prototype.readUInt32LE = function readUInt32LE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 4, this.length); - return (this[offset2] | this[offset2 + 1] << 8 | this[offset2 + 2] << 16) + this[offset2 + 3] * 16777216; - }; - Buffer3.prototype.readUint32BE = Buffer3.prototype.readUInt32BE = function readUInt32BE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 4, this.length); - return this[offset2] * 16777216 + (this[offset2 + 1] << 16 | this[offset2 + 2] << 8 | this[offset2 + 3]); - }; - Buffer3.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset2) { - offset2 = offset2 >>> 0; - validateNumber(offset2, "offset"); - const first = this[offset2]; - const last = this[offset2 + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset2, this.length - 8); - } - const lo = first + this[++offset2] * 2 ** 8 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 24; - const hi2 = this[++offset2] + this[++offset2] * 2 ** 8 + this[++offset2] * 2 ** 16 + last * 2 ** 24; - return BigInt(lo) + (BigInt(hi2) << BigInt(32)); - }); - Buffer3.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset2) { - offset2 = offset2 >>> 0; - validateNumber(offset2, "offset"); - const first = this[offset2]; - const last = this[offset2 + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset2, this.length - 8); - } - const hi2 = first * 2 ** 24 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + this[++offset2]; - const lo = this[++offset2] * 2 ** 24 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + last; - return (BigInt(hi2) << BigInt(32)) + BigInt(lo); + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +function concatBytes(...arrays) { + const r2 = new Uint8Array(arrays.reduce((sum, a2) => sum + a2.length, 0)); + let pad2 = 0; + arrays.forEach((a2) => { + if (!u8a(a2)) + throw new Error("Uint8Array expected"); + r2.set(a2, pad2); + pad2 += a2.length; }); - Buffer3.prototype.readIntLE = function readIntLE(offset2, byteLength3, noAssert) { - offset2 = offset2 >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) checkOffset(offset2, byteLength3, this.length); - let val = this[offset2]; - let mul = 1; - let i = 0; - while (++i < byteLength3 && (mul *= 256)) { - val += this[offset2 + i] * mul; - } - mul *= 128; - if (val >= mul) val -= Math.pow(2, 8 * byteLength3); - return val; - }; - Buffer3.prototype.readIntBE = function readIntBE(offset2, byteLength3, noAssert) { - offset2 = offset2 >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) checkOffset(offset2, byteLength3, this.length); - let i = byteLength3; - let mul = 1; - let val = this[offset2 + --i]; - while (i > 0 && (mul *= 256)) { - val += this[offset2 + --i] * mul; - } - mul *= 128; - if (val >= mul) val -= Math.pow(2, 8 * byteLength3); - return val; - }; - Buffer3.prototype.readInt8 = function readInt8(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 1, this.length); - if (!(this[offset2] & 128)) return this[offset2]; - return (255 - this[offset2] + 1) * -1; - }; - Buffer3.prototype.readInt16LE = function readInt16LE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 2, this.length); - const val = this[offset2] | this[offset2 + 1] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer3.prototype.readInt16BE = function readInt16BE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 2, this.length); - const val = this[offset2 + 1] | this[offset2] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer3.prototype.readInt32LE = function readInt32LE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 4, this.length); - return this[offset2] | this[offset2 + 1] << 8 | this[offset2 + 2] << 16 | this[offset2 + 3] << 24; + return r2; +} +function equalBytes(b1, b2) { + if (b1.length !== b2.length) + return false; + for (let i = 0; i < b1.length; i++) + if (b1[i] !== b2[i]) + return false; + return true; +} +function utf8ToBytes$1(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); +} +function bitLen(n2) { + let len; + for (len = 0; n2 > _0n$3; n2 >>= _1n$4, len += 1) + ; + return len; +} +function bitGet(n2, pos) { + return n2 >> BigInt(pos) & _1n$4; +} +const bitSet = (n2, pos, value) => { + return n2 | (value ? _1n$4 : _0n$3) << BigInt(pos); +}; +const bitMask = (n2) => (_2n$2 << BigInt(n2 - 1)) - _1n$4; +const u8n = (data) => new Uint8Array(data); +const u8fr = (arr) => Uint8Array.from(arr); +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + let v3 = u8n(hashLen); + let k2 = u8n(hashLen); + let i = 0; + const reset = () => { + v3.fill(1); + k2.fill(0); + i = 0; }; - Buffer3.prototype.readInt32BE = function readInt32BE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 4, this.length); - return this[offset2] << 24 | this[offset2 + 1] << 16 | this[offset2 + 2] << 8 | this[offset2 + 3]; + const h2 = (...b2) => hmacFn(k2, v3, ...b2); + const reseed = (seed = u8n()) => { + k2 = h2(u8fr([0]), seed); + v3 = h2(); + if (seed.length === 0) + return; + k2 = h2(u8fr([1]), seed); + v3 = h2(); }; - Buffer3.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset2) { - offset2 = offset2 >>> 0; - validateNumber(offset2, "offset"); - const first = this[offset2]; - const last = this[offset2 + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset2, this.length - 8); - } - const val = this[offset2 + 4] + this[offset2 + 5] * 2 ** 8 + this[offset2 + 6] * 2 ** 16 + (last << 24); - return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset2] * 2 ** 8 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 24); - }); - Buffer3.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset2) { - offset2 = offset2 >>> 0; - validateNumber(offset2, "offset"); - const first = this[offset2]; - const last = this[offset2 + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset2, this.length - 8); + const gen2 = () => { + if (i++ >= 1e3) + throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v3 = h2(); + const sl2 = v3.slice(); + out.push(sl2); + len += v3.length; } - const val = (first << 24) + // Overflow - this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + this[++offset2]; - return (BigInt(val) << BigInt(32)) + BigInt(this[++offset2] * 2 ** 24 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + last); - }); - Buffer3.prototype.readFloatLE = function readFloatLE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 4, this.length); - return ieee754$1.read(this, offset2, true, 23, 4); - }; - Buffer3.prototype.readFloatBE = function readFloatBE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 4, this.length); - return ieee754$1.read(this, offset2, false, 23, 4); - }; - Buffer3.prototype.readDoubleLE = function readDoubleLE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 8, this.length); - return ieee754$1.read(this, offset2, true, 52, 8); - }; - Buffer3.prototype.readDoubleBE = function readDoubleBE(offset2, noAssert) { - offset2 = offset2 >>> 0; - if (!noAssert) checkOffset(offset2, 8, this.length); - return ieee754$1.read(this, offset2, false, 52, 8); + return concatBytes(...out); }; - function checkInt(buf, value, offset2, ext, max2, min2) { - if (!Buffer3.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value > max2 || value < min2) throw new RangeError('"value" argument is out of bounds'); - if (offset2 + ext > buf.length) throw new RangeError("Index out of range"); - } - Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value, offset2, byteLength3, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength3) - 1; - checkInt(this, value, offset2, byteLength3, maxBytes, 0); - } - let mul = 1; - let i = 0; - this[offset2] = value & 255; - while (++i < byteLength3 && (mul *= 256)) { - this[offset2 + i] = value / mul & 255; - } - return offset2 + byteLength3; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while (!(res = pred(gen2()))) + reseed(); + reset(); + return res; }; - Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value, offset2, byteLength3, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength3) - 1; - checkInt(this, value, offset2, byteLength3, maxBytes, 0); - } - let i = byteLength3 - 1; - let mul = 1; - this[offset2 + i] = value & 255; - while (--i >= 0 && (mul *= 256)) { - this[offset2 + i] = value / mul & 255; + return genUntil; +} +const validatorFns = { + bigint: (val) => typeof val === "bigint", + function: (val) => typeof val === "function", + boolean: (val) => typeof val === "boolean", + string: (val) => typeof val === "string", + stringOrUint8Array: (val) => typeof val === "string" || val instanceof Uint8Array, + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object2) => object2.Fp.isValid(val), + hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) +}; +function validateObject(object2, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== "function") + throw new Error(`Invalid validator "${type}", expected function`); + const val = object2[fieldName]; + if (isOptional && val === void 0) + return; + if (!checkVal(val, object2)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); } - return offset2 + byteLength3; }; - Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = function writeUInt8(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 1, 255, 0); - this[offset2] = value & 255; - return offset2 + 1; - }; - Buffer3.prototype.writeUint16LE = Buffer3.prototype.writeUInt16LE = function writeUInt16LE(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 2, 65535, 0); - this[offset2] = value & 255; - this[offset2 + 1] = value >>> 8; - return offset2 + 2; - }; - Buffer3.prototype.writeUint16BE = Buffer3.prototype.writeUInt16BE = function writeUInt16BE(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 2, 65535, 0); - this[offset2] = value >>> 8; - this[offset2 + 1] = value & 255; - return offset2 + 2; - }; - Buffer3.prototype.writeUint32LE = Buffer3.prototype.writeUInt32LE = function writeUInt32LE(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 4, 4294967295, 0); - this[offset2 + 3] = value >>> 24; - this[offset2 + 2] = value >>> 16; - this[offset2 + 1] = value >>> 8; - this[offset2] = value & 255; - return offset2 + 4; - }; - Buffer3.prototype.writeUint32BE = Buffer3.prototype.writeUInt32BE = function writeUInt32BE(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 4, 4294967295, 0); - this[offset2] = value >>> 24; - this[offset2 + 1] = value >>> 16; - this[offset2 + 2] = value >>> 8; - this[offset2 + 3] = value & 255; - return offset2 + 4; - }; - function wrtBigUInt64LE(buf, value, offset2, min2, max2) { - checkIntBI(value, min2, max2, buf, offset2, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset2++] = lo; - lo = lo >> 8; - buf[offset2++] = lo; - lo = lo >> 8; - buf[offset2++] = lo; - lo = lo >> 8; - buf[offset2++] = lo; - let hi2 = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset2++] = hi2; - hi2 = hi2 >> 8; - buf[offset2++] = hi2; - hi2 = hi2 >> 8; - buf[offset2++] = hi2; - hi2 = hi2 >> 8; - buf[offset2++] = hi2; - return offset2; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object2; +} +const ut = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + bitGet, + bitLen, + bitMask, + bitSet, + bytesToHex: bytesToHex$1, + bytesToNumberBE, + bytesToNumberLE, + concatBytes, + createHmacDrbg, + ensureBytes, + equalBytes, + hexToBytes, + hexToNumber, + numberToBytesBE, + numberToBytesLE, + numberToHexUnpadded, + numberToVarBytesBE, + utf8ToBytes: utf8ToBytes$1, + validateObject +}, Symbol.toStringTag, { value: "Module" })); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n$2 = BigInt(0), _1n$3 = BigInt(1), _2n$1 = BigInt(2), _3n$1 = BigInt(3); +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +BigInt(9); +BigInt(16); +function mod(a2, b2) { + const result = a2 % b2; + return result >= _0n$2 ? result : b2 + result; +} +function pow(num, power, modulo) { + if (modulo <= _0n$2 || power < _0n$2) + throw new Error("Expected power/modulo > 0"); + if (modulo === _1n$3) + return _0n$2; + let res = _1n$3; + while (power > _0n$2) { + if (power & _1n$3) + res = res * num % modulo; + num = num * num % modulo; + power >>= _1n$3; } - function wrtBigUInt64BE(buf, value, offset2, min2, max2) { - checkIntBI(value, min2, max2, buf, offset2, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset2 + 7] = lo; - lo = lo >> 8; - buf[offset2 + 6] = lo; - lo = lo >> 8; - buf[offset2 + 5] = lo; - lo = lo >> 8; - buf[offset2 + 4] = lo; - let hi2 = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset2 + 3] = hi2; - hi2 = hi2 >> 8; - buf[offset2 + 2] = hi2; - hi2 = hi2 >> 8; - buf[offset2 + 1] = hi2; - hi2 = hi2 >> 8; - buf[offset2] = hi2; - return offset2 + 8; + return res; +} +function pow2(x2, power, modulo) { + let res = x2; + while (power-- > _0n$2) { + res *= res; + res %= modulo; } - Buffer3.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset2 = 0) { - return wrtBigUInt64LE(this, value, offset2, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer3.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset2 = 0) { - return wrtBigUInt64BE(this, value, offset2, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer3.prototype.writeIntLE = function writeIntLE(value, offset2, byteLength3, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength3 - 1); - checkInt(this, value, offset2, byteLength3, limit - 1, -limit); - } - let i = 0; - let mul = 1; - let sub = 0; - this[offset2] = value & 255; - while (++i < byteLength3 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset2 + i - 1] !== 0) { - sub = 1; - } - this[offset2 + i] = (value / mul >> 0) - sub & 255; - } - return offset2 + byteLength3; - }; - Buffer3.prototype.writeIntBE = function writeIntBE(value, offset2, byteLength3, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength3 - 1); - checkInt(this, value, offset2, byteLength3, limit - 1, -limit); - } - let i = byteLength3 - 1; - let mul = 1; - let sub = 0; - this[offset2 + i] = value & 255; - while (--i >= 0 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset2 + i + 1] !== 0) { - sub = 1; + return res; +} +function invert(number2, modulo) { + if (number2 === _0n$2 || modulo <= _0n$2) { + throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`); + } + let a2 = mod(number2, modulo); + let b2 = modulo; + let x2 = _0n$2, u2 = _1n$3; + while (a2 !== _0n$2) { + const q2 = b2 / a2; + const r2 = b2 % a2; + const m2 = x2 - u2 * q2; + b2 = a2, a2 = r2, x2 = u2, u2 = m2; + } + const gcd = b2; + if (gcd !== _1n$3) + throw new Error("invert: does not exist"); + return mod(x2, modulo); +} +function tonelliShanks(P2) { + const legendreC = (P2 - _1n$3) / _2n$1; + let Q2, S2, Z2; + for (Q2 = P2 - _1n$3, S2 = 0; Q2 % _2n$1 === _0n$2; Q2 /= _2n$1, S2++) + ; + for (Z2 = _2n$1; Z2 < P2 && pow(Z2, legendreC, P2) !== P2 - _1n$3; Z2++) + ; + if (S2 === 1) { + const p1div4 = (P2 + _1n$3) / _4n; + return function tonelliFast(Fp2, n2) { + const root2 = Fp2.pow(n2, p1div4); + if (!Fp2.eql(Fp2.sqr(root2), n2)) + throw new Error("Cannot find square root"); + return root2; + }; + } + const Q1div2 = (Q2 + _1n$3) / _2n$1; + return function tonelliSlow(Fp2, n2) { + if (Fp2.pow(n2, legendreC) === Fp2.neg(Fp2.ONE)) + throw new Error("Cannot find square root"); + let r2 = S2; + let g2 = Fp2.pow(Fp2.mul(Fp2.ONE, Z2), Q2); + let x2 = Fp2.pow(n2, Q1div2); + let b2 = Fp2.pow(n2, Q2); + while (!Fp2.eql(b2, Fp2.ONE)) { + if (Fp2.eql(b2, Fp2.ZERO)) + return Fp2.ZERO; + let m2 = 1; + for (let t2 = Fp2.sqr(b2); m2 < r2; m2++) { + if (Fp2.eql(t2, Fp2.ONE)) + break; + t2 = Fp2.sqr(t2); } - this[offset2 + i] = (value / mul >> 0) - sub & 255; + const ge2 = Fp2.pow(g2, _1n$3 << BigInt(r2 - m2 - 1)); + g2 = Fp2.sqr(ge2); + x2 = Fp2.mul(x2, ge2); + b2 = Fp2.mul(b2, g2); + r2 = m2; } - return offset2 + byteLength3; - }; - Buffer3.prototype.writeInt8 = function writeInt8(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 1, 127, -128); - if (value < 0) value = 255 + value + 1; - this[offset2] = value & 255; - return offset2 + 1; - }; - Buffer3.prototype.writeInt16LE = function writeInt16LE(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 2, 32767, -32768); - this[offset2] = value & 255; - this[offset2 + 1] = value >>> 8; - return offset2 + 2; - }; - Buffer3.prototype.writeInt16BE = function writeInt16BE(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 2, 32767, -32768); - this[offset2] = value >>> 8; - this[offset2 + 1] = value & 255; - return offset2 + 2; - }; - Buffer3.prototype.writeInt32LE = function writeInt32LE(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 4, 2147483647, -2147483648); - this[offset2] = value & 255; - this[offset2 + 1] = value >>> 8; - this[offset2 + 2] = value >>> 16; - this[offset2 + 3] = value >>> 24; - return offset2 + 4; - }; - Buffer3.prototype.writeInt32BE = function writeInt32BE(value, offset2, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) checkInt(this, value, offset2, 4, 2147483647, -2147483648); - if (value < 0) value = 4294967295 + value + 1; - this[offset2] = value >>> 24; - this[offset2 + 1] = value >>> 16; - this[offset2 + 2] = value >>> 8; - this[offset2 + 3] = value & 255; - return offset2 + 4; + return x2; }; - Buffer3.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset2 = 0) { - return wrtBigUInt64LE(this, value, offset2, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - Buffer3.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset2 = 0) { - return wrtBigUInt64BE(this, value, offset2, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - function checkIEEE754(buf, value, offset2, ext, max2, min2) { - if (offset2 + ext > buf.length) throw new RangeError("Index out of range"); - if (offset2 < 0) throw new RangeError("Index out of range"); +} +function FpSqrt(P2) { + if (P2 % _4n === _3n$1) { + const p1div4 = (P2 + _1n$3) / _4n; + return function sqrt3mod4(Fp2, n2) { + const root2 = Fp2.pow(n2, p1div4); + if (!Fp2.eql(Fp2.sqr(root2), n2)) + throw new Error("Cannot find square root"); + return root2; + }; } - function writeFloat(buf, value, offset2, littleEndian, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset2, 4); - } - ieee754$1.write(buf, value, offset2, littleEndian, 23, 4); - return offset2 + 4; + if (P2 % _8n === _5n) { + const c1 = (P2 - _5n) / _8n; + return function sqrt5mod8(Fp2, n2) { + const n22 = Fp2.mul(n2, _2n$1); + const v3 = Fp2.pow(n22, c1); + const nv = Fp2.mul(n2, v3); + const i = Fp2.mul(Fp2.mul(nv, _2n$1), v3); + const root2 = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); + if (!Fp2.eql(Fp2.sqr(root2), n2)) + throw new Error("Cannot find square root"); + return root2; + }; } - Buffer3.prototype.writeFloatLE = function writeFloatLE(value, offset2, noAssert) { - return writeFloat(this, value, offset2, true, noAssert); - }; - Buffer3.prototype.writeFloatBE = function writeFloatBE(value, offset2, noAssert) { - return writeFloat(this, value, offset2, false, noAssert); + return tonelliShanks(P2); +} +const FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" +]; +function validateField(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger" }; - function writeDouble(buf, value, offset2, littleEndian, noAssert) { - value = +value; - offset2 = offset2 >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset2, 8); - } - ieee754$1.write(buf, value, offset2, littleEndian, 52, 8); - return offset2 + 8; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + return validateObject(field, opts); +} +function FpPow(f2, num, power) { + if (power < _0n$2) + throw new Error("Expected power > 0"); + if (power === _0n$2) + return f2.ONE; + if (power === _1n$3) + return num; + let p2 = f2.ONE; + let d2 = num; + while (power > _0n$2) { + if (power & _1n$3) + p2 = f2.mul(p2, d2); + d2 = f2.sqr(d2); + power >>= _1n$3; } - Buffer3.prototype.writeDoubleLE = function writeDoubleLE(value, offset2, noAssert) { - return writeDouble(this, value, offset2, true, noAssert); - }; - Buffer3.prototype.writeDoubleBE = function writeDoubleBE(value, offset2, noAssert) { - return writeDouble(this, value, offset2, false, noAssert); - }; - Buffer3.prototype.copy = function copy2(target, targetStart, start, end) { - if (!Buffer3.isBuffer(target)) throw new TypeError("argument should be a Buffer"); - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); - } - if (start < 0 || start >= this.length) throw new RangeError("Index out of range"); - if (end < 0) throw new RangeError("sourceEnd out of bounds"); - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - const len = end - start; - if (this === target && typeof GlobalUint8Array.prototype.copyWithin === "function") { - this.copyWithin(targetStart, start, end); - } else { - GlobalUint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ); + return p2; +} +function FpInvertBatch(f2, nums) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f2.is0(num)) + return acc; + tmp[i] = acc; + return f2.mul(acc, num); + }, f2.ONE); + const inverted = f2.inv(lastMultiplied); + nums.reduceRight((acc, num, i) => { + if (f2.is0(num)) + return acc; + tmp[i] = f2.mul(acc, tmp[i]); + return f2.mul(acc, num); + }, inverted); + return tmp; +} +function nLength(n2, nBitLength) { + const _nBitLength = nBitLength !== void 0 ? nBitLength : n2.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +function Field(ORDER, bitLen2, isLE2 = false, redef = {}) { + if (ORDER <= _0n$2) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); + if (BYTES > 2048) + throw new Error("Field lengths over 2048 bytes are not supported"); + const sqrtP = FpSqrt(ORDER); + const f2 = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n$2, + ONE: _1n$3, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== "bigint") + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n$2 <= num && num < ORDER; + }, + is0: (num) => num === _0n$2, + isOdd: (num) => (num & _1n$3) === _1n$3, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f2, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n2) => sqrtP(f2, n2)), + invertBatch: (lst) => FpInvertBatch(f2, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a2, b2, c2) => c2 ? b2 : a2, + toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), + fromBytes: (bytes2) => { + if (bytes2.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`); + return isLE2 ? bytesToNumberLE(bytes2) : bytesToNumberBE(bytes2); } - return len; + }); + return Object.freeze(f2); +} +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== "bigint") + throw new Error("field order must be bigint"); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +function mapHashToField(key, fieldOrder, isLE2 = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE2 ? bytesToNumberBE(key) : bytesToNumberLE(key); + const reduced = mod(num, fieldOrder - _1n$3) + _1n$3; + return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n$1 = BigInt(0); +const _1n$2 = BigInt(1); +function wNAF(c2, bits) { + const constTimeNegate = (condition, item2) => { + const neg = item2.negate(); + return condition ? neg : item2; }; - Buffer3.prototype.fill = function fill(val, start, end, encoding) { - if (typeof val === "string") { - if (typeof start === "string") { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === "string") { - encoding = end; - end = this.length; - } - if (encoding !== void 0 && typeof encoding !== "string") { - throw new TypeError("encoding must be a string"); - } - if (typeof encoding === "string" && !Buffer3.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - if (val.length === 1) { - const code2 = val.charCodeAt(0); - if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { - val = code2; - } - } - } else if (typeof val === "number") { - val = val & 255; - } else if (typeof val === "boolean") { - val = Number(val); - } - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError("Out of range index"); - } - if (end <= start) { - return this; - } - start = start >>> 0; - end = end === void 0 ? this.length : end >>> 0; - if (!val) val = 0; - let i; - if (typeof val === "number") { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - const bytes2 = Buffer3.isBuffer(val) ? val : Buffer3.from(val, encoding); - const len = bytes2.length; - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes2[i % len]; - } - } - return this; + const opts = (W2) => { + const windows = Math.ceil(bits / W2) + 1; + const windowSize = 2 ** (W2 - 1); + return { windows, windowSize }; }; - const errors2 = {}; - function E2(sym, getMessage, Base2) { - errors2[sym] = class NodeError extends Base2 { - constructor() { - super(); - Object.defineProperty(this, "message", { - value: getMessage.apply(this, arguments), - writable: true, - configurable: true - }); - this.name = `${this.name} [${sym}]`; - this.stack; - delete this.name; - } - get code() { - return sym; - } - set code(value) { - Object.defineProperty(this, "code", { - configurable: true, - enumerable: true, - value, - writable: true - }); - } - toString() { - return `${this.name} [${sym}]: ${this.message}`; - } - }; - } - E2( - "ERR_BUFFER_OUT_OF_BOUNDS", - function(name2) { - if (name2) { - return `${name2} is outside of buffer bounds`; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n2) { + let p2 = c2.ZERO; + let d2 = elm; + while (n2 > _0n$1) { + if (n2 & _1n$2) + p2 = p2.add(d2); + d2 = d2.double(); + n2 >>= _1n$2; } - return "Attempt to access memory outside buffer bounds"; - }, - RangeError - ); - E2( - "ERR_INVALID_ARG_TYPE", - function(name2, actual) { - return `The "${name2}" argument must be of type number. Received type ${typeof actual}`; + return p2; }, - TypeError - ); - E2( - "ERR_OUT_OF_RANGE", - function(str, range2, input2) { - let msg = `The value of "${str}" is out of range.`; - let received = input2; - if (Number.isInteger(input2) && Math.abs(input2) > 2 ** 32) { - received = addNumericalSeparator(String(input2)); - } else if (typeof input2 === "bigint") { - received = String(input2); - if (input2 > BigInt(2) ** BigInt(32) || input2 < -(BigInt(2) ** BigInt(32))) { - received = addNumericalSeparator(received); + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W2) { + const { windows, windowSize } = opts(W2); + const points = []; + let p2 = elm; + let base = p2; + for (let window2 = 0; window2 < windows; window2++) { + base = p2; + points.push(base); + for (let i = 1; i < windowSize; i++) { + base = base.add(p2); + points.push(base); } - received += "n"; + p2 = base.double(); } - msg += ` It must be ${range2}. Received ${received}`; - return msg; + return points; }, - RangeError - ); - function addNumericalSeparator(val) { - let res = ""; - let i = val.length; - const start = val[0] === "-" ? 1 : 0; - for (; i >= start + 4; i -= 3) { - res = `_${val.slice(i - 3, i)}${res}`; - } - return `${val.slice(0, i)}${res}`; - } - function checkBounds(buf, offset2, byteLength3) { - validateNumber(offset2, "offset"); - if (buf[offset2] === void 0 || buf[offset2 + byteLength3] === void 0) { - boundsError(offset2, buf.length - (byteLength3 + 1)); - } - } - function checkIntBI(value, min2, max2, buf, offset2, byteLength3) { - if (value > max2 || value < min2) { - const n2 = typeof min2 === "bigint" ? "n" : ""; - let range2; - { - if (min2 === 0 || min2 === BigInt(0)) { - range2 = `>= 0${n2} and < 2${n2} ** ${(byteLength3 + 1) * 8}${n2}`; + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W2, precomputes, n2) { + const { windows, windowSize } = opts(W2); + let p2 = c2.ZERO; + let f2 = c2.BASE; + const mask2 = BigInt(2 ** W2 - 1); + const maxNumber = 2 ** W2; + const shiftBy = BigInt(W2); + for (let window2 = 0; window2 < windows; window2++) { + const offset2 = window2 * windowSize; + let wbits = Number(n2 & mask2); + n2 >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n2 += _1n$2; + } + const offset1 = offset2; + const offset22 = offset2 + Math.abs(wbits) - 1; + const cond1 = window2 % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f2 = f2.add(constTimeNegate(cond1, precomputes[offset1])); } else { - range2 = `>= -(2${n2} ** ${(byteLength3 + 1) * 8 - 1}${n2}) and < 2 ** ${(byteLength3 + 1) * 8 - 1}${n2}`; + p2 = p2.add(constTimeNegate(cond2, precomputes[offset22])); } } - throw new errors2.ERR_OUT_OF_RANGE("value", range2, value); - } - checkBounds(buf, offset2, byteLength3); - } - function validateNumber(value, name2) { - if (typeof value !== "number") { - throw new errors2.ERR_INVALID_ARG_TYPE(name2, "number", value); - } - } - function boundsError(value, length, type) { - if (Math.floor(value) !== value) { - validateNumber(value, type); - throw new errors2.ERR_OUT_OF_RANGE("offset", "an integer", value); - } - if (length < 0) { - throw new errors2.ERR_BUFFER_OUT_OF_BOUNDS(); - } - throw new errors2.ERR_OUT_OF_RANGE( - "offset", - `>= ${0} and <= ${length}`, - value - ); - } - const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - function base64clean(str) { - str = str.split("=")[0]; - str = str.trim().replace(INVALID_BASE64_RE, ""); - if (str.length < 2) return ""; - while (str.length % 4 !== 0) { - str = str + "="; - } - return str; - } - function utf8ToBytes2(string, units) { - units = units || Infinity; - let codePoint; - const length = string.length; - let leadSurrogate = null; - const bytes2 = []; - for (let i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - if (codePoint > 55295 && codePoint < 57344) { - if (!leadSurrogate) { - if (codePoint > 56319) { - if ((units -= 3) > -1) bytes2.push(239, 191, 189); - continue; - } else if (i + 1 === length) { - if ((units -= 3) > -1) bytes2.push(239, 191, 189); - continue; - } - leadSurrogate = codePoint; - continue; - } - if (codePoint < 56320) { - if ((units -= 3) > -1) bytes2.push(239, 191, 189); - leadSurrogate = codePoint; - continue; + return { p: p2, f: f2 }; + }, + wNAFCached(P2, precomputesMap, n2, transform) { + const W2 = P2._WINDOW_SIZE || 1; + let comp = precomputesMap.get(P2); + if (!comp) { + comp = this.precomputeWindow(P2, W2); + if (W2 !== 1) { + precomputesMap.set(P2, transform(comp)); } - codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; - } else if (leadSurrogate) { - if ((units -= 3) > -1) bytes2.push(239, 191, 189); - } - leadSurrogate = null; - if (codePoint < 128) { - if ((units -= 1) < 0) break; - bytes2.push(codePoint); - } else if (codePoint < 2048) { - if ((units -= 2) < 0) break; - bytes2.push( - codePoint >> 6 | 192, - codePoint & 63 | 128 - ); - } else if (codePoint < 65536) { - if ((units -= 3) < 0) break; - bytes2.push( - codePoint >> 12 | 224, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else if (codePoint < 1114112) { - if ((units -= 4) < 0) break; - bytes2.push( - codePoint >> 18 | 240, - codePoint >> 12 & 63 | 128, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else { - throw new Error("Invalid code point"); - } - } - return bytes2; - } - function asciiToBytes(str) { - const byteArray = []; - for (let i = 0; i < str.length; ++i) { - byteArray.push(str.charCodeAt(i) & 255); - } - return byteArray; - } - function utf16leToBytes(str, units) { - let c2, hi2, lo; - const byteArray = []; - for (let i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break; - c2 = str.charCodeAt(i); - hi2 = c2 >> 8; - lo = c2 % 256; - byteArray.push(lo); - byteArray.push(hi2); - } - return byteArray; - } - function base64ToBytes(str) { - return base64.toByteArray(base64clean(str)); - } - function blitBuffer(src, dst, offset2, length) { - let i; - for (i = 0; i < length; ++i) { - if (i + offset2 >= dst.length || i >= src.length) break; - dst[i + offset2] = src[i]; - } - return i; - } - function isInstance(obj, type) { - return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; - } - function numberIsNaN(obj) { - return obj !== obj; - } - const hexSliceLookupTable = function() { - const alphabet = "0123456789abcdef"; - const table = new Array(256); - for (let i = 0; i < 16; ++i) { - const i16 = i * 16; - for (let j2 = 0; j2 < 16; ++j2) { - table[i16 + j2] = alphabet[i] + alphabet[j2]; } + return this.wNAF(W2, comp, n2); } - return table; - }(); - function defineBigIntMethod(fn) { - return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; - } - function BufferBigIntNotDefined() { - throw new Error("BigInt not supported"); - } -})(buffer$2); -const Buffer2 = buffer$2.Buffer; -const Blob$1 = buffer$2.Blob; -const BlobOptions = buffer$2.BlobOptions; -const Buffer$1 = buffer$2.Buffer; -const File = buffer$2.File; -const FileOptions = buffer$2.FileOptions; -const INSPECT_MAX_BYTES = buffer$2.INSPECT_MAX_BYTES; -const SlowBuffer = buffer$2.SlowBuffer; -const TranscodeEncoding = buffer$2.TranscodeEncoding; -const atob$1 = buffer$2.atob; -const btoa$1 = buffer$2.btoa; -const constants = buffer$2.constants; -const isAscii = buffer$2.isAscii; -const isUtf8 = buffer$2.isUtf8; -const kMaxLength = buffer$2.kMaxLength; -const kStringMaxLength = buffer$2.kStringMaxLength; -const resolveObjectURL = buffer$2.resolveObjectURL; -const transcode = buffer$2.transcode; -const dist$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - Blob: Blob$1, - BlobOptions, - Buffer: Buffer$1, - File, - FileOptions, - INSPECT_MAX_BYTES, - SlowBuffer, - TranscodeEncoding, - atob: atob$1, - btoa: btoa$1, - constants, - default: Buffer2, - isAscii, - isUtf8, - kMaxLength, - kStringMaxLength, - resolveObjectURL, - transcode -}, Symbol.toStringTag, { value: "Module" })); -const version$8 = "3.7.7"; -const VERSION$2 = version$8; -const _hasBuffer = typeof Buffer2 === "function"; -const _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0; -const _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0; -const b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; -const b64chs = Array.prototype.slice.call(b64ch); -const b64tab = ((a2) => { - let tab = {}; - a2.forEach((c2, i) => tab[c2] = i); - return tab; -})(b64chs); -const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/; -const _fromCC = String.fromCharCode.bind(String); -const _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0)); -const _mkUriSafe = (src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_"); -const _tidyB64 = (s2) => s2.replace(/[^A-Za-z0-9\+\/]/g, ""); -const btoaPolyfill = (bin) => { - let u322, c0, c1, c2, asc = ""; - const pad2 = bin.length % 3; - for (let i = 0; i < bin.length; ) { - if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255) - throw new TypeError("invalid character found"); - u322 = c0 << 16 | c1 << 8 | c2; - asc += b64chs[u322 >> 18 & 63] + b64chs[u322 >> 12 & 63] + b64chs[u322 >> 6 & 63] + b64chs[u322 & 63]; - } - return pad2 ? asc.slice(0, pad2 - 3) + "===".substring(pad2) : asc; -}; -const _btoa = typeof btoa === "function" ? (bin) => btoa(bin) : _hasBuffer ? (bin) => Buffer2.from(bin, "binary").toString("base64") : btoaPolyfill; -const _fromUint8Array = _hasBuffer ? (u8a2) => Buffer2.from(u8a2).toString("base64") : (u8a2) => { - const maxargs = 4096; - let strs = []; - for (let i = 0, l2 = u8a2.length; i < l2; i += maxargs) { - strs.push(_fromCC.apply(null, u8a2.subarray(i, i + maxargs))); - } - return _btoa(strs.join("")); -}; -const fromUint8Array = (u8a2, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a2)) : _fromUint8Array(u8a2); -const cb_utob = (c2) => { - if (c2.length < 2) { - var cc2 = c2.charCodeAt(0); - return cc2 < 128 ? c2 : cc2 < 2048 ? _fromCC(192 | cc2 >>> 6) + _fromCC(128 | cc2 & 63) : _fromCC(224 | cc2 >>> 12 & 15) + _fromCC(128 | cc2 >>> 6 & 63) + _fromCC(128 | cc2 & 63); - } else { - var cc2 = 65536 + (c2.charCodeAt(0) - 55296) * 1024 + (c2.charCodeAt(1) - 56320); - return _fromCC(240 | cc2 >>> 18 & 7) + _fromCC(128 | cc2 >>> 12 & 63) + _fromCC(128 | cc2 >>> 6 & 63) + _fromCC(128 | cc2 & 63); - } -}; -const re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; -const utob = (u2) => u2.replace(re_utob, cb_utob); -const _encode = _hasBuffer ? (s2) => Buffer2.from(s2, "utf8").toString("base64") : _TE ? (s2) => _fromUint8Array(_TE.encode(s2)) : (s2) => _btoa(utob(s2)); -const encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src); -const encodeURI$1 = (src) => encode(src, true); -const re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g; -const cb_btou = (cccc) => { - switch (cccc.length) { - case 4: - var cp = (7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3), offset2 = cp - 65536; - return _fromCC((offset2 >>> 10) + 55296) + _fromCC((offset2 & 1023) + 56320); - case 3: - return _fromCC((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2)); - default: - return _fromCC((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1)); - } -}; -const btou = (b2) => b2.replace(re_btou, cb_btou); -const atobPolyfill = (asc) => { - asc = asc.replace(/\s+/g, ""); - if (!b64re.test(asc)) - throw new TypeError("malformed base64."); - asc += "==".slice(2 - (asc.length & 3)); - let u24, bin = "", r1, r2; - for (let i = 0; i < asc.length; ) { - u24 = b64tab[asc.charAt(i++)] << 18 | b64tab[asc.charAt(i++)] << 12 | (r1 = b64tab[asc.charAt(i++)]) << 6 | (r2 = b64tab[asc.charAt(i++)]); - bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255); - } - return bin; -}; -const _atob = typeof atob === "function" ? (asc) => atob(_tidyB64(asc)) : _hasBuffer ? (asc) => Buffer2.from(asc, "base64").toString("binary") : atobPolyfill; -const _toUint8Array = _hasBuffer ? (a2) => _U8Afrom(Buffer2.from(a2, "base64")) : (a2) => _U8Afrom(_atob(a2).split("").map((c2) => c2.charCodeAt(0))); -const toUint8Array$1 = (a2) => _toUint8Array(_unURI(a2)); -const _decode = _hasBuffer ? (a2) => Buffer2.from(a2, "base64").toString("utf8") : _TD ? (a2) => _TD.decode(_toUint8Array(a2)) : (a2) => btou(_atob(a2)); -const _unURI = (a2) => _tidyB64(a2.replace(/[-_]/g, (m0) => m0 == "-" ? "+" : "/")); -const decode = (src) => _decode(_unURI(src)); -const isValid = (src) => { - if (typeof src !== "string") - return false; - const s2 = src.replace(/\s+/g, "").replace(/={0,2}$/, ""); - return !/[^\s0-9a-zA-Z\+/]/.test(s2) || !/[^\s0-9a-zA-Z\-_]/.test(s2); -}; -const _noEnum = (v3) => { - return { - value: v3, - enumerable: false, - writable: true, - configurable: true }; -}; -const extendString = function() { - const _add = (name2, body) => Object.defineProperty(String.prototype, name2, _noEnum(body)); - _add("fromBase64", function() { - return decode(this); - }); - _add("toBase64", function(urlsafe) { - return encode(this, urlsafe); - }); - _add("toBase64URI", function() { - return encode(this, true); - }); - _add("toBase64URL", function() { - return encode(this, true); - }); - _add("toUint8Array", function() { - return toUint8Array$1(this); - }); -}; -const extendUint8Array = function() { - const _add = (name2, body) => Object.defineProperty(Uint8Array.prototype, name2, _noEnum(body)); - _add("toBase64", function(urlsafe) { - return fromUint8Array(this, urlsafe); +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field" + }, { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger" }); - _add("toBase64URI", function() { - return fromUint8Array(this, true); + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER } }); - _add("toBase64URL", function() { - return fromUint8Array(this, true); +} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: "field", + b: "field" + }, { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function" }); -}; -const extendBuiltins = () => { - extendString(); - extendUint8Array(); -}; -const gBase64 = { - version: version$8, - VERSION: VERSION$2, - atob: _atob, - atobPolyfill, - btoa: _btoa, - btoaPolyfill, - fromBase64: decode, - toBase64: encode, - encode, - encodeURI: encodeURI$1, - encodeURL: encodeURI$1, - utob, - btou, - decode, - isValid, - fromUint8Array, - toUint8Array: toUint8Array$1, - extendString, - extendUint8Array, - extendBuiltins -}; -var __assign = function() { - __assign = Object.assign || function __assign2(t2) { - for (var s2, i = 1, n2 = arguments.length; i < n2; i++) { - s2 = arguments[i]; - for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2)) t2[p2] = s2[p2]; - } - return t2; - }; - return __assign.apply(this, arguments); -}; -function __awaiter(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } + const { endo, Fp: Fp2, a: a2 } = opts; + if (endo) { + if (!Fp2.eql(a2, Fp2.ZERO)) { + throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { + throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); } - step((generator = generator.apply(thisArg, [])).next()); - }); -} -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { - if (t2[0] & 1) throw t2[1]; - return t2[1]; - }, trys: [], ops: [] }, f2, y2, t2, g2; - return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() { - return this; - }), g2; - function verb(n2) { - return function(v3) { - return step([n2, v3]); - }; } - function step(op) { - if (f2) throw new TypeError("Generator is already executing."); - while (g2 && (g2 = 0, op[0] && (_ = 0)), _) try { - if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2; - if (y2 = 0, t2) op = [op[0] & 2, t2.value]; - switch (op[0]) { - case 0: - case 1: - t2 = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y2 = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t2 = _.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t2[1]) { - _.label = t2[1]; - t2 = op; - break; - } - if (t2 && _.label < t2[2]) { - _.label = t2[2]; - _.ops.push(op); - break; - } - if (t2[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e2) { - op = [6, e2]; - y2 = 0; - } finally { - f2 = t2 = 0; + return Object.freeze({ ...opts }); +} +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +const DER = { + // asn.1 DER encoding utils + Err: class DERErr2 extends Error { + constructor(m2 = "") { + super(m2); } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; + }, + _parseInt(data) { + const { Err: E2 } = DER; + if (data.length < 2 || data[0] !== 2) + throw new E2("Invalid signature integer tag"); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E2("Invalid signature integer: wrong length"); + if (res[0] & 128) + throw new E2("Invalid signature integer: negative"); + if (res[0] === 0 && !(res[1] & 128)) + throw new E2("Invalid signature integer: unnecessary leading zero"); + return { d: b2n(res), l: data.subarray(len + 2) }; + }, + toSig(hex2) { + const { Err: E2 } = DER; + const data = typeof hex2 === "string" ? h2b(hex2) : hex2; + if (!(data instanceof Uint8Array)) + throw new Error("ui8a expected"); + let l2 = data.length; + if (l2 < 2 || data[0] != 48) + throw new E2("Invalid signature tag"); + if (data[1] !== l2 - 2) + throw new E2("Invalid signature: incorrect length"); + const { d: r2, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s2, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E2("Invalid signature: left bytes after parsing"); + return { r: r2, s: s2 }; + }, + hexFromSig(sig) { + const slice2 = (s3) => Number.parseInt(s3[0], 16) & 8 ? "00" + s3 : s3; + const h2 = (num) => { + const hex2 = num.toString(16); + return hex2.length & 1 ? `0${hex2}` : hex2; + }; + const s2 = slice2(h2(sig.s)); + const r2 = slice2(h2(sig.r)); + const shl = s2.length / 2; + const rhl = r2.length / 2; + const sl2 = h2(shl); + const rl2 = h2(rhl); + return `30${h2(rhl + shl + 4)}02${rl2}${r2}02${sl2}${s2}`; } -} -var encodeTypedDataHash$1 = function(typedData) { - return TypedDataEncoder.hash(typedData.domain, typedData.types, typedData.message); -}; -var ETHAuthVersion = "1"; -var ETHAuthPrefix = "eth"; -var ETHAuthEIP712Domain = { - name: "ETHAuth", - version: ETHAuthVersion }; -var Proof = ( - /** @class */ - function() { - function Proof2(args) { - this.prefix = ETHAuthPrefix; - this.address = (args === null || args === void 0 ? void 0 : args.address) ? args.address.toLowerCase() : ""; - this.claims = (args === null || args === void 0 ? void 0 : args.claims) ? args.claims : { app: "", iat: 0, exp: 0, v: ETHAuthVersion }; - this.signature = (args === null || args === void 0 ? void 0 : args.signature) ? args.signature : ""; - this.extra = (args === null || args === void 0 ? void 0 : args.extra) ? args.extra : ""; - } - Proof2.prototype.setIssuedAtNow = function() { - this.claims.iat = Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3); - }; - Proof2.prototype.setExpiryIn = function(seconds) { - this.claims.exp = Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3) + seconds; - }; - Proof2.prototype.validateClaims = function() { - return validateClaims(this.claims); - }; - Proof2.prototype.messageDigest = function() { - var isValid2 = this.validateClaims(); - if (isValid2.err) { - throw isValid2.err; - } - return getBytes(encodeTypedDataHash$1(this.messageTypedData())); - }; - Proof2.prototype.messageTypedData = function() { - var domain2 = __assign({}, ETHAuthEIP712Domain); - var types2 = { - Claims: [] - }; - var message = {}; - var typedData = { domain: domain2, types: types2, message }; - if (this.claims.app && this.claims.app.length > 0) { - typedData.types.Claims.push({ name: "app", type: "string" }); - typedData.message["app"] = this.claims.app; - } - if (this.claims.iat && this.claims.iat > 0) { - typedData.types.Claims.push({ name: "iat", type: "int64" }); - typedData.message["iat"] = this.claims.iat; - } - if (this.claims.exp && this.claims.exp > 0) { - typedData.types.Claims.push({ name: "exp", type: "int64" }); - typedData.message["exp"] = this.claims.exp; - } - if (this.claims.n && this.claims.n > 0) { - typedData.types.Claims.push({ name: "n", type: "uint64" }); - typedData.message["n"] = this.claims.n; - } - if (this.claims.typ && this.claims.typ.length > 0) { - typedData.types.Claims.push({ name: "typ", type: "string" }); - typedData.message["typ"] = this.claims.typ; - } - if (this.claims.ogn && this.claims.ogn.length > 0) { - typedData.types.Claims.push({ name: "ogn", type: "string" }); - typedData.message["ogn"] = this.claims.ogn; - } - if (this.claims.v && this.claims.v.length > 0) { - typedData.types.Claims.push({ name: "v", type: "string" }); - typedData.message["v"] = this.claims.v; - } - return typedData; - }; - return Proof2; - }() -); -var validateClaims = function(claims) { - if (claims.app === "") { - return { ok: false, err: new Error("claims: app is empty") }; +const _0n = BigInt(0), _1n$1 = BigInt(1); +BigInt(2); +const _3n = BigInt(3); +BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp: Fp2 } = CURVE; + const toBytes2 = CURVE.toBytes || ((_c2, point, _isCompressed) => { + const a2 = point.toAffine(); + return concatBytes(Uint8Array.from([4]), Fp2.toBytes(a2.x), Fp2.toBytes(a2.y)); + }); + const fromBytes = CURVE.fromBytes || ((bytes2) => { + const tail = bytes2.subarray(1); + const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x: x2, y: y2 }; + }); + function weierstrassEquation(x2) { + const { a: a2, b: b2 } = CURVE; + const x22 = Fp2.sqr(x2); + const x3 = Fp2.mul(x22, x2); + return Fp2.add(Fp2.add(x3, Fp2.mul(x2, a2)), b2); } - var now = Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3); - var drift = 5 * 60; - var max2 = 60 * 60 * 24 * 365 + drift; - if (claims.v === "") { - return { ok: false, err: new Error("claims: ethauth version is empty") }; + if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error("bad generator point: equation left != right"); + function isWithinCurveOrder(num) { + return typeof num === "bigint" && _0n < num && num < CURVE.n; } - if (claims.iat && claims.iat !== 0 && (claims.iat > now + drift || claims.iat < now - max2)) { - return { ok: false, err: new Error("claims: iat is invalid") }; + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error("Expected valid bigint: 0 < bigint < curve.n"); } - if (claims.exp < now - drift || claims.exp > now + max2) { - return { ok: false, err: new Error("claims: token has expired") }; + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: n2 } = CURVE; + if (lengths && typeof key !== "bigint") { + if (key instanceof Uint8Array) + key = bytesToHex$1(key); + if (typeof key !== "string" || !lengths.includes(key.length)) + throw new Error("Invalid key"); + key = key.padStart(nByteLength * 2, "0"); + } + let num; + try { + num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + } catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod(num, n2); + assertGE(num); + return num; } - return { ok: true }; -}; -var ValidateEOAProof = function(provider2, chainId, proof) { - return __awaiter(void 0, void 0, void 0, function() { - var messageDigest, address; - return __generator(this, function(_a2) { - messageDigest = proof.messageDigest(); - address = verifyMessage$1(messageDigest, proof.signature); - if (address.slice(0, 2) === "0x" && address.length === 42 && address.toLowerCase() === proof.address.toLowerCase()) { - return [2, { isValid: true, address: proof.address }]; - } else { - return [2, { isValid: false }]; - } - }); - }); -}; -var ValidateContractAccountProof = function(provider2, chainId, proof) { - return __awaiter(void 0, void 0, void 0, function() { - var messageDigest, walletCode, abi2, contract, isValidSignature2; - return __generator(this, function(_a2) { - switch (_a2.label) { - case 0: - if (!provider2 || provider2 === void 0) { - return [2, { isValid: false }]; - } - messageDigest = proof.messageDigest(); - return [4, provider2.getCode(proof.address)]; - case 1: - walletCode = _a2.sent(); - if (walletCode === "0x" || walletCode.length <= 2) { - throw new Error("ValidateContractAccountProof failed. unable to fetch wallet contract code"); - } - abi2 = ["function isValidSignature(bytes32, bytes) public view returns (bytes4)"]; - contract = new Contract(proof.address, abi2, provider2); - return [4, contract.isValidSignature(messageDigest, getBytes(proof.signature))]; - case 2: - isValidSignature2 = _a2.sent(); - if (isValidSignature2 === IsValidSignatureBytes32MagicValue) { - return [2, { isValid: true, address: proof.address }]; - } else { - return [2, { isValid: false }]; - } - } - }); - }); -}; -var IsValidSignatureBytes32MagicValue = "0x1626ba7e"; -var ETHAuth = ( - /** @class */ - /* @__PURE__ */ function() { - function ETHAuth2() { - var validators = []; - for (var _i2 = 0; _i2 < arguments.length; _i2++) { - validators[_i2] = arguments[_i2]; + const pointPrecomputes = /* @__PURE__ */ new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error("ProjectivePoint expected"); + } + class Point { + constructor(px2, py, pz) { + this.px = px2; + this.py = py; + this.pz = pz; + if (px2 == null || !Fp2.isValid(px2)) + throw new Error("x required"); + if (py == null || !Fp2.isValid(py)) + throw new Error("y required"); + if (pz == null || !Fp2.isValid(pz)) + throw new Error("z required"); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p2) { + const { x: x2, y: y2 } = p2 || {}; + if (!p2 || !Fp2.isValid(x2) || !Fp2.isValid(y2)) + throw new Error("invalid affine point"); + if (p2 instanceof Point) + throw new Error("projective point not allowed"); + const is0 = (i) => Fp2.eql(i, Fp2.ZERO); + if (is0(x2) && is0(y2)) + return Point.ZERO; + return new Point(x2, y2, Fp2.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp2.invertBatch(points.map((p2) => p2.pz)); + return points.map((p2, i) => p2.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex2) { + const P2 = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex2))); + P2.assertValidity(); + return P2; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + if (this.is0()) { + if (CURVE.allowInfinityPoint && !Fp2.is0(this.py)) + return; + throw new Error("bad point: ZERO"); } - var _this = this; - this.configJsonRpcProvider = function(ethereumJsonRpcURL) { - return __awaiter(_this, void 0, void 0, function() { - var netVersion; - return __generator(this, function(_a2) { - switch (_a2.label) { - case 0: - this.provider = new JsonRpcProvider$1(ethereumJsonRpcURL); - return [4, this.provider.send("net_version", [])]; - case 1: - netVersion = _a2.sent(); - this.chainId = parseInt(netVersion); - if (!this.chainId) { - throw new Error("ethauth: unable to get chainId"); - } - this.ethereumJsonRpcURL = ethereumJsonRpcURL; - return [ - 2 - /*return*/ - ]; - } - }); - }); - }; - this.configValidators = function() { - var validators2 = []; - for (var _i3 = 0; _i3 < arguments.length; _i3++) { - validators2[_i3] = arguments[_i3]; - } - if (validators2.length == 0) { - throw new Error("validators list is empty"); - } - _this.validators = validators2; - }; - this.encodeProof = function(proof, skipSignatureValidation) { - if (skipSignatureValidation === void 0) { - skipSignatureValidation = false; - } - return __awaiter(_this, void 0, void 0, function() { - var isValid2, claimsJSON, proofString; - return __generator(this, function(_a2) { - switch (_a2.label) { - case 0: - if (proof.address.length !== 42 || proof.address.slice(0, 2) !== "0x") { - throw new Error("ethauth: invalid address"); - } - if (proof.signature === "" || proof.signature.slice(0, 2) !== "0x") { - throw new Error("ethauth: invalid signature"); - } - if (proof.extra && proof.extra.slice(0, 2) !== "0x") { - throw new Error("ethauth: invalid extra encoding, expecting hex data"); - } - return [4, this.validateProof(proof, skipSignatureValidation)]; - case 1: - isValid2 = _a2.sent(); - if (!isValid2) { - throw new Error("ethauth: proof is invalid"); - } - claimsJSON = JSON.stringify(proof.claims); - proofString = ETHAuthPrefix + "." + proof.address.toLowerCase() + "." + gBase64.encode(claimsJSON, true) + "." + proof.signature; - if (proof.extra && proof.extra.length > 0) { - proofString += "." + proof.extra; - } - return [2, proofString]; - } - }); - }); - }; - this.decodeProof = function(proofString, skipSignatureValidation) { - if (skipSignatureValidation === void 0) { - skipSignatureValidation = false; - } - return __awaiter(_this, void 0, void 0, function() { - var parts, prefix, address, messageBase64, signature2, extra, message, claims, proof, isValid2; - return __generator(this, function(_a2) { - switch (_a2.label) { - case 0: - parts = proofString.split("."); - if (parts.length < 4 || parts.length > 5) { - throw new Error("ethauth: invalid proof string"); - } - prefix = parts[0], address = parts[1], messageBase64 = parts[2], signature2 = parts[3], extra = parts[4]; - if (prefix !== ETHAuthPrefix) { - throw new Error("ethauth: not an ethauth proof"); - } - message = gBase64.decode(messageBase64); - claims = JSON.parse(message); - proof = new Proof({ address, claims, signature: signature2, extra }); - return [4, this.validateProof(proof, skipSignatureValidation)]; - case 1: - isValid2 = _a2.sent(); - if (!isValid2) { - throw new Error("ethauth: proof is invalid"); - } - return [2, proof]; - } - }); - }); - }; - this.validateProof = function(proof, skipSignatureValidation) { - if (skipSignatureValidation === void 0) { - skipSignatureValidation = false; - } - return __awaiter(_this, void 0, void 0, function() { - var isValidClaims, isValidSig; - return __generator(this, function(_a2) { - switch (_a2.label) { - case 0: - isValidClaims = this.validateProofClaims(proof); - if (isValidClaims.err) { - throw new Error("ethauth: proof claims are invalid ".concat(isValidClaims.err)); - } - if (!(skipSignatureValidation !== true)) return [3, 2]; - return [4, this.validateProofSignature(proof)]; - case 1: - isValidSig = _a2.sent(); - if (isValidSig !== true) { - throw new Error("ethauth: proof signature is invalid"); - } - _a2.label = 2; - case 2: - return [2, true]; - } - }); - }); - }; - this.validateProofSignature = function(proof) { - return __awaiter(_this, void 0, void 0, function() { - var retIsValid, i, validator, isValid2, i; - return __generator(this, function(_a2) { - switch (_a2.label) { - case 0: - retIsValid = []; - i = 0; - _a2.label = 1; - case 1: - if (!(i < this.validators.length)) return [3, 6]; - _a2.label = 2; - case 2: - _a2.trys.push([2, 4, , 5]); - validator = this.validators[i]; - return [4, validator(this.provider, this.chainId, proof)]; - case 3: - isValid2 = _a2.sent().isValid; - if (isValid2 === true) { - return [2, true]; - } - retIsValid.push(isValid2); - return [3, 5]; - case 4: - _a2.sent(); - retIsValid.push(false); - return [3, 5]; - case 5: - i++; - return [3, 1]; - case 6: - for (i = 0; i < retIsValid.length; i++) { - if (retIsValid[i]) { - return [2, true]; - } - } - return [2, false]; - } - }); - }); - }; - this.validateProofClaims = function(proof) { - return proof.validateClaims(); - }; - if (validators.length == 0) { - this.validators = [ValidateEOAProof, ValidateContractAccountProof]; + const { x: x2, y: y2 } = this.toAffine(); + if (!Fp2.isValid(x2) || !Fp2.isValid(y2)) + throw new Error("bad point: x or y not FE"); + const left = Fp2.sqr(y2); + const right = weierstrassEquation(x2); + if (!Fp2.eql(left, right)) + throw new Error("bad point: equation left != right"); + if (!this.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); + } + hasEvenY() { + const { y: y2 } = this.toAffine(); + if (Fp2.isOdd) + return !Fp2.isOdd(y2); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U12 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); + const U22 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); + return U12 && U22; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp2.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a: a2, b: b2 } = CURVE; + const b3 = Fp2.mul(b2, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + let t0 = Fp2.mul(X1, X1); + let t1 = Fp2.mul(Y1, Y1); + let t2 = Fp2.mul(Z1, Z1); + let t3 = Fp2.mul(X1, Y1); + t3 = Fp2.add(t3, t3); + Z3 = Fp2.mul(X1, Z1); + Z3 = Fp2.add(Z3, Z3); + X3 = Fp2.mul(a2, Z3); + Y3 = Fp2.mul(b3, t2); + Y3 = Fp2.add(X3, Y3); + X3 = Fp2.sub(t1, Y3); + Y3 = Fp2.add(t1, Y3); + Y3 = Fp2.mul(X3, Y3); + X3 = Fp2.mul(t3, X3); + Z3 = Fp2.mul(b3, Z3); + t2 = Fp2.mul(a2, t2); + t3 = Fp2.sub(t0, t2); + t3 = Fp2.mul(a2, t3); + t3 = Fp2.add(t3, Z3); + Z3 = Fp2.add(t0, t0); + t0 = Fp2.add(Z3, t0); + t0 = Fp2.add(t0, t2); + t0 = Fp2.mul(t0, t3); + Y3 = Fp2.add(Y3, t0); + t2 = Fp2.mul(Y1, Z1); + t2 = Fp2.add(t2, t2); + t0 = Fp2.mul(t2, t3); + X3 = Fp2.sub(X3, t0); + Z3 = Fp2.mul(t2, t1); + Z3 = Fp2.add(Z3, Z3); + Z3 = Fp2.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + const a2 = CURVE.a; + const b3 = Fp2.mul(CURVE.b, _3n); + let t0 = Fp2.mul(X1, X2); + let t1 = Fp2.mul(Y1, Y2); + let t2 = Fp2.mul(Z1, Z2); + let t3 = Fp2.add(X1, Y1); + let t4 = Fp2.add(X2, Y2); + t3 = Fp2.mul(t3, t4); + t4 = Fp2.add(t0, t1); + t3 = Fp2.sub(t3, t4); + t4 = Fp2.add(X1, Z1); + let t5 = Fp2.add(X2, Z2); + t4 = Fp2.mul(t4, t5); + t5 = Fp2.add(t0, t2); + t4 = Fp2.sub(t4, t5); + t5 = Fp2.add(Y1, Z1); + X3 = Fp2.add(Y2, Z2); + t5 = Fp2.mul(t5, X3); + X3 = Fp2.add(t1, t2); + t5 = Fp2.sub(t5, X3); + Z3 = Fp2.mul(a2, t4); + X3 = Fp2.mul(b3, t2); + Z3 = Fp2.add(X3, Z3); + X3 = Fp2.sub(t1, Z3); + Z3 = Fp2.add(t1, Z3); + Y3 = Fp2.mul(X3, Z3); + t1 = Fp2.add(t0, t0); + t1 = Fp2.add(t1, t0); + t2 = Fp2.mul(a2, t2); + t4 = Fp2.mul(b3, t4); + t1 = Fp2.add(t1, t2); + t2 = Fp2.sub(t0, t2); + t2 = Fp2.mul(a2, t2); + t4 = Fp2.add(t4, t2); + t0 = Fp2.mul(t1, t4); + Y3 = Fp2.add(Y3, t0); + t0 = Fp2.mul(t5, t4); + X3 = Fp2.mul(t3, X3); + X3 = Fp2.sub(X3, t0); + t0 = Fp2.mul(t3, t1); + Z3 = Fp2.mul(t5, Z3); + Z3 = Fp2.add(Z3, t0); + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n2) { + return wnaf.wNAFCached(this, pointPrecomputes, n2, (comp) => { + const toInv = Fp2.invertBatch(comp.map((p2) => p2.pz)); + return comp.map((p2, i) => p2.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n2) { + const I2 = Point.ZERO; + if (n2 === _0n) + return I2; + assertGE(n2); + if (n2 === _1n$1) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n2); + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n2); + let k1p = I2; + let k2p = I2; + let d2 = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n$1) + k1p = k1p.add(d2); + if (k2 & _1n$1) + k2p = k2p.add(d2); + d2 = d2.double(); + k1 >>= _1n$1; + k2 >>= _1n$1; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n2 = scalar; + let point, fake; + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n2); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); } else { - this.validators = validators; + const { p: p2, f: f2 } = this.wNAF(n2); + point = p2; + fake = f2; } + return Point.normalizeZ([point, fake])[0]; } - return ETHAuth2; - }() -); -let ChainId = /* @__PURE__ */ function(ChainId2) { - ChainId2[ChainId2["MAINNET"] = 1] = "MAINNET"; - ChainId2[ChainId2["ROPSTEN"] = 3] = "ROPSTEN"; - ChainId2[ChainId2["RINKEBY"] = 4] = "RINKEBY"; - ChainId2[ChainId2["GOERLI"] = 5] = "GOERLI"; - ChainId2[ChainId2["KOVAN"] = 42] = "KOVAN"; - ChainId2[ChainId2["SEPOLIA"] = 11155111] = "SEPOLIA"; - ChainId2[ChainId2["POLYGON"] = 137] = "POLYGON"; - ChainId2[ChainId2["POLYGON_MUMBAI"] = 80001] = "POLYGON_MUMBAI"; - ChainId2[ChainId2["POLYGON_ZKEVM"] = 1101] = "POLYGON_ZKEVM"; - ChainId2[ChainId2["POLYGON_AMOY"] = 80002] = "POLYGON_AMOY"; - ChainId2[ChainId2["BSC"] = 56] = "BSC"; - ChainId2[ChainId2["BSC_TESTNET"] = 97] = "BSC_TESTNET"; - ChainId2[ChainId2["OPTIMISM"] = 10] = "OPTIMISM"; - ChainId2[ChainId2["OPTIMISM_KOVAN"] = 69] = "OPTIMISM_KOVAN"; - ChainId2[ChainId2["OPTIMISM_GOERLI"] = 420] = "OPTIMISM_GOERLI"; - ChainId2[ChainId2["OPTIMISM_SEPOLIA"] = 11155420] = "OPTIMISM_SEPOLIA"; - ChainId2[ChainId2["ARBITRUM"] = 42161] = "ARBITRUM"; - ChainId2[ChainId2["ARBITRUM_GOERLI"] = 421613] = "ARBITRUM_GOERLI"; - ChainId2[ChainId2["ARBITRUM_SEPOLIA"] = 421614] = "ARBITRUM_SEPOLIA"; - ChainId2[ChainId2["ARBITRUM_NOVA"] = 42170] = "ARBITRUM_NOVA"; - ChainId2[ChainId2["AVALANCHE"] = 43114] = "AVALANCHE"; - ChainId2[ChainId2["AVALANCHE_TESTNET"] = 43113] = "AVALANCHE_TESTNET"; - ChainId2[ChainId2["GNOSIS"] = 100] = "GNOSIS"; - ChainId2[ChainId2["BASE"] = 8453] = "BASE"; - ChainId2[ChainId2["BASE_GOERLI"] = 84531] = "BASE_GOERLI"; - ChainId2[ChainId2["BASE_SEPOLIA"] = 84532] = "BASE_SEPOLIA"; - ChainId2[ChainId2["HOMEVERSE_TESTNET"] = 40875] = "HOMEVERSE_TESTNET"; - ChainId2[ChainId2["HOMEVERSE"] = 19011] = "HOMEVERSE"; - ChainId2[ChainId2["XAI"] = 660279] = "XAI"; - ChainId2[ChainId2["XAI_SEPOLIA"] = 37714555429] = "XAI_SEPOLIA"; - ChainId2[ChainId2["ASTAR_ZKEVM"] = 3776] = "ASTAR_ZKEVM"; - ChainId2[ChainId2["ASTAR_ZKYOTO"] = 6038361] = "ASTAR_ZKYOTO"; - ChainId2[ChainId2["XR_SEPOLIA"] = 2730] = "XR_SEPOLIA"; - ChainId2[ChainId2["TELOS"] = 40] = "TELOS"; - ChainId2[ChainId2["B3_SEPOLIA"] = 1993] = "B3_SEPOLIA"; - ChainId2[ChainId2["APECHAIN_TESTNET"] = 33111] = "APECHAIN_TESTNET"; - ChainId2[ChainId2["BLAST"] = 81457] = "BLAST"; - ChainId2[ChainId2["BLAST_SEPOLIA"] = 168587773] = "BLAST_SEPOLIA"; - ChainId2[ChainId2["BORNE_TESTNET"] = 94984] = "BORNE_TESTNET"; - ChainId2[ChainId2["SKALE_NEBULA_TESTNET"] = 37084624] = "SKALE_NEBULA_TESTNET"; - ChainId2[ChainId2["HARDHAT"] = 31337] = "HARDHAT"; - ChainId2[ChainId2["HARDHAT_2"] = 31338] = "HARDHAT_2"; - return ChainId2; -}({}); -let NetworkType = /* @__PURE__ */ function(NetworkType2) { - NetworkType2["MAINNET"] = "mainnet"; - NetworkType2["TESTNET"] = "testnet"; - return NetworkType2; -}({}); -const networks = { - [ChainId.MAINNET]: { - chainId: ChainId.MAINNET, - type: NetworkType.MAINNET, - name: "mainnet", - title: "Ethereum", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.MAINNET}.webp`, - blockExplorer: { - name: "Etherscan", - rootUrl: "https://etherscan.io/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 - }, - ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e" - }, - [ChainId.ROPSTEN]: { - chainId: ChainId.ROPSTEN, - type: NetworkType.TESTNET, - name: "ropsten", - title: "Ropsten", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ROPSTEN}.webp`, - testnet: true, - blockExplorer: { - name: "Etherscan (Ropsten)", - rootUrl: "https://ropsten.etherscan.io/" - }, - nativeToken: { - symbol: "roETH", - name: "Ropsten Ether", - decimals: 18 - }, - ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", - deprecated: true - }, - [ChainId.RINKEBY]: { - chainId: ChainId.RINKEBY, - type: NetworkType.TESTNET, - name: "rinkeby", - title: "Rinkeby", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.RINKEBY}.webp`, - testnet: true, - blockExplorer: { - name: "Etherscan (Rinkeby)", - rootUrl: "https://rinkeby.etherscan.io/" - }, - nativeToken: { - symbol: "rETH", - name: "Rinkeby Ether", - decimals: 18 - }, - ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", - deprecated: true - }, - [ChainId.GOERLI]: { - chainId: ChainId.GOERLI, - type: NetworkType.TESTNET, - name: "goerli", - title: "Goerli", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.GOERLI}.webp`, - testnet: true, - blockExplorer: { - name: "Etherscan (Goerli)", - rootUrl: "https://goerli.etherscan.io/" - }, - nativeToken: { - symbol: "gETH", - name: "Goerli Ether", - decimals: 18 - }, - ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", - deprecated: true - }, - [ChainId.KOVAN]: { - chainId: ChainId.KOVAN, - type: NetworkType.TESTNET, - name: "kovan", - title: "Kovan", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.KOVAN}.webp`, - testnet: true, - blockExplorer: { - name: "Etherscan (Kovan)", - rootUrl: "https://kovan.etherscan.io/" - }, - nativeToken: { - symbol: "kETH", - name: "Kovan Ether", - decimals: 18 - }, - deprecated: true - }, - [ChainId.SEPOLIA]: { - chainId: ChainId.SEPOLIA, - type: NetworkType.TESTNET, - name: "sepolia", - title: "Sepolia", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.SEPOLIA}.webp`, - testnet: true, - blockExplorer: { - name: "Etherscan (Sepolia)", - rootUrl: "https://sepolia.etherscan.io/" - }, - nativeToken: { - symbol: "sETH", - name: "Sepolia Ether", - decimals: 18 + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q2, a2, b2) { + const G2 = Point.BASE; + const mul = (P2, a3) => a3 === _0n || a3 === _1n$1 || !P2.equals(G2) ? P2.multiplyUnsafe(a3) : P2.multiply(a3); + const sum = mul(this, a2).add(mul(Q2, b2)); + return sum.is0() ? void 0 : sum; } - }, - [ChainId.POLYGON]: { - chainId: ChainId.POLYGON, - type: NetworkType.MAINNET, - name: "polygon", - title: "Polygon", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.POLYGON}.webp`, - blockExplorer: { - name: "Polygonscan", - rootUrl: "https://polygonscan.com/" - }, - nativeToken: { - symbol: "POL", - name: "POL", - decimals: 18 + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x2, py: y2, pz: z2 } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? Fp2.ONE : Fp2.inv(z2); + const ax = Fp2.mul(x2, iz); + const ay = Fp2.mul(y2, iz); + const zz = Fp2.mul(z2, iz); + if (is0) + return { x: Fp2.ZERO, y: Fp2.ZERO }; + if (!Fp2.eql(zz, Fp2.ONE)) + throw new Error("invZ was invalid"); + return { x: ax, y: ay }; } - }, - [ChainId.POLYGON_MUMBAI]: { - chainId: ChainId.POLYGON_MUMBAI, - type: NetworkType.TESTNET, - name: "mumbai", - title: "Polygon Mumbai", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.POLYGON_MUMBAI}.webp`, - testnet: true, - blockExplorer: { - name: "Polygonscan (Mumbai)", - rootUrl: "https://mumbai.polygonscan.com/" - }, - nativeToken: { - symbol: "mMATIC", - name: "Mumbai Polygon", - decimals: 18 - }, - deprecated: true - }, - [ChainId.POLYGON_AMOY]: { - chainId: ChainId.POLYGON_AMOY, - type: NetworkType.TESTNET, - name: "amoy", - title: "Polygon Amoy", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.POLYGON_AMOY}.webp`, - testnet: true, - blockExplorer: { - name: "OKLink (Amoy)", - rootUrl: "https://www.oklink.com/amoy/" - }, - nativeToken: { - symbol: "aPOL", - name: "Amoy POL", - decimals: 18 + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n$1) + return true; + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error("isTorsionFree() has not been declared for the elliptic curve"); } - }, - [ChainId.POLYGON_ZKEVM]: { - chainId: ChainId.POLYGON_ZKEVM, - type: NetworkType.MAINNET, - name: "polygon-zkevm", - title: "Polygon zkEVM", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.POLYGON_ZKEVM}.webp`, - blockExplorer: { - name: "Polygonscan (zkEVM)", - rootUrl: "https://zkevm.polygonscan.com/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n$1) + return this; + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); } - }, - [ChainId.BSC]: { - chainId: ChainId.BSC, - type: NetworkType.MAINNET, - name: "bsc", - title: "BNB Smart Chain", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BSC}.webp`, - blockExplorer: { - name: "BSCScan", - rootUrl: "https://bscscan.com/" - }, - nativeToken: { - symbol: "BNB", - name: "BNB", - decimals: 18 + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes2(Point, this, isCompressed); } - }, - [ChainId.BSC_TESTNET]: { - chainId: ChainId.BSC_TESTNET, - type: NetworkType.TESTNET, - name: "bsc-testnet", - title: "BNB Smart Chain Testnet", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BSC_TESTNET}.webp`, - testnet: true, - blockExplorer: { - name: "BSCScan (Testnet)", - rootUrl: "https://testnet.bscscan.com/" + toHex(isCompressed = true) { + return bytesToHex$1(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE); + Point.ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: "hash", + hmac: "function", + randomBytes: "function" + }, { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean" + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp: Fp2, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp2.BYTES + 1; + const uncompressedLen = 2 * Fp2.BYTES + 1; + function isValidFieldElement(num) { + return _0n < num && num < Fp2.ORDER; + } + function modN(a2) { + return mod(a2, CURVE_ORDER); + } + function invN(a2) { + return invert(a2, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ + ...CURVE, + toBytes(_c2, point, isCompressed) { + const a2 = point.toAffine(); + const x2 = Fp2.toBytes(a2.x); + const cat = concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x2); + } else { + return cat(Uint8Array.from([4]), x2, Fp2.toBytes(a2.y)); + } }, - nativeToken: { - symbol: "tBNB", - name: "Testnet BNB", - decimals: 18 + fromBytes(bytes2) { + const len = bytes2.length; + const head = bytes2[0]; + const tail = bytes2.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x2 = bytesToNumberBE(tail); + if (!isValidFieldElement(x2)) + throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x2); + let y3 = Fp2.sqrt(y2); + const isYOdd = (y3 & _1n$1) === _1n$1; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y3 = Fp2.neg(y3); + return { x: x2, y: y3 }; + } else if (len === uncompressedLen && head === 4) { + const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x: x2, y: y2 }; + } else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + } + }); + const numToNByteStr = (num) => bytesToHex$1(numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number2) { + const HALF = CURVE_ORDER >> _1n$1; + return number2 > HALF; + } + function normalizeS(s2) { + return isBiggerThanHalfOrder(s2) ? modN(-s2) : s2; + } + const slcNum = (b2, from, to) => bytesToNumberBE(b2.slice(from, to)); + class Signature2 { + constructor(r2, s2, recovery) { + this.r = r2; + this.s = s2; + this.recovery = recovery; + this.assertValidity(); } - }, - [ChainId.OPTIMISM]: { - chainId: ChainId.OPTIMISM, - type: NetworkType.MAINNET, - name: "optimism", - title: "Optimism", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.OPTIMISM}.webp`, - blockExplorer: { - name: "Etherscan (Optimism)", - rootUrl: "https://optimistic.etherscan.io/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + // pair (bytes of r, bytes of s) + static fromCompact(hex2) { + const l2 = CURVE.nByteLength; + hex2 = ensureBytes("compactSignature", hex2, l2 * 2); + return new Signature2(slcNum(hex2, 0, l2), slcNum(hex2, l2, 2 * l2)); } - }, - [ChainId.OPTIMISM_KOVAN]: { - chainId: ChainId.OPTIMISM_KOVAN, - type: NetworkType.TESTNET, - name: "optimism-kovan", - title: "Optimism Kovan", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.OPTIMISM_KOVAN}.webp`, - testnet: true, - blockExplorer: { - name: "Etherscan (Optimism Kovan)", - rootUrl: "https://kovan-optimistic.etherscan.io/" - }, - nativeToken: { - symbol: "kETH", - name: "Kovan Ether", - decimals: 18 - }, - deprecated: true - }, - [ChainId.OPTIMISM_GOERLI]: { - chainId: ChainId.OPTIMISM_GOERLI, - type: NetworkType.TESTNET, - name: "optimism-goerli", - title: "Optimism Goerli", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.OPTIMISM_GOERLI}.webp`, - testnet: true, - blockExplorer: { - name: "Etherscan (Optimism Goerli)", - rootUrl: "https://goerli-optimistic.etherscan.io/" - }, - nativeToken: { - symbol: "gETH", - name: "Goerli Ether", - decimals: 18 - }, - deprecated: true - }, - [ChainId.OPTIMISM_SEPOLIA]: { - chainId: ChainId.OPTIMISM_SEPOLIA, - type: NetworkType.TESTNET, - name: "optimism-sepolia", - title: "Optimism Sepolia", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.OPTIMISM_SEPOLIA}.webp`, - testnet: true, - blockExplorer: { - name: "Etherscan (Optimism Sepolia)", - rootUrl: "https://sepolia-optimistic.etherscan.io/" - }, - nativeToken: { - symbol: "sETH", - name: "Sepolia Ether", - decimals: 18 + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex2) { + const { r: r2, s: s2 } = DER.toSig(ensureBytes("DER", hex2)); + return new Signature2(r2, s2); } - }, - [ChainId.ARBITRUM]: { - chainId: ChainId.ARBITRUM, - type: NetworkType.MAINNET, - name: "arbitrum", - title: "Arbitrum One", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ARBITRUM}.webp`, - blockExplorer: { - name: "Arbiscan", - rootUrl: "https://arbiscan.io/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + assertValidity() { + if (!isWithinCurveOrder(this.r)) + throw new Error("r must be 0 < r < CURVE.n"); + if (!isWithinCurveOrder(this.s)) + throw new Error("s must be 0 < s < CURVE.n"); } - }, - [ChainId.ARBITRUM_GOERLI]: { - chainId: ChainId.ARBITRUM_GOERLI, - type: NetworkType.TESTNET, - name: "arbitrum-goerli", - title: "Arbitrum Goerli", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ARBITRUM_GOERLI}.webp`, - testnet: true, - blockExplorer: { - name: "Arbiscan (Goerli Testnet)", - rootUrl: "https://testnet.arbiscan.io/" - }, - nativeToken: { - symbol: "gETH", - name: "Goerli Ether", - decimals: 18 - }, - deprecated: true - }, - [ChainId.ARBITRUM_SEPOLIA]: { - chainId: ChainId.ARBITRUM_SEPOLIA, - type: NetworkType.TESTNET, - name: "arbitrum-sepolia", - title: "Arbitrum Sepolia", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ARBITRUM_SEPOLIA}.webp`, - testnet: true, - blockExplorer: { - name: "Arbiscan (Sepolia Testnet)", - rootUrl: "https://sepolia.arbiscan.io/" - }, - nativeToken: { - symbol: "sETH", - name: "Sepolia Ether", - decimals: 18 + addRecoveryBit(recovery) { + return new Signature2(this.r, this.s, recovery); } - }, - [ChainId.ARBITRUM_NOVA]: { - chainId: ChainId.ARBITRUM_NOVA, - type: NetworkType.MAINNET, - name: "arbitrum-nova", - title: "Arbitrum Nova", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ARBITRUM_NOVA}.webp`, - blockExplorer: { - name: "Arbiscan Nova", - rootUrl: "https://nova.arbiscan.io/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + recoverPublicKey(msgHash) { + const { r: r2, s: s2, recovery: rec } = this; + const h2 = bits2int_modN(ensureBytes("msgHash", msgHash)); + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r2 + CURVE.n : r2; + if (radj >= Fp2.ORDER) + throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R2 = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); + const u1 = modN(-h2 * ir); + const u2 = modN(s2 * ir); + const Q2 = Point.BASE.multiplyAndAddUnsafe(R2, u1, u2); + if (!Q2) + throw new Error("point at infinify"); + Q2.assertValidity(); + return Q2; } - }, - [ChainId.AVALANCHE]: { - chainId: ChainId.AVALANCHE, - type: NetworkType.MAINNET, - name: "avalanche", - title: "Avalanche", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.AVALANCHE}.webp`, - blockExplorer: { - name: "Snowtrace", - rootUrl: "https://subnets.avax.network/c-chain/" - }, - nativeToken: { - symbol: "AVAX", - name: "AVAX", - decimals: 18 + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); } - }, - [ChainId.AVALANCHE_TESTNET]: { - chainId: ChainId.AVALANCHE_TESTNET, - type: NetworkType.TESTNET, - name: "avalanche-testnet", - title: "Avalanche Testnet", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.AVALANCHE_TESTNET}.webp`, - testnet: true, - blockExplorer: { - name: "Snowtrace (Testnet)", - rootUrl: "https://subnets-test.avax.network/c-chain/" - }, - nativeToken: { - symbol: "tAVAX", - name: "Testnet AVAX", - decimals: 18 + normalizeS() { + return this.hasHighS() ? new Signature2(this.r, modN(-this.s), this.recovery) : this; } - }, - [ChainId.GNOSIS]: { - chainId: ChainId.GNOSIS, - type: NetworkType.MAINNET, - name: "gnosis", - title: "Gnosis Chain", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.GNOSIS}.webp`, - blockExplorer: { - name: "Gnosis Chain Explorer", - rootUrl: "https://blockscout.com/xdai/mainnet/" - }, - nativeToken: { - symbol: "XDAI", - name: "XDAI", - decimals: 18 + // DER-encoded + toDERRawBytes() { + return hexToBytes(this.toDERHex()); } - }, - [ChainId.BASE]: { - chainId: ChainId.BASE, - type: NetworkType.MAINNET, - name: "base", - title: "Base (Coinbase)", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BASE}.webp`, - blockExplorer: { - name: "Base Explorer", - rootUrl: "https://basescan.org/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); } - }, - [ChainId.BASE_GOERLI]: { - chainId: ChainId.BASE_GOERLI, - type: NetworkType.TESTNET, - name: "base-goerli", - title: "Base Goerli", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BASE_GOERLI}.webp`, - testnet: true, - blockExplorer: { - name: "Base Goerli Explorer", - rootUrl: "https://goerli.basescan.org/" - }, - nativeToken: { - symbol: "gETH", - name: "Goerli Ether", - decimals: 18 + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils2 = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } }, - deprecated: true - }, - [ChainId.BASE_SEPOLIA]: { - chainId: ChainId.BASE_SEPOLIA, - type: NetworkType.TESTNET, - name: "base-sepolia", - title: "Base Sepolia", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BASE_SEPOLIA}.webp`, - testnet: true, - blockExplorer: { - name: "Base Sepolia Explorer", - rootUrl: "https://base-sepolia.blockscout.com/" + normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); }, - nativeToken: { - symbol: "sETH", - name: "Sepolia Ether", - decimals: 18 + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; } - }, - [ChainId.HOMEVERSE]: { - chainId: ChainId.HOMEVERSE, - type: NetworkType.MAINNET, - name: "homeverse", - title: "Oasys Homeverse", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.HOMEVERSE}.webp`, - blockExplorer: { - name: "Oasys Homeverse Explorer", - rootUrl: "https://explorer.oasys.homeverse.games/" - }, - nativeToken: { - symbol: "OAS", - name: "OAS", - decimals: 18 + }; + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + function isProbPub(item2) { + const arr = item2 instanceof Uint8Array; + const str = typeof item2 === "string"; + const len = (arr || str) && item2.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item2 instanceof Point) + return true; + return false; + } + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) + throw new Error("second arg must be public key"); + const b2 = Point.fromHex(publicB); + return b2.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + const bits2int = CURVE.bits2int || function(bytes2) { + const num = bytesToNumberBE(bytes2); + const delta = bytes2.length * 8 - CURVE.nBitLength; + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || function(bytes2) { + return modN(bits2int(bytes2)); + }; + const ORDER_MASK = bitMask(CURVE.nBitLength); + function int2octets(num) { + if (typeof num !== "bigint") + throw new Error("bigint expected"); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + return numberToBytesBE(num, CURVE.nByteLength); + } + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (["recovered", "canonical"].some((k2) => k2 in opts)) + throw new Error("sign() legacy options not supported"); + const { hash: hash2, randomBytes: randomBytes2 } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) + lowS = true; + msgHash = ensureBytes("msgHash", msgHash); + if (prehash) + msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); + const h1int = bits2int_modN(msgHash); + const d2 = normPrivateKeyToScalar(privateKey); + const seedArgs = [int2octets(d2), int2octets(h1int)]; + if (ent != null) { + const e2 = ent === true ? randomBytes2(Fp2.BYTES) : ent; + seedArgs.push(ensureBytes("extraEntropy", e2)); } - }, - [ChainId.HOMEVERSE_TESTNET]: { - chainId: ChainId.HOMEVERSE_TESTNET, - type: NetworkType.TESTNET, - name: "homeverse-testnet", - title: "Oasys Homeverse Testnet", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.HOMEVERSE_TESTNET}.webp`, - testnet: true, - blockExplorer: { - name: "Oasys Homeverse Explorer (Testnet)", - rootUrl: "https://explorer.testnet.oasys.homeverse.games/" - }, - nativeToken: { - symbol: "tOAS", - name: "Testnet OAS", - decimals: 18 + const seed = concatBytes(...seedArgs); + const m2 = h1int; + function k2sig(kBytes) { + const k2 = bits2int(kBytes); + if (!isWithinCurveOrder(k2)) + return; + const ik2 = invN(k2); + const q2 = Point.BASE.multiply(k2).toAffine(); + const r2 = modN(q2.x); + if (r2 === _0n) + return; + const s2 = modN(ik2 * modN(m2 + r2 * d2)); + if (s2 === _0n) + return; + let recovery = (q2.x === r2 ? 0 : 2) | Number(q2.y & _1n$1); + let normS = s2; + if (lowS && isBiggerThanHalfOrder(s2)) { + normS = normalizeS(s2); + recovery ^= 1; + } + return new Signature2(r2, normS, recovery); } - }, - [ChainId.XAI]: { - chainId: ChainId.XAI, - type: NetworkType.MAINNET, - name: "xai", - title: "Xai", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.XAI}.webp`, - blockExplorer: { - name: "Xai Explorer", - rootUrl: "https://explorer.xai-chain.net/" - }, - nativeToken: { - symbol: "XAI", - name: "XAI", - decimals: 18 + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const C2 = CURVE; + const drbg = createHmacDrbg(C2.hash.outputLen, C2.nByteLength, C2.hmac); + return drbg(seed, k2sig); + } + Point.BASE._setWindowSize(8); + function verify(signature2, msgHash, publicKey, opts = defaultVerOpts) { + var _a2; + const sg2 = signature2; + msgHash = ensureBytes("msgHash", msgHash); + publicKey = ensureBytes("publicKey", publicKey); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + const { lowS, prehash } = opts; + let _sig2 = void 0; + let P2; + try { + if (typeof sg2 === "string" || sg2 instanceof Uint8Array) { + try { + _sig2 = Signature2.fromDER(sg2); + } catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig2 = Signature2.fromCompact(sg2); + } + } else if (typeof sg2 === "object" && typeof sg2.r === "bigint" && typeof sg2.s === "bigint") { + const { r: r3, s: s3 } = sg2; + _sig2 = new Signature2(r3, s3); + } else { + throw new Error("PARSE"); + } + P2 = Point.fromHex(publicKey); + } catch (error) { + if (error.message === "PARSE") + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig2.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r: r2, s: s2 } = _sig2; + const h2 = bits2int_modN(msgHash); + const is = invN(s2); + const u1 = modN(h2 * is); + const u2 = modN(r2 * is); + const R2 = (_a2 = Point.BASE.multiplyAndAddUnsafe(P2, u1, u2)) == null ? void 0 : _a2.toAffine(); + if (!R2) + return false; + const v3 = modN(R2.x); + return v3 === r2; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature: Signature2, + utils: utils2 + }; +} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +function getHash(hash2) { + return { + hash: hash2, + hmac: (key, ...msgs) => hmac$1(hash2, key, concatBytes$1(...msgs)), + randomBytes: randomBytes$2 + }; +} +function createCurve(curveDef, defHash) { + const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); + return Object.freeze({ ...create(defHash), create }); +} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); +const secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a2, b2) => (a2 + b2 / _2n) / b2; +function sqrtMod(y2) { + const P2 = secp256k1P; + const _3n2 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = y2 * y2 * y2 % P2; + const b3 = b2 * b2 * y2 % P2; + const b6 = pow2(b3, _3n2, P2) * b3 % P2; + const b9 = pow2(b6, _3n2, P2) * b3 % P2; + const b11 = pow2(b9, _2n, P2) * b2 % P2; + const b22 = pow2(b11, _11n, P2) * b11 % P2; + const b44 = pow2(b22, _22n, P2) * b22 % P2; + const b88 = pow2(b44, _44n, P2) * b44 % P2; + const b176 = pow2(b88, _88n, P2) * b88 % P2; + const b220 = pow2(b176, _44n, P2) * b44 % P2; + const b223 = pow2(b220, _3n2, P2) * b3 % P2; + const t1 = pow2(b223, _23n, P2) * b22 % P2; + const t2 = pow2(t1, _6n, P2) * b2 % P2; + const root2 = pow2(t2, _2n, P2); + if (!Fp.eql(Fp.sqr(root2), y2)) + throw new Error("Cannot find square root"); + return root2; +} +const Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); +const secp256k1 = createCurve({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), + Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + splitScalar: (k2) => { + const n2 = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k2, n2); + const c2 = divNearest(-b1 * k2, n2); + let k1 = mod(k2 - c1 * a1 - c2 * a2, n2); + let k22 = mod(-c1 * b1 - c2 * b2, n2); + const k1neg = k1 > POW_2_128; + const k2neg = k22 > POW_2_128; + if (k1neg) + k1 = n2 - k1; + if (k2neg) + k22 = n2 - k22; + if (k1 > POW_2_128 || k22 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k2); + } + return { k1neg, k1, k2neg, k2: k22 }; } - }, - [ChainId.XAI_SEPOLIA]: { - chainId: ChainId.XAI_SEPOLIA, - type: NetworkType.TESTNET, - name: "xai-sepolia", - title: "Xai Sepolia", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.XAI_SEPOLIA}.webp`, - testnet: true, - blockExplorer: { - name: "Xai Sepolia Explorer", - rootUrl: "https://testnet-explorer-v2.xai-chain.net/" - }, - nativeToken: { - symbol: "sXAI", - name: "Sepolia XAI", - decimals: 18 + } +}, sha256$2); +BigInt(0); +secp256k1.ProjectivePoint; +const ZeroAddress = "0x0000000000000000000000000000000000000000"; +const ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"; +const N$1 = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const WeiPerEther = BigInt("1000000000000000000"); +const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const MinInt256 = BigInt("0x8000000000000000000000000000000000000000000000000000000000000000") * BigInt(-1); +const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const EtherSymbol = "Ξ"; +const MessagePrefix = "Ethereum Signed Message:\n"; +const BN_0$7 = BigInt(0); +const BN_1$3 = BigInt(1); +const BN_2$3 = BigInt(2); +const BN_27$1 = BigInt(27); +const BN_28$1 = BigInt(28); +const BN_35$1 = BigInt(35); +const _guard$3 = {}; +function toUint256(value) { + return zeroPadValue(toBeArray(value), 32); +} +const _Signature = class _Signature { + /** + * @private + */ + constructor(guard2, r2, s2, v3) { + __privateAdd(this, _r); + __privateAdd(this, _s); + __privateAdd(this, _v); + __privateAdd(this, _networkV); + assertPrivate(guard2, _guard$3, "Signature"); + __privateSet(this, _r, r2); + __privateSet(this, _s, s2); + __privateSet(this, _v, v3); + __privateSet(this, _networkV, null); + } + /** + * The ``r`` value for a signautre. + * + * This represents the ``x`` coordinate of a "reference" or + * challenge point, from which the ``y`` can be computed. + */ + get r() { + return __privateGet(this, _r); + } + set r(value) { + assertArgument(dataLength(value) === 32, "invalid r", "value", value); + __privateSet(this, _r, hexlify(value)); + } + /** + * The ``s`` value for a signature. + */ + get s() { + return __privateGet(this, _s); + } + set s(_value2) { + assertArgument(dataLength(_value2) === 32, "invalid s", "value", _value2); + const value = hexlify(_value2); + assertArgument(parseInt(value.substring(0, 3)) < 8, "non-canonical s", "value", value); + __privateSet(this, _s, value); + } + /** + * The ``v`` value for a signature. + * + * Since a given ``x`` value for ``r`` has two possible values for + * its correspondin ``y``, the ``v`` indicates which of the two ``y`` + * values to use. + * + * It is normalized to the values ``27`` or ``28`` for legacy + * purposes. + */ + get v() { + return __privateGet(this, _v); + } + set v(value) { + const v3 = getNumber(value, "value"); + assertArgument(v3 === 27 || v3 === 28, "invalid v", "v", value); + __privateSet(this, _v, v3); + } + /** + * The EIP-155 ``v`` for legacy transactions. For non-legacy + * transactions, this value is ``null``. + */ + get networkV() { + return __privateGet(this, _networkV); + } + /** + * The chain ID for EIP-155 legacy transactions. For non-legacy + * transactions, this value is ``null``. + */ + get legacyChainId() { + const v3 = this.networkV; + if (v3 == null) { + return null; } - }, - [ChainId.ASTAR_ZKEVM]: { - chainId: ChainId.ASTAR_ZKEVM, - type: NetworkType.MAINNET, - name: "astar-zkevm", - title: "Astar zkEVM", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ASTAR_ZKEVM}.webp`, - blockExplorer: { - name: "Astar zkEVM Explorer", - rootUrl: "https://astar-zkevm.explorer.startale.com/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + return _Signature.getChainId(v3); + } + /** + * The ``yParity`` for the signature. + * + * See ``v`` for more details on how this value is used. + */ + get yParity() { + return this.v === 27 ? 0 : 1; + } + /** + * The [[link-eip-2098]] compact representation of the ``yParity`` + * and ``s`` compacted into a single ``bytes32``. + */ + get yParityAndS() { + const yParityAndS = getBytes(this.s); + if (this.yParity) { + yParityAndS[0] |= 128; } - }, - [ChainId.ASTAR_ZKYOTO]: { - chainId: ChainId.ASTAR_ZKYOTO, - type: NetworkType.TESTNET, - name: "astar-zkyoto", - title: "Astar zKyoto Testnet", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ASTAR_ZKYOTO}.webp`, - testnet: true, - blockExplorer: { - name: "Astar zKyoto Explorer", - rootUrl: "https://astar-zkyoto.blockscout.com/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + return hexlify(yParityAndS); + } + /** + * The [[link-eip-2098]] compact representation. + */ + get compactSerialized() { + return concat([this.r, this.yParityAndS]); + } + /** + * The serialized representation. + */ + get serialized() { + return concat([this.r, this.s, this.yParity ? "0x1c" : "0x1b"]); + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`; + } + /** + * Returns a new identical [[Signature]]. + */ + clone() { + const clone = new _Signature(_guard$3, this.r, this.s, this.v); + if (this.networkV) { + __privateSet(clone, _networkV, this.networkV); } - }, - [ChainId.XR_SEPOLIA]: { - chainId: ChainId.XR_SEPOLIA, - type: NetworkType.TESTNET, - name: "xr-sepolia", - title: "XR Sepolia", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.XR_SEPOLIA}.webp`, - testnet: true, - blockExplorer: { - name: "XR Sepolia Explorer", - rootUrl: "https://xr-sepolia-testnet.explorer.caldera.xyz/" - }, - nativeToken: { - symbol: "tXR", - name: "Sepolia XR", - decimals: 18 + return clone; + } + /** + * Returns a representation that is compatible with ``JSON.stringify``. + */ + toJSON() { + const networkV = this.networkV; + return { + _type: "signature", + networkV: networkV != null ? networkV.toString() : null, + r: this.r, + s: this.s, + v: this.v + }; + } + /** + * Compute the chain ID from the ``v`` in a legacy EIP-155 transactions. + * + * @example: + * Signature.getChainId(45) + * //_result: + * + * Signature.getChainId(46) + * //_result: + */ + static getChainId(v3) { + const bv = getBigInt(v3, "v"); + if (bv == BN_27$1 || bv == BN_28$1) { + return BN_0$7; } - }, - [ChainId.B3_SEPOLIA]: { - chainId: ChainId.B3_SEPOLIA, - type: NetworkType.TESTNET, - name: "b3-sepolia", - title: "B3 Sepolia", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.B3_SEPOLIA}.webp`, - testnet: true, - blockExplorer: { - name: "B3 Sepolia Explorer", - rootUrl: "https://sepolia.explorer.b3.fun/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + assertArgument(bv >= BN_35$1, "invalid EIP-155 v", "v", v3); + return (bv - BN_35$1) / BN_2$3; + } + /** + * Compute the ``v`` for a chain ID for a legacy EIP-155 transactions. + * + * Legacy transactions which use [[link-eip-155]] hijack the ``v`` + * property to include the chain ID. + * + * @example: + * Signature.getChainIdV(5, 27) + * //_result: + * + * Signature.getChainIdV(5, 28) + * //_result: + * + */ + static getChainIdV(chainId, v3) { + return getBigInt(chainId) * BN_2$3 + BigInt(35 + v3 - 27); + } + /** + * Compute the normalized legacy transaction ``v`` from a ``yParirty``, + * a legacy transaction ``v`` or a legacy [[link-eip-155]] transaction. + * + * @example: + * // The values 0 and 1 imply v is actually yParity + * Signature.getNormalizedV(0) + * //_result: + * + * // Legacy non-EIP-1559 transaction (i.e. 27 or 28) + * Signature.getNormalizedV(27) + * //_result: + * + * // Legacy EIP-155 transaction (i.e. >= 35) + * Signature.getNormalizedV(46) + * //_result: + * + * // Invalid values throw + * Signature.getNormalizedV(5) + * //_error: + */ + static getNormalizedV(v3) { + const bv = getBigInt(v3); + if (bv === BN_0$7 || bv === BN_27$1) { + return 27; } - }, - [ChainId.APECHAIN_TESTNET]: { - chainId: ChainId.APECHAIN_TESTNET, - type: NetworkType.TESTNET, - name: "apechain-testnet", - title: "APE Chain Testnet", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.APECHAIN_TESTNET}.webp`, - testnet: true, - blockExplorer: { - name: "APE Chain Explorer", - rootUrl: "https://curtis.explorer.caldera.xyz/" - }, - nativeToken: { - symbol: "APE", - name: "ApeCoin", - decimals: 18 + if (bv === BN_1$3 || bv === BN_28$1) { + return 28; } - }, - [ChainId.BLAST]: { - chainId: ChainId.BLAST, - type: NetworkType.MAINNET, - name: "blast", - title: "Blast", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BLAST}.webp`, - blockExplorer: { - name: "Blast Explorer", - rootUrl: "https://blastscan.io/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + assertArgument(bv >= BN_35$1, "invalid v", "v", v3); + return bv & BN_1$3 ? 27 : 28; + } + /** + * Creates a new [[Signature]]. + * + * If no %%sig%% is provided, a new [[Signature]] is created + * with default values. + * + * If %%sig%% is a string, it is parsed. + */ + static from(sig) { + function assertError(check, message) { + assertArgument(check, message, "signature", sig); } - }, - [ChainId.BLAST_SEPOLIA]: { - chainId: ChainId.BLAST_SEPOLIA, - type: NetworkType.TESTNET, - name: "blast-sepolia", - title: "Blast Sepolia", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BLAST_SEPOLIA}.webp`, - testnet: true, - blockExplorer: { - name: "Blast Sepolia Explorer", - rootUrl: "https://sepolia.blastexplorer.io/" - }, - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + if (sig == null) { + return new _Signature(_guard$3, ZeroHash, ZeroHash, 27); } - }, - [ChainId.TELOS]: { - chainId: ChainId.TELOS, - type: NetworkType.MAINNET, - name: "telos", - title: "Telos", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.TELOS}.webp`, - blockExplorer: { - name: "Telos Explorer", - rootUrl: "https://explorer.telos.net/network/" - }, - nativeToken: { - symbol: "TLOS", - name: "TLOS", - decimals: 18 + if (typeof sig === "string") { + const bytes2 = getBytes(sig, "signature"); + if (bytes2.length === 64) { + const r3 = hexlify(bytes2.slice(0, 32)); + const s3 = bytes2.slice(32, 64); + const v5 = s3[0] & 128 ? 28 : 27; + s3[0] &= 127; + return new _Signature(_guard$3, r3, hexlify(s3), v5); + } + if (bytes2.length === 65) { + const r3 = hexlify(bytes2.slice(0, 32)); + const s3 = bytes2.slice(32, 64); + assertError((s3[0] & 128) === 0, "non-canonical s"); + const v5 = _Signature.getNormalizedV(bytes2[64]); + return new _Signature(_guard$3, r3, hexlify(s3), v5); + } + assertError(false, "invalid raw signature length"); } - }, - [ChainId.BORNE_TESTNET]: { - chainId: ChainId.BORNE_TESTNET, - type: NetworkType.TESTNET, - name: "borne-testnet", - title: "Borne Testnet", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BORNE_TESTNET}.webp`, - testnet: true, - blockExplorer: { - name: "Borne Testnet Explorer", - rootUrl: "https://subnets-test.avax.network/bornegfdn" - }, - nativeToken: { - symbol: "BORNE", - name: "BORNE", - decimals: 18 + if (sig instanceof _Signature) { + return sig.clone(); } - }, - [ChainId.SKALE_NEBULA_TESTNET]: { - chainId: ChainId.SKALE_NEBULA_TESTNET, - type: NetworkType.TESTNET, - name: "skale-nebula-testnet", - title: "SKALE Nebula Gaming Hub Testnet", - logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.SKALE_NEBULA_TESTNET}.webp`, - testnet: true, - blockExplorer: { - name: "SKALE Nebula Gaming Hub Testnet Explorer", - rootUrl: "https://lanky-ill-funny-testnet.explorer.testnet.skalenodes.com/" - }, - nativeToken: { - symbol: "sFUEL", - name: "SKALE Fuel", - decimals: 18 + const _r2 = sig.r; + assertError(_r2 != null, "missing r"); + const r2 = toUint256(_r2); + const s2 = function(s3, yParityAndS) { + if (s3 != null) { + return toUint256(s3); + } + if (yParityAndS != null) { + assertError(isHexString(yParityAndS, 32), "invalid yParityAndS"); + const bytes2 = getBytes(yParityAndS); + bytes2[0] &= 127; + return hexlify(bytes2); + } + assertError(false, "missing s"); + }(sig.s, sig.yParityAndS); + assertError((getBytes(s2)[0] & 128) == 0, "non-canonical s"); + const { networkV, v: v3 } = function(_v2, yParityAndS, yParity) { + if (_v2 != null) { + const v5 = getBigInt(_v2); + return { + networkV: v5 >= BN_35$1 ? v5 : void 0, + v: _Signature.getNormalizedV(v5) + }; + } + if (yParityAndS != null) { + assertError(isHexString(yParityAndS, 32), "invalid yParityAndS"); + return { v: getBytes(yParityAndS)[0] & 128 ? 28 : 27 }; + } + if (yParity != null) { + switch (getNumber(yParity, "sig.yParity")) { + case 0: + return { v: 27 }; + case 1: + return { v: 28 }; + } + assertError(false, "invalid yParity"); + } + assertError(false, "missing v"); + }(sig.v, sig.yParityAndS, sig.yParity); + const result = new _Signature(_guard$3, r2, s2, v3); + if (networkV) { + __privateSet(result, _networkV, networkV); } - }, - [ChainId.HARDHAT]: { - chainId: ChainId.HARDHAT, - name: "hardhat", - title: "Hardhat (local testnet)", - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + assertError(sig.yParity == null || getNumber(sig.yParity, "sig.yParity") === result.yParity, "yParity mismatch"); + assertError(sig.yParityAndS == null || sig.yParityAndS === result.yParityAndS, "yParityAndS mismatch"); + return result; + } +}; +_r = new WeakMap(); +_s = new WeakMap(); +_v = new WeakMap(); +_networkV = new WeakMap(); +let Signature = _Signature; +const _SigningKey = class _SigningKey { + /** + * Creates a new **SigningKey** for %%privateKey%%. + */ + constructor(privateKey) { + __privateAdd(this, _privateKey); + assertArgument(dataLength(privateKey) === 32, "invalid private key", "privateKey", "[REDACTED]"); + __privateSet(this, _privateKey, hexlify(privateKey)); + } + /** + * The private key. + */ + get privateKey() { + return __privateGet(this, _privateKey); + } + /** + * The uncompressed public key. + * + * This will always begin with the prefix ``0x04`` and be 132 + * characters long (the ``0x`` prefix and 130 hexadecimal nibbles). + */ + get publicKey() { + return _SigningKey.computePublicKey(__privateGet(this, _privateKey)); + } + /** + * The compressed public key. + * + * This will always begin with either the prefix ``0x02`` or ``0x03`` + * and be 68 characters long (the ``0x`` prefix and 33 hexadecimal + * nibbles) + */ + get compressedPublicKey() { + return _SigningKey.computePublicKey(__privateGet(this, _privateKey), true); + } + /** + * Return the signature of the signed %%digest%%. + */ + sign(digest) { + assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest); + const sig = secp256k1.sign(getBytesCopy(digest), getBytesCopy(__privateGet(this, _privateKey)), { + lowS: true + }); + return Signature.from({ + r: toBeHex(sig.r, 32), + s: toBeHex(sig.s, 32), + v: sig.recovery ? 28 : 27 + }); + } + /** + * Returns the [[link-wiki-ecdh]] shared secret between this + * private key and the %%other%% key. + * + * The %%other%% key may be any type of key, a raw public key, + * a compressed/uncompressed pubic key or aprivate key. + * + * Best practice is usually to use a cryptographic hash on the + * returned value before using it as a symetric secret. + * + * @example: + * sign1 = new SigningKey(id("some-secret-1")) + * sign2 = new SigningKey(id("some-secret-2")) + * + * // Notice that privA.computeSharedSecret(pubB)... + * sign1.computeSharedSecret(sign2.publicKey) + * //_result: + * + * // ...is equal to privB.computeSharedSecret(pubA). + * sign2.computeSharedSecret(sign1.publicKey) + * //_result: + */ + computeSharedSecret(other) { + const pubKey = _SigningKey.computePublicKey(other); + return hexlify(secp256k1.getSharedSecret(getBytesCopy(__privateGet(this, _privateKey)), getBytes(pubKey), false)); + } + /** + * Compute the public key for %%key%%, optionally %%compressed%%. + * + * The %%key%% may be any type of key, a raw public key, a + * compressed/uncompressed public key or private key. + * + * @example: + * sign = new SigningKey(id("some-secret")); + * + * // Compute the uncompressed public key for a private key + * SigningKey.computePublicKey(sign.privateKey) + * //_result: + * + * // Compute the compressed public key for a private key + * SigningKey.computePublicKey(sign.privateKey, true) + * //_result: + * + * // Compute the uncompressed public key + * SigningKey.computePublicKey(sign.publicKey, false); + * //_result: + * + * // Compute the Compressed a public key + * SigningKey.computePublicKey(sign.publicKey, true); + * //_result: + */ + static computePublicKey(key, compressed) { + let bytes2 = getBytes(key, "key"); + if (bytes2.length === 32) { + const pubKey = secp256k1.getPublicKey(bytes2, !!compressed); + return hexlify(pubKey); } - }, - [ChainId.HARDHAT_2]: { - chainId: ChainId.HARDHAT_2, - name: "hardhat2", - title: "Hardhat (local testnet)", - nativeToken: { - symbol: "ETH", - name: "Ether", - decimals: 18 + if (bytes2.length === 64) { + const pub = new Uint8Array(65); + pub[0] = 4; + pub.set(bytes2, 1); + bytes2 = pub; } + const point = secp256k1.ProjectivePoint.fromHex(bytes2); + return hexlify(point.toRawBytes(compressed)); + } + /** + * Returns the public key for the private key which produced the + * %%signature%% for the given %%digest%%. + * + * @example: + * key = new SigningKey(id("some-secret")) + * digest = id("hello world") + * sig = key.sign(digest) + * + * // Notice the signer public key... + * key.publicKey + * //_result: + * + * // ...is equal to the recovered public key + * SigningKey.recoverPublicKey(digest, sig) + * //_result: + * + */ + static recoverPublicKey(digest, signature2) { + assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest); + const sig = Signature.from(signature2); + let secpSig = secp256k1.Signature.fromCompact(getBytesCopy(concat([sig.r, sig.s]))); + secpSig = secpSig.addRecoveryBit(sig.yParity); + const pubKey = secpSig.recoverPublicKey(getBytesCopy(digest)); + assertArgument(pubKey != null, "invalid signautre for digest", "signature", signature2); + return "0x" + pubKey.toHex(false); + } + /** + * Returns the point resulting from adding the ellipic curve points + * %%p0%% and %%p1%%. + * + * This is not a common function most developers should require, but + * can be useful for certain privacy-specific techniques. + * + * For example, it is used by [[HDNodeWallet]] to compute child + * addresses from parent public keys and chain codes. + */ + static addPoints(p0, p1, compressed) { + const pub0 = secp256k1.ProjectivePoint.fromHex(_SigningKey.computePublicKey(p0).substring(2)); + const pub1 = secp256k1.ProjectivePoint.fromHex(_SigningKey.computePublicKey(p1).substring(2)); + return "0x" + pub0.add(pub1).toHex(!!compressed); } }; -function getDefaultExportFromCjs(x2) { - return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2; -} -var browser$1 = { exports: {} }; -var process = browser$1.exports = {}; -var cachedSetTimeout; -var cachedClearTimeout; -function defaultSetTimout() { - throw new Error("setTimeout has not been defined"); -} -function defaultClearTimeout() { - throw new Error("clearTimeout has not been defined"); +_privateKey = new WeakMap(); +let SigningKey = _SigningKey; +function lock() { + computeHmac.lock(); + keccak256.lock(); + pbkdf2.lock(); + randomBytes.lock(); + ripemd160.lock(); + scrypt.lock(); + scryptSync.lock(); + sha256$1.lock(); + sha512.lock(); + randomBytes.lock(); } -(function() { - try { - if (typeof setTimeout === "function") { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e2) { - cachedSetTimeout = defaultSetTimout; +const BN_0$6 = BigInt(0); +const BN_36 = BigInt(36); +function getChecksumAddress(address) { + address = address.toLowerCase(); + const chars = address.substring(2).split(""); + const expanded = new Uint8Array(40); + for (let i = 0; i < 40; i++) { + expanded[i] = chars[i].charCodeAt(0); } - try { - if (typeof clearTimeout === "function") { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; + const hashed = getBytes(keccak256(expanded)); + for (let i = 0; i < 40; i += 2) { + if (hashed[i >> 1] >> 4 >= 8) { + chars[i] = chars[i].toUpperCase(); + } + if ((hashed[i >> 1] & 15) >= 8) { + chars[i + 1] = chars[i + 1].toUpperCase(); } - } catch (e2) { - cachedClearTimeout = defaultClearTimeout; - } -})(); -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - return setTimeout(fun, 0); } - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); + return "0x" + chars.join(""); +} +const ibanLookup = {}; +for (let i = 0; i < 10; i++) { + ibanLookup[String(i)] = String(i); +} +for (let i = 0; i < 26; i++) { + ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); +} +const safeDigits = 15; +function ibanChecksum(address) { + address = address.toUpperCase(); + address = address.substring(4) + address.substring(0, 2) + "00"; + let expanded = address.split("").map((c2) => { + return ibanLookup[c2]; + }).join(""); + while (expanded.length >= safeDigits) { + let block = expanded.substring(0, safeDigits); + expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); } - try { - return cachedSetTimeout(fun, 0); - } catch (e2) { - try { - return cachedSetTimeout.call(null, fun, 0); - } catch (e22) { - return cachedSetTimeout.call(this, fun, 0); - } + let checksum2 = String(98 - parseInt(expanded, 10) % 97); + while (checksum2.length < 2) { + checksum2 = "0" + checksum2; } + return checksum2; } -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - return clearTimeout(marker); +const Base36 = function() { + const result = {}; + for (let i = 0; i < 36; i++) { + const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i]; + result[key] = BigInt(i); } - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); + return result; +}(); +function fromBase36(value) { + value = value.toLowerCase(); + let result = BN_0$6; + for (let i = 0; i < value.length; i++) { + result = result * BN_36 + Base36[value[i]]; } - try { - return cachedClearTimeout(marker); - } catch (e2) { - try { - return cachedClearTimeout.call(null, marker); - } catch (e22) { - return cachedClearTimeout.call(this, marker); + return result; +} +function getAddress(address) { + assertArgument(typeof address === "string", "invalid address", "address", address); + if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { + if (!address.startsWith("0x")) { + address = "0x" + address; + } + const result = getChecksumAddress(address); + assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, "bad address checksum", "address", address); + return result; + } + if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + assertArgument(address.substring(2, 4) === ibanChecksum(address), "bad icap checksum", "address", address); + let result = fromBase36(address.substring(4)).toString(16); + while (result.length < 40) { + result = "0" + result; } + return getChecksumAddress("0x" + result); } + assertArgument(false, "invalid address", "address", address); } -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; +function getIcapAddress(address) { + let base36 = BigInt(getAddress(address)).toString(36).toUpperCase(); + while (base36.length < 30) { + base36 = "0" + base36; } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); + return "XE" + ibanChecksum("XE00" + base36) + base36; +} +function getCreateAddress(tx) { + const from = getAddress(tx.from); + const nonce = getBigInt(tx.nonce, "tx.nonce"); + let nonceHex = nonce.toString(16); + if (nonceHex === "0") { + nonceHex = "0x"; + } else if (nonceHex.length % 2) { + nonceHex = "0x0" + nonceHex; } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); + nonceHex = "0x" + nonceHex; } + return getAddress(dataSlice(keccak256(encodeRlp([from, nonceHex])), 12)); } -function drainQueue() { - if (draining) { - return; +function getCreate2Address(_from, _salt, _initCodeHash) { + const from = getAddress(_from); + const salt = getBytes(_salt, "salt"); + const initCodeHash = getBytes(_initCodeHash, "initCodeHash"); + assertArgument(salt.length === 32, "salt must be 32 bytes", "salt", _salt); + assertArgument(initCodeHash.length === 32, "initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash); + return getAddress(dataSlice(keccak256(concat(["0xff", from, salt, initCodeHash])), 12)); +} +function isAddressable(value) { + return value && typeof value.getAddress === "function"; +} +function isAddress(value) { + try { + getAddress(value); + return true; + } catch (error) { } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while (len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; + return false; +} +async function checkAddress(target, promise) { + const result = await promise; + if (result == null || result === "0x0000000000000000000000000000000000000000") { + assert(typeof target !== "string", "unconfigured name", "UNCONFIGURED_NAME", { value: target }); + assertArgument(false, "invalid AddressLike value; did not resolve to a value address", "target", target); } - currentQueue = null; - draining = false; - runClearTimeout(timeout); + return getAddress(result); } -process.nextTick = function(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; +function resolveAddress(target, resolver) { + if (typeof target === "string") { + if (target.match(/^0x[0-9a-f]{40}$/i)) { + return getAddress(target); } + assert(resolver != null, "ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { operation: "resolveName" }); + return checkAddress(target, resolver.resolveName(target)); + } else if (isAddressable(target)) { + return checkAddress(target, target.getAddress()); + } else if (target && typeof target.then === "function") { + return checkAddress(target, target); } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); + assertArgument(false, "unsupported addressable value", "target", target); +} +const _gaurd = {}; +function n$1(value, width) { + let signed2 = false; + if (width < 0) { + signed2 = true; + width *= -1; } -}; -function Item(fun, array) { - this.fun = fun; - this.array = array; + return new Typed(_gaurd, `${signed2 ? "" : "u"}int${width}`, value, { signed: signed2, width }); } -Item.prototype.run = function() { - this.fun.apply(null, this.array); -}; -process.title = "browser"; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ""; -process.versions = {}; -function noop$2() { +function b$1(value, size2) { + return new Typed(_gaurd, `bytes${size2 ? size2 : ""}`, value, { size: size2 }); } -process.on = noop$2; -process.addListener = noop$2; -process.once = noop$2; -process.off = noop$2; -process.removeListener = noop$2; -process.removeAllListeners = noop$2; -process.emit = noop$2; -process.prependListener = noop$2; -process.prependOnceListener = noop$2; -process.listeners = function(name2) { - return []; -}; -process.binding = function(name2) { - throw new Error("process.binding is not supported"); -}; -process.cwd = function() { - return "/"; -}; -process.chdir = function(dir) { - throw new Error("process.chdir is not supported"); -}; -process.umask = function() { - return 0; -}; -var browserExports = browser$1.exports; -const process$1 = /* @__PURE__ */ getDefaultExportFromCjs(browserExports); -const extractProjectIdFromAccessKey = (accessKey) => { - const base64String = accessKey.replace(/-/g, "+").replace(/_/g, "/"); - const binaryString = atob(base64String); - const byteArray = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - byteArray[i] = binaryString.charCodeAt(i); +const _typedSymbol = Symbol.for("_ethers_typed"); +const _Typed = class _Typed { + /** + * @_ignore: + */ + constructor(gaurd, type, value, options) { + /** + * The type, as a Solidity-compatible type. + */ + __publicField(this, "type"); + /** + * The actual value. + */ + __publicField(this, "value"); + __privateAdd(this, _options); + /** + * @_ignore: + */ + __publicField(this, "_typedSymbol"); + if (options == null) { + options = null; + } + assertPrivate(_gaurd, gaurd, "Typed"); + defineProperties$1(this, { _typedSymbol, type, value }); + __privateSet(this, _options, options); + this.format(); + } + /** + * Format the type as a Human-Readable type. + */ + format() { + if (this.type === "array") { + throw new Error(""); + } else if (this.type === "dynamicArray") { + throw new Error(""); + } else if (this.type === "tuple") { + return `tuple(${this.value.map((v3) => v3.format()).join(",")})`; + } + return this.type; + } + /** + * The default value returned by this type. + */ + defaultValue() { + return 0; + } + /** + * The minimum value for numeric types. + */ + minValue() { + return 0; + } + /** + * The maximum value for numeric types. + */ + maxValue() { + return 0; + } + /** + * Returns ``true`` and provides a type guard is this is a [[TypedBigInt]]. + */ + isBigInt() { + return !!this.type.match(/^u?int[0-9]+$/); } - if (byteArray[0] !== 1) { - throw new Error("UnsupportedVersion"); + /** + * Returns ``true`` and provides a type guard is this is a [[TypedData]]. + */ + isData() { + return this.type.startsWith("bytes"); } - const projectIdBytes = byteArray.slice(1, 9); - const projectId = projectIdBytes[7] | projectIdBytes[6] << 8 | projectIdBytes[5] << 16 | projectIdBytes[4] << 24 | projectIdBytes[3] << 32 | projectIdBytes[2] << 40 | projectIdBytes[1] << 48 | projectIdBytes[0] << 56; - return projectId; -}; -const MAX_UINT_256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -const isBigNumberish = (value) => { - return value != null && (typeof value === "number" && value % 1 === 0 || typeof value === "string" && !!value.match(/^-?[0-9]+$/) || isHexString(value) || typeof value === "bigint"); -}; -const toHexString = (value) => { - const result = value.toString(16); - return `${result.length % 2 === 0 ? "0x" : "0x0"}${result}`; -}; -const parseUnits$1 = (value, decimals = 18) => { - let [integer, fraction = "0"] = value.split("."); - const negative = integer.startsWith("-"); - if (negative) { - integer = integer.slice(1); + /** + * Returns ``true`` and provides a type guard is this is a [[TypedString]]. + */ + isString() { + return this.type === "string"; } - fraction = fraction.replace(/(0+)$/, ""); - if (decimals === 0) { - integer = `${Math.round(Number(`${integer}.${fraction}`))}`; - fraction = ""; - } else if (fraction.length > decimals) { - const [left, unit, right] = [fraction.slice(0, decimals - 1), fraction.slice(decimals - 1, decimals), fraction.slice(decimals)]; - const rounded = Math.round(Number(`${unit}.${right}`)); - if (rounded > 9) { - fraction = `${BigInt(left) + 1n}0`.padStart(left.length + 1, "0"); - } else { - fraction = `${left}${rounded}`; + /** + * Returns the tuple name, if this is a tuple. Throws otherwise. + */ + get tupleName() { + if (this.type !== "tuple") { + throw TypeError("not a tuple"); } - if (fraction.length > decimals) { - fraction = fraction.slice(1); - integer = `${BigInt(integer) + 1n}`; + return __privateGet(this, _options); + } + // Returns the length of this type as an array + // - `null` indicates the length is unforced, it could be dynamic + // - `-1` indicates the length is dynamic + // - any other value indicates it is a static array and is its length + /** + * Returns the length of the array type or ``-1`` if it is dynamic. + * + * Throws if the type is not an array. + */ + get arrayLength() { + if (this.type !== "array") { + throw TypeError("not an array"); } - fraction = fraction.slice(0, decimals); - } else { - fraction = fraction.padEnd(decimals, "0"); + if (__privateGet(this, _options) === true) { + return -1; + } + if (__privateGet(this, _options) === false) { + return this.value.length; + } + return null; } - return BigInt(`${negative ? "-" : ""}${integer}${fraction}`); -}; -const parseEther = (value) => parseUnits$1(value, 18); -const formatUnits$1 = (value, decimals = 18) => { - let display = value.toString(); - const negative = display.startsWith("-"); - if (negative) { - display = display.slice(1); + /** + * Returns a new **Typed** of %%type%% with the %%value%%. + */ + static from(type, value) { + return new _Typed(_gaurd, type, value); } - display = display.padStart(decimals, "0"); - const integer = display.slice(0, display.length - decimals); - let fraction = display.slice(display.length - decimals); - fraction = fraction.replace(/(0+)$/, ""); - return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`; -}; -const formatEther$1 = (value) => formatUnits$1(value, 18); -const bigintReplacer = (key, value) => { - if (typeof value === "bigint") { - return { - $bigint: value.toString() - }; + /** + * Return a new ``uint8`` type for %%v%%. + */ + static uint8(v3) { + return n$1(v3, 8); } - return value; -}; -const bigintReviver = (key, value) => { - if (value !== null && typeof value === "object" && "$bigint" in value && typeof value.$bigint === "string") { - return BigInt(value.$bigint); + /** + * Return a new ``uint16`` type for %%v%%. + */ + static uint16(v3) { + return n$1(v3, 16); } - if (value !== null && typeof value === "object" && value.type === "BigNumber" && isHexString(value.hex)) { - return BigInt(value.hex); + /** + * Return a new ``uint24`` type for %%v%%. + */ + static uint24(v3) { + return n$1(v3, 24); } - return value; -}; -const base64Encode = (val) => { - return gBase64.encode(val, true); -}; -const base64EncodeObject = (obj) => { - return gBase64.encode(JSON.stringify(obj, bigintReplacer), true); -}; -const base64Decode = (encodedString) => { - if (encodedString === null || encodedString === void 0) { - return void 0; + /** + * Return a new ``uint32`` type for %%v%%. + */ + static uint32(v3) { + return n$1(v3, 32); } - return gBase64.decode(encodedString); -}; -const base64DecodeObject = (encodedObject) => { - if (encodedObject === null || encodedObject === void 0) { - return void 0; + /** + * Return a new ``uint40`` type for %%v%%. + */ + static uint40(v3) { + return n$1(v3, 40); } - return JSON.parse(gBase64.decode(encodedObject), bigintReviver); -}; -const encodeMessageDigest = (message) => { - if (typeof message === "string") { - return getBytes(id$1(message)); - } else { - return getBytes(keccak256$1(message)); + /** + * Return a new ``uint48`` type for %%v%%. + */ + static uint48(v3) { + return n$1(v3, 48); } -}; -const packMessageData = (walletAddress, chainId, digest) => { - return solidityPacked(["string", "uint256", "address", "bytes32"], ["", chainId, walletAddress, digest]); -}; -const subDigestOf = (address, chainId, digest) => { - return keccak256$1(packMessageData(address, chainId, digest)); -}; -const isNode$2 = () => { - if (typeof window === "undefined" && typeof process$1 === "object") { - return true; - } else { - return false; + /** + * Return a new ``uint56`` type for %%v%%. + */ + static uint56(v3) { + return n$1(v3, 56); } -}; -const isBrowser$1 = () => !isNode$2(); -const jwtDecodeClaims = (jwt) => { - const parts = jwt.split("."); - if (parts.length !== 3) { - throw new Error("invalid jwt"); + /** + * Return a new ``uint64`` type for %%v%%. + */ + static uint64(v3) { + return n$1(v3, 64); } - const claims = JSON.parse(gBase64.decode(parts[1])); - return claims; -}; -function _extends$e() { - _extends$e = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends$e.apply(this, arguments); -} -var logLevel = /* @__PURE__ */ function(logLevel2) { - logLevel2[logLevel2["DEBUG"] = 1] = "DEBUG"; - logLevel2[logLevel2["INFO"] = 2] = "INFO"; - logLevel2[logLevel2["WARN"] = 3] = "WARN"; - logLevel2[logLevel2["ERROR"] = 4] = "ERROR"; - logLevel2[logLevel2["DISABLED"] = 5] = "DISABLED"; - return logLevel2; -}(logLevel || {}); -class Logger { - constructor(config2) { - this.config = config2; - this.logLevel = void 0; - this.configure(config2); + /** + * Return a new ``uint72`` type for %%v%%. + */ + static uint72(v3) { + return n$1(v3, 72); } - configure(config2) { - this.config = _extends$e({}, this.config, config2); - switch (this.config.logLevel) { - case "DEBUG": - this.logLevel = logLevel.DEBUG; - break; - case "INFO": - this.logLevel = logLevel.INFO; - break; - case "WARN": - this.logLevel = logLevel.WARN; - break; - case "ERROR": - this.logLevel = logLevel.ERROR; - break; - case "DISABLED": - this.logLevel = logLevel.DISABLED; - break; - default: - this.logLevel = logLevel.INFO; - break; - } - if (this.config.silence === void 0) { - this.config.silence = false; - } + /** + * Return a new ``uint80`` type for %%v%%. + */ + static uint80(v3) { + return n$1(v3, 80); } - debug(message, ...optionalParams) { - if (this.config.silence === true) return; - if (this.logLevel === logLevel.DEBUG) { - console.log(message, ...optionalParams); - } + /** + * Return a new ``uint88`` type for %%v%%. + */ + static uint88(v3) { + return n$1(v3, 88); } - info(message, ...optionalParams) { - if (this.config.silence === true) return; - if (this.logLevel <= logLevel.INFO) { - console.log(message, ...optionalParams); - } + /** + * Return a new ``uint96`` type for %%v%%. + */ + static uint96(v3) { + return n$1(v3, 96); } - warn(message, ...optionalParams) { - if (this.config.silence === true) return; - if (this.logLevel <= logLevel.WARN) { - console.warn(message, ...optionalParams); - if (this.config.onwarn) { - this.config.onwarn(message, optionalParams); - } - } + /** + * Return a new ``uint104`` type for %%v%%. + */ + static uint104(v3) { + return n$1(v3, 104); } - error(message, ...optionalParams) { - if (this.config.silence === true) return; - if (this.logLevel <= logLevel.ERROR) { - console.error(message, ...optionalParams); - if (this.config.onerror) { - this.config.onerror(message, optionalParams); - } - } + /** + * Return a new ``uint112`` type for %%v%%. + */ + static uint112(v3) { + return n$1(v3, 112); } -} -const logger = new Logger({ - logLevel: "INFO", - // By default we silence the logger. In tests we should call `configureLogger` - // below to set silence: false. - silence: true -}); -const configureLogger = (config2) => logger.configure(config2); -class Base { - static bufferIndexOf(array, element, isSorted = false) { - if (isSorted) { - return Base.binarySearch(array, element, Base.compare); - } - const eqChecker = (buffer1, buffer2) => { - if (buffer1 === buffer2) { - return true; - } - if (buffer1.length !== buffer2.length) { - return false; - } - for (let i = 0; i < buffer1.length; i++) { - if (buffer1[i] !== buffer2[i]) { - return false; - } - } - return true; - }; - return Base.linearSearch(array, element, eqChecker); + /** + * Return a new ``uint120`` type for %%v%%. + */ + static uint120(v3) { + return n$1(v3, 120); } - static binarySearch(array, element, compareFunction) { - let start = 0; - let end = array.length - 1; - while (start <= end) { - const mid = Math.floor((start + end) / 2); - const ordering = compareFunction(array[mid], element); - if (ordering === 0) { - for (let i = mid - 1; i >= 0; i--) { - if (compareFunction(array[i], element) === 0) continue; - return i + 1; - } - return 0; - } else if (ordering < 0) { - start = mid + 1; - } else { - end = mid - 1; - } - } - return -1; + /** + * Return a new ``uint128`` type for %%v%%. + */ + static uint128(v3) { + return n$1(v3, 128); } - static compare(a2, b2) { - const len = Math.min(a2.length, b2.length); - for (let i = 0; i < len; i++) { - if (a2[i] !== b2[i]) { - return a2[i] - b2[i]; - } - } - return a2.length - b2.length; + /** + * Return a new ``uint136`` type for %%v%%. + */ + static uint136(v3) { + return n$1(v3, 136); } - static linearSearch(array, element, eqChecker) { - for (let i = 0; i < array.length; i++) { - if (eqChecker(array[i], element)) { - return i; - } - } - return -1; + /** + * Return a new ``uint144`` type for %%v%%. + */ + static uint144(v3) { + return n$1(v3, 144); } - static bufferify(value) { - if (typeof value === "string") { - return getBytes(value); - } - return value; + /** + * Return a new ``uint152`` type for %%v%%. + */ + static uint152(v3) { + return n$1(v3, 152); } - static isHexString(v3) { - return typeof v3 === "string" && /^(0x)?[0-9A-Fa-f]*$/.test(v3); + /** + * Return a new ``uint160`` type for %%v%%. + */ + static uint160(v3) { + return n$1(v3, 160); } - static bufferToHex(value, withPrefix = true) { - const prefixed = hexlify(value); - return withPrefix ? prefixed : prefixed.substring(2); + /** + * Return a new ``uint168`` type for %%v%%. + */ + static uint168(v3) { + return n$1(v3, 168); } - static bufferifyFn(f2) { - return (value) => { - return Base.bufferify(f2(value)); - }; + /** + * Return a new ``uint176`` type for %%v%%. + */ + static uint176(v3) { + return n$1(v3, 176); } -} -class MerkleTree extends Base { - constructor(leaves, options = {}) { - super(); - this.hashFn = void 0; - this.leaves = []; - this.layers = []; - this.sortLeaves = false; - this.sortPairs = false; - this.sortLeaves = !!options.sortLeaves; - this.sortPairs = !!options.sortPairs; - this.hashFn = Base.bufferifyFn(keccak256$1); - this.processLeaves(leaves); + /** + * Return a new ``uint184`` type for %%v%%. + */ + static uint184(v3) { + return n$1(v3, 184); } - getOptions() { - return { - sortLeaves: this.sortLeaves, - sortPairs: this.sortPairs - }; + /** + * Return a new ``uint192`` type for %%v%%. + */ + static uint192(v3) { + return n$1(v3, 192); } - processLeaves(leaves) { - this.leaves = leaves.map(Base.bufferify); - if (this.sortLeaves) { - this.leaves = this.leaves.sort(Base.compare); - } - this.createHashes(this.leaves); + /** + * Return a new ``uint200`` type for %%v%%. + */ + static uint200(v3) { + return n$1(v3, 200); } - createHashes(nodes) { - this.layers = [nodes]; - while (nodes.length > 1) { - const layerIndex = this.layers.length; - this.layers.push([]); - const layerLimit = nodes.length; - for (let i = 0; i < nodes.length; i += 2) { - if (i >= layerLimit) { - this.layers[layerIndex].push(...nodes.slice(layerLimit)); - break; - } else if (i + 1 === nodes.length) { - if (nodes.length % 2 === 1) { - this.layers[layerIndex].push(nodes[i]); - continue; - } - } - const left = nodes[i]; - const right = i + 1 === nodes.length ? left : nodes[i + 1]; - const combined = [left, right]; - if (this.sortPairs) { - combined.sort(Base.compare); - } - const hash2 = this.hashFn(concat$1(combined)); - this.layers[layerIndex].push(hash2); - } - nodes = this.layers[layerIndex]; - } + /** + * Return a new ``uint208`` type for %%v%%. + */ + static uint208(v3) { + return n$1(v3, 208); } - getRoot() { - if (this.layers.length === 0) { - return Uint8Array.from([]); - } - return this.layers[this.layers.length - 1][0] || Uint8Array.from([]); + /** + * Return a new ``uint216`` type for %%v%%. + */ + static uint216(v3) { + return n$1(v3, 216); } - getHexRoot() { - return Base.bufferToHex(this.getRoot()); + /** + * Return a new ``uint224`` type for %%v%%. + */ + static uint224(v3) { + return n$1(v3, 224); } - getProof(leaf, index2) { - if (typeof leaf === "undefined") { - throw new Error("leaf is required"); - } - leaf = Base.bufferify(leaf); - const proof = []; - if (!Number.isInteger(index2)) { - index2 = -1; - for (let i = 0; i < this.leaves.length; i++) { - if (Base.compare(leaf, this.leaves[i]) === 0) { - index2 = i; - } - } - } - index2 = index2; - if (index2 <= -1) { - return []; - } - for (let i = 0; i < this.layers.length; i++) { - const layer = this.layers[i]; - const isRightNode = index2 % 2; - const pairIndex = isRightNode ? index2 - 1 : index2 + 1; - if (pairIndex < layer.length) { - proof.push({ - position: isRightNode ? "left" : "right", - data: layer[pairIndex] - }); - } - index2 = index2 / 2 | 0; - } - return proof; + /** + * Return a new ``uint232`` type for %%v%%. + */ + static uint232(v3) { + return n$1(v3, 232); + } + /** + * Return a new ``uint240`` type for %%v%%. + */ + static uint240(v3) { + return n$1(v3, 240); + } + /** + * Return a new ``uint248`` type for %%v%%. + */ + static uint248(v3) { + return n$1(v3, 248); } - getHexProof(leaf, index2) { - return this.getProof(leaf, index2).map((item2) => Base.bufferToHex(item2.data)); + /** + * Return a new ``uint256`` type for %%v%%. + */ + static uint256(v3) { + return n$1(v3, 256); } - verify(proof, targetNode, root2) { - let hash2 = Base.bufferify(targetNode); - root2 = Base.bufferify(root2); - if (!Array.isArray(proof) || !targetNode || !root2) { - return false; - } - for (let i = 0; i < proof.length; i++) { - const node = proof[i]; - let data; - let isLeftNode; - if (typeof node === "string") { - data = Base.bufferify(node); - isLeftNode = true; - } else if (node instanceof Object) { - data = node.data; - isLeftNode = node.position === "left"; - } else { - throw new Error("Expected node to be of type string or object"); - } - const buffers = []; - if (this.sortPairs) { - if (Base.compare(hash2, data) < 0) { - buffers.push(hash2, data); - } else { - buffers.push(data, hash2); - } - hash2 = this.hashFn(concat$1(buffers)); - } else { - buffers.push(hash2); - buffers[isLeftNode ? "unshift" : "push"](data); - hash2 = this.hashFn(concat$1(buffers)); - } - } - return Base.compare(hash2, root2) === 0; + /** + * Return a new ``uint256`` type for %%v%%. + */ + static uint(v3) { + return n$1(v3, 256); } -} -class MerkleTreeGenerator { - constructor(elements, toLeaf) { - this.elements = void 0; - this.toLeaf = void 0; - this.tree = void 0; - this.elements = elements; - this.toLeaf = toLeaf; + /** + * Return a new ``int8`` type for %%v%%. + */ + static int8(v3) { + return n$1(v3, -8); } - generateTree() { - const hashed = this.elements.map((e2) => this.toLeaf(e2)); - return new MerkleTree(hashed, { - sortPairs: true, - sortLeaves: true - }); + /** + * Return a new ``int16`` type for %%v%%. + */ + static int16(v3) { + return n$1(v3, -16); } - generateRoot() { - if (!this.tree) this.tree = this.generateTree(); - return this.tree.getHexRoot(); + /** + * Return a new ``int24`` type for %%v%%. + */ + static int24(v3) { + return n$1(v3, -24); } - generateProof(element) { - if (!this.elements.includes(element)) throw new Error("Element not found"); - if (!this.tree) this.tree = this.generateTree(); - return this.tree.getHexProof(this.toLeaf(element)); + /** + * Return a new ``int32`` type for %%v%%. + */ + static int32(v3) { + return n$1(v3, -32); } - verifyProof(element, proof) { - if (!this.elements.includes(element)) throw new Error("Element not found"); - if (!this.tree) this.tree = this.generateTree(); - return this.tree.verify(proof, this.toLeaf(element), this.generateRoot()); + /** + * Return a new ``int40`` type for %%v%%. + */ + static int40(v3) { + return n$1(v3, -40); } -} -const getSaleItemsLeaf = (element) => solidityPackedKeccak256(["address", "uint256"], [element.address.toLowerCase(), element.tokenId]); -const getFetchRequest = (url, projectAccessKey2, jwt) => { - const req = new FetchRequest(url); - if (jwt) { - req.setHeader("Authorization", `BEARER ${jwt}`); + /** + * Return a new ``int48`` type for %%v%%. + */ + static int48(v3) { + return n$1(v3, -48); } - if (projectAccessKey2) { - req.setHeader("X-Access-Key", projectAccessKey2); + /** + * Return a new ``int56`` type for %%v%%. + */ + static int56(v3) { + return n$1(v3, -56); } - return req; -}; -let PromiseCache$1 = class PromiseCache { - constructor() { - this.cache = void 0; - this.cache = /* @__PURE__ */ new Map(); + /** + * Return a new ``int64`` type for %%v%%. + */ + static int64(v3) { + return n$1(v3, -64); } - do(key, validMilliseconds, task, ...args) { - key = `${key}:${id$1(JSON.stringify(args, deterministically$1))}`; - let entry = this.cache.get(key); - if (entry) { - if (entry.expiration) { - if (/* @__PURE__ */ new Date() >= entry.expiration) { - entry = void 0; - this.cache.delete(key); - } - } - } - if (!entry) { - const entry_ = { - promise: task(...args) - }; - if (validMilliseconds !== void 0) { - entry_.promise = entry_.promise.then((result) => { - entry_.expiration = new Date(Date.now() + validMilliseconds); - return result; - }); - } - entry = entry_; - this.cache.set(key, entry); - } - return entry.promise; + /** + * Return a new ``int72`` type for %%v%%. + */ + static int72(v3) { + return n$1(v3, -72); } -}; -function deterministically$1(_key, value) { - if (typeof value === "object" && value !== null && !Array.isArray(value)) { - return Object.fromEntries(Object.entries(value).sort()); + /** + * Return a new ``int80`` type for %%v%%. + */ + static int80(v3) { + return n$1(v3, -80); } - return value; -} -function promisify(f2, thisContext) { - return function(...a2) { - const args = Array.prototype.slice.call(a2); - return new Promise(async (resolve, reject) => { - try { - args.push((err, result) => err ? reject(err) : resolve(result)); - await f2.apply(thisContext, args); - } catch (e2) { - reject(e2); - } - }); - }; -} -function queryStringFromObject(name2, obj) { - const k2 = encodeURIComponent(name2); - const v3 = encodeURIComponent(JSON.stringify(obj)); - return `${k2}=${v3}`; -} -function queryStringToObject(qs) { - const p2 = qs.split("&"); - const o2 = {}; - for (const v3 of p2) { - const z2 = v3.split("="); - o2[decodeURIComponent(z2[0])] = JSON.parse(decodeURIComponent(z2[1])); + /** + * Return a new ``int88`` type for %%v%%. + */ + static int88(v3) { + return n$1(v3, -88); } - return o2; -} -const getRandomInt = (min2 = 0, max2 = Number.MAX_SAFE_INTEGER) => { - min2 = Math.ceil(min2); - max2 = Math.floor(max2); - return Math.floor(Math.random() * (max2 - min2 + 1)) + min2; -}; -const sanitizeNumberString = (numString) => { - if (!numString || typeof numString !== "string") { - return ""; + /** + * Return a new ``int96`` type for %%v%%. + */ + static int96(v3) { + return n$1(v3, -96); } - const v3 = numString.match(/[\d.]+/); - return v3 && v3.length > 0 ? v3[0].trim() : ""; -}; -const sanitizeAlphanumeric = (alphanum) => { - if (!alphanum || typeof alphanum !== "string") { - return ""; + /** + * Return a new ``int104`` type for %%v%%. + */ + static int104(v3) { + return n$1(v3, -104); } - const v3 = alphanum.match(/[\w\s\d]+/); - return v3 && v3.length > 0 ? v3[0].trim() : ""; -}; -const sanitizeHost = (host) => { - if (!host || typeof host !== "string") { - return ""; + /** + * Return a new ``int112`` type for %%v%%. + */ + static int112(v3) { + return n$1(v3, -112); } - const v3 = host.match(/[\w\d.\-:\/]+/); - return v3 && v3.length > 0 ? v3[0].trim() : ""; -}; -const sleep$1 = (t2) => { - return new Promise((resolve) => { - const timeout = setTimeout(() => { - clearTimeout(timeout); - resolve(); - }, t2); - }); -}; -const encodeTypedDataHash = (typedData) => { - const types2 = _extends$e({}, typedData.types); - delete types2["EIP712Domain"]; - return TypedDataEncoder.hash(typedData.domain, types2, typedData.message); -}; -const encodeTypedDataDigest = (typedData) => { - return getBytes(encodeTypedDataHash(typedData)); -}; -const { - defineProperties, - resolveProperties -} = ethers; -const urlClean = (url) => url.replace(/([^:]\/)\/+/g, "$1"); -const utils$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - Logger, - MAX_UINT_256, - MerkleTreeGenerator, - PromiseCache: PromiseCache$1, - base64Decode, - base64DecodeObject, - base64Encode, - base64EncodeObject, - bigintReplacer, - bigintReviver, - configureLogger, - defineProperties, - encodeMessageDigest, - encodeTypedDataDigest, - encodeTypedDataHash, - extractProjectIdFromAccessKey, - formatEther: formatEther$1, - formatUnits: formatUnits$1, - getFetchRequest, - getRandomInt, - getSaleItemsLeaf, - isBigNumberish, - isBrowser: isBrowser$1, - isNode: isNode$2, - jwtDecodeClaims, - logger, - packMessageData, - parseEther, - parseUnits: parseUnits$1, - promisify, - queryStringFromObject, - queryStringToObject, - resolveProperties, - sanitizeAlphanumeric, - sanitizeHost, - sanitizeNumberString, - sleep: sleep$1, - subDigestOf, - toHexString, - urlClean -}, Symbol.toStringTag, { value: "Module" })); -function _extends$d() { - _extends$d = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends$d.apply(this, arguments); -} -function isNetworkConfig(cand) { - return cand && cand.chainId !== void 0 && cand.name !== void 0 && cand.rpcUrl !== void 0 && cand.relayer !== void 0; -} -const getChainId$2 = (chainId) => { - if (typeof chainId === "number") { - return chainId; + /** + * Return a new ``int120`` type for %%v%%. + */ + static int120(v3) { + return n$1(v3, -120); } - if (chainId.chainId) { - return chainId.chainId; + /** + * Return a new ``int128`` type for %%v%%. + */ + static int128(v3) { + return n$1(v3, -128); } - return Number(chainId); -}; -const maybeChainId = (chainId) => { - if (!chainId) return void 0; - return getChainId$2(chainId); -}; -const isValidNetworkConfig = (networkConfig, raise = false, skipRelayerCheck = false) => { - if (!networkConfig) throw new Error(`invalid network config: empty config`); - const configs = []; - if (Array.isArray(networkConfig)) { - configs.push(...networkConfig); - } else { - configs.push(networkConfig); + /** + * Return a new ``int136`` type for %%v%%. + */ + static int136(v3) { + return n$1(v3, -136); } - if (configs.length === 0) { - if (raise) throw new Error(`invalid network config: empty config`); - return false; + /** + * Return a new ``int144`` type for %%v%%. + */ + static int144(v3) { + return n$1(v3, -144); } - const chainIds = configs.map((c2) => c2.chainId).sort(); - const dupes = chainIds.filter((c2, i) => chainIds.indexOf(c2) !== i); - if (dupes.length > 0) { - if (raise) throw new Error(`invalid network config: duplicate chainIds ${dupes}`); - return false; + /** + * Return a new ``int52`` type for %%v%%. + */ + static int152(v3) { + return n$1(v3, -152); } - configs.forEach((c2) => c2.name = c2.name.toLowerCase()); - const names2 = configs.map((c2) => c2.name).sort(); - const nameDupes = names2.filter((c2, i) => names2.indexOf(c2) !== i); - if (nameDupes.length > 0) { - if (raise) throw new Error(`invalid network config: duplicate network names ${nameDupes}`); - return false; + /** + * Return a new ``int160`` type for %%v%%. + */ + static int160(v3) { + return n$1(v3, -160); } - let defaultChain = false; - for (let i = 0; i < configs.length; i++) { - const c2 = configs[i]; - if ((!c2.rpcUrl || c2.rpcUrl === "") && !c2.provider) { - if (raise) throw new Error(`invalid network config for chainId ${c2.chainId}: rpcUrl or provider must be provided`); - return false; - } - if (!skipRelayerCheck) { - if (!c2.relayer) { - if (raise) throw new Error(`invalid network config for chainId ${c2.chainId}: relayer must be provided`); - return false; - } - } - if (c2.isDefaultChain) { - if (defaultChain) { - if (raise) throw new Error(`invalid network config for chainId ${c2.chainId}: DefaultChain is already set by another config`); - return false; - } - defaultChain = true; - } + /** + * Return a new ``int168`` type for %%v%%. + */ + static int168(v3) { + return n$1(v3, -168); } - if (!defaultChain) { - if (raise) throw new Error(`invalid network config: DefaultChain must be set`); - return false; + /** + * Return a new ``int176`` type for %%v%%. + */ + static int176(v3) { + return n$1(v3, -176); } - return true; -}; -const ensureValidNetworks = (networks2, skipRelayerCheck = false) => { - isValidNetworkConfig(networks2, true, skipRelayerCheck); - return networks2; -}; -const ensureUniqueNetworks = (networks2, raise = true) => { - const chainIds = networks2.map((c2) => c2.chainId).sort(); - const dupes = chainIds.filter((c2, i) => chainIds.indexOf(c2) !== i); - if (dupes.length > 0) { - if (raise) throw new Error(`invalid network config: duplicate chainIds ${dupes}`); - return false; + /** + * Return a new ``int184`` type for %%v%%. + */ + static int184(v3) { + return n$1(v3, -184); } - return true; -}; -const updateNetworkConfig = (src, dest) => { - if (!src || !dest) return; - if (!src.chainId && !src.name) { - throw new Error("failed to update network config: source config is missing chainId or name"); + /** + * Return a new ``int92`` type for %%v%%. + */ + static int192(v3) { + return n$1(v3, -192); } - if (src.chainId !== dest.chainId && src.name !== dest.name) { - throw new Error("failed to update network config: one of chainId or name must match"); + /** + * Return a new ``int200`` type for %%v%%. + */ + static int200(v3) { + return n$1(v3, -200); } - if (src.rpcUrl) { - dest.rpcUrl = src.rpcUrl; - dest.provider = void 0; + /** + * Return a new ``int208`` type for %%v%%. + */ + static int208(v3) { + return n$1(v3, -208); } - if (src.provider) { - dest.provider = src.provider; + /** + * Return a new ``int216`` type for %%v%%. + */ + static int216(v3) { + return n$1(v3, -216); } - if (src.relayer) { - dest.relayer = src.relayer; + /** + * Return a new ``int224`` type for %%v%%. + */ + static int224(v3) { + return n$1(v3, -224); } -}; -const validateAndSortNetworks = (networks2) => { - return ensureValidNetworks(sortNetworks(networks2)); -}; -const findNetworkConfig = (networks2, chainId) => { - if (typeof chainId === "string") { - if (chainId.startsWith("0x")) { - const id2 = Number(chainId); - return networks2.find((n2) => n2.chainId === id2); - } else { - return networks2.find((n2) => n2.name === chainId || `${n2.chainId}` === chainId); - } - } else if (typeof chainId === "number") { - return networks2.find((n2) => n2.chainId === chainId); - } else if (chainId.chainId) { - return networks2.find((n2) => n2.chainId === chainId.chainId); - } else if (typeof chainId === "bigint") { - const id2 = Number(chainId); - return networks2.find((n2) => n2.chainId === id2); - } else { - return void 0; + /** + * Return a new ``int232`` type for %%v%%. + */ + static int232(v3) { + return n$1(v3, -232); } -}; -const checkNetworkConfig = (network2, chainId) => { - if (!network2) return false; - if (network2.name === chainId) return true; - if (network2.chainId === chainId) return true; - return false; -}; -const networksIndex = (networks2) => { - const index2 = {}; - for (let i = 0; i < networks2.length; i++) { - index2[networks2[i].name] = networks2[i]; + /** + * Return a new ``int240`` type for %%v%%. + */ + static int240(v3) { + return n$1(v3, -240); } - return index2; -}; -const sortNetworks = (networks2) => { - if (!networks2) { - return []; + /** + * Return a new ``int248`` type for %%v%%. + */ + static int248(v3) { + return n$1(v3, -248); } - const config2 = networks2.sort((a2, b2) => { - if (a2.chainId === b2.chainId) return 0; - return a2.chainId < b2.chainId ? -1 : 1; - }); - const defaultConfigIdx = config2.findIndex((c2) => c2.isDefaultChain); - if (defaultConfigIdx > 0) config2.splice(0, 0, config2.splice(defaultConfigIdx, 1)[0]); - return config2; -}; -const stringTemplate = (sTemplate, mData) => { - if (typeof sTemplate === "string") { - mData = mData ? mData : {}; - return sTemplate.replace(/\$\{\s*([$#@\-\d\w]+)\s*\}/gim, function(fullMath, grp) { - let val = mData[grp]; - if (typeof val === "function") { - val = val(); - } else if (val === null || val === void 0) { - val = ""; - } else if (typeof val === "object" || typeof val === "symbol") { - val = val.toString(); - } else { - val = val.valueOf(); - } - return val; - }); + /** + * Return a new ``int256`` type for %%v%%. + */ + static int256(v3) { + return n$1(v3, -256); + } + /** + * Return a new ``int256`` type for %%v%%. + */ + static int(v3) { + return n$1(v3, -256); } - return ""; -}; -const indexerURL = (network2) => stringTemplate("https://${network}-indexer.sequence.app", { - network: network2 -}); -const relayerURL = (network2) => stringTemplate("https://${network}-relayer.sequence.app", { - network: network2 -}); -const nodesURL = (network2) => stringTemplate("https://nodes.sequence.app/${network}", { - network: network2 -}); -function findSupportedNetwork(chainIdOrName) { - return findNetworkConfig(allNetworks, chainIdOrName); -} -function toChainIdNumber(chainIdLike) { - if (typeof chainIdLike === "bigint") { - return chainIdLike; + /** + * Return a new ``bytes1`` type for %%v%%. + */ + static bytes1(v3) { + return b$1(v3, 1); } - if (isBigNumberish(chainIdLike)) { - return BigInt(chainIdLike); + /** + * Return a new ``bytes2`` type for %%v%%. + */ + static bytes2(v3) { + return b$1(v3, 2); } - return BigInt(chainIdLike.chainId); -} -const createNetworkConfig = (chainId, options) => { - const network2 = networks[chainId]; - if (!network2) { - throw new Error(`Network with chainId ${chainId} not found`); + /** + * Return a new ``bytes3`` type for %%v%%. + */ + static bytes3(v3) { + return b$1(v3, 3); } - const rpcUrl = nodesURL(network2.name); - return _extends$d({}, network2, { - rpcUrl, - indexerUrl: indexerURL(network2.name), - relayer: { - url: relayerURL(network2.name), - provider: { - url: rpcUrl - } - } - }, options); -}; -const hardhatNetworks = [_extends$d({}, networks[ChainId.HARDHAT], { - rpcUrl: "http://localhost:8545", - relayer: { - url: "http://localhost:3000", - provider: { - url: "http://localhost:8545" - } + /** + * Return a new ``bytes4`` type for %%v%%. + */ + static bytes4(v3) { + return b$1(v3, 4); } -}), _extends$d({}, networks[ChainId.HARDHAT_2], { - rpcUrl: "http://localhost:9545", - relayer: { - url: "http://localhost:3000", - provider: { - url: "http://localhost:9545" - } + /** + * Return a new ``bytes5`` type for %%v%%. + */ + static bytes5(v3) { + return b$1(v3, 5); } -})]; -const allNetworks = validateAndSortNetworks([_extends$d({}, createNetworkConfig(ChainId.POLYGON), { - isDefaultChain: true, - isAuthChain: true -}), createNetworkConfig(ChainId.MAINNET), createNetworkConfig(ChainId.BSC), createNetworkConfig(ChainId.AVALANCHE), createNetworkConfig(ChainId.ARBITRUM), createNetworkConfig(ChainId.ARBITRUM_NOVA), createNetworkConfig(ChainId.OPTIMISM), createNetworkConfig(ChainId.OPTIMISM_SEPOLIA), createNetworkConfig(ChainId.POLYGON_ZKEVM), createNetworkConfig(ChainId.GNOSIS), createNetworkConfig(ChainId.RINKEBY, { - disabled: true -}), createNetworkConfig(ChainId.GOERLI, { - disabled: true -}), createNetworkConfig(ChainId.SEPOLIA), createNetworkConfig(ChainId.POLYGON_MUMBAI, { - disabled: true -}), createNetworkConfig(ChainId.POLYGON_AMOY), createNetworkConfig(ChainId.BSC_TESTNET), createNetworkConfig(ChainId.ARBITRUM_SEPOLIA), createNetworkConfig(ChainId.BASE), createNetworkConfig(ChainId.BASE_SEPOLIA), createNetworkConfig(ChainId.HOMEVERSE), createNetworkConfig(ChainId.HOMEVERSE_TESTNET), createNetworkConfig(ChainId.XAI), createNetworkConfig(ChainId.XAI_SEPOLIA), createNetworkConfig(ChainId.AVALANCHE_TESTNET), createNetworkConfig(ChainId.ASTAR_ZKEVM), createNetworkConfig(ChainId.ASTAR_ZKYOTO), createNetworkConfig(ChainId.XR_SEPOLIA), createNetworkConfig(ChainId.B3_SEPOLIA), createNetworkConfig(ChainId.APECHAIN_TESTNET), createNetworkConfig(ChainId.BLAST), createNetworkConfig(ChainId.BLAST_SEPOLIA), createNetworkConfig(ChainId.TELOS), createNetworkConfig(ChainId.BORNE_TESTNET), createNetworkConfig(ChainId.SKALE_NEBULA_TESTNET), ...hardhatNetworks]); -class JsonRpcRouter { - constructor(middlewares, sender) { - this.sender = void 0; - this.handler = void 0; - this.sender = sender; - if (middlewares) { - this.setMiddleware(middlewares); - } + /** + * Return a new ``bytes6`` type for %%v%%. + */ + static bytes6(v3) { + return b$1(v3, 6); } - setMiddleware(middlewares) { - this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender); + /** + * Return a new ``bytes7`` type for %%v%%. + */ + static bytes7(v3) { + return b$1(v3, 7); } - request(request) { - return this.handler.request(request); + /** + * Return a new ``bytes8`` type for %%v%%. + */ + static bytes8(v3) { + return b$1(v3, 8); } -} -const createJsonRpcMiddlewareStack = (middlewares, handler) => { - if (middlewares.length === 0) return handler; - const toMiddleware = (v3) => { - if (v3.requestHandler) { - return v3.requestHandler; - } else { - return v3; - } - }; - let chain; - chain = toMiddleware(middlewares[middlewares.length - 1])(handler.request); - for (let i = middlewares.length - 2; i >= 0; i--) { - chain = toMiddleware(middlewares[i])(chain); + /** + * Return a new ``bytes9`` type for %%v%%. + */ + static bytes9(v3) { + return b$1(v3, 9); } - return { - request: chain - }; -}; -function isJsonRpcProvider(cand) { - return cand !== void 0 && cand.send !== void 0 && cand.constructor.defaultUrl !== void 0 && cand.detectNetwork !== void 0 && cand.getSigner !== void 0 && cand.perform !== void 0; -} -function isJsonRpcSender(cand) { - return cand !== void 0 && cand.send !== void 0; -} -class JsonRpcHandler { - constructor(provider2, defaultChainId) { - this.provider = void 0; - this.defaultChainId = void 0; - this.request = (request) => { - if (!request.chainId) { - request.chainId = this.defaultChainId; - } - return this.provider(request); - }; - if (isJsonRpcSender(provider2)) { - this.provider = (request) => { - return provider2.send(request.method, request.params, request.chainId); - }; - } else if (isJsonRpcProvider(provider2)) { - this.provider = (request) => { - return provider2.send(request.method, request.params || []); - }; - } else { - this.provider = provider2; - } - this.defaultChainId = defaultChainId; + /** + * Return a new ``bytes10`` type for %%v%%. + */ + static bytes10(v3) { + return b$1(v3, 10); } - send(method, params, chainId) { - const request = { - method, - params, - chainId - }; - return this.request(request); + /** + * Return a new ``bytes11`` type for %%v%%. + */ + static bytes11(v3) { + return b$1(v3, 11); } -} -class AllowProvider { - constructor(isAllowedFunc) { - this.requestHandler = void 0; - this.isAllowedFunc = void 0; - if (isAllowedFunc) { - this.isAllowedFunc = isAllowedFunc; - } else { - this.isAllowedFunc = (request) => true; - } - this.requestHandler = allowProviderMiddleware(this.isAllowedFunc); + /** + * Return a new ``bytes12`` type for %%v%%. + */ + static bytes12(v3) { + return b$1(v3, 12); } - setIsAllowedFunc(fn) { - this.isAllowedFunc = fn; - this.requestHandler = allowProviderMiddleware(this.isAllowedFunc); + /** + * Return a new ``bytes13`` type for %%v%%. + */ + static bytes13(v3) { + return b$1(v3, 13); } -} -const allowProviderMiddleware = (isAllowed) => (next) => { - return (request) => { - if (!isAllowed(request)) { - throw new Error("allowProvider middleware precondition is unmet."); - } - return next(request); - }; -}; -class CachedProvider { - constructor(options) { - var _this = this; - this.cachableJsonRpcMethods = ["net_version", "eth_chainId", "eth_accounts", "sequence_getWalletContext", "sequence_getNetworks"]; - this.cachableJsonRpcMethodsByBlock = ["eth_call", "eth_getCode"]; - this.cache = void 0; - this.cacheByBlock = void 0; - this.cacheByBlockResetLock = false; - this.onUpdateCallback = void 0; - this.defaultChainId = void 0; - this.requestHandler = (next) => { - return async function(request) { - if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) { - const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId); - const _result = _this.getCacheValue(key); - if (_result && _result !== "") { - return { - id: request.id, - result: _result - }; - } - } - const result = await next(request); - if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) { - if (result && _this.shouldCacheResponse(request, result)) { - const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId); - if (_this.cachableJsonRpcMethods.includes(request.method)) { - _this.setCacheValue(key, result); - } else { - _this.setCacheByBlockValue(key, result); - } - } - } - return result; - }; - }; - this.cacheKey = (method, params, chainId) => { - let key = ""; - if (chainId) { - key = `${chainId}:${method}:`; - } else { - key = `:${method}:`; - } - if (!params || params.length === 0) { - return key + "[]"; - } - return key + JSON.stringify(params); - }; - this.getCache = () => this.cache; - this.setCache = (cache2) => { - this.cache = cache2; - if (this.onUpdateCallback) { - this.onUpdateCallback(); - } - }; - this.getCacheValue = (key) => { - if (this.cache[key]) { - return this.cache[key]; - } - if (this.cacheByBlock[key]) { - return this.cacheByBlock[key]; - } - return void 0; - }; - this.setCacheValue = (key, value) => { - this.cache[key] = value; - if (this.onUpdateCallback) { - this.onUpdateCallback(key, value); - } - }; - this.setCacheByBlockValue = (key, value) => { - this.cacheByBlock[key] = value; - if (!this.cacheByBlockResetLock) { - this.cacheByBlockResetLock = true; - setTimeout(() => { - this.cacheByBlockResetLock = false; - this.cacheByBlock = {}; - }, 1500); - } - }; - this.shouldCacheResponse = (request, result) => { - if (!result) { - return false; - } - if (request.method === "eth_getCode" && result.length <= 2) { - return false; - } - return true; - }; - this.clearCache = () => { - this.cache = {}; - this.cacheByBlock = {}; - }; - this.cache = {}; - this.cacheByBlock = {}; - this.defaultChainId = options == null ? void 0 : options.defaultChainId; - if (!(options != null && options.blockCache)) { - this.cachableJsonRpcMethodsByBlock = []; - } else if ((options == null ? void 0 : options.blockCache) !== true) { - this.cachableJsonRpcMethodsByBlock = options == null ? void 0 : options.blockCache; - } + /** + * Return a new ``bytes14`` type for %%v%%. + */ + static bytes14(v3) { + return b$1(v3, 14); } - onUpdate(callback) { - this.onUpdateCallback = callback; + /** + * Return a new ``bytes15`` type for %%v%%. + */ + static bytes15(v3) { + return b$1(v3, 15); } -} -class EagerProvider { - constructor(options) { - var _this = this; - this.options = void 0; - this.requestHandler = (next) => { - return async function(request) { - switch (request.method) { - case "net_version": - if (_this.options.chainId) { - return `${_this.options.chainId}`; - } - break; - case "eth_chainId": - if (_this.options.chainId) { - return toQuantity(_this.options.chainId); - } - break; - case "eth_accounts": - if (_this.options.accountAddress) { - return [getAddress$1(_this.options.accountAddress)]; - } - break; - case "sequence_getWalletContext": - if (_this.options.walletContext) { - return _this.options.walletContext; - } - break; - } - return next(request); - }; - }; - this.options = options; + /** + * Return a new ``bytes16`` type for %%v%%. + */ + static bytes16(v3) { + return b$1(v3, 16); } -} -const exceptionProviderMiddleware = (next) => { - return async (request) => { - try { - return await next(request); - } catch (error) { - if (typeof error === "string") { - throw new Error(error); - } else { - throw new Error(error.message); - } - } - }; -}; -const loggingProviderMiddleware = (next) => { - return async (request) => { - const chainIdLabel = request.chainId ? ` chainId:${request.chainId}` : ""; - logger.info(`[provider request]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params); - try { - const result = await next(request); - logger.info(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `result:`, result); - return result; - } catch (error) { - logger.warn(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `error:`, error); - } - }; -}; -const networkProviderMiddleware = (getChainId2) => (next) => { - return async (request) => { - const networkChainId = getChainId2(request); - switch (request.method) { - case "net_version": { - return `${networkChainId}`; - } - case "eth_chainId": { - return toQuantity(networkChainId); - } - } - return next(request); - }; -}; -const SignerJsonRpcMethods = [ - "personal_sign", - "eth_sign", - "eth_signTypedData", - "eth_signTypedData_v4", - "eth_sendTransaction", - "eth_sendRawTransaction", - "sequence_sign", - // sequence-aware personal_sign - "sequence_signTypedData_v4", - // sequence-aware eth_signTypedData_v4 - "sequence_getWalletContext", - "sequence_getWalletConfig", - "sequence_getWalletState", - "sequence_getNetworks", - "sequence_updateConfig", - "sequence_publishConfig", - "sequence_gasRefundOptions", - "sequence_getNonce", - "sequence_relay", - "eth_decrypt", - "eth_getEncryptionPublicKey", - "wallet_addEthereumChain", - "wallet_switchEthereumChain", - "wallet_registerOnboarding", - "wallet_watchAsset", - "wallet_scanQRCode" -]; -class SigningProvider { - constructor(provider2) { - this.provider = void 0; - this.requestHandler = (next) => { - return (request) => { - if (SignerJsonRpcMethods.includes(request.method)) { - return this.provider.request(request); - } - return next(request); - }; - }; - this.provider = provider2; + /** + * Return a new ``bytes17`` type for %%v%%. + */ + static bytes17(v3) { + return b$1(v3, 17); } -} -class PublicProvider { - constructor(rpcUrl) { - this.privateJsonRpcMethods = ["net_version", "eth_chainId", "eth_accounts", ...SignerJsonRpcMethods]; - this.provider = void 0; - this.rpcUrl = void 0; - this.requestHandler = (next) => { - return (request) => { - if (this.provider && !this.privateJsonRpcMethods.includes(request.method)) { - return this.provider.send(request.method, request.params || []); - } - logger.debug("[public-provider] sending request to signer window", request.method); - return next(request); - }; - }; - if (rpcUrl) { - this.setRpcUrl(rpcUrl); - } + /** + * Return a new ``bytes18`` type for %%v%%. + */ + static bytes18(v3) { + return b$1(v3, 18); } - getRpcUrl() { - return this.rpcUrl; + /** + * Return a new ``bytes19`` type for %%v%%. + */ + static bytes19(v3) { + return b$1(v3, 19); } - setRpcUrl(rpcUrl) { - if (!rpcUrl || rpcUrl === "") { - this.rpcUrl = void 0; - this.provider = void 0; - } else { - this.rpcUrl = rpcUrl; - this.provider = new JsonRpcProvider$1(rpcUrl); - } + /** + * Return a new ``bytes20`` type for %%v%%. + */ + static bytes20(v3) { + return b$1(v3, 20); + } + /** + * Return a new ``bytes21`` type for %%v%%. + */ + static bytes21(v3) { + return b$1(v3, 21); + } + /** + * Return a new ``bytes22`` type for %%v%%. + */ + static bytes22(v3) { + return b$1(v3, 22); + } + /** + * Return a new ``bytes23`` type for %%v%%. + */ + static bytes23(v3) { + return b$1(v3, 23); } -} -class SingleflightMiddleware { - constructor() { - var _this = this; - this.singleflightJsonRpcMethods = ["eth_chainId", "net_version", "eth_call", "eth_getCode", "eth_blockNumber", "eth_getBalance", "eth_getStorageAt", "eth_getTransactionCount", "eth_getBlockTransactionCountByHash", "eth_getBlockTransactionCountByNumber", "eth_getUncleCountByBlockHash", "eth_getUncleCountByBlockNumber", "eth_getBlockByHash", "eth_getBlockByNumber", "eth_getTransactionByHash", "eth_getTransactionByBlockHashAndIndex", "eth_getTransactionByBlockNumberAndIndex", "eth_getTransactionReceipt", "eth_getUncleByBlockHashAndIndex", "eth_getUncleByBlockNumberAndIndex", "eth_getLogs"]; - this.inflight = void 0; - this.requestHandler = (next) => { - return async function(request) { - if (!_this.singleflightJsonRpcMethods.includes(request.method)) { - return next(request); - } - const key = _this.requestKey(request.method, request.params || [], request.chainId); - if (!_this.inflight[key]) { - _this.inflight[key] = []; - } else { - return new Promise((resolve, reject) => { - _this.inflight[key].push({ - id: request.id, - callback: (error, response) => { - if (error) { - reject(error); - } else { - resolve(response); - } - } - }); - }); - } - try { - const response = await next(request); - _this.inflight[key].forEach(({ - callback - }) => callback(void 0, response)); - return response; - } catch (error) { - _this.inflight[key].forEach(({ - callback - }) => callback(error, void 0)); - throw error; - } finally { - delete _this.inflight[key]; - } - }; - }; - this.requestKey = (method, params, chainId) => { - let key = ""; - if (chainId) { - key = `${chainId}:${method}:`; - } else { - key = `:${method}:`; - } - if (!params || params.length === 0) { - return key + "[]"; - } - return key + JSON.stringify(params); - }; - this.inflight = {}; + /** + * Return a new ``bytes24`` type for %%v%%. + */ + static bytes24(v3) { + return b$1(v3, 24); } -} -function _classPrivateFieldBase(receiver, privateKey) { - if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { - throw new TypeError("attempted to use private field on non-instance"); + /** + * Return a new ``bytes25`` type for %%v%%. + */ + static bytes25(v3) { + return b$1(v3, 25); } - return receiver; -} -var id = 0; -function _classPrivateFieldKey(name2) { - return "__private_" + id++ + "_" + name2; -} -var _chainId = /* @__PURE__ */ _classPrivateFieldKey("chainId"); -var _nextId = /* @__PURE__ */ _classPrivateFieldKey("nextId"); -var _sender = /* @__PURE__ */ _classPrivateFieldKey("sender"); -class JsonRpcProvider extends JsonRpcProvider$1 { - constructor(url, options, jsonRpcApiProviderOptions) { - var _this; - super(url, options == null ? void 0 : options.chainId, jsonRpcApiProviderOptions); - _this = this; - this.url = url; - Object.defineProperty(this, _chainId, { - writable: true, - value: void 0 - }); - Object.defineProperty(this, _nextId, { - writable: true, - value: 1 - }); - Object.defineProperty(this, _sender, { - writable: true, - value: void 0 - }); - this.fetch = async function(request) { - if (_this.url === void 0) { - throw new Error("missing provider URL"); - } - const { - method, - params - } = request; - const jsonRpcRequest = { - method, - params, - id: _classPrivateFieldBase(_this, _nextId)[_nextId]++, - jsonrpc: "2.0" - }; - const fetchRequest = typeof _this.url === "string" ? new FetchRequest(_this.url) : _this.url; - fetchRequest.body = JSON.stringify(jsonRpcRequest); - try { - const res = await fetchRequest.send(); - if (res.body) { - try { - const result = JSON.parse(toUtf8String(res.body)); - return getResult(result); - } catch (err) { - throw new Error("invalid JSON response"); - } - } - return null; - } catch (err) { - throw err; - } - }; - const chainId = options == null ? void 0 : options.chainId; - const middlewares = options == null ? void 0 : options.middlewares; - const blockCache = options == null ? void 0 : options.blockCache; - _classPrivateFieldBase(this, _chainId)[_chainId] = chainId; - const router = new JsonRpcRouter(middlewares != null ? middlewares : [ - // loggingProviderMiddleware, - new EagerProvider({ - chainId - }), - new SingleflightMiddleware(), - new CachedProvider({ - defaultChainId: chainId, - blockCache - }) - ], new JsonRpcHandler(this.fetch, chainId)); - _classPrivateFieldBase(this, _sender)[_sender] = router; + /** + * Return a new ``bytes26`` type for %%v%%. + */ + static bytes26(v3) { + return b$1(v3, 26); } - async request(request) { - return _classPrivateFieldBase(this, _sender)[_sender].request(request); + /** + * Return a new ``bytes27`` type for %%v%%. + */ + static bytes27(v3) { + return b$1(v3, 27); } - async send(method, params, chainId) { - return this.request({ - method, - params, - chainId - }); + /** + * Return a new ``bytes28`` type for %%v%%. + */ + static bytes28(v3) { + return b$1(v3, 28); } - async getNetwork() { - const chainId = _classPrivateFieldBase(this, _chainId)[_chainId]; - if (chainId) { - const network2 = networks[chainId]; - const name2 = (network2 == null ? void 0 : network2.name) || ""; - const ensAddress = network2 == null ? void 0 : network2.ensAddress; - return Network.from({ - name: name2, - chainId, - ensAddress - }); - } else { - const chainIdHex = await this.send("eth_chainId", []); - _classPrivateFieldBase(this, _chainId)[_chainId] = Number(chainIdHex); - return this.getNetwork(); - } + /** + * Return a new ``bytes29`` type for %%v%%. + */ + static bytes29(v3) { + return b$1(v3, 29); } -} -function getResult(payload) { - if (payload.error) { - const error = new Error(payload.error.message); - error.code = payload.error.code; - error.data = payload.error.data; - throw error; + /** + * Return a new ``bytes30`` type for %%v%%. + */ + static bytes30(v3) { + return b$1(v3, 30); } - return payload.result; -} -const network$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - AllowProvider, - CachedProvider, - ChainId, - EagerProvider, - JsonRpcHandler, - JsonRpcProvider, - JsonRpcRouter, - NetworkType, - PublicProvider, - SigningProvider, - SingleflightMiddleware, - allNetworks, - allowProviderMiddleware, - checkNetworkConfig, - createJsonRpcMiddlewareStack, - ensureUniqueNetworks, - ensureValidNetworks, - exceptionProviderMiddleware, - findNetworkConfig, - findSupportedNetwork, - getChainId: getChainId$2, - hardhatNetworks, - indexerURL, - isJsonRpcProvider, - isJsonRpcSender, - isNetworkConfig, - isValidNetworkConfig, - loggingProviderMiddleware, - maybeChainId, - networkProviderMiddleware, - networks, - networksIndex, - nodesURL, - relayerURL, - sortNetworks, - stringTemplate, - toChainIdNumber, - updateNetworkConfig, - validateAndSortNetworks -}, Symbol.toStringTag, { value: "Module" })); -function _extends$c() { - _extends$c = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends$c.apply(this, arguments); -} -var config$2 = /* @__PURE__ */ Object.freeze({ - __proto__: null -}); -function subdigestOf(payload) { - return solidityPackedKeccak256(["bytes", "uint256", "address", "bytes32"], ["0x1901", payload.chainId, payload.address, payload.digest]); -} -function isSignedPayload(payload) { - return payload.digest !== void 0 && payload.chainId !== void 0 && payload.address !== void 0; -} -var signature$2 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - subdigestOf, - isSignedPayload -}); -const EIP1271_MAGIC_VALUE = "0x1626ba7e"; -const EIP1271_ABI = [{ - inputs: [{ - internalType: "bytes32", - type: "bytes32" - }, { - internalType: "bytes", - type: "bytes" - }], - name: "isValidSignature", - outputs: [{ - internalType: "bytes4", - type: "bytes4" - }], - stateMutability: "view", - type: "function" -}]; -async function isValidEIP1271Signature(address, digest, signature2, provider2) { - const contract = new Contract(address, EIP1271_ABI, provider2); - const result = await contract.isValidSignature(digest, signature2); - return result === EIP1271_MAGIC_VALUE; -} -var validateEIP1271 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - isValidEIP1271Signature -}); -let SigType = /* @__PURE__ */ function(SigType2) { - SigType2[SigType2["EIP712"] = 1] = "EIP712"; - SigType2[SigType2["ETH_SIGN"] = 2] = "ETH_SIGN"; - SigType2[SigType2["WALLET_BYTES32"] = 3] = "WALLET_BYTES32"; - return SigType2; -}({}); -function canRecover(signature2) { - const bytes2 = getBytes(signature2); - const type = bytes2[bytes2.length - 1]; - return type === SigType.EIP712 || type === SigType.ETH_SIGN; -} -function recoverSigner(digest, signature2) { - const bytes2 = getBytes(signature2); - const digestBytes = getBytes(digest); - const type = bytes2[bytes2.length - 1]; - const r2 = hexlify(bytes2.slice(0, 32)); - const s2 = hexlify(bytes2.slice(32, 64)); - const v3 = Number(hexlify(bytes2.slice(64, 65))); - const splitSignature = { - r: r2, - s: s2, - v: v3 - }; - if (type === SigType.EIP712) { - return recoverAddress$1(digestBytes, splitSignature); + /** + * Return a new ``bytes31`` type for %%v%%. + */ + static bytes31(v3) { + return b$1(v3, 31); } - if (type === SigType.ETH_SIGN) { - return recoverAddress$1(hashMessage$1(digestBytes), splitSignature); + /** + * Return a new ``bytes32`` type for %%v%%. + */ + static bytes32(v3) { + return b$1(v3, 32); } - throw new Error(`Unsupported signature type: ${type}`); -} -function isValidSignature$1(address, digest, signature2, provider2) { - const bytes2 = getBytes(signature2); - const type = bytes2[bytes2.length - 1]; - if (type === SigType.EIP712 || type === SigType.ETH_SIGN) { - return address === recoverSigner(digest, signature2); + /** + * Return a new ``address`` type for %%v%%. + */ + static address(v3) { + return new _Typed(_gaurd, "address", v3); } - if (type === SigType.WALLET_BYTES32) { - return isValidEIP1271Signature(address, hexlify(digest), bytes2.slice(0, -1), provider2); + /** + * Return a new ``bool`` type for %%v%%. + */ + static bool(v3) { + return new _Typed(_gaurd, "bool", !!v3); } - throw new Error(`Unsupported signature type: ${type}`); -} -function tryRecoverSigner(digest, signature2) { - const bytes2 = getBytes(signature2); - if (bytes2.length !== 66) return void 0; - try { - return recoverSigner(digest, bytes2); - } catch (_unused) { + /** + * Return a new ``bytes`` type for %%v%%. + */ + static bytes(v3) { + return new _Typed(_gaurd, "bytes", v3); } - return void 0; -} -var signer = /* @__PURE__ */ Object.freeze({ - __proto__: null, - SigType, - canRecover, - recoverSigner, - isValidSignature: isValidSignature$1, - tryRecoverSigner -}); -let SignaturePartType$1 = /* @__PURE__ */ function(SignaturePartType2) { - SignaturePartType2[SignaturePartType2["EOASignature"] = 0] = "EOASignature"; - SignaturePartType2[SignaturePartType2["Address"] = 1] = "Address"; - SignaturePartType2[SignaturePartType2["DynamicSignature"] = 2] = "DynamicSignature"; - return SignaturePartType2; -}({}); -function isAddressMember(member) { - return member.address !== void 0 && !isUnrecoveredSignatureMember(member); -} -function isUnrecoveredSignatureMember(member) { - return member.signature !== void 0 && member.weight !== void 0 && member.isDynamic !== void 0; -} -function isUnrecoveredSignature$1(signature2) { - return signature2.threshold !== void 0 && signature2.signers !== void 0; -} -function decodeSignature$1(signature2) { - const bytes2 = getBytes(signature2); - const threshold = bytes2[0] << 8 | bytes2[1]; - const signers = []; - for (let i = 2; i < bytes2.length; ) { - const type = bytes2[i++]; - const weight = bytes2[i++]; - switch (type) { - case SignaturePartType$1.EOASignature: - signers.push({ - unrecovered: true, - weight, - signature: hexlify(bytes2.slice(i, i + 66)), - isDynamic: false - }); - i += 66; - break; - case SignaturePartType$1.Address: - signers.push({ - weight, - address: getAddress$1(hexlify(bytes2.slice(i, i + 20))) - }); - i += 20; - break; - case SignaturePartType$1.DynamicSignature: - const address = getAddress$1(hexlify(bytes2.slice(i, i + 20))); - i += 20; - const size2 = bytes2[i] << 8 | bytes2[i + 1]; - i += 2; - signers.push({ - unrecovered: true, - weight, - signature: hexlify(bytes2.slice(i, i + size2)), - address, - isDynamic: true - }); - i += size2; - break; - default: - throw new Error(`Unknown signature part type: ${type}`); - } + /** + * Return a new ``string`` type for %%v%%. + */ + static string(v3) { + return new _Typed(_gaurd, "string", v3); } - return { - version: 1, - threshold, - signers - }; -} -function encodeSignature$1(signature2) { - if (isBytesLike(signature2)) { - return hexlify(signature2); + /** + * Return a new ``array`` type for %%v%%, allowing %%dynamic%% length. + */ + static array(v3, dynamic) { + throw new Error("not implemented yet"); } - const { - signers, - threshold - } = isUnrecoveredSignature$1(signature2) ? signature2 : signature2.config; - const encodedSigners = signers.map((s2) => { - if (isAddressMember(s2)) { - return solidityPacked(["uint8", "uint8", "address"], [SignaturePartType$1.Address, s2.weight, s2.address]); - } - if (s2.isDynamic) { - const bytes2 = getBytes(s2.signature); - return solidityPacked(["uint8", "uint8", "address", "uint16", "bytes"], [SignaturePartType$1.DynamicSignature, s2.weight, s2.address, bytes2.length, bytes2]); - } - return solidityPacked(["uint8", "uint8", "bytes"], [SignaturePartType$1.EOASignature, s2.weight, s2.signature]); - }); - return solidityPacked(["uint16", ...new Array(encodedSigners.length).fill("bytes")], [threshold, ...encodedSigners]); -} -async function recoverSignature$1(data, payload, provider2) { - const subdigest = subdigestOf(payload); - const signers = await Promise.all(data.signers.map(async (s2) => { - if (isAddressMember(s2)) { - return s2; - } - if (s2.isDynamic) { - if (!s2.address) throw new Error("Dynamic signature part must have address"); - if (!isValidSignature$1(s2.address, subdigest, s2.signature, provider2)) { - throw new Error(`Invalid dynamic signature part ${s2.address}`); - } - return { - address: s2.address, - weight: s2.weight, - signature: s2.signature - }; - } else { - const address = recoverSigner(subdigest, s2.signature); - return { - address, - weight: s2.weight, - signature: s2.signature - }; - } - })); - return { - version: 1, - payload, - subdigest, - config: { - version: 1, - threshold: data.threshold, - signers - } - }; -} -function encodeSigners$1(config2, signatures, subdigests, _) { - if (subdigests.length !== 0) { - throw new Error("Explicit subdigests not supported on v1"); + /** + * Return a new ``tuple`` type for %%v%%, with the optional %%name%%. + */ + static tuple(v3, name2) { + throw new Error("not implemented yet"); } - let weight = 0n; - const parts = config2.signers.map((s2) => { - if (!signatures.has(s2.address)) { - return s2; - } - const signature2 = signatures.get(s2.address); - const bytes2 = getBytes(signature2.signature); - weight += BigInt(s2.weight); - if (signature2.isDynamic || bytes2.length !== 66) { - return _extends$c({}, s2, { - isDynamic: true, - signature: signature2.signature, - address: s2.address - }); - } - return _extends$c({}, s2, { - isDynamic: false, - signature: signature2.signature - }); - }); - const encoded = encodeSignature$1({ - version: 1, - threshold: config2.threshold, - signers: parts - }); - return { - encoded, - weight - }; -} -const SignatureCoder$1 = { - decode: (data) => { - return decodeSignature$1(data); - }, - encode: (data) => { - return encodeSignature$1(data); - }, - trim: async (data) => { - return data; - }, - supportsNoChainId: true, - recover: (data, payload, provider2) => { - return recoverSignature$1(data, payload, provider2); - }, - encodeSigners: (config2, signatures, subdigests, chainId) => { - return encodeSigners$1(config2, signatures, subdigests); - }, - hasEnoughSigningPower: (config2, signatures) => { - const { - weight - } = SignatureCoder$1.encodeSigners(config2, signatures, [], 0); - return weight >= BigInt(config2.threshold); - }, - chainSignatures: (_main, _suffix) => { - throw new Error("Signature chaining not supported on v1"); - }, - hashSetImageHash: function(_imageHash) { - throw new Error("Image hash not supported on v1"); - }, - signaturesOf(config2) { - return config2.signers.filter((s2) => s2.signature !== void 0).map((s2) => ({ - address: s2.address, - signature: s2.signature - })); - }, - signaturesOfDecoded: function(data) { - return data.signers.map((s2) => s2.signature).filter((s2) => s2 !== void 0); + /** + * Return a new ``uint8`` type for %%v%%. + */ + static overrides(v3) { + return new _Typed(_gaurd, "overrides", Object.assign({}, v3)); } -}; -var signature$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - SignaturePartType: SignaturePartType$1, - isAddressMember, - isUnrecoveredSignatureMember, - isUnrecoveredSignature: isUnrecoveredSignature$1, - decodeSignature: decodeSignature$1, - encodeSignature: encodeSignature$1, - recoverSignature: recoverSignature$1, - encodeSigners: encodeSigners$1, - SignatureCoder: SignatureCoder$1 -}); -const ConfigCoder$1 = { - isWalletConfig: (config2) => { - return config2.version === 1 && config2.threshold !== void 0 && config2.signers !== void 0; - }, - imageHashOf: (config2) => { - return config2.signers.reduce((imageHash2, signer2) => keccak256$1(AbiCoder.defaultAbiCoder().encode(["bytes32", "uint8", "address"], [imageHash2, signer2.weight, signer2.address])), solidityPacked(["uint256"], [config2.threshold])); - }, - hasSubdigest: (_walletConfig, _subdigest) => { - return false; - }, - isComplete: (_config) => { - return true; - }, - checkpointOf: (_config) => { - return 0n; - }, - signersOf: (config2) => { - return config2.signers.map((s2) => ({ - address: s2.address, - weight: Number(s2.weight) - })); - }, - fromSimple: (config2) => { - if (BigInt(config2.checkpoint) !== 0n) { - throw new Error("v1 wallet config does not support checkpoint"); - } - if (config2.subdigests && config2.subdigests.length > 0) { - throw new Error("v1 wallet config does not support subdigests"); - } - return { - version: 1, - threshold: config2.threshold, - signers: config2.signers - }; - }, - update: { - isKindUsed: true, - buildTransaction: (wallet, config2, context2, kind) => { - const module2 = new Interface([...walletContracts.mainModule.abi, ...walletContracts.mainModuleUpgradable.abi]); - const transactions2 = []; - if (!kind || kind === "first") { - transactions2.push({ - to: wallet, - data: module2.encodeFunctionData(module2.getFunction("updateImplementation"), [context2.mainModuleUpgradable]), - gasLimit: 0, - delegateCall: false, - revertOnError: true, - value: 0 - }); - } - transactions2.push({ - to: wallet, - data: module2.encodeFunctionData(module2.getFunction("updateImageHash"), [ConfigCoder$1.imageHashOf(config2)]), - gasLimit: 0, - delegateCall: false, - revertOnError: true, - value: 0 - }); - return { - entrypoint: wallet, - transactions: transactions2 - }; - }, - decodeTransaction: function(tx) { - throw new Error("Function not implemented."); - } - }, - toJSON: function(config2) { - const plainMembers = config2.signers.map((signer2) => { - return { - weight: BigInt(signer2.weight).toString(), - address: signer2.address - }; - }); - return JSON.stringify({ - version: config2.version, - threshold: BigInt(config2.threshold).toString(), - signers: plainMembers - }); - }, - fromJSON: function(json) { - const parsed = JSON.parse(json); - const signers = parsed.signers.map((signer2) => { - return { - weight: BigInt(signer2.weight), - address: signer2.address - }; - }); - return { - version: parsed.version, - threshold: BigInt(parsed.threshold), - signers - }; - }, - editConfig: function(config2, action) { - var _action$threshold; - const newSigners = config2.signers.slice(); - if (action.checkpoint && BigInt(action.checkpoint) !== 0n) { - throw new Error("v1 wallet config does not support checkpoint"); - } - if (action.add) { - for (const signer2 of action.add) { - if (newSigners.find((s2) => s2.address === signer2.address)) { - continue; - } - newSigners.push({ - weight: signer2.weight, - address: signer2.address - }); - } - } - if (action.remove) { - for (const address of action.remove) { - const index2 = newSigners.findIndex((signer2) => signer2.address === address); - if (index2 >= 0) { - newSigners.splice(index2, 1); - } - } - } - return { - version: config2.version, - threshold: (_action$threshold = action.threshold) != null ? _action$threshold : config2.threshold, - signers: newSigners - }; - }, - buildStubSignature: function(config2, overrides) { - const parts = /* @__PURE__ */ new Map(); - for (const [signer2, signature2] of overrides.entries()) { - parts.set(signer2, { - signature: signature2, - isDynamic: true - }); - const { - encoded, - weight - } = encodeSigners$1(config2, parts, []); - if (weight >= BigInt(config2.threshold)) { - return encoded; - } - } - const signers = config2.signers; - for (const { - address - } of signers.sort(({ - weight: a2 - }, { - weight: b2 - }) => Number(a2) - Number(b2))) { - const signature2 = "0x4e82f02f388a12b5f9d29eaf2452dd040c0ee5804b4e504b4dd64e396c6c781f2c7624195acba242dd825bfd25a290912e3c230841fd55c9a734c4de8d9899451b02"; - parts.set(address, { - signature: signature2, - isDynamic: false - }); - const { - encoded, - weight - } = encodeSigners$1(config2, parts, []); - if (weight >= BigInt(config2.threshold)) { - return encoded; + /** + * Returns true only if %%value%% is a [[Typed]] instance. + */ + static isTyped(value) { + return value && typeof value === "object" && "_typedSymbol" in value && value._typedSymbol === _typedSymbol; + } + /** + * If the value is a [[Typed]] instance, validates the underlying value + * and returns it, otherwise returns value directly. + * + * This is useful for functions that with to accept either a [[Typed]] + * object or values. + */ + static dereference(value, type) { + if (_Typed.isTyped(value)) { + if (value.type !== type) { + throw new Error(`invalid type: expecetd ${type}, got ${value.type}`); } + return value.value; } - return encodeSigners$1(config2, parts, []).encoded; + return value; } }; -var config$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - ConfigCoder: ConfigCoder$1 -}); -var context$2 = /* @__PURE__ */ Object.freeze({ - __proto__: null -}); -const version$1$1 = 1; -const DeployedWalletContext$1 = { - version: version$1$1, - factory: "0xf9D09D634Fb818b05149329C1dcCFAeA53639d96", - guestModule: "0x02390F3E6E5FD1C6786CB78FD3027C117a9955A7", - mainModule: "0xd01F11855bCcb95f88D7A48492F66410d4637313", - mainModuleUpgradable: "0x7EFE6cE415956c5f80C6530cC6cc81b4808F6118", - walletCreationCode: "0x603a600e3d39601a805130553df3363d3d373d3d3d363d30545af43d82803e903d91601857fd5bf3" -}; -var v1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - config: config$1, - context: context$2, - signature: signature$1, - version: version$1$1, - DeployedWalletContext: DeployedWalletContext$1 -}); -const SetImageHashPrefix = "0x8713a7c4465f6fbee2b6e9d6646d1d9f83fec929edfc4baf661f3c865bdd04d1"; -function hashSetImageHash(imageHash2) { - return keccak256$1(messageSetImageHash(imageHash2)); -} -function messageSetImageHash(imageHash2) { - return solidityPacked(["bytes32", "bytes32"], [SetImageHashPrefix, imageHash2]); -} -function decodeMessageSetImageHash(message) { - const arr = getBytes(message); - if (arr.length !== 64) { - return void 0; +_options = new WeakMap(); +let Typed = _Typed; +class AddressCoder extends Coder { + constructor(localName) { + super("address", "address", localName, false); } - if (hexlify(arr.slice(0, 32)) !== SetImageHashPrefix) { - return void 0; + defaultValue() { + return "0x0000000000000000000000000000000000000000"; + } + encode(writer, _value2) { + let value = Typed.dereference(_value2, "string"); + try { + value = getAddress(value); + } catch (error) { + return this._throwError(error.message, _value2); + } + return writer.writeValue(value); + } + decode(reader2) { + return getAddress(toBeHex(reader2.readValue(), 20)); } - return hexlify(arr.slice(32, 64)); -} -function isMessageSetImageHash(message) { - return decodeMessageSetImageHash(message) !== void 0; -} -var chained = /* @__PURE__ */ Object.freeze({ - __proto__: null, - SetImageHashPrefix, - hashSetImageHash, - messageSetImageHash, - decodeMessageSetImageHash, - isMessageSetImageHash -}); -let SignatureType$1 = /* @__PURE__ */ function(SignatureType2) { - SignatureType2[SignatureType2["Legacy"] = 0] = "Legacy"; - SignatureType2[SignatureType2["Dynamic"] = 1] = "Dynamic"; - SignatureType2[SignatureType2["NoChainIdDynamic"] = 2] = "NoChainIdDynamic"; - SignatureType2[SignatureType2["Chained"] = 3] = "Chained"; - return SignatureType2; -}({}); -let SignaturePartType = /* @__PURE__ */ function(SignaturePartType2) { - SignaturePartType2[SignaturePartType2["Signature"] = 0] = "Signature"; - SignaturePartType2[SignaturePartType2["Address"] = 1] = "Address"; - SignaturePartType2[SignaturePartType2["DynamicSignature"] = 2] = "DynamicSignature"; - SignaturePartType2[SignaturePartType2["Node"] = 3] = "Node"; - SignaturePartType2[SignaturePartType2["Branch"] = 4] = "Branch"; - SignaturePartType2[SignaturePartType2["Subdigest"] = 5] = "Subdigest"; - SignaturePartType2[SignaturePartType2["Nested"] = 6] = "Nested"; - return SignaturePartType2; -}({}); -const SignaturePartTypeLength = 66; -function isUnrecoveredNode(node) { - return node.left !== void 0 && node.right !== void 0; -} -function isUnrecoveredNestedLeaf(leaf) { - return leaf.tree !== void 0; } -function isUnrecoveredSignatureLeaf(leaf) { - return leaf.unrecovered && leaf.signature !== void 0 && leaf.isDynamic !== void 0; +class AnonymousCoder extends Coder { + constructor(coder) { + super(coder.name, coder.type, "_", coder.dynamic); + __publicField(this, "coder"); + this.coder = coder; + } + defaultValue() { + return this.coder.defaultValue(); + } + encode(writer, value) { + return this.coder.encode(writer, value); + } + decode(reader2) { + return this.coder.decode(reader2); + } } -function decodeSignatureTree(body) { - let arr = getBytes(body); - let pointer; - const append = (prevPointer, node) => { - if (!prevPointer) { - return { - left: node - }; - } - if (!prevPointer.right) { - return { - left: prevPointer.left, - right: node - }; +function pack(writer, coders2, values) { + let arrayValues = []; + if (Array.isArray(values)) { + arrayValues = values; + } else if (values && typeof values === "object") { + let unique = {}; + arrayValues = coders2.map((coder) => { + const name2 = coder.localName; + assert(name2, "cannot encode object for signature with missing names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); + assert(!unique[name2], "cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); + unique[name2] = true; + return values[name2]; + }); + } else { + assertArgument(false, "invalid tuple value", "tuple", values); + } + assertArgument(coders2.length === arrayValues.length, "types/value length mismatch", "tuple", values); + let staticWriter = new Writer(); + let dynamicWriter = new Writer(); + let updateFuncs = []; + coders2.forEach((coder, index2) => { + let value = arrayValues[index2]; + if (coder.dynamic) { + let dynamicOffset = dynamicWriter.length; + coder.encode(dynamicWriter, value); + let updateFunc = staticWriter.writeUpdatableValue(); + updateFuncs.push((baseOffset) => { + updateFunc(baseOffset + dynamicOffset); + }); + } else { + coder.encode(staticWriter, value); } - return { - left: prevPointer, - right: node - }; - }; - while (arr.length > 0) { - const type = arr[0]; - arr = arr.slice(1); - switch (type) { - case SignaturePartType.Signature: - { - const weight = arr[0]; - const signature2 = hexlify(arr.slice(1, SignaturePartTypeLength + 1)); - pointer = append(pointer, { - signature: signature2, - weight, - unrecovered: true, - isDynamic: false - }); - arr = arr.slice(SignaturePartTypeLength + 1); - } - break; - case SignaturePartType.Address: - { - const weight = arr[0]; - const address = getAddress$1(hexlify(arr.slice(1, 21))); - pointer = append(pointer, { - address, - weight - }); - arr = arr.slice(21); - } - break; - case SignaturePartType.DynamicSignature: - { - const weight = arr[0]; - const address = getAddress$1(hexlify(arr.slice(1, 21))); - const size2 = arr[21] << 16 | arr[22] << 8 | arr[23]; - const signature2 = hexlify(arr.slice(24, 24 + size2)); - pointer = append(pointer, { - address, - signature: signature2, - weight, - unrecovered: true, - isDynamic: true - }); - arr = arr.slice(24 + size2); - } - break; - case SignaturePartType.Node: - { - const nodeHash = hexlify(arr.slice(0, 32)); - pointer = append(pointer, { - nodeHash - }); - arr = arr.slice(32); - } - break; - case SignaturePartType.Branch: - { - const size2 = arr[0] << 16 | arr[1] << 8 | arr[2]; - const branch = decodeSignatureTree(arr.slice(3, 3 + size2)); - pointer = append(pointer, branch); - arr = arr.slice(3 + size2); - } - break; - case SignaturePartType.Subdigest: - { - const subdigest = hexlify(arr.slice(0, 32)); - pointer = append(pointer, { - subdigest - }); - arr = arr.slice(32); - } - break; - case SignaturePartType.Nested: - { - const weight = arr[0]; - const threshold = arr[1] << 8 | arr[2]; - const size2 = arr[3] << 16 | arr[4] << 8 | arr[5]; - const tree = decodeSignatureTree(arr.slice(6, 6 + size2)); - pointer = append(pointer, { - weight, - threshold, - tree - }); - arr = arr.slice(6 + size2); + }); + updateFuncs.forEach((func) => { + func(staticWriter.length); + }); + let length = writer.appendWriter(staticWriter); + length += writer.appendWriter(dynamicWriter); + return length; +} +function unpack(reader2, coders2) { + let values = []; + let keys = []; + let baseReader = reader2.subReader(0); + coders2.forEach((coder) => { + let value = null; + if (coder.dynamic) { + let offset2 = reader2.readIndex(); + let offsetReader = baseReader.subReader(offset2); + try { + value = coder.decode(offsetReader); + } catch (error) { + if (isError(error, "BUFFER_OVERRUN")) { + throw error; } - break; - default: - throw new Error(`Unknown signature part type: ${type}: ${hexlify(arr)}`); + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } else { + try { + value = coder.decode(reader2); + } catch (error) { + if (isError(error, "BUFFER_OVERRUN")) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + if (value == void 0) { + throw new Error("investigate"); } + values.push(value); + keys.push(coder.localName || null); + }); + return Result.fromItems(values, keys); +} +class ArrayCoder extends Coder { + constructor(coder, length, localName) { + const type = coder.type + "[" + (length >= 0 ? length : "") + "]"; + const dynamic = length === -1 || coder.dynamic; + super("array", type, localName, dynamic); + __publicField(this, "coder"); + __publicField(this, "length"); + defineProperties$1(this, { coder, length }); } - if (!pointer) { - throw new Error("Empty signature tree"); + defaultValue() { + const defaultChild = this.coder.defaultValue(); + const result = []; + for (let i = 0; i < this.length; i++) { + result.push(defaultChild); + } + return result; } - if (pointer.right) { - return pointer; + encode(writer, _value2) { + const value = Typed.dereference(_value2, "array"); + if (!Array.isArray(value)) { + this._throwError("expected array value", value); + } + let count2 = this.length; + if (count2 === -1) { + count2 = value.length; + writer.writeValue(value.length); + } + assertArgumentCount(value.length, count2, "coder array" + (this.localName ? " " + this.localName : "")); + let coders2 = []; + for (let i = 0; i < value.length; i++) { + coders2.push(this.coder); + } + return pack(writer, coders2, value); } - return pointer.left; -} -class InvalidSignatureLeafError extends Error { - constructor(leaf) { - super(`Invalid signature leaf: ${JSON.stringify(leaf)}`); - this.leaf = leaf; + decode(reader2) { + let count2 = this.length; + if (count2 === -1) { + count2 = reader2.readIndex(); + assert(count2 * WordSize <= reader2.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: reader2.bytes, offset: count2 * WordSize, length: reader2.dataLength }); + } + let coders2 = []; + for (let i = 0; i < count2; i++) { + coders2.push(new AnonymousCoder(this.coder)); + } + return unpack(reader2, coders2); } } -async function recoverTopology(unrecovered, subdigest, provider2) { - if (isUnrecoveredNode(unrecovered)) { - const [left, right] = await Promise.all([recoverTopology(unrecovered.left, subdigest, provider2), recoverTopology(unrecovered.right, subdigest, provider2)]); - return { - left, - right - }; +class BooleanCoder extends Coder { + constructor(localName) { + super("bool", "bool", localName, false); } - if (isUnrecoveredNestedLeaf(unrecovered)) { - return { - weight: unrecovered.weight, - threshold: unrecovered.threshold, - tree: await recoverTopology(unrecovered.tree, subdigest, provider2) - }; + defaultValue() { + return false; } - if (isUnrecoveredSignatureLeaf(unrecovered)) { - if (unrecovered.isDynamic) { - if (!unrecovered.address) { - throw new Error("Dynamic signature leaf without address"); - } - const isValid2 = await isValidSignature$1(unrecovered.address, subdigest, unrecovered.signature, provider2); - if (!isValid2) { - throw new InvalidSignatureLeafError(unrecovered); - } - return { - weight: unrecovered.weight, - address: unrecovered.address, - signature: unrecovered.signature, - subdigest - }; - } else { - return { - weight: unrecovered.weight, - address: recoverSigner(subdigest, unrecovered.signature), - signature: unrecovered.signature, - subdigest - }; - } + encode(writer, _value2) { + const value = Typed.dereference(_value2, "bool"); + return writer.writeValue(value ? 1 : 0); + } + decode(reader2) { + return !!reader2.readValue(); } - return unrecovered; } -const partEncoder = { - concat: (a2, b2) => { - return solidityPacked(["bytes", "bytes"], [a2, b2]); - }, - node: (nodeHash) => { - return solidityPacked(["uint8", "bytes32"], [SignaturePartType.Node, nodeHash]); - }, - branch: (tree) => { - const arr = getBytes(tree); - return solidityPacked(["uint8", "uint24", "bytes"], [SignaturePartType.Branch, arr.length, arr]); - }, - nested: (weight, threshold, tree) => { - const arr = getBytes(tree); - return solidityPacked(["uint8", "uint8", "uint16", "uint24", "bytes"], [SignaturePartType.Nested, weight, threshold, arr.length, arr]); - }, - subdigest: (subdigest) => { - return solidityPacked(["uint8", "bytes32"], [SignaturePartType.Subdigest, subdigest]); - }, - signature: (weight, signature2) => { - return solidityPacked(["uint8", "uint8", "bytes"], [SignaturePartType.Signature, weight, signature2]); - }, - dynamicSignature: (weight, address, signature2) => { - const arrSignature = getBytes(signature2); - return solidityPacked(["uint8", "uint8", "address", "uint24", "bytes"], [SignaturePartType.DynamicSignature, weight, address, arrSignature.length, arrSignature]); - }, - address: (weight, address) => { - return solidityPacked(["uint8", "uint8", "address"], [SignaturePartType.Address, weight, address]); +class DynamicBytesCoder extends Coder { + constructor(type, localName) { + super(type, type, localName, true); } -}; -function encodeSigners(config2, parts, subdigests, chainId, options = {}) { - const tree = encodeTree(config2.tree, parts, subdigests, options); - if (BigInt(chainId) === 0n) { - return { - encoded: solidityPacked(["uint8", "uint16", "uint32", "bytes"], [SignatureType$1.NoChainIdDynamic, config2.threshold, config2.checkpoint, tree.encoded]), - weight: tree.weight - }; + defaultValue() { + return "0x"; } - if (BigInt(config2.threshold) > 255n) { - return { - encoded: solidityPacked(["uint8", "uint16", "uint32", "bytes"], [SignatureType$1.Dynamic, config2.threshold, config2.checkpoint, tree.encoded]), - weight: tree.weight - }; + encode(writer, value) { + value = getBytesCopy(value); + let length = writer.writeValue(value.length); + length += writer.writeBytes(value); + return length; + } + decode(reader2) { + return reader2.readBytes(reader2.readIndex(), true); } - return { - encoded: solidityPacked(["uint8", "uint8", "uint32", "bytes"], [SignatureType$1.Legacy, config2.threshold, config2.checkpoint, tree.encoded]), - weight: tree.weight - }; } -function encodeTree(topology, parts, subdigests, options = {}) { - const trim2 = !options.disableTrim; - if (isNode$1(topology)) { - const left = encodeTree(topology.left, parts, subdigests); - const right = encodeTree(topology.right, parts, subdigests); - const isLeftSigner = isSignerLeaf(topology.left); - const isRightSigner = isSignerLeaf(topology.right); - if (trim2 && left.weight === 0n && right.weight === 0n && !isLeftSigner && !isRightSigner) { - return { - // We don't need to include anything for this node - // just the hash will be enough - encoded: partEncoder.node(hashNode(topology)), - weight: 0n - }; - } - if (trim2 && right.weight === 0n && !isRightSigner) { - return { - // The right node doesn't have any weight - // but we still need to include the left node encoded - encoded: partEncoder.concat(left.encoded, partEncoder.node(hashNode(topology.right))), - weight: left.weight - }; - } - if (trim2 && left.weight === 0n && !isLeftSigner) { - return { - // The left node doesn't have any weight - // we can just append its hash, but for the right node - // we need to create a new "branch" - encoded: partEncoder.concat(partEncoder.node(hashNode(topology.left)), partEncoder.branch(right.encoded)), - weight: right.weight - }; +class BytesCoder extends DynamicBytesCoder { + constructor(localName) { + super("bytes", localName); + } + decode(reader2) { + return hexlify(super.decode(reader2)); + } +} +class FixedBytesCoder extends Coder { + constructor(size2, localName) { + let name2 = "bytes" + String(size2); + super(name2, name2, localName, false); + __publicField(this, "size"); + defineProperties$1(this, { size: size2 }, { size: "number" }); + } + defaultValue() { + return "0x0000000000000000000000000000000000000000000000000000000000000000".substring(0, 2 + this.size * 2); + } + encode(writer, _value2) { + let data = getBytesCopy(Typed.dereference(_value2, this.type)); + if (data.length !== this.size) { + this._throwError("incorrect data length", _value2); } - return { - // Both nodes have weight, we need to include both - // the right one must be a branch - encoded: partEncoder.concat(left.encoded, partEncoder.branch(right.encoded)), - weight: left.weight + right.weight - }; + return writer.writeBytes(data); } - if (isNestedLeaf(topology)) { - const tree = encodeTree(topology.tree, parts, subdigests); - if (trim2 && tree.weight === 0n) { - return { - encoded: partEncoder.node(hashNode(topology)), - weight: 0n - }; + decode(reader2) { + return hexlify(reader2.readBytes(this.size)); + } +} +const Empty = new Uint8Array([]); +class NullCoder extends Coder { + constructor(localName) { + super("null", "", localName, false); + } + defaultValue() { + return null; + } + encode(writer, value) { + if (value != null) { + this._throwError("not null", value); } - return { - encoded: partEncoder.nested(topology.weight, topology.threshold, tree.encoded), - weight: tree.weight - }; + return writer.writeBytes(Empty); } - if (isNodeLeaf(topology)) { - return { - encoded: partEncoder.node(hashNode(topology)), - weight: 0n - }; + decode(reader2) { + reader2.readBytes(0); + return null; } - if (isSubdigestLeaf(topology)) { - const include = subdigests.includes(topology.subdigest); - return { - encoded: partEncoder.subdigest(topology.subdigest), - weight: include ? MAX_UINT_256 : 0n - }; +} +const BN_0$5 = BigInt(0); +const BN_1$2 = BigInt(1); +const BN_MAX_UINT256$1 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +class NumberCoder extends Coder { + constructor(size2, signed2, localName) { + const name2 = (signed2 ? "int" : "uint") + size2 * 8; + super(name2, name2, localName, false); + __publicField(this, "size"); + __publicField(this, "signed"); + defineProperties$1(this, { size: size2, signed: signed2 }, { size: "number", signed: "boolean" }); } - if (isSignerLeaf(topology)) { - const include = parts.has(topology.address); - if (include) { - const part = parts.get(topology.address); - const signature2 = part.signature; - if (options.forceDynamicEncoding || part.isDynamic) { - return { - encoded: partEncoder.dynamicSignature(topology.weight, topology.address, signature2), - weight: BigInt(topology.weight) - }; - } else { - return { - encoded: partEncoder.signature(topology.weight, signature2), - weight: BigInt(topology.weight) - }; + defaultValue() { + return 0; + } + encode(writer, _value2) { + let value = getBigInt(Typed.dereference(_value2, this.type)); + let maxUintValue = mask(BN_MAX_UINT256$1, WordSize * 8); + if (this.signed) { + let bounds = mask(maxUintValue, this.size * 8 - 1); + if (value > bounds || value < -(bounds + BN_1$2)) { + this._throwError("value out-of-bounds", _value2); } - } else { - return { - encoded: partEncoder.address(topology.weight, topology.address), - weight: 0n - }; + value = toTwos(value, 8 * WordSize); + } else if (value < BN_0$5 || value > mask(maxUintValue, this.size * 8)) { + this._throwError("value out-of-bounds", _value2); } + return writer.writeValue(value); } - throw new Error(`Invalid topology - unknown error: ${JSON.stringify(topology)}`); -} -function deepestConfigOfSignature(signature2) { - return isChainedSignature(signature2) ? deepestConfigOfSignature(signature2.suffix[signature2.suffix.length - 1]) : signature2.config; -} -function isUnrecoveredSignature(sig) { - return sig.type !== void 0 && sig.decoded !== void 0 && sig.version !== void 0 && sig.version === 2; -} -function isUnrecoveredChainedSignature(sig) { - return sig.suffix !== void 0 && Array.isArray(sig.suffix) && sig.suffix.every(isUnrecoveredSignature); -} -function isSignature(sig) { - return sig.type !== void 0 && sig.config !== void 0 && sig.digest !== void 0 && sig.version !== void 0 && sig.version === 2; -} -function isChainedSignature(sig) { - return sig.chain !== void 0 && Array.isArray(sig.chain) && sig.chain.every(isSignature); -} -function decodeSignature(signature2) { - const bytes2 = getBytes(signature2); - const type = bytes2[0]; - switch (type) { - case SignatureType$1.Legacy: - return { - version: 2, - type: SignatureType$1.Legacy, - decoded: decodeSignatureBody(bytes2) - }; - case SignatureType$1.Dynamic: - return { - version: 2, - type: SignatureType$1.Dynamic, - decoded: decodeSignatureBody(bytes2.slice(1)) - }; - case SignatureType$1.NoChainIdDynamic: - return { - version: 2, - type: SignatureType$1.NoChainIdDynamic, - decoded: decodeSignatureBody(bytes2.slice(1)) - }; - case SignatureType$1.Chained: - return decodeChainedSignature(bytes2); - default: - throw new Error(`Invalid signature type: ${type}`); + decode(reader2) { + let value = mask(reader2.readValue(), this.size * 8); + if (this.signed) { + value = fromTwos(value, this.size * 8); + } + return value; } } -function decodeSignatureBody(signature2) { - const bytes2 = getBytes(signature2); - const threshold = bytes2[0] << 8 | bytes2[1]; - const checkpoint = bytes2[2] << 24 | bytes2[3] << 16 | bytes2[4] << 8 | bytes2[5]; - const tree = decodeSignatureTree(bytes2.slice(6)); - return { - threshold, - checkpoint, - tree - }; -} -function decodeChainedSignature(signature2) { - const arr = getBytes(signature2); - const type = arr[0]; - if (type !== SignatureType$1.Chained) { - throw new Error(`Expected chained signature type: ${type}`); +class StringCoder extends DynamicBytesCoder { + constructor(localName) { + super("string", localName); } - const chain = []; - let index2 = 1; - while (index2 < arr.length) { - const size2 = arr[index2] << 16 | arr[index2 + 1] << 8 | arr[index2 + 2]; - index2 += 3; - const sig = decodeSignature(arr.slice(index2, index2 + size2)); - chain.push(sig); - index2 += size2; + defaultValue() { + return ""; } - const main2 = chain[0]; - if (isUnrecoveredChainedSignature(main2)) { - throw new Error(`Expected first link of chained signature to be a simple signature (not chained)`); + encode(writer, _value2) { + return super.encode(writer, toUtf8Bytes(Typed.dereference(_value2, "string"))); + } + decode(reader2) { + return toUtf8String(super.decode(reader2)); } - const suffix = chain.slice(1); - return _extends$c({}, main2, { - suffix - }); -} -function setImageHashStruct(imageHash2) { - return solidityPacked(["bytes32", "bytes32"], [solidityPackedKeccak256(["string"], ["SetImageHash(bytes32 imageHash)"]), imageHash2]); } -async function recoverSignature(signature2, payload, provider2) { - const signedPayload = payload.subdigest === void 0 ? payload : void 0; - const isNoChainId = signature2.type === SignatureType$1.NoChainIdDynamic; - if (isNoChainId && signedPayload) { - signedPayload.chainId = 0; +class TupleCoder extends Coder { + constructor(coders2, localName) { + let dynamic = false; + const types2 = []; + coders2.forEach((coder) => { + if (coder.dynamic) { + dynamic = true; + } + types2.push(coder.type); + }); + const type = "tuple(" + types2.join(",") + ")"; + super("tuple", type, localName, dynamic); + __publicField(this, "coders"); + defineProperties$1(this, { coders: Object.freeze(coders2.slice()) }); } - const subdigest = signedPayload ? subdigestOf(signedPayload) : payload.subdigest; - if (!isUnrecoveredChainedSignature(signature2)) { - const tree = await recoverTopology(signature2.decoded.tree, subdigest, provider2); - return { - version: 2, - type: signature2.type, - subdigest, - config: _extends$c({ - version: 2 - }, signature2.decoded, { - tree - }) - }; + defaultValue() { + const values = []; + this.coders.forEach((coder) => { + values.push(coder.defaultValue()); + }); + const uniqueNames = this.coders.reduce((accum, coder) => { + const name2 = coder.localName; + if (name2) { + if (!accum[name2]) { + accum[name2] = 0; + } + accum[name2]++; + } + return accum; + }, {}); + this.coders.forEach((coder, index2) => { + let name2 = coder.localName; + if (!name2 || uniqueNames[name2] !== 1) { + return; + } + if (name2 === "length") { + name2 = "_length"; + } + if (values[name2] != null) { + return; + } + values[name2] = values[index2]; + }); + return Object.freeze(values); } - if (!isSignedPayload(signedPayload)) { - throw new Error(`Chained signature recovery requires detailed signed payload, subdigest is not enough`); + encode(writer, _value2) { + const value = Typed.dereference(_value2, "tuple"); + return pack(writer, this.coders, value); } - const result = []; - let mutatedPayload = signedPayload; - for (const sig of [_extends$c({}, signature2, { - suffix: void 0 - }), ...signature2.suffix]) { - const recovered = await recoverSignature(sig, mutatedPayload, provider2); - result.unshift(recovered); - const nextMessage = setImageHashStruct(imageHash(deepestConfigOfSignature(recovered))); - mutatedPayload = _extends$c({}, mutatedPayload, { - message: nextMessage, - digest: keccak256$1(nextMessage) - }); + decode(reader2) { + return unpack(reader2, this.coders); } - const main2 = result[0]; - const suffix = result.slice(1); - return _extends$c({}, main2, { - suffix - }); } -function encodeChain(main2, suffix) { - const allSignatures = [main2, ...suffix || []]; - const encodedMap = allSignatures.map((s2) => getBytes(encodeSignature(s2))); - const body = solidityPacked(encodedMap.map(() => ["uint24", "bytes"]).flat(), encodedMap.map((s2) => [s2.length, s2]).flat()); - return solidityPacked(["uint8", "bytes"], [SignatureType$1.Chained, body]); +function id$1(value) { + return keccak256(toUtf8Bytes(value)); } -function encodeSignature(decoded) { - if (isBytesLike(decoded)) return hexlify(decoded); - if (isUnrecoveredChainedSignature(decoded) || isChainedSignature(decoded)) { - return encodeChain(encodeSignature(decoded), (decoded.suffix || []).map(encodeSignature)); +var COMPRESSED$1 = "AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQCuhzc3NzcBP68NEfMABQdHBuw5BV8FYAA9MzkI9r4ZBg7QyQAWA9CeOwLNCjcCjqkChuA/lm+RAsXTAoP6ASfnEQDytQFJAjWVCkeXAOsA6godAB/cwdAUE0WlBCN/AQUCQRjFD/MRBjHxDQSJbw0jBzUAswBxme+tnIcAYwabAysG8QAjAEMMmxcDqgPKQyDXCMMxA7kUQwD3NXOrAKmFIAAfBC0D3x4BJQDBGdUFAhEgVD8JnwmQJiNWYUzrg0oAGwAUAB0AFnNcACkAFgBP9h3gPfsDOWDKneY2ChglX1UDYD30ABsAFAAdABZzIGRAnwDD8wAjAEEMzRbDqgMB2sAFYwXqAtCnAsS4AwpUJKRtFHsadUz9AMMVbwLpABM1NJEX0ZkCgYMBEyMAxRVvAukAEzUBUFAtmUwSAy4DBTER33EftQHfSwB5MxJ/AjkWKQLzL8E/cwBB6QH9LQDPDtO9ASNriQC5DQANAwCK21EFI91zHwCoL9kBqQcHBwcHKzUDowBvAQohPvU3fAQgHwCyAc8CKQMA5zMSezr7ULgFmDp/LzVQBgEGAi8FYQVgt8AFcTtlQhpCWEmfe5tmZ6IAExsDzQ8t+X8rBKtTAltbAn0jsy8Bl6utPWMDTR8Ei2kRANkDBrNHNysDBzECQWUAcwFpJ3kAiyUhAJ0BUb8AL3EfAbfNAz81KUsFWwF3YQZtAm0A+VEfAzEJDQBRSQCzAQBlAHsAM70GD/v3IZWHBwARKQAxALsjTwHZAeMPEzmXgIHwABIAGQA8AEUAQDt3gdvIEGcQZAkGTRFMdEIVEwK0D64L7REdDNkq09PgADSxB/MDWwfzA1sDWwfzB/MDWwfzA1sDWwNbA1scEvAi28gQZw9QBHUFlgWTBN4IiyZREYkHMAjaVBV0JhxPA00BBCMtSSQ7mzMTJUpMFE0LCAQ2SmyvfUADTzGzVP2QqgPTMlc5dAkGHnkSqAAyD3skNb1OhnpPcagKU0+2tYdJak5vAsY6sEAACikJm2/Dd1YGRRAfJ6kQ+ww3AbkBPw3xS9wE9QY/BM0fgRkdD9GVoAipLeEM8SbnLqWAXiP5KocF8Uv4POELUVFsD10LaQnnOmeBUgMlAREijwrhDT0IcRD3Cs1vDekRSQc9A9lJngCpBwULFR05FbkmFGKwCw05ewb/GvoLkyazEy17AAXXGiUGUQEtGwMA0y7rhbRaNVwgT2MGBwspI8sUrFAkDSlAu3hMGh8HGSWtApVDdEqLUToelyH6PEENai4XUYAH+TwJGVMLhTyiRq9FEhHWPpE9TCJNTDAEOYMsMyePCdMPiQy9fHYBXQklCbUMdRM1ERs3yQg9Bx0xlygnGQglRplgngT7owP3E9UDDwVDCUUHFwO5HDETMhUtBRGBKNsC9zbZLrcCk1aEARsFzw8pH+MQVEfkDu0InwJpA4cl7wAxFSUAGyKfCEdnAGOP3FMJLs8Iy2pwI3gDaxTrZRF3B5UOWwerHDcVwxzlcMxeD4YMKKezCV8BeQmdAWME5wgNNV+MpCBFZ1eLXBifIGVBQ14AAjUMaRWjRMGHfAKPD28SHwE5AXcHPQ0FAnsR8RFvEJkI74YINbkz/DopBFMhhyAVCisDU2zSCysm/Qz8bQGnEmYDEDRBd/Jnr2C6KBgBBx0yyUFkIfULlk/RDKAaxRhGVDIZ6AfDA/ca9yfuQVsGAwOnBxc6UTPyBMELbQiPCUMATQ6nGwfbGG4KdYzUATWPAbudA1uVhwJzkwY7Bw8Aaw+LBX3pACECqwinAAkA0wNbAD0CsQehAB0AiUUBQQMrMwEl6QKTA5cINc8BmTMB9y0EH8cMGQD7O25OAsO1AoBuZqYF4VwCkgJNOQFRKQQJUktVA7N15QDfAE8GF+NLARmvTs8e50cB43MvAMsA/wAJOQcJRQHRAfdxALsBYws1Caa3uQFR7S0AhwAZbwHbAo0A4QA5AIP1AVcAUQVd/QXXAlNNARU1HC9bZQG/AyMBNwERAH0Gz5GpzQsjBHEH1wIQHxXlAu8yB7kFAyLjE9FCyQK94lkAMhoKPAqrCqpgX2Q3CjV2PVQAEh+sPss/UgVVO1c7XDtXO1w7VztcO1c7XDtXO1wDm8Pmw+YKcF9JYe8Mqg3YRMw6TRPfYFVgNhPMLbsUxRXSJVoZQRrAJwkl6FUNDwgt12Y0CDA0eRfAAEMpbINFY4oeNApPHOtTlVT8LR8AtUumM7MNsBsZREQFS3XxYi4WEgomAmSFAmJGX1GzAV83JAKh+wJonAJmDQKfiDgfDwJmPwJmKgRyBIMDfxcDfpY5Cjl7GzmGOicnAmwhAjI6OA4CbcsCbbLzjgM3a0kvAWsA4gDlAE4JB5wMkQECD8YAEbkCdzMCdqZDAnlPRwJ4viFg30WyRvcCfEMCeswCfQ0CfPRIBEiBZygALxlJXEpfGRtK0ALRBQLQ0EsrA4hTA4fqRMmRNgLypV0HAwOyS9JMMSkH001QTbMCi0MCitzFHwshR2sJuwKOOwKOYESbhQKO3QKOYHxRuFM5AQ5S2FSJApP/ApMQAO0AIFUiVbNV1AosHymZijLleGpFPz0Cl6MC77ZYJawAXSkClpMCloCgAK1ZsFoNhVEAPwKWuQKWUlxIXNUCmc8CmWhczl0LHQKcnznGOqECnBoCn58CnryOACETNS4TAp31Ap6WALlBYThh8wKe1wKgcgGtAp6jIwKeUqljzGQrKS8CJ7MCJoICoP8CoFDbAqYzAqXSAqgDAIECp/ZogGi1AAdNaiBq1QKs5wKssgKtawKtBgJXIQJV4AKx5dsDH1JsmwKywRECsuwbbORtZ21MYwMl0QK2YD9DbpQDKUkCuGICuUsZArkue3A6cOUCvR0DLbYDMhUCvoxyBgMzdQK+HnMmc1MCw88CwwhzhnRPOUl05AM8qwEDPJ4DPcMCxYACxksCxhSNAshtVQLISALJUwLJMgJkoQLd1nh9ZXiyeSlL1AMYp2cGAmH4GfeVKHsPXpZevxUCz28Cz3AzT1fW9xejAMqxAs93AS3uA04Wfk8JAtwrAtuOAtJTA1JgA1NjAQUDVZCAjUMEzxrxZEl5A4LSg5EC2ssC2eKEFIRNp0ADhqkAMwNkEoZ1Xf0AWQLfaQLevHd7AuIz7RgB8zQrAfSfAfLWiwLr9wLpdH0DAur9AuroAP1LAb0C7o0C66CWrpcHAu5DA4XkmH1w5HGlAvMHAG0DjhqZlwL3FwORcgOSiwL3nAL53QL4apogmq+/O5siA52HAv7+AR8APZ8gAZ+3AwWRA6ZuA6bdANXJAwZuoYyiCQ0DDE0BEwEjB3EGZb1rCQC/BG/DFY8etxEAG3k9ACcDNxJRA42DAWcrJQCM8wAlAOanC6OVCLsGI6fJBgCvBRnDBvElRUYFFoAFcD9GSDNCKUK8X3kZX8QAls0FOgCQVCGbwTsuYDoZutcONxjOGJHJ/gVfBWAFXwVgBWsFYAVfBWAFXwVgBV8FYAVfBWBOHQjfjW8KCgoKbF7xMwTRA7kGN8PDAMMEr8MA70gxFroFTj5xPnhCR0K+X30/X/AAWBkzswCNBsxzzASm70aCRS4rDDMeLz49fnXfcsH5GcoscQFz13Y4HwVnBXLJycnACNdRYwgICAqEXoWTxgA7P4kACxbZBu21Kw0AjMsTAwkVAOVtJUUsJ1JCuULESUArXy9gPi9AKwnJRQYKTD9LPoA+iT54PnkCkULEUUpDX9NWV3JVEjQAc1w3A3IBE3YnX+g7QiMJb6MKaiszRCUuQrNCxDPMCcwEX9EWJzYREBEEBwIHKn6l33JCNVIfybPJtAltydPUCmhBZw/tEKsZAJOVJU1CLRuxbUHOQAo7P0s+eEJHHA8SJVRPdGM0NVrpvBoKhfUlM0JHHGUQUhEWO1xLSj8MO0ucNAqJIzVCRxv9EFsqKyA4OQgNj2nwZgp5ZNFgE2A1K3YHS2AhQQojJmC7DgpzGG1WYFUZCQYHZO9gHWCdYIVgu2BTYJlwFh8GvRbcXbG8YgtDHrMBwzPVyQonHQgkCyYBgQJ0Ajc4nVqIAwGSCsBPIgDsK3SWEtIVBa5N8gGjAo+kVwVIZwD/AEUSCDweX4ITrRQsJ8K3TwBXFDwEAB0TvzVcAtoTS20RIwDgVgZ9BBImYgA5AL4Coi8LFnezOkCnIQFjAY4KBAPh9RcGsgZSBsEAJctdsWIRu2kTkQstRw7DAcMBKgpPBGIGMDAwKCYnKTQaLg4AKRSVAFwCdl+YUZ0JdicFD3lPAdt1F9ZZKCGxuE3yBxkFVGcA/wBFEgiCBwAOLHQSjxOtQDg1z7deFRMAZ8QTAGtKb1ApIiPHADkAvgKiLy1DFtYCmBiDAlDDWNB0eo7fpaMO/aEVRRv0ATEQZBIODyMEAc8JQhCbDRgzFD4TAEMAu9YBCgCsAOkAm5I3ABwAYxvONnR+MhXJAxgKQyxL2+kkJhMbhQKDBMkSsvF0AD9BNQ6uQC7WqSQHwxEAEEIu1hkhAH2z4iQPwyJPHNWpdyYBRSpnJALzoBAEVPPsH20MxA0CCEQKRgAFyAtFAlMNwwjEDUQJRArELtapMg7DDZgJIw+TGukEIwvDFkMAqAtDEMMMBhioe+QAO3MMRAACrgnEBSPY9Q0FDnbSBoMAB8MSYxkSxAEJAPIJAAB8FWMOFtMc/HcXwxhDAC7DAvOowwAewwJdKDKHAAHDAALrFUQVwwAbwyvzpWMWv8wA/ABpAy++bcYDUKPD0KhDCwKmJ1MAAmMA5+UZwxAagwipBRL/eADfw6fDGOMCGsOjk3l6BwOpo4sAEsMOGxMAA5sAbcMOAAvDp0MJGkMDwgipnNIPAwfIqUMGAOGDAAPzABXDAAcDAAnDAGmTABrDAA7DChjDjnEWAwABYwAOcwAuUyYABsMAF8MIKQANUgC6wy4AA8MADqMq8wCyYgAcIwAB8wqpAAXOCx0V4wAHowBCwwEKAGnDAAuDAB3DAAjDCakABdIAbqcZ3QCZCCkABdIAAAFDAAfjAB2jCCkABqIACYMAGzMAbSMA5sOIAAhjAAhDABTDBAkpAAbSAOOTAAlDC6kOzPtnAAdDAG6kQFAATwAKwwwAA0MACbUDPwAHIwAZgwACE6cDAAojAApDAAoDp/MGwwAJIwADEwAQQwgAFEMAEXMAD5MADfMADcMAGRMOFiMAFUMAbqMWuwHDAMIAE0MLAGkzEgDhUwACQwAEWgAXgwUjAAbYABjDBSYBgzBaAEFNALcQBxUMegAwMngBrA0IZgJ0KxQHBREPd1N0ZzKRJwaIHAZqNT4DqQq8BwngAB4DAwt2AX56T1ocKQNXAh1GATQGC3tOxYNagkgAMQA5CQADAQEAWxLjAIOYNAEzAH7tFRk6TglSAF8NAAlYAQ+S1ACAQwQorQBiAN4dAJ1wPyeTANVzuQDX3AIeEMp9eyMgXiUAEdkBkJizKltbVVAaRMqRAAEAhyQ/SDEz6BmfVwB6ATEsOClKIRcDOF0E/832AFNt5AByAnkCRxGCOs94NjXdAwINGBonDBwPALW2AwICAgAAAAAAAAYDBQMDARrUAwAtAAAAAgEGBgYGBgYFBQUFBQUEBQYHCAkEBQUFBQQAAAICAAAAIgCNAJAAlT0A6gC7ANwApEQAwgCyAK0AqADuAKYA2gCjAOcBCAEDAMcAgQBiANIA1AEDAN4A8gCQAKkBMQDqAN8A3AsBCQ8yO9ra2tq8xuLT1tRJOB0BUgFcNU0BWgFpAWgBWwFMUUlLbhMBUxsNEAs6PhMOACcUKy0vMj5AQENDQ0RFFEYGJFdXV1dZWVhZL1pbXVxcI2NnZ2ZoZypsbnZ1eHh4eHh4enp6enp6enp6enp8fH18e2IARPIASQCaAHgAMgBm+ACOAFcAVwA3AnbvAIsABfj4AGQAk/IAnwBPAGIAZP//sACFAIUAaQBWALEAJAC2AIMCQAJDAPwA5wD+AP4A6AD/AOkA6QDoAOYALwJ7AVEBQAE+AVQBPgE+AT4BOQE4ATgBOAEcAVgXADEQCAEAUx8SHgsdHhYAjgCWAKYAUQBqIAIxAHYAbwCXAxUDJzIDIUlGTzEAkQJPAMcCVwKkAMAClgKWApYClgKWApYCiwKWApYClgKWApYClgKVApUCmAKgApcClgKWApQClAKUApQCkgKVAnUB1AKXAp8ClgKWApUeAIETBQD+DQOfAmECOh8BVBg9AuIZEjMbAU4/G1WZAXusRAFpYQEFA0FPAQYAmTEeIJdyADFoAHEANgCRA5zMk/C2jGINwjMWygIZCaXdfDILBCs5dAE7YnQBugDlhoiHhoiGiYqKhouOjIaNkI6Ij4qQipGGkoaThpSSlYaWhpeKmIaZhpqGm4aci52QnoqfhuIC4XTpAt90AIp0LHSoAIsAdHQEQwRABEIERQRDBEkERgRBBEcESQRIBEQERgRJAJ5udACrA490ALxuAQ10ANFZdHQA13QCFHQA/mJ0AP4BIQD+APwA/AD9APwDhGZ03ASMK23HAP4A/AD8AP0A/CR0dACRYnQA/gCRASEA/gCRAvQA/gCRA4RmdNwEjCttxyR0AP9idAEhAP4A/gD8APwA/QD8AP8A/AD8AP0A/AOEZnTcBIwrbcckdHQAkWJ0ASEA/gCRAP4AkQL0AP4AkQOEZnTcBIwrbcckdAJLAT50AlIBQXQCU8l0dAJfdHQDpgL0A6YDpgOnA6cDpwOnA4RmdNwEjCttxyR0dACRYnQBIQOmAJEDpgCRAvQDpgCRA4RmdNwEjCttxyR0BDh0AJEEOQCRDpU5dSgCADR03gV2CwArdAEFAM5iCnR0AF1iAAYcOgp0dACRCnQAXAEIwWZ0CnRmdHQAkWZ0CnRmdEXgAFF03gp0dEY0tlT2u3SOAQTwscwhjZZKrhYcBSfFp9XNbKiVDOD2b+cpe4/Z17mQnbtzzhaeQtE2GGj0IDNTjRUSyTxxw/RPHW/+vS7d1NfRt9z9QPZg4X7QFfhCnkvgNPIItOsC2eV6hPannZNHlZ9xrwZXIMOlu3jSoQSq78WEjwLjw1ELSlF1aBvfzwk5ZX7AUvQzjPQKbDuQ+sm4wNOp4A6AdVuRS0t1y/DZpg4R6m7FNjM9HgvW7Bi88zaMjOo6lM8wtBBdj8LP4ylv3zCXPhebMKJc066o9sF71oFW/8JXu86HJbwDID5lzw5GWLR/LhT0Qqnp2JQxNZNfcbLIzPy+YypqRm/lBmGmex+82+PisxUumSeJkALIT6rJezxMH+CTJmQtt5uwTVbL3ptmjDUQzlSIvWi8Tl7ng1NpuRn1Ng4n14Qc+3Iil7OwkvNWogLSPkn3pihIFytyIGmMhOe3n1tWsuMy9BdKyqF4Z3v2SgggTL9KVvMXPnCbRe+oOuFFP3HejBG/w9gvmfNYvg6JuWia2lcSSN1uIjBktzoIazOHPJZ7kKHPz8mRWVdW3lA8WGF9dQF6Bm673boov3BUWDU2JNcahR23GtfHKLOz/viZ+rYnZFaIznXO67CYEJ1fXuTRpZhYZkKe54xeoagkNGLs+NTZHE0rX45/XvQ2RGADX6vcAvdxIUBV27wxGm2zjZo4X3ILgAlrOFheuZ6wtsvaIj4yLY7qqawlliaIcrz2G+c3vscAnCkCuMzMmZvMfu9lLwTvfX+3cVSyPdN9ZwgDZhfjRgNJcLiJ67b9xx8JHswprbiE3v9UphotAPIgnXVIN5KmMc0piXhc6cChPnN+MRhG9adtdttQTTwSIpl8I4/j//d3sz1326qTBTpPRM/Hgh3kzqEXs8ZAk4ErQhNO8hzrQ0DLkWMA/N+91tn2MdOJnWC2FCZehkQrwzwbKOjhvZsbM95QoeL9skYyMf4srVPVJSgg7pOLUtr/n9eT99oe9nLtFRpjA9okV2Kj8h9k5HaC0oivRD8VyXkJ81tcd4fHNXPCfloIQasxsuO18/46dR2jgul/UIet2G0kRvnyONMKhHs6J26FEoqSqd+rfYjeEGwHWVDpX1fh1jBBcKGMqRepju9Y00mDVHC+Xdij/j44rKfvfjGinNs1jO/0F3jB83XCDINN/HB84axlP+3E/klktRo+vl3U/aiyMJbIodE1XSsDn6UAzIoMtUObY2+k/4gY/l+AkZJ5Sj2vQrkyLm3FoxjhDX+31UXBFf9XrAH31fFqoBmDEZvhvvpnZ87N+oZEu7U9O/nnk+QWj3x8uyoRbEnf+O5UMr9i0nHP38IF5AvzrBW8YWBUR0mIAzIvndQq9N3v/Jto3aPjPXUPl8ASdPPyAp7jENf8bk7VMM9ol9XGmlBmeDMuGqt+WzuL6CXAxXjIhCPM5vACchgMJ/8XBGLO/D1isVvGhwwHHr1DLaI5mn2Jr/b1pUD90uciDaS8cXNDzCWvNmT/PhQe5e8nTnnnkt8Ds/SIjibcum/fqDhKopxAY8AkSrPn+IGDEKOO+U3XOP6djFs2H5N9+orhOahiQk5KnEUWa+CzkVzhp8bMHRbg81qhjjXuIKbHjSLSIBKWqockGtKinY+z4/RdBUF6pcc3JmnlxVcNgrI4SEzKUZSwcD2QCyxzKve+gAmg6ZuSRkpPFa6mfThu7LJNu3H5K42uCpNvPAsoedolKV/LHe/eJ+BbaG5MG0NaSGVPRUmNFMFFSSpXEcXwbVh7UETOZZtoVNRGOIbbkig3McEtR68cG0RZAoJevWYo7Dg/lZ1CQzblWeUvVHmr8fY4Nqd9JJiH/zEX24mJviH60fAyFr0A3c4bC1j3yZU60VgJxXn8JgJXLUIsiBnmKmMYz+7yBQFBvqb2eYnuW59joZBf56/wXvWIR4R8wTmV80i1mZy+S4+BUES+hzjk0uXpC///z/IlqHZ1monzlXp8aCfhGKMti73FI1KbL1q6IKO4fuBuZ59gagjn5xU79muMpHXg6S+e+gDM/U9BKLHbl9l6o8czQKl4RUkJJiqftQG2i3BMg/TQlUYFkJDYBOOvAugYuzYSDnZbDDd/aSd9x0Oe6F+bJcHfl9+gp6L5/TgA+BdFFovbfCrQ40s5vMPw8866pNX8zyFGeFWdxIpPVp9Rg1UPOVFbFZrvaFq/YAzHQgqMWpahMYfqHpmwXfHL1/kpYmGuHFwT55mQu0dylfNuq2Oq0hTMCPwqfxnuBIPLXfci4Y1ANy+1CUipQxld/izVh16WyG2Q0CQQ9NqtAnx1HCHwDj7sYxOSB0wopZSnOzxQOcExmxrVTF2BkOthVpGfuhaGECfCJpJKpjnihY+xOT2QJxN61+9K6QSqtv2Shr82I3jgJrqBg0wELFZPjvHpvzTtaJnLK6Vb97Yn933koO/saN7fsjwNKzp4l2lJVx2orjCGzC/4ZL4zCver6aQYtC5sdoychuFE6ufOiog+VWi5UDkbmvmtah/3aArEBIi39s5ILUnlFLgilcGuz9CQshEY7fw2ouoILAYPVT/gyAIq3TFAIwVsl+ktkRz/qGfnCDGrm5gsl/l9QdvCWGsjPz3dU7XuqKfdUrr/6XIgjp4rey6AJBmCmUJMjITHVdFb5m1p+dLMCL8t55zD42cmftmLEJC0Da04YiRCVUBLLa8D071/N5UBNBXDh0LFsmhV/5B5ExOB4j3WVG/S3lfK5o+V6ELHvy6RR9n4ac+VsK4VE4yphPvV+kG9FegTBH4ZRXL2HytUHCduJazB/KykjfetYxOXTLws267aGOd+I+JhKP//+VnXmS90OD/jvLcVu0asyqcuYN1mSb6XTlCkqv1vigZPIYwNF/zpWcT1GR/6aEIRjkh0yhg4LXJfaGobYJTY4JI58KiAKgmmgAKWdl5nYCeLqavRJGQNuYuZtZFGx+IkI4w4NS2xwbetNMunOjBu/hmKCI/w7tfiiyUd//4rbTeWt4izBY8YvGIN6vyKYmP/8X8wHKCeN+WRcKM70+tXKNGyevU9H2Dg5BsljnTf8YbsJ1TmMs74Ce2XlHisleguhyeg44rQOHZuw/6HTkhnnurK2d62q6yS7210SsAIaR+jXMQA+svkrLpsUY+F30Uw89uOdGAR6vo4FIME0EfVVeHTu6eKicfhSqOeXJhbftcd08sWEnNUL1C9fnprTgd83IMut8onVUF0hvqzZfHduPjbjwEXIcoYmy+P6tcJZHmeOv6VrvEdkHDJecjHuHeWANe79VG662qTjA/HCvumVv3qL+LrOcpqGps2ZGwQdFJ7PU4iuyRlBrwfO+xnPyr47s2cXVbWzAyznDiBGjCM3ksxjjqM62GE9C8f5U38kB3VjtabKp/nRdvMESPGDG90bWRLAt1Qk5DyLuazRR1YzdC1c+hZXvAWV8xA72S4A8B67vjVhbba3MMop293FeEXpe7zItMWrJG/LOH9ByOXmYnNJfjmfuX9KbrpgLOba4nZ+fl8Gbdv/ihv+6wFGKHCYrVwmhFC0J3V2bn2tIB1wCc1CST3d3X2OyxhguXcs4sm679UngzofuSeBewMFJboIQHbUh/m2JhW2hG9DIvG2t7yZIzKBTz9wBtnNC+2pCRYhSIuQ1j8xsz5VvqnyUIthvuoyyu7fNIrg/KQUVmGQaqkqZk/Vx5b33/gsEs8yX7SC1J+NV4icz6bvIE7C5G6McBaI8rVg56q5QBJWxn/87Q1sPK4+sQa8fLU5gXo4paaq4cOcQ4wR0VBHPGjKh+UlPCbA1nLXyEUX45qZ8J7/Ln4FPJE2TdzD0Z8MLSNQiykMMmSyOCiFfy84Rq60emYB2vD09KjYwsoIpeDcBDTElBbXxND72yhd9pC/1CMid/5HUMvAL27OtcIJDzNKpRPNqPOpyt2aPGz9QWIs9hQ9LiX5s8m9hjTUu/f7MyIatjjd+tSfQ3ufZxPpmJhTaBtZtKLUcfOCUqADuO+QoH8B9v6U+P0HV1GLQmtoNFTb3s74ivZgjES0qfK+8RdGgBbcCMSy8eBvh98+et1KIFqSe1KQPyXULBMTsIYnysIwiZBJYdI20vseV+wuJkcqGemehKjaAb9L57xZm3g2zX0bZ2xk/fU+bCo7TlnbW7JuF1YdURo/2Gw7VclDG1W7LOtas2LX4upifZ/23rzpsnY/ALfRgrcWP5hYmV9VxVOQA1fZvp9F2UNU+7d7xRyVm5wiLp3/0dlV7vdw1PMiZrbDAYzIVqEjRY2YU03sJhPnlwIPcZUG5ltL6S8XCxU1eYS5cjr34veBmXAvy7yN4ZjArIG0dfD/5UpBNlX1ZPoxJOwyqRi3wQWtOzd4oNKh0LkoTm8cwqgIfKhqqGOhwo71I+zXnMemTv2B2AUzABWyFztGgGULjDDzWYwJUVBTjKCn5K2QGMK1CQT7SzziOjo+BhAmqBjzuc3xYym2eedGeOIRJVyTwDw37iCMe4g5Vbnsb5ZBdxOAnMT7HU4DHpxWGuQ7GeiY30Cpbvzss55+5Km1YsbD5ea3NI9QNYIXol5apgSu9dZ8f8xS5dtHpido5BclDuLWY4lhik0tbJa07yJhH0BOyEut/GRbYTS6RfiTYWGMCkNpfSHi7HvdiTglEVHKZXaVhezH4kkXiIvKopYAlPusftpE4a5IZwvw1x/eLvoDIh/zpo9FiQInsTb2SAkKHV42XYBjpJDg4374XiVb3ws4qM0s9eSQ5HzsMU4OZJKuopFjBM+dAZEl8RUMx5uU2N486Kr141tVsGQfGjORYMCJAMsxELeNT4RmWjRcpdTGBwcx6XN9drWqPmJzcrGrH4+DRc7+n1w3kPZwu0BkNr6hQrqgo7JTB9A5kdJ/H7P4cWBMwsmuixAzJB3yrQpnGIq90lxAXLzDCdn1LPibsRt7rHNjgQBklRgPZ8vTbjXdgXrTWQsK5MdrXXQVPp0Rinq3frzZKJ0qD6Qhc40VzAraUXlob1gvkhK3vpmHgI6FRlQZNx6eRqkp0zy4AQlX813fAPtL3jMRaitGFFjo0zmErloC+h+YYdVQ6k4F/epxAoF0BmqEoKNTt6j4vQZNQ2BoqF9Vj53TOIoNmDiu9Xp15RkIgQIGcoLpfoIbenzpGUAtqFJp5W+LLnx38jHeECTJ/navKY1NWfN0sY1T8/pB8kIH3DU3DX+u6W3YwpypBMYOhbSxGjq84RZ84fWJow8pyHqn4S/9J15EcCMsXqrfwyd9mhiu3+rEo9pPpoJkdZqHjra4NvzFwuThNKy6hao/SlLw3ZADUcUp3w3SRVfW2rhl80zOgTYnKE0Hs2qp1J6H3xqPqIkvUDRMFDYyRbsFI3M9MEyovPk8rlw7/0a81cDVLmBsR2ze2pBuKb23fbeZC0uXoIvDppfTwIDxk1Oq2dGesGc+oJXWJLGkOha3CX+DUnzgAp9HGH9RsPZN63Hn4RMA5eSVhPHO+9RcRb/IOgtW31V1Q5IPGtoxPjC+MEJbVlIMYADd9aHYWUIQKopuPOHmoqSkubnAKnzgKHqgIOfW5RdAgotN6BN+O2ZYHkuemLnvQ8U9THVrS1RtLmKbcC7PeeDsYznvqzeg6VCNwmr0Yyx1wnLjyT84BZz3EJyCptD3yeueAyDWIs0L2qs/VQ3HUyqfrja0V1LdDzqAikeWuV4sc7RLIB69jEIBjCkyZedoUHqCrOvShVzyd73OdrJW0hPOuQv2qOoHDc9xVb6Yu6uq3Xqp2ZaH46A7lzevbxQEmfrzvAYSJuZ4WDk1Hz3QX1LVdiUK0EvlAGAYlG3Md30r7dcPN63yqBCIj25prpvZP0nI4+EgWoFG95V596CurXpKRBGRjQlHCvy5Ib/iW8nZJWwrET3mgd6mEhfP4KCuaLjopWs7h+MdXFdIv8dHQJgg1xi1eYqB0uDYjxwVmri0Sv5XKut/onqapC+FQiC2C1lvYJ9MVco6yDYsS3AANUfMtvtbYI2hfwZatiSsnoUeMZd34GVjkMMKA+XnjJpXgRW2SHTZplVowPmJsvXy6w3cfO1AK2dvtZEKTkC/TY9LFiKHCG0DnrMQdGm2lzlBHM9iEYynH2UcVMhUEjsc0oDBTgo2ZSQ1gzkAHeWeBXYFjYLuuf8yzTCy7/RFR81WDjXMbq2BOH5dURnxo6oivmxL3cKzKInlZkD31nvpHB9Kk7GfcfE1t+1V64b9LtgeJGlpRFxQCAqWJ5DoY77ski8gsOEOr2uywZaoO/NGa0X0y1pNQHBi3b2SUGNpcZxDT7rLbBf1FSnQ8guxGW3W+36BW0gBje4DOz6Ba6SVk0xiKgt+q2JOFyr4SYfnu+Ic1QZYIuwHBrgzr6UvOcSCzPTOo7D6IC4ISeS7zkl4h+2VoeHpnG/uWR3+ysNgPcOIXQbv0n4mr3BwQcdKJxgPSeyuP/z1Jjg4e9nUvoXegqQVIE30EHx5GHv+FAVUNTowYDJgyFhf5IvlYmEqRif6+WN1MkEJmDcQITx9FX23a4mxy1AQRsOHO/+eImX9l8EMJI3oPWzVXxSOeHU1dUWYr2uAA7AMb+vAEZSbU3qob9ibCyXeypEMpZ6863o6QPqlqGHZkuWABSTVNd4cOh9hv3qEpSx2Zy/DJMP6cItEmiBJ5PFqQnDEIt3NrA3COlOSgz43D7gpNFNJ5MBh4oFzhDPiglC2ypsNU4ISywY2erkyb1NC3Qh/IfWj0eDgZI4/ln8WPfBsT3meTjq1Uqt1E7Zl/qftqkx6aM9KueMCekSnMrcHj1CqTWWzEzPsZGcDe3Ue4Ws+XFYVxNbOFF8ezkvQGR6ZOtOLU2lQEnMBStx47vE6Pb7AYMBRj2OOfZXfisjJnpTfSNjo6sZ6qSvNxZNmDeS7Gk3yYyCk1HtKN2UnhMIjOXUzAqDv90lx9O/q/AT1ZMnit5XQe9wmQxnE/WSH0CqZ9/2Hy+Sfmpeg8RwsHI5Z8kC8H293m/LHVVM/BA7HaTJYg5Enk7M/xWpq0192ACfBai2LA/qrCjCr6Dh1BIMzMXINBmX96MJ5Hn2nxln/RXPFhwHxUmSV0EV2V0jm86/dxxuYSU1W7sVkEbN9EzkG0QFwPhyHKyb3t+Fj5WoUUTErcazE/N6EW6Lvp0d//SDPj7EV9UdJN+Amnf3Wwk3A0SlJ9Z00yvXZ7n3z70G47Hfsow8Wq1JXcfwnA+Yxa5mFsgV464KKP4T31wqIgzFPd3eCe3j5ory5fBF2hgCFyVFrLzI9eetNXvM7oQqyFgDo4CTp/hDV9NMX9JDHQ/nyHTLvZLNLF6ftn2OxjGm8+PqOwhxnPHWipkE/8wbtyri80Sr7pMNkQGMfo4ZYK9OcCC4ESVFFbLMIvlxSoRqWie0wxqnLfcLSXMSpMMQEJYDVObYsXIQNv4TGNwjq1kvT1UOkicTrG3IaBZ3XdScS3u8sgeZPVpOLkbiF940FjbCeNRINNvDbd01EPBrTCPpm12m43ze1bBB59Ia6Ovhnur/Nvx3IxwSWol+3H2qfCJR8df6aQf4v6WiONxkK+IqT4pKQrZK/LplgDI/PJZbOep8dtbV7oCr6CgfpWa8NczOkPx81iSHbsNhVSJBOtrLIMrL31LK9TqHqAbAHe0RLmmV806kRLDLNEhUEJfm9u0sxpkL93Zgd6rw+tqBfTMi59xqXHLXSHwSbSBl0EK0+loECOPtrl+/nsaFe197di4yUgoe4jKoAJDXc6DGDjrQOoFDWZJ9HXwt8xDrQP+7aRwWKWI1GF8s8O4KzxWBBcwnl3vnl1Oez3oh6Ea1vjR7/z7DDTrFtqU2W/KAEzAuXDNZ7MY73MF216dzdSbWmUp4lcm7keJfWaMHgut9x5C9mj66Z0lJ+yhsjVvyiWrfk1lzPOTdhG15Y7gQlXtacvI7qv/XNSscDwqkgwHT/gUsD5yB7LdRRvJxQGYINn9hTpodKFVSTPrtGvyQw+HlRFXIkodErAGu9Iy1YpfSPc3jkFh5CX3lPxv7aqjE/JAfTIpEjGb/H7MO0e2vsViSW1qa/Lmi4/n4DEI3g7lYrcanspDfEpKkdV1OjSLOy0BCUqVoECaB55vs06rXl4jqmLsPsFM/7vYJ0vrBhDCm/00A/H81l1uekJ/6Lml3Hb9+NKiLqATJmDpyzfYZFHumEjC662L0Bwkxi7E9U4cQA0XMVDuMYAIeLMPgQaMVOd8fmt5SflFIfuBoszeAw7ow5gXPE2Y/yBc/7jExARUf/BxIHQBF5Sn3i61w4z5xJdCyO1F1X3+3ax+JSvMeZ7S6QSKp1Fp/sjYz6Z+VgCZzibGeEoujryfMulH7Rai5kAft9ebcW50DyJr2uo2z97mTWIu45YsSnNSMrrNUuG1XsYBtD9TDYzQffKB87vWbkM4EbPAFgoBV4GQS+vtFDUqOFAoi1nTtmIOvg38N4hT2Sn8r8clmBCXspBlMBYTnrqFJGBT3wZOzAyJDre9dHH7+x7qaaKDOB4UQALD5ecS0DE4obubQEiuJZ0EpBVpLuYcce8Aa4PYd/V4DLDAJBYKQPCWTcrEaZ5HYbJi11Gd6hjGom1ii18VHYnG28NKpkz2UKVPxlhYSp8uZr367iOmoy7zsxehW9wzcy2zG0a80PBMCRQMb32hnaHeOR8fnNDzZhaNYhkOdDsBUZ3loDMa1YP0uS0cjUP3b/6DBlqmZOeNABDsLl5BI5QJups8uxAuWJdkUB/pO6Zax6tsg7fN5mjjDgMGngO+DPcKqiHIDbFIGudxtPTIyDi9SFMKBDcfdGQRv41q1AqmxgkVfJMnP8w/Bc7N9/TR6C7mGObFqFkIEom8sKi2xYqJLTCHK7cxzaZvqODo22c3wisBCP4HeAgcRbNPAsBkNRhSmD48dHupdBRw4mIvtS5oeF6zeT1KMCyhMnmhpkFAGWnGscoNkwvQ8ZM5lE/vgTHFYL99OuNxdFBxTEDd5v2qLR8y9WkXsWgG6kZNndFG+pO/UAkOCipqIhL3hq7cRSdrCq7YhUsTocEcnaFa6nVkhnSeRYUA1YO0z5itF9Sly3VlxYDw239TJJH6f3EUfYO5lb7bcFcz8Bp7Oo8QmnsUHOz/fagVUBtKEw1iT88j+aKkv8cscKNkMxjYr8344D1kFoZ7/td1W6LCNYN594301tUGRmFjAzeRg5vyoM1F6+bJZ/Q54jN/k8SFd3DxPTYaAUsivsBfgTn7Mx8H2SpPt4GOdYRnEJOH6jHM2p6SgB0gzIRq6fHxGMmSmqaPCmlfwxiuloaVIitLGN8wie2CDWhkzLoCJcODh7KIOAqbHEvXdUxaS4TTTs07Clzj/6GmVs9kiZDerMxEnhUB6QQPlcfqkG9882RqHoLiHGBoHfQuXIsAG8GTAtao2KVwRnvvam8jo1e312GQAKWEa4sUVEAMG4G6ckcONDwRcg1e2D3+ohXgY4UAWF8wHKQMrSnzCgfFpsxh+aHXMGtPQroQasRY4U6UdG0rz1Vjbka0MekOGRZQEvqQFlxseFor8zWFgHek3v29+WqN6gaK5gZOTOMZzpQIC1201LkMCXild3vWXSc5UX9xcFYfbRPzGFa1FDcPfPB/jUEq/FeGt419CI3YmBlVoHsa4KdcwQP5ZSwHHhFJ7/Ph/Rap/4vmG91eDwPP0lDfCDRCLszTqfzM71xpmiKi2HwS4WlqvGNwtvwF5Dqpn6KTq8ax00UMPkxDcZrEEEsIvHiUXXEphdb4GB4FymlPwBz4Gperqq5pW7TQ6/yNRhW8VT5NhuP0udlxo4gILq5ZxAZk8ZGh3g4CqxJlPKY7AQxupfUcVpWT5VItp1+30UqoyP4wWsRo3olRRgkWZZ2ZN6VC3OZFeXB8NbnUrSdikNptD1QiGuKkr8EmSR/AK9Rw+FF3s5uwuPbvHGiPeFOViltMK7AUaOsq9+x9cndk3iJEE5LKZRlWJbKOZweROzmPNVPkjE3K/TyA57Rs68TkZ3MR8akKpm7cFjnjPd/DdkWjgYoKHSr5Wu5ssoBYU4acRs5g2DHxUmdq8VXOXRbunD8QN0LhgkssgahcdoYsNvuXGUK/KXD/7oFb+VGdhqIn02veuM5bLudJOc2Ky0GMaG4W/xWBxIJcL7yliJOXOpx0AkBqUgzlDczmLT4iILXDxxtRR1oZa2JWFgiAb43obrJnG/TZC2KSK2wqOzRZTXavZZFMb1f3bXvVaNaK828w9TO610gk8JNf3gMfETzXXsbcvRGCG9JWQZ6+cDPqc4466Yo2RcKH+PILeKOqtnlbInR3MmBeGG3FH10yzkybuqEC2HSQwpA0An7d9+73BkDUTm30bZmoP/RGbgFN+GrCOfADgqr0WbI1a1okpFms8iHYw9hm0zUvlEMivBRxModrbJJ+9/p3jUdQQ9BCtQdxnOGrT5dzRUmw0593/mbRSdBg0nRvRZM5/E16m7ZHmDEtWhwvfdZCZ8J8M12W0yRMszXamWfQTwIZ4ayYktrnscQuWr8idp3PjT2eF/jmtdhIfcpMnb+IfZY2FebW6UY/AK3jP4u3Tu4zE4qlnQgLFbM19EBIsNf7KhjdbqQ/D6yiDb+NlEi2SKD+ivXVUK8ib0oBo366gXkR8ZxGjpJIDcEgZPa9TcYe0TIbiPl/rPUQDu3XBJ9X/GNq3FAUsKsll57DzaGMrjcT+gctp+9MLYXCq+sqP81eVQ0r9lt+gcQfZbACRbEjvlMskztZG8gbC8Qn9tt26Q7y7nDrbZq/LEz7kR6Jc6pg3N9rVX8Y5MJrGlML9p9lU4jbTkKqCveeZUJjHB03m2KRKR2TytoFkTXOLg7keU1s1lrPMQJpoOKLuAAC+y1HlJucU6ysB5hsXhvSPPLq5J7JtnqHKZ4vYjC4Vy8153QY+6780xDuGARsGbOs1WqzH0QS765rnSKEbbKlkO8oI/VDwUd0is13tKpqILu1mDJFNy/iJAWcvDgjxvusIT+PGz3ST/J9r9Mtfd0jpaGeiLYIqXc7DiHSS8TcjFVksi66PEkxW1z6ujbLLUGNNYnzOWpH8BZGK4bCK7iR+MbIv8ncDAz1u4StN3vTTzewr9IQjk9wxFxn+6N1ddKs0vffJiS08N3a4G1SVrlZ97Q/M+8G9fe5AP6d9/Qq4WRnORVhofPIKEdCr3llspUfE0oKIIYoByBRPh+bX1HLS3JWGJRhIvE1aW4NTd8ePi4Z+kXb+Z8snYfSNcqijhAgVsx4RCM54cXUiYkjeBmmC4ajOHrChoELscJJC7+9jjMjw5BagZKlgRMiSNYz7h7vvZIoQqbtQmspc0cUk1G/73iXtSpROl5wtLgQi0mW2Ex8i3WULhcggx6E1LMVHUsdc9GHI1PH3U2Ko0PyGdn9KdVOLm7FPBui0i9a0HpA60MsewVE4z8CAt5d401Gv6zXlIT5Ybit1VIA0FCs7wtvYreru1fUyW3oLAZ/+aTnZrOcYRNVA8spoRtlRoWflsRClFcgzkqiHOrf0/SVw+EpVaFlJ0g4Kxq1MMOmiQdpMNpte8lMMQqm6cIFXlnGbfJllysKDi+0JJMotkqgIxOSQgU9dn/lWkeVf8nUm3iwX2Nl3WDw9i6AUK3vBAbZZrcJpDQ/N64AVwjT07Jef30GSSmtNu2WlW7YoyW2FlWfZFQUwk867EdLYKk9VG6JgEnBiBxkY7LMo4YLQJJlAo9l/oTvJkSARDF/XtyAzM8O2t3eT/iXa6wDN3WewNmQHdPfsxChU/KtLG2Mn8i4ZqKdSlIaBZadxJmRzVS/o4yA65RTSViq60oa395Lqw0pzY4SipwE0SXXsKV+GZraGSkr/RW08wPRvqvSUkYBMA9lPx4m24az+IHmCbXA+0faxTRE9wuGeO06DIXa6QlKJ3puIyiuAVfPr736vzo2pBirS+Vxel3TMm3JKhz9o2ZoRvaFVpIkykb0Hcm4oHFBMcNSNj7/4GJt43ogonY2Vg4nsDQIWxAcorpXACzgBqQPjYsE/VUpXpwNManEru4NwMCFPkXvMoqvoeLN3qyu/N1eWEHttMD65v19l/0kH2mR35iv/FI+yjoHJ9gPMz67af3Mq/BoWXqu3rphiWMXVkmnPSEkpGpUI2h1MThideGFEOK6YZHPwYzMBvpNC7+ZHxPb7epfefGyIB4JzO9DTNEYnDLVVHdQyvOEVefrk6Uv5kTQYVYWWdqrdcIl7yljwwIWdfQ/y+2QB3eR/qxYObuYyB4gTbo2in4PzarU1sO9nETkmj9/AoxDA+JM3GMqQtJR4jtduHtnoCLxd1gQUscHRB/MoRYIEsP2pDZ9KvHgtlk1iTbWWbHhohwFEYX7y51fUV2nuUmnoUcqnWIQAAgl9LTVX+Bc0QGNEhChxHR4YjfE51PUdGfsSFE6ck7BL3/hTf9jLq4G1IafINxOLKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI"; +const FENCED = /* @__PURE__ */ new Map([[8217, "apostrophe"], [8260, "fraction slash"], [12539, "middle dot"]]); +const NSM_MAX = 4; +function decode_arithmetic(bytes2) { + let pos = 0; + function u16() { + return bytes2[pos++] << 8 | bytes2[pos++]; } - const body = isUnrecoveredSignature(decoded) ? decoded.decoded : decoded.config; - switch (decoded.type) { - case SignatureType$1.Legacy: - if (BigInt(body.threshold) > 255n) { - throw new Error(`Legacy signature threshold is too large: ${body.threshold} (max 255)`); + let symbol_count = u16(); + let total = 1; + let acc = [0, 1]; + for (let i = 1; i < symbol_count; i++) { + acc.push(total += u16()); + } + let skip = u16(); + let pos_payload = pos; + pos += skip; + let read_width = 0; + let read_buffer = 0; + function read_bit() { + if (read_width == 0) { + read_buffer = read_buffer << 8 | bytes2[pos++]; + read_width = 8; + } + return read_buffer >> --read_width & 1; + } + const N2 = 31; + const FULL = 2 ** N2; + const HALF = FULL >>> 1; + const QRTR = HALF >> 1; + const MASK = FULL - 1; + let register2 = 0; + for (let i = 0; i < N2; i++) register2 = register2 << 1 | read_bit(); + let symbols = []; + let low = 0; + let range2 = FULL; + while (true) { + let value = Math.floor(((register2 - low + 1) * total - 1) / range2); + let start = 0; + let end = symbol_count; + while (end - start > 1) { + let mid = start + end >>> 1; + if (value < acc[mid]) { + end = mid; + } else { + start = mid; } - return encodeSignatureBody(body); - case SignatureType$1.NoChainIdDynamic: - case SignatureType$1.Dynamic: - return solidityPacked(["uint8", "bytes"], [decoded.type, encodeSignatureBody(body)]); - case SignatureType$1.Chained: - throw new Error(`Unreachable code: Chained signature should be handled above`); - default: - throw new Error(`Invalid signature type: ${decoded.type}`); + } + if (start == 0) break; + symbols.push(start); + let a2 = low + Math.floor(range2 * acc[start] / total); + let b2 = low + Math.floor(range2 * acc[start + 1] / total) - 1; + while (((a2 ^ b2) & HALF) == 0) { + register2 = register2 << 1 & MASK | read_bit(); + a2 = a2 << 1 & MASK; + b2 = b2 << 1 & MASK | 1; + } + while (a2 & ~b2 & QRTR) { + register2 = register2 & HALF | register2 << 1 & MASK >>> 1 | read_bit(); + a2 = a2 << 1 ^ HALF; + b2 = (b2 ^ HALF) << 1 | HALF | 1; + } + low = a2; + range2 = 1 + b2 - a2; } + let offset2 = symbol_count - 4; + return symbols.map((x2) => { + switch (x2 - offset2) { + case 3: + return offset2 + 65792 + (bytes2[pos_payload++] << 16 | bytes2[pos_payload++] << 8 | bytes2[pos_payload++]); + case 2: + return offset2 + 256 + (bytes2[pos_payload++] << 8 | bytes2[pos_payload++]); + case 1: + return offset2 + bytes2[pos_payload++]; + default: + return x2 - 1; + } + }); } -function encodeSignatureBody(decoded) { - return solidityPacked(["uint16", "uint32", "bytes"], [decoded.threshold, decoded.checkpoint, encodeSignatureTree(decoded.tree)]); +function read_payload(v3) { + let pos = 0; + return () => v3[pos++]; } -function encodeSignatureTree(tree) { - if (isNode$1(tree) || isUnrecoveredNode(tree)) { - const encodedRight = getBytes(encodeSignatureTree(tree.right)); - const encodedLeft = getBytes(encodeSignatureTree(tree.left)); - const isBranching = isNode$1(tree.right) || isUnrecoveredNode(tree.right); - if (isBranching) { - return solidityPacked(["bytes", "uint8", "uint24", "bytes"], [encodedLeft, SignaturePartType.Branch, encodedRight.length, encodedRight]); - } else { - return solidityPacked(["bytes", "bytes"], [encodedLeft, encodedRight]); +function read_compressed_payload(s2) { + return read_payload(decode_arithmetic(unsafe_atob(s2))); +} +function unsafe_atob(s2) { + let lookup2 = []; + [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach((c2, i) => lookup2[c2.charCodeAt(0)] = i); + let n2 = s2.length; + let ret = new Uint8Array(6 * n2 >> 3); + for (let i = 0, pos = 0, width = 0, carry = 0; i < n2; i++) { + carry = carry << 6 | lookup2[s2.charCodeAt(i)]; + width += 6; + if (width >= 8) { + ret[pos++] = carry >> (width -= 8); } } - if (isNestedLeaf(tree) || isUnrecoveredNestedLeaf(tree)) { - const nested = getBytes(encodeSignatureTree(tree.tree)); - return solidityPacked(["uint8", "uint8", "uint16", "uint24", "bytes"], [SignaturePartType.Nested, tree.weight, tree.threshold, nested.length, nested]); - } - if (isUnrecoveredSignatureLeaf(tree) || isSignerLeaf(tree) && tree.signature !== void 0) { - const signature2 = getBytes(tree.signature); - if (tree.isDynamic || signature2.length !== SignaturePartTypeLength) { - if (!tree.address) throw new Error(`Dynamic signature leaf must have address`); - return solidityPacked(["uint8", "uint8", "address", "uint24", "bytes"], [SignaturePartType.DynamicSignature, tree.weight, tree.address, signature2.length, signature2]); - } else { - return solidityPacked(["uint8", "uint8", "bytes"], [SignaturePartType.Signature, tree.weight, signature2]); + return ret; +} +function signed(i) { + return i & 1 ? ~i >> 1 : i >> 1; +} +function read_deltas(n2, next) { + let v3 = Array(n2); + for (let i = 0, x2 = 0; i < n2; i++) v3[i] = x2 += signed(next()); + return v3; +} +function read_sorted(next, prev = 0) { + let ret = []; + while (true) { + let x2 = next(); + let n2 = next(); + if (!n2) break; + prev += x2; + for (let i = 0; i < n2; i++) { + ret.push(prev + i); } + prev += n2 + 1; } - if (isSignerLeaf(tree)) { - return solidityPacked(["uint8", "uint8", "address"], [SignaturePartType.Address, tree.weight, tree.address]); - } - if (isNodeLeaf(tree)) { - return solidityPacked(["uint8", "bytes32"], [SignaturePartType.Node, tree.nodeHash]); - } - if (isSubdigestLeaf(tree)) { - return solidityPacked(["uint8", "bytes32"], [SignaturePartType.Subdigest, tree.subdigest]); - } - throw new Error(`Unknown signature tree type: ${tree}`); + return ret; } -function signaturesOf(topology) { - if (isNode$1(topology)) { - return [...signaturesOf(topology.left), ...signaturesOf(topology.right)]; - } - if (isNestedLeaf(topology)) { - return signaturesOf(topology.tree); - } - if (isSignerLeaf(topology) && topology.signature) { - return [{ - address: topology.address, - signature: topology.signature - }]; - } - return []; +function read_sorted_arrays(next) { + return read_array_while(() => { + let v3 = read_sorted(next); + if (v3.length) return v3; + }); } -function signaturesOfDecoded(utopology) { - if (isUnrecoveredNode(utopology)) { - return [...signaturesOfDecoded(utopology.left), ...signaturesOfDecoded(utopology.right)]; - } - if (isUnrecoveredNestedLeaf(utopology)) { - return signaturesOfDecoded(utopology.tree); +function read_mapped(next) { + let ret = []; + while (true) { + let w2 = next(); + if (w2 == 0) break; + ret.push(read_linear_table(w2, next)); } - if (isUnrecoveredSignatureLeaf(utopology)) { - return [utopology.signature]; + while (true) { + let w2 = next() - 1; + if (w2 < 0) break; + ret.push(read_replacement_table(w2, next)); } - return []; + return ret.flat(); } -function subdigestsOfDecoded(utopology) { - if (isUnrecoveredNode(utopology)) { - return [...subdigestsOfDecoded(utopology.left), ...subdigestsOfDecoded(utopology.right)]; - } - if (isUnrecoveredNestedLeaf(utopology)) { - return subdigestsOfDecoded(utopology.tree); - } - if (isSubdigestLeaf(utopology)) { - return [utopology.subdigest]; +function read_array_while(next) { + let v3 = []; + while (true) { + let x2 = next(v3.length); + if (!x2) break; + v3.push(x2); } - return []; + return v3; } -async function trimSignature(signature2) { - const decoded = typeof signature2 === "string" ? decodeSignature(signature2) : signature2; - if (isUnrecoveredChainedSignature(decoded)) { - const _trimmed = await Promise.all([trimSignature(_extends$c({}, decoded, { - suffix: void 0 - })), ...decoded.suffix.map((s2) => trimSignature(s2))]); - return encodeChain(_trimmed[0], _trimmed.slice(1)); +function read_transposed(n2, w2, next) { + let m2 = Array(n2).fill().map(() => []); + for (let i = 0; i < w2; i++) { + read_deltas(n2, next).forEach((x2, j2) => m2[j2].push(x2)); } - const { - trimmed - } = await trimUnrecoveredTree(decoded.decoded.tree); - return encodeSignature(_extends$c({}, decoded, { - decoded: _extends$c({}, decoded.decoded, { - tree: trimmed - }) - })); + return m2; } -async function trimUnrecoveredTree(tree, trimStaticDigest = true) { - if (isUnrecoveredNode(tree)) { - const [left, right] = await Promise.all([trimUnrecoveredTree(tree.left), trimUnrecoveredTree(tree.right)]); - if (left.weight === 0 && right.weight === 0) { - try { - const recovered = await recoverTopology(tree, ZeroHash, void 0); - return { - weight: 0, - trimmed: { - nodeHash: hashNode(recovered) - } - }; - } catch (_unused) { - } - } else { - return { - weight: left.weight + right.weight, - trimmed: { - left: left.trimmed, - right: right.trimmed - } - }; - } +function read_linear_table(w2, next) { + let dx = 1 + next(); + let dy = next(); + let vN = read_array_while(next); + let m2 = read_transposed(vN.length, 1 + w2, next); + return m2.flatMap((v3, i) => { + let [x2, ...ys] = v3; + return Array(vN[i]).fill().map((_, j2) => { + let j_dy = j2 * dy; + return [x2 + j2 * dx, ys.map((y2) => y2 + j_dy)]; + }); + }); +} +function read_replacement_table(w2, next) { + let n2 = 1 + next(); + let m2 = read_transposed(n2, 1 + w2, next); + return m2.map((v3) => [v3[0], v3.slice(1)]); +} +function read_trie(next) { + let ret = []; + let sorted = read_sorted(next); + expand(decode2([]), []); + return ret; + function decode2(Q2) { + let S2 = next(); + let B2 = read_array_while(() => { + let cps = read_sorted(next).map((i) => sorted[i]); + if (cps.length) return decode2(cps); + }); + return { S: S2, B: B2, Q: Q2 }; } - if (isUnrecoveredNestedLeaf(tree)) { - const trimmed = await trimUnrecoveredTree(tree.tree); - if (trimmed.weight === 0) { - try { - const recovered = await recoverTopology(tree, ZeroHash, void 0); - return { - weight: 0, - trimmed: { - nodeHash: hashNode(recovered) - } - }; - } catch (_unused2) { + function expand({ S: S2, B: B2 }, cps, saved) { + if (S2 & 4 && saved === cps[cps.length - 1]) return; + if (S2 & 2) saved = cps[cps.length - 1]; + if (S2 & 1) ret.push(cps); + for (let br of B2) { + for (let cp of br.Q) { + expand(br, [...cps, cp], saved); } } - return { - weight: trimmed.weight, - trimmed: { - weight: tree.weight, - threshold: tree.threshold, - tree: trimmed.trimmed - } - }; } - if (isNodeLeaf(tree) && isEncodedSignerLeaf(tree.nodeHash)) { - return { - weight: 0, - trimmed: _extends$c({}, decodeSignerLeaf(tree.nodeHash)) - }; - } - if (isUnrecoveredSignatureLeaf(tree) || isSignerLeaf(tree) && tree.signature !== void 0) { - return { - weight: Number(tree.weight), - trimmed: tree - }; +} +function hex_cp(cp) { + return cp.toString(16).toUpperCase().padStart(2, "0"); +} +function quote_cp(cp) { + return `{${hex_cp(cp)}}`; +} +function explode_cp(s2) { + let cps = []; + for (let pos = 0, len = s2.length; pos < len; ) { + let cp = s2.codePointAt(pos); + pos += cp < 65536 ? 1 : 2; + cps.push(cp); } - if (!trimStaticDigest && isSubdigestLeaf(tree)) { - return { - weight: Infinity, - trimmed: tree - }; + return cps; +} +function str_from_cps(cps) { + const chunk = 4096; + let len = cps.length; + if (len < chunk) return String.fromCodePoint(...cps); + let buf = []; + for (let i = 0; i < len; ) { + buf.push(String.fromCodePoint(...cps.slice(i, i += chunk))); } - return { - weight: 0, - trimmed: tree - }; + return buf.join(""); } -const SignatureCoder = { - decode: (data) => { - return decodeSignature(data); - }, - encode: (data) => { - return encodeSignature(data); - }, - trim: (data) => { - return trimSignature(data); - }, - supportsNoChainId: true, - recover: (data, payload, provider2) => { - return recoverSignature(data, payload, provider2); - }, - encodeSigners: (config2, signatures, subdigests, chainId) => { - return encodeSigners(config2, signatures, subdigests, chainId); - }, - hasEnoughSigningPower: (config2, signatures) => { - const { - weight - } = SignatureCoder.encodeSigners(config2, signatures, [], 0); - return weight >= BigInt(config2.threshold); - }, - chainSignatures: (main2, suffix) => { - const reversed = suffix.reverse(); - const mraw = isBytesLike(main2) ? main2 : encodeSignature(main2); - const sraw = reversed.map((s2) => isBytesLike(s2) ? s2 : encodeSignature(s2)); - return encodeChain(mraw, sraw); - }, - hashSetImageHash: function(imageHash2) { - return hashSetImageHash(imageHash2); - }, - signaturesOf(config2) { - return signaturesOf(config2.tree); - }, - signaturesOfDecoded: function(data) { - return signaturesOfDecoded(data.decoded.tree); +function compare_arrays(a2, b2) { + let n2 = a2.length; + let c2 = n2 - b2.length; + for (let i = 0; c2 == 0 && i < n2; i++) c2 = a2[i] - b2[i]; + return c2; +} +var COMPRESSED = "AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSMEEEl5RFVMKvO0XQ8ExDdJMnIgsj26PTQyy8FfEQ8AY8IPAGcEbwRwBHEEcgRzBHQEdQR2BHcEeAR6BHsEfAR+BIAEgfndBQoBYgULAWIFDAFiBNcE2ATZBRAFEQUvBdALFAsVDPcNBw13DYcOMA4xDjMB4BllHI0B2grbAMDpHLkQ7QHVAPRNQQFnGRUEg0yEB2uaJF8AJpIBpob5AERSMAKNoAXqaQLUBMCzEiACnwRZEkkVsS7tANAsBG0RuAQLEPABv9HICTUBXigPZwRBApMDOwAamhtaABqEAY8KvKx3LQ4ArAB8UhwEBAVSagD8AEFZADkBIadVj2UMUgx5Il4ANQC9AxIB1BlbEPMAs30CGxlXAhwZKQIECBc6EbsCoxngzv7UzRQA8M0BawL6ZwkN7wABAD33OQRcsgLJCjMCjqUChtw/km+NAsXPAoP2BT84PwURAK0RAvptb6cApQS/OMMey5HJS84UdxpxTPkCogVFITaTOwERAK5pAvkNBOVyA7q3BKlOJSALAgUIBRcEdASpBXqzABXFSWZOawLCOqw//AolCZdvv3dSBkEQGyelEPcMMwG1ATsN7UvYBPEGOwTJH30ZGQ/NlZwIpS3dDO0m4y6hgFoj9SqDBe1L9DzdC01RaA9ZC2UJ4zpjgU4DIQENIosK3Q05CG0Q8wrJaw3lEUUHOQPVSZoApQcBCxEdNRW1JhBirAsJOXcG+xr2C48mrxMpevwF0xohBk0BKRr/AM8u54WwWjFcHE9fBgMLJSPHFKhQIA0lQLd4SBobBxUlqQKRQ3BKh1E2HpMh9jw9DWYuE1F8B/U8BRlPC4E8nkarRQ4R0j6NPUgiSUwsBDV/LC8niwnPD4UMuXxyAVkJIQmxDHETMREXN8UIOQcZLZckJxUIIUaVYJoE958D8xPRAwsFPwlBBxMDtRwtEy4VKQUNgSTXAvM21S6zAo9WgAEXBcsPJR/fEFBH4A7pCJsCZQODJesALRUhABcimwhDYwBfj9hTBS7LCMdqbCN0A2cU52ERcweRDlcHpxwzFb8c4XDIXguGCCijrwlbAXUJmQFfBOMICTVbjKAgQWdTi1gYmyBhQT9d/AIxDGUVn0S9h3gCiw9rEhsBNQFzBzkNAQJ3Ee0RaxCVCOuGBDW1M/g6JQRPIYMgEQonA09szgsnJvkM+GkBoxJiAww0PXfuZ6tgtiQX/QcZMsVBYCHxC5JPzQycGsEYQlQuGeQHvwPzGvMn6kFXBf8DowMTOk0z7gS9C2kIiwk/AEkOoxcH1xhqCnGM0AExiwG3mQNXkYMCb48GNwcLAGcLhwV55QAdAqcIowAFAM8DVwA5Aq0HnQAZAIVBAT0DJy8BIeUCjwOTCDHLAZUvAfMpBBvDDBUA9zduSgLDsQKAamaiBd1YAo4CSTUBTSUEBU5HUQOvceEA2wBLBhPfRwEVq0rLGuNDAd9vKwDHAPsABTUHBUEBzQHzbQC3AV8LMQmis7UBTekpAIMAFWsB1wKJAN0ANQB/8QFTAE0FWfkF0wJPSQERMRgrV2EBuwMfATMBDQB5BsuNpckHHwRtB9MCEBsV4QLvLge1AQMi3xPNQsUCvd5VoWACZIECYkJbTa9bNyACofcCaJgCZgkCn4Q4GwsCZjsCZiYEbgR/A38TA36SOQY5dxc5gjojIwJsHQIyNjgKAm3HAm2u74ozZ0UrAWcA3gDhAEoFB5gMjQD+C8IADbUCdy8CdqI/AnlLQwJ4uh1c20WuRtcCfD8CesgCfQkCfPAFWQUgSABIfWMkAoFtAoAAAoAFAn+uSVhKWxUXSswC0QEC0MxLJwOITwOH5kTFkTIC8qFdAwMDrkvOTC0lA89NTE2vAos/AorYwRsHHUNnBbcCjjcCjlxAl4ECjtkCjlx4UbRTNQpS1FSFApP7ApMMAOkAHFUeVa9V0AYsGymVhjLheGZFOzkCl58C77JYIagAWSUClo8ClnycAKlZrFoJgU0AOwKWtQKWTlxEXNECmcsCmWRcyl0HGQKcmznCOp0CnBYCn5sCnriKAB0PMSoPAp3xAp6SALU9YTRh7wKe0wKgbgGpAp6fHwKeTqVjyGQnJSsCJ68CJn4CoPsCoEwCot0CocQCpi8Cpc4Cp/8AfQKn8mh8aLEAA0lqHGrRAqzjAqyuAq1nAq0CAlcdAlXcArHh1wMfTmyXArK9DQKy6Bds4G1jbUhfAyXNArZcOz9ukAMpRQK4XgK5RxUCuSp3cDZw4QK9GQK72nCWAzIRAr6IcgIDM3ECvhpzInNPAsPLAsMEc4J0SzVFdOADPKcDPJoDPb8CxXwCxkcCxhCJAshpUQLIRALJTwLJLgJknQLd0nh5YXiueSVL0AMYo2cCAmH0GfOVJHsLXpJeuxECz2sCz2wvS1PS8xOfAMatAs9zASnqA04SfksFAtwnAtuKAtJPA1JcA1NfAQEDVYyAiT8AyxbtYEWCHILTgs6DjQLaxwLZ3oQQhEmnPAOGpQAvA2QOhnFZ+QBVAt9lAt64c3cC4i/tFAHzMCcB9JsB8tKHAuvzAulweQLq+QLq5AD5RwG5Au6JAuuclqqXAwLuPwOF4Jh5cOBxoQLzAwBpA44WmZMC9xMDkW4DkocC95gC+dkC+GaaHJqruzebHgOdgwL++gEbADmfHJ+zAwWNA6ZqA6bZANHFAwZqoYiiBQkDDEkCwAA/AwDhQRdTARHzA2sHl2cFAJMtK7evvdsBiZkUfxEEOQH7KQUhDp0JnwCS/SlXxQL3AZ0AtwW5AG8LbUEuFCaNLgFDAYD8AbUmAHUDDgRtACwCFgyhAAAKAj0CagPdA34EkQEgRQUhfAoABQBEABMANhICdwEABdUDa+8KxQIA9wqfJ7+xt+UBkSFBQgHpFH8RNMCJAAQAGwBaAkUChIsABjpTOpSNbQC4Oo860ACNOME63AClAOgAywE6gTo7Ofw5+Tt2iTpbO56JOm85GAFWATMBbAUvNV01njWtNWY1dTW2NcU1gjWRNdI14TWeNa017jX9NbI1wTYCNhE1xjXVNhY2JzXeNe02LjY9Ni41LSE2OjY9Njw2yTcIBJA8VzY4Nt03IDcPNsogN4k3MAoEsDxnNiQ3GTdsOo03IULUQwdC4EMLHA8PCZsobShRVQYA6X8A6bABFCnXAukBowC9BbcAbwNzBL8MDAMMAQgDAAkKCwsLCQoGBAVVBI/DvwDz9b29kaUCb0QtsRTNLt4eGBcSHAMZFhYZEhYEARAEBUEcQRxBHEEcQRxBHEEaQRxBHEFCSTxBPElISUhBNkM2QTYbNklISVmBVIgBFLWZAu0BhQCjBcEAbykBvwGJAaQcEZ0ePCklMAAhMvAIMAL54gC7Bm8EescjzQMpARQpKgDUABavAj626xQAJP0A3etzuf4NNRA7efy2Z9NQrCnC0OSyANz5BBIbJ5IFDR6miIavYS6tprjjmuKebxm5C74Q225X1pkaYYPb6f1DK4k3xMEBb9S2WMjEibTNWhsRJIA+vwNVEiXTE5iXs/wezV66oFLfp9NZGYW+Gk19J2+bCT6Ye2w6LDYdgzKMUabk595eLBCXANz9HUpWbATq9vqXVx9XDg+Pc9Xp4+bsS005SVM/BJBM4687WUuf+Uj9dEi8aDNaPxtpbDxcG1THTImUMZq4UCaaNYpsVqraNyKLJXDYsFZ/5jl7bLRtO88t7P3xZaAxhb5OdPMXqsSkp1WCieG8jXm1U99+blvLlXzPCS+M93VnJCiK+09LfaSaBAVBomyDgJua8dfUzR7ga34IvR2Nvj+A9heJ6lsl1KG4NkI1032Cnff1m1wof2B9oHJK4bi6JkEdSqeNeiuo6QoZZincoc73/TH9SXF8sCE7XyuYyW8WSgbGFCjPV0ihLKhdPs08Tx82fYAkLLc4I2wdl4apY7GU5lHRFzRWJep7Ww3wbeA3qmd59/86P4xuNaqDpygXt6M85glSBHOCGgJDnt+pN9bK7HApMguX6+06RZNjzVmcZJ+wcUrJ9//bpRNxNuKpNl9uFds+S9tdx7LaM5ZkIrPj6nIU9mnbFtVbs9s/uLgl8MVczAwet+iOEzzBlYW7RCMgE6gyNLeq6+1tIx4dpgZnd0DksJS5f+JNDpwwcPNXaaVspq1fbQajOrJgK0ofKtJ1Ne90L6VO4MOl5S886p7u6xo7OLjG8TGL+HU1JXGJgppg4nNbNJ5nlzSpuPYy21JUEcUA94PoFiZfjZue+QnyQ80ekOuZVkxx4g+cvhJfHgNl4hy1/a6+RKcKlar/J29y//EztlbVPHVUeQ1zX86eQVAjR/M3dA9w4W8LfaXp4EgM85wOWasli837PzVMOnsLzR+k3o75/lRPAJSE1xAKQzEi5v10ke+VBvRt1cwQRMd+U5mLCTGVd6XiZtgBG5cDi0w22GKcVNvHiu5LQbZEDVtz0onn7k5+heuKXVsZtSzilkLRAUmjMXEMB3J9YC50XBxPiz53SC+EhnPl9WsKCv92SM/OFFIMJZYfl0WW8tIO3UxYcwdMAj7FSmgrsZ2aAZO03BOhP1bNNZItyXYQFTpC3SG1VuPDqH9GkiCDmE+JwxyIVSO5siDErAOpEXFgjy6PQtOVDj+s6e1r8heWVvmZnTciuf4EiNZzCAd7SOMhXERIOlsHIMG399i9aLTy3m2hRLZjJVDNLS53iGIK11dPqQt0zBDyg6qc7YqkDm2M5Ve6dCWCaCbTXX2rToaIgz6+zh4lYUi/+6nqcFMAkQJKHYLK0wYk5N9szV6xihDbDDFr45lN1K4aCXBq/FitPSud9gLt5ZVn+ZqGX7cwm2z5EGMgfFpIFyhGGuDPmso6TItTMwny+7uPnLCf4W6goFQFV0oQSsc9VfMmVLcLr6ZetDZbaSFTLqnSO/bIPjA3/zAUoqgGFAEQS4IhuMzEp2I3jJzbzkk/IEmyax+rhZTwd6f+CGtwPixu8IvzACquPWPREu9ZvGkUzpRwvRRuaNN6cr0W1wWits9ICdYJ7ltbgMiSL3sTPeufgNcVqMVWFkCPDH4jG2jA0XcVgQj62Cb29v9f/z/+2KbYvIv/zzjpQAPkliaVDzNrW57TZ/ZOyZD0nlfMmAIBIAGAI0D3k/mdN4xr9v85ZbZbbqfH2jGd5hUqNZWwl5SPfoGmfElmazUIeNL1j/mkF7VNAzTq4jNt8JoQ11NQOcmhprXoxSxfRGJ9LDEOAQ+dmxAQH90iti9e2u/MoeuaGcDTHoC+xsmEeWmxEKefQuIzHbpw5Tc5cEocboAD09oipWQhtTO1wivf/O+DRe2rpl/E9wlrzBorjJsOeG1B/XPW4EaJEFdNlECEZga5ZoGRHXgYouGRuVkm8tDESiEyFNo+3s5M5puSdTyUL2llnINVHEt91XUNW4ewdMgJ4boJfEyt/iY5WXqbA+A2Fkt5Z0lutiWhe9nZIyIUjyXDC3UsaG1t+eNx6z4W/OYoTB7A6x+dNSTOi9AInctbESqm5gvOLww7OWXPrmHwVZasrl4eD113pm+JtT7JVOvnCXqdzzdTRHgJ0PiGTFYW5Gvt9R9LD6Lzfs0v/TZZHSmyVNq7viIHE6DBK7Qp07Iz55EM8SYtQvZf/obBniTWi5C2/ovHfw4VndkE5XYdjOhCMRjDeOEfXeN/CwfGduiUIfsoFeUxXeQXba7c7972XNv8w+dTjjUM0QeNAReW+J014dKAD/McQYXT7c0GQPIkn3Ll6R7gGjuiQoZD0TEeEqQpKoZ15g/0OPQI17QiSv9AUROa/V/TQN3dvLArec3RrsYlvBm1b8LWzltdugsC50lNKYLEp2a+ZZYqPejULRlOJh5zj/LVMyTDvwKhMxxwuDkxJ1QpoNI0OTWLom4Z71SNzI9TV1iXJrIu9Wcnd+MCaAw8o1jSXd94YU/1gnkrC9BUEOtQvEIQ7g0i6h+KL2JKk8Ydl7HruvgWMSAmNe+LshGhV4qnWHhO9/RIPQzY1tHRj2VqOyNsDpK0cww+56AdDC4gsWwY0XxoucIWIqs/GcwnWqlaT0KPr8mbK5U94/301i1WLt4YINTVvCFBrFZbIbY8eycOdeJ2teD5IfPLCRg7jjcFTwlMFNl9zdh/o3E/hHPwj7BWg0MU09pPrBLbrCgm54A6H+I6v27+jL5gkjWg/iYdks9jbfVP5y/n0dlgWEMlKasl7JvFZd56LfybW1eeaVO0gxTfXZwD8G4SI116yx7UKVRgui6Ya1YpixqXeNLc8IxtAwCU5IhwQgn+NqHnRaDv61CxKhOq4pOX7M6pkA+Pmpd4j1vn6ACUALoLLc4vpXci8VidLxzm7qFBe7s+quuJs6ETYmnpgS3LwSZxPIltgBDXz8M1k/W2ySNv2f9/NPhxLGK2D21dkHeSGmenRT3Yqcdl0m/h3OYr8V+lXNYGf8aCCpd4bWjE4QIPj7vUKN4Nrfs7ML6Y2OyS830JCnofg/k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g"; +const S0 = 44032; +const L0 = 4352; +const V0 = 4449; +const T0 = 4519; +const L_COUNT = 19; +const V_COUNT = 21; +const T_COUNT = 28; +const N_COUNT = V_COUNT * T_COUNT; +const S_COUNT = L_COUNT * N_COUNT; +const S1 = S0 + S_COUNT; +const L1 = L0 + L_COUNT; +const V1 = V0 + V_COUNT; +const T1$1 = T0 + T_COUNT; +function unpack_cc(packed) { + return packed >> 24 & 255; +} +function unpack_cp(packed) { + return packed & 16777215; +} +let SHIFTED_RANK, EXCLUSIONS, DECOMP, RECOMP; +function init$1() { + let r2 = read_compressed_payload(COMPRESSED); + SHIFTED_RANK = new Map(read_sorted_arrays(r2).flatMap((v3, i) => v3.map((x2) => [x2, i + 1 << 24]))); + EXCLUSIONS = new Set(read_sorted(r2)); + DECOMP = /* @__PURE__ */ new Map(); + RECOMP = /* @__PURE__ */ new Map(); + for (let [cp, cps] of read_mapped(r2)) { + if (!EXCLUSIONS.has(cp) && cps.length == 2) { + let [a2, b2] = cps; + let bucket = RECOMP.get(a2); + if (!bucket) { + bucket = /* @__PURE__ */ new Map(); + RECOMP.set(a2, bucket); + } + bucket.set(b2, cp); + } + DECOMP.set(cp, cps.reverse()); } -}; -var signature = /* @__PURE__ */ Object.freeze({ - __proto__: null, - SignatureType: SignatureType$1, - SignaturePartType, - SignaturePartTypeLength, - isUnrecoveredNode, - isUnrecoveredNestedLeaf, - isUnrecoveredSignatureLeaf, - decodeSignatureTree, - InvalidSignatureLeafError, - recoverTopology, - partEncoder, - encodeSigners, - encodeTree, - deepestConfigOfSignature, - isUnrecoveredSignature, - isUnrecoveredChainedSignature, - isSignature, - isChainedSignature, - decodeSignature, - decodeSignatureBody, - decodeChainedSignature, - setImageHashStruct, - recoverSignature, - encodeChain, - encodeSignature, - encodeSignatureBody, - encodeSignatureTree, - signaturesOf, - signaturesOfDecoded, - subdigestsOfDecoded, - trimSignature, - trimUnrecoveredTree, - SignatureCoder -}); -function isSignerLeaf(leaf) { - return leaf.address !== void 0 && leaf.weight !== void 0; } -function isSubdigestLeaf(leaf) { - return leaf.subdigest !== void 0 && leaf.address === void 0; +function is_hangul(cp) { + return cp >= S0 && cp < S1; } -function topologyToJSON(tree) { - if (isNode$1(tree)) { - return JSON.stringify({ - left: topologyToJSON(tree.left), - right: topologyToJSON(tree.right) - }); +function compose_pair(a2, b2) { + if (a2 >= L0 && a2 < L1 && b2 >= V0 && b2 < V1) { + return S0 + (a2 - L0) * N_COUNT + (b2 - V0) * T_COUNT; + } else if (is_hangul(a2) && b2 > T0 && b2 < T1$1 && (a2 - S0) % T_COUNT == 0) { + return a2 + (b2 - T0); + } else { + let recomp = RECOMP.get(a2); + if (recomp) { + recomp = recomp.get(b2); + if (recomp) { + return recomp; + } + } + return -1; } - if (isNestedLeaf(tree)) { - return JSON.stringify({ - weight: BigInt(tree.weight).toString(), - threshold: BigInt(tree.threshold).toString(), - tree: topologyToJSON(tree.tree) - }); +} +function decomposed(cps) { + if (!SHIFTED_RANK) init$1(); + let ret = []; + let buf = []; + let check_order = false; + function add2(cp) { + let cc2 = SHIFTED_RANK.get(cp); + if (cc2) { + check_order = true; + cp |= cc2; + } + ret.push(cp); } - if (isSignerLeaf(tree)) { - return JSON.stringify({ - address: tree.address, - weight: BigInt(tree.weight).toString() - }); + for (let cp of cps) { + while (true) { + if (cp < 128) { + ret.push(cp); + } else if (is_hangul(cp)) { + let s_index = cp - S0; + let l_index = s_index / N_COUNT | 0; + let v_index = s_index % N_COUNT / T_COUNT | 0; + let t_index = s_index % T_COUNT; + add2(L0 + l_index); + add2(V0 + v_index); + if (t_index > 0) add2(T0 + t_index); + } else { + let mapped = DECOMP.get(cp); + if (mapped) { + buf.push(...mapped); + } else { + add2(cp); + } + } + if (!buf.length) break; + cp = buf.pop(); + } } - return JSON.stringify(tree); -} -function topologyFromJSON(json) { - const parsed = typeof json === "string" ? JSON.parse(json) : json; - if (parsed.left !== void 0 && parsed.right !== void 0) { - return { - left: topologyFromJSON(parsed.left), - right: topologyFromJSON(parsed.right) - }; + if (check_order && ret.length > 1) { + let prev_cc = unpack_cc(ret[0]); + for (let i = 1; i < ret.length; i++) { + let cc2 = unpack_cc(ret[i]); + if (cc2 == 0 || prev_cc <= cc2) { + prev_cc = cc2; + continue; + } + let j2 = i - 1; + while (true) { + let tmp = ret[j2 + 1]; + ret[j2 + 1] = ret[j2]; + ret[j2] = tmp; + if (!j2) break; + prev_cc = unpack_cc(ret[--j2]); + if (prev_cc <= cc2) break; + } + prev_cc = unpack_cc(ret[i]); + } } - if (parsed.weight !== void 0 && parsed.threshold !== void 0 && parsed.tree !== void 0) { - return { - weight: BigInt(parsed.weight), - threshold: BigInt(parsed.threshold), - tree: topologyFromJSON(parsed.tree) - }; + return ret; +} +function composed_from_decomposed(v3) { + let ret = []; + let stack = []; + let prev_cp = -1; + let prev_cc = 0; + for (let packed of v3) { + let cc2 = unpack_cc(packed); + let cp = unpack_cp(packed); + if (prev_cp == -1) { + if (cc2 == 0) { + prev_cp = cp; + } else { + ret.push(cp); + } + } else if (prev_cc > 0 && prev_cc >= cc2) { + if (cc2 == 0) { + ret.push(prev_cp, ...stack); + stack.length = 0; + prev_cp = cp; + } else { + stack.push(cp); + } + prev_cc = cc2; + } else { + let composed = compose_pair(prev_cp, cp); + if (composed >= 0) { + prev_cp = composed; + } else if (prev_cc == 0 && cc2 == 0) { + ret.push(prev_cp); + prev_cp = cp; + } else { + stack.push(cp); + prev_cc = cc2; + } + } } - if (parsed.address !== void 0 && parsed.weight !== void 0) { - return { - address: parsed.address, - weight: BigInt(parsed.weight) - }; + if (prev_cp >= 0) { + ret.push(prev_cp, ...stack); } - return parsed; + return ret; } -function isNestedLeaf(leaf) { - return leaf.tree !== void 0 && leaf.weight !== void 0 && leaf.threshold !== void 0; +function nfd(cps) { + return decomposed(cps).map(unpack_cp); } -function isNodeLeaf(leaf) { - return leaf.nodeHash !== void 0; +function nfc(cps) { + return composed_from_decomposed(decomposed(cps)); } -function isLeaf$1(leaf) { - return isSignerLeaf(leaf) || isSubdigestLeaf(leaf) || isNestedLeaf(leaf) || isNodeLeaf(leaf); +const HYPHEN = 45; +const STOP_CH = "."; +const FE0F = 65039; +const UNIQUE_PH = 1; +const Array_from = (x2) => Array.from(x2); +function group_has_cp(g2, cp) { + return g2.P.has(cp) || g2.Q.has(cp); } -function isNode$1(node) { - return node.left !== void 0 && node.right !== void 0; +class Emoji extends Array { + get is_emoji() { + return true; + } + // free tagging system } -function isTopology(topology) { - return isNode$1(topology) || isLeaf$1(topology); +let MAPPED, IGNORED, CM, NSM, ESCAPE, GROUPS, WHOLE_VALID, WHOLE_MAP, VALID, EMOJI_LIST, EMOJI_ROOT; +function init() { + if (MAPPED) return; + let r2 = read_compressed_payload(COMPRESSED$1); + const read_sorted_array = () => read_sorted(r2); + const read_sorted_set = () => new Set(read_sorted_array()); + const set_add_many = (set, v3) => v3.forEach((x2) => set.add(x2)); + MAPPED = new Map(read_mapped(r2)); + IGNORED = read_sorted_set(); + CM = read_sorted_array(); + NSM = new Set(read_sorted_array().map((i) => CM[i])); + CM = new Set(CM); + ESCAPE = read_sorted_set(); + read_sorted_set(); + let chunks = read_sorted_arrays(r2); + let unrestricted = r2(); + const read_chunked = () => { + let set = /* @__PURE__ */ new Set(); + read_sorted_array().forEach((i) => set_add_many(set, chunks[i])); + set_add_many(set, read_sorted_array()); + return set; + }; + GROUPS = read_array_while((i) => { + let N2 = read_array_while(r2).map((x2) => x2 + 96); + if (N2.length) { + let R2 = i >= unrestricted; + N2[0] -= 32; + N2 = str_from_cps(N2); + if (R2) N2 = `Restricted[${N2}]`; + let P2 = read_chunked(); + let Q2 = read_chunked(); + let M2 = !r2(); + return { N: N2, P: P2, Q: Q2, M: M2, R: R2 }; + } + }); + WHOLE_VALID = read_sorted_set(); + WHOLE_MAP = /* @__PURE__ */ new Map(); + let wholes = read_sorted_array().concat(Array_from(WHOLE_VALID)).sort((a2, b2) => a2 - b2); + wholes.forEach((cp, i) => { + let d2 = r2(); + let w2 = wholes[i] = d2 ? wholes[i - d2] : { V: [], M: /* @__PURE__ */ new Map() }; + w2.V.push(cp); + if (!WHOLE_VALID.has(cp)) { + WHOLE_MAP.set(cp, w2); + } + }); + for (let { V: V2, M: M2 } of new Set(WHOLE_MAP.values())) { + let recs = []; + for (let cp of V2) { + let gs = GROUPS.filter((g2) => group_has_cp(g2, cp)); + let rec = recs.find(({ G: G2 }) => gs.some((g2) => G2.has(g2))); + if (!rec) { + rec = { G: /* @__PURE__ */ new Set(), V: [] }; + recs.push(rec); + } + rec.V.push(cp); + set_add_many(rec.G, gs); + } + let union = recs.flatMap((x2) => Array_from(x2.G)); + for (let { G: G2, V: V3 } of recs) { + let complement = new Set(union.filter((g2) => !G2.has(g2))); + for (let cp of V3) { + M2.set(cp, complement); + } + } + } + VALID = /* @__PURE__ */ new Set(); + let multi = /* @__PURE__ */ new Set(); + const add_to_union = (cp) => VALID.has(cp) ? multi.add(cp) : VALID.add(cp); + for (let g2 of GROUPS) { + for (let cp of g2.P) add_to_union(cp); + for (let cp of g2.Q) add_to_union(cp); + } + for (let cp of VALID) { + if (!WHOLE_MAP.has(cp) && !multi.has(cp)) { + WHOLE_MAP.set(cp, UNIQUE_PH); + } + } + set_add_many(VALID, nfd(VALID)); + EMOJI_LIST = read_trie(r2).map((v3) => Emoji.from(v3)).sort(compare_arrays); + EMOJI_ROOT = /* @__PURE__ */ new Map(); + for (let cps of EMOJI_LIST) { + let prev = [EMOJI_ROOT]; + for (let cp of cps) { + let next = prev.map((node) => { + let child = node.get(cp); + if (!child) { + child = /* @__PURE__ */ new Map(); + node.set(cp, child); + } + return child; + }); + if (cp === FE0F) { + prev.push(...next); + } else { + prev = next; + } + } + for (let x2 of prev) { + x2.V = cps; + } + } } -function encodeSignerLeaf(leaf) { - return solidityPacked(["uint96", "address"], [leaf.weight, leaf.address]); +function quoted_cp(cp) { + return (should_escape(cp) ? "" : `${bidi_qq(safe_str_from_cps([cp]))} `) + quote_cp(cp); } -function decodeSignerLeaf(encoded) { - const bytes2 = getBytes(encoded); - if (bytes2.length !== 32) { - throw new Error("Invalid encoded string length"); - } - const weight = BigInt(hexlify(bytes2.slice(0, 12))); - const address = getAddress$1(hexlify(bytes2.slice(12))); - return { - weight, - address - }; +function bidi_qq(s2) { + return `"${s2}"‎`; } -function isEncodedSignerLeaf(encoded) { - const bytes2 = getBytes(encoded); - if (bytes2.length !== 32) { - return false; +function check_label_extension(cps) { + if (cps.length >= 4 && cps[2] == HYPHEN && cps[3] == HYPHEN) { + throw new Error(`invalid label extension: "${str_from_cps(cps.slice(0, 4))}"`); } - const prefix = bytes2.slice(0, 11); - return prefix.every((byte) => byte === 0); } -function hashNode(node) { - if (isSignerLeaf(node)) { - return encodeSignerLeaf(node); +function check_leading_underscore(cps) { + const UNDERSCORE = 95; + for (let i = cps.lastIndexOf(UNDERSCORE); i > 0; ) { + if (cps[--i] !== UNDERSCORE) { + throw new Error("underscore allowed only at start"); + } } - if (isSubdigestLeaf(node)) { - return solidityPackedKeccak256(["string", "bytes32"], ["Sequence static digest:\n", node.subdigest]); +} +function check_fenced(cps) { + let cp = cps[0]; + let prev = FENCED.get(cp); + if (prev) throw error_placement(`leading ${prev}`); + let n2 = cps.length; + let last = -1; + for (let i = 1; i < n2; i++) { + cp = cps[i]; + let match = FENCED.get(cp); + if (match) { + if (last == i) throw error_placement(`${prev} + ${match}`); + last = i + 1; + prev = match; + } } - if (isNestedLeaf(node)) { - const nested = hashNode(node.tree); - return solidityPackedKeccak256(["string", "bytes32", "uint256", "uint256"], ["Sequence nested config:\n", nested, node.threshold, node.weight]); + if (last == n2) throw error_placement(`trailing ${prev}`); +} +function safe_str_from_cps(cps, max2 = Infinity, quoter = quote_cp) { + let buf = []; + if (is_combining_mark(cps[0])) buf.push("◌"); + if (cps.length > max2) { + max2 >>= 1; + cps = [...cps.slice(0, max2), 8230, ...cps.slice(-max2)]; } - if (isNodeLeaf(node)) { - return node.nodeHash; + let prev = 0; + let n2 = cps.length; + for (let i = 0; i < n2; i++) { + let cp = cps[i]; + if (should_escape(cp)) { + buf.push(str_from_cps(cps.slice(prev, i))); + buf.push(quoter(cp)); + prev = i + 1; + } } - return solidityPackedKeccak256(["bytes32", "bytes32"], [hashNode(node.left), hashNode(node.right)]); + buf.push(str_from_cps(cps.slice(prev, n2))); + return buf.join(""); } -function leftFace(topology) { - const stack = []; - let prev = topology; - while (!isLeaf$1(prev)) { - stack.unshift(prev.right); - prev = prev.left; - } - stack.unshift(prev); - return stack; +function is_combining_mark(cp) { + init(); + return CM.has(cp); } -function isWalletConfig(config2) { - return config2.threshold !== void 0 && config2.checkpoint !== void 0 && config2.tree !== void 0 && config2.version !== void 0 && config2.version === 2; +function should_escape(cp) { + init(); + return ESCAPE.has(cp); } -function imageHash(config2) { - return solidityPackedKeccak256(["bytes32", "uint256"], [solidityPackedKeccak256(["bytes32", "uint256"], [hashNode(config2.tree), config2.threshold]), config2.checkpoint]); +function ens_normalize(name2) { + return flatten(split(name2, nfc, filter_fe0f)); } -function isSimpleNestedMember(member) { - return member.threshold !== void 0 && member.weight !== void 0 && member.members !== void 0; +function split(name2, nf2, ef2) { + if (!name2) return []; + init(); + let offset2 = 0; + return name2.split(STOP_CH).map((label) => { + let input2 = explode_cp(label); + let info = { + input: input2, + offset: offset2 + // codepoint, not substring! + }; + offset2 += input2.length + 1; + try { + let tokens = info.tokens = tokens_from_str(input2, nf2, ef2); + let token_count = tokens.length; + let type; + if (!token_count) { + throw new Error(`empty label`); + } + let norm2 = info.output = tokens.flat(); + check_leading_underscore(norm2); + let emoji = info.emoji = token_count > 1 || tokens[0].is_emoji; + if (!emoji && norm2.every((cp) => cp < 128)) { + check_label_extension(norm2); + type = "ASCII"; + } else { + let chars = tokens.flatMap((x2) => x2.is_emoji ? [] : x2); + if (!chars.length) { + type = "Emoji"; + } else { + if (CM.has(norm2[0])) throw error_placement("leading combining mark"); + for (let i = 1; i < token_count; i++) { + let cps = tokens[i]; + if (!cps.is_emoji && CM.has(cps[0])) { + throw error_placement(`emoji + combining mark: "${str_from_cps(tokens[i - 1])} + ${safe_str_from_cps([cps[0]])}"`); + } + } + check_fenced(norm2); + let unique = Array_from(new Set(chars)); + let [g2] = determine_group(unique); + check_group(g2, chars); + check_whole(g2, unique); + type = g2.N; + } + } + info.type = type; + } catch (err) { + info.error = err; + } + return info; + }); } -function topologyToMembers(tree) { - if (isSignerLeaf(tree) || isSubdigestLeaf(tree)) { - return [tree]; - } - if (isNestedLeaf(tree)) { - return [{ - threshold: tree.threshold, - weight: tree.weight, - members: topologyToMembers(tree.tree) - }]; +function check_whole(group, unique) { + let maker; + let shared = []; + for (let cp of unique) { + let whole = WHOLE_MAP.get(cp); + if (whole === UNIQUE_PH) return; + if (whole) { + let set = whole.M.get(cp); + maker = maker ? maker.filter((g2) => set.has(g2)) : Array_from(set); + if (!maker.length) return; + } else { + shared.push(cp); + } } - if (isNodeLeaf(tree)) { - return []; + if (maker) { + for (let g2 of maker) { + if (shared.every((cp) => group_has_cp(g2, cp))) { + throw new Error(`whole-script confusable: ${group.N}/${g2.N}`); + } + } } - return [...topologyToMembers(tree.left), ...topologyToMembers(tree.right)]; } -function hasUnknownNodes(tree) { - if (isNodeLeaf(tree)) { - return true; +function determine_group(unique) { + let groups = GROUPS; + for (let cp of unique) { + let gs = groups.filter((g2) => group_has_cp(g2, cp)); + if (!gs.length) { + if (!GROUPS.some((g2) => group_has_cp(g2, cp))) { + throw error_disallowed(cp); + } else { + throw error_group_member(groups[0], cp); + } + } + groups = gs; + if (gs.length == 1) break; } - if (isNode$1(tree)) { - return hasUnknownNodes(tree.left) || hasUnknownNodes(tree.right); + return groups; +} +function flatten(split2) { + return split2.map(({ input: input2, error, output: output2 }) => { + if (error) { + let msg = error.message; + throw new Error(split2.length == 1 ? msg : `Invalid label ${bidi_qq(safe_str_from_cps(input2, 63))}: ${msg}`); + } + return str_from_cps(output2); + }).join(STOP_CH); +} +function error_disallowed(cp) { + return new Error(`disallowed character: ${quoted_cp(cp)}`); +} +function error_group_member(g2, cp) { + let quoted = quoted_cp(cp); + let gg2 = GROUPS.find((g3) => g3.P.has(cp)); + if (gg2) { + quoted = `${gg2.N} ${quoted}`; } - return false; + return new Error(`illegal mixture: ${g2.N} + ${quoted}`); } -function toSimpleWalletConfig(config2) { - return { - threshold: config2.threshold, - checkpoint: config2.checkpoint, - members: topologyToMembers(config2.tree) - }; +function error_placement(where) { + return new Error(`illegal placement: ${where}`); } -const membersAsTopologies = (members, builder) => { - return members.map((member) => { - if (isSimpleNestedMember(member)) { - return { - tree: builder(member.members), - threshold: member.threshold, - weight: member.weight - }; +function check_group(g2, cps) { + for (let cp of cps) { + if (!group_has_cp(g2, cp)) { + throw error_group_member(g2, cp); + } + } + if (g2.M) { + let decomposed2 = nfd(cps); + for (let i = 1, e2 = decomposed2.length; i < e2; i++) { + if (NSM.has(decomposed2[i])) { + let j2 = i + 1; + for (let cp; j2 < e2 && NSM.has(cp = decomposed2[j2]); j2++) { + for (let k2 = i; k2 < j2; k2++) { + if (decomposed2[k2] == cp) { + throw new Error(`duplicate non-spacing marks: ${quoted_cp(cp)}`); + } + } + } + if (j2 - i > NSM_MAX) { + throw new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(decomposed2.slice(i - 1, j2)))} (${j2 - i}/${NSM_MAX})`); + } + i = j2; + } } - return member; - }); -}; -function legacyTopologyBuilder(members) { - if (members.length === 0) { - throw new Error("Empty members array"); } - const asTopologies = membersAsTopologies(members, legacyTopologyBuilder); - return asTopologies.reduce((acc, member) => { - return { - left: acc, - right: member - }; - }); } -function merkleTopologyBuilder(members) { - if (members.length === 0) { - throw new Error("Empty members array"); - } - const leaves = membersAsTopologies(members, merkleTopologyBuilder); - for (let s2 = leaves.length; s2 > 1; s2 = s2 / 2) { - for (let i = 0; i < s2 / 2; i++) { - const j1 = i * 2; - const j2 = j1 + 1; - if (j2 >= s2) { - leaves[i] = leaves[j1]; +function tokens_from_str(input2, nf2, ef2) { + let ret = []; + let chars = []; + input2 = input2.slice().reverse(); + while (input2.length) { + let emoji = consume_emoji_reversed(input2); + if (emoji) { + if (chars.length) { + ret.push(nf2(chars)); + chars = []; + } + ret.push(ef2(emoji)); + } else { + let cp = input2.pop(); + if (VALID.has(cp)) { + chars.push(cp); } else { - leaves[i] = { - left: leaves[j1], - right: leaves[j2] - }; + let cps = MAPPED.get(cp); + if (cps) { + chars.push(...cps); + } else if (!IGNORED.has(cp)) { + throw error_disallowed(cp); + } } } } - return leaves[0]; + if (chars.length) { + ret.push(nf2(chars)); + } + return ret; } -function optimized2SignersTopologyBuilder(members) { - if (members.length > 8) { - return merkleTopologyBuilder(members); +function filter_fe0f(cps) { + return cps.filter((cp) => cp != FE0F); +} +function consume_emoji_reversed(cps, eaten) { + let node = EMOJI_ROOT; + let emoji; + let pos = cps.length; + while (pos) { + node = node.get(cps[--pos]); + if (!node) break; + let { V: V2 } = node; + if (V2) { + emoji = V2; + cps.length = pos; + } } - return legacyTopologyBuilder(members); + return emoji; } -function toWalletConfig(simpleWalletConfig, builder = optimized2SignersTopologyBuilder) { - return { - version: 2, - threshold: simpleWalletConfig.threshold, - checkpoint: simpleWalletConfig.checkpoint, - tree: builder(simpleWalletConfig.members) - }; +const Zeros = new Uint8Array(32); +Zeros.fill(0); +function checkComponent(comp) { + assertArgument(comp.length !== 0, "invalid ENS name; empty component", "comp", comp); + return comp; } -function hasSubdigest(tree, subdigest) { - if (isSubdigestLeaf(tree)) { - return tree.subdigest === subdigest; +function ensNameSplit(name2) { + const bytes2 = toUtf8Bytes(ensNormalize(name2)); + const comps = []; + if (name2.length === 0) { + return comps; } - if (isNode$1(tree)) { - return hasSubdigest(tree.left, subdigest) || hasSubdigest(tree.right, subdigest); + let last = 0; + for (let i = 0; i < bytes2.length; i++) { + const d2 = bytes2[i]; + if (d2 === 46) { + comps.push(checkComponent(bytes2.slice(last, i))); + last = i + 1; + } } - return false; + assertArgument(last < bytes2.length, "invalid ENS name; empty component", "name", name2); + comps.push(checkComponent(bytes2.slice(last))); + return comps; } -function signersOf(tree) { - const stack = [tree]; - const signers = /* @__PURE__ */ new Set(); - while (stack.length > 0) { - const node = stack.pop(); - if (isNestedLeaf(node)) { - stack.push(node.tree); - } else if (isNode$1(node)) { - stack.push(node.left); - stack.push(node.right); - } else if (isSignerLeaf(node)) { - signers.add({ - address: node.address, - weight: Number(node.weight) - }); +function ensNormalize(name2) { + try { + if (name2.length === 0) { + throw new Error("empty label"); } + return ens_normalize(name2); + } catch (error) { + assertArgument(false, `invalid ENS name (${error.message})`, "name", name2); } - return Array.from(signers); } -function isComplete(tree) { - if (isNode$1(tree)) { - return isComplete(tree.left) && isComplete(tree.right); +function isValidName(name2) { + try { + return ensNameSplit(name2).length !== 0; + } catch (error) { } - return !isNodeLeaf(tree); + return false; } -const ConfigCoder = { - isWalletConfig: (config2) => { - return config2.version === 2 && config2.threshold !== void 0 && config2.tree !== void 0; - }, - imageHashOf: (config2) => { - return imageHash(config2); - }, - hasSubdigest: (config2, subdigest) => { - return hasSubdigest(config2.tree, subdigest); - }, - checkpointOf: (config2) => { - return BigInt(config2.checkpoint); - }, - signersOf: (config2) => { - return signersOf(config2.tree); - }, - fromSimple: (config2) => { - var _config$subdigests; - return toWalletConfig(_extends$c({}, config2, { - members: [...config2.signers, ...((_config$subdigests = config2.subdigests) != null ? _config$subdigests : []).map((subdigest) => ({ - subdigest - }))] - })); - }, - isComplete: (config2) => { - return isComplete(config2.tree); - }, - // isValid = (config: WalletConfig): boolean {} - /** - * - * Notice: context and kind are ignored because v2 - * doesn't need to manually update the implementation before - * a configuration update, it's automatically done by the contract. - * - */ - update: { - isKindUsed: true, - buildTransaction: (wallet, config2, _context, _kind) => { - const module2 = new Interface(walletContracts.mainModuleUpgradable.abi); - return { - entrypoint: wallet, - transactions: [{ - to: wallet, - data: module2.encodeFunctionData(module2.getFunction("updateImageHash"), [ConfigCoder.imageHashOf(config2)]), - gasLimit: 0, - delegateCall: false, - revertOnError: true, - value: 0 - }] - }; - }, - decodeTransaction: function(tx) { - var _tx$transactions$0$va, _tx$transactions$, _tx$transactions$0$ga, _tx$transactions$2; - const module2 = new Interface(walletContracts.mainModuleUpgradable.abi); - if (tx.transactions.length !== 1) { - throw new Error("Invalid transaction bundle, expected 1 transaction"); - } - const data = tx.transactions[0].data; - if (!data) { - throw new Error("Invalid transaction bundle, expected data"); - } - const decoded = module2.decodeFunctionData(module2.getFunction("updateImageHash"), data); - if (!decoded) { - throw new Error("Invalid transaction bundle, expected valid data"); - } - if (tx.transactions[0].to !== tx.entrypoint) { - throw new Error("Invalid transaction bundle, expected to be sent to entrypoint"); - } - if (tx.transactions[0].delegateCall) { - throw new Error("Invalid transaction bundle, expected not to be a delegateCall"); - } - if (!tx.transactions[0].revertOnError) { - throw new Error("Invalid transaction bundle, expected revertOnError"); - } - if (BigInt((_tx$transactions$0$va = (_tx$transactions$ = tx.transactions[0]) == null ? void 0 : _tx$transactions$.value) != null ? _tx$transactions$0$va : 0) !== 0n) { - throw new Error("Invalid transaction bundle, expected value to be 0"); - } - if (BigInt((_tx$transactions$0$ga = (_tx$transactions$2 = tx.transactions[0]) == null ? void 0 : _tx$transactions$2.gasLimit) != null ? _tx$transactions$0$ga : 0) !== 0n) { - throw new Error("Invalid transaction bundle, expected value to be 0"); - } - return { - address: tx.entrypoint, - newImageHash: decoded[0], - kind: void 0 - }; - } - }, - toJSON: function(config2) { - return JSON.stringify({ - version: config2.version, - threshold: BigInt(config2.threshold).toString(), - checkpoint: BigInt(config2.checkpoint).toString(), - tree: topologyToJSON(config2.tree) - }); - }, - fromJSON: function(json) { - const config2 = JSON.parse(json); - return { - version: config2.version, - threshold: BigInt(config2.threshold), - checkpoint: BigInt(config2.checkpoint), - tree: topologyFromJSON(config2.tree) - }; - }, - editConfig: function(config2, action) { - var _action$threshold, _action$checkpoint; - const members = topologyToMembers(config2.tree); - if (action.add) { - for (const signer2 of action.add) { - if (members.find((s2) => isSignerLeaf(s2) && s2.address === signer2.address)) { - continue; - } - members.push({ - address: signer2.address, - weight: signer2.weight - }); - } - } - if (action.remove) { - for (const address of action.remove) { - const index2 = members.findIndex((s2) => isSignerLeaf(s2) && s2.address === address); - if (index2 >= 0) { - members.splice(index2, 1); - } - } - } - return { - version: config2.version, - threshold: (_action$threshold = action.threshold) != null ? _action$threshold : config2.threshold, - checkpoint: (_action$checkpoint = action.checkpoint) != null ? _action$checkpoint : config2.checkpoint, - tree: optimized2SignersTopologyBuilder(members) - }; - }, - buildStubSignature: function(config2, overrides) { - const parts = /* @__PURE__ */ new Map(); - for (const [signer2, signature2] of overrides.entries()) { - parts.set(signer2, { - signature: signature2, - isDynamic: true - }); - const { - encoded, - weight - } = encodeSigners(config2, parts, [], 0); - if (weight >= BigInt(config2.threshold)) { - return encoded; - } - } - const signers = signersOf(config2.tree); - for (const { - address - } of signers.sort(({ - weight: a2 - }, { - weight: b2 - }) => a2 - b2)) { - const signature2 = "0x4e82f02f388a12b5f9d29eaf2452dd040c0ee5804b4e504b4dd64e396c6c781f2c7624195acba242dd825bfd25a290912e3c230841fd55c9a734c4de8d9899451b02"; - parts.set(address, { - signature: signature2, - isDynamic: false - }); - const { - encoded, - weight - } = encodeSigners(config2, parts, [], 0); - if (weight >= BigInt(config2.threshold)) { - return encoded; - } - } - return encodeSigners(config2, parts, [], 0).encoded; +function namehash(name2) { + assertArgument(typeof name2 === "string", "invalid ENS name; not a string", "name", name2); + assertArgument(name2.length, `invalid ENS name (empty label)`, "name", name2); + let result = Zeros; + const comps = ensNameSplit(name2); + while (comps.length) { + result = keccak256(concat([result, keccak256(comps.pop())])); } -}; -var config = /* @__PURE__ */ Object.freeze({ - __proto__: null, - isSignerLeaf, - isSubdigestLeaf, - topologyToJSON, - topologyFromJSON, - isNestedLeaf, - isNodeLeaf, - isLeaf: isLeaf$1, - isNode: isNode$1, - isTopology, - encodeSignerLeaf, - decodeSignerLeaf, - isEncodedSignerLeaf, - hashNode, - leftFace, - isWalletConfig, - imageHash, - isSimpleNestedMember, - topologyToMembers, - hasUnknownNodes, - toSimpleWalletConfig, - legacyTopologyBuilder, - merkleTopologyBuilder, - optimized2SignersTopologyBuilder, - toWalletConfig, - hasSubdigest, - signersOf, - isComplete, - ConfigCoder -}); -var context$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null -}); -const coders = { - config: ConfigCoder, - signature: SignatureCoder -}; -const version$7 = 2; -const DeployedWalletContext = { - version: version$7, - factory: "0xFaA5c0b14d1bED5C888Ca655B9a8A5911F78eF4A", - guestModule: "0xfea230Ee243f88BC698dD8f1aE93F8301B6cdfaE", - mainModule: "0xfBf8f1A5E00034762D928f46d438B947f5d4065d", - mainModuleUpgradable: "0x4222dcA3974E39A8b41c411FeDDE9b09Ae14b911", - walletCreationCode: "0x603a600e3d39601a805130553df3363d3d373d3d3d363d30545af43d82803e903d91601857fd5bf3" -}; -var v2 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - config, - signature, - context: context$1, - chained, - coders, - version: version$7, - DeployedWalletContext -}); -function addressOf(context2, imageHash2) { - const codeHash = keccak256$1(solidityPacked(["bytes", "bytes32"], [context2.walletCreationCode, zeroPadValue(context2.mainModule, 32)])); - const hash2 = keccak256$1(solidityPacked(["bytes1", "address", "bytes32", "bytes32"], ["0xff", context2.factory, imageHash2, codeHash])); - return getAddress$1(dataSlice(hash2, 12)); + return hexlify(result); } -async function isValidCounterfactual(wallet, digest, signature2, chainId, provider2, contexts) { - const res = await Promise.all(allVersions.map(async (version2) => { - try { - const decoded = version2.signature.SignatureCoder.decode(hexlify(signature2)); - const recovered1 = await version2.signature.SignatureCoder.recover(decoded, { - address: wallet, - digest: hexlify(digest), - chainId - }, provider2); - const imageHash2 = version2.config.ConfigCoder.imageHashOf(recovered1.config); - const counterfactualAddress = addressOf(contexts[version2.version], imageHash2); - if (counterfactualAddress.toLowerCase() === wallet.toLowerCase()) { - return true; +function dnsEncode(name2, _maxLength) { + const length = _maxLength != null ? _maxLength : 63; + assertArgument(length <= 255, "DNS encoded label cannot exceed 255", "length", length); + return hexlify(concat(ensNameSplit(name2).map((comp) => { + assertArgument(comp.length <= length, `label ${JSON.stringify(name2)} exceeds ${length} bytes`, "name", name2); + const bytes2 = new Uint8Array(comp.length + 1); + bytes2.set(comp, 1); + bytes2[0] = bytes2.length - 1; + return bytes2; + }))) + "00"; +} +function accessSetify(addr, storageKeys) { + return { + address: getAddress(addr), + storageKeys: storageKeys.map((storageKey2, index2) => { + assertArgument(isHexString(storageKey2, 32), "invalid slot", `storageKeys[${index2}]`, storageKey2); + return storageKey2.toLowerCase(); + }) + }; +} +function accessListify(value) { + if (Array.isArray(value)) { + return value.map((set, index2) => { + if (Array.isArray(set)) { + assertArgument(set.length === 2, "invalid slot set", `value[${index2}]`, set); + return accessSetify(set[0], set[1]); } - const recovered2 = await version2.signature.SignatureCoder.recover(decoded, { - address: wallet, - digest: hexlify(digest), - chainId - }, provider2); - const imageHash22 = version2.config.ConfigCoder.imageHashOf(recovered2.config); - const counterfactualAddress2 = addressOf(contexts[version2.version], imageHash22); - return counterfactualAddress2.toLowerCase() === wallet.toLowerCase(); - } catch (_unused) { - } - return false; - })); - return res.some((r2) => r2); + assertArgument(set != null && typeof set === "object", "invalid address-slot set", "value", value); + return accessSetify(set.address, set.storageKeys); + }); + } + assertArgument(value != null && typeof value === "object", "invalid access list", "value", value); + const result = Object.keys(value).map((addr) => { + const storageKeys = value[addr].reduce((accum, storageKey2) => { + accum[storageKey2] = true; + return accum; + }, {}); + return accessSetify(addr, Object.keys(storageKeys).sort()); + }); + result.sort((a2, b2) => a2.address.localeCompare(b2.address)); + return result; } -function isValidVersionedContext(contexts) { - const versions = Object.keys(contexts).length; - for (let i = 1; i <= versions; i++) { - const context2 = contexts[i]; - if (!context2 || context2.version !== i) { - return false; - } +function computeAddress(key) { + let pubkey; + if (typeof key === "string") { + pubkey = SigningKey.computePublicKey(key, false); + } else { + pubkey = key.publicKey; } - return true; + return getAddress(keccak256("0x" + pubkey.substring(4)).substring(26)); } -function latestContext(contexts) { - const versions = Object.keys(contexts).length; - return contexts[versions]; +function recoverAddress(digest, signature2) { + return computeAddress(SigningKey.recoverPublicKey(digest, signature2)); } -const defaultContexts = { - 1: DeployedWalletContext$1, - 2: DeployedWalletContext -}; -var context = /* @__PURE__ */ Object.freeze({ - __proto__: null, - addressOf, - isValidCounterfactual, - isValidVersionedContext, - latestContext, - defaultContexts -}); -const MetaTransactionsType = `tuple( - bool delegateCall, - bool revertOnError, - uint256 gasLimit, - address target, - uint256 value, - bytes data -)[]`; -function intendTransactionBundle(bundle, wallet, chainId, id2) { - return _extends$c({}, bundle, { - chainId, - intent: { - id: id2, - wallet - } - }); +const BN_0$4 = BigInt(0); +const BN_2$2 = BigInt(2); +const BN_27 = BigInt(27); +const BN_28 = BigInt(28); +const BN_35 = BigInt(35); +const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const BLOB_SIZE = 4096 * 32; +function getVersionedHash(version2, hash2) { + let versioned = version2.toString(16); + while (versioned.length < 2) { + versioned = "0" + versioned; + } + versioned += sha256$1(hash2).substring(4); + return "0x" + versioned; } -function intendedTransactionID(bundle) { - return keccak256$1(AbiCoder.defaultAbiCoder().encode(["address", "uint256", "bytes32"], [bundle.intent.wallet, bundle.chainId, bundle.intent.id])); +function handleAddress(value) { + if (value === "0x") { + return null; + } + return getAddress(value); } -function unpackMetaTransactionsData(data) { - const res = AbiCoder.defaultAbiCoder().decode(["uint256", MetaTransactionsType], data); - if (res.length !== 2 || !res[0] || !res[1]) throw new Error("Invalid meta transaction data"); - return [res[0], res[1]]; +function handleAccessList(value, param) { + try { + return accessListify(value); + } catch (error) { + assertArgument(false, error.message, param, value); + } } -function packMetaTransactionsData(nonce, txs) { - return AbiCoder.defaultAbiCoder().encode(["uint256", MetaTransactionsType], [nonce, sequenceTxAbiEncode(txs)]); +function handleNumber(_value2, param) { + if (_value2 === "0x") { + return 0; + } + return getNumber(_value2, param); } -function digestOfTransactions(nonce, txs) { - return keccak256$1(packMetaTransactionsData(nonce, txs)); +function handleUint(_value2, param) { + if (_value2 === "0x") { + return BN_0$4; + } + const value = getBigInt(_value2, param); + assertArgument(value <= BN_MAX_UINT, "value exceeds uint size", param, value); + return value; } -function subdigestOfTransactions(address, chainId, nonce, txs) { - return subdigestOf({ - address, - chainId, - digest: digestOfTransactions(nonce, txs) - }); +function formatNumber(_value2, name2) { + const value = getBigInt(_value2, "value"); + const result = toBeArray(value); + assertArgument(result.length <= 32, `value too large`, `tx.${name2}`, value); + return result; } -function subdigestOfGuestModuleTransactions(guestModule, chainId, txs) { - return subdigestOf({ - address: guestModule, - chainId, - digest: keccak256$1(AbiCoder.defaultAbiCoder().encode(["string", MetaTransactionsType], ["guest:", sequenceTxAbiEncode(txs)])) - }); +function formatAccessList(value) { + return accessListify(value).map((set) => [set.address, set.storageKeys]); } -function toSequenceTransactions(wallet, txs) { - return txs.map((tx) => toSequenceTransaction(wallet, tx)); +function formatHashes(value, param) { + assertArgument(Array.isArray(value), `invalid ${param}`, "value", value); + for (let i = 0; i < value.length; i++) { + assertArgument(isHexString(value[i], 32), "invalid ${ param } hash", `value[${i}]`, value[i]); + } + return value; } -function toSequenceTransaction(wallet, tx) { - if (tx.to && tx.to !== ZeroAddress) { - return { - nonce: !isNullish(tx.nonce) ? BigInt(tx.nonce) : void 0, - transaction: { - delegateCall: false, - revertOnError: false, - gasLimit: !isNullish(tx.gasLimit) ? BigInt(tx.gasLimit) : void 0, - // XXX: `tx.to` could also be ethers Addressable type which returns a getAddress promise - // Keeping this as is for now so we don't have to change everything to async - to: tx.to, - value: BigInt(tx.value || 0), - data: tx.data || "0x" - } - }; +function _parseLegacy(data) { + const fields = decodeRlp(data); + assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 6), "invalid field count for legacy transaction", "data", data); + const tx = { + type: 0, + nonce: handleNumber(fields[0], "nonce"), + gasPrice: handleUint(fields[1], "gasPrice"), + gasLimit: handleUint(fields[2], "gasLimit"), + to: handleAddress(fields[3]), + value: handleUint(fields[4], "value"), + data: hexlify(fields[5]), + chainId: BN_0$4 + }; + if (fields.length === 6) { + return tx; + } + const v3 = handleUint(fields[6], "v"); + const r2 = handleUint(fields[7], "r"); + const s2 = handleUint(fields[8], "s"); + if (r2 === BN_0$4 && s2 === BN_0$4) { + tx.chainId = v3; } else { - const walletInterface = new Interface(walletContracts.mainModule.abi); - const data = walletInterface.encodeFunctionData(walletInterface.getFunction("createContract"), [tx.data]); - return { - nonce: typeof tx.nonce === "number" ? BigInt(tx.nonce) : void 0, - transaction: { - delegateCall: false, - revertOnError: false, - gasLimit: !isNullish(tx.gasLimit) ? BigInt(tx.gasLimit) : void 0, - to: wallet, - value: BigInt(tx.value || 0), - data - } - }; + let chainId = (v3 - BN_35) / BN_2$2; + if (chainId < BN_0$4) { + chainId = BN_0$4; + } + tx.chainId = chainId; + assertArgument(chainId !== BN_0$4 || (v3 === BN_27 || v3 === BN_28), "non-canonical legacy v", "v", fields[6]); + tx.signature = Signature.from({ + r: zeroPadValue(fields[7], 32), + s: zeroPadValue(fields[8], 32), + v: v3 + }); } + return tx; } -function isSequenceTransaction(tx) { - return tx.delegateCall !== void 0 || tx.revertOnError !== void 0; +function _serializeLegacy(tx, sig) { + const fields = [ + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit, "gasLimit"), + tx.to || "0x", + formatNumber(tx.value, "value"), + tx.data + ]; + let chainId = BN_0$4; + if (tx.chainId != BN_0$4) { + chainId = getBigInt(tx.chainId, "tx.chainId"); + assertArgument(!sig || sig.networkV == null || sig.legacyChainId === chainId, "tx.chainId/sig.v mismatch", "sig", sig); + } else if (tx.signature) { + const legacy = tx.signature.legacyChainId; + if (legacy != null) { + chainId = legacy; + } + } + if (!sig) { + if (chainId !== BN_0$4) { + fields.push(toBeArray(chainId)); + fields.push("0x"); + fields.push("0x"); + } + return encodeRlp(fields); + } + let v3 = BigInt(27 + sig.yParity); + if (chainId !== BN_0$4) { + v3 = Signature.getChainIdV(chainId, sig.v); + } else if (BigInt(sig.v) !== v3) { + assertArgument(false, "tx.chainId/sig.v mismatch", "sig", sig); + } + fields.push(toBeArray(v3)); + fields.push(toBeArray(sig.r)); + fields.push(toBeArray(sig.s)); + return encodeRlp(fields); } -function hasSequenceTransactions(txs) { - return txs.every(isSequenceTransaction); +function _parseEipSignature(tx, fields) { + let yParity; + try { + yParity = handleNumber(fields[0], "yParity"); + if (yParity !== 0 && yParity !== 1) { + throw new Error("bad yParity"); + } + } catch (error) { + assertArgument(false, "invalid yParity", "yParity", fields[0]); + } + const r2 = zeroPadValue(fields[1], 32); + const s2 = zeroPadValue(fields[2], 32); + const signature2 = Signature.from({ r: r2, s: s2, yParity }); + tx.signature = signature2; } -function sequenceTxAbiEncode(txs) { - return txs.map((tx) => { - var _tx$to; - return { - delegateCall: tx.delegateCall === true, - revertOnError: tx.revertOnError === true, - gasLimit: !isNullish(tx.gasLimit) ? BigInt(tx.gasLimit) : 0n, - target: (_tx$to = tx.to) != null ? _tx$to : ZeroAddress, - value: !isNullish(tx.value) ? tx.value : 0n, - data: tx.data || "0x" - }; - }); +function _parseEip1559(data) { + const fields = decodeRlp(getBytes(data).slice(1)); + assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 12), "invalid field count for transaction type: 2", "data", hexlify(data)); + const tx = { + type: 2, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"), + maxFeePerGas: handleUint(fields[3], "maxFeePerGas"), + gasPrice: null, + gasLimit: handleUint(fields[4], "gasLimit"), + to: handleAddress(fields[5]), + value: handleUint(fields[6], "value"), + data: hexlify(fields[7]), + accessList: handleAccessList(fields[8], "accessList") + }; + if (fields.length === 9) { + return tx; + } + _parseEipSignature(tx, fields.slice(9)); + return tx; } -function fromTxAbiEncode(txs) { - return txs.map((tx) => ({ - delegateCall: tx.delegateCall, - revertOnError: tx.revertOnError, - gasLimit: tx.gasLimit, - to: tx.target, - value: tx.value, - data: tx.data - })); +function _serializeEip1559(tx, sig) { + const fields = [ + formatNumber(tx.chainId, "chainId"), + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(tx.gasLimit, "gasLimit"), + tx.to || "0x", + formatNumber(tx.value, "value"), + tx.data, + formatAccessList(tx.accessList || []) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "yParity")); + fields.push(toBeArray(sig.r)); + fields.push(toBeArray(sig.s)); + } + return concat(["0x02", encodeRlp(fields)]); } -function encodeNonce(space, nonce) { - const bspace = BigInt(space); - const bnonce = BigInt(nonce); - const shl = 2n ** 96n; - if (bnonce / shl !== 0n) { - throw new Error("Space already encoded"); +function _parseEip2930(data) { + const fields = decodeRlp(getBytes(data).slice(1)); + assertArgument(Array.isArray(fields) && (fields.length === 8 || fields.length === 11), "invalid field count for transaction type: 1", "data", hexlify(data)); + const tx = { + type: 1, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + gasPrice: handleUint(fields[2], "gasPrice"), + gasLimit: handleUint(fields[3], "gasLimit"), + to: handleAddress(fields[4]), + value: handleUint(fields[5], "value"), + data: hexlify(fields[6]), + accessList: handleAccessList(fields[7], "accessList") + }; + if (fields.length === 8) { + return tx; } - return bnonce + bspace * shl; + _parseEipSignature(tx, fields.slice(8)); + return tx; } -function decodeNonce(nonce) { - const bnonce = BigInt(nonce); - const shr = 2n ** 96n; - return [bnonce / shr, bnonce % shr]; +function _serializeEip2930(tx, sig) { + const fields = [ + formatNumber(tx.chainId, "chainId"), + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit, "gasLimit"), + tx.to || "0x", + formatNumber(tx.value, "value"), + tx.data, + formatAccessList(tx.accessList || []) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "recoveryParam")); + fields.push(toBeArray(sig.r)); + fields.push(toBeArray(sig.s)); + } + return concat(["0x01", encodeRlp(fields)]); } -function fromTransactionish(wallet, transaction2) { - if (Array.isArray(transaction2)) { - if (hasSequenceTransactions(transaction2)) { - return transaction2; - } else { - const stx = toSequenceTransactions(wallet, transaction2); - return stx.map((t2) => t2.transaction); +function _parseEip4844(data) { + let fields = decodeRlp(getBytes(data).slice(1)); + let typeName = "3"; + let blobs = null; + if (fields.length === 4 && Array.isArray(fields[0])) { + typeName = "3 (network format)"; + const fBlobs = fields[1], fCommits = fields[2], fProofs = fields[3]; + assertArgument(Array.isArray(fBlobs), "invalid network format: blobs not an array", "fields[1]", fBlobs); + assertArgument(Array.isArray(fCommits), "invalid network format: commitments not an array", "fields[2]", fCommits); + assertArgument(Array.isArray(fProofs), "invalid network format: proofs not an array", "fields[3]", fProofs); + assertArgument(fBlobs.length === fCommits.length, "invalid network format: blobs/commitments length mismatch", "fields", fields); + assertArgument(fBlobs.length === fProofs.length, "invalid network format: blobs/proofs length mismatch", "fields", fields); + blobs = []; + for (let i = 0; i < fields[1].length; i++) { + blobs.push({ + data: fBlobs[i], + commitment: fCommits[i], + proof: fProofs[i] + }); } - } else if (isSequenceTransaction(transaction2)) { - return [transaction2]; - } else { - return [toSequenceTransaction(wallet, transaction2).transaction]; + fields = fields[0]; } + assertArgument(Array.isArray(fields) && (fields.length === 11 || fields.length === 14), `invalid field count for transaction type: ${typeName}`, "data", hexlify(data)); + const tx = { + type: 3, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"), + maxFeePerGas: handleUint(fields[3], "maxFeePerGas"), + gasPrice: null, + gasLimit: handleUint(fields[4], "gasLimit"), + to: handleAddress(fields[5]), + value: handleUint(fields[6], "value"), + data: hexlify(fields[7]), + accessList: handleAccessList(fields[8], "accessList"), + maxFeePerBlobGas: handleUint(fields[9], "maxFeePerBlobGas"), + blobVersionedHashes: fields[10] + }; + if (blobs) { + tx.blobs = blobs; + } + assertArgument(tx.to != null, `invalid address for transaction type: ${typeName}`, "data", data); + assertArgument(Array.isArray(tx.blobVersionedHashes), "invalid blobVersionedHashes: must be an array", "data", data); + for (let i = 0; i < tx.blobVersionedHashes.length; i++) { + assertArgument(isHexString(tx.blobVersionedHashes[i], 32), `invalid blobVersionedHash at index ${i}: must be length 32`, "data", data); + } + if (fields.length === 11) { + return tx; + } + _parseEipSignature(tx, fields.slice(11)); + return tx; } -function isTransactionBundle(cand) { - return cand !== void 0 && cand.entrypoint !== void 0 && cand.chainId !== void 0 && cand.transactions !== void 0 && cand.nonce !== void 0 && cand.intent !== void 0 && cand.intent.id !== void 0 && cand.intent.wallet !== void 0 && Array.isArray(cand.transactions) && cand.transactions.reduce((p2, c2) => p2 && isSequenceTransaction(c2), true); -} -function isSignedTransactionBundle(cand) { - return cand !== void 0 && cand.signature !== void 0 && cand.signature !== "" && isTransactionBundle(cand); -} -function encodeBundleExecData(bundle) { - const walletInterface = new Interface(walletContracts.mainModule.abi); - return walletInterface.encodeFunctionData(walletInterface.getFunction("execute"), isSignedTransactionBundle(bundle) ? [ - // Signed transaction bundle has all 3 parameters - sequenceTxAbiEncode(bundle.transactions), - bundle.nonce, - bundle.signature - ] : [ - // Unsigned bundle may be a GuestModule call, so signature and nonce are missing - sequenceTxAbiEncode(bundle.transactions), - 0, - new Uint8Array([]) - ]); +function _serializeEip4844(tx, sig, blobs) { + const fields = [ + formatNumber(tx.chainId, "chainId"), + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(tx.gasLimit, "gasLimit"), + tx.to || ZeroAddress, + formatNumber(tx.value, "value"), + tx.data, + formatAccessList(tx.accessList || []), + formatNumber(tx.maxFeePerBlobGas || 0, "maxFeePerBlobGas"), + formatHashes(tx.blobVersionedHashes || [], "blobVersionedHashes") + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "yParity")); + fields.push(toBeArray(sig.r)); + fields.push(toBeArray(sig.s)); + if (blobs) { + return concat([ + "0x03", + encodeRlp([ + fields, + blobs.map((b2) => b2.data), + blobs.map((b2) => b2.commitment), + blobs.map((b2) => b2.proof) + ]) + ]); + } + } + return concat(["0x03", encodeRlp(fields)]); } -const selfExecuteSelector = "0x61c2926c"; -const selfExecuteAbi = `tuple( - bool delegateCall, - bool revertOnError, - uint256 gasLimit, - address target, - uint256 value, - bytes data -)[]`; -const unwind = (wallet, transactions2) => { - const unwound = []; - const walletInterface = new Interface(walletContracts.mainModule.abi); - for (const tx of transactions2) { - const txData = getBytes(tx.data || "0x"); - if (tx.to === wallet && hexlify(txData.slice(0, 4)) === selfExecuteSelector) { - const data = txData.slice(4); - const decoded = AbiCoder.defaultAbiCoder().decode([selfExecuteAbi], data)[0]; - unwound.push(...unwind(tx.to, decoded.map((d2) => _extends$c({}, d2, { - to: d2.target - })))); - } else { - try { - const innerTransactions = walletInterface.decodeFunctionData("execute", txData)[0]; - const unwoundTransactions = unwind(wallet, innerTransactions.map((tx2) => _extends$c({}, tx2.toObject(), { - to: tx2.target - }))); - unwound.push(...unwoundTransactions); - } catch (_unused) { - unwound.push(tx); +const _Transaction = class _Transaction { + /** + * Creates a new Transaction with default values. + */ + constructor() { + __privateAdd(this, _Transaction_instances); + __privateAdd(this, _type); + __privateAdd(this, _to); + __privateAdd(this, _data4); + __privateAdd(this, _nonce); + __privateAdd(this, _gasLimit); + __privateAdd(this, _gasPrice); + __privateAdd(this, _maxPriorityFeePerGas); + __privateAdd(this, _maxFeePerGas); + __privateAdd(this, _value); + __privateAdd(this, _chainId2); + __privateAdd(this, _sig); + __privateAdd(this, _accessList); + __privateAdd(this, _maxFeePerBlobGas); + __privateAdd(this, _blobVersionedHashes); + __privateAdd(this, _kzg); + __privateAdd(this, _blobs); + __privateSet(this, _type, null); + __privateSet(this, _to, null); + __privateSet(this, _nonce, 0); + __privateSet(this, _gasLimit, BN_0$4); + __privateSet(this, _gasPrice, null); + __privateSet(this, _maxPriorityFeePerGas, null); + __privateSet(this, _maxFeePerGas, null); + __privateSet(this, _data4, "0x"); + __privateSet(this, _value, BN_0$4); + __privateSet(this, _chainId2, BN_0$4); + __privateSet(this, _sig, null); + __privateSet(this, _accessList, null); + __privateSet(this, _maxFeePerBlobGas, null); + __privateSet(this, _blobVersionedHashes, null); + __privateSet(this, _blobs, null); + __privateSet(this, _kzg, null); + } + /** + * The transaction type. + * + * If null, the type will be automatically inferred based on + * explicit properties. + */ + get type() { + return __privateGet(this, _type); + } + set type(value) { + switch (value) { + case null: + __privateSet(this, _type, null); + break; + case 0: + case "legacy": + __privateSet(this, _type, 0); + break; + case 1: + case "berlin": + case "eip-2930": + __privateSet(this, _type, 1); + break; + case 2: + case "london": + case "eip-1559": + __privateSet(this, _type, 2); + break; + case 3: + case "cancun": + case "eip-4844": + __privateSet(this, _type, 3); + break; + default: + assertArgument(false, "unsupported transaction type", "type", value); + } + } + /** + * The name of the transaction type. + */ + get typeName() { + switch (this.type) { + case 0: + return "legacy"; + case 1: + return "eip-2930"; + case 2: + return "eip-1559"; + case 3: + return "eip-4844"; + } + return null; + } + /** + * The ``to`` address for the transaction or ``null`` if the + * transaction is an ``init`` transaction. + */ + get to() { + const value = __privateGet(this, _to); + if (value == null && this.type === 3) { + return ZeroAddress; + } + return value; + } + set to(value) { + __privateSet(this, _to, value == null ? null : getAddress(value)); + } + /** + * The transaction nonce. + */ + get nonce() { + return __privateGet(this, _nonce); + } + set nonce(value) { + __privateSet(this, _nonce, getNumber(value, "value")); + } + /** + * The gas limit. + */ + get gasLimit() { + return __privateGet(this, _gasLimit); + } + set gasLimit(value) { + __privateSet(this, _gasLimit, getBigInt(value)); + } + /** + * The gas price. + * + * On legacy networks this defines the fee that will be paid. On + * EIP-1559 networks, this should be ``null``. + */ + get gasPrice() { + const value = __privateGet(this, _gasPrice); + if (value == null && (this.type === 0 || this.type === 1)) { + return BN_0$4; + } + return value; + } + set gasPrice(value) { + __privateSet(this, _gasPrice, value == null ? null : getBigInt(value, "gasPrice")); + } + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxPriorityFeePerGas() { + const value = __privateGet(this, _maxPriorityFeePerGas); + if (value == null) { + if (this.type === 2 || this.type === 3) { + return BN_0$4; } + return null; } + return value; } - return unwound; -}; -const isNullish = (value) => value === null || value === void 0; -var transaction = /* @__PURE__ */ Object.freeze({ - __proto__: null, - MetaTransactionsType, - intendTransactionBundle, - intendedTransactionID, - unpackMetaTransactionsData, - packMetaTransactionsData, - digestOfTransactions, - subdigestOfTransactions, - subdigestOfGuestModuleTransactions, - toSequenceTransactions, - toSequenceTransaction, - isSequenceTransaction, - hasSequenceTransactions, - sequenceTxAbiEncode, - fromTxAbiEncode, - encodeNonce, - decodeNonce, - fromTransactionish, - isTransactionBundle, - isSignedTransactionBundle, - encodeBundleExecData, - selfExecuteSelector, - selfExecuteAbi, - unwind -}); -const EIP_6492_OFFCHAIN_DEPLOY_CODE = "0x608060405234801561001057600080fd5b5060405161124a38038061124a83398101604081905261002f91610124565b600060405161003d906100dd565b604051809103906000f080158015610059573d6000803e3d6000fd5b5090506000816001600160a01b0316638f0684308686866040518463ffffffff1660e01b815260040161008e939291906101fb565b6020604051808303816000875af11580156100ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100d19190610244565b9050806000526001601ff35b610fdc8061026e83390190565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561011b578181015183820152602001610103565b50506000910152565b60008060006060848603121561013957600080fd5b83516001600160a01b038116811461015057600080fd5b6020850151604086015191945092506001600160401b038082111561017457600080fd5b818601915086601f83011261018857600080fd5b81518181111561019a5761019a6100ea565b604051601f8201601f19908116603f011681019083821181831017156101c2576101c26100ea565b816040528281528960208487010111156101db57600080fd5b6101ec836020830160208801610100565b80955050505050509250925092565b60018060a01b0384168152826020820152606060408201526000825180606084015261022e816080850160208701610100565b601f01601f191691909101608001949350505050565b60006020828403121561025657600080fd5b8151801515811461026657600080fd5b939250505056fe608060405234801561001057600080fd5b50610fbc806100206000396000f3fe608060405234801561001057600080fd5b50600436106100675760003560e01c806376be4cea1161005057806376be4cea146100a65780638f068430146100b957806398ef1ed8146100cc57600080fd5b80631c6453271461006c5780633d787b6314610093575b600080fd5b61007f61007a366004610ad4565b6100df565b604051901515815260200160405180910390f35b61007f6100a1366004610ad4565b61023d565b61007f6100b4366004610b3e565b61031e565b61007f6100c7366004610ad4565b6108e1565b61007f6100da366004610ad4565b61096e565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea9061012890889088908890889088908190600401610bc3565b6020604051808303816000875af1925050508015610181575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016820190925261017e91810190610c45565b60015b610232573d8080156101af576040519150601f19603f3d011682016040523d82523d6000602084013e6101b4565b606091505b508051600181900361022757816000815181106101d3576101d3610c69565b6020910101517fff00000000000000000000000000000000000000000000000000000000000000167f0100000000000000000000000000000000000000000000000000000000000000149250610235915050565b600092505050610235565b90505b949350505050565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea906102879088908890889088906001908990600401610bc3565b6020604051808303816000875af19250505080156102e0575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682019092526102dd91810190610c45565b60015b610232573d80801561030e576040519150601f19603f3d011682016040523d82523d6000602084013e610313565b606091505b506000915050610235565b600073ffffffffffffffffffffffffffffffffffffffff87163b6060827f64926492649264926492649264926492649264926492649264926492649264928888610369602082610c98565b610375928b9290610cd8565b61037e91610d02565b1490508015610484576000606089828a610399602082610c98565b926103a693929190610cd8565b8101906103b39190610e18565b955090925090508415806103c45750865b1561047d576000808373ffffffffffffffffffffffffffffffffffffffff16836040516103f19190610eb2565b6000604051808303816000865af19150503d806000811461042e576040519150601f19603f3d011682016040523d82523d6000602084013e610433565b606091505b50915091508161047a57806040517f9d0d6e2d0000000000000000000000000000000000000000000000000000000081526004016104719190610f18565b60405180910390fd5b50505b50506104be565b87878080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509294505050505b80806104ca5750600083115b156106bb576040517f1626ba7e00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8b1690631626ba7e90610523908c908690600401610f2b565b602060405180830381865afa92505050801561057a575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016820190925261057791810190610f44565b60015b61060f573d8080156105a8576040519150601f19603f3d011682016040523d82523d6000602084013e6105ad565b606091505b50851580156105bc5750600084115b156105db576105d08b8b8b8b8b600161031e565b9450505050506108d7565b806040517f6f2a95990000000000000000000000000000000000000000000000000000000081526004016104719190610f18565b7fffffffff0000000000000000000000000000000000000000000000000000000081167f1626ba7e000000000000000000000000000000000000000000000000000000001480158161065f575086155b801561066b5750600085115b1561068b5761067f8c8c8c8c8c600161031e565b955050505050506108d7565b841580156106965750825b80156106a0575087155b156106af57806000526001601ffd5b94506108d79350505050565b6041871461074b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603a60248201527f5369676e617475726556616c696461746f72237265636f7665725369676e657260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610471565b600061075a6020828a8c610cd8565b61076391610d02565b90506000610775604060208b8d610cd8565b61077e91610d02565b905060008a8a604081811061079557610795610c69565b919091013560f81c915050601b81148015906107b557508060ff16601c14155b15610842576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f5369676e617475726556616c696461746f723a20696e76616c6964207369676e60448201527f617475726520762076616c7565000000000000000000000000000000000000006064820152608401610471565b6040805160008152602081018083528e905260ff831691810191909152606081018490526080810183905273ffffffffffffffffffffffffffffffffffffffff8e169060019060a0016020604051602081039080840390855afa1580156108ad573d6000803e3d6000fd5b5050506020604051035173ffffffffffffffffffffffffffffffffffffffff161496505050505050505b9695505050505050565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea9061092b9088908890889088906001908990600401610bc3565b6020604051808303816000875af115801561094a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102329190610c45565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea906109b790889088908890889088908190600401610bc3565b6020604051808303816000875af1925050508015610a10575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0168201909252610a0d91810190610c45565b60015b610232573d808015610a3e576040519150601f19603f3d011682016040523d82523d6000602084013e610a43565b606091505b5080516001819003610a6257816000815181106101d3576101d3610c69565b8082fd5b73ffffffffffffffffffffffffffffffffffffffff81168114610a8857600080fd5b50565b60008083601f840112610a9d57600080fd5b50813567ffffffffffffffff811115610ab557600080fd5b602083019150836020828501011115610acd57600080fd5b9250929050565b60008060008060608587031215610aea57600080fd5b8435610af581610a66565b935060208501359250604085013567ffffffffffffffff811115610b1857600080fd5b610b2487828801610a8b565b95989497509550505050565b8015158114610a8857600080fd5b60008060008060008060a08789031215610b5757600080fd5b8635610b6281610a66565b955060208701359450604087013567ffffffffffffffff811115610b8557600080fd5b610b9189828a01610a8b565b9095509350506060870135610ba581610b30565b91506080870135610bb581610b30565b809150509295509295509295565b73ffffffffffffffffffffffffffffffffffffffff8716815285602082015260a060408201528360a0820152838560c0830137600060c085830181019190915292151560608201529015156080820152601f9092017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016909101019392505050565b600060208284031215610c5757600080fd5b8151610c6281610b30565b9392505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b81810381811115610cd2577f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b92915050565b60008085851115610ce857600080fd5b83861115610cf557600080fd5b5050820193919092039150565b80356020831015610cd2577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff602084900360031b1b1692915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b600082601f830112610d7e57600080fd5b813567ffffffffffffffff80821115610d9957610d99610d3e565b604051601f83017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0908116603f01168101908282118183101715610ddf57610ddf610d3e565b81604052838152866020858801011115610df857600080fd5b836020870160208301376000602085830101528094505050505092915050565b600080600060608486031215610e2d57600080fd5b8335610e3881610a66565b9250602084013567ffffffffffffffff80821115610e5557600080fd5b610e6187838801610d6d565b93506040860135915080821115610e7757600080fd5b50610e8486828701610d6d565b9150509250925092565b60005b83811015610ea9578181015183820152602001610e91565b50506000910152565b60008251610ec4818460208701610e8e565b9190910192915050565b60008151808452610ee6816020860160208601610e8e565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b602081526000610c626020830184610ece565b8281526040602082015260006102356040830184610ece565b600060208284031215610f5657600080fd5b81517fffffffff0000000000000000000000000000000000000000000000000000000081168114610c6257600080fdfea26469706673582212201a72aed4b15ffb05b6502997a9bb655992e06590bd26b336dfbb153d7ff6f34b64736f6c63430008120033"; -const EIP_6492_SUFFIX = "0x6492649264926492649264926492649264926492649264926492649264926492"; -async function validateEIP6492Offchain(provider2, signer2, hash2, signature2) { - try { - const result = await provider2.call({ - data: concat$1([EIP_6492_OFFCHAIN_DEPLOY_CODE, AbiCoder.defaultAbiCoder().encode(["address", "bytes32", "bytes"], [signer2, hash2, signature2])]) - }); - return result === "0x01"; - } catch (err) { - return false; + set maxPriorityFeePerGas(value) { + __privateSet(this, _maxPriorityFeePerGas, value == null ? null : getBigInt(value, "maxPriorityFeePerGas")); } -} -var validateEIP6492 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - EIP_6492_OFFCHAIN_DEPLOY_CODE, - EIP_6492_SUFFIX, - validateEIP6492Offchain -}); -class OnChainReader { - constructor(provider2) { - this.provider = provider2; - this.isDeployedCache = /* @__PURE__ */ new Set(); + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxFeePerGas() { + const value = __privateGet(this, _maxFeePerGas); + if (value == null) { + if (this.type === 2 || this.type === 3) { + return BN_0$4; + } + return null; + } + return value; } - module(address) { - return new Contract(address, [...walletContracts.mainModuleUpgradable.abi, ...walletContracts.mainModule.abi, ...walletContracts.erc1271.abi], this.provider); + set maxFeePerGas(value) { + __privateSet(this, _maxFeePerGas, value == null ? null : getBigInt(value, "maxFeePerGas")); } - async isDeployed(wallet) { - if (this.isDeployedCache.has(wallet)) { - return true; + /** + * The transaction data. For ``init`` transactions this is the + * deployment code. + */ + get data() { + return __privateGet(this, _data4); + } + set data(value) { + __privateSet(this, _data4, hexlify(value)); + } + /** + * The amount of ether (in wei) to send in this transactions. + */ + get value() { + return __privateGet(this, _value); + } + set value(value) { + __privateSet(this, _value, getBigInt(value, "value")); + } + /** + * The chain ID this transaction is valid on. + */ + get chainId() { + return __privateGet(this, _chainId2); + } + set chainId(value) { + __privateSet(this, _chainId2, getBigInt(value)); + } + /** + * If signed, the signature for this transaction. + */ + get signature() { + return __privateGet(this, _sig) || null; + } + set signature(value) { + __privateSet(this, _sig, value == null ? null : Signature.from(value)); + } + /** + * The access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get accessList() { + const value = __privateGet(this, _accessList) || null; + if (value == null) { + if (this.type === 1 || this.type === 2 || this.type === 3) { + return []; + } + return null; } - const code2 = await this.provider.getCode(wallet).then((c2) => getBytes(c2)); - const isDeployed = code2.length !== 0; - if (isDeployed) { - this.isDeployedCache.add(wallet); + return value; + } + set accessList(value) { + __privateSet(this, _accessList, value == null ? null : accessListify(value)); + } + /** + * The max fee per blob gas for Cancun transactions. + */ + get maxFeePerBlobGas() { + const value = __privateGet(this, _maxFeePerBlobGas); + if (value == null && this.type === 3) { + return BN_0$4; } - return isDeployed; + return value; } - async implementation(wallet) { - const position = AbiCoder.defaultAbiCoder().encode(["address"], [wallet]); - const val = await this.provider.getStorage(wallet, position).then((c2) => getBytes(c2)); - if (val.length === 20) { - return getAddress$1(hexlify(val)); + set maxFeePerBlobGas(value) { + __privateSet(this, _maxFeePerBlobGas, value == null ? null : getBigInt(value, "maxFeePerBlobGas")); + } + /** + * The BLOb versioned hashes for Cancun transactions. + */ + get blobVersionedHashes() { + let value = __privateGet(this, _blobVersionedHashes); + if (value == null && this.type === 3) { + return []; } - if (val.length === 32) { - return AbiCoder.defaultAbiCoder().decode(["address"], val)[0]; + return value; + } + set blobVersionedHashes(value) { + if (value != null) { + assertArgument(Array.isArray(value), "blobVersionedHashes must be an Array", "value", value); + value = value.slice(); + for (let i = 0; i < value.length; i++) { + assertArgument(isHexString(value[i], 32), "invalid blobVersionedHash", `value[${i}]`, value[i]); + } } - return void 0; + __privateSet(this, _blobVersionedHashes, value); } - async imageHash(wallet) { - try { - const imageHash2 = await this.module(wallet).imageHash(); - return imageHash2; - } catch (_unused) { + /** + * The BLObs for the Transaction, if any. + * + * If ``blobs`` is non-``null``, then the [[seriailized]] + * will return the network formatted sidecar, otherwise it + * will return the standard [[link-eip-2718]] payload. The + * [[unsignedSerialized]] is unaffected regardless. + * + * When setting ``blobs``, either fully valid [[Blob]] objects + * may be specified (i.e. correctly padded, with correct + * committments and proofs) or a raw [[BytesLike]] may + * be provided. + * + * If raw [[BytesLike]] are provided, the [[kzg]] property **must** + * be already set. The blob will be correctly padded and the + * [[KzgLibrary]] will be used to compute the committment and + * proof for the blob. + * + * A BLOb is a sequence of field elements, each of which must + * be within the BLS field modulo, so some additional processing + * may be required to encode arbitrary data to ensure each 32 byte + * field is within the valid range. + * + * Setting this automatically populates [[blobVersionedHashes]], + * overwriting any existing values. Setting this to ``null`` + * does **not** remove the [[blobVersionedHashes]], leaving them + * present. + */ + get blobs() { + if (__privateGet(this, _blobs) == null) { + return null; } - return void 0; + return __privateGet(this, _blobs).map((b2) => Object.assign({}, b2)); } - async nonce(wallet, space = 0) { - try { - const nonce = await this.module(wallet).readNonce(space); - return nonce; - } catch (e2) { - if (!await this.isDeployed(wallet)) { - return 0; + set blobs(_blobs2) { + if (_blobs2 == null) { + __privateSet(this, _blobs, null); + return; + } + const blobs = []; + const versionedHashes = []; + for (let i = 0; i < _blobs2.length; i++) { + const blob = _blobs2[i]; + if (isBytesLike(blob)) { + assert(__privateGet(this, _kzg), "adding a raw blob requires a KZG library", "UNSUPPORTED_OPERATION", { + operation: "set blobs()" + }); + let data = getBytes(blob); + assertArgument(data.length <= BLOB_SIZE, "blob is too large", `blobs[${i}]`, blob); + if (data.length !== BLOB_SIZE) { + const padded = new Uint8Array(BLOB_SIZE); + padded.set(data); + data = padded; + } + const commit = __privateGet(this, _kzg).blobToKzgCommitment(data); + const proof = hexlify(__privateGet(this, _kzg).computeBlobKzgProof(data, commit)); + blobs.push({ + data: hexlify(data), + commitment: hexlify(commit), + proof + }); + versionedHashes.push(getVersionedHash(1, commit)); + } else { + const commit = hexlify(blob.commitment); + blobs.push({ + data: hexlify(blob.data), + commitment: commit, + proof: hexlify(blob.proof) + }); + versionedHashes.push(getVersionedHash(1, commit)); } - throw e2; } + __privateSet(this, _blobs, blobs); + __privateSet(this, _blobVersionedHashes, versionedHashes); } - // We use the EIP-6492 validator contract to check the signature - // this means that if the wallet is not deployed, then the signature - // must be prefixed with a transaction that deploys the wallet - async isValidSignature(wallet, digest, signature2) { - return validateEIP6492Offchain(this.provider, wallet, digest, signature2); + get kzg() { + return __privateGet(this, _kzg); } -} -var reader = /* @__PURE__ */ Object.freeze({ - __proto__: null, - OnChainReader -}); -function isWalletSignRequestMetadata(obj) { - return obj && obj.address && obj.digest && obj.chainId !== void 0 && obj.config; -} -var index$1$2 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - config: config$2, - signature: signature$2, - context, - signer, - EIP1271: validateEIP1271, - transaction, - reader, - EIP6492: validateEIP6492, - isWalletSignRequestMetadata -}); -const ALL_CODERS = [{ - config: ConfigCoder$1, - signature: SignatureCoder$1 -}, { - config: ConfigCoder, - signature: SignatureCoder -}]; -function coderFor(version2) { - const index2 = version2 - 1; - if (index2 < 0 || index2 >= ALL_CODERS.length) { - throw new Error(`No coder for version: ${version2}`); + set kzg(kzg) { + __privateSet(this, _kzg, kzg); } - return ALL_CODERS[index2]; -} -function genericCoderFor(version2) { - return coderFor(version2); -} -var index$6 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - ALL_CODERS, - coderFor, - genericCoderFor -}); -const VERSION$1 = "2.0.9"; -const allVersions = [v1, v2]; -const core$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - VERSION: VERSION$1, - allVersions, - commons: index$1$2, - universal: index$6, - v1, - v2 -}, Symbol.toStringTag, { value: "Module" })); -function counterfactualVersion(address, firstImageHash, versions) { - for (let i = 0; i < versions.length; i++) { - if (index$1$2.context.addressOf(versions[i], firstImageHash) === address) { - return versions[i].version; + /** + * The transaction hash, if signed. Otherwise, ``null``. + */ + get hash() { + if (this.signature == null) { + return null; } + return keccak256(__privateMethod(this, _Transaction_instances, getSerialized_fn).call(this, true, false)); } - throw new Error("Could not find version for counterfactual address"); -} -var version$6 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - counterfactualVersion -}); -class Migration_v1v2 { - constructor() { - this.version = 2; - this.configCoder = v2.config.ConfigCoder; - this.signatureCoder = v2.signature.SignatureCoder; + /** + * The pre-image hash of this transaction. + * + * This is the digest that a [[Signer]] must sign to authorize + * this transaction. + */ + get unsignedHash() { + return keccak256(this.unsignedSerialized); } - buildTransaction(address, contexts, newConfig) { - if (!v2.config.ConfigCoder.isWalletConfig(newConfig)) { - const v2Config = v2.config.toWalletConfig({ - threshold: newConfig.threshold, - members: newConfig.signers, - checkpoint: 0 - }); - return this.buildTransaction(address, contexts, v2Config); + /** + * The sending address, if signed. Otherwise, ``null``. + */ + get from() { + if (this.signature == null) { + return null; } - const context2 = contexts[2]; - const contract = new Interface(walletContracts.mainModule.abi); - const updateBundle = v2.config.ConfigCoder.update.buildTransaction(address, newConfig, context2, "first"); - const tx = { - entrypoint: address, - nonce: index$1$2.transaction.encodeNonce(MIGRATION_NONCE_SPACE, 0), - transactions: [{ - to: address, - value: 0, - gasLimit: 0, - revertOnError: true, - delegateCall: false, - data: contract.encodeFunctionData(contract.getFunction("updateImplementation"), [context2.mainModuleUpgradable]) - }, ...updateBundle.transactions] + return recoverAddress(this.unsignedHash, this.signature); + } + /** + * The public key of the sender, if signed. Otherwise, ``null``. + */ + get fromPublicKey() { + if (this.signature == null) { + return null; + } + return SigningKey.recoverPublicKey(this.unsignedHash, this.signature); + } + /** + * Returns true if signed. + * + * This provides a Type Guard that properties requiring a signed + * transaction are non-null. + */ + isSigned() { + return this.signature != null; + } + /** + * The serialized transaction. + * + * This throws if the transaction is unsigned. For the pre-image, + * use [[unsignedSerialized]]. + */ + get serialized() { + return __privateMethod(this, _Transaction_instances, getSerialized_fn).call(this, true, true); + } + /** + * The transaction pre-image. + * + * The hash of this is the digest which needs to be signed to + * authorize this transaction. + */ + get unsignedSerialized() { + return __privateMethod(this, _Transaction_instances, getSerialized_fn).call(this, false, false); + } + /** + * Return the most "likely" type; currently the highest + * supported transaction type. + */ + inferType() { + const types2 = this.inferTypes(); + if (types2.indexOf(2) >= 0) { + return 2; + } + return types2.pop(); + } + /** + * Validates the explicit properties and returns a list of compatible + * transaction types. + */ + inferTypes() { + const hasGasPrice = this.gasPrice != null; + const hasFee = this.maxFeePerGas != null || this.maxPriorityFeePerGas != null; + const hasAccessList = this.accessList != null; + const hasBlob = __privateGet(this, _maxFeePerBlobGas) != null || __privateGet(this, _blobVersionedHashes); + if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) { + assert(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { value: this }); + } + assert(!hasFee || this.type !== 0 && this.type !== 1, "transaction type cannot have maxFeePerGas or maxPriorityFeePerGas", "BAD_DATA", { value: this }); + assert(this.type !== 0 || !hasAccessList, "legacy transaction cannot have accessList", "BAD_DATA", { value: this }); + const types2 = []; + if (this.type != null) { + types2.push(this.type); + } else { + if (hasFee) { + types2.push(2); + } else if (hasGasPrice) { + types2.push(1); + if (!hasAccessList) { + types2.push(0); + } + } else if (hasAccessList) { + types2.push(1); + types2.push(2); + } else if (hasBlob && this.to) { + types2.push(3); + } else { + types2.push(0); + types2.push(1); + types2.push(2); + types2.push(3); + } + } + types2.sort(); + return types2; + } + /** + * Returns true if this transaction is a legacy transaction (i.e. + * ``type === 0``). + * + * This provides a Type Guard that the related properties are + * non-null. + */ + isLegacy() { + return this.type === 0; + } + /** + * Returns true if this transaction is berlin hardform transaction (i.e. + * ``type === 1``). + * + * This provides a Type Guard that the related properties are + * non-null. + */ + isBerlin() { + return this.type === 1; + } + /** + * Returns true if this transaction is london hardform transaction (i.e. + * ``type === 2``). + * + * This provides a Type Guard that the related properties are + * non-null. + */ + isLondon() { + return this.type === 2; + } + /** + * Returns true if this transaction is an [[link-eip-4844]] BLOB + * transaction. + * + * This provides a Type Guard that the related properties are + * non-null. + */ + isCancun() { + return this.type === 3; + } + /** + * Create a copy of this transaciton. + */ + clone() { + return _Transaction.from(this); + } + /** + * Return a JSON-friendly object. + */ + toJSON() { + const s2 = (v3) => { + if (v3 == null) { + return null; + } + return v3.toString(); }; return { - tx, - fromVersion: this.version - 1, - toVersion: this.version, - toConfig: newConfig + type: this.type, + to: this.to, + // from: this.from, + data: this.data, + nonce: this.nonce, + gasLimit: s2(this.gasLimit), + gasPrice: s2(this.gasPrice), + maxPriorityFeePerGas: s2(this.maxPriorityFeePerGas), + maxFeePerGas: s2(this.maxFeePerGas), + value: s2(this.value), + chainId: s2(this.chainId), + sig: this.signature ? this.signature.toJSON() : null, + accessList: this.accessList }; } - decodeTransaction(tx, contexts) { - const address = tx.entrypoint; - if (tx.transactions.length < 2) { - throw new Error("Invalid transaction bundle size"); + /** + * Create a **Transaction** from a serialized transaction or a + * Transaction-like object. + */ + static from(tx) { + if (tx == null) { + return new _Transaction(); } - if (!tx.nonce || index$1$2.transaction.encodeNonce(MIGRATION_NONCE_SPACE, 0) !== BigInt(tx.nonce)) { - throw new Error("Invalid transaction bundle nonce"); + if (typeof tx === "string") { + const payload = getBytes(tx); + if (payload[0] >= 127) { + return _Transaction.from(_parseLegacy(payload)); + } + switch (payload[0]) { + case 1: + return _Transaction.from(_parseEip2930(payload)); + case 2: + return _Transaction.from(_parseEip1559(payload)); + case 3: + return _Transaction.from(_parseEip4844(payload)); + } + assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: "from" }); } - if (tx.transactions[0].to !== address || tx.transactions[1].to !== address || tx.transactions[0].delegateCall || tx.transactions[1].delegateCall || !tx.transactions[0].revertOnError || !tx.transactions[1].revertOnError || tx.transactions[0].value && BigInt(tx.transactions[0].value) !== 0n || tx.transactions[1].value && BigInt(tx.transactions[1].value) !== 0n || tx.transactions[0].gasLimit && BigInt(tx.transactions[0].gasLimit) !== 0n || tx.transactions[1].gasLimit && BigInt(tx.transactions[1].gasLimit) !== 0n) { - throw new Error("Invalid transaction bundle format"); + const result = new _Transaction(); + if (tx.type != null) { + result.type = tx.type; } - const context2 = contexts[2]; - const contract = new Interface(walletContracts.mainModule.abi); - const data1 = hexlify(tx.transactions[0].data || new Uint8Array()); - const expectData1 = hexlify(contract.encodeFunctionData(contract.getFunction("updateImplementation"), [context2.mainModuleUpgradable])); - if (data1 !== expectData1) { - throw new Error("Invalid new implementation on transaction"); + if (tx.to != null) { + result.to = tx.to; } - const decoded2 = v2.config.ConfigCoder.update.decodeTransaction({ - entrypoint: address, - transactions: [tx.transactions[1]] - }); - if (decoded2.address !== address) { - throw new Error("Invalid transaction bundle address"); + if (tx.nonce != null) { + result.nonce = tx.nonce; } - return decoded2; - } -} -const MIGRATION_NONCE_SPACE = "0xa04263acf755e8bd19c0d7e20eea39a9ff3729eb"; -const v1v2 = new Migration_v1v2(); -var index$5 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - MIGRATION_NONCE_SPACE, - v1v2 -}); -function _extends$b() { - _extends$b = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } + if (tx.gasLimit != null) { + result.gasLimit = tx.gasLimit; } - return target; - }; - return _extends$b.apply(this, arguments); -} -function validateMigrations(migrations) { - for (const [version2, migration2] of Object.entries(migrations)) { - if (version2 !== String(migration2.version - 1)) { - throw new Error(`Migration with key ${version2} has version ${migration2.version}, expected version to be key + 1`); + if (tx.gasPrice != null) { + result.gasPrice = tx.gasPrice; } - } -} -class Migrator { - constructor(tracker2, migrations, contexts) { - this.tracker = tracker2; - this.migrations = migrations; - this.contexts = contexts; - validateMigrations(migrations); - } - lastMigration() { - let last; - for (const migration2 of Object.values(this.migrations)) { - if (last === void 0 || migration2.version > last.version) { - last = migration2; - } + if (tx.maxPriorityFeePerGas != null) { + result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas; } - if (last === void 0) { - throw new Error("No migrations"); + if (tx.maxFeePerGas != null) { + result.maxFeePerGas = tx.maxFeePerGas; } - return last; - } - async getAllMigratePresignedTransaction(args) { - const { - address, - fromImageHash, - fromVersion, - chainId - } = args; - let fih = fromImageHash; - let fversion = fromVersion; - const versions = Object.values(this.contexts); - const migs = []; - for (let i = 1; i < versions.length; i++) { - const mig = await this.tracker.getMigration(address, fih, fversion, chainId); - if (!mig) return { - signedMigrations: migs, - missing: true, - lastImageHash: fih, - lastVersion: fversion - }; - migs.push(mig); - const migration2 = this.migrations[fversion]; - if (!migration2) { - throw new Error(`No migration found for version ${fversion}`); - } - const decoded = migration2.decodeTransaction(mig.tx, this.contexts); - if (decoded.address !== address) { - throw new Error(`Migration transaction address does not match expected address`); - } - fih = decoded.newImageHash; - fversion += 1; + if (tx.maxFeePerBlobGas != null) { + result.maxFeePerBlobGas = tx.maxFeePerBlobGas; } - return { - signedMigrations: migs, - missing: false, - lastImageHash: fih, - lastVersion: fversion - }; - } - async signNextMigration(address, fromVersion, wallet, nextConfig) { - const migration2 = this.migrations[fromVersion]; - if (!migration2) { - return void 0; + if (tx.data != null) { + result.data = tx.data; } - const unsignedMigration = migration2.buildTransaction(address, this.contexts, nextConfig); - const signedBundle = await wallet.signTransactionBundle(unsignedMigration.tx); - return _extends$b({}, unsignedMigration, { - tx: signedBundle - }); + if (tx.value != null) { + result.value = tx.value; + } + if (tx.chainId != null) { + result.chainId = tx.chainId; + } + if (tx.signature != null) { + result.signature = Signature.from(tx.signature); + } + if (tx.accessList != null) { + result.accessList = tx.accessList; + } + if (tx.blobVersionedHashes != null) { + result.blobVersionedHashes = tx.blobVersionedHashes; + } + if (tx.kzg != null) { + result.kzg = tx.kzg; + } + if (tx.blobs != null) { + result.blobs = tx.blobs; + } + if (tx.hash != null) { + assertArgument(result.isSigned(), "unsigned transaction cannot define '.hash'", "tx", tx); + assertArgument(result.hash === tx.hash, "hash mismatch", "tx", tx); + } + if (tx.from != null) { + assertArgument(result.isSigned(), "unsigned transaction cannot define '.from'", "tx", tx); + assertArgument(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx); + } + return result; } -} -var migrator = /* @__PURE__ */ Object.freeze({ - __proto__: null, - Migrator -}); -const DefaultMigrations = { - 1: v1v2 }; -var defaults = /* @__PURE__ */ Object.freeze({ - __proto__: null, - DefaultMigrations -}); -const migration$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - defaults, - migration: index$5, - migrator, - version: version$6 -}, Symbol.toStringTag, { value: "Module" })); -function _extends$a() { - _extends$a = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends$a.apply(this, arguments); -} -const DEFAULT_GAS_LIMIT = 800000n; -const ProviderRelayerDefaults = { - waitPollRate: 1e3, - deltaBlocksLog: 12, - fromBlockLog: -1024 +_type = new WeakMap(); +_to = new WeakMap(); +_data4 = new WeakMap(); +_nonce = new WeakMap(); +_gasLimit = new WeakMap(); +_gasPrice = new WeakMap(); +_maxPriorityFeePerGas = new WeakMap(); +_maxFeePerGas = new WeakMap(); +_value = new WeakMap(); +_chainId2 = new WeakMap(); +_sig = new WeakMap(); +_accessList = new WeakMap(); +_maxFeePerBlobGas = new WeakMap(); +_blobVersionedHashes = new WeakMap(); +_kzg = new WeakMap(); +_blobs = new WeakMap(); +_Transaction_instances = new WeakSet(); +getSerialized_fn = function(signed2, sidecar) { + assert(!signed2 || this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { operation: ".serialized" }); + const sig = signed2 ? this.signature : null; + switch (this.inferType()) { + case 0: + return _serializeLegacy(this, sig); + case 1: + return _serializeEip2930(this, sig); + case 2: + return _serializeEip1559(this, sig); + case 3: + return _serializeEip4844(this, sig, sidecar ? this.blobs : null); + } + assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: ".serialized" }); }; -function isProviderRelayerOptions(obj) { - return typeof obj === "object" && obj.provider instanceof AbstractProvider; -} -class ProviderRelayer { - constructor(options) { - this.provider = void 0; - this.waitPollRate = void 0; - this.deltaBlocksLog = void 0; - this.fromBlockLog = void 0; - const opts = _extends$a({}, ProviderRelayerDefaults, options); - this.provider = opts.provider; - this.waitPollRate = opts.waitPollRate; - this.deltaBlocksLog = opts.deltaBlocksLog; - this.fromBlockLog = opts.fromBlockLog; +let Transaction = _Transaction; +function hashMessage(message) { + if (typeof message === "string") { + message = toUtf8Bytes(message); } - async simulate(wallet, ...transactions2) { - var _this = this; - return (await Promise.all(transactions2.map(async function(tx) { - if (tx.gasLimit && BigInt(tx.gasLimit || 0) !== 0n) { - return tx.gasLimit; - } - if (tx.delegateCall) { - return DEFAULT_GAS_LIMIT; - } - if (tx.to === wallet && await _this.provider.getCode(wallet).then((code2) => getBytes(code2).length === 0)) { - return DEFAULT_GAS_LIMIT; + return keccak256(concat([ + toUtf8Bytes(MessagePrefix), + toUtf8Bytes(String(message.length)), + message + ])); +} +function verifyMessage(message, sig) { + const digest = hashMessage(message); + return recoverAddress(digest, sig); +} +const regexBytes = new RegExp("^bytes([0-9]+)$"); +const regexNumber = new RegExp("^(u?int)([0-9]*)$"); +const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$"); +function _pack(type, value, isArray2) { + switch (type) { + case "address": + if (isArray2) { + return getBytes(zeroPadValue(value, 32)); } - if (!_this.provider) { - throw new Error("signer.provider is not set, but is required"); + return getBytes(getAddress(value)); + case "string": + return toUtf8Bytes(value); + case "bytes": + return getBytes(value); + case "bool": + value = !!value ? "0x01" : "0x00"; + if (isArray2) { + return getBytes(zeroPadValue(value, 32)); } - return _this.provider.estimateGas({ - from: wallet, - to: tx.to, - data: tx.data, - value: tx.value - }); - }))).map((gasLimit) => ({ - executed: true, - succeeded: true, - gasUsed: Number(gasLimit), - gasLimit: Number(gasLimit) - })); + return getBytes(value); } - async getNonce(address, space, blockTag) { - if (!this.provider) { - throw new Error("provider is not set"); - } - if (await this.provider.getCode(address) === "0x") { - return 0; + let match = type.match(regexNumber); + if (match) { + let signed2 = match[1] === "int"; + let size2 = parseInt(match[2] || "256"); + assertArgument((!match[2] || match[2] === String(size2)) && size2 % 8 === 0 && size2 !== 0 && size2 <= 256, "invalid number type", "type", type); + if (isArray2) { + size2 = 256; } - if (space === void 0) { - space = 0; + if (signed2) { + value = toTwos(value, size2); } - const module2 = new Contract(address, walletContracts.mainModule.abi, this.provider); - const nonce = await module2.readNonce(space, { - blockTag - }); - return index$1$2.transaction.encodeNonce(space, nonce); + return getBytes(zeroPadValue(toBeArray(value), size2 / 8)); } - async wait(metaTxnId, timeoutDuration, delay2 = this.waitPollRate, maxFails = 5) { - var _this2 = this; - if (typeof metaTxnId !== "string") { - metaTxnId = index$1$2.transaction.intendedTransactionID(metaTxnId); - } - let timedOut = false; - const retry = async function retry2(f2, errorMessage) { - let fails = 0; - while (!timedOut) { - try { - return await f2(); - } catch (error) { - fails++; - if (maxFails !== void 0 && fails >= maxFails) { - logger.error(`giving up after ${fails} failed attempts${errorMessage ? `: ${errorMessage}` : ""}`, error); - throw error; - } else { - logger.warn(`attempt #${fails} failed${errorMessage ? `: ${errorMessage}` : ""}`, error); - } - } - if (delay2 > 0) { - await new Promise((resolve) => setTimeout(resolve, delay2)); - } - } - throw new Error(`timed out after ${fails} failed attempts${errorMessage ? `: ${errorMessage}` : ""}`); - }; - const waitReceipt = async function waitReceipt2() { - let lastBlock = _this2.fromBlockLog; - if (lastBlock < 0) { - const block = await retry(() => _this2.provider.getBlockNumber(), "unable to get latest block number"); - lastBlock = block + lastBlock; - } - if (typeof metaTxnId !== "string") { - throw new Error("impossible"); - } - const normalMetaTxnId = metaTxnId.replace("0x", ""); - while (!timedOut) { - const block = await retry(() => _this2.provider.getBlockNumber(), "unable to get latest block number"); - const logs = await retry(() => _this2.provider.getLogs({ - fromBlock: Math.max(0, lastBlock - _this2.deltaBlocksLog), - toBlock: block, - // Nonce change event topic - topics: ["0x1f180c27086c7a39ea2a7b25239d1ab92348f07ca7bb59d1438fcf527568f881"] - }), `unable to get NonceChange logs for blocks ${Math.max(0, lastBlock - _this2.deltaBlocksLog)} to ${block}`); - lastBlock = block; - const txs = await Promise.all(logs.map((l2) => retry(() => _this2.provider.getTransactionReceipt(l2.transactionHash), `unable to get receipt for transaction ${l2.transactionHash}`))); - const found = txs.find((tx) => tx == null ? void 0 : tx.logs.find((l2) => l2.topics.length === 0 && l2.data.replace("0x", "") === normalMetaTxnId || l2.topics.length === 1 && // TxFailed event topic - l2.topics[0] === "0x3dbd1590ea96dd3253a91f24e64e3a502e1225d602a5731357bc12643070ccd7" && l2.data.length >= 64 && l2.data.replace("0x", "").startsWith(normalMetaTxnId))); - if (found) { - const response = await retry(() => _this2.provider.getTransaction(found.hash), `unable to get transaction ${found.hash}`); - if (!response) { - throw new Error(`Transaction response not found for ${metaTxnId}`); - } - const out = response; - out.receipt = found; - return out; - } - if (!timedOut) { - await new Promise((r2) => setTimeout(r2, delay2)); - } - } - throw new Error(`Timeout waiting for transaction receipt ${metaTxnId}`); - }; - if (timeoutDuration !== void 0) { - return Promise.race([waitReceipt(), new Promise((_, reject) => setTimeout(() => { - timedOut = true; - reject(`Timeout waiting for transaction receipt ${metaTxnId}`); - }, timeoutDuration))]); - } else { - return waitReceipt(); + match = type.match(regexBytes); + if (match) { + const size2 = parseInt(match[1]); + assertArgument(String(size2) === match[1] && size2 !== 0 && size2 <= 32, "invalid bytes type", "type", type); + assertArgument(dataLength(value) === size2, `invalid value for ${type}`, "value", value); + if (isArray2) { + return getBytes(zeroPadBytes(value, 32)); } + return value; + } + match = type.match(regexArray); + if (match && Array.isArray(value)) { + const baseType = match[1]; + const count2 = parseInt(match[2] || String(value.length)); + assertArgument(count2 === value.length, `invalid array length for ${type}`, "value", value); + const result = []; + value.forEach(function(value2) { + result.push(_pack(baseType, value2, true)); + }); + return getBytes(concat(result)); } + assertArgument(false, "invalid type", "type", type); } -function isLocalRelayerOptions(obj) { - return typeof obj === "object" && obj.signer instanceof AbstractSigner; +function solidityPacked(types2, values) { + assertArgument(types2.length === values.length, "wrong number of values; expected ${ types.length }", "values", values); + const tight = []; + types2.forEach(function(type, index2) { + tight.push(_pack(type, values[index2])); + }); + return hexlify(concat(tight)); } -class LocalRelayer extends ProviderRelayer { - constructor(options) { - super(options instanceof AbstractSigner ? { - provider: options.provider - } : _extends$a({}, options, { - provider: options.signer.provider - })); - this.signer = void 0; - this.txnOptions = void 0; - this.signer = options instanceof AbstractSigner ? options : options.signer; - if (!this.signer.provider) throw new Error("Signer must have a provider"); - } - async getFeeOptions(_address, ..._transactions2) { - return { - options: [] - }; - } - async getFeeOptionsRaw(_entrypoint, _data6, _options4) { - return { - options: [] - }; - } - async gasRefundOptions(address, ...transactions2) { - const { - options - } = await this.getFeeOptions(address, ...transactions2); - return options; +function solidityPackedKeccak256(types2, values) { + return keccak256(solidityPacked(types2, values)); +} +function solidityPackedSha256(types2, values) { + return sha256$1(solidityPacked(types2, values)); +} +const padding = new Uint8Array(32); +padding.fill(0); +const BN__1 = BigInt(-1); +const BN_0$3 = BigInt(0); +const BN_1$1 = BigInt(1); +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +function hexPadRight(value) { + const bytes2 = getBytes(value); + const padOffset = bytes2.length % 32; + if (padOffset) { + return concat([bytes2, padding.slice(padOffset)]); } - setTransactionOptions(transactionRequest) { - this.txnOptions = transactionRequest; + return hexlify(bytes2); +} +const hexTrue = toBeHex(BN_1$1, 32); +const hexFalse = toBeHex(BN_0$3, 32); +const domainFieldTypes = { + name: "string", + version: "string", + chainId: "uint256", + verifyingContract: "address", + salt: "bytes32" +}; +const domainFieldNames = [ + "name", + "version", + "chainId", + "verifyingContract", + "salt" +]; +function checkString(key) { + return function(value) { + assertArgument(typeof value === "string", `invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); + return value; + }; +} +const domainChecks = { + name: checkString("name"), + version: checkString("version"), + chainId: function(_value2) { + const value = getBigInt(_value2, "domain.chainId"); + assertArgument(value >= 0, "invalid chain ID", "domain.chainId", _value2); + if (Number.isSafeInteger(value)) { + return Number(value); + } + return toQuantity(value); + }, + verifyingContract: function(value) { + try { + return getAddress(value).toLowerCase(); + } catch (error) { + } + assertArgument(false, `invalid domain value "verifyingContract"`, "domain.verifyingContract", value); + }, + salt: function(value) { + const bytes2 = getBytes(value, "domain.salt"); + assertArgument(bytes2.length === 32, `invalid domain value "salt"`, "domain.salt", value); + return hexlify(bytes2); } - async relay(signedTxs, quote, waitForReceipt = true) { - if (quote !== void 0) { - logger.warn(`LocalRelayer doesn't accept fee quotes`); +}; +function getBaseEncoder(type) { + { + const match = type.match(/^(u?)int(\d+)$/); + if (match) { + const signed2 = match[1] === ""; + const width = parseInt(match[2]); + assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && match[2] === String(width), "invalid numeric width", "type", type); + const boundsUpper = mask(BN_MAX_UINT256, signed2 ? width - 1 : width); + const boundsLower = signed2 ? (boundsUpper + BN_1$1) * BN__1 : BN_0$3; + return function(_value2) { + const value = getBigInt(_value2, "value"); + assertArgument(value >= boundsLower && value <= boundsUpper, `value out-of-bounds for ${type}`, "value", value); + return toBeHex(signed2 ? toTwos(value, 256) : value, 32); + }; } - const data = index$1$2.transaction.encodeBundleExecData(signedTxs); - const responsePromise = this.signer.sendTransaction(_extends$a({ - to: signedTxs.entrypoint, - data - }, this.txnOptions, { - gasLimit: 9e6 - })); - if (waitForReceipt) { - const response = await responsePromise; - response.receipt = await response.wait(); - return response; - } else { - return responsePromise; + } + { + const match = type.match(/^bytes(\d+)$/); + if (match) { + const width = parseInt(match[1]); + assertArgument(width !== 0 && width <= 32 && match[1] === String(width), "invalid bytes width", "type", type); + return function(value) { + const bytes2 = getBytes(value); + assertArgument(bytes2.length === width, `invalid length for ${type}`, "value", value); + return hexPadRight(value); + }; } } -} -const WebRPCVersion$2 = "v1"; -const WebRPCSchemaVersion$2 = "v0.4.1"; -const WebRPCSchemaHash$2 = "1e27d0fd295aa5897878939595ef0c6adc54b1a3"; -let ETHTxnStatus = /* @__PURE__ */ function(ETHTxnStatus2) { - ETHTxnStatus2["UNKNOWN"] = "UNKNOWN"; - ETHTxnStatus2["DROPPED"] = "DROPPED"; - ETHTxnStatus2["QUEUED"] = "QUEUED"; - ETHTxnStatus2["SENT"] = "SENT"; - ETHTxnStatus2["SUCCEEDED"] = "SUCCEEDED"; - ETHTxnStatus2["PARTIALLY_FAILED"] = "PARTIALLY_FAILED"; - ETHTxnStatus2["FAILED"] = "FAILED"; - return ETHTxnStatus2; -}({}); -let TransferType = /* @__PURE__ */ function(TransferType2) { - TransferType2["SEND"] = "SEND"; - TransferType2["RECEIVE"] = "RECEIVE"; - TransferType2["BRIDGE_DEPOSIT"] = "BRIDGE_DEPOSIT"; - TransferType2["BRIDGE_WITHDRAW"] = "BRIDGE_WITHDRAW"; - TransferType2["BURN"] = "BURN"; - TransferType2["UNKNOWN"] = "UNKNOWN"; - return TransferType2; -}({}); -let FeeTokenType$1 = /* @__PURE__ */ function(FeeTokenType2) { - FeeTokenType2["UNKNOWN"] = "UNKNOWN"; - FeeTokenType2["ERC20_TOKEN"] = "ERC20_TOKEN"; - FeeTokenType2["ERC1155_TOKEN"] = "ERC1155_TOKEN"; - return FeeTokenType2; -}({}); -let SortOrder$1 = /* @__PURE__ */ function(SortOrder2) { - SortOrder2["DESC"] = "DESC"; - SortOrder2["ASC"] = "ASC"; - return SortOrder2; -}({}); -class Relayer { - constructor(hostname, fetch2) { - this.hostname = void 0; - this.fetch = void 0; - this.path = "/rpc/Relayer/"; - this.ping = (headers, signal) => { - return this.fetch(this.url("Ping"), createHTTPRequest$6({}, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.version = (headers, signal) => { - return this.fetch(this.url("Version"), createHTTPRequest$6({}, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - version: _data6.version - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.runtimeStatus = (headers, signal) => { - return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$6({}, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getSequenceContext = (headers, signal) => { - return this.fetch(this.url("GetSequenceContext"), createHTTPRequest$6({}, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - data: _data6.data - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getChainID = (headers, signal) => { - return this.fetch(this.url("GetChainID"), createHTTPRequest$6({}, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - chainID: _data6.chainID - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.sendMetaTxn = (args, headers, signal) => { - return this.fetch(this.url("SendMetaTxn"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - status: _data6.status, - txnHash: _data6.txnHash - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getMetaTxnNonce = (args, headers, signal) => { - return this.fetch(this.url("GetMetaTxnNonce"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - nonce: _data6.nonce - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getMetaTxnReceipt = (args, headers, signal) => { - return this.fetch(this.url("GetMetaTxnReceipt"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - receipt: _data6.receipt - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.simulate = (args, headers, signal) => { - return this.fetch(this.url("Simulate"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - results: _data6.results - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateMetaTxnGasLimits = (args, headers, signal) => { - return this.fetch(this.url("UpdateMetaTxnGasLimits"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - payload: _data6.payload - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.feeTokens = (headers, signal) => { - return this.fetch(this.url("FeeTokens"), createHTTPRequest$6({}, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - isFeeRequired: _data6.isFeeRequired, - tokens: _data6.tokens - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.feeOptions = (args, headers, signal) => { - return this.fetch(this.url("FeeOptions"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - options: _data6.options, - sponsored: _data6.sponsored, - quote: _data6.quote - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getMetaTxnNetworkFeeOptions = (args, headers, signal) => { - return this.fetch(this.url("GetMetaTxnNetworkFeeOptions"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - options: _data6.options - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getMetaTransactions = (args, headers, signal) => { - return this.fetch(this.url("GetMetaTransactions"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - page: _data6.page, - transactions: _data6.transactions - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.sentTransactions = (args, headers, signal) => { - return this.fetch(this.url("SentTransactions"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - page: _data6.page, - transactions: _data6.transactions - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.pendingTransactions = (args, headers, signal) => { - return this.fetch(this.url("PendingTransactions"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - page: _data6.page, - transactions: _data6.transactions - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getGasTank = (args, headers, signal) => { - return this.fetch(this.url("GetGasTank"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - gasTank: _data6.gasTank - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.addGasTank = (args, headers, signal) => { - return this.fetch(this.url("AddGasTank"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - status: _data6.status, - gasTank: _data6.gasTank - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateGasTank = (args, headers, signal) => { - return this.fetch(this.url("UpdateGasTank"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - status: _data6.status, - gasTank: _data6.gasTank - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getGasSponsor = (args, headers, signal) => { - return this.fetch(this.url("GetGasSponsor"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - gasSponsor: _data6.gasSponsor - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.addressGasSponsors = (args, headers, signal) => { - return this.fetch(this.url("AddressGasSponsors"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - page: _data6.page, - gasSponsors: _data6.gasSponsors - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.listGasSponsors = (args, headers, signal) => { - return this.fetch(this.url("ListGasSponsors"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - page: _data6.page, - gasSponsors: _data6.gasSponsors - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.addGasSponsor = (args, headers, signal) => { - return this.fetch(this.url("AddGasSponsor"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - status: _data6.status, - gasSponsor: _data6.gasSponsor - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateGasSponsor = (args, headers, signal) => { - return this.fetch(this.url("UpdateGasSponsor"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - status: _data6.status, - gasSponsor: _data6.gasSponsor - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.removeGasSponsor = (args, headers, signal) => { - return this.fetch(this.url("RemoveGasSponsor"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.reportGasSponsorUsage = (args, headers, signal) => { - return this.fetch(this.url("ReportGasSponsorUsage"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - gasSponsorUsage: _data6.gasSponsorUsage - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.nextGasTankBalanceAdjustmentNonce = (args, headers, signal) => { - return this.fetch(this.url("NextGasTankBalanceAdjustmentNonce"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - nonce: _data6.nonce - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); + switch (type) { + case "address": + return function(value) { + return zeroPadValue(getAddress(value), 32); + }; + case "bool": + return function(value) { + return !value ? hexFalse : hexTrue; + }; + case "bytes": + return function(value) { + return keccak256(value); + }; + case "string": + return function(value) { + return id$1(value); + }; + } + return null; +} +function encodeType(name2, fields) { + return `${name2}(${fields.map(({ name: name3, type }) => type + " " + name3).join(",")})`; +} +function splitArray(type) { + const match = type.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/); + if (match) { + return { + base: match[1], + index: match[2] + match[4], + array: { + base: match[1], + prefix: match[1] + match[2], + count: match[5] ? parseInt(match[5]) : -1 + } }; - this.adjustGasTankBalance = (args, headers, signal) => { - return this.fetch(this.url("AdjustGasTankBalance"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - status: _data6.status, - adjustment: _data6.adjustment - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); + } + return { base: type }; +} +const _TypedDataEncoder = class _TypedDataEncoder { + /** + * Create a new **TypedDataEncoder** for %%types%%. + * + * This performs all necessary checking that types are valid and + * do not violate the [[link-eip-712]] structural constraints as + * well as computes the [[primaryType]]. + */ + constructor(_types2) { + __privateAdd(this, _TypedDataEncoder_instances); + /** + * The primary type for the structured [[types]]. + * + * This is derived automatically from the [[types]], since no + * recursion is possible, once the DAG for the types is consturcted + * internally, the primary type must be the only remaining type with + * no parent nodes. + */ + __publicField(this, "primaryType"); + __privateAdd(this, _types); + __privateAdd(this, _fullTypes); + __privateAdd(this, _encoderCache); + __privateSet(this, _fullTypes, /* @__PURE__ */ new Map()); + __privateSet(this, _encoderCache, /* @__PURE__ */ new Map()); + const links = /* @__PURE__ */ new Map(); + const parents = /* @__PURE__ */ new Map(); + const subtypes = /* @__PURE__ */ new Map(); + const types2 = {}; + Object.keys(_types2).forEach((type) => { + types2[type] = _types2[type].map(({ name: name2, type: type2 }) => { + let { base, index: index2 } = splitArray(type2); + if (base === "int" && !_types2["int"]) { + base = "int256"; + } + if (base === "uint" && !_types2["uint"]) { + base = "uint256"; + } + return { name: name2, type: base + (index2 || "") }; }); + links.set(type, /* @__PURE__ */ new Set()); + parents.set(type, []); + subtypes.set(type, /* @__PURE__ */ new Set()); + }); + __privateSet(this, _types, JSON.stringify(types2)); + for (const name2 in types2) { + const uniqueNames = /* @__PURE__ */ new Set(); + for (const field of types2[name2]) { + assertArgument(!uniqueNames.has(field.name), `duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name2)}`, "types", _types2); + uniqueNames.add(field.name); + const baseType = splitArray(field.type).base; + assertArgument(baseType !== name2, `circular type reference to ${JSON.stringify(baseType)}`, "types", _types2); + const encoder2 = getBaseEncoder(baseType); + if (encoder2) { + continue; + } + assertArgument(parents.has(baseType), `unknown type ${JSON.stringify(baseType)}`, "types", _types2); + parents.get(baseType).push(name2); + links.get(name2).add(baseType); + } + } + const primaryTypes = Array.from(parents.keys()).filter((n2) => parents.get(n2).length === 0); + assertArgument(primaryTypes.length !== 0, "missing primary type", "types", _types2); + assertArgument(primaryTypes.length === 1, `ambiguous primary types or unused types: ${primaryTypes.map((t2) => JSON.stringify(t2)).join(", ")}`, "types", _types2); + defineProperties$1(this, { primaryType: primaryTypes[0] }); + function checkCircular(type, found) { + assertArgument(!found.has(type), `circular type reference to ${JSON.stringify(type)}`, "types", _types2); + found.add(type); + for (const child of links.get(type)) { + if (!parents.has(child)) { + continue; + } + checkCircular(child, found); + for (const subtype of found) { + subtypes.get(subtype).add(child); + } + } + found.delete(type); + } + checkCircular(this.primaryType, /* @__PURE__ */ new Set()); + for (const [name2, set] of subtypes) { + const st = Array.from(set); + st.sort(); + __privateGet(this, _fullTypes).set(name2, encodeType(name2, types2[name2]) + st.map((t2) => encodeType(t2, types2[t2])).join("")); + } + } + /** + * The types. + */ + get types() { + return JSON.parse(__privateGet(this, _types)); + } + /** + * Returnthe encoder for the specific %%type%%. + */ + getEncoder(type) { + let encoder2 = __privateGet(this, _encoderCache).get(type); + if (!encoder2) { + encoder2 = __privateMethod(this, _TypedDataEncoder_instances, getEncoder_fn).call(this, type); + __privateGet(this, _encoderCache).set(type, encoder2); + } + return encoder2; + } + /** + * Return the full type for %%name%%. + */ + encodeType(name2) { + const result = __privateGet(this, _fullTypes).get(name2); + assertArgument(result, `unknown type: ${JSON.stringify(name2)}`, "name", name2); + return result; + } + /** + * Return the encoded %%value%% for the %%type%%. + */ + encodeData(type, value) { + return this.getEncoder(type)(value); + } + /** + * Returns the hash of %%value%% for the type of %%name%%. + */ + hashStruct(name2, value) { + return keccak256(this.encodeData(name2, value)); + } + /** + * Return the fulled encoded %%value%% for the [[types]]. + */ + encode(value) { + return this.encodeData(this.primaryType, value); + } + /** + * Return the hash of the fully encoded %%value%% for the [[types]]. + */ + hash(value) { + return this.hashStruct(this.primaryType, value); + } + /** + * @_ignore: + */ + _visit(type, value, callback) { + { + const encoder2 = getBaseEncoder(type); + if (encoder2) { + return callback(type, value); + } + } + const array = splitArray(type).array; + if (array) { + assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value); + return value.map((v3) => this._visit(array.prefix, v3, callback)); + } + const fields = this.types[type]; + if (fields) { + return fields.reduce((accum, { name: name2, type: type2 }) => { + accum[name2] = this._visit(type2, value[name2], callback); + return accum; + }, {}); + } + assertArgument(false, `unknown type: ${type}`, "type", type); + } + /** + * Call %%calback%% for each value in %%value%%, passing the type and + * component within %%value%%. + * + * This is useful for replacing addresses or other transformation that + * may be desired on each component, based on its type. + */ + visit(value, callback) { + return this._visit(this.primaryType, value, callback); + } + /** + * Create a new **TypedDataEncoder** for %%types%%. + */ + static from(types2) { + return new _TypedDataEncoder(types2); + } + /** + * Return the primary type for %%types%%. + */ + static getPrimaryType(types2) { + return _TypedDataEncoder.from(types2).primaryType; + } + /** + * Return the hashed struct for %%value%% using %%types%% and %%name%%. + */ + static hashStruct(name2, types2, value) { + return _TypedDataEncoder.from(types2).hashStruct(name2, value); + } + /** + * Return the domain hash for %%domain%%. + */ + static hashDomain(domain2) { + const domainFields = []; + for (const name2 in domain2) { + if (domain2[name2] == null) { + continue; + } + const type = domainFieldTypes[name2]; + assertArgument(type, `invalid typed-data domain key: ${JSON.stringify(name2)}`, "domain", domain2); + domainFields.push({ name: name2, type }); + } + domainFields.sort((a2, b2) => { + return domainFieldNames.indexOf(a2.name) - domainFieldNames.indexOf(b2.name); + }); + return _TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain2); + } + /** + * Return the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%. + */ + static encode(domain2, types2, value) { + return concat([ + "0x1901", + _TypedDataEncoder.hashDomain(domain2), + _TypedDataEncoder.from(types2).hash(value) + ]); + } + /** + * Return the hash of the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%. + */ + static hash(domain2, types2, value) { + return keccak256(_TypedDataEncoder.encode(domain2, types2, value)); + } + // Replaces all address types with ENS names with their looked up address + /** + * Resolves to the value from resolving all addresses in %%value%% for + * %%types%% and the %%domain%%. + */ + static async resolveNames(domain2, types2, value, resolveName) { + domain2 = Object.assign({}, domain2); + for (const key in domain2) { + if (domain2[key] == null) { + delete domain2[key]; + } + } + const ensCache = {}; + if (domain2.verifyingContract && !isHexString(domain2.verifyingContract, 20)) { + ensCache[domain2.verifyingContract] = "0x"; + } + const encoder2 = _TypedDataEncoder.from(types2); + encoder2.visit(value, (type, value2) => { + if (type === "address" && !isHexString(value2, 20)) { + ensCache[value2] = "0x"; + } + return value2; + }); + for (const name2 in ensCache) { + ensCache[name2] = await resolveName(name2); + } + if (domain2.verifyingContract && ensCache[domain2.verifyingContract]) { + domain2.verifyingContract = ensCache[domain2.verifyingContract]; + } + value = encoder2.visit(value, (type, value2) => { + if (type === "address" && ensCache[value2]) { + return ensCache[value2]; + } + return value2; + }); + return { domain: domain2, value }; + } + /** + * Returns the JSON-encoded payload expected by nodes which implement + * the JSON-RPC [[link-eip-712]] method. + */ + static getPayload(domain2, types2, value) { + _TypedDataEncoder.hashDomain(domain2); + const domainValues = {}; + const domainTypes = []; + domainFieldNames.forEach((name2) => { + const value2 = domain2[name2]; + if (value2 == null) { + return; + } + domainValues[name2] = domainChecks[name2](value2); + domainTypes.push({ name: name2, type: domainFieldTypes[name2] }); + }); + const encoder2 = _TypedDataEncoder.from(types2); + types2 = encoder2.types; + const typesWithDomain = Object.assign({}, types2); + assertArgument(typesWithDomain.EIP712Domain == null, "types must not contain EIP712Domain type", "types.EIP712Domain", types2); + typesWithDomain.EIP712Domain = domainTypes; + encoder2.encode(value); + return { + types: typesWithDomain, + domain: domainValues, + primaryType: encoder2.primaryType, + message: encoder2.visit(value, (type, value2) => { + if (type.match(/^bytes(\d*)/)) { + return hexlify(getBytes(value2)); + } + if (type.match(/^u?int/)) { + return getBigInt(value2).toString(); + } + switch (type) { + case "address": + return value2.toLowerCase(); + case "bool": + return !!value2; + case "string": + assertArgument(typeof value2 === "string", "invalid string", "value", value2); + return value2; + } + assertArgument(false, "unsupported type", "type", type); + }) }; - this.getGasTankBalanceAdjustment = (args, headers, signal) => { - return this.fetch(this.url("GetGasTankBalanceAdjustment"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - adjustment: _data6.adjustment - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); + } +}; +_types = new WeakMap(); +_fullTypes = new WeakMap(); +_encoderCache = new WeakMap(); +_TypedDataEncoder_instances = new WeakSet(); +getEncoder_fn = function(type) { + { + const encoder2 = getBaseEncoder(type); + if (encoder2) { + return encoder2; + } + } + const array = splitArray(type).array; + if (array) { + const subtype = array.prefix; + const subEncoder = this.getEncoder(subtype); + return (value) => { + assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value); + let result = value.map(subEncoder); + if (__privateGet(this, _fullTypes).has(subtype)) { + result = result.map(keccak256); + } + return keccak256(concat(result)); }; - this.listGasTankBalanceAdjustments = (args, headers, signal) => { - return this.fetch(this.url("ListGasTankBalanceAdjustments"), createHTTPRequest$6(args, headers, signal)).then((res) => { - return buildResponse$6(res).then((_data6) => { - return { - page: _data6.page, - adjustments: _data6.adjustments - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$6.new({ - cause: `fetch(): ${error.message || ""}` - }); + } + const fields = this.types[type]; + if (fields) { + const encodedType = id$1(__privateGet(this, _fullTypes).get(type)); + return (value) => { + const values = fields.map(({ name: name2, type: type2 }) => { + const result = this.getEncoder(type2)(value[name2]); + if (__privateGet(this, _fullTypes).has(type2)) { + return keccak256(result); + } + return result; }); + values.unshift(encodedType); + return concat(values); }; - this.hostname = hostname; - this.fetch = (input2, init2) => fetch2(input2, init2); } - url(name2) { - return this.hostname + this.path + name2; + assertArgument(false, `unknown type: ${type}`, "type", type); +}; +let TypedDataEncoder = _TypedDataEncoder; +function verifyTypedData(domain2, types2, value, signature2) { + return recoverAddress(TypedDataEncoder.hash(domain2, types2, value), signature2); +} +function setify(items) { + const result = /* @__PURE__ */ new Set(); + items.forEach((k2) => result.add(k2)); + return Object.freeze(result); +} +const _kwVisibDeploy = "external public payable override"; +const KwVisibDeploy = setify(_kwVisibDeploy.split(" ")); +const _kwVisib = "constant external internal payable private public pure view override"; +const KwVisib = setify(_kwVisib.split(" ")); +const _kwTypes = "constructor error event fallback function receive struct"; +const KwTypes = setify(_kwTypes.split(" ")); +const _kwModifiers = "calldata memory storage payable indexed"; +const KwModifiers = setify(_kwModifiers.split(" ")); +const _kwOther = "tuple returns"; +const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(" "); +const Keywords = setify(_keywords.split(" ")); +const SimpleTokens = { + "(": "OPEN_PAREN", + ")": "CLOSE_PAREN", + "[": "OPEN_BRACKET", + "]": "CLOSE_BRACKET", + ",": "COMMA", + "@": "AT" +}; +const regexWhitespacePrefix = new RegExp("^(\\s*)"); +const regexNumberPrefix = new RegExp("^([0-9]+)"); +const regexIdPrefix = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"); +const regexId = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"); +const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"); +const _TokenString = class _TokenString { + constructor(tokens) { + __privateAdd(this, _TokenString_instances); + __privateAdd(this, _offset2); + __privateAdd(this, _tokens); + __privateSet(this, _offset2, 0); + __privateSet(this, _tokens, tokens.slice()); + } + get offset() { + return __privateGet(this, _offset2); + } + get length() { + return __privateGet(this, _tokens).length - __privateGet(this, _offset2); + } + clone() { + return new _TokenString(__privateGet(this, _tokens)); + } + reset() { + __privateSet(this, _offset2, 0); + } + // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens + popKeyword(allowed) { + const top = this.peek(); + if (top.type !== "KEYWORD" || !allowed.has(top.text)) { + throw new Error(`expected keyword ${top.text}`); + } + return this.pop().text; + } + // Pops and returns the value of the next token if it is `type`; throws if out of tokens + popType(type) { + if (this.peek().type !== type) { + const top = this.peek(); + throw new Error(`expected ${type}; got ${top.type} ${JSON.stringify(top.text)}`); + } + return this.pop().text; + } + // Pops and returns a "(" TOKENS ")" + popParen() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = __privateMethod(this, _TokenString_instances, subTokenString_fn).call(this, __privateGet(this, _offset2) + 1, top.match + 1); + __privateSet(this, _offset2, top.match + 1); + return result; + } + // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")" + popParams() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = []; + while (__privateGet(this, _offset2) < top.match - 1) { + const link = this.peek().linkNext; + result.push(__privateMethod(this, _TokenString_instances, subTokenString_fn).call(this, __privateGet(this, _offset2) + 1, link)); + __privateSet(this, _offset2, link); + } + __privateSet(this, _offset2, top.match + 1); + return result; + } + // Returns the top Token, throwing if out of tokens + peek() { + if (__privateGet(this, _offset2) >= __privateGet(this, _tokens).length) { + throw new Error("out-of-bounds"); + } + return __privateGet(this, _tokens)[__privateGet(this, _offset2)]; + } + // Returns the next value, if it is a keyword in `allowed` + peekKeyword(allowed) { + const top = this.peekType("KEYWORD"); + return top != null && allowed.has(top) ? top : null; + } + // Returns the value of the next token if it is `type` + peekType(type) { + if (this.length === 0) { + return null; + } + const top = this.peek(); + return top.type === type ? top.text : null; + } + // Returns the next token; throws if out of tokens + pop() { + const result = this.peek(); + __privateWrapper(this, _offset2)._++; + return result; + } + toString() { + const tokens = []; + for (let i = __privateGet(this, _offset2); i < __privateGet(this, _tokens).length; i++) { + const token = __privateGet(this, _tokens)[i]; + tokens.push(`${token.type}:${token.text}`); + } + return ``; + } +}; +_offset2 = new WeakMap(); +_tokens = new WeakMap(); +_TokenString_instances = new WeakSet(); +subTokenString_fn = function(from = 0, to = 0) { + return new _TokenString(__privateGet(this, _tokens).slice(from, to).map((t2) => { + return Object.freeze(Object.assign({}, t2, { + match: t2.match - from, + linkBack: t2.linkBack - from, + linkNext: t2.linkNext - from + })); + })); +}; +let TokenString = _TokenString; +function lex(text2) { + const tokens = []; + const throwError2 = (message) => { + const token = offset2 < text2.length ? JSON.stringify(text2[offset2]) : "$EOI"; + throw new Error(`invalid token ${token} at ${offset2}: ${message}`); + }; + let brackets = []; + let commas = []; + let offset2 = 0; + while (offset2 < text2.length) { + let cur = text2.substring(offset2); + let match = cur.match(regexWhitespacePrefix); + if (match) { + offset2 += match[1].length; + cur = text2.substring(offset2); + } + const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset: offset2, value: -1 }; + tokens.push(token); + let type = SimpleTokens[cur[0]] || ""; + if (type) { + token.type = type; + token.text = cur[0]; + offset2++; + if (type === "OPEN_PAREN") { + brackets.push(tokens.length - 1); + commas.push(tokens.length - 1); + } else if (type == "CLOSE_PAREN") { + if (brackets.length === 0) { + throwError2("no matching open bracket"); + } + token.match = brackets.pop(); + tokens[token.match].match = tokens.length - 1; + token.depth--; + token.linkBack = commas.pop(); + tokens[token.linkBack].linkNext = tokens.length - 1; + } else if (type === "COMMA") { + token.linkBack = commas.pop(); + tokens[token.linkBack].linkNext = tokens.length - 1; + commas.push(tokens.length - 1); + } else if (type === "OPEN_BRACKET") { + token.type = "BRACKET"; + } else if (type === "CLOSE_BRACKET") { + let suffix = tokens.pop().text; + if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") { + const value = tokens.pop().text; + suffix = value + suffix; + tokens[tokens.length - 1].value = getNumber(value); + } + if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") { + throw new Error("missing opening bracket"); + } + tokens[tokens.length - 1].text += suffix; + } + continue; + } + match = cur.match(regexIdPrefix); + if (match) { + token.text = match[1]; + offset2 += token.text.length; + if (Keywords.has(token.text)) { + token.type = "KEYWORD"; + continue; + } + if (token.text.match(regexType)) { + token.type = "TYPE"; + continue; + } + token.type = "ID"; + continue; + } + match = cur.match(regexNumberPrefix); + if (match) { + token.text = match[1]; + token.type = "NUMBER"; + offset2 += token.text.length; + continue; + } + throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset2}`); } + return new TokenString(tokens.map((t2) => Object.freeze(t2))); } -const createHTTPRequest$6 = (body = {}, headers = {}, signal = null) => { - return { - method: "POST", - headers: _extends$a({}, headers, { - "Content-Type": "application/json" - }), - body: JSON.stringify(body || {}), - signal - }; -}; -const buildResponse$6 = (res) => { - return res.text().then((text2) => { - let data; - try { - data = JSON.parse(text2); - } catch (error) { - let message = ""; - if (error instanceof Error) { - message = error.message; +function allowSingle(set, allowed) { + let included = []; + for (const key in allowed.keys()) { + if (set.has(key)) { + included.push(key); + } + } + if (included.length > 1) { + throw new Error(`conflicting types: ${included.join(", ")}`); + } +} +function consumeName(type, tokens) { + if (tokens.peekKeyword(KwTypes)) { + const keyword = tokens.pop().text; + if (keyword !== type) { + throw new Error(`expected ${type}, got ${keyword}`); + } + } + return tokens.popType("ID"); +} +function consumeKeywords(tokens, allowed) { + const keywords = /* @__PURE__ */ new Set(); + while (true) { + const keyword = tokens.peekType("KEYWORD"); + if (keyword == null || allowed && !allowed.has(keyword)) { + break; + } + tokens.pop(); + if (keywords.has(keyword)) { + throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`); + } + keywords.add(keyword); + } + return Object.freeze(keywords); +} +function consumeMutability(tokens) { + let modifiers = consumeKeywords(tokens, KwVisib); + allowSingle(modifiers, setify("constant payable nonpayable".split(" "))); + allowSingle(modifiers, setify("pure view payable nonpayable".split(" "))); + if (modifiers.has("view")) { + return "view"; + } + if (modifiers.has("pure")) { + return "pure"; + } + if (modifiers.has("payable")) { + return "payable"; + } + if (modifiers.has("nonpayable")) { + return "nonpayable"; + } + if (modifiers.has("constant")) { + return "view"; + } + return "nonpayable"; +} +function consumeParams(tokens, allowIndexed) { + return tokens.popParams().map((t2) => ParamType.from(t2, allowIndexed)); +} +function consumeGas(tokens) { + if (tokens.peekType("AT")) { + tokens.pop(); + if (tokens.peekType("NUMBER")) { + return getBigInt(tokens.pop().text); + } + throw new Error("invalid gas"); + } + return null; +} +function consumeEoi(tokens) { + if (tokens.length) { + throw new Error(`unexpected tokens at offset ${tokens.offset}: ${tokens.toString()}`); + } +} +const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/); +function verifyBasicType(type) { + const match = type.match(regexType); + assertArgument(match, "invalid type", "type", type); + if (type === "uint") { + return "uint256"; + } + if (type === "int") { + return "int256"; + } + if (match[2]) { + const length = parseInt(match[2]); + assertArgument(length !== 0 && length <= 32, "invalid bytes length", "type", type); + } else if (match[3]) { + const size2 = parseInt(match[3]); + assertArgument(size2 !== 0 && size2 <= 256 && size2 % 8 === 0, "invalid numeric width", "type", type); + } + return type; +} +const _guard$2 = {}; +const internal$1 = Symbol.for("_ethers_internal"); +const ParamTypeInternal = "_ParamTypeInternal"; +const ErrorFragmentInternal = "_ErrorInternal"; +const EventFragmentInternal = "_EventInternal"; +const ConstructorFragmentInternal = "_ConstructorInternal"; +const FallbackFragmentInternal = "_FallbackInternal"; +const FunctionFragmentInternal = "_FunctionInternal"; +const StructFragmentInternal = "_StructInternal"; +const _ParamType = class _ParamType { + /** + * @private + */ + constructor(guard2, name2, type, baseType, indexed, components, arrayLength, arrayChildren) { + __privateAdd(this, _ParamType_instances); + /** + * The local name of the parameter (or ``""`` if unbound) + */ + __publicField(this, "name"); + /** + * The fully qualified type (e.g. ``"address"``, ``"tuple(address)"``, + * ``"uint256[3][]"``) + */ + __publicField(this, "type"); + /** + * The base type (e.g. ``"address"``, ``"tuple"``, ``"array"``) + */ + __publicField(this, "baseType"); + /** + * True if the parameters is indexed. + * + * For non-indexable types this is ``null``. + */ + __publicField(this, "indexed"); + /** + * The components for the tuple. + * + * For non-tuple types this is ``null``. + */ + __publicField(this, "components"); + /** + * The array length, or ``-1`` for dynamic-lengthed arrays. + * + * For non-array types this is ``null``. + */ + __publicField(this, "arrayLength"); + /** + * The type of each child in the array. + * + * For non-array types this is ``null``. + */ + __publicField(this, "arrayChildren"); + assertPrivate(guard2, _guard$2, "ParamType"); + Object.defineProperty(this, internal$1, { value: ParamTypeInternal }); + if (components) { + components = Object.freeze(components.slice()); + } + if (baseType === "array") { + if (arrayLength == null || arrayChildren == null) { + throw new Error(""); } - throw WebrpcBadResponseError$6.new({ - status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text2}` - }); + } else if (arrayLength != null || arrayChildren != null) { + throw new Error(""); } - if (!res.ok) { - const code2 = typeof data.code === "number" ? data.code : 0; - throw (webrpcErrorByCode$6[code2] || WebrpcError$6).new(data); + if (baseType === "tuple") { + if (components == null) { + throw new Error(""); + } + } else if (components != null) { + throw new Error(""); } - return data; - }); -}; -let WebrpcError$6 = class WebrpcError2 extends Error { - constructor(name2, code2, message, status, cause) { - super(message); - this.name = void 0; - this.code = void 0; - this.message = void 0; - this.status = void 0; - this.cause = void 0; - this.msg = void 0; - this.name = name2 || "WebrpcError"; - this.code = typeof code2 === "number" ? code2 : 0; - this.message = message || `endpoint error ${this.code}`; - this.msg = this.message; - this.status = typeof status === "number" ? status : 0; - this.cause = cause; - Object.setPrototypeOf(this, WebrpcError2.prototype); + defineProperties$1(this, { + name: name2, + type, + baseType, + indexed, + components, + arrayLength, + arrayChildren + }); } - static new(payload) { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + /** + * Return a string representation of this type. + * + * For example, + * + * ``sighash" => "(uint256,address)"`` + * + * ``"minimal" => "tuple(uint256,address) indexed"`` + * + * ``"full" => "tuple(uint256 foo, address bar) indexed baz"`` + */ + format(format2) { + if (format2 == null) { + format2 = "sighash"; + } + if (format2 === "json") { + const name2 = this.name || ""; + if (this.isArray()) { + const result3 = JSON.parse(this.arrayChildren.format("json")); + result3.name = name2; + result3.type += `[${this.arrayLength < 0 ? "" : String(this.arrayLength)}]`; + return JSON.stringify(result3); + } + const result2 = { + type: this.baseType === "tuple" ? "tuple" : this.type, + name: name2 + }; + if (typeof this.indexed === "boolean") { + result2.indexed = this.indexed; + } + if (this.isTuple()) { + result2.components = this.components.map((c2) => JSON.parse(c2.format(format2))); + } + return JSON.stringify(result2); + } + let result = ""; + if (this.isArray()) { + result += this.arrayChildren.format(format2); + result += `[${this.arrayLength < 0 ? "" : String(this.arrayLength)}]`; + } else { + if (this.isTuple()) { + result += "(" + this.components.map((comp) => comp.format(format2)).join(format2 === "full" ? ", " : ",") + ")"; + } else { + result += this.type; + } + } + if (format2 !== "sighash") { + if (this.indexed === true) { + result += " indexed"; + } + if (format2 === "full" && this.name) { + result += " " + this.name; + } + } + return result; } -}; -let WebrpcEndpointError$6 = class WebrpcEndpointError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcEndpointError2.prototype); + /** + * Returns true if %%this%% is an Array type. + * + * This provides a type gaurd ensuring that [[arrayChildren]] + * and [[arrayLength]] are non-null. + */ + isArray() { + return this.baseType === "array"; } -}; -let WebrpcRequestFailedError$6 = class WebrpcRequestFailedError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcRequestFailedError2.prototype); + /** + * Returns true if %%this%% is a Tuple type. + * + * This provides a type gaurd ensuring that [[components]] + * is non-null. + */ + isTuple() { + return this.baseType === "tuple"; } -}; -let WebrpcBadRouteError$6 = class WebrpcBadRouteError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRouteError2.prototype); + /** + * Returns true if %%this%% is an Indexable type. + * + * This provides a type gaurd ensuring that [[indexed]] + * is non-null. + */ + isIndexable() { + return this.indexed != null; } -}; -let WebrpcBadMethodError$6 = class WebrpcBadMethodError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadMethodError2.prototype); + /** + * Walks the **ParamType** with %%value%%, calling %%process%% + * on each type, destructing the %%value%% recursively. + */ + walk(value, process2) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invalid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + const _this = this; + return value.map((v3) => _this.arrayChildren.walk(v3, process2)); + } + if (this.isTuple()) { + if (!Array.isArray(value)) { + throw new Error("invalid tuple value"); + } + if (value.length !== this.components.length) { + throw new Error("array is wrong length"); + } + const _this = this; + return value.map((v3, i) => _this.components[i].walk(v3, process2)); + } + return process2(this.type, value); } -}; -let WebrpcBadRequestError$6 = class WebrpcBadRequestError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRequestError2.prototype); + /** + * Walks the **ParamType** with %%value%%, asynchronously calling + * %%process%% on each type, destructing the %%value%% recursively. + * + * This can be used to resolve ENS names by walking and resolving each + * ``"address"`` type. + */ + async walkAsync(value, process2) { + const promises = []; + const result = [value]; + __privateMethod(this, _ParamType_instances, walkAsync_fn).call(this, promises, value, process2, (value2) => { + result[0] = value2; + }); + if (promises.length) { + await Promise.all(promises); + } + return result[0]; + } + /** + * Creates a new **ParamType** for %%obj%%. + * + * If %%allowIndexed%% then the ``indexed`` keyword is permitted, + * otherwise the ``indexed`` keyword will throw an error. + */ + static from(obj, allowIndexed) { + if (_ParamType.isParamType(obj)) { + return obj; + } + if (typeof obj === "string") { + try { + return _ParamType.from(lex(obj), allowIndexed); + } catch (error) { + assertArgument(false, "invalid param type", "obj", obj); + } + } else if (obj instanceof TokenString) { + let type2 = "", baseType = ""; + let comps = null; + if (consumeKeywords(obj, setify(["tuple"])).has("tuple") || obj.peekType("OPEN_PAREN")) { + baseType = "tuple"; + comps = obj.popParams().map((t2) => _ParamType.from(t2)); + type2 = `tuple(${comps.map((c2) => c2.format()).join(",")})`; + } else { + type2 = verifyBasicType(obj.popType("TYPE")); + baseType = type2; + } + let arrayChildren = null; + let arrayLength = null; + while (obj.length && obj.peekType("BRACKET")) { + const bracket = obj.pop(); + arrayChildren = new _ParamType(_guard$2, "", type2, baseType, null, comps, arrayLength, arrayChildren); + arrayLength = bracket.value; + type2 += bracket.text; + baseType = "array"; + comps = null; + } + let indexed2 = null; + const keywords = consumeKeywords(obj, KwModifiers); + if (keywords.has("indexed")) { + if (!allowIndexed) { + throw new Error(""); + } + indexed2 = true; + } + const name3 = obj.peekType("ID") ? obj.pop().text : ""; + if (obj.length) { + throw new Error("leftover tokens"); + } + return new _ParamType(_guard$2, name3, type2, baseType, indexed2, comps, arrayLength, arrayChildren); + } + const name2 = obj.name; + assertArgument(!name2 || typeof name2 === "string" && name2.match(regexId), "invalid name", "obj.name", name2); + let indexed = obj.indexed; + if (indexed != null) { + assertArgument(allowIndexed, "parameter cannot be indexed", "obj.indexed", obj.indexed); + indexed = !!indexed; + } + let type = obj.type; + let arrayMatch = type.match(regexArrayType); + if (arrayMatch) { + const arrayLength = parseInt(arrayMatch[2] || "-1"); + const arrayChildren = _ParamType.from({ + type: arrayMatch[1], + components: obj.components + }); + return new _ParamType(_guard$2, name2 || "", type, "array", indexed, null, arrayLength, arrayChildren); + } + if (type === "tuple" || type.startsWith( + "tuple(" + /* fix: ) */ + ) || type.startsWith( + "(" + /* fix: ) */ + )) { + const comps = obj.components != null ? obj.components.map((c2) => _ParamType.from(c2)) : null; + const tuple = new _ParamType(_guard$2, name2 || "", type, "tuple", indexed, comps, null, null); + return tuple; + } + type = verifyBasicType(obj.type); + return new _ParamType(_guard$2, name2 || "", type, type, indexed, null, null, null); } -}; -let WebrpcBadResponseError$6 = class WebrpcBadResponseError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadResponseError2.prototype); + /** + * Returns true if %%value%% is a **ParamType**. + */ + static isParamType(value) { + return value && value[internal$1] === ParamTypeInternal; } }; -let WebrpcServerPanicError$6 = class WebrpcServerPanicError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcServerPanicError2.prototype); +_ParamType_instances = new WeakSet(); +walkAsync_fn = function(promises, value, process2, setValue) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invalid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + const childType = this.arrayChildren; + const result2 = value.slice(); + result2.forEach((value2, index2) => { + var _a2; + __privateMethod(_a2 = childType, _ParamType_instances, walkAsync_fn).call(_a2, promises, value2, process2, (value3) => { + result2[index2] = value3; + }); + }); + setValue(result2); + return; } -}; -let WebrpcInternalErrorError$6 = class WebrpcInternalErrorError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcInternalErrorError2.prototype); + if (this.isTuple()) { + const components = this.components; + let result2; + if (Array.isArray(value)) { + result2 = value.slice(); + } else { + if (value == null || typeof value !== "object") { + throw new Error("invalid tuple value"); + } + result2 = components.map((param) => { + if (!param.name) { + throw new Error("cannot use object value with unnamed components"); + } + if (!(param.name in value)) { + throw new Error(`missing value for component ${param.name}`); + } + return value[param.name]; + }); + } + if (result2.length !== this.components.length) { + throw new Error("array is wrong length"); + } + result2.forEach((value2, index2) => { + var _a2; + __privateMethod(_a2 = components[index2], _ParamType_instances, walkAsync_fn).call(_a2, promises, value2, process2, (value3) => { + result2[index2] = value3; + }); + }); + setValue(result2); + return; } -}; -let WebrpcClientDisconnectedError$6 = class WebrpcClientDisconnectedError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcClientDisconnectedError2.prototype); + const result = process2(this.type, value); + if (result.then) { + promises.push(async function() { + setValue(await result); + }()); + } else { + setValue(result); } }; -let WebrpcStreamLostError$6 = class WebrpcStreamLostError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamLostError2.prototype); +let ParamType = _ParamType; +class Fragment { + /** + * @private + */ + constructor(guard2, type, inputs) { + /** + * The type of the fragment. + */ + __publicField(this, "type"); + /** + * The inputs for the fragment. + */ + __publicField(this, "inputs"); + assertPrivate(guard2, _guard$2, "Fragment"); + inputs = Object.freeze(inputs.slice()); + defineProperties$1(this, { type, inputs }); } -}; -let WebrpcStreamFinishedError$6 = class WebrpcStreamFinishedError2 extends WebrpcError$6 { - constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamFinishedError2.prototype); + /** + * Creates a new **Fragment** for %%obj%%, wich can be any supported + * ABI frgament type. + */ + static from(obj) { + if (typeof obj === "string") { + try { + Fragment.from(JSON.parse(obj)); + } catch (e2) { + } + return Fragment.from(lex(obj)); + } + if (obj instanceof TokenString) { + const type = obj.peekKeyword(KwTypes); + switch (type) { + case "constructor": + return ConstructorFragment.from(obj); + case "error": + return ErrorFragment.from(obj); + case "event": + return EventFragment.from(obj); + case "fallback": + case "receive": + return FallbackFragment.from(obj); + case "function": + return FunctionFragment.from(obj); + case "struct": + return StructFragment.from(obj); + } + } else if (typeof obj === "object") { + switch (obj.type) { + case "constructor": + return ConstructorFragment.from(obj); + case "error": + return ErrorFragment.from(obj); + case "event": + return EventFragment.from(obj); + case "fallback": + case "receive": + return FallbackFragment.from(obj); + case "function": + return FunctionFragment.from(obj); + case "struct": + return StructFragment.from(obj); + } + assert(false, `unsupported type: ${obj.type}`, "UNSUPPORTED_OPERATION", { + operation: "Fragment.from" + }); + } + assertArgument(false, "unsupported frgament object", "obj", obj); } -}; -let UnauthorizedError$5 = class UnauthorizedError2 extends WebrpcError$6 { - constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, UnauthorizedError2.prototype); + /** + * Returns true if %%value%% is a [[ConstructorFragment]]. + */ + static isConstructor(value) { + return ConstructorFragment.isFragment(value); } -}; -let PermissionDeniedError$3 = class PermissionDeniedError2 extends WebrpcError$6 { - constructor(name2 = "PermissionDenied", code2 = 1001, message = "Permission denied", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, PermissionDeniedError2.prototype); + /** + * Returns true if %%value%% is an [[ErrorFragment]]. + */ + static isError(value) { + return ErrorFragment.isFragment(value); } -}; -let MethodNotFoundError$2 = class MethodNotFoundError extends WebrpcError$6 { - constructor(name2 = "MethodNotFound", code2 = 1003, message = "Method not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, MethodNotFoundError.prototype); + /** + * Returns true if %%value%% is an [[EventFragment]]. + */ + static isEvent(value) { + return EventFragment.isFragment(value); } -}; -let AbortedError$2 = class AbortedError2 extends WebrpcError$6 { - constructor(name2 = "Aborted", code2 = 1005, message = "Request aborted", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, AbortedError2.prototype); + /** + * Returns true if %%value%% is a [[FunctionFragment]]. + */ + static isFunction(value) { + return FunctionFragment.isFragment(value); } -}; -let InvalidArgumentError$4 = class InvalidArgumentError2 extends WebrpcError$6 { - constructor(name2 = "InvalidArgument", code2 = 2001, message = "Invalid argument", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, InvalidArgumentError2.prototype); + /** + * Returns true if %%value%% is a [[StructFragment]]. + */ + static isStruct(value) { + return StructFragment.isFragment(value); } -}; -let UnavailableError$2 = class UnavailableError2 extends WebrpcError$6 { - constructor(name2 = "Unavailable", code2 = 2002, message = "Unavailable resource", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, UnavailableError2.prototype); +} +class NamedFragment extends Fragment { + /** + * @private + */ + constructor(guard2, type, name2, inputs) { + super(guard2, type, inputs); + /** + * The name of the fragment. + */ + __publicField(this, "name"); + assertArgument(typeof name2 === "string" && name2.match(regexId), "invalid identifier", "name", name2); + inputs = Object.freeze(inputs.slice()); + defineProperties$1(this, { name: name2 }); } -}; -let QueryFailedError$4 = class QueryFailedError2 extends WebrpcError$6 { - constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, QueryFailedError2.prototype); +} +function joinParams(format2, params) { + return "(" + params.map((p2) => p2.format(format2)).join(format2 === "full" ? ", " : ",") + ")"; +} +class ErrorFragment extends NamedFragment { + /** + * @private + */ + constructor(guard2, name2, inputs) { + super(guard2, "error", name2, inputs); + Object.defineProperty(this, internal$1, { value: ErrorFragmentInternal }); } -}; -let NotFoundError$5 = class NotFoundError2 extends WebrpcError$6 { - constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, NotFoundError2.prototype); + /** + * The Custom Error selector. + */ + get selector() { + return id$1(this.format("sighash")).substring(0, 10); } -}; -let errors$2 = /* @__PURE__ */ function(errors2) { - errors2["WebrpcEndpoint"] = "WebrpcEndpoint"; - errors2["WebrpcRequestFailed"] = "WebrpcRequestFailed"; - errors2["WebrpcBadRoute"] = "WebrpcBadRoute"; - errors2["WebrpcBadMethod"] = "WebrpcBadMethod"; - errors2["WebrpcBadRequest"] = "WebrpcBadRequest"; - errors2["WebrpcBadResponse"] = "WebrpcBadResponse"; - errors2["WebrpcServerPanic"] = "WebrpcServerPanic"; - errors2["WebrpcInternalError"] = "WebrpcInternalError"; - errors2["WebrpcClientDisconnected"] = "WebrpcClientDisconnected"; - errors2["WebrpcStreamLost"] = "WebrpcStreamLost"; - errors2["WebrpcStreamFinished"] = "WebrpcStreamFinished"; - errors2["Unauthorized"] = "Unauthorized"; - errors2["PermissionDenied"] = "PermissionDenied"; - errors2["MethodNotFound"] = "MethodNotFound"; - errors2["Aborted"] = "Aborted"; - errors2["InvalidArgument"] = "InvalidArgument"; - errors2["Unavailable"] = "Unavailable"; - errors2["QueryFailed"] = "QueryFailed"; - errors2["NotFound"] = "NotFound"; - return errors2; -}({}); -const webrpcErrorByCode$6 = { - [0]: WebrpcEndpointError$6, - [-1]: WebrpcRequestFailedError$6, - [-2]: WebrpcBadRouteError$6, - [-3]: WebrpcBadMethodError$6, - [-4]: WebrpcBadRequestError$6, - [-5]: WebrpcBadResponseError$6, - [-6]: WebrpcServerPanicError$6, - [-7]: WebrpcInternalErrorError$6, - [-8]: WebrpcClientDisconnectedError$6, - [-9]: WebrpcStreamLostError$6, - [-10]: WebrpcStreamFinishedError$6, - [1e3]: UnauthorizedError$5, - [1001]: PermissionDeniedError$3, - [1003]: MethodNotFoundError$2, - [1005]: AbortedError$2, - [2001]: InvalidArgumentError$4, - [2002]: UnavailableError$2, - [2003]: QueryFailedError$4, - [3e3]: NotFoundError$5 -}; -var relayer_gen = /* @__PURE__ */ Object.freeze({ - __proto__: null, - WebRPCVersion: WebRPCVersion$2, - WebRPCSchemaVersion: WebRPCSchemaVersion$2, - WebRPCSchemaHash: WebRPCSchemaHash$2, - ETHTxnStatus, - TransferType, - FeeTokenType: FeeTokenType$1, - SortOrder: SortOrder$1, - Relayer, - WebrpcError: WebrpcError$6, - WebrpcEndpointError: WebrpcEndpointError$6, - WebrpcRequestFailedError: WebrpcRequestFailedError$6, - WebrpcBadRouteError: WebrpcBadRouteError$6, - WebrpcBadMethodError: WebrpcBadMethodError$6, - WebrpcBadRequestError: WebrpcBadRequestError$6, - WebrpcBadResponseError: WebrpcBadResponseError$6, - WebrpcServerPanicError: WebrpcServerPanicError$6, - WebrpcInternalErrorError: WebrpcInternalErrorError$6, - WebrpcClientDisconnectedError: WebrpcClientDisconnectedError$6, - WebrpcStreamLostError: WebrpcStreamLostError$6, - WebrpcStreamFinishedError: WebrpcStreamFinishedError$6, - UnauthorizedError: UnauthorizedError$5, - PermissionDeniedError: PermissionDeniedError$3, - MethodNotFoundError: MethodNotFoundError$2, - AbortedError: AbortedError$2, - InvalidArgumentError: InvalidArgumentError$4, - UnavailableError: UnavailableError$2, - QueryFailedError: QueryFailedError$4, - NotFoundError: NotFoundError$5, - errors: errors$2 -}); -const FINAL_STATUSES = [ETHTxnStatus.DROPPED, ETHTxnStatus.SUCCEEDED, ETHTxnStatus.PARTIALLY_FAILED, ETHTxnStatus.FAILED]; -const FAILED_STATUSES = [ETHTxnStatus.DROPPED, ETHTxnStatus.PARTIALLY_FAILED, ETHTxnStatus.FAILED]; -function isRpcRelayerOptions(obj) { - return obj.url !== void 0 && typeof obj.url === "string" && obj.provider !== void 0 && obj.provider instanceof AbstractProvider; -} -const fetch$5 = globalThis.fetch; -class RpcRelayer { - constructor(options) { - this.options = options; - this.service = void 0; - this.provider = void 0; - this._fetch = (input2, init2) => { - const headers = {}; - const { - jwtAuth, - projectAccessKey: projectAccessKey2 - } = this.options; - if (jwtAuth && jwtAuth.length > 0) { - headers["Authorization"] = `BEARER ${jwtAuth}`; - } - if (projectAccessKey2 && projectAccessKey2.length > 0) { - headers["X-Access-Key"] = projectAccessKey2; - } - init2.headers = _extends$a({}, init2.headers, headers); - return fetch$5(input2, init2); - }; - this.service = new Relayer(options.url, this._fetch); - if (options.provider instanceof AbstractProvider) { - this.provider = options.provider; - } else { - const { - jwtAuth, - projectAccessKey: projectAccessKey2 - } = this.options; - const fetchRequest = getFetchRequest(options.provider.url, projectAccessKey2, jwtAuth); - this.provider = new JsonRpcProvider$1(fetchRequest, void 0, { - staticNetwork: true - }); + /** + * Returns a string representation of this fragment as %%format%%. + */ + format(format2) { + if (format2 == null) { + format2 = "sighash"; } - } - async waitReceipt(metaTxnId, delay2 = 1e3, maxFails = 5, isCancelled) { - if (typeof metaTxnId !== "string") { - metaTxnId = index$1$2.transaction.intendedTransactionID(metaTxnId); + if (format2 === "json") { + return JSON.stringify({ + type: "error", + name: this.name, + inputs: this.inputs.map((input2) => JSON.parse(input2.format(format2))) + }); } - logger.info(`[rpc-relayer/waitReceipt] waiting for ${metaTxnId}`); - let fails = 0; - while (isCancelled === void 0 || !isCancelled()) { - try { - const { - receipt - } = await this.service.getMetaTxnReceipt({ - metaTxID: metaTxnId - }); - if (receipt && receipt.txnReceipt && receipt.txnReceipt !== "null" && FINAL_STATUSES.includes(receipt.status)) { - return { - receipt - }; - } - } catch (e2) { - fails++; - if (fails === maxFails) { - throw e2; - } - } - if (isCancelled === void 0 || !isCancelled()) { - await new Promise((resolve) => setTimeout(resolve, delay2)); - } + const result = []; + if (format2 !== "sighash") { + result.push("error"); } - throw new Error(`Cancelled waiting for transaction receipt ${metaTxnId}`); - } - async simulate(wallet, ...transactions2) { - const coder = AbiCoder.defaultAbiCoder(); - const encoded = coder.encode([index$1$2.transaction.MetaTransactionsType], [index$1$2.transaction.sequenceTxAbiEncode(transactions2)]); - return (await this.service.simulate({ - wallet, - transactions: encoded - })).results; + result.push(this.name + joinParams(format2, this.inputs)); + return result.join(" "); } - async getFeeOptions(address, ...transactions2) { - const feeTokens = await this.service.feeTokens(); - if (feeTokens.isFeeRequired) { - const symbols = feeTokens.tokens.map((token) => token.symbol).join(", "); - logger.info(`[rpc-relayer/getFeeOptions] relayer fees are required, accepted tokens are ${symbols}`); - const nonce = await this.getNonce(address); - if (!this.provider) { - logger.warn(`[rpc-relayer/getFeeOptions] provider not set, needed for stub signature`); - throw new Error("provider is not set"); - } - const { - options, - quote - } = await this.service.feeOptions({ - wallet: address, - to: address, - data: index$1$2.transaction.encodeBundleExecData({ - entrypoint: address, - transactions: transactions2, - nonce - }) - }); - logger.info(`[rpc-relayer/getFeeOptions] got refund options ${JSON.stringify(options, bigintReplacer)}`); - return { - options, - quote: { - _tag: "FeeQuote", - _quote: quote - } - }; - } else { - logger.info(`[rpc-relayer/getFeeOptions] relayer fees are not required`); - return { - options: [] - }; + /** + * Returns a new **ErrorFragment** for %%obj%%. + */ + static from(obj) { + if (ErrorFragment.isFragment(obj)) { + return obj; } + if (typeof obj === "string") { + return ErrorFragment.from(lex(obj)); + } else if (obj instanceof TokenString) { + const name2 = consumeName("error", obj); + const inputs = consumeParams(obj); + consumeEoi(obj); + return new ErrorFragment(_guard$2, name2, inputs); + } + return new ErrorFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); } - async getFeeOptionsRaw(entrypoint, data, options) { - const { - options: feeOptions2, - quote - } = await this.service.feeOptions({ - wallet: entrypoint, - to: entrypoint, - data: hexlify(data), - simulate: options == null ? void 0 : options.simulate - }); - return { - options: feeOptions2, - quote: { - _tag: "FeeQuote", - _quote: quote - } - }; - } - async gasRefundOptions(address, ...transactions2) { - const { - options - } = await this.getFeeOptions(address, ...transactions2); - return options; + /** + * Returns ``true`` and provides a type guard if %%value%% is an + * **ErrorFragment**. + */ + static isFragment(value) { + return value && value[internal$1] === ErrorFragmentInternal; } - async getNonce(address, space) { - logger.info(`[rpc-relayer/getNonce] get nonce for wallet ${address} space: ${space}`); - const encodedNonce = space !== void 0 ? toHexString(BigInt(space)) : void 0; - const resp = await this.service.getMetaTxnNonce({ - walletContractAddress: address, - space: encodedNonce - }); - const nonce = BigInt(resp.nonce); - const [decodedSpace, decodedNonce] = index$1$2.transaction.decodeNonce(nonce); - logger.info(`[rpc-relayer/getNonce] got next nonce for wallet ${address} ${decodedNonce} space: ${decodedSpace}`); - return nonce; +} +class EventFragment extends NamedFragment { + /** + * @private + */ + constructor(guard2, name2, inputs, anonymous) { + super(guard2, "event", name2, inputs); + /** + * Whether this event is anonymous. + */ + __publicField(this, "anonymous"); + Object.defineProperty(this, internal$1, { value: EventFragmentInternal }); + defineProperties$1(this, { anonymous }); } - async relay(signedTxs, quote, waitForReceipt = true) { - var _this = this; - logger.info(`[rpc-relayer/relay] relaying signed meta-transactions ${JSON.stringify(signedTxs, bigintReplacer)} with quote ${JSON.stringify(quote, bigintReplacer)}`); - let typecheckedQuote; - if (quote !== void 0) { - if (typeof quote._quote === "string") { - typecheckedQuote = quote._quote; - } else { - logger.warn("[rpc-relayer/relay] ignoring invalid fee quote"); - } + /** + * The Event topic hash. + */ + get topicHash() { + return id$1(this.format("sighash")); + } + /** + * Returns a string representation of this event as %%format%%. + */ + format(format2) { + if (format2 == null) { + format2 = "sighash"; } - if (!this.provider) { - logger.warn(`[rpc-relayer/relay] provider not set, failed relay`); - throw new Error("provider is not set"); + if (format2 === "json") { + return JSON.stringify({ + type: "event", + anonymous: this.anonymous, + name: this.name, + inputs: this.inputs.map((i) => JSON.parse(i.format(format2))) + }); } - const data = index$1$2.transaction.encodeBundleExecData(signedTxs); - const metaTxn = await this.service.sendMetaTxn({ - call: { - walletAddress: signedTxs.intent.wallet, - contract: signedTxs.entrypoint, - input: data - }, - quote: typecheckedQuote - }); - logger.info(`[rpc-relayer/relay] got relay result ${JSON.stringify(metaTxn, bigintReplacer)}`); - if (waitForReceipt) { - return this.wait(signedTxs.intent.id); - } else { - const response = { - hash: signedTxs.intent.id, - confirmations: 0, - from: signedTxs.intent.wallet, - wait: (_confirmations) => Promise.reject(new Error("impossible")) - }; - const wait2 = async function wait3(confirmations) { - var _waitResponse$receipt; - if (!_this.provider) { - throw new Error("cannot wait for receipt, relayer has no provider set"); - } - const waitResponse = await _this.wait(signedTxs.intent.id); - const transactionHash = (_waitResponse$receipt = waitResponse.receipt) == null ? void 0 : _waitResponse$receipt.transactionHash; - if (!transactionHash) { - throw new Error("cannot wait for receipt, unknown native transaction hash"); - } - Object.assign(response, waitResponse); - return _this.provider.waitForTransaction(transactionHash, confirmations); - }; - response.wait = wait2; - return response; + const result = []; + if (format2 !== "sighash") { + result.push("event"); } + result.push(this.name + joinParams(format2, this.inputs)); + if (format2 !== "sighash" && this.anonymous) { + result.push("anonymous"); + } + return result.join(" "); } - async wait(metaTxnId, timeout, delay2 = 1e3, maxFails = 5) { - var _this2 = this; - let timedOut = false; - const { - receipt - } = await (timeout !== void 0 ? Promise.race([this.waitReceipt(metaTxnId, delay2, maxFails, () => timedOut), new Promise((_, reject) => setTimeout(() => { - timedOut = true; - reject(`Timeout waiting for transaction receipt ${metaTxnId}`); - }, timeout))]) : this.waitReceipt(metaTxnId, delay2, maxFails)); - if (!receipt.txnReceipt || FAILED_STATUSES.includes(receipt.status)) { - throw new MetaTransactionResponseException(receipt); + /** + * Return the topic hash for an event with %%name%% and %%params%%. + */ + static getTopicHash(name2, params) { + params = (params || []).map((p2) => ParamType.from(p2)); + const fragment = new EventFragment(_guard$2, name2, params, false); + return fragment.topicHash; + } + /** + * Returns a new **EventFragment** for %%obj%%. + */ + static from(obj) { + if (EventFragment.isFragment(obj)) { + return obj; } - const txReceipt = JSON.parse(receipt.txnReceipt); - return { - blockHash: txReceipt.blockHash, - blockNumber: Number(txReceipt.blockNumber), - confirmations: 1, - from: typeof metaTxnId === "string" ? void 0 : metaTxnId.intent.wallet, - hash: txReceipt.transactionHash, - raw: receipt.txnReceipt, - receipt: txReceipt, - // extended type which is Sequence-specific. Contains the decoded metaTxReceipt - wait: async function(confirmations) { - return _this2.provider.waitForTransaction(txReceipt.transactionHash, confirmations); + if (typeof obj === "string") { + try { + return EventFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid event fragment", "obj", obj); } - }; + } else if (obj instanceof TokenString) { + const name2 = consumeName("event", obj); + const inputs = consumeParams(obj, true); + const anonymous = !!consumeKeywords(obj, setify(["anonymous"])).has("anonymous"); + consumeEoi(obj); + return new EventFragment(_guard$2, name2, inputs, anonymous); + } + return new EventFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map((p2) => ParamType.from(p2, true)) : [], !!obj.anonymous); } -} -class MetaTransactionResponseException { - constructor(receipt) { - this.receipt = receipt; + /** + * Returns ``true`` and provides a type guard if %%value%% is an + * **EventFragment**. + */ + static isFragment(value) { + return value && value[internal$1] === EventFragmentInternal; } } -function isRelayer(cand) { - return typeof cand === "object" && typeof cand.simulate === "function" && typeof cand.getFeeOptions === "function" && typeof cand.gasRefundOptions === "function" && typeof cand.getNonce === "function" && typeof cand.relay === "function" && typeof cand.wait === "function"; -} -const relayer$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - LocalRelayer, - ProviderRelayer, - ProviderRelayerDefaults, - RpcRelayer, - RpcRelayerProto: relayer_gen, - isLocalRelayerOptions, - isProviderRelayerOptions, - isRelayer, - isRpcRelayerOptions, - proto: relayer_gen -}, Symbol.toStringTag, { value: "Module" })); -function isSapientSigner(signer2) { - return signer2.getAddress !== void 0 && signer2.buildDeployTransaction !== void 0 && signer2.predecorateSignedTransactions !== void 0 && signer2.decorateTransactions !== void 0 && signer2.sign !== void 0 && signer2.notifyStatusChange !== void 0; -} -class SignerWrapper { - constructor(signer2, eoa = true) { - this.signer = signer2; - this.eoa = eoa; +class ConstructorFragment extends Fragment { + /** + * @private + */ + constructor(guard2, type, inputs, payable, gas) { + super(guard2, type, inputs); + /** + * Whether the constructor can receive an endowment. + */ + __publicField(this, "payable"); + /** + * The recommended gas limit for deployment or ``null``. + */ + __publicField(this, "gas"); + Object.defineProperty(this, internal$1, { value: ConstructorFragmentInternal }); + defineProperties$1(this, { payable, gas }); } - getAddress() { - return this.signer.getAddress(); + /** + * Returns a string representation of this constructor as %%format%%. + */ + format(format2) { + assert(format2 != null && format2 !== "sighash", "cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { operation: "format(sighash)" }); + if (format2 === "json") { + return JSON.stringify({ + type: "constructor", + stateMutability: this.payable ? "payable" : "undefined", + payable: this.payable, + gas: this.gas != null ? this.gas : void 0, + inputs: this.inputs.map((i) => JSON.parse(i.format(format2))) + }); + } + const result = [`constructor${joinParams(format2, this.inputs)}`]; + if (this.payable) { + result.push("payable"); + } + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + return result.join(" "); } - async buildDeployTransaction(_metadata) { - return; + /** + * Returns a new **ConstructorFragment** for %%obj%%. + */ + static from(obj) { + if (ConstructorFragment.isFragment(obj)) { + return obj; + } + if (typeof obj === "string") { + try { + return ConstructorFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid constuctor fragment", "obj", obj); + } + } else if (obj instanceof TokenString) { + consumeKeywords(obj, setify(["constructor"])); + const inputs = consumeParams(obj); + const payable = !!consumeKeywords(obj, KwVisibDeploy).has("payable"); + const gas = consumeGas(obj); + consumeEoi(obj); + return new ConstructorFragment(_guard$2, "constructor", inputs, payable, gas); + } + return new ConstructorFragment(_guard$2, "constructor", obj.inputs ? obj.inputs.map(ParamType.from) : [], !!obj.payable, obj.gas != null ? obj.gas : null); } - async predecorateSignedTransactions(_metadata) { - return []; + /** + * Returns ``true`` and provides a type guard if %%value%% is a + * **ConstructorFragment**. + */ + static isFragment(value) { + return value && value[internal$1] === ConstructorFragmentInternal; } - async decorateTransactions(bundle, _metadata) { - return bundle; +} +class FallbackFragment extends Fragment { + constructor(guard2, inputs, payable) { + super(guard2, "fallback", inputs); + /** + * If the function can be sent value during invocation. + */ + __publicField(this, "payable"); + Object.defineProperty(this, internal$1, { value: FallbackFragmentInternal }); + defineProperties$1(this, { payable }); } - sign(message) { - return this.signer.signMessage(message); + /** + * Returns a string representation of this fallback as %%format%%. + */ + format(format2) { + const type = this.inputs.length === 0 ? "receive" : "fallback"; + if (format2 === "json") { + const stateMutability = this.payable ? "payable" : "nonpayable"; + return JSON.stringify({ type, stateMutability }); + } + return `${type}()${this.payable ? " payable" : ""}`; } - notifyStatusChange(_i2, _s2, _m2) { + /** + * Returns a new **FallbackFragment** for %%obj%%. + */ + static from(obj) { + if (FallbackFragment.isFragment(obj)) { + return obj; + } + if (typeof obj === "string") { + try { + return FallbackFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid fallback fragment", "obj", obj); + } + } else if (obj instanceof TokenString) { + const errorObj = obj.toString(); + const topIsValid = obj.peekKeyword(setify(["fallback", "receive"])); + assertArgument(topIsValid, "type must be fallback or receive", "obj", errorObj); + const type = obj.popKeyword(setify(["fallback", "receive"])); + if (type === "receive") { + const inputs2 = consumeParams(obj); + assertArgument(inputs2.length === 0, `receive cannot have arguments`, "obj.inputs", inputs2); + consumeKeywords(obj, setify(["payable"])); + consumeEoi(obj); + return new FallbackFragment(_guard$2, [], true); + } + let inputs = consumeParams(obj); + if (inputs.length) { + assertArgument(inputs.length === 1 && inputs[0].type === "bytes", "invalid fallback inputs", "obj.inputs", inputs.map((i) => i.format("minimal")).join(", ")); + } else { + inputs = [ParamType.from("bytes")]; + } + const mutability = consumeMutability(obj); + assertArgument(mutability === "nonpayable" || mutability === "payable", "fallback cannot be constants", "obj.stateMutability", mutability); + if (consumeKeywords(obj, setify(["returns"])).has("returns")) { + const outputs = consumeParams(obj); + assertArgument(outputs.length === 1 && outputs[0].type === "bytes", "invalid fallback outputs", "obj.outputs", outputs.map((i) => i.format("minimal")).join(", ")); + } + consumeEoi(obj); + return new FallbackFragment(_guard$2, inputs, mutability === "payable"); + } + if (obj.type === "receive") { + return new FallbackFragment(_guard$2, [], true); + } + if (obj.type === "fallback") { + const inputs = [ParamType.from("bytes")]; + const payable = obj.stateMutability === "payable"; + return new FallbackFragment(_guard$2, inputs, payable); + } + assertArgument(false, "invalid fallback description", "obj", obj); } - suffix() { - return new Uint8Array([2]); + /** + * Returns ``true`` and provides a type guard if %%value%% is a + * **FallbackFragment**. + */ + static isFragment(value) { + return value && value[internal$1] === FallbackFragmentInternal; } } -var index$4 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - isSapientSigner, - SignerWrapper -}); -let SignerState = /* @__PURE__ */ function(SignerState2) { - SignerState2[SignerState2["INITIAL"] = 0] = "INITIAL"; - SignerState2[SignerState2["SIGNING"] = 1] = "SIGNING"; - SignerState2[SignerState2["SIGNED"] = 2] = "SIGNED"; - SignerState2[SignerState2["ERROR"] = 3] = "ERROR"; - return SignerState2; -}({}); -function isSignerStatusPending(status) { - return status === void 0 || status.state === SignerState.INITIAL || status.state === SignerState.SIGNING; -} -class Orchestrator { - constructor(signers, tag = Orchestrator.randomTag()) { - this.tag = tag; - this.observers = []; - this.signers = []; - this.count = 0; - this.setSigners(signers); - } - static randomTag() { - return `default-${hexlify(randomBytes$1(8)).slice(2)}`; - } - pullId() { - return `${this.tag}-${this.count++}`; - } - setSigners(signers) { - this.signers = signers.map((s2) => isSapientSigner(s2) ? s2 : new SignerWrapper(s2)); +class FunctionFragment extends NamedFragment { + /** + * @private + */ + constructor(guard2, name2, stateMutability, inputs, outputs, gas) { + super(guard2, "function", name2, inputs); + /** + * If the function is constant (e.g. ``pure`` or ``view`` functions). + */ + __publicField(this, "constant"); + /** + * The returned types for the result of calling this function. + */ + __publicField(this, "outputs"); + /** + * The state mutability (e.g. ``payable``, ``nonpayable``, ``view`` + * or ``pure``) + */ + __publicField(this, "stateMutability"); + /** + * If the function can be sent value during invocation. + */ + __publicField(this, "payable"); + /** + * The recommended gas limit to send when calling this function. + */ + __publicField(this, "gas"); + Object.defineProperty(this, internal$1, { value: FunctionFragmentInternal }); + outputs = Object.freeze(outputs.slice()); + const constant = stateMutability === "view" || stateMutability === "pure"; + const payable = stateMutability === "payable"; + defineProperties$1(this, { constant, gas, outputs, payable, stateMutability }); } - async getSigners() { - return Promise.all(this.signers.map(async function(s2) { - return s2.getAddress(); - })); + /** + * The Function selector. + */ + get selector() { + return id$1(this.format("sighash")).substring(0, 10); } - subscribe(observer) { - this.observers.push(observer); - return () => { - this.observers = this.observers.filter((o2) => o2 !== observer); - }; + /** + * Returns a string representation of this function as %%format%%. + */ + format(format2) { + if (format2 == null) { + format2 = "sighash"; + } + if (format2 === "json") { + return JSON.stringify({ + type: "function", + name: this.name, + constant: this.constant, + stateMutability: this.stateMutability !== "nonpayable" ? this.stateMutability : void 0, + payable: this.payable, + gas: this.gas != null ? this.gas : void 0, + inputs: this.inputs.map((i) => JSON.parse(i.format(format2))), + outputs: this.outputs.map((o2) => JSON.parse(o2.format(format2))) + }); + } + const result = []; + if (format2 !== "sighash") { + result.push("function"); + } + result.push(this.name + joinParams(format2, this.inputs)); + if (format2 !== "sighash") { + if (this.stateMutability !== "nonpayable") { + result.push(this.stateMutability); + } + if (this.outputs && this.outputs.length) { + result.push("returns"); + result.push(joinParams(format2, this.outputs)); + } + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + } + return result.join(" "); } - async notifyObservers(id2, status, metadata2) { - await Promise.all([...this.signers.map(async function(signer2) { - return signer2.notifyStatusChange(id2, status, metadata2); - }), ...this.observers.map(async function(observer) { - return observer(status, metadata2); - })]); + /** + * Return the selector for a function with %%name%% and %%params%%. + */ + static getSelector(name2, params) { + params = (params || []).map((p2) => ParamType.from(p2)); + const fragment = new FunctionFragment(_guard$2, name2, "view", params, [], null); + return fragment.selector; } - async buildDeployTransaction(metadata2) { - let bundle; - for (const signer2 of this.signers) { - const newBundle = await signer2.buildDeployTransaction(metadata2); - if (bundle === void 0) { - bundle = newBundle; - } else if (newBundle != null && newBundle.transactions) { - bundle.transactions = newBundle.transactions.concat(bundle.transactions); + /** + * Returns a new **FunctionFragment** for %%obj%%. + */ + static from(obj) { + if (FunctionFragment.isFragment(obj)) { + return obj; + } + if (typeof obj === "string") { + try { + return FunctionFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid function fragment", "obj", obj); + } + } else if (obj instanceof TokenString) { + const name2 = consumeName("function", obj); + const inputs = consumeParams(obj); + const mutability = consumeMutability(obj); + let outputs = []; + if (consumeKeywords(obj, setify(["returns"])).has("returns")) { + outputs = consumeParams(obj); + } + const gas = consumeGas(obj); + consumeEoi(obj); + return new FunctionFragment(_guard$2, name2, mutability, inputs, outputs, gas); + } + let stateMutability = obj.stateMutability; + if (stateMutability == null) { + stateMutability = "payable"; + if (typeof obj.constant === "boolean") { + stateMutability = "view"; + if (!obj.constant) { + stateMutability = "payable"; + if (typeof obj.payable === "boolean" && !obj.payable) { + stateMutability = "nonpayable"; + } + } + } else if (typeof obj.payable === "boolean" && !obj.payable) { + stateMutability = "nonpayable"; } } - return bundle; + return new FunctionFragment(_guard$2, obj.name, stateMutability, obj.inputs ? obj.inputs.map(ParamType.from) : [], obj.outputs ? obj.outputs.map(ParamType.from) : [], obj.gas != null ? obj.gas : null); } - async predecorateSignedTransactions(metadata2) { - const output2 = []; - for (const signer2 of this.signers) { - output2.push(...await signer2.predecorateSignedTransactions(metadata2 != null ? metadata2 : {})); - } - return output2; + /** + * Returns ``true`` and provides a type guard if %%value%% is a + * **FunctionFragment**. + */ + static isFragment(value) { + return value && value[internal$1] === FunctionFragmentInternal; } - async decorateTransactions(bundle, metadata2) { - for (const signer2 of this.signers) { - bundle = await signer2.decorateTransactions(bundle, metadata2 != null ? metadata2 : {}); - } - return bundle; +} +class StructFragment extends NamedFragment { + /** + * @private + */ + constructor(guard2, name2, inputs) { + super(guard2, "struct", name2, inputs); + Object.defineProperty(this, internal$1, { value: StructFragmentInternal }); } - signMessage(args) { - var _this = this; - const id2 = this.pullId(); - return new Promise(async function(resolve) { - const { - message, - metadata: metadata2, - callback, - candidates - } = args; - const status = { - ended: false, - message, - signers: {} - }; - let lastMetadata = metadata2 != null ? metadata2 : {}; - const onNewMetadata = (newMetadata) => { - lastMetadata = newMetadata; - _this.notifyObservers(id2, status, lastMetadata); - }; - const onStatusUpdate = () => { - try { - _this.notifyObservers(id2, status, lastMetadata); - const pending = Object.entries(status.signers).filter(([_, s2]) => isSignerStatusPending(s2)); - if (callback && callback(status, onNewMetadata) || pending.length === 0) { - status.ended = true; - resolve(status); - _this.notifyObservers(id2, status, lastMetadata); - return; - } - } catch (e2) { - console.error("Error while notifying observers", e2); - } - }; - let signers = _this.signers; - if (candidates) { - const addresses = await Promise.all(_this.signers.map(async function(s2) { - return s2.getAddress(); - })); - signers = _this.signers.filter((_, i) => candidates.includes(addresses[i])); - } - const accepted = await Promise.allSettled(signers.map(async function(s2) { - const saddr = await s2.getAddress(); - status.signers[saddr] = { - state: SignerState.SIGNING, - request: s2.sign(message, metadata2 != null ? metadata2 : {}).then((signature2) => { - const suffix = s2.suffix(); - status.signers[saddr] = { - state: SignerState.SIGNED, - signature: signature2, - suffix - }; - onStatusUpdate(); - return signature2; - }).catch((error) => { - status.signers[saddr] = { - state: SignerState.ERROR, - error - }; - onStatusUpdate(); - throw error; - }) - }; - })); - for (let i = 0; i < accepted.length; i++) { - const signer2 = _this.signers[i]; - const promise = accepted[i]; - if (promise.status === "rejected") { - const address = await signer2.getAddress(); - console.warn(`signer ${address} rejected the request: ${promise.reason}`); - status.signers[address] = { - state: SignerState.ERROR, - error: new Error(`signer ${address} rejected the request: ${promise.reason}`) - }; - } + /** + * Returns a string representation of this struct as %%format%%. + */ + format() { + throw new Error("@TODO"); + } + /** + * Returns a new **StructFragment** for %%obj%%. + */ + static from(obj) { + if (typeof obj === "string") { + try { + return StructFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid struct fragment", "obj", obj); } - onStatusUpdate(); - }); + } else if (obj instanceof TokenString) { + const name2 = consumeName("struct", obj); + const inputs = consumeParams(obj); + consumeEoi(obj); + return new StructFragment(_guard$2, name2, inputs); + } + return new StructFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); + } + // @TODO: fix this return type + /** + * Returns ``true`` and provides a type guard if %%value%% is a + * **StructFragment**. + */ + static isFragment(value) { + return value && value[internal$1] === StructFragmentInternal; } } -const signhub$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - Orchestrator, - SignerState, - isSignerStatusPending, - signers: index$4 -}, Symbol.toStringTag, { value: "Module" })); -function _extends$9() { - _extends$9 = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } +const PanicReasons$1 = /* @__PURE__ */ new Map(); +PanicReasons$1.set(0, "GENERIC_PANIC"); +PanicReasons$1.set(1, "ASSERT_FALSE"); +PanicReasons$1.set(17, "OVERFLOW"); +PanicReasons$1.set(18, "DIVIDE_BY_ZERO"); +PanicReasons$1.set(33, "ENUM_RANGE_ERROR"); +PanicReasons$1.set(34, "BAD_STORAGE_DATA"); +PanicReasons$1.set(49, "STACK_UNDERFLOW"); +PanicReasons$1.set(50, "ARRAY_RANGE_ERROR"); +PanicReasons$1.set(65, "OUT_OF_MEMORY"); +PanicReasons$1.set(81, "UNINITIALIZED_FUNCTION_CALL"); +const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); +const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); +let defaultCoder = null; +let defaultMaxInflation = 1024; +function getBuiltinCallException(action, tx, data, abiCoder) { + let message = "missing revert data"; + let reason = null; + const invocation = null; + let revert = null; + if (data) { + message = "execution reverted"; + const bytes2 = getBytes(data); + data = hexlify(data); + if (bytes2.length === 0) { + message += " (no data present; likely require(false) occurred"; + reason = "require(false)"; + } else if (bytes2.length % 32 !== 4) { + message += " (could not decode reason; invalid data length)"; + } else if (hexlify(bytes2.slice(0, 4)) === "0x08c379a0") { + try { + reason = abiCoder.decode(["string"], bytes2.slice(4))[0]; + revert = { + signature: "Error(string)", + name: "Error", + args: [reason] + }; + message += `: ${JSON.stringify(reason)}`; + } catch (error) { + message += " (could not decode reason; invalid string data)"; + } + } else if (hexlify(bytes2.slice(0, 4)) === "0x4e487b71") { + try { + const code2 = Number(abiCoder.decode(["uint256"], bytes2.slice(4))[0]); + revert = { + signature: "Panic(uint256)", + name: "Panic", + args: [code2] + }; + reason = `Panic due to ${PanicReasons$1.get(code2) || "UNKNOWN"}(${code2})`; + message += `: ${reason}`; + } catch (error) { + message += " (could not decode panic code)"; } + } else { + message += " (unknown custom error)"; } - return target; + } + const transaction2 = { + to: tx.to ? getAddress(tx.to) : null, + data: tx.data || "0x" }; - return _extends$9.apply(this, arguments); -} -async function resolveArrayProperties$1(object2) { - if (Array.isArray(object2)) { - return Promise.all(object2.map((o2) => resolveProperties$1(o2))); + if (tx.from) { + transaction2.from = getAddress(tx.from); } - return resolveProperties$1(object2); + return makeError(message, "CALL_EXCEPTION", { + action, + data, + reason, + transaction: transaction2, + invocation, + revert + }); } -const statusToSignatureParts = (status) => { - const parts = /* @__PURE__ */ new Map(); - for (const signer2 of Object.keys(status.signers)) { - const value = status.signers[signer2]; - if (value.state === SignerState.SIGNED) { - const suffix = getBytes(value.suffix); - const suffixed = solidityPacked(["bytes", "bytes"], [value.signature, suffix]); - parts.set(signer2, { - signature: suffixed, - isDynamic: suffix.length !== 1 || suffix[0] !== 2 - }); - } +const _AbiCoder = class _AbiCoder { + constructor() { + __privateAdd(this, _AbiCoder_instances); } - return parts; -}; -class Wallet extends AbstractSigner { - constructor(options) { - var _options$provider; - if (BigInt(options.chainId) === 0n && !options.coders.signature.supportsNoChainId) { - throw new Error(`Sequence version ${options.config.version} doesn't support chainId 0`); - } - super((_options$provider = options.provider) != null ? _options$provider : null); - this.context = void 0; - this.config = void 0; - this.address = void 0; - this.chainId = void 0; - this.relayer = void 0; - this.coders = void 0; - this.orchestrator = void 0; - this._reader = void 0; - this.context = options.context; - this.config = options.config; - this.orchestrator = options.orchestrator; - this.coders = options.coders; - this.address = options.address; - this.chainId = options.chainId; - this.relayer = options.relayer; - this._reader = options.reader; + /** + * Get the default values for the given %%types%%. + * + * For example, a ``uint`` is by default ``0`` and ``bool`` + * is by default ``false``. + */ + getDefaultValue(types2) { + const coders2 = types2.map((type) => __privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, ParamType.from(type))); + const coder = new TupleCoder(coders2, "_"); + return coder.defaultValue(); } - static newWallet(options) { - const address = index$1$2.context.addressOf(options.context, options.coders.config.imageHashOf(options.config)); - return new Wallet(_extends$9({}, options, { - address - })); + /** + * Encode the %%values%% as the %%types%% into ABI data. + * + * @returns DataHexstring + */ + encode(types2, values) { + assertArgumentCount(values.length, types2.length, "types/values length mismatch"); + const coders2 = types2.map((type) => __privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, ParamType.from(type))); + const coder = new TupleCoder(coders2, "_"); + const writer = new Writer(); + coder.encode(writer, values); + return writer.data; } - reader() { - if (this._reader) return this._reader; - if (!this.provider) throw new Error("Wallet status provider requires a provider"); - return new index$1$2.reader.OnChainReader(this.provider); + /** + * Decode the ABI %%data%% as the %%types%% into values. + * + * If %%loose%% decoding is enabled, then strict padding is + * not enforced. Some older versions of Solidity incorrectly + * padded event data emitted from ``external`` functions. + */ + decode(types2, data, loose) { + const coders2 = types2.map((type) => __privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, ParamType.from(type))); + const coder = new TupleCoder(coders2, "_"); + return coder.decode(new Reader(data, loose, defaultMaxInflation)); } - setConfig(config2) { - this.config = config2; + static _setDefaultMaxInflation(value) { + assertArgument(typeof value === "number" && Number.isInteger(value), "invalid defaultMaxInflation factor", "value", value); + defaultMaxInflation = value; } - setOrchestrator(orchestrator) { - this.orchestrator = orchestrator; + /** + * Returns the shared singleton instance of a default [[AbiCoder]]. + * + * On the first call, the instance is created internally. + */ + static defaultAbiCoder() { + if (defaultCoder == null) { + defaultCoder = new _AbiCoder(); + } + return defaultCoder; } - setAddress(address) { - this.address = address; + /** + * Returns an ethers-compatible [[CallExceptionError]] Error for the given + * result %%data%% for the [[CallExceptionAction]] %%action%% against + * the Transaction %%tx%%. + */ + static getBuiltinCallException(action, tx, data) { + return getBuiltinCallException(action, tx, data, _AbiCoder.defaultAbiCoder()); } - getSigners() { - return this.orchestrator.getSigners(); +}; +_AbiCoder_instances = new WeakSet(); +getCoder_fn = function(param) { + if (param.isArray()) { + return new ArrayCoder(__privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, param.arrayChildren), param.arrayLength, param.name); } - async getAddress() { - return this.address; + if (param.isTuple()) { + return new TupleCoder(param.components.map((c2) => __privateMethod(this, _AbiCoder_instances, getCoder_fn).call(this, c2)), param.name); } - async decorateTransactions(bundle) { - const decorated = await this.orchestrator.decorateTransactions(bundle); - if (await this.reader().isDeployed(this.address)) { - return decorated; - } - const transactions2 = [{ - to: decorated.entrypoint, - data: index$1$2.transaction.encodeBundleExecData(decorated), - revertOnError: true - }]; - const deployTx = await this.buildDeployTransaction(); - if (deployTx) { - transactions2.unshift(...deployTx.transactions); - } - return { - entrypoint: this.context.guestModule, - chainId: this.chainId, - intent: decorated.intent, - transactions: transactions2 - }; + switch (param.baseType) { + case "address": + return new AddressCoder(param.name); + case "bool": + return new BooleanCoder(param.name); + case "string": + return new StringCoder(param.name); + case "bytes": + return new BytesCoder(param.name); + case "": + return new NullCoder(param.name); } - async buildDeployTransaction(metadata2) { - if (metadata2 != null && metadata2.ignoreDeployed && await this.reader().isDeployed(this.address)) { - return; - } - const imageHash2 = this.coders.config.imageHashOf(this.config); - if (index$1$2.context.addressOf(this.context, imageHash2) !== this.address) { - throw new Error(`First address of config ${imageHash2} doesn't match wallet address ${this.address}`); - } - const bundle = Wallet.buildDeployTransaction(this.context, imageHash2); - if (metadata2 != null && metadata2.includeChildren) { - const childBundle = await this.orchestrator.buildDeployTransaction(metadata2); - if (childBundle) { - bundle.transactions = childBundle.transactions.concat(bundle.transactions); - } - } - return bundle; + let match = param.type.match(paramTypeNumber); + if (match) { + let size2 = parseInt(match[2] || "256"); + assertArgument(size2 !== 0 && size2 <= 256 && size2 % 8 === 0, "invalid " + match[1] + " bit length", "param", param); + return new NumberCoder(size2 / 8, match[1] === "int", param.name); } - async deploy(metadata2) { - const deployTx = await this.buildDeployTransaction(metadata2); - if (deployTx === void 0) { - return; - } - if (!this.relayer) throw new Error("Wallet deploy requires a relayer"); - return this.relayer.relay(_extends$9({}, deployTx, { - chainId: this.chainId, - intent: { - id: hexlify(randomBytes$1(32)), - wallet: this.address - } - })); + match = param.type.match(paramTypeBytes); + if (match) { + let size2 = parseInt(match[1]); + assertArgument(size2 !== 0 && size2 <= 32, "invalid bytes length", "param", param); + return new FixedBytesCoder(size2, param.name); } - static buildDeployTransaction(context2, imageHash2) { - const factoryInterface = new Interface(walletContracts.factory.abi); - return { - entrypoint: context2.guestModule, - transactions: [{ - to: context2.factory, - data: factoryInterface.encodeFunctionData(factoryInterface.getFunction("deploy"), [context2.mainModule, imageHash2]), - gasLimit: 1e5, - delegateCall: false, - revertOnError: true, - value: 0 - }] - }; + assertArgument(false, "invalid type", "type", param.type); +}; +let AbiCoder = _AbiCoder; +function encodeBytes32String(text2) { + const bytes2 = toUtf8Bytes(text2); + if (bytes2.length > 31) { + throw new Error("bytes32 string must be less than 32 bytes"); } - async buildUpdateConfigurationTransaction(config2) { - if (this.coders.config.update.isKindUsed) { - const implementation = await this.reader().implementation(this.address); - const isLaterUpdate = implementation && implementation === this.context.mainModuleUpgradable; - return this.coders.config.update.buildTransaction(this.address, config2, this.context, isLaterUpdate ? "later" : "first"); - } - return this.coders.config.update.buildTransaction(this.address, config2, this.context); + return zeroPadBytes(bytes2, 32); +} +function decodeBytes32String(_bytes) { + const data = getBytes(_bytes, "bytes"); + if (data.length !== 32) { + throw new Error("invalid bytes32 - not 32 bytes long"); } - async getNonce(space = 0) { - const nonce = await this.reader().nonce(this.address, space); - if (nonce === void 0) throw new Error("Unable to determine nonce"); - return Number(nonce); + if (data[31] !== 0) { + throw new Error("invalid bytes32 string - no null terminator"); } - async signDigest(digest, metadata2) { - const subdigest = subDigestOf(this.address, this.chainId, digest); - if (this.coders.config.hasSubdigest(this.config, subdigest)) { - return this.coders.signature.encodeSigners(this.config, /* @__PURE__ */ new Map(), [subdigest], this.chainId).encoded; - } - const childMetadata = _extends$9({}, metadata2, { - // Keep other metadata fields - digest, - chainId: this.chainId, - address: this.address, - config: this.config - }); - const subdigestBytes = getBytes(subdigest); - const signature2 = await this.orchestrator.signMessage({ - candidates: this.coders.config.signersOf(this.config).map((s2) => s2.address), - message: subdigestBytes, - metadata: childMetadata, - callback: (status, onNewMetadata) => { - const parts2 = statusToSignatureParts(status); - const newMetadata = _extends$9({}, childMetadata, { - parts: parts2 - }); - onNewMetadata(newMetadata); - return this.coders.signature.hasEnoughSigningPower(this.config, parts2); - } + let length = 31; + while (data[length - 1] === 0) { + length--; + } + return toUtf8String(data.slice(0, length)); +} +class LogDescription { + /** + * @_ignore: + */ + constructor(fragment, topic, args) { + /** + * The matching fragment for the ``topic0``. + */ + __publicField(this, "fragment"); + /** + * The name of the Event. + */ + __publicField(this, "name"); + /** + * The full Event signature. + */ + __publicField(this, "signature"); + /** + * The topic hash for the Event. + */ + __publicField(this, "topic"); + /** + * The arguments passed into the Event with ``emit``. + */ + __publicField(this, "args"); + const name2 = fragment.name, signature2 = fragment.format(); + defineProperties$1(this, { + fragment, + name: name2, + signature: signature2, + topic, + args }); - const parts = statusToSignatureParts(signature2); - return this.coders.signature.encodeSigners(this.config, parts, [], this.chainId).encoded; } - signMessage(message) { - return this.signDigest(keccak256$1(message), { - message +} +class TransactionDescription { + /** + * @_ignore: + */ + constructor(fragment, selector2, args, value) { + /** + * The matching fragment from the transaction ``data``. + */ + __publicField(this, "fragment"); + /** + * The name of the Function from the transaction ``data``. + */ + __publicField(this, "name"); + /** + * The arguments passed to the Function from the transaction ``data``. + */ + __publicField(this, "args"); + /** + * The full Function signature from the transaction ``data``. + */ + __publicField(this, "signature"); + /** + * The selector for the Function from the transaction ``data``. + */ + __publicField(this, "selector"); + /** + * The ``value`` (in wei) from the transaction. + */ + __publicField(this, "value"); + const name2 = fragment.name, signature2 = fragment.format(); + defineProperties$1(this, { + fragment, + name: name2, + args, + signature: signature2, + selector: selector2, + value }); } - // XXX This method is not implemented in the original code but required by the AbstractSigner interface - signTypedData(domain2, types2, value) { - const digest = encodeTypedDataDigest({ - domain: domain2, - types: types2, - message: value +} +class ErrorDescription { + /** + * @_ignore: + */ + constructor(fragment, selector2, args) { + /** + * The matching fragment. + */ + __publicField(this, "fragment"); + /** + * The name of the Error. + */ + __publicField(this, "name"); + /** + * The arguments passed to the Error with ``revert``. + */ + __publicField(this, "args"); + /** + * The full Error signature. + */ + __publicField(this, "signature"); + /** + * The selector for the Error. + */ + __publicField(this, "selector"); + const name2 = fragment.name, signature2 = fragment.format(); + defineProperties$1(this, { + fragment, + name: name2, + args, + signature: signature2, + selector: selector2 }); - return this.signDigest(digest); - } - signTransactionBundle(bundle) { - if (bundle.entrypoint !== this.address) { - throw new Error(`Invalid entrypoint: ${bundle.entrypoint} !== ${this.address}`); - } - return this.signTransactions(bundle.transactions, bundle.nonce); } - async fetchNonceOrSpace(nonce) { - let spaceValue; - if (nonce && nonce.space !== void 0) { - spaceValue = BigInt(nonce.space); - } else if (nonce === void 0) { - return this.randomNonce(); - } else if (nonce && nonce.serial === true) { - spaceValue = 0; - } else { - return nonce; - } - const resultNonce = await this.reader().nonce(this.address, spaceValue); - if (resultNonce === void 0) throw new Error("Unable to determine nonce"); - return index$1$2.transaction.encodeNonce(spaceValue, resultNonce); +} +class Indexed { + /** + * @_ignore: + */ + constructor(hash2) { + /** + * The ``keccak256`` of the value logged. + */ + __publicField(this, "hash"); + /** + * @_ignore: + */ + __publicField(this, "_isIndexed"); + defineProperties$1(this, { hash: hash2, _isIndexed: true }); } - // Generate nonce with random space - randomNonce() { - const randomNonceSpace = BigInt(hexlify(randomBytes$1(12))); - const randomNonce = index$1$2.transaction.encodeNonce(randomNonceSpace, 0); - return randomNonce; + /** + * Returns ``true`` if %%value%% is an **Indexed**. + * + * This provides a Type Guard for property access. + */ + static isIndexed(value) { + return !!(value && value._isIndexed); } - async signTransactions(txs, nonce, metadata2) { - const transaction2 = await resolveArrayProperties$1(txs); - const transactions2 = index$1$2.transaction.fromTransactionish(this.address, transaction2); - if (transactions2.length === 0) { - transactions2.push({ - to: this.address, - data: "0x", - value: 0, - gasLimit: 0, - delegateCall: false, - revertOnError: true - }); +} +const PanicReasons = { + "0": "generic panic", + "1": "assert(false)", + "17": "arithmetic overflow", + "18": "division or modulo by zero", + "33": "enum overflow", + "34": "invalid encoded storage byte array accessed", + "49": "out-of-bounds array access; popping on an empty array", + "50": "out-of-bounds access of an array or bytesN", + "65": "out of memory", + "81": "uninitialized function" +}; +const BuiltinErrors = { + "0x08c379a0": { + signature: "Error(string)", + name: "Error", + inputs: ["string"], + reason: (message) => { + return `reverted with reason string ${JSON.stringify(message)}`; + } + }, + "0x4e487b71": { + signature: "Panic(uint256)", + name: "Panic", + inputs: ["uint256"], + reason: (code2) => { + let reason = "unknown panic code"; + if (code2 >= 0 && code2 <= 255 && PanicReasons[code2.toString()]) { + reason = PanicReasons[code2.toString()]; + } + return `reverted with panic code 0x${code2.toString(16)} (${reason})`; } - const defaultedNonce = await this.fetchNonceOrSpace(nonce); - const digest = index$1$2.transaction.digestOfTransactions(defaultedNonce, transactions2); - const meta = _extends$9({ - digest, - transactions: transactions2 - }, metadata2); - const signature2 = await this.signDigest(digest, meta); - return { - intent: { - // Maybe is better if signDigest returns the subdigest directly - id: subDigestOf(this.address, this.chainId, digest), - wallet: this.address - }, - chainId: this.chainId, - transactions: transactions2, - entrypoint: this.address, - nonce: defaultedNonce, - signature: signature2 - }; - } - async sendSignedTransaction(signedBundle, quote) { - if (!this.relayer) throw new Error("Wallet sendTransaction requires a relayer"); - return this.relayer.relay(signedBundle, quote); } - // sendTransaction will dispatch the transaction to the relayer for submission to the network. - // This method is able to send transactions in serial or parallel (default). You can specify - // a specific nonce, or let the wallet determine the next nonce on-chain (serial:true). - // - // By default, nonces are generated randomly and assigned so transactioned can be executed - // in parallel. However, if you'd like to execute serially, pass { serial: true } as an option. - async sendTransaction(txs, options) { - let nonce; - if ((options == null ? void 0 : options.nonce) !== void 0) { - nonce = options.nonce; - } else if (options != null && options.serial) { - nonce = { - serial: true - }; +}; +const _Interface = class _Interface { + /** + * Create a new Interface for the %%fragments%%. + */ + constructor(fragments) { + __privateAdd(this, _Interface_instances); + /** + * All the Contract ABI members (i.e. methods, events, errors, etc). + */ + __publicField(this, "fragments"); + /** + * The Contract constructor. + */ + __publicField(this, "deploy"); + /** + * The Fallback method, if any. + */ + __publicField(this, "fallback"); + /** + * If receiving ether is supported. + */ + __publicField(this, "receive"); + __privateAdd(this, _errors); + __privateAdd(this, _events); + __privateAdd(this, _functions); + // #structs: Map; + __privateAdd(this, _abiCoder); + let abi2 = []; + if (typeof fragments === "string") { + abi2 = JSON.parse(fragments); } else { - nonce = this.randomNonce(); + abi2 = fragments; } - const signed2 = await this.signTransactions(txs, nonce); - const decorated = await this.decorateTransactions(signed2); - return this.sendSignedTransaction(decorated, options == null ? void 0 : options.quote); - } - async fillGasLimits(txs) { - const transaction2 = await resolveArrayProperties$1(txs); - const transactions2 = index$1$2.transaction.fromTransactionish(this.address, transaction2); - const relayer2 = this.relayer; - if (!relayer2) throw new Error("Wallet fillGasLimits requires a relayer"); - const simulations = await relayer2.simulate(this.address, ...transactions2); - return transactions2.map((tx, i) => { - const gasLimit = tx.gasLimit ? Number(tx.gasLimit) : simulations[i].gasLimit; - return _extends$9({}, tx, simulations[i], { - gasLimit - }); - }); - } - connect(provider2, relayer2) { - return new Wallet({ - // Sequence version configurator - coders: this.coders, - context: this.context, - config: this.config, - chainId: this.chainId, - address: this.address, - orchestrator: this.orchestrator, - reader: this._reader, - provider: provider2, - relayer: relayer2 != null ? relayer2 : this.relayer - }); - } - signTransaction(transaction2) { - throw new Error("Method not implemented."); - } -} -function _extends$8() { - _extends$8 = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } + __privateSet(this, _functions, /* @__PURE__ */ new Map()); + __privateSet(this, _errors, /* @__PURE__ */ new Map()); + __privateSet(this, _events, /* @__PURE__ */ new Map()); + const frags = []; + for (const a2 of abi2) { + try { + frags.push(Fragment.from(a2)); + } catch (error) { + console.log(`[Warning] Invalid Fragment ${JSON.stringify(a2)}:`, error.message); } } - return target; - }; - return _extends$8.apply(this, arguments); -} -function encodeGasRefundTransaction(option) { - if (!option) return []; - const value = BigInt(option.value); - switch (option.token.type) { - case relayer_gen.FeeTokenType.UNKNOWN: - return [{ - delegateCall: false, - revertOnError: true, - gasLimit: option.gasLimit, - to: option.to, - value: toHexString(value), - data: "0x" - }]; - case relayer_gen.FeeTokenType.ERC20_TOKEN: - if (!option.token.contractAddress) { - throw new Error(`No contract address for ERC-20 fee option`); + defineProperties$1(this, { + fragments: Object.freeze(frags) + }); + let fallback2 = null; + let receive = false; + __privateSet(this, _abiCoder, this.getAbiCoder()); + this.fragments.forEach((fragment, index2) => { + let bucket; + switch (fragment.type) { + case "constructor": + if (this.deploy) { + console.log("duplicate definition - constructor"); + return; + } + defineProperties$1(this, { deploy: fragment }); + return; + case "fallback": + if (fragment.inputs.length === 0) { + receive = true; + } else { + assertArgument(!fallback2 || fragment.payable !== fallback2.payable, "conflicting fallback fragments", `fragments[${index2}]`, fragment); + fallback2 = fragment; + receive = fallback2.payable; + } + return; + case "function": + bucket = __privateGet(this, _functions); + break; + case "event": + bucket = __privateGet(this, _events); + break; + case "error": + bucket = __privateGet(this, _errors); + break; + default: + return; } - return [{ - delegateCall: false, - revertOnError: true, - gasLimit: option.gasLimit, - to: option.token.contractAddress, - value: 0, - data: new Interface([{ - constant: false, - inputs: [{ - type: "address" - }, { - type: "uint256" - }], - name: "transfer", - outputs: [], - type: "function" - }]).encodeFunctionData("transfer", [option.to, toHexString(value)]) - }]; - default: - throw new Error(`Unhandled fee token type ${option.token.type}`); - } -} -class AccountSigner { - constructor(account2, chainId, options) { - this.account = account2; - this.chainId = chainId; - this.options = options; - } - get provider() { - return this.account.providerFor(this.chainId); - } - async getAddress() { - return this.account.address; + const signature2 = fragment.format(); + if (bucket.has(signature2)) { + return; + } + bucket.set(signature2, fragment); + }); + if (!this.deploy) { + defineProperties$1(this, { + deploy: ConstructorFragment.from("constructor()") + }); + } + defineProperties$1(this, { fallback: fallback2, receive }); } - signMessage(message) { - var _this$options$cantVal, _this$options; - return this.account.signMessage(message, this.chainId, (_this$options$cantVal = (_this$options = this.options) == null ? void 0 : _this$options.cantValidateBehavior) != null ? _this$options$cantVal : "throw"); + /** + * Returns the entire Human-Readable ABI, as an array of + * signatures, optionally as %%minimal%% strings, which + * removes parameter names and unneceesary spaces. + */ + format(minimal) { + const format2 = minimal ? "minimal" : "full"; + const abi2 = this.fragments.map((f2) => f2.format(format2)); + return abi2; } - signTypedData(domain2, types2, value) { - var _this$options$cantVal2, _this$options2; - return this.account.signTypedData(domain2, types2, value, this.chainId, (_this$options$cantVal2 = (_this$options2 = this.options) == null ? void 0 : _this$options2.cantValidateBehavior) != null ? _this$options$cantVal2 : "throw"); + /** + * Return the JSON-encoded ABI. This is the format Solidiy + * returns. + */ + formatJson() { + const abi2 = this.fragments.map((f2) => f2.format("json")); + return JSON.stringify(abi2.map((j2) => JSON.parse(j2))); } - async defaultSelectFee(_txs, options) { - if (options.length === 0) return void 0; - const balanceOfAbi = [{ - constant: true, - inputs: [{ - type: "address" - }], - name: "balanceOf", - outputs: [{ - type: "uint256" - }], - type: "function" - }]; - for (const option of options) { - if (option.token.type === relayer_gen.FeeTokenType.UNKNOWN) { - const balance = await this.getBalance(); - if (balance >= BigInt(option.value)) { - return option; - } - } else if (option.token.contractAddress && option.token.type === relayer_gen.FeeTokenType.ERC20_TOKEN) { - const token = new Contract(option.token.contractAddress, balanceOfAbi, this.provider); - const balance = await token.balanceOf(this.account.address); - if (balance >= BigInt(option.value)) { - return option; - } - } else ; - } - throw new Error("No fee option available - not enough balance"); + /** + * The ABI coder that will be used to encode and decode binary + * data. + */ + getAbiCoder() { + return AbiCoder.defaultAbiCoder(); } - async sendTransaction(txs, options) { - var _this$options$stubSig, _this$options3, _this$options$selectF, _this$options4, _this$options5; - const prepare = await this.account.prepareTransactions({ - txs, - chainId: this.chainId, - stubSignatureOverrides: (_this$options$stubSig = (_this$options3 = this.options) == null ? void 0 : _this$options3.stubSignatureOverrides) != null ? _this$options$stubSig : /* @__PURE__ */ new Map(), - simulateForFeeOptions: options == null ? void 0 : options.simulateForFeeOptions - }); - const selectMethod = (_this$options$selectF = (_this$options4 = this.options) == null ? void 0 : _this$options4.selectFee) != null ? _this$options$selectF : this.defaultSelectFee.bind(this); - const feeOption = await selectMethod(txs, prepare.feeOptions); - const finalTransactions = [...prepare.transactions, ...encodeGasRefundTransaction(feeOption)]; - return this.account.sendTransaction(finalTransactions, this.chainId, prepare.feeQuote, void 0, void 0, ((_this$options5 = this.options) == null ? void 0 : _this$options5.nonceSpace) !== void 0 ? { - nonceSpace: this.options.nonceSpace - } : void 0); + /** + * Get the function name for %%key%%, which may be a function selector, + * function name or function signature that belongs to the ABI. + */ + getFunctionName(key) { + const fragment = __privateMethod(this, _Interface_instances, getFunction_fn).call(this, key, null, false); + assertArgument(fragment, "no matching function", "key", key); + return fragment.name; } - getBalance(blockTag) { - return this.provider.getBalance(this.account.address, blockTag); + /** + * Returns true if %%key%% (a function selector, function name or + * function signature) is present in the ABI. + * + * In the case of a function name, the name may be ambiguous, so + * accessing the [[FunctionFragment]] may require refinement. + */ + hasFunction(key) { + return !!__privateMethod(this, _Interface_instances, getFunction_fn).call(this, key, null, false); } - call(transaction2, blockTag) { - return this.provider.call(_extends$8({}, transaction2, { - blockTag - })); + /** + * Get the [[FunctionFragment]] for %%key%%, which may be a function + * selector, function name or function signature that belongs to the ABI. + * + * If %%values%% is provided, it will use the Typed API to handle + * ambiguous cases where multiple functions match by name. + * + * If the %%key%% and %%values%% do not refine to a single function in + * the ABI, this will throw. + */ + getFunction(key, values) { + return __privateMethod(this, _Interface_instances, getFunction_fn).call(this, key, values || null, true); } - async resolveName(name2) { - const res = await this.provider.resolveName(name2); - if (!res) throw new Error(`Could not resolve name ${name2}`); - return res; + /** + * Iterate over all functions, calling %%callback%%, sorted by their name. + */ + forEachFunction(callback) { + const names2 = Array.from(__privateGet(this, _functions).keys()); + names2.sort((a2, b2) => a2.localeCompare(b2)); + for (let i = 0; i < names2.length; i++) { + const name2 = names2[i]; + callback(__privateGet(this, _functions).get(name2), i); + } } - connect(_provider6) { - throw new Error("Method not implemented."); + /** + * Get the event name for %%key%%, which may be a topic hash, + * event name or event signature that belongs to the ABI. + */ + getEventName(key) { + const fragment = __privateMethod(this, _Interface_instances, getEvent_fn).call(this, key, null, false); + assertArgument(fragment, "no matching event", "key", key); + return fragment.name; } - signTransaction(transaction2) { - throw new Error("Method not implemented."); + /** + * Returns true if %%key%% (an event topic hash, event name or + * event signature) is present in the ABI. + * + * In the case of an event name, the name may be ambiguous, so + * accessing the [[EventFragment]] may require refinement. + */ + hasEvent(key) { + return !!__privateMethod(this, _Interface_instances, getEvent_fn).call(this, key, null, false); } - getTransactionCount(blockTag) { - throw new Error("Method not implemented."); + /** + * Get the [[EventFragment]] for %%key%%, which may be a topic hash, + * event name or event signature that belongs to the ABI. + * + * If %%values%% is provided, it will use the Typed API to handle + * ambiguous cases where multiple events match by name. + * + * If the %%key%% and %%values%% do not refine to a single event in + * the ABI, this will throw. + */ + getEvent(key, values) { + return __privateMethod(this, _Interface_instances, getEvent_fn).call(this, key, values || null, true); } - estimateGas(transaction2) { - throw new Error("Method not implemented."); + /** + * Iterate over all events, calling %%callback%%, sorted by their name. + */ + forEachEvent(callback) { + const names2 = Array.from(__privateGet(this, _events).keys()); + names2.sort((a2, b2) => a2.localeCompare(b2)); + for (let i = 0; i < names2.length; i++) { + const name2 = names2[i]; + callback(__privateGet(this, _events).get(name2), i); + } } - getChainId() { - return Promise.resolve(Number(this.chainId)); + /** + * Get the [[ErrorFragment]] for %%key%%, which may be an error + * selector, error name or error signature that belongs to the ABI. + * + * If %%values%% is provided, it will use the Typed API to handle + * ambiguous cases where multiple errors match by name. + * + * If the %%key%% and %%values%% do not refine to a single error in + * the ABI, this will throw. + */ + getError(key, values) { + if (isHexString(key)) { + const selector2 = key.toLowerCase(); + if (BuiltinErrors[selector2]) { + return ErrorFragment.from(BuiltinErrors[selector2].signature); + } + for (const fragment of __privateGet(this, _errors).values()) { + if (selector2 === fragment.selector) { + return fragment; + } + } + return null; + } + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name2, fragment] of __privateGet(this, _errors)) { + if (name2.split( + "(" + /* fix:) */ + )[0] === key) { + matching.push(fragment); + } + } + if (matching.length === 0) { + if (key === "Error") { + return ErrorFragment.from("error Error(string)"); + } + if (key === "Panic") { + return ErrorFragment.from("error Panic(uint256)"); + } + return null; + } else if (matching.length > 1) { + const matchStr = matching.map((m2) => JSON.stringify(m2.format())).join(", "); + assertArgument(false, `ambiguous error description (i.e. ${matchStr})`, "name", key); + } + return matching[0]; + } + key = ErrorFragment.from(key).format(); + if (key === "Error(string)") { + return ErrorFragment.from("error Error(string)"); + } + if (key === "Panic(uint256)") { + return ErrorFragment.from("error Panic(uint256)"); + } + const result = __privateGet(this, _errors).get(key); + if (result) { + return result; + } + return null; } - getGasPrice() { - throw new Error("Method not implemented."); + /** + * Iterate over all errors, calling %%callback%%, sorted by their name. + */ + forEachError(callback) { + const names2 = Array.from(__privateGet(this, _errors).keys()); + names2.sort((a2, b2) => a2.localeCompare(b2)); + for (let i = 0; i < names2.length; i++) { + const name2 = names2[i]; + callback(__privateGet(this, _errors).get(name2), i); + } } - getFeeData() { - throw new Error("Method not implemented."); + // Get the 4-byte selector used by Solidity to identify a function + /* + getSelector(fragment: ErrorFragment | FunctionFragment): string { + if (typeof(fragment) === "string") { + const matches: Array = [ ]; + + try { matches.push(this.getFunction(fragment)); } catch (error) { } + try { matches.push(this.getError(fragment)); } catch (_) { } + + if (matches.length === 0) { + logger.throwArgumentError("unknown fragment", "key", fragment); + } else if (matches.length > 1) { + logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment); + } + + fragment = matches[0]; + } + + return dataSlice(id(fragment.format()), 0, 4); } - getNonce(blockTag) { - throw new Error("Method not implemented."); + */ + // Get the 32-byte topic hash used by Solidity to identify an event + /* + getEventTopic(fragment: EventFragment): string { + //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); } + return id(fragment.format()); } - populateCall(tx) { - throw new Error("Method not implemented."); + */ + _decodeParams(params, data) { + return __privateGet(this, _abiCoder).decode(params, data); } - checkTransaction(transaction2) { - throw new Error("Method not implemented."); + _encodeParams(params, values) { + return __privateGet(this, _abiCoder).encode(params, values); } - async populateTransaction(tx) { - throw new Error("Method not implemented."); + /** + * Encodes a ``tx.data`` object for deploying the Contract with + * the %%values%% as the constructor arguments. + */ + encodeDeploy(values) { + return this._encodeParams(this.deploy.inputs, values || []); } - _checkProvider(operation) { - throw new Error("Method not implemented."); + /** + * Decodes the result %%data%% (e.g. from an ``eth_call``) for the + * specified error (see [[getError]] for valid values for + * %%key%%). + * + * Most developers should prefer the [[parseCallResult]] method instead, + * which will automatically detect a ``CALL_EXCEPTION`` and throw the + * corresponding error. + */ + decodeErrorResult(fragment, data) { + if (typeof fragment === "string") { + const f2 = this.getError(fragment); + assertArgument(f2, "unknown error", "fragment", fragment); + fragment = f2; + } + assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match error ${fragment.name}.`, "data", data); + return this._decodeParams(fragment.inputs, dataSlice(data, 4)); } -} -class Chain0Reader { - async isDeployed(_wallet) { - return false; + /** + * Encodes the transaction revert data for a call result that + * reverted from the the Contract with the sepcified %%error%% + * (see [[getError]] for valid values for %%fragment%%) with the %%values%%. + * + * This is generally not used by most developers, unless trying to mock + * a result from a Contract. + */ + encodeErrorResult(fragment, values) { + if (typeof fragment === "string") { + const f2 = this.getError(fragment); + assertArgument(f2, "unknown error", "fragment", fragment); + fragment = f2; + } + return concat([ + fragment.selector, + this._encodeParams(fragment.inputs, values || []) + ]); } - async implementation(_wallet) { - return void 0; + /** + * Decodes the %%data%% from a transaction ``tx.data`` for + * the function specified (see [[getFunction]] for valid values + * for %%fragment%%). + * + * Most developers should prefer the [[parseTransaction]] method + * instead, which will automatically detect the fragment. + */ + decodeFunctionData(fragment, data) { + if (typeof fragment === "string") { + const f2 = this.getFunction(fragment); + assertArgument(f2, "unknown function", "fragment", fragment); + fragment = f2; + } + assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match function ${fragment.name}.`, "data", data); + return this._decodeParams(fragment.inputs, dataSlice(data, 4)); } - async imageHash(_wallet) { - return void 0; + /** + * Encodes the ``tx.data`` for a transaction that calls the function + * specified (see [[getFunction]] for valid values for %%fragment%%) with + * the %%values%%. + */ + encodeFunctionData(fragment, values) { + if (typeof fragment === "string") { + const f2 = this.getFunction(fragment); + assertArgument(f2, "unknown function", "fragment", fragment); + fragment = f2; + } + return concat([ + fragment.selector, + this._encodeParams(fragment.inputs, values || []) + ]); } - async nonce(_wallet, _space) { - return 0n; + /** + * Decodes the result %%data%% (e.g. from an ``eth_call``) for the + * specified function (see [[getFunction]] for valid values for + * %%key%%). + * + * Most developers should prefer the [[parseCallResult]] method instead, + * which will automatically detect a ``CALL_EXCEPTION`` and throw the + * corresponding error. + */ + decodeFunctionResult(fragment, data) { + if (typeof fragment === "string") { + const f2 = this.getFunction(fragment); + assertArgument(f2, "unknown function", "fragment", fragment); + fragment = f2; + } + let message = "invalid length for result data"; + const bytes2 = getBytesCopy(data); + if (bytes2.length % 32 === 0) { + try { + return __privateGet(this, _abiCoder).decode(fragment.outputs, bytes2); + } catch (error) { + message = "could not decode result data"; + } + } + assert(false, message, "BAD_DATA", { + value: hexlify(bytes2), + info: { method: fragment.name, signature: fragment.format() } + }); } - async isValidSignature(_wallet, _digest, _signature) { - throw new Error("Method not supported."); + makeError(_data6, tx) { + const data = getBytes(_data6, "data"); + const error = AbiCoder.getBuiltinCallException("call", tx, data); + const customPrefix = "execution reverted (unknown custom error)"; + if (error.message.startsWith(customPrefix)) { + const selector2 = hexlify(data.slice(0, 4)); + const ef2 = this.getError(selector2); + if (ef2) { + try { + const args = __privateGet(this, _abiCoder).decode(ef2.inputs, data.slice(4)); + error.revert = { + name: ef2.name, + signature: ef2.format(), + args + }; + error.reason = error.revert.signature; + error.message = `execution reverted: ${error.reason}`; + } catch (e2) { + error.message = `execution reverted (coult not decode custom error)`; + } + } + } + const parsed = this.parseTransaction(tx); + if (parsed) { + error.invocation = { + method: parsed.name, + signature: parsed.signature, + args: parsed.args + }; + } + return error; } -} -class Account { - constructor(options) { - this.address = void 0; - this.networks = void 0; - this.tracker = void 0; - this.contexts = void 0; - this.migrator = void 0; - this.migrations = void 0; - this.orchestrator = void 0; - this.jwt = void 0; - this.projectAccessKey = void 0; - this.address = getAddress$1(options.address); - this.contexts = options.contexts; - this.tracker = options.tracker; - this.networks = options.networks; - this.orchestrator = options.orchestrator; - this.jwt = options.jwt; - this.projectAccessKey = options.projectAccessKey; - this.migrations = options.migrations || defaults.DefaultMigrations; - this.migrator = new migrator.Migrator(options.tracker, this.migrations, this.contexts); + /** + * Encodes the result data (e.g. from an ``eth_call``) for the + * specified function (see [[getFunction]] for valid values + * for %%fragment%%) with %%values%%. + * + * This is generally not used by most developers, unless trying to mock + * a result from a Contract. + */ + encodeFunctionResult(fragment, values) { + if (typeof fragment === "string") { + const f2 = this.getFunction(fragment); + assertArgument(f2, "unknown function", "fragment", fragment); + fragment = f2; + } + return hexlify(__privateGet(this, _abiCoder).encode(fragment.outputs, values || [])); } - getSigner(chainId, options) { - return new AccountSigner(this, chainId, options); + /* + spelunk(inputs: Array, values: ReadonlyArray, processfunc: (type: string, value: any) => Promise): Promise> { + const promises: Array> = [ ]; + const process = function(type: ParamType, value: any): any { + if (type.baseType === "array") { + return descend(type.child + } + if (type. === "address") { + } + }; + + const descend = function (inputs: Array, values: ReadonlyArray) { + if (inputs.length !== values.length) { throw new Error("length mismatch"); } + + }; + + const result: Array = [ ]; + values.forEach((value, index) => { + if (value == null) { + topics.push(null); + } else if (param.baseType === "array" || param.baseType === "tuple") { + logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); + } else if (Array.isArray(value)) { + topics.push(value.map((value) => encodeTopic(param, value))); + } else { + topics.push(encodeTopic(param, value)); + } + }); + } + */ + // Create the filter for the event with search criteria (e.g. for eth_filterLog) + encodeFilterTopics(fragment, values) { + if (typeof fragment === "string") { + const f2 = this.getEvent(fragment); + assertArgument(f2, "unknown event", "eventFragment", fragment); + fragment = f2; + } + assert(values.length <= fragment.inputs.length, `too many arguments for ${fragment.format()}`, "UNEXPECTED_ARGUMENT", { count: values.length, expectedCount: fragment.inputs.length }); + const topics = []; + if (!fragment.anonymous) { + topics.push(fragment.topicHash); + } + const encodeTopic = (param, value) => { + if (param.type === "string") { + return id$1(value); + } else if (param.type === "bytes") { + return keccak256(hexlify(value)); + } + if (param.type === "bool" && typeof value === "boolean") { + value = value ? "0x01" : "0x00"; + } else if (param.type.match(/^u?int/)) { + value = toBeHex(value); + } else if (param.type.match(/^bytes/)) { + value = zeroPadBytes(value, 32); + } else if (param.type === "address") { + __privateGet(this, _abiCoder).encode(["address"], [value]); + } + return zeroPadValue(hexlify(value), 32); + }; + values.forEach((value, index2) => { + const param = fragment.inputs[index2]; + if (!param.indexed) { + assertArgument(value == null, "cannot filter non-indexed parameters; must be null", "contract." + param.name, value); + return; + } + if (value == null) { + topics.push(null); + } else if (param.baseType === "array" || param.baseType === "tuple") { + assertArgument(false, "filtering with tuples or arrays not supported", "contract." + param.name, value); + } else if (Array.isArray(value)) { + topics.push(value.map((value2) => encodeTopic(param, value2))); + } else { + topics.push(encodeTopic(param, value)); + } + }); + while (topics.length && topics[topics.length - 1] === null) { + topics.pop(); + } + return topics; } - static async new(options) { - var _options$migrations; - const mig = new migrator.Migrator(options.tracker, (_options$migrations = options.migrations) != null ? _options$migrations : defaults.DefaultMigrations, options.contexts); - const lastMigration = mig.lastMigration(); - const lastCoder = lastMigration.configCoder; - const config2 = lastCoder.fromSimple(options.config); - const imageHash2 = lastCoder.imageHashOf(config2); - const context2 = options.contexts[lastMigration.version]; - const address = index$1$2.context.addressOf(context2, imageHash2); - await options.tracker.saveCounterfactualWallet({ - config: config2, - context: Object.values(options.contexts) + encodeEventLog(fragment, values) { + if (typeof fragment === "string") { + const f2 = this.getEvent(fragment); + assertArgument(f2, "unknown event", "eventFragment", fragment); + fragment = f2; + } + const topics = []; + const dataTypes = []; + const dataValues = []; + if (!fragment.anonymous) { + topics.push(fragment.topicHash); + } + assertArgument(values.length === fragment.inputs.length, "event arguments/values mismatch", "values", values); + fragment.inputs.forEach((param, index2) => { + const value = values[index2]; + if (param.indexed) { + if (param.type === "string") { + topics.push(id$1(value)); + } else if (param.type === "bytes") { + topics.push(keccak256(value)); + } else if (param.baseType === "tuple" || param.baseType === "array") { + throw new Error("not implemented"); + } else { + topics.push(__privateGet(this, _abiCoder).encode([param.type], [value])); + } + } else { + dataTypes.push(param); + dataValues.push(value); + } }); - return new Account({ - address, - tracker: options.tracker, - contexts: options.contexts, - networks: options.networks, - orchestrator: options.orchestrator, - migrations: options.migrations, - projectAccessKey: options.projectAccessKey + return { + data: __privateGet(this, _abiCoder).encode(dataTypes, dataValues), + topics + }; + } + // Decode a filter for the event and the search criteria + decodeEventLog(fragment, data, topics) { + if (typeof fragment === "string") { + const f2 = this.getEvent(fragment); + assertArgument(f2, "unknown event", "eventFragment", fragment); + fragment = f2; + } + if (topics != null && !fragment.anonymous) { + const eventTopic = fragment.topicHash; + assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic, "fragment/topic mismatch", "topics[0]", topics[0]); + topics = topics.slice(1); + } + const indexed = []; + const nonIndexed = []; + const dynamic = []; + fragment.inputs.forEach((param, index2) => { + if (param.indexed) { + if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") { + indexed.push(ParamType.from({ type: "bytes32", name: param.name })); + dynamic.push(true); + } else { + indexed.push(param); + dynamic.push(false); + } + } else { + nonIndexed.push(param); + dynamic.push(false); + } + }); + const resultIndexed = topics != null ? __privateGet(this, _abiCoder).decode(indexed, concat(topics)) : null; + const resultNonIndexed = __privateGet(this, _abiCoder).decode(nonIndexed, data, true); + const values = []; + const keys = []; + let nonIndexedIndex = 0, indexedIndex = 0; + fragment.inputs.forEach((param, index2) => { + let value = null; + if (param.indexed) { + if (resultIndexed == null) { + value = new Indexed(null); + } else if (dynamic[index2]) { + value = new Indexed(resultIndexed[indexedIndex++]); + } else { + try { + value = resultIndexed[indexedIndex++]; + } catch (error) { + value = error; + } + } + } else { + try { + value = resultNonIndexed[nonIndexedIndex++]; + } catch (error) { + value = error; + } + } + values.push(value); + keys.push(param.name || null); }); + return Result.fromItems(values, keys); } - getAddress() { - return Promise.resolve(this.address); - } - get version() { - return this.migrator.lastMigration().version; - } - get coders() { - const lastMigration = this.migrator.lastMigration(); - return { - signature: lastMigration.signatureCoder, - config: lastMigration.configCoder - }; + /** + * Parses a transaction, finding the matching function and extracts + * the parameter values along with other useful function details. + * + * If the matching function cannot be found, return null. + */ + parseTransaction(tx) { + const data = getBytes(tx.data, "tx.data"); + const value = getBigInt(tx.value != null ? tx.value : 0, "tx.value"); + const fragment = this.getFunction(hexlify(data.slice(0, 4))); + if (!fragment) { + return null; + } + const args = __privateGet(this, _abiCoder).decode(fragment.inputs, data.slice(4)); + return new TransactionDescription(fragment, fragment.selector, args, value); } - network(chainId) { - const tcid = BigInt(chainId); - const found = this.networks.find((n2) => tcid === BigInt(n2.chainId)); - if (!found) throw new Error(`Network not found for chainId ${chainId}`); - return found; + parseCallResult(data) { + throw new Error("@TODO"); } - providerFor(chainId) { - const found = this.network(chainId); - if (!found.provider && !found.rpcUrl) { - throw new Error(`Provider not found for chainId ${chainId}`); + /** + * Parses a receipt log, finding the matching event and extracts + * the parameter values along with other useful event details. + * + * If the matching event cannot be found, returns null. + */ + parseLog(log) { + const fragment = this.getEvent(log.topics[0]); + if (!fragment || fragment.anonymous) { + return null; } - const network2 = new Network(found.name, found.chainId); - return found.provider || new JsonRpcProvider$1(getFetchRequest(found.rpcUrl, this.projectAccessKey, this.jwt), network2, { - staticNetwork: network2 - }); + return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics)); } - reader(chainId) { - if (BigInt(chainId) === 0n) { - return new Chain0Reader(); + /** + * Parses a revert data, finding the matching error and extracts + * the parameter values along with other useful error details. + * + * If the matching error cannot be found, returns null. + */ + parseError(data) { + const hexData = hexlify(data); + const fragment = this.getError(dataSlice(hexData, 0, 4)); + if (!fragment) { + return null; } - return new index$1$2.reader.OnChainReader(this.providerFor(chainId)); - } - relayer(chainId) { - const found = this.network(chainId); - if (!found.relayer) throw new Error(`Relayer not found for chainId ${chainId}`); - if (isRelayer(found.relayer)) return found.relayer; - return new RpcRelayer(_extends$8({}, found.relayer, this.projectAccessKey ? { - projectAccessKey: this.projectAccessKey - } : { - jwtAuth: this.jwt - })); - } - setOrchestrator(orchestrator) { - this.orchestrator = orchestrator; - } - setJwt(jwt) { - this.jwt = jwt; - } - contextFor(version2) { - const ctx = this.contexts[version2]; - if (!ctx) throw new Error(`Context not found for version ${version2}`); - return ctx; - } - walletForStatus(chainId, status) { - const coder = index$6.coderFor(status.version); - return this.walletFor(chainId, this.contextFor(status.version), status.config, coder); - } - walletFor(chainId, context2, config2, coders2) { - const isNetworkZero = BigInt(chainId) === 0n; - return new Wallet({ - config: config2, - context: context2, - chainId, - coders: coders2, - relayer: isNetworkZero ? void 0 : this.relayer(chainId), - address: this.address, - orchestrator: this.orchestrator, - reader: this.reader(chainId) - }); + const args = __privateGet(this, _abiCoder).decode(fragment.inputs, dataSlice(hexData, 4)); + return new ErrorDescription(fragment, fragment.selector, args); } - // Get the status of the account on a given network - // this does the following process: - // 1. Get the current on-chain status of the wallet (version + imageHash) - // 2. Get any pending migrations that have been signed by the wallet - // 3. Get any pending configuration updates that have been signed by the wallet - // 4. Fetch reverse lookups for both on-chain and pending configurations - async status(chainId, longestPath = false) { - var _this = this; - const isDeployedPromise = this.reader(chainId).isDeployed(this.address); - const counterfactualImageHashPromise = this.tracker.imageHashOfCounterfactualWallet({ - wallet: this.address - }).then((r2) => { - if (!r2) throw new Error(`Counterfactual imageHash not found for wallet ${this.address}`); - return r2; - }); - const counterFactualVersionPromise = counterfactualImageHashPromise.then((r2) => { - return version$6.counterfactualVersion(this.address, r2.imageHash, Object.values(this.contexts)); - }); - const onChainVersionPromise = async function() { - const isDeployed2 = await isDeployedPromise; - if (!isDeployed2) return counterFactualVersionPromise; - const implementation = await _this.reader(chainId).implementation(_this.address); - if (!implementation) throw new Error(`Implementation not found for wallet ${_this.address}`); - const versions = Object.values(_this.contexts); - for (let i = 0; i < versions.length; i++) { - if (versions[i].mainModule === implementation || versions[i].mainModuleUpgradable === implementation) { - return versions[i].version; - } - } - throw new Error(`Version not found for implementation ${implementation}`); - }(); - const onChainImageHashPromise = async function() { - const deployedImageHash = await _this.reader(chainId).imageHash(_this.address); - if (deployedImageHash) return deployedImageHash; - const counterfactualImageHash2 = await counterfactualImageHashPromise; - if (counterfactualImageHash2) return counterfactualImageHash2.imageHash; - throw new Error(`On-chain imageHash not found for wallet ${_this.address}`); - }(); - const onChainConfigPromise = async function() { - const onChainImageHash2 = await onChainImageHashPromise; - const onChainConfig = await _this.tracker.configOfImageHash({ - imageHash: onChainImageHash2 - }); - if (onChainConfig) return onChainConfig; - throw new Error(`On-chain config not found for imageHash ${onChainImageHash2}`); - }(); - const onChainVersion = await onChainVersionPromise; - const onChainImageHash = await onChainImageHashPromise; - let fromImageHash = onChainImageHash; - let lastVersion = onChainVersion; - let signedMigrations = []; - if (onChainVersion !== this.version) { - const presignedMigrate = await this.migrator.getAllMigratePresignedTransaction({ - address: this.address, - fromImageHash: onChainImageHash, - fromVersion: onChainVersion, - chainId - }); - fromImageHash = presignedMigrate.lastImageHash; - lastVersion = presignedMigrate.lastVersion; - signedMigrations = presignedMigrate.signedMigrations; + /** + * Creates a new [[Interface]] from the ABI %%value%%. + * + * The %%value%% may be provided as an existing [[Interface]] object, + * a JSON-encoded ABI or any Human-Readable ABI format. + */ + static from(value) { + if (value instanceof _Interface) { + return value; } - const presigned = await this.tracker.loadPresignedConfiguration({ - wallet: this.address, - fromImageHash, - longestPath - }); - const imageHash2 = presigned && presigned.length > 0 ? presigned[presigned.length - 1].nextImageHash : fromImageHash; - const config2 = await this.tracker.configOfImageHash({ - imageHash: imageHash2 - }); - if (!config2) { - throw new Error(`Config not found for imageHash ${imageHash2}`); + if (typeof value === "string") { + return new _Interface(JSON.parse(value)); } - const isDeployed = await isDeployedPromise; - const counterfactualImageHash = await counterfactualImageHashPromise; - const checkpoint = index$6.coderFor(lastVersion).config.checkpointOf(config2); - return { - original: _extends$8({}, counterfactualImageHash, { - version: await counterFactualVersionPromise - }), - onChain: { - imageHash: onChainImageHash, - config: await onChainConfigPromise, - version: onChainVersion, - deployed: isDeployed - }, - fullyMigrated: lastVersion === this.version, - signedMigrations, - version: lastVersion, - presignedConfigurations: presigned, - imageHash: imageHash2, - config: config2, - checkpoint, - canOnchainValidate: onChainVersion === this.version && isDeployed - }; - } - mustBeFullyMigrated(status) { - if (!status.fullyMigrated) { - throw new Error(`Wallet ${this.address} is not fully migrated`); + if (typeof value.formatJson === "function") { + return new _Interface(value.formatJson()); } - } - async predecorateSignedTransactions(status, chainId) { - const bundles = await this.orchestrator.predecorateSignedTransactions({ - chainId - }); - const predecorated = await this.predecorateTransactions([], status, chainId); - if (index$1$2.transaction.fromTransactionish(this.address, predecorated).length > 0) { - bundles.push(await this.signTransactions(predecorated, chainId)); + if (typeof value.format === "function") { + return new _Interface(value.format("json")); } - return bundles; + return new _Interface(value); } - async predecorateTransactions(txs, status, chainId) { - if (status.onChain.imageHash !== status.imageHash) { - const wallet = this.walletForStatus(chainId, status); - const updateConfig = await wallet.buildUpdateConfigurationTransaction(status.config); - return [Array.isArray(txs) ? txs : [txs], updateConfig.transactions].flat(); +}; +_errors = new WeakMap(); +_events = new WeakMap(); +_functions = new WeakMap(); +_abiCoder = new WeakMap(); +_Interface_instances = new WeakSet(); +// Find a function definition by any means necessary (unless it is ambiguous) +getFunction_fn = function(key, values, forceUnique) { + if (isHexString(key)) { + const selector2 = key.toLowerCase(); + for (const fragment of __privateGet(this, _functions).values()) { + if (selector2 === fragment.selector) { + return fragment; + } } - return txs; + return null; } - async decorateTransactions(bundles, status, chainId) { - var _chainId4, _bundles$; - if (!Array.isArray(bundles)) { - return this.decorateTransactions([bundles], status, chainId); + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name2, fragment] of __privateGet(this, _functions)) { + if (name2.split( + "(" + /* fix:) */ + )[0] === key) { + matching.push(fragment); + } } - chainId = (_chainId4 = chainId) != null ? _chainId4 : bundles[0].chainId; - const bootstrapBundle = await this.buildBootstrapTransactions(status, chainId); - const hasBootstrapTxs = bootstrapBundle.transactions.length > 0; - if (!hasBootstrapTxs && bundles.length === 1) { - return bundles[0]; + if (values) { + const lastValue = values.length > 0 ? values[values.length - 1] : null; + let valueLength = values.length; + let allowOptions = true; + if (Typed.isTyped(lastValue) && lastValue.type === "overrides") { + allowOptions = false; + valueLength--; + } + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs.length; + if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) { + matching.splice(i, 1); + } + } + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j2 = 0; j2 < values.length; j2++) { + if (!Typed.isTyped(values[j2])) { + continue; + } + if (j2 >= inputs.length) { + if (values[j2].type === "overrides") { + continue; + } + matching.splice(i, 1); + break; + } + if (values[j2].type !== inputs[j2].baseType) { + matching.splice(i, 1); + break; + } + } + } } - const { - entrypoint - } = hasBootstrapTxs ? bootstrapBundle : bundles[0]; - const decoratedBundle = { - entrypoint, - chainId, - // Intent of the first bundle is used - intent: (_bundles$ = bundles[0]) == null ? void 0 : _bundles$.intent, - transactions: [...bootstrapBundle.transactions, ...bundles.map((bundle) => ({ - to: bundle.entrypoint, - data: index$1$2.transaction.encodeBundleExecData(bundle), - gasLimit: 0, - delegateCall: false, - revertOnError: true, - value: 0 - }))] - }; - if (!status.onChain.deployed) { - const id2 = index$1$2.transaction.subdigestOfGuestModuleTransactions(this.contexts[this.version].guestModule, chainId, decoratedBundle.transactions); - if (decoratedBundle.intent === void 0) { - decoratedBundle.intent = { - id: id2, - wallet: this.address - }; - } else { - decoratedBundle.intent.id = id2; + if (matching.length === 1 && values && values.length !== matching[0].inputs.length) { + const lastArg = values[values.length - 1]; + if (lastArg == null || Array.isArray(lastArg) || typeof lastArg !== "object") { + matching.splice(0, 1); } } - return decoratedBundle; - } - async decorateSignature(signature2, status) { - if (!status.presignedConfigurations || status.presignedConfigurations.length === 0) { - return signature2; + if (matching.length === 0) { + return null; } - const coder = this.coders.signature; - const chain = status.presignedConfigurations.map((c2) => c2.signature); - const chainedSignature = coder.chainSignatures(signature2, chain); - return coder.trim(chainedSignature); + if (matching.length > 1 && forceUnique) { + const matchStr = matching.map((m2) => JSON.stringify(m2.format())).join(", "); + assertArgument(false, `ambiguous function description (i.e. matches ${matchStr})`, "key", key); + } + return matching[0]; } - async publishWitness() { - const digest = id$1(`This is a Sequence account woo! ${Date.now()}`); - const signature2 = await this.signDigest(digest, 0, false); - const decoded = this.coders.signature.decode(signature2); - const signatures = this.coders.signature.signaturesOfDecoded(decoded); - return this.tracker.saveWitnesses({ - wallet: this.address, - digest, - chainId: 0, - signatures - }); + const result = __privateGet(this, _functions).get(FunctionFragment.from(key).format()); + if (result) { + return result; } - async signDigest(digest, chainId, decorate = true, cantValidateBehavior = "ignore", metadata2) { - const chainRef = BigInt(chainId) === 0n ? this.networks[0].chainId : chainId; - const status = await this.status(chainRef); - this.mustBeFullyMigrated(status); - if (!status.canOnchainValidate && cantValidateBehavior === "throw") { - throw new Error("Wallet cannot validate onchain"); + return null; +}; +// Find an event definition by any means necessary (unless it is ambiguous) +getEvent_fn = function(key, values, forceUnique) { + if (isHexString(key)) { + const eventTopic = key.toLowerCase(); + for (const fragment of __privateGet(this, _events).values()) { + if (eventTopic === fragment.topicHash) { + return fragment; + } } - const wallet = this.walletForStatus(chainId, status); - const signature2 = await wallet.signDigest(digest, metadata2); - const decorated = decorate ? this.decorateSignature(signature2, status) : signature2; - if (!status.canOnchainValidate) { - switch (cantValidateBehavior) { - case "ignore": - return decorated; - case "eip6492": - return this.buildEIP6492Signature(await decorated, status, chainId); + return null; + } + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name2, fragment] of __privateGet(this, _events)) { + if (name2.split( + "(" + /* fix:) */ + )[0] === key) { + matching.push(fragment); } } - return decorated; + if (values) { + for (let i = matching.length - 1; i >= 0; i--) { + if (matching[i].inputs.length < values.length) { + matching.splice(i, 1); + } + } + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j2 = 0; j2 < values.length; j2++) { + if (!Typed.isTyped(values[j2])) { + continue; + } + if (values[j2].type !== inputs[j2].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + if (matching.length === 0) { + return null; + } + if (matching.length > 1 && forceUnique) { + const matchStr = matching.map((m2) => JSON.stringify(m2.format())).join(", "); + assertArgument(false, `ambiguous event description (i.e. matches ${matchStr})`, "key", key); + } + return matching[0]; } - buildOnChainSignature(digest) { - const subdigest = index$1$2.signature.subdigestOf({ - digest: hexlify(digest), - chainId: 0, - address: this.address - }); - const hexSubdigest = hexlify(subdigest); - const config2 = this.coders.config.fromSimple({ - // Threshold *only* needs to be > 0, this is not a magic number - // we only use 2 ** 15 because it may lead to lower gas costs in some chains - threshold: 32768, - checkpoint: 0, - signers: [], - subdigests: [hexSubdigest] - }); - const walletInterface = new Interface(walletContracts.mainModule.abi); - const bundle = { - entrypoint: this.address, - transactions: [{ - to: this.address, - data: walletInterface.encodeFunctionData( - // *NEVER* use updateImageHash here, as it would effectively destroy the wallet - // setExtraImageHash sets an additional imageHash, without changing the current one - "setExtraImageHash", - [ - this.coders.config.imageHashOf(config2), - // 2 ** 255 instead of max uint256, to have more zeros in the calldata - "57896044618658097711785492504343953926634992332820282019728792003956564819968" - ] - ), - // Conservative gas limit, used because the current relayer - // has trouble estimating gas for this transaction - gasLimit: 25e4 - }] - }; - this.tracker.saveWalletConfig({ - config: config2 + const result = __privateGet(this, _events).get(EventFragment.from(key).format()); + if (result) { + return result; + } + return null; +}; +let Interface = _Interface; +const BN_0$2 = BigInt(0); +function getValue(value) { + if (value == null) { + return null; + } + return value; +} +function toJson(value) { + if (value == null) { + return null; + } + return value.toString(); +} +class FeeData { + /** + * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and + * %%maxPriorityFeePerGas%%. + */ + constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { + /** + * The gas price for legacy networks. + */ + __publicField(this, "gasPrice"); + /** + * The maximum fee to pay per gas. + * + * The base fee per gas is defined by the network and based on + * congestion, increasing the cost during times of heavy load + * and lowering when less busy. + * + * The actual fee per gas will be the base fee for the block + * and the priority fee, up to the max fee per gas. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + __publicField(this, "maxFeePerGas"); + /** + * The additional amout to pay per gas to encourage a validator + * to include the transaction. + * + * The purpose of this is to compensate the validator for the + * adjusted risk for including a given transaction. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + __publicField(this, "maxPriorityFeePerGas"); + defineProperties$1(this, { + gasPrice: getValue(gasPrice), + maxFeePerGas: getValue(maxFeePerGas), + maxPriorityFeePerGas: getValue(maxPriorityFeePerGas) }); - const signature2 = this.coders.signature.encodeSigners(config2, /* @__PURE__ */ new Map(), [hexSubdigest], 0).encoded; + } + /** + * Returns a JSON-friendly value. + */ + toJSON() { + const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; return { - bundle, - signature: signature2 + _type: "FeeData", + gasPrice: toJson(gasPrice), + maxFeePerGas: toJson(maxFeePerGas), + maxPriorityFeePerGas: toJson(maxPriorityFeePerGas) }; } - async buildEIP6492Signature(signature2, status, chainId) { - const bootstrapBundle = await this.buildBootstrapTransactions(status, chainId); - if (bootstrapBundle.transactions.length === 0) { - throw new Error("Cannot build EIP-6492 signature without bootstrap transactions"); - } - const encoded = AbiCoder.defaultAbiCoder().encode(["address", "bytes", "bytes"], [bootstrapBundle.entrypoint, index$1$2.transaction.encodeBundleExecData(bootstrapBundle), signature2]); - return solidityPacked(["bytes", "bytes32"], [encoded, index$1$2.EIP6492.EIP_6492_SUFFIX]); +} +function copyRequest(req) { + const result = {}; + if (req.to) { + result.to = req.to; } - async editConfig(changes) { - const currentConfig = await this.status(0).then((s2) => s2.config); - const newConfig = this.coders.config.editConfig(currentConfig, _extends$8({}, changes, { - checkpoint: this.coders.config.checkpointOf(currentConfig) + 1n - })); - return this.updateConfig(newConfig); + if (req.from) { + result.from = req.from; } - async updateConfig(config2) { - if (!this.coders.config.isWalletConfig(config2)) { - throw new Error(`Invalid config for wallet ${this.address}`); - } - const nextImageHash = this.coders.config.imageHashOf(config2); - const updateStruct = this.coders.signature.hashSetImageHash(nextImageHash); - const signature2 = await this.signDigest(updateStruct, 0, false); - await this.tracker.savePresignedConfiguration({ - wallet: this.address, - nextConfig: config2, - signature: signature2 - }); - const reverseConfig = await this.tracker.configOfImageHash({ - imageHash: nextImageHash, - noCache: true - }); - if (!reverseConfig || this.coders.config.imageHashOf(reverseConfig) !== nextImageHash) { - throw Error(`Reverse lookup failed for imageHash ${nextImageHash}`); + if (req.data) { + result.data = hexlify(req.data); + } + const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/); + for (const key of bigIntKeys) { + if (!(key in req) || req[key] == null) { + continue; } + result[key] = getBigInt(req[key], `request.${key}`); } - /** - * This method is used to bootstrap the wallet on a given chain. - * this deploys the wallets and executes all the necessary transactions - * for that wallet to start working with the given version. - * - * This usually involves: (a) deploying the wallet, (b) executing migrations - * - * Notice: It should NOT explicitly include chained signatures. Unless internally used - * by any of the migrations. - * - */ - async buildBootstrapTransactions(status, chainId) { - var _bundle$transactions; - const bundle = await this.orchestrator.buildDeployTransaction({ - chainId - }); - const transactions2 = (_bundle$transactions = bundle == null ? void 0 : bundle.transactions) != null ? _bundle$transactions : []; - if (!status.onChain.deployed) { - const deployTransaction = Wallet.buildDeployTransaction(status.original.context, status.original.imageHash); - transactions2.push(...deployTransaction.transactions); + const numberKeys = "type,nonce".split(/,/); + for (const key of numberKeys) { + if (!(key in req) || req[key] == null) { + continue; } - transactions2.push(...status.signedMigrations.map((m2) => ({ - to: m2.tx.entrypoint, - data: index$1$2.transaction.encodeBundleExecData(m2.tx), - value: 0, - gasLimit: 0, - revertOnError: true, - delegateCall: false - }))); - const id2 = status.signedMigrations.length > 0 ? status.signedMigrations[0].tx.intent.id : index$1$2.transaction.subdigestOfGuestModuleTransactions(this.contexts[this.version].guestModule, chainId, transactions2); - const { - guestModule - } = this.contextFor(status.version); - return { - entrypoint: guestModule, - transactions: transactions2, - chainId, - intent: { - id: id2, - wallet: this.address - } - }; + result[key] = getNumber(req[key], `request.${key}`); } - async bootstrapTransactions(chainId, prestatus) { - const status = prestatus || await this.status(chainId); - return this.buildBootstrapTransactions(status, chainId); + if (req.accessList) { + result.accessList = accessListify(req.accessList); } - async doBootstrap(chainId, feeQuote, prestatus) { - const bootstrapTxs = await this.bootstrapTransactions(chainId, prestatus); - return this.relayer(chainId).relay(_extends$8({}, bootstrapTxs, { - chainId - }), feeQuote); + if ("blockTag" in req) { + result.blockTag = req.blockTag; } - signMessage(message, chainId, cantValidateBehavior = "ignore") { - return this.signDigest(keccak256$1(message), chainId, true, cantValidateBehavior); + if ("enableCcipRead" in req) { + result.enableCcipRead = !!req.enableCcipRead; } - async signTransactions(txs, chainId, pstatus, options) { - const status = pstatus || await this.status(chainId); - this.mustBeFullyMigrated(status); - const wallet = this.walletForStatus(chainId, status); - const metadata2 = { - address: this.address, - digest: "", - // Set in wallet.signTransactions - chainId, - config: { - version: this.version - }, - decorate: true, - cantValidateBehavior: "ignore" - }; - const nonceOptions = options != null && options.serial ? { - serial: true - } : (options == null ? void 0 : options.nonceSpace) !== void 0 ? { - space: options.nonceSpace - } : void 0; - const signed2 = await wallet.signTransactions(txs, nonceOptions, metadata2); - return _extends$8({}, signed2, { - signature: await this.decorateSignature(signed2.signature, status) - }); + if ("customData" in req) { + result.customData = req.customData; } - async signMigrations(chainId, editConfig) { - const status = await this.status(chainId); - if (status.fullyMigrated) return false; - const wallet = this.walletForStatus(chainId, status); - const nextConfig = editConfig(wallet.config); - const signed2 = await this.migrator.signNextMigration(this.address, status.version, wallet, nextConfig); - if (!signed2) return false; - await this.tracker.saveWalletConfig({ - config: nextConfig - }); - const nextCoder = index$6.coderFor(nextConfig.version).config; - const nextImageHash = nextCoder.imageHashOf(nextConfig); - const reverseConfig = await this.tracker.configOfImageHash({ - imageHash: nextImageHash, - noCache: true + if ("blobVersionedHashes" in req && req.blobVersionedHashes) { + result.blobVersionedHashes = req.blobVersionedHashes.slice(); + } + if ("kzg" in req) { + result.kzg = req.kzg; + } + if ("blobs" in req && req.blobs) { + result.blobs = req.blobs.map((b2) => { + if (isBytesLike(b2)) { + return hexlify(b2); + } + return Object.assign({}, b2); }); - if (!reverseConfig || nextCoder.imageHashOf(reverseConfig) !== nextImageHash) { - throw Error(`Reverse lookup failed for imageHash ${nextImageHash}`); - } - await this.tracker.saveMigration(this.address, signed2, this.contexts); - return true; } - async signAllMigrations(editConfig) { - var _this2 = this; - const failedChains = []; - const signedMigrations = await Promise.all(this.networks.map(async function(n2) { - try { - return await _this2.signMigrations(n2.chainId, editConfig); - } catch (error) { - console.warn(`Failed to sign migrations for chain ${n2.chainId}`, error); - failedChains.push(n2.chainId); - return null; + return result; +} +class Block { + /** + * Create a new **Block** object. + * + * This should generally not be necessary as the unless implementing a + * low-level library. + */ + constructor(block, provider2) { + /** + * The provider connected to the block used to fetch additional details + * if necessary. + */ + __publicField(this, "provider"); + /** + * The block number, sometimes called the block height. This is a + * sequential number that is one higher than the parent block. + */ + __publicField(this, "number"); + /** + * The block hash. + * + * This hash includes all properties, so can be safely used to identify + * an exact set of block properties. + */ + __publicField(this, "hash"); + /** + * The timestamp for this block, which is the number of seconds since + * epoch that this block was included. + */ + __publicField(this, "timestamp"); + /** + * The block hash of the parent block. + */ + __publicField(this, "parentHash"); + /** + * The hash tree root of the parent beacon block for the given + * execution block. See [[link-eip-4788]]. + */ + __publicField(this, "parentBeaconBlockRoot"); + /** + * The nonce. + * + * On legacy networks, this is the random number inserted which + * permitted the difficulty target to be reached. + */ + __publicField(this, "nonce"); + /** + * The difficulty target. + * + * On legacy networks, this is the proof-of-work target required + * for a block to meet the protocol rules to be included. + * + * On modern networks, this is a random number arrived at using + * randao. @TODO: Find links? + */ + __publicField(this, "difficulty"); + /** + * The total gas limit for this block. + */ + __publicField(this, "gasLimit"); + /** + * The total gas used in this block. + */ + __publicField(this, "gasUsed"); + /** + * The root hash for the global state after applying changes + * in this block. + */ + __publicField(this, "stateRoot"); + /** + * The hash of the transaction receipts trie. + */ + __publicField(this, "receiptsRoot"); + /** + * The total amount of blob gas consumed by the transactions + * within the block. See [[link-eip-4844]]. + */ + __publicField(this, "blobGasUsed"); + /** + * The running total of blob gas consumed in excess of the + * target, prior to the block. See [[link-eip-4844]]. + */ + __publicField(this, "excessBlobGas"); + /** + * The miner coinbase address, wihch receives any subsidies for + * including this block. + */ + __publicField(this, "miner"); + /** + * The latest RANDAO mix of the post beacon state of + * the previous block. + */ + __publicField(this, "prevRandao"); + /** + * Any extra data the validator wished to include. + */ + __publicField(this, "extraData"); + /** + * The base fee per gas that all transactions in this block were + * charged. + * + * This adjusts after each block, depending on how congested the network + * is. + */ + __publicField(this, "baseFeePerGas"); + __privateAdd(this, _transactions); + __privateSet(this, _transactions, block.transactions.map((tx) => { + if (typeof tx !== "string") { + return new TransactionResponse(tx, provider2); } + return tx; })); - const successfulSignedMigrations = signedMigrations.filter((migration2) => migration2 !== null); - return { - signedMigrations: successfulSignedMigrations, - failedChains - }; + defineProperties$1(this, { + provider: provider2, + hash: getValue(block.hash), + number: block.number, + timestamp: block.timestamp, + parentHash: block.parentHash, + parentBeaconBlockRoot: block.parentBeaconBlockRoot, + nonce: block.nonce, + difficulty: block.difficulty, + gasLimit: block.gasLimit, + gasUsed: block.gasUsed, + blobGasUsed: block.blobGasUsed, + excessBlobGas: block.excessBlobGas, + miner: block.miner, + prevRandao: getValue(block.prevRandao), + extraData: block.extraData, + baseFeePerGas: getValue(block.baseFeePerGas), + stateRoot: block.stateRoot, + receiptsRoot: block.receiptsRoot + }); } - async isMigratedAllChains() { - var _this3 = this; - const failedChains = []; - const statuses = await Promise.all(this.networks.map(async function(n2) { - try { - return await _this3.status(n2.chainId); - } catch (error) { - failedChains.push(n2.chainId); - console.warn(`Failed to get status for chain ${n2.chainId}`, error); - return { - fullyMigrated: true - }; + /** + * Returns the list of transaction hashes, in the order + * they were executed within the block. + */ + get transactions() { + return __privateGet(this, _transactions).map((tx) => { + if (typeof tx === "string") { + return tx; } - })); - const migratedAllChains = statuses.every((s2) => s2.fullyMigrated); - return { - migratedAllChains, - failedChains - }; + return tx.hash; + }); } - async sendSignedTransactions(signedBundle, chainId, quote, pstatus, callback) { - if (!Array.isArray(signedBundle)) { - return this.sendSignedTransactions([signedBundle], chainId, quote, pstatus, callback); + /** + * Returns the complete transactions, in the order they + * were executed within the block. + * + * This is only available for blocks which prefetched + * transactions, by passing ``true`` to %%prefetchTxs%% + * into [[Provider-getBlock]]. + */ + get prefetchedTransactions() { + const txs = __privateGet(this, _transactions).slice(); + if (txs.length === 0) { + return []; } - const status = pstatus || await this.status(chainId); - this.mustBeFullyMigrated(status); - const decoratedBundle = await this.decorateTransactions(signedBundle, status, chainId); - callback == null || callback(decoratedBundle); - return this.relayer(chainId).relay(decoratedBundle, quote); - } - async fillGasLimits(txs, chainId, status) { - const wallet = this.walletForStatus(chainId, status || await this.status(chainId)); - return wallet.fillGasLimits(txs); - } - async gasRefundQuotes(txs, chainId, stubSignatureOverrides, status, options) { - const wstatus = status || await this.status(chainId); - const wallet = this.walletForStatus(chainId, wstatus); - const predecorated = await this.predecorateTransactions(txs, wstatus, chainId); - const transactions2 = index$1$2.transaction.fromTransactionish(this.address, predecorated); - const stubSignature = wallet.coders.config.buildStubSignature(wallet.config, stubSignatureOverrides); - const intentId = hexlify(randomBytes$1(32)); - const signedBundle = { - chainId, - intent: { - id: intentId, - wallet: this.address - }, - signature: stubSignature, - transactions: transactions2, - entrypoint: this.address, - nonce: 0 - // The relayer also ignored the nonce - }; - const decoratedBundle = await this.decorateTransactions(signedBundle, wstatus); - const data = index$1$2.transaction.encodeBundleExecData(decoratedBundle); - const res = await this.relayer(chainId).getFeeOptionsRaw(decoratedBundle.entrypoint, data, options); - return _extends$8({}, res, { - decorated: decoratedBundle + assert(typeof txs[0] === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", { + operation: "transactionResponses()" }); + return txs; } - async prepareTransactions(args) { - const status = await this.status(args.chainId); - const transactions2 = await this.fillGasLimits(args.txs, args.chainId, status); - const gasRefundQuote = await this.gasRefundQuotes(transactions2, args.chainId, args.stubSignatureOverrides, status, { - simulate: args.simulateForFeeOptions - }); - const flatDecorated = index$1$2.transaction.unwind(this.address, gasRefundQuote.decorated.transactions); + /** + * Returns a JSON-friendly value. + */ + toJSON() { + const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash: hash2, miner, prevRandao, nonce, number: number2, parentHash, parentBeaconBlockRoot, stateRoot, receiptsRoot, timestamp, transactions: transactions2 } = this; return { - transactions: transactions2, - flatDecorated, - feeOptions: gasRefundQuote.options, - feeQuote: gasRefundQuote.quote + _type: "Block", + baseFeePerGas: toJson(baseFeePerGas), + difficulty: toJson(difficulty), + extraData, + gasLimit: toJson(gasLimit), + gasUsed: toJson(gasUsed), + blobGasUsed: toJson(this.blobGasUsed), + excessBlobGas: toJson(this.excessBlobGas), + hash: hash2, + miner, + prevRandao, + nonce, + number: number2, + parentHash, + timestamp, + parentBeaconBlockRoot, + stateRoot, + receiptsRoot, + transactions: transactions2 }; } - async sendTransaction(txs, chainId, quote, skipPreDecorate = false, callback, options) { - const status = await this.status(chainId); - const predecorated = skipPreDecorate ? txs : await this.predecorateTransactions(txs, status, chainId); - const hasTxs = index$1$2.transaction.fromTransactionish(this.address, predecorated).length > 0; - const signed2 = hasTxs ? await this.signTransactions(predecorated, chainId, void 0, options) : void 0; - const childBundles = await this.orchestrator.predecorateSignedTransactions({ - chainId - }); - const bundles = []; - if (signed2 !== void 0 && signed2.transactions.length > 0) { - bundles.push(signed2); - } - bundles.push(...childBundles.filter((b2) => b2.transactions.length > 0)); - return this.sendSignedTransactions(bundles, chainId, quote, void 0, callback); - } - async signTypedData(domain2, types2, message, chainId, cantValidateBehavior = "ignore") { - const digest = encodeTypedDataDigest({ - domain: domain2, - types: types2, - message - }); - return this.signDigest(digest, chainId, true, cantValidateBehavior); - } - async getSigners() { - var _this4 = this; - const last = (ts) => ts.length ? ts[ts.length - 1] : void 0; - return (await Promise.all(this.networks.map(async function({ - chainId, - name: name2 - }) { - try { - var _last; - const status = await _this4.status(chainId); - let latestImageHash = (_last = last(status.presignedConfigurations)) == null ? void 0 : _last.nextImageHash; - if (!latestImageHash) { - if (status.onChain.version !== status.version) { - const migration2 = last(status.signedMigrations); - if (migration2) { - const { - toVersion, - toConfig - } = migration2; - const _coder = index$6.genericCoderFor(toVersion); - latestImageHash = _coder.config.imageHashOf(toConfig); - } - } - } - if (!latestImageHash) { - latestImageHash = status.onChain.imageHash; - } - const latestConfig = await _this4.tracker.configOfImageHash({ - imageHash: latestImageHash - }); - if (!latestConfig) { - throw new Error(`unable to find config for image hash ${latestImageHash}`); + [Symbol.iterator]() { + let index2 = 0; + const txs = this.transactions; + return { + next: () => { + if (index2 < this.length) { + return { + value: txs[index2++], + done: false + }; } - const coder = index$6.genericCoderFor(latestConfig.version); - const signers = coder.config.signersOf(latestConfig); - return signers.map((signer2) => _extends$8({}, signer2, { - network: chainId - })); - } catch (error) { - console.warn(`unable to get signers on network ${chainId} ${name2}`, error); - return []; + return { value: void 0, done: true }; } - }))).flat(); + }; } - async getAllSigners() { - var _this5 = this; - const allSigners = []; - await Promise.all(this.networks.map(async function(network2) { - const chainId = network2.chainId; - const status = await _this5.status(chainId, true); - const fullChain = [status.onChain.imageHash, ...status.onChain.version !== status.version ? status.signedMigrations.map((m2) => index$6.coderFor(m2.toVersion).config.imageHashOf(m2.toConfig)) : [], ...status.presignedConfigurations.map((update) => update.nextImageHash)]; - return Promise.all(fullChain.map(async function(nextImageHash, iconf) { - const isLast = iconf === fullChain.length - 1; - const config2 = await _this5.tracker.configOfImageHash({ - imageHash: nextImageHash - }); - if (!config2) { - console.warn(`AllSigners may be incomplete, config not found for imageHash ${nextImageHash}`); - return; - } - const coder = index$6.genericCoderFor(config2.version); - const signers = coder.config.signersOf(config2); - signers.forEach((signer2) => { - const exists2 = allSigners.find((s2) => s2.address === signer2.address && s2.network === chainId); - if (exists2 && isLast && exists2.flaggedForRemoval) { - exists2.flaggedForRemoval = false; - return; - } - if (exists2) return; - allSigners.push({ - address: signer2.address, - weight: signer2.weight, - network: chainId, - flaggedForRemoval: !isLast - }); - }); - })); - })); - return allSigners; + /** + * The number of transactions in this block. + */ + get length() { + return __privateGet(this, _transactions).length; } -} -function isAccount(value) { - return value instanceof Account; -} -const account$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - Account, - isAccount -}, Symbol.toStringTag, { value: "Module" })); -function _extends$7() { - _extends$7 = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; + /** + * The [[link-js-date]] this block was included at. + */ + get date() { + if (this.timestamp == null) { + return null; + } + return new Date(this.timestamp * 1e3); + } + /** + * Get the transaction at %%indexe%% within this block. + */ + async getTransaction(indexOrHash) { + let tx = void 0; + if (typeof indexOrHash === "number") { + tx = __privateGet(this, _transactions)[indexOrHash]; + } else { + const hash2 = indexOrHash.toLowerCase(); + for (const v3 of __privateGet(this, _transactions)) { + if (typeof v3 === "string") { + if (v3 !== hash2) { + continue; + } + tx = v3; + break; + } else { + if (v3.hash === hash2) { + continue; + } + tx = v3; + break; } } } - return target; - }; - return _extends$7.apply(this, arguments); -} -const WebRPCVersion$1 = "v1"; -const WebRPCSchemaVersion$1 = "v0.4.0"; -const WebRPCSchemaHash$1 = "9accea267e7db3d66f40d5e0f27db92eb5a29e2f"; -let ContractType$1 = /* @__PURE__ */ function(ContractType2) { - ContractType2["UNKNOWN"] = "UNKNOWN"; - ContractType2["NATIVE"] = "NATIVE"; - ContractType2["ERC20"] = "ERC20"; - ContractType2["ERC721"] = "ERC721"; - ContractType2["ERC1155"] = "ERC1155"; - ContractType2["SEQUENCE_WALLET"] = "SEQUENCE_WALLET"; - ContractType2["ERC20_BRIDGE"] = "ERC20_BRIDGE"; - ContractType2["ERC721_BRIDGE"] = "ERC721_BRIDGE"; - ContractType2["ERC1155_BRIDGE"] = "ERC1155_BRIDGE"; - ContractType2["SEQ_MARKETPLACE"] = "SEQ_MARKETPLACE"; - return ContractType2; -}({}); -let EventLogType = /* @__PURE__ */ function(EventLogType2) { - EventLogType2["UNKNOWN"] = "UNKNOWN"; - EventLogType2["BLOCK_ADDED"] = "BLOCK_ADDED"; - EventLogType2["BLOCK_REMOVED"] = "BLOCK_REMOVED"; - return EventLogType2; -}({}); -let EventLogDataType = /* @__PURE__ */ function(EventLogDataType2) { - EventLogDataType2["EVENT"] = "EVENT"; - EventLogDataType2["TOKEN_TRANSFER"] = "TOKEN_TRANSFER"; - EventLogDataType2["NATIVE_TOKEN_TRANSFER"] = "NATIVE_TOKEN_TRANSFER"; - EventLogDataType2["SEQUENCE_TXN"] = "SEQUENCE_TXN"; - return EventLogDataType2; -}({}); -let OrderStatus = /* @__PURE__ */ function(OrderStatus2) { - OrderStatus2["OPEN"] = "OPEN"; - OrderStatus2["CLOSED"] = "CLOSED"; - OrderStatus2["CANCELLED"] = "CANCELLED"; - return OrderStatus2; -}({}); -let TxnTransferType = /* @__PURE__ */ function(TxnTransferType2) { - TxnTransferType2["UNKNOWN"] = "UNKNOWN"; - TxnTransferType2["SEND"] = "SEND"; - TxnTransferType2["RECEIVE"] = "RECEIVE"; - return TxnTransferType2; -}({}); -let TransactionStatus = /* @__PURE__ */ function(TransactionStatus2) { - TransactionStatus2["FAILED"] = "FAILED"; - TransactionStatus2["SUCCESSFUL"] = "SUCCESSFUL"; - return TransactionStatus2; -}({}); -let TransactionType = /* @__PURE__ */ function(TransactionType2) { - TransactionType2["LegacyTxnType"] = "LegacyTxnType"; - TransactionType2["AccessListTxnType"] = "AccessListTxnType"; - TransactionType2["DynamicFeeTxnType"] = "DynamicFeeTxnType"; - return TransactionType2; -}({}); -let SortOrder = /* @__PURE__ */ function(SortOrder2) { - SortOrder2["DESC"] = "DESC"; - SortOrder2["ASC"] = "ASC"; - return SortOrder2; -}({}); -class Indexer { - constructor(hostname, fetch2) { - this.hostname = void 0; - this.fetch = void 0; - this.path = "/rpc/Indexer/"; - this.ping = (headers, signal) => { - return this.fetch(this.url("Ping"), createHTTPRequest$5({}, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.version = (headers, signal) => { - return this.fetch(this.url("Version"), createHTTPRequest$5({}, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - version: _data6.version - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.runtimeStatus = (headers, signal) => { - return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$5({}, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getChainID = (headers, signal) => { - return this.fetch(this.url("GetChainID"), createHTTPRequest$5({}, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - chainID: _data6.chainID - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getEtherBalance = (args, headers, signal) => { - return this.fetch(this.url("GetEtherBalance"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - balance: _data6.balance - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getTokenBalances = (args, headers, signal) => { - return this.fetch(this.url("GetTokenBalances"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - page: _data6.page, - balances: _data6.balances - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getTokenSupplies = (args, headers, signal) => { - return this.fetch(this.url("GetTokenSupplies"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - page: _data6.page, - contractType: _data6.contractType, - tokenIDs: _data6.tokenIDs - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getTokenSuppliesMap = (args, headers, signal) => { - return this.fetch(this.url("GetTokenSuppliesMap"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - supplies: _data6.supplies - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getBalanceUpdates = (args, headers, signal) => { - return this.fetch(this.url("GetBalanceUpdates"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - page: _data6.page, - balances: _data6.balances - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getTransactionHistory = (args, headers, signal) => { - return this.fetch(this.url("GetTransactionHistory"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - page: _data6.page, - transactions: _data6.transactions - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.syncBalance = (args, headers, signal) => { - return this.fetch(this.url("SyncBalance"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.fetchTransactionReceipt = (args, headers, signal) => { - return this.fetch(this.url("FetchTransactionReceipt"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - receipt: _data6.receipt - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getOrderbookOrders = (args, headers, signal) => { - return this.fetch(this.url("GetOrderbookOrders"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - page: _data6.page, - orders: _data6.orders - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getTopOrders = (args, headers, signal) => { - return this.fetch(this.url("GetTopOrders"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - orders: _data6.orders - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.fetchTransactionReceiptWithFilter = (args, headers, signal) => { - return this.fetch(this.url("FetchTransactionReceiptWithFilter"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - receipt: _data6.receipt - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getAllWebhookListeners = (args, headers, signal) => { - return this.fetch(this.url("GetAllWebhookListeners"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - listeners: _data6.listeners - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getWebhookListener = (args, headers, signal) => { - return this.fetch(this.url("GetWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - listener: _data6.listener - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.addWebhookListener = (args, headers, signal) => { - return this.fetch(this.url("AddWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - status: _data6.status, - listener: _data6.listener - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateWebhookListener = (args, headers, signal) => { - return this.fetch(this.url("UpdateWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.removeWebhookListener = (args, headers, signal) => { - return this.fetch(this.url("RemoveWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.toggleWebhookListener = (args, headers, signal) => { - return this.fetch(this.url("ToggleWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - webhookListener: _data6.webhookListener - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.pauseAllWebhookListeners = (args, headers, signal) => { - return this.fetch(this.url("PauseAllWebhookListeners"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.resumeAllWebhookListeners = (args, headers, signal) => { - return this.fetch(this.url("ResumeAllWebhookListeners"), createHTTPRequest$5(args, headers, signal)).then((res) => { - return buildResponse$5(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$5.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.subscribeReceipts = (args, options) => { - const _fetch = () => this.fetch(this.url("SubscribeReceipts"), createHTTPRequest$5(args, options.headers, options.signal)).then(async function(res) { - await sseResponse(res, options, _fetch); - }, (error) => { - options.onError(error, _fetch); - }); - return _fetch(); + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof tx === "string") { + return await this.provider.getTransaction(tx); + } else { + return tx; + } + } + /** + * If a **Block** was fetched with a request to include the transactions + * this will allow synchronous access to those transactions. + * + * If the transactions were not prefetched, this will throw. + */ + getPrefetchedTransaction(indexOrHash) { + const txs = this.prefetchedTransactions; + if (typeof indexOrHash === "number") { + return txs[indexOrHash]; + } + indexOrHash = indexOrHash.toLowerCase(); + for (const tx of txs) { + if (tx.hash === indexOrHash) { + return tx; + } + } + assertArgument(false, "no matching transaction", "indexOrHash", indexOrHash); + } + /** + * Returns true if this block been mined. This provides a type guard + * for all properties on a [[MinedBlock]]. + */ + isMined() { + return !!this.hash; + } + /** + * Returns true if this block is an [[link-eip-2930]] block. + */ + isLondon() { + return !!this.baseFeePerGas; + } + /** + * @_ignore: + */ + orphanedEvent() { + if (!this.isMined()) { + throw new Error(""); + } + return createOrphanedBlockFilter(this); + } +} +_transactions = new WeakMap(); +class Log { + /** + * @_ignore: + */ + constructor(log, provider2) { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + __publicField(this, "provider"); + /** + * The transaction hash of the transaction this log occurred in. Use the + * [[Log-getTransaction]] to get the [[TransactionResponse]]. + */ + __publicField(this, "transactionHash"); + /** + * The block hash of the block this log occurred in. Use the + * [[Log-getBlock]] to get the [[Block]]. + */ + __publicField(this, "blockHash"); + /** + * The block number of the block this log occurred in. It is preferred + * to use the [[Block-hash]] when fetching the related [[Block]], + * since in the case of an orphaned block, the block at that height may + * have changed. + */ + __publicField(this, "blockNumber"); + /** + * If the **Log** represents a block that was removed due to an orphaned + * block, this will be true. + * + * This can only happen within an orphan event listener. + */ + __publicField(this, "removed"); + /** + * The address of the contract that emitted this log. + */ + __publicField(this, "address"); + /** + * The data included in this log when it was emitted. + */ + __publicField(this, "data"); + /** + * The indexed topics included in this log when it was emitted. + * + * All topics are included in the bloom filters, so they can be + * efficiently filtered using the [[Provider-getLogs]] method. + */ + __publicField(this, "topics"); + /** + * The index within the block this log occurred at. This is generally + * not useful to developers, but can be used with the various roots + * to proof inclusion within a block. + */ + __publicField(this, "index"); + /** + * The index within the transaction of this log. + */ + __publicField(this, "transactionIndex"); + this.provider = provider2; + const topics = Object.freeze(log.topics.slice()); + defineProperties$1(this, { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + removed: log.removed, + address: log.address, + data: log.data, + topics, + index: log.index, + transactionIndex: log.transactionIndex + }); + } + /** + * Returns a JSON-compatible object. + */ + toJSON() { + const { address, blockHash, blockNumber, data, index: index2, removed, topics, transactionHash, transactionIndex } = this; + return { + _type: "log", + address, + blockHash, + blockNumber, + data, + index: index2, + removed, + topics, + transactionHash, + transactionIndex }; - this.subscribeEvents = (args, options) => { - const _fetch = () => this.fetch(this.url("SubscribeEvents"), createHTTPRequest$5(args, options.headers, options.signal)).then(async function(res) { - await sseResponse(res, options, _fetch); - }, (error) => { - options.onError(error, _fetch); - }); - return _fetch(); + } + /** + * Returns the block that this log occurred in. + */ + async getBlock() { + const block = await this.provider.getBlock(this.blockHash); + assert(!!block, "failed to find transaction", "UNKNOWN_ERROR", {}); + return block; + } + /** + * Returns the transaction that this log occurred in. + */ + async getTransaction() { + const tx = await this.provider.getTransaction(this.transactionHash); + assert(!!tx, "failed to find transaction", "UNKNOWN_ERROR", {}); + return tx; + } + /** + * Returns the transaction receipt fot the transaction that this + * log occurred in. + */ + async getTransactionReceipt() { + const receipt = await this.provider.getTransactionReceipt(this.transactionHash); + assert(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", {}); + return receipt; + } + /** + * @_ignore: + */ + removedEvent() { + return createRemovedLogFilter(this); + } +} +class TransactionReceipt { + /** + * @_ignore: + */ + constructor(tx, provider2) { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + __publicField(this, "provider"); + /** + * The address the transaction was sent to. + */ + __publicField(this, "to"); + /** + * The sender of the transaction. + */ + __publicField(this, "from"); + /** + * The address of the contract if the transaction was directly + * responsible for deploying one. + * + * This is non-null **only** if the ``to`` is empty and the ``data`` + * was successfully executed as initcode. + */ + __publicField(this, "contractAddress"); + /** + * The transaction hash. + */ + __publicField(this, "hash"); + /** + * The index of this transaction within the block transactions. + */ + __publicField(this, "index"); + /** + * The block hash of the [[Block]] this transaction was included in. + */ + __publicField(this, "blockHash"); + /** + * The block number of the [[Block]] this transaction was included in. + */ + __publicField(this, "blockNumber"); + /** + * The bloom filter bytes that represent all logs that occurred within + * this transaction. This is generally not useful for most developers, + * but can be used to validate the included logs. + */ + __publicField(this, "logsBloom"); + /** + * The actual amount of gas used by this transaction. + * + * When creating a transaction, the amount of gas that will be used can + * only be approximated, but the sender must pay the gas fee for the + * entire gas limit. After the transaction, the difference is refunded. + */ + __publicField(this, "gasUsed"); + /** + * The gas used for BLObs. See [[link-eip-4844]]. + */ + __publicField(this, "blobGasUsed"); + /** + * The amount of gas used by all transactions within the block for this + * and all transactions with a lower ``index``. + * + * This is generally not useful for developers but can be used to + * validate certain aspects of execution. + */ + __publicField(this, "cumulativeGasUsed"); + /** + * The actual gas price used during execution. + * + * Due to the complexity of [[link-eip-1559]] this value can only + * be caluclated after the transaction has been mined, snce the base + * fee is protocol-enforced. + */ + __publicField(this, "gasPrice"); + /** + * The price paid per BLOB in gas. See [[link-eip-4844]]. + */ + __publicField(this, "blobGasPrice"); + /** + * The [[link-eip-2718]] transaction type. + */ + __publicField(this, "type"); + //readonly byzantium!: boolean; + /** + * The status of this transaction, indicating success (i.e. ``1``) or + * a revert (i.e. ``0``). + * + * This is available in post-byzantium blocks, but some backends may + * backfill this value. + */ + __publicField(this, "status"); + /** + * The root hash of this transaction. + * + * This is no present and was only included in pre-byzantium blocks, but + * could be used to validate certain parts of the receipt. + */ + __publicField(this, "root"); + __privateAdd(this, _logs); + __privateSet(this, _logs, Object.freeze(tx.logs.map((log) => { + return new Log(log, provider2); + }))); + let gasPrice = BN_0$2; + if (tx.effectiveGasPrice != null) { + gasPrice = tx.effectiveGasPrice; + } else if (tx.gasPrice != null) { + gasPrice = tx.gasPrice; + } + defineProperties$1(this, { + provider: provider2, + to: tx.to, + from: tx.from, + contractAddress: tx.contractAddress, + hash: tx.hash, + index: tx.index, + blockHash: tx.blockHash, + blockNumber: tx.blockNumber, + logsBloom: tx.logsBloom, + gasUsed: tx.gasUsed, + cumulativeGasUsed: tx.cumulativeGasUsed, + blobGasUsed: tx.blobGasUsed, + gasPrice, + blobGasPrice: tx.blobGasPrice, + type: tx.type, + //byzantium: tx.byzantium, + status: tx.status, + root: tx.root + }); + } + /** + * The logs for this transaction. + */ + get logs() { + return __privateGet(this, _logs); + } + /** + * Returns a JSON-compatible representation. + */ + toJSON() { + const { + to, + from, + contractAddress, + hash: hash2, + index: index2, + blockHash, + blockNumber, + logsBloom, + logs, + //byzantium, + status, + root: root2 + } = this; + return { + _type: "TransactionReceipt", + blockHash, + blockNumber, + //byzantium, + contractAddress, + cumulativeGasUsed: toJson(this.cumulativeGasUsed), + from, + gasPrice: toJson(this.gasPrice), + blobGasUsed: toJson(this.blobGasUsed), + blobGasPrice: toJson(this.blobGasPrice), + gasUsed: toJson(this.gasUsed), + hash: hash2, + index: index2, + logs, + logsBloom, + root: root2, + status, + to }; - this.subscribeBalanceUpdates = (args, options) => { - const _fetch = () => this.fetch(this.url("SubscribeBalanceUpdates"), createHTTPRequest$5(args, options.headers, options.signal)).then(async function(res) { - await sseResponse(res, options, _fetch); - }, (error) => { - options.onError(error, _fetch); - }); - return _fetch(); + } + /** + * @_ignore: + */ + get length() { + return this.logs.length; + } + [Symbol.iterator]() { + let index2 = 0; + return { + next: () => { + if (index2 < this.length) { + return { value: this.logs[index2++], done: false }; + } + return { value: void 0, done: true }; + } }; - this.hostname = hostname; - this.fetch = (input2, init2) => fetch2(input2, init2); } - url(name2) { - return this.hostname + this.path + name2; + /** + * The total fee for this transaction, in wei. + */ + get fee() { + return this.gasUsed * this.gasPrice; + } + /** + * Resolves to the block this transaction occurred in. + */ + async getBlock() { + const block = await this.provider.getBlock(this.blockHash); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + /** + * Resolves to the transaction this transaction occurred in. + */ + async getTransaction() { + const tx = await this.provider.getTransaction(this.hash); + if (tx == null) { + throw new Error("TODO"); + } + return tx; + } + /** + * Resolves to the return value of the execution of this transaction. + * + * Support for this feature is limited, as it requires an archive node + * with the ``debug_`` or ``trace_`` API enabled. + */ + async getResult() { + return await this.provider.getTransactionResult(this.hash); + } + /** + * Resolves to the number of confirmations this transaction has. + */ + async confirmations() { + return await this.provider.getBlockNumber() - this.blockNumber + 1; + } + /** + * @_ignore: + */ + removedEvent() { + return createRemovedTransactionFilter(this); + } + /** + * @_ignore: + */ + reorderedEvent(other) { + assert(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" }); + return createReorderedTransactionFilter(this, other); + } +} +_logs = new WeakMap(); +const _TransactionResponse = class _TransactionResponse { + /** + * @_ignore: + */ + constructor(tx, provider2) { + /** + * The provider this is connected to, which will influence how its + * methods will resolve its async inspection methods. + */ + __publicField(this, "provider"); + /** + * The block number of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + __publicField(this, "blockNumber"); + /** + * The blockHash of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + __publicField(this, "blockHash"); + /** + * The index within the block that this transaction resides at. + */ + __publicField(this, "index"); + /** + * The transaction hash. + */ + __publicField(this, "hash"); + /** + * The [[link-eip-2718]] transaction envelope type. This is + * ``0`` for legacy transactions types. + */ + __publicField(this, "type"); + /** + * The receiver of this transaction. + * + * If ``null``, then the transaction is an initcode transaction. + * This means the result of executing the [[data]] will be deployed + * as a new contract on chain (assuming it does not revert) and the + * address may be computed using [[getCreateAddress]]. + */ + __publicField(this, "to"); + /** + * The sender of this transaction. It is implicitly computed + * from the transaction pre-image hash (as the digest) and the + * [[signature]] using ecrecover. + */ + __publicField(this, "from"); + /** + * The nonce, which is used to prevent replay attacks and offer + * a method to ensure transactions from a given sender are explicitly + * ordered. + * + * When sending a transaction, this must be equal to the number of + * transactions ever sent by [[from]]. + */ + __publicField(this, "nonce"); + /** + * The maximum units of gas this transaction can consume. If execution + * exceeds this, the entries transaction is reverted and the sender + * is charged for the full amount, despite not state changes being made. + */ + __publicField(this, "gasLimit"); + /** + * The gas price can have various values, depending on the network. + * + * In modern networks, for transactions that are included this is + * the //effective gas price// (the fee per gas that was actually + * charged), while for transactions that have not been included yet + * is the [[maxFeePerGas]]. + * + * For legacy transactions, or transactions on legacy networks, this + * is the fee that will be charged per unit of gas the transaction + * consumes. + */ + __publicField(this, "gasPrice"); + /** + * The maximum priority fee (per unit of gas) to allow a + * validator to charge the sender. This is inclusive of the + * [[maxFeeFeePerGas]]. + */ + __publicField(this, "maxPriorityFeePerGas"); + /** + * The maximum fee (per unit of gas) to allow this transaction + * to charge the sender. + */ + __publicField(this, "maxFeePerGas"); + /** + * The [[link-eip-4844]] max fee per BLOb gas. + */ + __publicField(this, "maxFeePerBlobGas"); + /** + * The data. + */ + __publicField(this, "data"); + /** + * The value, in wei. Use [[formatEther]] to format this value + * as ether. + */ + __publicField(this, "value"); + /** + * The chain ID. + */ + __publicField(this, "chainId"); + /** + * The signature. + */ + __publicField(this, "signature"); + /** + * The [[link-eip-2930]] access list for transaction types that + * support it, otherwise ``null``. + */ + __publicField(this, "accessList"); + /** + * The [[link-eip-4844]] BLOb versioned hashes. + */ + __publicField(this, "blobVersionedHashes"); + __privateAdd(this, _startBlock); + this.provider = provider2; + this.blockNumber = tx.blockNumber != null ? tx.blockNumber : null; + this.blockHash = tx.blockHash != null ? tx.blockHash : null; + this.hash = tx.hash; + this.index = tx.index; + this.type = tx.type; + this.from = tx.from; + this.to = tx.to || null; + this.gasLimit = tx.gasLimit; + this.nonce = tx.nonce; + this.data = tx.data; + this.value = tx.value; + this.gasPrice = tx.gasPrice; + this.maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? tx.maxPriorityFeePerGas : null; + this.maxFeePerGas = tx.maxFeePerGas != null ? tx.maxFeePerGas : null; + this.maxFeePerBlobGas = tx.maxFeePerBlobGas != null ? tx.maxFeePerBlobGas : null; + this.chainId = tx.chainId; + this.signature = tx.signature; + this.accessList = tx.accessList != null ? tx.accessList : null; + this.blobVersionedHashes = tx.blobVersionedHashes != null ? tx.blobVersionedHashes : null; + __privateSet(this, _startBlock, -1); + } + /** + * Returns a JSON-compatible representation of this transaction. + */ + toJSON() { + const { blockNumber, blockHash, index: index2, hash: hash2, type, to, from, nonce, data, signature: signature2, accessList, blobVersionedHashes } = this; + return { + _type: "TransactionResponse", + accessList, + blockNumber, + blockHash, + blobVersionedHashes, + chainId: toJson(this.chainId), + data, + from, + gasLimit: toJson(this.gasLimit), + gasPrice: toJson(this.gasPrice), + hash: hash2, + maxFeePerGas: toJson(this.maxFeePerGas), + maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), + maxFeePerBlobGas: toJson(this.maxFeePerBlobGas), + nonce, + signature: signature2, + to, + index: index2, + type, + value: toJson(this.value) + }; } -} -const sseResponse = async (res, options, retryFetch) => { - const { - onMessage, - onOpen, - onClose, - onError - } = options; - if (!res.ok) { - try { - await buildResponse$5(res); - } catch (error) { - onError(error, retryFetch); + /** + * Resolves to the Block that this transaction was included in. + * + * This will return null if the transaction has not been included yet. + */ + async getBlock() { + let blockNumber = this.blockNumber; + if (blockNumber == null) { + const tx = await this.getTransaction(); + if (tx) { + blockNumber = tx.blockNumber; + } } - return; + if (blockNumber == null) { + return null; + } + const block = this.provider.getBlock(blockNumber); + if (block == null) { + throw new Error("TODO"); + } + return block; } - if (!res.body) { - onError(WebrpcBadResponseError$5.new({ - status: res.status, - cause: "Invalid response, missing body" - }), retryFetch); - return; + /** + * Resolves to this transaction being re-requested from the + * provider. This can be used if you have an unmined transaction + * and wish to get an up-to-date populated instance. + */ + async getTransaction() { + return this.provider.getTransaction(this.hash); } - onOpen && onOpen(); - const reader2 = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer2 = ""; - let lastReadTime = Date.now(); - const timeout = (10 + 1) * 1e3; - let intervalId; - try { - intervalId = setInterval(() => { - if (Date.now() - lastReadTime > timeout) { - throw WebrpcStreamLostError$5.new({ - cause: "Stream timed out" - }); + /** + * Resolve to the number of confirmations this transaction has. + */ + async confirmations() { + if (this.blockNumber == null) { + const { tx, blockNumber: blockNumber2 } = await resolveProperties$1({ + tx: this.getTransaction(), + blockNumber: this.provider.getBlockNumber() + }); + if (tx == null || tx.blockNumber == null) { + return 0; } - }, timeout); - while (true) { - let value; - let done; - try { - ; - ({ - value, - done - } = await reader2.read()); - lastReadTime = Date.now(); - buffer2 += decoder.decode(value, { - stream: true - }); - } catch (error) { - let message = ""; - if (error instanceof Error) { - message = error.message; - } - if (error instanceof DOMException && error.name === "AbortError") { - onError(WebrpcRequestFailedError$5.new({ - message: "AbortError", - cause: `AbortError: ${message}` - }), () => { - throw new Error("Abort signal cannot be used to reconnect"); - }); - } else { - onError(WebrpcStreamLostError$5.new({ - cause: `reader.read(): ${message}` - }), retryFetch); - } + return blockNumber2 - tx.blockNumber + 1; + } + const blockNumber = await this.provider.getBlockNumber(); + return blockNumber - this.blockNumber + 1; + } + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + async wait(_confirms, _timeout2) { + const confirms = _confirms == null ? 1 : _confirms; + const timeout = _timeout2 == null ? 0 : _timeout2; + let startBlock = __privateGet(this, _startBlock); + let nextScan = -1; + let stopScanning = startBlock === -1 ? true : false; + const checkReplacement = async () => { + if (stopScanning) { + return null; + } + const { blockNumber, nonce } = await resolveProperties$1({ + blockNumber: this.provider.getBlockNumber(), + nonce: this.provider.getTransactionCount(this.from) + }); + if (nonce < this.nonce) { + startBlock = blockNumber; return; } - let lines = buffer2.split("\n"); - for (let i = 0; i < lines.length - 1; i++) { - if (lines[i].length == 0) { - continue; + if (stopScanning) { + return null; + } + const mined = await this.getTransaction(); + if (mined && mined.blockNumber != null) { + return; + } + if (nextScan === -1) { + nextScan = startBlock - 3; + if (nextScan < __privateGet(this, _startBlock)) { + nextScan = __privateGet(this, _startBlock); } - let data; - try { - data = JSON.parse(lines[i]); - if (data.hasOwnProperty("webrpcError")) { - const error = data.webrpcError; - const code2 = typeof error.code === "number" ? error.code : 0; - onError((webrpcErrorByCode$5[code2] || WebrpcError$5).new(error), retryFetch); + } + while (nextScan <= blockNumber) { + if (stopScanning) { + return null; + } + const block = await this.provider.getBlock(nextScan, true); + if (block == null) { + return; + } + for (const hash2 of block) { + if (hash2 === this.hash) { return; } - } catch (error) { - if (error instanceof Error && error.message === "Abort signal cannot be used to reconnect") { - throw error; + } + for (let i = 0; i < block.length; i++) { + const tx = await block.getTransaction(i); + if (tx.from === this.from && tx.nonce === this.nonce) { + if (stopScanning) { + return null; + } + const receipt2 = await this.provider.getTransactionReceipt(tx.hash); + if (receipt2 == null) { + return; + } + if (blockNumber - receipt2.blockNumber + 1 < confirms) { + return; + } + let reason = "replaced"; + if (tx.data === this.data && tx.to === this.to && tx.value === this.value) { + reason = "repriced"; + } else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0$2) { + reason = "cancelled"; + } + assert(false, "transaction was replaced", "TRANSACTION_REPLACED", { + cancelled: reason === "replaced" || reason === "cancelled", + reason, + replacement: tx.replaceableTransaction(startBlock), + hash: tx.hash, + receipt: receipt2 + }); } - onError(WebrpcBadResponseError$5.new({ - status: res.status, - // @ts-ignore - cause: `JSON.parse(): ${error.message}` - }), retryFetch); } - onMessage(data); - } - if (!done) { - buffer2 = lines[lines.length - 1]; - continue; + nextScan++; } - onClose && onClose(); return; + }; + const checkReceipt = (receipt2) => { + if (receipt2 == null || receipt2.status !== 0) { + return receipt2; + } + assert(false, "transaction execution reverted", "CALL_EXCEPTION", { + action: "sendTransaction", + data: null, + reason: null, + invocation: null, + revert: null, + transaction: { + to: receipt2.to, + from: receipt2.from, + data: "" + // @TODO: in v7, split out sendTransaction properties + }, + receipt: receipt2 + }); + }; + const receipt = await this.provider.getTransactionReceipt(this.hash); + if (confirms === 0) { + return checkReceipt(receipt); } - } catch (error) { - if (error instanceof WebrpcStreamLostError$5) { - onError(error, retryFetch); + if (receipt) { + if (await receipt.confirmations() >= confirms) { + return checkReceipt(receipt); + } } else { - throw error; + await checkReplacement(); + if (confirms === 0) { + return null; + } } - } finally { - clearInterval(intervalId); - } -}; -const createHTTPRequest$5 = (body = {}, headers = {}, signal = null) => { - return { - method: "POST", - headers: _extends$7({}, headers, { - "Content-Type": "application/json" - }), - body: JSON.stringify(body || {}), - signal - }; -}; -const buildResponse$5 = (res) => { - return res.text().then((text2) => { - let data; - try { - data = JSON.parse(text2); - } catch (error) { - let message = ""; - if (error instanceof Error) { - message = error.message; + const waiter = new Promise((resolve, reject) => { + const cancellers = []; + const cancel = () => { + cancellers.forEach((c2) => c2()); + }; + cancellers.push(() => { + stopScanning = true; + }); + if (timeout > 0) { + const timer = setTimeout(() => { + cancel(); + reject(makeError("wait for transaction timeout", "TIMEOUT")); + }, timeout); + cancellers.push(() => { + clearTimeout(timer); + }); } - throw WebrpcBadResponseError$5.new({ - status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text2}` + const txListener = async (receipt2) => { + if (await receipt2.confirmations() >= confirms) { + cancel(); + try { + resolve(checkReceipt(receipt2)); + } catch (error) { + reject(error); + } + } + }; + cancellers.push(() => { + this.provider.off(this.hash, txListener); }); - } - if (!res.ok) { - const code2 = typeof data.code === "number" ? data.code : 0; - throw (webrpcErrorByCode$5[code2] || WebrpcError$5).new(data); - } - return data; - }); -}; -let WebrpcError$5 = class WebrpcError3 extends Error { - constructor(name2, code2, message, status, cause) { - super(message); - this.name = void 0; - this.code = void 0; - this.message = void 0; - this.status = void 0; - this.cause = void 0; - this.msg = void 0; - this.name = name2 || "WebrpcError"; - this.code = typeof code2 === "number" ? code2 : 0; - this.message = message || `endpoint error ${this.code}`; - this.msg = this.message; - this.status = typeof status === "number" ? status : 0; - this.cause = cause; - Object.setPrototypeOf(this, WebrpcError3.prototype); + this.provider.on(this.hash, txListener); + if (startBlock >= 0) { + const replaceListener = async () => { + try { + await checkReplacement(); + } catch (error) { + if (isError(error, "TRANSACTION_REPLACED")) { + cancel(); + reject(error); + return; + } + } + if (!stopScanning) { + this.provider.once("block", replaceListener); + } + }; + cancellers.push(() => { + this.provider.off("block", replaceListener); + }); + this.provider.once("block", replaceListener); + } + }); + return await waiter; } - static new(payload) { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + /** + * Returns ``true`` if this transaction has been included. + * + * This is effective only as of the time the TransactionResponse + * was instantiated. To get up-to-date information, use + * [[getTransaction]]. + * + * This provides a Type Guard that this transaction will have + * non-null property values for properties that are null for + * unmined transactions. + */ + isMined() { + return this.blockHash != null; } -}; -let WebrpcEndpointError$5 = class WebrpcEndpointError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcEndpointError3.prototype); + /** + * Returns true if the transaction is a legacy (i.e. ``type == 0``) + * transaction. + * + * This provides a Type Guard that this transaction will have + * the ``null``-ness for hardfork-specific properties set correctly. + */ + isLegacy() { + return this.type === 0; + } + /** + * Returns true if the transaction is a Berlin (i.e. ``type == 1``) + * transaction. See [[link-eip-2070]]. + * + * This provides a Type Guard that this transaction will have + * the ``null``-ness for hardfork-specific properties set correctly. + */ + isBerlin() { + return this.type === 1; + } + /** + * Returns true if the transaction is a London (i.e. ``type == 2``) + * transaction. See [[link-eip-1559]]. + * + * This provides a Type Guard that this transaction will have + * the ``null``-ness for hardfork-specific properties set correctly. + */ + isLondon() { + return this.type === 2; + } + /** + * Returns true if hte transaction is a Cancun (i.e. ``type == 3``) + * transaction. See [[link-eip-4844]]. + */ + isCancun() { + return this.type === 3; + } + /** + * Returns a filter which can be used to listen for orphan events + * that evict this transaction. + */ + removedEvent() { + assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + return createRemovedTransactionFilter(this); + } + /** + * Returns a filter which can be used to listen for orphan events + * that re-order this event against %%other%%. + */ + reorderedEvent(other) { + assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + return createReorderedTransactionFilter(this, other); + } + /** + * Returns a new TransactionResponse instance which has the ability to + * detect (and throw an error) if the transaction is replaced, which + * will begin scanning at %%startBlock%%. + * + * This should generally not be used by developers and is intended + * primarily for internal use. Setting an incorrect %%startBlock%% can + * have devastating performance consequences if used incorrectly. + */ + replaceableTransaction(startBlock) { + assertArgument(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock); + const tx = new _TransactionResponse(this, this.provider); + __privateSet(tx, _startBlock, startBlock); + return tx; } }; -let WebrpcRequestFailedError$5 = class WebrpcRequestFailedError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcRequestFailedError3.prototype); +_startBlock = new WeakMap(); +let TransactionResponse = _TransactionResponse; +function createOrphanedBlockFilter(block) { + return { orphan: "drop-block", hash: block.hash, number: block.number }; +} +function createReorderedTransactionFilter(tx, other) { + return { orphan: "reorder-transaction", tx, other }; +} +function createRemovedTransactionFilter(tx) { + return { orphan: "drop-transaction", tx }; +} +function createRemovedLogFilter(log) { + return { orphan: "drop-log", log: { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + address: log.address, + data: log.data, + topics: Object.freeze(log.topics.slice()), + index: log.index + } }; +} +class EventLog extends Log { + /** + * @_ignore: + */ + constructor(log, iface, fragment) { + super(log, log.provider); + /** + * The Contract Interface. + */ + __publicField(this, "interface"); + /** + * The matching event. + */ + __publicField(this, "fragment"); + /** + * The parsed arguments passed to the event by ``emit``. + */ + __publicField(this, "args"); + const args = iface.decodeEventLog(fragment, log.data, log.topics); + defineProperties$1(this, { args, fragment, interface: iface }); } -}; -let WebrpcBadRouteError$5 = class WebrpcBadRouteError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRouteError3.prototype); + /** + * The name of the event. + */ + get eventName() { + return this.fragment.name; } -}; -let WebrpcBadMethodError$5 = class WebrpcBadMethodError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadMethodError3.prototype); + /** + * The signature of the event. + */ + get eventSignature() { + return this.fragment.format(); } -}; -let WebrpcBadRequestError$5 = class WebrpcBadRequestError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRequestError3.prototype); +} +class UndecodedEventLog extends Log { + /** + * @_ignore: + */ + constructor(log, error) { + super(log, log.provider); + /** + * The error encounted when trying to decode the log. + */ + __publicField(this, "error"); + defineProperties$1(this, { error }); } -}; -let WebrpcBadResponseError$5 = class WebrpcBadResponseError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadResponseError3.prototype); +} +class ContractTransactionReceipt extends TransactionReceipt { + /** + * @_ignore: + */ + constructor(iface, provider2, tx) { + super(tx, provider2); + __privateAdd(this, _iface); + __privateSet(this, _iface, iface); } -}; -let WebrpcServerPanicError$5 = class WebrpcServerPanicError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcServerPanicError3.prototype); + /** + * The parsed logs for any [[Log]] which has a matching event in the + * Contract ABI. + */ + get logs() { + return super.logs.map((log) => { + const fragment = log.topics.length ? __privateGet(this, _iface).getEvent(log.topics[0]) : null; + if (fragment) { + try { + return new EventLog(log, __privateGet(this, _iface), fragment); + } catch (error) { + return new UndecodedEventLog(log, error); + } + } + return log; + }); } -}; -let WebrpcInternalErrorError$5 = class WebrpcInternalErrorError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcInternalErrorError3.prototype); +} +_iface = new WeakMap(); +class ContractTransactionResponse extends TransactionResponse { + /** + * @_ignore: + */ + constructor(iface, provider2, tx) { + super(tx, provider2); + __privateAdd(this, _iface2); + __privateSet(this, _iface2, iface); } -}; -let WebrpcClientDisconnectedError$5 = class WebrpcClientDisconnectedError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcClientDisconnectedError3.prototype); + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + async wait(confirms, timeout) { + const receipt = await super.wait(confirms, timeout); + if (receipt == null) { + return null; + } + return new ContractTransactionReceipt(__privateGet(this, _iface2), this.provider, receipt); } -}; -let WebrpcStreamLostError$5 = class WebrpcStreamLostError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamLostError3.prototype); +} +_iface2 = new WeakMap(); +class ContractUnknownEventPayload extends EventPayload { + /** + * @_event: + */ + constructor(contract, listener, filter2, log) { + super(contract, listener, filter2); + /** + * The log with no matching events. + */ + __publicField(this, "log"); + defineProperties$1(this, { log }); } -}; -let WebrpcStreamFinishedError$5 = class WebrpcStreamFinishedError3 extends WebrpcError$5 { - constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamFinishedError3.prototype); + /** + * Resolves to the block the event occured in. + */ + async getBlock() { + return await this.log.getBlock(); } -}; -let UnauthorizedError$4 = class UnauthorizedError3 extends WebrpcError$5 { - constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, UnauthorizedError3.prototype); + /** + * Resolves to the transaction the event occured in. + */ + async getTransaction() { + return await this.log.getTransaction(); } -}; -let PermissionDeniedError$2 = class PermissionDeniedError3 extends WebrpcError$5 { - constructor(name2 = "PermissionDenied", code2 = 1001, message = "Permission denied", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, PermissionDeniedError3.prototype); + /** + * Resolves to the transaction receipt the event occured in. + */ + async getTransactionReceipt() { + return await this.log.getTransactionReceipt(); } -}; -let SessionExpiredError$3 = class SessionExpiredError2 extends WebrpcError$5 { - constructor(name2 = "SessionExpired", code2 = 1002, message = "Session expired", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, SessionExpiredError2.prototype); +} +class ContractEventPayload extends ContractUnknownEventPayload { + /** + * @_ignore: + */ + constructor(contract, listener, filter2, fragment, _log) { + super(contract, listener, filter2, new EventLog(_log, contract.interface, fragment)); + const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics); + defineProperties$1(this, { args, fragment }); } -}; -let MethodNotFoundError$1 = class MethodNotFoundError2 extends WebrpcError$5 { - constructor(name2 = "MethodNotFound", code2 = 1003, message = "Method not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, MethodNotFoundError2.prototype); + /** + * The event name. + */ + get eventName() { + return this.fragment.name; } -}; -let RequestConflictError$1 = class RequestConflictError extends WebrpcError$5 { - constructor(name2 = "RequestConflict", code2 = 1004, message = "Conflict with target resource", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, RequestConflictError.prototype); + /** + * The event signature. + */ + get eventSignature() { + return this.fragment.format(); } -}; -let AbortedError$1 = class AbortedError3 extends WebrpcError$5 { - constructor(name2 = "Aborted", code2 = 1005, message = "Request aborted", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, AbortedError3.prototype); +} +const BN_0$1 = BigInt(0); +function canCall(value) { + return value && typeof value.call === "function"; +} +function canEstimate(value) { + return value && typeof value.estimateGas === "function"; +} +function canResolve(value) { + return value && typeof value.resolveName === "function"; +} +function canSend(value) { + return value && typeof value.sendTransaction === "function"; +} +function getResolver(value) { + if (value != null) { + if (canResolve(value)) { + return value; + } + if (value.provider) { + return value.provider; + } } -}; -let TimeoutError$2 = class TimeoutError extends WebrpcError$5 { - constructor(name2 = "Timeout", code2 = 2e3, message = "Request timed out", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, TimeoutError.prototype); + return void 0; +} +class PreparedTopicFilter { + constructor(contract, fragment, args) { + __privateAdd(this, _filter); + __publicField(this, "fragment"); + defineProperties$1(this, { fragment }); + if (fragment.inputs.length < args.length) { + throw new Error("too many arguments"); + } + const runner = getRunner(contract.runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + __privateSet(this, _filter, async function() { + const resolvedArgs = await Promise.all(fragment.inputs.map((param, index2) => { + const arg = args[index2]; + if (arg == null) { + return null; + } + return param.walkAsync(args[index2], (type, value) => { + if (type === "address") { + if (Array.isArray(value)) { + return Promise.all(value.map((v3) => resolveAddress(v3, resolver))); + } + return resolveAddress(value, resolver); + } + return value; + }); + })); + return contract.interface.encodeFilterTopics(fragment, resolvedArgs); + }()); } -}; -let InvalidArgumentError$3 = class InvalidArgumentError3 extends WebrpcError$5 { - constructor(name2 = "InvalidArgument", code2 = 2001, message = "Invalid argument", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, InvalidArgumentError3.prototype); + getTopicFilter() { + return __privateGet(this, _filter); } -}; -let UnavailableError$1 = class UnavailableError3 extends WebrpcError$5 { - constructor(name2 = "Unavailable", code2 = 2002, message = "Unavailable resource", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, UnavailableError3.prototype); +} +_filter = new WeakMap(); +function getRunner(value, feature) { + if (value == null) { + return null; } -}; -let QueryFailedError$3 = class QueryFailedError3 extends WebrpcError$5 { - constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, QueryFailedError3.prototype); + if (typeof value[feature] === "function") { + return value; } -}; -class ResourceExhaustedError extends WebrpcError$5 { - constructor(name2 = "ResourceExhausted", code2 = 2004, message = "Resource exhausted", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, ResourceExhaustedError.prototype); + if (value.provider && typeof value.provider[feature] === "function") { + return value.provider; } + return null; } -let NotFoundError$4 = class NotFoundError3 extends WebrpcError$5 { - constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, NotFoundError3.prototype); - } -}; -let ProjectNotFoundError$1 = class ProjectNotFoundError extends WebrpcError$5 { - constructor(name2 = "ProjectNotFound", code2 = 3002, message = "Project not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, ProjectNotFoundError.prototype); +function getProvider(value) { + if (value == null) { + return null; } -}; -class MetadataCallFailedError extends WebrpcError$5 { - constructor(name2 = "MetadataCallFailed", code2 = 3003, message = "Metadata service call failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, MetadataCallFailedError.prototype); + return value.provider || null; +} +async function copyOverrides(arg, allowed) { + const _overrides = Typed.dereference(arg, "overrides"); + assertArgument(typeof _overrides === "object", "invalid overrides parameter", "overrides", arg); + const overrides = copyRequest(_overrides); + assertArgument(overrides.to == null || (allowed || []).indexOf("to") >= 0, "cannot override to", "overrides.to", overrides.to); + assertArgument(overrides.data == null || (allowed || []).indexOf("data") >= 0, "cannot override data", "overrides.data", overrides.data); + if (overrides.from) { + overrides.from = overrides.from; } + return overrides; } -let errors$1 = /* @__PURE__ */ function(errors2) { - errors2["WebrpcEndpoint"] = "WebrpcEndpoint"; - errors2["WebrpcRequestFailed"] = "WebrpcRequestFailed"; - errors2["WebrpcBadRoute"] = "WebrpcBadRoute"; - errors2["WebrpcBadMethod"] = "WebrpcBadMethod"; - errors2["WebrpcBadRequest"] = "WebrpcBadRequest"; - errors2["WebrpcBadResponse"] = "WebrpcBadResponse"; - errors2["WebrpcServerPanic"] = "WebrpcServerPanic"; - errors2["WebrpcInternalError"] = "WebrpcInternalError"; - errors2["WebrpcClientDisconnected"] = "WebrpcClientDisconnected"; - errors2["WebrpcStreamLost"] = "WebrpcStreamLost"; - errors2["WebrpcStreamFinished"] = "WebrpcStreamFinished"; - errors2["Unauthorized"] = "Unauthorized"; - errors2["PermissionDenied"] = "PermissionDenied"; - errors2["SessionExpired"] = "SessionExpired"; - errors2["MethodNotFound"] = "MethodNotFound"; - errors2["RequestConflict"] = "RequestConflict"; - errors2["Aborted"] = "Aborted"; - errors2["Timeout"] = "Timeout"; - errors2["InvalidArgument"] = "InvalidArgument"; - errors2["Unavailable"] = "Unavailable"; - errors2["QueryFailed"] = "QueryFailed"; - errors2["ResourceExhausted"] = "ResourceExhausted"; - errors2["NotFound"] = "NotFound"; - errors2["ProjectNotFound"] = "ProjectNotFound"; - errors2["MetadataCallFailed"] = "MetadataCallFailed"; - return errors2; -}({}); -const webrpcErrorByCode$5 = { - [0]: WebrpcEndpointError$5, - [-1]: WebrpcRequestFailedError$5, - [-2]: WebrpcBadRouteError$5, - [-3]: WebrpcBadMethodError$5, - [-4]: WebrpcBadRequestError$5, - [-5]: WebrpcBadResponseError$5, - [-6]: WebrpcServerPanicError$5, - [-7]: WebrpcInternalErrorError$5, - [-8]: WebrpcClientDisconnectedError$5, - [-9]: WebrpcStreamLostError$5, - [-10]: WebrpcStreamFinishedError$5, - [1e3]: UnauthorizedError$4, - [1001]: PermissionDeniedError$2, - [1002]: SessionExpiredError$3, - [1003]: MethodNotFoundError$1, - [1004]: RequestConflictError$1, - [1005]: AbortedError$1, - [2e3]: TimeoutError$2, - [2001]: InvalidArgumentError$3, - [2002]: UnavailableError$1, - [2003]: QueryFailedError$3, - [2004]: ResourceExhaustedError, - [3e3]: NotFoundError$4, - [3002]: ProjectNotFoundError$1, - [3003]: MetadataCallFailedError -}; -const fetch$4 = globalThis.fetch; -class SequenceIndexer extends Indexer { - constructor(hostname, projectAccessKey2, jwtAuth) { - super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, fetch$4); - this.projectAccessKey = projectAccessKey2; - this.jwtAuth = jwtAuth; - this._fetch = (input2, init2) => { - const headers = {}; - const jwtAuth2 = this.jwtAuth; - const projectAccessKey3 = this.projectAccessKey; - if (jwtAuth2 && jwtAuth2.length > 0) { - headers["Authorization"] = `BEARER ${jwtAuth2}`; - } - if (projectAccessKey3 && projectAccessKey3.length > 0) { - headers["X-Access-Key"] = projectAccessKey3; +async function resolveArgs(_runner, inputs, args) { + const runner = getRunner(_runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + return await Promise.all(inputs.map((param, index2) => { + return param.walkAsync(args[index2], (type, value) => { + value = Typed.dereference(value, type); + if (type === "address") { + return resolveAddress(value, resolver); } - init2.headers = _extends$7({}, init2.headers, headers); - return fetch$4(input2, init2); - }; - this.fetch = this._fetch; - } + return value; + }); + })); } -const indexer$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - AbortedError: AbortedError$1, - ContractType: ContractType$1, - EventLogDataType, - EventLogType, - Indexer, - InvalidArgumentError: InvalidArgumentError$3, - MetadataCallFailedError, - MethodNotFoundError: MethodNotFoundError$1, - NotFoundError: NotFoundError$4, - OrderStatus, - PermissionDeniedError: PermissionDeniedError$2, - ProjectNotFoundError: ProjectNotFoundError$1, - QueryFailedError: QueryFailedError$3, - RequestConflictError: RequestConflictError$1, - ResourceExhaustedError, - SequenceIndexer, - SessionExpiredError: SessionExpiredError$3, - SortOrder, - TimeoutError: TimeoutError$2, - TransactionStatus, - TransactionType, - TxnTransferType, - UnauthorizedError: UnauthorizedError$4, - UnavailableError: UnavailableError$1, - WebRPCSchemaHash: WebRPCSchemaHash$1, - WebRPCSchemaVersion: WebRPCSchemaVersion$1, - WebRPCVersion: WebRPCVersion$1, - WebrpcBadMethodError: WebrpcBadMethodError$5, - WebrpcBadRequestError: WebrpcBadRequestError$5, - WebrpcBadResponseError: WebrpcBadResponseError$5, - WebrpcBadRouteError: WebrpcBadRouteError$5, - WebrpcClientDisconnectedError: WebrpcClientDisconnectedError$5, - WebrpcEndpointError: WebrpcEndpointError$5, - WebrpcError: WebrpcError$5, - WebrpcInternalErrorError: WebrpcInternalErrorError$5, - WebrpcRequestFailedError: WebrpcRequestFailedError$5, - WebrpcServerPanicError: WebrpcServerPanicError$5, - WebrpcStreamFinishedError: WebrpcStreamFinishedError$5, - WebrpcStreamLostError: WebrpcStreamLostError$5, - errors: errors$1 -}, Symbol.toStringTag, { value: "Module" })); -function _extends$6() { - _extends$6 = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } +function buildWrappedFallback(contract) { + const populateTransaction = async function(overrides) { + const tx = await copyOverrides(overrides, ["data"]); + tx.to = await contract.getAddress(); + if (tx.from) { + tx.from = await resolveAddress(tx.from, getResolver(contract.runner)); + } + const iface = contract.interface; + const noValue = getBigInt(tx.value || BN_0$1, "overrides.value") === BN_0$1; + const noData = (tx.data || "0x") === "0x"; + if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) { + assertArgument(false, "cannot send data to receive or send value to non-payable fallback", "overrides", overrides); + } + assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + const payable = iface.receive || iface.fallback && iface.fallback.payable; + assertArgument(payable || noValue, "cannot send value to non-payable fallback", "overrides.value", tx.value); + assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + return tx; + }; + const staticCall = async function(overrides) { + const runner = getRunner(contract.runner, "call"); + assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); + const tx = await populateTransaction(overrides); + try { + return await runner.call(tx); + } catch (error) { + if (isCallException(error) && error.data) { + throw contract.interface.makeError(error.data, tx); + } + throw error; + } + }; + const send = async function(overrides) { + const runner = contract.runner; + assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); + const tx = await runner.sendTransaction(await populateTransaction(overrides)); + const provider2 = getProvider(contract.runner); + return new ContractTransactionResponse(contract.interface, provider2, tx); + }; + const estimateGas2 = async function(overrides) { + const runner = getRunner(contract.runner, "estimateGas"); + assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); + return await runner.estimateGas(await populateTransaction(overrides)); + }; + const method = async (overrides) => { + return await send(overrides); + }; + defineProperties$1(method, { + _contract: contract, + estimateGas: estimateGas2, + populateTransaction, + send, + staticCall + }); + return method; +} +function buildWrappedMethod(contract, key) { + const getFragment = function(...args) { + const fragment = contract.interface.getFunction(key, args); + assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key, args } + }); + return fragment; + }; + const populateTransaction = async function(...args) { + const fragment = getFragment(...args); + let overrides = {}; + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); + if (overrides.from) { + overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner)); } } - return target; + if (fragment.inputs.length !== args.length) { + throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); + } + const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); + return Object.assign({}, overrides, await resolveProperties$1({ + to: contract.getAddress(), + data: contract.interface.encodeFunctionData(fragment, resolvedArgs) + })); }; - return _extends$6.apply(this, arguments); -} -const WebRPCVersion = "v1"; -const WebRPCSchemaVersion = "v0.4.0"; -const WebRPCSchemaHash = "9d0976f6ff345b6a688b69cff647454e7fd0e3a6"; -let ContractType = /* @__PURE__ */ function(ContractType2) { - ContractType2["UNKNOWN"] = "UNKNOWN"; - ContractType2["ERC20"] = "ERC20"; - ContractType2["ERC721"] = "ERC721"; - ContractType2["ERC1155"] = "ERC1155"; - return ContractType2; -}({}); -let PropertyType = /* @__PURE__ */ function(PropertyType2) { - PropertyType2["INT"] = "INT"; - PropertyType2["STRING"] = "STRING"; - PropertyType2["ARRAY"] = "ARRAY"; - PropertyType2["GENERIC"] = "GENERIC"; - return PropertyType2; -}({}); -let SwapType = /* @__PURE__ */ function(SwapType2) { - SwapType2["UNKNOWN"] = "UNKNOWN"; - SwapType2["BUY"] = "BUY"; - SwapType2["SELL"] = "SELL"; - return SwapType2; -}({}); -let TaskStatus = /* @__PURE__ */ function(TaskStatus2) { - TaskStatus2["PENDING"] = "PENDING"; - TaskStatus2["PAUSED"] = "PAUSED"; - TaskStatus2["FAILED"] = "FAILED"; - TaskStatus2["COMPLETED"] = "COMPLETED"; - TaskStatus2["DISABLED"] = "DISABLED"; - return TaskStatus2; -}({}); -class Metadata { - constructor(hostname, fetch2) { - this.hostname = void 0; - this.fetch = void 0; - this.path = "/rpc/Metadata/"; - this.ping = (headers, signal) => { - return this.fetch(this.url("Ping"), createHTTPRequest$4({}, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.version = (headers, signal) => { - return this.fetch(this.url("Version"), createHTTPRequest$4({}, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - version: _data6.version - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.runtimeStatus = (headers, signal) => { - return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$4({}, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getTokenMetadata = (args, headers, signal) => { - return this.fetch(this.url("GetTokenMetadata"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - tokenMetadata: _data6.tokenMetadata - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.refreshTokenMetadata = (args, headers, signal) => { - return this.fetch(this.url("RefreshTokenMetadata"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - taskId: _data6.taskId - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.enqueueTokensForRefresh = (args, headers, signal) => { - return this.fetch(this.url("EnqueueTokensForRefresh"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - taskId: _data6.taskId - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getTokenRefreshStatus = (args, headers, signal) => { - return this.fetch(this.url("GetTokenRefreshStatus"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getTokenRefreshResult = (args, headers, signal) => { - return this.fetch(this.url("GetTokenRefreshResult"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - status: _data6.status, - tokens: _data6.tokens, - failureReasons: _data6.failureReasons - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.cancelRefreshJob = (args, headers, signal) => { - return this.fetch(this.url("CancelRefreshJob"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getTokenMetadataBatch = (args, headers, signal) => { - return this.fetch(this.url("GetTokenMetadataBatch"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - contractTokenMetadata: _data6.contractTokenMetadata - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.searchTokenMetadata = (args, headers, signal) => { - return this.fetch(this.url("SearchTokenMetadata"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - page: _data6.page, - tokenMetadata: _data6.tokenMetadata - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.searchTokenIDs = (args, headers, signal) => { - return this.fetch(this.url("SearchTokenIDs"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - page: _data6.page, - tokenIds: _data6.tokenIds - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.tokenCollectionFilters = (args, headers, signal) => { - return this.fetch(this.url("TokenCollectionFilters"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - filters: _data6.filters - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getContractInfo = (args, headers, signal) => { - return this.fetch(this.url("GetContractInfo"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - contractInfo: _data6.contractInfo - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getContractInfoBatch = (args, headers, signal) => { - return this.fetch(this.url("GetContractInfoBatch"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - contractInfoMap: _data6.contractInfoMap - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.searchContractInfo = (args, headers, signal) => { - return this.fetch(this.url("SearchContractInfo"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - contractInfoList: _data6.contractInfoList - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.searchContractInfoBatch = (args, headers, signal) => { - return this.fetch(this.url("SearchContractInfoBatch"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - contractInfoByChain: _data6.contractInfoByChain - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.searchMetadata = (args, headers, signal) => { - return this.fetch(this.url("SearchMetadata"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - tokenMetadata: _data6.tokenMetadata, - contractInfo: _data6.contractInfo - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.searchTokens = (args, headers, signal) => { - return this.fetch(this.url("SearchTokens"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - tokenMetadata: _data6.tokenMetadata, - nextPage: _data6.nextPage - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.searchContracts = (args, headers, signal) => { - return this.fetch(this.url("SearchContracts"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - contractInfo: _data6.contractInfo, - nextPage: _data6.nextPage - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getNiftyswapTokenQuantity = (args, headers, signal) => { - return this.fetch(this.url("GetNiftyswapTokenQuantity"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - quantity: _data6.quantity - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getNiftyswapUnitPrices = (args, headers, signal) => { - return this.fetch(this.url("GetNiftyswapUnitPrices"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - prices: _data6.prices - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getNiftyswapUnitPricesWithQuantities = (args, headers, signal) => { - return this.fetch(this.url("GetNiftyswapUnitPricesWithQuantities"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - prices: _data6.prices - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.addContractToMintMonitor = (args, headers, signal) => { - return this.fetch(this.url("AddContractToMintMonitor"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.removeContractFromMintMonitor = (args, headers, signal) => { - return this.fetch(this.url("RemoveContractFromMintMonitor"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.mintMonitorJobStatus = (args, headers, signal) => { - return this.fetch(this.url("MintMonitorJobStatus"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - task: _data6.task - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.mintMonitorTriggerJob = (args, headers, signal) => { - return this.fetch(this.url("MintMonitorTriggerJob"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.syncContractTokens = (args, headers, signal) => { - return this.fetch(this.url("SyncContractTokens"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - taskID: _data6.taskID - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.abortContractSync = (args, headers, signal) => { - return this.fetch(this.url("AbortContractSync"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); + const staticCall = async function(...args) { + const result = await staticCallResult(...args); + if (result.length === 1) { + return result[0]; + } + return result; + }; + const send = async function(...args) { + const runner = contract.runner; + assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); + const tx = await runner.sendTransaction(await populateTransaction(...args)); + const provider2 = getProvider(contract.runner); + return new ContractTransactionResponse(contract.interface, provider2, tx); + }; + const estimateGas2 = async function(...args) { + const runner = getRunner(contract.runner, "estimateGas"); + assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); + return await runner.estimateGas(await populateTransaction(...args)); + }; + const staticCallResult = async function(...args) { + const runner = getRunner(contract.runner, "call"); + assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); + const tx = await populateTransaction(...args); + let result = "0x"; + try { + result = await runner.call(tx); + } catch (error) { + if (isCallException(error) && error.data) { + throw contract.interface.makeError(error.data, tx); + } + throw error; + } + const fragment = getFragment(...args); + return contract.interface.decodeFunctionResult(fragment, result); + }; + const method = async (...args) => { + const fragment = getFragment(...args); + if (fragment.constant) { + return await staticCall(...args); + } + return await send(...args); + }; + defineProperties$1(method, { + name: contract.interface.getFunctionName(key), + _contract: contract, + _key: key, + getFragment, + estimateGas: estimateGas2, + populateTransaction, + send, + staticCall, + staticCallResult + }); + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: () => { + const fragment = contract.interface.getFunction(key); + assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key } }); - }; - this.contractSyncJobStatus = (args, headers, signal) => { - return this.fetch(this.url("ContractSyncJobStatus"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - refreshTask: _data6.refreshTask, - syncTask: _data6.syncTask - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); + return fragment; + } + }); + return method; +} +function buildWrappedEvent(contract, key) { + const getFragment = function(...args) { + const fragment = contract.interface.getEvent(key, args); + assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key, args } + }); + return fragment; + }; + const method = function(...args) { + return new PreparedTopicFilter(contract, getFragment(...args), args); + }; + defineProperties$1(method, { + name: contract.interface.getEventName(key), + _contract: contract, + _key: key, + getFragment + }); + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: () => { + const fragment = contract.interface.getEvent(key); + assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key } }); + return fragment; + } + }); + return method; +} +const internal = Symbol.for("_ethersInternal_contract"); +const internalValues = /* @__PURE__ */ new WeakMap(); +function setInternal(contract, values) { + internalValues.set(contract[internal], values); +} +function getInternal(contract) { + return internalValues.get(contract[internal]); +} +function isDeferred(value) { + return value && typeof value === "object" && "getTopicFilter" in value && typeof value.getTopicFilter === "function" && value.fragment; +} +async function getSubInfo(contract, event) { + let topics; + let fragment = null; + if (Array.isArray(event)) { + const topicHashify = function(name2) { + if (isHexString(name2, 32)) { + return name2; + } + const fragment2 = contract.interface.getEvent(name2); + assertArgument(fragment2, "unknown fragment", "name", name2); + return fragment2.topicHash; }; - this.directoryGetNetworks = (args, headers, signal) => { - return this.fetch(this.url("DirectoryGetNetworks"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - networks: _data6.networks - }; + topics = event.map((e2) => { + if (e2 == null) { + return null; + } + if (Array.isArray(e2)) { + return e2.map(topicHashify); + } + return topicHashify(e2); + }); + } else if (event === "*") { + topics = [null]; + } else if (typeof event === "string") { + if (isHexString(event, 32)) { + topics = [event]; + } else { + fragment = contract.interface.getEvent(event); + assertArgument(fragment, "unknown fragment", "event", event); + topics = [fragment.topicHash]; + } + } else if (isDeferred(event)) { + topics = await event.getTopicFilter(); + } else if ("fragment" in event) { + fragment = event.fragment; + topics = [fragment.topicHash]; + } else { + assertArgument(false, "unknown event name", "event", event); + } + topics = topics.map((t2) => { + if (t2 == null) { + return null; + } + if (Array.isArray(t2)) { + const items = Array.from(new Set(t2.map((t3) => t3.toLowerCase())).values()); + if (items.length === 1) { + return items[0]; + } + items.sort(); + return items; + } + return t2.toLowerCase(); + }); + const tag = topics.map((t2) => { + if (t2 == null) { + return "null"; + } + if (Array.isArray(t2)) { + return t2.join("|"); + } + return t2; + }).join("&"); + return { fragment, tag, topics }; +} +async function hasSub(contract, event) { + const { subs } = getInternal(contract); + return subs.get((await getSubInfo(contract, event)).tag) || null; +} +async function getSub(contract, operation, event) { + const provider2 = getProvider(contract.runner); + assert(provider2, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { operation }); + const { fragment, tag, topics } = await getSubInfo(contract, event); + const { addr, subs } = getInternal(contract); + let sub = subs.get(tag); + if (!sub) { + const address = addr ? addr : contract; + const filter2 = { address, topics }; + const listener = (log) => { + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = contract.interface.getEvent(log.topics[0]); + } catch (error) { + } + } + if (foundFragment) { + const _foundFragment = foundFragment; + const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : []; + emit(contract, event, args, (listener2) => { + return new ContractEventPayload(contract, listener2, event, _foundFragment, log); }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` + } else { + emit(contract, event, [], (listener2) => { + return new ContractUnknownEventPayload(contract, listener2, event, log); }); - }); + } }; - this.directoryGetCollections = (args, headers, signal) => { - return this.fetch(this.url("DirectoryGetCollections"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - collections: _data6.collections, - page: _data6.page - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); + let starting = []; + const start = () => { + if (starting.length) { + return; + } + starting.push(provider2.on(filter2, listener)); }; - this.directorySearchCollections = (args, headers, signal) => { - return this.fetch(this.url("DirectorySearchCollections"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - collections: _data6.collections, - page: _data6.page - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` + const stop = async () => { + if (starting.length == 0) { + return; + } + let started = starting; + starting = []; + await Promise.all(started); + provider2.off(filter2, listener); + }; + sub = { tag, listeners: [], start, stop }; + subs.set(tag, sub); + } + return sub; +} +let lastEmit = Promise.resolve(); +async function _emit(contract, event, args, payloadFunc) { + await lastEmit; + const sub = await hasSub(contract, event); + if (!sub) { + return false; + } + const count2 = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once }) => { + const passArgs = Array.from(args); + if (payloadFunc) { + passArgs.push(payloadFunc(once ? null : listener)); + } + try { + listener.call(contract, ...passArgs); + } catch (error) { + } + return !once; + }); + if (sub.listeners.length === 0) { + sub.stop(); + getInternal(contract).subs.delete(sub.tag); + } + return count2 > 0; +} +async function emit(contract, event, args, payloadFunc) { + try { + await lastEmit; + } catch (error) { + } + const resultPromise = _emit(contract, event, args, payloadFunc); + lastEmit = resultPromise; + return await resultPromise; +} +const passProperties = ["then"]; +_k = internal; +const _BaseContract = class _BaseContract { + /** + * Creates a new contract connected to %%target%% with the %%abi%% and + * optionally connected to a %%runner%% to perform operations on behalf + * of. + */ + constructor(target, abi2, runner, _deployTx) { + /** + * The target to connect to. + * + * This can be an address, ENS name or any [[Addressable]], such as + * another contract. To get the resovled address, use the ``getAddress`` + * method. + */ + __publicField(this, "target"); + /** + * The contract Interface. + */ + __publicField(this, "interface"); + /** + * The connected runner. This is generally a [[Provider]] or a + * [[Signer]], which dictates what operations are supported. + * + * For example, a **Contract** connected to a [[Provider]] may + * only execute read-only operations. + */ + __publicField(this, "runner"); + /** + * All the Events available on this contract. + */ + __publicField(this, "filters"); + /** + * @_ignore: + */ + __publicField(this, _k); + /** + * The fallback or receive function if any. + */ + __publicField(this, "fallback"); + assertArgument(typeof target === "string" || isAddressable(target), "invalid value for Contract target", "target", target); + if (runner == null) { + runner = null; + } + const iface = Interface.from(abi2); + defineProperties$1(this, { target, runner, interface: iface }); + Object.defineProperty(this, internal, { value: {} }); + let addrPromise; + let addr = null; + let deployTx = null; + if (_deployTx) { + const provider2 = getProvider(runner); + deployTx = new ContractTransactionResponse(this.interface, provider2, _deployTx); + } + let subs = /* @__PURE__ */ new Map(); + if (typeof target === "string") { + if (isHexString(target)) { + addr = target; + addrPromise = Promise.resolve(target); + } else { + const resolver = getRunner(runner, "resolveName"); + if (!canResolve(resolver)) { + throw makeError("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { + operation: "resolveName" + }); + } + addrPromise = resolver.resolveName(target).then((addr2) => { + if (addr2 == null) { + throw makeError("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", { + value: target + }); + } + getInternal(this).addr = addr2; + return addr2; }); + } + } else { + addrPromise = target.getAddress().then((addr2) => { + if (addr2 == null) { + throw new Error("TODO"); + } + getInternal(this).addr = addr2; + return addr2; }); - }; - this.hostname = hostname; - this.fetch = (input2, init2) => fetch2(input2, init2); + } + setInternal(this, { addrPromise, addr, deployTx, subs }); + const filters = new Proxy({}, { + get: (target2, prop, receiver) => { + if (typeof prop === "symbol" || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target2, prop, receiver); + } + try { + return this.getEvent(prop); + } catch (error) { + if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } + return void 0; + }, + has: (target2, prop) => { + if (passProperties.indexOf(prop) >= 0) { + return Reflect.has(target2, prop); + } + return Reflect.has(target2, prop) || this.interface.hasEvent(String(prop)); + } + }); + defineProperties$1(this, { filters }); + defineProperties$1(this, { + fallback: iface.receive || iface.fallback ? buildWrappedFallback(this) : null + }); + return new Proxy(this, { + get: (target2, prop, receiver) => { + if (typeof prop === "symbol" || prop in target2 || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target2, prop, receiver); + } + try { + return target2.getFunction(prop); + } catch (error) { + if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } + return void 0; + }, + has: (target2, prop) => { + if (typeof prop === "symbol" || prop in target2 || passProperties.indexOf(prop) >= 0) { + return Reflect.has(target2, prop); + } + return target2.interface.hasFunction(prop); + } + }); + } + /** + * Return a new Contract instance with the same target and ABI, but + * a different %%runner%%. + */ + connect(runner) { + return new _BaseContract(this.target, this.interface, runner); + } + /** + * Return a new Contract instance with the same ABI and runner, but + * a different %%target%%. + */ + attach(target) { + return new _BaseContract(target, this.interface, this.runner); + } + /** + * Return the resolved address of this Contract. + */ + async getAddress() { + return await getInternal(this).addrPromise; + } + /** + * Return the deployed bytecode or null if no bytecode is found. + */ + async getDeployedCode() { + const provider2 = getProvider(this.runner); + assert(provider2, "runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "getDeployedCode" }); + const code2 = await provider2.getCode(await this.getAddress()); + if (code2 === "0x") { + return null; + } + return code2; + } + /** + * Resolve to this Contract once the bytecode has been deployed, or + * resolve immediately if already deployed. + */ + async waitForDeployment() { + const deployTx = this.deploymentTransaction(); + if (deployTx) { + await deployTx.wait(); + return this; + } + const code2 = await this.getDeployedCode(); + if (code2 != null) { + return this; + } + const provider2 = getProvider(this.runner); + assert(provider2 != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "waitForDeployment" }); + return new Promise((resolve, reject) => { + const checkCode = async () => { + try { + const code3 = await this.getDeployedCode(); + if (code3 != null) { + return resolve(this); + } + provider2.once("block", checkCode); + } catch (error) { + reject(error); + } + }; + checkCode(); + }); + } + /** + * Return the transaction used to deploy this contract. + * + * This is only available if this instance was returned from a + * [[ContractFactory]]. + */ + deploymentTransaction() { + return getInternal(this).deployTx; + } + /** + * Return the function for a given name. This is useful when a contract + * method name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getFunction(key) { + if (typeof key !== "string") { + key = key.format(); + } + const func = buildWrappedMethod(this, key); + return func; + } + /** + * Return the event for a given name. This is useful when a contract + * event name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getEvent(key) { + if (typeof key !== "string") { + key = key.format(); + } + return buildWrappedEvent(this, key); + } + /** + * @_ignore: + */ + async queryTransaction(hash2) { + throw new Error("@TODO"); + } + /* + // @TODO: this is a non-backwards compatible change, but will be added + // in v7 and in a potential SmartContract class in an upcoming + // v6 release + async getTransactionReceipt(hash: string): Promise { + const provider = getProvider(this.runner); + assert(provider, "contract runner does not have a provider", + "UNSUPPORTED_OPERATION", { operation: "queryTransaction" }); + + const receipt = await provider.getTransactionReceipt(hash); + if (receipt == null) { return null; } + + return new ContractTransactionReceipt(this.interface, provider, receipt); + } + */ + /** + * Provide historic access to event data for %%event%% in the range + * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``) + * inclusive. + */ + async queryFilter(event, fromBlock, toBlock) { + if (fromBlock == null) { + fromBlock = 0; + } + if (toBlock == null) { + toBlock = "latest"; + } + const { addr, addrPromise } = getInternal(this); + const address = addr ? addr : await addrPromise; + const { fragment, topics } = await getSubInfo(this, event); + const filter2 = { address, topics, fromBlock, toBlock }; + const provider2 = getProvider(this.runner); + assert(provider2, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { operation: "queryFilter" }); + return (await provider2.getLogs(filter2)).map((log) => { + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = this.interface.getEvent(log.topics[0]); + } catch (error) { + } + } + if (foundFragment) { + try { + return new EventLog(log, this.interface, foundFragment); + } catch (error) { + return new UndecodedEventLog(log, error); + } + } + return new Log(log, provider2); + }); } - url(name2) { - return this.hostname + this.path + name2; + /** + * Add an event %%listener%% for the %%event%%. + */ + async on(event, listener) { + const sub = await getSub(this, "on", event); + sub.listeners.push({ listener, once: false }); + sub.start(); + return this; + } + /** + * Add an event %%listener%% for the %%event%%, but remove the listener + * after it is fired once. + */ + async once(event, listener) { + const sub = await getSub(this, "once", event); + sub.listeners.push({ listener, once: true }); + sub.start(); + return this; + } + /** + * Emit an %%event%% calling all listeners with %%args%%. + * + * Resolves to ``true`` if any listeners were called. + */ + async emit(event, ...args) { + return await emit(this, event, args, null); + } + /** + * Resolves to the number of listeners of %%event%% or the total number + * of listeners if unspecified. + */ + async listenerCount(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return 0; + } + return sub.listeners.length; + } + const { subs } = getInternal(this); + let total = 0; + for (const { listeners } of subs.values()) { + total += listeners.length; + } + return total; + } + /** + * Resolves to the listeners subscribed to %%event%% or all listeners + * if unspecified. + */ + async listeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener }) => listener); + } + const { subs } = getInternal(this); + let result = []; + for (const { listeners } of subs.values()) { + result = result.concat(listeners.map(({ listener }) => listener)); + } + return result; + } + /** + * Remove the %%listener%% from the listeners for %%event%% or remove + * all listeners if unspecified. + */ + async off(event, listener) { + const sub = await hasSub(this, event); + if (!sub) { + return this; + } + if (listener) { + const index2 = sub.listeners.map(({ listener: listener2 }) => listener2).indexOf(listener); + if (index2 >= 0) { + sub.listeners.splice(index2, 1); + } + } + if (listener == null || sub.listeners.length === 0) { + sub.stop(); + getInternal(this).subs.delete(sub.tag); + } + return this; + } + /** + * Remove all the listeners for %%event%% or remove all listeners if + * unspecified. + */ + async removeAllListeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return this; + } + sub.stop(); + getInternal(this).subs.delete(sub.tag); + } else { + const { subs } = getInternal(this); + for (const { tag, stop } of subs.values()) { + stop(); + subs.delete(tag); + } + } + return this; + } + /** + * Alias for [on]. + */ + async addListener(event, listener) { + return await this.on(event, listener); + } + /** + * Alias for [off]. + */ + async removeListener(event, listener) { + return await this.off(event, listener); + } + /** + * Create a new Class for the %%abi%%. + */ + static buildClass(abi2) { + class CustomContract extends _BaseContract { + constructor(address, runner = null) { + super(address, abi2, runner); + } + } + return CustomContract; + } + /** + * Create a new BaseContract with a specified Interface. + */ + static from(target, abi2, runner) { + if (runner == null) { + runner = null; + } + const contract = new this(target, abi2, runner); + return contract; } +}; +let BaseContract = _BaseContract; +function _ContractBase() { + return BaseContract; } -class Collections { - constructor(hostname, fetch2) { - this.hostname = void 0; - this.fetch = void 0; - this.path = "/rpc/Collections/"; - this.createCollection = (args, headers, signal) => { - return this.fetch(this.url("CreateCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - collection: _data6.collection - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getCollection = (args, headers, signal) => { - return this.fetch(this.url("GetCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - collection: _data6.collection - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.listCollections = (args, headers, signal) => { - return this.fetch(this.url("ListCollections"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - page: _data6.page, - collections: _data6.collections - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateCollection = (args, headers, signal) => { - return this.fetch(this.url("UpdateCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - collection: _data6.collection - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.deleteCollection = (args, headers, signal) => { - return this.fetch(this.url("DeleteCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.publishCollection = (args, headers, signal) => { - return this.fetch(this.url("PublishCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - collection: _data6.collection - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.unpublishCollection = (args, headers, signal) => { - return this.fetch(this.url("UnpublishCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - collection: _data6.collection - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.createContractCollection = (args, headers, signal) => { - return this.fetch(this.url("CreateContractCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - contractCollection: _data6.contractCollection - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getContractCollection = (args, headers, signal) => { - return this.fetch(this.url("GetContractCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - contractCollection: _data6.contractCollection - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.listContractCollections = (args, headers, signal) => { - return this.fetch(this.url("ListContractCollections"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - contractCollections: _data6.contractCollections, - collections: _data6.collections, - page: _data6.page - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateContractCollection = (args, headers, signal) => { - return this.fetch(this.url("UpdateContractCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.deleteContractCollection = (args, headers, signal) => { - return this.fetch(this.url("DeleteContractCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.createToken = (args, headers, signal) => { - return this.fetch(this.url("CreateToken"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - token: _data6.token, - assets: _data6.assets - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getToken = (args, headers, signal) => { - return this.fetch(this.url("GetToken"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - token: _data6.token, - assets: _data6.assets - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.listTokens = (args, headers, signal) => { - return this.fetch(this.url("ListTokens"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - page: _data6.page, - tokens: _data6.tokens - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateToken = (args, headers, signal) => { - return this.fetch(this.url("UpdateToken"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - token: _data6.token - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.deleteToken = (args, headers, signal) => { - return this.fetch(this.url("DeleteToken"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.createAsset = (args, headers, signal) => { - return this.fetch(this.url("CreateAsset"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - asset: _data6.asset - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getAsset = (args, headers, signal) => { - return this.fetch(this.url("GetAsset"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - asset: _data6.asset - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.updateAsset = (args, headers, signal) => { - return this.fetch(this.url("UpdateAsset"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - asset: _data6.asset - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.deleteAsset = (args, headers, signal) => { - return this.fetch(this.url("DeleteAsset"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.hostname = hostname; - this.fetch = (input2, init2) => fetch2(input2, init2); +class Contract extends _ContractBase() { +} +class ContractFactory { + /** + * Create a new **ContractFactory** with %%abi%% and %%bytecode%%, + * optionally connected to %%runner%%. + * + * The %%bytecode%% may be the ``bytecode`` property within the + * standard Solidity JSON output. + */ + constructor(abi2, bytecode, runner) { + /** + * The Contract Interface. + */ + __publicField(this, "interface"); + /** + * The Contract deployment bytecode. Often called the initcode. + */ + __publicField(this, "bytecode"); + /** + * The ContractRunner to deploy the Contract as. + */ + __publicField(this, "runner"); + const iface = Interface.from(abi2); + if (bytecode instanceof Uint8Array) { + bytecode = hexlify(getBytes(bytecode)); + } else { + if (typeof bytecode === "object") { + bytecode = bytecode.object; + } + if (!bytecode.startsWith("0x")) { + bytecode = "0x" + bytecode; + } + bytecode = hexlify(getBytes(bytecode)); + } + defineProperties$1(this, { + bytecode, + interface: iface, + runner: runner || null + }); + } + attach(target) { + return new BaseContract(target, this.interface, this.runner); + } + /** + * Resolves to the transaction to deploy the contract, passing %%args%% + * into the constructor. + */ + async getDeployTransaction(...args) { + let overrides = {}; + const fragment = this.interface.deploy; + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); + } + if (fragment.inputs.length !== args.length) { + throw new Error("incorrect number of arguments to constructor"); + } + const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); + const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); + return Object.assign({}, overrides, { data }); + } + /** + * Resolves to the Contract deployed by passing %%args%% into the + * constructor. + * + * This will resolve to the Contract before it has been deployed to the + * network, so the [[BaseContract-waitForDeployment]] should be used before + * sending any transactions to it. + */ + async deploy(...args) { + const tx = await this.getDeployTransaction(...args); + assert(this.runner && typeof this.runner.sendTransaction === "function", "factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + const sentTx = await this.runner.sendTransaction(tx); + const address = getCreateAddress(sentTx); + return new BaseContract(address, this.interface, this.runner, sentTx); } - url(name2) { - return this.hostname + this.path + name2; + /** + * Return a new **ContractFactory** with the same ABI and bytecode, + * but connected to %%runner%%. + */ + connect(runner) { + return new ContractFactory(this.interface, this.bytecode, runner); + } + /** + * Create a new **ContractFactory** from the standard Solidity JSON output. + */ + static fromSolidity(output2, runner) { + assertArgument(output2 != null, "bad compiler output", "output", output2); + if (typeof output2 === "string") { + output2 = JSON.parse(output2); + } + const abi2 = output2.abi; + let bytecode = ""; + if (output2.bytecode) { + bytecode = output2.bytecode; + } else if (output2.evm && output2.evm.bytecode) { + bytecode = output2.evm.bytecode; + } + return new this(abi2, bytecode, runner); } } -class Admin { - constructor(hostname, fetch2) { - this.hostname = void 0; - this.fetch = void 0; - this.path = "/rpc/Admin/"; - this.addContractsToTokenDirectory = (args, headers, signal) => { - return this.fetch(this.url("AddContractsToTokenDirectory"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.removeContractsFromTokenDirectory = (args, headers, signal) => { - return this.fetch(this.url("RemoveContractsFromTokenDirectory"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.modifyFeatureIndex = (args, headers, signal) => { - return this.fetch(this.url("ModifyFeatureIndex"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getFeatureIndex = (args, headers, signal) => { - return this.fetch(this.url("GetFeatureIndex"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - featured: _data6.featured - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.listTokenDirectory = (args, headers, signal) => { - return this.fetch(this.url("ListTokenDirectory"), createHTTPRequest$4(args, headers, signal)).then((res) => { - return buildResponse$4(res).then((_data6) => { - return { - page: _data6.page, - collections: _data6.collections - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$4.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.hostname = hostname; - this.fetch = (input2, init2) => fetch2(input2, init2); +function getIpfsLink(link) { + if (link.match(/^ipfs:\/\/ipfs\//i)) { + link = link.substring(12); + } else if (link.match(/^ipfs:\/\//i)) { + link = link.substring(7); + } else { + assertArgument(false, "unsupported IPFS format", "link", link); } - url(name2) { - return this.hostname + this.path + name2; + return `https://gateway.ipfs.io/ipfs/${link}`; +} +class MulticoinProviderPlugin { + /** + * Creates a new **MulticoinProviderPluing** for %%name%%. + */ + constructor(name2) { + /** + * The name. + */ + __publicField(this, "name"); + defineProperties$1(this, { name: name2 }); + } + connect(proivder) { + return this; + } + /** + * Returns ``true`` if %%coinType%% is supported by this plugin. + */ + supportsCoinType(coinType) { + return false; + } + /** + * Resolves to the encoded %%address%% for %%coinType%%. + */ + async encodeAddress(coinType, address) { + throw new Error("unsupported coin"); + } + /** + * Resolves to the decoded %%data%% for %%coinType%%. + */ + async decodeAddress(coinType, data) { + throw new Error("unsupported coin"); } } -const createHTTPRequest$4 = (body = {}, headers = {}, signal = null) => { - return { - method: "POST", - headers: _extends$6({}, headers, { - "Content-Type": "application/json" - }), - body: JSON.stringify(body || {}), - signal - }; -}; -const buildResponse$4 = (res) => { - return res.text().then((text2) => { - let data; - try { - data = JSON.parse(text2); - } catch (error) { - let message = ""; - if (error instanceof Error) { - message = error.message; +const matcherIpfs = new RegExp("^(ipfs)://(.*)$", "i"); +const matchers = [ + new RegExp("^(https)://(.*)$", "i"), + new RegExp("^(data):(.*)$", "i"), + matcherIpfs, + new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i") +]; +const _EnsResolver = class _EnsResolver { + constructor(provider2, address, name2) { + __privateAdd(this, _EnsResolver_instances); + /** + * The connected provider. + */ + __publicField(this, "provider"); + /** + * The address of the resolver. + */ + __publicField(this, "address"); + /** + * The name this resolver was resolved against. + */ + __publicField(this, "name"); + // For EIP-2544 names, the ancestor that provided the resolver + __privateAdd(this, _supports2544); + __privateAdd(this, _resolver); + defineProperties$1(this, { provider: provider2, address, name: name2 }); + __privateSet(this, _supports2544, null); + __privateSet(this, _resolver, new Contract(address, [ + "function supportsInterface(bytes4) view returns (bool)", + "function resolve(bytes, bytes) view returns (bytes)", + "function addr(bytes32) view returns (address)", + "function addr(bytes32, uint) view returns (bytes)", + "function text(bytes32, string) view returns (string)", + "function contenthash(bytes32) view returns (bytes)" + ], provider2)); + } + /** + * Resolves to true if the resolver supports wildcard resolution. + */ + async supportsWildcard() { + if (__privateGet(this, _supports2544) == null) { + __privateSet(this, _supports2544, (async () => { + try { + return await __privateGet(this, _resolver).supportsInterface("0x9061b923"); + } catch (error) { + if (isError(error, "CALL_EXCEPTION")) { + return false; + } + __privateSet(this, _supports2544, null); + throw error; + } + })()); + } + return await __privateGet(this, _supports2544); + } + /** + * Resolves to the address for %%coinType%% or null if the + * provided %%coinType%% has not been configured. + */ + async getAddress(coinType) { + if (coinType == null) { + coinType = 60; + } + if (coinType === 60) { + try { + const result = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "addr(bytes32)"); + if (result == null || result === ZeroAddress) { + return null; + } + return result; + } catch (error) { + if (isError(error, "CALL_EXCEPTION")) { + return null; + } + throw error; } - throw WebrpcBadResponseError$4.new({ - status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text2}` - }); } - if (!res.ok) { - const code2 = typeof data.code === "number" ? data.code : 0; - throw (webrpcErrorByCode$4[code2] || WebrpcError$4).new(data); + if (coinType >= 0 && coinType < 2147483648) { + let ethCoinType = coinType + 2147483648; + const data2 = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "addr(bytes32,uint)", [ethCoinType]); + if (isHexString(data2, 20)) { + return getAddress(data2); + } + } + let coinPlugin = null; + for (const plugin of this.provider.plugins) { + if (!(plugin instanceof MulticoinProviderPlugin)) { + continue; + } + if (plugin.supportsCoinType(coinType)) { + coinPlugin = plugin; + break; + } + } + if (coinPlugin == null) { + return null; + } + const data = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "addr(bytes32,uint)", [coinType]); + if (data == null || data === "0x") { + return null; + } + const address = await coinPlugin.decodeAddress(coinType, data); + if (address != null) { + return address; + } + assert(false, `invalid coin data`, "UNSUPPORTED_OPERATION", { + operation: `getAddress(${coinType})`, + info: { coinType, data } + }); + } + /** + * Resolves to the EIP-634 text record for %%key%%, or ``null`` + * if unconfigured. + */ + async getText(key) { + const data = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "text(bytes32,string)", [key]); + if (data == null || data === "0x") { + return null; } return data; - }); -}; -let WebrpcError$4 = class WebrpcError4 extends Error { - constructor(name2, code2, message, status, cause) { - super(message); - this.name = void 0; - this.code = void 0; - this.message = void 0; - this.status = void 0; - this.cause = void 0; - this.msg = void 0; - this.name = name2 || "WebrpcError"; - this.code = typeof code2 === "number" ? code2 : 0; - this.message = message || `endpoint error ${this.code}`; - this.msg = this.message; - this.status = typeof status === "number" ? status : 0; - this.cause = cause; - Object.setPrototypeOf(this, WebrpcError4.prototype); } - static new(payload) { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + /** + * Rsolves to the content-hash or ``null`` if unconfigured. + */ + async getContentHash() { + const data = await __privateMethod(this, _EnsResolver_instances, fetch_fn).call(this, "contenthash(bytes32)"); + if (data == null || data === "0x") { + return null; + } + const ipfs = data.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); + if (ipfs) { + const scheme = ipfs[1] === "e3010170" ? "ipfs" : "ipns"; + const length = parseInt(ipfs[4], 16); + if (ipfs[5].length === length * 2) { + return `${scheme}://${encodeBase58("0x" + ipfs[2])}`; + } + } + const swarm = data.match(/^0xe40101fa011b20([0-9a-f]*)$/); + if (swarm && swarm[1].length === 64) { + return `bzz://${swarm[1]}`; + } + assert(false, `invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", { + operation: "getContentHash()", + info: { data } + }); } -}; -let WebrpcEndpointError$4 = class WebrpcEndpointError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcEndpointError4.prototype); + /** + * Resolves to the avatar url or ``null`` if the avatar is either + * unconfigured or incorrectly configured (e.g. references an NFT + * not owned by the address). + * + * If diagnosing issues with configurations, the [[_getAvatar]] + * method may be useful. + */ + async getAvatar() { + const avatar2 = await this._getAvatar(); + return avatar2.url; + } + /** + * When resolving an avatar, there are many steps involved, such + * fetching metadata and possibly validating ownership of an + * NFT. + * + * This method can be used to examine each step and the value it + * was working from. + */ + async _getAvatar() { + const linkage = [{ type: "name", value: this.name }]; + try { + const avatar2 = await this.getText("avatar"); + if (avatar2 == null) { + linkage.push({ type: "!avatar", value: "" }); + return { url: null, linkage }; + } + linkage.push({ type: "avatar", value: avatar2 }); + for (let i = 0; i < matchers.length; i++) { + const match = avatar2.match(matchers[i]); + if (match == null) { + continue; + } + const scheme = match[1].toLowerCase(); + switch (scheme) { + case "https": + case "data": + linkage.push({ type: "url", value: avatar2 }); + return { linkage, url: avatar2 }; + case "ipfs": { + const url = getIpfsLink(avatar2); + linkage.push({ type: "ipfs", value: avatar2 }); + linkage.push({ type: "url", value: url }); + return { linkage, url }; + } + case "erc721": + case "erc1155": { + const selector2 = scheme === "erc721" ? "tokenURI(uint256)" : "uri(uint256)"; + linkage.push({ type: scheme, value: avatar2 }); + const owner = await this.getAddress(); + if (owner == null) { + linkage.push({ type: "!owner", value: "" }); + return { url: null, linkage }; + } + const comps = (match[2] || "").split("/"); + if (comps.length !== 2) { + linkage.push({ type: `!${scheme}caip`, value: match[2] || "" }); + return { url: null, linkage }; + } + const tokenId = comps[1]; + const contract = new Contract(comps[0], [ + // ERC-721 + "function tokenURI(uint) view returns (string)", + "function ownerOf(uint) view returns (address)", + // ERC-1155 + "function uri(uint) view returns (string)", + "function balanceOf(address, uint256) view returns (uint)" + ], this.provider); + if (scheme === "erc721") { + const tokenOwner = await contract.ownerOf(tokenId); + if (owner !== tokenOwner) { + linkage.push({ type: "!owner", value: tokenOwner }); + return { url: null, linkage }; + } + linkage.push({ type: "owner", value: tokenOwner }); + } else if (scheme === "erc1155") { + const balance = await contract.balanceOf(owner, tokenId); + if (!balance) { + linkage.push({ type: "!balance", value: "0" }); + return { url: null, linkage }; + } + linkage.push({ type: "balance", value: balance.toString() }); + } + let metadataUrl = await contract[selector2](tokenId); + if (metadataUrl == null || metadataUrl === "0x") { + linkage.push({ type: "!metadata-url", value: "" }); + return { url: null, linkage }; + } + linkage.push({ type: "metadata-url-base", value: metadataUrl }); + if (scheme === "erc1155") { + metadataUrl = metadataUrl.replace("{id}", toBeHex(tokenId, 32).substring(2)); + linkage.push({ type: "metadata-url-expanded", value: metadataUrl }); + } + if (metadataUrl.match(/^ipfs:/i)) { + metadataUrl = getIpfsLink(metadataUrl); + } + linkage.push({ type: "metadata-url", value: metadataUrl }); + let metadata2 = {}; + const response = await new FetchRequest(metadataUrl).send(); + response.assertOk(); + try { + metadata2 = response.bodyJson; + } catch (error) { + try { + linkage.push({ type: "!metadata", value: response.bodyText }); + } catch (error2) { + const bytes2 = response.body; + if (bytes2) { + linkage.push({ type: "!metadata", value: hexlify(bytes2) }); + } + return { url: null, linkage }; + } + return { url: null, linkage }; + } + if (!metadata2) { + linkage.push({ type: "!metadata", value: "" }); + return { url: null, linkage }; + } + linkage.push({ type: "metadata", value: JSON.stringify(metadata2) }); + let imageUrl = metadata2.image; + if (typeof imageUrl !== "string") { + linkage.push({ type: "!imageUrl", value: "" }); + return { url: null, linkage }; + } + if (imageUrl.match(/^(https:\/\/|data:)/i)) { + } else { + const ipfs = imageUrl.match(matcherIpfs); + if (ipfs == null) { + linkage.push({ type: "!imageUrl-ipfs", value: imageUrl }); + return { url: null, linkage }; + } + linkage.push({ type: "imageUrl-ipfs", value: imageUrl }); + imageUrl = getIpfsLink(imageUrl); + } + linkage.push({ type: "url", value: imageUrl }); + return { linkage, url: imageUrl }; + } + } + } + } catch (error) { + } + return { linkage, url: null }; + } + static async getEnsAddress(provider2) { + const network2 = await provider2.getNetwork(); + const ensPlugin = network2.getPlugin("org.ethers.plugins.network.Ens"); + assert(ensPlugin, "network does not support ENS", "UNSUPPORTED_OPERATION", { + operation: "getEnsAddress", + info: { network: network2 } + }); + return ensPlugin.address; + } + /** + * Resolve to the ENS resolver for %%name%% using %%provider%% or + * ``null`` if unconfigured. + */ + static async fromName(provider2, name2) { + var _a2; + let currentName = name2; + while (true) { + if (currentName === "" || currentName === ".") { + return null; + } + if (name2 !== "eth" && currentName === "eth") { + return null; + } + const addr = await __privateMethod(_a2 = _EnsResolver, _EnsResolver_static, getResolver_fn).call(_a2, provider2, currentName); + if (addr != null) { + const resolver = new _EnsResolver(provider2, addr, name2); + if (currentName !== name2 && !await resolver.supportsWildcard()) { + return null; + } + return resolver; + } + currentName = currentName.split(".").slice(1).join("."); + } } }; -let WebrpcRequestFailedError$4 = class WebrpcRequestFailedError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcRequestFailedError4.prototype); +_supports2544 = new WeakMap(); +_resolver = new WeakMap(); +_EnsResolver_instances = new WeakSet(); +fetch_fn = async function(funcName, params) { + params = (params || []).slice(); + const iface = __privateGet(this, _resolver).interface; + params.unshift(namehash(this.name)); + let fragment = null; + if (await this.supportsWildcard()) { + fragment = iface.getFunction(funcName); + assert(fragment, "missing fragment", "UNKNOWN_ERROR", { + info: { funcName } + }); + params = [ + dnsEncode(this.name, 255), + iface.encodeFunctionData(fragment, params) + ]; + funcName = "resolve(bytes,bytes)"; } -}; -let WebrpcBadRouteError$4 = class WebrpcBadRouteError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRouteError4.prototype); + params.push({ + enableCcipRead: true + }); + try { + const result = await __privateGet(this, _resolver)[funcName](...params); + if (fragment) { + return iface.decodeFunctionResult(fragment, result)[0]; + } + return result; + } catch (error) { + if (!isError(error, "CALL_EXCEPTION")) { + throw error; + } } + return null; }; -let WebrpcBadMethodError$4 = class WebrpcBadMethodError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadMethodError4.prototype); +_EnsResolver_static = new WeakSet(); +getResolver_fn = async function(provider2, name2) { + const ensAddr = await _EnsResolver.getEnsAddress(provider2); + try { + const contract = new Contract(ensAddr, [ + "function resolver(bytes32) view returns (address)" + ], provider2); + const addr = await contract.resolver(namehash(name2), { + enableCcipRead: true + }); + if (addr === ZeroAddress) { + return null; + } + return addr; + } catch (error) { + throw error; } + return null; }; -let WebrpcBadRequestError$4 = class WebrpcBadRequestError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRequestError4.prototype); +__privateAdd(_EnsResolver, _EnsResolver_static); +let EnsResolver = _EnsResolver; +const BN_0 = BigInt(0); +function allowNull(format2, nullValue) { + return function(value) { + if (value == null) { + return nullValue; + } + return format2(value); + }; +} +function arrayOf(format2, allowNull2) { + return (array) => { + if (allowNull2 && array == null) { + return null; + } + if (!Array.isArray(array)) { + throw new Error("not an array"); + } + return array.map((i) => format2(i)); + }; +} +function object(format2, altNames) { + return (value) => { + const result = {}; + for (const key in format2) { + let srcKey = key; + if (altNames && key in altNames && !(srcKey in value)) { + for (const altKey of altNames[key]) { + if (altKey in value) { + srcKey = altKey; + break; + } + } + } + try { + const nv = format2[key](value[srcKey]); + if (nv !== void 0) { + result[key] = nv; + } + } catch (error) { + const message = error instanceof Error ? error.message : "not-an-error"; + assert(false, `invalid value for value.${key} (${message})`, "BAD_DATA", { value }); + } + } + return result; + }; +} +function formatBoolean(value) { + switch (value) { + case true: + case "true": + return true; + case false: + case "false": + return false; } -}; -let WebrpcBadResponseError$4 = class WebrpcBadResponseError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadResponseError4.prototype); + assertArgument(false, `invalid boolean; ${JSON.stringify(value)}`, "value", value); +} +function formatData(value) { + assertArgument(isHexString(value, true), "invalid data", "value", value); + return value; +} +function formatHash(value) { + assertArgument(isHexString(value, 32), "invalid hash", "value", value); + return value; +} +const _formatLog = object({ + address: getAddress, + blockHash: formatHash, + blockNumber: getNumber, + data: formatData, + index: getNumber, + removed: allowNull(formatBoolean, false), + topics: arrayOf(formatHash), + transactionHash: formatHash, + transactionIndex: getNumber +}, { + index: ["logIndex"] +}); +function formatLog(value) { + return _formatLog(value); +} +const _formatBlock = object({ + hash: allowNull(formatHash), + parentHash: formatHash, + parentBeaconBlockRoot: allowNull(formatHash, null), + number: getNumber, + timestamp: getNumber, + nonce: allowNull(formatData), + difficulty: getBigInt, + gasLimit: getBigInt, + gasUsed: getBigInt, + stateRoot: allowNull(formatHash, null), + receiptsRoot: allowNull(formatHash, null), + blobGasUsed: allowNull(getBigInt, null), + excessBlobGas: allowNull(getBigInt, null), + miner: allowNull(getAddress), + prevRandao: allowNull(formatHash, null), + extraData: formatData, + baseFeePerGas: allowNull(getBigInt) +}, { + prevRandao: ["mixHash"] +}); +function formatBlock(value) { + const result = _formatBlock(value); + result.transactions = value.transactions.map((tx) => { + if (typeof tx === "string") { + return tx; + } + return formatTransactionResponse(tx); + }); + return result; +} +const _formatReceiptLog = object({ + transactionIndex: getNumber, + blockNumber: getNumber, + transactionHash: formatHash, + address: getAddress, + topics: arrayOf(formatHash), + data: formatData, + index: getNumber, + blockHash: formatHash +}, { + index: ["logIndex"] +}); +function formatReceiptLog(value) { + return _formatReceiptLog(value); +} +const _formatTransactionReceipt = object({ + to: allowNull(getAddress, null), + from: allowNull(getAddress, null), + contractAddress: allowNull(getAddress, null), + // should be allowNull(hash), but broken-EIP-658 support is handled in receipt + index: getNumber, + root: allowNull(hexlify), + gasUsed: getBigInt, + blobGasUsed: allowNull(getBigInt, null), + logsBloom: allowNull(formatData), + blockHash: formatHash, + hash: formatHash, + logs: arrayOf(formatReceiptLog), + blockNumber: getNumber, + //confirmations: allowNull(getNumber, null), + cumulativeGasUsed: getBigInt, + effectiveGasPrice: allowNull(getBigInt), + blobGasPrice: allowNull(getBigInt, null), + status: allowNull(getNumber), + type: allowNull(getNumber, 0) +}, { + effectiveGasPrice: ["gasPrice"], + hash: ["transactionHash"], + index: ["transactionIndex"] +}); +function formatTransactionReceipt(value) { + return _formatTransactionReceipt(value); +} +function formatTransactionResponse(value) { + if (value.to && getBigInt(value.to) === BN_0) { + value.to = "0x0000000000000000000000000000000000000000"; } -}; -let WebrpcServerPanicError$4 = class WebrpcServerPanicError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcServerPanicError4.prototype); + const result = object({ + hash: formatHash, + // Some nodes do not return this, usually test nodes (like Ganache) + index: allowNull(getNumber, void 0), + type: (value2) => { + if (value2 === "0x" || value2 == null) { + return 0; + } + return getNumber(value2); + }, + accessList: allowNull(accessListify, null), + blobVersionedHashes: allowNull(arrayOf(formatHash, true), null), + blockHash: allowNull(formatHash, null), + blockNumber: allowNull(getNumber, null), + transactionIndex: allowNull(getNumber, null), + from: getAddress, + // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas) must be set + gasPrice: allowNull(getBigInt), + maxPriorityFeePerGas: allowNull(getBigInt), + maxFeePerGas: allowNull(getBigInt), + maxFeePerBlobGas: allowNull(getBigInt, null), + gasLimit: getBigInt, + to: allowNull(getAddress, null), + value: getBigInt, + nonce: getNumber, + data: formatData, + creates: allowNull(getAddress, null), + chainId: allowNull(getBigInt, null) + }, { + data: ["input"], + gasLimit: ["gas"], + index: ["transactionIndex"] + })(value); + if (result.to == null && result.creates == null) { + result.creates = getCreateAddress(result); } -}; -let WebrpcInternalErrorError$4 = class WebrpcInternalErrorError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcInternalErrorError4.prototype); + if ((value.type === 1 || value.type === 2) && value.accessList == null) { + result.accessList = []; } -}; -let WebrpcClientDisconnectedError$4 = class WebrpcClientDisconnectedError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcClientDisconnectedError4.prototype); + if (value.signature) { + result.signature = Signature.from(value.signature); + } else { + result.signature = Signature.from(value); } -}; -let WebrpcStreamLostError$4 = class WebrpcStreamLostError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamLostError4.prototype); + if (result.chainId == null) { + const chainId = result.signature.legacyChainId; + if (chainId != null) { + result.chainId = chainId; + } } -}; -let WebrpcStreamFinishedError$4 = class WebrpcStreamFinishedError4 extends WebrpcError$4 { - constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamFinishedError4.prototype); + if (result.blockHash && getBigInt(result.blockHash) === BN_0) { + result.blockHash = null; } -}; -let UnauthorizedError$3 = class UnauthorizedError4 extends WebrpcError$4 { - constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, UnauthorizedError4.prototype); + return result; +} +const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"; +class NetworkPlugin { + /** + * Creates a new **NetworkPlugin**. + */ + constructor(name2) { + /** + * The name of the plugin. + * + * It is recommended to use reverse-domain-notation, which permits + * unique names with a known authority as well as hierarchal entries. + */ + __publicField(this, "name"); + defineProperties$1(this, { name: name2 }); } -}; -let PermissionDeniedError$1 = class PermissionDeniedError4 extends WebrpcError$4 { - constructor(name2 = "PermissionDenied", code2 = 1001, message = "Permission denied", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, PermissionDeniedError4.prototype); + /** + * Creates a copy of this plugin. + */ + clone() { + return new NetworkPlugin(this.name); } -}; -let SessionExpiredError$2 = class SessionExpiredError3 extends WebrpcError$4 { - constructor(name2 = "SessionExpired", code2 = 1002, message = "Session expired", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, SessionExpiredError3.prototype); +} +class GasCostPlugin extends NetworkPlugin { + /** + * Creates a new GasCostPlugin from %%effectiveBlock%% until the + * latest block or another GasCostPlugin supercedes that block number, + * with the associated %%costs%%. + */ + constructor(effectiveBlock, costs) { + if (effectiveBlock == null) { + effectiveBlock = 0; + } + super(`org.ethers.network.plugins.GasCost#${effectiveBlock || 0}`); + /** + * The block number to treat these values as valid from. + * + * This allows a hardfork to have updated values included as well as + * mulutiple hardforks to be supported. + */ + __publicField(this, "effectiveBlock"); + /** + * The transactions base fee. + */ + __publicField(this, "txBase"); + /** + * The fee for creating a new account. + */ + __publicField(this, "txCreate"); + /** + * The fee per zero-byte in the data. + */ + __publicField(this, "txDataZero"); + /** + * The fee per non-zero-byte in the data. + */ + __publicField(this, "txDataNonzero"); + /** + * The fee per storage key in the [[link-eip-2930]] access list. + */ + __publicField(this, "txAccessListStorageKey"); + /** + * The fee per address in the [[link-eip-2930]] access list. + */ + __publicField(this, "txAccessListAddress"); + const props = { effectiveBlock }; + function set(name2, nullish) { + let value = (costs || {})[name2]; + if (value == null) { + value = nullish; + } + assertArgument(typeof value === "number", `invalud value for ${name2}`, "costs", costs); + props[name2] = value; + } + set("txBase", 21e3); + set("txCreate", 32e3); + set("txDataZero", 4); + set("txDataNonzero", 16); + set("txAccessListStorageKey", 1900); + set("txAccessListAddress", 2400); + defineProperties$1(this, props); } -}; -class MethodNotFoundError3 extends WebrpcError$4 { - constructor(name2 = "MethodNotFound", code2 = 1003, message = "Method not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, MethodNotFoundError3.prototype); + clone() { + return new GasCostPlugin(this.effectiveBlock, this); } } -class RequestConflictError2 extends WebrpcError$4 { - constructor(name2 = "RequestConflict", code2 = 1004, message = "Conflict with target resource", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, RequestConflictError2.prototype); +class EnsPlugin extends NetworkPlugin { + /** + * Creates a new **EnsPlugin** connected to %%address%% on the + * %%targetNetwork%%. The default ENS address and mainnet is used + * if unspecified. + */ + constructor(address, targetNetwork) { + super("org.ethers.plugins.network.Ens"); + /** + * The ENS Registrty Contract address. + */ + __publicField(this, "address"); + /** + * The chain ID that the ENS contract lives on. + */ + __publicField(this, "targetNetwork"); + defineProperties$1(this, { + address: address || EnsAddress, + targetNetwork: targetNetwork == null ? 1 : targetNetwork + }); } -} -class FailError extends WebrpcError$4 { - constructor(name2 = "Fail", code2 = 1005, message = "Request Failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, FailError.prototype); + clone() { + return new EnsPlugin(this.address, this.targetNetwork); } } -class GeoblockedError2 extends WebrpcError$4 { - constructor(name2 = "Geoblocked", code2 = 1006, message = "Geoblocked region", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, GeoblockedError2.prototype); +const _FeeDataNetworkPlugin = class _FeeDataNetworkPlugin extends NetworkPlugin { + /** + * Creates a new **FeeDataNetworkPlugin**. + */ + constructor(feeDataFunc) { + super("org.ethers.plugins.network.FeeData"); + __privateAdd(this, _feeDataFunc); + __privateSet(this, _feeDataFunc, feeDataFunc); } -} -let TimeoutError$1 = class TimeoutError2 extends WebrpcError$4 { - constructor(name2 = "Timeout", code2 = 2e3, message = "Request timed out", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, TimeoutError2.prototype); + /** + * The fee data function provided to the constructor. + */ + get feeDataFunc() { + return __privateGet(this, _feeDataFunc); } -}; -let InvalidArgumentError$2 = class InvalidArgumentError4 extends WebrpcError$4 { - constructor(name2 = "InvalidArgument", code2 = 2001, message = "Invalid argument", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, InvalidArgumentError4.prototype); + /** + * Resolves to the fee data. + */ + async getFeeData(provider2) { + return await __privateGet(this, _feeDataFunc).call(this, provider2); + } + clone() { + return new _FeeDataNetworkPlugin(__privateGet(this, _feeDataFunc)); } }; -class RequiredArgumentError extends WebrpcError$4 { - constructor(name2 = "RequiredArgument", code2 = 2002, message = "Required argument missing", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, RequiredArgumentError.prototype); +_feeDataFunc = new WeakMap(); +let FeeDataNetworkPlugin = _FeeDataNetworkPlugin; +class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin { + /** + * Creates a new **FetchUrlFeeDataNetworkPlugin** which will + * be used when computing the fee data for the network. + */ + constructor(url, processFunc) { + super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + __privateAdd(this, _url2); + __privateAdd(this, _processFunc); + __privateSet(this, _url2, url); + __privateSet(this, _processFunc, processFunc); } -} -let QueryFailedError$2 = class QueryFailedError4 extends WebrpcError$4 { - constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, QueryFailedError4.prototype); + /** + * The URL to initialize the FetchRequest with in %%processFunc%%. + */ + get url() { + return __privateGet(this, _url2); } -}; -let ValidationFailedError$1 = class ValidationFailedError extends WebrpcError$4 { - constructor(name2 = "ValidationFailed", code2 = 2004, message = "Validation failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, ValidationFailedError.prototype); + /** + * The callback to use when computing the FeeData. + */ + get processFunc() { + return __privateGet(this, _processFunc); } -}; -class RateLimitedError extends WebrpcError$4 { - constructor(name2 = "RateLimited", code2 = 2005, message = "Rate limited", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, RateLimitedError.prototype); + // We are immutable, so we can serve as our own clone + clone() { + return this; } } -let NotFoundError$3 = class NotFoundError4 extends WebrpcError$4 { - constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, NotFoundError4.prototype); +_url2 = new WeakMap(); +_processFunc = new WeakMap(); +const Networks = /* @__PURE__ */ new Map(); +const _Network = class _Network { + /** + * Creates a new **Network** for %%name%% and %%chainId%%. + */ + constructor(name2, chainId) { + __privateAdd(this, _name); + __privateAdd(this, _chainId3); + __privateAdd(this, _plugins); + __privateSet(this, _name, name2); + __privateSet(this, _chainId3, getBigInt(chainId)); + __privateSet(this, _plugins, /* @__PURE__ */ new Map()); } -}; -class ProjectNotFoundError2 extends WebrpcError$4 { - constructor(name2 = "ProjectNotFound", code2 = 3002, message = "Project not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, ProjectNotFoundError2.prototype); + /** + * Returns a JSON-compatible representation of a Network. + */ + toJSON() { + return { name: this.name, chainId: String(this.chainId) }; } -} -let ChainNotFoundError$1 = class ChainNotFoundError extends WebrpcError$4 { - constructor(name2 = "ChainNotFound", code2 = 3003, message = "Chain not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, ChainNotFoundError.prototype); + /** + * The network common name. + * + * This is the canonical name, as networks migh have multiple + * names. + */ + get name() { + return __privateGet(this, _name); } -}; -class TokenDirectoryDisabledError extends WebrpcError$4 { - constructor(name2 = "TokenDirectoryDisabled", code2 = 4001, message = "Token Directory is disabled", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, TokenDirectoryDisabledError.prototype); + set name(value) { + __privateSet(this, _name, value); } -} -let errors = /* @__PURE__ */ function(errors2) { - errors2["WebrpcEndpoint"] = "WebrpcEndpoint"; - errors2["WebrpcRequestFailed"] = "WebrpcRequestFailed"; - errors2["WebrpcBadRoute"] = "WebrpcBadRoute"; - errors2["WebrpcBadMethod"] = "WebrpcBadMethod"; - errors2["WebrpcBadRequest"] = "WebrpcBadRequest"; - errors2["WebrpcBadResponse"] = "WebrpcBadResponse"; - errors2["WebrpcServerPanic"] = "WebrpcServerPanic"; - errors2["WebrpcInternalError"] = "WebrpcInternalError"; - errors2["WebrpcClientDisconnected"] = "WebrpcClientDisconnected"; - errors2["WebrpcStreamLost"] = "WebrpcStreamLost"; - errors2["WebrpcStreamFinished"] = "WebrpcStreamFinished"; - errors2["Unauthorized"] = "Unauthorized"; - errors2["PermissionDenied"] = "PermissionDenied"; - errors2["SessionExpired"] = "SessionExpired"; - errors2["MethodNotFound"] = "MethodNotFound"; - errors2["RequestConflict"] = "RequestConflict"; - errors2["Fail"] = "Fail"; - errors2["Geoblocked"] = "Geoblocked"; - errors2["Timeout"] = "Timeout"; - errors2["InvalidArgument"] = "InvalidArgument"; - errors2["RequiredArgument"] = "RequiredArgument"; - errors2["QueryFailed"] = "QueryFailed"; - errors2["ValidationFailed"] = "ValidationFailed"; - errors2["RateLimited"] = "RateLimited"; - errors2["NotFound"] = "NotFound"; - errors2["ProjectNotFound"] = "ProjectNotFound"; - errors2["ChainNotFound"] = "ChainNotFound"; - errors2["TokenDirectoryDisabled"] = "TokenDirectoryDisabled"; - return errors2; -}({}); -const webrpcErrorByCode$4 = { - [0]: WebrpcEndpointError$4, - [-1]: WebrpcRequestFailedError$4, - [-2]: WebrpcBadRouteError$4, - [-3]: WebrpcBadMethodError$4, - [-4]: WebrpcBadRequestError$4, - [-5]: WebrpcBadResponseError$4, - [-6]: WebrpcServerPanicError$4, - [-7]: WebrpcInternalErrorError$4, - [-8]: WebrpcClientDisconnectedError$4, - [-9]: WebrpcStreamLostError$4, - [-10]: WebrpcStreamFinishedError$4, - [1e3]: UnauthorizedError$3, - [1001]: PermissionDeniedError$1, - [1002]: SessionExpiredError$2, - [1003]: MethodNotFoundError3, - [1004]: RequestConflictError2, - [1005]: FailError, - [1006]: GeoblockedError2, - [2e3]: TimeoutError$1, - [2001]: InvalidArgumentError$2, - [2002]: RequiredArgumentError, - [2003]: QueryFailedError$2, - [2004]: ValidationFailedError$1, - [2005]: RateLimitedError, - [3e3]: NotFoundError$3, - [3002]: ProjectNotFoundError2, - [3003]: ChainNotFoundError$1, - [4001]: TokenDirectoryDisabledError -}; -const fetch$3 = globalThis.fetch; -class SequenceMetadata extends Metadata { - constructor(hostname = "https://metadata.sequence.app", projectAccessKey2, jwtAuth) { - super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, fetch$3); - this.projectAccessKey = projectAccessKey2; - this.jwtAuth = jwtAuth; - this._fetch = (input2, init2) => { - const headers = {}; - const jwtAuth2 = this.jwtAuth; - const projectAccessKey3 = this.projectAccessKey; - if (jwtAuth2 && jwtAuth2.length > 0) { - headers["Authorization"] = `BEARER ${jwtAuth2}`; + /** + * The network chain ID. + */ + get chainId() { + return __privateGet(this, _chainId3); + } + set chainId(value) { + __privateSet(this, _chainId3, getBigInt(value, "chainId")); + } + /** + * Returns true if %%other%% matches this network. Any chain ID + * must match, and if no chain ID is present, the name must match. + * + * This method does not currently check for additional properties, + * such as ENS address or plug-in compatibility. + */ + matches(other) { + if (other == null) { + return false; + } + if (typeof other === "string") { + try { + return this.chainId === getBigInt(other); + } catch (error) { } - if (projectAccessKey3 && projectAccessKey3.length > 0) { - headers["X-Access-Key"] = projectAccessKey3; + return this.name === other; + } + if (typeof other === "number" || typeof other === "bigint") { + try { + return this.chainId === getBigInt(other); + } catch (error) { } - init2.headers = _extends$6({}, init2.headers, headers); - return fetch$3(input2, init2); - }; - this.fetch = this._fetch; - } -} -class SequenceCollections extends Collections { - constructor(hostname = "https://metadata.sequence.app", jwtAuth) { - super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, fetch$3); - this.jwtAuth = jwtAuth; - this._fetch = (input2, init2) => { - const headers = {}; - const jwtAuth2 = this.jwtAuth; - if (jwtAuth2 && jwtAuth2.length > 0) { - headers["Authorization"] = `BEARER ${jwtAuth2}`; + return false; + } + if (typeof other === "object") { + if (other.chainId != null) { + try { + return this.chainId === getBigInt(other.chainId); + } catch (error) { + } + return false; } - init2.headers = _extends$6({}, init2.headers, headers); - return fetch$3(input2, init2); - }; - this.fetch = this._fetch; + if (other.name != null) { + return this.name === other.name; + } + return false; + } + return false; } - // TODO: add uploadAsset() method similar to, - // https://github.com/0xsequence/go-sequence/blob/master/metadata/collections.go#L52 -} -const metadata$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - Admin, - ChainNotFoundError: ChainNotFoundError$1, - Collections, - ContractType, - FailError, - GeoblockedError: GeoblockedError2, - InvalidArgumentError: InvalidArgumentError$2, - Metadata, - MethodNotFoundError: MethodNotFoundError3, - NotFoundError: NotFoundError$3, - PermissionDeniedError: PermissionDeniedError$1, - ProjectNotFoundError: ProjectNotFoundError2, - PropertyType, - QueryFailedError: QueryFailedError$2, - RateLimitedError, - RequestConflictError: RequestConflictError2, - RequiredArgumentError, - SequenceCollections, - SequenceMetadata, - SessionExpiredError: SessionExpiredError$2, - SwapType, - TaskStatus, - TimeoutError: TimeoutError$1, - TokenDirectoryDisabledError, - UnauthorizedError: UnauthorizedError$3, - ValidationFailedError: ValidationFailedError$1, - WebRPCSchemaHash, - WebRPCSchemaVersion, - WebRPCVersion, - WebrpcBadMethodError: WebrpcBadMethodError$4, - WebrpcBadRequestError: WebrpcBadRequestError$4, - WebrpcBadResponseError: WebrpcBadResponseError$4, - WebrpcBadRouteError: WebrpcBadRouteError$4, - WebrpcClientDisconnectedError: WebrpcClientDisconnectedError$4, - WebrpcEndpointError: WebrpcEndpointError$4, - WebrpcError: WebrpcError$4, - WebrpcInternalErrorError: WebrpcInternalErrorError$4, - WebrpcRequestFailedError: WebrpcRequestFailedError$4, - WebrpcServerPanicError: WebrpcServerPanicError$4, - WebrpcStreamFinishedError: WebrpcStreamFinishedError$4, - WebrpcStreamLostError: WebrpcStreamLostError$4, - errors -}, Symbol.toStringTag, { value: "Module" })); -function useGateway(uri, gateway) { - const clean = uri.replace("ipfs://ipfs/", "").replace("ipfs://", ""); - if (uri.startsWith("ipfs://")) return `${gateway}${clean}`; - return uri; -} -function isIPFS(uri) { - return uri.startsWith("ipfs://"); -} -class CachedEIP5719 { - constructor(provider2, solver, window2 = 1e3) { - this.provider = provider2; - this.solver = solver; - this.window = window2; - this.pending = /* @__PURE__ */ new Map(); + /** + * Returns the list of plugins currently attached to this Network. + */ + get plugins() { + return Array.from(__privateGet(this, _plugins).values()); } - async runByEIP5719(address, digest, signature2) { - const key = `${address}-${digest}-${signature2}`; - const now = Date.now(); - if (this.pending.has(key) && now - this.pending.get(key).timestamp < this.window) { - return this.pending.get(key).promise; + /** + * Attach a new %%plugin%% to this Network. The network name + * must be unique, excluding any fragment. + */ + attachPlugin(plugin) { + if (__privateGet(this, _plugins).get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); } - const promise = runByEIP5719(address, this.provider, digest, signature2, this.solver); - this.pending.set(key, { - timestamp: now, - promise - }); - return promise; - } -} -function eip5719Contract(address, provider2) { - const abi2 = [{ - inputs: [{ - internalType: "bytes32", - type: "bytes32" - }], - name: "getAlternativeSignature", - outputs: [{ - internalType: "string", - type: "string" - }], - stateMutability: "view", - type: "function" - }]; - return new Contract(address, abi2, provider2); -} -async function tryAwait(promise) { - try { - return await promise; - } catch (_unused3) { - return void 0; + __privateGet(this, _plugins).set(plugin.name, plugin.clone()); + return this; } -} -async function runByEIP5719(address, provider2, digest, signature2, solver, tries = 0) { - if (tries > 10) throw new Error("EIP5719 - Too many tries"); - if (index$1$2.signer.canRecover(signature2)) { - const recoveredAddr = index$1$2.signer.recoverSigner(digest, signature2); - if (recoveredAddr && recoveredAddr.toLowerCase() === address.toLowerCase()) return signature2; + /** + * Return the plugin, if any, matching %%name%% exactly. Plugins + * with fragments will not be returned unless %%name%% includes + * a fragment. + */ + getPlugin(name2) { + return __privateGet(this, _plugins).get(name2) || null; } - try { - if (await index$1$2.signer.isValidSignature(address, digest, signature2, provider2)) { - return signature2; - } - } catch (_unused4) { + /** + * Gets a list of all plugins that match %%name%%, with otr without + * a fragment. + */ + getPlugins(basename) { + return this.plugins.filter((p2) => p2.name.split("#")[0] === basename); } - const altUri = await tryAwait(eip5719Contract(address, provider2).getAlternativeSignature(digest)); - if (!altUri || altUri === "") throw new Error("EIP5719 - Invalid signature and no alternative signature"); - const altSignature = hexlify(await (solver || new URISolverIPFS()).resolve(altUri)); - if (!altSignature || altSignature === "") throw new Error("EIP5719 - Empty alternative signature"); - if (altSignature === hexlify(signature2)) { - throw new Error("EIP5719 - Alternative signature is invalid or the same"); + /** + * Create a copy of this Network. + */ + clone() { + const clone = new _Network(this.name, this.chainId); + this.plugins.forEach((plugin) => { + clone.attachPlugin(plugin.clone()); + }); + return clone; } - return runByEIP5719(address, provider2, digest, altSignature, solver, tries + 1); -} -class URISolverIPFS { - constructor(gateway = "https://cloudflare-ipfs.com/ipfs/") { - var _this = this; - this.gateway = gateway; - this.uri = (uri) => { - if (isIPFS(uri)) return useGateway(uri, this.gateway); - return uri; - }; - this.resolve = async function(uri) { - const url = _this.uri(uri); - const res = await fetch(url); - if (!res.ok) throw new Error(`URISolverIPFS - Failed to fetch ${url}`); - return await res.text(); - }; + /** + * Compute the intrinsic gas required for a transaction. + * + * A GasCostPlugin can be attached to override the default + * values. + */ + computeIntrinsicGas(tx) { + const costs = this.getPlugin("org.ethers.plugins.network.GasCost") || new GasCostPlugin(); + let gas = costs.txBase; + if (tx.to == null) { + gas += costs.txCreate; + } + if (tx.data) { + for (let i = 2; i < tx.data.length; i += 2) { + if (tx.data.substring(i, i + 2) === "00") { + gas += costs.txDataZero; + } else { + gas += costs.txDataNonzero; + } + } + } + if (tx.accessList) { + const accessList = accessListify(tx.accessList); + for (const addr in accessList) { + gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length; + } + } + return gas; } -} -const instanceOfAny = (object2, constructors) => constructors.some((c2) => object2 instanceof c2); -let idbProxyableTypes; -let cursorAdvanceMethods; -function getIdbProxyableTypes() { - return idbProxyableTypes || (idbProxyableTypes = [ - IDBDatabase, - IDBObjectStore, - IDBIndex, - IDBCursor, - IDBTransaction - ]); -} -function getCursorAdvanceMethods() { - return cursorAdvanceMethods || (cursorAdvanceMethods = [ - IDBCursor.prototype.advance, - IDBCursor.prototype.continue, - IDBCursor.prototype.continuePrimaryKey - ]); -} -const cursorRequestMap = /* @__PURE__ */ new WeakMap(); -const transactionDoneMap = /* @__PURE__ */ new WeakMap(); -const transactionStoreNamesMap = /* @__PURE__ */ new WeakMap(); -const transformCache = /* @__PURE__ */ new WeakMap(); -const reverseTransformCache = /* @__PURE__ */ new WeakMap(); -function promisifyRequest(request) { - const promise = new Promise((resolve, reject) => { - const unlisten = () => { - request.removeEventListener("success", success); - request.removeEventListener("error", error); - }; - const success = () => { - resolve(wrap(request.result)); - unlisten(); - }; - const error = () => { - reject(request.error); - unlisten(); - }; - request.addEventListener("success", success); - request.addEventListener("error", error); - }); - promise.then((value) => { - if (value instanceof IDBCursor) { - cursorRequestMap.set(value, request); + /** + * Returns a new Network for the %%network%% name or chainId. + */ + static from(network2) { + injectCommonNetworks(); + if (network2 == null) { + return _Network.from("mainnet"); } - }).catch(() => { - }); - reverseTransformCache.set(promise, request); - return promise; -} -function cacheDonePromiseForTransaction(tx) { - if (transactionDoneMap.has(tx)) - return; - const done = new Promise((resolve, reject) => { - const unlisten = () => { - tx.removeEventListener("complete", complete); - tx.removeEventListener("error", error); - tx.removeEventListener("abort", error); - }; - const complete = () => { - resolve(); - unlisten(); - }; - const error = () => { - reject(tx.error || new DOMException("AbortError", "AbortError")); - unlisten(); - }; - tx.addEventListener("complete", complete); - tx.addEventListener("error", error); - tx.addEventListener("abort", error); - }); - transactionDoneMap.set(tx, done); -} -let idbProxyTraps = { - get(target, prop, receiver) { - if (target instanceof IDBTransaction) { - if (prop === "done") - return transactionDoneMap.get(target); - if (prop === "objectStoreNames") { - return target.objectStoreNames || transactionStoreNamesMap.get(target); + if (typeof network2 === "number") { + network2 = BigInt(network2); + } + if (typeof network2 === "string" || typeof network2 === "bigint") { + const networkFunc = Networks.get(network2); + if (networkFunc) { + return networkFunc(); } - if (prop === "store") { - return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]); + if (typeof network2 === "bigint") { + return new _Network("unknown", network2); } + assertArgument(false, "unknown network", "network", network2); } - return wrap(target[prop]); - }, - set(target, prop, value) { - target[prop] = value; - return true; - }, - has(target, prop) { - if (target instanceof IDBTransaction && (prop === "done" || prop === "store")) { - return true; + if (typeof network2.clone === "function") { + const clone = network2.clone(); + return clone; + } + if (typeof network2 === "object") { + assertArgument(typeof network2.name === "string" && typeof network2.chainId === "number", "invalid network object name or chainId", "network", network2); + const custom2 = new _Network(network2.name, network2.chainId); + if (network2.ensAddress || network2.ensNetwork != null) { + custom2.attachPlugin(new EnsPlugin(network2.ensAddress, network2.ensNetwork)); + } + return custom2; + } + assertArgument(false, "invalid network", "network", network2); + } + /** + * Register %%nameOrChainId%% with a function which returns + * an instance of a Network representing that chain. + */ + static register(nameOrChainId, networkFunc) { + if (typeof nameOrChainId === "number") { + nameOrChainId = BigInt(nameOrChainId); + } + const existing = Networks.get(nameOrChainId); + if (existing) { + assertArgument(false, `conflicting network for ${JSON.stringify(existing.name)}`, "nameOrChainId", nameOrChainId); + } + Networks.set(nameOrChainId, networkFunc); + } +}; +_name = new WeakMap(); +_chainId3 = new WeakMap(); +_plugins = new WeakMap(); +let Network = _Network; +function parseUnits$1(_value2, decimals) { + const value = String(_value2); + if (!value.match(/^[0-9.]+$/)) { + throw new Error(`invalid gwei value: ${_value2}`); + } + const comps = value.split("."); + if (comps.length === 1) { + comps.push(""); + } + if (comps.length !== 2) { + throw new Error(`invalid gwei value: ${_value2}`); + } + while (comps[1].length < decimals) { + comps[1] += "0"; + } + if (comps[1].length > 9) { + let frac = BigInt(comps[1].substring(0, 9)); + if (!comps[1].substring(9).match(/^0+$/)) { + frac++; } - return prop in target; + comps[1] = frac.toString(); } -}; -function replaceTraps(callback) { - idbProxyTraps = callback(idbProxyTraps); + return BigInt(comps[0] + comps[1]); } -function wrapFunction(func) { - if (func === IDBDatabase.prototype.transaction && !("objectStoreNames" in IDBTransaction.prototype)) { - return function(storeNames, ...args) { - const tx = func.call(unwrap(this), storeNames, ...args); - transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); - return wrap(tx); - }; +function getGasStationPlugin(url) { + return new FetchUrlFeeDataNetworkPlugin(url, async (fetchFeeData, provider2, request) => { + request.setHeader("User-Agent", "ethers"); + let response; + try { + const [_response, _feeData] = await Promise.all([ + request.send(), + fetchFeeData() + ]); + response = _response; + const payload = response.bodyJson.standard; + const feeData = { + gasPrice: _feeData.gasPrice, + maxFeePerGas: parseUnits$1(payload.maxFee, 9), + maxPriorityFeePerGas: parseUnits$1(payload.maxPriorityFee, 9) + }; + return feeData; + } catch (error) { + assert(false, `error encountered with polygon gas station (${JSON.stringify(request.url)})`, "SERVER_ERROR", { request, response, error }); + } + }); +} +let injected = false; +function injectCommonNetworks() { + if (injected) { + return; } - if (getCursorAdvanceMethods().includes(func)) { - return function(...args) { - func.apply(unwrap(this), args); - return wrap(cursorRequestMap.get(this)); + injected = true; + function registerEth(name2, chainId, options) { + const func = function() { + const network2 = new Network(name2, chainId); + if (options.ensNetwork != null) { + network2.attachPlugin(new EnsPlugin(null, options.ensNetwork)); + } + network2.attachPlugin(new GasCostPlugin()); + (options.plugins || []).forEach((plugin) => { + network2.attachPlugin(plugin); + }); + return network2; }; + Network.register(name2, func); + Network.register(chainId, func); + if (options.altNames) { + options.altNames.forEach((name3) => { + Network.register(name3, func); + }); + } } - return function(...args) { - return wrap(func.apply(unwrap(this), args)); - }; + registerEth("mainnet", 1, { ensNetwork: 1, altNames: ["homestead"] }); + registerEth("ropsten", 3, { ensNetwork: 3 }); + registerEth("rinkeby", 4, { ensNetwork: 4 }); + registerEth("goerli", 5, { ensNetwork: 5 }); + registerEth("kovan", 42, { ensNetwork: 42 }); + registerEth("sepolia", 11155111, { ensNetwork: 11155111 }); + registerEth("holesky", 17e3, { ensNetwork: 17e3 }); + registerEth("classic", 61, {}); + registerEth("classicKotti", 6, {}); + registerEth("arbitrum", 42161, { + ensNetwork: 1 + }); + registerEth("arbitrum-goerli", 421613, {}); + registerEth("arbitrum-sepolia", 421614, {}); + registerEth("base", 8453, { ensNetwork: 1 }); + registerEth("base-goerli", 84531, {}); + registerEth("base-sepolia", 84532, {}); + registerEth("bnb", 56, { ensNetwork: 1 }); + registerEth("bnbt", 97, {}); + registerEth("linea", 59144, { ensNetwork: 1 }); + registerEth("linea-goerli", 59140, {}); + registerEth("linea-sepolia", 59141, {}); + registerEth("matic", 137, { + ensNetwork: 1, + plugins: [ + getGasStationPlugin("https://gasstation.polygon.technology/v2") + ] + }); + registerEth("matic-amoy", 80002, {}); + registerEth("matic-mumbai", 80001, { + altNames: ["maticMumbai", "maticmum"], + plugins: [ + getGasStationPlugin("https://gasstation-testnet.polygon.technology/v2") + ] + }); + registerEth("optimism", 10, { + ensNetwork: 1, + plugins: [] + }); + registerEth("optimism-goerli", 420, {}); + registerEth("optimism-sepolia", 11155420, {}); + registerEth("xdai", 100, { ensNetwork: 1 }); } -function transformCachableValue(value) { - if (typeof value === "function") - return wrapFunction(value); - if (value instanceof IDBTransaction) - cacheDonePromiseForTransaction(value); - if (instanceOfAny(value, getIdbProxyableTypes())) - return new Proxy(value, idbProxyTraps); - return value; +function copy$3(obj) { + return JSON.parse(JSON.stringify(obj)); } -function wrap(value) { - if (value instanceof IDBRequest) - return promisifyRequest(value); - if (transformCache.has(value)) - return transformCache.get(value); - const newValue = transformCachableValue(value); - if (newValue !== value) { - transformCache.set(value, newValue); - reverseTransformCache.set(newValue, value); +class PollingBlockSubscriber { + /** + * Create a new **PollingBlockSubscriber** attached to %%provider%%. + */ + constructor(provider2) { + __privateAdd(this, _PollingBlockSubscriber_instances); + __privateAdd(this, _provider); + __privateAdd(this, _poller); + __privateAdd(this, _interval); + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + __privateAdd(this, _blockNumber); + __privateSet(this, _provider, provider2); + __privateSet(this, _poller, null); + __privateSet(this, _interval, 4e3); + __privateSet(this, _blockNumber, -2); } - return newValue; -} -const unwrap = (value) => reverseTransformCache.get(value); -function openDB(name2, version2, { blocked, upgrade, blocking, terminated } = {}) { - const request = indexedDB.open(name2, version2); - const openPromise = wrap(request); - if (upgrade) { - request.addEventListener("upgradeneeded", (event) => { - upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event); - }); + /** + * The polling interval. + */ + get pollingInterval() { + return __privateGet(this, _interval); } - if (blocked) { - request.addEventListener("blocked", (event) => blocked( - // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 - event.oldVersion, - event.newVersion, - event - )); + set pollingInterval(value) { + __privateSet(this, _interval, value); } - openPromise.then((db2) => { - if (terminated) - db2.addEventListener("close", () => terminated()); - if (blocking) { - db2.addEventListener("versionchange", (event) => blocking(event.oldVersion, event.newVersion, event)); + start() { + if (__privateGet(this, _poller)) { + return; } - }).catch(() => { - }); - return openPromise; -} -const readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"]; -const writeMethods = ["put", "add", "delete", "clear"]; -const cachedMethods = /* @__PURE__ */ new Map(); -function getMethod(target, prop) { - if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === "string")) { - return; + __privateSet(this, _poller, __privateGet(this, _provider)._setTimeout(__privateMethod(this, _PollingBlockSubscriber_instances, poll_fn).bind(this), __privateGet(this, _interval))); + __privateMethod(this, _PollingBlockSubscriber_instances, poll_fn).call(this); } - if (cachedMethods.get(prop)) - return cachedMethods.get(prop); - const targetFuncName = prop.replace(/FromIndex$/, ""); - const useIndex = prop !== targetFuncName; - const isWrite = writeMethods.includes(targetFuncName); - if ( - // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. - !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName)) - ) { - return; + stop() { + if (!__privateGet(this, _poller)) { + return; + } + __privateGet(this, _provider)._clearTimeout(__privateGet(this, _poller)); + __privateSet(this, _poller, null); } - const method = async function(storeName, ...args) { - const tx = this.transaction(storeName, isWrite ? "readwrite" : "readonly"); - let target2 = tx.store; - if (useIndex) - target2 = target2.index(args.shift()); - return (await Promise.all([ - target2[targetFuncName](...args), - isWrite && tx.done - ]))[0]; - }; - cachedMethods.set(prop, method); - return method; -} -replaceTraps((oldTraps) => ({ - ...oldTraps, - get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), - has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop) -})); -class ConfigTracker { - constructor() { - this.loadPresignedConfiguration = void 0; - this.savePresignedConfiguration = void 0; - this.saveWitnesses = void 0; - this.configOfImageHash = void 0; - this.saveWalletConfig = void 0; - this.imageHashOfCounterfactualWallet = void 0; - this.saveCounterfactualWallet = void 0; - this.walletsOfSigner = void 0; + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + __privateSet(this, _blockNumber, -2); + } + } + resume() { + this.start(); } } -var tracker = /* @__PURE__ */ Object.freeze({ - __proto__: null, - ConfigTracker -}); -class DebugConfigTracker { - constructor(tracker2) { - this.tracker = tracker2; +_provider = new WeakMap(); +_poller = new WeakMap(); +_interval = new WeakMap(); +_blockNumber = new WeakMap(); +_PollingBlockSubscriber_instances = new WeakSet(); +poll_fn = async function() { + try { + const blockNumber = await __privateGet(this, _provider).getBlockNumber(); + if (__privateGet(this, _blockNumber) === -2) { + __privateSet(this, _blockNumber, blockNumber); + return; + } + if (blockNumber !== __privateGet(this, _blockNumber)) { + for (let b2 = __privateGet(this, _blockNumber) + 1; b2 <= blockNumber; b2++) { + if (__privateGet(this, _poller) == null) { + return; + } + await __privateGet(this, _provider).emit("block", b2); + } + __privateSet(this, _blockNumber, blockNumber); + } + } catch (error) { } - async loadPresignedConfiguration(args) { - console.debug("? loadPresignedConfiguration"); - debug(args, "? "); - return debug(await this.tracker.loadPresignedConfiguration(args), "! "); + if (__privateGet(this, _poller) == null) { + return; } - savePresignedConfiguration(args) { - console.debug("? savePresignedConfiguration"); - debug(args, "? "); - return this.tracker.savePresignedConfiguration(args); + __privateSet(this, _poller, __privateGet(this, _provider)._setTimeout(__privateMethod(this, _PollingBlockSubscriber_instances, poll_fn).bind(this), __privateGet(this, _interval))); +}; +class OnBlockSubscriber { + /** + * Create a new **OnBlockSubscriber** attached to %%provider%%. + */ + constructor(provider2) { + __privateAdd(this, _provider2); + __privateAdd(this, _poll); + __privateAdd(this, _running); + __privateSet(this, _provider2, provider2); + __privateSet(this, _running, false); + __privateSet(this, _poll, (blockNumber) => { + this._poll(blockNumber, __privateGet(this, _provider2)); + }); } - saveWitnesses(args) { - console.debug("? saveWitnesses"); - debug(args, "? "); - return this.tracker.saveWitnesses(args); + /** + * Called on every new block. + */ + async _poll(blockNumber, provider2) { + throw new Error("sub-classes must override this"); } - async configOfImageHash(args) { - console.debug("? configOfImageHash"); - debug(args, "? "); - return debug(await this.tracker.configOfImageHash(args), "! "); + start() { + if (__privateGet(this, _running)) { + return; + } + __privateSet(this, _running, true); + __privateGet(this, _poll).call(this, -2); + __privateGet(this, _provider2).on("block", __privateGet(this, _poll)); } - saveWalletConfig(args) { - console.debug("? saveWalletConfig"); - debug(args, "? "); - return this.tracker.saveWalletConfig(args); + stop() { + if (!__privateGet(this, _running)) { + return; + } + __privateSet(this, _running, false); + __privateGet(this, _provider2).off("block", __privateGet(this, _poll)); } - async imageHashOfCounterfactualWallet(args) { - console.debug("? imageHashOfCounterfactualWallet"); - debug(args, "? "); - return debug(await this.tracker.imageHashOfCounterfactualWallet(args), "! "); + pause(dropWhilePaused) { + this.stop(); } - saveCounterfactualWallet(args) { - console.debug("? saveCounterfactualWallet"); - debug(args, "? "); - return this.tracker.saveCounterfactualWallet(args); + resume() { + this.start(); } - async walletsOfSigner(args) { - console.debug("? walletsOfSigner"); - debug(args, "? "); - return debug(await this.tracker.walletsOfSigner(args), "! "); +} +_provider2 = new WeakMap(); +_poll = new WeakMap(); +_running = new WeakMap(); +class PollingBlockTagSubscriber extends OnBlockSubscriber { + constructor(provider2, tag) { + super(provider2); + __privateAdd(this, _tag); + __privateAdd(this, _lastBlock); + __privateSet(this, _tag, tag); + __privateSet(this, _lastBlock, -2); } - async getMigration(address, fromImageHash, fromVersion, chainId) { - console.debug("? getMigration"); - debug({ - address, - fromImageHash, - fromVersion, - chainId - }, "? "); - return debug(await this.tracker.getMigration(address, fromImageHash, fromVersion, chainId), "! "); + pause(dropWhilePaused) { + if (dropWhilePaused) { + __privateSet(this, _lastBlock, -2); + } + super.pause(dropWhilePaused); } - saveMigration(address, signed2, contexts) { - console.debug("? saveMigration"); - debug({ - address, - signed: signed2, - contexts - }, "? "); - return this.tracker.saveMigration(address, signed2, contexts); + async _poll(blockNumber, provider2) { + const block = await provider2.getBlock(__privateGet(this, _tag)); + if (block == null) { + return; + } + if (__privateGet(this, _lastBlock) === -2) { + __privateSet(this, _lastBlock, block.number); + } else if (block.number > __privateGet(this, _lastBlock)) { + provider2.emit(__privateGet(this, _tag), block.number); + __privateSet(this, _lastBlock, block.number); + } } } -function debug(value, prefix = "") { - switch (value) { - case void 0: - console.debug(prefix + "undefined"); - break; - default: - JSON.stringify(value, bigintReplacer, 2).split("\n").map((line) => prefix + line).forEach((line) => console.debug(line)); - break; +_tag = new WeakMap(); +_lastBlock = new WeakMap(); +class PollingOrphanSubscriber extends OnBlockSubscriber { + constructor(provider2, filter2) { + super(provider2); + __privateAdd(this, _filter2); + __privateSet(this, _filter2, copy$3(filter2)); + } + async _poll(blockNumber, provider2) { + throw new Error("@TODO"); } - return value; -} -var debug$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - DebugConfigTracker -}); -function _extends$5() { - _extends$5 = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends$5.apply(this, arguments); } -class MemoryTrackerStore { - constructor() { - this.configs = {}; - this.v2Nodes = {}; - this.counterfactualWallets = {}; - this.payloads = {}; - this.signatures = {}; - this.migrations = {}; - this.loadConfig = (imageHash2) => { - return Promise.resolve(this.configs[imageHash2]); - }; - this.saveConfig = (imageHash2, config2) => { - this.configs[imageHash2] = config2; - return Promise.resolve(); - }; - this.loadV2Node = (nodeHash) => { - return Promise.resolve(this.v2Nodes[nodeHash]); - }; - this.saveV2Node = (nodeHash, node) => { - this.v2Nodes[nodeHash] = node; - return Promise.resolve(); - }; - this.loadCounterfactualWallet = (wallet) => { - return Promise.resolve(this.counterfactualWallets[wallet]); - }; - this.saveCounterfactualWallet = (wallet, imageHash2, context2) => { - this.counterfactualWallets[wallet] = { - imageHash: imageHash2, - context: context2 - }; - return Promise.resolve(); - }; - this.loadPayloadOfSubdigest = (subdigest) => { - return Promise.resolve(this.payloads[subdigest]); - }; - this.savePayloadOfSubdigest = (subdigest, payload) => { - this.payloads[subdigest] = payload; - return Promise.resolve(); - }; - this.loadSubdigestsOfSigner = (signer2) => { - return Promise.resolve(Object.keys(this.signatures[signer2] || {})); - }; - this.loadSignatureOfSubdigest = (signer2, subdigest) => { - var _this$signatures$sign; - return Promise.resolve((_this$signatures$sign = this.signatures[signer2]) == null ? void 0 : _this$signatures$sign[subdigest]); - }; - this.saveSignatureOfSubdigest = (signer2, subdigest, payload) => { - if (!this.signatures[signer2]) this.signatures[signer2] = {}; - this.signatures[signer2][subdigest] = payload; - return Promise.resolve(); - }; - this.loadMigrationsSubdigest = (wallet, fromVersion, toVersion) => { - var _this$migrations$wall; - return Promise.resolve(((_this$migrations$wall = this.migrations[wallet]) == null || (_this$migrations$wall = _this$migrations$wall[fromVersion]) == null ? void 0 : _this$migrations$wall[toVersion]) || []); - }; - this.saveMigrationsSubdigest = (wallet, fromVersion, toVersion, subdigest, toImageHash) => { - if (!this.migrations[wallet]) this.migrations[wallet] = {}; - if (!this.migrations[wallet][fromVersion]) this.migrations[wallet][fromVersion] = {}; - if (!this.migrations[wallet][fromVersion][toVersion]) this.migrations[wallet][fromVersion][toVersion] = []; - this.migrations[wallet][fromVersion][toVersion].push({ - subdigest, - toImageHash - }); - return Promise.resolve(); - }; +_filter2 = new WeakMap(); +class PollingTransactionSubscriber extends OnBlockSubscriber { + /** + * Create a new **PollingTransactionSubscriber** attached to + * %%provider%%, listening for %%hash%%. + */ + constructor(provider2, hash2) { + super(provider2); + __privateAdd(this, _hash); + __privateSet(this, _hash, hash2); + } + async _poll(blockNumber, provider2) { + const tx = await provider2.getTransactionReceipt(__privateGet(this, _hash)); + if (tx) { + provider2.emit(__privateGet(this, _hash), tx); + } } } -function recreateBigNumbers(object2) { - if (object2 === void 0) return void 0; - const result = {}; - for (const key of Object.keys(object2)) { - const val = object2[key]; - if (val._isBigNumber === true && val._hex !== void 0 && typeof val._hex === "string" && val._hex.length !== "") { - result[key] = BigInt(val._hex); - } else if (Array.isArray(val)) { - result[key] = val.map((v3) => recreateBigNumbers(v3)); - } else if (typeof val === "object" && val !== null) { - result[key] = recreateBigNumbers(val); - } else { - result[key] = val; +_hash = new WeakMap(); +class PollingEventSubscriber { + /** + * Create a new **PollingTransactionSubscriber** attached to + * %%provider%%, listening for %%filter%%. + */ + constructor(provider2, filter2) { + __privateAdd(this, _PollingEventSubscriber_instances); + __privateAdd(this, _provider3); + __privateAdd(this, _filter3); + __privateAdd(this, _poller2); + __privateAdd(this, _running2); + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + __privateAdd(this, _blockNumber2); + __privateSet(this, _provider3, provider2); + __privateSet(this, _filter3, copy$3(filter2)); + __privateSet(this, _poller2, __privateMethod(this, _PollingEventSubscriber_instances, poll_fn2).bind(this)); + __privateSet(this, _running2, false); + __privateSet(this, _blockNumber2, -2); + } + start() { + if (__privateGet(this, _running2)) { + return; + } + __privateSet(this, _running2, true); + if (__privateGet(this, _blockNumber2) === -2) { + __privateGet(this, _provider3).getBlockNumber().then((blockNumber) => { + __privateSet(this, _blockNumber2, blockNumber); + }); + } + __privateGet(this, _provider3).on("block", __privateGet(this, _poller2)); + } + stop() { + if (!__privateGet(this, _running2)) { + return; } + __privateSet(this, _running2, false); + __privateGet(this, _provider3).off("block", __privateGet(this, _poller2)); + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + __privateSet(this, _blockNumber2, -2); + } + } + resume() { + this.start(); } - return result; } -class IndexedDBStore { - constructor(dbName) { - var _this = this; - this.dbName = dbName; - this._lazyDb = void 0; - this.loadConfig = async function(imageHash2) { - const db2 = await _this.getDb(); - return db2.get("configs", imageHash2).then((c2) => recreateBigNumbers(c2)); - }; - this.saveConfig = async function(imageHash2, config2) { - const db2 = await _this.getDb(); - await db2.put("configs", config2, imageHash2); - }; - this.loadV2Node = async function(nodeHash) { - const db2 = await _this.getDb(); - return db2.get("v2Nodes", nodeHash).then((c2) => recreateBigNumbers(c2)); - }; - this.saveV2Node = async function(nodeHash, node) { - const db2 = await _this.getDb(); - await db2.put("v2Nodes", node, nodeHash); - }; - this.loadCounterfactualWallet = async function(wallet) { - const db2 = await _this.getDb(); - return db2.get("counterfactualWallets", wallet); - }; - this.saveCounterfactualWallet = async function(wallet, imageHash2, context2) { - const db2 = await _this.getDb(); - await db2.put("counterfactualWallets", { - imageHash: imageHash2, - context: context2 - }, wallet); - }; - this.loadPayloadOfSubdigest = async function(subdigest) { - const db2 = await _this.getDb(); - return db2.get("payloads", subdigest).then((c2) => recreateBigNumbers(c2)); - }; - this.savePayloadOfSubdigest = async function(subdigest, payload) { - const db2 = await _this.getDb(); - await db2.put("payloads", payload, subdigest); - }; - this.loadSubdigestsOfSigner = async function(signer2) { - const db2 = await _this.getDb(); - const index2 = await db2.getAllKeysFromIndex("signatures", "signer", IDBKeyRange.only(signer2)); - return index2.map((key) => key.split("-")[0]); - }; - this.loadSignatureOfSubdigest = async function(signer2, subdigest) { - const db2 = await _this.getDb(); - const signature2 = await db2.get("signatures", [subdigest, signer2].join("-")); - return signature2 == null ? void 0 : signature2.signature; - }; - this.saveSignatureOfSubdigest = async function(signer2, subdigest, payload) { - const db2 = await _this.getDb(); - await db2.put("signatures", { - signature: payload, - signer: signer2 - }, [subdigest, signer2].join("-")); - }; - this.loadMigrationsSubdigest = async function(wallet, fromVersion, toVersion) { - const db2 = await _this.getDb(); - const index2 = await db2.getAllFromIndex("migrations", "jump", IDBKeyRange.only([wallet, fromVersion, toVersion])); - return index2.map((key) => ({ - subdigest: key.subdigest, - toImageHash: key.toImageHash - })); - }; - this.saveMigrationsSubdigest = async function(wallet, fromVersion, toVersion, subdigest, toImageHash) { - const db2 = await _this.getDb(); - await db2.put("migrations", { - wallet, - fromVersion, - toVersion, - subdigest, - toImageHash - }, subdigest); - }; +_provider3 = new WeakMap(); +_filter3 = new WeakMap(); +_poller2 = new WeakMap(); +_running2 = new WeakMap(); +_blockNumber2 = new WeakMap(); +_PollingEventSubscriber_instances = new WeakSet(); +poll_fn2 = async function(blockNumber) { + if (__privateGet(this, _blockNumber2) === -2) { + return; } - async getDb() { - if (this._lazyDb) return this._lazyDb; - const dbName = this.dbName; - this._lazyDb = await openDB(dbName, 1, { - upgrade(db2, oldVersion, newVersion, transaction2) { - console.log(`upgrading ${dbName} from ${oldVersion} to ${newVersion} - ${transaction2}`); - if (oldVersion === 0) { - db2.createObjectStore("configs"); - db2.createObjectStore("v2Nodes"); - db2.createObjectStore("counterfactualWallets"); - db2.createObjectStore("payloads"); - const signatures = db2.createObjectStore("signatures"); - signatures.createIndex("signer", "signer", { - unique: false - }); - const migrations = db2.createObjectStore("migrations"); - migrations.createIndex("jump", ["wallet", "fromVersion", "toVersion"]); - } - } - }); - return this._lazyDb; + const filter2 = copy$3(__privateGet(this, _filter3)); + filter2.fromBlock = __privateGet(this, _blockNumber2) + 1; + filter2.toBlock = blockNumber; + const logs = await __privateGet(this, _provider3).getLogs(filter2); + if (logs.length === 0) { + if (__privateGet(this, _blockNumber2) < blockNumber - 60) { + __privateSet(this, _blockNumber2, blockNumber - 60); + } + return; + } + for (const log of logs) { + __privateGet(this, _provider3).emit(__privateGet(this, _filter3), log); + __privateSet(this, _blockNumber2, log.blockNumber); } +}; +const BN_2$1 = BigInt(2); +const MAX_CCIP_REDIRECTS = 10; +function isPromise$1(value) { + return value && typeof value.then === "function"; } -function isPlainNode(node) { - return node.left !== void 0 && node.right !== void 0; +function getTag$1(prefix, value) { + return prefix + ":" + JSON.stringify(value, (k2, v3) => { + if (v3 == null) { + return "null"; + } + if (typeof v3 === "bigint") { + return `bigint:${v3.toString()}`; + } + if (typeof v3 === "string") { + return v3.toLowerCase(); + } + if (typeof v3 === "object" && !Array.isArray(v3)) { + const keys = Object.keys(v3); + keys.sort(); + return keys.reduce((accum, key) => { + accum[key] = v3[key]; + return accum; + }, {}); + } + return v3; + }); } -function isPlainNested(node) { - return node.weight !== void 0 && node.threshold !== void 0 && node.tree !== void 0; +class UnmanagedSubscriber { + /** + * Create a new UnmanagedSubscriber with %%name%%. + */ + constructor(name2) { + /** + * The name fof the event. + */ + __publicField(this, "name"); + defineProperties$1(this, { name: name2 }); + } + start() { + } + stop() { + } + pause(dropWhilePaused) { + } + resume() { + } } -function isPlainV2Config(config2) { - return config2.version === 2 && config2.threshold !== void 0 && config2.checkpoint !== void 0 && config2.tree !== void 0 && typeof config2.tree === "string"; +function copy$2(value) { + return JSON.parse(JSON.stringify(value)); } -var index$2$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - isPlainNode, - isPlainNested, - isPlainV2Config, - MemoryTrackerStore, - recreateBigNumbers, - IndexedDBStore -}); -class LocalConfigTracker { - constructor(provider2, store = new MemoryTrackerStore(), useEIP5719 = false) { - var _this = this; - this.provider = provider2; - this.store = store; - this.useEIP5719 = useEIP5719; - this.cachedEIP5719 = void 0; - this.loadTopology = async function(hash2) { - const node = await _this.store.loadV2Node(hash2); - if (!node) return { - nodeHash: hash2 - }; - if (isPlainNode(node)) { - const [left, right] = await Promise.all([_this.loadTopology(node.left), _this.loadTopology(node.right)]); - return { - left, - right - }; - } - if (isPlainNested(node)) { - return { - weight: BigInt(node.weight), - threshold: BigInt(node.threshold), - tree: await _this.loadTopology(node.tree) - }; - } - return node; - }; - this.saveTopology = async function(node) { - if (v2.config.isNodeLeaf(node)) { - return; - } - const hash2 = v2.config.hashNode(node); - if (v2.config.isNode(node)) { - const saveLeft = _this.saveTopology(node.left); - const saveRight = _this.saveTopology(node.right); - const saveThis = _this.store.saveV2Node(hash2, { - left: v2.config.hashNode(node.left), - right: v2.config.hashNode(node.right) - }); - await Promise.all([saveLeft, saveRight, saveThis]); - return; - } - if (v2.config.isNestedLeaf(node)) { - const saveTree = _this.saveTopology(node.tree); - const saveThis = _this.store.saveV2Node(hash2, { - weight: BigInt(node.weight).toString(), - threshold: BigInt(node.threshold).toString(), - tree: v2.config.hashNode(node.tree) - }); - await Promise.all([saveTree, saveThis]); - return; - } - if (v2.config.isSignerLeaf(node)) { - return _this.store.saveV2Node(hash2, { - address: node.address, - weight: node.weight - }); - } - if (v2.config.isSubdigestLeaf(node)) { - return _this.store.saveV2Node(hash2, { - subdigest: node.subdigest - }); - } - throw new Error(`Unknown topology type: ${node}`); - }; - this.saveWalletConfig = async function(args) { - const { - config: config2 - } = args; - if (v1.config.ConfigCoder.isWalletConfig(config2)) { - const imageHash2 = v1.config.ConfigCoder.imageHashOf(config2); - return _this.store.saveConfig(imageHash2, config2); - } - if (v2.config.ConfigCoder.isWalletConfig(config2)) { - const imageHash2 = v2.config.ConfigCoder.imageHashOf(config2); - if (v2.config.isComplete(config2.tree)) { - return _this.store.saveConfig(imageHash2, config2); - } - } - return; - }; - this.configOfImageHashCache = {}; - this.configOfImageHash = async function(args) { - const { - imageHash: imageHash2 - } = args; - if (_this.configOfImageHashCache[args.imageHash]) { - return _this.configOfImageHashCache[args.imageHash]; - } - const config2 = await _this.store.loadConfig(imageHash2); - if (!config2) { - return void 0; - } - if (config2.version === 1 || config2.version === 2 && !isPlainV2Config(config2)) { - _this.configOfImageHashCache[args.imageHash] = config2; - return config2; - } - if (isPlainV2Config(config2)) { - const fullConfig = { - version: 2, - threshold: BigInt(config2.threshold), - checkpoint: BigInt(config2.checkpoint), - tree: await _this.loadTopology(config2.tree) - }; - _this.configOfImageHashCache[args.imageHash] = fullConfig; - return fullConfig; - } - throw new Error(`Unknown config type: ${config2}`); - }; - this.saveCounterfactualWallet = async function(args) { - const { - config: config2, - context: context2 - } = args; - const imageHash2 = index$6.genericCoderFor(config2.version).config.imageHashOf(config2); - await Promise.all([_this.saveWalletConfig({ - config: config2 - }), ...context2.map((ctx) => { - const address = index$1$2.context.addressOf(ctx, imageHash2); - return _this.store.saveCounterfactualWallet(address, imageHash2, ctx); - })]); - }; - this.imageHashOfCounterfactualWallet = async function(args) { - const { - wallet - } = args; - const result = await _this.store.loadCounterfactualWallet(wallet); - if (!result) return void 0; - return { - imageHash: result.imageHash, - context: result.context - }; - }; - this.savePayload = async function(args) { - const { - payload - } = args; - const subdigest = index$1$2.signature.subdigestOf(payload); - await _this.store.savePayloadOfSubdigest(subdigest, payload); - }; - this.payloadOfSubdigestCache = {}; - this.payloadOfSubdigest = async function(args) { - if (_this.payloadOfSubdigestCache[args.subdigest]) { - return _this.payloadOfSubdigestCache[args.subdigest]; - } - const { - subdigest - } = args; - const res = await _this.store.loadPayloadOfSubdigest(subdigest); - if (res) { - _this.payloadOfSubdigestCache[subdigest] = res; - } - return res; - }; - this.savePresignedConfiguration = async function(args) { - const decoded = v2.signature.SignatureCoder.decode(args.signature); - const nextImageHash = index$6.genericCoderFor(args.nextConfig.version).config.imageHashOf(args.nextConfig); - const message = v2.chained.messageSetImageHash(nextImageHash); - const digest = keccak256$1(message); - const payload = { - message, - address: args.wallet, - chainId: 0, - digest - }; - const savePayload = _this.savePayload({ - payload - }); - const saveNextConfig = _this.saveWalletConfig({ - config: args.nextConfig - }); - const recovered = await v2.signature.SignatureCoder.recover(decoded, payload, _this.provider); - const signatures = v2.signature.signaturesOf(recovered.config.tree); - await Promise.all([savePayload, saveNextConfig, _this.saveWalletConfig({ - config: recovered.config - }), ...signatures.map((sig) => _this.store.saveSignatureOfSubdigest(sig.address, recovered.subdigest, sig.signature))]); - }; - this.loadPresignedConfiguration = async function(args) { - const { - wallet, - fromImageHash, - longestPath - } = args; - const fromConfig = await _this.configOfImageHash({ - imageHash: fromImageHash - }); - if (!fromConfig || !v2.config.ConfigCoder.isWalletConfig(fromConfig)) { - return []; - } - const signers = v2.config.signersOf(fromConfig.tree).map((s2) => s2.address); - const subdigestsOfSigner = await Promise.all(signers.map((s2) => _this.store.loadSubdigestsOfSigner(s2))); - const subdigests = [...new Set(subdigestsOfSigner.flat())]; - const payloads = await Promise.all([...new Set(subdigests)].map(async function(s2) { - return _extends$5({}, await _this.payloadOfSubdigest({ - subdigest: s2 - }), { - subdigest: s2 - }); - })); - const nextImageHashes = payloads.filter((p2) => (p2 == null ? void 0 : p2.message) && (p2 == null ? void 0 : p2.address) && p2.address === wallet).map((p2) => ({ - payload: p2, - nextImageHash: v2.chained.decodeMessageSetImageHash(p2.message) - })).filter((p2) => p2 == null ? void 0 : p2.nextImageHash); - let bestCandidate; - const nextConfigsAndCheckpoints = await Promise.all(nextImageHashes.map(async function({ - nextImageHash, - payload - }) { - const nextConfig = await _this.configOfImageHash({ - imageHash: nextImageHash - }); - if (!nextConfig || !v2.config.isWalletConfig(nextConfig)) return void 0; - const nextCheckpoint = BigInt(nextConfig.checkpoint); - return { - nextConfig, - nextCheckpoint, - nextImageHash, - payload - }; - })); - const sortedNextConfigsAndCheckpoints = nextConfigsAndCheckpoints.filter((c2) => c2 !== void 0).filter((c2) => c2.nextCheckpoint > BigInt(fromConfig.checkpoint)).sort((a2, b2) => ( - // If we are looking for the longest path, sort by ascending checkpoint - // because we want to find the smalles jump, and we should start with the - // closest one. If we are not looking for the longest path, sort by - // descending checkpoint, because we want to find the largest jump. - // - // We don't have a guarantee that all "next configs" will be valid - // so worst case scenario we will need to try all of them. - // But we can try to optimize for the most common case. - a2.nextCheckpoint > b2.nextCheckpoint ? longestPath ? 1 : -1 : longestPath ? -1 : 1 - )); - for (const entry of sortedNextConfigsAndCheckpoints) { - const { - nextConfig, - nextCheckpoint, - nextImageHash, - payload - } = entry; - if (bestCandidate) { - const bestCheckpoint = bestCandidate.checkpoint; - if (longestPath) { - if (nextCheckpoint >= bestCheckpoint) continue; - } else { - if (nextCheckpoint <= bestCheckpoint) continue; - } - } - const signatures = new Map((await Promise.all(signers.map(async function(signer2) { - const signature2 = await _this.store.loadSignatureOfSubdigest(signer2, payload.subdigest); - if (!signature2) { - return [signer2, void 0]; - } - const replacedSignature = hexlify(_this.useEIP5719 ? await _this.cachedEIP5719.runByEIP5719(signer2, payload.subdigest, signature2) : signature2); - const isDynamic = index$1$2.signer.tryRecoverSigner(payload.subdigest, replacedSignature) !== signer2; - return [signer2, { - isDynamic, - signature: replacedSignature - }]; - }))).filter((signature2) => Boolean(signature2[1]))); - if (signatures.size === 0) continue; - const encoded = v2.signature.SignatureCoder.encodeSigners(fromConfig, signatures, [], 0); - if (encoded.weight < BigInt(fromConfig.threshold)) continue; - bestCandidate = { - nextImageHash, - checkpoint: BigInt(nextConfig.checkpoint), - signature: encoded.encoded - }; - } - if (!bestCandidate) { - return []; +function concisify(items) { + items = Array.from(new Set(items).values()); + items.sort(); + return items; +} +async function getSubscription(_event2, provider2) { + if (_event2 == null) { + throw new Error("invalid event"); + } + if (Array.isArray(_event2)) { + _event2 = { topics: _event2 }; + } + if (typeof _event2 === "string") { + switch (_event2) { + case "block": + case "debug": + case "error": + case "finalized": + case "network": + case "pending": + case "safe": { + return { type: _event2, tag: _event2 }; } - const nextStep = await _this.loadPresignedConfiguration({ - wallet, - fromImageHash: bestCandidate.nextImageHash, - longestPath - }); - return [{ - wallet, - nextImageHash: bestCandidate.nextImageHash, - signature: bestCandidate.signature - }, ...nextStep]; + } + } + if (isHexString(_event2, 32)) { + const hash2 = _event2.toLowerCase(); + return { type: "transaction", tag: getTag$1("tx", { hash: hash2 }), hash: hash2 }; + } + if (_event2.orphan) { + const event = _event2; + return { type: "orphan", tag: getTag$1("orphan", event), filter: copy$2(event) }; + } + if (_event2.address || _event2.topics) { + const event = _event2; + const filter2 = { + topics: (event.topics || []).map((t2) => { + if (t2 == null) { + return null; + } + if (Array.isArray(t2)) { + return concisify(t2.map((t3) => t3.toLowerCase())); + } + return t2.toLowerCase(); + }) }; - this.saveWitnesses = async function(args) { - const payload = { - digest: args.digest, - address: args.wallet, - chainId: args.chainId + if (event.address) { + const addresses = []; + const promises = []; + const addAddress = (addr) => { + if (isHexString(addr)) { + addresses.push(addr); + } else { + promises.push((async () => { + addresses.push(await resolveAddress(addr, provider2)); + })()); + } }; - const subdigest = index$1$2.signature.subdigestOf(payload); - await Promise.all([_this.savePayload({ - payload - }), ...args.signatures.filter((signature2) => { - return index$1$2.signer.canRecover(signature2); - }).map((signature2) => { - const signer2 = index$1$2.signer.recoverSigner(subdigest, signature2); - return _this.store.saveSignatureOfSubdigest(signer2, subdigest, signature2); - })]); - }; - this.walletsOfSigner = async function(args) { - const subdigests = await _this.store.loadSubdigestsOfSigner(args.signer); - const payloads = await Promise.all(subdigests.map((s2) => _this.payloadOfSubdigest({ - subdigest: s2 - }))).then((p2) => p2.filter((p3) => p3 !== void 0)); - const result = []; - for (const payload of payloads) { - const wallet = payload.address; - if (result.find((r2) => r2.wallet === wallet)) continue; - const subdigest = index$1$2.signature.subdigestOf(payload); - const signature2 = await _this.store.loadSignatureOfSubdigest(args.signer, subdigest); - if (!signature2) continue; - result.push({ - wallet, - proof: { - digest: payload.digest, - chainId: BigInt(payload.chainId), - signature: hexlify(signature2) - } - }); + if (Array.isArray(event.address)) { + event.address.forEach(addAddress); + } else { + addAddress(event.address); } - return result; - }; - this.cachedEIP5719 = new CachedEIP5719(provider2); + if (promises.length) { + await Promise.all(promises); + } + filter2.address = concisify(addresses.map((a2) => a2.toLowerCase())); + } + return { filter: filter2, tag: getTag$1("event", filter2), type: "event" }; } - async saveMigration(address, signed2, contexts) { - const fromVersion = signed2.fromVersion; - if (fromVersion !== 1) throw new Error("Migration not supported"); - if (!v2.config.isWalletConfig(signed2.toConfig)) throw new Error("Invalid to config"); - const { - newImageHash, - address: decodedAddress - } = index$5.v1v2.decodeTransaction(signed2.tx, contexts); - if (decodedAddress !== address) throw new Error("Invalid migration transaction - address"); - if (v2.config.ConfigCoder.imageHashOf(signed2.toConfig) != newImageHash) throw new Error("Invalid migration transaction - config"); - const message = index$1$2.transaction.packMetaTransactionsData(signed2.tx.nonce, signed2.tx.transactions); - const digest = keccak256$1(message); - const payload = { - chainId: signed2.tx.chainId, - message, - address, - digest - }; - const subdigest = index$1$2.signature.subdigestOf(payload); - const savePayload = this.savePayload({ - payload - }); - const saveToConfig = this.saveWalletConfig({ - config: signed2.toConfig - }); - const decoded = v1.signature.SignatureCoder.decode(signed2.tx.signature); - const recovered = await v1.signature.SignatureCoder.recover(decoded, payload, this.provider); - const signatures = v1.signature.SignatureCoder.signaturesOf(recovered.config); - await Promise.all([savePayload, saveToConfig, this.saveWalletConfig({ - config: recovered.config - }), this.store.saveMigrationsSubdigest(address, fromVersion, fromVersion + 1, subdigest, newImageHash), ...signatures.map((sig) => this.store.saveSignatureOfSubdigest(sig.address, recovered.subdigest, sig.signature))]); + assertArgument(false, "unknown ProviderEvent", "event", _event2); +} +function getTime$1() { + return (/* @__PURE__ */ new Date()).getTime(); +} +const defaultOptions$1 = { + cacheTimeout: 250, + pollingInterval: 4e3 +}; +class AbstractProvider { + /** + * Create a new **AbstractProvider** connected to %%network%%, or + * use the various network detection capabilities to discover the + * [[Network]] if necessary. + */ + constructor(_network3, options) { + __privateAdd(this, _AbstractProvider_instances); + __privateAdd(this, _subs); + __privateAdd(this, _plugins2); + // null=unpaused, true=paused+dropWhilePaused, false=paused + __privateAdd(this, _pausedState); + __privateAdd(this, _destroyed); + __privateAdd(this, _networkPromise); + __privateAdd(this, _anyNetwork); + __privateAdd(this, _performCache); + // The most recent block number if running an event or -1 if no "block" event + __privateAdd(this, _lastBlockNumber); + __privateAdd(this, _nextTimer); + __privateAdd(this, _timers); + __privateAdd(this, _disableCcipRead); + __privateAdd(this, _options2); + __privateSet(this, _options2, Object.assign({}, defaultOptions$1, options || {})); + if (_network3 === "any") { + __privateSet(this, _anyNetwork, true); + __privateSet(this, _networkPromise, null); + } else if (_network3) { + const network2 = Network.from(_network3); + __privateSet(this, _anyNetwork, false); + __privateSet(this, _networkPromise, Promise.resolve(network2)); + setTimeout(() => { + this.emit("network", network2, null); + }, 0); + } else { + __privateSet(this, _anyNetwork, false); + __privateSet(this, _networkPromise, null); + } + __privateSet(this, _lastBlockNumber, -1); + __privateSet(this, _performCache, /* @__PURE__ */ new Map()); + __privateSet(this, _subs, /* @__PURE__ */ new Map()); + __privateSet(this, _plugins2, /* @__PURE__ */ new Map()); + __privateSet(this, _pausedState, null); + __privateSet(this, _destroyed, false); + __privateSet(this, _nextTimer, 1); + __privateSet(this, _timers, /* @__PURE__ */ new Map()); + __privateSet(this, _disableCcipRead, false); } - async getMigration(address, fromImageHash, fromVersion, chainId) { - var _this2 = this; - const [currentConfig, txs] = await Promise.all([this.configOfImageHash({ - imageHash: fromImageHash - }), this.store.loadMigrationsSubdigest(address, fromVersion, fromVersion + 1)]); - const coder = index$6.coderFor(fromVersion); - if (!currentConfig) { - return void 0; + get pollingInterval() { + return __privateGet(this, _options2).pollingInterval; + } + /** + * Returns ``this``, to allow an **AbstractProvider** to implement + * the [[ContractRunner]] interface. + */ + get provider() { + return this; + } + /** + * Returns all the registered plug-ins. + */ + get plugins() { + return Array.from(__privateGet(this, _plugins2).values()); + } + /** + * Attach a new plug-in. + */ + attachPlugin(plugin) { + if (__privateGet(this, _plugins2).get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); } - if (!coder.config.isWalletConfig(currentConfig)) { - return void 0; + __privateGet(this, _plugins2).set(plugin.name, plugin.connect(this)); + return this; + } + /** + * Get a plugin by name. + */ + getPlugin(name2) { + return __privateGet(this, _plugins2).get(name2) || null; + } + /** + * Prevent any CCIP-read operation, regardless of whether requested + * in a [[call]] using ``enableCcipRead``. + */ + get disableCcipRead() { + return __privateGet(this, _disableCcipRead); + } + set disableCcipRead(value) { + __privateSet(this, _disableCcipRead, !!value); + } + /** + * Resolves to the data for executing the CCIP-read operations. + */ + async ccipReadFetch(tx, calldata, urls) { + if (this.disableCcipRead || urls.length === 0 || tx.to == null) { + return null; } - const candidates = await Promise.all(txs.map(async function(tx) { - const { - subdigest, - toImageHash - } = tx; - const payload = await _this2.payloadOfSubdigest({ - subdigest - }); - if (!payload || !payload.message) return void 0; - if (BigInt(chainId) !== BigInt(payload.chainId)) return void 0; - const signers = coder.config.signersOf(currentConfig).map((s2) => s2.address); - const signatures = new Map((await Promise.all(signers.map(async function(signer2) { - const signature2 = await _this2.store.loadSignatureOfSubdigest(signer2, subdigest); - if (!signature2) { - return [signer2, void 0]; + const sender = tx.to.toLowerCase(); + const data = calldata.toLowerCase(); + const errorMessages = []; + for (let i = 0; i < urls.length; i++) { + const url = urls[i]; + const href = url.replace("{sender}", sender).replace("{data}", data); + const request = new FetchRequest(href); + if (url.indexOf("{data}") === -1) { + request.body = { data, sender }; + } + this.emit("debug", { action: "sendCcipReadFetchRequest", request, index: i, urls }); + let errorMessage = "unknown error"; + const resp = await request.send(); + try { + const result = resp.bodyJson; + if (result.data) { + this.emit("debug", { action: "receiveCcipReadFetchResult", request, result }); + return result.data; } - const replacedSignature = hexlify(_this2.useEIP5719 ? await _this2.cachedEIP5719.runByEIP5719(signer2, subdigest, signature2) : signature2); - const isDynamic = index$1$2.signer.tryRecoverSigner(subdigest, replacedSignature) !== signer2; - return [signer2, { - isDynamic, - signature: replacedSignature - }]; - }))).filter((signature2) => Boolean(signature2[1]))); - const encoded = coder.signature.encodeSigners(currentConfig, signatures, [], chainId); - if (!encoded || encoded.weight < BigInt(currentConfig.threshold)) return void 0; - const [nonce, transactions2] = index$1$2.transaction.unpackMetaTransactionsData(payload.message); - return { - tx: { - entrypoint: address, - transactions: index$1$2.transaction.fromTxAbiEncode(transactions2), - chainId, - nonce, - signature: encoded.encoded, - intent: { - id: subdigest, - wallet: address - } - }, - toConfig: await _this2.configOfImageHash({ - imageHash: toImageHash - }), - fromVersion, - toVersion: fromVersion + 1 - }; - })).then((c2) => c2.filter((c3) => c3 !== void 0)); - return candidates[0]; + if (result.message) { + errorMessage = result.message; + } + this.emit("debug", { action: "receiveCcipReadFetchError", request, result }); + } catch (error) { + } + assert(resp.statusCode < 400 || resp.statusCode >= 500, `response not found during CCIP fetch: ${errorMessage}`, "OFFCHAIN_FAULT", { reason: "404_MISSING_RESOURCE", transaction: tx, info: { url, errorMessage } }); + errorMessages.push(errorMessage); + } + assert(false, `error encountered during CCIP fetch: ${errorMessages.map((m2) => JSON.stringify(m2)).join(", ")}`, "OFFCHAIN_FAULT", { + reason: "500_SERVER_ERROR", + transaction: tx, + info: { urls, errorMessages } + }); } - updateProvider(provider2) { - this.provider = provider2; + /** + * Provides the opportunity for a sub-class to wrap a block before + * returning it, to add additional properties or an alternate + * sub-class of [[Block]]. + */ + _wrapBlock(value, network2) { + return new Block(formatBlock(value), this); } -} -var local = /* @__PURE__ */ Object.freeze({ - __proto__: null, - LocalConfigTracker -}); -let SignatureType = /* @__PURE__ */ function(SignatureType2) { - SignatureType2["EIP712"] = "EIP712"; - SignatureType2["EthSign"] = "EthSign"; - SignatureType2["EIP1271"] = "EIP1271"; - return SignatureType2; -}({}); -class Sessions { - constructor(hostname, fetch2) { - this.hostname = void 0; - this.fetch = void 0; - this.path = "/rpc/Sessions/"; - this.ping = (headers, signal) => { - return this.fetch(this.url("Ping"), createHTTPRequest$3({}, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.config = (args, headers, signal) => { - return this.fetch(this.url("Config"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return { - version: _data6.version, - config: _data6.config - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.wallets = (args, headers, signal) => { - return this.fetch(this.url("Wallets"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return { - wallets: _data6.wallets - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.deployHash = (args, headers, signal) => { - return this.fetch(this.url("DeployHash"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return { - deployHash: _data6.deployHash, - context: _data6.context - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.configUpdates = (args, headers, signal) => { - return this.fetch(this.url("ConfigUpdates"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return { - updates: _data6.updates - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.migrations = (args, headers, signal) => { - return this.fetch(this.url("Migrations"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return { - migrations: _data6.migrations - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.saveConfig = (args, headers, signal) => { - return this.fetch(this.url("SaveConfig"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.saveWallet = (args, headers, signal) => { - return this.fetch(this.url("SaveWallet"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.saveSignature = (args, headers, signal) => { - return this.fetch(this.url("SaveSignature"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.saveSignerSignatures = (args, headers, signal) => { - return this.fetch(this.url("SaveSignerSignatures"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.saveMigration = (args, headers, signal) => { - return this.fetch(this.url("SaveMigration"), createHTTPRequest$3(args, headers, signal)).then((res) => { - return buildResponse$3(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$3.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.hostname = hostname; - this.fetch = (input2, init2) => fetch2(input2, init2); + /** + * Provides the opportunity for a sub-class to wrap a log before + * returning it, to add additional properties or an alternate + * sub-class of [[Log]]. + */ + _wrapLog(value, network2) { + return new Log(formatLog(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a transaction + * receipt before returning it, to add additional properties or an + * alternate sub-class of [[TransactionReceipt]]. + */ + _wrapTransactionReceipt(value, network2) { + return new TransactionReceipt(formatTransactionReceipt(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a transaction + * response before returning it, to add additional properties or an + * alternate sub-class of [[TransactionResponse]]. + */ + _wrapTransactionResponse(tx, network2) { + return new TransactionResponse(formatTransactionResponse(tx), this); + } + /** + * Resolves to the Network, forcing a network detection using whatever + * technique the sub-class requires. + * + * Sub-classes **must** override this. + */ + _detectNetwork() { + assert(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", { + operation: "_detectNetwork" + }); } - url(name2) { - return this.hostname + this.path + name2; + /** + * Sub-classes should use this to perform all built-in operations. All + * methods sanitizes and normalizes the values passed into this. + * + * Sub-classes **must** override this. + */ + async _perform(req) { + assert(false, `unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", { + operation: req.method, + info: req + }); } -} -const createHTTPRequest$3 = (body = {}, headers = {}, signal = null) => { - return { - method: "POST", - headers: _extends$5({}, headers, { - "Content-Type": "application/json" - }), - body: JSON.stringify(body || {}), - signal - }; -}; -const buildResponse$3 = (res) => { - return res.text().then((text2) => { - let data; - try { - data = JSON.parse(text2); - } catch (error) { - let message = ""; - if (error instanceof Error) { - message = error.message; - } - throw WebrpcBadResponseError$3.new({ - status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text2}` - }); - } - if (!res.ok) { - const code2 = typeof data.code === "number" ? data.code : 0; - throw (webrpcErrorByCode$3[code2] || WebrpcError$3).new(data); + // State + async getBlockNumber() { + const blockNumber = getNumber(await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getBlockNumber" }), "%response"); + if (__privateGet(this, _lastBlockNumber) >= 0) { + __privateSet(this, _lastBlockNumber, blockNumber); } - return data; - }); -}; -let WebrpcError$3 = class WebrpcError5 extends Error { - constructor(name2, code2, message, status, cause) { - super(message); - this.name = void 0; - this.code = void 0; - this.message = void 0; - this.status = void 0; - this.cause = void 0; - this.msg = void 0; - this.name = name2 || "WebrpcError"; - this.code = typeof code2 === "number" ? code2 : 0; - this.message = message || `endpoint error ${this.code}`; - this.msg = this.message; - this.status = typeof status === "number" ? status : 0; - this.cause = cause; - Object.setPrototypeOf(this, WebrpcError5.prototype); + return blockNumber; } - static new(payload) { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + /** + * Returns or resolves to the address for %%address%%, resolving ENS + * names and [[Addressable]] objects and returning if already an + * address. + */ + _getAddress(address) { + return resolveAddress(address, this); } -}; -let WebrpcEndpointError$3 = class WebrpcEndpointError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcEndpointError5.prototype); + /** + * Returns or resolves to a valid block tag for %%blockTag%%, resolving + * negative values and returning if already a valid block tag. + */ + _getBlockTag(blockTag) { + if (blockTag == null) { + return "latest"; + } + switch (blockTag) { + case "earliest": + return "0x0"; + case "finalized": + case "latest": + case "pending": + case "safe": + return blockTag; + } + if (isHexString(blockTag)) { + if (isHexString(blockTag, 32)) { + return blockTag; + } + return toQuantity(blockTag); + } + if (typeof blockTag === "bigint") { + blockTag = getNumber(blockTag, "blockTag"); + } + if (typeof blockTag === "number") { + if (blockTag >= 0) { + return toQuantity(blockTag); + } + if (__privateGet(this, _lastBlockNumber) >= 0) { + return toQuantity(__privateGet(this, _lastBlockNumber) + blockTag); + } + return this.getBlockNumber().then((b2) => toQuantity(b2 + blockTag)); + } + assertArgument(false, "invalid blockTag", "blockTag", blockTag); } -}; -let WebrpcRequestFailedError$3 = class WebrpcRequestFailedError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcRequestFailedError5.prototype); + /** + * Returns or resolves to a filter for %%filter%%, resolving any ENS + * names or [[Addressable]] object and returning if already a valid + * filter. + */ + _getFilter(filter2) { + const topics = (filter2.topics || []).map((t2) => { + if (t2 == null) { + return null; + } + if (Array.isArray(t2)) { + return concisify(t2.map((t3) => t3.toLowerCase())); + } + return t2.toLowerCase(); + }); + const blockHash = "blockHash" in filter2 ? filter2.blockHash : void 0; + const resolve = (_address, fromBlock2, toBlock2) => { + let address2 = void 0; + switch (_address.length) { + case 0: + break; + case 1: + address2 = _address[0]; + break; + default: + _address.sort(); + address2 = _address; + } + if (blockHash) { + if (fromBlock2 != null || toBlock2 != null) { + throw new Error("invalid filter"); + } + } + const filter3 = {}; + if (address2) { + filter3.address = address2; + } + if (topics.length) { + filter3.topics = topics; + } + if (fromBlock2) { + filter3.fromBlock = fromBlock2; + } + if (toBlock2) { + filter3.toBlock = toBlock2; + } + if (blockHash) { + filter3.blockHash = blockHash; + } + return filter3; + }; + let address = []; + if (filter2.address) { + if (Array.isArray(filter2.address)) { + for (const addr of filter2.address) { + address.push(this._getAddress(addr)); + } + } else { + address.push(this._getAddress(filter2.address)); + } + } + let fromBlock = void 0; + if ("fromBlock" in filter2) { + fromBlock = this._getBlockTag(filter2.fromBlock); + } + let toBlock = void 0; + if ("toBlock" in filter2) { + toBlock = this._getBlockTag(filter2.toBlock); + } + if (address.filter((a2) => typeof a2 !== "string").length || fromBlock != null && typeof fromBlock !== "string" || toBlock != null && typeof toBlock !== "string") { + return Promise.all([Promise.all(address), fromBlock, toBlock]).then((result) => { + return resolve(result[0], result[1], result[2]); + }); + } + return resolve(address, fromBlock, toBlock); } -}; -let WebrpcBadRouteError$3 = class WebrpcBadRouteError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRouteError5.prototype); + /** + * Returns or resolves to a transaction for %%request%%, resolving + * any ENS names or [[Addressable]] and returning if already a valid + * transaction. + */ + _getTransactionRequest(_request3) { + const request = copyRequest(_request3); + const promises = []; + ["to", "from"].forEach((key) => { + if (request[key] == null) { + return; + } + const addr = resolveAddress(request[key], this); + if (isPromise$1(addr)) { + promises.push(async function() { + request[key] = await addr; + }()); + } else { + request[key] = addr; + } + }); + if (request.blockTag != null) { + const blockTag = this._getBlockTag(request.blockTag); + if (isPromise$1(blockTag)) { + promises.push(async function() { + request.blockTag = await blockTag; + }()); + } else { + request.blockTag = blockTag; + } + } + if (promises.length) { + return async function() { + await Promise.all(promises); + return request; + }(); + } + return request; } -}; -let WebrpcBadMethodError$3 = class WebrpcBadMethodError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadMethodError5.prototype); + async getNetwork() { + if (__privateGet(this, _networkPromise) == null) { + const detectNetwork = (async () => { + try { + const network2 = await this._detectNetwork(); + this.emit("network", network2, null); + return network2; + } catch (error) { + if (__privateGet(this, _networkPromise) === detectNetwork) { + __privateSet(this, _networkPromise, null); + } + throw error; + } + })(); + __privateSet(this, _networkPromise, detectNetwork); + return (await detectNetwork).clone(); + } + const networkPromise = __privateGet(this, _networkPromise); + const [expected, actual] = await Promise.all([ + networkPromise, + this._detectNetwork() + // The actual connected network + ]); + if (expected.chainId !== actual.chainId) { + if (__privateGet(this, _anyNetwork)) { + this.emit("network", actual, expected); + if (__privateGet(this, _networkPromise) === networkPromise) { + __privateSet(this, _networkPromise, Promise.resolve(actual)); + } + } else { + assert(false, `network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", { + event: "changed" + }); + } + } + return expected.clone(); } -}; -let WebrpcBadRequestError$3 = class WebrpcBadRequestError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRequestError5.prototype); + async getFeeData() { + const network2 = await this.getNetwork(); + const getFeeDataFunc = async () => { + const { _block, gasPrice, priorityFee } = await resolveProperties$1({ + _block: __privateMethod(this, _AbstractProvider_instances, getBlock_fn).call(this, "latest", false), + gasPrice: (async () => { + try { + const value = await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getGasPrice" }); + return getBigInt(value, "%response"); + } catch (error) { + } + return null; + })(), + priorityFee: (async () => { + try { + const value = await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getPriorityFee" }); + return getBigInt(value, "%response"); + } catch (error) { + } + return null; + })() + }); + let maxFeePerGas = null; + let maxPriorityFeePerGas = null; + const block = this._wrapBlock(_block, network2); + if (block && block.baseFeePerGas) { + maxPriorityFeePerGas = priorityFee != null ? priorityFee : BigInt("1000000000"); + maxFeePerGas = block.baseFeePerGas * BN_2$1 + maxPriorityFeePerGas; + } + return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); + }; + const plugin = network2.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + if (plugin) { + const req = new FetchRequest(plugin.url); + const feeData = await plugin.processFunc(getFeeDataFunc, this, req); + return new FeeData(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas); + } + return await getFeeDataFunc(); } -}; -let WebrpcBadResponseError$3 = class WebrpcBadResponseError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadResponseError5.prototype); + async estimateGas(_tx) { + let tx = this._getTransactionRequest(_tx); + if (isPromise$1(tx)) { + tx = await tx; + } + return getBigInt(await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { + method: "estimateGas", + transaction: tx + }), "%response"); } -}; -let WebrpcServerPanicError$3 = class WebrpcServerPanicError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcServerPanicError5.prototype); + async call(_tx) { + const { tx, blockTag } = await resolveProperties$1({ + tx: this._getTransactionRequest(_tx), + blockTag: this._getBlockTag(_tx.blockTag) + }); + return await __privateMethod(this, _AbstractProvider_instances, checkNetwork_fn).call(this, __privateMethod(this, _AbstractProvider_instances, call_fn).call(this, tx, blockTag, _tx.enableCcipRead ? 0 : -1)); } -}; -let WebrpcInternalErrorError$3 = class WebrpcInternalErrorError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcInternalErrorError5.prototype); + async getBalance(address, blockTag) { + return getBigInt(await __privateMethod(this, _AbstractProvider_instances, getAccountValue_fn).call(this, { method: "getBalance" }, address, blockTag), "%response"); } -}; -let WebrpcClientDisconnectedError$3 = class WebrpcClientDisconnectedError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcClientDisconnectedError5.prototype); + async getTransactionCount(address, blockTag) { + return getNumber(await __privateMethod(this, _AbstractProvider_instances, getAccountValue_fn).call(this, { method: "getTransactionCount" }, address, blockTag), "%response"); } -}; -let WebrpcStreamLostError$3 = class WebrpcStreamLostError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamLostError5.prototype); + async getCode(address, blockTag) { + return hexlify(await __privateMethod(this, _AbstractProvider_instances, getAccountValue_fn).call(this, { method: "getCode" }, address, blockTag)); } -}; -let WebrpcStreamFinishedError$3 = class WebrpcStreamFinishedError5 extends WebrpcError$3 { - constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamFinishedError5.prototype); + async getStorage(address, _position, blockTag) { + const position = getBigInt(_position, "position"); + return hexlify(await __privateMethod(this, _AbstractProvider_instances, getAccountValue_fn).call(this, { method: "getStorage", position }, address, blockTag)); } -}; -let InvalidArgumentError$1 = class InvalidArgumentError5 extends WebrpcError$3 { - constructor(name2 = "InvalidArgument", code2 = 1, message = "invalid argument", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, InvalidArgumentError5.prototype); + // Write + async broadcastTransaction(signedTx) { + const { blockNumber, hash: hash2, network: network2 } = await resolveProperties$1({ + blockNumber: this.getBlockNumber(), + hash: this._perform({ + method: "broadcastTransaction", + signedTransaction: signedTx + }), + network: this.getNetwork() + }); + const tx = Transaction.from(signedTx); + if (tx.hash !== hash2) { + throw new Error("@TODO: the returned hash did not match"); + } + return this._wrapTransactionResponse(tx, network2).replaceableTransaction(blockNumber); } -}; -let NotFoundError$2 = class NotFoundError5 extends WebrpcError$3 { - constructor(name2 = "NotFound", code2 = 2, message = "not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, NotFoundError5.prototype); + // Queries + async getBlock(block, prefetchTxs) { + const { network: network2, params } = await resolveProperties$1({ + network: this.getNetwork(), + params: __privateMethod(this, _AbstractProvider_instances, getBlock_fn).call(this, block, !!prefetchTxs) + }); + if (params == null) { + return null; + } + return this._wrapBlock(params, network2); } -}; -const webrpcErrorByCode$3 = { - [0]: WebrpcEndpointError$3, - [-1]: WebrpcRequestFailedError$3, - [-2]: WebrpcBadRouteError$3, - [-3]: WebrpcBadMethodError$3, - [-4]: WebrpcBadRequestError$3, - [-5]: WebrpcBadResponseError$3, - [-6]: WebrpcServerPanicError$3, - [-7]: WebrpcInternalErrorError$3, - [-8]: WebrpcClientDisconnectedError$3, - [-9]: WebrpcStreamLostError$3, - [-10]: WebrpcStreamFinishedError$3, - [1]: InvalidArgumentError$1, - [2]: NotFoundError$2 -}; -class RemoteConfigTracker { - constructor(hostname, onlyRecoverable = true) { - this.onlyRecoverable = onlyRecoverable; - this.sessions = void 0; - this.sessions = new Sessions(hostname, fetch); + async getTransaction(hash2) { + const { network: network2, params } = await resolveProperties$1({ + network: this.getNetwork(), + params: __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getTransaction", hash: hash2 }) + }); + if (params == null) { + return null; + } + return this._wrapTransactionResponse(params, network2); } - async loadPresignedConfiguration(args) { - try { - const { - updates - } = await this.sessions.configUpdates({ - wallet: args.wallet, - fromImageHash: args.fromImageHash, - allUpdates: args.longestPath - }); - return updates.map(({ - toImageHash, - signature: signature2 - }) => ({ - wallet: args.wallet, - nextImageHash: toImageHash, - signature: signature2 - })); - } catch (error) { - if (is404NotFound(error)) { - return []; - } else { - throw error; + async getTransactionReceipt(hash2) { + const { network: network2, params } = await resolveProperties$1({ + network: this.getNetwork(), + params: __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getTransactionReceipt", hash: hash2 }) + }); + if (params == null) { + return null; + } + if (params.gasPrice == null && params.effectiveGasPrice == null) { + const tx = await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getTransaction", hash: hash2 }); + if (tx == null) { + throw new Error("report this; could not find tx or effectiveGasPrice"); } + params.effectiveGasPrice = tx.gasPrice; } + return this._wrapTransactionReceipt(params, network2); } - async savePresignedConfiguration(args) { - const config2 = args.nextConfig; - const imageHash2 = index$6.genericCoderFor(config2.version).config.imageHashOf(config2); - const message = v2.signature.setImageHashStruct(imageHash2); - const digest = keccak256$1(message); - await this.sessions.saveSignature({ - wallet: args.wallet, - digest, - chainID: "0", - signature: args.signature, - toConfig: encodeConfig(config2) + async getTransactionResult(hash2) { + const { result } = await resolveProperties$1({ + network: this.getNetwork(), + result: __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getTransactionResult", hash: hash2 }) }); + if (result == null) { + return null; + } + return hexlify(result); } - async saveWitnesses(args) { - let filteredSignatures = args.signatures; - if (this.onlyRecoverable) { - filteredSignatures = filteredSignatures.filter((signature2) => { - return index$1$2.signer.canRecover(signature2); - }); + // Bloom-filter Queries + async getLogs(_filter5) { + let filter2 = this._getFilter(_filter5); + if (isPromise$1(filter2)) { + filter2 = await filter2; } - await this.sessions.saveSignerSignatures({ - wallet: args.wallet, - digest: args.digest, - chainID: numberString(args.chainId), - signatures: filteredSignatures + const { network: network2, params } = await resolveProperties$1({ + network: this.getNetwork(), + params: __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { method: "getLogs", filter: filter2 }) }); + return params.map((p2) => this._wrapLog(p2, network2)); } - async configOfImageHash(args) { - try { - const { - version: version2, - config: config2 - } = await this.sessions.config(args); - return decodeConfig(version2, config2); - } catch (error) { - if (is404NotFound(error)) { - return; - } else { - throw error; - } + // ENS + _getProvider(chainId) { + assert(false, "provider cannot connect to target network", "UNSUPPORTED_OPERATION", { + operation: "_getProvider()" + }); + } + async getResolver(name2) { + return await EnsResolver.fromName(this, name2); + } + async getAvatar(name2) { + const resolver = await this.getResolver(name2); + if (resolver) { + return await resolver.getAvatar(); } + return null; } - async saveWalletConfig(args) { - const config2 = encodeConfig(args.config); - await this.sessions.saveConfig({ - version: args.config.version, - config: config2 - }); + async resolveName(name2) { + const resolver = await this.getResolver(name2); + if (resolver) { + return await resolver.getAddress(); + } + return null; } - async imageHashOfCounterfactualWallet(args) { + async lookupAddress(address) { + address = getAddress(address); + const node = namehash(address.substring(2).toLowerCase() + ".addr.reverse"); try { - const { - deployHash, - context: context2 - } = await this.sessions.deployHash(args); - return { - imageHash: deployHash, - context: context2 - }; + const ensAddr = await EnsResolver.getEnsAddress(this); + const ensContract = new Contract(ensAddr, [ + "function resolver(bytes32) view returns (address)" + ], this); + const resolver = await ensContract.resolver(node); + if (resolver == null || resolver === ZeroAddress) { + return null; + } + const resolverContract = new Contract(resolver, [ + "function name(bytes32) view returns (string)" + ], this); + const name2 = await resolverContract.name(node); + const check = await this.resolveName(name2); + if (check !== address) { + return null; + } + return name2; } catch (error) { - if (is404NotFound(error)) { - return; - } else { - throw error; + if (isError(error, "BAD_DATA") && error.value === "0x") { + return null; } - } - } - async saveCounterfactualWallet(args) { - const deployConfig = encodeConfig(args.config); - await this.sessions.saveWallet({ - version: args.config.version, - deployConfig - }); - } - async walletsOfSigner(args) { - const { - wallets - } = await this.sessions.wallets(args); - return Object.entries(wallets).map(([wallet, { - digest, - chainID, - type, - signature: signature2 - }]) => { - switch (type) { - case SignatureType.EIP712: - signature2 += toBeHex(index$1$2.signer.SigType.EIP712).slice(2); - break; - case SignatureType.EthSign: - signature2 += toBeHex(index$1$2.signer.SigType.ETH_SIGN).slice(2); - break; - case SignatureType.EIP1271: - signature2 += toBeHex(index$1$2.signer.SigType.WALLET_BYTES32).slice(2); - break; + if (isError(error, "CALL_EXCEPTION")) { + return null; } - return { - wallet, - proof: { - digest, - signature: signature2, - chainId: BigInt(chainID) - } - }; - }); + throw error; + } + return null; } - async getMigration(wallet, fromImageHash, fromVersion, chainId) { - var _this = this; - const chainIdString = numberString(chainId); - const { - migrations - } = await this.sessions.migrations({ - wallet, - fromVersion, - fromImageHash, - chainID: chainIdString - }); - const chooseMigration = async function chooseMigration2(chainId2) { - const migrations_ = migrations[chainId2]; - if (migrations_) { - const toVersions = Object.keys(migrations_).map(Number).sort((a2, b2) => b2 - a2); - for (const toVersion of toVersions) { - for (const [toHash, transactions2] of Object.entries(migrations_[toVersion])) { - try { - const toConfig = await _this.configOfImageHash({ - imageHash: toHash - }); - if (toConfig) { - return { - fromVersion, - toVersion, - toConfig, - tx: { - entrypoint: transactions2.executor, - transactions: transactions2.transactions, - nonce: transactions2.nonce, - signature: transactions2.signature, - chainId: chainId2, - intent: { - id: index$1$2.transaction.subdigestOfTransactions(wallet, chainId2, transactions2.nonce, transactions2.transactions), - wallet - } - } - }; + async waitForTransaction(hash2, _confirms, timeout) { + const confirms = _confirms != null ? _confirms : 1; + if (confirms === 0) { + return this.getTransactionReceipt(hash2); + } + return new Promise(async (resolve, reject) => { + let timer = null; + const listener = async (blockNumber) => { + try { + const receipt = await this.getTransactionReceipt(hash2); + if (receipt != null) { + if (blockNumber - receipt.blockNumber + 1 >= confirms) { + resolve(receipt); + if (timer) { + clearTimeout(timer); + timer = null; } - } catch (error) { - console.error(error); + return; } } + } catch (error) { + console.log("EEE", error); } + this.once("block", listener); + }; + if (timeout != null) { + timer = setTimeout(() => { + if (timer == null) { + return; + } + timer = null; + this.off("block", listener); + reject(makeError("timeout", "TIMEOUT", { reason: "timeout" })); + }, timeout); } - return; - }; - const migration2 = await chooseMigration(chainIdString); - if (migration2) { - return migration2; - } - for (const _chainId4 in migrations) { - if (_chainId4 !== chainIdString) { - const _migration = await chooseMigration(_chainId4); - if (_migration) { - return _migration; - } - } - } - return; + listener(await this.getBlockNumber()); + }); } - async saveMigration(wallet, signed2, _contexts) { - await this.sessions.saveMigration({ - wallet, - fromVersion: signed2.fromVersion, - toVersion: signed2.toVersion, - toConfig: encodeConfig(signed2.toConfig), - executor: signed2.tx.entrypoint, - transactions: signed2.tx.transactions.map(encodeTransaction), - nonce: numberString(signed2.tx.nonce), - signature: signed2.tx.signature, - chainID: numberString(signed2.tx.chainId) + async waitForBlock(blockTag) { + assert(false, "not implemented yet", "NOT_IMPLEMENTED", { + operation: "waitForBlock" }); } -} -function encodeConfig(config2) { - switch (config2.version) { - case 1: - if (v1.config.ConfigCoder.isWalletConfig(config2)) { - return { - threshold: numberNumber(config2.threshold), - signers: config2.signers.map(({ - weight, - address - }) => ({ - weight: numberNumber(weight), - address - })) - }; - } else { - throw new Error(`not a v${config2.version} config: ${config2}`); - } - case 2: - if (v2.config.ConfigCoder.isWalletConfig(config2)) { - return { - threshold: numberNumber(config2.threshold), - checkpoint: numberNumber(config2.checkpoint), - tree: encodeV2ConfigTree(config2.tree) - }; - } else { - throw new Error(`not a v${config2.version} config: ${config2}`); - } - default: - throw new Error(`unknown version ${config2.version}`); + /** + * Clear a timer created using the [[_setTimeout]] method. + */ + _clearTimeout(timerId) { + const timer = __privateGet(this, _timers).get(timerId); + if (!timer) { + return; + } + if (timer.timer) { + clearTimeout(timer.timer); + } + __privateGet(this, _timers).delete(timerId); } -} -function encodeV2ConfigTree(tree) { - if (v2.config.isNode(tree)) { - return { - left: encodeV2ConfigTree(tree.left), - right: encodeV2ConfigTree(tree.right) - }; - } else if (v2.config.isSignerLeaf(tree)) { - return { - weight: numberNumber(tree.weight), - address: tree.address - }; - } else if (v2.config.isNestedLeaf(tree)) { - return { - weight: numberNumber(tree.weight), - threshold: numberNumber(tree.threshold), - tree: encodeV2ConfigTree(tree.tree) - }; - } else if (v2.config.isNodeLeaf(tree)) { - return { - node: tree.nodeHash + /** + * Create a timer that will execute %%func%% after at least %%timeout%% + * (in ms). If %%timeout%% is unspecified, then %%func%% will execute + * in the next event loop. + * + * [Pausing](AbstractProvider-paused) the provider will pause any + * associated timers. + */ + _setTimeout(_func, timeout) { + if (timeout == null) { + timeout = 0; + } + const timerId = __privateWrapper(this, _nextTimer)._++; + const func = () => { + __privateGet(this, _timers).delete(timerId); + _func(); }; - } else { - return _extends$5({}, tree); + if (this.paused) { + __privateGet(this, _timers).set(timerId, { timer: null, func, time: timeout }); + } else { + const timer = setTimeout(func, timeout); + __privateGet(this, _timers).set(timerId, { timer, func, time: getTime$1() }); + } + return timerId; } -} -function decodeConfig(version2, config2) { - switch (version2) { - case 1: - return _extends$5({}, config2, { - version: version2 - }); - case 2: - return _extends$5({}, config2, { - version: version2, - tree: decodeV2ConfigTree(config2.tree) - }); - default: - throw new Error(`unknown version ${version2}`); + /** + * Perform %%func%% on each subscriber. + */ + _forEachSubscriber(func) { + for (const sub of __privateGet(this, _subs).values()) { + func(sub.subscriber); + } } -} -function decodeV2ConfigTree(tree) { - switch (typeof tree) { - case "object": - const tree_ = _extends$5({}, tree); - if (tree_.left !== void 0) { - tree_.left = decodeV2ConfigTree(tree_.left); + /** + * Sub-classes may override this to customize subscription + * implementations. + */ + _getSubscriber(sub) { + switch (sub.type) { + case "debug": + case "error": + case "network": + return new UnmanagedSubscriber(sub.type); + case "block": { + const subscriber = new PollingBlockSubscriber(this); + subscriber.pollingInterval = this.pollingInterval; + return subscriber; } - if (tree_.right !== void 0) { - tree_.right = decodeV2ConfigTree(tree_.right); + case "safe": + case "finalized": + return new PollingBlockTagSubscriber(this, sub.type); + case "event": + return new PollingEventSubscriber(this, sub.filter); + case "transaction": + return new PollingTransactionSubscriber(this, sub.hash); + case "orphan": + return new PollingOrphanSubscriber(this, sub.filter); + } + throw new Error(`unsupported event: ${sub.type}`); + } + /** + * If a [[Subscriber]] fails and needs to replace itself, this + * method may be used. + * + * For example, this is used for providers when using the + * ``eth_getFilterChanges`` method, which can return null if state + * filters are not supported by the backend, allowing the Subscriber + * to swap in a [[PollingEventSubscriber]]. + */ + _recoverSubscriber(oldSub, newSub) { + for (const sub of __privateGet(this, _subs).values()) { + if (sub.subscriber === oldSub) { + if (sub.started) { + sub.subscriber.stop(); + } + sub.subscriber = newSub; + if (sub.started) { + newSub.start(); + } + if (__privateGet(this, _pausedState) != null) { + newSub.pause(__privateGet(this, _pausedState)); + } + break; } - if (tree_.tree !== void 0) { - tree_.tree = decodeV2ConfigTree(tree_.tree); + } + } + async on(event, listener) { + const sub = await __privateMethod(this, _AbstractProvider_instances, getSub_fn).call(this, event); + sub.listeners.push({ listener, once: false }); + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (__privateGet(this, _pausedState) != null) { + sub.subscriber.pause(__privateGet(this, _pausedState)); } - if (tree_.node !== void 0) { - tree_.nodeHash = tree_.node; - delete tree_.node; + } + return this; + } + async once(event, listener) { + const sub = await __privateMethod(this, _AbstractProvider_instances, getSub_fn).call(this, event); + sub.listeners.push({ listener, once: true }); + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (__privateGet(this, _pausedState) != null) { + sub.subscriber.pause(__privateGet(this, _pausedState)); } - return tree_; - default: - throw new Error(`v2 config tree ${tree} is not an object`); + } + return this; } -} -function encodeTransaction(transaction2) { - return { - to: transaction2.to, - value: transaction2.value !== void 0 ? numberString(transaction2.value) : void 0, - data: transaction2.data !== void 0 ? hexlify(transaction2.data) : void 0, - gasLimit: transaction2.gasLimit !== void 0 ? numberString(transaction2.gasLimit) : void 0, - delegateCall: transaction2.delegateCall, - revertOnError: transaction2.revertOnError - }; -} -function numberNumber(n2) { - return Number(n2); -} -function numberString(n2) { - return BigInt(n2).toString(); -} -function is404NotFound(error) { - return typeof error === "object" && error.status === 404; -} -var index$1$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - RemoteConfigTracker -}); -function raceUntil(promises, fallback2, evalRes) { - return new Promise((resolve) => { - let count2 = 0; - promises.forEach((p2) => p2.then((val) => { - if (evalRes(val)) { - resolve(val); - } else { - count2++; - if (count2 === promises.length) { - resolve(fallback2); - } + async emit(event, ...args) { + const sub = await __privateMethod(this, _AbstractProvider_instances, hasSub_fn).call(this, event, args); + if (!sub || sub.listeners.length === 0) { + return false; + } + const count2 = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once }) => { + const payload = new EventPayload(this, once ? null : listener, event); + try { + listener.call(this, ...args, payload); + } catch (error) { } - }).catch(() => { - count2++; - if (count2 === promises.length) { - resolve(fallback2); + return !once; + }); + if (sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); } - })); - }); -} -async function allSafe(promises, fallback2) { - return Promise.all(promises.map((promise) => promise.catch(() => fallback2))); -} -class MultipleTracker { - constructor(trackers) { - this.trackers = trackers; + __privateGet(this, _subs).delete(sub.tag); + } + return count2 > 0; } - async configOfImageHash(args) { - const requests = this.trackers.map(async function(t2, i) { - return { - res: await t2.configOfImageHash(args), - i - }; - }); - const result1 = await raceUntil(requests, void 0, (val) => { - if ((val == null ? void 0 : val.res) === void 0) return false; - return index$6.genericCoderFor(val.res.version).config.isComplete(val.res); - }); - if (result1 != null && result1.res) { - this.saveWalletConfig({ - config: result1.res, - skipTracker: result1.i - }); - return result1.res; + async listenerCount(event) { + if (event) { + const sub = await __privateMethod(this, _AbstractProvider_instances, hasSub_fn).call(this, event); + if (!sub) { + return 0; + } + return sub.listeners.length; + } + let total = 0; + for (const { listeners } of __privateGet(this, _subs).values()) { + total += listeners.length; + } + return total; + } + async listeners(event) { + if (event) { + const sub = await __privateMethod(this, _AbstractProvider_instances, hasSub_fn).call(this, event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener }) => listener); } - const tmptracker = new LocalConfigTracker(void 0); - const results2 = await allSafe(requests, void 0); - for (const r2 of results2) { - if (r2 != null && r2.res) await tmptracker.saveWalletConfig({ - config: r2.res - }); + let result = []; + for (const { listeners } of __privateGet(this, _subs).values()) { + result = result.concat(listeners.map(({ listener }) => listener)); } - const result2 = await tmptracker.configOfImageHash(args); - if (result2) this.saveWalletConfig({ - config: result2 - }); - return result2; + return result; } - async saveWalletConfig(args) { - await Promise.all(this.trackers.map((t2, i) => { - if (i === args.skipTracker) return; - return t2.saveWalletConfig(args); - })); + async off(event, listener) { + const sub = await __privateMethod(this, _AbstractProvider_instances, hasSub_fn).call(this, event); + if (!sub) { + return this; + } + if (listener) { + const index2 = sub.listeners.map(({ listener: listener2 }) => listener2).indexOf(listener); + if (index2 >= 0) { + sub.listeners.splice(index2, 1); + } + } + if (!listener || sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); + } + __privateGet(this, _subs).delete(sub.tag); + } + return this; } - async imageHashOfCounterfactualWallet(args) { - const imageHash2 = await raceUntil(this.trackers.map((t2) => t2.imageHashOfCounterfactualWallet(args)), void 0, (result) => Boolean(result)); - if (imageHash2) { - this.configOfImageHash({ - imageHash: imageHash2.imageHash - }).then((config2) => { - if (config2) { - this.saveCounterfactualWallet({ - config: config2, - context: [imageHash2.context] - }); + async removeAllListeners(event) { + if (event) { + const { tag, started, subscriber } = await __privateMethod(this, _AbstractProvider_instances, getSub_fn).call(this, event); + if (started) { + subscriber.stop(); + } + __privateGet(this, _subs).delete(tag); + } else { + for (const [tag, { started, subscriber }] of __privateGet(this, _subs)) { + if (started) { + subscriber.stop(); } - }); + __privateGet(this, _subs).delete(tag); + } } - return imageHash2; + return this; } - async saveCounterfactualWallet(args) { - await Promise.all(this.trackers.map((t2, i) => { - if (i === args.skipTracker) return; - return t2.saveCounterfactualWallet(args); - })); + // Alias for "on" + async addListener(event, listener) { + return await this.on(event, listener); } - async walletsOfSigner(args) { - const results2 = await allSafe(this.trackers.map((t2) => t2.walletsOfSigner(args)), []).then((r2) => r2.flat()); - const wallets = {}; - for (const r2 of results2) { - wallets[r2.wallet] = r2.proof; + // Alias for "off" + async removeListener(event, listener) { + return this.off(event, listener); + } + /** + * If this provider has been destroyed using the [[destroy]] method. + * + * Once destroyed, all resources are reclaimed, internal event loops + * and timers are cleaned up and no further requests may be sent to + * the provider. + */ + get destroyed() { + return __privateGet(this, _destroyed); + } + /** + * Sub-classes may use this to shutdown any sockets or release their + * resources and reject any pending requests. + * + * Sub-classes **must** call ``super.destroy()``. + */ + destroy() { + this.removeAllListeners(); + for (const timerId of __privateGet(this, _timers).keys()) { + this._clearTimeout(timerId); } - const result = Object.keys(wallets).map((w2) => ({ - wallet: w2, - proof: wallets[w2] - })); - const witnesses = /* @__PURE__ */ new Map(); - result.forEach(({ - wallet, - proof: { - digest, - chainId, - signature: signature2 + __privateSet(this, _destroyed, true); + } + /** + * Whether the provider is currently paused. + * + * A paused provider will not emit any events, and generally should + * not make any requests to the network, but that is up to sub-classes + * to manage. + * + * Setting ``paused = true`` is identical to calling ``.pause(false)``, + * which will buffer any events that occur while paused until the + * provider is unpaused. + */ + get paused() { + return __privateGet(this, _pausedState) != null; + } + set paused(pause) { + if (!!pause === this.paused) { + return; + } + if (this.paused) { + this.resume(); + } else { + this.pause(false); + } + } + /** + * Pause the provider. If %%dropWhilePaused%%, any events that occur + * while paused are dropped, otherwise all events will be emitted once + * the provider is unpaused. + */ + pause(dropWhilePaused) { + __privateSet(this, _lastBlockNumber, -1); + if (__privateGet(this, _pausedState) != null) { + if (__privateGet(this, _pausedState) == !!dropWhilePaused) { + return; } - }) => { - const key = `${wallet}-${digest}-${chainId}`; - let signatures = witnesses.get(key); - if (!signatures) { - signatures = { - wallet, - digest, - chainId, - signatures: [] - }; - witnesses.set(key, signatures); + assert(false, "cannot change pause type; resume first", "UNSUPPORTED_OPERATION", { + operation: "pause" + }); + } + this._forEachSubscriber((s2) => s2.pause(dropWhilePaused)); + __privateSet(this, _pausedState, !!dropWhilePaused); + for (const timer of __privateGet(this, _timers).values()) { + if (timer.timer) { + clearTimeout(timer.timer); } - signatures.signatures.push(signature2); - }); - witnesses.forEach((witnesses2) => this.saveWitnesses(witnesses2)); - return result; + timer.time = getTime$1() - timer.time; + } } - async saveWitnesses(args) { - await Promise.all(this.trackers.map((t2) => t2.saveWitnesses(args))); + /** + * Resume the provider. + */ + resume() { + if (__privateGet(this, _pausedState) == null) { + return; + } + this._forEachSubscriber((s2) => s2.resume()); + __privateSet(this, _pausedState, null); + for (const timer of __privateGet(this, _timers).values()) { + let timeout = timer.time; + if (timeout < 0) { + timeout = 0; + } + timer.time = getTime$1(); + setTimeout(timer.func, timeout); + } } - async loadPresignedConfiguration(args) { - var _this = this; - const results2 = await allSafe(this.trackers.map((t2) => t2.loadPresignedConfiguration(args)), []); - const checkpoints = await allSafe(results2.map(async function(r2) { - const last = r2[r2.length - 1]; - const config3 = await _this.configOfImageHash({ - imageHash: last.nextImageHash - }); - if (!config3) return void 0; - return { - checkpoint: index$6.genericCoderFor(config3.version).config.checkpointOf(config3), - result: r2 - }; - }), void 0); - const best = checkpoints.reduce((acc, val) => { - if (!val) return acc; - if (!acc) return val; - if (val.checkpoint > acc.checkpoint) return val; - return acc; - }); - if (!best) return []; - const configs = /* @__PURE__ */ new Map(); - const config2 = (imageHash2) => { - if (!configs.has(imageHash2)) { - configs.set(imageHash2, this.configOfImageHash({ - imageHash: imageHash2 - })); +} +_subs = new WeakMap(); +_plugins2 = new WeakMap(); +_pausedState = new WeakMap(); +_destroyed = new WeakMap(); +_networkPromise = new WeakMap(); +_anyNetwork = new WeakMap(); +_performCache = new WeakMap(); +_lastBlockNumber = new WeakMap(); +_nextTimer = new WeakMap(); +_timers = new WeakMap(); +_disableCcipRead = new WeakMap(); +_options2 = new WeakMap(); +_AbstractProvider_instances = new WeakSet(); +perform_fn = async function(req) { + const timeout = __privateGet(this, _options2).cacheTimeout; + if (timeout < 0) { + return await this._perform(req); + } + const tag = getTag$1(req.method, req); + let perform = __privateGet(this, _performCache).get(tag); + if (!perform) { + perform = this._perform(req); + __privateGet(this, _performCache).set(tag, perform); + setTimeout(() => { + if (__privateGet(this, _performCache).get(tag) === perform) { + __privateGet(this, _performCache).delete(tag); } - return configs.get(imageHash2); - }; - best.result.forEach(async function(res) { - const nextConfig = await config2(res.nextImageHash); - if (nextConfig) { - _this.savePresignedConfiguration({ - wallet: args.wallet, - nextConfig, - signature: res.signature + }, timeout); + } + return await perform; +}; +call_fn = async function(tx, blockTag, attempt) { + assert(attempt < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", { + reason: "TOO_MANY_REDIRECTS", + transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true }) + }); + const transaction2 = copyRequest(tx); + try { + return hexlify(await this._perform({ method: "call", transaction: transaction2, blockTag })); + } catch (error) { + if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction2.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") { + const data = error.data; + const txSender = await resolveAddress(transaction2.to, this); + let ccipArgs; + try { + ccipArgs = parseOffchainLookup(dataSlice(error.data, 4)); + } catch (error2) { + assert(false, error2.message, "OFFCHAIN_FAULT", { + reason: "BAD_DATA", + transaction: transaction2, + info: { data } }); } + assert(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), "CCIP Read sender mismatch", "CALL_EXCEPTION", { + action: "call", + data, + reason: "OffchainLookup", + transaction: transaction2, + invocation: null, + revert: { + signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + name: "OffchainLookup", + args: ccipArgs.errorArgs + } + }); + const ccipResult = await this.ccipReadFetch(transaction2, ccipArgs.calldata, ccipArgs.urls); + assert(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { + reason: "FETCH_FAILED", + transaction: transaction2, + info: { data: error.data, errorArgs: ccipArgs.errorArgs } + }); + const tx2 = { + to: txSender, + data: concat([ccipArgs.selector, encodeBytes([ccipResult, ccipArgs.extraData])]) + }; + this.emit("debug", { action: "sendCcipReadCall", transaction: tx2 }); + try { + const result = await __privateMethod(this, _AbstractProvider_instances, call_fn).call(this, tx2, blockTag, attempt + 1); + this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({}, tx2), result }); + return result; + } catch (error2) { + this.emit("debug", { action: "receiveCcipReadCallError", transaction: Object.assign({}, tx2), error: error2 }); + throw error2; + } + } + throw error; + } +}; +checkNetwork_fn = async function(promise) { + const { value } = await resolveProperties$1({ + network: this.getNetwork(), + value: promise + }); + return value; +}; +getAccountValue_fn = async function(request, _address, _blockTag) { + let address = this._getAddress(_address); + let blockTag = this._getBlockTag(_blockTag); + if (typeof address !== "string" || typeof blockTag !== "string") { + [address, blockTag] = await Promise.all([address, blockTag]); + } + return await __privateMethod(this, _AbstractProvider_instances, checkNetwork_fn).call(this, __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, Object.assign(request, { address, blockTag }))); +}; +getBlock_fn = async function(block, includeTransactions) { + if (isHexString(block, 32)) { + return await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { + method: "getBlock", + blockHash: block, + includeTransactions }); - return best.result; } - async savePresignedConfiguration(args) { - await Promise.all(this.trackers.map((t2) => t2.savePresignedConfiguration(args))); + let blockTag = this._getBlockTag(block); + if (typeof blockTag !== "string") { + blockTag = await blockTag; } - async getMigration(address, fromImageHash, fromVersion, chainId) { - const results2 = await Promise.all(this.trackers.map((t2) => t2.getMigration(address, fromImageHash, fromVersion, chainId))); - return results2.find((r2) => !!r2); + return await __privateMethod(this, _AbstractProvider_instances, perform_fn).call(this, { + method: "getBlock", + blockTag, + includeTransactions + }); +}; +hasSub_fn = async function(event, emitArgs) { + let sub = await getSubscription(event, this); + if (sub.type === "event" && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) { + sub = await getSubscription({ orphan: "drop-log", log: emitArgs[0] }, this); } - async saveMigration(address, signed2, contexts) { - await Promise.all(this.trackers.map((t2) => t2.saveMigration(address, signed2, contexts))); + return __privateGet(this, _subs).get(sub.tag) || null; +}; +getSub_fn = async function(event) { + const subscription = await getSubscription(event, this); + const tag = subscription.tag; + let sub = __privateGet(this, _subs).get(tag); + if (!sub) { + const subscriber = this._getSubscriber(subscription); + const addressableMap = /* @__PURE__ */ new WeakMap(); + const nameMap = /* @__PURE__ */ new Map(); + sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [] }; + __privateGet(this, _subs).set(tag, sub); + } + return sub; +}; +function _parseString(result, start) { + try { + const bytes2 = _parseBytes(result, start); + if (bytes2) { + return toUtf8String(bytes2); + } + } catch (error) { } + return null; } -class CachedTracker { - constructor(tracker2, cache2, contexts) { - this.tracker = tracker2; - this.cache = cache2; - this.contexts = contexts; +function _parseBytes(result, start) { + if (result === "0x") { + return null; } - async loadPresignedConfiguration(args) { - var _this = this; - const results2 = [this.tracker.loadPresignedConfiguration(args), this.cache.loadPresignedConfiguration(args)]; - let best; - const [result1, result2] = await Promise.all(results2); - if (result1.length > 0 && result2.length > 0 && result1[result1.length - 1].nextImageHash === result2[result2.length - 1].nextImageHash) { - best = args.longestPath === true ? result1.length > result2.length ? result1 : result2 : result1.length < result2.length ? result1 : result2; - } else { - var _checkpoints$reduce$r, _checkpoints$reduce; - const checkpoints = await Promise.all(results2.map(async function(result) { - const r2 = await result; - const last = r2[r2.length - 1]; - if (!last) return void 0; - const config2 = await _this.configOfImageHash({ - imageHash: last.nextImageHash - }); - if (!config2) return void 0; - return { - checkpoint: index$6.genericCoderFor(config2.version).config.checkpointOf(config2), - result: r2 - }; - })); - best = (_checkpoints$reduce$r = (_checkpoints$reduce = checkpoints.reduce((acc, val) => { - if (!val) return acc; - if (!acc) return val; - if (val.checkpoint > acc.checkpoint) return val; - return acc; - })) == null ? void 0 : _checkpoints$reduce.result) != null ? _checkpoints$reduce$r : []; - } - if (!best) return []; - return best; + try { + const offset2 = getNumber(dataSlice(result, start, start + 32)); + const length = getNumber(dataSlice(result, offset2, offset2 + 32)); + return dataSlice(result, offset2 + 32, offset2 + 32 + length); + } catch (error) { } - async savePresignedConfiguration(args) { - await Promise.all([this.tracker.savePresignedConfiguration(args), this.cache.savePresignedConfiguration(args)]); + return null; +} +function numPad(value) { + const result = toBeArray(value); + if (result.length > 32) { + throw new Error("internal; should not happen"); } - async configOfImageHash(args) { - if (args.noCache !== true) { - const config3 = await this.cache.configOfImageHash(args); - if (config3) return config3; - } - const config2 = await this.tracker.configOfImageHash(args); - if (config2) { - await this.cache.saveWalletConfig({ - config: config2 - }); - } - return config2; + const padded = new Uint8Array(32); + padded.set(result, 32 - result.length); + return padded; +} +function bytesPad(value) { + if (value.length % 32 === 0) { + return value; } - async saveWalletConfig(args) { - await Promise.all([this.tracker.saveWalletConfig(args), this.cache.saveWalletConfig(args)]); + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; +} +const empty = new Uint8Array([]); +function encodeBytes(datas) { + const result = []; + let byteCount = 0; + for (let i = 0; i < datas.length; i++) { + result.push(empty); + byteCount += 32; } - async imageHashOfCounterfactualWallet(args) { - if (args.noCache !== true) { - const result1 = await this.cache.imageHashOfCounterfactualWallet(args); - if (result1) return result1; - } - const result2 = await this.tracker.imageHashOfCounterfactualWallet(args); - if (result2) { - const config2 = await this.configOfImageHash({ - imageHash: result2.imageHash - }); - if (config2) { - await this.cache.saveCounterfactualWallet({ - config: config2, - context: [result2.context] - }); + for (let i = 0; i < datas.length; i++) { + const data = getBytes(datas[i]); + result[i] = numPad(byteCount); + result.push(numPad(data.length)); + result.push(bytesPad(data)); + byteCount += 32 + Math.ceil(data.length / 32) * 32; + } + return concat(result); +} +const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000"; +function parseOffchainLookup(data) { + const result = { + sender: "", + urls: [], + calldata: "", + selector: "", + extraData: "", + errorArgs: [] + }; + assert(dataLength(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", { + reason: "insufficient OffchainLookup data" + }); + const sender = dataSlice(data, 0, 32); + assert(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup sender" + }); + result.sender = dataSlice(sender, 12); + try { + const urls = []; + const urlsOffset = getNumber(dataSlice(data, 32, 64)); + const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32)); + const urlsData = dataSlice(data, urlsOffset + 32); + for (let u2 = 0; u2 < urlsLength; u2++) { + const url = _parseString(urlsData, u2 * 32); + if (url == null) { + throw new Error("abort"); } + urls.push(url); } - return result2; - } - async saveCounterfactualWallet(args) { - await Promise.all([this.tracker.saveCounterfactualWallet(args), this.cache.saveCounterfactualWallet(args)]); + result.urls = urls; + } catch (error) { + assert(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup urls" + }); } - async walletsOfSigner(args) { - if (args.noCache) { - return this.tracker.walletsOfSigner(args); - } - const results2 = await Promise.all([this.tracker.walletsOfSigner(args), this.cache.walletsOfSigner(args)]); - const wallets = /* @__PURE__ */ new Map(); - for (const result of results2) { - for (const wallet of result) { - wallets.set(wallet.wallet, wallet); - } + try { + const calldata = _parseBytes(data, 64); + if (calldata == null) { + throw new Error("abort"); } - return Array.from(wallets.values()); - } - async saveWitnesses(args) { - await Promise.all([this.tracker.saveWitnesses(args), this.cache.saveWitnesses(args)]); + result.calldata = calldata; + } catch (error) { + assert(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup calldata" + }); } - async getMigration(address, fromImageHash, fromVersion, chainId) { - const migration1 = await this.cache.getMigration(address, fromImageHash, fromVersion, chainId); - if (migration1) return migration1; - const migration2 = await this.tracker.getMigration(address, fromImageHash, fromVersion, chainId); - if (migration2) { - await this.cache.saveMigration(address, migration2, this.contexts); + assert(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup callbaackSelector" + }); + result.selector = dataSlice(data, 96, 100); + try { + const extraData = _parseBytes(data, 128); + if (extraData == null) { + throw new Error("abort"); } - return migration2; - } - async saveMigration(address, signed2, contexts) { - await Promise.all([this.tracker.saveMigration(address, signed2, contexts), this.cache.saveMigration(address, signed2, contexts)]); + result.extraData = extraData; + } catch (error) { + assert(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup extraData" + }); } + result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k2) => result[k2]); + return result; } -class PromiseCache2 { - constructor() { - this.cache = void 0; - this.cache = /* @__PURE__ */ new Map(); - } - do(key, validMilliseconds, task, ...args) { - key = `${key}:${id$1(JSON.stringify(args, deterministically))}`; - let entry = this.cache.get(key); - if (entry) { - if (entry.expiration) { - if (/* @__PURE__ */ new Date() >= entry.expiration) { - entry = void 0; - this.cache.delete(key); - } - } - } - if (!entry) { - const entry_ = { - promise: task(...args) - }; - if (validMilliseconds !== void 0) { - entry_.promise = entry_.promise.then((result) => { - entry_.expiration = new Date(Date.now() + validMilliseconds); - return result; - }); - } - entry = entry_; - this.cache.set(key, entry); - } - return entry.promise; +function checkProvider(signer2, operation) { + if (signer2.provider) { + return signer2.provider; } + assert(false, "missing provider", "UNSUPPORTED_OPERATION", { operation }); } -function deterministically(_key, value) { - if (typeof value === "object" && value !== null && !Array.isArray(value)) { - return Object.fromEntries(Object.entries(value).sort()); - } else if (typeof value === "bigint") { - return value.toString(); +async function populate(signer2, tx) { + let pop = copyRequest(tx); + if (pop.to != null) { + pop.to = resolveAddress(pop.to, signer2); } - return value; -} -function isDedupedTracker(tracker2) { - return tracker2 instanceof DedupedTracker; + if (pop.from != null) { + const from = pop.from; + pop.from = Promise.all([ + signer2.getAddress(), + resolveAddress(from, signer2) + ]).then(([address, from2]) => { + assertArgument(address.toLowerCase() === from2.toLowerCase(), "transaction from mismatch", "tx.from", from2); + return address; + }); + } else { + pop.from = signer2.getAddress(); + } + return await resolveProperties$1(pop); } -class DedupedTracker { - constructor(tracker2, window2 = 50, verbose = false) { - this.tracker = tracker2; - this.window = window2; - this.verbose = verbose; - this.cache = new PromiseCache2(); +class AbstractSigner { + /** + * Creates a new Signer connected to %%provider%%. + */ + constructor(provider2) { + /** + * The provider this signer is connected to. + */ + __publicField(this, "provider"); + defineProperties$1(this, { provider: provider2 || null }); } - invalidateCache() { - this.cache = new PromiseCache2(); + async getNonce(blockTag) { + return checkProvider(this, "getTransactionCount").getTransactionCount(await this.getAddress(), blockTag); } - configOfImageHash(args) { - return this.cache.do("configOfImageHash", this.window, (args2) => this.tracker.configOfImageHash(args2), args); + async populateCall(tx) { + const pop = await populate(this, tx); + return pop; } - getMigration(address, fromImageHash, fromVersion, chainId) { - return this.cache.do("getMigration", this.window, (...args) => this.tracker.getMigration(...args), address, fromImageHash, fromVersion, chainId); + async populateTransaction(tx) { + const provider2 = checkProvider(this, "populateTransaction"); + const pop = await populate(this, tx); + if (pop.nonce == null) { + pop.nonce = await this.getNonce("pending"); + } + if (pop.gasLimit == null) { + pop.gasLimit = await this.estimateGas(pop); + } + const network2 = await this.provider.getNetwork(); + if (pop.chainId != null) { + const chainId = getBigInt(pop.chainId); + assertArgument(chainId === network2.chainId, "transaction chainId mismatch", "tx.chainId", tx.chainId); + } else { + pop.chainId = network2.chainId; + } + const hasEip1559 = pop.maxFeePerGas != null || pop.maxPriorityFeePerGas != null; + if (pop.gasPrice != null && (pop.type === 2 || hasEip1559)) { + assertArgument(false, "eip-1559 transaction do not support gasPrice", "tx", tx); + } else if ((pop.type === 0 || pop.type === 1) && hasEip1559) { + assertArgument(false, "pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "tx", tx); + } + if ((pop.type === 2 || pop.type == null) && (pop.maxFeePerGas != null && pop.maxPriorityFeePerGas != null)) { + pop.type = 2; + } else if (pop.type === 0 || pop.type === 1) { + const feeData = await provider2.getFeeData(); + assert(feeData.gasPrice != null, "network does not support gasPrice", "UNSUPPORTED_OPERATION", { + operation: "getGasPrice" + }); + if (pop.gasPrice == null) { + pop.gasPrice = feeData.gasPrice; + } + } else { + const feeData = await provider2.getFeeData(); + if (pop.type == null) { + if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) { + pop.type = 2; + if (pop.gasPrice != null) { + const gasPrice = pop.gasPrice; + delete pop.gasPrice; + pop.maxFeePerGas = gasPrice; + pop.maxPriorityFeePerGas = gasPrice; + } else { + if (pop.maxFeePerGas == null) { + pop.maxFeePerGas = feeData.maxFeePerGas; + } + if (pop.maxPriorityFeePerGas == null) { + pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + } + } + } else if (feeData.gasPrice != null) { + assert(!hasEip1559, "network does not support EIP-1559", "UNSUPPORTED_OPERATION", { + operation: "populateTransaction" + }); + if (pop.gasPrice == null) { + pop.gasPrice = feeData.gasPrice; + } + pop.type = 0; + } else { + assert(false, "failed to get consistent fee data", "UNSUPPORTED_OPERATION", { + operation: "signer.getFeeData" + }); + } + } else if (pop.type === 2 || pop.type === 3) { + if (pop.maxFeePerGas == null) { + pop.maxFeePerGas = feeData.maxFeePerGas; + } + if (pop.maxPriorityFeePerGas == null) { + pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + } + } + } + return await resolveProperties$1(pop); } - saveMigration(address, signed2, contexts) { - return this.cache.do("saveMigration", void 0, (...args) => this.tracker.saveMigration(...args), address, signed2, contexts); + async estimateGas(tx) { + return checkProvider(this, "estimateGas").estimateGas(await this.populateCall(tx)); } - loadPresignedConfiguration(args) { - return this.cache.do("loadPresignedConfiguration", this.window, (args2) => this.tracker.loadPresignedConfiguration(args2), args); + async call(tx) { + return checkProvider(this, "call").call(await this.populateCall(tx)); } - savePresignedConfiguration(args) { - return this.cache.do("savePresignedConfiguration", void 0, (args2) => this.tracker.savePresignedConfiguration(args2), args); + async resolveName(name2) { + const provider2 = checkProvider(this, "resolveName"); + return await provider2.resolveName(name2); } - saveWitnesses(args) { - return this.cache.do("saveWitnesses", void 0, (args2) => this.tracker.saveWitnesses(args2), args); + async sendTransaction(tx) { + const provider2 = checkProvider(this, "sendTransaction"); + const pop = await this.populateTransaction(tx); + delete pop.from; + const txObj = Transaction.from(pop); + return await provider2.broadcastTransaction(await this.signTransaction(txObj)); } - saveWalletConfig(args) { - return this.cache.do("saveWalletConfig", void 0, (args2) => this.tracker.saveWalletConfig(args2), args); +} +const _VoidSigner = class _VoidSigner extends AbstractSigner { + /** + * Creates a new **VoidSigner** with %%address%% attached to + * %%provider%%. + */ + constructor(address, provider2) { + super(provider2); + __privateAdd(this, _VoidSigner_instances); + /** + * The signer address. + */ + __publicField(this, "address"); + defineProperties$1(this, { address }); } - imageHashOfCounterfactualWallet(args) { - return this.cache.do("imageHashOfCounterfactualWallet", void 0, (args2) => this.tracker.imageHashOfCounterfactualWallet(args2), args); + async getAddress() { + return this.address; } - saveCounterfactualWallet(args) { - return this.cache.do("saveCounterfactualWallet", void 0, (args2) => this.tracker.saveCounterfactualWallet(args2), args); + connect(provider2) { + return new _VoidSigner(this.address, provider2); } - walletsOfSigner(args) { - return this.cache.do("walletsOfSigner", this.window, (args2) => this.tracker.walletsOfSigner(args2), args); + async signTransaction(tx) { + __privateMethod(this, _VoidSigner_instances, throwUnsupported_fn).call(this, "transactions", "signTransaction"); } - updateProvider(provider2) { - if (this.tracker instanceof LocalConfigTracker) { - this.tracker.updateProvider(provider2); - } + async signMessage(message) { + __privateMethod(this, _VoidSigner_instances, throwUnsupported_fn).call(this, "messages", "signMessage"); } -} -var index$3 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - debug: debug$1, - local, - remote: index$1$1, - stores: index$2$1, - raceUntil, - allSafe, - MultipleTracker, - CachedTracker, - isDedupedTracker, - DedupedTracker -}); -const sessions$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - tracker, - trackers: index$3 -}, Symbol.toStringTag, { value: "Module" })); -const DEFAULT_SESSION_EXPIRATION$1 = 60 * 60 * 24 * 7; -const EXPIRATION_JWT_MARGIN = 60; -class Services { - constructor(account2, settings, status = {}, projectAccessKey2) { - this.account = account2; - this.settings = settings; - this.status = status; - this._initialAuthRequest = void 0; - this.proofStrings = /* @__PURE__ */ new Map(); - this.onAuthCallbacks = []; - this.apiClient = void 0; - this.metadataClient = void 0; - this.indexerClients = /* @__PURE__ */ new Map(); - this.projectAccessKey = void 0; - this.projectAccessKey = projectAccessKey2; + async signTypedData(domain2, types2, value) { + __privateMethod(this, _VoidSigner_instances, throwUnsupported_fn).call(this, "typed-data", "signTypedData"); } - now() { - return Math.floor(Date.now() / 1e3); +}; +_VoidSigner_instances = new WeakSet(); +throwUnsupported_fn = function(suffix, operation) { + assert(false, `VoidSigner cannot sign ${suffix}`, "UNSUPPORTED_OPERATION", { operation }); +}; +let VoidSigner = _VoidSigner; +const shown = /* @__PURE__ */ new Set(); +function showThrottleMessage(service) { + if (shown.has(service)) { + return; } - get expiration() { - var _this$settings$metada; - return Math.max((_this$settings$metada = this.settings.metadata.expiration) != null ? _this$settings$metada : DEFAULT_SESSION_EXPIRATION$1, 120); + shown.add(service); + console.log("========= NOTICE ========="); + console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`); + console.log(""); + console.log("The default API keys for each service are provided as a highly-throttled,"); + console.log("community resource for low-traffic projects and early prototyping."); + console.log(""); + console.log("While your application will continue to function, we highly recommended"); + console.log("signing up for your own API keys to improve performance, increase your"); + console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."); + console.log(""); + console.log("For more details: https://docs.ethers.org/api-keys/"); + console.log("=========================="); +} +function copy$1(obj) { + return JSON.parse(JSON.stringify(obj)); +} +class FilterIdSubscriber { + /** + * Creates a new **FilterIdSubscriber** which will used [[_subscribe]] + * and [[_emitResults]] to setup the subscription and provide the event + * to the %%provider%%. + */ + constructor(provider2) { + __privateAdd(this, _FilterIdSubscriber_instances); + __privateAdd(this, _provider4); + __privateAdd(this, _filterIdPromise); + __privateAdd(this, _poller3); + __privateAdd(this, _running3); + __privateAdd(this, _network); + __privateAdd(this, _hault); + __privateSet(this, _provider4, provider2); + __privateSet(this, _filterIdPromise, null); + __privateSet(this, _poller3, __privateMethod(this, _FilterIdSubscriber_instances, poll_fn3).bind(this)); + __privateSet(this, _running3, false); + __privateSet(this, _network, null); + __privateSet(this, _hault, false); } - onAuth(cb2) { - this.onAuthCallbacks.push(cb2); - return () => this.onAuthCallbacks = this.onAuthCallbacks.filter((c2) => c2 !== cb2); + /** + * Sub-classes **must** override this to begin the subscription. + */ + _subscribe(provider2) { + throw new Error("subclasses must override this"); } - async dump() { - if (!this.status.jwt) return { - metadata: this.settings.metadata - }; - return { - jwt: { - token: await this.status.jwt.token, - expiration: this.status.jwt.expiration - }, - metadata: this.status.metadata - }; + /** + * Sub-classes **must** override this handle the events. + */ + _emitResults(provider2, result) { + throw new Error("subclasses must override this"); } - auth(maxTries = 5) { - var _this = this; - if (this._initialAuthRequest) return this._initialAuthRequest; - this._initialAuthRequest = async function() { - const url = _this.settings.sequenceApiUrl; - if (!url) throw Error("No sequence api url"); - let jwtAuth; - for (let i = 1; ; i++) { - try { - jwtAuth = (await _this.getJWT(true)).token; - break; - } catch (error) { - if (i === maxTries) { - console.error(`couldn't authenticate after ${maxTries} attempts`, error); - throw error; - } - } - } - return new SequenceAPIClient(url, void 0, jwtAuth); - }(); - return this._initialAuthRequest; + /** + * Sub-classes **must** override this handle recovery on errors. + */ + _recover(provider2) { + throw new Error("subclasses must override this"); } - async getJWT(tryAuth) { - var _this2 = this; - const url = this.settings.sequenceApiUrl; - if (!url) throw Error("No sequence api url"); - if (this.status.jwt) { - const _jwt = this.status.jwt; - const _token = await _jwt.token; - if (this.now() < _jwt.expiration) { - return { - token: _token, - expiration: _jwt.expiration - }; - } - this.status.jwt = void 0; - } - if (!tryAuth) { - throw new Error("no auth token in memory"); + start() { + if (__privateGet(this, _running3)) { + return; } - const proofStringKey = this.getProofStringKey(); - const { - proofString, - expiration - } = this.getProofString(proofStringKey); - const jwt = { - token: proofString.then(async function(proofString2) { - const api2 = new SequenceAPIClient(url); - const authResp = await api2.getAuthToken({ - ewtString: proofString2 - }); - if ((authResp == null ? void 0 : authResp.status) === true && authResp.jwtToken.length !== 0) { - return authResp.jwtToken; - } else { - if (!await _this2.isProofStringValid(proofString2)) { - _this2.proofStrings.delete(proofStringKey); - } - throw new Error("no auth token from server"); - } - }).catch((reason) => { - this.status.jwt = void 0; - throw reason; - }), - expiration - }; - this.status.jwt = jwt; - jwt.token.then((token2) => { - this.onAuthCallbacks.forEach((cb2) => { - try { - cb2({ - status: "fulfilled", - value: token2 - }); - } catch (_unused) { - } - }); - }).catch((reason) => { - this.onAuthCallbacks.forEach((cb2) => { - try { - cb2({ - status: "rejected", - reason - }); - } catch (_unused2) { - } - }); - }); - const token = await jwt.token; - return { - token, - expiration - }; - } - getProofStringKey() { - return `${this.account.address} - ${this.settings.metadata.name}`; + __privateSet(this, _running3, true); + __privateMethod(this, _FilterIdSubscriber_instances, poll_fn3).call(this, -2); } - async isProofStringValid(proofString) { - try { - const ethAuth = new ETHAuth(); - const chainId = BigInt(this.settings.sequenceApiChainId); - const found = findNetworkConfig(this.account.networks, chainId); - if (!found) { - throw Error("No network found"); - } - ethAuth.chainId = Number(chainId); - const network2 = new Network(found.name, chainId); - ethAuth.provider = new JsonRpcProvider$1(getFetchRequest(found.rpcUrl, this.projectAccessKey), network2, { - staticNetwork: network2 - }); - await ethAuth.decodeProof(proofString); - return true; - } catch (_unused3) { - return false; + stop() { + if (!__privateGet(this, _running3)) { + return; } + __privateSet(this, _running3, false); + __privateSet(this, _hault, true); + __privateMethod(this, _FilterIdSubscriber_instances, teardown_fn).call(this); + __privateGet(this, _provider4).off("block", __privateGet(this, _poller3)); } - async getAPIClient(tryAuth = true) { - if (!this.apiClient) { - const url = this.settings.sequenceApiUrl; - if (!url) throw Error("No sequence api url"); - const jwtAuth = (await this.getJWT(tryAuth)).token; - this.apiClient = new SequenceAPIClient(url, void 0, jwtAuth); + pause(dropWhilePaused) { + if (dropWhilePaused) { + __privateMethod(this, _FilterIdSubscriber_instances, teardown_fn).call(this); } - return this.apiClient; + __privateGet(this, _provider4).off("block", __privateGet(this, _poller3)); } - async getMetadataClient(tryAuth = true) { - if (!this.metadataClient) { - const jwtAuth = (await this.getJWT(tryAuth)).token; - this.metadataClient = new SequenceMetadata(this.settings.sequenceMetadataUrl, void 0, jwtAuth); - } - return this.metadataClient; + resume() { + this.start(); } - async getIndexerClient(chainId, tryAuth = true) { - const network2 = findNetworkConfig(this.account.networks, chainId); - if (!network2) { - throw Error(`No network for chain ${chainId}`); +} +_provider4 = new WeakMap(); +_filterIdPromise = new WeakMap(); +_poller3 = new WeakMap(); +_running3 = new WeakMap(); +_network = new WeakMap(); +_hault = new WeakMap(); +_FilterIdSubscriber_instances = new WeakSet(); +poll_fn3 = async function(blockNumber) { + try { + if (__privateGet(this, _filterIdPromise) == null) { + __privateSet(this, _filterIdPromise, this._subscribe(__privateGet(this, _provider4))); } - if (!this.indexerClients.has(network2.chainId)) { - if (network2.indexer) { - this.indexerClients.set(network2.chainId, network2.indexer); - } else if (network2.indexerUrl) { - const jwtAuth = (await this.getJWT(tryAuth)).token; - this.indexerClients.set(network2.chainId, new SequenceIndexer(network2.indexerUrl, void 0, jwtAuth)); - } else { - throw Error(`No indexer url for chain ${chainId}`); + let filterId = null; + try { + filterId = await __privateGet(this, _filterIdPromise); + } catch (error) { + if (!isError(error, "UNSUPPORTED_OPERATION") || error.operation !== "eth_newFilter") { + throw error; } } - return this.indexerClients.get(network2.chainId); + if (filterId == null) { + __privateSet(this, _filterIdPromise, null); + __privateGet(this, _provider4)._recoverSubscriber(this, this._recover(__privateGet(this, _provider4))); + return; + } + const network2 = await __privateGet(this, _provider4).getNetwork(); + if (!__privateGet(this, _network)) { + __privateSet(this, _network, network2); + } + if (__privateGet(this, _network).chainId !== network2.chainId) { + throw new Error("chaid changed"); + } + if (__privateGet(this, _hault)) { + return; + } + const result = await __privateGet(this, _provider4).send("eth_getFilterChanges", [filterId]); + await this._emitResults(__privateGet(this, _provider4), result); + } catch (error) { + console.log("@TODO", error); } - getProofString(key) { - if (this.proofStrings.has(key)) { - const _proofString = this.proofStrings.get(key); - if (this.now() < _proofString.expiration) { - return _proofString; + __privateGet(this, _provider4).once("block", __privateGet(this, _poller3)); +}; +teardown_fn = function() { + const filterIdPromise = __privateGet(this, _filterIdPromise); + if (filterIdPromise) { + __privateSet(this, _filterIdPromise, null); + filterIdPromise.then((filterId) => { + if (__privateGet(this, _provider4).destroyed) { + return; } - this.proofStrings.delete(key); - } - const proof = new Proof({ - address: this.account.address + __privateGet(this, _provider4).send("eth_uninstallFilter", [filterId]); }); - proof.claims.app = this.settings.metadata.name; - if (typeof window === "object") { - proof.claims.ogn = window.location.origin; + } +}; +class FilterIdEventSubscriber extends FilterIdSubscriber { + /** + * Creates a new **FilterIdEventSubscriber** attached to %%provider%% + * listening for %%filter%%. + */ + constructor(provider2, filter2) { + super(provider2); + __privateAdd(this, _event); + __privateSet(this, _event, copy$1(filter2)); + } + _recover(provider2) { + return new PollingEventSubscriber(provider2, __privateGet(this, _event)); + } + async _subscribe(provider2) { + const filterId = await provider2.send("eth_newFilter", [__privateGet(this, _event)]); + return filterId; + } + async _emitResults(provider2, results2) { + for (const result of results2) { + provider2.emit(__privateGet(this, _event), provider2._wrapLog(result, provider2._network)); } - proof.setExpiryIn(this.expiration); - const ethAuth = new ETHAuth(); - const chainId = BigInt(this.settings.sequenceApiChainId); - const found = findNetworkConfig(this.account.networks, chainId); - if (!found) { - throw Error("No network found"); + } +} +_event = new WeakMap(); +class FilterIdPendingSubscriber extends FilterIdSubscriber { + async _subscribe(provider2) { + return await provider2.send("eth_newPendingTransactionFilter", []); + } + async _emitResults(provider2, results2) { + for (const result of results2) { + provider2.emit("pending", result); } - ethAuth.chainId = Number(chainId); - const network2 = new Network(found.name, chainId); - ethAuth.provider = new JsonRpcProvider$1(getFetchRequest(found.rpcUrl, this.projectAccessKey), network2, { - staticNetwork: network2 - }); - const expiration = this.now() + this.expiration - EXPIRATION_JWT_MARGIN; - const proofString = { - proofString: Promise.resolve( - // NOTICE: TODO: Here we ask the account to sign the message - // using whatever configuration we have ON-CHAIN, this means - // that the account will still use the v1 wallet, even if the migration - // was signed. - // - // This works for Sequence webapp v1 -> v2 because all v1 configurations share the same formula - // (torus + guard), but if we ever decide to allow cross-device login, then it will not work, because - // those other signers may not be part of the configuration. - // - this.account.signDigest(proof.messageDigest(), this.settings.sequenceApiChainId, true, "eip6492") - ).then((s2) => { - proof.signature = s2; - return ethAuth.encodeProof(proof, true); - }).catch((reason) => { - this.proofStrings.delete(key); - throw reason; - }), - expiration - }; - this.proofStrings.set(key, proofString); - return proofString; } } -const signAuthorization = async (signer2, chainId, options) => { - const address = getAddress$1(await signer2.getAddress()); - if (!address || address === "" || address === "0x") { - throw ErrAccountIsRequired; +const Primitive$1 = "bigint,boolean,function,number,string,symbol".split(/,/g); +function deepCopy(value) { + if (value == null || Primitive$1.indexOf(typeof value) >= 0) { + return value; } - const proof = new Proof(); - proof.address = address; - if (!options || !options.app || options.app === "") { - throw new AuthError("authorization options requires app to be set"); + if (typeof value.getAddress === "function") { + return value; } - proof.claims.app = options.app; - proof.claims.ogn = options.origin; - proof.claims.n = options.nonce; - proof.setExpiryIn(options.expiry ? Math.max(options.expiry, 200) : DEFAULT_SESSION_EXPIRATION$1); - const typedData = proof.messageTypedData(); - const chainIdNumber = toChainIdNumber(chainId); - proof.signature = await (signer2 instanceof Account ? ( - // Account can sign EIP-6492 signatures, so it doesn't require deploying the wallet - signer2.signTypedData(typedData.domain, typedData.types, typedData.message, chainIdNumber, "eip6492") - ) : signer2.signTypedData(typedData.domain, typedData.types, typedData.message, chainIdNumber)); - const ethAuth = new ETHAuth(); - const proofString = await ethAuth.encodeProof(proof, true); - return { - typedData, - proofString - }; -}; -class AuthError extends Error { - constructor(message) { - super(message); - this.name = "AuthError"; + if (Array.isArray(value)) { + return value.map(deepCopy); } + if (typeof value === "object") { + return Object.keys(value).reduce((accum, key) => { + accum[key] = value[key]; + return accum; + }, {}); + } + throw new Error(`should not happen: ${value} (${typeof value})`); } -const ErrAccountIsRequired = new AuthError("auth error: account address is empty"); -function _extends$4() { - _extends$4 = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends$4.apply(this, arguments); +function stall$3(duration) { + return new Promise((resolve) => { + setTimeout(resolve, duration); + }); } -function isSessionDumpV1(obj) { - return obj.config && obj.metadata && obj.version === void 0; +function getLowerCase(value) { + if (value) { + return value.toLowerCase(); + } + return value; } -function isSessionDumpV2(obj) { - return obj.version === 2 && obj.address; +function isPollable(value) { + return value && typeof value.pollingInterval === "number"; } -const CRITICAL_CHAINS = [1, 137]; -const SessionSettingsDefault = { - contexts: index$1$2.context.defaultContexts, - networks: allNetworks, - tracker: new index$3.remote.RemoteConfigTracker("https://sessions.sequence.app") +const defaultOptions = { + polling: false, + staticNetwork: null, + batchStallTime: 10, + batchMaxSize: 1 << 20, + batchMaxCount: 100, + cacheTimeout: 250, + pollingInterval: 4e3 }; -class Session { - constructor(networks2, contexts, account2, services) { - this.networks = networks2; - this.contexts = contexts; - this.account = account2; - this.services = services; +class JsonRpcSigner extends AbstractSigner { + constructor(provider2, address) { + super(provider2); + __publicField(this, "address"); + address = getAddress(address); + defineProperties$1(this, { address }); } - async dump() { - const base = { - version: 2, - address: this.account.address - }; - if (this.services) { - return _extends$4({}, base, await this.services.dump()); - } - return base; + connect(provider2) { + assert(false, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", { + operation: "signer.connect" + }); } - static async singleSigner(args) { - let { - signer: signer2 - } = args; - if (typeof signer2 === "string") { - signer2 = new Wallet$1(signer2); + async getAddress() { + return this.address; + } + // JSON-RPC will automatially fill in nonce, etc. so we just check from + async populateTransaction(tx) { + return await this.populateCall(tx); + } + // Returns just the hash of the transaction after sent, which is what + // the bare JSON-RPC API does; + async sendUncheckedTransaction(_tx) { + const tx = deepCopy(_tx); + const promises = []; + if (tx.from) { + const _from = tx.from; + promises.push((async () => { + const from = await resolveAddress(_from, this.provider); + assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + })()); + } else { + tx.from = this.address; } - const orchestrator = new Orchestrator([signer2]); - const referenceSigner = await signer2.getAddress(); - const threshold = 1; - const addSigners = [{ - weight: 1, - address: referenceSigner - }]; - const selectWallet = args.selectWallet || async function(wallets) { - var _args$settings$tracke, _args$settings; - if (wallets.length === 0) return void 0; - const tracker2 = (_args$settings$tracke = (_args$settings = args.settings) == null ? void 0 : _args$settings.tracker) != null ? _args$settings$tracke : SessionSettingsDefault.tracker; - const configs = await Promise.all(wallets.map(async function(wallet) { - const imageHash2 = await tracker2.imageHashOfCounterfactualWallet({ - wallet - }); - return { - wallet, - config: imageHash2 && await tracker2.configOfImageHash({ - imageHash: imageHash2.imageHash - }) - }; - })); - for (const config2 of configs) { - if (!config2.config) { - continue; - } - const coder = index$6.genericCoderFor(config2.config.version); - const signers = coder.config.signersOf(config2.config); - if (signers.length === 1 && signers[0].address === referenceSigner) { - return config2.wallet; - } - } - return void 0; - }; - return Session.open(_extends$4({}, args, { - orchestrator, - referenceSigner, - threshold, - addSigners, - selectWallet - })); + if (tx.gasLimit == null) { + promises.push((async () => { + tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address }); + })()); + } + if (tx.to != null) { + const _to2 = tx.to; + promises.push((async () => { + tx.to = await resolveAddress(_to2, this.provider); + })()); + } + if (promises.length) { + await Promise.all(promises); + } + const hexTx = this.provider.getRpcTransaction(tx); + return this.provider.send("eth_sendTransaction", [hexTx]); } - static async open(args) { - var _findNetworkConfig$ch, _findNetworkConfig, _settings$services$se, _settings$services, _networks$; - const { - referenceSigner, - threshold, - addSigners, - selectWallet, - onAccountAddress, - settings, - editConfigOnMigration, - onMigration, - orchestrator, - projectAccessKey: projectAccessKey2 - } = args; - const { - contexts, - networks: networks2, - tracker: tracker2, - services - } = _extends$4({}, SessionSettingsDefault, settings); - const referenceChainId = (_findNetworkConfig$ch = (_findNetworkConfig = findNetworkConfig(networks2, (_settings$services$se = settings == null || (_settings$services = settings.services) == null ? void 0 : _settings$services.sequenceApiChainId) != null ? _settings$services$se : ChainId.MAINNET)) == null ? void 0 : _findNetworkConfig.chainId) != null ? _findNetworkConfig$ch : (_networks$ = networks2[0]) == null ? void 0 : _networks$.chainId; - if (!referenceChainId) throw Error("No reference chain found"); - const foundWallets = await tracker2.walletsOfSigner({ - signer: referenceSigner - }); - const selectedWallet = await selectWallet(foundWallets.map((w2) => w2.wallet)); - let account2; - if (selectedWallet) { - onAccountAddress == null || onAccountAddress(selectedWallet); - account2 = new Account({ - address: selectedWallet, - tracker: tracker2, - networks: networks2, - contexts, - orchestrator, - projectAccessKey: projectAccessKey2 - }); - if (addSigners && addSigners.length > 0) { - let status = await account2.status(referenceChainId); - if (status.original.version !== status.version || account2.version !== status.version) { - const { - migratedAllChains: isFullyMigrated, - failedChains - } = await account2.isMigratedAllChains(); - if (failedChains.some((c2) => CRITICAL_CHAINS.includes(c2))) { - throw Error(`Failed to fetch account status on ${failedChains.join(", ")}`); + async sendTransaction(tx) { + const blockNumber = await this.provider.getBlockNumber(); + const hash2 = await this.sendUncheckedTransaction(tx); + return await new Promise((resolve, reject) => { + const timeouts = [1e3, 100]; + let invalids = 0; + const checkTx = async () => { + try { + const tx2 = await this.provider.getTransaction(hash2); + if (tx2 != null) { + resolve(tx2.replaceableTransaction(blockNumber)); + return; } - if (!isFullyMigrated) { - if (onMigration && !await onMigration(account2)) { - throw Error("Migration cancelled, cannot open session"); + } catch (error) { + if (isError(error, "CANCELLED") || isError(error, "BAD_DATA") || isError(error, "NETWORK_ERROR")) { + if (error.info == null) { + error.info = {}; } - const { - failedChains: _failedChains - } = await account2.signAllMigrations(editConfigOnMigration || ((c2) => c2)); - if (_failedChains.some((c2) => CRITICAL_CHAINS.includes(c2))) { - throw Error(`Failed to sign migrations on ${_failedChains.join(", ")}`); + error.info.sendTransactionHash = hash2; + reject(error); + return; + } + if (isError(error, "INVALID_ARGUMENT")) { + invalids++; + if (error.info == null) { + error.info = {}; } - if (index$3.isDedupedTracker(tracker2)) { - tracker2.invalidateCache(); + error.info.sendTransactionHash = hash2; + if (invalids > 10) { + reject(error); + return; } - let isFullyMigrated2; - [isFullyMigrated2, status] = await Promise.all([account2.isMigratedAllChains().then((r2) => r2.migratedAllChains), account2.status(referenceChainId)]); - if (!isFullyMigrated2) throw Error("Failed to migrate account"); + } + this.provider.emit("error", makeError("failed to fetch transation after sending (will try again)", "UNKNOWN_ERROR", { error })); + } + this.provider._setTimeout(() => { + checkTx(); + }, timeouts.pop() || 4e3); + }; + checkTx(); + }); + } + async signTransaction(_tx) { + const tx = deepCopy(_tx); + if (tx.from) { + const from = await resolveAddress(tx.from, this.provider); + assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + } else { + tx.from = this.address; + } + const hexTx = this.provider.getRpcTransaction(tx); + return await this.provider.send("eth_signTransaction", [hexTx]); + } + async signMessage(_message) { + const message = typeof _message === "string" ? toUtf8Bytes(_message) : _message; + return await this.provider.send("personal_sign", [ + hexlify(message), + this.address.toLowerCase() + ]); + } + async signTypedData(domain2, types2, _value2) { + const value = deepCopy(_value2); + const populated = await TypedDataEncoder.resolveNames(domain2, types2, value, async (value2) => { + const address = await resolveAddress(value2); + assertArgument(address != null, "TypedData does not support null address", "value", value2); + return address; + }); + return await this.provider.send("eth_signTypedData_v4", [ + this.address.toLowerCase(), + JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types2, populated.value)) + ]); + } + async unlock(password) { + return this.provider.send("personal_unlockAccount", [ + this.address.toLowerCase(), + password, + null + ]); + } + // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign + async _legacySignMessage(_message) { + const message = typeof _message === "string" ? toUtf8Bytes(_message) : _message; + return await this.provider.send("eth_sign", [ + this.address.toLowerCase(), + hexlify(message) + ]); + } +} +class JsonRpcApiProvider extends AbstractProvider { + constructor(network2, options) { + super(network2, options); + __privateAdd(this, _JsonRpcApiProvider_instances); + __privateAdd(this, _options3); + // The next ID to use for the JSON-RPC ID field + __privateAdd(this, _nextId2); + // Payloads are queued and triggered in batches using the drainTimer + __privateAdd(this, _payloads); + __privateAdd(this, _drainTimer); + __privateAdd(this, _notReady); + __privateAdd(this, _network2); + __privateAdd(this, _pendingDetectNetwork); + __privateSet(this, _nextId2, 1); + __privateSet(this, _options3, Object.assign({}, defaultOptions, options || {})); + __privateSet(this, _payloads, []); + __privateSet(this, _drainTimer, null); + __privateSet(this, _network2, null); + __privateSet(this, _pendingDetectNetwork, null); + { + let resolve = null; + const promise = new Promise((_resolve) => { + resolve = _resolve; + }); + __privateSet(this, _notReady, { promise, resolve }); + } + const staticNetwork = this._getOption("staticNetwork"); + if (typeof staticNetwork === "boolean") { + assertArgument(!staticNetwork || network2 !== "any", "staticNetwork cannot be used on special network 'any'", "options", options); + if (staticNetwork && network2 != null) { + __privateSet(this, _network2, Network.from(network2)); + } + } else if (staticNetwork) { + assertArgument(network2 == null || staticNetwork.matches(network2), "staticNetwork MUST match network object", "options", options); + __privateSet(this, _network2, staticNetwork); + } + } + /** + * Returns the value associated with the option %%key%%. + * + * Sub-classes can use this to inquire about configuration options. + */ + _getOption(key) { + return __privateGet(this, _options3)[key]; + } + /** + * Gets the [[Network]] this provider has committed to. On each call, the network + * is detected, and if it has changed, the call will reject. + */ + get _network() { + assert(__privateGet(this, _network2), "network is not available yet", "NETWORK_ERROR"); + return __privateGet(this, _network2); + } + /** + * Resolves to the non-normalized value by performing %%req%%. + * + * Sub-classes may override this to modify behavior of actions, + * and should generally call ``super._perform`` as a fallback. + */ + async _perform(req) { + if (req.method === "call" || req.method === "estimateGas") { + let tx = req.transaction; + if (tx && tx.type != null && getBigInt(tx.type)) { + if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { + const feeData = await this.getFeeData(); + if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { + req = Object.assign({}, req, { + transaction: Object.assign({}, tx, { type: void 0 }) + }); } } - if (status.onChain.version !== status.version) { - await account2.doBootstrap(referenceChainId, void 0, status); - } - const prevConfig = status.config; - const nextConfig = account2.coders.config.editConfig(prevConfig, { - add: addSigners, - threshold - }); - if (account2.coders.config.imageHashOf(prevConfig) !== account2.coders.config.imageHashOf(nextConfig)) { - const newConfig = account2.coders.config.editConfig(nextConfig, { - checkpoint: account2.coders.config.checkpointOf(prevConfig) + 1n - }); - await account2.updateConfig(newConfig); - } } - } else { - if (!addSigners || addSigners.length === 0) { - throw Error("Cannot create new account without signers"); + } + const request = this.getRpcRequest(req); + if (request != null) { + return await this.send(request.method, request.args); + } + return super._perform(req); + } + /** + * Sub-classes may override this; it detects the *actual* network that + * we are **currently** connected to. + * + * Keep in mind that [[send]] may only be used once [[ready]], otherwise the + * _send primitive must be used instead. + */ + async _detectNetwork() { + const network2 = this._getOption("staticNetwork"); + if (network2) { + if (network2 === true) { + if (__privateGet(this, _network2)) { + return __privateGet(this, _network2); + } + } else { + return network2; } - if (!threshold) { - throw Error("Cannot create new account without threshold"); + } + if (__privateGet(this, _pendingDetectNetwork)) { + return await __privateGet(this, _pendingDetectNetwork); + } + if (this.ready) { + __privateSet(this, _pendingDetectNetwork, (async () => { + try { + const result = Network.from(getBigInt(await this.send("eth_chainId", []))); + __privateSet(this, _pendingDetectNetwork, null); + return result; + } catch (error) { + __privateSet(this, _pendingDetectNetwork, null); + throw error; + } + })()); + return await __privateGet(this, _pendingDetectNetwork); + } + __privateSet(this, _pendingDetectNetwork, (async () => { + const payload = { + id: __privateWrapper(this, _nextId2)._++, + method: "eth_chainId", + params: [], + jsonrpc: "2.0" + }; + this.emit("debug", { action: "sendRpcPayload", payload }); + let result; + try { + result = (await this._send(payload))[0]; + __privateSet(this, _pendingDetectNetwork, null); + } catch (error) { + __privateSet(this, _pendingDetectNetwork, null); + this.emit("debug", { action: "receiveRpcError", error }); + throw error; } - account2 = await Account.new({ - config: { - threshold, - checkpoint: 0, - signers: addSigners - }, - tracker: tracker2, - contexts, - orchestrator, - networks: networks2, - projectAccessKey: projectAccessKey2 - }); - onAccountAddress == null || onAccountAddress(account2.address); - await account2.publishWitness(); - const _foundWallets = await tracker2.walletsOfSigner({ - signer: referenceSigner, - noCache: true - }); - if (!_foundWallets.some((w2) => w2.wallet === account2.address)) { - throw Error("Account not found on tracker"); + this.emit("debug", { action: "receiveRpcResult", result }); + if ("result" in result) { + return Network.from(getBigInt(result.result)); } + throw this.getRpcError(payload, result); + })()); + return await __privateGet(this, _pendingDetectNetwork); + } + /** + * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls + * will be passed to [[_send]] from [[send]]. If it is overridden, then + * ``super._start()`` **MUST** be called. + * + * Calling it multiple times is safe and has no effect. + */ + _start() { + if (__privateGet(this, _notReady) == null || __privateGet(this, _notReady).resolve == null) { + return; } - let servicesObj; - if (services) { - servicesObj = new Services(account2, services); - servicesObj.auth(); - servicesObj.onAuth((result) => { - if (result.status === "fulfilled") { - account2.setJwt(result.value); + __privateGet(this, _notReady).resolve(); + __privateSet(this, _notReady, null); + (async () => { + while (__privateGet(this, _network2) == null && !this.destroyed) { + try { + __privateSet(this, _network2, await this._detectNetwork()); + } catch (error) { + if (this.destroyed) { + break; + } + console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"); + this.emit("error", makeError("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error } })); + await stall$3(1e3); } - }); + } + __privateMethod(this, _JsonRpcApiProvider_instances, scheduleDrain_fn).call(this); + })(); + } + /** + * Resolves once the [[_start]] has been called. This can be used in + * sub-classes to defer sending data until the connection has been + * established. + */ + async _waitUntilReady() { + if (__privateGet(this, _notReady) == null) { + return; } - return new Session(networks2, contexts, account2, servicesObj); + return await __privateGet(this, _notReady).promise; } - static async load(args) { - const { - dump, - settings, - editConfigOnMigration, - onMigration, - orchestrator - } = args; - const { - contexts, - networks: networks2, - tracker: tracker2, - services - } = _extends$4({}, SessionSettingsDefault, settings); - let account2; - if (isSessionDumpV1(dump)) { - var _dump$jwt$expiration, _dump$jwt, _dump$jwt2; - const oldAddress = dump.config.address || index$1$2.context.addressOf(contexts[1], v1.config.ConfigCoder.imageHashOf(_extends$4({}, dump.config, { - version: 1 - }))); - const jwtExpired = ((_dump$jwt$expiration = (_dump$jwt = dump.jwt) == null ? void 0 : _dump$jwt.expiration) != null ? _dump$jwt$expiration : 0) < Math.floor(Date.now() / 1e3); - account2 = new Account({ - address: oldAddress, - tracker: tracker2, - networks: networks2, - contexts, - orchestrator, - jwt: jwtExpired ? void 0 : (_dump$jwt2 = dump.jwt) == null ? void 0 : _dump$jwt2.token - }); - if (!await account2.isMigratedAllChains().then((r2) => r2.migratedAllChains)) { - if (onMigration && !await onMigration(account2)) { - throw Error("Migration cancelled, cannot open session"); - } - console.log("Migrating account..."); - await account2.signAllMigrations(editConfigOnMigration); - if (!await account2.isMigratedAllChains().then((r2) => r2.migratedAllChains)) throw Error("Failed to migrate account"); + /** + * Return a Subscriber that will manage the %%sub%%. + * + * Sub-classes may override this to modify the behavior of + * subscription management. + */ + _getSubscriber(sub) { + if (sub.type === "pending") { + return new FilterIdPendingSubscriber(this); + } + if (sub.type === "event") { + if (this._getOption("polling")) { + return new PollingEventSubscriber(this, sub.filter); } - } else if (isSessionDumpV2(dump)) { - var _dump$jwt$expiration2, _dump$jwt3, _dump$jwt4; - const jwtExpired = ((_dump$jwt$expiration2 = (_dump$jwt3 = dump.jwt) == null ? void 0 : _dump$jwt3.expiration) != null ? _dump$jwt$expiration2 : 0) < Math.floor(Date.now() / 1e3); - account2 = new Account({ - address: dump.address, - tracker: tracker2, - networks: networks2, - contexts, - orchestrator, - jwt: jwtExpired ? void 0 : (_dump$jwt4 = dump.jwt) == null ? void 0 : _dump$jwt4.token - }); - } else { - throw Error("Invalid dump format"); + return new FilterIdEventSubscriber(this, sub.filter); } - let servicesObj; - if (services) { - var _dump$jwt$expiration3; - servicesObj = new Services(account2, services, dump.jwt && { - jwt: { - token: Promise.resolve(dump.jwt.token), - expiration: (_dump$jwt$expiration3 = dump.jwt.expiration) != null ? _dump$jwt$expiration3 : jwtDecodeClaims(dump.jwt.token).exp - }, - metadata: dump.metadata - }); + if (sub.type === "orphan" && sub.filter.orphan === "drop-log") { + return new UnmanagedSubscriber("orphan"); } - return new Session(networks2, contexts, account2, servicesObj); + return super._getSubscriber(sub); } -} -const ValidateSequenceWalletProof = (readerFor, tracker2, context2) => { - return async (_provider6, chainId, proof) => { - const digest = proof.messageDigest(); - const isValid2 = await readerFor(chainId).isValidSignature(proof.address, digest, proof.signature); - return { - isValid: isValid2 - }; - }; -}; -const auth$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - AuthError, - CRITICAL_CHAINS, - ErrAccountIsRequired, - Session, - SessionSettingsDefault, - ValidateSequenceWalletProof, - isSessionDumpV1, - isSessionDumpV2, - signAuthorization -}, Symbol.toStringTag, { value: "Module" })); -function _extends$3() { - _extends$3 = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } + /** + * Returns true only if the [[_start]] has been called. + */ + get ready() { + return __privateGet(this, _notReady) == null; + } + /** + * Returns %%tx%% as a normalized JSON-RPC transaction request, + * which has all values hexlified and any numeric values converted + * to Quantity values. + */ + getRpcTransaction(tx) { + const result = {}; + ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach((key) => { + if (tx[key] == null) { + return; + } + let dstKey = key; + if (key === "gasLimit") { + dstKey = "gas"; + } + result[dstKey] = toQuantity(getBigInt(tx[key], `tx.${key}`)); + }); + ["from", "to", "data"].forEach((key) => { + if (tx[key] == null) { + return; } + result[key] = hexlify(tx[key]); + }); + if (tx.accessList) { + result["accessList"] = accessListify(tx.accessList); } - return target; - }; - return _extends$3.apply(this, arguments); -} -class Guard { - constructor(hostname, fetch2) { - this.hostname = void 0; - this.fetch = void 0; - this.path = "/rpc/Guard/"; - this.ping = (headers, signal) => { - return this.fetch(this.url("Ping"), createHTTPRequest$2({}, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.version = (headers, signal) => { - return this.fetch(this.url("Version"), createHTTPRequest$2({}, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - version: _data6.version - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.runtimeStatus = (headers, signal) => { - return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$2({}, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.getSignerConfig = (args, headers, signal) => { - return this.fetch(this.url("GetSignerConfig"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - signerConfig: _data6.signerConfig - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.sign = (args, headers, signal) => { - return this.fetch(this.url("Sign"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - sig: _data6.sig - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.signWith = (args, headers, signal) => { - return this.fetch(this.url("SignWith"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - sig: _data6.sig - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.patch = (args, headers, signal) => { - return this.fetch(this.url("Patch"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - txs: _data6.txs - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.authMethods = (args, headers, signal) => { - return this.fetch(this.url("AuthMethods"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - methods: _data6.methods, - active: _data6.active - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.setPIN = (args, headers, signal) => { - return this.fetch(this.url("SetPIN"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.resetPIN = (args, headers, signal) => { - return this.fetch(this.url("ResetPIN"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.createTOTP = (args, headers, signal) => { - return this.fetch(this.url("CreateTOTP"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - uri: _data6.uri - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.commitTOTP = (args, headers, signal) => { - return this.fetch(this.url("CommitTOTP"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { + if (tx.blobVersionedHashes) { + result["blobVersionedHashes"] = tx.blobVersionedHashes.map((h2) => h2.toLowerCase()); + } + return result; + } + /** + * Returns the request method and arguments required to perform + * %%req%%. + */ + getRpcRequest(req) { + switch (req.method) { + case "chainId": + return { method: "eth_chainId", args: [] }; + case "getBlockNumber": + return { method: "eth_blockNumber", args: [] }; + case "getGasPrice": + return { method: "eth_gasPrice", args: [] }; + case "getPriorityFee": + return { method: "eth_maxPriorityFeePerGas", args: [] }; + case "getBalance": + return { + method: "eth_getBalance", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getTransactionCount": + return { + method: "eth_getTransactionCount", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getCode": + return { + method: "eth_getCode", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getStorage": + return { + method: "eth_getStorageAt", + args: [ + getLowerCase(req.address), + "0x" + req.position.toString(16), + req.blockTag + ] + }; + case "broadcastTransaction": + return { + method: "eth_sendRawTransaction", + args: [req.signedTransaction] + }; + case "getBlock": + if ("blockTag" in req) { return { - codes: _data6.codes + method: "eth_getBlockByNumber", + args: [req.blockTag, !!req.includeTransactions] }; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.resetTOTP = (args, headers, signal) => { - return this.fetch(this.url("ResetTOTP"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.reset2FA = (args, headers, signal) => { - return this.fetch(this.url("Reset2FA"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return {}; - }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); - }); - }; - this.recoveryCodes = (args, headers, signal) => { - return this.fetch(this.url("RecoveryCodes"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { + } else if ("blockHash" in req) { return { - codes: _data6.codes + method: "eth_getBlockByHash", + args: [req.blockHash, !!req.includeTransactions] }; + } + break; + case "getTransaction": + return { + method: "eth_getTransactionByHash", + args: [req.hash] + }; + case "getTransactionReceipt": + return { + method: "eth_getTransactionReceipt", + args: [req.hash] + }; + case "call": + return { + method: "eth_call", + args: [this.getRpcTransaction(req.transaction), req.blockTag] + }; + case "estimateGas": { + return { + method: "eth_estimateGas", + args: [this.getRpcTransaction(req.transaction)] + }; + } + case "getLogs": + if (req.filter && req.filter.address != null) { + if (Array.isArray(req.filter.address)) { + req.filter.address = req.filter.address.map(getLowerCase); + } else { + req.filter.address = getLowerCase(req.filter.address); + } + } + return { method: "eth_getLogs", args: [req.filter] }; + } + return null; + } + /** + * Returns an ethers-style Error for the given JSON-RPC error + * %%payload%%, coalescing the various strings and error shapes + * that different nodes return, coercing them into a machine-readable + * standardized error. + */ + getRpcError(payload, _error2) { + const { method } = payload; + const { error } = _error2; + if (method === "eth_estimateGas" && error.message) { + const msg = error.message; + if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) { + return makeError("insufficient funds", "INSUFFICIENT_FUNDS", { + transaction: payload.params[0], + info: { payload, error } }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` - }); + } + } + if (method === "eth_call" || method === "eth_estimateGas") { + const result = spelunkData(error); + const e2 = AbiCoder.getBuiltinCallException(method === "eth_call" ? "call" : "estimateGas", payload.params[0], result ? result.data : null); + e2.info = { error, payload }; + return e2; + } + const message = JSON.stringify(spelunkMessage(error)); + if (typeof error.message === "string" && error.message.match(/user denied|ethers-user-denied/i)) { + const actionMap = { + eth_sign: "signMessage", + personal_sign: "signMessage", + eth_signTypedData_v4: "signTypedData", + eth_signTransaction: "signTransaction", + eth_sendTransaction: "sendTransaction", + eth_requestAccounts: "requestAccess", + wallet_requestAccounts: "requestAccess" + }; + return makeError(`user rejected action`, "ACTION_REJECTED", { + action: actionMap[method] || "unknown", + reason: "rejected", + info: { payload, error } }); - }; - this.resetRecoveryCodes = (args, headers, signal) => { - return this.fetch(this.url("ResetRecoveryCodes"), createHTTPRequest$2(args, headers, signal)).then((res) => { - return buildResponse$2(res).then((_data6) => { - return { - codes: _data6.codes - }; + } + if (method === "eth_sendRawTransaction" || method === "eth_sendTransaction") { + const transaction2 = payload.params[0]; + if (message.match(/insufficient funds|base fee exceeds gas limit/i)) { + return makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction: transaction2, + info: { error } }); - }, (error) => { - throw WebrpcRequestFailedError$2.new({ - cause: `fetch(): ${error.message || ""}` + } + if (message.match(/nonce/i) && message.match(/too low/i)) { + return makeError("nonce has already been used", "NONCE_EXPIRED", { transaction: transaction2, info: { error } }); + } + if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) { + return makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { transaction: transaction2, info: { error } }); + } + if (message.match(/only replay-protected/i)) { + return makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", { + operation: method, + info: { transaction: transaction2, info: { error } } }); + } + } + let unsupported = !!message.match(/the method .* does not exist/i); + if (!unsupported) { + if (error && error.details && error.details.startsWith("Unauthorized method:")) { + unsupported = true; + } + } + if (unsupported) { + return makeError("unsupported operation", "UNSUPPORTED_OPERATION", { + operation: payload.method, + info: { error, payload } }); - }; - this.hostname = hostname; - this.fetch = (input2, init2) => fetch2(input2, init2); + } + return makeError("could not coalesce error", "UNKNOWN_ERROR", { error, payload }); } - url(name2) { - return this.hostname + this.path + name2; + /** + * Requests the %%method%% with %%params%% via the JSON-RPC protocol + * over the underlying channel. This can be used to call methods + * on the backend that do not have a high-level API within the Provider + * API. + * + * This method queues requests according to the batch constraints + * in the options, assigns the request a unique ID. + * + * **Do NOT override** this method in sub-classes; instead + * override [[_send]] or force the options values in the + * call to the constructor to modify this method's behavior. + */ + send(method, params) { + if (this.destroyed) { + return Promise.reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: method })); + } + const id2 = __privateWrapper(this, _nextId2)._++; + const promise = new Promise((resolve, reject) => { + __privateGet(this, _payloads).push({ + resolve, + reject, + payload: { method, params, id: id2, jsonrpc: "2.0" } + }); + }); + __privateMethod(this, _JsonRpcApiProvider_instances, scheduleDrain_fn).call(this); + return promise; } -} -const createHTTPRequest$2 = (body = {}, headers = {}, signal = null) => { - return { - method: "POST", - headers: _extends$3({}, headers, { - "Content-Type": "application/json" - }), - body: JSON.stringify(body || {}), - signal - }; -}; -const buildResponse$2 = (res) => { - return res.text().then((text2) => { - let data; - try { - data = JSON.parse(text2); - } catch (error) { - let message = ""; - if (error instanceof Error) { - message = error.message; + /** + * Resolves to the [[Signer]] account for %%address%% managed by + * the client. + * + * If the %%address%% is a number, it is used as an index in the + * the accounts from [[listAccounts]]. + * + * This can only be used on clients which manage accounts (such as + * Geth with imported account or MetaMask). + * + * Throws if the account doesn't exist. + */ + async getSigner(address) { + if (address == null) { + address = 0; + } + const accountsPromise = this.send("eth_accounts", []); + if (typeof address === "number") { + const accounts2 = await accountsPromise; + if (address >= accounts2.length) { + throw new Error("no such account"); } - throw WebrpcBadResponseError$2.new({ - status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text2}` - }); + return new JsonRpcSigner(this, accounts2[address]); } - if (!res.ok) { - const code2 = typeof data.code === "number" ? data.code : 0; - throw (webrpcErrorByCode$2[code2] || WebrpcError$2).new(data); + const { accounts } = await resolveProperties$1({ + network: this.getNetwork(), + accounts: accountsPromise + }); + address = getAddress(address); + for (const account2 of accounts) { + if (getAddress(account2) === address) { + return new JsonRpcSigner(this, address); + } } - return data; - }); -}; -let WebrpcError$2 = class WebrpcError6 extends Error { - constructor(name2, code2, message, status, cause) { - super(message); - this.name = void 0; - this.code = void 0; - this.message = void 0; - this.status = void 0; - this.cause = void 0; - this.msg = void 0; - this.name = name2 || "WebrpcError"; - this.code = typeof code2 === "number" ? code2 : 0; - this.message = message || `endpoint error ${this.code}`; - this.msg = this.message; - this.status = typeof status === "number" ? status : 0; - this.cause = cause; - Object.setPrototypeOf(this, WebrpcError6.prototype); - } - static new(payload) { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); - } -}; -let WebrpcEndpointError$2 = class WebrpcEndpointError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcEndpointError6.prototype); - } -}; -let WebrpcRequestFailedError$2 = class WebrpcRequestFailedError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcRequestFailedError6.prototype); - } -}; -let WebrpcBadRouteError$2 = class WebrpcBadRouteError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRouteError6.prototype); - } -}; -let WebrpcBadMethodError$2 = class WebrpcBadMethodError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadMethodError6.prototype); - } -}; -let WebrpcBadRequestError$2 = class WebrpcBadRequestError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadRequestError6.prototype); - } -}; -let WebrpcBadResponseError$2 = class WebrpcBadResponseError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcBadResponseError6.prototype); - } -}; -let WebrpcServerPanicError$2 = class WebrpcServerPanicError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcServerPanicError6.prototype); - } -}; -let WebrpcInternalErrorError$2 = class WebrpcInternalErrorError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcInternalErrorError6.prototype); - } -}; -let WebrpcClientDisconnectedError$2 = class WebrpcClientDisconnectedError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcClientDisconnectedError6.prototype); - } -}; -let WebrpcStreamLostError$2 = class WebrpcStreamLostError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamLostError6.prototype); - } -}; -let WebrpcStreamFinishedError$2 = class WebrpcStreamFinishedError6 extends WebrpcError$2 { - constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, WebrpcStreamFinishedError6.prototype); - } -}; -let UnauthorizedError$2 = class UnauthorizedError5 extends WebrpcError$2 { - constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, UnauthorizedError5.prototype); - } -}; -let SessionExpiredError$1 = class SessionExpiredError4 extends WebrpcError$2 { - constructor(name2 = "SessionExpired", code2 = 1002, message = "Session expired", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, SessionExpiredError4.prototype); - } -}; -class AbortedError4 extends WebrpcError$2 { - constructor(name2 = "Aborted", code2 = 1005, message = "Request aborted", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, AbortedError4.prototype); - } -} -class InvalidArgumentError6 extends WebrpcError$2 { - constructor(name2 = "InvalidArgument", code2 = 2001, message = "Invalid argument", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, InvalidArgumentError6.prototype); - } -} -class UnavailableError4 extends WebrpcError$2 { - constructor(name2 = "Unavailable", code2 = 2002, message = "Unavailable resource", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, UnavailableError4.prototype); + throw new Error("invalid account"); } -} -let QueryFailedError$1 = class QueryFailedError5 extends WebrpcError$2 { - constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, QueryFailedError5.prototype); + async listAccounts() { + const accounts = await this.send("eth_accounts", []); + return accounts.map((a2) => new JsonRpcSigner(this, a2)); } -}; -class ValidationFailedError2 extends WebrpcError$2 { - constructor(name2 = "ValidationFailed", code2 = 2004, message = "Validation Failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, ValidationFailedError2.prototype); + destroy() { + if (__privateGet(this, _drainTimer)) { + clearTimeout(__privateGet(this, _drainTimer)); + __privateSet(this, _drainTimer, null); + } + for (const { payload, reject } of __privateGet(this, _payloads)) { + reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method })); + } + __privateSet(this, _payloads, []); + super.destroy(); } } -let NotFoundError$1 = class NotFoundError6 extends WebrpcError$2 { - constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, NotFoundError6.prototype); - } -}; -const webrpcErrorByCode$2 = { - [0]: WebrpcEndpointError$2, - [-1]: WebrpcRequestFailedError$2, - [-2]: WebrpcBadRouteError$2, - [-3]: WebrpcBadMethodError$2, - [-4]: WebrpcBadRequestError$2, - [-5]: WebrpcBadResponseError$2, - [-6]: WebrpcServerPanicError$2, - [-7]: WebrpcInternalErrorError$2, - [-8]: WebrpcClientDisconnectedError$2, - [-9]: WebrpcStreamLostError$2, - [-10]: WebrpcStreamFinishedError$2, - [1e3]: UnauthorizedError$2, - [1002]: SessionExpiredError$1, - [1005]: AbortedError4, - [2001]: InvalidArgumentError6, - [2002]: UnavailableError4, - [2003]: QueryFailedError$1, - [2004]: ValidationFailedError2, - [3e3]: NotFoundError$1 -}; -const fetch$2 = globalThis.fetch; -class GuardSigner { - constructor(address, url, appendSuffix = false) { - this.address = address; - this.url = url; - this.appendSuffix = appendSuffix; - this.guard = void 0; - this.guard = new Guard(url, fetch$2); - } - async getAddress() { - return this.address; - } - async buildDeployTransaction(_metadata) { - return void 0; - } - async predecorateSignedTransactions(_metadata) { - return []; +_options3 = new WeakMap(); +_nextId2 = new WeakMap(); +_payloads = new WeakMap(); +_drainTimer = new WeakMap(); +_notReady = new WeakMap(); +_network2 = new WeakMap(); +_pendingDetectNetwork = new WeakMap(); +_JsonRpcApiProvider_instances = new WeakSet(); +scheduleDrain_fn = function() { + if (__privateGet(this, _drainTimer)) { + return; } - async decorateTransactions(bundle, _metadata) { - return bundle; + const stallTime = this._getOption("batchMaxCount") === 1 ? 0 : this._getOption("batchStallTime"); + __privateSet(this, _drainTimer, setTimeout(() => { + __privateSet(this, _drainTimer, null); + const payloads = __privateGet(this, _payloads); + __privateSet(this, _payloads, []); + while (payloads.length) { + const batch = [payloads.shift()]; + while (payloads.length) { + if (batch.length === __privateGet(this, _options3).batchMaxCount) { + break; + } + batch.push(payloads.shift()); + const bytes2 = JSON.stringify(batch.map((p2) => p2.payload)); + if (bytes2.length > __privateGet(this, _options3).batchMaxSize) { + payloads.unshift(batch.pop()); + break; + } + } + (async () => { + const payload = batch.length === 1 ? batch[0].payload : batch.map((p2) => p2.payload); + this.emit("debug", { action: "sendRpcPayload", payload }); + try { + const result = await this._send(payload); + this.emit("debug", { action: "receiveRpcResult", result }); + for (const { resolve, reject, payload: payload2 } of batch) { + if (this.destroyed) { + reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload2.method })); + continue; + } + const resp = result.filter((r2) => r2.id === payload2.id)[0]; + if (resp == null) { + const error = makeError("missing response for request", "BAD_DATA", { + value: result, + info: { payload: payload2 } + }); + this.emit("error", error); + reject(error); + continue; + } + if ("error" in resp) { + reject(this.getRpcError(payload2, resp)); + continue; + } + resolve(resp.result); + } + } catch (error) { + this.emit("debug", { action: "receiveRpcError", error }); + for (const { reject } of batch) { + reject(error); + } + } + })(); + } + }, stallTime)); +}; +class JsonRpcApiPollingProvider extends JsonRpcApiProvider { + constructor(network2, options) { + super(network2, options); + __privateAdd(this, _pollingInterval); + let pollingInterval = this._getOption("pollingInterval"); + if (pollingInterval == null) { + pollingInterval = defaultOptions.pollingInterval; + } + __privateSet(this, _pollingInterval, pollingInterval); } - async sign(message, metadata2) { - var _metadata$parts; - if (!index$1$2.isWalletSignRequestMetadata(metadata2)) { - throw new Error("expected sequence signature request metadata"); + _getSubscriber(sub) { + const subscriber = super._getSubscriber(sub); + if (isPollable(subscriber)) { + subscriber.pollingInterval = __privateGet(this, _pollingInterval); } - const guardTotpCode = metadata2.guardTotpCode; - const coder = index$6.genericCoderFor(metadata2.config.version); - const { - encoded - } = coder.signature.encodeSigners(metadata2.config, (_metadata$parts = metadata2.parts) != null ? _metadata$parts : /* @__PURE__ */ new Map(), [], metadata2.chainId); - return (await this.guard.signWith({ - signer: this.address, - request: { - msg: hexlify(message), - auxData: this.packMsgAndSig(metadata2.address, metadata2.digest, encoded, metadata2.chainId), - chainId: Number(metadata2.chainId) - }, - token: guardTotpCode ? { - id: AuthMethod.TOTP, - token: guardTotpCode - } : void 0 - })).sig; + return subscriber; } - notifyStatusChange(_id, _status, _metadata) { + /** + * The polling interval (default: 4000 ms) + */ + get pollingInterval() { + return __privateGet(this, _pollingInterval); } - async getAuthMethods(proof) { - let response; - if ("jwt" in proof) { - response = await this.guard.authMethods({}, { - Authorization: `BEARER ${proof.jwt}` - }); - } else { - const signedProof = await signOwnershipProof(proof); - response = await this.guard.authMethods({ - proof: { - wallet: signedProof.walletAddress, - timestamp: signedProof.timestamp.getTime(), - signer: signedProof.signerAddress, - signature: signedProof.signature - } - }); + set pollingInterval(value) { + if (!Number.isInteger(value) || value < 0) { + throw new Error("invalid interval"); } - return _extends$3({}, response, { - methods: response.methods.map(parseAuthMethod) + __privateSet(this, _pollingInterval, value); + this._forEachSubscriber((sub) => { + if (isPollable(sub)) { + sub.pollingInterval = __privateGet(this, _pollingInterval); + } }); } - async setPin(pin, proof) { - const signedProof = await signAuthUpdateProof(proof); - if (pin === void 0) { - await this.guard.resetPIN({ - timestamp: signedProof.timestamp.getTime(), - signature: signedProof.signature - }, { - Authorization: `BEARER ${proof.jwt}` - }); +} +_pollingInterval = new WeakMap(); +let JsonRpcProvider$1 = (_l = class extends JsonRpcApiPollingProvider { + constructor(url, network2, options) { + if (url == null) { + url = "http://localhost:8545"; + } + super(network2, options); + __privateAdd(this, _connect); + if (typeof url === "string") { + __privateSet(this, _connect, new FetchRequest(url)); } else { - await this.guard.setPIN({ - pin, - timestamp: signedProof.timestamp.getTime(), - signature: signedProof.signature - }, { - Authorization: `BEARER ${proof.jwt}` - }); + __privateSet(this, _connect, url.clone()); } } - resetPin(proof) { - return this.setPin(void 0, proof); + _getConnection() { + return __privateGet(this, _connect).clone(); } - async createTotp(proof) { - const signedProof = await signAuthUpdateProof(proof); - const { - uri - } = await this.guard.createTOTP({ - timestamp: signedProof.timestamp.getTime(), - signature: signedProof.signature - }, { - Authorization: `BEARER ${proof.jwt}` - }); - return new URL(uri); + async send(method, params) { + await this._start(); + return await super.send(method, params); } - async commitTotp(token, jwt) { - const { - codes - } = await this.guard.commitTOTP({ - token - }, { - Authorization: `BEARER ${jwt}` - }); - return codes; + async _send(payload) { + const request = this._getConnection(); + request.body = JSON.stringify(payload); + request.setHeader("content-type", "application/json"); + const response = await request.send(); + response.assertOk(); + let resp = response.bodyJson; + if (!Array.isArray(resp)) { + resp = [resp]; + } + return resp; } - async resetTotp(proof) { - const signedProof = await signAuthUpdateProof(proof); - await this.guard.resetTOTP({ - timestamp: signedProof.timestamp.getTime(), - signature: signedProof.signature - }, { - Authorization: `BEARER ${proof.jwt}` - }); +}, _connect = new WeakMap(), _l); +function spelunkData(value) { + if (value == null) { + return null; } - async reset2fa(recoveryCode, proof) { - if ("jwt" in proof) { - await this.guard.reset2FA({ - code: recoveryCode - }, { - Authorization: `BEARER ${proof.jwt}` - }); - } else { - const signedProof = await signOwnershipProof(proof); - await this.guard.reset2FA({ - code: recoveryCode, - proof: { - wallet: signedProof.walletAddress, - timestamp: signedProof.timestamp.getTime(), - signer: signedProof.signerAddress, - signature: signedProof.signature - } - }); + if (typeof value.message === "string" && value.message.match(/revert/i) && isHexString(value.data)) { + return { message: value.message, data: value.data }; + } + if (typeof value === "object") { + for (const key in value) { + const result = spelunkData(value[key]); + if (result) { + return result; + } } + return null; } - async getRecoveryCodes(proof) { - const signedProof = await signAuthUpdateProof(proof); - const { - codes - } = await this.guard.recoveryCodes({ - timestamp: signedProof.timestamp.getTime(), - signature: signedProof.signature - }, { - Authorization: `BEARER ${proof.jwt}` - }); - return codes; + if (typeof value === "string") { + try { + return spelunkData(JSON.parse(value)); + } catch (error) { + } } - async resetRecoveryCodes(proof) { - const signedProof = await signAuthUpdateProof(proof); - const { - codes - } = await this.guard.resetRecoveryCodes({ - timestamp: signedProof.timestamp.getTime(), - signature: signedProof.signature - }, { - Authorization: `BEARER ${proof.jwt}` - }); - return codes; + return null; +} +function _spelunkMessage(value, result) { + if (value == null) { + return; } - packMsgAndSig(address, msg, sig, chainId) { - return AbiCoder.defaultAbiCoder().encode(["address", "uint256", "bytes", "bytes"], [address, chainId, msg, sig]); + if (typeof value.message === "string") { + result.push(value.message); } - suffix() { - return new Uint8Array(this.appendSuffix ? [3] : []); + if (typeof value === "object") { + for (const key in value) { + _spelunkMessage(value[key], result); + } } -} -let AuthMethod = /* @__PURE__ */ function(AuthMethod2) { - AuthMethod2["PIN"] = "PIN"; - AuthMethod2["TOTP"] = "TOTP"; - return AuthMethod2; -}({}); -function parseAuthMethod(method) { - switch (method) { - case AuthMethod.PIN: - case AuthMethod.TOTP: - return method; - default: - throw new Error(`unknown auth method '${method}'`); + if (typeof value === "string") { + try { + return _spelunkMessage(JSON.parse(value), result); + } catch (error) { + } } } -function isSignedOwnershipProof(proof) { - return "signerAddress" in proof && typeof proof.signerAddress === "string"; +function spelunkMessage(value) { + const result = []; + _spelunkMessage(value, result); + return result; } -async function signOwnershipProof(proof) { - if (isSignedOwnershipProof(proof)) { - return proof; - } else { - const signer2 = index$4.isSapientSigner(proof.signer) ? proof.signer : new index$4.SignerWrapper(proof.signer); - const signerAddress = await signer2.getAddress(); - const timestamp = /* @__PURE__ */ new Date(); - const typedData = getOwnershipProofTypedData(proof.walletAddress, timestamp); - const digest = encodeTypedDataDigest(typedData); - return { - walletAddress: proof.walletAddress, - timestamp, - signerAddress, - signature: hexlify(await signer2.sign(digest, {})) - }; +const defaultApiKey$1 = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972"; +function getHost$5(name2) { + switch (name2) { + case "mainnet": + return "rpc.ankr.com/eth"; + case "goerli": + return "rpc.ankr.com/eth_goerli"; + case "sepolia": + return "rpc.ankr.com/eth_sepolia"; + case "arbitrum": + return "rpc.ankr.com/arbitrum"; + case "base": + return "rpc.ankr.com/base"; + case "base-goerli": + return "rpc.ankr.com/base_goerli"; + case "base-sepolia": + return "rpc.ankr.com/base_sepolia"; + case "bnb": + return "rpc.ankr.com/bsc"; + case "bnbt": + return "rpc.ankr.com/bsc_testnet_chapel"; + case "matic": + return "rpc.ankr.com/polygon"; + case "matic-mumbai": + return "rpc.ankr.com/polygon_mumbai"; + case "optimism": + return "rpc.ankr.com/optimism"; + case "optimism-goerli": + return "rpc.ankr.com/optimism_testnet"; + case "optimism-sepolia": + return "rpc.ankr.com/optimism_sepolia"; } + assertArgument(false, "unsupported network", "network", name2); } -async function signAuthUpdateProof(proof) { - if ("wallet" in proof) { - var _typedData$domain$cha; - const timestamp = /* @__PURE__ */ new Date(); - const typedData = getAuthUpdateProofTypedData(timestamp); - const signature2 = await proof.wallet.signTypedData(typedData.domain, typedData.types, typedData.message, (_typedData$domain$cha = typedData.domain.chainId) != null ? _typedData$domain$cha : 1, "eip6492"); - return { - jwt: proof.jwt, - timestamp, - signature: signature2 - }; - } else { - return proof; +class AnkrProvider extends JsonRpcProvider$1 { + /** + * Create a new **AnkrProvider**. + * + * By default connecting to ``mainnet`` with a highly throttled + * API key. + */ + constructor(_network3, apiKey) { + if (_network3 == null) { + _network3 = "mainnet"; + } + const network2 = Network.from(_network3); + if (apiKey == null) { + apiKey = defaultApiKey$1; + } + const options = { polling: true, staticNetwork: network2 }; + const request = AnkrProvider.getRequest(network2, apiKey); + super(request, network2, options); + /** + * The API key for the Ankr connection. + */ + __publicField(this, "apiKey"); + defineProperties$1(this, { apiKey }); } -} -function getOwnershipProofTypedData(wallet, timestamp) { - return { - domain, - types: { - AuthMethods: [{ - name: "wallet", - type: "address" - }, { - name: "timestamp", - type: "string" - }] - }, - message: { - wallet: getAddress$1(wallet), - timestamp: toUTCString(timestamp) + _getProvider(chainId) { + try { + return new AnkrProvider(chainId, this.apiKey); + } catch (error) { } - }; -} -function getAuthUpdateProofTypedData(timestamp) { - return { - domain, - types: { - AuthUpdate: [{ - name: "timestamp", - type: "string" - }] - }, - message: { - timestamp: toUTCString(timestamp) + return super._getProvider(chainId); + } + /** + * Returns a prepared request for connecting to %%network%% with + * %%apiKey%%. + */ + static getRequest(network2, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey$1; } - }; -} -const domain = { - name: "Sequence Guard", - version: "1", - chainId: 1 -}; -function toUTCString(date) { - return date.toUTCString().replace("GMT", "UTC"); -} -const guard$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - AuthMethod, - Guard, - GuardSigner, - getAuthUpdateProofTypedData, - getOwnershipProofTypedData, - isSignedOwnershipProof, - signOwnershipProof -}, Symbol.toStringTag, { value: "Module" })); -var eventemitter2 = { exports: {} }; -(function(module2, exports) { - !function(undefined$1) { - var hasOwnProperty = Object.hasOwnProperty; - var isArray2 = Array.isArray ? Array.isArray : function _isArray(obj) { - return Object.prototype.toString.call(obj) === "[object Array]"; - }; - var defaultMaxListeners = 10; - var nextTickSupported = typeof process$1 == "object" && typeof process$1.nextTick == "function"; - var symbolsSupported = typeof Symbol === "function"; - var reflectSupported = typeof Reflect === "object"; - var setImmediateSupported = typeof setImmediate === "function"; - var _setImmediate = setImmediateSupported ? setImmediate : setTimeout; - var ownKeys2 = symbolsSupported ? reflectSupported && typeof Reflect.ownKeys === "function" ? Reflect.ownKeys : function(obj) { - var arr = Object.getOwnPropertyNames(obj); - arr.push.apply(arr, Object.getOwnPropertySymbols(obj)); - return arr; - } : Object.keys; - function init2() { - this._events = {}; - if (this._conf) { - configure.call(this, this._conf); - } + const request = new FetchRequest(`https://${getHost$5(network2.name)}/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey$1) { + request.retryFunc = async (request2, response, attempt) => { + showThrottleMessage("AnkrProvider"); + return true; + }; } - function configure(conf) { - if (conf) { - this._conf = conf; - conf.delimiter && (this.delimiter = conf.delimiter); - if (conf.maxListeners !== undefined$1) { - this._maxListeners = conf.maxListeners; - } - conf.wildcard && (this.wildcard = conf.wildcard); - conf.newListener && (this._newListener = conf.newListener); - conf.removeListener && (this._removeListener = conf.removeListener); - conf.verboseMemoryLeak && (this.verboseMemoryLeak = conf.verboseMemoryLeak); - conf.ignoreErrors && (this.ignoreErrors = conf.ignoreErrors); - if (this.wildcard) { - this.listenerTree = {}; - } + return request; + } + getRpcError(payload, error) { + if (payload.method === "eth_sendRawTransaction") { + if (error && error.error && error.error.message === "INTERNAL_ERROR: could not replace existing tx") { + error.error.message = "replacement transaction underpriced"; } } - function logPossibleMemoryLeak(count2, eventName) { - var errorMsg = "(node) warning: possible EventEmitter memory leak detected. " + count2 + " listeners added. Use emitter.setMaxListeners() to increase limit."; - if (this.verboseMemoryLeak) { - errorMsg += " Event name: " + eventName + "."; - } - if (typeof process$1 !== "undefined" && process$1.emitWarning) { - var e2 = new Error(errorMsg); - e2.name = "MaxListenersExceededWarning"; - e2.emitter = this; - e2.count = count2; - process$1.emitWarning(e2); - } else { - console.error(errorMsg); - if (console.trace) { - console.trace(); - } - } + return super.getRpcError(payload, error); + } + isCommunityResource() { + return this.apiKey === defaultApiKey$1; + } +} +const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC"; +function getHost$4(name2) { + switch (name2) { + case "mainnet": + return "eth-mainnet.alchemyapi.io"; + case "goerli": + return "eth-goerli.g.alchemy.com"; + case "sepolia": + return "eth-sepolia.g.alchemy.com"; + case "arbitrum": + return "arb-mainnet.g.alchemy.com"; + case "arbitrum-goerli": + return "arb-goerli.g.alchemy.com"; + case "arbitrum-sepolia": + return "arb-sepolia.g.alchemy.com"; + case "base": + return "base-mainnet.g.alchemy.com"; + case "base-goerli": + return "base-goerli.g.alchemy.com"; + case "base-sepolia": + return "base-sepolia.g.alchemy.com"; + case "matic": + return "polygon-mainnet.g.alchemy.com"; + case "matic-amoy": + return "polygon-amoy.g.alchemy.com"; + case "matic-mumbai": + return "polygon-mumbai.g.alchemy.com"; + case "optimism": + return "opt-mainnet.g.alchemy.com"; + case "optimism-goerli": + return "opt-goerli.g.alchemy.com"; + case "optimism-sepolia": + return "opt-sepolia.g.alchemy.com"; + } + assertArgument(false, "unsupported network", "network", name2); +} +class AlchemyProvider extends JsonRpcProvider$1 { + constructor(_network3, apiKey) { + if (_network3 == null) { + _network3 = "mainnet"; } - var toArray = function(a2, b2, c2) { - var n2 = arguments.length; - switch (n2) { - case 0: - return []; - case 1: - return [a2]; - case 2: - return [a2, b2]; - case 3: - return [a2, b2, c2]; - default: - var arr = new Array(n2); - while (n2--) { - arr[n2] = arguments[n2]; - } - return arr; - } - }; - function toObject2(keys, values) { - var obj = {}; - var key; - var len = keys.length; - var valuesCount = 0; - for (var i = 0; i < len; i++) { - key = keys[i]; - obj[key] = i < valuesCount ? values[i] : undefined$1; - } - return obj; + const network2 = Network.from(_network3); + if (apiKey == null) { + apiKey = defaultApiKey; } - function TargetObserver(emitter, target, options) { - this._emitter = emitter; - this._target = target; - this._listeners = {}; - this._listenersCount = 0; - var on, off; - if (options.on || options.off) { - on = options.on; - off = options.off; - } - if (target.addEventListener) { - on = target.addEventListener; - off = target.removeEventListener; - } else if (target.addListener) { - on = target.addListener; - off = target.removeListener; - } else if (target.on) { - on = target.on; - off = target.off; - } - if (!on && !off) { - throw Error("target does not implement any known event API"); - } - if (typeof on !== "function") { - throw TypeError("on method must be a function"); - } - if (typeof off !== "function") { - throw TypeError("off method must be a function"); - } - this._on = on; - this._off = off; - var _observers2 = emitter._observers; - if (_observers2) { - _observers2.push(this); - } else { - emitter._observers = [this]; - } + const request = AlchemyProvider.getRequest(network2, apiKey); + super(request, network2, { staticNetwork: network2 }); + __publicField(this, "apiKey"); + defineProperties$1(this, { apiKey }); + } + _getProvider(chainId) { + try { + return new AlchemyProvider(chainId, this.apiKey); + } catch (error) { } - Object.assign(TargetObserver.prototype, { - subscribe: function(event, localEvent, reducer) { - var observer = this; - var target = this._target; - var emitter = this._emitter; - var listeners = this._listeners; - var handler = function() { - var args = toArray.apply(null, arguments); - var eventObj = { - data: args, - name: localEvent, - original: event - }; - if (reducer) { - var result = reducer.call(target, eventObj); - if (result !== false) { - emitter.emit.apply(emitter, [eventObj.name].concat(args)); - } - return; - } - emitter.emit.apply(emitter, [localEvent].concat(args)); - }; - if (listeners[event]) { - throw Error("Event '" + event + "' is already listening"); - } - this._listenersCount++; - if (emitter._newListener && emitter._removeListener && !observer._onNewListener) { - this._onNewListener = function(_event2) { - if (_event2 === localEvent && listeners[event] === null) { - listeners[event] = handler; - observer._on.call(target, event, handler); - } - }; - emitter.on("newListener", this._onNewListener); - this._onRemoveListener = function(_event2) { - if (_event2 === localEvent && !emitter.hasListeners(_event2) && listeners[event]) { - listeners[event] = null; - observer._off.call(target, event, handler); - } - }; - listeners[event] = null; - emitter.on("removeListener", this._onRemoveListener); - } else { - listeners[event] = handler; - observer._on.call(target, event, handler); - } - }, - unsubscribe: function(event) { - var observer = this; - var listeners = this._listeners; - var emitter = this._emitter; - var handler; - var events; - var off = this._off; - var target = this._target; - var i; - if (event && typeof event !== "string") { - throw TypeError("event must be a string"); - } - function clearRefs() { - if (observer._onNewListener) { - emitter.off("newListener", observer._onNewListener); - emitter.off("removeListener", observer._onRemoveListener); - observer._onNewListener = null; - observer._onRemoveListener = null; - } - var index2 = findTargetIndex.call(emitter, observer); - emitter._observers.splice(index2, 1); - } - if (event) { - handler = listeners[event]; - if (!handler) return; - off.call(target, event, handler); - delete listeners[event]; - if (!--this._listenersCount) { - clearRefs(); - } - } else { - events = ownKeys2(listeners); - i = events.length; - while (i-- > 0) { - event = events[i]; - off.call(target, event, listeners[event]); - } - this._listeners = {}; - this._listenersCount = 0; - clearRefs(); - } - } - }); - function resolveOptions(options, schema, reducers, allowUnknown) { - var computedOptions = Object.assign({}, schema); - if (!options) return computedOptions; - if (typeof options !== "object") { - throw TypeError("options must be an object"); + return super._getProvider(chainId); + } + async _perform(req) { + if (req.method === "getTransactionResult") { + const { trace, tx } = await resolveProperties$1({ + trace: this.send("trace_transaction", [req.hash]), + tx: this.getTransaction(req.hash) + }); + if (trace == null || tx == null) { + return null; } - var keys = Object.keys(options); - var length = keys.length; - var option, value; - var reducer; - function reject(reason) { - throw Error('Invalid "' + option + '" option value' + (reason ? ". Reason: " + reason : "")); + let data; + let error = false; + try { + data = trace[0].result.output; + error = trace[0].error === "Reverted"; + } catch (error2) { } - for (var i = 0; i < length; i++) { - option = keys[i]; - if (!hasOwnProperty.call(schema, option)) { - throw Error('Unknown "' + option + '" option'); - } - value = options[option]; - if (value !== undefined$1) { - reducer = reducers[option]; - computedOptions[option] = reducer ? reducer(value, reject) : value; - } + if (data) { + assert(!error, "an error occurred during transaction executions", "CALL_EXCEPTION", { + action: "getTransactionResult", + data, + reason: null, + transaction: tx, + invocation: null, + revert: null + // @TODO + }); + return data; } - return computedOptions; + assert(false, "could not parse trace result", "BAD_DATA", { value: trace }); } - function constructorReducer(value, reject) { - if (typeof value !== "function" || !value.hasOwnProperty("prototype")) { - reject("value must be a constructor"); - } - return value; + return await super._perform(req); + } + isCommunityResource() { + return this.apiKey === defaultApiKey; + } + static getRequest(network2, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey; } - function makeTypeReducer(types2) { - var message = "value must be type of " + types2.join("|"); - var len = types2.length; - var firstType = types2[0]; - var secondType = types2[1]; - if (len === 1) { - return function(v3, reject) { - if (typeof v3 === firstType) { - return v3; - } - reject(message); - }; - } - if (len === 2) { - return function(v3, reject) { - var kind = typeof v3; - if (kind === firstType || kind === secondType) return v3; - reject(message); - }; - } - return function(v3, reject) { - var kind = typeof v3; - var i = len; - while (i-- > 0) { - if (kind === types2[i]) return v3; - } - reject(message); + const request = new FetchRequest(`https://${getHost$4(network2.name)}/v2/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey) { + request.retryFunc = async (request2, response, attempt) => { + showThrottleMessage("alchemy"); + return true; }; } - var functionReducer = makeTypeReducer(["function"]); - var objectFunctionReducer = makeTypeReducer(["object", "function"]); - function makeCancelablePromise(Promise2, executor, options) { - var isCancelable; - var callbacks; - var timer = 0; - var subscriptionClosed; - var promise = new Promise2(function(resolve, reject, onCancel) { - options = resolveOptions(options, { - timeout: 0, - overload: false - }, { - timeout: function(value, reject2) { - value *= 1; - if (typeof value !== "number" || value < 0 || !Number.isFinite(value)) { - reject2("timeout must be a positive number"); - } - return value; - } - }); - isCancelable = !options.overload && typeof Promise2.prototype.cancel === "function" && typeof onCancel === "function"; - function cleanup() { - if (callbacks) { - callbacks = null; - } - if (timer) { - clearTimeout(timer); - timer = 0; - } - } - var _resolve = function(value) { - cleanup(); - resolve(value); - }; - var _reject = function(err) { - cleanup(); - reject(err); - }; - if (isCancelable) { - executor(_resolve, _reject, onCancel); - } else { - callbacks = [function(reason) { - _reject(reason || Error("canceled")); - }]; - executor(_resolve, _reject, function(cb2) { - if (subscriptionClosed) { - throw Error("Unable to subscribe on cancel event asynchronously"); - } - if (typeof cb2 !== "function") { - throw TypeError("onCancel callback must be a function"); - } - callbacks.push(cb2); - }); - subscriptionClosed = true; - } - if (options.timeout > 0) { - timer = setTimeout(function() { - var reason = Error("timeout"); - reason.code = "ETIMEDOUT"; - timer = 0; - promise.cancel(reason); - reject(reason); - }, options.timeout); - } - }); - if (!isCancelable) { - promise.cancel = function(reason) { - if (!callbacks) { - return; - } - var length = callbacks.length; - for (var i = 1; i < length; i++) { - callbacks[i](reason); - } - callbacks[0](reason); - callbacks = null; - }; - } - return promise; + return request; + } +} +function getApiKey(name2) { + switch (name2) { + case "mainnet": + return "39f1d67cedf8b7831010a665328c9197"; + case "arbitrum": + return "0550c209db33c3abf4cc927e1e18cea1"; + case "bnb": + return "98b5a77e531614387366f6fc5da097f8"; + case "matic": + return "cd9d4d70377471aa7c142ec4a4205249"; + } + assertArgument(false, "unsupported network", "network", name2); +} +function getHost$3(name2) { + switch (name2) { + case "mainnet": + return "ethereum-mainnet.core.chainstack.com"; + case "arbitrum": + return "arbitrum-mainnet.core.chainstack.com"; + case "bnb": + return "bsc-mainnet.core.chainstack.com"; + case "matic": + return "polygon-mainnet.core.chainstack.com"; + } + assertArgument(false, "unsupported network", "network", name2); +} +class ChainstackProvider extends JsonRpcProvider$1 { + /** + * Creates a new **ChainstackProvider**. + */ + constructor(_network3, apiKey) { + if (_network3 == null) { + _network3 = "mainnet"; } - function findTargetIndex(observer) { - var observers2 = this._observers; - if (!observers2) { - return -1; - } - var len = observers2.length; - for (var i = 0; i < len; i++) { - if (observers2[i]._target === observer) return i; - } - return -1; + const network2 = Network.from(_network3); + if (apiKey == null) { + apiKey = getApiKey(network2.name); + } + const request = ChainstackProvider.getRequest(network2, apiKey); + super(request, network2, { staticNetwork: network2 }); + /** + * The API key for the Chainstack connection. + */ + __publicField(this, "apiKey"); + defineProperties$1(this, { apiKey }); + } + _getProvider(chainId) { + try { + return new ChainstackProvider(chainId, this.apiKey); + } catch (error) { + } + return super._getProvider(chainId); + } + isCommunityResource() { + return this.apiKey === getApiKey(this._network.name); + } + /** + * Returns a prepared request for connecting to %%network%% + * with %%apiKey%% and %%projectSecret%%. + */ + static getRequest(network2, apiKey) { + if (apiKey == null) { + apiKey = getApiKey(network2.name); + } + const request = new FetchRequest(`https://${getHost$3(network2.name)}/${apiKey}`); + request.allowGzip = true; + if (apiKey === getApiKey(network2.name)) { + request.retryFunc = async (request2, response, attempt) => { + showThrottleMessage("ChainstackProvider"); + return true; + }; + } + return request; + } +} +class CloudflareProvider extends JsonRpcProvider$1 { + constructor(_network3) { + if (_network3 == null) { + _network3 = "mainnet"; + } + const network2 = Network.from(_network3); + assertArgument(network2.name === "mainnet", "unsupported network", "network", _network3); + super("https://cloudflare-eth.com/", network2, { staticNetwork: network2 }); + } +} +const THROTTLE = 2e3; +function isPromise(value) { + return value && typeof value.then === "function"; +} +const EtherscanPluginId = "org.ethers.plugins.provider.Etherscan"; +class EtherscanPlugin extends NetworkPlugin { + /** + * Creates a new **EtherscanProvider** which will use + * %%baseUrl%%. + */ + constructor(baseUrl) { + super(EtherscanPluginId); + /** + * The Etherscan API base URL. + */ + __publicField(this, "baseUrl"); + defineProperties$1(this, { baseUrl }); + } + clone() { + return new EtherscanPlugin(this.baseUrl); + } +} +const skipKeys = ["enableCcipRead"]; +let nextId = 1; +class EtherscanProvider extends AbstractProvider { + /** + * Creates a new **EtherscanBaseProvider**. + */ + constructor(_network3, _apiKey) { + const apiKey = _apiKey != null ? _apiKey : null; + super(); + /** + * The connected network. + */ + __publicField(this, "network"); + /** + * The API key or null if using the community provided bandwidth. + */ + __publicField(this, "apiKey"); + __privateAdd(this, _plugin); + const network2 = Network.from(_network3); + __privateSet(this, _plugin, network2.getPlugin(EtherscanPluginId)); + defineProperties$1(this, { apiKey, network: network2 }); + this.getBaseUrl(); + } + /** + * Returns the base URL. + * + * If an [[EtherscanPlugin]] is configured on the + * [[EtherscanBaseProvider_network]], returns the plugin's + * baseUrl. + */ + getBaseUrl() { + if (__privateGet(this, _plugin)) { + return __privateGet(this, _plugin).baseUrl; + } + switch (this.network.name) { + case "mainnet": + return "https://api.etherscan.io"; + case "goerli": + return "https://api-goerli.etherscan.io"; + case "sepolia": + return "https://api-sepolia.etherscan.io"; + case "holesky": + return "https://api-holesky.etherscan.io"; + case "arbitrum": + return "https://api.arbiscan.io"; + case "arbitrum-goerli": + return "https://api-goerli.arbiscan.io"; + case "base": + return "https://api.basescan.org"; + case "base-sepolia": + return "https://api-sepolia.basescan.org"; + case "bnb": + return "https://api.bscscan.com"; + case "bnbt": + return "https://api-testnet.bscscan.com"; + case "matic": + return "https://api.polygonscan.com"; + case "matic-amoy": + return "https://api-amoy.polygonscan.com"; + case "matic-mumbai": + return "https://api-testnet.polygonscan.com"; + case "optimism": + return "https://api-optimistic.etherscan.io"; + case "optimism-goerli": + return "https://api-goerli-optimistic.etherscan.io"; } - function searchListenerTree(handlers, type, tree, i, typeLength) { - if (!tree) { - return null; + assertArgument(false, "unsupported network", "network", this.network); + } + /** + * Returns the URL for the %%module%% and %%params%%. + */ + getUrl(module2, params) { + const query = Object.keys(params).reduce((accum, key) => { + const value = params[key]; + if (value != null) { + accum += `&${key}=${value}`; } - if (i === 0) { - var kind = typeof type; - if (kind === "string") { - var ns, n2, l2 = 0, j2 = 0, delimiter = this.delimiter, dl2 = delimiter.length; - if ((n2 = type.indexOf(delimiter)) !== -1) { - ns = new Array(5); - do { - ns[l2++] = type.slice(j2, n2); - j2 = n2 + dl2; - } while ((n2 = type.indexOf(delimiter, j2)) !== -1); - ns[l2++] = type.slice(j2); - type = ns; - typeLength = l2; - } else { - type = [type]; - typeLength = 1; - } - } else if (kind === "object") { - typeLength = type.length; - } else { - type = [type]; - typeLength = 1; - } + return accum; + }, ""); + const apiKey = this.apiKey ? `&apikey=${this.apiKey}` : ""; + return `${this.getBaseUrl()}/api?module=${module2}${query}${apiKey}`; + } + /** + * Returns the URL for using POST requests. + */ + getPostUrl() { + return `${this.getBaseUrl()}/api`; + } + /** + * Returns the parameters for using POST requests. + */ + getPostData(module2, params) { + params.module = module2; + params.apikey = this.apiKey; + return params; + } + async detectNetwork() { + return this.network; + } + /** + * Resolves to the result of calling %%module%% with %%params%%. + * + * If %%post%%, the request is made as a POST request. + */ + async fetch(module2, params, post) { + const id2 = nextId++; + const url = post ? this.getPostUrl() : this.getUrl(module2, params); + const payload = post ? this.getPostData(module2, params) : null; + this.emit("debug", { action: "sendRequest", id: id2, url, payload }); + const request = new FetchRequest(url); + request.setThrottleParams({ slotInterval: 1e3 }); + request.retryFunc = (req, resp, attempt) => { + if (this.isCommunityResource()) { + showThrottleMessage("Etherscan"); } - var listeners = null, branch, xTree, xxTree, isolatedBranch, endReached, currentType = type[i], nextType = type[i + 1], branches, _listeners2; - if (i === typeLength) { - if (tree._listeners) { - if (typeof tree._listeners === "function") { - handlers && handlers.push(tree._listeners); - listeners = [tree]; - } else { - handlers && handlers.push.apply(handlers, tree._listeners); - listeners = [tree]; - } + return Promise.resolve(true); + }; + request.processFunc = async (request2, response2) => { + const result2 = response2.hasBody() ? JSON.parse(toUtf8String(response2.body)) : {}; + const throttle = (typeof result2.result === "string" ? result2.result : "").toLowerCase().indexOf("rate limit") >= 0; + if (module2 === "proxy") { + if (result2 && result2.status == 0 && result2.message == "NOTOK" && throttle) { + this.emit("debug", { action: "receiveError", id: id2, reason: "proxy-NOTOK", error: result2 }); + response2.throwThrottleError(result2.result, THROTTLE); } } else { - if (currentType === "*") { - branches = ownKeys2(tree); - n2 = branches.length; - while (n2-- > 0) { - branch = branches[n2]; - if (branch !== "_listeners") { - _listeners2 = searchListenerTree(handlers, type, tree[branch], i + 1, typeLength); - if (_listeners2) { - if (listeners) { - listeners.push.apply(listeners, _listeners2); - } else { - listeners = _listeners2; - } - } - } - } - return listeners; - } else if (currentType === "**") { - endReached = i + 1 === typeLength || i + 2 === typeLength && nextType === "*"; - if (endReached && tree._listeners) { - listeners = searchListenerTree(handlers, type, tree, typeLength, typeLength); - } - branches = ownKeys2(tree); - n2 = branches.length; - while (n2-- > 0) { - branch = branches[n2]; - if (branch !== "_listeners") { - if (branch === "*" || branch === "**") { - if (tree[branch]._listeners && !endReached) { - _listeners2 = searchListenerTree(handlers, type, tree[branch], typeLength, typeLength); - if (_listeners2) { - if (listeners) { - listeners.push.apply(listeners, _listeners2); - } else { - listeners = _listeners2; - } - } - } - _listeners2 = searchListenerTree(handlers, type, tree[branch], i, typeLength); - } else if (branch === nextType) { - _listeners2 = searchListenerTree(handlers, type, tree[branch], i + 2, typeLength); - } else { - _listeners2 = searchListenerTree(handlers, type, tree[branch], i, typeLength); - } - if (_listeners2) { - if (listeners) { - listeners.push.apply(listeners, _listeners2); - } else { - listeners = _listeners2; - } - } - } - } - return listeners; - } else if (tree[currentType]) { - listeners = searchListenerTree(handlers, type, tree[currentType], i + 1, typeLength); - } - } - xTree = tree["*"]; - if (xTree) { - searchListenerTree(handlers, type, xTree, i + 1, typeLength); - } - xxTree = tree["**"]; - if (xxTree) { - if (i < typeLength) { - if (xxTree._listeners) { - searchListenerTree(handlers, type, xxTree, typeLength, typeLength); - } - branches = ownKeys2(xxTree); - n2 = branches.length; - while (n2-- > 0) { - branch = branches[n2]; - if (branch !== "_listeners") { - if (branch === nextType) { - searchListenerTree(handlers, type, xxTree[branch], i + 2, typeLength); - } else if (branch === currentType) { - searchListenerTree(handlers, type, xxTree[branch], i + 1, typeLength); - } else { - isolatedBranch = {}; - isolatedBranch[branch] = xxTree[branch]; - searchListenerTree(handlers, type, { "**": isolatedBranch }, i + 1, typeLength); - } - } - } - } else if (xxTree._listeners) { - searchListenerTree(handlers, type, xxTree, typeLength, typeLength); - } else if (xxTree["*"] && xxTree["*"]._listeners) { - searchListenerTree(handlers, type, xxTree["*"], typeLength, typeLength); + if (throttle) { + this.emit("debug", { action: "receiveError", id: id2, reason: "null result", error: result2.result }); + response2.throwThrottleError(result2.result, THROTTLE); } } - return listeners; + return response2; + }; + if (payload) { + request.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8"); + request.body = Object.keys(payload).map((k2) => `${k2}=${payload[k2]}`).join("&"); } - function growListenerTree(type, listener, prepend) { - var len = 0, j2 = 0, i, delimiter = this.delimiter, dl2 = delimiter.length, ns; - if (typeof type === "string") { - if ((i = type.indexOf(delimiter)) !== -1) { - ns = new Array(5); - do { - ns[len++] = type.slice(j2, i); - j2 = i + dl2; - } while ((i = type.indexOf(delimiter, j2)) !== -1); - ns[len++] = type.slice(j2); - } else { - ns = [type]; - len = 1; - } - } else { - ns = type; - len = type.length; - } - if (len > 1) { - for (i = 0; i + 1 < len; i++) { - if (ns[i] === "**" && ns[i + 1] === "**") { - return; - } - } - } - var tree = this.listenerTree, name2; - for (i = 0; i < len; i++) { - name2 = ns[i]; - tree = tree[name2] || (tree[name2] = {}); - if (i === len - 1) { - if (!tree._listeners) { - tree._listeners = listener; - } else { - if (typeof tree._listeners === "function") { - tree._listeners = [tree._listeners]; - } - if (prepend) { - tree._listeners.unshift(listener); - } else { - tree._listeners.push(listener); - } - if (!tree._listeners.warned && this._maxListeners > 0 && tree._listeners.length > this._maxListeners) { - tree._listeners.warned = true; - logPossibleMemoryLeak.call(this, tree._listeners.length, name2); - } - } - return true; - } - } - return true; + const response = await request.send(); + try { + response.assertOk(); + } catch (error) { + this.emit("debug", { action: "receiveError", id: id2, error, reason: "assertOk" }); + assert(false, "response error", "SERVER_ERROR", { request, response }); } - function collectTreeEvents(tree, events, root2, asArray) { - var branches = ownKeys2(tree); - var i = branches.length; - var branch, branchName, path; - var hasListeners = tree["_listeners"]; - var isArrayPath; - while (i-- > 0) { - branchName = branches[i]; - branch = tree[branchName]; - if (branchName === "_listeners") { - path = root2; - } else { - path = root2 ? root2.concat(branchName) : [branchName]; - } - isArrayPath = asArray || typeof branchName === "symbol"; - hasListeners && events.push(isArrayPath ? path : path.join(this.delimiter)); - if (typeof branch === "object") { - collectTreeEvents.call(this, branch, events, path, isArrayPath); - } - } - return events; + if (!response.hasBody()) { + this.emit("debug", { action: "receiveError", id: id2, error: "missing body", reason: "null body" }); + assert(false, "missing response", "SERVER_ERROR", { request, response }); } - function recursivelyGarbageCollect(root2) { - var keys = ownKeys2(root2); - var i = keys.length; - var obj, key, flag; - while (i-- > 0) { - key = keys[i]; - obj = root2[key]; - if (obj) { - flag = true; - if (key !== "_listeners" && !recursivelyGarbageCollect(obj)) { - delete root2[key]; - } - } + const result = JSON.parse(toUtf8String(response.body)); + if (module2 === "proxy") { + if (result.jsonrpc != "2.0") { + this.emit("debug", { action: "receiveError", id: id2, result, reason: "invalid JSON-RPC" }); + assert(false, "invalid JSON-RPC response (missing jsonrpc='2.0')", "SERVER_ERROR", { request, response, info: { result } }); } - return flag; - } - function Listener(emitter, event, listener) { - this.emitter = emitter; - this.event = event; - this.listener = listener; - } - Listener.prototype.off = function() { - this.emitter.off(this.event, this.listener); - return this; - }; - function setupListener(event, listener, options) { - if (options === true) { - promisify2 = true; - } else if (options === false) { - async = true; - } else { - if (!options || typeof options !== "object") { - throw TypeError("options should be an object or true"); - } - var async = options.async; - var promisify2 = options.promisify; - var nextTick2 = options.nextTick; - var objectify = options.objectify; + if (result.error) { + this.emit("debug", { action: "receiveError", id: id2, result, reason: "JSON-RPC error" }); + assert(false, "error response", "SERVER_ERROR", { request, response, info: { result } }); } - if (async || nextTick2 || promisify2) { - var _listener2 = listener; - var _origin = listener._origin || listener; - if (nextTick2 && !nextTickSupported) { - throw Error("process.nextTick is not supported"); - } - if (promisify2 === undefined$1) { - promisify2 = listener.constructor.name === "AsyncFunction"; - } - listener = function() { - var args = arguments; - var context2 = this; - var event2 = this.event; - return promisify2 ? nextTick2 ? Promise.resolve() : new Promise(function(resolve) { - _setImmediate(resolve); - }).then(function() { - context2.event = event2; - return _listener2.apply(context2, args); - }) : (nextTick2 ? process$1.nextTick : _setImmediate)(function() { - context2.event = event2; - _listener2.apply(context2, args); - }); - }; - listener._async = true; - listener._origin = _origin; + this.emit("debug", { action: "receiveRequest", id: id2, result }); + return result.result; + } else { + if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) { + this.emit("debug", { action: "receiveRequest", id: id2, result }); + return result.result; } - return [listener, objectify ? new Listener(this, event, listener) : this]; - } - function EventEmitter2(conf) { - this._events = {}; - this._newListener = false; - this._removeListener = false; - this.verboseMemoryLeak = false; - configure.call(this, conf); + if (result.status != 1 || typeof result.message === "string" && !result.message.match(/^OK/)) { + this.emit("debug", { action: "receiveError", id: id2, result }); + assert(false, "error response", "SERVER_ERROR", { request, response, info: { result } }); + } + this.emit("debug", { action: "receiveRequest", id: id2, result }); + return result.result; } - EventEmitter2.EventEmitter2 = EventEmitter2; - EventEmitter2.prototype.listenTo = function(target, events, options) { - if (typeof target !== "object") { - throw TypeError("target musts be an object"); + } + /** + * Returns %%transaction%% normalized for the Etherscan API. + */ + _getTransactionPostData(transaction2) { + const result = {}; + for (let key in transaction2) { + if (skipKeys.indexOf(key) >= 0) { + continue; } - var emitter = this; - options = resolveOptions(options, { - on: undefined$1, - off: undefined$1, - reducers: undefined$1 - }, { - on: functionReducer, - off: functionReducer, - reducers: objectFunctionReducer - }); - function listen(events2) { - if (typeof events2 !== "object") { - throw TypeError("events must be an object"); - } - var reducers = options.reducers; - var index2 = findTargetIndex.call(emitter, target); - var observer; - if (index2 === -1) { - observer = new TargetObserver(emitter, target, options); - } else { - observer = emitter._observers[index2]; - } - var keys = ownKeys2(events2); - var len = keys.length; - var event; - var isSingleReducer = typeof reducers === "function"; - for (var i = 0; i < len; i++) { - event = keys[i]; - observer.subscribe( - event, - events2[event] || event, - isSingleReducer ? reducers : reducers && reducers[event] - ); - } + if (transaction2[key] == null) { + continue; } - isArray2(events) ? listen(toObject2(events)) : typeof events === "string" ? listen(toObject2(events.split(/\s+/))) : listen(events); - return this; - }; - EventEmitter2.prototype.stopListeningTo = function(target, event) { - var observers2 = this._observers; - if (!observers2) { - return false; + let value = transaction2[key]; + if (key === "type" && value === 0) { + continue; } - var i = observers2.length; - var observer; - var matched = false; - if (target && typeof target !== "object") { - throw TypeError("target should be an object"); + if (key === "blockTag" && value === "latest") { + continue; } - while (i-- > 0) { - observer = observers2[i]; - if (!target || observer._target === target) { - observer.unsubscribe(event); - matched = true; + if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) { + value = toQuantity(value); + } else if (key === "accessList") { + value = "[" + accessListify(value).map((set) => { + return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`; + }).join(",") + "]"; + } else if (key === "blobVersionedHashes") { + if (value.length === 0) { + continue; } + assert(false, "Etherscan API does not support blobVersionedHashes", "UNSUPPORTED_OPERATION", { + operation: "_getTransactionPostData", + info: { transaction: transaction2 } + }); + } else { + value = hexlify(value); } - return matched; - }; - EventEmitter2.prototype.delimiter = "."; - EventEmitter2.prototype.setMaxListeners = function(n2) { - if (n2 !== undefined$1) { - this._maxListeners = n2; - if (!this._conf) this._conf = {}; - this._conf.maxListeners = n2; - } - }; - EventEmitter2.prototype.getMaxListeners = function() { - return this._maxListeners; - }; - EventEmitter2.prototype.event = ""; - EventEmitter2.prototype.once = function(event, fn, options) { - return this._once(event, fn, false, options); - }; - EventEmitter2.prototype.prependOnceListener = function(event, fn, options) { - return this._once(event, fn, true, options); - }; - EventEmitter2.prototype._once = function(event, fn, prepend, options) { - return this._many(event, 1, fn, prepend, options); - }; - EventEmitter2.prototype.many = function(event, ttl, fn, options) { - return this._many(event, ttl, fn, false, options); - }; - EventEmitter2.prototype.prependMany = function(event, ttl, fn, options) { - return this._many(event, ttl, fn, true, options); - }; - EventEmitter2.prototype._many = function(event, ttl, fn, prepend, options) { - var self2 = this; - if (typeof fn !== "function") { - throw new Error("many only accepts instances of Function"); + result[key] = value; + } + return result; + } + /** + * Throws the normalized Etherscan error. + */ + _checkError(req, error, transaction2) { + let message = ""; + if (isError(error, "SERVER_ERROR")) { + try { + message = error.info.result.error.message; + } catch (e2) { } - function listener() { - if (--ttl === 0) { - self2.off(event, listener); + if (!message) { + try { + message = error.info.message; + } catch (e2) { } - return fn.apply(this, arguments); } - listener._origin = fn; - return this._on(event, listener, prepend, options); - }; - EventEmitter2.prototype.emit = function() { - if (!this._events && !this._all) { - return false; + } + if (req.method === "estimateGas") { + if (!message.match(/revert/i) && message.match(/insufficient funds/i)) { + assert(false, "insufficient funds", "INSUFFICIENT_FUNDS", { + transaction: req.transaction + }); } - this._events || init2.call(this); - var type = arguments[0], ns, wildcard = this.wildcard; - var args, l2, i, j2, containsSymbol; - if (type === "newListener" && !this._newListener) { - if (!this._events.newListener) { - return false; + } + if (req.method === "call" || req.method === "estimateGas") { + if (message.match(/execution reverted/i)) { + let data = ""; + try { + data = error.info.result.error.data; + } catch (error2) { } + const e2 = AbiCoder.getBuiltinCallException(req.method, req.transaction, data); + e2.info = { request: req, error }; + throw e2; } - if (wildcard) { - ns = type; - if (type !== "newListener" && type !== "removeListener") { - if (typeof type === "object") { - l2 = type.length; - if (symbolsSupported) { - for (i = 0; i < l2; i++) { - if (typeof type[i] === "symbol") { - containsSymbol = true; - break; - } - } - } - if (!containsSymbol) { - type = type.join(this.delimiter); - } - } + } + if (message) { + if (req.method === "broadcastTransaction") { + const transaction3 = Transaction.from(req.signedTransaction); + if (message.match(/replacement/i) && message.match(/underpriced/i)) { + assert(false, "replacement fee too low", "REPLACEMENT_UNDERPRICED", { + transaction: transaction3 + }); } - } - var al2 = arguments.length; - var handler; - if (this._all && this._all.length) { - handler = this._all.slice(); - for (i = 0, l2 = handler.length; i < l2; i++) { - this.event = type; - switch (al2) { - case 1: - handler[i].call(this, type); - break; - case 2: - handler[i].call(this, type, arguments[1]); - break; - case 3: - handler[i].call(this, type, arguments[1], arguments[2]); - break; - default: - handler[i].apply(this, arguments); - } + if (message.match(/insufficient funds/)) { + assert(false, "insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction: transaction3 + }); } - } - if (wildcard) { - handler = []; - searchListenerTree.call(this, handler, ns, this.listenerTree, 0, l2); - } else { - handler = this._events[type]; - if (typeof handler === "function") { - this.event = type; - switch (al2) { - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - default: - args = new Array(al2 - 1); - for (j2 = 1; j2 < al2; j2++) args[j2 - 1] = arguments[j2]; - handler.apply(this, args); - } - return true; - } else if (handler) { - handler = handler.slice(); + if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) { + assert(false, "nonce has already been used", "NONCE_EXPIRED", { + transaction: transaction3 + }); } } - if (handler && handler.length) { - if (al2 > 3) { - args = new Array(al2 - 1); - for (j2 = 1; j2 < al2; j2++) args[j2 - 1] = arguments[j2]; + } + throw error; + } + async _detectNetwork() { + return this.network; + } + async _perform(req) { + switch (req.method) { + case "chainId": + return this.network.chainId; + case "getBlockNumber": + return this.fetch("proxy", { action: "eth_blockNumber" }); + case "getGasPrice": + return this.fetch("proxy", { action: "eth_gasPrice" }); + case "getPriorityFee": + if (this.network.name === "mainnet") { + return "1000000000"; + } else if (this.network.name === "optimism") { + return "1000000"; + } else { + throw new Error("fallback onto the AbstractProvider default"); } - for (i = 0, l2 = handler.length; i < l2; i++) { - this.event = type; - switch (al2) { - case 1: - handler[i].call(this); - break; - case 2: - handler[i].call(this, arguments[1]); - break; - case 3: - handler[i].call(this, arguments[1], arguments[2]); - break; - default: - handler[i].apply(this, args); - } + case "getBalance": + return this.fetch("account", { + action: "balance", + address: req.address, + tag: req.blockTag + }); + case "getTransactionCount": + return this.fetch("proxy", { + action: "eth_getTransactionCount", + address: req.address, + tag: req.blockTag + }); + case "getCode": + return this.fetch("proxy", { + action: "eth_getCode", + address: req.address, + tag: req.blockTag + }); + case "getStorage": + return this.fetch("proxy", { + action: "eth_getStorageAt", + address: req.address, + position: req.position, + tag: req.blockTag + }); + case "broadcastTransaction": + return this.fetch("proxy", { + action: "eth_sendRawTransaction", + hex: req.signedTransaction + }, true).catch((error) => { + return this._checkError(req, error, req.signedTransaction); + }); + case "getBlock": + if ("blockTag" in req) { + return this.fetch("proxy", { + action: "eth_getBlockByNumber", + tag: req.blockTag, + boolean: req.includeTransactions ? "true" : "false" + }); } - return true; - } else if (!this.ignoreErrors && !this._all && type === "error") { - if (arguments[1] instanceof Error) { - throw arguments[1]; - } else { - throw new Error("Uncaught, unspecified 'error' event."); + assert(false, "getBlock by blockHash not supported by Etherscan", "UNSUPPORTED_OPERATION", { + operation: "getBlock(blockHash)" + }); + case "getTransaction": + return this.fetch("proxy", { + action: "eth_getTransactionByHash", + txhash: req.hash + }); + case "getTransactionReceipt": + return this.fetch("proxy", { + action: "eth_getTransactionReceipt", + txhash: req.hash + }); + case "call": { + if (req.blockTag !== "latest") { + throw new Error("EtherscanProvider does not support blockTag for call"); + } + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_call"; + try { + return await this.fetch("proxy", postData, true); + } catch (error) { + return this._checkError(req, error, req.transaction); } } - return !!this._all; - }; - EventEmitter2.prototype.emitAsync = function() { - if (!this._events && !this._all) { - return false; + case "estimateGas": { + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_estimateGas"; + try { + return await this.fetch("proxy", postData, true); + } catch (error) { + return this._checkError(req, error, req.transaction); + } } - this._events || init2.call(this); - var type = arguments[0], wildcard = this.wildcard, ns, containsSymbol; - var args, l2, i, j2; - if (type === "newListener" && !this._newListener) { - if (!this._events.newListener) { - return Promise.resolve([false]); + } + return super._perform(req); + } + async getNetwork() { + return this.network; + } + /** + * Resolves to the current price of ether. + * + * This returns ``0`` on any network other than ``mainnet``. + */ + async getEtherPrice() { + if (this.network.name !== "mainnet") { + return 0; + } + return parseFloat((await this.fetch("stats", { action: "ethprice" })).ethusd); + } + /** + * Resolves to a [Contract]] for %%address%%, using the + * Etherscan API to retreive the Contract ABI. + */ + async getContract(_address) { + let address = this._getAddress(_address); + if (isPromise(address)) { + address = await address; + } + try { + const resp = await this.fetch("contract", { + action: "getabi", + address + }); + const abi2 = JSON.parse(resp); + return new Contract(address, abi2, this); + } catch (error) { + return null; + } + } + isCommunityResource() { + return this.apiKey == null; + } +} +_plugin = new WeakMap(); +function getGlobal() { + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global$1 !== "undefined") { + return global$1; + } + throw new Error("unable to locate global object"); +} +const _WebSocket = getGlobal().WebSocket; +class SocketSubscriber { + /** + * Creates a new **SocketSubscriber** attached to %%provider%% listening + * to %%filter%%. + */ + constructor(provider2, filter2) { + __privateAdd(this, _provider5); + __privateAdd(this, _filter4); + __privateAdd(this, _filterId); + __privateAdd(this, _paused); + __privateAdd(this, _emitPromise); + __privateSet(this, _provider5, provider2); + __privateSet(this, _filter4, JSON.stringify(filter2)); + __privateSet(this, _filterId, null); + __privateSet(this, _paused, null); + __privateSet(this, _emitPromise, null); + } + /** + * The filter. + */ + get filter() { + return JSON.parse(__privateGet(this, _filter4)); + } + start() { + __privateSet(this, _filterId, __privateGet(this, _provider5).send("eth_subscribe", this.filter).then((filterId) => { + __privateGet(this, _provider5)._register(filterId, this); + return filterId; + })); + } + stop() { + __privateGet(this, _filterId).then((filterId) => { + if (__privateGet(this, _provider5).destroyed) { + return; + } + __privateGet(this, _provider5).send("eth_unsubscribe", [filterId]); + }); + __privateSet(this, _filterId, null); + } + // @TODO: pause should trap the current blockNumber, unsub, and on resume use getLogs + // and resume + pause(dropWhilePaused) { + assert(dropWhilePaused, "preserve logs while paused not supported by SocketSubscriber yet", "UNSUPPORTED_OPERATION", { operation: "pause(false)" }); + __privateSet(this, _paused, !!dropWhilePaused); + } + resume() { + __privateSet(this, _paused, null); + } + /** + * @_ignore: + */ + _handleMessage(message) { + if (__privateGet(this, _filterId) == null) { + return; + } + if (__privateGet(this, _paused) === null) { + let emitPromise = __privateGet(this, _emitPromise); + if (emitPromise == null) { + emitPromise = this._emit(__privateGet(this, _provider5), message); + } else { + emitPromise = emitPromise.then(async () => { + await this._emit(__privateGet(this, _provider5), message); + }); + } + __privateSet(this, _emitPromise, emitPromise.then(() => { + if (__privateGet(this, _emitPromise) === emitPromise) { + __privateSet(this, _emitPromise, null); + } + })); + } + } + /** + * Sub-classes **must** override this to emit the events on the + * provider. + */ + async _emit(provider2, message) { + throw new Error("sub-classes must implemente this; _emit"); + } +} +_provider5 = new WeakMap(); +_filter4 = new WeakMap(); +_filterId = new WeakMap(); +_paused = new WeakMap(); +_emitPromise = new WeakMap(); +class SocketBlockSubscriber extends SocketSubscriber { + /** + * @_ignore: + */ + constructor(provider2) { + super(provider2, ["newHeads"]); + } + async _emit(provider2, message) { + provider2.emit("block", parseInt(message.number)); + } +} +class SocketPendingSubscriber extends SocketSubscriber { + /** + * @_ignore: + */ + constructor(provider2) { + super(provider2, ["newPendingTransactions"]); + } + async _emit(provider2, message) { + provider2.emit("pending", message); + } +} +class SocketEventSubscriber extends SocketSubscriber { + /** + * @_ignore: + */ + constructor(provider2, filter2) { + super(provider2, ["logs", filter2]); + __privateAdd(this, _logFilter); + __privateSet(this, _logFilter, JSON.stringify(filter2)); + } + /** + * The filter. + */ + get logFilter() { + return JSON.parse(__privateGet(this, _logFilter)); + } + async _emit(provider2, message) { + provider2.emit(this.logFilter, provider2._wrapLog(message, provider2._network)); + } +} +_logFilter = new WeakMap(); +class SocketProvider extends JsonRpcApiProvider { + /** + * Creates a new **SocketProvider** connected to %%network%%. + * + * If unspecified, the network will be discovered. + */ + constructor(network2, _options4) { + const options = Object.assign({}, _options4 != null ? _options4 : {}); + assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1, "sockets-based providers do not support batches", "options.batchMaxCount", _options4); + options.batchMaxCount = 1; + if (options.staticNetwork == null) { + options.staticNetwork = true; + } + super(network2, options); + __privateAdd(this, _callbacks); + // Maps each filterId to its subscriber + __privateAdd(this, _subs2); + // If any events come in before a subscriber has finished + // registering, queue them + __privateAdd(this, _pending); + __privateSet(this, _callbacks, /* @__PURE__ */ new Map()); + __privateSet(this, _subs2, /* @__PURE__ */ new Map()); + __privateSet(this, _pending, /* @__PURE__ */ new Map()); + } + // This value is only valid after _start has been called + /* + get _network(): Network { + if (this.#network == null) { + throw new Error("this shouldn't happen"); + } + return this.#network.clone(); + } + */ + _getSubscriber(sub) { + switch (sub.type) { + case "close": + return new UnmanagedSubscriber("close"); + case "block": + return new SocketBlockSubscriber(this); + case "pending": + return new SocketPendingSubscriber(this); + case "event": + return new SocketEventSubscriber(this, sub.filter); + case "orphan": + if (sub.filter.orphan === "drop-log") { + return new UnmanagedSubscriber("drop-log"); } + } + return super._getSubscriber(sub); + } + /** + * Register a new subscriber. This is used internalled by Subscribers + * and generally is unecessary unless extending capabilities. + */ + _register(filterId, subscriber) { + __privateGet(this, _subs2).set(filterId, subscriber); + const pending = __privateGet(this, _pending).get(filterId); + if (pending) { + for (const message of pending) { + subscriber._handleMessage(message); } - if (wildcard) { - ns = type; - if (type !== "newListener" && type !== "removeListener") { - if (typeof type === "object") { - l2 = type.length; - if (symbolsSupported) { - for (i = 0; i < l2; i++) { - if (typeof type[i] === "symbol") { - containsSymbol = true; - break; - } - } - } - if (!containsSymbol) { - type = type.join(this.delimiter); - } + __privateGet(this, _pending).delete(filterId); + } + } + async _send(payload) { + assertArgument(!Array.isArray(payload), "WebSocket does not support batch send", "payload", payload); + const promise = new Promise((resolve, reject) => { + __privateGet(this, _callbacks).set(payload.id, { payload, resolve, reject }); + }); + await this._waitUntilReady(); + await this._write(JSON.stringify(payload)); + return [await promise]; + } + // Sub-classes must call this once they are connected + /* + async _start(): Promise { + if (this.#ready) { return; } + + for (const { payload } of this.#callbacks.values()) { + await this._write(JSON.stringify(payload)); } - } + + this.#ready = (async function() { + await super._start(); + })(); } - var promises = []; - var al2 = arguments.length; - var handler; - if (this._all) { - for (i = 0, l2 = this._all.length; i < l2; i++) { - this.event = type; - switch (al2) { - case 1: - promises.push(this._all[i].call(this, type)); - break; - case 2: - promises.push(this._all[i].call(this, type, arguments[1])); - break; - case 3: - promises.push(this._all[i].call(this, type, arguments[1], arguments[2])); - break; - default: - promises.push(this._all[i].apply(this, arguments)); - } - } + */ + /** + * Sub-classes **must** call this with messages received over their + * transport to be processed and dispatched. + */ + async _processMessage(message) { + const result = JSON.parse(message); + if (result && typeof result === "object" && "id" in result) { + const callback = __privateGet(this, _callbacks).get(result.id); + if (callback == null) { + this.emit("error", makeError("received result for unknown id", "UNKNOWN_ERROR", { + reasonCode: "UNKNOWN_ID", + result + })); + return; } - if (wildcard) { - handler = []; - searchListenerTree.call(this, handler, ns, this.listenerTree, 0); + __privateGet(this, _callbacks).delete(result.id); + callback.resolve(result); + } else if (result && result.method === "eth_subscription") { + const filterId = result.params.subscription; + const subscriber = __privateGet(this, _subs2).get(filterId); + if (subscriber) { + subscriber._handleMessage(result.params.result); } else { - handler = this._events[type]; - } - if (typeof handler === "function") { - this.event = type; - switch (al2) { - case 1: - promises.push(handler.call(this)); - break; - case 2: - promises.push(handler.call(this, arguments[1])); - break; - case 3: - promises.push(handler.call(this, arguments[1], arguments[2])); - break; - default: - args = new Array(al2 - 1); - for (j2 = 1; j2 < al2; j2++) args[j2 - 1] = arguments[j2]; - promises.push(handler.apply(this, args)); - } - } else if (handler && handler.length) { - handler = handler.slice(); - if (al2 > 3) { - args = new Array(al2 - 1); - for (j2 = 1; j2 < al2; j2++) args[j2 - 1] = arguments[j2]; - } - for (i = 0, l2 = handler.length; i < l2; i++) { - this.event = type; - switch (al2) { - case 1: - promises.push(handler[i].call(this)); - break; - case 2: - promises.push(handler[i].call(this, arguments[1])); - break; - case 3: - promises.push(handler[i].call(this, arguments[1], arguments[2])); - break; - default: - promises.push(handler[i].apply(this, args)); - } - } - } else if (!this.ignoreErrors && !this._all && type === "error") { - if (arguments[1] instanceof Error) { - return Promise.reject(arguments[1]); - } else { - return Promise.reject("Uncaught, unspecified 'error' event."); + let pending = __privateGet(this, _pending).get(filterId); + if (pending == null) { + pending = []; + __privateGet(this, _pending).set(filterId, pending); } + pending.push(result.params.result); } - return Promise.all(promises); - }; - EventEmitter2.prototype.on = function(type, listener, options) { - return this._on(type, listener, false, options); - }; - EventEmitter2.prototype.prependListener = function(type, listener, options) { - return this._on(type, listener, true, options); - }; - EventEmitter2.prototype.onAny = function(fn) { - return this._onAny(fn, false); - }; - EventEmitter2.prototype.prependAny = function(fn) { - return this._onAny(fn, true); - }; - EventEmitter2.prototype.addListener = EventEmitter2.prototype.on; - EventEmitter2.prototype._onAny = function(fn, prepend) { - if (typeof fn !== "function") { - throw new Error("onAny only accepts instances of Function"); - } - if (!this._all) { - this._all = []; - } - if (prepend) { - this._all.unshift(fn); - } else { - this._all.push(fn); + } else { + this.emit("error", makeError("received unexpected message", "UNKNOWN_ERROR", { + reasonCode: "UNEXPECTED_MESSAGE", + result + })); + return; + } + } + /** + * Sub-classes **must** override this to send %%message%% over their + * transport. + */ + async _write(message) { + throw new Error("sub-classes must override this"); + } +} +_callbacks = new WeakMap(); +_subs2 = new WeakMap(); +_pending = new WeakMap(); +class WebSocketProvider extends SocketProvider { + constructor(url, network2, options) { + super(network2, options); + __privateAdd(this, _connect2); + __privateAdd(this, _websocket); + if (typeof url === "string") { + __privateSet(this, _connect2, () => { + return new _WebSocket(url); + }); + __privateSet(this, _websocket, __privateGet(this, _connect2).call(this)); + } else if (typeof url === "function") { + __privateSet(this, _connect2, url); + __privateSet(this, _websocket, url()); + } else { + __privateSet(this, _connect2, null); + __privateSet(this, _websocket, url); + } + this.websocket.onopen = async () => { + try { + await this._start(); + this.resume(); + } catch (error) { + console.log("failed to start WebsocketProvider", error); } - return this; }; - EventEmitter2.prototype._on = function(type, listener, prepend, options) { - if (typeof type === "function") { - this._onAny(type, listener); - return this; - } - if (typeof listener !== "function") { - throw new Error("on only accepts instances of Function"); - } - this._events || init2.call(this); - var returnValue = this, temp; - if (options !== undefined$1) { - temp = setupListener.call(this, type, listener, options); - listener = temp[0]; - returnValue = temp[1]; - } - if (this._newListener) { - this.emit("newListener", type, listener); - } - if (this.wildcard) { - growListenerTree.call(this, type, listener, prepend); - return returnValue; - } - if (!this._events[type]) { - this._events[type] = listener; - } else { - if (typeof this._events[type] === "function") { - this._events[type] = [this._events[type]]; - } - if (prepend) { - this._events[type].unshift(listener); - } else { - this._events[type].push(listener); - } - if (!this._events[type].warned && this._maxListeners > 0 && this._events[type].length > this._maxListeners) { - this._events[type].warned = true; - logPossibleMemoryLeak.call(this, this._events[type].length, type); - } - } - return returnValue; + this.websocket.onmessage = (message) => { + this._processMessage(message.data); }; - EventEmitter2.prototype.off = function(type, listener) { - if (typeof listener !== "function") { - throw new Error("removeListener only takes instances of Function"); - } - var handlers, leafs = []; - if (this.wildcard) { - var ns = typeof type === "string" ? type.split(this.delimiter) : type.slice(); - leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); - if (!leafs) return this; - } else { - if (!this._events[type]) return this; - handlers = this._events[type]; - leafs.push({ _listeners: handlers }); - } - for (var iLeaf = 0; iLeaf < leafs.length; iLeaf++) { - var leaf = leafs[iLeaf]; - handlers = leaf._listeners; - if (isArray2(handlers)) { - var position = -1; - for (var i = 0, length = handlers.length; i < length; i++) { - if (handlers[i] === listener || handlers[i].listener && handlers[i].listener === listener || handlers[i]._origin && handlers[i]._origin === listener) { - position = i; - break; - } - } - if (position < 0) { - continue; - } - if (this.wildcard) { - leaf._listeners.splice(position, 1); - } else { - this._events[type].splice(position, 1); - } - if (handlers.length === 0) { - if (this.wildcard) { - delete leaf._listeners; - } else { - delete this._events[type]; - } - } - if (this._removeListener) - this.emit("removeListener", type, listener); - return this; - } else if (handlers === listener || handlers.listener && handlers.listener === listener || handlers._origin && handlers._origin === listener) { - if (this.wildcard) { - delete leaf._listeners; - } else { - delete this._events[type]; + } + get websocket() { + if (__privateGet(this, _websocket) == null) { + throw new Error("websocket closed"); + } + return __privateGet(this, _websocket); + } + async _write(message) { + this.websocket.send(message); + } + async destroy() { + if (__privateGet(this, _websocket) != null) { + __privateGet(this, _websocket).close(); + __privateSet(this, _websocket, null); + } + super.destroy(); + } +} +_connect2 = new WeakMap(); +_websocket = new WeakMap(); +const defaultProjectId = "84842078b09946638c03157f83405213"; +function getHost$2(name2) { + switch (name2) { + case "mainnet": + return "mainnet.infura.io"; + case "goerli": + return "goerli.infura.io"; + case "sepolia": + return "sepolia.infura.io"; + case "arbitrum": + return "arbitrum-mainnet.infura.io"; + case "arbitrum-goerli": + return "arbitrum-goerli.infura.io"; + case "arbitrum-sepolia": + return "arbitrum-sepolia.infura.io"; + case "base": + return "base-mainnet.infura.io"; + case "base-goerlia": + return "base-goerli.infura.io"; + case "base-sepolia": + return "base-sepolia.infura.io"; + case "bnb": + return "bnbsmartchain-mainnet.infura.io"; + case "bnbt": + return "bnbsmartchain-testnet.infura.io"; + case "linea": + return "linea-mainnet.infura.io"; + case "linea-goerli": + return "linea-goerli.infura.io"; + case "linea-sepolia": + return "linea-sepolia.infura.io"; + case "matic": + return "polygon-mainnet.infura.io"; + case "matic-amoy": + return "polygon-amoy.infura.io"; + case "matic-mumbai": + return "polygon-mumbai.infura.io"; + case "optimism": + return "optimism-mainnet.infura.io"; + case "optimism-goerli": + return "optimism-goerli.infura.io"; + case "optimism-sepolia": + return "optimism-sepolia.infura.io"; + } + assertArgument(false, "unsupported network", "network", name2); +} +class InfuraWebSocketProvider extends WebSocketProvider { + /** + * Creates a new **InfuraWebSocketProvider**. + */ + constructor(network2, projectId) { + const provider2 = new InfuraProvider(network2, projectId); + const req = provider2._getConnection(); + assert(!req.credentials, "INFURA WebSocket project secrets unsupported", "UNSUPPORTED_OPERATION", { operation: "InfuraProvider.getWebSocketProvider()" }); + const url = req.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/"); + super(url, provider2._network); + /** + * The Project ID for the INFURA connection. + */ + __publicField(this, "projectId"); + /** + * The Project Secret. + * + * If null, no authenticated requests are made. This should not + * be used outside of private contexts. + */ + __publicField(this, "projectSecret"); + defineProperties$1(this, { + projectId: provider2.projectId, + projectSecret: provider2.projectSecret + }); + } + isCommunityResource() { + return this.projectId === defaultProjectId; + } +} +class InfuraProvider extends JsonRpcProvider$1 { + /** + * Creates a new **InfuraProvider**. + */ + constructor(_network3, projectId, projectSecret) { + if (_network3 == null) { + _network3 = "mainnet"; + } + const network2 = Network.from(_network3); + if (projectId == null) { + projectId = defaultProjectId; + } + if (projectSecret == null) { + projectSecret = null; + } + const request = InfuraProvider.getRequest(network2, projectId, projectSecret); + super(request, network2, { staticNetwork: network2 }); + /** + * The Project ID for the INFURA connection. + */ + __publicField(this, "projectId"); + /** + * The Project Secret. + * + * If null, no authenticated requests are made. This should not + * be used outside of private contexts. + */ + __publicField(this, "projectSecret"); + defineProperties$1(this, { projectId, projectSecret }); + } + _getProvider(chainId) { + try { + return new InfuraProvider(chainId, this.projectId, this.projectSecret); + } catch (error) { + } + return super._getProvider(chainId); + } + isCommunityResource() { + return this.projectId === defaultProjectId; + } + /** + * Creates a new **InfuraWebSocketProvider**. + */ + static getWebSocketProvider(network2, projectId) { + return new InfuraWebSocketProvider(network2, projectId); + } + /** + * Returns a prepared request for connecting to %%network%% + * with %%projectId%% and %%projectSecret%%. + */ + static getRequest(network2, projectId, projectSecret) { + if (projectId == null) { + projectId = defaultProjectId; + } + if (projectSecret == null) { + projectSecret = null; + } + const request = new FetchRequest(`https://${getHost$2(network2.name)}/v3/${projectId}`); + request.allowGzip = true; + if (projectSecret) { + request.setCredentials("", projectSecret); + } + if (projectId === defaultProjectId) { + request.retryFunc = async (request2, response, attempt) => { + showThrottleMessage("InfuraProvider"); + return true; + }; + } + return request; + } +} +const defaultToken = "919b412a057b5e9c9b6dce193c5a60242d6efadb"; +function getHost$1(name2) { + switch (name2) { + case "mainnet": + return "ethers.quiknode.pro"; + case "goerli": + return "ethers.ethereum-goerli.quiknode.pro"; + case "sepolia": + return "ethers.ethereum-sepolia.quiknode.pro"; + case "holesky": + return "ethers.ethereum-holesky.quiknode.pro"; + case "arbitrum": + return "ethers.arbitrum-mainnet.quiknode.pro"; + case "arbitrum-goerli": + return "ethers.arbitrum-goerli.quiknode.pro"; + case "arbitrum-sepolia": + return "ethers.arbitrum-sepolia.quiknode.pro"; + case "base": + return "ethers.base-mainnet.quiknode.pro"; + case "base-goerli": + return "ethers.base-goerli.quiknode.pro"; + case "base-spolia": + return "ethers.base-sepolia.quiknode.pro"; + case "bnb": + return "ethers.bsc.quiknode.pro"; + case "bnbt": + return "ethers.bsc-testnet.quiknode.pro"; + case "matic": + return "ethers.matic.quiknode.pro"; + case "matic-mumbai": + return "ethers.matic-testnet.quiknode.pro"; + case "optimism": + return "ethers.optimism.quiknode.pro"; + case "optimism-goerli": + return "ethers.optimism-goerli.quiknode.pro"; + case "optimism-sepolia": + return "ethers.optimism-sepolia.quiknode.pro"; + case "xdai": + return "ethers.xdai.quiknode.pro"; + } + assertArgument(false, "unsupported network", "network", name2); +} +class QuickNodeProvider extends JsonRpcProvider$1 { + /** + * Creates a new **QuickNodeProvider**. + */ + constructor(_network3, token) { + if (_network3 == null) { + _network3 = "mainnet"; + } + const network2 = Network.from(_network3); + if (token == null) { + token = defaultToken; + } + const request = QuickNodeProvider.getRequest(network2, token); + super(request, network2, { staticNetwork: network2 }); + /** + * The API token. + */ + __publicField(this, "token"); + defineProperties$1(this, { token }); + } + _getProvider(chainId) { + try { + return new QuickNodeProvider(chainId, this.token); + } catch (error) { + } + return super._getProvider(chainId); + } + isCommunityResource() { + return this.token === defaultToken; + } + /** + * Returns a new request prepared for %%network%% and the + * %%token%%. + */ + static getRequest(network2, token) { + if (token == null) { + token = defaultToken; + } + const request = new FetchRequest(`https://${getHost$1(network2.name)}/${token}`); + request.allowGzip = true; + if (token === defaultToken) { + request.retryFunc = async (request2, response, attempt) => { + showThrottleMessage("QuickNodeProvider"); + return true; + }; + } + return request; + } +} +const BN_1 = BigInt("1"); +const BN_2 = BigInt("2"); +function shuffle(array) { + for (let i = array.length - 1; i > 0; i--) { + const j2 = Math.floor(Math.random() * (i + 1)); + const tmp = array[i]; + array[i] = array[j2]; + array[j2] = tmp; + } +} +function stall$2(duration) { + return new Promise((resolve) => { + setTimeout(resolve, duration); + }); +} +function getTime() { + return (/* @__PURE__ */ new Date()).getTime(); +} +function stringify$1(value) { + return JSON.stringify(value, (key, value2) => { + if (typeof value2 === "bigint") { + return { type: "bigint", value: value2.toString() }; + } + return value2; + }); +} +const defaultConfig = { stallTimeout: 400, priority: 1, weight: 1 }; +const defaultState = { + blockNumber: -2, + requests: 0, + lateResponses: 0, + errorResponses: 0, + outOfSync: -1, + unsupportedEvents: 0, + rollingDuration: 0, + score: 0, + _network: null, + _updateNumber: null, + _totalTime: 0, + _lastFatalError: null, + _lastFatalErrorTimestamp: 0 +}; +async function waitForSync(config2, blockNumber) { + while (config2.blockNumber < 0 || config2.blockNumber < blockNumber) { + if (!config2._updateNumber) { + config2._updateNumber = (async () => { + try { + const blockNumber2 = await config2.provider.getBlockNumber(); + if (blockNumber2 > config2.blockNumber) { + config2.blockNumber = blockNumber2; } - if (this._removeListener) - this.emit("removeListener", type, listener); + } catch (error) { + config2.blockNumber = -2; + config2._lastFatalError = error; + config2._lastFatalErrorTimestamp = getTime(); } + config2._updateNumber = null; + })(); + } + await config2._updateNumber; + config2.outOfSync++; + if (config2._lastFatalError) { + break; + } + } +} +function _normalize(value) { + if (value == null) { + return "null"; + } + if (Array.isArray(value)) { + return "[" + value.map(_normalize).join(",") + "]"; + } + if (typeof value === "object" && typeof value.toJSON === "function") { + return _normalize(value.toJSON()); + } + switch (typeof value) { + case "boolean": + case "symbol": + return value.toString(); + case "bigint": + case "number": + return BigInt(value).toString(); + case "string": + return JSON.stringify(value); + case "object": { + const keys = Object.keys(value); + keys.sort(); + return "{" + keys.map((k2) => `${JSON.stringify(k2)}:${_normalize(value[k2])}`).join(",") + "}"; + } + } + console.log("Could not serialize", value); + throw new Error("Hmm..."); +} +function normalizeResult(value) { + if ("error" in value) { + const error = value.error; + return { tag: _normalize(error), value: error }; + } + const result = value.result; + return { tag: _normalize(result), value: result }; +} +function checkQuorum(quorum, results2) { + const tally = /* @__PURE__ */ new Map(); + for (const { value, tag, weight } of results2) { + const t2 = tally.get(tag) || { value, weight: 0 }; + t2.weight += weight; + tally.set(tag, t2); + } + let best = null; + for (const r2 of tally.values()) { + if (r2.weight >= quorum && (!best || r2.weight > best.weight)) { + best = r2; + } + } + if (best) { + return best.value; + } + return void 0; +} +function getMedian(quorum, results2) { + let resultWeight = 0; + const errorMap = /* @__PURE__ */ new Map(); + let bestError = null; + const values = []; + for (const { value, tag, weight } of results2) { + if (value instanceof Error) { + const e2 = errorMap.get(tag) || { value, weight: 0 }; + e2.weight += weight; + errorMap.set(tag, e2); + if (bestError == null || e2.weight > bestError.weight) { + bestError = e2; } - this.listenerTree && recursivelyGarbageCollect(this.listenerTree); - return this; - }; - EventEmitter2.prototype.offAny = function(fn) { - var i = 0, l2 = 0, fns; - if (fn && this._all && this._all.length > 0) { - fns = this._all; - for (i = 0, l2 = fns.length; i < l2; i++) { - if (fn === fns[i]) { - fns.splice(i, 1); - if (this._removeListener) - this.emit("removeListenerAny", fn); - return this; - } - } + } else { + values.push(BigInt(value)); + resultWeight += weight; + } + } + if (resultWeight < quorum) { + if (bestError && bestError.weight >= quorum) { + return bestError.value; + } + return void 0; + } + values.sort((a2, b2) => a2 < b2 ? -1 : b2 > a2 ? 1 : 0); + const mid = Math.floor(values.length / 2); + if (values.length % 2) { + return values[mid]; + } + return (values[mid - 1] + values[mid] + BN_1) / BN_2; +} +function getAnyResult(quorum, results2) { + const result = checkQuorum(quorum, results2); + if (result !== void 0) { + return result; + } + for (const r2 of results2) { + if (r2.value) { + return r2.value; + } + } + return void 0; +} +function getFuzzyMode(quorum, results2) { + if (quorum === 1) { + return getNumber(getMedian(quorum, results2), "%internal"); + } + const tally = /* @__PURE__ */ new Map(); + const add2 = (result, weight) => { + const t2 = tally.get(result) || { result, weight: 0 }; + t2.weight += weight; + tally.set(result, t2); + }; + for (const { weight, value } of results2) { + const r2 = getNumber(value); + add2(r2 - 1, weight); + add2(r2, weight); + add2(r2 + 1, weight); + } + let bestWeight = 0; + let bestResult = void 0; + for (const { weight, result } of tally.values()) { + if (weight >= quorum && (weight > bestWeight || bestResult != null && weight === bestWeight && result > bestResult)) { + bestWeight = weight; + bestResult = result; + } + } + return bestResult; +} +class FallbackProvider extends AbstractProvider { + /** + * Creates a new **FallbackProvider** with %%providers%% connected to + * %%network%%. + * + * If a [[Provider]] is included in %%providers%%, defaults are used + * for the configuration. + */ + constructor(providers, network2, options) { + super(network2, options); + __privateAdd(this, _FallbackProvider_instances); + /** + * The number of backends that must agree on a value before it is + * accpeted. + */ + __publicField(this, "quorum"); + /** + * @_ignore: + */ + __publicField(this, "eventQuorum"); + /** + * @_ignore: + */ + __publicField(this, "eventWorkers"); + __privateAdd(this, _configs); + __privateAdd(this, _height); + __privateAdd(this, _initialSyncPromise); + __privateSet(this, _configs, providers.map((p2) => { + if (p2 instanceof AbstractProvider) { + return Object.assign({ provider: p2 }, defaultConfig, defaultState); } else { - fns = this._all; - if (this._removeListener) { - for (i = 0, l2 = fns.length; i < l2; i++) - this.emit("removeListenerAny", fns[i]); - } - this._all = []; - } - return this; - }; - EventEmitter2.prototype.removeListener = EventEmitter2.prototype.off; - EventEmitter2.prototype.removeAllListeners = function(type) { - if (type === undefined$1) { - !this._events || init2.call(this); - return this; + return Object.assign({}, defaultConfig, p2, defaultState); } - if (this.wildcard) { - var leafs = searchListenerTree.call(this, null, type, this.listenerTree, 0), leaf, i; - if (!leafs) return this; - for (i = 0; i < leafs.length; i++) { - leaf = leafs[i]; - leaf._listeners = null; + })); + __privateSet(this, _height, -2); + __privateSet(this, _initialSyncPromise, null); + if (options && options.quorum != null) { + this.quorum = options.quorum; + } else { + this.quorum = Math.ceil(__privateGet(this, _configs).reduce((accum, config2) => { + accum += config2.weight; + return accum; + }, 0) / 2); + } + this.eventQuorum = 1; + this.eventWorkers = 1; + assertArgument(this.quorum <= __privateGet(this, _configs).reduce((a2, c2) => a2 + c2.weight, 0), "quorum exceed provider weight", "quorum", this.quorum); + } + get providerConfigs() { + return __privateGet(this, _configs).map((c2) => { + const result = Object.assign({}, c2); + for (const key in result) { + if (key[0] === "_") { + delete result[key]; } - this.listenerTree && recursivelyGarbageCollect(this.listenerTree); - } else if (this._events) { - this._events[type] = null; } - return this; - }; - EventEmitter2.prototype.listeners = function(type) { - var _events2 = this._events; - var keys, listeners, allListeners; - var i; - var listenerTree; - if (type === undefined$1) { - if (this.wildcard) { - throw Error("event name required for wildcard emitter"); - } - if (!_events2) { - return []; + return result; + }); + } + async _detectNetwork() { + return Network.from(getBigInt(await this._perform({ method: "chainId" }))); + } + // @TODO: Add support to select providers to be the event subscriber + //_getSubscriber(sub: Subscription): Subscriber { + // throw new Error("@TODO"); + //} + /** + * Transforms a %%req%% into the correct method call on %%provider%%. + */ + async _translatePerform(provider2, req) { + switch (req.method) { + case "broadcastTransaction": + return await provider2.broadcastTransaction(req.signedTransaction); + case "call": + return await provider2.call(Object.assign({}, req.transaction, { blockTag: req.blockTag })); + case "chainId": + return (await provider2.getNetwork()).chainId; + case "estimateGas": + return await provider2.estimateGas(req.transaction); + case "getBalance": + return await provider2.getBalance(req.address, req.blockTag); + case "getBlock": { + const block = "blockHash" in req ? req.blockHash : req.blockTag; + return await provider2.getBlock(block, req.includeTransactions); + } + case "getBlockNumber": + return await provider2.getBlockNumber(); + case "getCode": + return await provider2.getCode(req.address, req.blockTag); + case "getGasPrice": + return (await provider2.getFeeData()).gasPrice; + case "getPriorityFee": + return (await provider2.getFeeData()).maxPriorityFeePerGas; + case "getLogs": + return await provider2.getLogs(req.filter); + case "getStorage": + return await provider2.getStorage(req.address, req.position, req.blockTag); + case "getTransaction": + return await provider2.getTransaction(req.hash); + case "getTransactionCount": + return await provider2.getTransactionCount(req.address, req.blockTag); + case "getTransactionReceipt": + return await provider2.getTransactionReceipt(req.hash); + case "getTransactionResult": + return await provider2.getTransactionResult(req.hash); + } + } + async _perform(req) { + if (req.method === "broadcastTransaction") { + const results2 = __privateGet(this, _configs).map((c2) => null); + const broadcasts = __privateGet(this, _configs).map(async ({ provider: provider2, weight }, index2) => { + try { + const result3 = await provider2._perform(req); + results2[index2] = Object.assign(normalizeResult({ result: result3 }), { weight }); + } catch (error) { + results2[index2] = Object.assign(normalizeResult({ error }), { weight }); } - keys = ownKeys2(_events2); - i = keys.length; - allListeners = []; - while (i-- > 0) { - listeners = _events2[keys[i]]; - if (typeof listeners === "function") { - allListeners.push(listeners); - } else { - allListeners.push.apply(allListeners, listeners); + }); + while (true) { + const done = results2.filter((r2) => r2 != null); + for (const { value } of done) { + if (!(value instanceof Error)) { + return value; } } - return allListeners; - } else { - if (this.wildcard) { - listenerTree = this.listenerTree; - if (!listenerTree) return []; - var handlers = []; - var ns = typeof type === "string" ? type.split(this.delimiter) : type.slice(); - searchListenerTree.call(this, handlers, ns, listenerTree, 0); - return handlers; - } - if (!_events2) { - return []; + const result3 = checkQuorum(this.quorum, results2.filter((r2) => r2 != null)); + if (isError(result3, "INSUFFICIENT_FUNDS")) { + throw result3; } - listeners = _events2[type]; - if (!listeners) { - return []; + const waiting = broadcasts.filter((b2, i) => results2[i] == null); + if (waiting.length === 0) { + break; } - return typeof listeners === "function" ? [listeners] : listeners; + await Promise.race(waiting); } - }; - EventEmitter2.prototype.eventNames = function(nsAsArray) { - var _events2 = this._events; - return this.wildcard ? collectTreeEvents.call(this, this.listenerTree, [], null, nsAsArray) : _events2 ? ownKeys2(_events2) : []; - }; - EventEmitter2.prototype.listenerCount = function(type) { - return this.listeners(type).length; - }; - EventEmitter2.prototype.hasListeners = function(type) { - if (this.wildcard) { - var handlers = []; - var ns = typeof type === "string" ? type.split(this.delimiter) : type.slice(); - searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); - return handlers.length > 0; + const result2 = getAnyResult(this.quorum, results2); + assert(result2 !== void 0, "problem multi-broadcasting", "SERVER_ERROR", { + request: "%sub-requests", + info: { request: req, results: results2.map(stringify$1) } + }); + if (result2 instanceof Error) { + throw result2; } - var _events2 = this._events; - var _all = this._all; - return !!(_all && _all.length || _events2 && (type === undefined$1 ? ownKeys2(_events2).length : _events2[type])); - }; - EventEmitter2.prototype.listenersAny = function() { - if (this._all) { - return this._all; - } else { - return []; + return result2; + } + await __privateMethod(this, _FallbackProvider_instances, initialSync_fn).call(this); + const running = /* @__PURE__ */ new Set(); + let inflightQuorum = 0; + while (true) { + const runner = __privateMethod(this, _FallbackProvider_instances, addRunner_fn).call(this, running, req); + if (runner == null) { + break; } - }; - EventEmitter2.prototype.waitFor = function(event, options) { - var self2 = this; - var type = typeof options; - if (type === "number") { - options = { timeout: options }; - } else if (type === "function") { - options = { filter: options }; + inflightQuorum += runner.config.weight; + if (inflightQuorum >= this.quorum) { + break; } - options = resolveOptions(options, { - timeout: 0, - filter: undefined$1, - handleError: false, - Promise, - overload: false - }, { - filter: functionReducer, - Promise: constructorReducer - }); - return makeCancelablePromise(options.Promise, function(resolve, reject, onCancel) { - function listener() { - var filter2 = options.filter; - if (filter2 && !filter2.apply(self2, arguments)) { - return; - } - self2.off(event, listener); - if (options.handleError) { - var err = arguments[0]; - err ? reject(err) : resolve(toArray.apply(null, arguments).slice(1)); - } else { - resolve(toArray.apply(null, arguments)); - } + } + const result = await __privateMethod(this, _FallbackProvider_instances, waitForQuorum_fn).call(this, running, req); + for (const runner of running) { + if (runner.perform && runner.result == null) { + runner.config.lateResponses++; + } + } + return result; + } + async destroy() { + for (const { provider: provider2 } of __privateGet(this, _configs)) { + provider2.destroy(); + } + super.destroy(); + } +} +_configs = new WeakMap(); +_height = new WeakMap(); +_initialSyncPromise = new WeakMap(); +_FallbackProvider_instances = new WeakSet(); +// Grab the next (random) config that is not already part of +// the running set +getNextConfig_fn = function(running) { + const configs = Array.from(running).map((r2) => r2.config); + const allConfigs = __privateGet(this, _configs).slice(); + shuffle(allConfigs); + allConfigs.sort((a2, b2) => a2.priority - b2.priority); + for (const config2 of allConfigs) { + if (config2._lastFatalError) { + continue; + } + if (configs.indexOf(config2) === -1) { + return config2; + } + } + return null; +}; +// Adds a new runner (if available) to running. +addRunner_fn = function(running, req) { + const config2 = __privateMethod(this, _FallbackProvider_instances, getNextConfig_fn).call(this, running); + if (config2 == null) { + return null; + } + const runner = { + config: config2, + result: null, + didBump: false, + perform: null, + staller: null + }; + const now = getTime(); + runner.perform = (async () => { + try { + config2.requests++; + const result = await this._translatePerform(config2.provider, req); + runner.result = { result }; + } catch (error) { + config2.errorResponses++; + runner.result = { error }; + } + const dt = getTime() - now; + config2._totalTime += dt; + config2.rollingDuration = 0.95 * config2.rollingDuration + 0.05 * dt; + runner.perform = null; + })(); + runner.staller = (async () => { + await stall$2(config2.stallTimeout); + runner.staller = null; + })(); + running.add(runner); + return runner; +}; +initialSync_fn = async function() { + let initialSync = __privateGet(this, _initialSyncPromise); + if (!initialSync) { + const promises = []; + __privateGet(this, _configs).forEach((config2) => { + promises.push((async () => { + await waitForSync(config2, 0); + if (!config2._lastFatalError) { + config2._network = await config2.provider.getNetwork(); } - onCancel(function() { - self2.off(event, listener); - }); - self2._on(event, listener, false); - }, { - timeout: options.timeout, - overload: options.overload - }); - }; - function once(emitter, name2, options) { - options = resolveOptions(options, { - Promise, - timeout: 0, - overload: false - }, { - Promise: constructorReducer - }); - var _Promise = options.Promise; - return makeCancelablePromise(_Promise, function(resolve, reject, onCancel) { - var handler; - if (typeof emitter.addEventListener === "function") { - handler = function() { - resolve(toArray.apply(null, arguments)); - }; - onCancel(function() { - emitter.removeEventListener(name2, handler); - }); - emitter.addEventListener( - name2, - handler, - { once: true } - ); - return; + })()); + }); + __privateSet(this, _initialSyncPromise, initialSync = (async () => { + await Promise.all(promises); + let chainId = null; + for (const config2 of __privateGet(this, _configs)) { + if (config2._lastFatalError) { + continue; } - var eventListener = function() { - errorListener && emitter.removeListener("error", errorListener); - resolve(toArray.apply(null, arguments)); - }; - var errorListener; - if (name2 !== "error") { - errorListener = function(err) { - emitter.removeListener(name2, eventListener); - reject(err); - }; - emitter.once("error", errorListener); + const network2 = config2._network; + if (chainId == null) { + chainId = network2.chainId; + } else if (network2.chainId !== chainId) { + assert(false, "cannot mix providers on different networks", "UNSUPPORTED_OPERATION", { + operation: "new FallbackProvider" + }); } - onCancel(function() { - errorListener && emitter.removeListener("error", errorListener); - emitter.removeListener(name2, eventListener); - }); - emitter.once(name2, eventListener); - }, { - timeout: options.timeout, - overload: options.overload - }); + } + })()); + } + await initialSync; +}; +checkQuorum_fn = async function(running, req) { + const results2 = []; + for (const runner of running) { + if (runner.result != null) { + const { tag, value } = normalizeResult(runner.result); + results2.push({ tag, value, weight: runner.config.weight }); } - var prototype = EventEmitter2.prototype; - Object.defineProperties(EventEmitter2, { - defaultMaxListeners: { - get: function() { - return prototype._maxListeners; - }, - set: function(n2) { - if (typeof n2 !== "number" || n2 < 0 || Number.isNaN(n2)) { - throw TypeError("n must be a non-negative number"); - } - prototype._maxListeners = n2; - }, - enumerable: true - }, - once: { - value: once, - writable: true, - configurable: true + } + if (results2.reduce((a2, r2) => a2 + r2.weight, 0) < this.quorum) { + return void 0; + } + switch (req.method) { + case "getBlockNumber": { + if (__privateGet(this, _height) === -2) { + __privateSet(this, _height, Math.ceil(getNumber(getMedian(this.quorum, __privateGet(this, _configs).filter((c2) => !c2._lastFatalError).map((c2) => ({ + value: c2.blockNumber, + tag: getNumber(c2.blockNumber).toString(), + weight: c2.weight + })))))); } - }); - Object.defineProperties(prototype, { - _maxListeners: { - value: defaultMaxListeners, - writable: true, - configurable: true - }, - _observers: { value: null, writable: true, configurable: true } - }); - { - module2.exports = EventEmitter2; + const mode = getFuzzyMode(this.quorum, results2); + if (mode === void 0) { + return void 0; + } + if (mode > __privateGet(this, _height)) { + __privateSet(this, _height, mode); + } + return __privateGet(this, _height); } - }(); -})(eventemitter2); -var eventemitter2Exports = eventemitter2.exports; -function isBytes$2(a2) { - return a2 instanceof Uint8Array || a2 != null && typeof a2 === "object" && a2.constructor.name === "Uint8Array"; -} -function bytes$1(b2, ...lengths) { - if (!isBytes$2(b2)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b2.length)) - throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b2.length}`); -} -function exists$1(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function output$1(out, instance) { - bytes$1(out); - const min2 = instance.outputLen; - if (out.length < min2) { - throw new Error(`digestInto() expects output buffer of length at least ${min2}`); + case "getGasPrice": + case "getPriorityFee": + case "estimateGas": + return getMedian(this.quorum, results2); + case "getBlock": + if ("blockTag" in req && req.blockTag === "pending") { + return getAnyResult(this.quorum, results2); + } + return checkQuorum(this.quorum, results2); + case "call": + case "chainId": + case "getBalance": + case "getTransactionCount": + case "getCode": + case "getStorage": + case "getTransaction": + case "getTransactionReceipt": + case "getLogs": + return checkQuorum(this.quorum, results2); + case "broadcastTransaction": + return getAnyResult(this.quorum, results2); } -} -/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -const rotr$1 = (word, shift2) => word << 32 - shift2 | word >>> shift2; -new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; -const hexes$2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); -function bytesToHex$2(bytes2) { - bytes$1(bytes2); - let hex2 = ""; - for (let i = 0; i < bytes2.length; i++) { - hex2 += hexes$2[bytes2[i]]; + assert(false, "unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${stringify$1(req.method)})` + }); +}; +waitForQuorum_fn = async function(running, req) { + if (running.size === 0) { + throw new Error("no runners?!"); } - return hex2; -} -function utf8ToBytes$2(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); + const interesting = []; + let newRunners = 0; + for (const runner of running) { + if (runner.perform) { + interesting.push(runner.perform); + } + if (runner.staller) { + interesting.push(runner.staller); + continue; + } + if (runner.didBump) { + continue; + } + runner.didBump = true; + newRunners++; + } + const value = await __privateMethod(this, _FallbackProvider_instances, checkQuorum_fn).call(this, running, req); + if (value !== void 0) { + if (value instanceof Error) { + throw value; + } + return value; + } + for (let i = 0; i < newRunners; i++) { + __privateMethod(this, _FallbackProvider_instances, addRunner_fn).call(this, running, req); + } + assert(interesting.length > 0, "quorum not met", "SERVER_ERROR", { + request: "%sub-requests", + info: { request: req, results: Array.from(running).map((r2) => stringify$1(r2.result)) } + }); + await Promise.race(interesting); + return await __privateMethod(this, _FallbackProvider_instances, waitForQuorum_fn).call(this, running, req); +}; +function isWebSocketLike(value) { + return value && typeof value.send === "function" && typeof value.close === "function"; } -function toBytes$2(data) { - if (typeof data === "string") - data = utf8ToBytes$2(data); - bytes$1(data); - return data; +const Testnets = "goerli kovan sepolia classicKotti optimism-goerli arbitrum-goerli matic-mumbai bnbt".split(" "); +function getDefaultProvider(network2, options) { + if (options == null) { + options = {}; + } + const allowService = (name2) => { + if (options[name2] === "-") { + return false; + } + if (typeof options.exclusive === "string") { + return name2 === options.exclusive; + } + if (Array.isArray(options.exclusive)) { + return options.exclusive.indexOf(name2) !== -1; + } + return true; + }; + if (typeof network2 === "string" && network2.match(/^https?:/)) { + return new JsonRpcProvider$1(network2); + } + if (typeof network2 === "string" && network2.match(/^wss?:/) || isWebSocketLike(network2)) { + return new WebSocketProvider(network2); + } + let staticNetwork = null; + try { + staticNetwork = Network.from(network2); + } catch (error) { + } + const providers = []; + if (allowService("publicPolygon") && staticNetwork) { + if (staticNetwork.name === "matic") { + providers.push(new JsonRpcProvider$1("https://polygon-rpc.com/", staticNetwork, { staticNetwork })); + } else if (staticNetwork.name === "matic-amoy") { + providers.push(new JsonRpcProvider$1("https://rpc-amoy.polygon.technology/", staticNetwork, { staticNetwork })); + } + } + if (allowService("alchemy")) { + try { + providers.push(new AlchemyProvider(network2, options.alchemy)); + } catch (error) { + } + } + if (allowService("ankr") && options.ankr != null) { + try { + providers.push(new AnkrProvider(network2, options.ankr)); + } catch (error) { + } + } + if (allowService("chainstack")) { + try { + providers.push(new ChainstackProvider(network2, options.chainstack)); + } catch (error) { + } + } + if (allowService("cloudflare")) { + try { + providers.push(new CloudflareProvider(network2)); + } catch (error) { + } + } + if (allowService("etherscan")) { + try { + providers.push(new EtherscanProvider(network2, options.etherscan)); + } catch (error) { + } + } + if (allowService("infura")) { + try { + let projectId = options.infura; + let projectSecret = void 0; + if (typeof projectId === "object") { + projectSecret = projectId.projectSecret; + projectId = projectId.projectId; + } + providers.push(new InfuraProvider(network2, projectId, projectSecret)); + } catch (error) { + } + } + if (allowService("quicknode")) { + try { + let token = options.quicknode; + providers.push(new QuickNodeProvider(network2, token)); + } catch (error) { + } + } + assert(providers.length, "unsupported default network", "UNSUPPORTED_OPERATION", { + operation: "getDefaultProvider" + }); + if (providers.length === 1) { + return providers[0]; + } + let quorum = Math.floor(providers.length / 2); + if (quorum > 2) { + quorum = 2; + } + if (staticNetwork && Testnets.indexOf(staticNetwork.name) !== -1) { + quorum = 1; + } + if (options && options.quorum) { + quorum = options.quorum; + } + return new FallbackProvider(providers, void 0, { quorum }); } -let Hash$1 = class Hash2 { - // Safe version that clones internal state - clone() { - return this._cloneInto(); +const _NonceManager = class _NonceManager extends AbstractSigner { + /** + * Creates a new **NonceManager** to manage %%signer%%. + */ + constructor(signer2) { + super(signer2.provider); + /** + * The Signer being managed. + */ + __publicField(this, "signer"); + __privateAdd(this, _noncePromise); + __privateAdd(this, _delta); + defineProperties$1(this, { signer: signer2 }); + __privateSet(this, _noncePromise, null); + __privateSet(this, _delta, 0); + } + async getAddress() { + return this.signer.getAddress(); + } + connect(provider2) { + return new _NonceManager(this.signer.connect(provider2)); + } + async getNonce(blockTag) { + if (blockTag === "pending") { + if (__privateGet(this, _noncePromise) == null) { + __privateSet(this, _noncePromise, super.getNonce("pending")); + } + const delta = __privateGet(this, _delta); + return await __privateGet(this, _noncePromise) + delta; + } + return super.getNonce(blockTag); + } + /** + * Manually increment the nonce. This may be useful when managng + * offline transactions. + */ + increment() { + __privateWrapper(this, _delta)._++; + } + /** + * Resets the nonce, causing the **NonceManager** to reload the current + * nonce from the blockchain on the next transaction. + */ + reset() { + __privateSet(this, _delta, 0); + __privateSet(this, _noncePromise, null); + } + async sendTransaction(tx) { + const noncePromise = this.getNonce("pending"); + this.increment(); + tx = await this.signer.populateTransaction(tx); + tx.nonce = await noncePromise; + return await this.signer.sendTransaction(tx); + } + signTransaction(tx) { + return this.signer.signTransaction(tx); + } + signMessage(message) { + return this.signer.signMessage(message); + } + signTypedData(domain2, types2, value) { + return this.signer.signTypedData(domain2, types2, value); + } +}; +_noncePromise = new WeakMap(); +_delta = new WeakMap(); +let NonceManager = _NonceManager; +class BrowserProvider extends JsonRpcApiPollingProvider { + /** + * Connnect to the %%ethereum%% provider, optionally forcing the + * %%network%%. + */ + constructor(ethereum, network2, _options4) { + const options = Object.assign({}, _options4 != null ? _options4 : {}, { batchMaxCount: 1 }); + assertArgument(ethereum && ethereum.request, "invalid EIP-1193 provider", "ethereum", ethereum); + super(network2, options); + __privateAdd(this, _request2); + __privateSet(this, _request2, async (method, params) => { + const payload = { method, params }; + this.emit("debug", { action: "sendEip1193Request", payload }); + try { + const result = await ethereum.request(payload); + this.emit("debug", { action: "receiveEip1193Result", result }); + return result; + } catch (e2) { + const error = new Error(e2.message); + error.code = e2.code; + error.data = e2.data; + error.payload = payload; + this.emit("debug", { action: "receiveEip1193Error", error }); + throw error; + } + }); + } + async send(method, params) { + await this._start(); + return await super.send(method, params); + } + async _send(payload) { + assertArgument(!Array.isArray(payload), "EIP-1193 does not support batch request", "payload", payload); + try { + const result = await __privateGet(this, _request2).call(this, payload.method, payload.params || []); + return [{ id: payload.id, result }]; + } catch (e2) { + return [{ + id: payload.id, + error: { code: e2.code, data: e2.data, message: e2.message } + }]; + } + } + getRpcError(payload, error) { + error = JSON.parse(JSON.stringify(error)); + switch (error.error.code || -1) { + case 4001: + error.error.message = `ethers-user-denied: ${error.error.message}`; + break; + case 4200: + error.error.message = `ethers-unsupported: ${error.error.message}`; + break; + } + return super.getRpcError(payload, error); + } + /** + * Resolves to ``true`` if the provider manages the %%address%%. + */ + async hasSigner(address) { + if (address == null) { + address = 0; + } + const accounts = await this.send("eth_accounts", []); + if (typeof address === "number") { + return accounts.length > address; + } + address = address.toLowerCase(); + return accounts.filter((a2) => a2.toLowerCase() === address).length !== 0; + } + async getSigner(address) { + if (address == null) { + address = 0; + } + if (!await this.hasSigner(address)) { + try { + await __privateGet(this, _request2).call(this, "eth_requestAccounts", []); + } catch (error) { + const payload = error.payload; + throw this.getRpcError(payload, { id: payload.id, error }); + } + } + return await super.getSigner(address); } -}; -function wrapConstructor$1(hashCons) { - const hashC = (msg) => hashCons().update(toBytes$2(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; } -function setBigUint64$1(view, byteOffset, value, isLE2) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE2); - const _32n2 = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh2 = Number(value >> _32n2 & _u32_max); - const wl = Number(value & _u32_max); - const h2 = isLE2 ? 4 : 0; - const l2 = isLE2 ? 0 : 4; - view.setUint32(byteOffset + h2, wh2, isLE2); - view.setUint32(byteOffset + l2, wl, isLE2); +_request2 = new WeakMap(); +const defaultApplicationId = "62e1ad51b37b8e00394bda3b"; +function getHost(name2) { + switch (name2) { + case "mainnet": + return "eth-mainnet.gateway.pokt.network"; + case "goerli": + return "eth-goerli.gateway.pokt.network"; + case "matic": + return "poly-mainnet.gateway.pokt.network"; + case "matic-mumbai": + return "polygon-mumbai-rpc.gateway.pokt.network"; + } + assertArgument(false, "unsupported network", "network", name2); } -const Chi$1 = (a2, b2, c2) => a2 & b2 ^ ~a2 & c2; -const Maj$1 = (a2, b2, c2) => a2 & b2 ^ a2 & c2 ^ b2 & c2; -let HashMD$1 = class HashMD extends Hash$1 { - constructor(blockLen, outputLen, padOffset, isLE2) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE2; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView$1(this.buffer); +class PocketProvider extends JsonRpcProvider$1 { + /** + * Create a new **PocketProvider**. + * + * By default connecting to ``mainnet`` with a highly throttled + * API key. + */ + constructor(_network3, applicationId, applicationSecret) { + if (_network3 == null) { + _network3 = "mainnet"; + } + const network2 = Network.from(_network3); + if (applicationId == null) { + applicationId = defaultApplicationId; + } + if (applicationSecret == null) { + applicationSecret = null; + } + const options = { staticNetwork: network2 }; + const request = PocketProvider.getRequest(network2, applicationId, applicationSecret); + super(request, network2, options); + /** + * The Application ID for the Pocket connection. + */ + __publicField(this, "applicationId"); + /** + * The Application Secret for making authenticated requests + * to the Pocket connection. + */ + __publicField(this, "applicationSecret"); + defineProperties$1(this, { applicationId, applicationSecret }); } - update(data) { - exists$1(this); - const { view, buffer: buffer2, blockLen } = this; - data = toBytes$2(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView$1(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer2.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } + _getProvider(chainId) { + try { + return new PocketProvider(chainId, this.applicationId, this.applicationSecret); + } catch (error) { } - this.length += data.length; - this.roundClean(); - return this; + return super._getProvider(chainId); } - digestInto(out) { - exists$1(this); - output$1(out, this); - this.finished = true; - const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; - let { pos } = this; - buffer2[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; + /** + * Returns a prepared request for connecting to %%network%% with + * %%applicationId%%. + */ + static getRequest(network2, applicationId, applicationSecret) { + if (applicationId == null) { + applicationId = defaultApplicationId; } - for (let i = pos; i < blockLen; i++) - buffer2[i] = 0; - setBigUint64$1(view, blockLen - 8, BigInt(this.length * 8), isLE2); - this.process(view, 0); - const oview = createView$1(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE2); + const request = new FetchRequest(`https://${getHost(network2.name)}/v1/lb/${applicationId}`); + request.allowGzip = true; + if (applicationSecret) { + request.setCredentials("", applicationSecret); + } + if (applicationId === defaultApplicationId) { + request.retryFunc = async (request2, response, attempt) => { + showThrottleMessage("PocketProvider"); + return true; + }; + } + return request; } - digest() { - const { buffer: buffer2, outputLen } = this; - this.digestInto(buffer2); - const res = buffer2.slice(0, outputLen); - this.destroy(); - return res; + isCommunityResource() { + return this.applicationId === defaultApplicationId; } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer2); - return to; +} +const IpcSocketProvider = void 0; +const _BaseWallet = class _BaseWallet extends AbstractSigner { + /** + * Creates a new BaseWallet for %%privateKey%%, optionally + * connected to %%provider%%. + * + * If %%provider%% is not specified, only offline methods can + * be used. + */ + constructor(privateKey, provider2) { + super(provider2); + /** + * The wallet address. + */ + __publicField(this, "address"); + __privateAdd(this, _signingKey); + assertArgument(privateKey && typeof privateKey.sign === "function", "invalid private key", "privateKey", "[ REDACTED ]"); + __privateSet(this, _signingKey, privateKey); + const address = computeAddress(this.signingKey.publicKey); + defineProperties$1(this, { address }); } -}; -const SHA256_K$1 = /* @__PURE__ */ new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]); -const SHA256_IV$1 = /* @__PURE__ */ new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -const SHA256_W$1 = /* @__PURE__ */ new Uint32Array(64); -let SHA256$1 = class SHA2562 extends HashMD$1 { - constructor() { - super(64, 32, 8, false); - this.A = SHA256_IV$1[0] | 0; - this.B = SHA256_IV$1[1] | 0; - this.C = SHA256_IV$1[2] | 0; - this.D = SHA256_IV$1[3] | 0; - this.E = SHA256_IV$1[4] | 0; - this.F = SHA256_IV$1[5] | 0; - this.G = SHA256_IV$1[6] | 0; - this.H = SHA256_IV$1[7] | 0; + // Store private values behind getters to reduce visibility + // in console.log + /** + * The [[SigningKey]] used for signing payloads. + */ + get signingKey() { + return __privateGet(this, _signingKey); } - get() { - const { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; - return [A2, B2, C2, D2, E2, F2, G2, H2]; + /** + * The private key for this wallet. + */ + get privateKey() { + return this.signingKey.privateKey; } - // prettier-ignore - set(A2, B2, C2, D2, E2, F2, G2, H2) { - this.A = A2 | 0; - this.B = B2 | 0; - this.C = C2 | 0; - this.D = D2 | 0; - this.E = E2 | 0; - this.F = F2 | 0; - this.G = G2 | 0; - this.H = H2 | 0; + async getAddress() { + return this.address; } - process(view, offset2) { - for (let i = 0; i < 16; i++, offset2 += 4) - SHA256_W$1[i] = view.getUint32(offset2, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W$1[i - 15]; - const W2 = SHA256_W$1[i - 2]; - const s0 = rotr$1(W15, 7) ^ rotr$1(W15, 18) ^ W15 >>> 3; - const s1 = rotr$1(W2, 17) ^ rotr$1(W2, 19) ^ W2 >>> 10; - SHA256_W$1[i] = s1 + SHA256_W$1[i - 7] + s0 + SHA256_W$1[i - 16] | 0; + connect(provider2) { + return new _BaseWallet(__privateGet(this, _signingKey), provider2); + } + async signTransaction(tx) { + const { to, from } = await resolveProperties$1({ + to: tx.to ? resolveAddress(tx.to, this.provider) : void 0, + from: tx.from ? resolveAddress(tx.from, this.provider) : void 0 + }); + if (to != null) { + tx.to = to; } - let { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr$1(E2, 6) ^ rotr$1(E2, 11) ^ rotr$1(E2, 25); - const T12 = H2 + sigma1 + Chi$1(E2, F2, G2) + SHA256_K$1[i] + SHA256_W$1[i] | 0; - const sigma0 = rotr$1(A2, 2) ^ rotr$1(A2, 13) ^ rotr$1(A2, 22); - const T22 = sigma0 + Maj$1(A2, B2, C2) | 0; - H2 = G2; - G2 = F2; - F2 = E2; - E2 = D2 + T12 | 0; - D2 = C2; - C2 = B2; - B2 = A2; - A2 = T12 + T22 | 0; + if (from != null) { + tx.from = from; } - A2 = A2 + this.A | 0; - B2 = B2 + this.B | 0; - C2 = C2 + this.C | 0; - D2 = D2 + this.D | 0; - E2 = E2 + this.E | 0; - F2 = F2 + this.F | 0; - G2 = G2 + this.G | 0; - H2 = H2 + this.H | 0; - this.set(A2, B2, C2, D2, E2, F2, G2, H2); + if (tx.from != null) { + assertArgument(getAddress(tx.from) === this.address, "transaction from address mismatch", "tx.from", tx.from); + delete tx.from; + } + const btx = Transaction.from(tx); + btx.signature = this.signingKey.sign(btx.unsignedHash); + return btx.serialized; } - roundClean() { - SHA256_W$1.fill(0); + async signMessage(message) { + return this.signMessageSync(message); } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); + // @TODO: Add a secialized signTx and signTyped sync that enforces + // all parameters are known? + /** + * Returns the signature for %%message%% signed with this wallet. + */ + signMessageSync(message) { + return this.signingKey.sign(hashMessage(message)).serialized; } -}; -const sha256$2 = /* @__PURE__ */ wrapConstructor$1(() => new SHA256$1()); -var Databeat = class { - constructor(hostname, fetch2) { - __publicField(this, "hostname"); - __publicField(this, "fetch"); - __publicField(this, "path", "/rpc/Databeat/"); - __publicField(this, "ping", (headers, signal) => { - return this.fetch( - this.url("Ping"), - createHTTPRequest$1({}, headers, signal) - ).then((res) => { - return buildResponse$1(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); - }); - }); - __publicField(this, "version", (headers, signal) => { - return this.fetch( - this.url("Version"), - createHTTPRequest$1({}, headers, signal) - ).then((res) => { - return buildResponse$1(res).then((_data6) => { - return { - version: _data6.version - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); - }); - }); - __publicField(this, "runtimeStatus", (headers, signal) => { - return this.fetch( - this.url("RuntimeStatus"), - createHTTPRequest$1({}, headers, signal) - ).then((res) => { - return buildResponse$1(res).then((_data6) => { - return { - status: _data6.status - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); - }); - }); - __publicField(this, "tick", (args, headers, signal) => { - return this.fetch( - this.url("Tick"), - createHTTPRequest$1(args, headers, signal) - ).then((res) => { - return buildResponse$1(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); + async signTypedData(domain2, types2, value) { + const populated = await TypedDataEncoder.resolveNames(domain2, types2, value, async (name2) => { + assert(this.provider != null, "cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + info: { name: name2 } }); - }); - __publicField(this, "rawEvents", (args, headers, signal) => { - return this.fetch( - this.url("RawEvents"), - createHTTPRequest$1(args, headers, signal) - ).then((res) => { - return buildResponse$1(res).then((_data6) => { - return { - ok: _data6.ok - }; - }); - }, (error) => { - throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); + const address = await this.provider.resolveName(name2); + assert(address != null, "unconfigured ENS name", "UNCONFIGURED_NAME", { + value: name2 }); + return address; }); - this.hostname = hostname; - this.fetch = (input2, init2) => fetch2(input2, init2); - } - url(name2) { - return this.hostname + this.path + name2; + return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types2, populated.value)).serialized; } }; -var createHTTPRequest$1 = (body = {}, headers = {}, signal = null) => { - return { - method: "POST", - headers: { ...headers, "Content-Type": "application/json" }, - body: JSON.stringify(body || {}), - signal - }; -}; -var buildResponse$1 = (res) => { - return res.text().then((text2) => { - let data; - try { - data = JSON.parse(text2); - } catch (error) { - let message = ""; - if (error instanceof Error) { - message = error.message; - } - throw WebrpcBadResponseError$1.new( - { - status: res.status, - cause: `JSON.parse(): ${message}: response text: ${text2}` - } - ); +_signingKey = new WeakMap(); +let BaseWallet = _BaseWallet; +const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; +const Word = /^[a-z]*$/i; +function unfold(words2, sep) { + let initial = 97; + return words2.reduce((accum, word) => { + if (word === sep) { + initial++; + } else if (word.match(Word)) { + accum.push(String.fromCharCode(initial) + word); + } else { + initial = 97; + accum.push(word); } - if (!res.ok) { - const code2 = typeof data.code === "number" ? data.code : 0; - throw (webrpcErrorByCode$1[code2] || WebrpcError$1).new(data); + return accum; + }, []); +} +function decode$1(data, subs) { + for (let i = subsChrs.length - 1; i >= 0; i--) { + data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); + } + const clumps = []; + const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item2, semi, word) => { + if (semi) { + for (let i = parseInt(semi); i >= 0; i--) { + clumps.push(";"); + } + } else { + clumps.push(item2.toLowerCase()); } - return data; + return ""; }); -}; -var WebrpcError$1 = class _WebrpcError extends Error { - constructor(name2, code2, message, status, cause) { - super(message); - __publicField(this, "name"); - __publicField(this, "code"); - __publicField(this, "message"); - __publicField(this, "status"); - __publicField(this, "cause"); - /** @deprecated Use message instead of msg. Deprecated in webrpc v0.11.0. */ - __publicField(this, "msg"); - this.name = name2 || "WebrpcError"; - this.code = typeof code2 === "number" ? code2 : 0; - this.message = message || `endpoint error ${this.code}`; - this.msg = this.message; - this.status = typeof status === "number" ? status : 0; - this.cause = cause; - Object.setPrototypeOf(this, _WebrpcError.prototype); + if (leftover) { + throw new Error(`leftovers: ${JSON.stringify(leftover)}`); } - static new(payload) { - return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + return unfold(unfold(clumps, ";"), ":"); +} +function decodeOwl(data) { + assertArgument(data[0] === "0", "unsupported auwl data", "data", data); + return decode$1(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); +} +class Wordlist { + /** + * Creates a new Wordlist instance. + * + * Sub-classes MUST call this if they provide their own constructor, + * passing in the locale string of the language. + * + * Generally there is no need to create instances of a Wordlist, + * since each language-specific Wordlist creates an instance and + * there is no state kept internally, so they are safe to share. + */ + constructor(locale) { + __publicField(this, "locale"); + defineProperties$1(this, { locale }); } -}; -var WebrpcEndpointError$1 = class _WebrpcEndpointError extends WebrpcError$1 { - constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcEndpointError.prototype); + /** + * Sub-classes may override this to provide a language-specific + * method for spliting %%phrase%% into individual words. + * + * By default, %%phrase%% is split using any sequences of + * white-space as defined by regular expressions (i.e. ``/\s+/``). + */ + split(phrase) { + return phrase.toLowerCase().split(/\s+/g); } -}; -var WebrpcRequestFailedError$1 = class _WebrpcRequestFailedError extends WebrpcError$1 { - constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcRequestFailedError.prototype); + /** + * Sub-classes may override this to provider a language-specific + * method for joining %%words%% into a phrase. + * + * By default, %%words%% are joined by a single space. + */ + join(words2) { + return words2.join(" "); } -}; -var WebrpcBadRouteError$1 = class _WebrpcBadRouteError extends WebrpcError$1 { - constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcBadRouteError.prototype); +} +class WordlistOwl extends Wordlist { + /** + * Creates a new Wordlist for %%locale%% using the OWL %%data%% + * and validated against the %%checksum%%. + */ + constructor(locale, data, checksum2) { + super(locale); + __privateAdd(this, _WordlistOwl_instances); + __privateAdd(this, _data5); + __privateAdd(this, _checksum); + __privateAdd(this, _words); + __privateSet(this, _data5, data); + __privateSet(this, _checksum, checksum2); + __privateSet(this, _words, null); } -}; -var WebrpcBadMethodError$1 = class _WebrpcBadMethodError extends WebrpcError$1 { - constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcBadMethodError.prototype); + /** + * The OWL-encoded data. + */ + get _data() { + return __privateGet(this, _data5); } -}; -var WebrpcBadRequestError$1 = class _WebrpcBadRequestError extends WebrpcError$1 { - constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcBadRequestError.prototype); + /** + * Decode all the words for the wordlist. + */ + _decodeWords() { + return decodeOwl(__privateGet(this, _data5)); } -}; -var WebrpcBadResponseError$1 = class _WebrpcBadResponseError extends WebrpcError$1 { - constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcBadResponseError.prototype); + getWord(index2) { + const words2 = __privateMethod(this, _WordlistOwl_instances, loadWords_fn).call(this); + assertArgument(index2 >= 0 && index2 < words2.length, `invalid word index: ${index2}`, "index", index2); + return words2[index2]; } -}; -var WebrpcServerPanicError$1 = class _WebrpcServerPanicError extends WebrpcError$1 { - constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcServerPanicError.prototype); + getWordIndex(word) { + return __privateMethod(this, _WordlistOwl_instances, loadWords_fn).call(this).indexOf(word); } -}; -var WebrpcInternalErrorError$1 = class _WebrpcInternalErrorError extends WebrpcError$1 { - constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcInternalErrorError.prototype); +} +_data5 = new WeakMap(); +_checksum = new WeakMap(); +_words = new WeakMap(); +_WordlistOwl_instances = new WeakSet(); +loadWords_fn = function() { + if (__privateGet(this, _words) == null) { + const words2 = this._decodeWords(); + const checksum2 = id$1(words2.join("\n") + "\n"); + if (checksum2 !== __privateGet(this, _checksum)) { + throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); + } + __privateSet(this, _words, words2); } + return __privateGet(this, _words); }; -var WebrpcClientDisconnectedError$1 = class _WebrpcClientDisconnectedError extends WebrpcError$1 { - constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcClientDisconnectedError.prototype); +const words = "0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-PM&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryFN Noc|PutQuirySSue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOgAyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO"; +const checksum = "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60"; +let wordlist = null; +class LangEn extends WordlistOwl { + /** + * Creates a new instance of the English language Wordlist. + * + * This should be unnecessary most of the time as the exported + * [[langEn]] should suffice. + * + * @_ignore: + */ + constructor() { + super("en", words, checksum); } -}; -var WebrpcStreamLostError$1 = class _WebrpcStreamLostError extends WebrpcError$1 { - constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcStreamLostError.prototype); + /** + * Returns a singleton instance of a ``LangEn``, creating it + * if this is the first time being called. + */ + static wordlist() { + if (wordlist == null) { + wordlist = new LangEn(); + } + return wordlist; } -}; -var WebrpcStreamFinishedError$1 = class _WebrpcStreamFinishedError extends WebrpcError$1 { - constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _WebrpcStreamFinishedError.prototype); +} +function getUpperMask(bits) { + return (1 << bits) - 1 << 8 - bits & 255; +} +function getLowerMask(bits) { + return (1 << bits) - 1 & 255; +} +function mnemonicToEntropy(mnemonic, wordlist2) { + assertNormalize("NFKD"); + if (wordlist2 == null) { + wordlist2 = LangEn.wordlist(); } -}; -var UnauthorizedError$1 = class _UnauthorizedError extends WebrpcError$1 { - constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _UnauthorizedError.prototype); + const words2 = wordlist2.split(mnemonic); + assertArgument(words2.length % 3 === 0 && words2.length >= 12 && words2.length <= 24, "invalid mnemonic length", "mnemonic", "[ REDACTED ]"); + const entropy = new Uint8Array(Math.ceil(11 * words2.length / 8)); + let offset2 = 0; + for (let i = 0; i < words2.length; i++) { + let index2 = wordlist2.getWordIndex(words2[i].normalize("NFKD")); + assertArgument(index2 >= 0, `invalid mnemonic word at index ${i}`, "mnemonic", "[ REDACTED ]"); + for (let bit = 0; bit < 11; bit++) { + if (index2 & 1 << 10 - bit) { + entropy[offset2 >> 3] |= 1 << 7 - offset2 % 8; + } + offset2++; + } } -}; -var PermissionDeniedError5 = class _PermissionDeniedError extends WebrpcError$1 { - constructor(name2 = "PermissionDenied", code2 = 2e3, message = "Permission denied", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _PermissionDeniedError.prototype); + const entropyBits = 32 * words2.length / 3; + const checksumBits = words2.length / 3; + const checksumMask = getUpperMask(checksumBits); + const checksum2 = getBytes(sha256$1(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; + assertArgument(checksum2 === (entropy[entropy.length - 1] & checksumMask), "invalid mnemonic checksum", "mnemonic", "[ REDACTED ]"); + return hexlify(entropy.slice(0, entropyBits / 8)); +} +function entropyToMnemonic(entropy, wordlist2) { + assertArgument(entropy.length % 4 === 0 && entropy.length >= 16 && entropy.length <= 32, "invalid entropy size", "entropy", "[ REDACTED ]"); + if (wordlist2 == null) { + wordlist2 = LangEn.wordlist(); } -}; -var SessionExpiredError5 = class _SessionExpiredError extends WebrpcError$1 { - constructor(name2 = "SessionExpired", code2 = 2001, message = "Session expired", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _SessionExpiredError.prototype); + const indices = [0]; + let remainingBits = 11; + for (let i = 0; i < entropy.length; i++) { + if (remainingBits > 8) { + indices[indices.length - 1] <<= 8; + indices[indices.length - 1] |= entropy[i]; + remainingBits -= 8; + } else { + indices[indices.length - 1] <<= remainingBits; + indices[indices.length - 1] |= entropy[i] >> 8 - remainingBits; + indices.push(entropy[i] & getLowerMask(8 - remainingBits)); + remainingBits += 3; + } } -}; -var NotFoundError7 = class _NotFoundError extends WebrpcError$1 { - constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _NotFoundError.prototype); + const checksumBits = entropy.length / 4; + const checksum2 = parseInt(sha256$1(entropy).substring(2, 4), 16) & getUpperMask(checksumBits); + indices[indices.length - 1] <<= checksumBits; + indices[indices.length - 1] |= checksum2 >> 8 - checksumBits; + return wordlist2.join(indices.map((index2) => wordlist2.getWord(index2))); +} +const _guard$1 = {}; +class Mnemonic { + /** + * @private + */ + constructor(guard2, entropy, phrase, password, wordlist2) { + /** + * The mnemonic phrase of 12, 15, 18, 21 or 24 words. + * + * Use the [[wordlist]] ``split`` method to get the individual words. + */ + __publicField(this, "phrase"); + /** + * The password used for this mnemonic. If no password is used this + * is the empty string (i.e. ``""``) as per the specification. + */ + __publicField(this, "password"); + /** + * The wordlist for this mnemonic. + */ + __publicField(this, "wordlist"); + /** + * The underlying entropy which the mnemonic encodes. + */ + __publicField(this, "entropy"); + if (password == null) { + password = ""; + } + if (wordlist2 == null) { + wordlist2 = LangEn.wordlist(); + } + assertPrivate(guard2, _guard$1, "Mnemonic"); + defineProperties$1(this, { phrase, password, wordlist: wordlist2, entropy }); } -}; -var InvalidAppKeyError = class _InvalidAppKeyError extends WebrpcError$1 { - constructor(name2 = "InvalidAppKey", code2 = 4e3, message = "Invalid app key", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _InvalidAppKeyError.prototype); + /** + * Returns the seed for the mnemonic. + */ + computeSeed() { + const salt = toUtf8Bytes("mnemonic" + this.password, "NFKD"); + return pbkdf2(toUtf8Bytes(this.phrase, "NFKD"), salt, 2048, 64, "sha512"); } -}; -var QueryFailedError6 = class _QueryFailedError extends WebrpcError$1 { - constructor(name2 = "QueryFailed", code2 = 4001, message = "DB query failed", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _QueryFailedError.prototype); + /** + * Creates a new Mnemonic for the %%phrase%%. + * + * The default %%password%% is the empty string and the default + * wordlist is the [English wordlists](LangEn). + */ + static fromPhrase(phrase, password, wordlist2) { + const entropy = mnemonicToEntropy(phrase, wordlist2); + phrase = entropyToMnemonic(getBytes(entropy), wordlist2); + return new Mnemonic(_guard$1, entropy, phrase, password, wordlist2); } -}; -var InvalidProjectIdError = class _InvalidProjectIdError extends WebrpcError$1 { - constructor(name2 = "InvalidProjectId", code2 = 4002, message = "Invalid project id", status = 0, cause) { - super(name2, code2, message, status, cause); - Object.setPrototypeOf(this, _InvalidProjectIdError.prototype); + /** + * Create a new **Mnemonic** from the %%entropy%%. + * + * The default %%password%% is the empty string and the default + * wordlist is the [English wordlists](LangEn). + */ + static fromEntropy(_entropy, password, wordlist2) { + const entropy = getBytes(_entropy, "entropy"); + const phrase = entropyToMnemonic(entropy, wordlist2); + return new Mnemonic(_guard$1, hexlify(entropy), phrase, password, wordlist2); } -}; -var webrpcErrorByCode$1 = { - [0]: WebrpcEndpointError$1, - [-1]: WebrpcRequestFailedError$1, - [-2]: WebrpcBadRouteError$1, - [-3]: WebrpcBadMethodError$1, - [-4]: WebrpcBadRequestError$1, - [-5]: WebrpcBadResponseError$1, - [-6]: WebrpcServerPanicError$1, - [-7]: WebrpcInternalErrorError$1, - [-8]: WebrpcClientDisconnectedError$1, - [-9]: WebrpcStreamLostError$1, - [-10]: WebrpcStreamFinishedError$1, - [1e3]: UnauthorizedError$1, - [2e3]: PermissionDeniedError5, - [2001]: SessionExpiredError5, - [3e3]: NotFoundError7, - [4e3]: InvalidAppKeyError, - [4001]: QueryFailedError6, - [4002]: InvalidProjectIdError -}; -var DatabeatRpcClient = class extends Databeat { - constructor(hostname, auth2) { - const globalFetch = globalThis.fetch.bind(globalThis); - super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, globalFetch); - __publicField(this, "_globalFetch"); - __publicField(this, "_fetch", (input2, init2) => { - var _a2; - if (this.auth) { - let headers = {}; - if (((_a2 = this.auth.jwt) == null ? void 0 : _a2.length) > 0) { - headers["Authorization"] = `BEARER ${this.auth.jwt}`; - } - if (this.auth.headers) { - headers = { ...headers, ...this.auth.headers }; - } - init2.headers = { ...init2.headers, ...headers }; - } - return this._globalFetch(input2, init2); - }); - this.auth = auth2; - this._globalFetch = globalFetch; - this.fetch = this._fetch; + /** + * Returns the phrase for %%mnemonic%%. + */ + static entropyToPhrase(_entropy, wordlist2) { + const entropy = getBytes(_entropy, "entropy"); + return entropyToMnemonic(entropy, wordlist2); } -}; -var MAX_QUEUE_SIZE = 150; -var defaultDatabeatOptions = { - defaultEnabled: true, - noop: false, - privacy: { userIdHash: true, userAgentSalt: false }, - userIdentTracking: false, - strictMode: false, - flushInterval: 500, - initProps: () => { - return {}; + /** + * Returns the entropy for %%phrase%%. + */ + static phraseToEntropy(phrase, wordlist2) { + return mnemonicToEntropy(phrase, wordlist2); } -}; -var Databeat2 = class { - constructor(host, auth2, options) { - __publicField(this, "rpc"); - __publicField(this, "auth"); - __publicField(this, "options"); - __publicField(this, "enabled"); - __publicField(this, "ident"); - __publicField(this, "userId"); - __publicField(this, "sessionId"); - __publicField(this, "allowUserTracking"); - __publicField(this, "projectId"); - __publicField(this, "queue"); - __publicField(this, "flushTimeout"); - __publicField(this, "defaultProps"); - __publicField(this, "previousPageKey"); - __publicField(this, "ts"); - __publicField(this, "flush", async () => { - if (this.flushTimeout !== null) { - clearTimeout(this.flushTimeout); - this.flushTimeout = null; - } - if (!this.enabled) - return; - if (this.options.noop) - return; - if (this.options.strictMode && !this.allowUserTracking) - return; - if (this.queue.length === 0) - return; - const events = this.dedupedQueue(); - this.queue = []; - try { - await this.rpc.tick({ events }); - } catch (err) { - console.warn(`databeat flush failed: ${err}`); - } - }); - __publicField(this, "dedupedQueue", () => { - const uniqEvents = /* @__PURE__ */ new Map(); - for (let i = 0; i < this.queue.length; i++) { - const ev = this.queue[i]; - const key = `${ev.event}:${ev.source}:${ev.userId}:${ev.sessionId}:${JSON.stringify(ev.props)}:${JSON.stringify(ev.nums)}`; - if (!uniqEvents.has(key)) { - uniqEvents.set(key, ev); - } - } - return Array.from(uniqEvents.values()); - }); - this.auth = auth2; - this.rpc = new DatabeatRpcClient(host, auth2); - this.options = defaultDatabeatOptions; - if (options) { - this.options = { - defaultEnabled: options.defaultEnabled || defaultDatabeatOptions.defaultEnabled, - projectId: options.projectId || null, - privacy: options.privacy || defaultDatabeatOptions.privacy, - userIdentTracking: options.userIdentTracking || defaultDatabeatOptions.userIdentTracking, - strictMode: options.strictMode || defaultDatabeatOptions.strictMode, - flushInterval: options.flushInterval || defaultDatabeatOptions.flushInterval, - noop: options.noop || false, - initProps: options.initProps || defaultDatabeatOptions.initProps - }; + /** + * Returns true if %%phrase%% is a valid [[link-bip-39]] phrase. + * + * This checks all the provided words belong to the %%wordlist%%, + * that the length is valid and the checksum is correct. + */ + static isValidMnemonic(phrase, wordlist2) { + try { + mnemonicToEntropy(phrase, wordlist2); + return true; + } catch (error) { } - this.init(); + return false; + } +} +/*! MIT License. Copyright 2015-2022 Richard Moore . See LICENSE.txt. */ +var __classPrivateFieldGet$2 = function(receiver, state, kind, f2) { + if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver); +}; +var __classPrivateFieldSet$2 = function(receiver, state, value, kind, f2) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value; +}; +var _AES_key, _AES_Kd, _AES_Ke; +const numberOfRounds = { 16: 10, 24: 12, 32: 14 }; +const rcon = [1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145]; +const S = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22]; +const Si = [82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125]; +const T1 = [3328402341, 4168907908, 4000806809, 4135287693, 4294111757, 3597364157, 3731845041, 2445657428, 1613770832, 33620227, 3462883241, 1445669757, 3892248089, 3050821474, 1303096294, 3967186586, 2412431941, 528646813, 2311702848, 4202528135, 4026202645, 2992200171, 2387036105, 4226871307, 1101901292, 3017069671, 1604494077, 1169141738, 597466303, 1403299063, 3832705686, 2613100635, 1974974402, 3791519004, 1033081774, 1277568618, 1815492186, 2118074177, 4126668546, 2211236943, 1748251740, 1369810420, 3521504564, 4193382664, 3799085459, 2883115123, 1647391059, 706024767, 134480908, 2512897874, 1176707941, 2646852446, 806885416, 932615841, 168101135, 798661301, 235341577, 605164086, 461406363, 3756188221, 3454790438, 1311188841, 2142417613, 3933566367, 302582043, 495158174, 1479289972, 874125870, 907746093, 3698224818, 3025820398, 1537253627, 2756858614, 1983593293, 3084310113, 2108928974, 1378429307, 3722699582, 1580150641, 327451799, 2790478837, 3117535592, 0, 3253595436, 1075847264, 3825007647, 2041688520, 3059440621, 3563743934, 2378943302, 1740553945, 1916352843, 2487896798, 2555137236, 2958579944, 2244988746, 3151024235, 3320835882, 1336584933, 3992714006, 2252555205, 2588757463, 1714631509, 293963156, 2319795663, 3925473552, 67240454, 4269768577, 2689618160, 2017213508, 631218106, 1269344483, 2723238387, 1571005438, 2151694528, 93294474, 1066570413, 563977660, 1882732616, 4059428100, 1673313503, 2008463041, 2950355573, 1109467491, 537923632, 3858759450, 4260623118, 3218264685, 2177748300, 403442708, 638784309, 3287084079, 3193921505, 899127202, 2286175436, 773265209, 2479146071, 1437050866, 4236148354, 2050833735, 3362022572, 3126681063, 840505643, 3866325909, 3227541664, 427917720, 2655997905, 2749160575, 1143087718, 1412049534, 999329963, 193497219, 2353415882, 3354324521, 1807268051, 672404540, 2816401017, 3160301282, 369822493, 2916866934, 3688947771, 1681011286, 1949973070, 336202270, 2454276571, 201721354, 1210328172, 3093060836, 2680341085, 3184776046, 1135389935, 3294782118, 965841320, 831886756, 3554993207, 4068047243, 3588745010, 2345191491, 1849112409, 3664604599, 26054028, 2983581028, 2622377682, 1235855840, 3630984372, 2891339514, 4092916743, 3488279077, 3395642799, 4101667470, 1202630377, 268961816, 1874508501, 4034427016, 1243948399, 1546530418, 941366308, 1470539505, 1941222599, 2546386513, 3421038627, 2715671932, 3899946140, 1042226977, 2521517021, 1639824860, 227249030, 260737669, 3765465232, 2084453954, 1907733956, 3429263018, 2420656344, 100860677, 4160157185, 470683154, 3261161891, 1781871967, 2924959737, 1773779408, 394692241, 2579611992, 974986535, 664706745, 3655459128, 3958962195, 731420851, 571543859, 3530123707, 2849626480, 126783113, 865375399, 765172662, 1008606754, 361203602, 3387549984, 2278477385, 2857719295, 1344809080, 2782912378, 59542671, 1503764984, 160008576, 437062935, 1707065306, 3622233649, 2218934982, 3496503480, 2185314755, 697932208, 1512910199, 504303377, 2075177163, 2824099068, 1841019862, 739644986]; +const T2 = [2781242211, 2230877308, 2582542199, 2381740923, 234877682, 3184946027, 2984144751, 1418839493, 1348481072, 50462977, 2848876391, 2102799147, 434634494, 1656084439, 3863849899, 2599188086, 1167051466, 2636087938, 1082771913, 2281340285, 368048890, 3954334041, 3381544775, 201060592, 3963727277, 1739838676, 4250903202, 3930435503, 3206782108, 4149453988, 2531553906, 1536934080, 3262494647, 484572669, 2923271059, 1783375398, 1517041206, 1098792767, 49674231, 1334037708, 1550332980, 4098991525, 886171109, 150598129, 2481090929, 1940642008, 1398944049, 1059722517, 201851908, 1385547719, 1699095331, 1587397571, 674240536, 2704774806, 252314885, 3039795866, 151914247, 908333586, 2602270848, 1038082786, 651029483, 1766729511, 3447698098, 2682942837, 454166793, 2652734339, 1951935532, 775166490, 758520603, 3000790638, 4004797018, 4217086112, 4137964114, 1299594043, 1639438038, 3464344499, 2068982057, 1054729187, 1901997871, 2534638724, 4121318227, 1757008337, 0, 750906861, 1614815264, 535035132, 3363418545, 3988151131, 3201591914, 1183697867, 3647454910, 1265776953, 3734260298, 3566750796, 3903871064, 1250283471, 1807470800, 717615087, 3847203498, 384695291, 3313910595, 3617213773, 1432761139, 2484176261, 3481945413, 283769337, 100925954, 2180939647, 4037038160, 1148730428, 3123027871, 3813386408, 4087501137, 4267549603, 3229630528, 2315620239, 2906624658, 3156319645, 1215313976, 82966005, 3747855548, 3245848246, 1974459098, 1665278241, 807407632, 451280895, 251524083, 1841287890, 1283575245, 337120268, 891687699, 801369324, 3787349855, 2721421207, 3431482436, 959321879, 1469301956, 4065699751, 2197585534, 1199193405, 2898814052, 3887750493, 724703513, 2514908019, 2696962144, 2551808385, 3516813135, 2141445340, 1715741218, 2119445034, 2872807568, 2198571144, 3398190662, 700968686, 3547052216, 1009259540, 2041044702, 3803995742, 487983883, 1991105499, 1004265696, 1449407026, 1316239930, 504629770, 3683797321, 168560134, 1816667172, 3837287516, 1570751170, 1857934291, 4014189740, 2797888098, 2822345105, 2754712981, 936633572, 2347923833, 852879335, 1133234376, 1500395319, 3084545389, 2348912013, 1689376213, 3533459022, 3762923945, 3034082412, 4205598294, 133428468, 634383082, 2949277029, 2398386810, 3913789102, 403703816, 3580869306, 2297460856, 1867130149, 1918643758, 607656988, 4049053350, 3346248884, 1368901318, 600565992, 2090982877, 2632479860, 557719327, 3717614411, 3697393085, 2249034635, 2232388234, 2430627952, 1115438654, 3295786421, 2865522278, 3633334344, 84280067, 33027830, 303828494, 2747425121, 1600795957, 4188952407, 3496589753, 2434238086, 1486471617, 658119965, 3106381470, 953803233, 334231800, 3005978776, 857870609, 3151128937, 1890179545, 2298973838, 2805175444, 3056442267, 574365214, 2450884487, 550103529, 1233637070, 4289353045, 2018519080, 2057691103, 2399374476, 4166623649, 2148108681, 387583245, 3664101311, 836232934, 3330556482, 3100665960, 3280093505, 2955516313, 2002398509, 287182607, 3413881008, 4238890068, 3597515707, 975967766]; +const T3 = [1671808611, 2089089148, 2006576759, 2072901243, 4061003762, 1807603307, 1873927791, 3310653893, 810573872, 16974337, 1739181671, 729634347, 4263110654, 3613570519, 2883997099, 1989864566, 3393556426, 2191335298, 3376449993, 2106063485, 4195741690, 1508618841, 1204391495, 4027317232, 2917941677, 3563566036, 2734514082, 2951366063, 2629772188, 2767672228, 1922491506, 3227229120, 3082974647, 4246528509, 2477669779, 644500518, 911895606, 1061256767, 4144166391, 3427763148, 878471220, 2784252325, 3845444069, 4043897329, 1905517169, 3631459288, 827548209, 356461077, 67897348, 3344078279, 593839651, 3277757891, 405286936, 2527147926, 84871685, 2595565466, 118033927, 305538066, 2157648768, 3795705826, 3945188843, 661212711, 2999812018, 1973414517, 152769033, 2208177539, 745822252, 439235610, 455947803, 1857215598, 1525593178, 2700827552, 1391895634, 994932283, 3596728278, 3016654259, 695947817, 3812548067, 795958831, 2224493444, 1408607827, 3513301457, 0, 3979133421, 543178784, 4229948412, 2982705585, 1542305371, 1790891114, 3410398667, 3201918910, 961245753, 1256100938, 1289001036, 1491644504, 3477767631, 3496721360, 4012557807, 2867154858, 4212583931, 1137018435, 1305975373, 861234739, 2241073541, 1171229253, 4178635257, 33948674, 2139225727, 1357946960, 1011120188, 2679776671, 2833468328, 1374921297, 2751356323, 1086357568, 2408187279, 2460827538, 2646352285, 944271416, 4110742005, 3168756668, 3066132406, 3665145818, 560153121, 271589392, 4279952895, 4077846003, 3530407890, 3444343245, 202643468, 322250259, 3962553324, 1608629855, 2543990167, 1154254916, 389623319, 3294073796, 2817676711, 2122513534, 1028094525, 1689045092, 1575467613, 422261273, 1939203699, 1621147744, 2174228865, 1339137615, 3699352540, 577127458, 712922154, 2427141008, 2290289544, 1187679302, 3995715566, 3100863416, 339486740, 3732514782, 1591917662, 186455563, 3681988059, 3762019296, 844522546, 978220090, 169743370, 1239126601, 101321734, 611076132, 1558493276, 3260915650, 3547250131, 2901361580, 1655096418, 2443721105, 2510565781, 3828863972, 2039214713, 3878868455, 3359869896, 928607799, 1840765549, 2374762893, 3580146133, 1322425422, 2850048425, 1823791212, 1459268694, 4094161908, 3928346602, 1706019429, 2056189050, 2934523822, 135794696, 3134549946, 2022240376, 628050469, 779246638, 472135708, 2800834470, 3032970164, 3327236038, 3894660072, 3715932637, 1956440180, 522272287, 1272813131, 3185336765, 2340818315, 2323976074, 1888542832, 1044544574, 3049550261, 1722469478, 1222152264, 50660867, 4127324150, 236067854, 1638122081, 895445557, 1475980887, 3117443513, 2257655686, 3243809217, 489110045, 2662934430, 3778599393, 4162055160, 2561878936, 288563729, 1773916777, 3648039385, 2391345038, 2493985684, 2612407707, 505560094, 2274497927, 3911240169, 3460925390, 1442818645, 678973480, 3749357023, 2358182796, 2717407649, 2306869641, 219617805, 3218761151, 3862026214, 1120306242, 1756942440, 1103331905, 2578459033, 762796589, 252780047, 2966125488, 1425844308, 3151392187, 372911126]; +const T4 = [1667474886, 2088535288, 2004326894, 2071694838, 4075949567, 1802223062, 1869591006, 3318043793, 808472672, 16843522, 1734846926, 724270422, 4278065639, 3621216949, 2880169549, 1987484396, 3402253711, 2189597983, 3385409673, 2105378810, 4210693615, 1499065266, 1195886990, 4042263547, 2913856577, 3570689971, 2728590687, 2947541573, 2627518243, 2762274643, 1920112356, 3233831835, 3082273397, 4261223649, 2475929149, 640051788, 909531756, 1061110142, 4160160501, 3435941763, 875846760, 2779116625, 3857003729, 4059105529, 1903268834, 3638064043, 825316194, 353713962, 67374088, 3351728789, 589522246, 3284360861, 404236336, 2526454071, 84217610, 2593830191, 117901582, 303183396, 2155911963, 3806477791, 3958056653, 656894286, 2998062463, 1970642922, 151591698, 2206440989, 741110872, 437923380, 454765878, 1852748508, 1515908788, 2694904667, 1381168804, 993742198, 3604373943, 3014905469, 690584402, 3823320797, 791638366, 2223281939, 1398011302, 3520161977, 0, 3991743681, 538992704, 4244381667, 2981218425, 1532751286, 1785380564, 3419096717, 3200178535, 960056178, 1246420628, 1280103576, 1482221744, 3486468741, 3503319995, 4025428677, 2863326543, 4227536621, 1128514950, 1296947098, 859002214, 2240123921, 1162203018, 4193849577, 33687044, 2139062782, 1347481760, 1010582648, 2678045221, 2829640523, 1364325282, 2745433693, 1077985408, 2408548869, 2459086143, 2644360225, 943212656, 4126475505, 3166494563, 3065430391, 3671750063, 555836226, 269496352, 4294908645, 4092792573, 3537006015, 3452783745, 202118168, 320025894, 3974901699, 1600119230, 2543297077, 1145359496, 387397934, 3301201811, 2812801621, 2122220284, 1027426170, 1684319432, 1566435258, 421079858, 1936954854, 1616945344, 2172753945, 1330631070, 3705438115, 572679748, 707427924, 2425400123, 2290647819, 1179044492, 4008585671, 3099120491, 336870440, 3739122087, 1583276732, 185277718, 3688593069, 3772791771, 842159716, 976899700, 168435220, 1229577106, 101059084, 606366792, 1549591736, 3267517855, 3553849021, 2897014595, 1650632388, 2442242105, 2509612081, 3840161747, 2038008818, 3890688725, 3368567691, 926374254, 1835907034, 2374863873, 3587531953, 1313788572, 2846482505, 1819063512, 1448540844, 4109633523, 3941213647, 1701162954, 2054852340, 2930698567, 134748176, 3132806511, 2021165296, 623210314, 774795868, 471606328, 2795958615, 3031746419, 3334885783, 3907527627, 3722280097, 1953799400, 522133822, 1263263126, 3183336545, 2341176845, 2324333839, 1886425312, 1044267644, 3048588401, 1718004428, 1212733584, 50529542, 4143317495, 235803164, 1633788866, 892690282, 1465383342, 3115962473, 2256965911, 3250673817, 488449850, 2661202215, 3789633753, 4177007595, 2560144171, 286339874, 1768537042, 3654906025, 2391705863, 2492770099, 2610673197, 505291324, 2273808917, 3924369609, 3469625735, 1431699370, 673740880, 3755965093, 2358021891, 2711746649, 2307489801, 218961690, 3217021541, 3873845719, 1111672452, 1751693520, 1094828930, 2576986153, 757954394, 252645662, 2964376443, 1414855848, 3149649517, 370555436]; +const T5 = [1374988112, 2118214995, 437757123, 975658646, 1001089995, 530400753, 2902087851, 1273168787, 540080725, 2910219766, 2295101073, 4110568485, 1340463100, 3307916247, 641025152, 3043140495, 3736164937, 632953703, 1172967064, 1576976609, 3274667266, 2169303058, 2370213795, 1809054150, 59727847, 361929877, 3211623147, 2505202138, 3569255213, 1484005843, 1239443753, 2395588676, 1975683434, 4102977912, 2572697195, 666464733, 3202437046, 4035489047, 3374361702, 2110667444, 1675577880, 3843699074, 2538681184, 1649639237, 2976151520, 3144396420, 4269907996, 4178062228, 1883793496, 2403728665, 2497604743, 1383856311, 2876494627, 1917518562, 3810496343, 1716890410, 3001755655, 800440835, 2261089178, 3543599269, 807962610, 599762354, 33778362, 3977675356, 2328828971, 2809771154, 4077384432, 1315562145, 1708848333, 101039829, 3509871135, 3299278474, 875451293, 2733856160, 92987698, 2767645557, 193195065, 1080094634, 1584504582, 3178106961, 1042385657, 2531067453, 3711829422, 1306967366, 2438237621, 1908694277, 67556463, 1615861247, 429456164, 3602770327, 2302690252, 1742315127, 2968011453, 126454664, 3877198648, 2043211483, 2709260871, 2084704233, 4169408201, 0, 159417987, 841739592, 504459436, 1817866830, 4245618683, 260388950, 1034867998, 908933415, 168810852, 1750902305, 2606453969, 607530554, 202008497, 2472011535, 3035535058, 463180190, 2160117071, 1641816226, 1517767529, 470948374, 3801332234, 3231722213, 1008918595, 303765277, 235474187, 4069246893, 766945465, 337553864, 1475418501, 2943682380, 4003061179, 2743034109, 4144047775, 1551037884, 1147550661, 1543208500, 2336434550, 3408119516, 3069049960, 3102011747, 3610369226, 1113818384, 328671808, 2227573024, 2236228733, 3535486456, 2935566865, 3341394285, 496906059, 3702665459, 226906860, 2009195472, 733156972, 2842737049, 294930682, 1206477858, 2835123396, 2700099354, 1451044056, 573804783, 2269728455, 3644379585, 2362090238, 2564033334, 2801107407, 2776292904, 3669462566, 1068351396, 742039012, 1350078989, 1784663195, 1417561698, 4136440770, 2430122216, 775550814, 2193862645, 2673705150, 1775276924, 1876241833, 3475313331, 3366754619, 270040487, 3902563182, 3678124923, 3441850377, 1851332852, 3969562369, 2203032232, 3868552805, 2868897406, 566021896, 4011190502, 3135740889, 1248802510, 3936291284, 699432150, 832877231, 708780849, 3332740144, 899835584, 1951317047, 4236429990, 3767586992, 866637845, 4043610186, 1106041591, 2144161806, 395441711, 1984812685, 1139781709, 3433712980, 3835036895, 2664543715, 1282050075, 3240894392, 1181045119, 2640243204, 25965917, 4203181171, 4211818798, 3009879386, 2463879762, 3910161971, 1842759443, 2597806476, 933301370, 1509430414, 3943906441, 3467192302, 3076639029, 3776767469, 2051518780, 2631065433, 1441952575, 404016761, 1942435775, 1408749034, 1610459739, 3745345300, 2017778566, 3400528769, 3110650942, 941896748, 3265478751, 371049330, 3168937228, 675039627, 4279080257, 967311729, 135050206, 3635733660, 1683407248, 2076935265, 3576870512, 1215061108, 3501741890]; +const T6 = [1347548327, 1400783205, 3273267108, 2520393566, 3409685355, 4045380933, 2880240216, 2471224067, 1428173050, 4138563181, 2441661558, 636813900, 4233094615, 3620022987, 2149987652, 2411029155, 1239331162, 1730525723, 2554718734, 3781033664, 46346101, 310463728, 2743944855, 3328955385, 3875770207, 2501218972, 3955191162, 3667219033, 768917123, 3545789473, 692707433, 1150208456, 1786102409, 2029293177, 1805211710, 3710368113, 3065962831, 401639597, 1724457132, 3028143674, 409198410, 2196052529, 1620529459, 1164071807, 3769721975, 2226875310, 486441376, 2499348523, 1483753576, 428819965, 2274680428, 3075636216, 598438867, 3799141122, 1474502543, 711349675, 129166120, 53458370, 2592523643, 2782082824, 4063242375, 2988687269, 3120694122, 1559041666, 730517276, 2460449204, 4042459122, 2706270690, 3446004468, 3573941694, 533804130, 2328143614, 2637442643, 2695033685, 839224033, 1973745387, 957055980, 2856345839, 106852767, 1371368976, 4181598602, 1033297158, 2933734917, 1179510461, 3046200461, 91341917, 1862534868, 4284502037, 605657339, 2547432937, 3431546947, 2003294622, 3182487618, 2282195339, 954669403, 3682191598, 1201765386, 3917234703, 3388507166, 0, 2198438022, 1211247597, 2887651696, 1315723890, 4227665663, 1443857720, 507358933, 657861945, 1678381017, 560487590, 3516619604, 975451694, 2970356327, 261314535, 3535072918, 2652609425, 1333838021, 2724322336, 1767536459, 370938394, 182621114, 3854606378, 1128014560, 487725847, 185469197, 2918353863, 3106780840, 3356761769, 2237133081, 1286567175, 3152976349, 4255350624, 2683765030, 3160175349, 3309594171, 878443390, 1988838185, 3704300486, 1756818940, 1673061617, 3403100636, 272786309, 1075025698, 545572369, 2105887268, 4174560061, 296679730, 1841768865, 1260232239, 4091327024, 3960309330, 3497509347, 1814803222, 2578018489, 4195456072, 575138148, 3299409036, 446754879, 3629546796, 4011996048, 3347532110, 3252238545, 4270639778, 915985419, 3483825537, 681933534, 651868046, 2755636671, 3828103837, 223377554, 2607439820, 1649704518, 3270937875, 3901806776, 1580087799, 4118987695, 3198115200, 2087309459, 2842678573, 3016697106, 1003007129, 2802849917, 1860738147, 2077965243, 164439672, 4100872472, 32283319, 2827177882, 1709610350, 2125135846, 136428751, 3874428392, 3652904859, 3460984630, 3572145929, 3593056380, 2939266226, 824852259, 818324884, 3224740454, 930369212, 2801566410, 2967507152, 355706840, 1257309336, 4148292826, 243256656, 790073846, 2373340630, 1296297904, 1422699085, 3756299780, 3818836405, 457992840, 3099667487, 2135319889, 77422314, 1560382517, 1945798516, 788204353, 1521706781, 1385356242, 870912086, 325965383, 2358957921, 2050466060, 2388260884, 2313884476, 4006521127, 901210569, 3990953189, 1014646705, 1503449823, 1062597235, 2031621326, 3212035895, 3931371469, 1533017514, 350174575, 2256028891, 2177544179, 1052338372, 741876788, 1606591296, 1914052035, 213705253, 2334669897, 1107234197, 1899603969, 3725069491, 2631447780, 2422494913, 1635502980, 1893020342, 1950903388, 1120974935]; +const T7 = [2807058932, 1699970625, 2764249623, 1586903591, 1808481195, 1173430173, 1487645946, 59984867, 4199882800, 1844882806, 1989249228, 1277555970, 3623636965, 3419915562, 1149249077, 2744104290, 1514790577, 459744698, 244860394, 3235995134, 1963115311, 4027744588, 2544078150, 4190530515, 1608975247, 2627016082, 2062270317, 1507497298, 2200818878, 567498868, 1764313568, 3359936201, 2305455554, 2037970062, 1047239e3, 1910319033, 1337376481, 2904027272, 2892417312, 984907214, 1243112415, 830661914, 861968209, 2135253587, 2011214180, 2927934315, 2686254721, 731183368, 1750626376, 4246310725, 1820824798, 4172763771, 3542330227, 48394827, 2404901663, 2871682645, 671593195, 3254988725, 2073724613, 145085239, 2280796200, 2779915199, 1790575107, 2187128086, 472615631, 3029510009, 4075877127, 3802222185, 4107101658, 3201631749, 1646252340, 4270507174, 1402811438, 1436590835, 3778151818, 3950355702, 3963161475, 4020912224, 2667994737, 273792366, 2331590177, 104699613, 95345982, 3175501286, 2377486676, 1560637892, 3564045318, 369057872, 4213447064, 3919042237, 1137477952, 2658625497, 1119727848, 2340947849, 1530455833, 4007360968, 172466556, 266959938, 516552836, 0, 2256734592, 3980931627, 1890328081, 1917742170, 4294704398, 945164165, 3575528878, 958871085, 3647212047, 2787207260, 1423022939, 775562294, 1739656202, 3876557655, 2530391278, 2443058075, 3310321856, 547512796, 1265195639, 437656594, 3121275539, 719700128, 3762502690, 387781147, 218828297, 3350065803, 2830708150, 2848461854, 428169201, 122466165, 3720081049, 1627235199, 648017665, 4122762354, 1002783846, 2117360635, 695634755, 3336358691, 4234721005, 4049844452, 3704280881, 2232435299, 574624663, 287343814, 612205898, 1039717051, 840019705, 2708326185, 793451934, 821288114, 1391201670, 3822090177, 376187827, 3113855344, 1224348052, 1679968233, 2361698556, 1058709744, 752375421, 2431590963, 1321699145, 3519142200, 2734591178, 188127444, 2177869557, 3727205754, 2384911031, 3215212461, 2648976442, 2450346104, 3432737375, 1180849278, 331544205, 3102249176, 4150144569, 2952102595, 2159976285, 2474404304, 766078933, 313773861, 2570832044, 2108100632, 1668212892, 3145456443, 2013908262, 418672217, 3070356634, 2594734927, 1852171925, 3867060991, 3473416636, 3907448597, 2614737639, 919489135, 164948639, 2094410160, 2997825956, 590424639, 2486224549, 1723872674, 3157750862, 3399941250, 3501252752, 3625268135, 2555048196, 3673637356, 1343127501, 4130281361, 3599595085, 2957853679, 1297403050, 81781910, 3051593425, 2283490410, 532201772, 1367295589, 3926170974, 895287692, 1953757831, 1093597963, 492483431, 3528626907, 1446242576, 1192455638, 1636604631, 209336225, 344873464, 1015671571, 669961897, 3375740769, 3857572124, 2973530695, 3747192018, 1933530610, 3464042516, 935293895, 3454686199, 2858115069, 1863638845, 3683022916, 4085369519, 3292445032, 875313188, 1080017571, 3279033885, 621591778, 1233856572, 2504130317, 24197544, 3017672716, 3835484340, 3247465558, 2220981195, 3060847922, 1551124588, 1463996600]; +const T8 = [4104605777, 1097159550, 396673818, 660510266, 2875968315, 2638606623, 4200115116, 3808662347, 821712160, 1986918061, 3430322568, 38544885, 3856137295, 718002117, 893681702, 1654886325, 2975484382, 3122358053, 3926825029, 4274053469, 796197571, 1290801793, 1184342925, 3556361835, 2405426947, 2459735317, 1836772287, 1381620373, 3196267988, 1948373848, 3764988233, 3385345166, 3263785589, 2390325492, 1480485785, 3111247143, 3780097726, 2293045232, 548169417, 3459953789, 3746175075, 439452389, 1362321559, 1400849762, 1685577905, 1806599355, 2174754046, 137073913, 1214797936, 1174215055, 3731654548, 2079897426, 1943217067, 1258480242, 529487843, 1437280870, 3945269170, 3049390895, 3313212038, 923313619, 679998e3, 3215307299, 57326082, 377642221, 3474729866, 2041877159, 133361907, 1776460110, 3673476453, 96392454, 878845905, 2801699524, 777231668, 4082475170, 2330014213, 4142626212, 2213296395, 1626319424, 1906247262, 1846563261, 562755902, 3708173718, 1040559837, 3871163981, 1418573201, 3294430577, 114585348, 1343618912, 2566595609, 3186202582, 1078185097, 3651041127, 3896688048, 2307622919, 425408743, 3371096953, 2081048481, 1108339068, 2216610296, 0, 2156299017, 736970802, 292596766, 1517440620, 251657213, 2235061775, 2933202493, 758720310, 265905162, 1554391400, 1532285339, 908999204, 174567692, 1474760595, 4002861748, 2610011675, 3234156416, 3693126241, 2001430874, 303699484, 2478443234, 2687165888, 585122620, 454499602, 151849742, 2345119218, 3064510765, 514443284, 4044981591, 1963412655, 2581445614, 2137062819, 19308535, 1928707164, 1715193156, 4219352155, 1126790795, 600235211, 3992742070, 3841024952, 836553431, 1669664834, 2535604243, 3323011204, 1243905413, 3141400786, 4180808110, 698445255, 2653899549, 2989552604, 2253581325, 3252932727, 3004591147, 1891211689, 2487810577, 3915653703, 4237083816, 4030667424, 2100090966, 865136418, 1229899655, 953270745, 3399679628, 3557504664, 4118925222, 2061379749, 3079546586, 2915017791, 983426092, 2022837584, 1607244650, 2118541908, 2366882550, 3635996816, 972512814, 3283088770, 1568718495, 3499326569, 3576539503, 621982671, 2895723464, 410887952, 2623762152, 1002142683, 645401037, 1494807662, 2595684844, 1335535747, 2507040230, 4293295786, 3167684641, 367585007, 3885750714, 1865862730, 2668221674, 2960971305, 2763173681, 1059270954, 2777952454, 2724642869, 1320957812, 2194319100, 2429595872, 2815956275, 77089521, 3973773121, 3444575871, 2448830231, 1305906550, 4021308739, 2857194700, 2516901860, 3518358430, 1787304780, 740276417, 1699839814, 1592394909, 2352307457, 2272556026, 188821243, 1729977011, 3687994002, 274084841, 3594982253, 3613494426, 2701949495, 4162096729, 322734571, 2837966542, 1640576439, 484830689, 1202797690, 3537852828, 4067639125, 349075736, 3342319475, 4157467219, 4255800159, 1030690015, 1155237496, 2951971274, 1757691577, 607398968, 2738905026, 499347990, 3794078908, 1011452712, 227885567, 2818666809, 213114376, 3034881240, 1455525988, 3414450555, 850817237, 1817998408, 3092726480]; +const U1 = [0, 235474187, 470948374, 303765277, 941896748, 908933415, 607530554, 708780849, 1883793496, 2118214995, 1817866830, 1649639237, 1215061108, 1181045119, 1417561698, 1517767529, 3767586992, 4003061179, 4236429990, 4069246893, 3635733660, 3602770327, 3299278474, 3400528769, 2430122216, 2664543715, 2362090238, 2193862645, 2835123396, 2801107407, 3035535058, 3135740889, 3678124923, 3576870512, 3341394285, 3374361702, 3810496343, 3977675356, 4279080257, 4043610186, 2876494627, 2776292904, 3076639029, 3110650942, 2472011535, 2640243204, 2403728665, 2169303058, 1001089995, 899835584, 666464733, 699432150, 59727847, 226906860, 530400753, 294930682, 1273168787, 1172967064, 1475418501, 1509430414, 1942435775, 2110667444, 1876241833, 1641816226, 2910219766, 2743034109, 2976151520, 3211623147, 2505202138, 2606453969, 2302690252, 2269728455, 3711829422, 3543599269, 3240894392, 3475313331, 3843699074, 3943906441, 4178062228, 4144047775, 1306967366, 1139781709, 1374988112, 1610459739, 1975683434, 2076935265, 1775276924, 1742315127, 1034867998, 866637845, 566021896, 800440835, 92987698, 193195065, 429456164, 395441711, 1984812685, 2017778566, 1784663195, 1683407248, 1315562145, 1080094634, 1383856311, 1551037884, 101039829, 135050206, 437757123, 337553864, 1042385657, 807962610, 573804783, 742039012, 2531067453, 2564033334, 2328828971, 2227573024, 2935566865, 2700099354, 3001755655, 3168937228, 3868552805, 3902563182, 4203181171, 4102977912, 3736164937, 3501741890, 3265478751, 3433712980, 1106041591, 1340463100, 1576976609, 1408749034, 2043211483, 2009195472, 1708848333, 1809054150, 832877231, 1068351396, 766945465, 599762354, 159417987, 126454664, 361929877, 463180190, 2709260871, 2943682380, 3178106961, 3009879386, 2572697195, 2538681184, 2236228733, 2336434550, 3509871135, 3745345300, 3441850377, 3274667266, 3910161971, 3877198648, 4110568485, 4211818798, 2597806476, 2497604743, 2261089178, 2295101073, 2733856160, 2902087851, 3202437046, 2968011453, 3936291284, 3835036895, 4136440770, 4169408201, 3535486456, 3702665459, 3467192302, 3231722213, 2051518780, 1951317047, 1716890410, 1750902305, 1113818384, 1282050075, 1584504582, 1350078989, 168810852, 67556463, 371049330, 404016761, 841739592, 1008918595, 775550814, 540080725, 3969562369, 3801332234, 4035489047, 4269907996, 3569255213, 3669462566, 3366754619, 3332740144, 2631065433, 2463879762, 2160117071, 2395588676, 2767645557, 2868897406, 3102011747, 3069049960, 202008497, 33778362, 270040487, 504459436, 875451293, 975658646, 675039627, 641025152, 2084704233, 1917518562, 1615861247, 1851332852, 1147550661, 1248802510, 1484005843, 1451044056, 933301370, 967311729, 733156972, 632953703, 260388950, 25965917, 328671808, 496906059, 1206477858, 1239443753, 1543208500, 1441952575, 2144161806, 1908694277, 1675577880, 1842759443, 3610369226, 3644379585, 3408119516, 3307916247, 4011190502, 3776767469, 4077384432, 4245618683, 2809771154, 2842737049, 3144396420, 3043140495, 2673705150, 2438237621, 2203032232, 2370213795]; +const U2 = [0, 185469197, 370938394, 487725847, 741876788, 657861945, 975451694, 824852259, 1483753576, 1400783205, 1315723890, 1164071807, 1950903388, 2135319889, 1649704518, 1767536459, 2967507152, 3152976349, 2801566410, 2918353863, 2631447780, 2547432937, 2328143614, 2177544179, 3901806776, 3818836405, 4270639778, 4118987695, 3299409036, 3483825537, 3535072918, 3652904859, 2077965243, 1893020342, 1841768865, 1724457132, 1474502543, 1559041666, 1107234197, 1257309336, 598438867, 681933534, 901210569, 1052338372, 261314535, 77422314, 428819965, 310463728, 3409685355, 3224740454, 3710368113, 3593056380, 3875770207, 3960309330, 4045380933, 4195456072, 2471224067, 2554718734, 2237133081, 2388260884, 3212035895, 3028143674, 2842678573, 2724322336, 4138563181, 4255350624, 3769721975, 3955191162, 3667219033, 3516619604, 3431546947, 3347532110, 2933734917, 2782082824, 3099667487, 3016697106, 2196052529, 2313884476, 2499348523, 2683765030, 1179510461, 1296297904, 1347548327, 1533017514, 1786102409, 1635502980, 2087309459, 2003294622, 507358933, 355706840, 136428751, 53458370, 839224033, 957055980, 605657339, 790073846, 2373340630, 2256028891, 2607439820, 2422494913, 2706270690, 2856345839, 3075636216, 3160175349, 3573941694, 3725069491, 3273267108, 3356761769, 4181598602, 4063242375, 4011996048, 3828103837, 1033297158, 915985419, 730517276, 545572369, 296679730, 446754879, 129166120, 213705253, 1709610350, 1860738147, 1945798516, 2029293177, 1239331162, 1120974935, 1606591296, 1422699085, 4148292826, 4233094615, 3781033664, 3931371469, 3682191598, 3497509347, 3446004468, 3328955385, 2939266226, 2755636671, 3106780840, 2988687269, 2198438022, 2282195339, 2501218972, 2652609425, 1201765386, 1286567175, 1371368976, 1521706781, 1805211710, 1620529459, 2105887268, 1988838185, 533804130, 350174575, 164439672, 46346101, 870912086, 954669403, 636813900, 788204353, 2358957921, 2274680428, 2592523643, 2441661558, 2695033685, 2880240216, 3065962831, 3182487618, 3572145929, 3756299780, 3270937875, 3388507166, 4174560061, 4091327024, 4006521127, 3854606378, 1014646705, 930369212, 711349675, 560487590, 272786309, 457992840, 106852767, 223377554, 1678381017, 1862534868, 1914052035, 2031621326, 1211247597, 1128014560, 1580087799, 1428173050, 32283319, 182621114, 401639597, 486441376, 768917123, 651868046, 1003007129, 818324884, 1503449823, 1385356242, 1333838021, 1150208456, 1973745387, 2125135846, 1673061617, 1756818940, 2970356327, 3120694122, 2802849917, 2887651696, 2637442643, 2520393566, 2334669897, 2149987652, 3917234703, 3799141122, 4284502037, 4100872472, 3309594171, 3460984630, 3545789473, 3629546796, 2050466060, 1899603969, 1814803222, 1730525723, 1443857720, 1560382517, 1075025698, 1260232239, 575138148, 692707433, 878443390, 1062597235, 243256656, 91341917, 409198410, 325965383, 3403100636, 3252238545, 3704300486, 3620022987, 3874428392, 3990953189, 4042459122, 4227665663, 2460449204, 2578018489, 2226875310, 2411029155, 3198115200, 3046200461, 2827177882, 2743944855]; +const U3 = [0, 218828297, 437656594, 387781147, 875313188, 958871085, 775562294, 590424639, 1750626376, 1699970625, 1917742170, 2135253587, 1551124588, 1367295589, 1180849278, 1265195639, 3501252752, 3720081049, 3399941250, 3350065803, 3835484340, 3919042237, 4270507174, 4085369519, 3102249176, 3051593425, 2734591178, 2952102595, 2361698556, 2177869557, 2530391278, 2614737639, 3145456443, 3060847922, 2708326185, 2892417312, 2404901663, 2187128086, 2504130317, 2555048196, 3542330227, 3727205754, 3375740769, 3292445032, 3876557655, 3926170974, 4246310725, 4027744588, 1808481195, 1723872674, 1910319033, 2094410160, 1608975247, 1391201670, 1173430173, 1224348052, 59984867, 244860394, 428169201, 344873464, 935293895, 984907214, 766078933, 547512796, 1844882806, 1627235199, 2011214180, 2062270317, 1507497298, 1423022939, 1137477952, 1321699145, 95345982, 145085239, 532201772, 313773861, 830661914, 1015671571, 731183368, 648017665, 3175501286, 2957853679, 2807058932, 2858115069, 2305455554, 2220981195, 2474404304, 2658625497, 3575528878, 3625268135, 3473416636, 3254988725, 3778151818, 3963161475, 4213447064, 4130281361, 3599595085, 3683022916, 3432737375, 3247465558, 3802222185, 4020912224, 4172763771, 4122762354, 3201631749, 3017672716, 2764249623, 2848461854, 2331590177, 2280796200, 2431590963, 2648976442, 104699613, 188127444, 472615631, 287343814, 840019705, 1058709744, 671593195, 621591778, 1852171925, 1668212892, 1953757831, 2037970062, 1514790577, 1463996600, 1080017571, 1297403050, 3673637356, 3623636965, 3235995134, 3454686199, 4007360968, 3822090177, 4107101658, 4190530515, 2997825956, 3215212461, 2830708150, 2779915199, 2256734592, 2340947849, 2627016082, 2443058075, 172466556, 122466165, 273792366, 492483431, 1047239e3, 861968209, 612205898, 695634755, 1646252340, 1863638845, 2013908262, 1963115311, 1446242576, 1530455833, 1277555970, 1093597963, 1636604631, 1820824798, 2073724613, 1989249228, 1436590835, 1487645946, 1337376481, 1119727848, 164948639, 81781910, 331544205, 516552836, 1039717051, 821288114, 669961897, 719700128, 2973530695, 3157750862, 2871682645, 2787207260, 2232435299, 2283490410, 2667994737, 2450346104, 3647212047, 3564045318, 3279033885, 3464042516, 3980931627, 3762502690, 4150144569, 4199882800, 3070356634, 3121275539, 2904027272, 2686254721, 2200818878, 2384911031, 2570832044, 2486224549, 3747192018, 3528626907, 3310321856, 3359936201, 3950355702, 3867060991, 4049844452, 4234721005, 1739656202, 1790575107, 2108100632, 1890328081, 1402811438, 1586903591, 1233856572, 1149249077, 266959938, 48394827, 369057872, 418672217, 1002783846, 919489135, 567498868, 752375421, 209336225, 24197544, 376187827, 459744698, 945164165, 895287692, 574624663, 793451934, 1679968233, 1764313568, 2117360635, 1933530610, 1343127501, 1560637892, 1243112415, 1192455638, 3704280881, 3519142200, 3336358691, 3419915562, 3907448597, 3857572124, 4075877127, 4294704398, 3029510009, 3113855344, 2927934315, 2744104290, 2159976285, 2377486676, 2594734927, 2544078150]; +const U4 = [0, 151849742, 303699484, 454499602, 607398968, 758720310, 908999204, 1059270954, 1214797936, 1097159550, 1517440620, 1400849762, 1817998408, 1699839814, 2118541908, 2001430874, 2429595872, 2581445614, 2194319100, 2345119218, 3034881240, 3186202582, 2801699524, 2951971274, 3635996816, 3518358430, 3399679628, 3283088770, 4237083816, 4118925222, 4002861748, 3885750714, 1002142683, 850817237, 698445255, 548169417, 529487843, 377642221, 227885567, 77089521, 1943217067, 2061379749, 1640576439, 1757691577, 1474760595, 1592394909, 1174215055, 1290801793, 2875968315, 2724642869, 3111247143, 2960971305, 2405426947, 2253581325, 2638606623, 2487810577, 3808662347, 3926825029, 4044981591, 4162096729, 3342319475, 3459953789, 3576539503, 3693126241, 1986918061, 2137062819, 1685577905, 1836772287, 1381620373, 1532285339, 1078185097, 1229899655, 1040559837, 923313619, 740276417, 621982671, 439452389, 322734571, 137073913, 19308535, 3871163981, 4021308739, 4104605777, 4255800159, 3263785589, 3414450555, 3499326569, 3651041127, 2933202493, 2815956275, 3167684641, 3049390895, 2330014213, 2213296395, 2566595609, 2448830231, 1305906550, 1155237496, 1607244650, 1455525988, 1776460110, 1626319424, 2079897426, 1928707164, 96392454, 213114376, 396673818, 514443284, 562755902, 679998e3, 865136418, 983426092, 3708173718, 3557504664, 3474729866, 3323011204, 4180808110, 4030667424, 3945269170, 3794078908, 2507040230, 2623762152, 2272556026, 2390325492, 2975484382, 3092726480, 2738905026, 2857194700, 3973773121, 3856137295, 4274053469, 4157467219, 3371096953, 3252932727, 3673476453, 3556361835, 2763173681, 2915017791, 3064510765, 3215307299, 2156299017, 2307622919, 2459735317, 2610011675, 2081048481, 1963412655, 1846563261, 1729977011, 1480485785, 1362321559, 1243905413, 1126790795, 878845905, 1030690015, 645401037, 796197571, 274084841, 425408743, 38544885, 188821243, 3613494426, 3731654548, 3313212038, 3430322568, 4082475170, 4200115116, 3780097726, 3896688048, 2668221674, 2516901860, 2366882550, 2216610296, 3141400786, 2989552604, 2837966542, 2687165888, 1202797690, 1320957812, 1437280870, 1554391400, 1669664834, 1787304780, 1906247262, 2022837584, 265905162, 114585348, 499347990, 349075736, 736970802, 585122620, 972512814, 821712160, 2595684844, 2478443234, 2293045232, 2174754046, 3196267988, 3079546586, 2895723464, 2777952454, 3537852828, 3687994002, 3234156416, 3385345166, 4142626212, 4293295786, 3841024952, 3992742070, 174567692, 57326082, 410887952, 292596766, 777231668, 660510266, 1011452712, 893681702, 1108339068, 1258480242, 1343618912, 1494807662, 1715193156, 1865862730, 1948373848, 2100090966, 2701949495, 2818666809, 3004591147, 3122358053, 2235061775, 2352307457, 2535604243, 2653899549, 3915653703, 3764988233, 4219352155, 4067639125, 3444575871, 3294430577, 3746175075, 3594982253, 836553431, 953270745, 600235211, 718002117, 367585007, 484830689, 133361907, 251657213, 2041877159, 1891211689, 1806599355, 1654886325, 1568718495, 1418573201, 1335535747, 1184342925]; +function convertToInt32(bytes2) { + const result = []; + for (let i = 0; i < bytes2.length; i += 4) { + result.push(bytes2[i] << 24 | bytes2[i + 1] << 16 | bytes2[i + 2] << 8 | bytes2[i + 3]); } - // init is called on load by the constructor and also by reset(). - init() { - this.enabled = isEnabled(this.options.defaultEnabled, this.auth); - this.projectId = this.options.projectId || null; - this.userId = null; - this.sessionId = genSessionId(); - this.queue = []; - this.flushTimeout = null; - this.defaultProps = { ...getDefaultProps(), ...this.options.initProps() }; - this.identify(); + return result; +} +class AES { + get key() { + return __classPrivateFieldGet$2(this, _AES_key, "f").slice(); } - // reset will reset the user_id and session_id details. Similar to a "logout" action. - reset(skipInit) { - this.enabled = isEnabled(this.options.defaultEnabled, this.auth); - if (this.userId && !this.isAnon()) { - this.userId = null; + constructor(key) { + _AES_key.set(this, void 0); + _AES_Kd.set(this, void 0); + _AES_Ke.set(this, void 0); + if (!(this instanceof AES)) { + throw Error("AES must be instanitated with `new`"); } - this.ident = 0; - this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); - if (skipInit === true) { - return; + __classPrivateFieldSet$2(this, _AES_key, new Uint8Array(key), "f"); + const rounds = numberOfRounds[this.key.length]; + if (rounds == null) { + throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)"); } - this.init(); - } - // identify can be called to seed the userId, where the behaviour changes - // depending on privacy or strict modes. identify is also called on init, - // where we load the data from localStorage. - identify(userId, options) { - if (!isBrowser()) - return; - if (options && options.allowTracking !== void 0) { - this.allowTracking(options.allowTracking); + __classPrivateFieldSet$2(this, _AES_Ke, [], "f"); + __classPrivateFieldSet$2(this, _AES_Kd, [], "f"); + for (let i = 0; i <= rounds; i++) { + __classPrivateFieldGet$2(this, _AES_Ke, "f").push([0, 0, 0, 0]); + __classPrivateFieldGet$2(this, _AES_Kd, "f").push([0, 0, 0, 0]); } - if (!userId) { - const val = getStorageVal(); - if (val !== null && val.id !== null) { - this.userId = val.id; - this.ident = val.it; - this.allowUserTracking = val.ut; - if (val.it === void 0) { - if (this.userId.startsWith("anon:")) { - this.ident = 0; - } else { - this.ident = 1; - } - this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); - } else { - this.ident = val.it; + const roundKeyCount = (rounds + 1) * 4; + const KC = this.key.length / 4; + const tk2 = convertToInt32(this.key); + let index2; + for (let i = 0; i < KC; i++) { + index2 = i >> 2; + __classPrivateFieldGet$2(this, _AES_Ke, "f")[index2][i % 4] = tk2[i]; + __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds - index2][i % 4] = tk2[i]; + } + let rconpointer = 0; + let t2 = KC, tt; + while (t2 < roundKeyCount) { + tt = tk2[KC - 1]; + tk2[0] ^= S[tt >> 16 & 255] << 24 ^ S[tt >> 8 & 255] << 16 ^ S[tt & 255] << 8 ^ S[tt >> 24 & 255] ^ rcon[rconpointer] << 24; + rconpointer += 1; + if (KC != 8) { + for (let i2 = 1; i2 < KC; i2++) { + tk2[i2] ^= tk2[i2 - 1]; } + } else { + for (let i2 = 1; i2 < KC / 2; i2++) { + tk2[i2] ^= tk2[i2 - 1]; + } + tt = tk2[KC / 2 - 1]; + tk2[KC / 2] ^= S[tt & 255] ^ S[tt >> 8 & 255] << 8 ^ S[tt >> 16 & 255] << 16 ^ S[tt >> 24 & 255] << 24; + for (let i2 = KC / 2 + 1; i2 < KC; i2++) { + tk2[i2] ^= tk2[i2 - 1]; + } + } + let i = 0, r2, c2; + while (i < KC && t2 < roundKeyCount) { + r2 = t2 >> 2; + c2 = t2 % 4; + __classPrivateFieldGet$2(this, _AES_Ke, "f")[r2][c2] = tk2[i]; + __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds - r2][c2] = tk2[i++]; + t2++; } } - if (userId || this.userId === null) { - const v3 = genUserId(userId, this.allowUserTracking, this.options); - this.userId = v3.userId; - this.ident = v3.ident; - this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); + for (let r2 = 1; r2 < rounds; r2++) { + for (let c2 = 0; c2 < 4; c2++) { + tt = __classPrivateFieldGet$2(this, _AES_Kd, "f")[r2][c2]; + __classPrivateFieldGet$2(this, _AES_Kd, "f")[r2][c2] = U1[tt >> 24 & 255] ^ U2[tt >> 16 & 255] ^ U3[tt >> 8 & 255] ^ U4[tt & 255]; + } } - this.track({ event: "INIT", source: getPagePath(), props: this.defaultProps }); - this.flush(); } - // allowTracking is used by strict mode to enable/disable tracking. - allowTracking(allowTracking) { - this.allowUserTracking = allowTracking; - setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); - if (this.options.strictMode) { - if (allowTracking) { - this.enable(); - } else { - this.disable(); + encrypt(plaintext) { + if (plaintext.length != 16) { + throw new TypeError("invalid plaintext size (must be 16 bytes)"); + } + const rounds = __classPrivateFieldGet$2(this, _AES_Ke, "f").length - 1; + const a2 = [0, 0, 0, 0]; + let t2 = convertToInt32(plaintext); + for (let i = 0; i < 4; i++) { + t2[i] ^= __classPrivateFieldGet$2(this, _AES_Ke, "f")[0][i]; + } + for (let r2 = 1; r2 < rounds; r2++) { + for (let i = 0; i < 4; i++) { + a2[i] = T1[t2[i] >> 24 & 255] ^ T2[t2[(i + 1) % 4] >> 16 & 255] ^ T3[t2[(i + 2) % 4] >> 8 & 255] ^ T4[t2[(i + 3) % 4] & 255] ^ __classPrivateFieldGet$2(this, _AES_Ke, "f")[r2][i]; } + t2 = a2.slice(); + } + const result = new Uint8Array(16); + let tt = 0; + for (let i = 0; i < 4; i++) { + tt = __classPrivateFieldGet$2(this, _AES_Ke, "f")[rounds][i]; + result[4 * i] = (S[t2[i] >> 24 & 255] ^ tt >> 24) & 255; + result[4 * i + 1] = (S[t2[(i + 1) % 4] >> 16 & 255] ^ tt >> 16) & 255; + result[4 * i + 2] = (S[t2[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; + result[4 * i + 3] = (S[t2[(i + 3) % 4] & 255] ^ tt) & 255; } + return result; } - async track(events, options) { - if (isBrowser() && this.userId === null) { - throw new Error("databeat: init first"); + decrypt(ciphertext) { + if (ciphertext.length != 16) { + throw new TypeError("invalid ciphertext size (must be 16 bytes)"); } - if (Array.isArray(events)) { - for (let i = 0; i < events.length; i++) { - events[i].ident = this.ident; - events[i].userId = this.userId; - events[i].sessionId = this.sessionId; - if (!events[i].projectId && this.projectId) { - events[i].projectId = this.projectId; - } - } - this.queue.push(...events); - } else { - events.ident = this.ident; - events.userId = this.userId; - events.sessionId = this.sessionId; - if (!events.projectId && this.projectId) { - events.projectId = this.projectId; - } - this.queue.push(events); + const rounds = __classPrivateFieldGet$2(this, _AES_Kd, "f").length - 1; + const a2 = [0, 0, 0, 0]; + let t2 = convertToInt32(ciphertext); + for (let i = 0; i < 4; i++) { + t2[i] ^= __classPrivateFieldGet$2(this, _AES_Kd, "f")[0][i]; } - if (this.queue.length > MAX_QUEUE_SIZE) { - this.queue = this.queue.splice(this.queue.length - MAX_QUEUE_SIZE); + for (let r2 = 1; r2 < rounds; r2++) { + for (let i = 0; i < 4; i++) { + a2[i] = T5[t2[i] >> 24 & 255] ^ T6[t2[(i + 3) % 4] >> 16 & 255] ^ T7[t2[(i + 2) % 4] >> 8 & 255] ^ T8[t2[(i + 1) % 4] & 255] ^ __classPrivateFieldGet$2(this, _AES_Kd, "f")[r2][i]; + } + t2 = a2.slice(); } - if (!this.enabled) - return; - if (options && options.flush) { - await this.flush(); - } else if (this.flushTimeout === null) { - this.flushTimeout = setTimeout(() => { - this.flush(); - }, this.options.flushInterval); + const result = new Uint8Array(16); + let tt = 0; + for (let i = 0; i < 4; i++) { + tt = __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds][i]; + result[4 * i] = (Si[t2[i] >> 24 & 255] ^ tt >> 24) & 255; + result[4 * i + 1] = (Si[t2[(i + 3) % 4] >> 16 & 255] ^ tt >> 16) & 255; + result[4 * i + 2] = (Si[t2[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; + result[4 * i + 3] = (Si[t2[(i + 1) % 4] & 255] ^ tt) & 255; } + return result; } - trackView(props = {}) { - const eventProps = { ...this.defaultProps, ...props }; - const eventSource = getPagePath(); - const pageKey = `${eventSource}:${JSON.stringify(eventProps)}:${this.userId}:${this.sessionId}`; - if (this.previousPageKey === pageKey) - return; - this.previousPageKey = pageKey; - this.track({ event: "VIEW", source: eventSource, props: eventProps }); - } - isEnabled() { - return this.enabled; - } - isAnon() { - return this.ident === 0; - } - getIdent() { - return this.ident; +} +_AES_key = /* @__PURE__ */ new WeakMap(), _AES_Kd = /* @__PURE__ */ new WeakMap(), _AES_Ke = /* @__PURE__ */ new WeakMap(); +class ModeOfOperation { + constructor(name2, key, cls) { + if (cls && !(this instanceof cls)) { + throw new Error(`${name2} must be instantiated with "new"`); + } + Object.defineProperties(this, { + aes: { enumerable: true, value: new AES(key) }, + name: { enumerable: true, value: name2 } + }); } - getUserId() { - return this.userId; +} +var __classPrivateFieldSet$1 = function(receiver, state, value, kind, f2) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value; +}; +var __classPrivateFieldGet$1 = function(receiver, state, kind, f2) { + if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver); +}; +var _CBC_iv, _CBC_lastBlock; +class CBC extends ModeOfOperation { + constructor(key, iv) { + super("ECC", key, CBC); + _CBC_iv.set(this, void 0); + _CBC_lastBlock.set(this, void 0); + if (iv) { + if (iv.length % 16) { + throw new TypeError("invalid iv size (must be 16 bytes)"); + } + __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(iv), "f"); + } else { + __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(16), "f"); + } + __classPrivateFieldSet$1(this, _CBC_lastBlock, this.iv, "f"); } - getSessionId() { - return this.sessionId; + get iv() { + return new Uint8Array(__classPrivateFieldGet$1(this, _CBC_iv, "f")); } - getStorageTS() { - if (this.ts) { - return this.ts; + encrypt(plaintext) { + if (plaintext.length % 16) { + throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)"); } - const val = getStorageVal(); - if (val === void 0 || val === null || val.id === null) { - return void 0; + const ciphertext = new Uint8Array(plaintext.length); + for (let i = 0; i < plaintext.length; i += 16) { + for (let j2 = 0; j2 < 16; j2++) { + __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j2] ^= plaintext[i + j2]; + } + __classPrivateFieldSet$1(this, _CBC_lastBlock, this.aes.encrypt(__classPrivateFieldGet$1(this, _CBC_lastBlock, "f")), "f"); + ciphertext.set(__classPrivateFieldGet$1(this, _CBC_lastBlock, "f"), i); } - this.ts = val.ts; - return this.ts; + return ciphertext; } - enable() { - if (!isAuthEnabled(this.auth)) { - this.enabled = false; - return; + decrypt(ciphertext) { + if (ciphertext.length % 16) { + throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)"); } - if (!isBrowser()) - return; - this.enabled = true; - this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); - this.identify(); - } - disable() { - if (!isBrowser()) - return; - this.enabled = false; - this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); + const plaintext = new Uint8Array(ciphertext.length); + for (let i = 0; i < ciphertext.length; i += 16) { + const block = this.aes.decrypt(ciphertext.subarray(i, i + 16)); + for (let j2 = 0; j2 < 16; j2++) { + plaintext[i + j2] = block[j2] ^ __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j2]; + __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j2] = ciphertext[i + j2]; + } + } + return plaintext; } +} +_CBC_iv = /* @__PURE__ */ new WeakMap(), _CBC_lastBlock = /* @__PURE__ */ new WeakMap(); +var __classPrivateFieldSet = function(receiver, state, value, kind, f2) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value; }; -var isBrowser = () => { - return typeof window === "object" && typeof window.localStorage === "object" && typeof window.localStorage.getItem === "function" && typeof window.localStorage.setItem === "function"; +var __classPrivateFieldGet = function(receiver, state, kind, f2) { + if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver); }; -var isEnabled = (defaultEnabled, auth2) => { - if (!isAuthEnabled(auth2)) { - return false; - } - if (!isBrowser()) { - return true; - } - const val = getStorageVal(); - if (val === null) { - if (defaultEnabled !== null && defaultEnabled !== void 0) { - return defaultEnabled; +var _CTR_remaining, _CTR_remainingIndex, _CTR_counter; +class CTR extends ModeOfOperation { + constructor(key, initialValue) { + super("CTR", key, CTR); + _CTR_remaining.set(this, void 0); + _CTR_remainingIndex.set(this, void 0); + _CTR_counter.set(this, void 0); + __classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), "f"); + __classPrivateFieldGet(this, _CTR_counter, "f").fill(0); + __classPrivateFieldSet(this, _CTR_remaining, __classPrivateFieldGet(this, _CTR_counter, "f"), "f"); + __classPrivateFieldSet(this, _CTR_remainingIndex, 16, "f"); + if (initialValue == null) { + initialValue = 1; + } + if (typeof initialValue === "number") { + this.setCounterValue(initialValue); } else { - return true; + this.setCounterBytes(initialValue); } - } else { - return val.on; - } -}; -var isAuthEnabled = (auth2) => { - var _a2; - if (((_a2 = auth2 == null ? void 0 : auth2.jwt) == null ? void 0 : _a2.length) > 0) { - return true; } - if ((auth2 == null ? void 0 : auth2.headers) && Object.keys(auth2.headers).length > 0) { - return true; - } - return false; -}; -var getPagePath = () => { - try { - return window.location.pathname; - } catch (err) { - return ""; + get counter() { + return new Uint8Array(__classPrivateFieldGet(this, _CTR_counter, "f")); } -}; -var getDefaultProps = () => { - if (!isBrowser()) - return {}; - const params = new URL(window.location.href).searchParams; - const props = {}; - props["origin"] = window.location.origin; - if (params.get("ref") && params.get("ref") !== "") { - props["ref"] = params.get("ref") || ""; + setCounterValue(value) { + if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) { + throw new TypeError("invalid counter initial integer value"); + } + for (let index2 = 15; index2 >= 0; --index2) { + __classPrivateFieldGet(this, _CTR_counter, "f")[index2] = value % 256; + value = Math.floor(value / 256); + } } - if (params.get("source") && params.get("source") !== "") { - props["source"] = params.get("source") || ""; + setCounterBytes(value) { + if (value.length !== 16) { + throw new TypeError("invalid counter initial Uint8Array value length"); + } + __classPrivateFieldGet(this, _CTR_counter, "f").set(value); } - if (params.get("utm_source") && params.get("utm_source") !== "") { - props["utmSource"] = params.get("utm_source") || ""; + increment() { + for (let i = 15; i >= 0; i--) { + if (__classPrivateFieldGet(this, _CTR_counter, "f")[i] === 255) { + __classPrivateFieldGet(this, _CTR_counter, "f")[i] = 0; + } else { + __classPrivateFieldGet(this, _CTR_counter, "f")[i]++; + break; + } + } } - if (params.get("utm_campaign") && params.get("utm_campaign") !== "") { - props["utmCampaign"] = params.get("utm_campaign") || ""; + encrypt(plaintext) { + var _a2, _b2; + const crypttext = new Uint8Array(plaintext); + for (let i = 0; i < crypttext.length; i++) { + if (__classPrivateFieldGet(this, _CTR_remainingIndex, "f") === 16) { + __classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet(this, _CTR_counter, "f")), "f"); + __classPrivateFieldSet(this, _CTR_remainingIndex, 0, "f"); + this.increment(); + } + crypttext[i] ^= __classPrivateFieldGet(this, _CTR_remaining, "f")[__classPrivateFieldSet(this, _CTR_remainingIndex, (_b2 = __classPrivateFieldGet(this, _CTR_remainingIndex, "f"), _a2 = _b2++, _b2), "f"), _a2]; + } + return crypttext; } - if (params.get("utm_medium") && params.get("utm_medium") !== "") { - props["utmMedium"] = params.get("utm_medium") || ""; + decrypt(ciphertext) { + return this.encrypt(ciphertext); } - if (params.get("utm_content") && params.get("utm_content") !== "") { - props["utmContent"] = params.get("utm_content") || ""; +} +_CTR_remaining = /* @__PURE__ */ new WeakMap(), _CTR_remainingIndex = /* @__PURE__ */ new WeakMap(), _CTR_counter = /* @__PURE__ */ new WeakMap(); +function pkcs7Strip(data) { + if (data.length < 16) { + throw new TypeError("PKCS#7 invalid length"); } - if (params.get("utm_term") && params.get("utm_term") !== "") { - props["utmTerm"] = params.get("utm_term") || ""; + const padder = data[data.length - 1]; + if (padder > 16) { + throw new TypeError("PKCS#7 padding byte out of range"); } - if (document.referrer && document.referrer !== "") { - props["referrer"] = document.referrer; + const length = data.length - padder; + for (let i = 0; i < padder; i++) { + if (data[length + i] !== padder) { + throw new TypeError("PKCS#7 invalid padding byte"); + } } - if (params.get("gclid") && params.get("gclid") !== "") { - props["gclid"] = params.get("gclid") || ""; + return new Uint8Array(data.subarray(0, length)); +} +function looseArrayify(hexString) { + if (typeof hexString === "string" && !hexString.startsWith("0x")) { + hexString = "0x" + hexString; } - if (params.get("wbraid") && params.get("wbraid") !== "") { - props["wbraid"] = params.get("wbraid") || ""; + return getBytesCopy(hexString); +} +function zpad$1(value, length) { + value = String(value); + while (value.length < length) { + value = "0" + value; } - return props; -}; -var storageKey = "_dbeat"; -var getStorageVal = () => { - try { - return JSON.parse(window.localStorage.getItem(storageKey)); - } catch (err) { - return null; + return value; +} +function getPassword(password) { + if (typeof password === "string") { + return toUtf8Bytes(password, "NFKC"); } -}; -var setStorageVal = (val) => { - try { - if (!val.ts) { - val.ts = Math.floor(Date.now() / 1e3); + return getBytesCopy(password); +} +function spelunk(object2, _path) { + const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i); + assertArgument(match != null, "invalid path", "path", _path); + const path = match[1]; + const type = match[3]; + const reqd = match[4] === "!"; + let cur = object2; + for (const comp of path.toLowerCase().split(".")) { + if (Array.isArray(cur)) { + if (!comp.match(/^[0-9]+$/)) { + break; + } + cur = cur[parseInt(comp)]; + } else if (typeof cur === "object") { + let found = null; + for (const key in cur) { + if (key.toLowerCase() === comp) { + found = cur[key]; + break; + } + } + cur = found; + } else { + cur = null; + } + if (cur == null) { + break; } - window.localStorage.setItem(storageKey, JSON.stringify(val)); - return val.ts; - } catch (err) { - return; - } -}; -var genUserId = (seed, allowUserTracking, options) => { - if (!seed || seed === null || seed === "") { - const id2 = Math.floor(Math.random() * 1e14); - return { - userId: `${id2}`, - ident: 0 - /* ANON */ - }; - } - if (options.userIdentTracking && allowUserTracking) { - return { - userId: seed, - ident: 2 - /* USER */ - }; } - if (options.privacy.userIdHash === true || !options.userIdentTracking || !allowUserTracking) { - if (isBrowser() && options.privacy.userAgentSalt === true) { - seed = seed + ":" + navigator.userAgent; + assertArgument(!reqd || cur != null, "missing required value", "path", path); + if (type && cur != null) { + if (type === "int") { + if (typeof cur === "string" && cur.match(/^-?[0-9]+$/)) { + return parseInt(cur); + } else if (Number.isSafeInteger(cur)) { + return cur; + } + } + if (type === "number") { + if (typeof cur === "string" && cur.match(/^-?[0-9.]*$/)) { + return parseFloat(cur); + } + } + if (type === "data") { + if (typeof cur === "string") { + return looseArrayify(cur); + } + } + if (type === "array" && Array.isArray(cur)) { + return cur; } - if (options.privacy.extraSalt && options.privacy.extraSalt.length > 0) { - seed = seed + ":" + options.privacy.extraSalt; + if (type === typeof cur) { + return cur; } - return { - userId: bytesToHex$2(sha256$2(seed)).substring(0, 50), - ident: 1 - /* PRIVATE */ - }; - } else { - throw new Error("invalid configuration"); + assertArgument(false, `wrong type found for ${type} `, "path", path); } -}; -var genSessionId = () => { - const isSessionStorageAvail = isBrowser() && typeof window.sessionStorage === "object" && typeof window.sessionStorage.getItem === "function" && typeof window.sessionStorage.setItem === "function"; - if (!isSessionStorageAvail) { - return genRandHex(16); - } else { - const sid = window.sessionStorage.getItem(storageKey); - if (!!sid && sid.length > 0) { - return sid; - } else { - const sid2 = genRandHex(16); - window.sessionStorage.setItem(storageKey, sid2); - return sid2; + return cur; +} +const defaultPath$1 = "m/44'/60'/0'/0/0"; +function isKeystoreJson(json) { + try { + const data = JSON.parse(json); + const version2 = data.version != null ? parseInt(data.version) : 0; + if (version2 === 3) { + return true; } + } catch (error) { } -}; -var genRandHex = (n2) => { - let hexString = ""; - for (let i = 0; i < n2; i++) { - hexString += Math.floor(Math.random() * 16).toString(16); - } - return "0x" + hexString; -}; -if (typeof process$1 === "object" && process$1.version && process$1.version < "v18") { - console.error(`ERROR! expecting node v18+ but your node version is reporting ${process$1.version}`); - if (process$1 && process$1.exit) { - process$1.exit(1); + return false; +} +function decrypt(data, key, ciphertext) { + const cipher = spelunk(data, "crypto.cipher:string"); + if (cipher === "aes-128-ctr") { + const iv = spelunk(data, "crypto.cipherparams.iv:data!"); + const aesCtr = new CTR(key, iv); + return hexlify(aesCtr.decrypt(ciphertext)); } + assert(false, "unsupported cipher", "UNSUPPORTED_OPERATION", { + operation: "decrypt" + }); } -const PROHIBITED_FUNCTIONS = new Map(["addHook(bytes4,address)", "clearExtraImageHashes(bytes32[])", "removeHook(bytes4)", "setExtraImageHash(bytes32,uint256)", "updateIPFSRoot(bytes32)", "updateImageHash(bytes32)", "updateImageHashAndIPFS(bytes32,bytes32)", "updateImplementation(address)"].map((signature2) => [id$1(signature2).slice(0, 10), signature2])); -function validateTransactionRequest(wallet, transaction2) { - const transactions2 = index$1$2.transaction.fromTransactionish(wallet, transaction2); - const unwound = index$1$2.transaction.unwind(wallet, transactions2); - unwound.forEach((transaction22) => validateTransaction(wallet, transaction22)); +function getAccount(data, _key) { + const key = getBytes(_key); + const ciphertext = spelunk(data, "crypto.ciphertext:data!"); + const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2); + assertArgument(computedMAC === spelunk(data, "crypto.mac:string!").toLowerCase(), "incorrect password", "password", "[ REDACTED ]"); + const privateKey = decrypt(data, key.slice(0, 16), ciphertext); + const address = computeAddress(privateKey); + if (data.address) { + let check = data.address.toLowerCase(); + if (!check.startsWith("0x")) { + check = "0x" + check; + } + assertArgument(getAddress(check) === address, "keystore address/privateKey mismatch", "address", data.address); + } + const account2 = { address, privateKey }; + const version2 = spelunk(data, "x-ethers.version:string"); + if (version2 === "0.1") { + const mnemonicKey = key.slice(32, 64); + const mnemonicCiphertext = spelunk(data, "x-ethers.mnemonicCiphertext:data!"); + const mnemonicIv = spelunk(data, "x-ethers.mnemonicCounter:data!"); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + account2.mnemonic = { + path: spelunk(data, "x-ethers.path:string") || defaultPath$1, + locale: spelunk(data, "x-ethers.locale:string") || "en", + entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))) + }; + } + return account2; } -function validateTransaction(wallet, transaction2) { - if (transaction2.to.toLowerCase() === wallet.toLowerCase()) { - if (transaction2.data) { - const data = getBytes(transaction2.data); - if (data.length >= 4 && !isCreateContractCall(data)) { - throw new Error("self calls are forbidden"); - } +function getDecryptKdfParams(data) { + const kdf = spelunk(data, "crypto.kdf:string"); + if (kdf && typeof kdf === "string") { + if (kdf.toLowerCase() === "scrypt") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const N2 = spelunk(data, "crypto.kdfparams.n:int!"); + const r2 = spelunk(data, "crypto.kdfparams.r:int!"); + const p2 = spelunk(data, "crypto.kdfparams.p:int!"); + assertArgument(N2 > 0 && (N2 & N2 - 1) === 0, "invalid kdf.N", "kdf.N", N2); + assertArgument(r2 > 0 && p2 > 0, "invalid kdf", "kdf", kdf); + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dflen", dkLen); + return { name: "scrypt", salt, N: N2, r: r2, p: p2, dkLen: 64 }; + } else if (kdf.toLowerCase() === "pbkdf2") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const prf = spelunk(data, "crypto.kdfparams.prf:string!"); + const algorithm = prf.split("-").pop(); + assertArgument(algorithm === "sha256" || algorithm === "sha512", "invalid kdf.pdf", "kdf.pdf", prf); + const count2 = spelunk(data, "crypto.kdfparams.c:int!"); + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dklen", dkLen); + return { name: "pbkdf2", salt, count: count2, dkLen, algorithm }; } } - if (transaction2.delegateCall) { - throw new Error("delegate calls are forbidden"); + assertArgument(false, "unsupported key-derivation function", "kdf", kdf); +} +function decryptKeystoreJsonSync(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getDecryptKdfParams(data); + if (params.name === "pbkdf2") { + const { salt: salt2, count: count2, dkLen: dkLen2, algorithm } = params; + const key2 = pbkdf2(password, salt2, count2, dkLen2, algorithm); + return getAccount(data, key2); } - if (transaction2.data) { - const data = hexlify(transaction2.data); - const selector2 = data.slice(0, 10); - const signature2 = PROHIBITED_FUNCTIONS.get(selector2); - if (signature2) { - const name2 = signature2.slice(0, signature2.indexOf("(")); - throw new Error(`${name2} calls are forbidden`); + assert(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params }); + const { salt, N: N2, r: r2, p: p2, dkLen } = params; + const key = scryptSync(password, salt, N2, r2, p2, dkLen); + return getAccount(data, key); +} +function stall$1(duration) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, duration); + }); +} +async function decryptKeystoreJson(json, _password, progress2) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getDecryptKdfParams(data); + if (params.name === "pbkdf2") { + if (progress2) { + progress2(0); + await stall$1(0); + } + const { salt: salt2, count: count2, dkLen: dkLen2, algorithm } = params; + const key2 = pbkdf2(password, salt2, count2, dkLen2, algorithm); + if (progress2) { + progress2(1); + await stall$1(0); } + return getAccount(data, key2); } + assert(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params }); + const { salt, N: N2, r: r2, p: p2, dkLen } = params; + const key = await scrypt(password, salt, N2, r2, p2, dkLen, progress2); + return getAccount(data, key); } -function isCreateContractCall(data) { - const walletInterface = new Interface(walletContracts.mainModule.abi); - try { - walletInterface.decodeFunctionData("createContract", data); - return true; - } catch (_unused) { - return false; +function getEncryptKdfParams(options) { + const salt = options.salt != null ? getBytes(options.salt, "options.salt") : randomBytes(32); + let N2 = 1 << 17, r2 = 8, p2 = 1; + if (options.scrypt) { + if (options.scrypt.N) { + N2 = options.scrypt.N; + } + if (options.scrypt.r) { + r2 = options.scrypt.r; + } + if (options.scrypt.p) { + p2 = options.scrypt.p; + } } + assertArgument(typeof N2 === "number" && N2 > 0 && Number.isSafeInteger(N2) && (BigInt(N2) & BigInt(N2 - 1)) === BigInt(0), "invalid scrypt N parameter", "options.N", N2); + assertArgument(typeof r2 === "number" && r2 > 0 && Number.isSafeInteger(r2), "invalid scrypt r parameter", "options.r", r2); + assertArgument(typeof p2 === "number" && p2 > 0 && Number.isSafeInteger(p2), "invalid scrypt p parameter", "options.p", p2); + return { name: "scrypt", dkLen: 32, salt, N: N2, r: r2, p: p2 }; } -function _extends$2() { - _extends$2 = Object.assign ? Object.assign.bind() : function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } +function _encryptKeystore(key, kdf, account2, options) { + const privateKey = getBytes(account2.privateKey, "privateKey"); + const iv = options.iv != null ? getBytes(options.iv, "options.iv") : randomBytes(16); + assertArgument(iv.length === 16, "invalid options.iv length", "options.iv", options.iv); + const uuidRandom = options.uuid != null ? getBytes(options.uuid, "options.uuid") : randomBytes(16); + assertArgument(uuidRandom.length === 16, "invalid options.uuid length", "options.uuid", options.iv); + const derivedKey = key.slice(0, 16); + const macPrefix = key.slice(16, 32); + const aesCtr = new CTR(derivedKey, iv); + const ciphertext = getBytes(aesCtr.encrypt(privateKey)); + const mac = keccak256(concat([macPrefix, ciphertext])); + const data = { + address: account2.address.substring(2).toLowerCase(), + id: uuidV4(uuidRandom), + version: 3, + Crypto: { + cipher: "aes-128-ctr", + cipherparams: { + iv: hexlify(iv).substring(2) + }, + ciphertext: hexlify(ciphertext).substring(2), + kdf: "scrypt", + kdfparams: { + salt: hexlify(kdf.salt).substring(2), + n: kdf.N, + dklen: 32, + p: kdf.p, + r: kdf.r + }, + mac: mac.substring(2) } - return target; }; - return _extends$2.apply(this, arguments); + if (account2.mnemonic) { + const client2 = options.client != null ? options.client : `ethers/${version$5}`; + const path = account2.mnemonic.path || defaultPath$1; + const locale = account2.mnemonic.locale || "en"; + const mnemonicKey = key.slice(32, 64); + const entropy = getBytes(account2.mnemonic.entropy, "account.mnemonic.entropy"); + const mnemonicIv = randomBytes(16); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + const mnemonicCiphertext = getBytes(mnemonicAesCtr.encrypt(entropy)); + const now = /* @__PURE__ */ new Date(); + const timestamp = now.getUTCFullYear() + "-" + zpad$1(now.getUTCMonth() + 1, 2) + "-" + zpad$1(now.getUTCDate(), 2) + "T" + zpad$1(now.getUTCHours(), 2) + "-" + zpad$1(now.getUTCMinutes(), 2) + "-" + zpad$1(now.getUTCSeconds(), 2) + ".0Z"; + const gethFilename = "UTC--" + timestamp + "--" + data.address; + data["x-ethers"] = { + client: client2, + gethFilename, + path, + locale, + mnemonicCounter: hexlify(mnemonicIv).substring(2), + mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2), + version: "0.1" + }; + } + return JSON.stringify(data); } -function isProviderTransport(transport) { - return transport && typeof transport === "object" && typeof transport.register === "function" && typeof transport.unregister === "function" && typeof transport.openWallet === "function" && typeof transport.closeWallet === "function" && typeof transport.isOpened === "function" && typeof transport.isConnected === "function" && typeof transport.on === "function"; +function encryptKeystoreJsonSync(account2, password, options) { + if (options == null) { + options = {}; + } + const passwordBytes = getPassword(password); + const kdf = getEncryptKdfParams(options); + const key = scryptSync(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64); + return _encryptKeystore(getBytes(key), kdf, account2, options); } -class WindowSessionParams extends URLSearchParams { - static new(init2) { - return new URLSearchParams(init2); +async function encryptKeystoreJson(account2, password, options) { + if (options == null) { + options = {}; } + const passwordBytes = getPassword(password); + const kdf = getEncryptKdfParams(options); + const key = await scrypt(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64, options.progressCallback); + return _encryptKeystore(getBytes(key), kdf, account2, options); } -let EventType = /* @__PURE__ */ function(EventType2) { - EventType2["OPEN"] = "open"; - EventType2["CLOSE"] = "close"; - EventType2["MESSAGE"] = "message"; - EventType2["CONNECT"] = "connect"; - EventType2["DISCONNECT"] = "disconnect"; - EventType2["ACCOUNTS_CHANGED"] = "accountsChanged"; - EventType2["CHAIN_CHANGED"] = "chainChanged"; - EventType2["NETWORKS"] = "networks"; - EventType2["WALLET_CONTEXT"] = "walletContext"; - EventType2["INIT"] = "init"; - EventType2["DEBUG"] = "_debug"; - return EventType2; -}({}); -let OpenState = /* @__PURE__ */ function(OpenState2) { - OpenState2[OpenState2["CLOSED"] = 0] = "CLOSED"; - OpenState2[OpenState2["OPENING"] = 1] = "OPENING"; - OpenState2[OpenState2["OPENED"] = 2] = "OPENED"; - return OpenState2; -}({}); -let InitState = /* @__PURE__ */ function(InitState2) { - InitState2[InitState2["NIL"] = 0] = "NIL"; - InitState2[InitState2["SENT_NONCE"] = 1] = "SENT_NONCE"; - InitState2[InitState2["OK"] = 2] = "OK"; - return InitState2; -}({}); -class ProviderError extends Error { - constructor(message) { - super(message); - this.name = "ProviderError"; +const defaultPath = "m/44'/60'/0'/0/0"; +const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]); +const HardenedBit = 2147483648; +const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const Nibbles = "0123456789abcdef"; +function zpad(value, length) { + let result = ""; + while (value) { + result = Nibbles[value % 16] + result; + value = Math.trunc(value / 16); } + while (result.length < length * 2) { + result = "0" + result; + } + return "0x" + result; } -const ErrSignedInRequired = new ProviderError("Wallet is not signed in. Connect a wallet and try again."); -const PROVIDER_OPEN_TIMEOUT = 3e4; -let _messageIdx = 0; -const nextMessageIdx = () => ++_messageIdx; -class BaseProviderTransport { - constructor() { - var _this = this; - this.pendingMessageRequests = []; - this.responseCallbacks = /* @__PURE__ */ new Map(); - this.state = void 0; - this.confirmationOnly = false; - this.events = new eventemitter2Exports.EventEmitter2(); - this.openPayload = void 0; - this.connectPayload = void 0; - this.accountsChangedPayload = void 0; - this.networksPayload = void 0; - this.walletContextPayload = void 0; - this._sessionId = void 0; - this._init = void 0; - this._registered = void 0; - this.sendMessageRequest = async function(message) { - return new Promise((resolve, reject) => { - if ((!message.idx || message.idx <= 0) && message.type !== "init") { - reject(new Error("message idx not set")); - } - const responseCallback = (error, response) => { - if (error) { - reject(error); - } else if (response) { - resolve(response); - } else { - throw new Error("no valid response to return"); - } - }; - const idx = message.idx; - if (!_this.responseCallbacks.get(idx)) { - _this.responseCallbacks.set(idx, responseCallback); - } else { - reject(new Error("duplicate message idx, should never happen")); - } - if (!_this.isOpened()) { - logger.debug("pushing to pending requests", message); - _this.pendingMessageRequests.push(message); - } else { - _this.sendMessage(message); - } - }); - }; - this.waitUntilOpened = async function(openTimeout = PROVIDER_OPEN_TIMEOUT) { - let opened = false; - return Promise.race([new Promise((_, reject) => { - const timeout = setTimeout(() => { - clearTimeout(timeout); - if (!opened) { - _this.state = OpenState.CLOSED; - _this.events.emit("close", { - code: 1005, - message: "opening wallet timed out" - }); - } - reject(new Error("opening wallet timed out")); - }, openTimeout); - }), new Promise((resolve) => { - if (_this.isOpened()) { - var _this$openPayload; - opened = true; - resolve((_this$openPayload = _this.openPayload) == null ? void 0 : _this$openPayload.session); - return; - } - _this.events.once("open", (openInfo) => { - _this.openPayload = openInfo; - opened = true; - resolve(openInfo.session); - }); - })]); - }; - this.waitUntilConnected = async function() { - await _this.waitUntilOpened(); - const connect2 = new Promise((resolve) => { - if (_this.connectPayload) { - resolve(_this.connectPayload); - return; - } - _this.events.once("connect", (connectDetails) => { - _this.connectPayload = connectDetails; - resolve(connectDetails); - }); - }); - const closeWallet = new Promise((_, reject) => { - _this.events.once("close", (error) => { - if (error) { - reject(new Error(`wallet closed due to ${JSON.stringify(error)}`)); - } else { - reject(new Error(`user closed the wallet`)); - } - }); - }); - return Promise.race([connect2, closeWallet]); - }; - this.state = OpenState.CLOSED; - this._registered = false; - this._init = InitState.NIL; +function encodeBase58Check(_value2) { + const value = getBytes(_value2); + const check = dataSlice(sha256$1(sha256$1(value)), 0, 4); + const bytes2 = concat([value, check]); + return encodeBase58(bytes2); +} +const _guard = {}; +function ser_I(index2, chainCode, publicKey, privateKey) { + const data = new Uint8Array(37); + if (index2 & HardenedBit) { + assert(privateKey != null, "cannot derive child of neutered node", "UNSUPPORTED_OPERATION", { + operation: "deriveChild" + }); + data.set(getBytes(privateKey), 1); + } else { + data.set(getBytes(publicKey)); } - get registered() { - return this._registered; + for (let i = 24; i >= 0; i -= 8) { + data[33 + (i >> 3)] = index2 >> 24 - i & 255; } - register() { - throw new Error("abstract method"); + const I2 = getBytes(computeHmac("sha512", chainCode, data)); + return { IL: I2.slice(0, 32), IR: I2.slice(32) }; +} +function derivePath(node, path) { + const components = path.split("/"); + assertArgument(components.length > 0, "invalid path", "path", path); + if (components[0] === "m") { + assertArgument(node.depth === 0, `cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${node.depth}`, "path", path); + components.shift(); + } + let result = node; + for (let i = 0; i < components.length; i++) { + const component = components[i]; + if (component.match(/^[0-9]+'$/)) { + const index2 = parseInt(component.substring(0, component.length - 1)); + assertArgument(index2 < HardenedBit, "invalid path index", `path[${i}]`, component); + result = result.deriveChild(HardenedBit + index2); + } else if (component.match(/^[0-9]+$/)) { + const index2 = parseInt(component); + assertArgument(index2 < HardenedBit, "invalid path index", `path[${i}]`, component); + result = result.deriveChild(index2); + } else { + assertArgument(false, "invalid path component", `path[${i}]`, component); + } + } + return result; +} +const _HDNodeWallet = class _HDNodeWallet extends BaseWallet { + /** + * @private + */ + constructor(guard2, signingKey, parentFingerprint, chainCode, path, index2, depth, mnemonic, provider2) { + super(signingKey, provider2); + __privateAdd(this, _HDNodeWallet_instances); + /** + * The compressed public key. + */ + __publicField(this, "publicKey"); + /** + * The fingerprint. + * + * A fingerprint allows quick qay to detect parent and child nodes, + * but developers should be prepared to deal with collisions as it + * is only 4 bytes. + */ + __publicField(this, "fingerprint"); + /** + * The parent fingerprint. + */ + __publicField(this, "parentFingerprint"); + /** + * The mnemonic used to create this HD Node, if available. + * + * Sources such as extended keys do not encode the mnemonic, in + * which case this will be ``null``. + */ + __publicField(this, "mnemonic"); + /** + * The chaincode, which is effectively a public key used + * to derive children. + */ + __publicField(this, "chainCode"); + /** + * The derivation path of this wallet. + * + * Since extended keys do not provide full path details, this + * may be ``null``, if instantiated from a source that does not + * encode it. + */ + __publicField(this, "path"); + /** + * The child index of this wallet. Values over ``2 *\* 31`` indicate + * the node is hardened. + */ + __publicField(this, "index"); + /** + * The depth of this wallet, which is the number of components + * in its path. + */ + __publicField(this, "depth"); + assertPrivate(guard2, _guard, "HDNodeWallet"); + defineProperties$1(this, { publicKey: signingKey.compressedPublicKey }); + const fingerprint = dataSlice(ripemd160(sha256$1(this.publicKey)), 0, 4); + defineProperties$1(this, { + parentFingerprint, + fingerprint, + chainCode, + path, + index: index2, + depth + }); + defineProperties$1(this, { mnemonic }); } - unregister() { - throw new Error("abstract method"); + connect(provider2) { + return new _HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider2); } - openWallet(path, intent, networkId) { - throw new Error("abstract method"); + /** + * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with + * %%password%%. + * + * If %%progressCallback%% is specified, it will receive periodic + * updates as the encryption process progreses. + */ + async encrypt(password, progressCallback) { + return await encryptKeystoreJson(__privateMethod(this, _HDNodeWallet_instances, account_fn).call(this), password, { progressCallback }); } - closeWallet() { - throw new Error("abstract method"); + /** + * Returns a [JSON Keystore Wallet](json-wallets) encryped with + * %%password%%. + * + * It is preferred to use the [async version](encrypt) instead, + * which allows a [[ProgressCallback]] to keep the user informed. + * + * This method will block the event loop (freezing all UI) until + * it is complete, which may be a non-trivial duration. + */ + encryptSync(password) { + return encryptKeystoreJsonSync(__privateMethod(this, _HDNodeWallet_instances, account_fn).call(this), password); } - isOpened() { - return this.registered && this.state === OpenState.OPENED; + /** + * The extended key. + * + * This key will begin with the prefix ``xpriv`` and can be used to + * reconstruct this HD Node to derive its children. + */ + get extendedKey() { + assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" }); + return encodeBase58Check(concat([ + "0x0488ADE4", + zpad(this.depth, 1), + this.parentFingerprint, + zpad(this.index, 4), + this.chainCode, + concat(["0x00", this.privateKey]) + ])); } - isConnected() { - var _this$openPayload2; - const session = (_this$openPayload2 = this.openPayload) == null ? void 0 : _this$openPayload2.session; - return this.registered && session !== void 0 && !!session.accountAddress && session.accountAddress.length === 42 && !!session.networks && session.networks.length > 0; + /** + * Returns true if this wallet has a path, providing a Type Guard + * that the path is non-null. + */ + hasPath() { + return this.path != null; } - async request(request) { - if (this.state === OpenState.CLOSED) { - this.confirmationOnly = true; - } - this.openWallet(void 0, { - type: "jsonRpcRequest", - method: request.method - }, request.chainId); - if (!this.isOpened()) { - await this.waitUntilOpened(); - } - const response = await this.sendMessageRequest({ - idx: nextMessageIdx(), - type: EventType.MESSAGE, - data: request, - chainId: request.chainId, - clientVersion: VERSION$1 - }); - return response.data; + /** + * Returns a neutered HD Node, which removes the private details + * of an HD Node. + * + * A neutered node has no private key, but can be used to derive + * child addresses and other public data about the HD Node. + */ + neuter() { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider); } - // handleMessage will handle message received from the remote wallet - handleMessage(message) { - var _this2 = this; - if (message.type === EventType.INIT) { - logger.debug("MessageProvider, received INIT message", message); - const { - nonce - } = message.data; - if (!nonce || nonce.length == 0) { - logger.error("invalid init nonce"); - return; - } - this._init = InitState.OK; - this.sendMessage({ - idx: -1, - type: EventType.INIT, - data: { - sessionId: this._sessionId, - nonce - }, - clientVersion: VERSION$1 - }); - } - if (this._init !== InitState.OK) { - return; - } - logger.debug("RECEIVED MESSAGE FROM WALLET", message.idx, message); - const requestIdx = message.idx; - const responseCallback = this.responseCallbacks.get(requestIdx); - if (requestIdx) { - this.responseCallbacks.delete(requestIdx); - } - if (message.type === EventType.OPEN && !this.isOpened()) { - var _message$data, _message$data2; - if (this._sessionId && this._sessionId !== ((_message$data = message.data) == null ? void 0 : _message$data.sessionId)) { - logger.debug("open event received from wallet, but does not match sessionId", this._sessionId); - return; - } - if ((_message$data2 = message.data) != null && _message$data2.error) { - var _message$data3; - const err = new Error(`opening wallet failed: received ${(_message$data3 = message.data) == null ? void 0 : _message$data3.error}`); - logger.error(err); - this.close(); - throw err; - } - this.state = OpenState.OPENED; - this.openPayload = message.data; - this.events.emit("open", this.openPayload); - if (this.pendingMessageRequests.length !== 0) { - const pendingMessageRequests = this.pendingMessageRequests.splice(0, this.pendingMessageRequests.length); - pendingMessageRequests.forEach(async function(pendingMessageRequest) { - _this2.sendMessage(pendingMessageRequest); - }); + /** + * Return the child for %%index%%. + */ + deriveChild(_index) { + const index2 = getNumber(_index, "index"); + assertArgument(index2 <= 4294967295, "invalid index", "index", index2); + let path = this.path; + if (path) { + path += "/" + (index2 & ~HardenedBit); + if (index2 & HardenedBit) { + path += "'"; } - return; } - if (message.type === EventType.MESSAGE) { - if (this.confirmationOnly) { - setTimeout(() => { - if (this.responseCallbacks.size === 0) { - this.closeWallet(); - } - }, 500); - } - if (!responseCallback) { - throw new Error("impossible state"); - } - if (responseCallback) { - this.events.emit("message", message); - responseCallback(message.data.error, message); - return; + const { IR, IL } = ser_I(index2, this.chainCode, this.publicKey, this.privateKey); + const ki2 = new SigningKey(toBeHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32)); + return new _HDNodeWallet(_guard, ki2, this.fingerprint, hexlify(IR), path, index2, this.depth + 1, this.mnemonic, this.provider); + } + /** + * Return the HDNode for %%path%% from this node. + */ + derivePath(path) { + return derivePath(this, path); + } + /** + * Creates a new HD Node from %%extendedKey%%. + * + * If the %%extendedKey%% will either have a prefix or ``xpub`` or + * ``xpriv``, returning a neutered HD Node ([[HDNodeVoidWallet]]) + * or full HD Node ([[HDNodeWallet) respectively. + */ + static fromExtendedKey(extendedKey) { + const bytes2 = toBeArray(decodeBase58(extendedKey)); + assertArgument(bytes2.length === 82 || encodeBase58Check(bytes2.slice(0, 78)) === extendedKey, "invalid extended key", "extendedKey", "[ REDACTED ]"); + const depth = bytes2[4]; + const parentFingerprint = hexlify(bytes2.slice(5, 9)); + const index2 = parseInt(hexlify(bytes2.slice(9, 13)).substring(2), 16); + const chainCode = hexlify(bytes2.slice(13, 45)); + const key = bytes2.slice(45, 78); + switch (hexlify(bytes2.slice(0, 4))) { + case "0x0488b21e": + case "0x043587cf": { + const publicKey = hexlify(key); + return new HDNodeVoidWallet(_guard, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index2, depth, null); } + case "0x0488ade4": + case "0x04358394 ": + if (key[0] !== 0) { + break; + } + return new _HDNodeWallet(_guard, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index2, depth, null, null); } - if (message.type === EventType.ACCOUNTS_CHANGED) { - this.accountsChangedPayload = { - accounts: [] - }; - if (message.data && message.data.length > 0) { - this.accountsChangedPayload = { - accounts: [getAddress$1(message.data[0])], - origin: message.origin - }; - this.events.emit("accountsChanged", this.accountsChangedPayload.accounts, this.accountsChangedPayload.origin); - } else { - this.events.emit("accountsChanged", [], message.origin); - } - return; + assertArgument(false, "invalid extended key prefix", "extendedKey", "[ REDACTED ]"); + } + /** + * Creates a new random HDNode. + */ + static createRandom(password, path, wordlist2) { + var _a2; + if (password == null) { + password = ""; } - if (message.type === EventType.CHAIN_CHANGED) { - this.events.emit("chainChanged", message.data, message.origin); - return; + if (path == null) { + path = defaultPath; } - if (message.type === EventType.NETWORKS) { - this.networksPayload = message.data; - this.events.emit("networks", this.networksPayload); - return; + if (wordlist2 == null) { + wordlist2 = LangEn.wordlist(); } - if (message.type === EventType.WALLET_CONTEXT) { - this.walletContextPayload = message.data; - this.events.emit("walletContext", this.walletContextPayload); - return; + const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist2); + return __privateMethod(_a2 = _HDNodeWallet, _HDNodeWallet_static, fromSeed_fn).call(_a2, mnemonic.computeSeed(), mnemonic).derivePath(path); + } + /** + * Create an HD Node from %%mnemonic%%. + */ + static fromMnemonic(mnemonic, path) { + var _a2; + if (!path) { + path = defaultPath; } - if (message.type === EventType.CLOSE) { - if (this.state !== OpenState.CLOSED) { - this.close(message.data); - } + return __privateMethod(_a2 = _HDNodeWallet, _HDNodeWallet_static, fromSeed_fn).call(_a2, mnemonic.computeSeed(), mnemonic).derivePath(path); + } + /** + * Creates an HD Node from a mnemonic %%phrase%%. + */ + static fromPhrase(phrase, password, path, wordlist2) { + var _a2; + if (password == null) { + password = ""; } - if (message.type === EventType.CONNECT) { - this.connectPayload = message.data; - this.events.emit("connect", this.connectPayload); + if (path == null) { + path = defaultPath; } - if (message.type === EventType.DISCONNECT) { - if (this.isConnected()) { - this.events.emit("disconnect", message.data, message.origin); - this.close(); - } + if (wordlist2 == null) { + wordlist2 = LangEn.wordlist(); } + const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist2); + return __privateMethod(_a2 = _HDNodeWallet, _HDNodeWallet_static, fromSeed_fn).call(_a2, mnemonic.computeSeed(), mnemonic).derivePath(path); } - sendMessage(message) { - throw new Error("abstract method"); - } - on(event, fn) { - this.events.on(event, fn); - } - once(event, fn) { - this.events.once(event, fn); - } - emit(event, ...args) { - return this.events.emit(event, ...args); - } - close(error) { - if (this.state === OpenState.CLOSED) return; - this.state = OpenState.CLOSED; - this.confirmationOnly = false; - this._sessionId = void 0; - logger.info("closing wallet and flushing!"); - this.pendingMessageRequests.length = 0; - this.responseCallbacks.forEach((responseCallback) => { - responseCallback(_extends$2({}, new Error("wallet closed"), { - code: 4001 - })); - }); - this.responseCallbacks.clear(); - this.connectPayload = void 0; - this.openPayload = void 0; - this.accountsChangedPayload = void 0; - this.networksPayload = void 0; - this.walletContextPayload = void 0; - this.events.emit("close", error); - } -} -function messageIsExemptFromEIP191Prefix(message) { - return EIP_191_PREFIX_EXCEPTIONS.some((e2) => e2.predicate(message)); -} -const EIP_191_PREFIX_EXCEPTIONS = [ - // NOTE: Decentraland does not support 191 correctly. - { - name: "Decentraland Exception", - predicate: isDecentralandLoginMessage - }, - // NOTE: 0x v3 does not support 191 correctly. - // See https://gov.0x.org/t/zeip-proposal-fix-v3-eip-191-non-compliance-when-validating-eip-1271-signatures/3396 for more info. - { - name: "0x v3 Exception", - predicate: isZeroExV3Order - } -]; -const DCL_REGEX = /^Decentraland Login\nEphemeral address: 0x[a-fA-F0-9]{40}\nExpiration: (\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)((-(\d{2}):(\d{2})|Z)?)$/; -function isDecentralandLoginMessage(bytes2) { - try { - const stringified = toUtf8String(bytes2); - return DCL_REGEX.test(stringified); - } catch (_unused) { - return false; - } -} -function isZeroExV3Order(bytes2) { - const abi2 = new Interface(ZeroXV3EIP1271OrderWithHashAbi); - try { - abi2.decodeFunctionData("OrderWithHash", bytes2); - return true; - } catch (err) { - return false; - } -} -const ZeroXV3EIP1271OrderWithHashAbi = [{ - inputs: [{ - components: [{ - internalType: "address", - name: "makerAddress", - type: "address" - }, { - internalType: "address", - name: "takerAddress", - type: "address" - }, { - internalType: "address", - name: "feeRecipientAddress", - type: "address" - }, { - internalType: "address", - name: "senderAddress", - type: "address" - }, { - internalType: "uint256", - name: "makerAssetAmount", - type: "uint256" - }, { - internalType: "uint256", - name: "takerAssetAmount", - type: "uint256" - }, { - internalType: "uint256", - name: "makerFee", - type: "uint256" - }, { - internalType: "uint256", - name: "takerFee", - type: "uint256" - }, { - internalType: "uint256", - name: "expirationTimeSeconds", - type: "uint256" - }, { - internalType: "uint256", - name: "salt", - type: "uint256" - }, { - internalType: "bytes", - name: "makerAssetData", - type: "bytes" - }, { - internalType: "bytes", - name: "takerAssetData", - type: "bytes" - }, { - internalType: "bytes", - name: "makerFeeAssetData", - type: "bytes" - }, { - internalType: "bytes", - name: "takerFeeAssetData", - type: "bytes" - }], - internalType: "struct IEIP1271Data.Order", - name: "order", - type: "tuple" - }, { - internalType: "bytes32", - name: "orderHash", - type: "bytes32" - }], - name: "OrderWithHash", - outputs: [], - stateMutability: "pure", - type: "function" -}]; -const eip191prefix = toUtf8Bytes("Ethereum Signed Message:\n"); -const messageToBytes = (message) => { - if (isBytesLike(message)) { - return getBytes(message); + /** + * Creates an HD Node from a %%seed%%. + */ + static fromSeed(seed) { + var _a2; + return __privateMethod(_a2 = _HDNodeWallet, _HDNodeWallet_static, fromSeed_fn).call(_a2, seed, null); } - return toUtf8Bytes(message); }; -const prefixEIP191Message = (message) => { - const messageBytes = messageToBytes(message); - if (messageIsExemptFromEIP191Prefix(messageBytes)) { - return messageBytes; - } else { - return getBytes(concat$1([eip191prefix, toUtf8Bytes(String(messageBytes.length)), messageBytes])); +_HDNodeWallet_instances = new WeakSet(); +account_fn = function() { + const account2 = { address: this.address, privateKey: this.privateKey }; + const m2 = this.mnemonic; + if (this.path && m2 && m2.wordlist.locale === "en" && m2.password === "") { + account2.mnemonic = { + path: this.path, + locale: "en", + entropy: m2.entropy + }; } + return account2; }; -const trimEIP191Prefix = (prefixedMessage) => { - if (JSON.stringify(prefixedMessage.slice(0, eip191prefix.length)) !== JSON.stringify(eip191prefix)) { - return prefixedMessage; - } - const ethereumSignedMessagePartSlicedArray = prefixedMessage.slice(eip191prefix.length); - const maxPrefixCharLength = String(ethereumSignedMessagePartSlicedArray.length).length; - let prefixCharLenght; - let prefixAsNumber; - try { - prefixAsNumber = Number(toUtf8String(ethereumSignedMessagePartSlicedArray.slice(0, maxPrefixCharLength))); - } catch (_unused) { - prefixAsNumber = Number(hexlify(ethereumSignedMessagePartSlicedArray.slice(0, maxPrefixCharLength))); +_HDNodeWallet_static = new WeakSet(); +fromSeed_fn = function(_seed, mnemonic) { + assertArgument(isBytesLike(_seed), "invalid seed", "seed", "[REDACTED]"); + const seed = getBytes(_seed, "seed"); + assertArgument(seed.length >= 16 && seed.length <= 64, "invalid seed", "seed", "[REDACTED]"); + const I2 = getBytes(computeHmac("sha512", MasterSecret, seed)); + const signingKey = new SigningKey(hexlify(I2.slice(0, 32))); + return new _HDNodeWallet(_guard, signingKey, "0x00000000", hexlify(I2.slice(32)), "m", 0, 0, mnemonic, null); +}; +__privateAdd(_HDNodeWallet, _HDNodeWallet_static); +let HDNodeWallet = _HDNodeWallet; +class HDNodeVoidWallet extends VoidSigner { + /** + * @private + */ + constructor(guard2, address, publicKey, parentFingerprint, chainCode, path, index2, depth, provider2) { + super(address, provider2); + /** + * The compressed public key. + */ + __publicField(this, "publicKey"); + /** + * The fingerprint. + * + * A fingerprint allows quick qay to detect parent and child nodes, + * but developers should be prepared to deal with collisions as it + * is only 4 bytes. + */ + __publicField(this, "fingerprint"); + /** + * The parent node fingerprint. + */ + __publicField(this, "parentFingerprint"); + /** + * The chaincode, which is effectively a public key used + * to derive children. + */ + __publicField(this, "chainCode"); + /** + * The derivation path of this wallet. + * + * Since extended keys do not provider full path details, this + * may be ``null``, if instantiated from a source that does not + * enocde it. + */ + __publicField(this, "path"); + /** + * The child index of this wallet. Values over ``2 *\* 31`` indicate + * the node is hardened. + */ + __publicField(this, "index"); + /** + * The depth of this wallet, which is the number of components + * in its path. + */ + __publicField(this, "depth"); + assertPrivate(guard2, _guard, "HDNodeVoidWallet"); + defineProperties$1(this, { publicKey }); + const fingerprint = dataSlice(ripemd160(sha256$1(publicKey)), 0, 4); + defineProperties$1(this, { + publicKey, + fingerprint, + parentFingerprint, + chainCode, + path, + index: index2, + depth + }); } - if (prefixAsNumber > ethereumSignedMessagePartSlicedArray.length || !Number.isInteger(prefixAsNumber)) { - prefixCharLenght = maxPrefixCharLength - 1; - } else { - prefixCharLenght = maxPrefixCharLength; + connect(provider2) { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider2); } - const prefixRevertedMessage = ethereumSignedMessagePartSlicedArray.slice(prefixCharLenght); - return prefixRevertedMessage; -}; -const isValidSignature = async (address, digest, sig, provider2) => { - const reader2 = new index$1$2.reader.OnChainReader(provider2); - return reader2.isValidSignature(address, digest, sig); -}; -const isValidMessageSignature = async (address, message, signature2, provider2) => { - const prefixed = prefixEIP191Message(message); - const digest = encodeMessageDigest(prefixed); - return isValidSignature(address, digest, signature2, provider2); -}; -const isValidTypedDataSignature = (address, typedData, signature2, provider2) => { - return isValidSignature(address, encodeTypedDataDigest(typedData), signature2, provider2); -}; -const isBrowserExtension = () => window.location.protocol === "chrome-extension:" || window.location.protocol === "moz-extension:"; -const isUnityPlugin = () => !!navigator.userAgent.match(/UnitySequence/i); -const isWalletUpToDate = (status) => { - return status.onChain.deployed && status.fullyMigrated; -}; -class MemoryItemStore { - constructor() { - this.callbacks = []; - this.store = {}; + /** + * The extended key. + * + * This key will begin with the prefix ``xpub`` and can be used to + * reconstruct this neutered key to derive its children addresses. + */ + get extendedKey() { + assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" }); + return encodeBase58Check(concat([ + "0x0488B21E", + zpad(this.depth, 1), + this.parentFingerprint, + zpad(this.index, 4), + this.chainCode, + this.publicKey + ])); } - getItem(key) { - return this.store[key] || null; + /** + * Returns true if this wallet has a path, providing a Type Guard + * that the path is non-null. + */ + hasPath() { + return this.path != null; } - setItem(key, value) { - this.store[key] = value; - this.callbacks.filter((c2) => c2.key === key).forEach((c2) => c2.cb(value)); + /** + * Return the child for %%index%%. + */ + deriveChild(_index) { + const index2 = getNumber(_index, "index"); + assertArgument(index2 <= 4294967295, "invalid index", "index", index2); + let path = this.path; + if (path) { + path += "/" + (index2 & ~HardenedBit); + if (index2 & HardenedBit) { + path += "'"; + } + } + const { IR, IL } = ser_I(index2, this.chainCode, this.publicKey, null); + const Ki2 = SigningKey.addPoints(IL, this.publicKey, true); + const address = computeAddress(Ki2); + return new HDNodeVoidWallet(_guard, address, Ki2, this.fingerprint, hexlify(IR), path, index2, this.depth + 1, this.provider); } - removeItem(key) { - delete this.store[key]; + /** + * Return the signer for %%path%% from this node. + */ + derivePath(path) { + return derivePath(this, path); } - onItemChange(key, cb2) { - this.callbacks.push({ - key, - cb: cb2 - }); - return () => { - this.callbacks = this.callbacks.filter((c2) => c2.cb !== cb2); - }; +} +function getAccountPath(_index) { + const index2 = getNumber(_index, "index"); + assertArgument(index2 >= 0 && index2 < HardenedBit, "invalid account index", "index", index2); + return `m/44'/60'/${index2}'/0/0`; +} +function getIndexedAccountPath(_index) { + const index2 = getNumber(_index, "index"); + assertArgument(index2 >= 0 && index2 < HardenedBit, "invalid account index", "index", index2); + return `m/44'/60'/0'/0/${index2}`; +} +function isCrowdsaleJson(json) { + try { + const data = JSON.parse(json); + if (data.encseed) { + return true; + } + } catch (error) { } + return false; } -class LocalStorage { - static isAvailable() { - return typeof window === "object" && typeof window.localStorage === "object"; +function decryptCrowdsaleJson(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + const address = getAddress(spelunk(data, "ethaddr:string!")); + const encseed = looseArrayify(spelunk(data, "encseed:string!")); + assertArgument(encseed && encseed.length % 16 === 0, "invalid encseed", "json", json); + const key = getBytes(pbkdf2(password, password, 2e3, 32, "sha256")).slice(0, 16); + const iv = encseed.slice(0, 16); + const encryptedSeed = encseed.slice(16); + const aesCbc = new CBC(key, iv); + const seed = pkcs7Strip(getBytes(aesCbc.decrypt(encryptedSeed))); + let seedHex = ""; + for (let i = 0; i < seed.length; i++) { + seedHex += String.fromCharCode(seed[i]); } - constructor() { - this.callbacks = []; - if (!LocalStorage.isAvailable()) { - throw new Error("LocalStorage is not available"); + return { address, privateKey: id$1(seedHex) }; +} +function stall(duration) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, duration); + }); +} +let Wallet$1 = (_m = class extends BaseWallet { + /** + * Create a new wallet for the private %%key%%, optionally connected + * to %%provider%%. + */ + constructor(key, provider2) { + if (typeof key === "string" && !key.startsWith("0x")) { + key = "0x" + key; } - window.addEventListener("storage", (e2) => { - const { - key - } = e2; - const cb2 = this.callbacks.filter((c2) => c2.key === key); - cb2.forEach((c2) => c2.cb(this.getItem(key))); - }); + let signingKey = typeof key === "string" ? new SigningKey(key) : key; + super(signingKey, provider2); } - getItem(key) { - return window.localStorage.getItem(key); + connect(provider2) { + return new _m(this.signingKey, provider2); } - setItem(key, value) { - window.localStorage.setItem(key, value); - this.callbacks.filter((c2) => c2.key === key).forEach((c2) => c2.cb(value)); + /** + * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with + * %%password%%. + * + * If %%progressCallback%% is specified, it will receive periodic + * updates as the encryption process progreses. + */ + async encrypt(password, progressCallback) { + const account2 = { address: this.address, privateKey: this.privateKey }; + return await encryptKeystoreJson(account2, password, { progressCallback }); } - removeItem(key) { - window.localStorage.removeItem(key); - this.callbacks.filter((c2) => c2.key === key).forEach((c2) => c2.cb(null)); + /** + * Returns a [JSON Keystore Wallet](json-wallets) encryped with + * %%password%%. + * + * It is preferred to use the [async version](encrypt) instead, + * which allows a [[ProgressCallback]] to keep the user informed. + * + * This method will block the event loop (freezing all UI) until + * it is complete, which may be a non-trivial duration. + */ + encryptSync(password) { + const account2 = { address: this.address, privateKey: this.privateKey }; + return encryptKeystoreJsonSync(account2, password); } - onItemChange(key, cb2) { - this.callbacks.push({ - key, - cb: cb2 - }); - return () => { - this.callbacks = this.callbacks.filter((c2) => c2.cb !== cb2); - }; + /** + * Creates (asynchronously) a **Wallet** by decrypting the %%json%% + * with %%password%%. + * + * If %%progress%% is provided, it is called periodically during + * decryption so that any UI can be updated. + */ + static async fromEncryptedJson(json, password, progress2) { + var _a2; + let account2 = null; + if (isKeystoreJson(json)) { + account2 = await decryptKeystoreJson(json, password, progress2); + } else if (isCrowdsaleJson(json)) { + if (progress2) { + progress2(0); + await stall(0); + } + account2 = decryptCrowdsaleJson(json, password); + if (progress2) { + progress2(1); + await stall(0); + } + } + return __privateMethod(_a2 = _m, _Wallet_static, fromAccount_fn).call(_a2, account2); } -} -function useBestStore() { - if (LocalStorage.isAvailable()) { - return new LocalStorage(); + /** + * Creates a **Wallet** by decrypting the %%json%% with %%password%%. + * + * The [[fromEncryptedJson]] method is preferred, as this method + * will lock up and freeze the UI during decryption, which may take + * some time. + */ + static fromEncryptedJsonSync(json, password) { + var _a2; + let account2 = null; + if (isKeystoreJson(json)) { + account2 = decryptKeystoreJsonSync(json, password); + } else if (isCrowdsaleJson(json)) { + account2 = decryptCrowdsaleJson(json, password); + } else { + assertArgument(false, "invalid JSON wallet", "json", "[ REDACTED ]"); + } + return __privateMethod(_a2 = _m, _Wallet_static, fromAccount_fn).call(_a2, account2); } - return new MemoryItemStore(); -} -async function resolveArrayProperties(object2) { - if (Array.isArray(object2)) { - return Promise.all(object2.map((o2) => resolveProperties$1(o2))); + /** + * Creates a new random [[HDNodeWallet]] using the available + * [cryptographic random source](randomBytes). + * + * If there is no crytographic random source, this will throw. + */ + static createRandom(provider2) { + const wallet = HDNodeWallet.createRandom(); + if (provider2) { + return wallet.connect(provider2); + } + return wallet; } - return resolveProperties$1(object2); -} -const TRANSPORT_SESSION_LS_KEY = "@sequence.transportSession"; -class BaseWalletTransport { - constructor(walletRequestHandler) { - var _this = this; - this.walletRequestHandler = void 0; - this._sessionId = void 0; - this._registered = void 0; - this._init = void 0; - this._initNonce = void 0; - this._initCallback = void 0; - this.appOrigin = void 0; - this.handleMessage = async function(message) { - const request = message; - if (_this._init !== InitState.OK) { - if (request.type === EventType.INIT) { - if (_this.isValidInitAck(message)) { - if (_this._initCallback) _this._initCallback(); - } else { - if (_this._initCallback) _this._initCallback("invalid init"); - return; - } - } - return; - } - switch (request.type) { - case EventType.OPEN: { - if (_this._init !== InitState.OK) return; - const session = { - sessionId: request.data.sessionId, - intent: request.data.intent, - networkId: request.data.networkId - }; - await _this.open(session); - return; - } - case EventType.CLOSE: { - if (_this._init !== InitState.OK) return; - return; - } - case EventType.MESSAGE: { - const response = await _this.walletRequestHandler.sendMessageRequest(request); - _this.sendMessage(response); - if (response.data.error) ; - return; - } - default: { - logger.error(`unexpected payload type ${request.type}`); - } - } - }; - this.sendMessageRequest = async function(message) { - return _this.walletRequestHandler.sendMessageRequest(message); - }; - this.open = async function({ - sessionId, - intent, - networkId - }) { - if (sessionId) { - _this._sessionId = sanitizeNumberString(sessionId); - _this.saveTransportSession({ - sessionId, - intent, - networkId - }); - } - _this.walletRequestHandler.setOpenIntent(intent); - await _this.init(); - let chainId = void 0; - try { - if (networkId) { - const network2 = findSupportedNetwork(networkId); - if (network2) { - chainId = network2.chainId; - } else { - throw new Error(`unknown network ${networkId}`); - } - } else { - chainId = _this.walletRequestHandler.defaultChainId(); - } - } catch (err) { - console.error(err); - } - if (intent && intent.type === "connect" && intent.options) { - const connectOptions = intent.options; - const authorizeOptions = connectOptions; - if (_this.appOrigin && authorizeOptions != null && authorizeOptions.origin) { - if (!isBrowserExtension()) { - if (authorizeOptions.origin !== _this.appOrigin) { - throw new Error("origin is invalid"); - } - } - } else if (!_this.appOrigin && authorizeOptions != null && authorizeOptions.origin) { - connectOptions.origin = sanitizeHost(authorizeOptions.origin); - } else if (_this.appOrigin) { - connectOptions.origin = _this.appOrigin; - } - if (connectOptions.app) { - connectOptions.app = sanitizeAlphanumeric(connectOptions.app); - } - if (connectOptions.networkId) { - networkId = connectOptions.networkId; - } else if (networkId) { - connectOptions.networkId = networkId; - } - _this.walletRequestHandler.setConnectOptions(connectOptions); - } else { - _this.walletRequestHandler.setConnectOptions(void 0); - } - await _this.walletRequestHandler.getAccount(); - if (!await _this.walletRequestHandler.isSignedIn()) { - _this.notifyOpen({ - sessionId: _this._sessionId - }); - return true; - } else { - if (intent && intent.type === "connect") { - if (!chainId || chainId <= 0) { - console.log("Failed to set default network on open"); - } - _this.notifyOpen({ - sessionId: _this._sessionId - }); - try { - const connectDetails = await _this.walletRequestHandler.promptConnect(intent.options); - if (connectDetails.connected) { - _this.walletRequestHandler.notifyConnect(connectDetails); - } - } catch (err) { - logger.warn("promptConnect not connected:", err); - } finally { - if (!intent.options || intent.options.keepWalletOpened !== true) { - _this.notifyClose(); - } - } - } else { - if (!chainId || chainId <= 0) { - _this.notifyOpen({ - sessionId: _this._sessionId, - error: `failed to open wallet on network ${networkId}` - }); - return false; - } - _this.notifyOpen({ - sessionId: _this._sessionId, - chainId: `${chainId}`, - session: await _this.walletRequestHandler.walletSession(chainId) - }); - } - } - return true; - }; - this.saveTransportSession = (session) => { - useBestStore().setItem(TRANSPORT_SESSION_LS_KEY, JSON.stringify(session)); - }; - this.getCachedTransportSession = async function() { - const session = useBestStore().getItem(TRANSPORT_SESSION_LS_KEY); - try { - return session ? JSON.parse(session) : null; - } catch (err) { - console.error(`unable to parse transport session: ${session}`); - return null; - } - }; - this.walletRequestHandler = walletRequestHandler; - this._init = InitState.NIL; - this.walletRequestHandler.on("connect", (connectDetails) => { - if (!this.registered) return; - this.notifyConnect(connectDetails); - }); - this.walletRequestHandler.on("disconnect", (error, origin) => { - if (!this.registered) return; - this.notifyDisconnect(error, origin); - }); - this.walletRequestHandler.on("accountsChanged", (accounts, origin) => { - if (!this.registered) return; - this.notifyAccountsChanged(accounts, origin); - }); - this.walletRequestHandler.on("networks", (networks2) => { - if (!this.registered) return; - this.notifyNetworks(networks2); - if (!networks2 || networks2.length === 0) { - this.notifyChainChanged("0x0"); + /** + * Creates a [[HDNodeWallet]] for %%phrase%%. + */ + static fromPhrase(phrase, provider2) { + const wallet = HDNodeWallet.fromPhrase(phrase); + if (provider2) { + return wallet.connect(provider2); + } + return wallet; + } +}, _Wallet_static = new WeakSet(), fromAccount_fn = function(account2) { + assertArgument(account2, "invalid JSON wallet", "json", "[ REDACTED ]"); + if ("mnemonic" in account2 && account2.mnemonic && account2.mnemonic.locale === "en") { + const mnemonic = Mnemonic.fromEntropy(account2.mnemonic.entropy); + const wallet2 = HDNodeWallet.fromMnemonic(mnemonic, account2.mnemonic.path); + if (wallet2.address === account2.address && wallet2.privateKey === account2.privateKey) { + return wallet2; + } + console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key"); + } + const wallet = new _m(account2.privateKey); + assertArgument(wallet.address === account2.address, "address/privateKey mismatch", "json", "[ REDACTED ]"); + return wallet; +}, __privateAdd(_m, _Wallet_static), _m); +const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; +function decodeBits(width, data) { + const maxValue2 = (1 << width) - 1; + const result = []; + let accum = 0, bits = 0, flood = 0; + for (let i = 0; i < data.length; i++) { + accum = accum << 6 | Base64.indexOf(data[i]); + bits += 6; + while (bits >= width) { + const value = accum >> bits - width; + accum &= (1 << bits - width) - 1; + bits -= width; + if (value === 0) { + flood += maxValue2; } else { - this.notifyChainChanged(toQuantity(networks2.find((network2) => network2.isDefaultChain).chainId)); + result.push(value + flood); + flood = 0; } + } + } + return result; +} +function decodeOwlA(data, accents) { + let words2 = decodeOwl(data).join(","); + accents.split(/,/g).forEach((accent) => { + const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); + assertArgument(match !== null, "internal error parsing accents", "accents", accents); + let posOffset = 0; + const positions = decodeBits(parseInt(match[3]), match[4]); + const charCode = parseInt(match[2]); + const regex = new RegExp(`([${match[1]}])`, "g"); + words2 = words2.replace(regex, (all, letter) => { + const rem = --positions[posOffset]; + if (rem === 0) { + letter = String.fromCharCode(letter.charCodeAt(0), charCode); + posOffset++; + } + return letter; }); - this.walletRequestHandler.on("chainChanged", (chainIdHex, origin) => { - this.notifyChainChanged(chainIdHex, origin); - }); - this.walletRequestHandler.on("walletContext", (walletContext) => { - if (!this.registered || !walletContext) return; - this.notifyWalletContext(walletContext); - }); - this.walletRequestHandler.on("close", (error) => { - if (!this.registered) return; - this.notifyClose(error); - }); - } - get registered() { - return this._registered; + }); + return words2.split(","); +} +class WordlistOwlA extends WordlistOwl { + /** + * Creates a new Wordlist for %%locale%% using the OWLA %%data%% + * and %%accent%% data and validated against the %%checksum%%. + */ + constructor(locale, data, accent, checksum2) { + super(locale, data, checksum2); + __privateAdd(this, _accent); + __privateSet(this, _accent, accent); } - register() { - throw new Error("abstract method"); + /** + * The OWLA-encoded accent data. + */ + get _accent() { + return __privateGet(this, _accent); } - unregister() { - throw new Error("abstract method"); + /** + * Decode all the words for the wordlist. + */ + _decodeWords() { + return decodeOwlA(this._data, this._accent); } - request(request) { - throw new Error("abstract method"); +} +_accent = new WeakMap(); +const wordlists = { + en: LangEn.wordlist() +}; +const ethers = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + AbiCoder, + AbstractProvider, + AbstractSigner, + AlchemyProvider, + AnkrProvider, + BaseContract, + BaseWallet, + Block, + BrowserProvider, + ChainstackProvider, + CloudflareProvider, + ConstructorFragment, + Contract, + ContractEventPayload, + ContractFactory, + ContractTransactionReceipt, + ContractTransactionResponse, + ContractUnknownEventPayload, + EnsPlugin, + EnsResolver, + ErrorDescription, + ErrorFragment, + EtherSymbol, + EtherscanPlugin, + EtherscanProvider, + EventFragment, + EventLog, + EventPayload, + FallbackFragment, + FallbackProvider, + FeeData, + FeeDataNetworkPlugin, + FetchCancelSignal, + FetchRequest, + FetchResponse, + FetchUrlFeeDataNetworkPlugin, + FixedNumber, + Fragment, + FunctionFragment, + GasCostPlugin, + HDNodeVoidWallet, + HDNodeWallet, + Indexed, + InfuraProvider, + InfuraWebSocketProvider, + Interface, + IpcSocketProvider, + JsonRpcApiProvider, + JsonRpcProvider: JsonRpcProvider$1, + JsonRpcSigner, + LangEn, + Log, + LogDescription, + MaxInt256, + MaxUint256, + MessagePrefix, + MinInt256, + Mnemonic, + MulticoinProviderPlugin, + N: N$1, + NamedFragment, + Network, + NetworkPlugin, + NonceManager, + ParamType, + PocketProvider, + QuickNodeProvider, + Result, + Signature, + SigningKey, + SocketBlockSubscriber, + SocketEventSubscriber, + SocketPendingSubscriber, + SocketProvider, + SocketSubscriber, + StructFragment, + Transaction, + TransactionDescription, + TransactionReceipt, + TransactionResponse, + Typed, + TypedDataEncoder, + UndecodedEventLog, + UnmanagedSubscriber, + Utf8ErrorFuncs, + VoidSigner, + Wallet: Wallet$1, + WebSocketProvider, + WeiPerEther, + Wordlist, + WordlistOwl, + WordlistOwlA, + ZeroAddress, + ZeroHash, + accessListify, + assert, + assertArgument, + assertArgumentCount, + assertNormalize, + assertPrivate, + checkResultErrors, + computeAddress, + computeHmac, + concat, + copyRequest, + dataLength, + dataSlice, + decodeBase58, + decodeBase64, + decodeBytes32String, + decodeRlp, + decryptCrowdsaleJson, + decryptKeystoreJson, + decryptKeystoreJsonSync, + defaultPath, + defineProperties: defineProperties$1, + dnsEncode, + encodeBase58, + encodeBase64, + encodeBytes32String, + encodeRlp, + encryptKeystoreJson, + encryptKeystoreJsonSync, + ensNormalize, + formatEther: formatEther$1, + formatUnits: formatUnits$1, + fromTwos, + getAccountPath, + getAddress, + getBigInt, + getBytes, + getBytesCopy, + getCreate2Address, + getCreateAddress, + getDefaultProvider, + getIcapAddress, + getIndexedAccountPath, + getNumber, + getUint, + hashMessage, + hexlify, + id: id$1, + isAddress, + isAddressable, + isBytesLike, + isCallException, + isCrowdsaleJson, + isError, + isHexString, + isKeystoreJson, + isValidName, + keccak256, + lock, + makeError, + mask, + namehash, + parseEther: parseEther$1, + parseUnits: parseUnits$2, + pbkdf2, + randomBytes, + recoverAddress, + resolveAddress, + resolveProperties: resolveProperties$1, + ripemd160, + scrypt, + scryptSync, + sha256: sha256$1, + sha512, + showThrottleMessage, + solidityPacked, + solidityPackedKeccak256, + solidityPackedSha256, + stripZerosLeft, + toBeArray, + toBeHex, + toBigInt, + toNumber, + toQuantity, + toTwos, + toUtf8Bytes, + toUtf8CodePoints, + toUtf8String, + uuidV4, + verifyMessage, + verifyTypedData, + version: version$5, + wordlists, + zeroPadBytes, + zeroPadValue +}, Symbol.toStringTag, { value: "Module" })); +var buffer = {}; +var base64Js = {}; +base64Js.byteLength = byteLength; +base64Js.toByteArray = toByteArray; +base64Js.fromByteArray = fromByteArray; +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; +var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +for (var i$2 = 0, len = code.length; i$2 < len; ++i$2) { + lookup[i$2] = code[i$2]; + revLookup[code.charCodeAt(i$2)] = i$2; +} +revLookup["-".charCodeAt(0)] = 62; +revLookup["_".charCodeAt(0)] = 63; +function getLens(b64) { + var len = b64.length; + if (len % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); } - sendMessage(message) { - throw new Error("abstract method"); + var validLen = b64.indexOf("="); + if (validLen === -1) validLen = len; + var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; +} +function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +} +function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +} +function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i; + for (i = 0; i < len; i += 4) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; } - notifyOpen(openInfo) { - const { - chainId, - sessionId, - session, - error - } = openInfo; - this.sendMessage({ - idx: -1, - type: EventType.OPEN, - data: { - chainId, - sessionId, - session, - error - }, - clientVersion: VERSION$1 - }); + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[curByte++] = tmp & 255; } - notifyClose(error) { - this.sendMessage({ - idx: -1, - type: EventType.CLOSE, - data: error ? { - error - } : null, - clientVersion: VERSION$1 - }); + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; } - notifyConnect(connectDetails) { - this.sendMessage({ - idx: -1, - type: EventType.CONNECT, - data: connectDetails, - clientVersion: VERSION$1 - }); + return arr; +} +function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; +} +function encodeChunk(uint8, start, end) { + var tmp; + var output2 = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255); + output2.push(tripletToBase64(tmp)); } - notifyDisconnect(error, origin) { - this.sendMessage({ - idx: -1, - type: EventType.DISCONNECT, - data: error ? { - error - } : null, - origin, - clientVersion: VERSION$1 - }); + return output2.join(""); +} +function fromByteArray(uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); } - notifyAccountsChanged(accounts, origin) { - this.sendMessage({ - idx: -1, - type: EventType.ACCOUNTS_CHANGED, - data: accounts, - origin, - clientVersion: VERSION$1 - }); + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push( + lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" + ); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push( + lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" + ); } - notifyChainChanged(chainIdHex, origin) { - this.sendMessage({ - idx: -1, - type: EventType.CHAIN_CHANGED, - data: chainIdHex, - origin, - clientVersion: VERSION$1 - }); + return parts.join(""); +} +var ieee754 = {}; +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +ieee754.read = function(buffer2, offset2, isLE2, mLen, nBytes) { + var e2, m2; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE2 ? nBytes - 1 : 0; + var d2 = isLE2 ? -1 : 1; + var s2 = buffer2[offset2 + i]; + i += d2; + e2 = s2 & (1 << -nBits) - 1; + s2 >>= -nBits; + nBits += eLen; + for (; nBits > 0; e2 = e2 * 256 + buffer2[offset2 + i], i += d2, nBits -= 8) { } - notifyNetworks(networks2) { - this.sendMessage({ - idx: -1, - type: EventType.NETWORKS, - data: networks2, - clientVersion: VERSION$1 - }); + m2 = e2 & (1 << -nBits) - 1; + e2 >>= -nBits; + nBits += mLen; + for (; nBits > 0; m2 = m2 * 256 + buffer2[offset2 + i], i += d2, nBits -= 8) { } - notifyWalletContext(walletContext) { - this.sendMessage({ - idx: -1, - type: EventType.WALLET_CONTEXT, - data: walletContext, - clientVersion: VERSION$1 - }); + if (e2 === 0) { + e2 = 1 - eBias; + } else if (e2 === eMax) { + return m2 ? NaN : (s2 ? -1 : 1) * Infinity; + } else { + m2 = m2 + Math.pow(2, mLen); + e2 = e2 - eBias; } - isValidInitAck(message) { - if (this._init === InitState.OK) { - logger.warn("isValidInitAck, already in init'd state, so inquiry is invalid."); - return false; - } - if (message.type !== EventType.INIT) { - logger.warn("isValidInitAck, invalid message type, expecting init"); - return false; + return (s2 ? -1 : 1) * m2 * Math.pow(2, e2 - mLen); +}; +ieee754.write = function(buffer2, value, offset2, isLE2, mLen, nBytes) { + var e2, m2, c2; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE2 ? 0 : nBytes - 1; + var d2 = isLE2 ? 1 : -1; + var s2 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m2 = isNaN(value) ? 1 : 0; + e2 = eMax; + } else { + e2 = Math.floor(Math.log(value) / Math.LN2); + if (value * (c2 = Math.pow(2, -e2)) < 1) { + e2--; + c2 *= 2; } - const { - sessionId, - nonce - } = message.data; - if (!sessionId || sessionId.length === 0 || !nonce || nonce.length === 0) { - logger.error("invalid init ack"); - return false; + if (e2 + eBias >= 1) { + value += rt / c2; + } else { + value += rt * Math.pow(2, 1 - eBias); } - if (sessionId !== this._sessionId || nonce !== this._initNonce) { - logger.error("invalid init ack match"); - return false; + if (value * c2 >= 2) { + e2++; + c2 /= 2; + } + if (e2 + eBias >= eMax) { + m2 = 0; + e2 = eMax; + } else if (e2 + eBias >= 1) { + m2 = (value * c2 - 1) * Math.pow(2, mLen); + e2 = e2 + eBias; + } else { + m2 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e2 = 0; } - return true; - } - init() { - return new Promise((resolve, reject) => { - if (this._init === InitState.OK) { - resolve(); - return; - } - if (this._init !== InitState.NIL || this._initCallback) { - reject("transport init is in progress"); - return; - } - const initTimeout = setTimeout(() => { - logger.warn("transport init timed out"); - if (this._initCallback) { - this._initCallback("transport init timed out"); - } - }, PROVIDER_OPEN_TIMEOUT / 2); - this._initCallback = (error) => { - this._initCallback = void 0; - clearTimeout(initTimeout); - if (error) { - reject(error); - } else { - this._init = InitState.OK; - resolve(); - } - }; - this._initNonce = `${performance.now()}`; - this.sendMessage({ - idx: -1, - type: EventType.INIT, - data: { - nonce: this._initNonce - }, - clientVersion: VERSION$1 - }); - this._init = InitState.SENT_NONCE; - }); - } -} -class ProxyMessageChannel { - constructor() { - this.app = void 0; - this.wallet = void 0; - const port1 = new ProxyMessageChannelPort(); - const port2 = new ProxyMessageChannelPort(); - port1.conn = port2; - port2.conn = port1; - this.app = port1; - this.wallet = port2; } -} -class ProxyMessageChannelPort { - constructor() { - this.conn = void 0; - this.events = new eventemitter2Exports.EventEmitter2(); - this.handleMessage = (message) => { - throw new Error("ProxyMessageChannelPort is not registered"); - }; - this.sendMessage = (message) => { - this.conn.handleMessage(message); - if (message.type === "open") { - this.events.emit("open", message); - } - if (message.type === "close") { - this.events.emit("close", message); - } - if (message.type === "connect") { - this.events.emit("connect", message); - } - if (message.type === "disconnect") { - this.events.emit("disconnect", message); - } - }; + for (; mLen >= 8; buffer2[offset2 + i] = m2 & 255, i += d2, m2 /= 256, mLen -= 8) { } - on(event, fn) { - this.events.on(event, fn); + e2 = e2 << mLen | m2; + eLen += mLen; + for (; eLen > 0; buffer2[offset2 + i] = e2 & 255, i += d2, e2 /= 256, eLen -= 8) { } - once(event, fn) { - this.events.once(event, fn); + buffer2[offset2 + i - d2] |= s2 * 128; +}; +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +(function(exports) { + const base64 = base64Js; + const ieee754$1 = ieee754; + const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports.Buffer = Buffer3; + exports.SlowBuffer = SlowBuffer2; + exports.INSPECT_MAX_BYTES = 50; + const K_MAX_LENGTH = 2147483647; + exports.kMaxLength = K_MAX_LENGTH; + const { Uint8Array: GlobalUint8Array, ArrayBuffer: GlobalArrayBuffer, SharedArrayBuffer: GlobalSharedArrayBuffer } = globalThis; + Buffer3.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer3.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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." + ); } -} -class ProxyMessageProvider extends BaseProviderTransport { - constructor(port) { - super(); - this.port = void 0; - this.register = () => { - this.port.handleMessage = (message) => { - this.handleMessage(message); - }; - this.on("open", (...args) => { - this.port.events.emit("open", ...args); - }); - this.on("close", (...args) => { - this.port.events.emit("close", ...args); - }); - this.on("connect", (...args) => { - this.port.events.emit("connect", ...args); - }); - this.on("disconnect", (...args) => { - this.port.events.emit("disconnect", ...args); - }); - this._registered = true; - }; - this.unregister = () => { - this._registered = false; - this.closeWallet(); - this.events.removeAllListeners(); - this.port.handleMessage = void 0; - }; - this.openWallet = (path, intent, networkId) => { - if (this.state === OpenState.CLOSED) { - this.state = OpenState.OPENING; - const sessionId = `${performance.now()}`; - this._sessionId = sessionId; - this.sendMessage({ - idx: -1, - type: EventType.OPEN, - data: { - path, - intent, - networkId, - sessionId - }, - clientVersion: VERSION$1 - }); + function typedArraySupport() { + try { + const arr = new GlobalUint8Array(1); + const proto = { foo: function() { + return 42; + } }; + Object.setPrototypeOf(proto, GlobalUint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e2) { + return false; + } + } + Object.defineProperty(Buffer3.prototype, "parent", { + enumerable: true, + get: function() { + if (!Buffer3.isBuffer(this)) return void 0; + return this.buffer; + } + }); + Object.defineProperty(Buffer3.prototype, "offset", { + enumerable: true, + get: function() { + if (!Buffer3.isBuffer(this)) return void 0; + return this.byteOffset; + } + }); + function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"'); + } + const buf = new GlobalUint8Array(length); + Object.setPrototypeOf(buf, Buffer3.prototype); + return buf; + } + function Buffer3(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ); } - }; - this.state = OpenState.CLOSED; - this.port = port; - if (!port) { - throw new Error("port argument cannot be empty"); + return allocUnsafe(arg); } - this._init = InitState.OK; + return from(arg, encodingOrOffset, length); } - closeWallet() { - this.sendMessage({ - idx: -1, - type: EventType.CLOSE, - data: null, - clientVersion: VERSION$1 - }); - this.close(); + Buffer3.poolSize = 8192; + function from(value, encodingOrOffset, length) { + if (typeof value === "string") { + return fromString(value, encodingOrOffset); + } + if (GlobalArrayBuffer.isView(value)) { + return fromArrayView(value); + } + if (value == null) { + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + if (isInstance(value, GlobalArrayBuffer) || value && isInstance(value.buffer, GlobalArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof GlobalSharedArrayBuffer !== "undefined" && (isInstance(value, GlobalSharedArrayBuffer) || value && isInstance(value.buffer, GlobalSharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof value === "number") { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ); + } + const valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer3.from(valueOf, encodingOrOffset, length); + } + const b2 = fromObject(value); + if (b2) return b2; + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { + return Buffer3.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); + } + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); } - sendMessage(message) { - if (!message.idx) { - throw new Error("message idx is empty"); + Buffer3.from = function(value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length); + }; + Object.setPrototypeOf(Buffer3.prototype, GlobalUint8Array.prototype); + Object.setPrototypeOf(Buffer3, GlobalUint8Array); + function assertSize2(size2) { + if (typeof size2 !== "number") { + throw new TypeError('"size" argument must be of type number'); + } else if (size2 < 0) { + throw new RangeError('The value "' + size2 + '" is invalid for option "size"'); } - this.port.sendMessage(message); } -} -class ProxyMessageHandler extends BaseWalletTransport { - constructor(walletRequestHandler, port) { - super(walletRequestHandler); - this.port = void 0; - this.port = port; - this._init = InitState.OK; + function alloc(size2, fill, encoding) { + assertSize2(size2); + if (size2 <= 0) { + return createBuffer(size2); + } + if (fill !== void 0) { + return typeof encoding === "string" ? createBuffer(size2).fill(fill, encoding) : createBuffer(size2).fill(fill); + } + return createBuffer(size2); } - register() { - this.port.handleMessage = (message) => { - this.handleMessage(message); - }; - this._registered = true; + Buffer3.alloc = function(size2, fill, encoding) { + return alloc(size2, fill, encoding); + }; + function allocUnsafe(size2) { + assertSize2(size2); + return createBuffer(size2 < 0 ? 0 : checked(size2) | 0); } - // note: we can't decide whether to restore the session within register(), because session info is - // received asyncronously via EventType.OPEN after register() is executed. - // And in the case of a redirect/reload, EventType.OPEN is not sent at all, - // because the wallet is already open. - // - // call this method from wallet redirect hander when a session restore is needed - async restoreSession() { - const cachedSession = await this.getCachedTransportSession(); - if (cachedSession) { - this.open(cachedSession); + Buffer3.allocUnsafe = function(size2) { + return allocUnsafe(size2); + }; + Buffer3.allocUnsafeSlow = function(size2) { + return allocUnsafe(size2); + }; + function fromString(string, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer3.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + const length = byteLength2(string, encoding) | 0; + let buf = createBuffer(length); + const actual = buf.write(string, encoding); + if (actual !== length) { + buf = buf.slice(0, actual); } + return buf; } - unregister() { - this.port.handleMessage = void 0; - this._registered = false; + function fromArrayLike(array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0; + const buf = createBuffer(length); + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf; } - sendMessage(message) { - this.port.sendMessage(message); + function fromArrayView(arrayView) { + if (isInstance(arrayView, GlobalUint8Array)) { + const copy2 = new GlobalUint8Array(arrayView); + return fromArrayBuffer(copy2.buffer, copy2.byteOffset, copy2.byteLength); + } + return fromArrayLike(arrayView); } -} -function overrideLogs(side) { - var _window$ue; - if ((_window$ue = window.ue) != null && _window$ue.sequencewallettransport && !window.logsOverriddenForUnreal) { - var _window$ue2; - const t2 = (_window$ue2 = window.ue) == null ? void 0 : _window$ue2.sequencewallettransport; - console.log = (...args) => { - t2.logfromjs(`${side}: ${stringify$1(args)}`); - }; - console.warn = (...args) => { - t2.warnfromjs(`${side}: ${stringify$1(args)}`); - }; - console.error = (...args) => { - t2.errorfromjs(`${side}: ${stringify$1(args)}`); - }; - window.logsOverriddenForUnreal = true; + function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + let buf; + if (byteOffset === void 0 && length === void 0) { + buf = new GlobalUint8Array(array); + } else if (length === void 0) { + buf = new GlobalUint8Array(array, byteOffset); + } else { + buf = new GlobalUint8Array(array, byteOffset, length); + } + Object.setPrototypeOf(buf, Buffer3.prototype); + return buf; } -} -function stringify$1(things) { - return things.map((a2) => typeof a2 === "object" ? a2 instanceof Error ? a2.message : JSON.stringify(a2) : String(a2)).join(" "); -} -let registeredUnrealMessageProvider; -class UnrealMessageProvider extends BaseProviderTransport { - constructor(walletAppURL) { - super(); - this.walletURL = void 0; - this.register = () => { - var _window$ue; - overrideLogs("dapp"); - if (registeredUnrealMessageProvider) { - registeredUnrealMessageProvider.unregister(); - registeredUnrealMessageProvider = this; - } - if ((_window$ue = window.ue) != null && _window$ue.sequencewallettransport) { - window.ue.sequencewallettransport.onmessagefromwallet = this.onUnrealCallback; - } - registeredUnrealMessageProvider = this; - this._registered = true; - console.log("registering transport!"); - }; - this.unregister = () => { - var _window$ue2; - this._registered = false; - this.closeWallet(); - if (registeredUnrealMessageProvider === this) { - registeredUnrealMessageProvider = void 0; - } - if (((_window$ue2 = window.ue) == null || (_window$ue2 = _window$ue2.sequencewallettransport) == null ? void 0 : _window$ue2.onmessagefromwallet) === this.onUnrealCallback) { - delete window.ue.sequencewallettransport.onmessagefromwallet; - } - this.events.removeAllListeners(); - }; - this.openWallet = (path, intent, networkId) => { - if (this.isOpened()) { - console.log("wallet already open!"); - return; - } - console.log("opening wallet!"); - const walletURL = new URL(this.walletURL.href); - const windowSessionParams = new WindowSessionParams(); - if (path) { - walletURL.pathname = path.toLowerCase(); - } - this._init = InitState.NIL; - this._sessionId = `${performance.now()}`; - windowSessionParams.set("sid", this._sessionId); - if (intent) { - windowSessionParams.set("intent", base64EncodeObject(intent)); - } - if (networkId) { - windowSessionParams.set("net", `${networkId}`); + function fromObject(obj) { + if (Buffer3.isBuffer(obj)) { + const len = checked(obj.length) | 0; + const buf = createBuffer(len); + if (buf.length === 0) { + return buf; } - walletURL.search = windowSessionParams.toString(); - console.log("opening wallet to", walletURL.href); - window.open(walletURL.href); - }; - this.onUnrealCallback = (message) => { - if (!message) { - throw new Error("ProviderMessage object is empty"); + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== void 0) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); } - this.handleMessage(message); - }; - this.walletURL = new URL(walletAppURL); - } - closeWallet() { - this.close(); + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } } - // all lowercase is an annoying limitation of Unreal CEF BindUObject - sendMessage(message) { - var _window$ue3; - const postedMessage = typeof message !== "string" ? JSON.stringify(message, bigintReplacer) : message; - console.log("Sending message to wallet:", postedMessage); - (_window$ue3 = window.ue) == null || (_window$ue3 = _window$ue3.sequencewallettransport) == null || _window$ue3.sendmessagetowallet(postedMessage); + function checked(length) { + if (length >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length | 0; } -} -class UnrealMessageHandler extends BaseWalletTransport { - constructor(walletRequestHandler) { - super(walletRequestHandler); - this.onMessageFromUnreal = (request) => { - logger.debug("RECEIVED MESSAGE", request); - this.handleMessage(request); - }; - this.getUnrealTransportSession = (windowParams) => { - const params = new WindowSessionParams(windowParams); - return { - sessionId: params.get("sid"), - networkId: params.get("net"), - intent: base64DecodeObject(params.get("intent")) - }; - }; - this._init = InitState.NIL; + function SlowBuffer2(length) { + if (+length != length) { + length = 0; + } + return Buffer3.alloc(+length); } - async register(windowHref) { - var _window$ue; - if (((_window$ue = window.ue) == null ? void 0 : _window$ue.sequencewallettransport) === void 0) { - return; + Buffer3.isBuffer = function isBuffer(b2) { + return b2 != null && b2._isBuffer === true && b2 !== Buffer3.prototype; + }; + Buffer3.compare = function compare(a2, b2) { + if (isInstance(a2, GlobalUint8Array)) a2 = Buffer3.from(a2, a2.offset, a2.byteLength); + if (isInstance(b2, GlobalUint8Array)) b2 = Buffer3.from(b2, b2.offset, b2.byteLength); + if (!Buffer3.isBuffer(a2) || !Buffer3.isBuffer(b2)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ); + } + if (a2 === b2) return 0; + let x2 = a2.length; + let y2 = b2.length; + for (let i = 0, len = Math.min(x2, y2); i < len; ++i) { + if (a2[i] !== b2[i]) { + x2 = a2[i]; + y2 = b2[i]; + break; + } + } + if (x2 < y2) return -1; + if (y2 < x2) return 1; + return 0; + }; + Buffer3.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; + Buffer3.concat = function concat2(list2, length) { + if (!Array.isArray(list2)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list2.length === 0) { + return Buffer3.alloc(0); + } + let i; + if (length === void 0) { + length = 0; + for (i = 0; i < list2.length; ++i) { + length += list2[i].length; + } + } + const buffer2 = Buffer3.allocUnsafe(length); + let pos = 0; + for (i = 0; i < list2.length; ++i) { + let buf = list2[i]; + if (isInstance(buf, GlobalUint8Array)) { + if (pos + buf.length > buffer2.length) { + if (!Buffer3.isBuffer(buf)) buf = Buffer3.from(buf); + buf.copy(buffer2, pos); + } else { + GlobalUint8Array.prototype.set.call( + buffer2, + buf, + pos + ); + } + } else if (!Buffer3.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer2, pos); + } + pos += buf.length; } - overrideLogs("wallet"); - const { - search: rawParams - } = new URL(windowHref || window.location.href); - let session = this.getUnrealTransportSession(rawParams); - const isNewWindowSession = !!session.sessionId; - if (!isNewWindowSession) { - session = await this.getCachedTransportSession(); + return buffer2; + }; + function byteLength2(string, encoding) { + if (Buffer3.isBuffer(string)) { + return string.length; } - if (!session) { - logger.error("unreal session is undefined"); - return; + if (GlobalArrayBuffer.isView(string) || isInstance(string, GlobalArrayBuffer)) { + return string.byteLength; } - window.ue.sequencewallettransport.onmessagefromsequencejs = this.onMessageFromUnreal; - this._registered = true; - this.open(session).then((opened) => { - if (!opened) { - var _session; - const err = `failed to open to network ${(_session = session) == null ? void 0 : _session.networkId}`; - logger.error(err); - this.notifyClose({ - message: err - }); - window.close(); + if (typeof string !== "string") { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string + ); + } + const len = string.length; + const mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) return 0; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + return utf8ToBytes2(string).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes2(string).length; + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; } - }).catch((e2) => { - var _session2; - const err = `failed to open to network ${(_session2 = session) == null ? void 0 : _session2.networkId}, due to: ${e2}`; - logger.error(err); - this.notifyClose({ - message: err - }); - window.close(); - }); - } - unregister() { - var _window$ue2; - if (((_window$ue2 = window.ue) == null || (_window$ue2 = _window$ue2.sequencewallettransport) == null ? void 0 : _window$ue2.onmessagefromsequencejs) === this.onMessageFromUnreal) { - delete window.ue.sequencewallettransport.onmessagefromsequencejs; } - this._registered = false; } - // sendMessage sends message to the dapp window - sendMessage(message) { - var _window$ue3; - if (message.type !== EventType.INIT && this._init !== InitState.OK) { - logger.error("impossible state, should not be calling postMessage until inited"); - return; + Buffer3.byteLength = byteLength2; + function slowToString(encoding, start, end) { + let loweredCase = false; + if (start === void 0 || start < 0) { + start = 0; } - const payload = JSON.stringify(message, bigintReplacer); - (_window$ue3 = window.ue) == null || (_window$ue3 = _window$ue3.sequencewallettransport) == null || _window$ue3.sendmessagetosequencejs(payload); - } -} -const CHANNEL_ID = "sequence-extension-message-handler"; -class ExtensionMessageHandler extends BaseWalletTransport { - constructor(walletRequestHandler, runtime) { - super(walletRequestHandler); - this.runtime = runtime; - this.port = void 0; - this._init = InitState.OK; - } - register() { - this._registered = true; - this.port = this.runtime.connect({ - name: CHANNEL_ID - }); - } - sendMessage(message) { - logger.info("[ExtensionMessageHandler send]", message); - this.port.postMessage(message); - } -} -class ExtensionMessageProvider extends BaseProviderTransport { - constructor(runtime) { - super(); - this.register = () => { - this._registered = true; - }; - runtime.onConnect.addListener((port) => { - if (port.name === CHANNEL_ID) { - this._init = InitState.OK; - port.onMessage.addListener((message) => { - this.handleMessage(message); - }); + if (start > this.length) { + return ""; + } + if (end === void 0 || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding) encoding = "utf8"; + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + case "ascii": + return asciiSlice(this, start, end); + case "latin1": + case "binary": + return latin1Slice(this, start, end); + case "base64": + return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; } - }); - } - sendMessage(message) { - } - unregister() { + } } - openWallet(path, intent, networkId) { + Buffer3.prototype._isBuffer = true; + function swap(b2, n2, m2) { + const i = b2[n2]; + b2[n2] = b2[m2]; + b2[m2] = i; } - closeWallet() { + Buffer3.prototype.swap16 = function swap16() { + const len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; + }; + Buffer3.prototype.swap32 = function swap32() { + const len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; + }; + Buffer3.prototype.swap64 = function swap64() { + const len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; + }; + Buffer3.prototype.toString = function toString2() { + const length = this.length; + if (length === 0) return ""; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + Buffer3.prototype.toLocaleString = Buffer3.prototype.toString; + Buffer3.prototype.equals = function equals(b2) { + if (!Buffer3.isBuffer(b2)) throw new TypeError("Argument must be a Buffer"); + if (this === b2) return true; + return Buffer3.compare(this, b2) === 0; + }; + Buffer3.prototype.inspect = function inspect() { + let str = ""; + const max2 = exports.INSPECT_MAX_BYTES; + str = this.toString("hex", 0, max2).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max2) str += " ... "; + return ""; + }; + if (customInspectSymbol) { + Buffer3.prototype[customInspectSymbol] = Buffer3.prototype.inspect; } -} -class BaseInjectedTransport extends eventemitter2Exports.EventEmitter2 { - constructor(stream) { - var _this; - super(); - _this = this; - this.stream = stream; - this.responseCallbacks = /* @__PURE__ */ new Map(); - this._messageIdx = 0; - this.nextMessageIdx = () => ++this._messageIdx; - this.handleMessage = (message) => { - if (!message.type || !message.data) { - return; - } - logger.info("[received message]", message); - const requestIdx = message.idx; - const responseCallback = this.responseCallbacks.get(requestIdx); - if (requestIdx) { - this.responseCallbacks.delete(requestIdx); + Buffer3.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (isInstance(target, GlobalUint8Array)) { + target = Buffer3.from(target, target.offset, target.byteLength); + } + if (!Buffer3.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target + ); + } + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = target ? target.length : 0; + } + if (thisStart === void 0) { + thisStart = 0; + } + if (thisEnd === void 0) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + let x2 = thisEnd - thisStart; + let y2 = end - start; + const len = Math.min(x2, y2); + const thisCopy = this.slice(thisStart, thisEnd); + const targetCopy = target.slice(start, end); + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x2 = thisCopy[i]; + y2 = targetCopy[i]; + break; } - switch (message.type) { - case EventType.MESSAGE: - if (responseCallback) { - this.emit(EventType.MESSAGE, message); - responseCallback(message.data.error, message); - } else { - throw new Error("impossible state"); - } - break; - case EventType.DISCONNECT: - case EventType.ACCOUNTS_CHANGED: - case EventType.CHAIN_CHANGED: - this.emit(message.type, message.data); - break; - default: - console.error("unknown message type", message); - break; + } + if (x2 < y2) return -1; + if (y2 < x2) return 1; + return 0; + }; + function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) { + if (buffer2.length === 0) return -1; + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer2.length - 1; + } + if (byteOffset < 0) byteOffset = buffer2.length + byteOffset; + if (byteOffset >= buffer2.length) { + if (dir) return -1; + else byteOffset = buffer2.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1; + } + if (typeof val === "string") { + val = Buffer3.from(val, encoding); + } + if (Buffer3.isBuffer(val)) { + if (val.length === 0) { + return -1; } - }; - this.sendMessageRequest = async function(message) { - return new Promise((resolve, reject) => { - if (!message.idx || message.idx <= 0) { - reject(new Error("message idx not set")); - } - const responseCallback = (error, response) => { - if (error) { - reject(error); - } else if (response) { - resolve(response); - } else { - throw new Error("no valid response to return"); - } - }; - const { - idx - } = message; - if (!_this.responseCallbacks.get(idx)) { - _this.responseCallbacks.set(idx, responseCallback); + return arrayIndexOf(buffer2, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof GlobalUint8Array.prototype.indexOf === "function") { + if (dir) { + return GlobalUint8Array.prototype.indexOf.call(buffer2, val, byteOffset); } else { - reject(new Error("duplicate message idx, should never happen")); + return GlobalUint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset); } - _this.sendMessage(message); - }); - }; - this.stream.on("data", this.handleMessage); - } - sendMessage(message) { - if (!this.stream.writable) { - console.error("window post message stream is not writable"); + } + return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir); } - this.stream.write(message); + throw new TypeError("val must be string, number or Buffer"); } -} -let registeredWindowMessageProvider; -class WindowMessageProvider extends BaseProviderTransport { - constructor(walletAppURL) { - super(); - this.walletURL = void 0; - this.walletWindow = void 0; - this.register = () => { - if (registeredWindowMessageProvider) { - registeredWindowMessageProvider.unregister(); - registeredWindowMessageProvider = this; - } - window.addEventListener("message", this.onWindowEvent); - registeredWindowMessageProvider = this; - this.on("open", () => { - const popup = this.walletWindow; - const interval = setInterval(() => { - if (popup && popup.closed) { - clearInterval(interval); - this.close(); - } - }, 500); - }); - this.on("close", () => { - if (this.walletWindow) { - this.walletWindow.close(); - this.walletWindow = null; + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + let indexSize = 1; + let arrLength = arr.length; + let valLength = val.length; + if (encoding !== void 0) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; } - }); - this._registered = true; - }; - this.unregister = () => { - this._registered = false; - this.closeWallet(); - if (registeredWindowMessageProvider === this) { - registeredWindowMessageProvider = void 0; + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; } - window.removeEventListener("message", this.onWindowEvent); - this.events.removeAllListeners(); - }; - this.openWallet = (path, intent, networkId) => { - if (this.walletWindow && this.isOpened()) { - this.walletWindow.focus(); - return; + } + function read(buf, i2) { + if (indexSize === 1) { + return buf[i2]; + } else { + return buf.readUInt16BE(i2 * indexSize); } - const walletURL = new URL(this.walletURL.href); - const windowSessionParams = new WindowSessionParams(); - if (path && path !== "") { - walletURL.pathname = path.toLowerCase(); + } + let i; + if (dir) { + let foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } } - this._init = InitState.NIL; - this._sessionId = `${performance.now()}`; - windowSessionParams.set("sid", this._sessionId); - if (intent) { - if (intent.type === "connect") { - if (!intent.options) intent.options = { - app: window.location.origin - }; - if (!isBrowserExtension() && !isUnityPlugin() && intent.options) { - intent.options.origin = window.location.origin; + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + let found = true; + for (let j2 = 0; j2 < valLength; j2++) { + if (read(arr, i + j2) !== read(val, j2)) { + found = false; + break; } } - windowSessionParams.set("intent", base64EncodeObject(intent)); - } - if (networkId) { - windowSessionParams.set("net", `${networkId}`); - } - let windowSize; - let windowPos; - if (isBrowserExtension()) { - windowSize = [450, 750]; - windowPos = [Math.abs(window.screen.width / 2 - windowSize[0] / 2), Math.abs(window.screen.height / 2 - windowSize[1] / 2)]; - } else { - windowSize = [450, 750]; - windowPos = [Math.abs(window.screenX + window.innerWidth / 2 - windowSize[0] / 2), Math.abs(window.screenY + window.innerHeight / 2 - windowSize[1] / 2)]; - } - const windowFeatures = `toolbar=0,location=0,menubar=0,scrollbars=yes,status=yes,width=${windowSize[0]},height=${windowSize[1]},left=${windowPos[0]},top=${windowPos[1]}`; - walletURL.search = windowSessionParams.toString(); - this.walletWindow = window.open(walletURL.href, "sequence.app", windowFeatures); - }; - this.onWindowEvent = (event) => { - if (event.origin !== this.walletURL.origin) { - return; - } - let message; - try { - message = JSON.parse(event.data, bigintReviver); - } catch (err) { - return; + if (found) return i; } - if (!message) { - throw new Error("ProviderMessage object is empty"); + } + return -1; + } + Buffer3.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + Buffer3.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + function hexWrite(buf, string, offset2, length) { + offset2 = Number(offset2) || 0; + const remaining = buf.length - offset2; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; } - this.handleMessage(message); - }; - this.walletURL = new URL(walletAppURL); + } + const strLen = string.length; + if (length > strLen / 2) { + length = strLen / 2; + } + let i; + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i; + buf[offset2 + i] = parsed; + } + return i; } - closeWallet() { - var _this$walletWindow; - this.close(); - (_this$walletWindow = this.walletWindow) == null || _this$walletWindow.close(); + function utf8Write(buf, string, offset2, length) { + return blitBuffer(utf8ToBytes2(string, buf.length - offset2), buf, offset2, length); } - sendMessage(message) { - if (!this.walletWindow) { - logger.warn("WindowMessageProvider: sendMessage failed as walletWindow is unavailable"); - return; - } - const postedMessage = typeof message !== "string" ? JSON.stringify(message, bigintReplacer) : message; - this.walletWindow.postMessage(postedMessage, this.walletURL.origin); + function asciiWrite(buf, string, offset2, length) { + return blitBuffer(asciiToBytes(string), buf, offset2, length); } -} -class WindowMessageHandler extends BaseWalletTransport { - constructor(walletRequestHandler) { - var _this; - super(walletRequestHandler); - _this = this; - this.parentWindow = void 0; - this._isPopup = false; - this.onWindowEvent = async function(event) { - if (!event.origin || event.origin === "") { - return; - } - if (_this.appOrigin && event.origin !== _this.appOrigin) { - return; + function base64Write(buf, string, offset2, length) { + return blitBuffer(base64ToBytes(string), buf, offset2, length); + } + function ucs2Write(buf, string, offset2, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset2), buf, offset2, length); + } + Buffer3.prototype.write = function write(string, offset2, length, encoding) { + if (offset2 === void 0) { + encoding = "utf8"; + length = this.length; + offset2 = 0; + } else if (length === void 0 && typeof offset2 === "string") { + encoding = offset2; + length = this.length; + offset2 = 0; + } else if (isFinite(offset2)) { + offset2 = offset2 >>> 0; + if (isFinite(length)) { + length = length >>> 0; + if (encoding === void 0) encoding = "utf8"; + } else { + encoding = length; + length = void 0; } - let request; - try { - request = JSON.parse(event.data, bigintReviver); - } catch (err) { - return; + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } + const remaining = this.length - offset2; + if (length === void 0 || length > remaining) length = remaining; + if (string.length > 0 && (length < 0 || offset2 < 0) || offset2 > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding) encoding = "utf8"; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "hex": + return hexWrite(this, string, offset2, length); + case "utf8": + case "utf-8": + return utf8Write(this, string, offset2, length); + case "ascii": + case "latin1": + case "binary": + return asciiWrite(this, string, offset2, length); + case "base64": + return base64Write(this, string, offset2, length); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string, offset2, length); + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; } - logger.debug("RECEIVED MESSAGE", request); - if (_this._init !== InitState.OK && _this.isValidInitAck(request)) { - _this.appOrigin = event.origin; + } + }; + Buffer3.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf); + } else { + return base64.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + const res = []; + let i = start; + while (i < end) { + const firstByte = buf[i]; + let codePoint = null; + let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } } - if (_this._init === InitState.OK && (!_this.appOrigin || _this.appOrigin.length < 8)) { - logger.error("impossible state, init.OK and appOrigin required"); - return; + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; } - _this.handleMessage(request); - }; - this.getWindowTransportSession = (windowParams) => { - const params = new WindowSessionParams(windowParams); - return { - sessionId: params.get("sid"), - networkId: params.get("net"), - intent: base64DecodeObject(params.get("intent")) - }; - }; - this._init = InitState.NIL; + res.push(codePoint); + i += bytesPerSequence; + } + return decodeCodePointsArray(res); } - async register(windowHref) { - const isPopup = parent.window.opener !== null; - this._isPopup = isPopup; - if (isPopup !== true) { - return; + const MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + const len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); } - const { - search: rawParams - } = new URL(windowHref || window.location.href); - let session = this.getWindowTransportSession(rawParams); - const isNewWindowSession = !!session.sessionId; - if (!isNewWindowSession) { - session = await this.getCachedTransportSession(); + let res = ""; + let i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); } - if (!session) { - logger.error("window session is undefined"); - return; + return res; + } + function asciiSlice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 127); } - this.parentWindow = parent.window.opener; - window.addEventListener("message", this.onWindowEvent, false); - this._registered = true; - this.open(session).then((opened) => { - if (!opened) { - var _session; - const err = `failed to open to network ${(_session = session) == null ? void 0 : _session.networkId}`; - logger.error(err); - this.notifyClose({ - message: err - }); - window.close(); - } - }).catch((e2) => { - var _session2; - const err = `failed to open to network ${(_session2 = session) == null ? void 0 : _session2.networkId}, due to: ${e2}`; - logger.error(err); - this.notifyClose({ - message: err - }); - window.close(); - }); + return ret; } - unregister() { - window.removeEventListener("message", this.onWindowEvent); - this._registered = false; + function latin1Slice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; } - // postMessage sends message to the dapp window - sendMessage(message) { - const payload = JSON.stringify(message, bigintReplacer); - if (message.type === EventType.INIT) { - this.postMessage(payload, true); - } else { - this.postMessage(payload); + function hexSlice(buf, start, end) { + const len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + let out = ""; + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; } + return out; } - get isPopup() { - return this._isPopup; + function utf16leSlice(buf, start, end) { + const bytes2 = buf.slice(start, end); + let res = ""; + for (let i = 0; i < bytes2.length - 1; i += 2) { + res += String.fromCharCode(bytes2[i] + bytes2[i + 1] * 256); + } + return res; + } + Buffer3.prototype.slice = function slice2(start, end) { + const len = this.length; + start = ~~start; + end = end === void 0 ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + if (end < start) end = start; + const newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer3.prototype); + return newBuf; + }; + function checkOffset(offset2, ext, length) { + if (offset2 % 1 !== 0 || offset2 < 0) throw new RangeError("offset is not uint"); + if (offset2 + ext > length) throw new RangeError("Trying to access beyond buffer length"); + } + Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset2, byteLength3, noAssert) { + offset2 = offset2 >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) checkOffset(offset2, byteLength3, this.length); + let val = this[offset2]; + let mul = 1; + let i = 0; + while (++i < byteLength3 && (mul *= 256)) { + val += this[offset2 + i] * mul; + } + return val; + }; + Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset2, byteLength3, noAssert) { + offset2 = offset2 >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) { + checkOffset(offset2, byteLength3, this.length); + } + let val = this[offset2 + --byteLength3]; + let mul = 1; + while (byteLength3 > 0 && (mul *= 256)) { + val += this[offset2 + --byteLength3] * mul; + } + return val; + }; + Buffer3.prototype.readUint8 = Buffer3.prototype.readUInt8 = function readUInt8(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 1, this.length); + return this[offset2]; + }; + Buffer3.prototype.readUint16LE = Buffer3.prototype.readUInt16LE = function readUInt16LE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 2, this.length); + return this[offset2] | this[offset2 + 1] << 8; + }; + Buffer3.prototype.readUint16BE = Buffer3.prototype.readUInt16BE = function readUInt16BE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 2, this.length); + return this[offset2] << 8 | this[offset2 + 1]; + }; + Buffer3.prototype.readUint32LE = Buffer3.prototype.readUInt32LE = function readUInt32LE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return (this[offset2] | this[offset2 + 1] << 8 | this[offset2 + 2] << 16) + this[offset2 + 3] * 16777216; + }; + Buffer3.prototype.readUint32BE = Buffer3.prototype.readUInt32BE = function readUInt32BE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return this[offset2] * 16777216 + (this[offset2 + 1] << 16 | this[offset2 + 2] << 8 | this[offset2 + 3]); + }; + Buffer3.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset2) { + offset2 = offset2 >>> 0; + validateNumber(offset2, "offset"); + const first = this[offset2]; + const last = this[offset2 + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset2, this.length - 8); + } + const lo = first + this[++offset2] * 2 ** 8 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 24; + const hi2 = this[++offset2] + this[++offset2] * 2 ** 8 + this[++offset2] * 2 ** 16 + last * 2 ** 24; + return BigInt(lo) + (BigInt(hi2) << BigInt(32)); + }); + Buffer3.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset2) { + offset2 = offset2 >>> 0; + validateNumber(offset2, "offset"); + const first = this[offset2]; + const last = this[offset2 + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset2, this.length - 8); + } + const hi2 = first * 2 ** 24 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + this[++offset2]; + const lo = this[++offset2] * 2 ** 24 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + last; + return (BigInt(hi2) << BigInt(32)) + BigInt(lo); + }); + Buffer3.prototype.readIntLE = function readIntLE(offset2, byteLength3, noAssert) { + offset2 = offset2 >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) checkOffset(offset2, byteLength3, this.length); + let val = this[offset2]; + let mul = 1; + let i = 0; + while (++i < byteLength3 && (mul *= 256)) { + val += this[offset2 + i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength3); + return val; + }; + Buffer3.prototype.readIntBE = function readIntBE(offset2, byteLength3, noAssert) { + offset2 = offset2 >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) checkOffset(offset2, byteLength3, this.length); + let i = byteLength3; + let mul = 1; + let val = this[offset2 + --i]; + while (i > 0 && (mul *= 256)) { + val += this[offset2 + --i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength3); + return val; + }; + Buffer3.prototype.readInt8 = function readInt8(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 1, this.length); + if (!(this[offset2] & 128)) return this[offset2]; + return (255 - this[offset2] + 1) * -1; + }; + Buffer3.prototype.readInt16LE = function readInt16LE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 2, this.length); + const val = this[offset2] | this[offset2 + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer3.prototype.readInt16BE = function readInt16BE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 2, this.length); + const val = this[offset2 + 1] | this[offset2] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer3.prototype.readInt32LE = function readInt32LE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return this[offset2] | this[offset2 + 1] << 8 | this[offset2 + 2] << 16 | this[offset2 + 3] << 24; + }; + Buffer3.prototype.readInt32BE = function readInt32BE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return this[offset2] << 24 | this[offset2 + 1] << 16 | this[offset2 + 2] << 8 | this[offset2 + 3]; + }; + Buffer3.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset2) { + offset2 = offset2 >>> 0; + validateNumber(offset2, "offset"); + const first = this[offset2]; + const last = this[offset2 + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset2, this.length - 8); + } + const val = this[offset2 + 4] + this[offset2 + 5] * 2 ** 8 + this[offset2 + 6] * 2 ** 16 + (last << 24); + return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset2] * 2 ** 8 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 24); + }); + Buffer3.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset2) { + offset2 = offset2 >>> 0; + validateNumber(offset2, "offset"); + const first = this[offset2]; + const last = this[offset2 + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset2, this.length - 8); + } + const val = (first << 24) + // Overflow + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + this[++offset2]; + return (BigInt(val) << BigInt(32)) + BigInt(this[++offset2] * 2 ** 24 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + last); + }); + Buffer3.prototype.readFloatLE = function readFloatLE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return ieee754$1.read(this, offset2, true, 23, 4); + }; + Buffer3.prototype.readFloatBE = function readFloatBE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return ieee754$1.read(this, offset2, false, 23, 4); + }; + Buffer3.prototype.readDoubleLE = function readDoubleLE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 8, this.length); + return ieee754$1.read(this, offset2, true, 52, 8); + }; + Buffer3.prototype.readDoubleBE = function readDoubleBE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 8, this.length); + return ieee754$1.read(this, offset2, false, 52, 8); + }; + function checkInt(buf, value, offset2, ext, max2, min2) { + if (!Buffer3.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max2 || value < min2) throw new RangeError('"value" argument is out of bounds'); + if (offset2 + ext > buf.length) throw new RangeError("Index out of range"); } - postMessage(message, init2 = false) { - if (init2 !== true && this._init !== InitState.OK) { - logger.error("impossible state, should not be calling postMessage until inited"); - return; + Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value, offset2, byteLength3, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength3) - 1; + checkInt(this, value, offset2, byteLength3, maxBytes, 0); } - if (init2) { - this.parentWindow.postMessage(message, "*"); - } else { - if (this.appOrigin && this.appOrigin.length > 4) { - this.parentWindow.postMessage(message, this.appOrigin); - } else { - logger.error("unable to postMessage as parentOrigin is invalid"); - } + let mul = 1; + let i = 0; + this[offset2] = value & 255; + while (++i < byteLength3 && (mul *= 256)) { + this[offset2 + i] = value / mul & 255; + } + return offset2 + byteLength3; + }; + Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value, offset2, byteLength3, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength3) - 1; + checkInt(this, value, offset2, byteLength3, maxBytes, 0); + } + let i = byteLength3 - 1; + let mul = 1; + this[offset2 + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + this[offset2 + i] = value / mul & 255; } + return offset2 + byteLength3; + }; + Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = function writeUInt8(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 1, 255, 0); + this[offset2] = value & 255; + return offset2 + 1; + }; + Buffer3.prototype.writeUint16LE = Buffer3.prototype.writeUInt16LE = function writeUInt16LE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 2, 65535, 0); + this[offset2] = value & 255; + this[offset2 + 1] = value >>> 8; + return offset2 + 2; + }; + Buffer3.prototype.writeUint16BE = Buffer3.prototype.writeUInt16BE = function writeUInt16BE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 2, 65535, 0); + this[offset2] = value >>> 8; + this[offset2 + 1] = value & 255; + return offset2 + 2; + }; + Buffer3.prototype.writeUint32LE = Buffer3.prototype.writeUInt32LE = function writeUInt32LE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 4, 4294967295, 0); + this[offset2 + 3] = value >>> 24; + this[offset2 + 2] = value >>> 16; + this[offset2 + 1] = value >>> 8; + this[offset2] = value & 255; + return offset2 + 4; + }; + Buffer3.prototype.writeUint32BE = Buffer3.prototype.writeUInt32BE = function writeUInt32BE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 4, 4294967295, 0); + this[offset2] = value >>> 24; + this[offset2 + 1] = value >>> 16; + this[offset2 + 2] = value >>> 8; + this[offset2 + 3] = value & 255; + return offset2 + 4; + }; + function wrtBigUInt64LE(buf, value, offset2, min2, max2) { + checkIntBI(value, min2, max2, buf, offset2, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset2++] = lo; + lo = lo >> 8; + buf[offset2++] = lo; + lo = lo >> 8; + buf[offset2++] = lo; + lo = lo >> 8; + buf[offset2++] = lo; + let hi2 = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset2++] = hi2; + hi2 = hi2 >> 8; + buf[offset2++] = hi2; + hi2 = hi2 >> 8; + buf[offset2++] = hi2; + hi2 = hi2 >> 8; + buf[offset2++] = hi2; + return offset2; } -} -function isMuxTransportTemplate(obj) { - return obj && typeof obj === "object" && (obj.windowTransport && typeof obj.windowTransport === "object" || obj.proxyTransport && typeof obj.proxyTransport === "object" || obj.extensionTransport && typeof obj.extensionTransport === "object" || obj.unrealTransport && typeof obj.unrealTransport === "object") && // One of the transports must be enabled - (obj.windowTransport && obj.windowTransport.enabled || obj.proxyTransport && obj.proxyTransport.enabled || obj.extensionTransport && obj.extensionTransport.enabled || obj.unrealTransport && obj.unrealTransport.enabled); -} -class MuxMessageProvider { - constructor(...messageProviders) { - var _this = this; - this.messageProviders = void 0; - this.provider = void 0; - this.register = () => { - if (this.messageProviders.length === 1) { - this.provider = this.messageProviders[0]; - this.provider.register(); - return; - } - this.messageProviders.forEach((m2) => { - m2.register(); - m2.once("open", () => { - if (!this.provider) { - this.provider = m2; - this.messageProviders.forEach((m22) => { - if (this.provider !== m22) { - m22.unregister(); - } - }); - } - }); - }); - }; - this.unregister = () => { - this.messageProviders.forEach((m2) => m2.unregister()); - this.provider = void 0; - }; - this.openWallet = (path, intent, networkId) => { - if (this.provider) { - this.provider.openWallet(path, intent, networkId); - return; - } - this.messageProviders.forEach((m2) => m2.openWallet(path, intent, networkId)); - }; - this.sendMessageRequest = async function(message) { - if (_this.provider) { - return _this.provider.sendMessageRequest(message); - } - throw new Error("impossible state, wallet must be opened first"); - }; - this.waitUntilOpened = async function() { - if (_this.provider) { - return _this.provider.waitUntilOpened(); - } - return Promise.race(_this.messageProviders.map((p2) => p2.waitUntilOpened())); - }; - this.waitUntilConnected = async function() { - if (_this.provider) { - return _this.provider.waitUntilConnected(); - } - throw new Error("impossible state, wallet must be opened first"); - }; - this.messageProviders = messageProviders; - this.provider = void 0; + function wrtBigUInt64BE(buf, value, offset2, min2, max2) { + checkIntBI(value, min2, max2, buf, offset2, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset2 + 7] = lo; + lo = lo >> 8; + buf[offset2 + 6] = lo; + lo = lo >> 8; + buf[offset2 + 5] = lo; + lo = lo >> 8; + buf[offset2 + 4] = lo; + let hi2 = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset2 + 3] = hi2; + hi2 = hi2 >> 8; + buf[offset2 + 2] = hi2; + hi2 = hi2 >> 8; + buf[offset2 + 1] = hi2; + hi2 = hi2 >> 8; + buf[offset2] = hi2; + return offset2 + 8; } - static new(template) { - var _template$windowTrans, _template$proxyTransp, _template$extensionTr, _template$unrealTrans; - const muxMessageProvider = new MuxMessageProvider(); - if ((_template$windowTrans = template.windowTransport) != null && _template$windowTrans.enabled && typeof window === "object" && template.walletAppURL) { - const windowMessageProvider = new WindowMessageProvider(template.walletAppURL); - muxMessageProvider.add(windowMessageProvider); - } - if ((_template$proxyTransp = template.proxyTransport) != null && _template$proxyTransp.enabled) { - const proxyMessageProvider = new ProxyMessageProvider(template.proxyTransport.appPort); - muxMessageProvider.add(proxyMessageProvider); + Buffer3.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset2 = 0) { + return wrtBigUInt64LE(this, value, offset2, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer3.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset2 = 0) { + return wrtBigUInt64BE(this, value, offset2, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer3.prototype.writeIntLE = function writeIntLE(value, offset2, byteLength3, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength3 - 1); + checkInt(this, value, offset2, byteLength3, limit - 1, -limit); } - if ((_template$extensionTr = template.extensionTransport) != null && _template$extensionTr.enabled) { - const extensionMessageProvider = new ExtensionMessageProvider(template.extensionTransport.runtime); - muxMessageProvider.add(extensionMessageProvider); + let i = 0; + let mul = 1; + let sub = 0; + this[offset2] = value & 255; + while (++i < byteLength3 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset2 + i - 1] !== 0) { + sub = 1; + } + this[offset2 + i] = (value / mul >> 0) - sub & 255; } - if ((_template$unrealTrans = template.unrealTransport) != null && _template$unrealTrans.enabled && template.windowTransport && template.walletAppURL) { - const unrealMessageProvider = new UnrealMessageProvider(template.walletAppURL); - muxMessageProvider.add(unrealMessageProvider); + return offset2 + byteLength3; + }; + Buffer3.prototype.writeIntBE = function writeIntBE(value, offset2, byteLength3, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength3 - 1); + checkInt(this, value, offset2, byteLength3, limit - 1, -limit); } - muxMessageProvider.register(); - return muxMessageProvider; - } - add(...messageProviders) { - this.messageProviders.push(...messageProviders); - } - closeWallet() { - if (this.provider) { - this.provider.closeWallet(); + let i = byteLength3 - 1; + let mul = 1; + let sub = 0; + this[offset2 + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset2 + i + 1] !== 0) { + sub = 1; + } + this[offset2 + i] = (value / mul >> 0) - sub & 255; } + return offset2 + byteLength3; + }; + Buffer3.prototype.writeInt8 = function writeInt8(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 1, 127, -128); + if (value < 0) value = 255 + value + 1; + this[offset2] = value & 255; + return offset2 + 1; + }; + Buffer3.prototype.writeInt16LE = function writeInt16LE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 2, 32767, -32768); + this[offset2] = value & 255; + this[offset2 + 1] = value >>> 8; + return offset2 + 2; + }; + Buffer3.prototype.writeInt16BE = function writeInt16BE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 2, 32767, -32768); + this[offset2] = value >>> 8; + this[offset2 + 1] = value & 255; + return offset2 + 2; + }; + Buffer3.prototype.writeInt32LE = function writeInt32LE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 4, 2147483647, -2147483648); + this[offset2] = value & 255; + this[offset2 + 1] = value >>> 8; + this[offset2 + 2] = value >>> 16; + this[offset2 + 3] = value >>> 24; + return offset2 + 4; + }; + Buffer3.prototype.writeInt32BE = function writeInt32BE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 4, 2147483647, -2147483648); + if (value < 0) value = 4294967295 + value + 1; + this[offset2] = value >>> 24; + this[offset2 + 1] = value >>> 16; + this[offset2 + 2] = value >>> 8; + this[offset2 + 3] = value & 255; + return offset2 + 4; + }; + Buffer3.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset2 = 0) { + return wrtBigUInt64LE(this, value, offset2, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + Buffer3.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset2 = 0) { + return wrtBigUInt64BE(this, value, offset2, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function checkIEEE754(buf, value, offset2, ext, max2, min2) { + if (offset2 + ext > buf.length) throw new RangeError("Index out of range"); + if (offset2 < 0) throw new RangeError("Index out of range"); } - isOpened() { - if (this.provider) { - return this.provider.isOpened(); + function writeFloat(buf, value, offset2, littleEndian, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset2, 4); } - return false; + ieee754$1.write(buf, value, offset2, littleEndian, 23, 4); + return offset2 + 4; } - isConnected() { - if (this.provider) { - return this.provider.isConnected(); + Buffer3.prototype.writeFloatLE = function writeFloatLE(value, offset2, noAssert) { + return writeFloat(this, value, offset2, true, noAssert); + }; + Buffer3.prototype.writeFloatBE = function writeFloatBE(value, offset2, noAssert) { + return writeFloat(this, value, offset2, false, noAssert); + }; + function writeDouble(buf, value, offset2, littleEndian, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset2, 8); } - return false; + ieee754$1.write(buf, value, offset2, littleEndian, 52, 8); + return offset2 + 8; } - on(event, fn) { - if (this.provider) { - this.provider.on(event, fn); - return; + Buffer3.prototype.writeDoubleLE = function writeDoubleLE(value, offset2, noAssert) { + return writeDouble(this, value, offset2, true, noAssert); + }; + Buffer3.prototype.writeDoubleBE = function writeDoubleBE(value, offset2, noAssert) { + return writeDouble(this, value, offset2, false, noAssert); + }; + Buffer3.prototype.copy = function copy2(target, targetStart, start, end) { + if (!Buffer3.isBuffer(target)) throw new TypeError("argument should be a Buffer"); + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); } - this.messageProviders.forEach((m2) => { - m2.on(event, fn); - }); - } - once(event, fn) { - if (this.provider) { - this.provider.once(event, fn); - return; + if (start < 0 || start >= this.length) throw new RangeError("Index out of range"); + if (end < 0) throw new RangeError("sourceEnd out of bounds"); + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; } - this.messageProviders.forEach((m2) => { - m2.once(event, fn); - }); - } - emit(event, ...args) { - if (this.provider) { - return this.provider.emit(event, ...args); + const len = end - start; + if (this === target && typeof GlobalUint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + GlobalUint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); } - for (let i = 0; i < this.messageProviders.length; i++) { - this.messageProviders[i].emit(event, ...args); + return len; + }; + Buffer3.prototype.fill = function fill(val, start, end, encoding) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (encoding !== void 0 && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer3.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + if (val.length === 1) { + const code2 = val.charCodeAt(0); + if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { + val = code2; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); } - return true; - } - request(request) { - if (!this.provider) { - throw new Error("impossible state, wallet must be opened first"); + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); } - return this.provider.request(request); - } - sendMessage(message) { - if (!message.idx || message.idx <= 0) { - throw new Error("message idx is empty"); + if (end <= start) { + return this; } - if (this.provider) { - this.provider.sendMessage(message); + start = start >>> 0; + end = end === void 0 ? this.length : end >>> 0; + if (!val) val = 0; + let i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } } else { - throw new Error("impossible state, wallet must be opened first"); - } - } - handleMessage(message) { - if (this.provider) { - this.provider.handleMessage(message); - return; + const bytes2 = Buffer3.isBuffer(val) ? val : Buffer3.from(val, encoding); + const len = bytes2.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes2[i % len]; + } } - throw new Error("impossible state, wallet must be opened first"); - } -} -function toExtended(transactions2) { - if (transactions2.length === 0) { - throw new Error("No transaction provided"); - } - const [first, ...rest] = transactions2; - return _extends$2({}, first, { - auxiliary: rest - }); -} -function fromExtended(transaction2) { - return [transaction2, ...transaction2.auxiliary || []]; -} -const SIGNER_READY_TIMEOUT = 1e4; -class WalletRequestHandler { - constructor(account2, prompter, networks2) { - var _this = this; - this.account = void 0; - this.signerReadyCallbacks = []; - this.prompter = void 0; - this.networks = void 0; - this._openIntent = void 0; - this._connectOptions = void 0; - this.events = new eventemitter2Exports.EventEmitter2(); - this.onConnectOptionsChange = void 0; - this.promptConnect = async function(options) { - if (!options && !_this._connectOptions) { - throw new Error("prompter connect options are empty"); + return this; + }; + const errors2 = {}; + function E2(sym, getMessage, Base2) { + errors2[sym] = class NodeError extends Base2 { + constructor() { + super(); + Object.defineProperty(this, "message", { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }); + this.name = `${this.name} [${sym}]`; + this.stack; + delete this.name; } - if (!_this.prompter) { - return _this.connect(options); + get code() { + return sym; } - const promptConnectDetails = await _this.prompter.promptConnect(options || _this._connectOptions).catch((_) => { - return { - connected: false - }; - }); - const connectDetails = promptConnectDetails; - if (connectDetails.connected && !connectDetails.session) { - connectDetails.session = await _this.walletSession(options == null ? void 0 : options.networkId); + set code(value) { + Object.defineProperty(this, "code", { + configurable: true, + enumerable: true, + value, + writable: true + }); } - return promptConnectDetails; - }; - this.isSignedIn = async function() { - await _this.signerReady(); - return !!_this.account; - }; - this.getAccount = async function() { - await _this.signerReady(); - if (_this.account === void 0) { - throw new Error("signerReady failed resolve"); + toString() { + return `${this.name} [${sym}]: ${this.message}`; } - return _this.account; }; - this.account = account2; - this.prompter = prompter; - this.networks = networks2; - } - defaultChainId() { - var _this$prompter$getDef, _this$prompter; - return (_this$prompter$getDef = (_this$prompter = this.prompter) == null ? void 0 : _this$prompter.getDefaultChainId()) != null ? _this$prompter$getDef : this.networks[0].chainId; } - async signIn(account2, options = {}) { - this.setAccount(account2); - const { - connect: connect2, - defaultNetworkId - } = options; - if (connect2) { - const connectOptions = this._connectOptions; - let connectDetails; - if (this.prompter !== null) { - var _this$prompter2; - connectDetails = await ((_this$prompter2 = this.prompter) == null ? void 0 : _this$prompter2.promptSignInConnect(connectOptions)); - } else { - connectDetails = await this.connect(connectOptions); + E2( + "ERR_BUFFER_OUT_OF_BOUNDS", + function(name2) { + if (name2) { + return `${name2} is outside of buffer bounds`; } - this.notifyConnect(connectDetails); - if (!connectOptions || connectOptions.keepWalletOpened !== true) { - this.notifyClose(); + return "Attempt to access memory outside buffer bounds"; + }, + RangeError + ); + E2( + "ERR_INVALID_ARG_TYPE", + function(name2, actual) { + return `The "${name2}" argument must be of type number. Received type ${typeof actual}`; + }, + TypeError + ); + E2( + "ERR_OUT_OF_RANGE", + function(str, range2, input2) { + let msg = `The value of "${str}" is out of range.`; + let received = input2; + if (Number.isInteger(input2) && Math.abs(input2) > 2 ** 32) { + received = addNumericalSeparator(String(input2)); + } else if (typeof input2 === "bigint") { + received = String(input2); + if (input2 > BigInt(2) ** BigInt(32) || input2 < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received); + } + received += "n"; } + msg += ` It must be ${range2}. Received ${received}`; + return msg; + }, + RangeError + ); + function addNumericalSeparator(val) { + let res = ""; + let i = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}`; } - if (defaultNetworkId && this.defaultChainId() !== defaultNetworkId) { - var _this$prompter3; - await ((_this$prompter3 = this.prompter) == null ? void 0 : _this$prompter3.promptChangeNetwork(defaultNetworkId)); - } + return `${val.slice(0, i)}${res}`; } - signOut() { - if (this.account) { - this.notifyDisconnect(); + function checkBounds(buf, offset2, byteLength3) { + validateNumber(offset2, "offset"); + if (buf[offset2] === void 0 || buf[offset2 + byteLength3] === void 0) { + boundsError(offset2, buf.length - (byteLength3 + 1)); } - this.setAccount(null); } - signerReset() { - this.account = void 0; - } - signerReady(timeout = SIGNER_READY_TIMEOUT) { - return new Promise((resolve, reject) => { - if (this.account !== void 0) { - resolve(); - } else { - setTimeout(() => { - if (this.account === void 0) { - this.signerReadyCallbacks = []; - reject(`signerReady timed out`); - } - }, timeout); - this.signerReadyCallbacks.push(resolve); + function checkIntBI(value, min2, max2, buf, offset2, byteLength3) { + if (value > max2 || value < min2) { + const n2 = typeof min2 === "bigint" ? "n" : ""; + let range2; + { + if (min2 === 0 || min2 === BigInt(0)) { + range2 = `>= 0${n2} and < 2${n2} ** ${(byteLength3 + 1) * 8}${n2}`; + } else { + range2 = `>= -(2${n2} ** ${(byteLength3 + 1) * 8 - 1}${n2}) and < 2 ** ${(byteLength3 + 1) * 8 - 1}${n2}`; + } } - }); + throw new errors2.ERR_OUT_OF_RANGE("value", range2, value); + } + checkBounds(buf, offset2, byteLength3); } - async connect(options) { - var _ref, _options$networkId; - if (!this.account) { - return { - connected: false, - chainId: "0x0", - error: "unable to connect without signed in account" - }; + function validateNumber(value, name2) { + if (typeof value !== "number") { + throw new errors2.ERR_INVALID_ARG_TYPE(name2, "number", value); } - const networkId = (_ref = (_options$networkId = options == null ? void 0 : options.networkId) != null ? _options$networkId : this.defaultChainId()) != null ? _ref : ChainId.MAINNET; - const chainId = findSupportedNetwork(networkId).chainId; - const connectDetails = { - connected: true, - chainId: toQuantity(chainId) - }; - if (options && options.authorize) { - const authOptions = { - app: options.app, - origin: options.origin, - expiry: options.expiry, - nonce: options.authorizeNonce - }; - try { - connectDetails.proof = await signAuthorization(this.account, chainId, authOptions); - } catch (err) { - logger.warn(`connect, signAuthorization failed for options: ${JSON.stringify(options)}, due to: ${err.message}`); - return { - connected: false, - chainId: "0x0", - error: `signAuthorization failed: ${err.message}` - }; - } + } + function boundsError(value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type); + throw new errors2.ERR_OUT_OF_RANGE("offset", "an integer", value); } - connectDetails.session = this.walletSession(chainId); - return connectDetails; + if (length < 0) { + throw new errors2.ERR_BUFFER_OUT_OF_BOUNDS(); + } + throw new errors2.ERR_OUT_OF_RANGE( + "offset", + `>= ${0} and <= ${length}`, + value + ); } - // sendMessageRequest will unwrap the ProviderMessageRequest and send it to the JsonRpcHandler - // (aka, the signer in this instance) and then responds with a wrapped response of - // ProviderMessageResponse to be sent over the transport - async sendMessageRequest(message) { - var _message$clientVersio; - const majorVersion = Number(((_message$clientVersio = message.clientVersion) == null ? void 0 : _message$clientVersio.split(".")[0]) || "0"); - const isJsonRpcResponse = majorVersion < 2; - const jsonRpcResponse = { - id: message.data.id, - jsonrpc: "2.0", - result: null, - error: void 0 - }; - try { - const result = await this.request({ - method: message.data.method, - params: message.data.params, - chainId: message.chainId - }); - return _extends$2({}, message, { - data: isJsonRpcResponse ? _extends$2({}, jsonRpcResponse, { - result - }) : result - }); - } catch (error) { - return _extends$2({}, message, { - data: isJsonRpcResponse ? _extends$2({}, jsonRpcResponse, { - error - }) : { - error - } - }); + const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str) { + str = str.split("=")[0]; + str = str.trim().replace(INVALID_BASE64_RE, ""); + if (str.length < 2) return ""; + while (str.length % 4 !== 0) { + str = str + "="; } + return str; } - async request(request) { - await this.getAccount(); - try { - var _this$account, _request$chainId; - if ((!this.account || this.account === null) && !permittedJsonRpcMethods.includes(request.method)) { - throw ErrSignedInRequired; - } - const account2 = this.account; - if (!account2) { - throw new Error("WalletRequestHandler: wallet account is not configured"); - } - const provider2 = (_this$account = this.account) == null ? void 0 : _this$account.providerFor((_request$chainId = request.chainId) != null ? _request$chainId : this.defaultChainId()); - if (!provider2) { - throw new Error(`WalletRequestHandler: wallet provider is not configured for chainId ${request.chainId}`); - } - const jsonRpcProvider = provider2 instanceof JsonRpcProvider$1 ? provider2 : void 0; - switch (request.method) { - case "net_version": { - if (!jsonRpcProvider) { - throw new Error(`Account provider doesn't support send method`); - } - return await jsonRpcProvider.send("net_version", []); - } - case "eth_chainId": { - if (!jsonRpcProvider) { - throw new Error(`Account provider doesn't support send method`); - } - return await jsonRpcProvider.send("eth_chainId", []); - } - case "eth_accounts": { - return [account2.address]; - } - case "eth_getBalance": { - const [accountAddress, blockTag] = request.params; - const walletBalance = await provider2.getBalance(accountAddress, blockTag); - return toHexString(walletBalance); - } - case "sequence_sign": - case "personal_sign": - case "eth_sign": { - let message; - switch (request.method) { - case "sequence_sign": - case "personal_sign": { - const [data, _address] = request.params; - message = data; - break; - } - case "eth_sign": { - const [_address, data] = request.params; - message = data; - break; - } - } - let sig = ""; - const prefixedMessage = prefixEIP191Message(message); - const sequenceVerified = request.method === "sequence_sign"; - if (this.prompter === null) { - var _request$chainId2; - sig = await account2.signMessage(prefixedMessage, (_request$chainId2 = request.chainId) != null ? _request$chainId2 : this.defaultChainId(), sequenceVerified ? "eip6492" : "ignore"); - } else { - sig = await this.prompter.promptSignMessage({ - chainId: request.chainId, - message: getBytes(prefixedMessage), - eip6492: sequenceVerified - }, this.connectOptions); - } - if (sig && sig.length > 0) { - return sig; - } else { - throw new Error("declined by user"); - } - } - case "sequence_signTypedData_v4": - case "eth_signTypedData": - case "eth_signTypedData_v4": { - const [signingAddress, typedDataObject] = request.params; - let typedData = void 0; - if (typeof typedDataObject === "string") { - try { - typedData = JSON.parse(typedDataObject); - } catch (e2) { - console.warn("walletRequestHandler: error parsing typedData", e2); - } - } else { - typedData = typedDataObject; - } - if (!typedData || !typedData.domain || !typedData.types || !typedData.message) { - throw new Error("invalid typedData object"); - } - let sig = ""; - const sequenceVerified = request.method === "sequence_signTypedData_v4"; - if (this.prompter === null) { - var _request$chainId3; - sig = await account2.signTypedData(typedData.domain, typedData.types, typedData.message, (_request$chainId3 = request.chainId) != null ? _request$chainId3 : this.defaultChainId(), sequenceVerified ? "eip6492" : "ignore"); - } else { - sig = await this.prompter.promptSignMessage({ - chainId: request.chainId, - typedData, - eip6492: sequenceVerified - }, this.connectOptions); - } - if (sig && sig.length > 0) { - return sig; - } else { - throw new Error("declined by user"); - } - } - case "eth_sendTransaction": { - const transactionParams = fromExtended(request.params[0]).map((tx) => { - if ("gas" in tx && tx.gasLimit === void 0) { - tx.gasLimit = tx.gas; - delete tx.gas; - } - return tx; - }); - validateTransactionRequest(account2.address, transactionParams); - let txnHash = ""; - if (this.prompter === null) { - var _request$chainId4, _txnResponse$hash; - const txnResponse = await account2.sendTransaction(transactionParams, (_request$chainId4 = request.chainId) != null ? _request$chainId4 : this.defaultChainId()); - txnHash = (_txnResponse$hash = txnResponse == null ? void 0 : txnResponse.hash) != null ? _txnResponse$hash : ""; - } else { - txnHash = await this.prompter.promptSendTransaction(transactionParams, request.chainId, this.connectOptions); - } - if (txnHash) { - return txnHash; - } else { - throw new Error("declined by user"); - } - } - case "eth_signTransaction": { - const [transaction2] = request.params; - const sender = getAddress$1(transaction2.from); - if (sender !== account2.address) { - throw new Error("sender address does not match wallet"); - } - validateTransactionRequest(account2.address, transaction2); - if (this.prompter === null) { - var _request$chainId5; - return await account2.signTransactions(transaction2, (_request$chainId5 = request.chainId) != null ? _request$chainId5 : this.defaultChainId()); - } else { - return await this.prompter.promptSignTransaction(transaction2, request.chainId, this.connectOptions); - } - } - case "eth_sendRawTransaction": { - if (index$1$2.transaction.isSignedTransactionBundle(request.params[0])) { - const txChainId = Number(request.params[0].chainId); - const tx = await account2.relayer(txChainId).relay(request.params[0]); - return tx.hash; - } else { - const tx = await provider2.broadcastTransaction(request.params[0]); - return tx.hash; - } - } - case "eth_getTransactionCount": { - const address = getAddress$1(request.params[0]); - const tag = request.params[1]; - const count2 = await provider2.getTransactionCount(address, tag); - return toHexString(BigInt(count2)); - } - case "eth_blockNumber": { - return await provider2.getBlockNumber(); - } - case "eth_getBlockByNumber": { - return await provider2.getBlock( - request.params[0] - /* , jsonRpcRequest.params[1] */ - ); - } - case "eth_getBlockByHash": { - return await provider2.getBlock( - request.params[0] - /* , jsonRpcRequest.params[1] */ - ); - } - case "eth_getTransactionByHash": { - return await provider2.getTransaction(request.params[0]); - } - case "eth_call": { - const [transactionObject, blockTag] = request.params; - return await provider2.call(_extends$2({}, transactionObject, { - blockTag - })); - } - case "eth_getCode": { - const [contractAddress, blockTag] = request.params; - return await provider2.getCode(contractAddress, blockTag); - } - case "eth_estimateGas": { - const [transactionObject] = request.params; - return await provider2.estimateGas(transactionObject); - } - case "eth_gasPrice": { - const feeData = await provider2.getFeeData(); - return feeData.gasPrice === null ? null : toHexString(feeData.gasPrice); - } - case "wallet_switchEthereumChain": { - const [switchParams] = request.params; - if (!switchParams.chainId || switchParams.chainId.length === 0) { - throw new Error("invalid chainId"); - } - const chainId = BigInt(switchParams.chainId); - this.setDefaultChainId(Number(chainId)); - return null; - } - case "sequence_getWalletContext": { - return account2.contexts; - } - case "sequence_getWalletConfig": { - const [chainId] = request.params; - if (chainId) { - return [(await account2.status(chainId)).onChain.config]; - } else { - return await Promise.all(account2.networks.map(async function(network2) { - const status = await account2.status(network2.chainId); - return status.onChain.config; - })); - } - } - case "sequence_getWalletState": { - const [chainId] = request.params; - if (chainId) { - return [getLegacyWalletState(chainId, await account2.status(chainId))]; - } else { - return await Promise.all(account2.networks.map(async function(network2) { - const status = await account2.status(network2.chainId); - return getLegacyWalletState(network2.chainId, status); - })); - } - } - case "sequence_getNetworks": { - return await this.getNetworks(true); - } - case "sequence_isSequence": { - return true; - } - case "sequence_updateConfig": { - throw new Error("sequence_updateConfig method is not allowed from a dapp"); - } - case "sequence_publishConfig": { - throw new Error("sequence_publishConfig method is not allowed from a dapp"); - } - case "sequence_gasRefundOptions": { - break; - } - case "sequence_getNonce": { - break; - } - case "sequence_relay": { - break; - } - case "sequence_setDefaultNetwork": { - const [defaultChainId] = request.params; - if (!defaultChainId) { - throw new Error("invalid request, method argument defaultChainId cannot be empty"); + function utf8ToBytes2(string, units) { + units = units || Infinity; + let codePoint; + const length = string.length; + let leadSurrogate = null; + const bytes2 = []; + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) bytes2.push(239, 191, 189); + continue; + } else if (i + 1 === length) { + if ((units -= 3) > -1) bytes2.push(239, 191, 189); + continue; } - this.setDefaultChainId(defaultChainId); - return await this.getNetworks(true); + leadSurrogate = codePoint; + continue; } - default: { - if (!jsonRpcProvider) { - throw new Error(`Account provider doesn't support send method`); - } - return await jsonRpcProvider.send(request.method, request.params); + if (codePoint < 56320) { + if ((units -= 3) > -1) bytes2.push(239, 191, 189); + leadSurrogate = codePoint; + continue; } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + if ((units -= 3) > -1) bytes2.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) break; + bytes2.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) break; + bytes2.push( + codePoint >> 6 | 192, + codePoint & 63 | 128 + ); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) break; + bytes2.push( + codePoint >> 12 | 224, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) break; + bytes2.push( + codePoint >> 18 | 240, + codePoint >> 12 & 63 | 128, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else { + throw new Error("Invalid code point"); } - } catch (err) { - logger.error(err); - throw { - message: typeof err == "string" ? err : (err == null ? void 0 : err.message) || "unkown error", - code: 4001 - }; } + return bytes2; } - on(event, fn) { - this.events.on(event, fn); - } - once(event, fn) { - this.events.once(event, fn); - } - async getAddress() { - var _this$account$address, _this$account2; - return (_this$account$address = (_this$account2 = this.account) == null ? void 0 : _this$account2.address) != null ? _this$account$address : ""; - } - get openIntent() { - return this._openIntent; + function asciiToBytes(str) { + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + byteArray.push(str.charCodeAt(i) & 255); + } + return byteArray; } - setOpenIntent(intent) { - this._openIntent = intent; + function utf16leToBytes(str, units) { + let c2, hi2, lo; + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + c2 = str.charCodeAt(i); + hi2 = c2 >> 8; + lo = c2 % 256; + byteArray.push(lo); + byteArray.push(hi2); + } + return byteArray; } - get connectOptions() { - return this._connectOptions; + function base64ToBytes(str) { + return base64.toByteArray(base64clean(str)); } - setConnectOptions(options) { - var _this$onConnectOption; - this._connectOptions = options; - (_this$onConnectOption = this.onConnectOptionsChange) == null || _this$onConnectOption.call(this, options); + function blitBuffer(src, dst, offset2, length) { + let i; + for (i = 0; i < length; ++i) { + if (i + offset2 >= dst.length || i >= src.length) break; + dst[i + offset2] = src[i]; + } + return i; } - async setDefaultChainId(chainId) { - var _this$prompter4; - await ((_this$prompter4 = this.prompter) == null ? void 0 : _this$prompter4.promptChangeNetwork(chainId)); - return this.defaultChainId(); + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; } - async getNetworks(jsonRpcResponse) { - if (!this.account) { - logger.warn("signer not set: getNetworks is returning an empty list"); - return []; - } - if (jsonRpcResponse) { - return this.account.networks.map((n2) => { - const network2 = _extends$2({}, n2); - network2.provider = void 0; - network2.relayer = void 0; - return network2; - }); - } else { - return this.account.networks; - } + function numberIsNaN(obj) { + return obj !== obj; } - walletSession(networkId) { - if (!this.account) { - return void 0; - } - const session = { - walletContext: this.account.contexts, - accountAddress: this.account.address, - // The dapp shouldn't access the relayer directly, and the provider (as an object) is not serializable. - networks: this.account.networks.map((n2) => _extends$2({}, n2, { - provider: void 0, - relayer: void 0 - })) - }; - if (networkId) { - const network2 = findNetworkConfig(session.networks, networkId); - if (network2) { - var _session$networks; - (_session$networks = session.networks) == null || _session$networks.forEach((n2) => delete n2.isDefaultChain); - network2.isDefaultChain = true; + const hexSliceLookupTable = function() { + const alphabet = "0123456789abcdef"; + const table = new Array(256); + for (let i = 0; i < 16; ++i) { + const i16 = i * 16; + for (let j2 = 0; j2 < 16; ++j2) { + table[i16 + j2] = alphabet[i] + alphabet[j2]; } } - return session; + return table; + }(); + function defineBigIntMethod(fn) { + return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; } - notifyConnect(connectDetails, origin) { - var _connectDetails$sessi; - console.log("emit connect", connectDetails); - this.events.emit("connect", connectDetails); - if ((_connectDetails$sessi = connectDetails.session) != null && _connectDetails$sessi.accountAddress) { - var _connectDetails$sessi2; - this.events.emit("accountsChanged", [(_connectDetails$sessi2 = connectDetails.session) == null ? void 0 : _connectDetails$sessi2.accountAddress], origin); - } + function BufferBigIntNotDefined() { + throw new Error("BigInt not supported"); } - notifyDisconnect(origin) { - this.events.emit("accountsChanged", [], origin); - this.events.emit("disconnect", void 0, origin); +})(buffer); +const Buffer2 = buffer.Buffer; +const Blob$1 = buffer.Blob; +const BlobOptions = buffer.BlobOptions; +const Buffer$1 = buffer.Buffer; +const File = buffer.File; +const FileOptions = buffer.FileOptions; +const INSPECT_MAX_BYTES = buffer.INSPECT_MAX_BYTES; +const SlowBuffer = buffer.SlowBuffer; +const TranscodeEncoding = buffer.TranscodeEncoding; +const atob$1 = buffer.atob; +const btoa$1 = buffer.btoa; +const constants = buffer.constants; +const isAscii = buffer.isAscii; +const isUtf8 = buffer.isUtf8; +const kMaxLength = buffer.kMaxLength; +const kStringMaxLength = buffer.kStringMaxLength; +const resolveObjectURL = buffer.resolveObjectURL; +const transcode = buffer.transcode; +const dist$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Blob: Blob$1, + BlobOptions, + Buffer: Buffer$1, + File, + FileOptions, + INSPECT_MAX_BYTES, + SlowBuffer, + TranscodeEncoding, + atob: atob$1, + btoa: btoa$1, + constants, + default: Buffer2, + isAscii, + isUtf8, + kMaxLength, + kStringMaxLength, + resolveObjectURL, + transcode +}, Symbol.toStringTag, { value: "Module" })); +const version$4 = "3.7.7"; +const VERSION$2 = version$4; +const _hasBuffer = typeof Buffer2 === "function"; +const _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0; +const _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0; +const b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; +const b64chs = Array.prototype.slice.call(b64ch); +const b64tab = ((a2) => { + let tab = {}; + a2.forEach((c2, i) => tab[c2] = i); + return tab; +})(b64chs); +const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/; +const _fromCC = String.fromCharCode.bind(String); +const _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0)); +const _mkUriSafe = (src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_"); +const _tidyB64 = (s2) => s2.replace(/[^A-Za-z0-9\+\/]/g, ""); +const btoaPolyfill = (bin) => { + let u322, c0, c1, c2, asc = ""; + const pad2 = bin.length % 3; + for (let i = 0; i < bin.length; ) { + if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255) + throw new TypeError("invalid character found"); + u322 = c0 << 16 | c1 << 8 | c2; + asc += b64chs[u322 >> 18 & 63] + b64chs[u322 >> 12 & 63] + b64chs[u322 >> 6 & 63] + b64chs[u322 & 63]; } - notifyChainChanged(chainId, origin) { - this.events.emit("chainChanged", toQuantity(chainId), origin); + return pad2 ? asc.slice(0, pad2 - 3) + "===".substring(pad2) : asc; +}; +const _btoa = typeof btoa === "function" ? (bin) => btoa(bin) : _hasBuffer ? (bin) => Buffer2.from(bin, "binary").toString("base64") : btoaPolyfill; +const _fromUint8Array = _hasBuffer ? (u8a2) => Buffer2.from(u8a2).toString("base64") : (u8a2) => { + const maxargs = 4096; + let strs = []; + for (let i = 0, l2 = u8a2.length; i < l2; i += maxargs) { + strs.push(_fromCC.apply(null, u8a2.subarray(i, i + maxargs))); } - async notifyNetworks(networks2) { - const n2 = networks2 || await this.getNetworks(true); - this.events.emit("networks", n2); - if (n2.length > 0) { - const defaultNetwork = n2.find((network2) => network2.chainId === this.defaultChainId()); - if (defaultNetwork) { - this.events.emit("chainChanged", toQuantity(defaultNetwork.chainId)); - } - } else { - this.events.emit("chainChanged", "0x0"); - } + return _btoa(strs.join("")); +}; +const fromUint8Array = (u8a2, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a2)) : _fromUint8Array(u8a2); +const cb_utob = (c2) => { + if (c2.length < 2) { + var cc2 = c2.charCodeAt(0); + return cc2 < 128 ? c2 : cc2 < 2048 ? _fromCC(192 | cc2 >>> 6) + _fromCC(128 | cc2 & 63) : _fromCC(224 | cc2 >>> 12 & 15) + _fromCC(128 | cc2 >>> 6 & 63) + _fromCC(128 | cc2 & 63); + } else { + var cc2 = 65536 + (c2.charCodeAt(0) - 55296) * 1024 + (c2.charCodeAt(1) - 56320); + return _fromCC(240 | cc2 >>> 18 & 7) + _fromCC(128 | cc2 >>> 12 & 63) + _fromCC(128 | cc2 >>> 6 & 63) + _fromCC(128 | cc2 & 63); } - async notifyWalletContext() { - if (!this.account) { - logger.warn("signer not set: skipping to notify wallet context"); - return; - } - const walletContext = this.account.contexts; - this.events.emit("walletContext", walletContext); +}; +const re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; +const utob = (u2) => u2.replace(re_utob, cb_utob); +const _encode = _hasBuffer ? (s2) => Buffer2.from(s2, "utf8").toString("base64") : _TE ? (s2) => _fromUint8Array(_TE.encode(s2)) : (s2) => _btoa(utob(s2)); +const encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src); +const encodeURI$1 = (src) => encode(src, true); +const re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g; +const cb_btou = (cccc) => { + switch (cccc.length) { + case 4: + var cp = (7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3), offset2 = cp - 65536; + return _fromCC((offset2 >>> 10) + 55296) + _fromCC((offset2 & 1023) + 56320); + case 3: + return _fromCC((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2)); + default: + return _fromCC((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1)); } - notifyClose(error) { - this.events.emit("close", error); +}; +const btou = (b2) => b2.replace(re_btou, cb_btou); +const atobPolyfill = (asc) => { + asc = asc.replace(/\s+/g, ""); + if (!b64re.test(asc)) + throw new TypeError("malformed base64."); + asc += "==".slice(2 - (asc.length & 3)); + let u24, bin = "", r1, r2; + for (let i = 0; i < asc.length; ) { + u24 = b64tab[asc.charAt(i++)] << 18 | b64tab[asc.charAt(i++)] << 12 | (r1 = b64tab[asc.charAt(i++)]) << 6 | (r2 = b64tab[asc.charAt(i++)]); + bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255); } - setAccount(account2) { - this.account = account2; - if (account2 !== void 0) { - for (let i = 0; i < this.signerReadyCallbacks.length; i++) { - this.signerReadyCallbacks[i](); - } - this.signerReadyCallbacks = []; + return bin; +}; +const _atob = typeof atob === "function" ? (asc) => atob(_tidyB64(asc)) : _hasBuffer ? (asc) => Buffer2.from(asc, "base64").toString("binary") : atobPolyfill; +const _toUint8Array = _hasBuffer ? (a2) => _U8Afrom(Buffer2.from(a2, "base64")) : (a2) => _U8Afrom(_atob(a2).split("").map((c2) => c2.charCodeAt(0))); +const toUint8Array$1 = (a2) => _toUint8Array(_unURI(a2)); +const _decode = _hasBuffer ? (a2) => Buffer2.from(a2, "base64").toString("utf8") : _TD ? (a2) => _TD.decode(_toUint8Array(a2)) : (a2) => btou(_atob(a2)); +const _unURI = (a2) => _tidyB64(a2.replace(/[-_]/g, (m0) => m0 == "-" ? "+" : "/")); +const decode = (src) => _decode(_unURI(src)); +const isValid = (src) => { + if (typeof src !== "string") + return false; + const s2 = src.replace(/\s+/g, "").replace(/={0,2}$/, ""); + return !/[^\s0-9a-zA-Z\+/]/.test(s2) || !/[^\s0-9a-zA-Z\-_]/.test(s2); +}; +const _noEnum = (v3) => { + return { + value: v3, + enumerable: false, + writable: true, + configurable: true + }; +}; +const extendString = function() { + const _add = (name2, body) => Object.defineProperty(String.prototype, name2, _noEnum(body)); + _add("fromBase64", function() { + return decode(this); + }); + _add("toBase64", function(urlsafe) { + return encode(this, urlsafe); + }); + _add("toBase64URI", function() { + return encode(this, true); + }); + _add("toBase64URL", function() { + return encode(this, true); + }); + _add("toUint8Array", function() { + return toUint8Array$1(this); + }); +}; +const extendUint8Array = function() { + const _add = (name2, body) => Object.defineProperty(Uint8Array.prototype, name2, _noEnum(body)); + _add("toBase64", function(urlsafe) { + return fromUint8Array(this, urlsafe); + }); + _add("toBase64URI", function() { + return fromUint8Array(this, true); + }); + _add("toBase64URL", function() { + return fromUint8Array(this, true); + }); +}; +const extendBuiltins = () => { + extendString(); + extendUint8Array(); +}; +const gBase64 = { + version: version$4, + VERSION: VERSION$2, + atob: _atob, + atobPolyfill, + btoa: _btoa, + btoaPolyfill, + fromBase64: decode, + toBase64: encode, + encode, + encodeURI: encodeURI$1, + encodeURL: encodeURI$1, + utob, + btou, + decode, + isValid, + fromUint8Array, + toUint8Array: toUint8Array$1, + extendString, + extendUint8Array, + extendBuiltins +}; +var __assign = function() { + __assign = Object.assign || function __assign2(t2) { + for (var s2, i = 1, n2 = arguments.length; i < n2; i++) { + s2 = arguments[i]; + for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2)) t2[p2] = s2[p2]; } + return t2; + }; + return __assign.apply(this, arguments); +}; +function __awaiter(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); } - async handleConfirmWalletDeployPrompt(prompter, account2, sequenceVerified, chainId) { - if (!chainId) { - return true; - } - const skipsDeploy = (status2) => { - return status2.canOnchainValidate || status2.original.version === 2 && sequenceVerified; - }; - const status = await account2.status(chainId); - if (skipsDeploy(status)) { - return true; + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } } - const promptResult = await prompter.promptConfirmWalletDeploy(chainId, this.connectOptions); - if (promptResult) { - const status2 = await account2.status(chainId); - if (skipsDeploy(status2)) { - return true; - } else { - logger.error("WalletRequestHandler: result for promptConfirmWalletDeploy is not correct"); - return false; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); } } - return false; - } -} -function getLegacyWalletState(chainId, status) { - return { - context: status.original.context, - config: status.onChain.config, - address: index$1$2.context.addressOf(status.original.context, status.original.imageHash), - chainId, - deployed: status.onChain.deployed, - imageHash: status.imageHash, - lastImageHash: status.onChain.imageHash, - published: true, - status - }; -} -const permittedJsonRpcMethods = ["net_version", "eth_chainId", "eth_getBalance", "eth_getTransactionCount", "eth_blockNumber", "eth_getBlockByNumber", "eth_getBlockByHash", "eth_getTransactionByHash", "eth_getCode", "eth_estimateGas", "eth_gasPrice", "sequence_getWalletContext", "sequence_getNetworks", "sequence_setDefaultNetwork"]; -function _objectWithoutPropertiesLoose$3(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - return target; + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, [])).next()); + }); } -class SequenceSigner { - get utils() { - return this.provider.utils; - } - constructor(client2, provider2) { - this.client = client2; - this.provider = provider2; - this.singleNetworkSigners = {}; - this._isSequenceSigner = true; - } - async getAddress() { - return this.client.getAddress(); +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { + if (t2[0] & 1) throw t2[1]; + return t2[1]; + }, trys: [], ops: [] }, f2, y2, t2, g2; + return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() { + return this; + }), g2; + function verb(n2) { + return function(v3) { + return step([n2, v3]); + }; } - // This method shouldn't be used directly - // it exists to maintain compatibility with ethers.Signer - connect(provider2) { - if (!SequenceProvider.is(provider2)) { - throw new Error("SequenceSigner can only be connected to a SequenceProvider"); + function step(op) { + if (f2) throw new TypeError("Generator is already executing."); + while (g2 && (g2 = 0, op[0] && (_ = 0)), _) try { + if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2; + if (y2 = 0, t2) op = [op[0] & 2, t2.value]; + switch (op[0]) { + case 0: + case 1: + t2 = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y2 = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t2 = _.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t2[1]) { + _.label = t2[1]; + t2 = op; + break; + } + if (t2 && _.label < t2[2]) { + _.label = t2[2]; + _.ops.push(op); + break; + } + if (t2[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e2) { + op = [6, e2]; + y2 = 0; + } finally { + f2 = t2 = 0; } - return new SequenceSigner(this.client, provider2); + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; } - getSigner(chainId) { - if (!chainId) { - return this; - } - const useChainId2 = this.provider.toChainId(chainId); - if (!this.singleNetworkSigners[useChainId2]) { - this.singleNetworkSigners[useChainId2] = new SingleNetworkSequenceSigner(this.client, this.provider, useChainId2); +} +var encodeTypedDataHash$1 = function(typedData) { + return TypedDataEncoder.hash(typedData.domain, typedData.types, typedData.message); +}; +var ETHAuthVersion = "1"; +var ETHAuthPrefix = "eth"; +var ETHAuthEIP712Domain = { + name: "ETHAuth", + version: ETHAuthVersion +}; +var Proof = ( + /** @class */ + function() { + function Proof2(args) { + this.prefix = ETHAuthPrefix; + this.address = (args === null || args === void 0 ? void 0 : args.address) ? args.address.toLowerCase() : ""; + this.claims = (args === null || args === void 0 ? void 0 : args.claims) ? args.claims : { app: "", iat: 0, exp: 0, v: ETHAuthVersion }; + this.signature = (args === null || args === void 0 ? void 0 : args.signature) ? args.signature : ""; + this.extra = (args === null || args === void 0 ? void 0 : args.extra) ? args.extra : ""; } - return this.singleNetworkSigners[useChainId2]; - } - /** - * Resolves the chainId to use for the given request. If no chainId is provided, - * it uses the chainId defined by the client (default chainId). This can be - * overriden to build a single-network SequenceProvider. - */ - useChainId(chainId) { - return this.provider.toChainId(chainId) || this.client.getChainId(); + Proof2.prototype.setIssuedAtNow = function() { + this.claims.iat = Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3); + }; + Proof2.prototype.setExpiryIn = function(seconds) { + this.claims.exp = Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3) + seconds; + }; + Proof2.prototype.validateClaims = function() { + return validateClaims(this.claims); + }; + Proof2.prototype.messageDigest = function() { + var isValid2 = this.validateClaims(); + if (isValid2.err) { + throw isValid2.err; + } + return getBytes(encodeTypedDataHash$1(this.messageTypedData())); + }; + Proof2.prototype.messageTypedData = function() { + var domain2 = __assign({}, ETHAuthEIP712Domain); + var types2 = { + Claims: [] + }; + var message = {}; + var typedData = { domain: domain2, types: types2, message }; + if (this.claims.app && this.claims.app.length > 0) { + typedData.types.Claims.push({ name: "app", type: "string" }); + typedData.message["app"] = this.claims.app; + } + if (this.claims.iat && this.claims.iat > 0) { + typedData.types.Claims.push({ name: "iat", type: "int64" }); + typedData.message["iat"] = this.claims.iat; + } + if (this.claims.exp && this.claims.exp > 0) { + typedData.types.Claims.push({ name: "exp", type: "int64" }); + typedData.message["exp"] = this.claims.exp; + } + if (this.claims.n && this.claims.n > 0) { + typedData.types.Claims.push({ name: "n", type: "uint64" }); + typedData.message["n"] = this.claims.n; + } + if (this.claims.typ && this.claims.typ.length > 0) { + typedData.types.Claims.push({ name: "typ", type: "string" }); + typedData.message["typ"] = this.claims.typ; + } + if (this.claims.ogn && this.claims.ogn.length > 0) { + typedData.types.Claims.push({ name: "ogn", type: "string" }); + typedData.message["ogn"] = this.claims.ogn; + } + if (this.claims.v && this.claims.v.length > 0) { + typedData.types.Claims.push({ name: "v", type: "string" }); + typedData.message["v"] = this.claims.v; + } + return typedData; + }; + return Proof2; + }() +); +var validateClaims = function(claims) { + if (claims.app === "") { + return { ok: false, err: new Error("claims: app is empty") }; } - async signMessage(message, options) { - const { - eip6492 = true - } = options || {}; - const chainId = this.useChainId(options == null ? void 0 : options.chainId); - return this.client.signMessage(message, { - eip6492, - chainId - }); + var now = Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3); + var drift = 5 * 60; + var max2 = 60 * 60 * 24 * 365 + drift; + if (claims.v === "") { + return { ok: false, err: new Error("claims: ethauth version is empty") }; } - async signTypedData(domain2, types2, message, options) { - const { - eip6492 = true - } = options || {}; - const chainId = this.useChainId(options == null ? void 0 : options.chainId); - return this.client.signTypedData({ - domain: domain2, - types: types2, - message - }, { - eip6492, - chainId - }); + if (claims.iat && claims.iat !== 0 && (claims.iat > now + drift || claims.iat < now - max2)) { + return { ok: false, err: new Error("claims: iat is invalid") }; } - getProvider(chainId) { - return this.provider.getProvider(chainId); + if (claims.exp < now - drift || claims.exp > now + max2) { + return { ok: false, err: new Error("claims: token has expired") }; } - async sendTransaction(transaction2, options) { - const chainId = this.useChainId(options == null ? void 0 : options.chainId); - const resolved = await resolveArrayProperties(transaction2); - const txHash = await this.client.sendTransaction(resolved, { - chainId + return { ok: true }; +}; +var ValidateEOAProof = function(provider2, chainId, proof) { + return __awaiter(void 0, void 0, void 0, function() { + var messageDigest, address; + return __generator(this, function(_a2) { + messageDigest = proof.messageDigest(); + address = verifyMessage(messageDigest, proof.signature); + if (address.slice(0, 2) === "0x" && address.length === 42 && address.toLowerCase() === proof.address.toLowerCase()) { + return [2, { isValid: true, address: proof.address }]; + } else { + return [2, { isValid: false }]; + } }); - const provider2 = this.getProvider(chainId); - try { - const result = await new Promise((resolve) => { - const check = async function check2() { - const tx = await provider2.getTransaction(txHash); - if (tx !== null) { - return resolve(tx); + }); +}; +var ValidateContractAccountProof = function(provider2, chainId, proof) { + return __awaiter(void 0, void 0, void 0, function() { + var messageDigest, walletCode, abi2, contract, isValidSignature2; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + if (!provider2 || provider2 === void 0) { + return [2, { isValid: false }]; } - await provider2.once("block", check2); - }; - check(); - }); - return result; - } catch (err) { - err.transactionHash = txHash; - throw err; + messageDigest = proof.messageDigest(); + return [4, provider2.getCode(proof.address)]; + case 1: + walletCode = _a2.sent(); + if (walletCode === "0x" || walletCode.length <= 2) { + throw new Error("ValidateContractAccountProof failed. unable to fetch wallet contract code"); + } + abi2 = ["function isValidSignature(bytes32, bytes) public view returns (bytes4)"]; + contract = new Contract(proof.address, abi2, provider2); + return [4, contract.isValidSignature(messageDigest, getBytes(proof.signature))]; + case 2: + isValidSignature2 = _a2.sent(); + if (isValidSignature2 === IsValidSignatureBytes32MagicValue) { + return [2, { isValid: true, address: proof.address }]; + } else { + return [2, { isValid: false }]; + } + } + }); + }); +}; +var IsValidSignatureBytes32MagicValue = "0x1626ba7e"; +var ETHAuth = ( + /** @class */ + /* @__PURE__ */ function() { + function ETHAuth2() { + var validators = []; + for (var _i2 = 0; _i2 < arguments.length; _i2++) { + validators[_i2] = arguments[_i2]; + } + var _this = this; + this.configJsonRpcProvider = function(ethereumJsonRpcURL) { + return __awaiter(_this, void 0, void 0, function() { + var netVersion; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + this.provider = new JsonRpcProvider$1(ethereumJsonRpcURL); + return [4, this.provider.send("net_version", [])]; + case 1: + netVersion = _a2.sent(); + this.chainId = parseInt(netVersion); + if (!this.chainId) { + throw new Error("ethauth: unable to get chainId"); + } + this.ethereumJsonRpcURL = ethereumJsonRpcURL; + return [ + 2 + /*return*/ + ]; + } + }); + }); + }; + this.configValidators = function() { + var validators2 = []; + for (var _i3 = 0; _i3 < arguments.length; _i3++) { + validators2[_i3] = arguments[_i3]; + } + if (validators2.length == 0) { + throw new Error("validators list is empty"); + } + _this.validators = validators2; + }; + this.encodeProof = function(proof, skipSignatureValidation) { + if (skipSignatureValidation === void 0) { + skipSignatureValidation = false; + } + return __awaiter(_this, void 0, void 0, function() { + var isValid2, claimsJSON, proofString; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + if (proof.address.length !== 42 || proof.address.slice(0, 2) !== "0x") { + throw new Error("ethauth: invalid address"); + } + if (proof.signature === "" || proof.signature.slice(0, 2) !== "0x") { + throw new Error("ethauth: invalid signature"); + } + if (proof.extra && proof.extra.slice(0, 2) !== "0x") { + throw new Error("ethauth: invalid extra encoding, expecting hex data"); + } + return [4, this.validateProof(proof, skipSignatureValidation)]; + case 1: + isValid2 = _a2.sent(); + if (!isValid2) { + throw new Error("ethauth: proof is invalid"); + } + claimsJSON = JSON.stringify(proof.claims); + proofString = ETHAuthPrefix + "." + proof.address.toLowerCase() + "." + gBase64.encode(claimsJSON, true) + "." + proof.signature; + if (proof.extra && proof.extra.length > 0) { + proofString += "." + proof.extra; + } + return [2, proofString]; + } + }); + }); + }; + this.decodeProof = function(proofString, skipSignatureValidation) { + if (skipSignatureValidation === void 0) { + skipSignatureValidation = false; + } + return __awaiter(_this, void 0, void 0, function() { + var parts, prefix, address, messageBase64, signature2, extra, message, claims, proof, isValid2; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + parts = proofString.split("."); + if (parts.length < 4 || parts.length > 5) { + throw new Error("ethauth: invalid proof string"); + } + prefix = parts[0], address = parts[1], messageBase64 = parts[2], signature2 = parts[3], extra = parts[4]; + if (prefix !== ETHAuthPrefix) { + throw new Error("ethauth: not an ethauth proof"); + } + message = gBase64.decode(messageBase64); + claims = JSON.parse(message); + proof = new Proof({ address, claims, signature: signature2, extra }); + return [4, this.validateProof(proof, skipSignatureValidation)]; + case 1: + isValid2 = _a2.sent(); + if (!isValid2) { + throw new Error("ethauth: proof is invalid"); + } + return [2, proof]; + } + }); + }); + }; + this.validateProof = function(proof, skipSignatureValidation) { + if (skipSignatureValidation === void 0) { + skipSignatureValidation = false; + } + return __awaiter(_this, void 0, void 0, function() { + var isValidClaims, isValidSig; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + isValidClaims = this.validateProofClaims(proof); + if (isValidClaims.err) { + throw new Error("ethauth: proof claims are invalid ".concat(isValidClaims.err)); + } + if (!(skipSignatureValidation !== true)) return [3, 2]; + return [4, this.validateProofSignature(proof)]; + case 1: + isValidSig = _a2.sent(); + if (isValidSig !== true) { + throw new Error("ethauth: proof signature is invalid"); + } + _a2.label = 2; + case 2: + return [2, true]; + } + }); + }); + }; + this.validateProofSignature = function(proof) { + return __awaiter(_this, void 0, void 0, function() { + var retIsValid, i, validator, isValid2, i; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + retIsValid = []; + i = 0; + _a2.label = 1; + case 1: + if (!(i < this.validators.length)) return [3, 6]; + _a2.label = 2; + case 2: + _a2.trys.push([2, 4, , 5]); + validator = this.validators[i]; + return [4, validator(this.provider, this.chainId, proof)]; + case 3: + isValid2 = _a2.sent().isValid; + if (isValid2 === true) { + return [2, true]; + } + retIsValid.push(isValid2); + return [3, 5]; + case 4: + _a2.sent(); + retIsValid.push(false); + return [3, 5]; + case 5: + i++; + return [3, 1]; + case 6: + for (i = 0; i < retIsValid.length; i++) { + if (retIsValid[i]) { + return [2, true]; + } + } + return [2, false]; + } + }); + }); + }; + this.validateProofClaims = function(proof) { + return proof.validateClaims(); + }; + if (validators.length == 0) { + this.validators = [ValidateEOAProof, ValidateContractAccountProof]; + } else { + this.validators = validators; + } + } + return ETHAuth2; + }() +); +let ChainId = /* @__PURE__ */ function(ChainId2) { + ChainId2[ChainId2["MAINNET"] = 1] = "MAINNET"; + ChainId2[ChainId2["ROPSTEN"] = 3] = "ROPSTEN"; + ChainId2[ChainId2["RINKEBY"] = 4] = "RINKEBY"; + ChainId2[ChainId2["GOERLI"] = 5] = "GOERLI"; + ChainId2[ChainId2["KOVAN"] = 42] = "KOVAN"; + ChainId2[ChainId2["SEPOLIA"] = 11155111] = "SEPOLIA"; + ChainId2[ChainId2["POLYGON"] = 137] = "POLYGON"; + ChainId2[ChainId2["POLYGON_MUMBAI"] = 80001] = "POLYGON_MUMBAI"; + ChainId2[ChainId2["POLYGON_ZKEVM"] = 1101] = "POLYGON_ZKEVM"; + ChainId2[ChainId2["POLYGON_AMOY"] = 80002] = "POLYGON_AMOY"; + ChainId2[ChainId2["BSC"] = 56] = "BSC"; + ChainId2[ChainId2["BSC_TESTNET"] = 97] = "BSC_TESTNET"; + ChainId2[ChainId2["OPTIMISM"] = 10] = "OPTIMISM"; + ChainId2[ChainId2["OPTIMISM_KOVAN"] = 69] = "OPTIMISM_KOVAN"; + ChainId2[ChainId2["OPTIMISM_GOERLI"] = 420] = "OPTIMISM_GOERLI"; + ChainId2[ChainId2["OPTIMISM_SEPOLIA"] = 11155420] = "OPTIMISM_SEPOLIA"; + ChainId2[ChainId2["ARBITRUM"] = 42161] = "ARBITRUM"; + ChainId2[ChainId2["ARBITRUM_GOERLI"] = 421613] = "ARBITRUM_GOERLI"; + ChainId2[ChainId2["ARBITRUM_SEPOLIA"] = 421614] = "ARBITRUM_SEPOLIA"; + ChainId2[ChainId2["ARBITRUM_NOVA"] = 42170] = "ARBITRUM_NOVA"; + ChainId2[ChainId2["AVALANCHE"] = 43114] = "AVALANCHE"; + ChainId2[ChainId2["AVALANCHE_TESTNET"] = 43113] = "AVALANCHE_TESTNET"; + ChainId2[ChainId2["GNOSIS"] = 100] = "GNOSIS"; + ChainId2[ChainId2["BASE"] = 8453] = "BASE"; + ChainId2[ChainId2["BASE_GOERLI"] = 84531] = "BASE_GOERLI"; + ChainId2[ChainId2["BASE_SEPOLIA"] = 84532] = "BASE_SEPOLIA"; + ChainId2[ChainId2["HOMEVERSE_TESTNET"] = 40875] = "HOMEVERSE_TESTNET"; + ChainId2[ChainId2["HOMEVERSE"] = 19011] = "HOMEVERSE"; + ChainId2[ChainId2["XAI"] = 660279] = "XAI"; + ChainId2[ChainId2["XAI_SEPOLIA"] = 37714555429] = "XAI_SEPOLIA"; + ChainId2[ChainId2["ASTAR_ZKEVM"] = 3776] = "ASTAR_ZKEVM"; + ChainId2[ChainId2["ASTAR_ZKYOTO"] = 6038361] = "ASTAR_ZKYOTO"; + ChainId2[ChainId2["XR_SEPOLIA"] = 2730] = "XR_SEPOLIA"; + ChainId2[ChainId2["TELOS"] = 40] = "TELOS"; + ChainId2[ChainId2["B3_SEPOLIA"] = 1993] = "B3_SEPOLIA"; + ChainId2[ChainId2["APECHAIN_TESTNET"] = 33111] = "APECHAIN_TESTNET"; + ChainId2[ChainId2["BLAST"] = 81457] = "BLAST"; + ChainId2[ChainId2["BLAST_SEPOLIA"] = 168587773] = "BLAST_SEPOLIA"; + ChainId2[ChainId2["BORNE_TESTNET"] = 94984] = "BORNE_TESTNET"; + ChainId2[ChainId2["SKALE_NEBULA_TESTNET"] = 37084624] = "SKALE_NEBULA_TESTNET"; + ChainId2[ChainId2["HARDHAT"] = 31337] = "HARDHAT"; + ChainId2[ChainId2["HARDHAT_2"] = 31338] = "HARDHAT_2"; + return ChainId2; +}({}); +let NetworkType = /* @__PURE__ */ function(NetworkType2) { + NetworkType2["MAINNET"] = "mainnet"; + NetworkType2["TESTNET"] = "testnet"; + return NetworkType2; +}({}); +const networks = { + [ChainId.MAINNET]: { + chainId: ChainId.MAINNET, + type: NetworkType.MAINNET, + name: "mainnet", + title: "Ethereum", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.MAINNET}.webp`, + blockExplorer: { + name: "Etherscan", + rootUrl: "https://etherscan.io/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 + }, + ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e" + }, + [ChainId.ROPSTEN]: { + chainId: ChainId.ROPSTEN, + type: NetworkType.TESTNET, + name: "ropsten", + title: "Ropsten", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ROPSTEN}.webp`, + testnet: true, + blockExplorer: { + name: "Etherscan (Ropsten)", + rootUrl: "https://ropsten.etherscan.io/" + }, + nativeToken: { + symbol: "roETH", + name: "Ropsten Ether", + decimals: 18 + }, + ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + deprecated: true + }, + [ChainId.RINKEBY]: { + chainId: ChainId.RINKEBY, + type: NetworkType.TESTNET, + name: "rinkeby", + title: "Rinkeby", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.RINKEBY}.webp`, + testnet: true, + blockExplorer: { + name: "Etherscan (Rinkeby)", + rootUrl: "https://rinkeby.etherscan.io/" + }, + nativeToken: { + symbol: "rETH", + name: "Rinkeby Ether", + decimals: 18 + }, + ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + deprecated: true + }, + [ChainId.GOERLI]: { + chainId: ChainId.GOERLI, + type: NetworkType.TESTNET, + name: "goerli", + title: "Goerli", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.GOERLI}.webp`, + testnet: true, + blockExplorer: { + name: "Etherscan (Goerli)", + rootUrl: "https://goerli.etherscan.io/" + }, + nativeToken: { + symbol: "gETH", + name: "Goerli Ether", + decimals: 18 + }, + ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + deprecated: true + }, + [ChainId.KOVAN]: { + chainId: ChainId.KOVAN, + type: NetworkType.TESTNET, + name: "kovan", + title: "Kovan", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.KOVAN}.webp`, + testnet: true, + blockExplorer: { + name: "Etherscan (Kovan)", + rootUrl: "https://kovan.etherscan.io/" + }, + nativeToken: { + symbol: "kETH", + name: "Kovan Ether", + decimals: 18 + }, + deprecated: true + }, + [ChainId.SEPOLIA]: { + chainId: ChainId.SEPOLIA, + type: NetworkType.TESTNET, + name: "sepolia", + title: "Sepolia", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.SEPOLIA}.webp`, + testnet: true, + blockExplorer: { + name: "Etherscan (Sepolia)", + rootUrl: "https://sepolia.etherscan.io/" + }, + nativeToken: { + symbol: "sETH", + name: "Sepolia Ether", + decimals: 18 + } + }, + [ChainId.POLYGON]: { + chainId: ChainId.POLYGON, + type: NetworkType.MAINNET, + name: "polygon", + title: "Polygon", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.POLYGON}.webp`, + blockExplorer: { + name: "Polygonscan", + rootUrl: "https://polygonscan.com/" + }, + nativeToken: { + symbol: "POL", + name: "POL", + decimals: 18 } - } - async getWalletConfig(chainId) { - const useChainId2 = this.useChainId(chainId); - return this.client.getOnchainWalletConfig({ - chainId: useChainId2 - }); - } - getNetworks() { - return this.client.getNetworks(); - } - async getBalance(blockTag, optionals) { - const provider2 = this.getProvider(optionals == null ? void 0 : optionals.chainId); - return provider2.getBalance(this.getAddress(), blockTag); - } - async estimateGas(transaction2, optionals) { - return this.getProvider(optionals == null ? void 0 : optionals.chainId).estimateGas(transaction2); - } - async call(transaction2, optionals) { - return this.getProvider(optionals == null ? void 0 : optionals.chainId).call(transaction2); - } - getChainId() { - return Promise.resolve(this.client.getChainId()); - } - async getFeeData(optionals) { - return this.getProvider(optionals == null ? void 0 : optionals.chainId).getFeeData(); - } - async resolveName(name2) { - const res = await this.provider.resolveName(name2); - if (res === null) { - throw new Error(`ENS name not found: ${name2}`); + }, + [ChainId.POLYGON_MUMBAI]: { + chainId: ChainId.POLYGON_MUMBAI, + type: NetworkType.TESTNET, + name: "mumbai", + title: "Polygon Mumbai", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.POLYGON_MUMBAI}.webp`, + testnet: true, + blockExplorer: { + name: "Polygonscan (Mumbai)", + rootUrl: "https://mumbai.polygonscan.com/" + }, + nativeToken: { + symbol: "mMATIC", + name: "Mumbai Polygon", + decimals: 18 + }, + deprecated: true + }, + [ChainId.POLYGON_AMOY]: { + chainId: ChainId.POLYGON_AMOY, + type: NetworkType.TESTNET, + name: "amoy", + title: "Polygon Amoy", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.POLYGON_AMOY}.webp`, + testnet: true, + blockExplorer: { + name: "OKLink (Amoy)", + rootUrl: "https://www.oklink.com/amoy/" + }, + nativeToken: { + symbol: "aPOL", + name: "Amoy POL", + decimals: 18 } - return res; - } - _checkProvider(_operation) { - } - getNonce(_blockTag) { - throw new Error("SequenceSigner does not support getNonce"); - } - populateCall(_transaction) { - throw new Error("SequenceSigner does not support populateCall"); - } - populateTransaction(_transaction) { - throw new Error("SequenceSigner does not support populateTransaction"); - } - checkTransaction(_transaction) { - throw new Error("SequenceSigner does not support checkTransaction"); - } - getTransactionCount(_blockTag) { - throw new Error("SequenceSigner does not support getTransactionCount"); - } - signTransaction(_transaction) { - throw new Error("SequenceWallet does not support signTransaction, use sendTransaction instead."); - } - static is(cand) { - return cand && typeof cand === "object" && cand._isSequenceSigner === true; - } -} -class SingleNetworkSequenceSigner extends SequenceSigner { - constructor(client2, provider2, chainId) { - super(client2, provider2.getProvider(chainId)); - this.chainId = chainId; - this._isSingleNetworkSequenceSigner = true; - } - _useChainId(chainId) { - const provided = this.provider.toChainId(chainId); - if (provided && provided !== this.chainId) { - throw new Error(`This signer only supports the network ${this.chainId}, but ${provided} was requested.`); + }, + [ChainId.POLYGON_ZKEVM]: { + chainId: ChainId.POLYGON_ZKEVM, + type: NetworkType.MAINNET, + name: "polygon-zkevm", + title: "Polygon zkEVM", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.POLYGON_ZKEVM}.webp`, + blockExplorer: { + name: "Polygonscan (zkEVM)", + rootUrl: "https://zkevm.polygonscan.com/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - return provided || this.provider.toChainId(this.chainId); - } - useChainId(chainId) { - return this._useChainId(chainId); - } - getChainId() { - return Promise.resolve(this.provider.toChainId(this.chainId)); - } - /** - * Override getProvider and getSigner so they always use `useChainId` - * this way they can't return providers and signers that can switch networks, - * or that don't match the chainId of this signer. - */ - getProvider(chainId) { - return super.getProvider(this._useChainId(chainId)); - } - getSigner(chainId) { - if (this._useChainId(chainId) !== this.chainId) { - throw new Error(`Unreachable code`); + }, + [ChainId.BSC]: { + chainId: ChainId.BSC, + type: NetworkType.MAINNET, + name: "bsc", + title: "BNB Smart Chain", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BSC}.webp`, + blockExplorer: { + name: "BSCScan", + rootUrl: "https://bscscan.com/" + }, + nativeToken: { + symbol: "BNB", + name: "BNB", + decimals: 18 } - return this; - } - static is(cand) { - return cand && typeof cand === "object" && cand._isSingleNetworkSequenceSigner === true; - } -} -class WalletUtils { - constructor(signer2) { - this.signer = signer2; - if (SingleNetworkSequenceSigner.is(signer2)) { - throw new Error("WalletUtils does not support SingleNetworkSequenceSigner"); + }, + [ChainId.BSC_TESTNET]: { + chainId: ChainId.BSC_TESTNET, + type: NetworkType.TESTNET, + name: "bsc-testnet", + title: "BNB Smart Chain Testnet", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BSC_TESTNET}.webp`, + testnet: true, + blockExplorer: { + name: "BSCScan (Testnet)", + rootUrl: "https://testnet.bscscan.com/" + }, + nativeToken: { + symbol: "tBNB", + name: "Testnet BNB", + decimals: 18 } - } - // Sign message on a specified chain, or DefaultChain by default - signMessage(message, chainId, eip6492) { - return this.signer.signMessage(message, { - chainId, - eip6492 - }); - } - // Sign EIP-712 TypedData on a specified chain, or DefaultChain by default - signTypedData(domain2, types2, message, chainId, eip6492) { - return this.signer.signTypedData(domain2, types2, message, { - chainId, - eip6492 - }); - } - // Verify signature of a digest, one of a message, typedData or other - async isValidSignature(address, digest, signature2, chainId) { - return isValidSignature(address, digest, signature2, this.signer.getProvider(chainId)); - } - // Verify message signature - async isValidMessageSignature(address, message, signature2, chainId) { - const provider2 = this.signer.getProvider(chainId); - const prefixed = prefixEIP191Message(message); - const digest = encodeMessageDigest(prefixed); - return isValidSignature(address, digest, signature2, provider2); - } - // Verify typedData signature - isValidTypedDataSignature(address, typedData, signature2, chainId) { - return this.isValidSignature(address, encodeTypedDataDigest(typedData), signature2, chainId); - } - // sendTransaction() - // sendTransactions() - // sendETH() - // sendToken() - // sendCoin() -- sugar for sendToken() - // sendCollectible() -- sugar for sendToken() - // callContract() - // transactionHistory() - // getReceipt() - // getLogs() - // // .. - // validateSignature() - // recoverWalletConfig() - // recoverAddress() -} -const _excluded$5 = ["method"]; -const EIP1193EventTypes = ["connect", "disconnect", "chainChanged", "accountsChanged"]; -class SequenceProvider extends AbstractProvider { - constructor(client2, providerFor, networks2 = allNetworks, options) { - super(client2.getChainId(), options); - this.client = client2; - this.providerFor = providerFor; - this.networks = networks2; - this.options = options; - this.singleNetworkProviders = {}; - this._isSequenceProvider = true; - this.utils = void 0; - this.signer = void 0; - this.eip1193EventListeners = /* @__PURE__ */ new Map(); - client2.onConnect((details) => { - var _this$eip1193EventLis; - (_this$eip1193EventLis = this.eip1193EventListeners.get("connect")) == null || _this$eip1193EventLis.forEach((listener) => listener(details)); - }); - client2.onDisconnect((error) => { - var _this$eip1193EventLis2; - (_this$eip1193EventLis2 = this.eip1193EventListeners.get("disconnect")) == null || _this$eip1193EventLis2.forEach((listener) => listener(error)); - }); - client2.onDefaultChainIdChanged((chainId) => { - var _this$eip1193EventLis3; - (_this$eip1193EventLis3 = this.eip1193EventListeners.get("chainChanged")) == null || _this$eip1193EventLis3.forEach((listener) => listener(chainId)); - }); - client2.onAccountsChanged((accounts) => { - var _this$eip1193EventLis4; - (_this$eip1193EventLis4 = this.eip1193EventListeners.get("accountsChanged")) == null || _this$eip1193EventLis4.forEach((listener) => listener(accounts)); - }); - this.signer = new SequenceSigner(this.client, this); - this.utils = new WalletUtils(this.signer); - } - async on(event, listener) { - if (EIP1193EventTypes.includes(event)) { - const listeners = this.eip1193EventListeners.get(event) || /* @__PURE__ */ new Set(); - listeners.add(listener); - this.eip1193EventListeners.set(event, listeners); - return this; + }, + [ChainId.OPTIMISM]: { + chainId: ChainId.OPTIMISM, + type: NetworkType.MAINNET, + name: "optimism", + title: "Optimism", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.OPTIMISM}.webp`, + blockExplorer: { + name: "Etherscan (Optimism)", + rootUrl: "https://optimistic.etherscan.io/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - return super.on(event, listener); - } - async off(event, listener) { - if (EIP1193EventTypes.includes(event)) { - const listeners = this.eip1193EventListeners.get(event); - if (listeners) { - if (listener) { - listeners.delete(listener); - } else { - listeners.clear(); - } - } - return this; + }, + [ChainId.OPTIMISM_KOVAN]: { + chainId: ChainId.OPTIMISM_KOVAN, + type: NetworkType.TESTNET, + name: "optimism-kovan", + title: "Optimism Kovan", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.OPTIMISM_KOVAN}.webp`, + testnet: true, + blockExplorer: { + name: "Etherscan (Optimism Kovan)", + rootUrl: "https://kovan-optimistic.etherscan.io/" + }, + nativeToken: { + symbol: "kETH", + name: "Kovan Ether", + decimals: 18 + }, + deprecated: true + }, + [ChainId.OPTIMISM_GOERLI]: { + chainId: ChainId.OPTIMISM_GOERLI, + type: NetworkType.TESTNET, + name: "optimism-goerli", + title: "Optimism Goerli", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.OPTIMISM_GOERLI}.webp`, + testnet: true, + blockExplorer: { + name: "Etherscan (Optimism Goerli)", + rootUrl: "https://goerli-optimistic.etherscan.io/" + }, + nativeToken: { + symbol: "gETH", + name: "Goerli Ether", + decimals: 18 + }, + deprecated: true + }, + [ChainId.OPTIMISM_SEPOLIA]: { + chainId: ChainId.OPTIMISM_SEPOLIA, + type: NetworkType.TESTNET, + name: "optimism-sepolia", + title: "Optimism Sepolia", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.OPTIMISM_SEPOLIA}.webp`, + testnet: true, + blockExplorer: { + name: "Etherscan (Optimism Sepolia)", + rootUrl: "https://sepolia-optimistic.etherscan.io/" + }, + nativeToken: { + symbol: "sETH", + name: "Sepolia Ether", + decimals: 18 } - return super.off(event, listener); - } - getSigner(chainId) { - return this.signer.getSigner(chainId); - } - connect(options) { - return this.client.connect(options); - } - disconnect() { - return this.client.disconnect(); - } - isConnected() { - return this.client.isConnected(); - } - getSession() { - return this.client.getSession(); - } - listAccounts() { - return [this.client.getAddress()]; - } - // @deprecated use getSigner() instead - getAddress() { - return this.client.getAddress(); - } - getNetworks() { - return this.client.getNetworks(); - } - getChainId() { - return this.client.getChainId(); - } - setDefaultChainId(chainId) { - return this.client.setDefaultChainId(this.toChainId(chainId)); - } - isOpened() { - return this.client.isOpened(); - } - closeWallet() { - return this.client.closeWallet(); - } - getWalletContext() { - return this.client.getWalletContext(); - } - // @deprecated use getSigner() instead - async getWalletConfig(chainId) { - const useChainId2 = await this.useChainId(chainId); - return this.client.getOnchainWalletConfig({ - chainId: useChainId2 - }); - } - authorize(options) { - return this.client.connect(_extends$2({}, options, { - authorize: true - })); - } - async openWallet(path, intent) { - await this.client.openWallet(path, intent); - return true; - } - toChainId(chainId) { - if (chainId === void 0) { - return void 0; + }, + [ChainId.ARBITRUM]: { + chainId: ChainId.ARBITRUM, + type: NetworkType.MAINNET, + name: "arbitrum", + title: "Arbitrum One", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ARBITRUM}.webp`, + blockExplorer: { + name: "Arbiscan", + rootUrl: "https://arbiscan.io/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - const resolved = findNetworkConfig(this.networks, chainId); - if (!resolved) { - throw new Error(`Unsupported network ${chainId}`); + }, + [ChainId.ARBITRUM_GOERLI]: { + chainId: ChainId.ARBITRUM_GOERLI, + type: NetworkType.TESTNET, + name: "arbitrum-goerli", + title: "Arbitrum Goerli", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ARBITRUM_GOERLI}.webp`, + testnet: true, + blockExplorer: { + name: "Arbiscan (Goerli Testnet)", + rootUrl: "https://testnet.arbiscan.io/" + }, + nativeToken: { + symbol: "gETH", + name: "Goerli Ether", + decimals: 18 + }, + deprecated: true + }, + [ChainId.ARBITRUM_SEPOLIA]: { + chainId: ChainId.ARBITRUM_SEPOLIA, + type: NetworkType.TESTNET, + name: "arbitrum-sepolia", + title: "Arbitrum Sepolia", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ARBITRUM_SEPOLIA}.webp`, + testnet: true, + blockExplorer: { + name: "Arbiscan (Sepolia Testnet)", + rootUrl: "https://sepolia.arbiscan.io/" + }, + nativeToken: { + symbol: "sETH", + name: "Sepolia Ether", + decimals: 18 } - return resolved.chainId; - } - /** - * Resolves the chainId to use for the given request. If no chainId is provided, - * it uses the chainId defined by the client (default chainId). This can be - * overriden to build a single-network SequenceProvider. - */ - async useChainId(chainId) { - return this.toChainId(chainId) || this.client.getChainId(); - } - /** - * This generates a provider that ONLY works for the given chainId. - * the generated provider can't switch networks, and can't handle requests - * for other networks. - */ - getProvider(chainId) { - if (!chainId) { - return this; + }, + [ChainId.ARBITRUM_NOVA]: { + chainId: ChainId.ARBITRUM_NOVA, + type: NetworkType.MAINNET, + name: "arbitrum-nova", + title: "Arbitrum Nova", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ARBITRUM_NOVA}.webp`, + blockExplorer: { + name: "Arbiscan Nova", + rootUrl: "https://nova.arbiscan.io/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 + } + }, + [ChainId.AVALANCHE]: { + chainId: ChainId.AVALANCHE, + type: NetworkType.MAINNET, + name: "avalanche", + title: "Avalanche", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.AVALANCHE}.webp`, + blockExplorer: { + name: "Snowtrace", + rootUrl: "https://subnets.avax.network/c-chain/" + }, + nativeToken: { + symbol: "AVAX", + name: "AVAX", + decimals: 18 } - const useChainId2 = this.toChainId(chainId); - if (!this.singleNetworkProviders[useChainId2]) { - this.singleNetworkProviders[useChainId2] = new SingleNetworkSequenceProvider(this.client, this.providerFor, useChainId2, this.options); + }, + [ChainId.AVALANCHE_TESTNET]: { + chainId: ChainId.AVALANCHE_TESTNET, + type: NetworkType.TESTNET, + name: "avalanche-testnet", + title: "Avalanche Testnet", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.AVALANCHE_TESTNET}.webp`, + testnet: true, + blockExplorer: { + name: "Snowtrace (Testnet)", + rootUrl: "https://subnets-test.avax.network/c-chain/" + }, + nativeToken: { + symbol: "tAVAX", + name: "Testnet AVAX", + decimals: 18 } - return this.singleNetworkProviders[useChainId2]; - } - /** - * This returns a subprovider, this is a regular non-sequence provider that - * can be used to fulfill read only requests on a given network. - */ - async _getSubprovider(chainId) { - const useChainId2 = await this.useChainId(chainId); - const provider2 = this.providerFor(useChainId2); - if (!provider2) { - throw new Error(`Unsupported network ${useChainId2}`); + }, + [ChainId.GNOSIS]: { + chainId: ChainId.GNOSIS, + type: NetworkType.MAINNET, + name: "gnosis", + title: "Gnosis Chain", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.GNOSIS}.webp`, + blockExplorer: { + name: "Gnosis Chain Explorer", + rootUrl: "https://blockscout.com/xdai/mainnet/" + }, + nativeToken: { + symbol: "XDAI", + name: "XDAI", + decimals: 18 } - return provider2; - } - async _perform(req) { - var _provider$getRpcReque; - const { - method - } = req, args = _objectWithoutPropertiesLoose$3(req, _excluded$5); - const provider2 = await this._getSubprovider(); - const prepared = (_provider$getRpcReque = provider2.getRpcRequest(req)) != null ? _provider$getRpcReque : { - method, - args: Object.values(args) - }; - if (!prepared) { - throw new Error(`Unsupported method ${req.method}`); + }, + [ChainId.BASE]: { + chainId: ChainId.BASE, + type: NetworkType.MAINNET, + name: "base", + title: "Base (Coinbase)", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BASE}.webp`, + blockExplorer: { + name: "Base Explorer", + rootUrl: "https://basescan.org/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - return provider2.send(prepared.method, prepared.args); - } - async perform(method, params) { - if (method === "eth_chainId") { - return toQuantity(await this.useChainId()); + }, + [ChainId.BASE_GOERLI]: { + chainId: ChainId.BASE_GOERLI, + type: NetworkType.TESTNET, + name: "base-goerli", + title: "Base Goerli", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BASE_GOERLI}.webp`, + testnet: true, + blockExplorer: { + name: "Base Goerli Explorer", + rootUrl: "https://goerli.basescan.org/" + }, + nativeToken: { + symbol: "gETH", + name: "Goerli Ether", + decimals: 18 + }, + deprecated: true + }, + [ChainId.BASE_SEPOLIA]: { + chainId: ChainId.BASE_SEPOLIA, + type: NetworkType.TESTNET, + name: "base-sepolia", + title: "Base Sepolia", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BASE_SEPOLIA}.webp`, + testnet: true, + blockExplorer: { + name: "Base Sepolia Explorer", + rootUrl: "https://base-sepolia.blockscout.com/" + }, + nativeToken: { + symbol: "sETH", + name: "Sepolia Ether", + decimals: 18 } - if (method === "eth_accounts") { - return [this.client.getAddress()]; + }, + [ChainId.HOMEVERSE]: { + chainId: ChainId.HOMEVERSE, + type: NetworkType.MAINNET, + name: "homeverse", + title: "Oasys Homeverse", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.HOMEVERSE}.webp`, + blockExplorer: { + name: "Oasys Homeverse Explorer", + rootUrl: "https://explorer.oasys.homeverse.games/" + }, + nativeToken: { + symbol: "OAS", + name: "OAS", + decimals: 18 } - if (method === "wallet_switchEthereumChain") { - const args = params[0]; - const chainId = normalizeChainId$2(args); - return this.setDefaultChainId(chainId); + }, + [ChainId.HOMEVERSE_TESTNET]: { + chainId: ChainId.HOMEVERSE_TESTNET, + type: NetworkType.TESTNET, + name: "homeverse-testnet", + title: "Oasys Homeverse Testnet", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.HOMEVERSE_TESTNET}.webp`, + testnet: true, + blockExplorer: { + name: "Oasys Homeverse Explorer (Testnet)", + rootUrl: "https://explorer.testnet.oasys.homeverse.games/" + }, + nativeToken: { + symbol: "tOAS", + name: "Testnet OAS", + decimals: 18 } - if (method === "eth_sendTransaction" || method === "eth_sign" || method === "eth_signTypedData" || method === "eth_signTypedData_v4" || method === "personal_sign" || // These methods will use EIP-6492 - // but this is handled directly by the wallet - method === "sequence_sign" || method === "sequence_signTypedData_v4") { - return this.client.request({ - method, - params, - chainId: this.getChainId() - }); + }, + [ChainId.XAI]: { + chainId: ChainId.XAI, + type: NetworkType.MAINNET, + name: "xai", + title: "Xai", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.XAI}.webp`, + blockExplorer: { + name: "Xai Explorer", + rootUrl: "https://explorer.xai-chain.net/" + }, + nativeToken: { + symbol: "XAI", + name: "XAI", + decimals: 18 } - return this._perform(_extends$2({ - method - }, params)); - } - send(method, params) { - return this.perform(method, params); - } - request(request) { - return this.perform(request.method, request.params); - } - async _detectNetwork() { - const chainId = this.client.getChainId(); - const found = findNetworkConfig(this.networks, chainId); - if (!found) { - throw new Error(`Unknown network ${chainId}`); + }, + [ChainId.XAI_SEPOLIA]: { + chainId: ChainId.XAI_SEPOLIA, + type: NetworkType.TESTNET, + name: "xai-sepolia", + title: "Xai Sepolia", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.XAI_SEPOLIA}.webp`, + testnet: true, + blockExplorer: { + name: "Xai Sepolia Explorer", + rootUrl: "https://testnet-explorer-v2.xai-chain.net/" + }, + nativeToken: { + symbol: "sXAI", + name: "Sepolia XAI", + decimals: 18 } - const network2 = new Network(found.name, found.chainId); - return network2; - } - async detectNetwork() { - return this._detectNetwork(); - } - // Override most of the methods, so we add support for an optional chainId - // argument, which is used to select the provider to use. - // - // NOTICE: We could use generics to avoid repeating the same code - // but this would make the code harder to read, and it's not worth it - // since we only have a few methods to override. - async waitForTransaction(transactionHash, confirmations, timeout, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.waitForTransaction(transactionHash, confirmations, timeout); - } - async getBlockNumber(optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.getBlockNumber(); - } - async getFeeData(optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.getFeeData(); - } - async getBalance(addressOrName, blockTag, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.getBalance(addressOrName, blockTag); - } - async getTransactionCount(addressOrName, blockTag, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.getTransactionCount(addressOrName, blockTag); - } - async getCode(addressOrName, blockTag, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.getCode(addressOrName, blockTag); - } - async getStorage(addressOrName, position, blockTag, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.getStorage(addressOrName, position, blockTag); - } - async call(transaction2, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.call(transaction2); - } - async estimateGas(transaction2, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.estimateGas(transaction2); - } - async getBlock(blockHashOrBlockTag, prefetchTxs, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.getBlock(blockHashOrBlockTag, prefetchTxs); - } - async getTransaction(transactionHash, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.getTransaction(transactionHash); - } - async getLogs(filter2, optionals) { - const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); - return provider2.getLogs(filter2); - } - // ENS methods - async supportsENS() { - const networks2 = await this.getNetworks(); - return networks2.some((n2) => n2.chainId === 1); - } - async getResolver(name2) { - if (!await this.supportsENS()) { - return null; + }, + [ChainId.ASTAR_ZKEVM]: { + chainId: ChainId.ASTAR_ZKEVM, + type: NetworkType.MAINNET, + name: "astar-zkevm", + title: "Astar zkEVM", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ASTAR_ZKEVM}.webp`, + blockExplorer: { + name: "Astar zkEVM Explorer", + rootUrl: "https://astar-zkevm.explorer.startale.com/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - const provider2 = await this._getSubprovider(1); - return provider2.getResolver(name2); - } - async resolveName(name2) { - if (isAddress$1(name2)) { - return name2; + }, + [ChainId.ASTAR_ZKYOTO]: { + chainId: ChainId.ASTAR_ZKYOTO, + type: NetworkType.TESTNET, + name: "astar-zkyoto", + title: "Astar zKyoto Testnet", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.ASTAR_ZKYOTO}.webp`, + testnet: true, + blockExplorer: { + name: "Astar zKyoto Explorer", + rootUrl: "https://astar-zkyoto.blockscout.com/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - if (!await this.supportsENS()) { - return null; + }, + [ChainId.XR_SEPOLIA]: { + chainId: ChainId.XR_SEPOLIA, + type: NetworkType.TESTNET, + name: "xr-sepolia", + title: "XR Sepolia", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.XR_SEPOLIA}.webp`, + testnet: true, + blockExplorer: { + name: "XR Sepolia Explorer", + rootUrl: "https://xr-sepolia-testnet.explorer.caldera.xyz/" + }, + nativeToken: { + symbol: "tXR", + name: "Sepolia XR", + decimals: 18 } - const provider2 = await this._getSubprovider(1); - return provider2.resolveName(name2); - } - async lookupAddress(address) { - if (!await this.supportsENS()) { - return null; + }, + [ChainId.B3_SEPOLIA]: { + chainId: ChainId.B3_SEPOLIA, + type: NetworkType.TESTNET, + name: "b3-sepolia", + title: "B3 Sepolia", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.B3_SEPOLIA}.webp`, + testnet: true, + blockExplorer: { + name: "B3 Sepolia Explorer", + rootUrl: "https://sepolia.explorer.b3.fun/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - const provider2 = await this._getSubprovider(1); - return provider2.lookupAddress(address); - } - async getAvatar(nameOrAddress) { - if (!await this.supportsENS()) { - return null; + }, + [ChainId.APECHAIN_TESTNET]: { + chainId: ChainId.APECHAIN_TESTNET, + type: NetworkType.TESTNET, + name: "apechain-testnet", + title: "APE Chain Testnet", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.APECHAIN_TESTNET}.webp`, + testnet: true, + blockExplorer: { + name: "APE Chain Explorer", + rootUrl: "https://curtis.explorer.caldera.xyz/" + }, + nativeToken: { + symbol: "APE", + name: "ApeCoin", + decimals: 18 } - const provider2 = await this._getSubprovider(1); - return provider2.getAvatar(nameOrAddress); - } -} -SequenceProvider.is = (provider2) => { - return provider2 && typeof provider2 === "object" && provider2._isSequenceProvider === true; -}; -function normalizeChainId$2(chainId) { - if (typeof chainId === "object") return normalizeChainId$2(chainId.chainId); - return Number(chainId); -} -class SingleNetworkSequenceProvider extends SequenceProvider { - constructor(client2, providerFor, chainId, options) { - super(client2, providerFor, void 0, options); - this.chainId = chainId; - this._isSingleNetworkSequenceProvider = true; - } - _useChainId(chainId) { - const provided = this.toChainId(chainId); - if (provided && provided !== this.chainId) { - throw new Error(`This provider only supports the network ${this.chainId}, but ${provided} was requested.`); + }, + [ChainId.BLAST]: { + chainId: ChainId.BLAST, + type: NetworkType.MAINNET, + name: "blast", + title: "Blast", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BLAST}.webp`, + blockExplorer: { + name: "Blast Explorer", + rootUrl: "https://blastscan.io/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - return provided || super.toChainId(this.chainId); - } - useChainId(chainId) { - return Promise.resolve(this._useChainId(chainId)); - } - getChainId() { - return super.toChainId(this.chainId); - } - async getNetwork() { - const networks2 = await this.client.getNetworks(); - const found = findNetworkConfig(networks2, this.chainId); - if (!found) { - throw new Error(`Unsupported network ${this.chainId}`); + }, + [ChainId.BLAST_SEPOLIA]: { + chainId: ChainId.BLAST_SEPOLIA, + type: NetworkType.TESTNET, + name: "blast-sepolia", + title: "Blast Sepolia", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BLAST_SEPOLIA}.webp`, + testnet: true, + blockExplorer: { + name: "Blast Sepolia Explorer", + rootUrl: "https://sepolia.blastexplorer.io/" + }, + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - return new Network(found.name, found.chainId); - } - /** - * Override getProvider and getSigner so they always use `useChainId` - * this way they can't return providers and signers that can switch networks, - * or that don't match the chainId of this signer. - */ - getProvider(chainId) { - if (this._useChainId(chainId) !== this.chainId) { - throw new Error(`Unreachable code`); + }, + [ChainId.TELOS]: { + chainId: ChainId.TELOS, + type: NetworkType.MAINNET, + name: "telos", + title: "Telos", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.TELOS}.webp`, + blockExplorer: { + name: "Telos Explorer", + rootUrl: "https://explorer.telos.net/network/" + }, + nativeToken: { + symbol: "TLOS", + name: "TLOS", + decimals: 18 } - return this; - } - getSigner(chainId) { - return super.getSigner(this._useChainId(chainId)); - } - setDefaultChainId(_chainId4) { - throw new Error(`This provider only supports the network ${this.chainId}; use the parent provider to switch networks.`); - } - static is(cand) { - return cand && typeof cand === "object" && cand._isSingleNetworkSequenceProvider === true; - } -} -class Analytics extends Databeat2 { -} -const setupAnalytics = (projectAccessKey2, server) => { - if (!server) { - server = "https://nodes.sequence.app"; - } - const noop2 = !projectAccessKey2; - const auth2 = {}; - if (projectAccessKey2) { - auth2.headers = { - "X-Access-Key": projectAccessKey2 - }; - } - return new Analytics(server, auth2, { - noop: noop2, - defaultEnabled: true, - privacy: { - userIdHash: true, - userAgentSalt: false + }, + [ChainId.BORNE_TESTNET]: { + chainId: ChainId.BORNE_TESTNET, + type: NetworkType.TESTNET, + name: "borne-testnet", + title: "Borne Testnet", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.BORNE_TESTNET}.webp`, + testnet: true, + blockExplorer: { + name: "Borne Testnet Explorer", + rootUrl: "https://subnets-test.avax.network/bornegfdn" + }, + nativeToken: { + symbol: "BORNE", + name: "BORNE", + decimals: 18 + } + }, + [ChainId.SKALE_NEBULA_TESTNET]: { + chainId: ChainId.SKALE_NEBULA_TESTNET, + type: NetworkType.TESTNET, + name: "skale-nebula-testnet", + title: "SKALE Nebula Gaming Hub Testnet", + logoURI: `https://assets.sequence.info/images/networks/medium/${ChainId.SKALE_NEBULA_TESTNET}.webp`, + testnet: true, + blockExplorer: { + name: "SKALE Nebula Gaming Hub Testnet Explorer", + rootUrl: "https://lanky-ill-funny-testnet.explorer.testnet.skalenodes.com/" }, - initProps: () => { - if (!isBrowser()) { - return {}; - } else { - return { - origin: window.location.origin - }; - } + nativeToken: { + symbol: "sFUEL", + name: "SKALE Fuel", + decimals: 18 } - }); -}; -class SequenceClientSession { - constructor(store) { - this.store = store; - } - connectedSession() { - const session = this.getSession(); - if (session && session.accountAddress && session.walletContext && session.networks) { - return { - accountAddress: session.accountAddress, - walletContext: session.walletContext, - networks: session.networks - }; + }, + [ChainId.HARDHAT]: { + chainId: ChainId.HARDHAT, + name: "hardhat", + title: "Hardhat (local testnet)", + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - throw new Error("Sequence session not connected"); - } - hasSession() { - var _this$getSession; - return ((_this$getSession = this.getSession()) == null ? void 0 : _this$getSession.accountAddress) !== void 0; - } - setSession(session) { - return this.store.setItem(SequenceClientSession.SESSION_LOCALSTORE_KEY, JSON.stringify(session)); - } - getSession() { - const session = this.store.getItem(SequenceClientSession.SESSION_LOCALSTORE_KEY); - if (session) { - return JSON.parse(session); + }, + [ChainId.HARDHAT_2]: { + chainId: ChainId.HARDHAT_2, + name: "hardhat2", + title: "Hardhat (local testnet)", + nativeToken: { + symbol: "ETH", + name: "Ether", + decimals: 18 } - return void 0; - } - async clearSession() { - return this.store.removeItem(SequenceClientSession.SESSION_LOCALSTORE_KEY); } +}; +function getDefaultExportFromCjs(x2) { + return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2; } -SequenceClientSession.SESSION_LOCALSTORE_KEY = "@sequence.session"; -class DefaultChainIdTracker { - constructor(store, startingChainId = 1) { - this.store = store; - this.startingChainId = startingChainId; - this.callbacks = []; - store.onItemChange(DefaultChainIdTracker.SESSION_CHAIN_ID_KEY, (value) => { - if (value) { - const chainId = parseInt(value); - this.callbacks.forEach((cb2) => cb2(chainId)); - } - }); - } - onDefaultChainIdChanged(callback) { - this.callbacks.push(callback); - return () => { - this.callbacks = this.callbacks.filter((cb2) => cb2 !== callback); - }; - } - setDefaultChainId(chainId) { - if (chainId !== this.getDefaultChainId()) { - this.store.setItem(DefaultChainIdTracker.SESSION_CHAIN_ID_KEY, chainId.toString()); - } - } - getDefaultChainId() { - const read = this.store.getItem(DefaultChainIdTracker.SESSION_CHAIN_ID_KEY); - if (!read || read.length === 0) { - return this.startingChainId; - } - return parseInt(read); - } +var browser$1 = { exports: {} }; +var process = browser$1.exports = {}; +var cachedSetTimeout; +var cachedClearTimeout; +function defaultSetTimout() { + throw new Error("setTimeout has not been defined"); } -DefaultChainIdTracker.SESSION_CHAIN_ID_KEY = "@sequence.session.defaultChainId"; -class SequenceClient { - constructor(transport, store, options) { - var _options$defaultEIP, _this$session$getSess; - this.session = void 0; - this.defaultChainId = void 0; - this.callbacks = {}; - this.transport = void 0; - this.defaultEIP6492 = void 0; - this.projectAccessKey = void 0; - this.analytics = void 0; - if (isMuxTransportTemplate(transport)) { - this.transport = MuxMessageProvider.new(transport); - } else if (isProviderTransport(transport)) { - this.transport = transport; +function defaultClearTimeout() { + throw new Error("clearTimeout has not been defined"); +} +(function() { + try { + if (typeof setTimeout === "function") { + cachedSetTimeout = setTimeout; } else { - throw new Error("Invalid transport"); - } - const defaultChainId = options == null ? void 0 : options.defaultChainId; - this.defaultEIP6492 = (_options$defaultEIP = options == null ? void 0 : options.defaultEIP6492) != null ? _options$defaultEIP : false; - this.session = new SequenceClientSession(store); - this.defaultChainId = new DefaultChainIdTracker(store, defaultChainId); - this.transport.on("accountsChanged", (accounts) => { - var _this$callbacks$accou; - if (accounts.length > 1) { - console.warn("SequenceClient: wallet-webapp returned more than one account"); - } - (_this$callbacks$accou = this.callbacks.accountsChanged) == null || _this$callbacks$accou.forEach((cb2) => cb2(accounts)); - }); - this.transport.on("connect", (response) => { - var _this$callbacks$conne; - const chainIdHex = toQuantity(this.getChainId()); - (_this$callbacks$conne = this.callbacks.connect) == null || _this$callbacks$conne.forEach((cb2) => cb2(_extends$2({}, response, { - // Ignore the full connect response - // use the chainId defined locally - chainId: chainIdHex - }))); - }); - this.transport.on("disconnect", (error, origin) => { - var _this$callbacks$disco; - (_this$callbacks$disco = this.callbacks.disconnect) == null || _this$callbacks$disco.forEach((cb2) => cb2(error, origin)); - }); - this.transport.on("networks", (networks2) => { - var _this$callbacks$netwo; - (_this$callbacks$netwo = this.callbacks.networks) == null || _this$callbacks$netwo.forEach((cb2) => cb2(networks2)); - }); - this.transport.on("walletContext", (context2) => { - var _this$callbacks$walle; - (_this$callbacks$walle = this.callbacks.walletContext) == null || _this$callbacks$walle.forEach((cb2) => cb2(context2)); - }); - this.transport.on("open", (info) => { - var _this$callbacks$open; - (_this$callbacks$open = this.callbacks.open) == null || _this$callbacks$open.forEach((cb2) => cb2(info)); - }); - this.transport.on("close", () => { - var _this$callbacks$close; - (_this$callbacks$close = this.callbacks.close) == null || _this$callbacks$close.forEach((cb2) => cb2()); - }); - this.transport.on("chainChanged", (chainIdHex, origin) => { - var _this$callbacks$chain; - (_this$callbacks$chain = this.callbacks.chainChanged) == null || _this$callbacks$chain.forEach((cb2) => cb2(chainIdHex, origin)); - }); - this.defaultChainId.onDefaultChainIdChanged((chainId) => { - var _this$callbacks$chain2; - const chainIdHex = toQuantity(chainId); - (_this$callbacks$chain2 = this.callbacks.chainChanged) == null || _this$callbacks$chain2.forEach((cb2) => cb2(chainIdHex)); - }); - if (options != null && options.projectAccessKey) { - this.projectAccessKey = options.projectAccessKey; - } - if (this.projectAccessKey && options != null && options.analytics) { - this.analytics = setupAnalytics(this.projectAccessKey); - } - if ((_this$session$getSess = this.session.getSession()) != null && _this$session$getSess.accountAddress) { - var _this$analytics, _this$session$getSess2; - (_this$analytics = this.analytics) == null || _this$analytics.identify((_this$session$getSess2 = this.session.getSession()) == null || (_this$session$getSess2 = _this$session$getSess2.accountAddress) == null ? void 0 : _this$session$getSess2.toLowerCase()); + cachedSetTimeout = defaultSetTimout; } + } catch (e2) { + cachedSetTimeout = defaultSetTimout; } - // Callbacks - registerCallback(eventName, callback) { - if (!this.callbacks[eventName]) { - this.callbacks[eventName] = []; + try { + if (typeof clearTimeout === "function") { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; } - this.callbacks[eventName].push(callback); - return () => { - this.callbacks[eventName] = this.callbacks[eventName].filter((c2) => c2 !== callback); - }; - } - // Individual callbacks lead to more idiomatic code - onOpen(callback) { - return this.registerCallback("open", callback); - } - onClose(callback) { - return this.registerCallback("close", callback); - } - onConnect(callback) { - return this.registerCallback("connect", callback); - } - onDisconnect(callback) { - return this.registerCallback("disconnect", callback); - } - onNetworks(callback) { - return this.registerCallback("networks", callback); - } - onAccountsChanged(callback) { - return this.registerCallback("accountsChanged", callback); - } - // @deprecated - onWalletContext(callback) { - return this.registerCallback("walletContext", callback); - } - onChainChanged(callback) { - return this.registerCallback("chainChanged", callback); - } - onDefaultChainIdChanged(callback) { - return this.registerCallback("chainChanged", callback); - } - getChainId() { - return this.defaultChainId.getDefaultChainId(); - } - setDefaultChainId(chainId) { - return this.defaultChainId.setDefaultChainId(chainId); - } - // Proxy transport methods - async openWallet(path, intent) { - this.transport.openWallet(path, intent, this.getChainId()); - await this.transport.waitUntilOpened(); - return this.isOpened(); - } - closeWallet() { - return this.transport.closeWallet(); - } - isOpened() { - return this.transport.isOpened(); - } - isConnected() { - return this.session.hasSession(); - } - getSession() { - return this.session.getSession(); + } catch (e2) { + cachedClearTimeout = defaultClearTimeout; } - // Basic API - getAddress() { - const session = this.session.connectedSession(); - return session.accountAddress; +})(); +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + return setTimeout(fun, 0); } - async connect(options) { - if ((options == null ? void 0 : options.authorizeVersion) === void 0) { - options.authorizeVersion = 2; - } - if ((options == null ? void 0 : options.refresh) === true) { - this.disconnect(); - } - options.projectAccessKey = this.projectAccessKey; - if (options) { - if (options.authorize) { - if (!options.app) { - throw new Error(`connecting with 'authorize' option also requires 'app' to be set`); - } - if (options.authorizeVersion === void 0) { - options.authorizeVersion = 2; - } - } - } - await this.openWallet(void 0, { - type: "connect", - options: _extends$2({}, options, { - networkId: this.getChainId(), - clientVersion: VERSION$1 - }) - }); - const connectDetails = await this.transport.waitUntilConnected().catch((error) => { - if (error instanceof Error) { - return { - connected: false, - error: error.message - }; - } else { - return { - connected: false, - error: JSON.stringify(error) - }; - } - }); - if (connectDetails.chainId) { - connectDetails.chainId = BigInt(connectDetails.chainId).toString(); - } - if (connectDetails.connected) { - var _connectDetails$sessi; - if (!connectDetails.session) { - throw new Error("impossible state, connect response is missing session"); - } - this.session.setSession(connectDetails.session); - if ((_connectDetails$sessi = connectDetails.session) != null && _connectDetails$sessi.accountAddress) { - var _this$analytics2; - (_this$analytics2 = this.analytics) == null || _this$analytics2.identify(connectDetails.session.accountAddress.toLowerCase()); - } - } - return connectDetails; + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); } - disconnect() { - var _this$analytics3; - if (this.isOpened()) { - this.closeWallet(); + try { + return cachedSetTimeout(fun, 0); + } catch (e2) { + try { + return cachedSetTimeout.call(null, fun, 0); + } catch (e22) { + return cachedSetTimeout.call(this, fun, 0); } - (_this$analytics3 = this.analytics) == null || _this$analytics3.reset(); - return this.session.clearSession(); } - // Higher level API - async request(request) { - request.method = this.mapSignMethod(request.method); - const result = await this.transport.request(request); - return unwrapJsonRpcResponse(result); +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + return clearTimeout(marker); } - async getNetworks(pull) { - const connectedSession = this.session.connectedSession(); - if (pull) { - connectedSession.networks = await this.request({ - method: "sequence_getNetworks" - }); - this.session.setSession(connectedSession); - } - return connectedSession.networks; + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); } - // NOTICE: `legacy_sign` will get overriden by `send` - // it is done this way to ensure that: - // - `send` handles `personal_sign` as a request for the default sign method - // - explicit `personal_sign` is not replaced by `sequence_sign` (if default is EI6492) - signMethod(options) { - if ((options == null ? void 0 : options.eip6492) === void 0) { - return "personal_sign"; + try { + return cachedClearTimeout(marker); + } catch (e2) { + try { + return cachedClearTimeout.call(null, marker); + } catch (e22) { + return cachedClearTimeout.call(this, marker); } - return options.eip6492 ? "sequence_sign" : "legacy_sign"; } - signTypedDataMethod(options) { - if ((options == null ? void 0 : options.eip6492) === void 0) { - return "eth_signTypedData_v4"; - } - return options.eip6492 ? "sequence_signTypedData_v4" : "legacy_signTypedData_v4"; +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; } - mapSignMethod(method) { - if (method === "personal_sign") { - if (this.defaultEIP6492) { - return "sequence_sign"; - } else { - return "personal_sign"; - } - } - if (method === "eth_signTypedData_v4") { - if (this.defaultEIP6492) { - return "sequence_signTypedData_v4"; - } else { - return "eth_signTypedData_v4"; - } - } - if (method === "legacy_sign") { - return "personal_sign"; - } - if (method === "legacy_signTypedData_v4") { - return "eth_signTypedData_v4"; - } - return method; + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; } - async signMessage(message, options) { - var _this$analytics4; - const method = this.signMethod(options); - (_this$analytics4 = this.analytics) == null || _this$analytics4.track({ - event: "SIGN_MESSAGE_REQUEST", - props: { - chainId: `${(options == null ? void 0 : options.chainId) || this.getChainId()}` - } - }); - message = hexlify(messageToBytes(message)); - return this.request({ - method, - params: [message, this.getAddress()], - chainId: options == null ? void 0 : options.chainId - }); + if (queue.length) { + drainQueue(); } - async signTypedData(typedData, options) { - var _this$analytics5; - const method = this.signTypedDataMethod(options); - const encoded = TypedDataEncoder.getPayload(typedData.domain, typedData.types, typedData.message); - (_this$analytics5 = this.analytics) == null || _this$analytics5.track({ - event: "SIGN_TYPED_DATA_REQUEST", - props: { - chainId: `${(options == null ? void 0 : options.chainId) || this.getChainId()}` - } - }); - return this.request({ - method, - params: [this.getAddress(), encoded], - chainId: (options == null ? void 0 : options.chainId) || typedData.domain.chainId && Number(typedData.domain.chainId) || this.getChainId() - }); +} +function drainQueue() { + if (draining) { + return; } - async sendTransaction(tx, options) { - var _this$analytics6; - const sequenceTxs = Array.isArray(tx) ? tx : [tx]; - const extendedTxs = toExtended(sequenceTxs); - (_this$analytics6 = this.analytics) == null || _this$analytics6.track({ - event: "SEND_TRANSACTION_REQUEST", - props: { - chainId: `${(options == null ? void 0 : options.chainId) || this.getChainId()}` + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while (len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); } - }); - return this.request({ - method: "eth_sendTransaction", - params: [extendedTxs], - chainId: options == null ? void 0 : options.chainId - }); - } - async getWalletContext() { - return this.request({ - method: "sequence_getWalletContext" - }); - } - async getOnchainWalletConfig(options) { - const res = await this.request({ - method: "sequence_getWalletConfig", - params: [(options == null ? void 0 : options.chainId) || this.getChainId()], - chainId: options == null ? void 0 : options.chainId - }); - return Array.isArray(res) ? res[0] : res; + } + queueIndex = -1; + len = queue.length; } - // NOTICE: We are leaving out all the "regular" methods os a tipical - // JSON RPC Provider (eth_getBlockByNumber, eth_call, etc) - // wallet-webapp does implement them, but this client is meant to be - // exclusively used for Sequence specific methods + currentQueue = null; + draining = false; + runClearTimeout(timeout); } -const unwrapJsonRpcResponse = (response) => { - if (response && typeof response === "object" && "jsonrpc" in response && "result" in response) { - return response.result; +process.nextTick = function(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); } - return response; }; -const DefaultProviderConfig = { - transports: { - walletAppURL: "https://sequence.app", - windowTransport: { - enabled: true - }, - proxyTransport: { - enabled: false - } - }, - defaultNetwork: 1, - analytics: true +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function() { + this.fun.apply(null, this.array); }; -let sequenceWalletProvider; -const initWallet = (projectAccessKey2, partialConfig) => { - var _config$networks$filt, _config$networks, _findNetworkConfig; - if (!projectAccessKey2 || typeof projectAccessKey2 !== "string") { - throw new Error("Please pass a projectAccessKey in initWallet."); +process.title = "browser"; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ""; +process.versions = {}; +function noop() { +} +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; +process.listeners = function(name2) { + return []; +}; +process.binding = function(name2) { + throw new Error("process.binding is not supported"); +}; +process.cwd = function() { + return "/"; +}; +process.chdir = function(dir) { + throw new Error("process.chdir is not supported"); +}; +process.umask = function() { + return 0; +}; +var browserExports = browser$1.exports; +const process$1 = /* @__PURE__ */ getDefaultExportFromCjs(browserExports); +const extractProjectIdFromAccessKey = (accessKey) => { + const base64String = accessKey.replace(/-/g, "+").replace(/_/g, "/"); + const binaryString = atob(base64String); + const byteArray = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + byteArray[i] = binaryString.charCodeAt(i); } - if (sequenceWalletProvider) { - return sequenceWalletProvider; + if (byteArray[0] !== 1) { + throw new Error("UnsupportedVersion"); } - const config2 = _extends$2({}, DefaultProviderConfig, partialConfig, { - transports: _extends$2({}, DefaultProviderConfig.transports, partialConfig == null ? void 0 : partialConfig.transports) - }); - const rpcProviders = {}; - const newNetworks = (_config$networks$filt = (_config$networks = config2.networks) == null ? void 0 : _config$networks.filter((n2) => { - n2.rpcUrl !== void 0 && n2.chainId !== void 0 && !allNetworks.find((an) => an.chainId === n2.chainId); - })) != null ? _config$networks$filt : []; - const combinedNetworks = allNetworks.map((n2) => { - var _config$networks2; - const network2 = (_config$networks2 = config2.networks) == null ? void 0 : _config$networks2.find((cn) => cn.chainId === n2.chainId); - return network2 ? _extends$2({}, n2, network2) : n2; - }).concat(newNetworks).map((network2) => { - if (network2.rpcUrl.includes(projectAccessKey2)) { - return network2; + const projectIdBytes = byteArray.slice(1, 9); + const projectId = projectIdBytes[7] | projectIdBytes[6] << 8 | projectIdBytes[5] << 16 | projectIdBytes[4] << 24 | projectIdBytes[3] << 32 | projectIdBytes[2] << 40 | projectIdBytes[1] << 48 | projectIdBytes[0] << 56; + return projectId; +}; +const MAX_UINT_256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const isBigNumberish = (value) => { + return value != null && (typeof value === "number" && value % 1 === 0 || typeof value === "string" && !!value.match(/^-?[0-9]+$/) || isHexString(value) || typeof value === "bigint"); +}; +const toHexString = (value) => { + const result = value.toString(16); + return `${result.length % 2 === 0 ? "0x" : "0x0"}${result}`; +}; +const parseUnits = (value, decimals = 18) => { + let [integer, fraction = "0"] = value.split("."); + const negative = integer.startsWith("-"); + if (negative) { + integer = integer.slice(1); + } + fraction = fraction.replace(/(0+)$/, ""); + if (decimals === 0) { + integer = `${Math.round(Number(`${integer}.${fraction}`))}`; + fraction = ""; + } else if (fraction.length > decimals) { + const [left, unit, right] = [fraction.slice(0, decimals - 1), fraction.slice(decimals - 1, decimals), fraction.slice(decimals)]; + const rounded = Math.round(Number(`${unit}.${right}`)); + if (rounded > 9) { + fraction = `${BigInt(left) + 1n}0`.padStart(left.length + 1, "0"); + } else { + fraction = `${left}${rounded}`; } - network2.rpcUrl = network2.rpcUrl + `/${projectAccessKey2}`; - return network2; - }); - const providerForChainId = (chainId) => { - if (!rpcProviders[chainId]) { - var _combinedNetworks$fin; - const rpcUrl = (_combinedNetworks$fin = combinedNetworks.find((n2) => n2.chainId === chainId)) == null ? void 0 : _combinedNetworks$fin.rpcUrl; - if (!rpcUrl) { - throw new Error(`no rpcUrl found for chainId: ${chainId}`); - } - rpcProviders[chainId] = new JsonRpcProvider(rpcUrl, { - middlewares: [loggingProviderMiddleware, exceptionProviderMiddleware, new CachedProvider()] - }, { - cacheTimeout: -1 - }); + if (fraction.length > decimals) { + fraction = fraction.slice(1); + integer = `${BigInt(integer) + 1n}`; } - return rpcProviders[chainId]; - }; - const defaultNetwork = config2.defaultNetwork ? (_findNetworkConfig = findNetworkConfig(combinedNetworks, config2.defaultNetwork)) == null ? void 0 : _findNetworkConfig.chainId : void 0; - if (!defaultNetwork && config2.defaultNetwork) { - throw new Error(`defaultNetwork not found for chainId: ${config2.defaultNetwork}`); + fraction = fraction.slice(0, decimals); + } else { + fraction = fraction.padEnd(decimals, "0"); } - const itemStore = config2.localStorage || useBestStore(); - const client2 = new SequenceClient(config2.transports, itemStore, { - defaultChainId: defaultNetwork, - defaultEIP6492: config2.defaultEIP6492, - projectAccessKey: projectAccessKey2, - analytics: config2.analytics - }); - sequenceWalletProvider = new SequenceProvider(client2, providerForChainId); - return sequenceWalletProvider; -}; -const unregisterWallet = () => { - if (!sequenceWalletProvider) return; - sequenceWalletProvider.client.closeWallet(); - sequenceWalletProvider.client.transport.unregister(); - sequenceWalletProvider = void 0; + return BigInt(`${negative ? "-" : ""}${integer}${fraction}`); }; -const getWallet = () => { - if (!sequenceWalletProvider) { - throw new Error("Wallet has not been initialized, call sequence.initWallet(config) first."); +const parseEther = (value) => parseUnits(value, 18); +const formatUnits = (value, decimals = 18) => { + let display = value.toString(); + const negative = display.startsWith("-"); + if (negative) { + display = display.slice(1); } - return sequenceWalletProvider; + display = display.padStart(decimals, "0"); + const integer = display.slice(0, display.length - decimals); + let fraction = display.slice(display.length - decimals); + fraction = fraction.replace(/(0+)$/, ""); + return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`; }; -const provider$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - BaseInjectedTransport, - BaseProviderTransport, - BaseWalletTransport, - CHANNEL_ID, - DefaultChainIdTracker, - DefaultProviderConfig, - ErrSignedInRequired, - EventType, - ExtensionMessageHandler, - ExtensionMessageProvider, - InitState, - LocalStorage, - MemoryItemStore, - MuxMessageProvider, - OpenState, - PROVIDER_OPEN_TIMEOUT, - ProviderError, - ProxyMessageChannel, - ProxyMessageChannelPort, - ProxyMessageHandler, - ProxyMessageProvider, - SequenceClient, - SequenceClientSession, - SequenceProvider, - SequenceSigner, - SingleNetworkSequenceProvider, - SingleNetworkSequenceSigner, - UnrealMessageHandler, - UnrealMessageProvider, - WalletRequestHandler, - WindowMessageHandler, - WindowMessageProvider, - WindowSessionParams, - getWallet, - initWallet, - isBrowserExtension, - isMuxTransportTemplate, - isProviderTransport, - isUnityPlugin, - isValidMessageSignature, - isValidSignature, - isValidTypedDataSignature, - isWalletUpToDate, - messageToBytes, - nextMessageIdx, - prefixEIP191Message, - resolveArrayProperties, - trimEIP191Prefix, - unregisterWallet, - useBestStore, - validateTransactionRequest -}, Symbol.toStringTag, { value: "Module" })); -function _mergeNamespaces$1(n2, m2) { - m2.forEach(function(e2) { - e2 && typeof e2 !== "string" && !Array.isArray(e2) && Object.keys(e2).forEach(function(k2) { - if (k2 !== "default" && !(k2 in n2)) { - var d2 = Object.getOwnPropertyDescriptor(e2, k2); - Object.defineProperty(n2, k2, d2.get ? d2 : { - enumerable: true, - get: function() { - return e2[k2]; - } - }); - } - }); - }); - return Object.freeze(n2); -} -var abi$2 = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [abi$1$2]); -var api = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [api$1]); -var auth = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [auth$1]); -var guard = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [guard$1]); -var indexer = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [indexer$1]); -var metadata = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [metadata$1]); -var network = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [network$1]); -var provider = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [provider$1]); -var relayer = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [relayer$1]); -const transactions = index$1$2.transaction; -var transactions$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - transactions -}); -var utils = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null, - isValidSignature, - isValidMessageSignature, - isValidTypedDataSignature, - isWalletUpToDate -}, [utils$1]); -var core = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [core$1]); -var signhub = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [signhub$1]); -var sessions = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [sessions$1]); -var migration = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [migration$1]); -var account = /* @__PURE__ */ _mergeNamespaces$1({ - __proto__: null -}, [account$1]); -var sequence$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - abi: abi$2, - api, - auth, - guard, - indexer, - metadata, - network, - provider, - relayer, - transactions: transactions$1, - utils, - core, - signhub, - sessions, - migration, - account, - initWallet, - getWallet, - unregisterWallet, - SequenceProvider, - SequenceClient, - SequenceSigner -}); -function useLoadGsiScript(options = {}) { - const { nonce, onScriptLoadSuccess, onScriptLoadError } = options; - const [scriptLoadedSuccessfully, setScriptLoadedSuccessfully] = reactExports.useState(false); - const onScriptLoadSuccessRef = reactExports.useRef(onScriptLoadSuccess); - onScriptLoadSuccessRef.current = onScriptLoadSuccess; - const onScriptLoadErrorRef = reactExports.useRef(onScriptLoadError); - onScriptLoadErrorRef.current = onScriptLoadError; - reactExports.useEffect(() => { - const scriptTag = document.createElement("script"); - scriptTag.src = "https://accounts.google.com/gsi/client"; - scriptTag.async = true; - scriptTag.defer = true; - scriptTag.nonce = nonce; - scriptTag.onload = () => { - var _a2; - setScriptLoadedSuccessfully(true); - (_a2 = onScriptLoadSuccessRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(onScriptLoadSuccessRef); - }; - scriptTag.onerror = () => { - var _a2; - setScriptLoadedSuccessfully(false); - (_a2 = onScriptLoadErrorRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(onScriptLoadErrorRef); - }; - document.body.appendChild(scriptTag); - return () => { - document.body.removeChild(scriptTag); +const formatEther = (value) => formatUnits(value, 18); +const bigintReplacer = (key, value) => { + if (typeof value === "bigint") { + return { + $bigint: value.toString() }; - }, [nonce]); - return scriptLoadedSuccessfully; -} -const GoogleOAuthContext = reactExports.createContext(null); -function GoogleOAuthProvider({ clientId, nonce, onScriptLoadSuccess, onScriptLoadError, children }) { - const scriptLoadedSuccessfully = useLoadGsiScript({ - nonce, - onScriptLoadSuccess, - onScriptLoadError - }); - const contextValue = reactExports.useMemo(() => ({ - clientId, - scriptLoadedSuccessfully - }), [clientId, scriptLoadedSuccessfully]); - return React.createElement(GoogleOAuthContext.Provider, { value: contextValue }, children); -} -function useGoogleOAuth() { - const context2 = reactExports.useContext(GoogleOAuthContext); - if (!context2) { - throw new Error("Google OAuth components must be used within GoogleOAuthProvider"); } - return context2; -} -function extractClientId(credentialResponse) { - var _a2; - const clientId = (_a2 = credentialResponse === null || credentialResponse === void 0 ? void 0 : credentialResponse.clientId) !== null && _a2 !== void 0 ? _a2 : credentialResponse === null || credentialResponse === void 0 ? void 0 : credentialResponse.client_id; - return clientId; -} -const containerHeightMap = { large: 40, medium: 32, small: 20 }; -function GoogleLogin({ onSuccess, onError, useOneTap, promptMomentNotification, type = "standard", theme = "outline", size: size2 = "large", text: text2, shape, logo_alignment, width, locale, click_listener, containerProps, ...props }) { - const btnContainerRef = reactExports.useRef(null); - const { clientId, scriptLoadedSuccessfully } = useGoogleOAuth(); - const onSuccessRef = reactExports.useRef(onSuccess); - onSuccessRef.current = onSuccess; - const onErrorRef = reactExports.useRef(onError); - onErrorRef.current = onError; - const promptMomentNotificationRef = reactExports.useRef(promptMomentNotification); - promptMomentNotificationRef.current = promptMomentNotification; - reactExports.useEffect(() => { - var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _j2; - if (!scriptLoadedSuccessfully) - return; - (_c2 = (_b2 = (_a2 = window === null || window === void 0 ? void 0 : window.google) === null || _a2 === void 0 ? void 0 : _a2.accounts) === null || _b2 === void 0 ? void 0 : _b2.id) === null || _c2 === void 0 ? void 0 : _c2.initialize({ - client_id: clientId, - callback: (credentialResponse) => { - var _a3; - if (!(credentialResponse === null || credentialResponse === void 0 ? void 0 : credentialResponse.credential)) { - return (_a3 = onErrorRef.current) === null || _a3 === void 0 ? void 0 : _a3.call(onErrorRef); - } - const { credential, select_by } = credentialResponse; - onSuccessRef.current({ - credential, - clientId: extractClientId(credentialResponse), - select_by - }); - }, - ...props - }); - (_f2 = (_e2 = (_d2 = window === null || window === void 0 ? void 0 : window.google) === null || _d2 === void 0 ? void 0 : _d2.accounts) === null || _e2 === void 0 ? void 0 : _e2.id) === null || _f2 === void 0 ? void 0 : _f2.renderButton(btnContainerRef.current, { - type, - theme, - size: size2, - text: text2, - shape, - logo_alignment, - width, - locale, - click_listener - }); - if (useOneTap) - (_j2 = (_h2 = (_g2 = window === null || window === void 0 ? void 0 : window.google) === null || _g2 === void 0 ? void 0 : _g2.accounts) === null || _h2 === void 0 ? void 0 : _h2.id) === null || _j2 === void 0 ? void 0 : _j2.prompt(promptMomentNotificationRef.current); - return () => { - var _a3, _b3, _c3; - if (useOneTap) - (_c3 = (_b3 = (_a3 = window === null || window === void 0 ? void 0 : window.google) === null || _a3 === void 0 ? void 0 : _a3.accounts) === null || _b3 === void 0 ? void 0 : _b3.id) === null || _c3 === void 0 ? void 0 : _c3.cancel(); - }; - }, [ - clientId, - scriptLoadedSuccessfully, - useOneTap, - type, - theme, - size2, - text2, - shape, - logo_alignment, - width, - locale - ]); - return React.createElement("div", { ...containerProps, ref: btnContainerRef, style: { height: containerHeightMap[size2], ...containerProps === null || containerProps === void 0 ? void 0 : containerProps.style } }); -} -const version$5 = "2.21.10"; -let errorConfig = { - getDocsUrl: ({ docsBaseUrl, docsPath: docsPath2 = "", docsSlug }) => docsPath2 ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath2}${docsSlug ? `#${docsSlug}` : ""}` : void 0, - version: version$5 + return value; }; -let BaseError$3 = class BaseError extends Error { - constructor(shortMessage, args = {}) { - var _a2; - const details = (() => { - var _a3; - if (args.cause instanceof BaseError) - return args.cause.details; - if ((_a3 = args.cause) == null ? void 0 : _a3.message) - return args.cause.message; - return args.details; - })(); - const docsPath2 = (() => { - if (args.cause instanceof BaseError) - return args.cause.docsPath || args.docsPath; - return args.docsPath; - })(); - const docsUrl = (_a2 = errorConfig.getDocsUrl) == null ? void 0 : _a2.call(errorConfig, { ...args, docsPath: docsPath2 }); - const message = [ - shortMessage || "An error occurred.", - "", - ...args.metaMessages ? [...args.metaMessages, ""] : [], - ...docsUrl ? [`Docs: ${docsUrl}`] : [], - ...details ? [`Details: ${details}`] : [], - ...[`Version: ${errorConfig.version}`] - ].join("\n"); - super(message, args.cause ? { cause: args.cause } : void 0); - Object.defineProperty(this, "details", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "docsPath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "metaMessages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "shortMessage", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "version", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "BaseError" - }); - this.details = details; - this.docsPath = docsPath2; - this.metaMessages = args.metaMessages; - this.name = args.name ?? this.name; - this.shortMessage = shortMessage; - this.version = version$5; +const bigintReviver = (key, value) => { + if (value !== null && typeof value === "object" && "$bigint" in value && typeof value.$bigint === "string") { + return BigInt(value.$bigint); + } + if (value !== null && typeof value === "object" && value.type === "BigNumber" && isHexString(value.hex)) { + return BigInt(value.hex); + } + return value; +}; +const base64Encode = (val) => { + return gBase64.encode(val, true); +}; +const base64EncodeObject = (obj) => { + return gBase64.encode(JSON.stringify(obj, bigintReplacer), true); +}; +const base64Decode = (encodedString) => { + if (encodedString === null || encodedString === void 0) { + return void 0; + } + return gBase64.decode(encodedString); +}; +const base64DecodeObject = (encodedObject) => { + if (encodedObject === null || encodedObject === void 0) { + return void 0; } - walk(fn) { - return walk(this, fn); + return JSON.parse(gBase64.decode(encodedObject), bigintReviver); +}; +const encodeMessageDigest = (message) => { + if (typeof message === "string") { + return getBytes(id$1(message)); + } else { + return getBytes(keccak256(message)); } }; -function walk(err, fn) { - if (fn == null ? void 0 : fn(err)) - return err; - if (err && typeof err === "object" && "cause" in err) - return walk(err.cause, fn); - return fn ? null : err; -} -class IntegerOutOfRangeError extends BaseError$3 { - constructor({ max: max2, min: min2, signed: signed2, size: size2, value }) { - super(`Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed2 ? "signed" : "unsigned"} ` : ""}integer range ${max2 ? `(${min2} to ${max2})` : `(above ${min2})`}`, { name: "IntegerOutOfRangeError" }); +const packMessageData = (walletAddress, chainId, digest) => { + return solidityPacked(["string", "uint256", "address", "bytes32"], ["", chainId, walletAddress, digest]); +}; +const subDigestOf = (address, chainId, digest) => { + return keccak256(packMessageData(address, chainId, digest)); +}; +const isNode$2 = () => { + if (typeof window === "undefined" && typeof process$1 === "object") { + return true; + } else { + return false; } -} -class InvalidBytesBooleanError extends BaseError$3 { - constructor(bytes2) { - super(`Bytes value "${bytes2}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, { - name: "InvalidBytesBooleanError" - }); +}; +const isBrowser$1 = () => !isNode$2(); +const jwtDecodeClaims = (jwt) => { + const parts = jwt.split("."); + if (parts.length !== 3) { + throw new Error("invalid jwt"); } + const claims = JSON.parse(gBase64.decode(parts[1])); + return claims; +}; +function _extends$e() { + _extends$e = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends$e.apply(this, arguments); } -class InvalidHexBooleanError extends BaseError$3 { - constructor(hex2) { - super(`Hex value "${hex2}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`, { name: "InvalidHexBooleanError" }); +var logLevel = /* @__PURE__ */ function(logLevel2) { + logLevel2[logLevel2["DEBUG"] = 1] = "DEBUG"; + logLevel2[logLevel2["INFO"] = 2] = "INFO"; + logLevel2[logLevel2["WARN"] = 3] = "WARN"; + logLevel2[logLevel2["ERROR"] = 4] = "ERROR"; + logLevel2[logLevel2["DISABLED"] = 5] = "DISABLED"; + return logLevel2; +}(logLevel || {}); +class Logger { + constructor(config2) { + this.config = config2; + this.logLevel = void 0; + this.configure(config2); } -} -class SizeOverflowError extends BaseError$3 { - constructor({ givenSize, maxSize }) { - super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); + configure(config2) { + this.config = _extends$e({}, this.config, config2); + switch (this.config.logLevel) { + case "DEBUG": + this.logLevel = logLevel.DEBUG; + break; + case "INFO": + this.logLevel = logLevel.INFO; + break; + case "WARN": + this.logLevel = logLevel.WARN; + break; + case "ERROR": + this.logLevel = logLevel.ERROR; + break; + case "DISABLED": + this.logLevel = logLevel.DISABLED; + break; + default: + this.logLevel = logLevel.INFO; + break; + } + if (this.config.silence === void 0) { + this.config.silence = false; + } } -} -class SliceOffsetOutOfBoundsError extends BaseError$3 { - constructor({ offset: offset2, position, size: size2 }) { - super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset2}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" }); + debug(message, ...optionalParams) { + if (this.config.silence === true) return; + if (this.logLevel === logLevel.DEBUG) { + console.log(message, ...optionalParams); + } } -} -class SizeExceedsPaddingSizeError extends BaseError$3 { - constructor({ size: size2, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); + info(message, ...optionalParams) { + if (this.config.silence === true) return; + if (this.logLevel <= logLevel.INFO) { + console.log(message, ...optionalParams); + } } -} -class InvalidBytesLengthError extends BaseError$3 { - constructor({ size: size2, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size2} ${type} long.`, { name: "InvalidBytesLengthError" }); + warn(message, ...optionalParams) { + if (this.config.silence === true) return; + if (this.logLevel <= logLevel.WARN) { + console.warn(message, ...optionalParams); + if (this.config.onwarn) { + this.config.onwarn(message, optionalParams); + } + } + } + error(message, ...optionalParams) { + if (this.config.silence === true) return; + if (this.logLevel <= logLevel.ERROR) { + console.error(message, ...optionalParams); + if (this.config.onerror) { + this.config.onerror(message, optionalParams); + } + } } } -function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) { - if (typeof hexOrBytes === "string") - return padHex(hexOrBytes, { dir, size: size2 }); - return padBytes(hexOrBytes, { dir, size: size2 }); +const logger = new Logger({ + logLevel: "INFO", + // By default we silence the logger. In tests we should call `configureLogger` + // below to set silence: false. + silence: true +}); +const configureLogger = (config2) => logger.configure(config2); +class Base { + static bufferIndexOf(array, element, isSorted = false) { + if (isSorted) { + return Base.binarySearch(array, element, Base.compare); + } + const eqChecker = (buffer1, buffer2) => { + if (buffer1 === buffer2) { + return true; + } + if (buffer1.length !== buffer2.length) { + return false; + } + for (let i = 0; i < buffer1.length; i++) { + if (buffer1[i] !== buffer2[i]) { + return false; + } + } + return true; + }; + return Base.linearSearch(array, element, eqChecker); + } + static binarySearch(array, element, compareFunction) { + let start = 0; + let end = array.length - 1; + while (start <= end) { + const mid = Math.floor((start + end) / 2); + const ordering = compareFunction(array[mid], element); + if (ordering === 0) { + for (let i = mid - 1; i >= 0; i--) { + if (compareFunction(array[i], element) === 0) continue; + return i + 1; + } + return 0; + } else if (ordering < 0) { + start = mid + 1; + } else { + end = mid - 1; + } + } + return -1; + } + static compare(a2, b2) { + const len = Math.min(a2.length, b2.length); + for (let i = 0; i < len; i++) { + if (a2[i] !== b2[i]) { + return a2[i] - b2[i]; + } + } + return a2.length - b2.length; + } + static linearSearch(array, element, eqChecker) { + for (let i = 0; i < array.length; i++) { + if (eqChecker(array[i], element)) { + return i; + } + } + return -1; + } + static bufferify(value) { + if (typeof value === "string") { + return getBytes(value); + } + return value; + } + static isHexString(v3) { + return typeof v3 === "string" && /^(0x)?[0-9A-Fa-f]*$/.test(v3); + } + static bufferToHex(value, withPrefix = true) { + const prefixed = hexlify(value); + return withPrefix ? prefixed : prefixed.substring(2); + } + static bufferifyFn(f2) { + return (value) => { + return Base.bufferify(f2(value)); + }; + } } -function padHex(hex_, { dir, size: size2 = 32 } = {}) { - if (size2 === null) - return hex_; - const hex2 = hex_.replace("0x", ""); - if (hex2.length > size2 * 2) - throw new SizeExceedsPaddingSizeError({ - size: Math.ceil(hex2.length / 2), - targetSize: size2, - type: "hex" - }); - return `0x${hex2[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`; +class MerkleTree extends Base { + constructor(leaves, options = {}) { + super(); + this.hashFn = void 0; + this.leaves = []; + this.layers = []; + this.sortLeaves = false; + this.sortPairs = false; + this.sortLeaves = !!options.sortLeaves; + this.sortPairs = !!options.sortPairs; + this.hashFn = Base.bufferifyFn(keccak256); + this.processLeaves(leaves); + } + getOptions() { + return { + sortLeaves: this.sortLeaves, + sortPairs: this.sortPairs + }; + } + processLeaves(leaves) { + this.leaves = leaves.map(Base.bufferify); + if (this.sortLeaves) { + this.leaves = this.leaves.sort(Base.compare); + } + this.createHashes(this.leaves); + } + createHashes(nodes) { + this.layers = [nodes]; + while (nodes.length > 1) { + const layerIndex = this.layers.length; + this.layers.push([]); + const layerLimit = nodes.length; + for (let i = 0; i < nodes.length; i += 2) { + if (i >= layerLimit) { + this.layers[layerIndex].push(...nodes.slice(layerLimit)); + break; + } else if (i + 1 === nodes.length) { + if (nodes.length % 2 === 1) { + this.layers[layerIndex].push(nodes[i]); + continue; + } + } + const left = nodes[i]; + const right = i + 1 === nodes.length ? left : nodes[i + 1]; + const combined = [left, right]; + if (this.sortPairs) { + combined.sort(Base.compare); + } + const hash2 = this.hashFn(concat(combined)); + this.layers[layerIndex].push(hash2); + } + nodes = this.layers[layerIndex]; + } + } + getRoot() { + if (this.layers.length === 0) { + return Uint8Array.from([]); + } + return this.layers[this.layers.length - 1][0] || Uint8Array.from([]); + } + getHexRoot() { + return Base.bufferToHex(this.getRoot()); + } + getProof(leaf, index2) { + if (typeof leaf === "undefined") { + throw new Error("leaf is required"); + } + leaf = Base.bufferify(leaf); + const proof = []; + if (!Number.isInteger(index2)) { + index2 = -1; + for (let i = 0; i < this.leaves.length; i++) { + if (Base.compare(leaf, this.leaves[i]) === 0) { + index2 = i; + } + } + } + index2 = index2; + if (index2 <= -1) { + return []; + } + for (let i = 0; i < this.layers.length; i++) { + const layer = this.layers[i]; + const isRightNode = index2 % 2; + const pairIndex = isRightNode ? index2 - 1 : index2 + 1; + if (pairIndex < layer.length) { + proof.push({ + position: isRightNode ? "left" : "right", + data: layer[pairIndex] + }); + } + index2 = index2 / 2 | 0; + } + return proof; + } + getHexProof(leaf, index2) { + return this.getProof(leaf, index2).map((item2) => Base.bufferToHex(item2.data)); + } + verify(proof, targetNode, root2) { + let hash2 = Base.bufferify(targetNode); + root2 = Base.bufferify(root2); + if (!Array.isArray(proof) || !targetNode || !root2) { + return false; + } + for (let i = 0; i < proof.length; i++) { + const node = proof[i]; + let data; + let isLeftNode; + if (typeof node === "string") { + data = Base.bufferify(node); + isLeftNode = true; + } else if (node instanceof Object) { + data = node.data; + isLeftNode = node.position === "left"; + } else { + throw new Error("Expected node to be of type string or object"); + } + const buffers = []; + if (this.sortPairs) { + if (Base.compare(hash2, data) < 0) { + buffers.push(hash2, data); + } else { + buffers.push(data, hash2); + } + hash2 = this.hashFn(concat(buffers)); + } else { + buffers.push(hash2); + buffers[isLeftNode ? "unshift" : "push"](data); + hash2 = this.hashFn(concat(buffers)); + } + } + return Base.compare(hash2, root2) === 0; + } } -function padBytes(bytes2, { dir, size: size2 = 32 } = {}) { - if (size2 === null) - return bytes2; - if (bytes2.length > size2) - throw new SizeExceedsPaddingSizeError({ - size: bytes2.length, - targetSize: size2, - type: "bytes" +class MerkleTreeGenerator { + constructor(elements, toLeaf) { + this.elements = void 0; + this.toLeaf = void 0; + this.tree = void 0; + this.elements = elements; + this.toLeaf = toLeaf; + } + generateTree() { + const hashed = this.elements.map((e2) => this.toLeaf(e2)); + return new MerkleTree(hashed, { + sortPairs: true, + sortLeaves: true }); - const paddedBytes = new Uint8Array(size2); - for (let i = 0; i < size2; i++) { - const padEnd = dir === "right"; - paddedBytes[padEnd ? i : size2 - i - 1] = bytes2[padEnd ? i : bytes2.length - i - 1]; } - return paddedBytes; -} -function isHex(value, { strict = true } = {}) { - if (!value) - return false; - if (typeof value !== "string") - return false; - return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x"); -} -function size$5(value) { - if (isHex(value, { strict: false })) - return Math.ceil((value.length - 2) / 2); - return value.length; -} -function trim(hexOrBytes, { dir = "left" } = {}) { - let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes; - let sliceLength = 0; - for (let i = 0; i < data.length - 1; i++) { - if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") - sliceLength++; - else - break; + generateRoot() { + if (!this.tree) this.tree = this.generateTree(); + return this.tree.getHexRoot(); } - data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); - if (typeof hexOrBytes === "string") { - if (data.length === 1 && dir === "right") - data = `${data}0`; - return `0x${data.length % 2 === 1 ? `0${data}` : data}`; + generateProof(element) { + if (!this.elements.includes(element)) throw new Error("Element not found"); + if (!this.tree) this.tree = this.generateTree(); + return this.tree.getHexProof(this.toLeaf(element)); } - return data; -} -const encoder$1 = /* @__PURE__ */ new TextEncoder(); -function toBytes$1(value, opts = {}) { - if (typeof value === "number" || typeof value === "bigint") - return numberToBytes(value, opts); - if (typeof value === "boolean") - return boolToBytes(value, opts); - if (isHex(value)) - return hexToBytes$1(value, opts); - return stringToBytes(value, opts); -} -function boolToBytes(value, opts = {}) { - const bytes2 = new Uint8Array(1); - bytes2[0] = Number(value); - if (typeof opts.size === "number") { - assertSize(bytes2, { size: opts.size }); - return pad(bytes2, { size: opts.size }); + verifyProof(element, proof) { + if (!this.elements.includes(element)) throw new Error("Element not found"); + if (!this.tree) this.tree = this.generateTree(); + return this.tree.verify(proof, this.toLeaf(element), this.generateRoot()); } - return bytes2; } -const charCodeMap = { - zero: 48, - nine: 57, - A: 65, - F: 70, - a: 97, - f: 102 +const getSaleItemsLeaf = (element) => solidityPackedKeccak256(["address", "uint256"], [element.address.toLowerCase(), element.tokenId]); +const getFetchRequest = (url, projectAccessKey2, jwt) => { + const req = new FetchRequest(url); + if (jwt) { + req.setHeader("Authorization", `BEARER ${jwt}`); + } + if (projectAccessKey2) { + req.setHeader("X-Access-Key", projectAccessKey2); + } + return req; }; -function charCodeToBase16(char) { - if (char >= charCodeMap.zero && char <= charCodeMap.nine) - return char - charCodeMap.zero; - if (char >= charCodeMap.A && char <= charCodeMap.F) - return char - (charCodeMap.A - 10); - if (char >= charCodeMap.a && char <= charCodeMap.f) - return char - (charCodeMap.a - 10); - return void 0; -} -function hexToBytes$1(hex_, opts = {}) { - let hex2 = hex_; - if (opts.size) { - assertSize(hex2, { size: opts.size }); - hex2 = pad(hex2, { dir: "right", size: opts.size }); +let PromiseCache$1 = class PromiseCache { + constructor() { + this.cache = void 0; + this.cache = /* @__PURE__ */ new Map(); } - let hexString = hex2.slice(2); - if (hexString.length % 2) - hexString = `0${hexString}`; - const length = hexString.length / 2; - const bytes2 = new Uint8Array(length); - for (let index2 = 0, j2 = 0; index2 < length; index2++) { - const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j2++)); - const nibbleRight = charCodeToBase16(hexString.charCodeAt(j2++)); - if (nibbleLeft === void 0 || nibbleRight === void 0) { - throw new BaseError$3(`Invalid byte sequence ("${hexString[j2 - 2]}${hexString[j2 - 1]}" in "${hexString}").`); + do(key, validMilliseconds, task, ...args) { + key = `${key}:${id$1(JSON.stringify(args, deterministically$1))}`; + let entry = this.cache.get(key); + if (entry) { + if (entry.expiration) { + if (/* @__PURE__ */ new Date() >= entry.expiration) { + entry = void 0; + this.cache.delete(key); + } + } + } + if (!entry) { + const entry_ = { + promise: task(...args) + }; + if (validMilliseconds !== void 0) { + entry_.promise = entry_.promise.then((result) => { + entry_.expiration = new Date(Date.now() + validMilliseconds); + return result; + }); + } + entry = entry_; + this.cache.set(key, entry); } - bytes2[index2] = nibbleLeft * 16 + nibbleRight; + return entry.promise; } - return bytes2; -} -function numberToBytes(value, opts) { - const hex2 = numberToHex(value, opts); - return hexToBytes$1(hex2); -} -function stringToBytes(value, opts = {}) { - const bytes2 = encoder$1.encode(value); - if (typeof opts.size === "number") { - assertSize(bytes2, { size: opts.size }); - return pad(bytes2, { dir: "right", size: opts.size }); +}; +function deterministically$1(_key, value) { + if (typeof value === "object" && value !== null && !Array.isArray(value)) { + return Object.fromEntries(Object.entries(value).sort()); } - return bytes2; + return value; } -function assertSize(hexOrBytes, { size: size2 }) { - if (size$5(hexOrBytes) > size2) - throw new SizeOverflowError({ - givenSize: size$5(hexOrBytes), - maxSize: size2 +function promisify(f2, thisContext) { + return function(...a2) { + const args = Array.prototype.slice.call(a2); + return new Promise(async (resolve, reject) => { + try { + args.push((err, result) => err ? reject(err) : resolve(result)); + await f2.apply(thisContext, args); + } catch (e2) { + reject(e2); + } }); + }; } -function fromHex$1(hex2, toOrOpts) { - const opts = { to: toOrOpts }; - const to = opts.to; - if (to === "number") - return hexToNumber$1(hex2, opts); - if (to === "bigint") - return hexToBigInt(hex2, opts); - if (to === "string") - return hexToString(hex2, opts); - if (to === "boolean") - return hexToBool(hex2, opts); - return hexToBytes$1(hex2, opts); -} -function hexToBigInt(hex2, opts = {}) { - const { signed: signed2 } = opts; - if (opts.size) - assertSize(hex2, { size: opts.size }); - const value = BigInt(hex2); - if (!signed2) - return value; - const size2 = (hex2.length - 2) / 2; - const max2 = (1n << BigInt(size2) * 8n - 1n) - 1n; - if (value <= max2) - return value; - return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n; +function queryStringFromObject(name2, obj) { + const k2 = encodeURIComponent(name2); + const v3 = encodeURIComponent(JSON.stringify(obj)); + return `${k2}=${v3}`; } -function hexToBool(hex_, opts = {}) { - let hex2 = hex_; - if (opts.size) { - assertSize(hex2, { size: opts.size }); - hex2 = trim(hex2); +function queryStringToObject(qs) { + const p2 = qs.split("&"); + const o2 = {}; + for (const v3 of p2) { + const z2 = v3.split("="); + o2[decodeURIComponent(z2[0])] = JSON.parse(decodeURIComponent(z2[1])); } - if (trim(hex2) === "0x00") - return false; - if (trim(hex2) === "0x01") - return true; - throw new InvalidHexBooleanError(hex2); -} -function hexToNumber$1(hex2, opts = {}) { - return Number(hexToBigInt(hex2, opts)); + return o2; } -function hexToString(hex2, opts = {}) { - let bytes2 = hexToBytes$1(hex2); - if (opts.size) { - assertSize(bytes2, { size: opts.size }); - bytes2 = trim(bytes2, { dir: "right" }); +const getRandomInt = (min2 = 0, max2 = Number.MAX_SAFE_INTEGER) => { + min2 = Math.ceil(min2); + max2 = Math.floor(max2); + return Math.floor(Math.random() * (max2 - min2 + 1)) + min2; +}; +const sanitizeNumberString = (numString) => { + if (!numString || typeof numString !== "string") { + return ""; } - return new TextDecoder().decode(bytes2); -} -const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_v2, i) => i.toString(16).padStart(2, "0")); -function toHex$1(value, opts = {}) { - if (typeof value === "number" || typeof value === "bigint") - return numberToHex(value, opts); - if (typeof value === "string") { - return stringToHex(value, opts); + const v3 = numString.match(/[\d.]+/); + return v3 && v3.length > 0 ? v3[0].trim() : ""; +}; +const sanitizeAlphanumeric = (alphanum) => { + if (!alphanum || typeof alphanum !== "string") { + return ""; } - if (typeof value === "boolean") - return boolToHex(value, opts); - return bytesToHex$1(value, opts); -} -function boolToHex(value, opts = {}) { - const hex2 = `0x${Number(value)}`; - if (typeof opts.size === "number") { - assertSize(hex2, { size: opts.size }); - return pad(hex2, { size: opts.size }); + const v3 = alphanum.match(/[\w\s\d]+/); + return v3 && v3.length > 0 ? v3[0].trim() : ""; +}; +const sanitizeHost = (host) => { + if (!host || typeof host !== "string") { + return ""; } - return hex2; + const v3 = host.match(/[\w\d.\-:\/]+/); + return v3 && v3.length > 0 ? v3[0].trim() : ""; +}; +const sleep = (t2) => { + return new Promise((resolve) => { + const timeout = setTimeout(() => { + clearTimeout(timeout); + resolve(); + }, t2); + }); +}; +const encodeTypedDataHash = (typedData) => { + const types2 = _extends$e({}, typedData.types); + delete types2["EIP712Domain"]; + return TypedDataEncoder.hash(typedData.domain, types2, typedData.message); +}; +const encodeTypedDataDigest = (typedData) => { + return getBytes(encodeTypedDataHash(typedData)); +}; +const { + defineProperties, + resolveProperties +} = ethers; +const urlClean = (url) => url.replace(/([^:]\/)\/+/g, "$1"); +const utils$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Logger, + MAX_UINT_256, + MerkleTreeGenerator, + PromiseCache: PromiseCache$1, + base64Decode, + base64DecodeObject, + base64Encode, + base64EncodeObject, + bigintReplacer, + bigintReviver, + configureLogger, + defineProperties, + encodeMessageDigest, + encodeTypedDataDigest, + encodeTypedDataHash, + extractProjectIdFromAccessKey, + formatEther, + formatUnits, + getFetchRequest, + getRandomInt, + getSaleItemsLeaf, + isBigNumberish, + isBrowser: isBrowser$1, + isNode: isNode$2, + jwtDecodeClaims, + logger, + packMessageData, + parseEther, + parseUnits, + promisify, + queryStringFromObject, + queryStringToObject, + resolveProperties, + sanitizeAlphanumeric, + sanitizeHost, + sanitizeNumberString, + sleep, + subDigestOf, + toHexString, + urlClean +}, Symbol.toStringTag, { value: "Module" })); +function _extends$d() { + _extends$d = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends$d.apply(this, arguments); } -function bytesToHex$1(value, opts = {}) { - let string = ""; - for (let i = 0; i < value.length; i++) { - string += hexes$1[value[i]]; +function isNetworkConfig(cand) { + return cand && cand.chainId !== void 0 && cand.name !== void 0 && cand.rpcUrl !== void 0 && cand.relayer !== void 0; +} +const getChainId = (chainId) => { + if (typeof chainId === "number") { + return chainId; } - const hex2 = `0x${string}`; - if (typeof opts.size === "number") { - assertSize(hex2, { size: opts.size }); - return pad(hex2, { dir: "right", size: opts.size }); + if (chainId.chainId) { + return chainId.chainId; } - return hex2; -} -function numberToHex(value_, opts = {}) { - const { signed: signed2, size: size2 } = opts; - const value = BigInt(value_); - let maxValue2; - if (size2) { - if (signed2) - maxValue2 = (1n << BigInt(size2) * 8n - 1n) - 1n; - else - maxValue2 = 2n ** (BigInt(size2) * 8n) - 1n; - } else if (typeof value_ === "number") { - maxValue2 = BigInt(Number.MAX_SAFE_INTEGER); + return Number(chainId); +}; +const maybeChainId = (chainId) => { + if (!chainId) return void 0; + return getChainId(chainId); +}; +const isValidNetworkConfig = (networkConfig, raise = false, skipRelayerCheck = false) => { + if (!networkConfig) throw new Error(`invalid network config: empty config`); + const configs = []; + if (Array.isArray(networkConfig)) { + configs.push(...networkConfig); + } else { + configs.push(networkConfig); } - const minValue = typeof maxValue2 === "bigint" && signed2 ? -maxValue2 - 1n : 0; - if (maxValue2 && value > maxValue2 || value < minValue) { - const suffix = typeof value_ === "bigint" ? "n" : ""; - throw new IntegerOutOfRangeError({ - max: maxValue2 ? `${maxValue2}${suffix}` : void 0, - min: `${minValue}${suffix}`, - signed: signed2, - size: size2, - value: `${value_}${suffix}` - }); + if (configs.length === 0) { + if (raise) throw new Error(`invalid network config: empty config`); + return false; } - const hex2 = `0x${(signed2 && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`; - if (size2) - return pad(hex2, { size: size2 }); - return hex2; -} -const encoder = /* @__PURE__ */ new TextEncoder(); -function stringToHex(value_, opts = {}) { - const value = encoder.encode(value_); - return bytesToHex$1(value, opts); -} -async function addChain(client2, { chain }) { - const { id: id2, name: name2, nativeCurrency, rpcUrls, blockExplorers } = chain; - await client2.request({ - method: "wallet_addEthereumChain", - params: [ - { - chainId: numberToHex(id2), - chainName: name2, - nativeCurrency, - rpcUrls: rpcUrls.default.http, - blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url }) => url) : void 0 + const chainIds = configs.map((c2) => c2.chainId).sort(); + const dupes = chainIds.filter((c2, i) => chainIds.indexOf(c2) !== i); + if (dupes.length > 0) { + if (raise) throw new Error(`invalid network config: duplicate chainIds ${dupes}`); + return false; + } + configs.forEach((c2) => c2.name = c2.name.toLowerCase()); + const names2 = configs.map((c2) => c2.name).sort(); + const nameDupes = names2.filter((c2, i) => names2.indexOf(c2) !== i); + if (nameDupes.length > 0) { + if (raise) throw new Error(`invalid network config: duplicate network names ${nameDupes}`); + return false; + } + let defaultChain = false; + for (let i = 0; i < configs.length; i++) { + const c2 = configs[i]; + if ((!c2.rpcUrl || c2.rpcUrl === "") && !c2.provider) { + if (raise) throw new Error(`invalid network config for chainId ${c2.chainId}: rpcUrl or provider must be provided`); + return false; + } + if (!skipRelayerCheck) { + if (!c2.relayer) { + if (raise) throw new Error(`invalid network config for chainId ${c2.chainId}: relayer must be provided`); + return false; } - ] - }, { dedupe: true, retryCount: 0 }); -} -function formatAbiItem$1(abiItem, { includeName = false } = {}) { - if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error") - throw new InvalidDefinitionTypeError(abiItem.type); - return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`; -} -function formatAbiParams(params, { includeName = false } = {}) { - if (!params) - return ""; - return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ","); -} -function formatAbiParam(param, { includeName }) { - if (param.type.startsWith("tuple")) { - return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`; + } + if (c2.isDefaultChain) { + if (defaultChain) { + if (raise) throw new Error(`invalid network config for chainId ${c2.chainId}: DefaultChain is already set by another config`); + return false; + } + defaultChain = true; + } } - return param.type + (includeName && param.name ? ` ${param.name}` : ""); -} -class AbiConstructorNotFoundError extends BaseError$3 { - constructor({ docsPath: docsPath2 }) { - super([ - "A constructor was not found on the ABI.", - "Make sure you are using the correct ABI and that the constructor exists on it." - ].join("\n"), { - docsPath: docsPath2, - name: "AbiConstructorNotFoundError" - }); + if (!defaultChain) { + if (raise) throw new Error(`invalid network config: DefaultChain must be set`); + return false; } -} -class AbiConstructorParamsNotFoundError extends BaseError$3 { - constructor({ docsPath: docsPath2 }) { - super([ - "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.", - "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists." - ].join("\n"), { - docsPath: docsPath2, - name: "AbiConstructorParamsNotFoundError" - }); + return true; +}; +const ensureValidNetworks = (networks2, skipRelayerCheck = false) => { + isValidNetworkConfig(networks2, true, skipRelayerCheck); + return networks2; +}; +const ensureUniqueNetworks = (networks2, raise = true) => { + const chainIds = networks2.map((c2) => c2.chainId).sort(); + const dupes = chainIds.filter((c2, i) => chainIds.indexOf(c2) !== i); + if (dupes.length > 0) { + if (raise) throw new Error(`invalid network config: duplicate chainIds ${dupes}`); + return false; } -} -class AbiDecodingDataSizeTooSmallError extends BaseError$3 { - constructor({ data, params, size: size2 }) { - super([`Data size of ${size2} bytes is too small for given parameters.`].join("\n"), { - metaMessages: [ - `Params: (${formatAbiParams(params, { includeName: true })})`, - `Data: ${data} (${size2} bytes)` - ], - name: "AbiDecodingDataSizeTooSmallError" - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "params", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "size", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.data = data; - this.params = params; - this.size = size2; + return true; +}; +const updateNetworkConfig = (src, dest) => { + if (!src || !dest) return; + if (!src.chainId && !src.name) { + throw new Error("failed to update network config: source config is missing chainId or name"); } -} -class AbiDecodingZeroDataError extends BaseError$3 { - constructor() { - super('Cannot decode zero data ("0x") with ABI parameters.', { - name: "AbiDecodingZeroDataError" - }); + if (src.chainId !== dest.chainId && src.name !== dest.name) { + throw new Error("failed to update network config: one of chainId or name must match"); } -} -class AbiEncodingArrayLengthMismatchError extends BaseError$3 { - constructor({ expectedLength, givenLength, type }) { - super([ - `ABI encoding array length mismatch for type ${type}.`, - `Expected length: ${expectedLength}`, - `Given length: ${givenLength}` - ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" }); + if (src.rpcUrl) { + dest.rpcUrl = src.rpcUrl; + dest.provider = void 0; } -} -class AbiEncodingBytesSizeMismatchError extends BaseError$3 { - constructor({ expectedSize, value }) { - super(`Size of bytes "${value}" (bytes${size$5(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); + if (src.provider) { + dest.provider = src.provider; } -} -class AbiEncodingLengthMismatchError extends BaseError$3 { - constructor({ expectedLength, givenLength }) { - super([ - "ABI encoding params/values length mismatch.", - `Expected length (params): ${expectedLength}`, - `Given length (values): ${givenLength}` - ].join("\n"), { name: "AbiEncodingLengthMismatchError" }); + if (src.relayer) { + dest.relayer = src.relayer; } -} -class AbiErrorSignatureNotFoundError extends BaseError$3 { - constructor(signature2, { docsPath: docsPath2 }) { - super([ - `Encoded error signature "${signature2}" not found on ABI.`, - "Make sure you are using the correct ABI and that the error exists on it.", - `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature2}.` - ].join("\n"), { - docsPath: docsPath2, - name: "AbiErrorSignatureNotFoundError" - }); - Object.defineProperty(this, "signature", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.signature = signature2; +}; +const validateAndSortNetworks = (networks2) => { + return ensureValidNetworks(sortNetworks(networks2)); +}; +const findNetworkConfig = (networks2, chainId) => { + if (typeof chainId === "string") { + if (chainId.startsWith("0x")) { + const id2 = Number(chainId); + return networks2.find((n2) => n2.chainId === id2); + } else { + return networks2.find((n2) => n2.name === chainId || `${n2.chainId}` === chainId); + } + } else if (typeof chainId === "number") { + return networks2.find((n2) => n2.chainId === chainId); + } else if (chainId.chainId) { + return networks2.find((n2) => n2.chainId === chainId.chainId); + } else if (typeof chainId === "bigint") { + const id2 = Number(chainId); + return networks2.find((n2) => n2.chainId === id2); + } else { + return void 0; } -} -class AbiEventSignatureEmptyTopicsError extends BaseError$3 { - constructor({ docsPath: docsPath2 }) { - super("Cannot extract event signature from empty topics.", { - docsPath: docsPath2, - name: "AbiEventSignatureEmptyTopicsError" - }); +}; +const checkNetworkConfig = (network2, chainId) => { + if (!network2) return false; + if (network2.name === chainId) return true; + if (network2.chainId === chainId) return true; + return false; +}; +const networksIndex = (networks2) => { + const index2 = {}; + for (let i = 0; i < networks2.length; i++) { + index2[networks2[i].name] = networks2[i]; } -} -class AbiEventSignatureNotFoundError extends BaseError$3 { - constructor(signature2, { docsPath: docsPath2 }) { - super([ - `Encoded event signature "${signature2}" not found on ABI.`, - "Make sure you are using the correct ABI and that the event exists on it.", - `You can look up the signature here: https://openchain.xyz/signatures?query=${signature2}.` - ].join("\n"), { - docsPath: docsPath2, - name: "AbiEventSignatureNotFoundError" - }); + return index2; +}; +const sortNetworks = (networks2) => { + if (!networks2) { + return []; } -} -class AbiEventNotFoundError extends BaseError$3 { - constructor(eventName, { docsPath: docsPath2 } = {}) { - super([ - `Event ${eventName ? `"${eventName}" ` : ""}not found on ABI.`, - "Make sure you are using the correct ABI and that the event exists on it." - ].join("\n"), { - docsPath: docsPath2, - name: "AbiEventNotFoundError" + const config2 = networks2.sort((a2, b2) => { + if (a2.chainId === b2.chainId) return 0; + return a2.chainId < b2.chainId ? -1 : 1; + }); + const defaultConfigIdx = config2.findIndex((c2) => c2.isDefaultChain); + if (defaultConfigIdx > 0) config2.splice(0, 0, config2.splice(defaultConfigIdx, 1)[0]); + return config2; +}; +const stringTemplate = (sTemplate, mData) => { + if (typeof sTemplate === "string") { + mData = mData ? mData : {}; + return sTemplate.replace(/\$\{\s*([$#@\-\d\w]+)\s*\}/gim, function(fullMath, grp) { + let val = mData[grp]; + if (typeof val === "function") { + val = val(); + } else if (val === null || val === void 0) { + val = ""; + } else if (typeof val === "object" || typeof val === "symbol") { + val = val.toString(); + } else { + val = val.valueOf(); + } + return val; }); } + return ""; +}; +const indexerURL = (network2) => stringTemplate("https://${network}-indexer.sequence.app", { + network: network2 +}); +const relayerURL = (network2) => stringTemplate("https://${network}-relayer.sequence.app", { + network: network2 +}); +const nodesURL = (network2) => stringTemplate("https://nodes.sequence.app/${network}", { + network: network2 +}); +function findSupportedNetwork(chainIdOrName) { + return findNetworkConfig(allNetworks, chainIdOrName); } -class AbiFunctionNotFoundError extends BaseError$3 { - constructor(functionName, { docsPath: docsPath2 } = {}) { - super([ - `Function ${functionName ? `"${functionName}" ` : ""}not found on ABI.`, - "Make sure you are using the correct ABI and that the function exists on it." - ].join("\n"), { - docsPath: docsPath2, - name: "AbiFunctionNotFoundError" - }); +function toChainIdNumber(chainIdLike) { + if (typeof chainIdLike === "bigint") { + return chainIdLike; } -} -class AbiFunctionOutputsNotFoundError extends BaseError$3 { - constructor(functionName, { docsPath: docsPath2 }) { - super([ - `Function "${functionName}" does not contain any \`outputs\` on ABI.`, - "Cannot decode function result without knowing what the parameter types are.", - "Make sure you are using the correct ABI and that the function exists on it." - ].join("\n"), { - docsPath: docsPath2, - name: "AbiFunctionOutputsNotFoundError" - }); + if (isBigNumberish(chainIdLike)) { + return BigInt(chainIdLike); } + return BigInt(chainIdLike.chainId); } -class AbiItemAmbiguityError extends BaseError$3 { - constructor(x2, y2) { - super("Found ambiguous types in overloaded ABI items.", { - metaMessages: [ - `\`${x2.type}\` in \`${formatAbiItem$1(x2.abiItem)}\`, and`, - `\`${y2.type}\` in \`${formatAbiItem$1(y2.abiItem)}\``, - "", - "These types encode differently and cannot be distinguished at runtime.", - "Remove one of the ambiguous items in the ABI." - ], - name: "AbiItemAmbiguityError" - }); +const createNetworkConfig = (chainId, options) => { + const network2 = networks[chainId]; + if (!network2) { + throw new Error(`Network with chainId ${chainId} not found`); } -} -class BytesSizeMismatchError extends BaseError$3 { - constructor({ expectedSize, givenSize }) { - super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { - name: "BytesSizeMismatchError" - }); + const rpcUrl = nodesURL(network2.name); + return _extends$d({}, network2, { + rpcUrl, + indexerUrl: indexerURL(network2.name), + relayer: { + url: relayerURL(network2.name), + provider: { + url: rpcUrl + } + } + }, options); +}; +const hardhatNetworks = [_extends$d({}, networks[ChainId.HARDHAT], { + rpcUrl: "http://localhost:8545", + relayer: { + url: "http://localhost:3000", + provider: { + url: "http://localhost:8545" + } } -} -class DecodeLogDataMismatch extends BaseError$3 { - constructor({ abiItem, data, params, size: size2 }) { - super([ - `Data size of ${size2} bytes is too small for non-indexed event parameters.` - ].join("\n"), { - metaMessages: [ - `Params: (${formatAbiParams(params, { includeName: true })})`, - `Data: ${data} (${size2} bytes)` - ], - name: "DecodeLogDataMismatch" - }); - Object.defineProperty(this, "abiItem", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "params", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "size", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.abiItem = abiItem; - this.data = data; - this.params = params; - this.size = size2; +}), _extends$d({}, networks[ChainId.HARDHAT_2], { + rpcUrl: "http://localhost:9545", + relayer: { + url: "http://localhost:3000", + provider: { + url: "http://localhost:9545" + } } -} -class DecodeLogTopicsMismatch extends BaseError$3 { - constructor({ abiItem, param }) { - super([ - `Expected a topic for indexed event parameter${param.name ? ` "${param.name}"` : ""} on event "${formatAbiItem$1(abiItem, { includeName: true })}".` - ].join("\n"), { name: "DecodeLogTopicsMismatch" }); - Object.defineProperty(this, "abiItem", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.abiItem = abiItem; +})]; +const allNetworks = validateAndSortNetworks([_extends$d({}, createNetworkConfig(ChainId.POLYGON), { + isDefaultChain: true, + isAuthChain: true +}), createNetworkConfig(ChainId.MAINNET), createNetworkConfig(ChainId.BSC), createNetworkConfig(ChainId.AVALANCHE), createNetworkConfig(ChainId.ARBITRUM), createNetworkConfig(ChainId.ARBITRUM_NOVA), createNetworkConfig(ChainId.OPTIMISM), createNetworkConfig(ChainId.OPTIMISM_SEPOLIA), createNetworkConfig(ChainId.POLYGON_ZKEVM), createNetworkConfig(ChainId.GNOSIS), createNetworkConfig(ChainId.RINKEBY, { + disabled: true +}), createNetworkConfig(ChainId.GOERLI, { + disabled: true +}), createNetworkConfig(ChainId.SEPOLIA), createNetworkConfig(ChainId.POLYGON_MUMBAI, { + disabled: true +}), createNetworkConfig(ChainId.POLYGON_AMOY), createNetworkConfig(ChainId.BSC_TESTNET), createNetworkConfig(ChainId.ARBITRUM_SEPOLIA), createNetworkConfig(ChainId.BASE), createNetworkConfig(ChainId.BASE_SEPOLIA), createNetworkConfig(ChainId.HOMEVERSE), createNetworkConfig(ChainId.HOMEVERSE_TESTNET), createNetworkConfig(ChainId.XAI), createNetworkConfig(ChainId.XAI_SEPOLIA), createNetworkConfig(ChainId.AVALANCHE_TESTNET), createNetworkConfig(ChainId.ASTAR_ZKEVM), createNetworkConfig(ChainId.ASTAR_ZKYOTO), createNetworkConfig(ChainId.XR_SEPOLIA), createNetworkConfig(ChainId.B3_SEPOLIA), createNetworkConfig(ChainId.APECHAIN_TESTNET), createNetworkConfig(ChainId.BLAST), createNetworkConfig(ChainId.BLAST_SEPOLIA), createNetworkConfig(ChainId.TELOS), createNetworkConfig(ChainId.BORNE_TESTNET), createNetworkConfig(ChainId.SKALE_NEBULA_TESTNET), ...hardhatNetworks]); +class JsonRpcRouter { + constructor(middlewares, sender) { + this.sender = void 0; + this.handler = void 0; + this.sender = sender; + if (middlewares) { + this.setMiddleware(middlewares); + } } -} -class InvalidAbiEncodingTypeError extends BaseError$3 { - constructor(type, { docsPath: docsPath2 }) { - super([ - `Type "${type}" is not a valid encoding type.`, - "Please provide a valid ABI type." - ].join("\n"), { docsPath: docsPath2, name: "InvalidAbiEncodingType" }); + setMiddleware(middlewares) { + this.handler = createJsonRpcMiddlewareStack(middlewares, this.sender); } -} -class InvalidAbiDecodingTypeError extends BaseError$3 { - constructor(type, { docsPath: docsPath2 }) { - super([ - `Type "${type}" is not a valid decoding type.`, - "Please provide a valid ABI type." - ].join("\n"), { docsPath: docsPath2, name: "InvalidAbiDecodingType" }); + request(request) { + return this.handler.request(request); } } -class InvalidArrayError extends BaseError$3 { - constructor(value) { - super([`Value "${value}" is not a valid array.`].join("\n"), { - name: "InvalidArrayError" - }); +const createJsonRpcMiddlewareStack = (middlewares, handler) => { + if (middlewares.length === 0) return handler; + const toMiddleware = (v3) => { + if (v3.requestHandler) { + return v3.requestHandler; + } else { + return v3; + } + }; + let chain; + chain = toMiddleware(middlewares[middlewares.length - 1])(handler.request); + for (let i = middlewares.length - 2; i >= 0; i--) { + chain = toMiddleware(middlewares[i])(chain); } + return { + request: chain + }; +}; +function isJsonRpcProvider(cand) { + return cand !== void 0 && cand.send !== void 0 && cand.constructor.defaultUrl !== void 0 && cand.detectNetwork !== void 0 && cand.getSigner !== void 0 && cand.perform !== void 0; } -class InvalidDefinitionTypeError extends BaseError$3 { - constructor(type) { - super([ - `"${type}" is not a valid definition type.`, - 'Valid types: "function", "event", "error"' - ].join("\n"), { name: "InvalidDefinitionTypeError" }); - } +function isJsonRpcSender(cand) { + return cand !== void 0 && cand.send !== void 0; } -function concat(values) { - if (typeof values[0] === "string") - return concatHex(values); - return concatBytes$2(values); +class JsonRpcHandler { + constructor(provider2, defaultChainId) { + this.provider = void 0; + this.defaultChainId = void 0; + this.request = (request) => { + if (!request.chainId) { + request.chainId = this.defaultChainId; + } + return this.provider(request); + }; + if (isJsonRpcSender(provider2)) { + this.provider = (request) => { + return provider2.send(request.method, request.params, request.chainId); + }; + } else if (isJsonRpcProvider(provider2)) { + this.provider = (request) => { + return provider2.send(request.method, request.params || []); + }; + } else { + this.provider = provider2; + } + this.defaultChainId = defaultChainId; + } + send(method, params, chainId) { + const request = { + method, + params, + chainId + }; + return this.request(request); + } } -function concatBytes$2(values) { - let length = 0; - for (const arr of values) { - length += arr.length; +class AllowProvider { + constructor(isAllowedFunc) { + this.requestHandler = void 0; + this.isAllowedFunc = void 0; + if (isAllowedFunc) { + this.isAllowedFunc = isAllowedFunc; + } else { + this.isAllowedFunc = (request) => true; + } + this.requestHandler = allowProviderMiddleware(this.isAllowedFunc); } - const result = new Uint8Array(length); - let offset2 = 0; - for (const arr of values) { - result.set(arr, offset2); - offset2 += arr.length; + setIsAllowedFunc(fn) { + this.isAllowedFunc = fn; + this.requestHandler = allowProviderMiddleware(this.isAllowedFunc); } - return result; } -function concatHex(values) { - return `0x${values.reduce((acc, x2) => acc + x2.replace("0x", ""), "")}`; +const allowProviderMiddleware = (isAllowed) => (next) => { + return (request) => { + if (!isAllowed(request)) { + throw new Error("allowProvider middleware precondition is unmet."); + } + return next(request); + }; +}; +class CachedProvider { + constructor(options) { + var _this = this; + this.cachableJsonRpcMethods = ["net_version", "eth_chainId", "eth_accounts", "sequence_getWalletContext", "sequence_getNetworks"]; + this.cachableJsonRpcMethodsByBlock = ["eth_call", "eth_getCode"]; + this.cache = void 0; + this.cacheByBlock = void 0; + this.cacheByBlockResetLock = false; + this.onUpdateCallback = void 0; + this.defaultChainId = void 0; + this.requestHandler = (next) => { + return async function(request) { + if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) { + const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId); + const _result = _this.getCacheValue(key); + if (_result && _result !== "") { + return { + id: request.id, + result: _result + }; + } + } + const result = await next(request); + if (_this.cachableJsonRpcMethods.includes(request.method) || _this.cachableJsonRpcMethodsByBlock.includes(request.method)) { + if (result && _this.shouldCacheResponse(request, result)) { + const key = _this.cacheKey(request.method, request.params, request.chainId || _this.defaultChainId); + if (_this.cachableJsonRpcMethods.includes(request.method)) { + _this.setCacheValue(key, result); + } else { + _this.setCacheByBlockValue(key, result); + } + } + } + return result; + }; + }; + this.cacheKey = (method, params, chainId) => { + let key = ""; + if (chainId) { + key = `${chainId}:${method}:`; + } else { + key = `:${method}:`; + } + if (!params || params.length === 0) { + return key + "[]"; + } + return key + JSON.stringify(params); + }; + this.getCache = () => this.cache; + this.setCache = (cache2) => { + this.cache = cache2; + if (this.onUpdateCallback) { + this.onUpdateCallback(); + } + }; + this.getCacheValue = (key) => { + if (this.cache[key]) { + return this.cache[key]; + } + if (this.cacheByBlock[key]) { + return this.cacheByBlock[key]; + } + return void 0; + }; + this.setCacheValue = (key, value) => { + this.cache[key] = value; + if (this.onUpdateCallback) { + this.onUpdateCallback(key, value); + } + }; + this.setCacheByBlockValue = (key, value) => { + this.cacheByBlock[key] = value; + if (!this.cacheByBlockResetLock) { + this.cacheByBlockResetLock = true; + setTimeout(() => { + this.cacheByBlockResetLock = false; + this.cacheByBlock = {}; + }, 1500); + } + }; + this.shouldCacheResponse = (request, result) => { + if (!result) { + return false; + } + if (request.method === "eth_getCode" && result.length <= 2) { + return false; + } + return true; + }; + this.clearCache = () => { + this.cache = {}; + this.cacheByBlock = {}; + }; + this.cache = {}; + this.cacheByBlock = {}; + this.defaultChainId = options == null ? void 0 : options.defaultChainId; + if (!(options != null && options.blockCache)) { + this.cachableJsonRpcMethodsByBlock = []; + } else if ((options == null ? void 0 : options.blockCache) !== true) { + this.cachableJsonRpcMethodsByBlock = options == null ? void 0 : options.blockCache; + } + } + onUpdate(callback) { + this.onUpdateCallback = callback; + } } -class InvalidAddressError extends BaseError$3 { - constructor({ address }) { - super(`Address "${address}" is invalid.`, { - metaMessages: [ - "- Address must be a hex value of 20 bytes (40 hex characters).", - "- Address must match its checksum counterpart." - ], - name: "InvalidAddressError" - }); +class EagerProvider { + constructor(options) { + var _this = this; + this.options = void 0; + this.requestHandler = (next) => { + return async function(request) { + switch (request.method) { + case "net_version": + if (_this.options.chainId) { + return `${_this.options.chainId}`; + } + break; + case "eth_chainId": + if (_this.options.chainId) { + return toQuantity(_this.options.chainId); + } + break; + case "eth_accounts": + if (_this.options.accountAddress) { + return [getAddress(_this.options.accountAddress)]; + } + break; + case "sequence_getWalletContext": + if (_this.options.walletContext) { + return _this.options.walletContext; + } + break; + } + return next(request); + }; + }; + this.options = options; } } -class LruMap extends Map { - constructor(size2) { - super(); - Object.defineProperty(this, "maxSize", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxSize = size2; +const exceptionProviderMiddleware = (next) => { + return async (request) => { + try { + return await next(request); + } catch (error) { + if (typeof error === "string") { + throw new Error(error); + } else { + throw new Error(error.message); + } + } + }; +}; +const loggingProviderMiddleware = (next) => { + return async (request) => { + const chainIdLabel = request.chainId ? ` chainId:${request.chainId}` : ""; + logger.info(`[provider request]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params); + try { + const result = await next(request); + logger.info(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `result:`, result); + return result; + } catch (error) { + logger.warn(`[provider response]${chainIdLabel} id:${request.id} method:${request.method} params:`, request.params, `error:`, error); + } + }; +}; +const networkProviderMiddleware = (getChainId2) => (next) => { + return async (request) => { + const networkChainId = getChainId2(request); + switch (request.method) { + case "net_version": { + return `${networkChainId}`; + } + case "eth_chainId": { + return toQuantity(networkChainId); + } + } + return next(request); + }; +}; +const SignerJsonRpcMethods = [ + "personal_sign", + "eth_sign", + "eth_signTypedData", + "eth_signTypedData_v4", + "eth_sendTransaction", + "eth_sendRawTransaction", + "sequence_sign", + // sequence-aware personal_sign + "sequence_signTypedData_v4", + // sequence-aware eth_signTypedData_v4 + "sequence_getWalletContext", + "sequence_getWalletConfig", + "sequence_getWalletState", + "sequence_getNetworks", + "sequence_updateConfig", + "sequence_publishConfig", + "sequence_gasRefundOptions", + "sequence_getNonce", + "sequence_relay", + "eth_decrypt", + "eth_getEncryptionPublicKey", + "wallet_addEthereumChain", + "wallet_switchEthereumChain", + "wallet_registerOnboarding", + "wallet_watchAsset", + "wallet_scanQRCode" +]; +class SigningProvider { + constructor(provider2) { + this.provider = void 0; + this.requestHandler = (next) => { + return (request) => { + if (SignerJsonRpcMethods.includes(request.method)) { + return this.provider.request(request); + } + return next(request); + }; + }; + this.provider = provider2; } - get(key) { - const value = super.get(key); - if (super.has(key) && value !== void 0) { - this.delete(key); - super.set(key, value); +} +class PublicProvider { + constructor(rpcUrl) { + this.privateJsonRpcMethods = ["net_version", "eth_chainId", "eth_accounts", ...SignerJsonRpcMethods]; + this.provider = void 0; + this.rpcUrl = void 0; + this.requestHandler = (next) => { + return (request) => { + if (this.provider && !this.privateJsonRpcMethods.includes(request.method)) { + return this.provider.send(request.method, request.params || []); + } + logger.debug("[public-provider] sending request to signer window", request.method); + return next(request); + }; + }; + if (rpcUrl) { + this.setRpcUrl(rpcUrl); } - return value; } - set(key, value) { - super.set(key, value); - if (this.maxSize && this.size > this.maxSize) { - const firstKey = this.keys().next().value; - if (firstKey) - this.delete(firstKey); - } - return this; + getRpcUrl() { + return this.rpcUrl; } -} -function number(n2) { - if (!Number.isSafeInteger(n2) || n2 < 0) - throw new Error(`positive integer expected, not ${n2}`); -} -function isBytes$1(a2) { - return a2 instanceof Uint8Array || a2 != null && typeof a2 === "object" && a2.constructor.name === "Uint8Array"; -} -function bytes(b2, ...lengths) { - if (!isBytes$1(b2)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b2.length)) - throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b2.length}`); -} -function hash$1(h2) { - if (typeof h2 !== "function" || typeof h2.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - number(h2.outputLen); - number(h2.blockLen); -} -function exists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function output(out, instance) { - bytes(out); - const min2 = instance.outputLen; - if (out.length < min2) { - throw new Error(`digestInto() expects output buffer of length at least ${min2}`); + setRpcUrl(rpcUrl) { + if (!rpcUrl || rpcUrl === "") { + this.rpcUrl = void 0; + this.provider = void 0; + } else { + this.rpcUrl = rpcUrl; + this.provider = new JsonRpcProvider$1(rpcUrl); + } } } -const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); -const _32n = /* @__PURE__ */ BigInt(32); -function fromBig(n2, le2 = false) { - if (le2) - return { h: Number(n2 & U32_MASK64), l: Number(n2 >> _32n & U32_MASK64) }; - return { h: Number(n2 >> _32n & U32_MASK64) | 0, l: Number(n2 & U32_MASK64) | 0 }; -} -function split(lst, le2 = false) { - let Ah2 = new Uint32Array(lst.length); - let Al = new Uint32Array(lst.length); - for (let i = 0; i < lst.length; i++) { - const { h: h2, l: l2 } = fromBig(lst[i], le2); - [Ah2[i], Al[i]] = [h2, l2]; +class SingleflightMiddleware { + constructor() { + var _this = this; + this.singleflightJsonRpcMethods = ["eth_chainId", "net_version", "eth_call", "eth_getCode", "eth_blockNumber", "eth_getBalance", "eth_getStorageAt", "eth_getTransactionCount", "eth_getBlockTransactionCountByHash", "eth_getBlockTransactionCountByNumber", "eth_getUncleCountByBlockHash", "eth_getUncleCountByBlockNumber", "eth_getBlockByHash", "eth_getBlockByNumber", "eth_getTransactionByHash", "eth_getTransactionByBlockHashAndIndex", "eth_getTransactionByBlockNumberAndIndex", "eth_getTransactionReceipt", "eth_getUncleByBlockHashAndIndex", "eth_getUncleByBlockNumberAndIndex", "eth_getLogs"]; + this.inflight = void 0; + this.requestHandler = (next) => { + return async function(request) { + if (!_this.singleflightJsonRpcMethods.includes(request.method)) { + return next(request); + } + const key = _this.requestKey(request.method, request.params || [], request.chainId); + if (!_this.inflight[key]) { + _this.inflight[key] = []; + } else { + return new Promise((resolve, reject) => { + _this.inflight[key].push({ + id: request.id, + callback: (error, response) => { + if (error) { + reject(error); + } else { + resolve(response); + } + } + }); + }); + } + try { + const response = await next(request); + _this.inflight[key].forEach(({ + callback + }) => callback(void 0, response)); + return response; + } catch (error) { + _this.inflight[key].forEach(({ + callback + }) => callback(error, void 0)); + throw error; + } finally { + delete _this.inflight[key]; + } + }; + }; + this.requestKey = (method, params, chainId) => { + let key = ""; + if (chainId) { + key = `${chainId}:${method}:`; + } else { + key = `:${method}:`; + } + if (!params || params.length === 0) { + return key + "[]"; + } + return key + JSON.stringify(params); + }; + this.inflight = {}; } - return [Ah2, Al]; } -const rotlSH = (h2, l2, s2) => h2 << s2 | l2 >>> 32 - s2; -const rotlSL = (h2, l2, s2) => l2 << s2 | h2 >>> 32 - s2; -const rotlBH = (h2, l2, s2) => l2 << s2 - 32 | h2 >>> 64 - s2; -const rotlBL = (h2, l2, s2) => h2 << s2 - 32 | l2 >>> 64 - s2; -const crypto$1 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; -/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -const rotr = (word, shift2) => word << 32 - shift2 | word >>> shift2; -const isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; -const byteSwap = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; -function byteSwap32(arr) { - for (let i = 0; i < arr.length; i++) { - arr[i] = byteSwap(arr[i]); +function _classPrivateFieldBase(receiver, privateKey) { + if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { + throw new TypeError("attempted to use private field on non-instance"); } + return receiver; } -function utf8ToBytes$1(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); -} -function toBytes(data) { - if (typeof data === "string") - data = utf8ToBytes$1(data); - bytes(data); - return data; +var id = 0; +function _classPrivateFieldKey(name2) { + return "__private_" + id++ + "_" + name2; } -function concatBytes$1(...arrays) { - let sum = 0; - for (let i = 0; i < arrays.length; i++) { - const a2 = arrays[i]; - bytes(a2); - sum += a2.length; +var _chainId = /* @__PURE__ */ _classPrivateFieldKey("chainId"); +var _nextId = /* @__PURE__ */ _classPrivateFieldKey("nextId"); +var _sender = /* @__PURE__ */ _classPrivateFieldKey("sender"); +class JsonRpcProvider extends JsonRpcProvider$1 { + constructor(url, options, jsonRpcApiProviderOptions) { + var _this; + super(url, options == null ? void 0 : options.chainId, jsonRpcApiProviderOptions); + _this = this; + this.url = url; + Object.defineProperty(this, _chainId, { + writable: true, + value: void 0 + }); + Object.defineProperty(this, _nextId, { + writable: true, + value: 1 + }); + Object.defineProperty(this, _sender, { + writable: true, + value: void 0 + }); + this.fetch = async function(request) { + if (_this.url === void 0) { + throw new Error("missing provider URL"); + } + const { + method, + params + } = request; + const jsonRpcRequest = { + method, + params, + id: _classPrivateFieldBase(_this, _nextId)[_nextId]++, + jsonrpc: "2.0" + }; + const fetchRequest = typeof _this.url === "string" ? new FetchRequest(_this.url) : _this.url; + fetchRequest.body = JSON.stringify(jsonRpcRequest); + try { + const res = await fetchRequest.send(); + if (res.body) { + try { + const result = JSON.parse(toUtf8String(res.body)); + return getResult(result); + } catch (err) { + throw new Error("invalid JSON response"); + } + } + return null; + } catch (err) { + throw err; + } + }; + const chainId = options == null ? void 0 : options.chainId; + const middlewares = options == null ? void 0 : options.middlewares; + const blockCache = options == null ? void 0 : options.blockCache; + _classPrivateFieldBase(this, _chainId)[_chainId] = chainId; + const router = new JsonRpcRouter(middlewares != null ? middlewares : [ + // loggingProviderMiddleware, + new EagerProvider({ + chainId + }), + new SingleflightMiddleware(), + new CachedProvider({ + defaultChainId: chainId, + blockCache + }) + ], new JsonRpcHandler(this.fetch, chainId)); + _classPrivateFieldBase(this, _sender)[_sender] = router; } - const res = new Uint8Array(sum); - for (let i = 0, pad2 = 0; i < arrays.length; i++) { - const a2 = arrays[i]; - res.set(a2, pad2); - pad2 += a2.length; + async request(request) { + return _classPrivateFieldBase(this, _sender)[_sender].request(request); } - return res; -} -class Hash3 { - // Safe version that clones internal state - clone() { - return this._cloneInto(); + async send(method, params, chainId) { + return this.request({ + method, + params, + chainId + }); } -} -function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; -} -function randomBytes(bytesLength = 32) { - if (crypto$1 && typeof crypto$1.getRandomValues === "function") { - return crypto$1.getRandomValues(new Uint8Array(bytesLength)); + async getNetwork() { + const chainId = _classPrivateFieldBase(this, _chainId)[_chainId]; + if (chainId) { + const network2 = networks[chainId]; + const name2 = (network2 == null ? void 0 : network2.name) || ""; + const ensAddress = network2 == null ? void 0 : network2.ensAddress; + return Network.from({ + name: name2, + chainId, + ensAddress + }); + } else { + const chainIdHex = await this.send("eth_chainId", []); + _classPrivateFieldBase(this, _chainId)[_chainId] = Number(chainIdHex); + return this.getNetwork(); + } } - throw new Error("crypto.getRandomValues must be defined"); } -const SHA3_PI = []; -const SHA3_ROTL = []; -const _SHA3_IOTA = []; -const _0n$4 = /* @__PURE__ */ BigInt(0); -const _1n$5 = /* @__PURE__ */ BigInt(1); -const _2n$3 = /* @__PURE__ */ BigInt(2); -const _7n = /* @__PURE__ */ BigInt(7); -const _256n = /* @__PURE__ */ BigInt(256); -const _0x71n = /* @__PURE__ */ BigInt(113); -for (let round2 = 0, R2 = _1n$5, x2 = 1, y2 = 0; round2 < 24; round2++) { - [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; - SHA3_PI.push(2 * (5 * y2 + x2)); - SHA3_ROTL.push((round2 + 1) * (round2 + 2) / 2 % 64); - let t2 = _0n$4; - for (let j2 = 0; j2 < 7; j2++) { - R2 = (R2 << _1n$5 ^ (R2 >> _7n) * _0x71n) % _256n; - if (R2 & _2n$3) - t2 ^= _1n$5 << (_1n$5 << /* @__PURE__ */ BigInt(j2)) - _1n$5; +function getResult(payload) { + if (payload.error) { + const error = new Error(payload.error.message); + error.code = payload.error.code; + error.data = payload.error.data; + throw error; } - _SHA3_IOTA.push(t2); + return payload.result; } -const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); -const rotlH = (h2, l2, s2) => s2 > 32 ? rotlBH(h2, l2, s2) : rotlSH(h2, l2, s2); -const rotlL = (h2, l2, s2) => s2 > 32 ? rotlBL(h2, l2, s2) : rotlSL(h2, l2, s2); -function keccakP(s2, rounds = 24) { - const B2 = new Uint32Array(5 * 2); - for (let round2 = 24 - rounds; round2 < 24; round2++) { - for (let x2 = 0; x2 < 10; x2++) - B2[x2] = s2[x2] ^ s2[x2 + 10] ^ s2[x2 + 20] ^ s2[x2 + 30] ^ s2[x2 + 40]; - for (let x2 = 0; x2 < 10; x2 += 2) { - const idx1 = (x2 + 8) % 10; - const idx0 = (x2 + 2) % 10; - const B0 = B2[idx0]; - const B1 = B2[idx0 + 1]; - const Th2 = rotlH(B0, B1, 1) ^ B2[idx1]; - const Tl = rotlL(B0, B1, 1) ^ B2[idx1 + 1]; - for (let y2 = 0; y2 < 50; y2 += 10) { - s2[x2 + y2] ^= Th2; - s2[x2 + y2 + 1] ^= Tl; +const network$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + AllowProvider, + CachedProvider, + ChainId, + EagerProvider, + JsonRpcHandler, + JsonRpcProvider, + JsonRpcRouter, + NetworkType, + PublicProvider, + SigningProvider, + SingleflightMiddleware, + allNetworks, + allowProviderMiddleware, + checkNetworkConfig, + createJsonRpcMiddlewareStack, + ensureUniqueNetworks, + ensureValidNetworks, + exceptionProviderMiddleware, + findNetworkConfig, + findSupportedNetwork, + getChainId, + hardhatNetworks, + indexerURL, + isJsonRpcProvider, + isJsonRpcSender, + isNetworkConfig, + isValidNetworkConfig, + loggingProviderMiddleware, + maybeChainId, + networkProviderMiddleware, + networks, + networksIndex, + nodesURL, + relayerURL, + sortNetworks, + stringTemplate, + toChainIdNumber, + updateNetworkConfig, + validateAndSortNetworks +}, Symbol.toStringTag, { value: "Module" })); +function _extends$c() { + _extends$c = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } } } - let curH = s2[2]; - let curL = s2[3]; - for (let t2 = 0; t2 < 24; t2++) { - const shift2 = SHA3_ROTL[t2]; - const Th2 = rotlH(curH, curL, shift2); - const Tl = rotlL(curH, curL, shift2); - const PI = SHA3_PI[t2]; - curH = s2[PI]; - curL = s2[PI + 1]; - s2[PI] = Th2; - s2[PI + 1] = Tl; - } - for (let y2 = 0; y2 < 50; y2 += 10) { - for (let x2 = 0; x2 < 10; x2++) - B2[x2] = s2[y2 + x2]; - for (let x2 = 0; x2 < 10; x2++) - s2[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; - } - s2[0] ^= SHA3_IOTA_H[round2]; - s2[1] ^= SHA3_IOTA_L[round2]; - } - B2.fill(0); + return target; + }; + return _extends$c.apply(this, arguments); } -class Keccak2 extends Hash3 { - // NOTE: we accept arguments in bytes instead of bits here. - constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { - super(); - this.blockLen = blockLen; - this.suffix = suffix; - this.outputLen = outputLen; - this.enableXOF = enableXOF; - this.rounds = rounds; - this.pos = 0; - this.posOut = 0; - this.finished = false; - this.destroyed = false; - number(outputLen); - if (0 >= this.blockLen || this.blockLen >= 200) - throw new Error("Sha3 supports only keccak-f1600 function"); - this.state = new Uint8Array(200); - this.state32 = u32(this.state); - } - keccak() { - if (!isLE) - byteSwap32(this.state32); - keccakP(this.state32, this.rounds); - if (!isLE) - byteSwap32(this.state32); - this.posOut = 0; - this.pos = 0; - } - update(data) { - exists(this); - const { blockLen, state } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0; i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); - } - return this; - } - finish() { - if (this.finished) - return; - this.finished = true; - const { state, suffix, pos, blockLen } = this; - state[pos] ^= suffix; - if ((suffix & 128) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 128; - this.keccak(); - } - writeInto(out) { - exists(this, false); - bytes(out); - this.finish(); - const bufferOut = this.state; - const { blockLen } = this; - for (let pos = 0, len = out.length; pos < len; ) { - if (this.posOut >= blockLen) - this.keccak(); - const take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; - } - return out; - } - xofInto(out) { - if (!this.enableXOF) - throw new Error("XOF is not possible for this instance"); - return this.writeInto(out); - } - xof(bytes2) { - number(bytes2); - return this.xofInto(new Uint8Array(bytes2)); - } - digestInto(out) { - output(out, this); - if (this.finished) - throw new Error("digest() was already called"); - this.writeInto(out); - this.destroy(); - return out; +var config$2 = /* @__PURE__ */ Object.freeze({ + __proto__: null +}); +function subdigestOf(payload) { + return solidityPackedKeccak256(["bytes", "uint256", "address", "bytes32"], ["0x1901", payload.chainId, payload.address, payload.digest]); +} +function isSignedPayload(payload) { + return payload.digest !== void 0 && payload.chainId !== void 0 && payload.address !== void 0; +} +var signature$2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + subdigestOf, + isSignedPayload +}); +const EIP1271_MAGIC_VALUE = "0x1626ba7e"; +const EIP1271_ABI = [{ + inputs: [{ + internalType: "bytes32", + type: "bytes32" + }, { + internalType: "bytes", + type: "bytes" + }], + name: "isValidSignature", + outputs: [{ + internalType: "bytes4", + type: "bytes4" + }], + stateMutability: "view", + type: "function" +}]; +async function isValidEIP1271Signature(address, digest, signature2, provider2) { + const contract = new Contract(address, EIP1271_ABI, provider2); + const result = await contract.isValidSignature(digest, signature2); + return result === EIP1271_MAGIC_VALUE; +} +var validateEIP1271 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + isValidEIP1271Signature +}); +let SigType = /* @__PURE__ */ function(SigType2) { + SigType2[SigType2["EIP712"] = 1] = "EIP712"; + SigType2[SigType2["ETH_SIGN"] = 2] = "ETH_SIGN"; + SigType2[SigType2["WALLET_BYTES32"] = 3] = "WALLET_BYTES32"; + return SigType2; +}({}); +function canRecover(signature2) { + const bytes2 = getBytes(signature2); + const type = bytes2[bytes2.length - 1]; + return type === SigType.EIP712 || type === SigType.ETH_SIGN; +} +function recoverSigner(digest, signature2) { + const bytes2 = getBytes(signature2); + const digestBytes = getBytes(digest); + const type = bytes2[bytes2.length - 1]; + const r2 = hexlify(bytes2.slice(0, 32)); + const s2 = hexlify(bytes2.slice(32, 64)); + const v3 = Number(hexlify(bytes2.slice(64, 65))); + const splitSignature = { + r: r2, + s: s2, + v: v3 + }; + if (type === SigType.EIP712) { + return recoverAddress(digestBytes, splitSignature); } - digest() { - return this.digestInto(new Uint8Array(this.outputLen)); + if (type === SigType.ETH_SIGN) { + return recoverAddress(hashMessage(digestBytes), splitSignature); } - destroy() { - this.destroyed = true; - this.state.fill(0); + throw new Error(`Unsupported signature type: ${type}`); +} +function isValidSignature$1(address, digest, signature2, provider2) { + const bytes2 = getBytes(signature2); + const type = bytes2[bytes2.length - 1]; + if (type === SigType.EIP712 || type === SigType.ETH_SIGN) { + return address === recoverSigner(digest, signature2); } - _cloneInto(to) { - const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to || (to = new Keccak2(blockLen, suffix, outputLen, enableXOF, rounds)); - to.state32.set(this.state32); - to.pos = this.pos; - to.posOut = this.posOut; - to.finished = this.finished; - to.rounds = rounds; - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.destroyed = this.destroyed; - return to; + if (type === SigType.WALLET_BYTES32) { + return isValidEIP1271Signature(address, hexlify(digest), bytes2.slice(0, -1), provider2); } + throw new Error(`Unsupported signature type: ${type}`); } -const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak2(blockLen, suffix, outputLen)); -const keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); -function keccak256(value, to_) { - const to = to_ || "hex"; - const bytes2 = keccak_256(isHex(value, { strict: false }) ? toBytes$1(value) : value); - if (to === "bytes") - return bytes2; - return toHex$1(bytes2); -} -const checksumAddressCache = /* @__PURE__ */ new LruMap(8192); -function checksumAddress(address_, chainId) { - if (checksumAddressCache.has(`${address_}.${chainId}`)) - return checksumAddressCache.get(`${address_}.${chainId}`); - const hexAddress = address_.substring(2).toLowerCase(); - const hash2 = keccak256(stringToBytes(hexAddress), "bytes"); - const address = hexAddress.split(""); - for (let i = 0; i < 40; i += 2) { - if (hash2[i >> 1] >> 4 >= 8 && address[i]) { - address[i] = address[i].toUpperCase(); - } - if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) { - address[i + 1] = address[i + 1].toUpperCase(); - } +function tryRecoverSigner(digest, signature2) { + const bytes2 = getBytes(signature2); + if (bytes2.length !== 66) return void 0; + try { + return recoverSigner(digest, bytes2); + } catch (_unused) { } - const result = `0x${address.join("")}`; - checksumAddressCache.set(`${address_}.${chainId}`, result); - return result; -} -function getAddress(address, chainId) { - if (!isAddress(address, { strict: false })) - throw new InvalidAddressError({ address }); - return checksumAddress(address, chainId); + return void 0; } -const addressRegex = /^0x[a-fA-F0-9]{40}$/; -const isAddressCache = /* @__PURE__ */ new LruMap(8192); -function isAddress(address, options) { - const { strict = true } = options ?? {}; - const cacheKey2 = `${address}.${strict}`; - if (isAddressCache.has(cacheKey2)) - return isAddressCache.get(cacheKey2); - const result = (() => { - if (!addressRegex.test(address)) - return false; - if (address.toLowerCase() === address) - return true; - if (strict) - return checksumAddress(address) === address; - return true; - })(); - isAddressCache.set(cacheKey2, result); - return result; +var signer = /* @__PURE__ */ Object.freeze({ + __proto__: null, + SigType, + canRecover, + recoverSigner, + isValidSignature: isValidSignature$1, + tryRecoverSigner +}); +let SignaturePartType$1 = /* @__PURE__ */ function(SignaturePartType2) { + SignaturePartType2[SignaturePartType2["EOASignature"] = 0] = "EOASignature"; + SignaturePartType2[SignaturePartType2["Address"] = 1] = "Address"; + SignaturePartType2[SignaturePartType2["DynamicSignature"] = 2] = "DynamicSignature"; + return SignaturePartType2; +}({}); +function isAddressMember(member) { + return member.address !== void 0 && !isUnrecoveredSignatureMember(member); } -function slice(value, start, end, { strict } = {}) { - if (isHex(value, { strict: false })) - return sliceHex(value, start, end, { - strict - }); - return sliceBytes(value, start, end, { - strict - }); +function isUnrecoveredSignatureMember(member) { + return member.signature !== void 0 && member.weight !== void 0 && member.isDynamic !== void 0; } -function assertStartOffset(value, start) { - if (typeof start === "number" && start > 0 && start > size$5(value) - 1) - throw new SliceOffsetOutOfBoundsError({ - offset: start, - position: "start", - size: size$5(value) - }); +function isUnrecoveredSignature$1(signature2) { + return signature2.threshold !== void 0 && signature2.signers !== void 0; } -function assertEndOffset(value, start, end) { - if (typeof start === "number" && typeof end === "number" && size$5(value) !== end - start) { - throw new SliceOffsetOutOfBoundsError({ - offset: end, - position: "end", - size: size$5(value) - }); +function decodeSignature$1(signature2) { + const bytes2 = getBytes(signature2); + const threshold = bytes2[0] << 8 | bytes2[1]; + const signers = []; + for (let i = 2; i < bytes2.length; ) { + const type = bytes2[i++]; + const weight = bytes2[i++]; + switch (type) { + case SignaturePartType$1.EOASignature: + signers.push({ + unrecovered: true, + weight, + signature: hexlify(bytes2.slice(i, i + 66)), + isDynamic: false + }); + i += 66; + break; + case SignaturePartType$1.Address: + signers.push({ + weight, + address: getAddress(hexlify(bytes2.slice(i, i + 20))) + }); + i += 20; + break; + case SignaturePartType$1.DynamicSignature: + const address = getAddress(hexlify(bytes2.slice(i, i + 20))); + i += 20; + const size2 = bytes2[i] << 8 | bytes2[i + 1]; + i += 2; + signers.push({ + unrecovered: true, + weight, + signature: hexlify(bytes2.slice(i, i + size2)), + address, + isDynamic: true + }); + i += size2; + break; + default: + throw new Error(`Unknown signature part type: ${type}`); + } } + return { + version: 1, + threshold, + signers + }; } -function sliceBytes(value_, start, end, { strict } = {}) { - assertStartOffset(value_, start); - const value = value_.slice(start, end); - if (strict) - assertEndOffset(value, start, end); - return value; -} -function sliceHex(value_, start, end, { strict } = {}) { - assertStartOffset(value_, start); - const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`; - if (strict) - assertEndOffset(value, start, end); - return value; -} -function encodeAbiParameters(params, values) { - if (params.length !== values.length) - throw new AbiEncodingLengthMismatchError({ - expectedLength: params.length, - givenLength: values.length - }); - const preparedParams = prepareParams({ - params, - values +function encodeSignature$1(signature2) { + if (isBytesLike(signature2)) { + return hexlify(signature2); + } + const { + signers, + threshold + } = isUnrecoveredSignature$1(signature2) ? signature2 : signature2.config; + const encodedSigners = signers.map((s2) => { + if (isAddressMember(s2)) { + return solidityPacked(["uint8", "uint8", "address"], [SignaturePartType$1.Address, s2.weight, s2.address]); + } + if (s2.isDynamic) { + const bytes2 = getBytes(s2.signature); + return solidityPacked(["uint8", "uint8", "address", "uint16", "bytes"], [SignaturePartType$1.DynamicSignature, s2.weight, s2.address, bytes2.length, bytes2]); + } + return solidityPacked(["uint8", "uint8", "bytes"], [SignaturePartType$1.EOASignature, s2.weight, s2.signature]); }); - const data = encodeParams(preparedParams); - if (data.length === 0) - return "0x"; - return data; + return solidityPacked(["uint16", ...new Array(encodedSigners.length).fill("bytes")], [threshold, ...encodedSigners]); } -function prepareParams({ params, values }) { - const preparedParams = []; - for (let i = 0; i < params.length; i++) { - preparedParams.push(prepareParam({ param: params[i], value: values[i] })); - } - return preparedParams; +async function recoverSignature$1(data, payload, provider2) { + const subdigest = subdigestOf(payload); + const signers = await Promise.all(data.signers.map(async (s2) => { + if (isAddressMember(s2)) { + return s2; + } + if (s2.isDynamic) { + if (!s2.address) throw new Error("Dynamic signature part must have address"); + if (!isValidSignature$1(s2.address, subdigest, s2.signature, provider2)) { + throw new Error(`Invalid dynamic signature part ${s2.address}`); + } + return { + address: s2.address, + weight: s2.weight, + signature: s2.signature + }; + } else { + const address = recoverSigner(subdigest, s2.signature); + return { + address, + weight: s2.weight, + signature: s2.signature + }; + } + })); + return { + version: 1, + payload, + subdigest, + config: { + version: 1, + threshold: data.threshold, + signers + } + }; } -function prepareParam({ param, value }) { - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return encodeArray(value, { length, param: { ...param, type } }); +function encodeSigners$1(config2, signatures, subdigests, _) { + if (subdigests.length !== 0) { + throw new Error("Explicit subdigests not supported on v1"); } - if (param.type === "tuple") { - return encodeTuple(value, { - param + let weight = 0n; + const parts = config2.signers.map((s2) => { + if (!signatures.has(s2.address)) { + return s2; + } + const signature2 = signatures.get(s2.address); + const bytes2 = getBytes(signature2.signature); + weight += BigInt(s2.weight); + if (signature2.isDynamic || bytes2.length !== 66) { + return _extends$c({}, s2, { + isDynamic: true, + signature: signature2.signature, + address: s2.address + }); + } + return _extends$c({}, s2, { + isDynamic: false, + signature: signature2.signature }); - } - if (param.type === "address") { - return encodeAddress(value); - } - if (param.type === "bool") { - return encodeBool(value); - } - if (param.type.startsWith("uint") || param.type.startsWith("int")) { - const signed2 = param.type.startsWith("int"); - return encodeNumber(value, { signed: signed2 }); - } - if (param.type.startsWith("bytes")) { - return encodeBytes(value, { param }); - } - if (param.type === "string") { - return encodeString(value); - } - throw new InvalidAbiEncodingTypeError(param.type, { - docsPath: "/docs/contract/encodeAbiParameters" }); + const encoded = encodeSignature$1({ + version: 1, + threshold: config2.threshold, + signers: parts + }); + return { + encoded, + weight + }; } -function encodeParams(preparedParams) { - let staticSize = 0; - for (let i = 0; i < preparedParams.length; i++) { - const { dynamic, encoded } = preparedParams[i]; - if (dynamic) - staticSize += 32; - else - staticSize += size$5(encoded); +const SignatureCoder$1 = { + decode: (data) => { + return decodeSignature$1(data); + }, + encode: (data) => { + return encodeSignature$1(data); + }, + trim: async (data) => { + return data; + }, + supportsNoChainId: true, + recover: (data, payload, provider2) => { + return recoverSignature$1(data, payload, provider2); + }, + encodeSigners: (config2, signatures, subdigests, chainId) => { + return encodeSigners$1(config2, signatures, subdigests); + }, + hasEnoughSigningPower: (config2, signatures) => { + const { + weight + } = SignatureCoder$1.encodeSigners(config2, signatures, [], 0); + return weight >= BigInt(config2.threshold); + }, + chainSignatures: (_main, _suffix) => { + throw new Error("Signature chaining not supported on v1"); + }, + hashSetImageHash: function(_imageHash) { + throw new Error("Image hash not supported on v1"); + }, + signaturesOf(config2) { + return config2.signers.filter((s2) => s2.signature !== void 0).map((s2) => ({ + address: s2.address, + signature: s2.signature + })); + }, + signaturesOfDecoded: function(data) { + return data.signers.map((s2) => s2.signature).filter((s2) => s2 !== void 0); } - const staticParams = []; - const dynamicParams = []; - let dynamicSize = 0; - for (let i = 0; i < preparedParams.length; i++) { - const { dynamic, encoded } = preparedParams[i]; - if (dynamic) { - staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 })); - dynamicParams.push(encoded); - dynamicSize += size$5(encoded); - } else { - staticParams.push(encoded); +}; +var signature$1 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + SignaturePartType: SignaturePartType$1, + isAddressMember, + isUnrecoveredSignatureMember, + isUnrecoveredSignature: isUnrecoveredSignature$1, + decodeSignature: decodeSignature$1, + encodeSignature: encodeSignature$1, + recoverSignature: recoverSignature$1, + encodeSigners: encodeSigners$1, + SignatureCoder: SignatureCoder$1 +}); +const ConfigCoder$1 = { + isWalletConfig: (config2) => { + return config2.version === 1 && config2.threshold !== void 0 && config2.signers !== void 0; + }, + imageHashOf: (config2) => { + return config2.signers.reduce((imageHash2, signer2) => keccak256(AbiCoder.defaultAbiCoder().encode(["bytes32", "uint8", "address"], [imageHash2, signer2.weight, signer2.address])), solidityPacked(["uint256"], [config2.threshold])); + }, + hasSubdigest: (_walletConfig, _subdigest) => { + return false; + }, + isComplete: (_config) => { + return true; + }, + checkpointOf: (_config) => { + return 0n; + }, + signersOf: (config2) => { + return config2.signers.map((s2) => ({ + address: s2.address, + weight: Number(s2.weight) + })); + }, + fromSimple: (config2) => { + if (BigInt(config2.checkpoint) !== 0n) { + throw new Error("v1 wallet config does not support checkpoint"); } - } - return concat([...staticParams, ...dynamicParams]); -} -function encodeAddress(value) { - if (!isAddress(value)) - throw new InvalidAddressError({ address: value }); - return { dynamic: false, encoded: padHex(value.toLowerCase()) }; -} -function encodeArray(value, { length, param }) { - const dynamic = length === null; - if (!Array.isArray(value)) - throw new InvalidArrayError(value); - if (!dynamic && value.length !== length) - throw new AbiEncodingArrayLengthMismatchError({ - expectedLength: length, - givenLength: value.length, - type: `${param.type}[${length}]` + if (config2.subdigests && config2.subdigests.length > 0) { + throw new Error("v1 wallet config does not support subdigests"); + } + return { + version: 1, + threshold: config2.threshold, + signers: config2.signers + }; + }, + update: { + isKindUsed: true, + buildTransaction: (wallet, config2, context2, kind) => { + const module2 = new Interface([...walletContracts.mainModule.abi, ...walletContracts.mainModuleUpgradable.abi]); + const transactions2 = []; + if (!kind || kind === "first") { + transactions2.push({ + to: wallet, + data: module2.encodeFunctionData(module2.getFunction("updateImplementation"), [context2.mainModuleUpgradable]), + gasLimit: 0, + delegateCall: false, + revertOnError: true, + value: 0 + }); + } + transactions2.push({ + to: wallet, + data: module2.encodeFunctionData(module2.getFunction("updateImageHash"), [ConfigCoder$1.imageHashOf(config2)]), + gasLimit: 0, + delegateCall: false, + revertOnError: true, + value: 0 + }); + return { + entrypoint: wallet, + transactions: transactions2 + }; + }, + decodeTransaction: function(tx) { + throw new Error("Function not implemented."); + } + }, + toJSON: function(config2) { + const plainMembers = config2.signers.map((signer2) => { + return { + weight: BigInt(signer2.weight).toString(), + address: signer2.address + }; }); - let dynamicChild = false; - const preparedParams = []; - for (let i = 0; i < value.length; i++) { - const preparedParam = prepareParam({ param, value: value[i] }); - if (preparedParam.dynamic) - dynamicChild = true; - preparedParams.push(preparedParam); - } - if (dynamic || dynamicChild) { - const data = encodeParams(preparedParams); - if (dynamic) { - const length2 = numberToHex(preparedParams.length, { size: 32 }); + return JSON.stringify({ + version: config2.version, + threshold: BigInt(config2.threshold).toString(), + signers: plainMembers + }); + }, + fromJSON: function(json) { + const parsed = JSON.parse(json); + const signers = parsed.signers.map((signer2) => { return { - dynamic: true, - encoded: preparedParams.length > 0 ? concat([length2, data]) : length2 + weight: BigInt(signer2.weight), + address: signer2.address }; + }); + return { + version: parsed.version, + threshold: BigInt(parsed.threshold), + signers + }; + }, + editConfig: function(config2, action) { + var _action$threshold; + const newSigners = config2.signers.slice(); + if (action.checkpoint && BigInt(action.checkpoint) !== 0n) { + throw new Error("v1 wallet config does not support checkpoint"); + } + if (action.add) { + for (const signer2 of action.add) { + if (newSigners.find((s2) => s2.address === signer2.address)) { + continue; + } + newSigners.push({ + weight: signer2.weight, + address: signer2.address + }); + } + } + if (action.remove) { + for (const address of action.remove) { + const index2 = newSigners.findIndex((signer2) => signer2.address === address); + if (index2 >= 0) { + newSigners.splice(index2, 1); + } + } } - if (dynamicChild) - return { dynamic: true, encoded: data }; - } - return { - dynamic: false, - encoded: concat(preparedParams.map(({ encoded }) => encoded)) - }; -} -function encodeBytes(value, { param }) { - const [, paramSize] = param.type.split("bytes"); - const bytesSize = size$5(value); - if (!paramSize) { - let value_ = value; - if (bytesSize % 32 !== 0) - value_ = padHex(value_, { - dir: "right", - size: Math.ceil((value.length - 2) / 2 / 32) * 32 - }); return { - dynamic: true, - encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]) + version: config2.version, + threshold: (_action$threshold = action.threshold) != null ? _action$threshold : config2.threshold, + signers: newSigners }; + }, + buildStubSignature: function(config2, overrides) { + const parts = /* @__PURE__ */ new Map(); + for (const [signer2, signature2] of overrides.entries()) { + parts.set(signer2, { + signature: signature2, + isDynamic: true + }); + const { + encoded, + weight + } = encodeSigners$1(config2, parts, []); + if (weight >= BigInt(config2.threshold)) { + return encoded; + } + } + const signers = config2.signers; + for (const { + address + } of signers.sort(({ + weight: a2 + }, { + weight: b2 + }) => Number(a2) - Number(b2))) { + const signature2 = "0x4e82f02f388a12b5f9d29eaf2452dd040c0ee5804b4e504b4dd64e396c6c781f2c7624195acba242dd825bfd25a290912e3c230841fd55c9a734c4de8d9899451b02"; + parts.set(address, { + signature: signature2, + isDynamic: false + }); + const { + encoded, + weight + } = encodeSigners$1(config2, parts, []); + if (weight >= BigInt(config2.threshold)) { + return encoded; + } + } + return encodeSigners$1(config2, parts, []).encoded; } - if (bytesSize !== Number.parseInt(paramSize)) - throw new AbiEncodingBytesSizeMismatchError({ - expectedSize: Number.parseInt(paramSize), - value - }); - return { dynamic: false, encoded: padHex(value, { dir: "right" }) }; -} -function encodeBool(value) { - if (typeof value !== "boolean") - throw new BaseError$3(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); - return { dynamic: false, encoded: padHex(boolToHex(value)) }; +}; +var config$1 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ConfigCoder: ConfigCoder$1 +}); +var context$2 = /* @__PURE__ */ Object.freeze({ + __proto__: null +}); +const version$1$1 = 1; +const DeployedWalletContext$1 = { + version: version$1$1, + factory: "0xf9D09D634Fb818b05149329C1dcCFAeA53639d96", + guestModule: "0x02390F3E6E5FD1C6786CB78FD3027C117a9955A7", + mainModule: "0xd01F11855bCcb95f88D7A48492F66410d4637313", + mainModuleUpgradable: "0x7EFE6cE415956c5f80C6530cC6cc81b4808F6118", + walletCreationCode: "0x603a600e3d39601a805130553df3363d3d373d3d3d363d30545af43d82803e903d91601857fd5bf3" +}; +var v1 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + config: config$1, + context: context$2, + signature: signature$1, + version: version$1$1, + DeployedWalletContext: DeployedWalletContext$1 +}); +const SetImageHashPrefix = "0x8713a7c4465f6fbee2b6e9d6646d1d9f83fec929edfc4baf661f3c865bdd04d1"; +function hashSetImageHash(imageHash2) { + return keccak256(messageSetImageHash(imageHash2)); } -function encodeNumber(value, { signed: signed2 }) { - return { - dynamic: false, - encoded: numberToHex(value, { - size: 32, - signed: signed2 - }) - }; +function messageSetImageHash(imageHash2) { + return solidityPacked(["bytes32", "bytes32"], [SetImageHashPrefix, imageHash2]); } -function encodeString(value) { - const hexValue = stringToHex(value); - const partsLength = Math.ceil(size$5(hexValue) / 32); - const parts = []; - for (let i = 0; i < partsLength; i++) { - parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), { - dir: "right" - })); +function decodeMessageSetImageHash(message) { + const arr = getBytes(message); + if (arr.length !== 64) { + return void 0; } - return { - dynamic: true, - encoded: concat([ - padHex(numberToHex(size$5(hexValue), { size: 32 })), - ...parts - ]) - }; -} -function encodeTuple(value, { param }) { - let dynamic = false; - const preparedParams = []; - for (let i = 0; i < param.components.length; i++) { - const param_ = param.components[i]; - const index2 = Array.isArray(value) ? i : param_.name; - const preparedParam = prepareParam({ - param: param_, - value: value[index2] - }); - preparedParams.push(preparedParam); - if (preparedParam.dynamic) - dynamic = true; + if (hexlify(arr.slice(0, 32)) !== SetImageHashPrefix) { + return void 0; } - return { - dynamic, - encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded)) - }; -} -function getArrayComponents(type) { - const matches = type.match(/^(.*)\[(\d+)?\]$/); - return matches ? ( - // Return `null` if the array is dynamic. - [matches[2] ? Number(matches[2]) : null, matches[1]] - ) : void 0; -} -const docsPath$4 = "/docs/contract/encodeDeployData"; -function encodeDeployData(parameters) { - const { abi: abi2, args, bytecode } = parameters; - if (!args || args.length === 0) - return bytecode; - const description2 = abi2.find((x2) => "type" in x2 && x2.type === "constructor"); - if (!description2) - throw new AbiConstructorNotFoundError({ docsPath: docsPath$4 }); - if (!("inputs" in description2)) - throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath$4 }); - if (!description2.inputs || description2.inputs.length === 0) - throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath$4 }); - const data = encodeAbiParameters(description2.inputs, args); - return concatHex([bytecode, data]); + return hexlify(arr.slice(32, 64)); } -function parseAccount(account2) { - if (typeof account2 === "string") - return { address: account2, type: "json-rpc" }; - return account2; +function isMessageSetImageHash(message) { + return decodeMessageSetImageHash(message) !== void 0; } -class AccountNotFoundError extends BaseError$3 { - constructor({ docsPath: docsPath2 } = {}) { - super([ - "Could not find an Account to execute with this Action.", - "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client." - ].join("\n"), { - docsPath: docsPath2, - docsSlug: "account", - name: "AccountNotFoundError" - }); - } +var chained = /* @__PURE__ */ Object.freeze({ + __proto__: null, + SetImageHashPrefix, + hashSetImageHash, + messageSetImageHash, + decodeMessageSetImageHash, + isMessageSetImageHash +}); +let SignatureType$1 = /* @__PURE__ */ function(SignatureType2) { + SignatureType2[SignatureType2["Legacy"] = 0] = "Legacy"; + SignatureType2[SignatureType2["Dynamic"] = 1] = "Dynamic"; + SignatureType2[SignatureType2["NoChainIdDynamic"] = 2] = "NoChainIdDynamic"; + SignatureType2[SignatureType2["Chained"] = 3] = "Chained"; + return SignatureType2; +}({}); +let SignaturePartType = /* @__PURE__ */ function(SignaturePartType2) { + SignaturePartType2[SignaturePartType2["Signature"] = 0] = "Signature"; + SignaturePartType2[SignaturePartType2["Address"] = 1] = "Address"; + SignaturePartType2[SignaturePartType2["DynamicSignature"] = 2] = "DynamicSignature"; + SignaturePartType2[SignaturePartType2["Node"] = 3] = "Node"; + SignaturePartType2[SignaturePartType2["Branch"] = 4] = "Branch"; + SignaturePartType2[SignaturePartType2["Subdigest"] = 5] = "Subdigest"; + SignaturePartType2[SignaturePartType2["Nested"] = 6] = "Nested"; + return SignaturePartType2; +}({}); +const SignaturePartTypeLength = 66; +function isUnrecoveredNode(node) { + return node.left !== void 0 && node.right !== void 0; } -class AccountTypeNotSupportedError extends BaseError$3 { - constructor({ docsPath: docsPath2, metaMessages, type }) { - super(`Account type "${type}" is not supported.`, { - docsPath: docsPath2, - metaMessages, - name: "AccountTypeNotSupportedError" - }); - } +function isUnrecoveredNestedLeaf(leaf) { + return leaf.tree !== void 0; } -function publicKeyToAddress(publicKey) { - const address = keccak256(`0x${publicKey.substring(4)}`).substring(26); - return checksumAddress(`0x${address}`); +function isUnrecoveredSignatureLeaf(leaf) { + return leaf.unrecovered && leaf.signature !== void 0 && leaf.isDynamic !== void 0; } -const scriptRel = "modulepreload"; -const assetsURL = function(dep, importerUrl) { - return new URL(dep, importerUrl).href; -}; -const seen = {}; -const __vitePreload = function preload(baseModule, deps, importerUrl) { - let promise = Promise.resolve(); - if (deps && deps.length > 0) { - const links = document.getElementsByTagName("link"); - const cspNonceMeta = document.querySelector( - "meta[property=csp-nonce]" - ); - const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce")); - promise = Promise.allSettled( - deps.map((dep) => { - dep = assetsURL(dep, importerUrl); - if (dep in seen) return; - seen[dep] = true; - const isCss = dep.endsWith(".css"); - const cssSelector = isCss ? '[rel="stylesheet"]' : ""; - const isBaseRelative = !!importerUrl; - if (isBaseRelative) { - for (let i = links.length - 1; i >= 0; i--) { - const link2 = links[i]; - if (link2.href === dep && (!isCss || link2.rel === "stylesheet")) { - return; - } - } - } else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) { - return; +function decodeSignatureTree(body) { + let arr = getBytes(body); + let pointer; + const append = (prevPointer, node) => { + if (!prevPointer) { + return { + left: node + }; + } + if (!prevPointer.right) { + return { + left: prevPointer.left, + right: node + }; + } + return { + left: prevPointer, + right: node + }; + }; + while (arr.length > 0) { + const type = arr[0]; + arr = arr.slice(1); + switch (type) { + case SignaturePartType.Signature: + { + const weight = arr[0]; + const signature2 = hexlify(arr.slice(1, SignaturePartTypeLength + 1)); + pointer = append(pointer, { + signature: signature2, + weight, + unrecovered: true, + isDynamic: false + }); + arr = arr.slice(SignaturePartTypeLength + 1); } - const link = document.createElement("link"); - link.rel = isCss ? "stylesheet" : scriptRel; - if (!isCss) { - link.as = "script"; + break; + case SignaturePartType.Address: + { + const weight = arr[0]; + const address = getAddress(hexlify(arr.slice(1, 21))); + pointer = append(pointer, { + address, + weight + }); + arr = arr.slice(21); } - link.crossOrigin = ""; - link.href = dep; - if (cspNonce) { - link.setAttribute("nonce", cspNonce); + break; + case SignaturePartType.DynamicSignature: + { + const weight = arr[0]; + const address = getAddress(hexlify(arr.slice(1, 21))); + const size2 = arr[21] << 16 | arr[22] << 8 | arr[23]; + const signature2 = hexlify(arr.slice(24, 24 + size2)); + pointer = append(pointer, { + address, + signature: signature2, + weight, + unrecovered: true, + isDynamic: true + }); + arr = arr.slice(24 + size2); } - document.head.appendChild(link); - if (isCss) { - return new Promise((res, rej) => { - link.addEventListener("load", res); - link.addEventListener( - "error", - () => rej(new Error(`Unable to preload CSS for ${dep}`)) - ); + break; + case SignaturePartType.Node: + { + const nodeHash = hexlify(arr.slice(0, 32)); + pointer = append(pointer, { + nodeHash }); + arr = arr.slice(32); } - }) - ); - } - function handlePreloadError(err) { - const e2 = new Event("vite:preloadError", { - cancelable: true - }); - e2.payload = err; - window.dispatchEvent(e2); - if (!e2.defaultPrevented) { - throw err; + break; + case SignaturePartType.Branch: + { + const size2 = arr[0] << 16 | arr[1] << 8 | arr[2]; + const branch = decodeSignatureTree(arr.slice(3, 3 + size2)); + pointer = append(pointer, branch); + arr = arr.slice(3 + size2); + } + break; + case SignaturePartType.Subdigest: + { + const subdigest = hexlify(arr.slice(0, 32)); + pointer = append(pointer, { + subdigest + }); + arr = arr.slice(32); + } + break; + case SignaturePartType.Nested: + { + const weight = arr[0]; + const threshold = arr[1] << 8 | arr[2]; + const size2 = arr[3] << 16 | arr[4] << 8 | arr[5]; + const tree = decodeSignatureTree(arr.slice(6, 6 + size2)); + pointer = append(pointer, { + weight, + threshold, + tree + }); + arr = arr.slice(6 + size2); + } + break; + default: + throw new Error(`Unknown signature part type: ${type}: ${hexlify(arr)}`); } } - return promise.then((res) => { - for (const item2 of res || []) { - if (item2.status !== "rejected") continue; - handlePreloadError(item2.reason); - } - return baseModule().catch(handlePreloadError); - }); -}; -async function recoverPublicKey({ hash: hash2, signature: signature2 }) { - const hashHex = isHex(hash2) ? hash2 : toHex$1(hash2); - const { secp256k1: secp256k12 } = await __vitePreload(async () => { - const { secp256k1: secp256k13 } = await Promise.resolve().then(() => secp256k1$1); - return { secp256k1: secp256k13 }; - }, true ? void 0 : void 0, import.meta.url); - const signature_ = (() => { - if (typeof signature2 === "object" && "r" in signature2 && "s" in signature2) { - const { r: r2, s: s2, v: v3, yParity } = signature2; - const yParityOrV2 = Number(yParity ?? v3); - const recoveryBit2 = toRecoveryBit(yParityOrV2); - return new secp256k12.Signature(hexToBigInt(r2), hexToBigInt(s2)).addRecoveryBit(recoveryBit2); - } - const signatureHex = isHex(signature2) ? signature2 : toHex$1(signature2); - const yParityOrV = hexToNumber$1(`0x${signatureHex.slice(130)}`); - const recoveryBit = toRecoveryBit(yParityOrV); - return secp256k12.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit); - })(); - const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false); - return `0x${publicKey}`; -} -function toRecoveryBit(yParityOrV) { - if (yParityOrV === 0 || yParityOrV === 1) - return yParityOrV; - if (yParityOrV === 27) - return 0; - if (yParityOrV === 28) - return 1; - throw new Error("Invalid yParityOrV value"); -} -async function recoverAddress({ hash: hash2, signature: signature2 }) { - return publicKeyToAddress(await recoverPublicKey({ hash: hash2, signature: signature2 })); -} -class NegativeOffsetError extends BaseError$3 { - constructor({ offset: offset2 }) { - super(`Offset \`${offset2}\` cannot be negative.`, { - name: "NegativeOffsetError" - }); + if (!pointer) { + throw new Error("Empty signature tree"); + } + if (pointer.right) { + return pointer; } + return pointer.left; } -class PositionOutOfBoundsError extends BaseError$3 { - constructor({ length, position }) { - super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); +class InvalidSignatureLeafError extends Error { + constructor(leaf) { + super(`Invalid signature leaf: ${JSON.stringify(leaf)}`); + this.leaf = leaf; } } -class RecursiveReadLimitExceededError extends BaseError$3 { - constructor({ count: count2, limit }) { - super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count2}\`).`, { name: "RecursiveReadLimitExceededError" }); +async function recoverTopology(unrecovered, subdigest, provider2) { + if (isUnrecoveredNode(unrecovered)) { + const [left, right] = await Promise.all([recoverTopology(unrecovered.left, subdigest, provider2), recoverTopology(unrecovered.right, subdigest, provider2)]); + return { + left, + right + }; + } + if (isUnrecoveredNestedLeaf(unrecovered)) { + return { + weight: unrecovered.weight, + threshold: unrecovered.threshold, + tree: await recoverTopology(unrecovered.tree, subdigest, provider2) + }; + } + if (isUnrecoveredSignatureLeaf(unrecovered)) { + if (unrecovered.isDynamic) { + if (!unrecovered.address) { + throw new Error("Dynamic signature leaf without address"); + } + const isValid2 = await isValidSignature$1(unrecovered.address, subdigest, unrecovered.signature, provider2); + if (!isValid2) { + throw new InvalidSignatureLeafError(unrecovered); + } + return { + weight: unrecovered.weight, + address: unrecovered.address, + signature: unrecovered.signature, + subdigest + }; + } else { + return { + weight: unrecovered.weight, + address: recoverSigner(subdigest, unrecovered.signature), + signature: unrecovered.signature, + subdigest + }; + } } + return unrecovered; } -const staticCursor = { - bytes: new Uint8Array(), - dataView: new DataView(new ArrayBuffer(0)), - position: 0, - positionReadCount: /* @__PURE__ */ new Map(), - recursiveReadCount: 0, - recursiveReadLimit: Number.POSITIVE_INFINITY, - assertReadLimit() { - if (this.recursiveReadCount >= this.recursiveReadLimit) - throw new RecursiveReadLimitExceededError({ - count: this.recursiveReadCount + 1, - limit: this.recursiveReadLimit - }); - }, - assertPosition(position) { - if (position < 0 || position > this.bytes.length - 1) - throw new PositionOutOfBoundsError({ - length: this.bytes.length, - position - }); - }, - decrementPosition(offset2) { - if (offset2 < 0) - throw new NegativeOffsetError({ offset: offset2 }); - const position = this.position - offset2; - this.assertPosition(position); - this.position = position; - }, - getReadCount(position) { - return this.positionReadCount.get(position || this.position) || 0; - }, - incrementPosition(offset2) { - if (offset2 < 0) - throw new NegativeOffsetError({ offset: offset2 }); - const position = this.position + offset2; - this.assertPosition(position); - this.position = position; - }, - inspectByte(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectBytes(length, position_) { - const position = position_ ?? this.position; - this.assertPosition(position + length - 1); - return this.bytes.subarray(position, position + length); - }, - inspectUint8(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectUint16(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 1); - return this.dataView.getUint16(position); - }, - inspectUint24(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 2); - return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); - }, - inspectUint32(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 3); - return this.dataView.getUint32(position); - }, - pushByte(byte) { - this.assertPosition(this.position); - this.bytes[this.position] = byte; - this.position++; - }, - pushBytes(bytes2) { - this.assertPosition(this.position + bytes2.length - 1); - this.bytes.set(bytes2, this.position); - this.position += bytes2.length; - }, - pushUint8(value) { - this.assertPosition(this.position); - this.bytes[this.position] = value; - this.position++; - }, - pushUint16(value) { - this.assertPosition(this.position + 1); - this.dataView.setUint16(this.position, value); - this.position += 2; - }, - pushUint24(value) { - this.assertPosition(this.position + 2); - this.dataView.setUint16(this.position, value >> 8); - this.dataView.setUint8(this.position + 2, value & ~4294967040); - this.position += 3; - }, - pushUint32(value) { - this.assertPosition(this.position + 3); - this.dataView.setUint32(this.position, value); - this.position += 4; - }, - readByte() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectByte(); - this.position++; - return value; - }, - readBytes(length, size2) { - this.assertReadLimit(); - this._touch(); - const value = this.inspectBytes(length); - this.position += size2 ?? length; - return value; +const partEncoder = { + concat: (a2, b2) => { + return solidityPacked(["bytes", "bytes"], [a2, b2]); }, - readUint8() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint8(); - this.position += 1; - return value; + node: (nodeHash) => { + return solidityPacked(["uint8", "bytes32"], [SignaturePartType.Node, nodeHash]); }, - readUint16() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint16(); - this.position += 2; - return value; + branch: (tree) => { + const arr = getBytes(tree); + return solidityPacked(["uint8", "uint24", "bytes"], [SignaturePartType.Branch, arr.length, arr]); }, - readUint24() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint24(); - this.position += 3; - return value; + nested: (weight, threshold, tree) => { + const arr = getBytes(tree); + return solidityPacked(["uint8", "uint8", "uint16", "uint24", "bytes"], [SignaturePartType.Nested, weight, threshold, arr.length, arr]); }, - readUint32() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint32(); - this.position += 4; - return value; + subdigest: (subdigest) => { + return solidityPacked(["uint8", "bytes32"], [SignaturePartType.Subdigest, subdigest]); }, - get remaining() { - return this.bytes.length - this.position; + signature: (weight, signature2) => { + return solidityPacked(["uint8", "uint8", "bytes"], [SignaturePartType.Signature, weight, signature2]); }, - setPosition(position) { - const oldPosition = this.position; - this.assertPosition(position); - this.position = position; - return () => this.position = oldPosition; + dynamicSignature: (weight, address, signature2) => { + const arrSignature = getBytes(signature2); + return solidityPacked(["uint8", "uint8", "address", "uint24", "bytes"], [SignaturePartType.DynamicSignature, weight, address, arrSignature.length, arrSignature]); }, - _touch() { - if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) - return; - const count2 = this.getReadCount(); - this.positionReadCount.set(this.position, count2 + 1); - if (count2 > 0) - this.recursiveReadCount++; + address: (weight, address) => { + return solidityPacked(["uint8", "uint8", "address"], [SignaturePartType.Address, weight, address]); } }; -function createCursor(bytes2, { recursiveReadLimit = 8192 } = {}) { - const cursor = Object.create(staticCursor); - cursor.bytes = bytes2; - cursor.dataView = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength); - cursor.positionReadCount = /* @__PURE__ */ new Map(); - cursor.recursiveReadLimit = recursiveReadLimit; - return cursor; -} -function toRlp(bytes2, to = "hex") { - const encodable = getEncodable(bytes2); - const cursor = createCursor(new Uint8Array(encodable.length)); - encodable.encode(cursor); - if (to === "hex") - return bytesToHex$1(cursor.bytes); - return cursor.bytes; -} -function getEncodable(bytes2) { - if (Array.isArray(bytes2)) - return getEncodableList(bytes2.map((x2) => getEncodable(x2))); - return getEncodableBytes(bytes2); -} -function getEncodableList(list2) { - const bodyLength = list2.reduce((acc, x2) => acc + x2.length, 0); - const sizeOfBodyLength = getSizeOfLength(bodyLength); - const length = (() => { - if (bodyLength <= 55) - return 1 + bodyLength; - return 1 + sizeOfBodyLength + bodyLength; - })(); +function encodeSigners(config2, parts, subdigests, chainId, options = {}) { + const tree = encodeTree(config2.tree, parts, subdigests, options); + if (BigInt(chainId) === 0n) { + return { + encoded: solidityPacked(["uint8", "uint16", "uint32", "bytes"], [SignatureType$1.NoChainIdDynamic, config2.threshold, config2.checkpoint, tree.encoded]), + weight: tree.weight + }; + } + if (BigInt(config2.threshold) > 255n) { + return { + encoded: solidityPacked(["uint8", "uint16", "uint32", "bytes"], [SignatureType$1.Dynamic, config2.threshold, config2.checkpoint, tree.encoded]), + weight: tree.weight + }; + } return { - length, - encode(cursor) { - if (bodyLength <= 55) { - cursor.pushByte(192 + bodyLength); - } else { - cursor.pushByte(192 + 55 + sizeOfBodyLength); - if (sizeOfBodyLength === 1) - cursor.pushUint8(bodyLength); - else if (sizeOfBodyLength === 2) - cursor.pushUint16(bodyLength); - else if (sizeOfBodyLength === 3) - cursor.pushUint24(bodyLength); - else - cursor.pushUint32(bodyLength); - } - for (const { encode: encode2 } of list2) { - encode2(cursor); - } - } + encoded: solidityPacked(["uint8", "uint8", "uint32", "bytes"], [SignatureType$1.Legacy, config2.threshold, config2.checkpoint, tree.encoded]), + weight: tree.weight }; } -function getEncodableBytes(bytesOrHex) { - const bytes2 = typeof bytesOrHex === "string" ? hexToBytes$1(bytesOrHex) : bytesOrHex; - const sizeOfBytesLength = getSizeOfLength(bytes2.length); - const length = (() => { - if (bytes2.length === 1 && bytes2[0] < 128) - return 1; - if (bytes2.length <= 55) - return 1 + bytes2.length; - return 1 + sizeOfBytesLength + bytes2.length; - })(); - return { - length, - encode(cursor) { - if (bytes2.length === 1 && bytes2[0] < 128) { - cursor.pushBytes(bytes2); - } else if (bytes2.length <= 55) { - cursor.pushByte(128 + bytes2.length); - cursor.pushBytes(bytes2); - } else { - cursor.pushByte(128 + 55 + sizeOfBytesLength); - if (sizeOfBytesLength === 1) - cursor.pushUint8(bytes2.length); - else if (sizeOfBytesLength === 2) - cursor.pushUint16(bytes2.length); - else if (sizeOfBytesLength === 3) - cursor.pushUint24(bytes2.length); - else - cursor.pushUint32(bytes2.length); - cursor.pushBytes(bytes2); - } +function encodeTree(topology, parts, subdigests, options = {}) { + const trim2 = !options.disableTrim; + if (isNode$1(topology)) { + const left = encodeTree(topology.left, parts, subdigests); + const right = encodeTree(topology.right, parts, subdigests); + const isLeftSigner = isSignerLeaf(topology.left); + const isRightSigner = isSignerLeaf(topology.right); + if (trim2 && left.weight === 0n && right.weight === 0n && !isLeftSigner && !isRightSigner) { + return { + // We don't need to include anything for this node + // just the hash will be enough + encoded: partEncoder.node(hashNode(topology)), + weight: 0n + }; } - }; -} -function getSizeOfLength(length) { - if (length < 2 ** 8) - return 1; - if (length < 2 ** 16) - return 2; - if (length < 2 ** 24) - return 3; - if (length < 2 ** 32) - return 4; - throw new BaseError$3("Length is too large."); -} -function hashAuthorization(parameters) { - const { chainId, contractAddress, nonce, to } = parameters; - const hash2 = keccak256(concatHex([ - "0x05", - toRlp([ - numberToHex(chainId), - contractAddress, - nonce ? numberToHex(nonce) : "0x" - ]) - ])); - if (to === "bytes") - return hexToBytes$1(hash2); - return hash2; -} -async function recoverAuthorizationAddress(parameters) { - const { authorization, signature: signature2 } = parameters; - return recoverAddress({ - hash: hashAuthorization(authorization), - signature: signature2 ?? authorization - }); -} -class ChainDoesNotSupportContract extends BaseError$3 { - constructor({ blockNumber, chain, contract }) { - super(`Chain "${chain.name}" does not support contract "${contract.name}".`, { - metaMessages: [ - "This could be due to any of the following:", - ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [ - `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).` - ] : [ - `- The chain does not have the contract "${contract.name}" configured.` - ] - ], - name: "ChainDoesNotSupportContract" - }); + if (trim2 && right.weight === 0n && !isRightSigner) { + return { + // The right node doesn't have any weight + // but we still need to include the left node encoded + encoded: partEncoder.concat(left.encoded, partEncoder.node(hashNode(topology.right))), + weight: left.weight + }; + } + if (trim2 && left.weight === 0n && !isLeftSigner) { + return { + // The left node doesn't have any weight + // we can just append its hash, but for the right node + // we need to create a new "branch" + encoded: partEncoder.concat(partEncoder.node(hashNode(topology.left)), partEncoder.branch(right.encoded)), + weight: right.weight + }; + } + return { + // Both nodes have weight, we need to include both + // the right one must be a branch + encoded: partEncoder.concat(left.encoded, partEncoder.branch(right.encoded)), + weight: left.weight + right.weight + }; } -} -class ChainMismatchError extends BaseError$3 { - constructor({ chain, currentChainId }) { - super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} – ${chain.name}).`, { - metaMessages: [ - `Current Chain ID: ${currentChainId}`, - `Expected Chain ID: ${chain.id} – ${chain.name}` - ], - name: "ChainMismatchError" - }); + if (isNestedLeaf(topology)) { + const tree = encodeTree(topology.tree, parts, subdigests); + if (trim2 && tree.weight === 0n) { + return { + encoded: partEncoder.node(hashNode(topology)), + weight: 0n + }; + } + return { + encoded: partEncoder.nested(topology.weight, topology.threshold, tree.encoded), + weight: tree.weight + }; } -} -class ChainNotFoundError2 extends BaseError$3 { - constructor() { - super([ - "No chain was provided to the request.", - "Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient." - ].join("\n"), { - name: "ChainNotFoundError" - }); + if (isNodeLeaf(topology)) { + return { + encoded: partEncoder.node(hashNode(topology)), + weight: 0n + }; } -} -class ClientChainNotConfiguredError extends BaseError$3 { - constructor() { - super("No chain was provided to the Client.", { - name: "ClientChainNotConfiguredError" - }); + if (isSubdigestLeaf(topology)) { + const include = subdigests.includes(topology.subdigest); + return { + encoded: partEncoder.subdigest(topology.subdigest), + weight: include ? MAX_UINT_256 : 0n + }; + } + if (isSignerLeaf(topology)) { + const include = parts.has(topology.address); + if (include) { + const part = parts.get(topology.address); + const signature2 = part.signature; + if (options.forceDynamicEncoding || part.isDynamic) { + return { + encoded: partEncoder.dynamicSignature(topology.weight, topology.address, signature2), + weight: BigInt(topology.weight) + }; + } else { + return { + encoded: partEncoder.signature(topology.weight, signature2), + weight: BigInt(topology.weight) + }; + } + } else { + return { + encoded: partEncoder.address(topology.weight, topology.address), + weight: 0n + }; + } } + throw new Error(`Invalid topology - unknown error: ${JSON.stringify(topology)}`); } -function assertCurrentChain({ chain, currentChainId }) { - if (!chain) - throw new ChainNotFoundError2(); - if (currentChainId !== chain.id) - throw new ChainMismatchError({ chain, currentChainId }); +function deepestConfigOfSignature(signature2) { + return isChainedSignature(signature2) ? deepestConfigOfSignature(signature2.suffix[signature2.suffix.length - 1]) : signature2.config; } -const etherUnits = { - gwei: 9, - wei: 18 -}; -const gweiUnits = { - ether: -9, - wei: 9 -}; -function formatUnits(value, decimals) { - let display = value.toString(); - const negative = display.startsWith("-"); - if (negative) - display = display.slice(1); - display = display.padStart(decimals, "0"); - let [integer, fraction] = [ - display.slice(0, display.length - decimals), - display.slice(display.length - decimals) - ]; - fraction = fraction.replace(/(0+)$/, ""); - return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`; +function isUnrecoveredSignature(sig) { + return sig.type !== void 0 && sig.decoded !== void 0 && sig.version !== void 0 && sig.version === 2; } -function formatGwei(wei, unit = "wei") { - return formatUnits(wei, gweiUnits[unit]); +function isUnrecoveredChainedSignature(sig) { + return sig.suffix !== void 0 && Array.isArray(sig.suffix) && sig.suffix.every(isUnrecoveredSignature); } -class ExecutionRevertedError extends BaseError$3 { - constructor({ cause, message } = {}) { - var _a2; - const reason = (_a2 = message == null ? void 0 : message.replace("execution reverted: ", "")) == null ? void 0 : _a2.replace("execution reverted", ""); - super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { - cause, - name: "ExecutionRevertedError" - }); - } +function isSignature(sig) { + return sig.type !== void 0 && sig.config !== void 0 && sig.digest !== void 0 && sig.version !== void 0 && sig.version === 2; } -Object.defineProperty(ExecutionRevertedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 3 -}); -Object.defineProperty(ExecutionRevertedError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /execution reverted/ -}); -class FeeCapTooHighError extends BaseError$3 { - constructor({ cause, maxFeePerGas } = {}) { - super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, { - cause, - name: "FeeCapTooHighError" - }); - } +function isChainedSignature(sig) { + return sig.chain !== void 0 && Array.isArray(sig.chain) && sig.chain.every(isSignature); } -Object.defineProperty(FeeCapTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/ -}); -class FeeCapTooLowError extends BaseError$3 { - constructor({ cause, maxFeePerGas } = {}) { - super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, { - cause, - name: "FeeCapTooLowError" - }); +function decodeSignature(signature2) { + const bytes2 = getBytes(signature2); + const type = bytes2[0]; + switch (type) { + case SignatureType$1.Legacy: + return { + version: 2, + type: SignatureType$1.Legacy, + decoded: decodeSignatureBody(bytes2) + }; + case SignatureType$1.Dynamic: + return { + version: 2, + type: SignatureType$1.Dynamic, + decoded: decodeSignatureBody(bytes2.slice(1)) + }; + case SignatureType$1.NoChainIdDynamic: + return { + version: 2, + type: SignatureType$1.NoChainIdDynamic, + decoded: decodeSignatureBody(bytes2.slice(1)) + }; + case SignatureType$1.Chained: + return decodeChainedSignature(bytes2); + default: + throw new Error(`Invalid signature type: ${type}`); } } -Object.defineProperty(FeeCapTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/ -}); -class NonceTooHighError extends BaseError$3 { - constructor({ cause, nonce } = {}) { - super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" }); - } +function decodeSignatureBody(signature2) { + const bytes2 = getBytes(signature2); + const threshold = bytes2[0] << 8 | bytes2[1]; + const checkpoint = bytes2[2] << 24 | bytes2[3] << 16 | bytes2[4] << 8 | bytes2[5]; + const tree = decodeSignatureTree(bytes2.slice(6)); + return { + threshold, + checkpoint, + tree + }; } -Object.defineProperty(NonceTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce too high/ -}); -class NonceTooLowError extends BaseError$3 { - constructor({ cause, nonce } = {}) { - super([ - `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`, - "Try increasing the nonce or find the latest nonce with `getTransactionCount`." - ].join("\n"), { cause, name: "NonceTooLowError" }); +function decodeChainedSignature(signature2) { + const arr = getBytes(signature2); + const type = arr[0]; + if (type !== SignatureType$1.Chained) { + throw new Error(`Expected chained signature type: ${type}`); } -} -Object.defineProperty(NonceTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce too low|transaction already imported|already known/ -}); -class NonceMaxValueError extends BaseError$3 { - constructor({ cause, nonce } = {}) { - super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" }); + const chain = []; + let index2 = 1; + while (index2 < arr.length) { + const size2 = arr[index2] << 16 | arr[index2 + 1] << 8 | arr[index2 + 2]; + index2 += 3; + const sig = decodeSignature(arr.slice(index2, index2 + size2)); + chain.push(sig); + index2 += size2; } -} -Object.defineProperty(NonceMaxValueError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce has max value/ -}); -class InsufficientFundsError extends BaseError$3 { - constructor({ cause } = {}) { - super([ - "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account." - ].join("\n"), { - cause, - metaMessages: [ - "This error could arise when the account does not have enough funds to:", - " - pay for the total gas fee,", - " - pay for the value to send.", - " ", - "The cost of the transaction is calculated as `gas * gas fee + value`, where:", - " - `gas` is the amount of gas needed for transaction to execute,", - " - `gas fee` is the gas fee,", - " - `value` is the amount of ether to send to the recipient." - ], - name: "InsufficientFundsError" - }); + const main2 = chain[0]; + if (isUnrecoveredChainedSignature(main2)) { + throw new Error(`Expected first link of chained signature to be a simple signature (not chained)`); } + const suffix = chain.slice(1); + return _extends$c({}, main2, { + suffix + }); } -Object.defineProperty(InsufficientFundsError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /insufficient funds|exceeds transaction sender account balance/ -}); -class IntrinsicGasTooHighError extends BaseError$3 { - constructor({ cause, gas } = {}) { - super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, { - cause, - name: "IntrinsicGasTooHighError" - }); - } +function setImageHashStruct(imageHash2) { + return solidityPacked(["bytes32", "bytes32"], [solidityPackedKeccak256(["string"], ["SetImageHash(bytes32 imageHash)"]), imageHash2]); } -Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /intrinsic gas too high|gas limit reached/ -}); -class IntrinsicGasTooLowError extends BaseError$3 { - constructor({ cause, gas } = {}) { - super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, { - cause, - name: "IntrinsicGasTooLowError" - }); +async function recoverSignature(signature2, payload, provider2) { + const signedPayload = payload.subdigest === void 0 ? payload : void 0; + const isNoChainId = signature2.type === SignatureType$1.NoChainIdDynamic; + if (isNoChainId && signedPayload) { + signedPayload.chainId = 0; } -} -Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /intrinsic gas too low/ -}); -class TransactionTypeNotSupportedError extends BaseError$3 { - constructor({ cause }) { - super("The transaction type is not supported for this chain.", { - cause, - name: "TransactionTypeNotSupportedError" - }); + const subdigest = signedPayload ? subdigestOf(signedPayload) : payload.subdigest; + if (!isUnrecoveredChainedSignature(signature2)) { + const tree = await recoverTopology(signature2.decoded.tree, subdigest, provider2); + return { + version: 2, + type: signature2.type, + subdigest, + config: _extends$c({ + version: 2 + }, signature2.decoded, { + tree + }) + }; } -} -Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /transaction type not valid/ -}); -class TipAboveFeeCapError extends BaseError$3 { - constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) { - super([ - `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).` - ].join("\n"), { - cause, - name: "TipAboveFeeCapError" - }); + if (!isSignedPayload(signedPayload)) { + throw new Error(`Chained signature recovery requires detailed signed payload, subdigest is not enough`); } -} -Object.defineProperty(TipAboveFeeCapError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/ -}); -class UnknownNodeError extends BaseError$3 { - constructor({ cause }) { - super(`An error occurred while executing: ${cause == null ? void 0 : cause.shortMessage}`, { - cause, - name: "UnknownNodeError" + const result = []; + let mutatedPayload = signedPayload; + for (const sig of [_extends$c({}, signature2, { + suffix: void 0 + }), ...signature2.suffix]) { + const recovered = await recoverSignature(sig, mutatedPayload, provider2); + result.unshift(recovered); + const nextMessage = setImageHashStruct(imageHash(deepestConfigOfSignature(recovered))); + mutatedPayload = _extends$c({}, mutatedPayload, { + message: nextMessage, + digest: keccak256(nextMessage) }); } + const main2 = result[0]; + const suffix = result.slice(1); + return _extends$c({}, main2, { + suffix + }); } -function formatEther(wei, unit = "wei") { - return formatUnits(wei, etherUnits[unit]); -} -function prettyPrint(args) { - const entries = Object.entries(args).map(([key, value]) => { - if (value === void 0 || value === false) - return null; - return [key, value]; - }).filter(Boolean); - const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0); - return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n"); +function encodeChain(main2, suffix) { + const allSignatures = [main2, ...suffix || []]; + const encodedMap = allSignatures.map((s2) => getBytes(encodeSignature(s2))); + const body = solidityPacked(encodedMap.map(() => ["uint24", "bytes"]).flat(), encodedMap.map((s2) => [s2.length, s2]).flat()); + return solidityPacked(["uint8", "bytes"], [SignatureType$1.Chained, body]); } -class FeeConflictError extends BaseError$3 { - constructor() { - super([ - "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.", - "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others." - ].join("\n"), { name: "FeeConflictError" }); +function encodeSignature(decoded) { + if (isBytesLike(decoded)) return hexlify(decoded); + if (isUnrecoveredChainedSignature(decoded) || isChainedSignature(decoded)) { + return encodeChain(encodeSignature(decoded), (decoded.suffix || []).map(encodeSignature)); } -} -class InvalidSerializableTransactionError extends BaseError$3 { - constructor({ transaction: transaction2 }) { - super("Cannot infer a transaction type from provided transaction.", { - metaMessages: [ - "Provided Transaction:", - "{", - prettyPrint(transaction2), - "}", - "", - "To infer the type, either provide:", - "- a `type` to the Transaction, or", - "- an EIP-1559 Transaction with `maxFeePerGas`, or", - "- an EIP-2930 Transaction with `gasPrice` & `accessList`, or", - "- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or", - "- an EIP-7702 Transaction with `authorizationList`, or", - "- a Legacy Transaction with `gasPrice`" - ], - name: "InvalidSerializableTransactionError" - }); + const body = isUnrecoveredSignature(decoded) ? decoded.decoded : decoded.config; + switch (decoded.type) { + case SignatureType$1.Legacy: + if (BigInt(body.threshold) > 255n) { + throw new Error(`Legacy signature threshold is too large: ${body.threshold} (max 255)`); + } + return encodeSignatureBody(body); + case SignatureType$1.NoChainIdDynamic: + case SignatureType$1.Dynamic: + return solidityPacked(["uint8", "bytes"], [decoded.type, encodeSignatureBody(body)]); + case SignatureType$1.Chained: + throw new Error(`Unreachable code: Chained signature should be handled above`); + default: + throw new Error(`Invalid signature type: ${decoded.type}`); } } -class TransactionExecutionError extends BaseError$3 { - constructor(cause, { account: account2, docsPath: docsPath2, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) { - var _a2; - const prettyArgs = prettyPrint({ - chain: chain && `${chain == null ? void 0 : chain.name} (id: ${chain == null ? void 0 : chain.id})`, - from: account2 == null ? void 0 : account2.address, - to, - value: typeof value !== "undefined" && `${formatEther(value)} ${((_a2 = chain == null ? void 0 : chain.nativeCurrency) == null ? void 0 : _a2.symbol) || "ETH"}`, - data, - gas, - gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, - maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, - maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, - nonce - }); - super(cause.shortMessage, { - cause, - docsPath: docsPath2, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - "Request Arguments:", - prettyArgs - ].filter(Boolean), - name: "TransactionExecutionError" - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.cause = cause; - } +function encodeSignatureBody(decoded) { + return solidityPacked(["uint16", "uint32", "bytes"], [decoded.threshold, decoded.checkpoint, encodeSignatureTree(decoded.tree)]); } -class TransactionNotFoundError extends BaseError$3 { - constructor({ blockHash, blockNumber, blockTag, hash: hash2, index: index2 }) { - let identifier = "Transaction"; - if (blockTag && index2 !== void 0) - identifier = `Transaction at block time "${blockTag}" at index "${index2}"`; - if (blockHash && index2 !== void 0) - identifier = `Transaction at block hash "${blockHash}" at index "${index2}"`; - if (blockNumber && index2 !== void 0) - identifier = `Transaction at block number "${blockNumber}" at index "${index2}"`; - if (hash2) - identifier = `Transaction with hash "${hash2}"`; - super(`${identifier} could not be found.`, { - name: "TransactionNotFoundError" - }); +function encodeSignatureTree(tree) { + if (isNode$1(tree) || isUnrecoveredNode(tree)) { + const encodedRight = getBytes(encodeSignatureTree(tree.right)); + const encodedLeft = getBytes(encodeSignatureTree(tree.left)); + const isBranching = isNode$1(tree.right) || isUnrecoveredNode(tree.right); + if (isBranching) { + return solidityPacked(["bytes", "uint8", "uint24", "bytes"], [encodedLeft, SignaturePartType.Branch, encodedRight.length, encodedRight]); + } else { + return solidityPacked(["bytes", "bytes"], [encodedLeft, encodedRight]); + } } -} -class TransactionReceiptNotFoundError extends BaseError$3 { - constructor({ hash: hash2 }) { - super(`Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`, { - name: "TransactionReceiptNotFoundError" - }); + if (isNestedLeaf(tree) || isUnrecoveredNestedLeaf(tree)) { + const nested = getBytes(encodeSignatureTree(tree.tree)); + return solidityPacked(["uint8", "uint8", "uint16", "uint24", "bytes"], [SignaturePartType.Nested, tree.weight, tree.threshold, nested.length, nested]); + } + if (isUnrecoveredSignatureLeaf(tree) || isSignerLeaf(tree) && tree.signature !== void 0) { + const signature2 = getBytes(tree.signature); + if (tree.isDynamic || signature2.length !== SignaturePartTypeLength) { + if (!tree.address) throw new Error(`Dynamic signature leaf must have address`); + return solidityPacked(["uint8", "uint8", "address", "uint24", "bytes"], [SignaturePartType.DynamicSignature, tree.weight, tree.address, signature2.length, signature2]); + } else { + return solidityPacked(["uint8", "uint8", "bytes"], [SignaturePartType.Signature, tree.weight, signature2]); + } + } + if (isSignerLeaf(tree)) { + return solidityPacked(["uint8", "uint8", "address"], [SignaturePartType.Address, tree.weight, tree.address]); + } + if (isNodeLeaf(tree)) { + return solidityPacked(["uint8", "bytes32"], [SignaturePartType.Node, tree.nodeHash]); + } + if (isSubdigestLeaf(tree)) { + return solidityPacked(["uint8", "bytes32"], [SignaturePartType.Subdigest, tree.subdigest]); } + throw new Error(`Unknown signature tree type: ${tree}`); } -class WaitForTransactionReceiptTimeoutError extends BaseError$3 { - constructor({ hash: hash2 }) { - super(`Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`, { name: "WaitForTransactionReceiptTimeoutError" }); +function signaturesOf(topology) { + if (isNode$1(topology)) { + return [...signaturesOf(topology.left), ...signaturesOf(topology.right)]; + } + if (isNestedLeaf(topology)) { + return signaturesOf(topology.tree); + } + if (isSignerLeaf(topology) && topology.signature) { + return [{ + address: topology.address, + signature: topology.signature + }]; } + return []; } -const stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => { - const value2 = typeof value_ === "bigint" ? value_.toString() : value_; - return value2; -}, space); -const getContractAddress = (address) => address; -const getUrl = (url) => url; -class HttpRequestError extends BaseError$3 { - constructor({ body, cause, details, headers, status, url }) { - super("HTTP request failed.", { - cause, - details, - metaMessages: [ - status && `Status: ${status}`, - `URL: ${getUrl(url)}`, - body && `Request body: ${stringify(body)}` - ].filter(Boolean), - name: "HttpRequestError" - }); - Object.defineProperty(this, "body", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "headers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "url", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.body = body; - this.headers = headers; - this.status = status; - this.url = url; +function signaturesOfDecoded(utopology) { + if (isUnrecoveredNode(utopology)) { + return [...signaturesOfDecoded(utopology.left), ...signaturesOfDecoded(utopology.right)]; } + if (isUnrecoveredNestedLeaf(utopology)) { + return signaturesOfDecoded(utopology.tree); + } + if (isUnrecoveredSignatureLeaf(utopology)) { + return [utopology.signature]; + } + return []; } -class RpcRequestError extends BaseError$3 { - constructor({ body, error, url }) { - super("RPC Request failed.", { - cause: error, - details: error.message, - metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`], - name: "RpcRequestError" - }); - Object.defineProperty(this, "code", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.code = error.code; +function subdigestsOfDecoded(utopology) { + if (isUnrecoveredNode(utopology)) { + return [...subdigestsOfDecoded(utopology.left), ...subdigestsOfDecoded(utopology.right)]; } + if (isUnrecoveredNestedLeaf(utopology)) { + return subdigestsOfDecoded(utopology.tree); + } + if (isSubdigestLeaf(utopology)) { + return [utopology.subdigest]; + } + return []; } -class TimeoutError3 extends BaseError$3 { - constructor({ body, url }) { - super("The request took too long to respond.", { - details: "The request timed out.", - metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`], - name: "TimeoutError" - }); +async function trimSignature(signature2) { + const decoded = typeof signature2 === "string" ? decodeSignature(signature2) : signature2; + if (isUnrecoveredChainedSignature(decoded)) { + const _trimmed = await Promise.all([trimSignature(_extends$c({}, decoded, { + suffix: void 0 + })), ...decoded.suffix.map((s2) => trimSignature(s2))]); + return encodeChain(_trimmed[0], _trimmed.slice(1)); } + const { + trimmed + } = await trimUnrecoveredTree(decoded.decoded.tree); + return encodeSignature(_extends$c({}, decoded, { + decoded: _extends$c({}, decoded.decoded, { + tree: trimmed + }) + })); } -const unknownErrorCode = -1; -class RpcError extends BaseError$3 { - constructor(cause, { code: code2, docsPath: docsPath2, metaMessages, name: name2, shortMessage }) { - super(shortMessage, { - cause, - docsPath: docsPath2, - metaMessages: metaMessages || (cause == null ? void 0 : cause.metaMessages), - name: name2 || "RpcError" - }); - Object.defineProperty(this, "code", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = name2 || cause.name; - this.code = cause instanceof RpcRequestError ? cause.code : code2 ?? unknownErrorCode; +async function trimUnrecoveredTree(tree, trimStaticDigest = true) { + if (isUnrecoveredNode(tree)) { + const [left, right] = await Promise.all([trimUnrecoveredTree(tree.left), trimUnrecoveredTree(tree.right)]); + if (left.weight === 0 && right.weight === 0) { + try { + const recovered = await recoverTopology(tree, ZeroHash, void 0); + return { + weight: 0, + trimmed: { + nodeHash: hashNode(recovered) + } + }; + } catch (_unused) { + } + } else { + return { + weight: left.weight + right.weight, + trimmed: { + left: left.trimmed, + right: right.trimmed + } + }; + } + } + if (isUnrecoveredNestedLeaf(tree)) { + const trimmed = await trimUnrecoveredTree(tree.tree); + if (trimmed.weight === 0) { + try { + const recovered = await recoverTopology(tree, ZeroHash, void 0); + return { + weight: 0, + trimmed: { + nodeHash: hashNode(recovered) + } + }; + } catch (_unused2) { + } + } + return { + weight: trimmed.weight, + trimmed: { + weight: tree.weight, + threshold: tree.threshold, + tree: trimmed.trimmed + } + }; } -} -class ProviderRpcError extends RpcError { - constructor(cause, options) { - super(cause, options); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.data = options.data; + if (isNodeLeaf(tree) && isEncodedSignerLeaf(tree.nodeHash)) { + return { + weight: 0, + trimmed: _extends$c({}, decodeSignerLeaf(tree.nodeHash)) + }; } -} -class ParseRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: ParseRpcError.code, - name: "ParseRpcError", - shortMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text." - }); + if (isUnrecoveredSignatureLeaf(tree) || isSignerLeaf(tree) && tree.signature !== void 0) { + return { + weight: Number(tree.weight), + trimmed: tree + }; } -} -Object.defineProperty(ParseRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32700 -}); -class InvalidRequestRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: InvalidRequestRpcError.code, - name: "InvalidRequestRpcError", - shortMessage: "JSON is not a valid request object." - }); + if (!trimStaticDigest && isSubdigestLeaf(tree)) { + return { + weight: Infinity, + trimmed: tree + }; } + return { + weight: 0, + trimmed: tree + }; } -Object.defineProperty(InvalidRequestRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32600 -}); -class MethodNotFoundRpcError extends RpcError { - constructor(cause, { method } = {}) { - super(cause, { - code: MethodNotFoundRpcError.code, - name: "MethodNotFoundRpcError", - shortMessage: `The method${method ? ` "${method}"` : ""} does not exist / is not available.` - }); +const SignatureCoder = { + decode: (data) => { + return decodeSignature(data); + }, + encode: (data) => { + return encodeSignature(data); + }, + trim: (data) => { + return trimSignature(data); + }, + supportsNoChainId: true, + recover: (data, payload, provider2) => { + return recoverSignature(data, payload, provider2); + }, + encodeSigners: (config2, signatures, subdigests, chainId) => { + return encodeSigners(config2, signatures, subdigests, chainId); + }, + hasEnoughSigningPower: (config2, signatures) => { + const { + weight + } = SignatureCoder.encodeSigners(config2, signatures, [], 0); + return weight >= BigInt(config2.threshold); + }, + chainSignatures: (main2, suffix) => { + const reversed = suffix.reverse(); + const mraw = isBytesLike(main2) ? main2 : encodeSignature(main2); + const sraw = reversed.map((s2) => isBytesLike(s2) ? s2 : encodeSignature(s2)); + return encodeChain(mraw, sraw); + }, + hashSetImageHash: function(imageHash2) { + return hashSetImageHash(imageHash2); + }, + signaturesOf(config2) { + return signaturesOf(config2.tree); + }, + signaturesOfDecoded: function(data) { + return signaturesOfDecoded(data.decoded.tree); } -} -Object.defineProperty(MethodNotFoundRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32601 +}; +var signature = /* @__PURE__ */ Object.freeze({ + __proto__: null, + SignatureType: SignatureType$1, + SignaturePartType, + SignaturePartTypeLength, + isUnrecoveredNode, + isUnrecoveredNestedLeaf, + isUnrecoveredSignatureLeaf, + decodeSignatureTree, + InvalidSignatureLeafError, + recoverTopology, + partEncoder, + encodeSigners, + encodeTree, + deepestConfigOfSignature, + isUnrecoveredSignature, + isUnrecoveredChainedSignature, + isSignature, + isChainedSignature, + decodeSignature, + decodeSignatureBody, + decodeChainedSignature, + setImageHashStruct, + recoverSignature, + encodeChain, + encodeSignature, + encodeSignatureBody, + encodeSignatureTree, + signaturesOf, + signaturesOfDecoded, + subdigestsOfDecoded, + trimSignature, + trimUnrecoveredTree, + SignatureCoder }); -class InvalidParamsRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: InvalidParamsRpcError.code, - name: "InvalidParamsRpcError", - shortMessage: [ - "Invalid parameters were provided to the RPC method.", - "Double check you have provided the correct parameters." - ].join("\n") - }); - } +function isSignerLeaf(leaf) { + return leaf.address !== void 0 && leaf.weight !== void 0; } -Object.defineProperty(InvalidParamsRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32602 -}); -class InternalRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: InternalRpcError.code, - name: "InternalRpcError", - shortMessage: "An internal error was received." - }); - } +function isSubdigestLeaf(leaf) { + return leaf.subdigest !== void 0 && leaf.address === void 0; } -Object.defineProperty(InternalRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32603 -}); -class InvalidInputRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: InvalidInputRpcError.code, - name: "InvalidInputRpcError", - shortMessage: [ - "Missing or invalid parameters.", - "Double check you have provided the correct parameters." - ].join("\n") +function topologyToJSON(tree) { + if (isNode$1(tree)) { + return JSON.stringify({ + left: topologyToJSON(tree.left), + right: topologyToJSON(tree.right) }); } -} -Object.defineProperty(InvalidInputRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32e3 -}); -class ResourceNotFoundRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: ResourceNotFoundRpcError.code, - name: "ResourceNotFoundRpcError", - shortMessage: "Requested resource not found." - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "ResourceNotFoundRpcError" + if (isNestedLeaf(tree)) { + return JSON.stringify({ + weight: BigInt(tree.weight).toString(), + threshold: BigInt(tree.threshold).toString(), + tree: topologyToJSON(tree.tree) }); } -} -Object.defineProperty(ResourceNotFoundRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32001 -}); -class ResourceUnavailableRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: ResourceUnavailableRpcError.code, - name: "ResourceUnavailableRpcError", - shortMessage: "Requested resource not available." + if (isSignerLeaf(tree)) { + return JSON.stringify({ + address: tree.address, + weight: BigInt(tree.weight).toString() }); } + return JSON.stringify(tree); } -Object.defineProperty(ResourceUnavailableRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32002 -}); -class TransactionRejectedRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: TransactionRejectedRpcError.code, - name: "TransactionRejectedRpcError", - shortMessage: "Transaction creation failed." - }); +function topologyFromJSON(json) { + const parsed = typeof json === "string" ? JSON.parse(json) : json; + if (parsed.left !== void 0 && parsed.right !== void 0) { + return { + left: topologyFromJSON(parsed.left), + right: topologyFromJSON(parsed.right) + }; } -} -Object.defineProperty(TransactionRejectedRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32003 -}); -class MethodNotSupportedRpcError extends RpcError { - constructor(cause, { method } = {}) { - super(cause, { - code: MethodNotSupportedRpcError.code, - name: "MethodNotSupportedRpcError", - shortMessage: `Method${method ? ` "${method}"` : ""} is not implemented.` - }); + if (parsed.weight !== void 0 && parsed.threshold !== void 0 && parsed.tree !== void 0) { + return { + weight: BigInt(parsed.weight), + threshold: BigInt(parsed.threshold), + tree: topologyFromJSON(parsed.tree) + }; } -} -Object.defineProperty(MethodNotSupportedRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32004 -}); -class LimitExceededRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: LimitExceededRpcError.code, - name: "LimitExceededRpcError", - shortMessage: "Request exceeds defined limit." - }); + if (parsed.address !== void 0 && parsed.weight !== void 0) { + return { + address: parsed.address, + weight: BigInt(parsed.weight) + }; } + return parsed; } -Object.defineProperty(LimitExceededRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32005 -}); -class JsonRpcVersionUnsupportedError extends RpcError { - constructor(cause) { - super(cause, { - code: JsonRpcVersionUnsupportedError.code, - name: "JsonRpcVersionUnsupportedError", - shortMessage: "Version of JSON-RPC protocol is not supported." - }); - } +function isNestedLeaf(leaf) { + return leaf.tree !== void 0 && leaf.weight !== void 0 && leaf.threshold !== void 0; } -Object.defineProperty(JsonRpcVersionUnsupportedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32006 -}); -class UserRejectedRequestError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: UserRejectedRequestError.code, - name: "UserRejectedRequestError", - shortMessage: "User rejected the request." - }); - } +function isNodeLeaf(leaf) { + return leaf.nodeHash !== void 0; } -Object.defineProperty(UserRejectedRequestError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4001 -}); -class UnauthorizedProviderError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: UnauthorizedProviderError.code, - name: "UnauthorizedProviderError", - shortMessage: "The requested method and/or account has not been authorized by the user." - }); - } +function isLeaf$1(leaf) { + return isSignerLeaf(leaf) || isSubdigestLeaf(leaf) || isNestedLeaf(leaf) || isNodeLeaf(leaf); } -Object.defineProperty(UnauthorizedProviderError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4100 -}); -class UnsupportedProviderMethodError extends ProviderRpcError { - constructor(cause, { method } = {}) { - super(cause, { - code: UnsupportedProviderMethodError.code, - name: "UnsupportedProviderMethodError", - shortMessage: `The Provider does not support the requested method${method ? ` " ${method}"` : ""}.` - }); - } +function isNode$1(node) { + return node.left !== void 0 && node.right !== void 0; } -Object.defineProperty(UnsupportedProviderMethodError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4200 -}); -class ProviderDisconnectedError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: ProviderDisconnectedError.code, - name: "ProviderDisconnectedError", - shortMessage: "The Provider is disconnected from all chains." - }); - } +function isTopology(topology) { + return isNode$1(topology) || isLeaf$1(topology); } -Object.defineProperty(ProviderDisconnectedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4900 -}); -class ChainDisconnectedError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: ChainDisconnectedError.code, - name: "ChainDisconnectedError", - shortMessage: "The Provider is not connected to the requested chain." - }); - } +function encodeSignerLeaf(leaf) { + return solidityPacked(["uint96", "address"], [leaf.weight, leaf.address]); } -Object.defineProperty(ChainDisconnectedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4901 -}); -class SwitchChainError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: SwitchChainError.code, - name: "SwitchChainError", - shortMessage: "An error occurred when attempting to switch chain." - }); +function decodeSignerLeaf(encoded) { + const bytes2 = getBytes(encoded); + if (bytes2.length !== 32) { + throw new Error("Invalid encoded string length"); } + const weight = BigInt(hexlify(bytes2.slice(0, 12))); + const address = getAddress(hexlify(bytes2.slice(12))); + return { + weight, + address + }; } -Object.defineProperty(SwitchChainError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4902 -}); -class UnknownRpcError extends RpcError { - constructor(cause) { - super(cause, { - name: "UnknownRpcError", - shortMessage: "An unknown RPC error occurred." - }); +function isEncodedSignerLeaf(encoded) { + const bytes2 = getBytes(encoded); + if (bytes2.length !== 32) { + return false; } + const prefix = bytes2.slice(0, 11); + return prefix.every((byte) => byte === 0); } -function getNodeError(err, args) { - const message = (err.details || "").toLowerCase(); - const executionRevertedError = err instanceof BaseError$3 ? err.walk((e2) => e2.code === ExecutionRevertedError.code) : err; - if (executionRevertedError instanceof BaseError$3) - return new ExecutionRevertedError({ - cause: err, - message: executionRevertedError.details - }); - if (ExecutionRevertedError.nodeMessage.test(message)) - return new ExecutionRevertedError({ - cause: err, - message: err.details - }); - if (FeeCapTooHighError.nodeMessage.test(message)) - return new FeeCapTooHighError({ - cause: err, - maxFeePerGas: args == null ? void 0 : args.maxFeePerGas - }); - if (FeeCapTooLowError.nodeMessage.test(message)) - return new FeeCapTooLowError({ - cause: err, - maxFeePerGas: args == null ? void 0 : args.maxFeePerGas - }); - if (NonceTooHighError.nodeMessage.test(message)) - return new NonceTooHighError({ cause: err, nonce: args == null ? void 0 : args.nonce }); - if (NonceTooLowError.nodeMessage.test(message)) - return new NonceTooLowError({ cause: err, nonce: args == null ? void 0 : args.nonce }); - if (NonceMaxValueError.nodeMessage.test(message)) - return new NonceMaxValueError({ cause: err, nonce: args == null ? void 0 : args.nonce }); - if (InsufficientFundsError.nodeMessage.test(message)) - return new InsufficientFundsError({ cause: err }); - if (IntrinsicGasTooHighError.nodeMessage.test(message)) - return new IntrinsicGasTooHighError({ cause: err, gas: args == null ? void 0 : args.gas }); - if (IntrinsicGasTooLowError.nodeMessage.test(message)) - return new IntrinsicGasTooLowError({ cause: err, gas: args == null ? void 0 : args.gas }); - if (TransactionTypeNotSupportedError.nodeMessage.test(message)) - return new TransactionTypeNotSupportedError({ cause: err }); - if (TipAboveFeeCapError.nodeMessage.test(message)) - return new TipAboveFeeCapError({ - cause: err, - maxFeePerGas: args == null ? void 0 : args.maxFeePerGas, - maxPriorityFeePerGas: args == null ? void 0 : args.maxPriorityFeePerGas - }); - return new UnknownNodeError({ - cause: err - }); -} -function getTransactionError(err, { docsPath: docsPath2, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new TransactionExecutionError(cause, { - docsPath: docsPath2, - ...args - }); -} -function extract(value_, { format: format2 }) { - if (!format2) - return {}; - const value = {}; - function extract_(formatted2) { - const keys = Object.keys(formatted2); - for (const key of keys) { - if (key in value_) - value[key] = value_[key]; - if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key])) - extract_(formatted2[key]); - } +function hashNode(node) { + if (isSignerLeaf(node)) { + return encodeSignerLeaf(node); + } + if (isSubdigestLeaf(node)) { + return solidityPackedKeccak256(["string", "bytes32"], ["Sequence static digest:\n", node.subdigest]); + } + if (isNestedLeaf(node)) { + const nested = hashNode(node.tree); + return solidityPackedKeccak256(["string", "bytes32", "uint256", "uint256"], ["Sequence nested config:\n", nested, node.threshold, node.weight]); } - const formatted = format2(value_ || {}); - extract_(formatted); - return value; + if (isNodeLeaf(node)) { + return node.nodeHash; + } + return solidityPackedKeccak256(["bytes32", "bytes32"], [hashNode(node.left), hashNode(node.right)]); } -const rpcTransactionType = { - legacy: "0x0", - eip2930: "0x1", - eip1559: "0x2", - eip4844: "0x3", - eip7702: "0x4" -}; -function formatTransactionRequest(request) { - const rpcRequest = {}; - if (typeof request.authorizationList !== "undefined") - rpcRequest.authorizationList = formatAuthorizationList$1(request.authorizationList); - if (typeof request.accessList !== "undefined") - rpcRequest.accessList = request.accessList; - if (typeof request.blobVersionedHashes !== "undefined") - rpcRequest.blobVersionedHashes = request.blobVersionedHashes; - if (typeof request.blobs !== "undefined") { - if (typeof request.blobs[0] !== "string") - rpcRequest.blobs = request.blobs.map((x2) => bytesToHex$1(x2)); - else - rpcRequest.blobs = request.blobs; +function leftFace(topology) { + const stack = []; + let prev = topology; + while (!isLeaf$1(prev)) { + stack.unshift(prev.right); + prev = prev.left; } - if (typeof request.data !== "undefined") - rpcRequest.data = request.data; - if (typeof request.from !== "undefined") - rpcRequest.from = request.from; - if (typeof request.gas !== "undefined") - rpcRequest.gas = numberToHex(request.gas); - if (typeof request.gasPrice !== "undefined") - rpcRequest.gasPrice = numberToHex(request.gasPrice); - if (typeof request.maxFeePerBlobGas !== "undefined") - rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas); - if (typeof request.maxFeePerGas !== "undefined") - rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas); - if (typeof request.maxPriorityFeePerGas !== "undefined") - rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas); - if (typeof request.nonce !== "undefined") - rpcRequest.nonce = numberToHex(request.nonce); - if (typeof request.to !== "undefined") - rpcRequest.to = request.to; - if (typeof request.type !== "undefined") - rpcRequest.type = rpcTransactionType[request.type]; - if (typeof request.value !== "undefined") - rpcRequest.value = numberToHex(request.value); - return rpcRequest; + stack.unshift(prev); + return stack; } -function formatAuthorizationList$1(authorizationList) { - return authorizationList.map((authorization) => ({ - address: authorization.contractAddress, - r: authorization.r, - s: authorization.s, - chainId: numberToHex(authorization.chainId), - nonce: numberToHex(authorization.nonce), - ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {}, - ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {} - })); +function isWalletConfig(config2) { + return config2.threshold !== void 0 && config2.checkpoint !== void 0 && config2.tree !== void 0 && config2.version !== void 0 && config2.version === 2; } -function getAction$1(client2, actionFn, name2) { - const action_implicit = client2[actionFn.name]; - if (typeof action_implicit === "function") - return action_implicit; - const action_explicit = client2[name2]; - if (typeof action_explicit === "function") - return action_explicit; - return (params) => actionFn(client2, params); +function imageHash(config2) { + return solidityPackedKeccak256(["bytes32", "uint256"], [solidityPackedKeccak256(["bytes32", "uint256"], [hashNode(config2.tree), config2.threshold]), config2.checkpoint]); } -const maxUint256 = 2n ** 256n - 1n; -function assertRequest(args) { - const { account: account_, gasPrice, maxFeePerGas, maxPriorityFeePerGas, to } = args; - const account2 = account_ ? parseAccount(account_) : void 0; - if (account2 && !isAddress(account2.address)) - throw new InvalidAddressError({ address: account2.address }); - if (to && !isAddress(to)) - throw new InvalidAddressError({ address: to }); - if (typeof gasPrice !== "undefined" && (typeof maxFeePerGas !== "undefined" || typeof maxPriorityFeePerGas !== "undefined")) - throw new FeeConflictError(); - if (maxFeePerGas && maxFeePerGas > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas }); - if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) - throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +function isSimpleNestedMember(member) { + return member.threshold !== void 0 && member.weight !== void 0 && member.members !== void 0; } -async function getChainId$1(client2) { - const chainIdHex = await client2.request({ - method: "eth_chainId" - }, { dedupe: true }); - return hexToNumber$1(chainIdHex); +function topologyToMembers(tree) { + if (isSignerLeaf(tree) || isSubdigestLeaf(tree)) { + return [tree]; + } + if (isNestedLeaf(tree)) { + return [{ + threshold: tree.threshold, + weight: tree.weight, + members: topologyToMembers(tree.tree) + }]; + } + if (isNodeLeaf(tree)) { + return []; + } + return [...topologyToMembers(tree.left), ...topologyToMembers(tree.right)]; } -class BaseFeeScalarError extends BaseError$3 { - constructor() { - super("`baseFeeMultiplier` must be greater than 1.", { - name: "BaseFeeScalarError" - }); +function hasUnknownNodes(tree) { + if (isNodeLeaf(tree)) { + return true; } + if (isNode$1(tree)) { + return hasUnknownNodes(tree.left) || hasUnknownNodes(tree.right); + } + return false; } -class Eip1559FeesNotSupportedError extends BaseError$3 { - constructor() { - super("Chain does not support EIP-1559 fees.", { - name: "Eip1559FeesNotSupportedError" - }); +function toSimpleWalletConfig(config2) { + return { + threshold: config2.threshold, + checkpoint: config2.checkpoint, + members: topologyToMembers(config2.tree) + }; +} +const membersAsTopologies = (members, builder) => { + return members.map((member) => { + if (isSimpleNestedMember(member)) { + return { + tree: builder(member.members), + threshold: member.threshold, + weight: member.weight + }; + } + return member; + }); +}; +function legacyTopologyBuilder(members) { + if (members.length === 0) { + throw new Error("Empty members array"); } + const asTopologies = membersAsTopologies(members, legacyTopologyBuilder); + return asTopologies.reduce((acc, member) => { + return { + left: acc, + right: member + }; + }); } -class MaxFeePerGasTooLowError extends BaseError$3 { - constructor({ maxPriorityFeePerGas }) { - super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" }); +function merkleTopologyBuilder(members) { + if (members.length === 0) { + throw new Error("Empty members array"); + } + const leaves = membersAsTopologies(members, merkleTopologyBuilder); + for (let s2 = leaves.length; s2 > 1; s2 = s2 / 2) { + for (let i = 0; i < s2 / 2; i++) { + const j1 = i * 2; + const j2 = j1 + 1; + if (j2 >= s2) { + leaves[i] = leaves[j1]; + } else { + leaves[i] = { + left: leaves[j1], + right: leaves[j2] + }; + } + } } + return leaves[0]; } -class BlockNotFoundError extends BaseError$3 { - constructor({ blockHash, blockNumber }) { - let identifier = "Block"; - if (blockHash) - identifier = `Block at hash "${blockHash}"`; - if (blockNumber) - identifier = `Block at number "${blockNumber}"`; - super(`${identifier} could not be found.`, { name: "BlockNotFoundError" }); +function optimized2SignersTopologyBuilder(members) { + if (members.length > 8) { + return merkleTopologyBuilder(members); } + return legacyTopologyBuilder(members); } -const transactionType = { - "0x0": "legacy", - "0x1": "eip2930", - "0x2": "eip1559", - "0x3": "eip4844", - "0x4": "eip7702" -}; -function formatTransaction(transaction2) { - const transaction_ = { - ...transaction2, - blockHash: transaction2.blockHash ? transaction2.blockHash : null, - blockNumber: transaction2.blockNumber ? BigInt(transaction2.blockNumber) : null, - chainId: transaction2.chainId ? hexToNumber$1(transaction2.chainId) : void 0, - gas: transaction2.gas ? BigInt(transaction2.gas) : void 0, - gasPrice: transaction2.gasPrice ? BigInt(transaction2.gasPrice) : void 0, - maxFeePerBlobGas: transaction2.maxFeePerBlobGas ? BigInt(transaction2.maxFeePerBlobGas) : void 0, - maxFeePerGas: transaction2.maxFeePerGas ? BigInt(transaction2.maxFeePerGas) : void 0, - maxPriorityFeePerGas: transaction2.maxPriorityFeePerGas ? BigInt(transaction2.maxPriorityFeePerGas) : void 0, - nonce: transaction2.nonce ? hexToNumber$1(transaction2.nonce) : void 0, - to: transaction2.to ? transaction2.to : null, - transactionIndex: transaction2.transactionIndex ? Number(transaction2.transactionIndex) : null, - type: transaction2.type ? transactionType[transaction2.type] : void 0, - typeHex: transaction2.type ? transaction2.type : void 0, - value: transaction2.value ? BigInt(transaction2.value) : void 0, - v: transaction2.v ? BigInt(transaction2.v) : void 0 +function toWalletConfig(simpleWalletConfig, builder = optimized2SignersTopologyBuilder) { + return { + version: 2, + threshold: simpleWalletConfig.threshold, + checkpoint: simpleWalletConfig.checkpoint, + tree: builder(simpleWalletConfig.members) }; - if (transaction2.authorizationList) - transaction_.authorizationList = formatAuthorizationList(transaction2.authorizationList); - transaction_.yParity = (() => { - if (transaction2.yParity) - return Number(transaction2.yParity); - if (typeof transaction_.v === "bigint") { - if (transaction_.v === 0n || transaction_.v === 27n) - return 0; - if (transaction_.v === 1n || transaction_.v === 28n) - return 1; - if (transaction_.v >= 35n) - return transaction_.v % 2n === 0n ? 1 : 0; - } - return void 0; - })(); - if (transaction_.type === "legacy") { - delete transaction_.accessList; - delete transaction_.maxFeePerBlobGas; - delete transaction_.maxFeePerGas; - delete transaction_.maxPriorityFeePerGas; - delete transaction_.yParity; +} +function hasSubdigest(tree, subdigest) { + if (isSubdigestLeaf(tree)) { + return tree.subdigest === subdigest; } - if (transaction_.type === "eip2930") { - delete transaction_.maxFeePerBlobGas; - delete transaction_.maxFeePerGas; - delete transaction_.maxPriorityFeePerGas; + if (isNode$1(tree)) { + return hasSubdigest(tree.left, subdigest) || hasSubdigest(tree.right, subdigest); } - if (transaction_.type === "eip1559") { - delete transaction_.maxFeePerBlobGas; + return false; +} +function signersOf(tree) { + const stack = [tree]; + const signers = /* @__PURE__ */ new Set(); + while (stack.length > 0) { + const node = stack.pop(); + if (isNestedLeaf(node)) { + stack.push(node.tree); + } else if (isNode$1(node)) { + stack.push(node.left); + stack.push(node.right); + } else if (isSignerLeaf(node)) { + signers.add({ + address: node.address, + weight: Number(node.weight) + }); + } } - return transaction_; + return Array.from(signers); } -function formatAuthorizationList(authorizationList) { - return authorizationList.map((authorization) => ({ - contractAddress: authorization.address, - r: authorization.r, - s: authorization.s, - chainId: Number(authorization.chainId), - nonce: Number(authorization.nonce), - ...typeof authorization.yParity !== "undefined" ? { yParity: Number(authorization.yParity) } : {}, - ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: Number(authorization.v) } : {} - })); +function isComplete(tree) { + if (isNode$1(tree)) { + return isComplete(tree.left) && isComplete(tree.right); + } + return !isNodeLeaf(tree); +} +const ConfigCoder = { + isWalletConfig: (config2) => { + return config2.version === 2 && config2.threshold !== void 0 && config2.tree !== void 0; + }, + imageHashOf: (config2) => { + return imageHash(config2); + }, + hasSubdigest: (config2, subdigest) => { + return hasSubdigest(config2.tree, subdigest); + }, + checkpointOf: (config2) => { + return BigInt(config2.checkpoint); + }, + signersOf: (config2) => { + return signersOf(config2.tree); + }, + fromSimple: (config2) => { + var _config$subdigests; + return toWalletConfig(_extends$c({}, config2, { + members: [...config2.signers, ...((_config$subdigests = config2.subdigests) != null ? _config$subdigests : []).map((subdigest) => ({ + subdigest + }))] + })); + }, + isComplete: (config2) => { + return isComplete(config2.tree); + }, + // isValid = (config: WalletConfig): boolean {} + /** + * + * Notice: context and kind are ignored because v2 + * doesn't need to manually update the implementation before + * a configuration update, it's automatically done by the contract. + * + */ + update: { + isKindUsed: true, + buildTransaction: (wallet, config2, _context, _kind) => { + const module2 = new Interface(walletContracts.mainModuleUpgradable.abi); + return { + entrypoint: wallet, + transactions: [{ + to: wallet, + data: module2.encodeFunctionData(module2.getFunction("updateImageHash"), [ConfigCoder.imageHashOf(config2)]), + gasLimit: 0, + delegateCall: false, + revertOnError: true, + value: 0 + }] + }; + }, + decodeTransaction: function(tx) { + var _tx$transactions$0$va, _tx$transactions$, _tx$transactions$0$ga, _tx$transactions$2; + const module2 = new Interface(walletContracts.mainModuleUpgradable.abi); + if (tx.transactions.length !== 1) { + throw new Error("Invalid transaction bundle, expected 1 transaction"); + } + const data = tx.transactions[0].data; + if (!data) { + throw new Error("Invalid transaction bundle, expected data"); + } + const decoded = module2.decodeFunctionData(module2.getFunction("updateImageHash"), data); + if (!decoded) { + throw new Error("Invalid transaction bundle, expected valid data"); + } + if (tx.transactions[0].to !== tx.entrypoint) { + throw new Error("Invalid transaction bundle, expected to be sent to entrypoint"); + } + if (tx.transactions[0].delegateCall) { + throw new Error("Invalid transaction bundle, expected not to be a delegateCall"); + } + if (!tx.transactions[0].revertOnError) { + throw new Error("Invalid transaction bundle, expected revertOnError"); + } + if (BigInt((_tx$transactions$0$va = (_tx$transactions$ = tx.transactions[0]) == null ? void 0 : _tx$transactions$.value) != null ? _tx$transactions$0$va : 0) !== 0n) { + throw new Error("Invalid transaction bundle, expected value to be 0"); + } + if (BigInt((_tx$transactions$0$ga = (_tx$transactions$2 = tx.transactions[0]) == null ? void 0 : _tx$transactions$2.gasLimit) != null ? _tx$transactions$0$ga : 0) !== 0n) { + throw new Error("Invalid transaction bundle, expected value to be 0"); + } + return { + address: tx.entrypoint, + newImageHash: decoded[0], + kind: void 0 + }; + } + }, + toJSON: function(config2) { + return JSON.stringify({ + version: config2.version, + threshold: BigInt(config2.threshold).toString(), + checkpoint: BigInt(config2.checkpoint).toString(), + tree: topologyToJSON(config2.tree) + }); + }, + fromJSON: function(json) { + const config2 = JSON.parse(json); + return { + version: config2.version, + threshold: BigInt(config2.threshold), + checkpoint: BigInt(config2.checkpoint), + tree: topologyFromJSON(config2.tree) + }; + }, + editConfig: function(config2, action) { + var _action$threshold, _action$checkpoint; + const members = topologyToMembers(config2.tree); + if (action.add) { + for (const signer2 of action.add) { + if (members.find((s2) => isSignerLeaf(s2) && s2.address === signer2.address)) { + continue; + } + members.push({ + address: signer2.address, + weight: signer2.weight + }); + } + } + if (action.remove) { + for (const address of action.remove) { + const index2 = members.findIndex((s2) => isSignerLeaf(s2) && s2.address === address); + if (index2 >= 0) { + members.splice(index2, 1); + } + } + } + return { + version: config2.version, + threshold: (_action$threshold = action.threshold) != null ? _action$threshold : config2.threshold, + checkpoint: (_action$checkpoint = action.checkpoint) != null ? _action$checkpoint : config2.checkpoint, + tree: optimized2SignersTopologyBuilder(members) + }; + }, + buildStubSignature: function(config2, overrides) { + const parts = /* @__PURE__ */ new Map(); + for (const [signer2, signature2] of overrides.entries()) { + parts.set(signer2, { + signature: signature2, + isDynamic: true + }); + const { + encoded, + weight + } = encodeSigners(config2, parts, [], 0); + if (weight >= BigInt(config2.threshold)) { + return encoded; + } + } + const signers = signersOf(config2.tree); + for (const { + address + } of signers.sort(({ + weight: a2 + }, { + weight: b2 + }) => a2 - b2)) { + const signature2 = "0x4e82f02f388a12b5f9d29eaf2452dd040c0ee5804b4e504b4dd64e396c6c781f2c7624195acba242dd825bfd25a290912e3c230841fd55c9a734c4de8d9899451b02"; + parts.set(address, { + signature: signature2, + isDynamic: false + }); + const { + encoded, + weight + } = encodeSigners(config2, parts, [], 0); + if (weight >= BigInt(config2.threshold)) { + return encoded; + } + } + return encodeSigners(config2, parts, [], 0).encoded; + } +}; +var config$3 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + isSignerLeaf, + isSubdigestLeaf, + topologyToJSON, + topologyFromJSON, + isNestedLeaf, + isNodeLeaf, + isLeaf: isLeaf$1, + isNode: isNode$1, + isTopology, + encodeSignerLeaf, + decodeSignerLeaf, + isEncodedSignerLeaf, + hashNode, + leftFace, + isWalletConfig, + imageHash, + isSimpleNestedMember, + topologyToMembers, + hasUnknownNodes, + toSimpleWalletConfig, + legacyTopologyBuilder, + merkleTopologyBuilder, + optimized2SignersTopologyBuilder, + toWalletConfig, + hasSubdigest, + signersOf, + isComplete, + ConfigCoder +}); +var context$1 = /* @__PURE__ */ Object.freeze({ + __proto__: null +}); +const coders = { + config: ConfigCoder, + signature: SignatureCoder +}; +const version$3 = 2; +const DeployedWalletContext = { + version: version$3, + factory: "0xFaA5c0b14d1bED5C888Ca655B9a8A5911F78eF4A", + guestModule: "0xfea230Ee243f88BC698dD8f1aE93F8301B6cdfaE", + mainModule: "0xfBf8f1A5E00034762D928f46d438B947f5d4065d", + mainModuleUpgradable: "0x4222dcA3974E39A8b41c411FeDDE9b09Ae14b911", + walletCreationCode: "0x603a600e3d39601a805130553df3363d3d373d3d3d363d30545af43d82803e903d91601857fd5bf3" +}; +var v2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + config: config$3, + signature, + context: context$1, + chained, + coders, + version: version$3, + DeployedWalletContext +}); +function addressOf(context2, imageHash2) { + const codeHash = keccak256(solidityPacked(["bytes", "bytes32"], [context2.walletCreationCode, zeroPadValue(context2.mainModule, 32)])); + const hash2 = keccak256(solidityPacked(["bytes1", "address", "bytes32", "bytes32"], ["0xff", context2.factory, imageHash2, codeHash])); + return getAddress(dataSlice(hash2, 12)); } -function formatBlock(block) { - var _a2; - const transactions2 = (_a2 = block.transactions) == null ? void 0 : _a2.map((transaction2) => { - if (typeof transaction2 === "string") - return transaction2; - return formatTransaction(transaction2); - }); - return { - ...block, - baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null, - blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0, - difficulty: block.difficulty ? BigInt(block.difficulty) : void 0, - excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0, - gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0, - gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0, - hash: block.hash ? block.hash : null, - logsBloom: block.logsBloom ? block.logsBloom : null, - nonce: block.nonce ? block.nonce : null, - number: block.number ? BigInt(block.number) : null, - size: block.size ? BigInt(block.size) : void 0, - timestamp: block.timestamp ? BigInt(block.timestamp) : void 0, - transactions: transactions2, - totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null - }; +async function isValidCounterfactual(wallet, digest, signature2, chainId, provider2, contexts) { + const res = await Promise.all(allVersions.map(async (version2) => { + try { + const decoded = version2.signature.SignatureCoder.decode(hexlify(signature2)); + const recovered1 = await version2.signature.SignatureCoder.recover(decoded, { + address: wallet, + digest: hexlify(digest), + chainId + }, provider2); + const imageHash2 = version2.config.ConfigCoder.imageHashOf(recovered1.config); + const counterfactualAddress = addressOf(contexts[version2.version], imageHash2); + if (counterfactualAddress.toLowerCase() === wallet.toLowerCase()) { + return true; + } + const recovered2 = await version2.signature.SignatureCoder.recover(decoded, { + address: wallet, + digest: hexlify(digest), + chainId + }, provider2); + const imageHash22 = version2.config.ConfigCoder.imageHashOf(recovered2.config); + const counterfactualAddress2 = addressOf(contexts[version2.version], imageHash22); + return counterfactualAddress2.toLowerCase() === wallet.toLowerCase(); + } catch (_unused) { + } + return false; + })); + return res.some((r2) => r2); } -async function getBlock(client2, { blockHash, blockNumber, blockTag: blockTag_, includeTransactions: includeTransactions_ } = {}) { - var _a2, _b2, _c2; - const blockTag = blockTag_ ?? "latest"; - const includeTransactions = includeTransactions_ ?? false; - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - let block = null; - if (blockHash) { - block = await client2.request({ - method: "eth_getBlockByHash", - params: [blockHash, includeTransactions] - }, { dedupe: true }); - } else { - block = await client2.request({ - method: "eth_getBlockByNumber", - params: [blockNumberHex || blockTag, includeTransactions] - }, { dedupe: Boolean(blockNumberHex) }); +function isValidVersionedContext(contexts) { + const versions = Object.keys(contexts).length; + for (let i = 1; i <= versions; i++) { + const context2 = contexts[i]; + if (!context2 || context2.version !== i) { + return false; + } } - if (!block) - throw new BlockNotFoundError({ blockHash, blockNumber }); - const format2 = ((_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.block) == null ? void 0 : _c2.format) || formatBlock; - return format2(block); + return true; } -async function getGasPrice(client2) { - const gasPrice = await client2.request({ - method: "eth_gasPrice" +function latestContext(contexts) { + const versions = Object.keys(contexts).length; + return contexts[versions]; +} +const defaultContexts = { + 1: DeployedWalletContext$1, + 2: DeployedWalletContext +}; +var context = /* @__PURE__ */ Object.freeze({ + __proto__: null, + addressOf, + isValidCounterfactual, + isValidVersionedContext, + latestContext, + defaultContexts +}); +const MetaTransactionsType = `tuple( + bool delegateCall, + bool revertOnError, + uint256 gasLimit, + address target, + uint256 value, + bytes data +)[]`; +function intendTransactionBundle(bundle, wallet, chainId, id2) { + return _extends$c({}, bundle, { + chainId, + intent: { + id: id2, + wallet + } }); - return BigInt(gasPrice); } -async function estimateMaxPriorityFeePerGas(client2, args) { - return internal_estimateMaxPriorityFeePerGas(client2, args); +function intendedTransactionID(bundle) { + return keccak256(AbiCoder.defaultAbiCoder().encode(["address", "uint256", "bytes32"], [bundle.intent.wallet, bundle.chainId, bundle.intent.id])); } -async function internal_estimateMaxPriorityFeePerGas(client2, args) { - var _a2, _b2; - const { block: block_, chain = client2.chain, request } = args || {}; - try { - const maxPriorityFeePerGas = ((_a2 = chain == null ? void 0 : chain.fees) == null ? void 0 : _a2.maxPriorityFeePerGas) ?? ((_b2 = chain == null ? void 0 : chain.fees) == null ? void 0 : _b2.defaultPriorityFee); - if (typeof maxPriorityFeePerGas === "function") { - const block = block_ || await getAction$1(client2, getBlock, "getBlock")({}); - const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({ - block, - client: client2, - request - }); - if (maxPriorityFeePerGas_ === null) - throw new Error(); - return maxPriorityFeePerGas_; - } - if (typeof maxPriorityFeePerGas !== "undefined") - return maxPriorityFeePerGas; - const maxPriorityFeePerGasHex = await client2.request({ - method: "eth_maxPriorityFeePerGas" - }); - return hexToBigInt(maxPriorityFeePerGasHex); - } catch { - const [block, gasPrice] = await Promise.all([ - block_ ? Promise.resolve(block_) : getAction$1(client2, getBlock, "getBlock")({}), - getAction$1(client2, getGasPrice, "getGasPrice")({}) - ]); - if (typeof block.baseFeePerGas !== "bigint") - throw new Eip1559FeesNotSupportedError(); - const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas; - if (maxPriorityFeePerGas < 0n) - return 0n; - return maxPriorityFeePerGas; - } +function unpackMetaTransactionsData(data) { + const res = AbiCoder.defaultAbiCoder().decode(["uint256", MetaTransactionsType], data); + if (res.length !== 2 || !res[0] || !res[1]) throw new Error("Invalid meta transaction data"); + return [res[0], res[1]]; } -async function estimateFeesPerGas(client2, args) { - return internal_estimateFeesPerGas(client2, args); +function packMetaTransactionsData(nonce, txs) { + return AbiCoder.defaultAbiCoder().encode(["uint256", MetaTransactionsType], [nonce, sequenceTxAbiEncode(txs)]); } -async function internal_estimateFeesPerGas(client2, args) { - var _a2, _b2; - const { block: block_, chain = client2.chain, request, type = "eip1559" } = args || {}; - const baseFeeMultiplier = await (async () => { - var _a3, _b3; - if (typeof ((_a3 = chain == null ? void 0 : chain.fees) == null ? void 0 : _a3.baseFeeMultiplier) === "function") - return chain.fees.baseFeeMultiplier({ - block: block_, - client: client2, - request - }); - return ((_b3 = chain == null ? void 0 : chain.fees) == null ? void 0 : _b3.baseFeeMultiplier) ?? 1.2; - })(); - if (baseFeeMultiplier < 1) - throw new BaseFeeScalarError(); - const decimals = ((_a2 = baseFeeMultiplier.toString().split(".")[1]) == null ? void 0 : _a2.length) ?? 0; - const denominator = 10 ** decimals; - const multiply = (base) => base * BigInt(Math.ceil(baseFeeMultiplier * denominator)) / BigInt(denominator); - const block = block_ ? block_ : await getAction$1(client2, getBlock, "getBlock")({}); - if (typeof ((_b2 = chain == null ? void 0 : chain.fees) == null ? void 0 : _b2.estimateFeesPerGas) === "function") { - const fees = await chain.fees.estimateFeesPerGas({ - block: block_, - client: client2, - multiply, - request, - type - }); - if (fees !== null) - return fees; - } - if (type === "eip1559") { - if (typeof block.baseFeePerGas !== "bigint") - throw new Eip1559FeesNotSupportedError(); - const maxPriorityFeePerGas = typeof (request == null ? void 0 : request.maxPriorityFeePerGas) === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client2, { - block, - chain, - request - }); - const baseFeePerGas = multiply(block.baseFeePerGas); - const maxFeePerGas = (request == null ? void 0 : request.maxFeePerGas) ?? baseFeePerGas + maxPriorityFeePerGas; - return { - maxFeePerGas, - maxPriorityFeePerGas - }; - } - const gasPrice = (request == null ? void 0 : request.gasPrice) ?? multiply(await getAction$1(client2, getGasPrice, "getGasPrice")({})); - return { - gasPrice - }; +function digestOfTransactions(nonce, txs) { + return keccak256(packMetaTransactionsData(nonce, txs)); } -class EstimateGasExecutionError extends BaseError$3 { - constructor(cause, { account: account2, docsPath: docsPath2, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) { - var _a2; - const prettyArgs = prettyPrint({ - from: account2 == null ? void 0 : account2.address, - to, - value: typeof value !== "undefined" && `${formatEther(value)} ${((_a2 = chain == null ? void 0 : chain.nativeCurrency) == null ? void 0 : _a2.symbol) || "ETH"}`, - data, - gas, - gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, - maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, - maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, - nonce - }); - super(cause.shortMessage, { - cause, - docsPath: docsPath2, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - "Estimate Gas Arguments:", - prettyArgs - ].filter(Boolean), - name: "EstimateGasExecutionError" - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.cause = cause; - } +function subdigestOfTransactions(address, chainId, nonce, txs) { + return subdigestOf({ + address, + chainId, + digest: digestOfTransactions(nonce, txs) + }); } -function getEstimateGasError(err, { docsPath: docsPath2, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new EstimateGasExecutionError(cause, { - docsPath: docsPath2, - ...args +function subdigestOfGuestModuleTransactions(guestModule, chainId, txs) { + return subdigestOf({ + address: guestModule, + chainId, + digest: keccak256(AbiCoder.defaultAbiCoder().encode(["string", MetaTransactionsType], ["guest:", sequenceTxAbiEncode(txs)])) }); } -class AccountStateConflictError extends BaseError$3 { - constructor({ address }) { - super(`State for account "${address}" is set multiple times.`, { - name: "AccountStateConflictError" - }); - } +function toSequenceTransactions(wallet, txs) { + return txs.map((tx) => toSequenceTransaction(wallet, tx)); } -class StateAssignmentConflictError extends BaseError$3 { - constructor() { - super("state and stateDiff are set on the same account.", { - name: "StateAssignmentConflictError" - }); +function toSequenceTransaction(wallet, tx) { + if (tx.to && tx.to !== ZeroAddress) { + return { + nonce: !isNullish(tx.nonce) ? BigInt(tx.nonce) : void 0, + transaction: { + delegateCall: false, + revertOnError: false, + gasLimit: !isNullish(tx.gasLimit) ? BigInt(tx.gasLimit) : void 0, + // XXX: `tx.to` could also be ethers Addressable type which returns a getAddress promise + // Keeping this as is for now so we don't have to change everything to async + to: tx.to, + value: BigInt(tx.value || 0), + data: tx.data || "0x" + } + }; + } else { + const walletInterface = new Interface(walletContracts.mainModule.abi); + const data = walletInterface.encodeFunctionData(walletInterface.getFunction("createContract"), [tx.data]); + return { + nonce: typeof tx.nonce === "number" ? BigInt(tx.nonce) : void 0, + transaction: { + delegateCall: false, + revertOnError: false, + gasLimit: !isNullish(tx.gasLimit) ? BigInt(tx.gasLimit) : void 0, + to: wallet, + value: BigInt(tx.value || 0), + data + } + }; } } -function prettyStateMapping(stateMapping) { - return stateMapping.reduce((pretty, { slot, value }) => { - return `${pretty} ${slot}: ${value} -`; - }, ""); +function isSequenceTransaction(tx) { + return tx.delegateCall !== void 0 || tx.revertOnError !== void 0; } -function prettyStateOverride(stateOverride) { - return stateOverride.reduce((pretty, { address, ...state }) => { - let val = `${pretty} ${address}: -`; - if (state.nonce) - val += ` nonce: ${state.nonce} -`; - if (state.balance) - val += ` balance: ${state.balance} -`; - if (state.code) - val += ` code: ${state.code} -`; - if (state.state) { - val += " state:\n"; - val += prettyStateMapping(state.state); - } - if (state.stateDiff) { - val += " stateDiff:\n"; - val += prettyStateMapping(state.stateDiff); - } - return val; - }, " State Override:\n").slice(0, -1); +function hasSequenceTransactions(txs) { + return txs.every(isSequenceTransaction); } -function serializeStateMapping(stateMapping) { - if (!stateMapping || stateMapping.length === 0) - return void 0; - return stateMapping.reduce((acc, { slot, value }) => { - if (slot.length !== 66) - throw new InvalidBytesLengthError({ - size: slot.length, - targetSize: 66, - type: "hex" - }); - if (value.length !== 66) - throw new InvalidBytesLengthError({ - size: value.length, - targetSize: 66, - type: "hex" - }); - acc[slot] = value; - return acc; - }, {}); +function sequenceTxAbiEncode(txs) { + return txs.map((tx) => { + var _tx$to; + return { + delegateCall: tx.delegateCall === true, + revertOnError: tx.revertOnError === true, + gasLimit: !isNullish(tx.gasLimit) ? BigInt(tx.gasLimit) : 0n, + target: (_tx$to = tx.to) != null ? _tx$to : ZeroAddress, + value: !isNullish(tx.value) ? tx.value : 0n, + data: tx.data || "0x" + }; + }); } -function serializeAccountStateOverride(parameters) { - const { balance, nonce, state, stateDiff, code: code2 } = parameters; - const rpcAccountStateOverride = {}; - if (code2 !== void 0) - rpcAccountStateOverride.code = code2; - if (balance !== void 0) - rpcAccountStateOverride.balance = numberToHex(balance); - if (nonce !== void 0) - rpcAccountStateOverride.nonce = numberToHex(nonce); - if (state !== void 0) - rpcAccountStateOverride.state = serializeStateMapping(state); - if (stateDiff !== void 0) { - if (rpcAccountStateOverride.state) - throw new StateAssignmentConflictError(); - rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff); - } - return rpcAccountStateOverride; +function fromTxAbiEncode(txs) { + return txs.map((tx) => ({ + delegateCall: tx.delegateCall, + revertOnError: tx.revertOnError, + gasLimit: tx.gasLimit, + to: tx.target, + value: tx.value, + data: tx.data + })); } -function serializeStateOverride(parameters) { - if (!parameters) - return void 0; - const rpcStateOverride = {}; - for (const { address, ...accountState } of parameters) { - if (!isAddress(address, { strict: false })) - throw new InvalidAddressError({ address }); - if (rpcStateOverride[address]) - throw new AccountStateConflictError({ address }); - rpcStateOverride[address] = serializeAccountStateOverride(accountState); +function encodeNonce(space, nonce) { + const bspace = BigInt(space); + const bnonce = BigInt(nonce); + const shl = 2n ** 96n; + if (bnonce / shl !== 0n) { + throw new Error("Space already encoded"); } - return rpcStateOverride; + return bnonce + bspace * shl; } -async function getBalance(client2, { address, blockNumber, blockTag = "latest" }) { - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const balance = await client2.request({ - method: "eth_getBalance", - params: [address, blockNumberHex || blockTag] - }); - return BigInt(balance); +function decodeNonce(nonce) { + const bnonce = BigInt(nonce); + const shr = 2n ** 96n; + return [bnonce / shr, bnonce % shr]; } -async function estimateGas(client2, args) { - var _a2, _b2, _c2; - const account_ = args.account ?? client2.account; - const account2 = account_ ? parseAccount(account_) : void 0; - try { - let estimateGas_rpc = function(parameters) { - const { block: block2, request: request2, rpcStateOverride: rpcStateOverride2 } = parameters; - return client2.request({ - method: "eth_estimateGas", - params: rpcStateOverride2 ? [request2, block2 ?? "latest", rpcStateOverride2] : block2 ? [request2, block2] : [request2] - }); - }; - const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = await prepareTransactionRequest(client2, { - ...args, - parameters: ( - // Some RPC Providers do not compute versioned hashes from blobs. We will need - // to compute them. - (account2 == null ? void 0 : account2.type) === "local" ? void 0 : ["blobVersionedHashes"] - ) - }); - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const block = blockNumberHex || blockTag; - const rpcStateOverride = serializeStateOverride(stateOverride); - const to = await (async () => { - if (rest.to) - return rest.to; - if (authorizationList && authorizationList.length > 0) - return await recoverAuthorizationAddress({ - authorization: authorizationList[0] - }).catch(() => { - throw new BaseError$3("`to` is required. Could not infer from `authorizationList`"); - }); - return void 0; - })(); - assertRequest(args); - const chainFormat = (_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.transactionRequest) == null ? void 0 : _c2.format; - const format2 = chainFormat || formatTransactionRequest; - const request = format2({ - // Pick out extra data that might exist on the chain's transaction request type. - ...extract(rest, { format: chainFormat }), - from: account2 == null ? void 0 : account2.address, - accessList, - authorizationList, - blobs, - blobVersionedHashes, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to, - value - }); - let estimate = BigInt(await estimateGas_rpc({ block, request, rpcStateOverride })); - if (authorizationList) { - const value2 = await getBalance(client2, { address: request.from }); - const estimates = await Promise.all(authorizationList.map(async (authorization) => { - const { contractAddress } = authorization; - const estimate2 = await estimateGas_rpc({ - block, - request: { - authorizationList: void 0, - data, - from: account2 == null ? void 0 : account2.address, - to: contractAddress, - value: numberToHex(value2) - }, - rpcStateOverride - }).catch(() => 100000n); - return 2n * BigInt(estimate2); - })); - estimate += estimates.reduce((acc, curr) => acc + curr, 0n); +function fromTransactionish(wallet, transaction2) { + if (Array.isArray(transaction2)) { + if (hasSequenceTransactions(transaction2)) { + return transaction2; + } else { + const stx = toSequenceTransactions(wallet, transaction2); + return stx.map((t2) => t2.transaction); } - return estimate; - } catch (err) { - throw getEstimateGasError(err, { - ...args, - account: account2, - chain: client2.chain - }); + } else if (isSequenceTransaction(transaction2)) { + return [transaction2]; + } else { + return [toSequenceTransaction(wallet, transaction2).transaction]; } } -async function getTransactionCount(client2, { address, blockTag = "latest", blockNumber }) { - const count2 = await client2.request({ - method: "eth_getTransactionCount", - params: [address, blockNumber ? numberToHex(blockNumber) : blockTag] - }, { dedupe: Boolean(blockNumber) }); - return hexToNumber$1(count2); +function isTransactionBundle(cand) { + return cand !== void 0 && cand.entrypoint !== void 0 && cand.chainId !== void 0 && cand.transactions !== void 0 && cand.nonce !== void 0 && cand.intent !== void 0 && cand.intent.id !== void 0 && cand.intent.wallet !== void 0 && Array.isArray(cand.transactions) && cand.transactions.reduce((p2, c2) => p2 && isSequenceTransaction(c2), true); } -function blobsToCommitments(parameters) { - const { kzg } = parameters; - const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); - const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes$1(x2)) : parameters.blobs; - const commitments = []; - for (const blob of blobs) - commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob))); - return to === "bytes" ? commitments : commitments.map((x2) => bytesToHex$1(x2)); +function isSignedTransactionBundle(cand) { + return cand !== void 0 && cand.signature !== void 0 && cand.signature !== "" && isTransactionBundle(cand); } -function blobsToProofs(parameters) { - const { kzg } = parameters; - const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); - const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes$1(x2)) : parameters.blobs; - const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x2) => hexToBytes$1(x2)) : parameters.commitments; - const proofs = []; - for (let i = 0; i < blobs.length; i++) { - const blob = blobs[i]; - const commitment = commitments[i]; - proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))); - } - return to === "bytes" ? proofs : proofs.map((x2) => bytesToHex$1(x2)); +function encodeBundleExecData(bundle) { + const walletInterface = new Interface(walletContracts.mainModule.abi); + return walletInterface.encodeFunctionData(walletInterface.getFunction("execute"), isSignedTransactionBundle(bundle) ? [ + // Signed transaction bundle has all 3 parameters + sequenceTxAbiEncode(bundle.transactions), + bundle.nonce, + bundle.signature + ] : [ + // Unsigned bundle may be a GuestModule call, so signature and nonce are missing + sequenceTxAbiEncode(bundle.transactions), + 0, + new Uint8Array([]) + ]); } -function setBigUint64(view, byteOffset, value, isLE2) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE2); - const _32n2 = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh2 = Number(value >> _32n2 & _u32_max); - const wl = Number(value & _u32_max); - const h2 = isLE2 ? 4 : 0; - const l2 = isLE2 ? 0 : 4; - view.setUint32(byteOffset + h2, wh2, isLE2); - view.setUint32(byteOffset + l2, wl, isLE2); +const selfExecuteSelector = "0x61c2926c"; +const selfExecuteAbi = `tuple( + bool delegateCall, + bool revertOnError, + uint256 gasLimit, + address target, + uint256 value, + bytes data +)[]`; +const unwind = (wallet, transactions2) => { + const unwound = []; + const walletInterface = new Interface(walletContracts.mainModule.abi); + for (const tx of transactions2) { + const txData = getBytes(tx.data || "0x"); + if (tx.to === wallet && hexlify(txData.slice(0, 4)) === selfExecuteSelector) { + const data = txData.slice(4); + const decoded = AbiCoder.defaultAbiCoder().decode([selfExecuteAbi], data)[0]; + unwound.push(...unwind(tx.to, decoded.map((d2) => _extends$c({}, d2, { + to: d2.target + })))); + } else { + try { + const innerTransactions = walletInterface.decodeFunctionData("execute", txData)[0]; + const unwoundTransactions = unwind(wallet, innerTransactions.map((tx2) => _extends$c({}, tx2.toObject(), { + to: tx2.target + }))); + unwound.push(...unwoundTransactions); + } catch (_unused) { + unwound.push(tx); + } + } + } + return unwound; +}; +const isNullish = (value) => value === null || value === void 0; +var transaction = /* @__PURE__ */ Object.freeze({ + __proto__: null, + MetaTransactionsType, + intendTransactionBundle, + intendedTransactionID, + unpackMetaTransactionsData, + packMetaTransactionsData, + digestOfTransactions, + subdigestOfTransactions, + subdigestOfGuestModuleTransactions, + toSequenceTransactions, + toSequenceTransaction, + isSequenceTransaction, + hasSequenceTransactions, + sequenceTxAbiEncode, + fromTxAbiEncode, + encodeNonce, + decodeNonce, + fromTransactionish, + isTransactionBundle, + isSignedTransactionBundle, + encodeBundleExecData, + selfExecuteSelector, + selfExecuteAbi, + unwind +}); +const EIP_6492_OFFCHAIN_DEPLOY_CODE = "0x608060405234801561001057600080fd5b5060405161124a38038061124a83398101604081905261002f91610124565b600060405161003d906100dd565b604051809103906000f080158015610059573d6000803e3d6000fd5b5090506000816001600160a01b0316638f0684308686866040518463ffffffff1660e01b815260040161008e939291906101fb565b6020604051808303816000875af11580156100ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100d19190610244565b9050806000526001601ff35b610fdc8061026e83390190565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561011b578181015183820152602001610103565b50506000910152565b60008060006060848603121561013957600080fd5b83516001600160a01b038116811461015057600080fd5b6020850151604086015191945092506001600160401b038082111561017457600080fd5b818601915086601f83011261018857600080fd5b81518181111561019a5761019a6100ea565b604051601f8201601f19908116603f011681019083821181831017156101c2576101c26100ea565b816040528281528960208487010111156101db57600080fd5b6101ec836020830160208801610100565b80955050505050509250925092565b60018060a01b0384168152826020820152606060408201526000825180606084015261022e816080850160208701610100565b601f01601f191691909101608001949350505050565b60006020828403121561025657600080fd5b8151801515811461026657600080fd5b939250505056fe608060405234801561001057600080fd5b50610fbc806100206000396000f3fe608060405234801561001057600080fd5b50600436106100675760003560e01c806376be4cea1161005057806376be4cea146100a65780638f068430146100b957806398ef1ed8146100cc57600080fd5b80631c6453271461006c5780633d787b6314610093575b600080fd5b61007f61007a366004610ad4565b6100df565b604051901515815260200160405180910390f35b61007f6100a1366004610ad4565b61023d565b61007f6100b4366004610b3e565b61031e565b61007f6100c7366004610ad4565b6108e1565b61007f6100da366004610ad4565b61096e565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea9061012890889088908890889088908190600401610bc3565b6020604051808303816000875af1925050508015610181575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016820190925261017e91810190610c45565b60015b610232573d8080156101af576040519150601f19603f3d011682016040523d82523d6000602084013e6101b4565b606091505b508051600181900361022757816000815181106101d3576101d3610c69565b6020910101517fff00000000000000000000000000000000000000000000000000000000000000167f0100000000000000000000000000000000000000000000000000000000000000149250610235915050565b600092505050610235565b90505b949350505050565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea906102879088908890889088906001908990600401610bc3565b6020604051808303816000875af19250505080156102e0575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682019092526102dd91810190610c45565b60015b610232573d80801561030e576040519150601f19603f3d011682016040523d82523d6000602084013e610313565b606091505b506000915050610235565b600073ffffffffffffffffffffffffffffffffffffffff87163b6060827f64926492649264926492649264926492649264926492649264926492649264928888610369602082610c98565b610375928b9290610cd8565b61037e91610d02565b1490508015610484576000606089828a610399602082610c98565b926103a693929190610cd8565b8101906103b39190610e18565b955090925090508415806103c45750865b1561047d576000808373ffffffffffffffffffffffffffffffffffffffff16836040516103f19190610eb2565b6000604051808303816000865af19150503d806000811461042e576040519150601f19603f3d011682016040523d82523d6000602084013e610433565b606091505b50915091508161047a57806040517f9d0d6e2d0000000000000000000000000000000000000000000000000000000081526004016104719190610f18565b60405180910390fd5b50505b50506104be565b87878080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509294505050505b80806104ca5750600083115b156106bb576040517f1626ba7e00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8b1690631626ba7e90610523908c908690600401610f2b565b602060405180830381865afa92505050801561057a575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016820190925261057791810190610f44565b60015b61060f573d8080156105a8576040519150601f19603f3d011682016040523d82523d6000602084013e6105ad565b606091505b50851580156105bc5750600084115b156105db576105d08b8b8b8b8b600161031e565b9450505050506108d7565b806040517f6f2a95990000000000000000000000000000000000000000000000000000000081526004016104719190610f18565b7fffffffff0000000000000000000000000000000000000000000000000000000081167f1626ba7e000000000000000000000000000000000000000000000000000000001480158161065f575086155b801561066b5750600085115b1561068b5761067f8c8c8c8c8c600161031e565b955050505050506108d7565b841580156106965750825b80156106a0575087155b156106af57806000526001601ffd5b94506108d79350505050565b6041871461074b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603a60248201527f5369676e617475726556616c696461746f72237265636f7665725369676e657260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610471565b600061075a6020828a8c610cd8565b61076391610d02565b90506000610775604060208b8d610cd8565b61077e91610d02565b905060008a8a604081811061079557610795610c69565b919091013560f81c915050601b81148015906107b557508060ff16601c14155b15610842576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f5369676e617475726556616c696461746f723a20696e76616c6964207369676e60448201527f617475726520762076616c7565000000000000000000000000000000000000006064820152608401610471565b6040805160008152602081018083528e905260ff831691810191909152606081018490526080810183905273ffffffffffffffffffffffffffffffffffffffff8e169060019060a0016020604051602081039080840390855afa1580156108ad573d6000803e3d6000fd5b5050506020604051035173ffffffffffffffffffffffffffffffffffffffff161496505050505050505b9695505050505050565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea9061092b9088908890889088906001908990600401610bc3565b6020604051808303816000875af115801561094a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102329190610c45565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea906109b790889088908890889088908190600401610bc3565b6020604051808303816000875af1925050508015610a10575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0168201909252610a0d91810190610c45565b60015b610232573d808015610a3e576040519150601f19603f3d011682016040523d82523d6000602084013e610a43565b606091505b5080516001819003610a6257816000815181106101d3576101d3610c69565b8082fd5b73ffffffffffffffffffffffffffffffffffffffff81168114610a8857600080fd5b50565b60008083601f840112610a9d57600080fd5b50813567ffffffffffffffff811115610ab557600080fd5b602083019150836020828501011115610acd57600080fd5b9250929050565b60008060008060608587031215610aea57600080fd5b8435610af581610a66565b935060208501359250604085013567ffffffffffffffff811115610b1857600080fd5b610b2487828801610a8b565b95989497509550505050565b8015158114610a8857600080fd5b60008060008060008060a08789031215610b5757600080fd5b8635610b6281610a66565b955060208701359450604087013567ffffffffffffffff811115610b8557600080fd5b610b9189828a01610a8b565b9095509350506060870135610ba581610b30565b91506080870135610bb581610b30565b809150509295509295509295565b73ffffffffffffffffffffffffffffffffffffffff8716815285602082015260a060408201528360a0820152838560c0830137600060c085830181019190915292151560608201529015156080820152601f9092017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016909101019392505050565b600060208284031215610c5757600080fd5b8151610c6281610b30565b9392505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b81810381811115610cd2577f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b92915050565b60008085851115610ce857600080fd5b83861115610cf557600080fd5b5050820193919092039150565b80356020831015610cd2577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff602084900360031b1b1692915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b600082601f830112610d7e57600080fd5b813567ffffffffffffffff80821115610d9957610d99610d3e565b604051601f83017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0908116603f01168101908282118183101715610ddf57610ddf610d3e565b81604052838152866020858801011115610df857600080fd5b836020870160208301376000602085830101528094505050505092915050565b600080600060608486031215610e2d57600080fd5b8335610e3881610a66565b9250602084013567ffffffffffffffff80821115610e5557600080fd5b610e6187838801610d6d565b93506040860135915080821115610e7757600080fd5b50610e8486828701610d6d565b9150509250925092565b60005b83811015610ea9578181015183820152602001610e91565b50506000910152565b60008251610ec4818460208701610e8e565b9190910192915050565b60008151808452610ee6816020860160208601610e8e565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b602081526000610c626020830184610ece565b8281526040602082015260006102356040830184610ece565b600060208284031215610f5657600080fd5b81517fffffffff0000000000000000000000000000000000000000000000000000000081168114610c6257600080fdfea26469706673582212201a72aed4b15ffb05b6502997a9bb655992e06590bd26b336dfbb153d7ff6f34b64736f6c63430008120033"; +const EIP_6492_SUFFIX = "0x6492649264926492649264926492649264926492649264926492649264926492"; +async function validateEIP6492Offchain(provider2, signer2, hash2, signature2) { + try { + const result = await provider2.call({ + data: concat([EIP_6492_OFFCHAIN_DEPLOY_CODE, AbiCoder.defaultAbiCoder().encode(["address", "bytes32", "bytes"], [signer2, hash2, signature2])]) + }); + return result === "0x01"; + } catch (err) { + return false; + } } -const Chi = (a2, b2, c2) => a2 & b2 ^ ~a2 & c2; -const Maj = (a2, b2, c2) => a2 & b2 ^ a2 & c2 ^ b2 & c2; -class HashMD2 extends Hash3 { - constructor(blockLen, outputLen, padOffset, isLE2) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE2; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); +var validateEIP6492 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + EIP_6492_OFFCHAIN_DEPLOY_CODE, + EIP_6492_SUFFIX, + validateEIP6492Offchain +}); +class OnChainReader { + constructor(provider2) { + this.provider = provider2; + this.isDeployedCache = /* @__PURE__ */ new Set(); } - update(data) { - exists(this); - const { view, buffer: buffer2, blockLen } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer2.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } + module(address) { + return new Contract(address, [...walletContracts.mainModuleUpgradable.abi, ...walletContracts.mainModule.abi, ...walletContracts.erc1271.abi], this.provider); + } + async isDeployed(wallet) { + if (this.isDeployedCache.has(wallet)) { + return true; } - this.length += data.length; - this.roundClean(); - return this; + const code2 = await this.provider.getCode(wallet).then((c2) => getBytes(c2)); + const isDeployed = code2.length !== 0; + if (isDeployed) { + this.isDeployedCache.add(wallet); + } + return isDeployed; } - digestInto(out) { - exists(this); - output(out, this); - this.finished = true; - const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; - let { pos } = this; - buffer2[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; + async implementation(wallet) { + const position = AbiCoder.defaultAbiCoder().encode(["address"], [wallet]); + const val = await this.provider.getStorage(wallet, position).then((c2) => getBytes(c2)); + if (val.length === 20) { + return getAddress(hexlify(val)); } - for (let i = pos; i < blockLen; i++) - buffer2[i] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE2); + if (val.length === 32) { + return AbiCoder.defaultAbiCoder().decode(["address"], val)[0]; + } + return void 0; } - digest() { - const { buffer: buffer2, outputLen } = this; - this.digestInto(buffer2); - const res = buffer2.slice(0, outputLen); - this.destroy(); - return res; + async imageHash(wallet) { + try { + const imageHash2 = await this.module(wallet).imageHash(); + return imageHash2; + } catch (_unused) { + } + return void 0; } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer2); - return to; + async nonce(wallet, space = 0) { + try { + const nonce = await this.module(wallet).readNonce(space); + return nonce; + } catch (e2) { + if (!await this.isDeployed(wallet)) { + return 0; + } + throw e2; + } + } + // We use the EIP-6492 validator contract to check the signature + // this means that if the wallet is not deployed, then the signature + // must be prefixed with a transaction that deploys the wallet + async isValidSignature(wallet, digest, signature2) { + return validateEIP6492Offchain(this.provider, wallet, digest, signature2); } } -const SHA256_K = /* @__PURE__ */ new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]); -const SHA256_IV = /* @__PURE__ */ new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -const SHA256_W = /* @__PURE__ */ new Uint32Array(64); -class SHA2563 extends HashMD2 { +var reader = /* @__PURE__ */ Object.freeze({ + __proto__: null, + OnChainReader +}); +function isWalletSignRequestMetadata(obj) { + return obj && obj.address && obj.digest && obj.chainId !== void 0 && obj.config; +} +var index$1$1 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + config: config$2, + signature: signature$2, + context, + signer, + EIP1271: validateEIP1271, + transaction, + reader, + EIP6492: validateEIP6492, + isWalletSignRequestMetadata +}); +const ALL_CODERS = [{ + config: ConfigCoder$1, + signature: SignatureCoder$1 +}, { + config: ConfigCoder, + signature: SignatureCoder +}]; +function coderFor(version2) { + const index2 = version2 - 1; + if (index2 < 0 || index2 >= ALL_CODERS.length) { + throw new Error(`No coder for version: ${version2}`); + } + return ALL_CODERS[index2]; +} +function genericCoderFor(version2) { + return coderFor(version2); +} +var index$6 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ALL_CODERS, + coderFor, + genericCoderFor +}); +const VERSION$1 = "2.0.9"; +const allVersions = [v1, v2]; +const core$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + VERSION: VERSION$1, + allVersions, + commons: index$1$1, + universal: index$6, + v1, + v2 +}, Symbol.toStringTag, { value: "Module" })); +function counterfactualVersion(address, firstImageHash, versions) { + for (let i = 0; i < versions.length; i++) { + if (index$1$1.context.addressOf(versions[i], firstImageHash) === address) { + return versions[i].version; + } + } + throw new Error("Could not find version for counterfactual address"); +} +var version$2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + counterfactualVersion +}); +class Migration_v1v2 { constructor() { - super(64, 32, 8, false); - this.A = SHA256_IV[0] | 0; - this.B = SHA256_IV[1] | 0; - this.C = SHA256_IV[2] | 0; - this.D = SHA256_IV[3] | 0; - this.E = SHA256_IV[4] | 0; - this.F = SHA256_IV[5] | 0; - this.G = SHA256_IV[6] | 0; - this.H = SHA256_IV[7] | 0; + this.version = 2; + this.configCoder = v2.config.ConfigCoder; + this.signatureCoder = v2.signature.SignatureCoder; } - get() { - const { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; - return [A2, B2, C2, D2, E2, F2, G2, H2]; + buildTransaction(address, contexts, newConfig) { + if (!v2.config.ConfigCoder.isWalletConfig(newConfig)) { + const v2Config = v2.config.toWalletConfig({ + threshold: newConfig.threshold, + members: newConfig.signers, + checkpoint: 0 + }); + return this.buildTransaction(address, contexts, v2Config); + } + const context2 = contexts[2]; + const contract = new Interface(walletContracts.mainModule.abi); + const updateBundle = v2.config.ConfigCoder.update.buildTransaction(address, newConfig, context2, "first"); + const tx = { + entrypoint: address, + nonce: index$1$1.transaction.encodeNonce(MIGRATION_NONCE_SPACE, 0), + transactions: [{ + to: address, + value: 0, + gasLimit: 0, + revertOnError: true, + delegateCall: false, + data: contract.encodeFunctionData(contract.getFunction("updateImplementation"), [context2.mainModuleUpgradable]) + }, ...updateBundle.transactions] + }; + return { + tx, + fromVersion: this.version - 1, + toVersion: this.version, + toConfig: newConfig + }; } - // prettier-ignore - set(A2, B2, C2, D2, E2, F2, G2, H2) { - this.A = A2 | 0; - this.B = B2 | 0; - this.C = C2 | 0; - this.D = D2 | 0; - this.E = E2 | 0; - this.F = F2 | 0; - this.G = G2 | 0; - this.H = H2 | 0; + decodeTransaction(tx, contexts) { + const address = tx.entrypoint; + if (tx.transactions.length < 2) { + throw new Error("Invalid transaction bundle size"); + } + if (!tx.nonce || index$1$1.transaction.encodeNonce(MIGRATION_NONCE_SPACE, 0) !== BigInt(tx.nonce)) { + throw new Error("Invalid transaction bundle nonce"); + } + if (tx.transactions[0].to !== address || tx.transactions[1].to !== address || tx.transactions[0].delegateCall || tx.transactions[1].delegateCall || !tx.transactions[0].revertOnError || !tx.transactions[1].revertOnError || tx.transactions[0].value && BigInt(tx.transactions[0].value) !== 0n || tx.transactions[1].value && BigInt(tx.transactions[1].value) !== 0n || tx.transactions[0].gasLimit && BigInt(tx.transactions[0].gasLimit) !== 0n || tx.transactions[1].gasLimit && BigInt(tx.transactions[1].gasLimit) !== 0n) { + throw new Error("Invalid transaction bundle format"); + } + const context2 = contexts[2]; + const contract = new Interface(walletContracts.mainModule.abi); + const data1 = hexlify(tx.transactions[0].data || new Uint8Array()); + const expectData1 = hexlify(contract.encodeFunctionData(contract.getFunction("updateImplementation"), [context2.mainModuleUpgradable])); + if (data1 !== expectData1) { + throw new Error("Invalid new implementation on transaction"); + } + const decoded2 = v2.config.ConfigCoder.update.decodeTransaction({ + entrypoint: address, + transactions: [tx.transactions[1]] + }); + if (decoded2.address !== address) { + throw new Error("Invalid transaction bundle address"); + } + return decoded2; } - process(view, offset2) { - for (let i = 0; i < 16; i++, offset2 += 4) - SHA256_W[i] = view.getUint32(offset2, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; +} +const MIGRATION_NONCE_SPACE = "0xa04263acf755e8bd19c0d7e20eea39a9ff3729eb"; +const v1v2 = new Migration_v1v2(); +var index$5 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + MIGRATION_NONCE_SPACE, + v1v2 +}); +function _extends$b() { + _extends$b = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends$b.apply(this, arguments); +} +function validateMigrations(migrations) { + for (const [version2, migration2] of Object.entries(migrations)) { + if (version2 !== String(migration2.version - 1)) { + throw new Error(`Migration with key ${version2} has version ${migration2.version}, expected version to be key + 1`); + } + } +} +class Migrator { + constructor(tracker2, migrations, contexts) { + this.tracker = tracker2; + this.migrations = migrations; + this.contexts = contexts; + validateMigrations(migrations); + } + lastMigration() { + let last; + for (const migration2 of Object.values(this.migrations)) { + if (last === void 0 || migration2.version > last.version) { + last = migration2; + } } - let { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E2, 6) ^ rotr(E2, 11) ^ rotr(E2, 25); - const T12 = H2 + sigma1 + Chi(E2, F2, G2) + SHA256_K[i] + SHA256_W[i] | 0; - const sigma0 = rotr(A2, 2) ^ rotr(A2, 13) ^ rotr(A2, 22); - const T22 = sigma0 + Maj(A2, B2, C2) | 0; - H2 = G2; - G2 = F2; - F2 = E2; - E2 = D2 + T12 | 0; - D2 = C2; - C2 = B2; - B2 = A2; - A2 = T12 + T22 | 0; + if (last === void 0) { + throw new Error("No migrations"); } - A2 = A2 + this.A | 0; - B2 = B2 + this.B | 0; - C2 = C2 + this.C | 0; - D2 = D2 + this.D | 0; - E2 = E2 + this.E | 0; - F2 = F2 + this.F | 0; - G2 = G2 + this.G | 0; - H2 = H2 + this.H | 0; - this.set(A2, B2, C2, D2, E2, F2, G2, H2); + return last; } - roundClean() { - SHA256_W.fill(0); + async getAllMigratePresignedTransaction(args) { + const { + address, + fromImageHash, + fromVersion, + chainId + } = args; + let fih = fromImageHash; + let fversion = fromVersion; + const versions = Object.values(this.contexts); + const migs = []; + for (let i = 1; i < versions.length; i++) { + const mig = await this.tracker.getMigration(address, fih, fversion, chainId); + if (!mig) return { + signedMigrations: migs, + missing: true, + lastImageHash: fih, + lastVersion: fversion + }; + migs.push(mig); + const migration2 = this.migrations[fversion]; + if (!migration2) { + throw new Error(`No migration found for version ${fversion}`); + } + const decoded = migration2.decodeTransaction(mig.tx, this.contexts); + if (decoded.address !== address) { + throw new Error(`Migration transaction address does not match expected address`); + } + fih = decoded.newImageHash; + fversion += 1; + } + return { + signedMigrations: migs, + missing: false, + lastImageHash: fih, + lastVersion: fversion + }; } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); + async signNextMigration(address, fromVersion, wallet, nextConfig) { + const migration2 = this.migrations[fromVersion]; + if (!migration2) { + return void 0; + } + const unsignedMigration = migration2.buildTransaction(address, this.contexts, nextConfig); + const signedBundle = await wallet.signTransactionBundle(unsignedMigration.tx); + return _extends$b({}, unsignedMigration, { + tx: signedBundle + }); } } -const sha256$1 = /* @__PURE__ */ wrapConstructor(() => new SHA2563()); -function sha256(value, to_) { - const bytes2 = sha256$1(isHex(value, { strict: false }) ? toBytes$1(value) : value); - return bytes2; +var migrator = /* @__PURE__ */ Object.freeze({ + __proto__: null, + Migrator +}); +const DefaultMigrations = { + 1: v1v2 +}; +var defaults = /* @__PURE__ */ Object.freeze({ + __proto__: null, + DefaultMigrations +}); +const migration$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + defaults, + migration: index$5, + migrator, + version: version$2 +}, Symbol.toStringTag, { value: "Module" })); +function _extends$a() { + _extends$a = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends$a.apply(this, arguments); } -function commitmentToVersionedHash(parameters) { - const { commitment, version: version2 = 1 } = parameters; - const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes"); - const versionedHash = sha256(commitment); - versionedHash.set([version2], 0); - return to === "bytes" ? versionedHash : bytesToHex$1(versionedHash); +const DEFAULT_GAS_LIMIT = 800000n; +const ProviderRelayerDefaults = { + waitPollRate: 1e3, + deltaBlocksLog: 12, + fromBlockLog: -1024 +}; +function isProviderRelayerOptions(obj) { + return typeof obj === "object" && obj.provider instanceof AbstractProvider; } -function commitmentsToVersionedHashes(parameters) { - const { commitments, version: version2 } = parameters; - const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes"); - const hashes = []; - for (const commitment of commitments) { - hashes.push(commitmentToVersionedHash({ - commitment, - to, - version: version2 +class ProviderRelayer { + constructor(options) { + this.provider = void 0; + this.waitPollRate = void 0; + this.deltaBlocksLog = void 0; + this.fromBlockLog = void 0; + const opts = _extends$a({}, ProviderRelayerDefaults, options); + this.provider = opts.provider; + this.waitPollRate = opts.waitPollRate; + this.deltaBlocksLog = opts.deltaBlocksLog; + this.fromBlockLog = opts.fromBlockLog; + } + async simulate(wallet, ...transactions2) { + var _this = this; + return (await Promise.all(transactions2.map(async function(tx) { + if (tx.gasLimit && BigInt(tx.gasLimit || 0) !== 0n) { + return tx.gasLimit; + } + if (tx.delegateCall) { + return DEFAULT_GAS_LIMIT; + } + if (tx.to === wallet && await _this.provider.getCode(wallet).then((code2) => getBytes(code2).length === 0)) { + return DEFAULT_GAS_LIMIT; + } + if (!_this.provider) { + throw new Error("signer.provider is not set, but is required"); + } + return _this.provider.estimateGas({ + from: wallet, + to: tx.to, + data: tx.data, + value: tx.value + }); + }))).map((gasLimit) => ({ + executed: true, + succeeded: true, + gasUsed: Number(gasLimit), + gasLimit: Number(gasLimit) })); } - return hashes; -} -const blobsPerTransaction = 6; -const bytesPerFieldElement = 32; -const fieldElementsPerBlob = 4096; -const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob; -const maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80). -1 - // zero byte (0x00) appended to each field element. -1 * fieldElementsPerBlob * blobsPerTransaction; -class BlobSizeTooLargeError extends BaseError$3 { - constructor({ maxSize, size: size2 }) { - super("Blob size is too large.", { - metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size2} bytes`], - name: "BlobSizeTooLargeError" + async getNonce(address, space, blockTag) { + if (!this.provider) { + throw new Error("provider is not set"); + } + if (await this.provider.getCode(address) === "0x") { + return 0; + } + if (space === void 0) { + space = 0; + } + const module2 = new Contract(address, walletContracts.mainModule.abi, this.provider); + const nonce = await module2.readNonce(space, { + blockTag }); + return index$1$1.transaction.encodeNonce(space, nonce); } -} -class EmptyBlobError extends BaseError$3 { - constructor() { - super("Blob data must not be empty.", { name: "EmptyBlobError" }); - } -} -function toBlobs(parameters) { - const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes"); - const data = typeof parameters.data === "string" ? hexToBytes$1(parameters.data) : parameters.data; - const size_ = size$5(data); - if (!size_) - throw new EmptyBlobError(); - if (size_ > maxBytesPerTransaction) - throw new BlobSizeTooLargeError({ - maxSize: maxBytesPerTransaction, - size: size_ - }); - const blobs = []; - let active = true; - let position = 0; - while (active) { - const blob = createCursor(new Uint8Array(bytesPerBlob)); - let size2 = 0; - while (size2 < fieldElementsPerBlob) { - const bytes2 = data.slice(position, position + (bytesPerFieldElement - 1)); - blob.pushByte(0); - blob.pushBytes(bytes2); - if (bytes2.length < 31) { - blob.pushByte(128); - active = false; - break; + async wait(metaTxnId, timeoutDuration, delay2 = this.waitPollRate, maxFails = 5) { + var _this2 = this; + if (typeof metaTxnId !== "string") { + metaTxnId = index$1$1.transaction.intendedTransactionID(metaTxnId); + } + let timedOut = false; + const retry = async function retry2(f2, errorMessage) { + let fails = 0; + while (!timedOut) { + try { + return await f2(); + } catch (error) { + fails++; + if (maxFails !== void 0 && fails >= maxFails) { + logger.error(`giving up after ${fails} failed attempts${errorMessage ? `: ${errorMessage}` : ""}`, error); + throw error; + } else { + logger.warn(`attempt #${fails} failed${errorMessage ? `: ${errorMessage}` : ""}`, error); + } + } + if (delay2 > 0) { + await new Promise((resolve) => setTimeout(resolve, delay2)); + } } - size2++; - position += 31; + throw new Error(`timed out after ${fails} failed attempts${errorMessage ? `: ${errorMessage}` : ""}`); + }; + const waitReceipt = async function waitReceipt2() { + let lastBlock = _this2.fromBlockLog; + if (lastBlock < 0) { + const block = await retry(() => _this2.provider.getBlockNumber(), "unable to get latest block number"); + lastBlock = block + lastBlock; + } + if (typeof metaTxnId !== "string") { + throw new Error("impossible"); + } + const normalMetaTxnId = metaTxnId.replace("0x", ""); + while (!timedOut) { + const block = await retry(() => _this2.provider.getBlockNumber(), "unable to get latest block number"); + const logs = await retry(() => _this2.provider.getLogs({ + fromBlock: Math.max(0, lastBlock - _this2.deltaBlocksLog), + toBlock: block, + // Nonce change event topic + topics: ["0x1f180c27086c7a39ea2a7b25239d1ab92348f07ca7bb59d1438fcf527568f881"] + }), `unable to get NonceChange logs for blocks ${Math.max(0, lastBlock - _this2.deltaBlocksLog)} to ${block}`); + lastBlock = block; + const txs = await Promise.all(logs.map((l2) => retry(() => _this2.provider.getTransactionReceipt(l2.transactionHash), `unable to get receipt for transaction ${l2.transactionHash}`))); + const found = txs.find((tx) => tx == null ? void 0 : tx.logs.find((l2) => l2.topics.length === 0 && l2.data.replace("0x", "") === normalMetaTxnId || l2.topics.length === 1 && // TxFailed event topic + l2.topics[0] === "0x3dbd1590ea96dd3253a91f24e64e3a502e1225d602a5731357bc12643070ccd7" && l2.data.length >= 64 && l2.data.replace("0x", "").startsWith(normalMetaTxnId))); + if (found) { + const response = await retry(() => _this2.provider.getTransaction(found.hash), `unable to get transaction ${found.hash}`); + if (!response) { + throw new Error(`Transaction response not found for ${metaTxnId}`); + } + const out = response; + out.receipt = found; + return out; + } + if (!timedOut) { + await new Promise((r2) => setTimeout(r2, delay2)); + } + } + throw new Error(`Timeout waiting for transaction receipt ${metaTxnId}`); + }; + if (timeoutDuration !== void 0) { + return Promise.race([waitReceipt(), new Promise((_, reject) => setTimeout(() => { + timedOut = true; + reject(`Timeout waiting for transaction receipt ${metaTxnId}`); + }, timeoutDuration))]); + } else { + return waitReceipt(); } - blobs.push(blob); } - return to === "bytes" ? blobs.map((x2) => x2.bytes) : blobs.map((x2) => bytesToHex$1(x2.bytes)); } -function toBlobSidecars(parameters) { - const { data, kzg, to } = parameters; - const blobs = parameters.blobs ?? toBlobs({ data, to }); - const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to }); - const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to }); - const sidecars = []; - for (let i = 0; i < blobs.length; i++) - sidecars.push({ - blob: blobs[i], - commitment: commitments[i], - proof: proofs[i] - }); - return sidecars; +function isLocalRelayerOptions(obj) { + return typeof obj === "object" && obj.signer instanceof AbstractSigner; } -function getTransactionType(transaction2) { - if (transaction2.type) - return transaction2.type; - if (typeof transaction2.authorizationList !== "undefined") - return "eip7702"; - if (typeof transaction2.blobs !== "undefined" || typeof transaction2.blobVersionedHashes !== "undefined" || typeof transaction2.maxFeePerBlobGas !== "undefined" || typeof transaction2.sidecars !== "undefined") - return "eip4844"; - if (typeof transaction2.maxFeePerGas !== "undefined" || typeof transaction2.maxPriorityFeePerGas !== "undefined") { - return "eip1559"; +class LocalRelayer extends ProviderRelayer { + constructor(options) { + super(options instanceof AbstractSigner ? { + provider: options.provider + } : _extends$a({}, options, { + provider: options.signer.provider + })); + this.signer = void 0; + this.txnOptions = void 0; + this.signer = options instanceof AbstractSigner ? options : options.signer; + if (!this.signer.provider) throw new Error("Signer must have a provider"); } - if (typeof transaction2.gasPrice !== "undefined") { - if (typeof transaction2.accessList !== "undefined") - return "eip2930"; - return "legacy"; + async getFeeOptions(_address, ..._transactions2) { + return { + options: [] + }; } - throw new InvalidSerializableTransactionError({ transaction: transaction2 }); -} -const defaultParameters = [ - "blobVersionedHashes", - "chainId", - "fees", - "gas", - "nonce", - "type" -]; -async function prepareTransactionRequest(client2, args) { - const { account: account_ = client2.account, blobs, chain, gas, kzg, nonce, nonceManager, parameters = defaultParameters, type } = args; - const account2 = account_ ? parseAccount(account_) : void 0; - const request = { ...args, ...account2 ? { from: account2 == null ? void 0 : account2.address } : {} }; - let block; - async function getBlock$1() { - if (block) - return block; - block = await getAction$1(client2, getBlock, "getBlock")({ blockTag: "latest" }); - return block; + async getFeeOptionsRaw(_entrypoint, _data6, _options4) { + return { + options: [] + }; } - let chainId; - async function getChainId2() { - if (chainId) - return chainId; - if (chain) - return chain.id; - if (typeof args.chainId !== "undefined") - return args.chainId; - const chainId_ = await getAction$1(client2, getChainId$1, "getChainId")({}); - chainId = chainId_; - return chainId; + async gasRefundOptions(address, ...transactions2) { + const { + options + } = await this.getFeeOptions(address, ...transactions2); + return options; } - if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) { - const commitments = blobsToCommitments({ blobs, kzg }); - if (parameters.includes("blobVersionedHashes")) { - const versionedHashes = commitmentsToVersionedHashes({ - commitments, - to: "hex" + setTransactionOptions(transactionRequest) { + this.txnOptions = transactionRequest; + } + async relay(signedTxs, quote, waitForReceipt = true) { + if (quote !== void 0) { + logger.warn(`LocalRelayer doesn't accept fee quotes`); + } + const data = index$1$1.transaction.encodeBundleExecData(signedTxs); + const responsePromise = this.signer.sendTransaction(_extends$a({ + to: signedTxs.entrypoint, + data + }, this.txnOptions, { + gasLimit: 9e6 + })); + if (waitForReceipt) { + const response = await responsePromise; + response.receipt = await response.wait(); + return response; + } else { + return responsePromise; + } + } +} +const WebRPCVersion$2 = "v1"; +const WebRPCSchemaVersion$2 = "v0.4.1"; +const WebRPCSchemaHash$2 = "1e27d0fd295aa5897878939595ef0c6adc54b1a3"; +let ETHTxnStatus = /* @__PURE__ */ function(ETHTxnStatus2) { + ETHTxnStatus2["UNKNOWN"] = "UNKNOWN"; + ETHTxnStatus2["DROPPED"] = "DROPPED"; + ETHTxnStatus2["QUEUED"] = "QUEUED"; + ETHTxnStatus2["SENT"] = "SENT"; + ETHTxnStatus2["SUCCEEDED"] = "SUCCEEDED"; + ETHTxnStatus2["PARTIALLY_FAILED"] = "PARTIALLY_FAILED"; + ETHTxnStatus2["FAILED"] = "FAILED"; + return ETHTxnStatus2; +}({}); +let TransferType = /* @__PURE__ */ function(TransferType2) { + TransferType2["SEND"] = "SEND"; + TransferType2["RECEIVE"] = "RECEIVE"; + TransferType2["BRIDGE_DEPOSIT"] = "BRIDGE_DEPOSIT"; + TransferType2["BRIDGE_WITHDRAW"] = "BRIDGE_WITHDRAW"; + TransferType2["BURN"] = "BURN"; + TransferType2["UNKNOWN"] = "UNKNOWN"; + return TransferType2; +}({}); +let FeeTokenType$1 = /* @__PURE__ */ function(FeeTokenType2) { + FeeTokenType2["UNKNOWN"] = "UNKNOWN"; + FeeTokenType2["ERC20_TOKEN"] = "ERC20_TOKEN"; + FeeTokenType2["ERC1155_TOKEN"] = "ERC1155_TOKEN"; + return FeeTokenType2; +}({}); +let SortOrder$1 = /* @__PURE__ */ function(SortOrder2) { + SortOrder2["DESC"] = "DESC"; + SortOrder2["ASC"] = "ASC"; + return SortOrder2; +}({}); +class Relayer { + constructor(hostname, fetch2) { + this.hostname = void 0; + this.fetch = void 0; + this.path = "/rpc/Relayer/"; + this.ping = (headers, signal) => { + return this.fetch(this.url("Ping"), createHTTPRequest$6({}, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.version = (headers, signal) => { + return this.fetch(this.url("Version"), createHTTPRequest$6({}, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + version: _data6.version + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.runtimeStatus = (headers, signal) => { + return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$6({}, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getSequenceContext = (headers, signal) => { + return this.fetch(this.url("GetSequenceContext"), createHTTPRequest$6({}, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + data: _data6.data + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getChainID = (headers, signal) => { + return this.fetch(this.url("GetChainID"), createHTTPRequest$6({}, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + chainID: _data6.chainID + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - request.blobVersionedHashes = versionedHashes; - } - if (parameters.includes("sidecars")) { - const proofs = blobsToProofs({ blobs, commitments, kzg }); - const sidecars = toBlobSidecars({ - blobs, - commitments, - proofs, - to: "hex" + }; + this.sendMetaTxn = (args, headers, signal) => { + return this.fetch(this.url("SendMetaTxn"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + status: _data6.status, + txnHash: _data6.txnHash + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - request.sidecars = sidecars; - } - } - if (parameters.includes("chainId")) - request.chainId = await getChainId2(); - if (parameters.includes("nonce") && typeof nonce === "undefined" && account2) { - if (nonceManager) { - const chainId2 = await getChainId2(); - request.nonce = await nonceManager.consume({ - address: account2.address, - chainId: chainId2, - client: client2 + }; + this.getMetaTxnNonce = (args, headers, signal) => { + return this.fetch(this.url("GetMetaTxnNonce"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + nonce: _data6.nonce + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - } else { - request.nonce = await getAction$1(client2, getTransactionCount, "getTransactionCount")({ - address: account2.address, - blockTag: "pending" + }; + this.getMetaTxnReceipt = (args, headers, signal) => { + return this.fetch(this.url("GetMetaTxnReceipt"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + receipt: _data6.receipt + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - } - } - if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") { - try { - request.type = getTransactionType(request); - } catch { - const block2 = await getBlock$1(); - request.type = typeof (block2 == null ? void 0 : block2.baseFeePerGas) === "bigint" ? "eip1559" : "legacy"; - } - } - if (parameters.includes("fees")) { - if (request.type !== "legacy" && request.type !== "eip2930") { - if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") { - const block2 = await getBlock$1(); - const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client2, { - block: block2, - chain, - request + }; + this.simulate = (args, headers, signal) => { + return this.fetch(this.url("Simulate"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + results: _data6.results + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` }); - if (typeof args.maxPriorityFeePerGas === "undefined" && args.maxFeePerGas && args.maxFeePerGas < maxPriorityFeePerGas) - throw new MaxFeePerGasTooLowError({ - maxPriorityFeePerGas - }); - request.maxPriorityFeePerGas = maxPriorityFeePerGas; - request.maxFeePerGas = maxFeePerGas; - } - } else { - if (typeof args.maxFeePerGas !== "undefined" || typeof args.maxPriorityFeePerGas !== "undefined") - throw new Eip1559FeesNotSupportedError(); - const block2 = await getBlock$1(); - const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client2, { - block: block2, - chain, - request, - type: "legacy" }); - request.gasPrice = gasPrice_; - } - } - if (parameters.includes("gas") && typeof gas === "undefined") - request.gas = await getAction$1(client2, estimateGas, "estimateGas")({ - ...request, - account: account2 ? { address: account2.address, type: "json-rpc" } : void 0 - }); - assertRequest(request); - delete request.parameters; - return request; -} -async function sendRawTransaction(client2, { serializedTransaction }) { - return client2.request({ - method: "eth_sendRawTransaction", - params: [serializedTransaction] - }, { retryCount: 0 }); -} -async function sendTransaction$1(client2, parameters) { - var _a2, _b2, _c2, _d2; - const { account: account_ = client2.account, chain = client2.chain, accessList, authorizationList, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, ...rest } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/sendTransaction" - }); - const account2 = parseAccount(account_); - try { - assertRequest(parameters); - const to = await (async () => { - if (parameters.to) - return parameters.to; - if (authorizationList && authorizationList.length > 0) - return await recoverAuthorizationAddress({ - authorization: authorizationList[0] - }).catch(() => { - throw new BaseError$3("`to` is required. Could not infer from `authorizationList`."); + }; + this.updateMetaTxnGasLimits = (args, headers, signal) => { + return this.fetch(this.url("UpdateMetaTxnGasLimits"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + payload: _data6.payload + }; }); - return void 0; - })(); - if (account2.type === "json-rpc") { - let chainId; - if (chain !== null) { - chainId = await getAction$1(client2, getChainId$1, "getChainId")({}); - assertCurrentChain({ - currentChainId: chainId, - chain + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` }); - } - const chainFormat = (_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.transactionRequest) == null ? void 0 : _c2.format; - const format2 = chainFormat || formatTransactionRequest; - const request = format2({ - // Pick out extra data that might exist on the chain's transaction request type. - ...extract(rest, { format: chainFormat }), - accessList, - authorizationList, - blobs, - chainId, - data, - from: account2.address, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to, - value }); - return await client2.request({ - method: "eth_sendTransaction", - params: [request] - }, { retryCount: 0 }); - } - if (account2.type === "local") { - const request = await getAction$1(client2, prepareTransactionRequest, "prepareTransactionRequest")({ - account: account2, - accessList, - authorizationList, - blobs, - chain, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - nonceManager: account2.nonceManager, - parameters: [...defaultParameters, "sidecars"], - value, - ...rest, - to + }; + this.feeTokens = (headers, signal) => { + return this.fetch(this.url("FeeTokens"), createHTTPRequest$6({}, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + isFeeRequired: _data6.isFeeRequired, + tokens: _data6.tokens + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - const serializer = (_d2 = chain == null ? void 0 : chain.serializers) == null ? void 0 : _d2.transaction; - const serializedTransaction = await account2.signTransaction(request, { - serializer + }; + this.feeOptions = (args, headers, signal) => { + return this.fetch(this.url("FeeOptions"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + options: _data6.options, + sponsored: _data6.sponsored, + quote: _data6.quote + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - return await getAction$1(client2, sendRawTransaction, "sendRawTransaction")({ - serializedTransaction + }; + this.getMetaTxnNetworkFeeOptions = (args, headers, signal) => { + return this.fetch(this.url("GetMetaTxnNetworkFeeOptions"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + options: _data6.options + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - } - if (account2.type === "smart") - throw new AccountTypeNotSupportedError({ - metaMessages: [ - "Consider using the `sendUserOperation` Action instead." - ], - docsPath: "/docs/actions/bundler/sendUserOperation", - type: "smart" + }; + this.getMetaTransactions = (args, headers, signal) => { + return this.fetch(this.url("GetMetaTransactions"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + page: _data6.page, + transactions: _data6.transactions + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - throw new AccountTypeNotSupportedError({ - docsPath: "/docs/actions/wallet/sendTransaction", - type: account2.type - }); - } catch (err) { - if (err instanceof AccountTypeNotSupportedError) - throw err; - throw getTransactionError(err, { - ...parameters, - account: account2, - chain: parameters.chain || void 0 - }); + }; + this.sentTransactions = (args, headers, signal) => { + return this.fetch(this.url("SentTransactions"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + page: _data6.page, + transactions: _data6.transactions + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.pendingTransactions = (args, headers, signal) => { + return this.fetch(this.url("PendingTransactions"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + page: _data6.page, + transactions: _data6.transactions + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getGasTank = (args, headers, signal) => { + return this.fetch(this.url("GetGasTank"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + gasTank: _data6.gasTank + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.addGasTank = (args, headers, signal) => { + return this.fetch(this.url("AddGasTank"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + status: _data6.status, + gasTank: _data6.gasTank + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.updateGasTank = (args, headers, signal) => { + return this.fetch(this.url("UpdateGasTank"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + status: _data6.status, + gasTank: _data6.gasTank + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getGasSponsor = (args, headers, signal) => { + return this.fetch(this.url("GetGasSponsor"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + gasSponsor: _data6.gasSponsor + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.addressGasSponsors = (args, headers, signal) => { + return this.fetch(this.url("AddressGasSponsors"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + page: _data6.page, + gasSponsors: _data6.gasSponsors + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.listGasSponsors = (args, headers, signal) => { + return this.fetch(this.url("ListGasSponsors"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + page: _data6.page, + gasSponsors: _data6.gasSponsors + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.addGasSponsor = (args, headers, signal) => { + return this.fetch(this.url("AddGasSponsor"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + status: _data6.status, + gasSponsor: _data6.gasSponsor + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.updateGasSponsor = (args, headers, signal) => { + return this.fetch(this.url("UpdateGasSponsor"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + status: _data6.status, + gasSponsor: _data6.gasSponsor + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.removeGasSponsor = (args, headers, signal) => { + return this.fetch(this.url("RemoveGasSponsor"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.reportGasSponsorUsage = (args, headers, signal) => { + return this.fetch(this.url("ReportGasSponsorUsage"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + gasSponsorUsage: _data6.gasSponsorUsage + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.nextGasTankBalanceAdjustmentNonce = (args, headers, signal) => { + return this.fetch(this.url("NextGasTankBalanceAdjustmentNonce"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + nonce: _data6.nonce + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.adjustGasTankBalance = (args, headers, signal) => { + return this.fetch(this.url("AdjustGasTankBalance"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + status: _data6.status, + adjustment: _data6.adjustment + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getGasTankBalanceAdjustment = (args, headers, signal) => { + return this.fetch(this.url("GetGasTankBalanceAdjustment"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + adjustment: _data6.adjustment + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.listGasTankBalanceAdjustments = (args, headers, signal) => { + return this.fetch(this.url("ListGasTankBalanceAdjustments"), createHTTPRequest$6(args, headers, signal)).then((res) => { + return buildResponse$6(res).then((_data6) => { + return { + page: _data6.page, + adjustments: _data6.adjustments + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$6.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.hostname = hostname; + this.fetch = (input2, init2) => fetch2(input2, init2); + } + url(name2) { + return this.hostname + this.path + name2; } } -function deployContract(walletClient, parameters) { - const { abi: abi2, args, bytecode, ...request } = parameters; - const calldata = encodeDeployData({ abi: abi2, args, bytecode }); - return sendTransaction$1(walletClient, { - ...request, - data: calldata - }); -} -const multicall3Abi = [ - { - inputs: [ - { - components: [ - { - name: "target", - type: "address" - }, - { - name: "allowFailure", - type: "bool" - }, - { - name: "callData", - type: "bytes" - } - ], - name: "calls", - type: "tuple[]" - } - ], - name: "aggregate3", - outputs: [ - { - components: [ - { - name: "success", - type: "bool" - }, - { - name: "returnData", - type: "bytes" - } - ], - name: "returnData", - type: "tuple[]" +const createHTTPRequest$6 = (body = {}, headers = {}, signal = null) => { + return { + method: "POST", + headers: _extends$a({}, headers, { + "Content-Type": "application/json" + }), + body: JSON.stringify(body || {}), + signal + }; +}; +const buildResponse$6 = (res) => { + return res.text().then((text2) => { + let data; + try { + data = JSON.parse(text2); + } catch (error) { + let message = ""; + if (error instanceof Error) { + message = error.message; } - ], - stateMutability: "view", - type: "function" + throw WebrpcBadResponseError$6.new({ + status: res.status, + cause: `JSON.parse(): ${message}: response text: ${text2}` + }); + } + if (!res.ok) { + const code2 = typeof data.code === "number" ? data.code : 0; + throw (webrpcErrorByCode$6[code2] || WebrpcError$6).new(data); + } + return data; + }); +}; +let WebrpcError$6 = class WebrpcError2 extends Error { + constructor(name2, code2, message, status, cause) { + super(message); + this.name = void 0; + this.code = void 0; + this.message = void 0; + this.status = void 0; + this.cause = void 0; + this.msg = void 0; + this.name = name2 || "WebrpcError"; + this.code = typeof code2 === "number" ? code2 : 0; + this.message = message || `endpoint error ${this.code}`; + this.msg = this.message; + this.status = typeof status === "number" ? status : 0; + this.cause = cause; + Object.setPrototypeOf(this, WebrpcError2.prototype); } -]; -const universalResolverErrors = [ - { - inputs: [], - name: "ResolverNotFound", - type: "error" - }, - { - inputs: [], - name: "ResolverWildcardNotSupported", - type: "error" - }, - { - inputs: [], - name: "ResolverNotContract", - type: "error" - }, - { - inputs: [ - { - name: "returnData", - type: "bytes" - } - ], - name: "ResolverError", - type: "error" - }, - { - inputs: [ - { - components: [ - { - name: "status", - type: "uint16" - }, - { - name: "message", - type: "string" - } - ], - name: "errors", - type: "tuple[]" - } - ], - name: "HttpError", - type: "error" + static new(payload) { + return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); } -]; -const universalResolverResolveAbi = [ - ...universalResolverErrors, - { - name: "resolve", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes" }, - { name: "data", type: "bytes" } - ], - outputs: [ - { name: "", type: "bytes" }, - { name: "address", type: "address" } - ] - }, - { - name: "resolve", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes" }, - { name: "data", type: "bytes" }, - { name: "gateways", type: "string[]" } - ], - outputs: [ - { name: "", type: "bytes" }, - { name: "address", type: "address" } - ] +}; +let WebrpcEndpointError$6 = class WebrpcEndpointError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcEndpointError2.prototype); } -]; -const universalResolverReverseAbi = [ - ...universalResolverErrors, - { - name: "reverse", - type: "function", - stateMutability: "view", - inputs: [{ type: "bytes", name: "reverseName" }], - outputs: [ - { type: "string", name: "resolvedName" }, - { type: "address", name: "resolvedAddress" }, - { type: "address", name: "reverseResolver" }, - { type: "address", name: "resolver" } - ] - }, - { - name: "reverse", - type: "function", - stateMutability: "view", - inputs: [ - { type: "bytes", name: "reverseName" }, - { type: "string[]", name: "gateways" } - ], - outputs: [ - { type: "string", name: "resolvedName" }, - { type: "address", name: "resolvedAddress" }, - { type: "address", name: "reverseResolver" }, - { type: "address", name: "resolver" } - ] +}; +let WebrpcRequestFailedError$6 = class WebrpcRequestFailedError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcRequestFailedError2.prototype); } -]; -const textResolverAbi = [ - { - name: "text", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes32" }, - { name: "key", type: "string" } - ], - outputs: [{ name: "", type: "string" }] +}; +let WebrpcBadRouteError$6 = class WebrpcBadRouteError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRouteError2.prototype); } -]; -const addressResolverAbi = [ - { - name: "addr", - type: "function", - stateMutability: "view", - inputs: [{ name: "name", type: "bytes32" }], - outputs: [{ name: "", type: "address" }] - }, - { - name: "addr", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes32" }, - { name: "coinType", type: "uint256" } - ], - outputs: [{ name: "", type: "bytes" }] +}; +let WebrpcBadMethodError$6 = class WebrpcBadMethodError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadMethodError2.prototype); } -]; -const universalSignatureValidatorAbi = [ - { - inputs: [ - { - name: "_signer", - type: "address" - }, - { - name: "_hash", - type: "bytes32" - }, - { - name: "_signature", - type: "bytes" - } - ], - stateMutability: "nonpayable", - type: "constructor" +}; +let WebrpcBadRequestError$6 = class WebrpcBadRequestError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRequestError2.prototype); } -]; -function bytesToBigInt(bytes2, opts = {}) { - if (typeof opts.size !== "undefined") - assertSize(bytes2, { size: opts.size }); - const hex2 = bytesToHex$1(bytes2, opts); - return hexToBigInt(hex2, opts); -} -function bytesToBool(bytes_, opts = {}) { - let bytes2 = bytes_; - if (typeof opts.size !== "undefined") { - assertSize(bytes2, { size: opts.size }); - bytes2 = trim(bytes2); +}; +let WebrpcBadResponseError$6 = class WebrpcBadResponseError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadResponseError2.prototype); } - if (bytes2.length > 1 || bytes2[0] > 1) - throw new InvalidBytesBooleanError(bytes2); - return Boolean(bytes2[0]); -} -function bytesToNumber(bytes2, opts = {}) { - if (typeof opts.size !== "undefined") - assertSize(bytes2, { size: opts.size }); - const hex2 = bytesToHex$1(bytes2, opts); - return hexToNumber$1(hex2, opts); -} -function bytesToString(bytes_, opts = {}) { - let bytes2 = bytes_; - if (typeof opts.size !== "undefined") { - assertSize(bytes2, { size: opts.size }); - bytes2 = trim(bytes2, { dir: "right" }); +}; +let WebrpcServerPanicError$6 = class WebrpcServerPanicError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcServerPanicError2.prototype); } - return new TextDecoder().decode(bytes2); -} -function decodeAbiParameters(params, data) { - const bytes2 = typeof data === "string" ? hexToBytes$1(data) : data; - const cursor = createCursor(bytes2); - if (size$5(bytes2) === 0 && params.length > 0) - throw new AbiDecodingZeroDataError(); - if (size$5(data) && size$5(data) < 32) - throw new AbiDecodingDataSizeTooSmallError({ - data: typeof data === "string" ? data : bytesToHex$1(data), - params, - size: size$5(data) - }); - let consumed = 0; - const values = []; - for (let i = 0; i < params.length; ++i) { - const param = params[i]; - cursor.setPosition(consumed); - const [data2, consumed_] = decodeParameter(cursor, param, { - staticPosition: 0 - }); - consumed += consumed_; - values.push(data2); +}; +let WebrpcInternalErrorError$6 = class WebrpcInternalErrorError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcInternalErrorError2.prototype); } - return values; -} -function decodeParameter(cursor, param, { staticPosition }) { - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return decodeArray(cursor, { ...param, type }, { length, staticPosition }); +}; +let WebrpcClientDisconnectedError$6 = class WebrpcClientDisconnectedError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcClientDisconnectedError2.prototype); } - if (param.type === "tuple") - return decodeTuple(cursor, param, { staticPosition }); - if (param.type === "address") - return decodeAddress(cursor); - if (param.type === "bool") - return decodeBool(cursor); - if (param.type.startsWith("bytes")) - return decodeBytes(cursor, param, { staticPosition }); - if (param.type.startsWith("uint") || param.type.startsWith("int")) - return decodeNumber(cursor, param); - if (param.type === "string") - return decodeString(cursor, { staticPosition }); - throw new InvalidAbiDecodingTypeError(param.type, { - docsPath: "/docs/contract/decodeAbiParameters" - }); -} -const sizeOfLength = 32; -const sizeOfOffset = 32; -function decodeAddress(cursor) { - const value = cursor.readBytes(32); - return [checksumAddress(bytesToHex$1(sliceBytes(value, -20))), 32]; -} -function decodeArray(cursor, param, { length, staticPosition }) { - if (!length) { - const offset2 = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset2; - const startOfData = start + sizeOfLength; - cursor.setPosition(start); - const length2 = bytesToNumber(cursor.readBytes(sizeOfLength)); - const dynamicChild = hasDynamicChild(param); - let consumed2 = 0; - const value2 = []; - for (let i = 0; i < length2; ++i) { - cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); - const [data, consumed_] = decodeParameter(cursor, param, { - staticPosition: startOfData +}; +let WebrpcStreamLostError$6 = class WebrpcStreamLostError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamLostError2.prototype); + } +}; +let WebrpcStreamFinishedError$6 = class WebrpcStreamFinishedError2 extends WebrpcError$6 { + constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamFinishedError2.prototype); + } +}; +let UnauthorizedError$5 = class UnauthorizedError2 extends WebrpcError$6 { + constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, UnauthorizedError2.prototype); + } +}; +let PermissionDeniedError$3 = class PermissionDeniedError2 extends WebrpcError$6 { + constructor(name2 = "PermissionDenied", code2 = 1001, message = "Permission denied", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, PermissionDeniedError2.prototype); + } +}; +let MethodNotFoundError$2 = class MethodNotFoundError extends WebrpcError$6 { + constructor(name2 = "MethodNotFound", code2 = 1003, message = "Method not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, MethodNotFoundError.prototype); + } +}; +let AbortedError$2 = class AbortedError2 extends WebrpcError$6 { + constructor(name2 = "Aborted", code2 = 1005, message = "Request aborted", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, AbortedError2.prototype); + } +}; +let InvalidArgumentError$4 = class InvalidArgumentError2 extends WebrpcError$6 { + constructor(name2 = "InvalidArgument", code2 = 2001, message = "Invalid argument", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, InvalidArgumentError2.prototype); + } +}; +let UnavailableError$2 = class UnavailableError2 extends WebrpcError$6 { + constructor(name2 = "Unavailable", code2 = 2002, message = "Unavailable resource", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, UnavailableError2.prototype); + } +}; +let QueryFailedError$4 = class QueryFailedError2 extends WebrpcError$6 { + constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, QueryFailedError2.prototype); + } +}; +let NotFoundError$5 = class NotFoundError2 extends WebrpcError$6 { + constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, NotFoundError2.prototype); + } +}; +let errors$2 = /* @__PURE__ */ function(errors2) { + errors2["WebrpcEndpoint"] = "WebrpcEndpoint"; + errors2["WebrpcRequestFailed"] = "WebrpcRequestFailed"; + errors2["WebrpcBadRoute"] = "WebrpcBadRoute"; + errors2["WebrpcBadMethod"] = "WebrpcBadMethod"; + errors2["WebrpcBadRequest"] = "WebrpcBadRequest"; + errors2["WebrpcBadResponse"] = "WebrpcBadResponse"; + errors2["WebrpcServerPanic"] = "WebrpcServerPanic"; + errors2["WebrpcInternalError"] = "WebrpcInternalError"; + errors2["WebrpcClientDisconnected"] = "WebrpcClientDisconnected"; + errors2["WebrpcStreamLost"] = "WebrpcStreamLost"; + errors2["WebrpcStreamFinished"] = "WebrpcStreamFinished"; + errors2["Unauthorized"] = "Unauthorized"; + errors2["PermissionDenied"] = "PermissionDenied"; + errors2["MethodNotFound"] = "MethodNotFound"; + errors2["Aborted"] = "Aborted"; + errors2["InvalidArgument"] = "InvalidArgument"; + errors2["Unavailable"] = "Unavailable"; + errors2["QueryFailed"] = "QueryFailed"; + errors2["NotFound"] = "NotFound"; + return errors2; +}({}); +const webrpcErrorByCode$6 = { + [0]: WebrpcEndpointError$6, + [-1]: WebrpcRequestFailedError$6, + [-2]: WebrpcBadRouteError$6, + [-3]: WebrpcBadMethodError$6, + [-4]: WebrpcBadRequestError$6, + [-5]: WebrpcBadResponseError$6, + [-6]: WebrpcServerPanicError$6, + [-7]: WebrpcInternalErrorError$6, + [-8]: WebrpcClientDisconnectedError$6, + [-9]: WebrpcStreamLostError$6, + [-10]: WebrpcStreamFinishedError$6, + [1e3]: UnauthorizedError$5, + [1001]: PermissionDeniedError$3, + [1003]: MethodNotFoundError$2, + [1005]: AbortedError$2, + [2001]: InvalidArgumentError$4, + [2002]: UnavailableError$2, + [2003]: QueryFailedError$4, + [3e3]: NotFoundError$5 +}; +var relayer_gen = /* @__PURE__ */ Object.freeze({ + __proto__: null, + WebRPCVersion: WebRPCVersion$2, + WebRPCSchemaVersion: WebRPCSchemaVersion$2, + WebRPCSchemaHash: WebRPCSchemaHash$2, + ETHTxnStatus, + TransferType, + FeeTokenType: FeeTokenType$1, + SortOrder: SortOrder$1, + Relayer, + WebrpcError: WebrpcError$6, + WebrpcEndpointError: WebrpcEndpointError$6, + WebrpcRequestFailedError: WebrpcRequestFailedError$6, + WebrpcBadRouteError: WebrpcBadRouteError$6, + WebrpcBadMethodError: WebrpcBadMethodError$6, + WebrpcBadRequestError: WebrpcBadRequestError$6, + WebrpcBadResponseError: WebrpcBadResponseError$6, + WebrpcServerPanicError: WebrpcServerPanicError$6, + WebrpcInternalErrorError: WebrpcInternalErrorError$6, + WebrpcClientDisconnectedError: WebrpcClientDisconnectedError$6, + WebrpcStreamLostError: WebrpcStreamLostError$6, + WebrpcStreamFinishedError: WebrpcStreamFinishedError$6, + UnauthorizedError: UnauthorizedError$5, + PermissionDeniedError: PermissionDeniedError$3, + MethodNotFoundError: MethodNotFoundError$2, + AbortedError: AbortedError$2, + InvalidArgumentError: InvalidArgumentError$4, + UnavailableError: UnavailableError$2, + QueryFailedError: QueryFailedError$4, + NotFoundError: NotFoundError$5, + errors: errors$2 +}); +const FINAL_STATUSES = [ETHTxnStatus.DROPPED, ETHTxnStatus.SUCCEEDED, ETHTxnStatus.PARTIALLY_FAILED, ETHTxnStatus.FAILED]; +const FAILED_STATUSES = [ETHTxnStatus.DROPPED, ETHTxnStatus.PARTIALLY_FAILED, ETHTxnStatus.FAILED]; +function isRpcRelayerOptions(obj) { + return obj.url !== void 0 && typeof obj.url === "string" && obj.provider !== void 0 && obj.provider instanceof AbstractProvider; +} +const fetch$5 = globalThis.fetch; +class RpcRelayer { + constructor(options) { + this.options = options; + this.service = void 0; + this.provider = void 0; + this._fetch = (input2, init2) => { + const headers = {}; + const { + jwtAuth, + projectAccessKey: projectAccessKey2 + } = this.options; + if (jwtAuth && jwtAuth.length > 0) { + headers["Authorization"] = `BEARER ${jwtAuth}`; + } + if (projectAccessKey2 && projectAccessKey2.length > 0) { + headers["X-Access-Key"] = projectAccessKey2; + } + init2.headers = _extends$a({}, init2.headers, headers); + return fetch$5(input2, init2); + }; + this.service = new Relayer(options.url, this._fetch); + if (options.provider instanceof AbstractProvider) { + this.provider = options.provider; + } else { + const { + jwtAuth, + projectAccessKey: projectAccessKey2 + } = this.options; + const fetchRequest = getFetchRequest(options.provider.url, projectAccessKey2, jwtAuth); + this.provider = new JsonRpcProvider$1(fetchRequest, void 0, { + staticNetwork: true }); - consumed2 += consumed_; - value2.push(data); } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; } - if (hasDynamicChild(param)) { - const offset2 = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset2; - const value2 = []; - for (let i = 0; i < length; ++i) { - cursor.setPosition(start + i * 32); - const [data] = decodeParameter(cursor, param, { - staticPosition: start - }); - value2.push(data); + async waitReceipt(metaTxnId, delay2 = 1e3, maxFails = 5, isCancelled) { + if (typeof metaTxnId !== "string") { + metaTxnId = index$1$1.transaction.intendedTransactionID(metaTxnId); } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; - } - let consumed = 0; - const value = []; - for (let i = 0; i < length; ++i) { - const [data, consumed_] = decodeParameter(cursor, param, { - staticPosition: staticPosition + consumed - }); - consumed += consumed_; - value.push(data); - } - return [value, consumed]; -} -function decodeBool(cursor) { - return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]; -} -function decodeBytes(cursor, param, { staticPosition }) { - const [_, size2] = param.type.split("bytes"); - if (!size2) { - const offset2 = bytesToNumber(cursor.readBytes(32)); - cursor.setPosition(staticPosition + offset2); - const length = bytesToNumber(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["0x", 32]; + logger.info(`[rpc-relayer/waitReceipt] waiting for ${metaTxnId}`); + let fails = 0; + while (isCancelled === void 0 || !isCancelled()) { + try { + const { + receipt + } = await this.service.getMetaTxnReceipt({ + metaTxID: metaTxnId + }); + if (receipt && receipt.txnReceipt && receipt.txnReceipt !== "null" && FINAL_STATUSES.includes(receipt.status)) { + return { + receipt + }; + } + } catch (e2) { + fails++; + if (fails === maxFails) { + throw e2; + } + } + if (isCancelled === void 0 || !isCancelled()) { + await new Promise((resolve) => setTimeout(resolve, delay2)); + } } - const data = cursor.readBytes(length); - cursor.setPosition(staticPosition + 32); - return [bytesToHex$1(data), 32]; + throw new Error(`Cancelled waiting for transaction receipt ${metaTxnId}`); } - const value = bytesToHex$1(cursor.readBytes(Number.parseInt(size2), 32)); - return [value, 32]; -} -function decodeNumber(cursor, param) { - const signed2 = param.type.startsWith("int"); - const size2 = Number.parseInt(param.type.split("int")[1] || "256"); - const value = cursor.readBytes(32); - return [ - size2 > 48 ? bytesToBigInt(value, { signed: signed2 }) : bytesToNumber(value, { signed: signed2 }), - 32 - ]; -} -function decodeTuple(cursor, param, { staticPosition }) { - const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name: name2 }) => !name2); - const value = hasUnnamedChild ? [] : {}; - let consumed = 0; - if (hasDynamicChild(param)) { - const offset2 = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset2; - for (let i = 0; i < param.components.length; ++i) { - const component = param.components[i]; - cursor.setPosition(start + consumed); - const [data, consumed_] = decodeParameter(cursor, component, { - staticPosition: start + async simulate(wallet, ...transactions2) { + const coder = AbiCoder.defaultAbiCoder(); + const encoded = coder.encode([index$1$1.transaction.MetaTransactionsType], [index$1$1.transaction.sequenceTxAbiEncode(transactions2)]); + return (await this.service.simulate({ + wallet, + transactions: encoded + })).results; + } + async getFeeOptions(address, ...transactions2) { + const feeTokens = await this.service.feeTokens(); + if (feeTokens.isFeeRequired) { + const symbols = feeTokens.tokens.map((token) => token.symbol).join(", "); + logger.info(`[rpc-relayer/getFeeOptions] relayer fees are required, accepted tokens are ${symbols}`); + const nonce = await this.getNonce(address); + if (!this.provider) { + logger.warn(`[rpc-relayer/getFeeOptions] provider not set, needed for stub signature`); + throw new Error("provider is not set"); + } + const { + options, + quote + } = await this.service.feeOptions({ + wallet: address, + to: address, + data: index$1$1.transaction.encodeBundleExecData({ + entrypoint: address, + transactions: transactions2, + nonce + }) }); - consumed += consumed_; - value[hasUnnamedChild ? i : component == null ? void 0 : component.name] = data; + logger.info(`[rpc-relayer/getFeeOptions] got refund options ${JSON.stringify(options, bigintReplacer)}`); + return { + options, + quote: { + _tag: "FeeQuote", + _quote: quote + } + }; + } else { + logger.info(`[rpc-relayer/getFeeOptions] relayer fees are not required`); + return { + options: [] + }; } - cursor.setPosition(staticPosition + 32); - return [value, 32]; } - for (let i = 0; i < param.components.length; ++i) { - const component = param.components[i]; - const [data, consumed_] = decodeParameter(cursor, component, { - staticPosition + async getFeeOptionsRaw(entrypoint, data, options) { + const { + options: feeOptions2, + quote + } = await this.service.feeOptions({ + wallet: entrypoint, + to: entrypoint, + data: hexlify(data), + simulate: options == null ? void 0 : options.simulate }); - value[hasUnnamedChild ? i : component == null ? void 0 : component.name] = data; - consumed += consumed_; + return { + options: feeOptions2, + quote: { + _tag: "FeeQuote", + _quote: quote + } + }; } - return [value, consumed]; -} -function decodeString(cursor, { staticPosition }) { - const offset2 = bytesToNumber(cursor.readBytes(32)); - const start = staticPosition + offset2; - cursor.setPosition(start); - const length = bytesToNumber(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["", 32]; + async gasRefundOptions(address, ...transactions2) { + const { + options + } = await this.getFeeOptions(address, ...transactions2); + return options; } - const data = cursor.readBytes(length, 32); - const value = bytesToString(trim(data)); - cursor.setPosition(staticPosition + 32); - return [value, 32]; -} -function hasDynamicChild(param) { - var _a2; - const { type } = param; - if (type === "string") - return true; - if (type === "bytes") - return true; - if (type.endsWith("[]")) - return true; - if (type === "tuple") - return (_a2 = param.components) == null ? void 0 : _a2.some(hasDynamicChild); - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] })) - return true; - return false; -} -const hash = (value) => keccak256(toBytes$1(value)); -function hashSignature(sig) { - return hash(sig); -} -const version$4 = "1.0.5"; -let BaseError$2 = class BaseError2 extends Error { - constructor(shortMessage, args = {}) { - var _a2; - const details = args.cause instanceof BaseError2 ? args.cause.details : ((_a2 = args.cause) == null ? void 0 : _a2.message) ? args.cause.message : args.details; - const docsPath2 = args.cause instanceof BaseError2 ? args.cause.docsPath || args.docsPath : args.docsPath; - const message = [ - shortMessage || "An error occurred.", - "", - ...args.metaMessages ? [...args.metaMessages, ""] : [], - ...docsPath2 ? [`Docs: https://abitype.dev${docsPath2}`] : [], - ...details ? [`Details: ${details}`] : [], - `Version: abitype@${version$4}` - ].join("\n"); - super(message); - Object.defineProperty(this, "details", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "docsPath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "metaMessages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "shortMessage", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiTypeError" + async getNonce(address, space) { + logger.info(`[rpc-relayer/getNonce] get nonce for wallet ${address} space: ${space}`); + const encodedNonce = space !== void 0 ? toHexString(BigInt(space)) : void 0; + const resp = await this.service.getMetaTxnNonce({ + walletContractAddress: address, + space: encodedNonce }); - if (args.cause) - this.cause = args.cause; - this.details = details; - this.docsPath = docsPath2; - this.metaMessages = args.metaMessages; - this.shortMessage = shortMessage; + const nonce = BigInt(resp.nonce); + const [decodedSpace, decodedNonce] = index$1$1.transaction.decodeNonce(nonce); + logger.info(`[rpc-relayer/getNonce] got next nonce for wallet ${address} ${decodedNonce} space: ${decodedSpace}`); + return nonce; } -}; -function execTyped(regex, string) { - const match = regex.exec(string); - return match == null ? void 0 : match.groups; -} -const bytesRegex$1 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; -const integerRegex$1 = /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; -const isTupleRegex = /^\(.+?\).*?$/; -const tupleRegex = /^tuple(?(\[(\d*)\])*)$/; -function formatAbiParameter(abiParameter) { - let type = abiParameter.type; - if (tupleRegex.test(abiParameter.type) && "components" in abiParameter) { - type = "("; - const length = abiParameter.components.length; - for (let i = 0; i < length; i++) { - const component = abiParameter.components[i]; - type += formatAbiParameter(component); - if (i < length - 1) - type += ", "; + async relay(signedTxs, quote, waitForReceipt = true) { + var _this = this; + logger.info(`[rpc-relayer/relay] relaying signed meta-transactions ${JSON.stringify(signedTxs, bigintReplacer)} with quote ${JSON.stringify(quote, bigintReplacer)}`); + let typecheckedQuote; + if (quote !== void 0) { + if (typeof quote._quote === "string") { + typecheckedQuote = quote._quote; + } else { + logger.warn("[rpc-relayer/relay] ignoring invalid fee quote"); + } } - const result = execTyped(tupleRegex, abiParameter.type); - type += `)${(result == null ? void 0 : result.array) ?? ""}`; - return formatAbiParameter({ - ...abiParameter, - type - }); - } - if ("indexed" in abiParameter && abiParameter.indexed) - type = `${type} indexed`; - if (abiParameter.name) - return `${type} ${abiParameter.name}`; - return type; -} -function formatAbiParameters(abiParameters) { - let params = ""; - const length = abiParameters.length; - for (let i = 0; i < length; i++) { - const abiParameter = abiParameters[i]; - params += formatAbiParameter(abiParameter); - if (i !== length - 1) - params += ", "; - } - return params; -} -function formatAbiItem(abiItem) { - if (abiItem.type === "function") - return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== "nonpayable" ? ` ${abiItem.stateMutability}` : ""}${abiItem.outputs.length ? ` returns (${formatAbiParameters(abiItem.outputs)})` : ""}`; - if (abiItem.type === "event") - return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; - if (abiItem.type === "error") - return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; - if (abiItem.type === "constructor") - return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === "payable" ? " payable" : ""}`; - if (abiItem.type === "fallback") - return "fallback()"; - return "receive() external payable"; -} -const errorSignatureRegex = /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; -function isErrorSignature(signature2) { - return errorSignatureRegex.test(signature2); -} -function execErrorSignature(signature2) { - return execTyped(errorSignatureRegex, signature2); -} -const eventSignatureRegex = /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; -function isEventSignature(signature2) { - return eventSignatureRegex.test(signature2); -} -function execEventSignature(signature2) { - return execTyped(eventSignatureRegex, signature2); -} -const functionSignatureRegex = /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/; -function isFunctionSignature(signature2) { - return functionSignatureRegex.test(signature2); -} -function execFunctionSignature(signature2) { - return execTyped(functionSignatureRegex, signature2); -} -const structSignatureRegex = /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/; -function isStructSignature(signature2) { - return structSignatureRegex.test(signature2); -} -function execStructSignature(signature2) { - return execTyped(structSignatureRegex, signature2); -} -const constructorSignatureRegex = /^constructor\((?.*?)\)(?:\s(?payable{1}))?$/; -function isConstructorSignature(signature2) { - return constructorSignatureRegex.test(signature2); -} -function execConstructorSignature(signature2) { - return execTyped(constructorSignatureRegex, signature2); -} -const fallbackSignatureRegex = /^fallback\(\) external(?:\s(?payable{1}))?$/; -function isFallbackSignature(signature2) { - return fallbackSignatureRegex.test(signature2); -} -const receiveSignatureRegex = /^receive\(\) external payable$/; -function isReceiveSignature(signature2) { - return receiveSignatureRegex.test(signature2); -} -const eventModifiers = /* @__PURE__ */ new Set(["indexed"]); -const functionModifiers = /* @__PURE__ */ new Set([ - "calldata", - "memory", - "storage" -]); -class UnknownTypeError extends BaseError$2 { - constructor({ type }) { - super("Unknown type.", { - metaMessages: [ - `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "UnknownTypeError" - }); - } -} -class UnknownSolidityTypeError extends BaseError$2 { - constructor({ type }) { - super("Unknown type.", { - metaMessages: [`Type "${type}" is not a valid ABI type.`] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "UnknownSolidityTypeError" - }); - } -} -class InvalidParameterError extends BaseError$2 { - constructor({ param }) { - super("Invalid ABI parameter.", { - details: param - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidParameterError" + if (!this.provider) { + logger.warn(`[rpc-relayer/relay] provider not set, failed relay`); + throw new Error("provider is not set"); + } + const data = index$1$1.transaction.encodeBundleExecData(signedTxs); + const metaTxn = await this.service.sendMetaTxn({ + call: { + walletAddress: signedTxs.intent.wallet, + contract: signedTxs.entrypoint, + input: data + }, + quote: typecheckedQuote }); + logger.info(`[rpc-relayer/relay] got relay result ${JSON.stringify(metaTxn, bigintReplacer)}`); + if (waitForReceipt) { + return this.wait(signedTxs.intent.id); + } else { + const response = { + hash: signedTxs.intent.id, + confirmations: 0, + from: signedTxs.intent.wallet, + wait: (_confirmations) => Promise.reject(new Error("impossible")) + }; + const wait2 = async function wait3(confirmations) { + var _waitResponse$receipt; + if (!_this.provider) { + throw new Error("cannot wait for receipt, relayer has no provider set"); + } + const waitResponse = await _this.wait(signedTxs.intent.id); + const transactionHash = (_waitResponse$receipt = waitResponse.receipt) == null ? void 0 : _waitResponse$receipt.transactionHash; + if (!transactionHash) { + throw new Error("cannot wait for receipt, unknown native transaction hash"); + } + Object.assign(response, waitResponse); + return _this.provider.waitForTransaction(transactionHash, confirmations); + }; + response.wait = wait2; + return response; + } } -} -class SolidityProtectedKeywordError extends BaseError$2 { - constructor({ param, name: name2 }) { - super("Invalid ABI parameter.", { - details: param, - metaMessages: [ - `"${name2}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "SolidityProtectedKeywordError" - }); + async wait(metaTxnId, timeout, delay2 = 1e3, maxFails = 5) { + var _this2 = this; + let timedOut = false; + const { + receipt + } = await (timeout !== void 0 ? Promise.race([this.waitReceipt(metaTxnId, delay2, maxFails, () => timedOut), new Promise((_, reject) => setTimeout(() => { + timedOut = true; + reject(`Timeout waiting for transaction receipt ${metaTxnId}`); + }, timeout))]) : this.waitReceipt(metaTxnId, delay2, maxFails)); + if (!receipt.txnReceipt || FAILED_STATUSES.includes(receipt.status)) { + throw new MetaTransactionResponseException(receipt); + } + const txReceipt = JSON.parse(receipt.txnReceipt); + return { + blockHash: txReceipt.blockHash, + blockNumber: Number(txReceipt.blockNumber), + confirmations: 1, + from: typeof metaTxnId === "string" ? void 0 : metaTxnId.intent.wallet, + hash: txReceipt.transactionHash, + raw: receipt.txnReceipt, + receipt: txReceipt, + // extended type which is Sequence-specific. Contains the decoded metaTxReceipt + wait: async function(confirmations) { + return _this2.provider.waitForTransaction(txReceipt.transactionHash, confirmations); + } + }; } } -class InvalidModifierError extends BaseError$2 { - constructor({ param, type, modifier }) { - super("Invalid ABI parameter.", { - details: param, - metaMessages: [ - `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidModifierError" - }); +class MetaTransactionResponseException { + constructor(receipt) { + this.receipt = receipt; } } -class InvalidFunctionModifierError extends BaseError$2 { - constructor({ param, type, modifier }) { - super("Invalid ABI parameter.", { - details: param, - metaMessages: [ - `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.`, - `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidFunctionModifierError" - }); - } +function isRelayer(cand) { + return typeof cand === "object" && typeof cand.simulate === "function" && typeof cand.getFeeOptions === "function" && typeof cand.gasRefundOptions === "function" && typeof cand.getNonce === "function" && typeof cand.relay === "function" && typeof cand.wait === "function"; } -class InvalidAbiTypeParameterError extends BaseError$2 { - constructor({ abiParameter }) { - super("Invalid ABI parameter.", { - details: JSON.stringify(abiParameter, null, 2), - metaMessages: ["ABI parameter type is invalid."] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidAbiTypeParameterError" - }); - } +const relayer$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + LocalRelayer, + ProviderRelayer, + ProviderRelayerDefaults, + RpcRelayer, + RpcRelayerProto: relayer_gen, + isLocalRelayerOptions, + isProviderRelayerOptions, + isRelayer, + isRpcRelayerOptions, + proto: relayer_gen +}, Symbol.toStringTag, { value: "Module" })); +function isSapientSigner(signer2) { + return signer2.getAddress !== void 0 && signer2.buildDeployTransaction !== void 0 && signer2.predecorateSignedTransactions !== void 0 && signer2.decorateTransactions !== void 0 && signer2.sign !== void 0 && signer2.notifyStatusChange !== void 0; } -class InvalidSignatureError extends BaseError$2 { - constructor({ signature: signature2, type }) { - super(`Invalid ${type} signature.`, { - details: signature2 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidSignatureError" - }); +class SignerWrapper { + constructor(signer2, eoa = true) { + this.signer = signer2; + this.eoa = eoa; } -} -class UnknownSignatureError extends BaseError$2 { - constructor({ signature: signature2 }) { - super("Unknown signature.", { - details: signature2 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "UnknownSignatureError" - }); + getAddress() { + return this.signer.getAddress(); } -} -class InvalidStructSignatureError extends BaseError$2 { - constructor({ signature: signature2 }) { - super("Invalid struct signature.", { - details: signature2, - metaMessages: ["No properties exist."] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidStructSignatureError" - }); + async buildDeployTransaction(_metadata) { + return; } -} -class CircularReferenceError extends BaseError$2 { - constructor({ type }) { - super("Circular reference detected.", { - metaMessages: [`Struct "${type}" is a circular reference.`] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "CircularReferenceError" - }); + async predecorateSignedTransactions(_metadata) { + return []; } -} -class InvalidParenthesisError extends BaseError$2 { - constructor({ current, depth }) { - super("Unbalanced parentheses.", { - metaMessages: [ - `"${current.trim()}" has too many ${depth > 0 ? "opening" : "closing"} parentheses.` - ], - details: `Depth "${depth}"` - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidParenthesisError" - }); + async decorateTransactions(bundle, _metadata) { + return bundle; + } + sign(message) { + return this.signer.signMessage(message); + } + notifyStatusChange(_i2, _s2, _m2) { + } + suffix() { + return new Uint8Array([2]); } } -function getParameterCacheKey(param, type) { - if (type) - return `${type}:${param}`; - return param; +var index$4 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + isSapientSigner, + SignerWrapper +}); +let SignerState = /* @__PURE__ */ function(SignerState2) { + SignerState2[SignerState2["INITIAL"] = 0] = "INITIAL"; + SignerState2[SignerState2["SIGNING"] = 1] = "SIGNING"; + SignerState2[SignerState2["SIGNED"] = 2] = "SIGNED"; + SignerState2[SignerState2["ERROR"] = 3] = "ERROR"; + return SignerState2; +}({}); +function isSignerStatusPending(status) { + return status === void 0 || status.state === SignerState.INITIAL || status.state === SignerState.SIGNING; } -const parameterCache = /* @__PURE__ */ new Map([ - // Unnamed - ["address", { type: "address" }], - ["bool", { type: "bool" }], - ["bytes", { type: "bytes" }], - ["bytes32", { type: "bytes32" }], - ["int", { type: "int256" }], - ["int256", { type: "int256" }], - ["string", { type: "string" }], - ["uint", { type: "uint256" }], - ["uint8", { type: "uint8" }], - ["uint16", { type: "uint16" }], - ["uint24", { type: "uint24" }], - ["uint32", { type: "uint32" }], - ["uint64", { type: "uint64" }], - ["uint96", { type: "uint96" }], - ["uint112", { type: "uint112" }], - ["uint160", { type: "uint160" }], - ["uint192", { type: "uint192" }], - ["uint256", { type: "uint256" }], - // Named - ["address owner", { type: "address", name: "owner" }], - ["address to", { type: "address", name: "to" }], - ["bool approved", { type: "bool", name: "approved" }], - ["bytes _data", { type: "bytes", name: "_data" }], - ["bytes data", { type: "bytes", name: "data" }], - ["bytes signature", { type: "bytes", name: "signature" }], - ["bytes32 hash", { type: "bytes32", name: "hash" }], - ["bytes32 r", { type: "bytes32", name: "r" }], - ["bytes32 root", { type: "bytes32", name: "root" }], - ["bytes32 s", { type: "bytes32", name: "s" }], - ["string name", { type: "string", name: "name" }], - ["string symbol", { type: "string", name: "symbol" }], - ["string tokenURI", { type: "string", name: "tokenURI" }], - ["uint tokenId", { type: "uint256", name: "tokenId" }], - ["uint8 v", { type: "uint8", name: "v" }], - ["uint256 balance", { type: "uint256", name: "balance" }], - ["uint256 tokenId", { type: "uint256", name: "tokenId" }], - ["uint256 value", { type: "uint256", name: "value" }], - // Indexed - [ - "event:address indexed from", - { type: "address", name: "from", indexed: true } - ], - ["event:address indexed to", { type: "address", name: "to", indexed: true }], - [ - "event:uint indexed tokenId", - { type: "uint256", name: "tokenId", indexed: true } - ], - [ - "event:uint256 indexed tokenId", - { type: "uint256", name: "tokenId", indexed: true } - ] -]); -function parseSignature(signature2, structs = {}) { - if (isFunctionSignature(signature2)) { - const match = execFunctionSignature(signature2); - if (!match) - throw new InvalidSignatureError({ signature: signature2, type: "function" }); - const inputParams = splitParameters(match.parameters); - const inputs = []; - const inputLength = inputParams.length; - for (let i = 0; i < inputLength; i++) { - inputs.push(parseAbiParameter(inputParams[i], { - modifiers: functionModifiers, - structs, - type: "function" - })); - } - const outputs = []; - if (match.returns) { - const outputParams = splitParameters(match.returns); - const outputLength = outputParams.length; - for (let i = 0; i < outputLength; i++) { - outputs.push(parseAbiParameter(outputParams[i], { - modifiers: functionModifiers, - structs, - type: "function" - })); - } - } - return { - name: match.name, - type: "function", - stateMutability: match.stateMutability ?? "nonpayable", - inputs, - outputs - }; +class Orchestrator { + constructor(signers, tag = Orchestrator.randomTag()) { + this.tag = tag; + this.observers = []; + this.signers = []; + this.count = 0; + this.setSigners(signers); } - if (isEventSignature(signature2)) { - const match = execEventSignature(signature2); - if (!match) - throw new InvalidSignatureError({ signature: signature2, type: "event" }); - const params = splitParameters(match.parameters); - const abiParameters = []; - const length = params.length; - for (let i = 0; i < length; i++) { - abiParameters.push(parseAbiParameter(params[i], { - modifiers: eventModifiers, - structs, - type: "event" - })); - } - return { name: match.name, type: "event", inputs: abiParameters }; + static randomTag() { + return `default-${hexlify(randomBytes(8)).slice(2)}`; } - if (isErrorSignature(signature2)) { - const match = execErrorSignature(signature2); - if (!match) - throw new InvalidSignatureError({ signature: signature2, type: "error" }); - const params = splitParameters(match.parameters); - const abiParameters = []; - const length = params.length; - for (let i = 0; i < length; i++) { - abiParameters.push(parseAbiParameter(params[i], { structs, type: "error" })); - } - return { name: match.name, type: "error", inputs: abiParameters }; + pullId() { + return `${this.tag}-${this.count++}`; } - if (isConstructorSignature(signature2)) { - const match = execConstructorSignature(signature2); - if (!match) - throw new InvalidSignatureError({ signature: signature2, type: "constructor" }); - const params = splitParameters(match.parameters); - const abiParameters = []; - const length = params.length; - for (let i = 0; i < length; i++) { - abiParameters.push(parseAbiParameter(params[i], { structs, type: "constructor" })); - } - return { - type: "constructor", - stateMutability: match.stateMutability ?? "nonpayable", - inputs: abiParameters - }; + setSigners(signers) { + this.signers = signers.map((s2) => isSapientSigner(s2) ? s2 : new SignerWrapper(s2)); } - if (isFallbackSignature(signature2)) - return { type: "fallback" }; - if (isReceiveSignature(signature2)) - return { - type: "receive", - stateMutability: "payable" + async getSigners() { + return Promise.all(this.signers.map(async function(s2) { + return s2.getAddress(); + })); + } + subscribe(observer) { + this.observers.push(observer); + return () => { + this.observers = this.observers.filter((o2) => o2 !== observer); }; - throw new UnknownSignatureError({ signature: signature2 }); -} -const abiParameterWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; -const abiParameterWithTupleRegex = /^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; -const dynamicIntegerRegex = /^u?int$/; -function parseAbiParameter(param, options) { - var _a2, _b2; - const parameterCacheKey = getParameterCacheKey(param, options == null ? void 0 : options.type); - if (parameterCache.has(parameterCacheKey)) - return parameterCache.get(parameterCacheKey); - const isTuple = isTupleRegex.test(param); - const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param); - if (!match) - throw new InvalidParameterError({ param }); - if (match.name && isSolidityKeyword(match.name)) - throw new SolidityProtectedKeywordError({ param, name: match.name }); - const name2 = match.name ? { name: match.name } : {}; - const indexed = match.modifier === "indexed" ? { indexed: true } : {}; - const structs = (options == null ? void 0 : options.structs) ?? {}; - let type; - let components = {}; - if (isTuple) { - type = "tuple"; - const params = splitParameters(match.type); - const components_ = []; - const length = params.length; - for (let i = 0; i < length; i++) { - components_.push(parseAbiParameter(params[i], { structs })); + } + async notifyObservers(id2, status, metadata2) { + await Promise.all([...this.signers.map(async function(signer2) { + return signer2.notifyStatusChange(id2, status, metadata2); + }), ...this.observers.map(async function(observer) { + return observer(status, metadata2); + })]); + } + async buildDeployTransaction(metadata2) { + let bundle; + for (const signer2 of this.signers) { + const newBundle = await signer2.buildDeployTransaction(metadata2); + if (bundle === void 0) { + bundle = newBundle; + } else if (newBundle != null && newBundle.transactions) { + bundle.transactions = newBundle.transactions.concat(bundle.transactions); + } } - components = { components: components_ }; - } else if (match.type in structs) { - type = "tuple"; - components = { components: structs[match.type] }; - } else if (dynamicIntegerRegex.test(match.type)) { - type = `${match.type}256`; - } else { - type = match.type; - if (!((options == null ? void 0 : options.type) === "struct") && !isSolidityType(type)) - throw new UnknownSolidityTypeError({ type }); + return bundle; } - if (match.modifier) { - if (!((_b2 = (_a2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _a2.has) == null ? void 0 : _b2.call(_a2, match.modifier))) - throw new InvalidModifierError({ - param, - type: options == null ? void 0 : options.type, - modifier: match.modifier - }); - if (functionModifiers.has(match.modifier) && !isValidDataLocation(type, !!match.array)) - throw new InvalidFunctionModifierError({ - param, - type: options == null ? void 0 : options.type, - modifier: match.modifier - }); + async predecorateSignedTransactions(metadata2) { + const output2 = []; + for (const signer2 of this.signers) { + output2.push(...await signer2.predecorateSignedTransactions(metadata2 != null ? metadata2 : {})); + } + return output2; } - const abiParameter = { - type: `${type}${match.array ?? ""}`, - ...name2, - ...indexed, - ...components - }; - parameterCache.set(parameterCacheKey, abiParameter); - return abiParameter; -} -function splitParameters(params, result = [], current = "", depth = 0) { - const length = params.trim().length; - for (let i = 0; i < length; i++) { - const char = params[i]; - const tail = params.slice(i + 1); - switch (char) { - case ",": - return depth === 0 ? splitParameters(tail, [...result, current.trim()]) : splitParameters(tail, result, `${current}${char}`, depth); - case "(": - return splitParameters(tail, result, `${current}${char}`, depth + 1); - case ")": - return splitParameters(tail, result, `${current}${char}`, depth - 1); - default: - return splitParameters(tail, result, `${current}${char}`, depth); + async decorateTransactions(bundle, metadata2) { + for (const signer2 of this.signers) { + bundle = await signer2.decorateTransactions(bundle, metadata2 != null ? metadata2 : {}); } + return bundle; + } + signMessage(args) { + var _this = this; + const id2 = this.pullId(); + return new Promise(async function(resolve) { + const { + message, + metadata: metadata2, + callback, + candidates + } = args; + const status = { + ended: false, + message, + signers: {} + }; + let lastMetadata = metadata2 != null ? metadata2 : {}; + const onNewMetadata = (newMetadata) => { + lastMetadata = newMetadata; + _this.notifyObservers(id2, status, lastMetadata); + }; + const onStatusUpdate = () => { + try { + _this.notifyObservers(id2, status, lastMetadata); + const pending = Object.entries(status.signers).filter(([_, s2]) => isSignerStatusPending(s2)); + if (callback && callback(status, onNewMetadata) || pending.length === 0) { + status.ended = true; + resolve(status); + _this.notifyObservers(id2, status, lastMetadata); + return; + } + } catch (e2) { + console.error("Error while notifying observers", e2); + } + }; + let signers = _this.signers; + if (candidates) { + const addresses = await Promise.all(_this.signers.map(async function(s2) { + return s2.getAddress(); + })); + signers = _this.signers.filter((_, i) => candidates.includes(addresses[i])); + } + const accepted = await Promise.allSettled(signers.map(async function(s2) { + const saddr = await s2.getAddress(); + status.signers[saddr] = { + state: SignerState.SIGNING, + request: s2.sign(message, metadata2 != null ? metadata2 : {}).then((signature2) => { + const suffix = s2.suffix(); + status.signers[saddr] = { + state: SignerState.SIGNED, + signature: signature2, + suffix + }; + onStatusUpdate(); + return signature2; + }).catch((error) => { + status.signers[saddr] = { + state: SignerState.ERROR, + error + }; + onStatusUpdate(); + throw error; + }) + }; + })); + for (let i = 0; i < accepted.length; i++) { + const signer2 = _this.signers[i]; + const promise = accepted[i]; + if (promise.status === "rejected") { + const address = await signer2.getAddress(); + console.warn(`signer ${address} rejected the request: ${promise.reason}`); + status.signers[address] = { + state: SignerState.ERROR, + error: new Error(`signer ${address} rejected the request: ${promise.reason}`) + }; + } + } + onStatusUpdate(); + }); } - if (current === "") - return result; - if (depth !== 0) - throw new InvalidParenthesisError({ current, depth }); - result.push(current.trim()); - return result; } -function isSolidityType(type) { - return type === "address" || type === "bool" || type === "function" || type === "string" || bytesRegex$1.test(type) || integerRegex$1.test(type); -} -const protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/; -function isSolidityKeyword(name2) { - return name2 === "address" || name2 === "bool" || name2 === "function" || name2 === "string" || name2 === "tuple" || bytesRegex$1.test(name2) || integerRegex$1.test(name2) || protectedKeywordsRegex.test(name2); +const signhub$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Orchestrator, + SignerState, + isSignerStatusPending, + signers: index$4 +}, Symbol.toStringTag, { value: "Module" })); +function _extends$9() { + _extends$9 = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends$9.apply(this, arguments); } -function isValidDataLocation(type, isArray2) { - return isArray2 || type === "bytes" || type === "string" || type === "tuple"; +async function resolveArrayProperties$1(object2) { + if (Array.isArray(object2)) { + return Promise.all(object2.map((o2) => resolveProperties$1(o2))); + } + return resolveProperties$1(object2); } -function parseStructs(signatures) { - const shallowStructs = {}; - const signaturesLength = signatures.length; - for (let i = 0; i < signaturesLength; i++) { - const signature2 = signatures[i]; - if (!isStructSignature(signature2)) - continue; - const match = execStructSignature(signature2); - if (!match) - throw new InvalidSignatureError({ signature: signature2, type: "struct" }); - const properties = match.properties.split(";"); - const components = []; - const propertiesLength = properties.length; - for (let k2 = 0; k2 < propertiesLength; k2++) { - const property = properties[k2]; - const trimmed = property.trim(); - if (!trimmed) - continue; - const abiParameter = parseAbiParameter(trimmed, { - type: "struct" +const statusToSignatureParts = (status) => { + const parts = /* @__PURE__ */ new Map(); + for (const signer2 of Object.keys(status.signers)) { + const value = status.signers[signer2]; + if (value.state === SignerState.SIGNED) { + const suffix = getBytes(value.suffix); + const suffixed = solidityPacked(["bytes", "bytes"], [value.signature, suffix]); + parts.set(signer2, { + signature: suffixed, + isDynamic: suffix.length !== 1 || suffix[0] !== 2 }); - components.push(abiParameter); } - if (!components.length) - throw new InvalidStructSignatureError({ signature: signature2 }); - shallowStructs[match.name] = components; - } - const resolvedStructs = {}; - const entries = Object.entries(shallowStructs); - const entriesLength = entries.length; - for (let i = 0; i < entriesLength; i++) { - const [name2, parameters] = entries[i]; - resolvedStructs[name2] = resolveStructs(parameters, shallowStructs); } - return resolvedStructs; -} -const typeWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/; -function resolveStructs(abiParameters, structs, ancestors = /* @__PURE__ */ new Set()) { - const components = []; - const length = abiParameters.length; - for (let i = 0; i < length; i++) { - const abiParameter = abiParameters[i]; - const isTuple = isTupleRegex.test(abiParameter.type); - if (isTuple) - components.push(abiParameter); - else { - const match = execTyped(typeWithoutTupleRegex, abiParameter.type); - if (!(match == null ? void 0 : match.type)) - throw new InvalidAbiTypeParameterError({ abiParameter }); - const { array, type } = match; - if (type in structs) { - if (ancestors.has(type)) - throw new CircularReferenceError({ type }); - components.push({ - ...abiParameter, - type: `tuple${array ?? ""}`, - components: resolveStructs(structs[type] ?? [], structs, /* @__PURE__ */ new Set([...ancestors, type])) - }); - } else { - if (isSolidityType(type)) - components.push(abiParameter); - else - throw new UnknownTypeError({ type }); - } + return parts; +}; +class Wallet extends AbstractSigner { + constructor(options) { + var _options$provider; + if (BigInt(options.chainId) === 0n && !options.coders.signature.supportsNoChainId) { + throw new Error(`Sequence version ${options.config.version} doesn't support chainId 0`); } + super((_options$provider = options.provider) != null ? _options$provider : null); + this.context = void 0; + this.config = void 0; + this.address = void 0; + this.chainId = void 0; + this.relayer = void 0; + this.coders = void 0; + this.orchestrator = void 0; + this._reader = void 0; + this.context = options.context; + this.config = options.config; + this.orchestrator = options.orchestrator; + this.coders = options.coders; + this.address = options.address; + this.chainId = options.chainId; + this.relayer = options.relayer; + this._reader = options.reader; } - return components; -} -function parseAbi(signatures) { - const structs = parseStructs(signatures); - const abi2 = []; - const length = signatures.length; - for (let i = 0; i < length; i++) { - const signature2 = signatures[i]; - if (isStructSignature(signature2)) - continue; - abi2.push(parseSignature(signature2, structs)); + static newWallet(options) { + const address = index$1$1.context.addressOf(options.context, options.coders.config.imageHashOf(options.config)); + return new Wallet(_extends$9({}, options, { + address + })); } - return abi2; -} -function normalizeSignature(signature2) { - let active = true; - let current = ""; - let level = 0; - let result = ""; - let valid = false; - for (let i = 0; i < signature2.length; i++) { - const char = signature2[i]; - if (["(", ")", ","].includes(char)) - active = true; - if (char === "(") - level++; - if (char === ")") - level--; - if (!active) - continue; - if (level === 0) { - if (char === " " && ["event", "function", ""].includes(result)) - result = ""; - else { - result += char; - if (char === ")") { - valid = true; - break; - } - } - continue; + reader() { + if (this._reader) return this._reader; + if (!this.provider) throw new Error("Wallet status provider requires a provider"); + return new index$1$1.reader.OnChainReader(this.provider); + } + setConfig(config2) { + this.config = config2; + } + setOrchestrator(orchestrator) { + this.orchestrator = orchestrator; + } + setAddress(address) { + this.address = address; + } + getSigners() { + return this.orchestrator.getSigners(); + } + async getAddress() { + return this.address; + } + async decorateTransactions(bundle) { + const decorated = await this.orchestrator.decorateTransactions(bundle); + if (await this.reader().isDeployed(this.address)) { + return decorated; } - if (char === " ") { - if (signature2[i - 1] !== "," && current !== "," && current !== ",(") { - current = ""; - active = false; - } - continue; + const transactions2 = [{ + to: decorated.entrypoint, + data: index$1$1.transaction.encodeBundleExecData(decorated), + revertOnError: true + }]; + const deployTx = await this.buildDeployTransaction(); + if (deployTx) { + transactions2.unshift(...deployTx.transactions); } - result += char; - current += char; + return { + entrypoint: this.context.guestModule, + chainId: this.chainId, + intent: decorated.intent, + transactions: transactions2 + }; } - if (!valid) - throw new BaseError$3("Unable to normalize signature."); - return result; -} -const toSignature = (def) => { - const def_ = (() => { - if (typeof def === "string") - return def; - return formatAbiItem(def); - })(); - return normalizeSignature(def_); -}; -function toSignatureHash(fn) { - return hashSignature(toSignature(fn)); -} -const toEventSelector = toSignatureHash; -const toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4); -function getAbiItem(parameters) { - const { abi: abi2, args = [], name: name2 } = parameters; - const isSelector = isHex(name2, { strict: false }); - const abiItems = abi2.filter((abiItem) => { - if (isSelector) { - if (abiItem.type === "function") - return toFunctionSelector(abiItem) === name2; - if (abiItem.type === "event") - return toEventSelector(abiItem) === name2; - return false; + async buildDeployTransaction(metadata2) { + if (metadata2 != null && metadata2.ignoreDeployed && await this.reader().isDeployed(this.address)) { + return; } - return "name" in abiItem && abiItem.name === name2; - }); - if (abiItems.length === 0) - return void 0; - if (abiItems.length === 1) - return abiItems[0]; - let matchedAbiItem = void 0; - for (const abiItem of abiItems) { - if (!("inputs" in abiItem)) - continue; - if (!args || args.length === 0) { - if (!abiItem.inputs || abiItem.inputs.length === 0) - return abiItem; - continue; + const imageHash2 = this.coders.config.imageHashOf(this.config); + if (index$1$1.context.addressOf(this.context, imageHash2) !== this.address) { + throw new Error(`First address of config ${imageHash2} doesn't match wallet address ${this.address}`); } - if (!abiItem.inputs) - continue; - if (abiItem.inputs.length === 0) - continue; - if (abiItem.inputs.length !== args.length) - continue; - const matched = args.every((arg, index2) => { - const abiParameter = "inputs" in abiItem && abiItem.inputs[index2]; - if (!abiParameter) - return false; - return isArgOfType(arg, abiParameter); - }); - if (matched) { - if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { - const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args); - if (ambiguousTypes) - throw new AbiItemAmbiguityError({ - abiItem, - type: ambiguousTypes[0] - }, { - abiItem: matchedAbiItem, - type: ambiguousTypes[1] - }); + const bundle = Wallet.buildDeployTransaction(this.context, imageHash2); + if (metadata2 != null && metadata2.includeChildren) { + const childBundle = await this.orchestrator.buildDeployTransaction(metadata2); + if (childBundle) { + bundle.transactions = childBundle.transactions.concat(bundle.transactions); } - matchedAbiItem = abiItem; } + return bundle; } - if (matchedAbiItem) - return matchedAbiItem; - return abiItems[0]; -} -function isArgOfType(arg, abiParameter) { - const argType = typeof arg; - const abiParameterType = abiParameter.type; - switch (abiParameterType) { - case "address": - return isAddress(arg, { strict: false }); - case "bool": - return argType === "boolean"; - case "function": - return argType === "string"; - case "string": - return argType === "string"; - default: { - if (abiParameterType === "tuple" && "components" in abiParameter) - return Object.values(abiParameter.components).every((component, index2) => { - return isArgOfType(Object.values(arg)[index2], component); - }); - if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) - return argType === "number" || argType === "bigint"; - if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) - return argType === "string" || arg instanceof Uint8Array; - if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { - return Array.isArray(arg) && arg.every((x2) => isArgOfType(x2, { - ...abiParameter, - // Pop off `[]` or `[M]` from end of type - type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") - })); - } - return false; + async deploy(metadata2) { + const deployTx = await this.buildDeployTransaction(metadata2); + if (deployTx === void 0) { + return; } - } -} -function getAmbiguousTypes(sourceParameters, targetParameters, args) { - for (const parameterIndex in sourceParameters) { - const sourceParameter = sourceParameters[parameterIndex]; - const targetParameter = targetParameters[parameterIndex]; - if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) - return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]); - const types2 = [sourceParameter.type, targetParameter.type]; - const ambiguous = (() => { - if (types2.includes("address") && types2.includes("bytes20")) - return true; - if (types2.includes("address") && types2.includes("string")) - return isAddress(args[parameterIndex], { strict: false }); - if (types2.includes("address") && types2.includes("bytes")) - return isAddress(args[parameterIndex], { strict: false }); - return false; - })(); - if (ambiguous) - return types2; - } - return; -} -const docsPath$3 = "/docs/contract/decodeFunctionResult"; -function decodeFunctionResult(parameters) { - const { abi: abi2, args, functionName, data } = parameters; - let abiItem = abi2[0]; - if (functionName) { - const item2 = getAbiItem({ abi: abi2, args, name: functionName }); - if (!item2) - throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath$3 }); - abiItem = item2; - } - if (abiItem.type !== "function") - throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath$3 }); - if (!abiItem.outputs) - throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath$3 }); - const values = decodeAbiParameters(abiItem.outputs, data); - if (values && values.length > 1) - return values; - if (values && values.length === 1) - return values[0]; - return void 0; -} -const docsPath$2 = "/docs/contract/encodeFunctionData"; -function prepareEncodeFunctionData(parameters) { - const { abi: abi2, args, functionName } = parameters; - let abiItem = abi2[0]; - if (functionName) { - const item2 = getAbiItem({ - abi: abi2, - args, - name: functionName - }); - if (!item2) - throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath$2 }); - abiItem = item2; - } - if (abiItem.type !== "function") - throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath$2 }); - return { - abi: [abiItem], - functionName: toFunctionSelector(formatAbiItem$1(abiItem)) - }; -} -function encodeFunctionData(parameters) { - const { args } = parameters; - const { abi: abi2, functionName } = (() => { - var _a2; - if (parameters.abi.length === 1 && ((_a2 = parameters.functionName) == null ? void 0 : _a2.startsWith("0x"))) - return parameters; - return prepareEncodeFunctionData(parameters); - })(); - const abiItem = abi2[0]; - const signature2 = functionName; - const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : void 0; - return concatHex([signature2, data ?? "0x"]); -} -function getChainContractAddress({ blockNumber, chain, contract: name2 }) { - var _a2; - const contract = (_a2 = chain == null ? void 0 : chain.contracts) == null ? void 0 : _a2[name2]; - if (!contract) - throw new ChainDoesNotSupportContract({ - chain, - contract: { name: name2 } - }); - if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber) - throw new ChainDoesNotSupportContract({ - blockNumber, - chain, - contract: { - name: name2, - blockCreated: contract.blockCreated + if (!this.relayer) throw new Error("Wallet deploy requires a relayer"); + return this.relayer.relay(_extends$9({}, deployTx, { + chainId: this.chainId, + intent: { + id: hexlify(randomBytes(32)), + wallet: this.address } - }); - return contract.address; -} -const panicReasons = { - 1: "An `assert` condition failed.", - 17: "Arithmetic operation resulted in underflow or overflow.", - 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).", - 33: "Attempted to convert to an invalid type.", - 34: "Attempted to access a storage byte array that is incorrectly encoded.", - 49: "Performed `.pop()` on an empty array", - 50: "Array index is out of bounds.", - 65: "Allocated too much memory or created an array which is too large.", - 81: "Attempted to call a zero-initialized variable of internal function type." -}; -const solidityError = { - inputs: [ - { - name: "message", - type: "string" - } - ], - name: "Error", - type: "error" -}; -const solidityPanic = { - inputs: [ - { - name: "reason", - type: "uint256" - } - ], - name: "Panic", - type: "error" -}; -function decodeErrorResult(parameters) { - const { abi: abi2, data } = parameters; - const signature2 = slice(data, 0, 4); - if (signature2 === "0x") - throw new AbiDecodingZeroDataError(); - const abi_ = [...abi2 || [], solidityError, solidityPanic]; - const abiItem = abi_.find((x2) => x2.type === "error" && signature2 === toFunctionSelector(formatAbiItem$1(x2))); - if (!abiItem) - throw new AbiErrorSignatureNotFoundError(signature2, { - docsPath: "/docs/contract/decodeErrorResult" - }); - return { - abiItem, - args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : void 0, - errorName: abiItem.name - }; -} -function formatAbiItemWithArgs({ abiItem, args, includeFunctionName = true, includeName = false }) { - if (!("name" in abiItem)) - return; - if (!("inputs" in abiItem)) - return; - if (!abiItem.inputs) - return; - return `${includeFunctionName ? abiItem.name : ""}(${abiItem.inputs.map((input2, i) => `${includeName && input2.name ? `${input2.name}: ` : ""}${typeof args[i] === "object" ? stringify(args[i]) : args[i]}`).join(", ")})`; -} -class CallExecutionError extends BaseError$3 { - constructor(cause, { account: account_, docsPath: docsPath2, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride }) { - var _a2; - const account2 = account_ ? parseAccount(account_) : void 0; - let prettyArgs = prettyPrint({ - from: account2 == null ? void 0 : account2.address, - to, - value: typeof value !== "undefined" && `${formatEther(value)} ${((_a2 = chain == null ? void 0 : chain.nativeCurrency) == null ? void 0 : _a2.symbol) || "ETH"}`, - data, - gas, - gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, - maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, - maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, - nonce - }); - if (stateOverride) { - prettyArgs += ` -${prettyStateOverride(stateOverride)}`; + })); + } + static buildDeployTransaction(context2, imageHash2) { + const factoryInterface = new Interface(walletContracts.factory.abi); + return { + entrypoint: context2.guestModule, + transactions: [{ + to: context2.factory, + data: factoryInterface.encodeFunctionData(factoryInterface.getFunction("deploy"), [context2.mainModule, imageHash2]), + gasLimit: 1e5, + delegateCall: false, + revertOnError: true, + value: 0 + }] + }; + } + async buildUpdateConfigurationTransaction(config2) { + if (this.coders.config.update.isKindUsed) { + const implementation = await this.reader().implementation(this.address); + const isLaterUpdate = implementation && implementation === this.context.mainModuleUpgradable; + return this.coders.config.update.buildTransaction(this.address, config2, this.context, isLaterUpdate ? "later" : "first"); } - super(cause.shortMessage, { - cause, - docsPath: docsPath2, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - "Raw Call Arguments:", - prettyArgs - ].filter(Boolean), - name: "CallExecutionError" - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.cause = cause; + return this.coders.config.update.buildTransaction(this.address, config2, this.context); } -} -class ContractFunctionExecutionError extends BaseError$3 { - constructor(cause, { abi: abi2, args, contractAddress, docsPath: docsPath2, functionName, sender }) { - const abiItem = getAbiItem({ abi: abi2, args, name: functionName }); - const formattedArgs = abiItem ? formatAbiItemWithArgs({ - abiItem, - args, - includeFunctionName: false, - includeName: false - }) : void 0; - const functionWithParams = abiItem ? formatAbiItem$1(abiItem, { includeName: true }) : void 0; - const prettyArgs = prettyPrint({ - address: contractAddress && getContractAddress(contractAddress), - function: functionWithParams, - args: formattedArgs && formattedArgs !== "()" && `${[...Array((functionName == null ? void 0 : functionName.length) ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`, - sender - }); - super(cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`, { - cause, - docsPath: docsPath2, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - prettyArgs && "Contract Call:", - prettyArgs - ].filter(Boolean), - name: "ContractFunctionExecutionError" - }); - Object.defineProperty(this, "abi", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "args", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "contractAddress", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "formattedArgs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "functionName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "sender", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.abi = abi2; - this.args = args; - this.cause = cause; - this.contractAddress = contractAddress; - this.functionName = functionName; - this.sender = sender; + async getNonce(space = 0) { + const nonce = await this.reader().nonce(this.address, space); + if (nonce === void 0) throw new Error("Unable to determine nonce"); + return Number(nonce); } -} -class ContractFunctionRevertedError extends BaseError$3 { - constructor({ abi: abi2, data, functionName, message }) { - let cause; - let decodedData = void 0; - let metaMessages; - let reason; - if (data && data !== "0x") { - try { - decodedData = decodeErrorResult({ abi: abi2, data }); - const { abiItem, errorName, args: errorArgs } = decodedData; - if (errorName === "Error") { - reason = errorArgs[0]; - } else if (errorName === "Panic") { - const [firstArg] = errorArgs; - reason = panicReasons[firstArg]; - } else { - const errorWithParams = abiItem ? formatAbiItem$1(abiItem, { includeName: true }) : void 0; - const formattedArgs = abiItem && errorArgs ? formatAbiItemWithArgs({ - abiItem, - args: errorArgs, - includeFunctionName: false, - includeName: false - }) : void 0; - metaMessages = [ - errorWithParams ? `Error: ${errorWithParams}` : "", - formattedArgs && formattedArgs !== "()" ? ` ${[...Array((errorName == null ? void 0 : errorName.length) ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : "" - ]; - } - } catch (err) { - cause = err; - } - } else if (message) - reason = message; - let signature2; - if (cause instanceof AbiErrorSignatureNotFoundError) { - signature2 = cause.signature; - metaMessages = [ - `Unable to decode signature "${signature2}" as it was not found on the provided ABI.`, - "Make sure you are using the correct ABI and that the error exists on it.", - `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature2}.` - ]; + async signDigest(digest, metadata2) { + const subdigest = subDigestOf(this.address, this.chainId, digest); + if (this.coders.config.hasSubdigest(this.config, subdigest)) { + return this.coders.signature.encodeSigners(this.config, /* @__PURE__ */ new Map(), [subdigest], this.chainId).encoded; } - super(reason && reason !== "execution reverted" || signature2 ? [ - `The contract function "${functionName}" reverted with the following ${signature2 ? "signature" : "reason"}:`, - reason || signature2 - ].join("\n") : `The contract function "${functionName}" reverted.`, { - cause, - metaMessages, - name: "ContractFunctionRevertedError" - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "reason", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + const childMetadata = _extends$9({}, metadata2, { + // Keep other metadata fields + digest, + chainId: this.chainId, + address: this.address, + config: this.config }); - Object.defineProperty(this, "signature", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + const subdigestBytes = getBytes(subdigest); + const signature2 = await this.orchestrator.signMessage({ + candidates: this.coders.config.signersOf(this.config).map((s2) => s2.address), + message: subdigestBytes, + metadata: childMetadata, + callback: (status, onNewMetadata) => { + const parts2 = statusToSignatureParts(status); + const newMetadata = _extends$9({}, childMetadata, { + parts: parts2 + }); + onNewMetadata(newMetadata); + return this.coders.signature.hasEnoughSigningPower(this.config, parts2); + } }); - this.data = decodedData; - this.reason = reason; - this.signature = signature2; + const parts = statusToSignatureParts(signature2); + return this.coders.signature.encodeSigners(this.config, parts, [], this.chainId).encoded; } -} -class ContractFunctionZeroDataError extends BaseError$3 { - constructor({ functionName }) { - super(`The contract function "${functionName}" returned no data ("0x").`, { - metaMessages: [ - "This could be due to any of the following:", - ` - The contract does not have the function "${functionName}",`, - " - The parameters passed to the contract function may be invalid, or", - " - The address is not a contract." - ], - name: "ContractFunctionZeroDataError" + signMessage(message) { + return this.signDigest(keccak256(message), { + message }); } -} -class CounterfactualDeploymentFailedError extends BaseError$3 { - constructor({ factory: factory2 }) { - super(`Deployment for counterfactual contract call failed${factory2 ? ` for factory "${factory2}".` : ""}`, { - metaMessages: [ - "Please ensure:", - "- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).", - "- The `factoryData` is a valid encoded function call for contract deployment function on the factory." - ], - name: "CounterfactualDeploymentFailedError" + // XXX This method is not implemented in the original code but required by the AbstractSigner interface + signTypedData(domain2, types2, value) { + const digest = encodeTypedDataDigest({ + domain: domain2, + types: types2, + message: value }); + return this.signDigest(digest); } -} -class RawContractError extends BaseError$3 { - constructor({ data, message }) { - super(message || "", { name: "RawContractError" }); - Object.defineProperty(this, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 3 - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.data = data; + signTransactionBundle(bundle) { + if (bundle.entrypoint !== this.address) { + throw new Error(`Invalid entrypoint: ${bundle.entrypoint} !== ${this.address}`); + } + return this.signTransactions(bundle.transactions, bundle.nonce); } -} -function isNullUniversalResolverError(err, callType) { - var _a2, _b2, _c2, _d2, _e2, _f2; - if (!(err instanceof BaseError$3)) - return false; - const cause = err.walk((e2) => e2 instanceof ContractFunctionRevertedError); - if (!(cause instanceof ContractFunctionRevertedError)) - return false; - if (((_a2 = cause.data) == null ? void 0 : _a2.errorName) === "ResolverNotFound") - return true; - if (((_b2 = cause.data) == null ? void 0 : _b2.errorName) === "ResolverWildcardNotSupported") - return true; - if (((_c2 = cause.data) == null ? void 0 : _c2.errorName) === "ResolverNotContract") - return true; - if (((_d2 = cause.data) == null ? void 0 : _d2.errorName) === "ResolverError") - return true; - if (((_e2 = cause.data) == null ? void 0 : _e2.errorName) === "HttpError") - return true; - if ((_f2 = cause.reason) == null ? void 0 : _f2.includes("Wildcard on non-extended resolvers is not supported")) - return true; - if (callType === "reverse" && cause.reason === panicReasons[50]) - return true; - return false; -} -function encodedLabelToLabelhash(label) { - if (label.length !== 66) - return null; - if (label.indexOf("[") !== 0) - return null; - if (label.indexOf("]") !== 65) - return null; - const hash2 = `0x${label.slice(1, 65)}`; - if (!isHex(hash2)) - return null; - return hash2; -} -function namehash(name2) { - let result = new Uint8Array(32).fill(0); - if (!name2) - return bytesToHex$1(result); - const labels = name2.split("."); - for (let i = labels.length - 1; i >= 0; i -= 1) { - const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]); - const hashed = hashFromEncodedLabel ? toBytes$1(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes"); - result = keccak256(concat([result, hashed]), "bytes"); + async fetchNonceOrSpace(nonce) { + let spaceValue; + if (nonce && nonce.space !== void 0) { + spaceValue = BigInt(nonce.space); + } else if (nonce === void 0) { + return this.randomNonce(); + } else if (nonce && nonce.serial === true) { + spaceValue = 0; + } else { + return nonce; + } + const resultNonce = await this.reader().nonce(this.address, spaceValue); + if (resultNonce === void 0) throw new Error("Unable to determine nonce"); + return index$1$1.transaction.encodeNonce(spaceValue, resultNonce); } - return bytesToHex$1(result); -} -function encodeLabelhash(hash2) { - return `[${hash2.slice(2)}]`; -} -function labelhash(label) { - const result = new Uint8Array(32).fill(0); - if (!label) - return bytesToHex$1(result); - return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label)); -} -function packetToBytes(packet) { - const value = packet.replace(/^\.|\.$/gm, ""); - if (value.length === 0) - return new Uint8Array(1); - const bytes2 = new Uint8Array(stringToBytes(value).byteLength + 2); - let offset2 = 0; - const list2 = value.split("."); - for (let i = 0; i < list2.length; i++) { - let encoded = stringToBytes(list2[i]); - if (encoded.byteLength > 255) - encoded = stringToBytes(encodeLabelhash(labelhash(list2[i]))); - bytes2[offset2] = encoded.length; - bytes2.set(encoded, offset2 + 1); - offset2 += encoded.length + 1; + // Generate nonce with random space + randomNonce() { + const randomNonceSpace = BigInt(hexlify(randomBytes(12))); + const randomNonce = index$1$1.transaction.encodeNonce(randomNonceSpace, 0); + return randomNonce; } - if (bytes2.byteLength !== offset2 + 1) - return bytes2.slice(0, offset2 + 1); - return bytes2; -} -const EXECUTION_REVERTED_ERROR_CODE = 3; -function getContractError(err, { abi: abi2, address, args, docsPath: docsPath2, functionName, sender }) { - const { code: code2, data, message, shortMessage } = err instanceof RawContractError ? err : err instanceof BaseError$3 ? err.walk((err2) => "data" in err2) || err.walk() : {}; - const cause = (() => { - if (err instanceof AbiDecodingZeroDataError) - return new ContractFunctionZeroDataError({ functionName }); - if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code2) && (data || message || shortMessage)) { - return new ContractFunctionRevertedError({ - abi: abi2, - data: typeof data === "object" ? data.data : data, - functionName, - message: shortMessage ?? message + async signTransactions(txs, nonce, metadata2) { + const transaction2 = await resolveArrayProperties$1(txs); + const transactions2 = index$1$1.transaction.fromTransactionish(this.address, transaction2); + if (transactions2.length === 0) { + transactions2.push({ + to: this.address, + data: "0x", + value: 0, + gasLimit: 0, + delegateCall: false, + revertOnError: true }); } - return err; - })(); - return new ContractFunctionExecutionError(cause, { - abi: abi2, - args, - contractAddress: address, - docsPath: docsPath2, - functionName, - sender - }); -} -const aggregate3Signature = "0x82ad56cb"; -const deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe"; -const deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe"; -const universalSignatureValidatorByteCode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572"; -function getCallError(err, { docsPath: docsPath2, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new CallExecutionError(cause, { - docsPath: docsPath2, - ...args - }); -} -const schedulerCache = /* @__PURE__ */ new Map(); -function createBatchScheduler({ fn, id: id2, shouldSplitBatch, wait: wait2 = 0, sort }) { - const exec = async () => { - const scheduler2 = getScheduler(); - flush(); - const args = scheduler2.map(({ args: args2 }) => args2); - if (args.length === 0) - return; - fn(args).then((data) => { - var _a2; - if (sort && Array.isArray(data)) - data.sort(sort); - for (let i = 0; i < scheduler2.length; i++) { - const { pendingPromise } = scheduler2[i]; - (_a2 = pendingPromise.resolve) == null ? void 0 : _a2.call(pendingPromise, [data[i], data]); - } - }).catch((err) => { - var _a2; - for (let i = 0; i < scheduler2.length; i++) { - const { pendingPromise } = scheduler2[i]; - (_a2 = pendingPromise.reject) == null ? void 0 : _a2.call(pendingPromise, err); - } - }); - }; - const flush = () => schedulerCache.delete(id2); - const getBatchedArgs = () => getScheduler().map(({ args }) => args); - const getScheduler = () => schedulerCache.get(id2) || []; - const setScheduler = (item2) => schedulerCache.set(id2, [...getScheduler(), item2]); - return { - flush, - async schedule(args) { - const pendingPromise = {}; - const promise = new Promise((resolve, reject) => { - pendingPromise.resolve = resolve; - pendingPromise.reject = reject; + const defaultedNonce = await this.fetchNonceOrSpace(nonce); + const digest = index$1$1.transaction.digestOfTransactions(defaultedNonce, transactions2); + const meta = _extends$9({ + digest, + transactions: transactions2 + }, metadata2); + const signature2 = await this.signDigest(digest, meta); + return { + intent: { + // Maybe is better if signDigest returns the subdigest directly + id: subDigestOf(this.address, this.chainId, digest), + wallet: this.address + }, + chainId: this.chainId, + transactions: transactions2, + entrypoint: this.address, + nonce: defaultedNonce, + signature: signature2 + }; + } + async sendSignedTransaction(signedBundle, quote) { + if (!this.relayer) throw new Error("Wallet sendTransaction requires a relayer"); + return this.relayer.relay(signedBundle, quote); + } + // sendTransaction will dispatch the transaction to the relayer for submission to the network. + // This method is able to send transactions in serial or parallel (default). You can specify + // a specific nonce, or let the wallet determine the next nonce on-chain (serial:true). + // + // By default, nonces are generated randomly and assigned so transactioned can be executed + // in parallel. However, if you'd like to execute serially, pass { serial: true } as an option. + async sendTransaction(txs, options) { + let nonce; + if ((options == null ? void 0 : options.nonce) !== void 0) { + nonce = options.nonce; + } else if (options != null && options.serial) { + nonce = { + serial: true + }; + } else { + nonce = this.randomNonce(); + } + const signed2 = await this.signTransactions(txs, nonce); + const decorated = await this.decorateTransactions(signed2); + return this.sendSignedTransaction(decorated, options == null ? void 0 : options.quote); + } + async fillGasLimits(txs) { + const transaction2 = await resolveArrayProperties$1(txs); + const transactions2 = index$1$1.transaction.fromTransactionish(this.address, transaction2); + const relayer2 = this.relayer; + if (!relayer2) throw new Error("Wallet fillGasLimits requires a relayer"); + const simulations = await relayer2.simulate(this.address, ...transactions2); + return transactions2.map((tx, i) => { + const gasLimit = tx.gasLimit ? Number(tx.gasLimit) : simulations[i].gasLimit; + return _extends$9({}, tx, simulations[i], { + gasLimit }); - const split2 = shouldSplitBatch == null ? void 0 : shouldSplitBatch([...getBatchedArgs(), args]); - if (split2) - exec(); - const hasActiveScheduler = getScheduler().length > 0; - if (hasActiveScheduler) { - setScheduler({ args, pendingPromise }); - return promise; + }); + } + connect(provider2, relayer2) { + return new Wallet({ + // Sequence version configurator + coders: this.coders, + context: this.context, + config: this.config, + chainId: this.chainId, + address: this.address, + orchestrator: this.orchestrator, + reader: this._reader, + provider: provider2, + relayer: relayer2 != null ? relayer2 : this.relayer + }); + } + signTransaction(transaction2) { + throw new Error("Method not implemented."); + } +} +function _extends$8() { + _extends$8 = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } } - setScheduler({ args, pendingPromise }); - setTimeout(exec, wait2); - return promise; } + return target; }; + return _extends$8.apply(this, arguments); } -async function call(client2, args) { - var _a2, _b2, _c2, _d2; - const { account: account_ = client2.account, batch = Boolean((_a2 = client2.batch) == null ? void 0 : _a2.multicall), blockNumber, blockTag = "latest", accessList, blobs, code: code2, data: data_, factory: factory2, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride, ...rest } = args; - const account2 = account_ ? parseAccount(account_) : void 0; - if (code2 && (factory2 || factoryData)) - throw new BaseError$3("Cannot provide both `code` & `factory`/`factoryData` as parameters."); - if (code2 && to) - throw new BaseError$3("Cannot provide both `code` & `to` as parameters."); - const deploylessCallViaBytecode = code2 && data_; - const deploylessCallViaFactory = factory2 && factoryData && to && data_; - const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory; - const data = (() => { - if (deploylessCallViaBytecode) - return toDeploylessCallViaBytecodeData({ - code: code2, - data: data_ - }); - if (deploylessCallViaFactory) - return toDeploylessCallViaFactoryData({ - data: data_, - factory: factory2, - factoryData, - to - }); - return data_; - })(); - try { - assertRequest(args); - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const block = blockNumberHex || blockTag; - const rpcStateOverride = serializeStateOverride(stateOverride); - const chainFormat = (_d2 = (_c2 = (_b2 = client2.chain) == null ? void 0 : _b2.formatters) == null ? void 0 : _c2.transactionRequest) == null ? void 0 : _d2.format; - const format2 = chainFormat || formatTransactionRequest; - const request = format2({ - // Pick out extra data that might exist on the chain's transaction request type. - ...extract(rest, { format: chainFormat }), - from: account2 == null ? void 0 : account2.address, - accessList, - blobs, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to: deploylessCall ? void 0 : to, - value - }); - if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) { - try { - return await scheduleMulticall(client2, { - ...request, - blockNumber, - blockTag - }); - } catch (err) { - if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract)) - throw err; +function encodeGasRefundTransaction(option) { + if (!option) return []; + const value = BigInt(option.value); + switch (option.token.type) { + case relayer_gen.FeeTokenType.UNKNOWN: + return [{ + delegateCall: false, + revertOnError: true, + gasLimit: option.gasLimit, + to: option.to, + value: toHexString(value), + data: "0x" + }]; + case relayer_gen.FeeTokenType.ERC20_TOKEN: + if (!option.token.contractAddress) { + throw new Error(`No contract address for ERC-20 fee option`); } + return [{ + delegateCall: false, + revertOnError: true, + gasLimit: option.gasLimit, + to: option.token.contractAddress, + value: 0, + data: new Interface([{ + constant: false, + inputs: [{ + type: "address" + }, { + type: "uint256" + }], + name: "transfer", + outputs: [], + type: "function" + }]).encodeFunctionData("transfer", [option.to, toHexString(value)]) + }]; + default: + throw new Error(`Unhandled fee token type ${option.token.type}`); + } +} +class AccountSigner { + constructor(account2, chainId, options) { + this.account = account2; + this.chainId = chainId; + this.options = options; + } + get provider() { + return this.account.providerFor(this.chainId); + } + async getAddress() { + return this.account.address; + } + signMessage(message) { + var _this$options$cantVal, _this$options; + return this.account.signMessage(message, this.chainId, (_this$options$cantVal = (_this$options = this.options) == null ? void 0 : _this$options.cantValidateBehavior) != null ? _this$options$cantVal : "throw"); + } + signTypedData(domain2, types2, value) { + var _this$options$cantVal2, _this$options2; + return this.account.signTypedData(domain2, types2, value, this.chainId, (_this$options$cantVal2 = (_this$options2 = this.options) == null ? void 0 : _this$options2.cantValidateBehavior) != null ? _this$options$cantVal2 : "throw"); + } + async defaultSelectFee(_txs, options) { + if (options.length === 0) return void 0; + const balanceOfAbi = [{ + constant: true, + inputs: [{ + type: "address" + }], + name: "balanceOf", + outputs: [{ + type: "uint256" + }], + type: "function" + }]; + for (const option of options) { + if (option.token.type === relayer_gen.FeeTokenType.UNKNOWN) { + const balance = await this.getBalance(); + if (balance >= BigInt(option.value)) { + return option; + } + } else if (option.token.contractAddress && option.token.type === relayer_gen.FeeTokenType.ERC20_TOKEN) { + const token = new Contract(option.token.contractAddress, balanceOfAbi, this.provider); + const balance = await token.balanceOf(this.account.address); + if (balance >= BigInt(option.value)) { + return option; + } + } else ; } - const response = await client2.request({ - method: "eth_call", - params: rpcStateOverride ? [ - request, - block, - rpcStateOverride - ] : [request, block] - }); - if (response === "0x") - return { data: void 0 }; - return { data: response }; - } catch (err) { - const data2 = getRevertErrorData(err); - const { offchainLookup, offchainLookupSignature } = await __vitePreload(async () => { - const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-BUGx8scz.js"); - return { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 }; - }, true ? [] : void 0, import.meta.url); - if (client2.ccipRead !== false && (data2 == null ? void 0 : data2.slice(0, 10)) === offchainLookupSignature && to) - return { data: await offchainLookup(client2, { data: data2, to }) }; - if (deploylessCall && (data2 == null ? void 0 : data2.slice(0, 10)) === "0x101bb98d") - throw new CounterfactualDeploymentFailedError({ factory: factory2 }); - throw getCallError(err, { - ...args, - account: account2, - chain: client2.chain + throw new Error("No fee option available - not enough balance"); + } + async sendTransaction(txs, options) { + var _this$options$stubSig, _this$options3, _this$options$selectF, _this$options4, _this$options5; + const prepare = await this.account.prepareTransactions({ + txs, + chainId: this.chainId, + stubSignatureOverrides: (_this$options$stubSig = (_this$options3 = this.options) == null ? void 0 : _this$options3.stubSignatureOverrides) != null ? _this$options$stubSig : /* @__PURE__ */ new Map(), + simulateForFeeOptions: options == null ? void 0 : options.simulateForFeeOptions }); + const selectMethod = (_this$options$selectF = (_this$options4 = this.options) == null ? void 0 : _this$options4.selectFee) != null ? _this$options$selectF : this.defaultSelectFee.bind(this); + const feeOption = await selectMethod(txs, prepare.feeOptions); + const finalTransactions = [...prepare.transactions, ...encodeGasRefundTransaction(feeOption)]; + return this.account.sendTransaction(finalTransactions, this.chainId, prepare.feeQuote, void 0, void 0, ((_this$options5 = this.options) == null ? void 0 : _this$options5.nonceSpace) !== void 0 ? { + nonceSpace: this.options.nonceSpace + } : void 0); + } + getBalance(blockTag) { + return this.provider.getBalance(this.account.address, blockTag); + } + call(transaction2, blockTag) { + return this.provider.call(_extends$8({}, transaction2, { + blockTag + })); + } + async resolveName(name2) { + const res = await this.provider.resolveName(name2); + if (!res) throw new Error(`Could not resolve name ${name2}`); + return res; + } + connect(_provider6) { + throw new Error("Method not implemented."); + } + signTransaction(transaction2) { + throw new Error("Method not implemented."); + } + getTransactionCount(blockTag) { + throw new Error("Method not implemented."); + } + estimateGas(transaction2) { + throw new Error("Method not implemented."); + } + getChainId() { + return Promise.resolve(Number(this.chainId)); + } + getGasPrice() { + throw new Error("Method not implemented."); + } + getFeeData() { + throw new Error("Method not implemented."); + } + getNonce(blockTag) { + throw new Error("Method not implemented."); + } + populateCall(tx) { + throw new Error("Method not implemented."); + } + checkTransaction(transaction2) { + throw new Error("Method not implemented."); + } + async populateTransaction(tx) { + throw new Error("Method not implemented."); + } + _checkProvider(operation) { + throw new Error("Method not implemented."); } } -function shouldPerformMulticall({ request }) { - const { data, to, ...request_ } = request; - if (!data) - return false; - if (data.startsWith(aggregate3Signature)) - return false; - if (!to) - return false; - if (Object.values(request_).filter((x2) => typeof x2 !== "undefined").length > 0) +class Chain0Reader { + async isDeployed(_wallet) { return false; - return true; -} -async function scheduleMulticall(client2, args) { - var _a2; - const { batchSize = 1024, wait: wait2 = 0 } = typeof ((_a2 = client2.batch) == null ? void 0 : _a2.multicall) === "object" ? client2.batch.multicall : {}; - const { blockNumber, blockTag = "latest", data, multicallAddress: multicallAddress_, to } = args; - let multicallAddress = multicallAddress_; - if (!multicallAddress) { - if (!client2.chain) - throw new ClientChainNotConfiguredError(); - multicallAddress = getChainContractAddress({ - blockNumber, - chain: client2.chain, - contract: "multicall3" - }); } - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const block = blockNumberHex || blockTag; - const { schedule } = createBatchScheduler({ - id: `${client2.uid}.${block}`, - wait: wait2, - shouldSplitBatch(args2) { - const size2 = args2.reduce((size3, { data: data2 }) => size3 + (data2.length - 2), 0); - return size2 > batchSize * 2; - }, - fn: async (requests) => { - const calls = requests.map((request) => ({ - allowFailure: true, - callData: request.data, - target: request.to - })); - const calldata = encodeFunctionData({ - abi: multicall3Abi, - args: [calls], - functionName: "aggregate3" - }); - const data2 = await client2.request({ - method: "eth_call", - params: [ - { - data: calldata, - to: multicallAddress - }, - block - ] - }); - return decodeFunctionResult({ - abi: multicall3Abi, - args: [calls], - functionName: "aggregate3", - data: data2 || "0x" - }); - } - }); - const [{ returnData, success }] = await schedule({ data, to }); - if (!success) - throw new RawContractError({ data: returnData }); - if (returnData === "0x") - return { data: void 0 }; - return { data: returnData }; -} -function toDeploylessCallViaBytecodeData(parameters) { - const { code: code2, data } = parameters; - return encodeDeployData({ - abi: parseAbi(["constructor(bytes, bytes)"]), - bytecode: deploylessCallViaBytecodeBytecode, - args: [code2, data] - }); -} -function toDeploylessCallViaFactoryData(parameters) { - const { data, factory: factory2, factoryData, to } = parameters; - return encodeDeployData({ - abi: parseAbi(["constructor(address, bytes, address, bytes)"]), - bytecode: deploylessCallViaFactoryBytecode, - args: [to, data, factory2, factoryData] - }); -} -function getRevertErrorData(err) { - var _a2; - if (!(err instanceof BaseError$3)) + async implementation(_wallet) { return void 0; - const error = err.walk(); - return typeof (error == null ? void 0 : error.data) === "object" ? (_a2 = error.data) == null ? void 0 : _a2.data : error.data; -} -async function readContract$1(client2, parameters) { - const { abi: abi2, address, args, functionName, ...rest } = parameters; - const calldata = encodeFunctionData({ - abi: abi2, - args, - functionName - }); - try { - const { data } = await getAction$1(client2, call, "call")({ - ...rest, - data: calldata, - to: address - }); - return decodeFunctionResult({ - abi: abi2, - args, - functionName, - data: data || "0x" - }); - } catch (error) { - throw getContractError(error, { - abi: abi2, - address, - args, - docsPath: "/docs/contract/readContract", - functionName - }); + } + async imageHash(_wallet) { + return void 0; + } + async nonce(_wallet, _space) { + return 0n; + } + async isValidSignature(_wallet, _digest, _signature) { + throw new Error("Method not supported."); } } -async function getEnsAddress(client2, { blockNumber, blockTag, coinType, name: name2, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { - let universalResolverAddress = universalResolverAddress_; - if (!universalResolverAddress) { - if (!client2.chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - universalResolverAddress = getChainContractAddress({ - blockNumber, - chain: client2.chain, - contract: "ensUniversalResolver" - }); +class Account { + constructor(options) { + this.address = void 0; + this.networks = void 0; + this.tracker = void 0; + this.contexts = void 0; + this.migrator = void 0; + this.migrations = void 0; + this.orchestrator = void 0; + this.jwt = void 0; + this.projectAccessKey = void 0; + this.address = getAddress(options.address); + this.contexts = options.contexts; + this.tracker = options.tracker; + this.networks = options.networks; + this.orchestrator = options.orchestrator; + this.jwt = options.jwt; + this.projectAccessKey = options.projectAccessKey; + this.migrations = options.migrations || defaults.DefaultMigrations; + this.migrator = new migrator.Migrator(options.tracker, this.migrations, this.contexts); } - try { - const functionData = encodeFunctionData({ - abi: addressResolverAbi, - functionName: "addr", - ...coinType != null ? { args: [namehash(name2), BigInt(coinType)] } : { args: [namehash(name2)] } + getSigner(chainId, options) { + return new AccountSigner(this, chainId, options); + } + static async new(options) { + var _options$migrations; + const mig = new migrator.Migrator(options.tracker, (_options$migrations = options.migrations) != null ? _options$migrations : defaults.DefaultMigrations, options.contexts); + const lastMigration = mig.lastMigration(); + const lastCoder = lastMigration.configCoder; + const config2 = lastCoder.fromSimple(options.config); + const imageHash2 = lastCoder.imageHashOf(config2); + const context2 = options.contexts[lastMigration.version]; + const address = index$1$1.context.addressOf(context2, imageHash2); + await options.tracker.saveCounterfactualWallet({ + config: config2, + context: Object.values(options.contexts) }); - const readContractParameters = { - address: universalResolverAddress, - abi: universalResolverResolveAbi, - functionName: "resolve", - args: [toHex$1(packetToBytes(name2)), functionData], - blockNumber, - blockTag - }; - const readContractAction = getAction$1(client2, readContract$1, "readContract"); - const res = gatewayUrls ? await readContractAction({ - ...readContractParameters, - args: [...readContractParameters.args, gatewayUrls] - }) : await readContractAction(readContractParameters); - if (res[0] === "0x") - return null; - const address = decodeFunctionResult({ - abi: addressResolverAbi, - args: coinType != null ? [namehash(name2), BigInt(coinType)] : void 0, - functionName: "addr", - data: res[0] + return new Account({ + address, + tracker: options.tracker, + contexts: options.contexts, + networks: options.networks, + orchestrator: options.orchestrator, + migrations: options.migrations, + projectAccessKey: options.projectAccessKey }); - if (address === "0x") - return null; - if (trim(address) === "0x00") - return null; - return address; - } catch (err) { - if (strict) - throw err; - if (isNullUniversalResolverError(err, "resolve")) - return null; - throw err; } -} -class EnsAvatarInvalidMetadataError extends BaseError$3 { - constructor({ data }) { - super("Unable to extract image from metadata. The metadata may be malformed or invalid.", { - metaMessages: [ - "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.", - "", - `Provided data: ${JSON.stringify(data)}` - ], - name: "EnsAvatarInvalidMetadataError" - }); + getAddress() { + return Promise.resolve(this.address); } -} -class EnsAvatarInvalidNftUriError extends BaseError$3 { - constructor({ reason }) { - super(`ENS NFT avatar URI is invalid. ${reason}`, { - name: "EnsAvatarInvalidNftUriError" - }); + get version() { + return this.migrator.lastMigration().version; } -} -class EnsAvatarUriResolutionError extends BaseError$3 { - constructor({ uri }) { - super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" }); + get coders() { + const lastMigration = this.migrator.lastMigration(); + return { + signature: lastMigration.signatureCoder, + config: lastMigration.configCoder + }; } -} -class EnsAvatarUnsupportedNamespaceError extends BaseError$3 { - constructor({ namespace }) { - super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" }); + network(chainId) { + const tcid = BigInt(chainId); + const found = this.networks.find((n2) => tcid === BigInt(n2.chainId)); + if (!found) throw new Error(`Network not found for chainId ${chainId}`); + return found; } -} -const networkRegex = /(?https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/; -const ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/; -const base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/; -const dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/; -async function isImageUri(uri) { - try { - const res = await fetch(uri, { method: "HEAD" }); - if (res.status === 200) { - const contentType = res.headers.get("content-type"); - return contentType == null ? void 0 : contentType.startsWith("image/"); - } - return false; - } catch (error) { - if (typeof error === "object" && typeof error.response !== "undefined") { - return false; + providerFor(chainId) { + const found = this.network(chainId); + if (!found.provider && !found.rpcUrl) { + throw new Error(`Provider not found for chainId ${chainId}`); } - if (!globalThis.hasOwnProperty("Image")) - return false; - return new Promise((resolve) => { - const img2 = new Image(); - img2.onload = () => { - resolve(true); - }; - img2.onerror = () => { - resolve(false); - }; - img2.src = uri; + const network2 = new Network(found.name, found.chainId); + return found.provider || new JsonRpcProvider$1(getFetchRequest(found.rpcUrl, this.projectAccessKey, this.jwt), network2, { + staticNetwork: network2 }); } -} -function getGateway(custom2, defaultGateway) { - if (!custom2) - return defaultGateway; - if (custom2.endsWith("/")) - return custom2.slice(0, -1); - return custom2; -} -function resolveAvatarUri({ uri, gatewayUrls }) { - const isEncoded = base64Regex.test(uri); - if (isEncoded) - return { uri, isOnChain: true, isEncoded }; - const ipfsGateway = getGateway(gatewayUrls == null ? void 0 : gatewayUrls.ipfs, "https://ipfs.io"); - const arweaveGateway = getGateway(gatewayUrls == null ? void 0 : gatewayUrls.arweave, "https://arweave.net"); - const networkRegexMatch = uri.match(networkRegex); - const { protocol, subpath, target, subtarget = "" } = (networkRegexMatch == null ? void 0 : networkRegexMatch.groups) || {}; - const isIPNS = protocol === "ipns:/" || subpath === "ipns/"; - const isIPFS2 = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri); - if (uri.startsWith("http") && !isIPNS && !isIPFS2) { - let replacedUri = uri; - if (gatewayUrls == null ? void 0 : gatewayUrls.arweave) - replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls == null ? void 0 : gatewayUrls.arweave); - return { uri: replacedUri, isOnChain: false, isEncoded: false }; + reader(chainId) { + if (BigInt(chainId) === 0n) { + return new Chain0Reader(); + } + return new index$1$1.reader.OnChainReader(this.providerFor(chainId)); } - if ((isIPNS || isIPFS2) && target) { - return { - uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`, - isOnChain: false, - isEncoded: false - }; + relayer(chainId) { + const found = this.network(chainId); + if (!found.relayer) throw new Error(`Relayer not found for chainId ${chainId}`); + if (isRelayer(found.relayer)) return found.relayer; + return new RpcRelayer(_extends$8({}, found.relayer, this.projectAccessKey ? { + projectAccessKey: this.projectAccessKey + } : { + jwtAuth: this.jwt + })); } - if (protocol === "ar:/" && target) { - return { - uri: `${arweaveGateway}/${target}${subtarget || ""}`, - isOnChain: false, - isEncoded: false - }; + setOrchestrator(orchestrator) { + this.orchestrator = orchestrator; } - let parsedUri = uri.replace(dataURIRegex, ""); - if (parsedUri.startsWith(" res2.json()); - const image = await parseAvatarUri({ - gatewayUrls, - uri: getJsonImage(res) + walletFor(chainId, context2, config2, coders2) { + const isNetworkZero = BigInt(chainId) === 0n; + return new Wallet({ + config: config2, + context: context2, + chainId, + coders: coders2, + relayer: isNetworkZero ? void 0 : this.relayer(chainId), + address: this.address, + orchestrator: this.orchestrator, + reader: this.reader(chainId) }); - return image; - } catch { - throw new EnsAvatarUriResolutionError({ uri }); } -} -async function parseAvatarUri({ gatewayUrls, uri }) { - const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls }); - if (isOnChain) - return resolvedURI; - const isImage = await isImageUri(resolvedURI); - if (isImage) - return resolvedURI; - throw new EnsAvatarUriResolutionError({ uri }); -} -function parseNftUri(uri_) { - let uri = uri_; - if (uri.startsWith("did:nft:")) { - uri = uri.replace("did:nft:", "").replace(/_/g, "/"); - } - const [reference, asset_namespace, tokenID] = uri.split("/"); - const [eip_namespace, chainID] = reference.split(":"); - const [erc_namespace, contractAddress] = asset_namespace.split(":"); - if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155") - throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" }); - if (!chainID) - throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" }); - if (!contractAddress) - throw new EnsAvatarInvalidNftUriError({ - reason: "Contract address not found" + // Get the status of the account on a given network + // this does the following process: + // 1. Get the current on-chain status of the wallet (version + imageHash) + // 2. Get any pending migrations that have been signed by the wallet + // 3. Get any pending configuration updates that have been signed by the wallet + // 4. Fetch reverse lookups for both on-chain and pending configurations + async status(chainId, longestPath = false) { + var _this = this; + const isDeployedPromise = this.reader(chainId).isDeployed(this.address); + const counterfactualImageHashPromise = this.tracker.imageHashOfCounterfactualWallet({ + wallet: this.address + }).then((r2) => { + if (!r2) throw new Error(`Counterfactual imageHash not found for wallet ${this.address}`); + return r2; }); - if (!tokenID) - throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" }); - if (!erc_namespace) - throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" }); - return { - chainID: Number.parseInt(chainID), - namespace: erc_namespace.toLowerCase(), - contractAddress, - tokenID - }; -} -async function getNftTokenUri(client2, { nft }) { - if (nft.namespace === "erc721") { - return readContract$1(client2, { - address: nft.contractAddress, - abi: [ - { - name: "tokenURI", - type: "function", - stateMutability: "view", - inputs: [{ name: "tokenId", type: "uint256" }], - outputs: [{ name: "", type: "string" }] + const counterFactualVersionPromise = counterfactualImageHashPromise.then((r2) => { + return version$2.counterfactualVersion(this.address, r2.imageHash, Object.values(this.contexts)); + }); + const onChainVersionPromise = async function() { + const isDeployed2 = await isDeployedPromise; + if (!isDeployed2) return counterFactualVersionPromise; + const implementation = await _this.reader(chainId).implementation(_this.address); + if (!implementation) throw new Error(`Implementation not found for wallet ${_this.address}`); + const versions = Object.values(_this.contexts); + for (let i = 0; i < versions.length; i++) { + if (versions[i].mainModule === implementation || versions[i].mainModuleUpgradable === implementation) { + return versions[i].version; } - ], - functionName: "tokenURI", - args: [BigInt(nft.tokenID)] + } + throw new Error(`Version not found for implementation ${implementation}`); + }(); + const onChainImageHashPromise = async function() { + const deployedImageHash = await _this.reader(chainId).imageHash(_this.address); + if (deployedImageHash) return deployedImageHash; + const counterfactualImageHash2 = await counterfactualImageHashPromise; + if (counterfactualImageHash2) return counterfactualImageHash2.imageHash; + throw new Error(`On-chain imageHash not found for wallet ${_this.address}`); + }(); + const onChainConfigPromise = async function() { + const onChainImageHash2 = await onChainImageHashPromise; + const onChainConfig = await _this.tracker.configOfImageHash({ + imageHash: onChainImageHash2 + }); + if (onChainConfig) return onChainConfig; + throw new Error(`On-chain config not found for imageHash ${onChainImageHash2}`); + }(); + const onChainVersion = await onChainVersionPromise; + const onChainImageHash = await onChainImageHashPromise; + let fromImageHash = onChainImageHash; + let lastVersion = onChainVersion; + let signedMigrations = []; + if (onChainVersion !== this.version) { + const presignedMigrate = await this.migrator.getAllMigratePresignedTransaction({ + address: this.address, + fromImageHash: onChainImageHash, + fromVersion: onChainVersion, + chainId + }); + fromImageHash = presignedMigrate.lastImageHash; + lastVersion = presignedMigrate.lastVersion; + signedMigrations = presignedMigrate.signedMigrations; + } + const presigned = await this.tracker.loadPresignedConfiguration({ + wallet: this.address, + fromImageHash, + longestPath + }); + const imageHash2 = presigned && presigned.length > 0 ? presigned[presigned.length - 1].nextImageHash : fromImageHash; + const config2 = await this.tracker.configOfImageHash({ + imageHash: imageHash2 }); + if (!config2) { + throw new Error(`Config not found for imageHash ${imageHash2}`); + } + const isDeployed = await isDeployedPromise; + const counterfactualImageHash = await counterfactualImageHashPromise; + const checkpoint = index$6.coderFor(lastVersion).config.checkpointOf(config2); + return { + original: _extends$8({}, counterfactualImageHash, { + version: await counterFactualVersionPromise + }), + onChain: { + imageHash: onChainImageHash, + config: await onChainConfigPromise, + version: onChainVersion, + deployed: isDeployed + }, + fullyMigrated: lastVersion === this.version, + signedMigrations, + version: lastVersion, + presignedConfigurations: presigned, + imageHash: imageHash2, + config: config2, + checkpoint, + canOnchainValidate: onChainVersion === this.version && isDeployed + }; } - if (nft.namespace === "erc1155") { - return readContract$1(client2, { - address: nft.contractAddress, - abi: [ - { - name: "uri", - type: "function", - stateMutability: "view", - inputs: [{ name: "_id", type: "uint256" }], - outputs: [{ name: "", type: "string" }] - } - ], - functionName: "uri", - args: [BigInt(nft.tokenID)] + mustBeFullyMigrated(status) { + if (!status.fullyMigrated) { + throw new Error(`Wallet ${this.address} is not fully migrated`); + } + } + async predecorateSignedTransactions(status, chainId) { + const bundles = await this.orchestrator.predecorateSignedTransactions({ + chainId }); + const predecorated = await this.predecorateTransactions([], status, chainId); + if (index$1$1.transaction.fromTransactionish(this.address, predecorated).length > 0) { + bundles.push(await this.signTransactions(predecorated, chainId)); + } + return bundles; } - throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace }); -} -async function parseAvatarRecord(client2, { gatewayUrls, record }) { - if (/eip155:/i.test(record)) - return parseNftAvatarUri(client2, { gatewayUrls, record }); - return parseAvatarUri({ uri: record, gatewayUrls }); -} -async function parseNftAvatarUri(client2, { gatewayUrls, record }) { - const nft = parseNftUri(record); - const nftUri = await getNftTokenUri(client2, { nft }); - const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls }); - if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) { - const encodedJson = isEncoded ? ( - // if it is encoded, decode it - atob(resolvedNftUri.replace("data:application/json;base64,", "")) - ) : ( - // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is) - resolvedNftUri - ); - const decoded = JSON.parse(encodedJson); - return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls }); + async predecorateTransactions(txs, status, chainId) { + if (status.onChain.imageHash !== status.imageHash) { + const wallet = this.walletForStatus(chainId, status); + const updateConfig = await wallet.buildUpdateConfigurationTransaction(status.config); + return [Array.isArray(txs) ? txs : [txs], updateConfig.transactions].flat(); + } + return txs; } - let uriTokenId = nft.tokenID; - if (nft.namespace === "erc1155") - uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0"); - return getMetadataAvatarUri({ - gatewayUrls, - uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId) - }); -} -async function getEnsText(client2, { blockNumber, blockTag, name: name2, key, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { - let universalResolverAddress = universalResolverAddress_; - if (!universalResolverAddress) { - if (!client2.chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - universalResolverAddress = getChainContractAddress({ - blockNumber, - chain: client2.chain, - contract: "ensUniversalResolver" + async decorateTransactions(bundles, status, chainId) { + var _chainId4, _bundles$; + if (!Array.isArray(bundles)) { + return this.decorateTransactions([bundles], status, chainId); + } + chainId = (_chainId4 = chainId) != null ? _chainId4 : bundles[0].chainId; + const bootstrapBundle = await this.buildBootstrapTransactions(status, chainId); + const hasBootstrapTxs = bootstrapBundle.transactions.length > 0; + if (!hasBootstrapTxs && bundles.length === 1) { + return bundles[0]; + } + const { + entrypoint + } = hasBootstrapTxs ? bootstrapBundle : bundles[0]; + const decoratedBundle = { + entrypoint, + chainId, + // Intent of the first bundle is used + intent: (_bundles$ = bundles[0]) == null ? void 0 : _bundles$.intent, + transactions: [...bootstrapBundle.transactions, ...bundles.map((bundle) => ({ + to: bundle.entrypoint, + data: index$1$1.transaction.encodeBundleExecData(bundle), + gasLimit: 0, + delegateCall: false, + revertOnError: true, + value: 0 + }))] + }; + if (!status.onChain.deployed) { + const id2 = index$1$1.transaction.subdigestOfGuestModuleTransactions(this.contexts[this.version].guestModule, chainId, decoratedBundle.transactions); + if (decoratedBundle.intent === void 0) { + decoratedBundle.intent = { + id: id2, + wallet: this.address + }; + } else { + decoratedBundle.intent.id = id2; + } + } + return decoratedBundle; + } + async decorateSignature(signature2, status) { + if (!status.presignedConfigurations || status.presignedConfigurations.length === 0) { + return signature2; + } + const coder = this.coders.signature; + const chain = status.presignedConfigurations.map((c2) => c2.signature); + const chainedSignature = coder.chainSignatures(signature2, chain); + return coder.trim(chainedSignature); + } + async publishWitness() { + const digest = id$1(`This is a Sequence account woo! ${Date.now()}`); + const signature2 = await this.signDigest(digest, 0, false); + const decoded = this.coders.signature.decode(signature2); + const signatures = this.coders.signature.signaturesOfDecoded(decoded); + return this.tracker.saveWitnesses({ + wallet: this.address, + digest, + chainId: 0, + signatures }); } - try { - const readContractParameters = { - address: universalResolverAddress, - abi: universalResolverResolveAbi, - functionName: "resolve", - args: [ - toHex$1(packetToBytes(name2)), - encodeFunctionData({ - abi: textResolverAbi, - functionName: "text", - args: [namehash(name2), key] - }) - ], - blockNumber, - blockTag + async signDigest(digest, chainId, decorate = true, cantValidateBehavior = "ignore", metadata2) { + const chainRef = BigInt(chainId) === 0n ? this.networks[0].chainId : chainId; + const status = await this.status(chainRef); + this.mustBeFullyMigrated(status); + if (!status.canOnchainValidate && cantValidateBehavior === "throw") { + throw new Error("Wallet cannot validate onchain"); + } + const wallet = this.walletForStatus(chainId, status); + const signature2 = await wallet.signDigest(digest, metadata2); + const decorated = decorate ? this.decorateSignature(signature2, status) : signature2; + if (!status.canOnchainValidate) { + switch (cantValidateBehavior) { + case "ignore": + return decorated; + case "eip6492": + return this.buildEIP6492Signature(await decorated, status, chainId); + } + } + return decorated; + } + buildOnChainSignature(digest) { + const subdigest = index$1$1.signature.subdigestOf({ + digest: hexlify(digest), + chainId: 0, + address: this.address + }); + const hexSubdigest = hexlify(subdigest); + const config2 = this.coders.config.fromSimple({ + // Threshold *only* needs to be > 0, this is not a magic number + // we only use 2 ** 15 because it may lead to lower gas costs in some chains + threshold: 32768, + checkpoint: 0, + signers: [], + subdigests: [hexSubdigest] + }); + const walletInterface = new Interface(walletContracts.mainModule.abi); + const bundle = { + entrypoint: this.address, + transactions: [{ + to: this.address, + data: walletInterface.encodeFunctionData( + // *NEVER* use updateImageHash here, as it would effectively destroy the wallet + // setExtraImageHash sets an additional imageHash, without changing the current one + "setExtraImageHash", + [ + this.coders.config.imageHashOf(config2), + // 2 ** 255 instead of max uint256, to have more zeros in the calldata + "57896044618658097711785492504343953926634992332820282019728792003956564819968" + ] + ), + // Conservative gas limit, used because the current relayer + // has trouble estimating gas for this transaction + gasLimit: 25e4 + }] }; - const readContractAction = getAction$1(client2, readContract$1, "readContract"); - const res = gatewayUrls ? await readContractAction({ - ...readContractParameters, - args: [...readContractParameters.args, gatewayUrls] - }) : await readContractAction(readContractParameters); - if (res[0] === "0x") - return null; - const record = decodeFunctionResult({ - abi: textResolverAbi, - functionName: "text", - data: res[0] + this.tracker.saveWalletConfig({ + config: config2 }); - return record === "" ? null : record; - } catch (err) { - if (strict) - throw err; - if (isNullUniversalResolverError(err, "resolve")) - return null; - throw err; + const signature2 = this.coders.signature.encodeSigners(config2, /* @__PURE__ */ new Map(), [hexSubdigest], 0).encoded; + return { + bundle, + signature: signature2 + }; } -} -async function getEnsAvatar(client2, { blockNumber, blockTag, assetGatewayUrls, name: name2, gatewayUrls, strict, universalResolverAddress }) { - const record = await getAction$1(client2, getEnsText, "getEnsText")({ - blockNumber, - blockTag, - key: "avatar", - name: name2, - universalResolverAddress, - gatewayUrls, - strict - }); - if (!record) - return null; - try { - return await parseAvatarRecord(client2, { - record, - gatewayUrls: assetGatewayUrls + async buildEIP6492Signature(signature2, status, chainId) { + const bootstrapBundle = await this.buildBootstrapTransactions(status, chainId); + if (bootstrapBundle.transactions.length === 0) { + throw new Error("Cannot build EIP-6492 signature without bootstrap transactions"); + } + const encoded = AbiCoder.defaultAbiCoder().encode(["address", "bytes", "bytes"], [bootstrapBundle.entrypoint, index$1$1.transaction.encodeBundleExecData(bootstrapBundle), signature2]); + return solidityPacked(["bytes", "bytes32"], [encoded, index$1$1.EIP6492.EIP_6492_SUFFIX]); + } + async editConfig(changes) { + const currentConfig = await this.status(0).then((s2) => s2.config); + const newConfig = this.coders.config.editConfig(currentConfig, _extends$8({}, changes, { + checkpoint: this.coders.config.checkpointOf(currentConfig) + 1n + })); + return this.updateConfig(newConfig); + } + async updateConfig(config2) { + if (!this.coders.config.isWalletConfig(config2)) { + throw new Error(`Invalid config for wallet ${this.address}`); + } + const nextImageHash = this.coders.config.imageHashOf(config2); + const updateStruct = this.coders.signature.hashSetImageHash(nextImageHash); + const signature2 = await this.signDigest(updateStruct, 0, false); + await this.tracker.savePresignedConfiguration({ + wallet: this.address, + nextConfig: config2, + signature: signature2 }); - } catch { - return null; - } -} -async function getEnsName(client2, { address, blockNumber, blockTag, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { - let universalResolverAddress = universalResolverAddress_; - if (!universalResolverAddress) { - if (!client2.chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - universalResolverAddress = getChainContractAddress({ - blockNumber, - chain: client2.chain, - contract: "ensUniversalResolver" + const reverseConfig = await this.tracker.configOfImageHash({ + imageHash: nextImageHash, + noCache: true }); + if (!reverseConfig || this.coders.config.imageHashOf(reverseConfig) !== nextImageHash) { + throw Error(`Reverse lookup failed for imageHash ${nextImageHash}`); + } } - const reverseNode = `${address.toLowerCase().substring(2)}.addr.reverse`; - try { - const readContractParameters = { - address: universalResolverAddress, - abi: universalResolverReverseAbi, - functionName: "reverse", - args: [toHex$1(packetToBytes(reverseNode))], - blockNumber, - blockTag + /** + * This method is used to bootstrap the wallet on a given chain. + * this deploys the wallets and executes all the necessary transactions + * for that wallet to start working with the given version. + * + * This usually involves: (a) deploying the wallet, (b) executing migrations + * + * Notice: It should NOT explicitly include chained signatures. Unless internally used + * by any of the migrations. + * + */ + async buildBootstrapTransactions(status, chainId) { + var _bundle$transactions; + const bundle = await this.orchestrator.buildDeployTransaction({ + chainId + }); + const transactions2 = (_bundle$transactions = bundle == null ? void 0 : bundle.transactions) != null ? _bundle$transactions : []; + if (!status.onChain.deployed) { + const deployTransaction = Wallet.buildDeployTransaction(status.original.context, status.original.imageHash); + transactions2.push(...deployTransaction.transactions); + } + transactions2.push(...status.signedMigrations.map((m2) => ({ + to: m2.tx.entrypoint, + data: index$1$1.transaction.encodeBundleExecData(m2.tx), + value: 0, + gasLimit: 0, + revertOnError: true, + delegateCall: false + }))); + const id2 = status.signedMigrations.length > 0 ? status.signedMigrations[0].tx.intent.id : index$1$1.transaction.subdigestOfGuestModuleTransactions(this.contexts[this.version].guestModule, chainId, transactions2); + const { + guestModule + } = this.contextFor(status.version); + return { + entrypoint: guestModule, + transactions: transactions2, + chainId, + intent: { + id: id2, + wallet: this.address + } }; - const readContractAction = getAction$1(client2, readContract$1, "readContract"); - const [name2, resolvedAddress] = gatewayUrls ? await readContractAction({ - ...readContractParameters, - args: [...readContractParameters.args, gatewayUrls] - }) : await readContractAction(readContractParameters); - if (address.toLowerCase() !== resolvedAddress.toLowerCase()) - return null; - return name2; - } catch (err) { - if (strict) - throw err; - if (isNullUniversalResolverError(err, "reverse")) - return null; - throw err; } -} -async function getEnsResolver(client2, { blockNumber, blockTag, name: name2, universalResolverAddress: universalResolverAddress_ }) { - let universalResolverAddress = universalResolverAddress_; - if (!universalResolverAddress) { - if (!client2.chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - universalResolverAddress = getChainContractAddress({ - blockNumber, - chain: client2.chain, - contract: "ensUniversalResolver" + async bootstrapTransactions(chainId, prestatus) { + const status = prestatus || await this.status(chainId); + return this.buildBootstrapTransactions(status, chainId); + } + async doBootstrap(chainId, feeQuote, prestatus) { + const bootstrapTxs = await this.bootstrapTransactions(chainId, prestatus); + return this.relayer(chainId).relay(_extends$8({}, bootstrapTxs, { + chainId + }), feeQuote); + } + signMessage(message, chainId, cantValidateBehavior = "ignore") { + return this.signDigest(keccak256(message), chainId, true, cantValidateBehavior); + } + async signTransactions(txs, chainId, pstatus, options) { + const status = pstatus || await this.status(chainId); + this.mustBeFullyMigrated(status); + const wallet = this.walletForStatus(chainId, status); + const metadata2 = { + address: this.address, + digest: "", + // Set in wallet.signTransactions + chainId, + config: { + version: this.version + }, + decorate: true, + cantValidateBehavior: "ignore" + }; + const nonceOptions = options != null && options.serial ? { + serial: true + } : (options == null ? void 0 : options.nonceSpace) !== void 0 ? { + space: options.nonceSpace + } : void 0; + const signed2 = await wallet.signTransactions(txs, nonceOptions, metadata2); + return _extends$8({}, signed2, { + signature: await this.decorateSignature(signed2.signature, status) }); } - const [resolverAddress] = await getAction$1(client2, readContract$1, "readContract")({ - address: universalResolverAddress, - abi: [ - { - inputs: [{ type: "bytes" }], - name: "findResolver", - outputs: [{ type: "address" }, { type: "bytes32" }], - stateMutability: "view", - type: "function" - } - ], - functionName: "findResolver", - args: [toHex$1(packetToBytes(name2))], - blockNumber, - blockTag - }); - return resolverAddress; -} -function createFilterRequestScope(client2, { method }) { - var _a2, _b2; - const requestMap = {}; - if (client2.transport.type === "fallback") - (_b2 = (_a2 = client2.transport).onResponse) == null ? void 0 : _b2.call(_a2, ({ method: method_, response: id2, status, transport }) => { - if (status === "success" && method === method_) - requestMap[id2] = transport.request; + async signMigrations(chainId, editConfig) { + const status = await this.status(chainId); + if (status.fullyMigrated) return false; + const wallet = this.walletForStatus(chainId, status); + const nextConfig = editConfig(wallet.config); + const signed2 = await this.migrator.signNextMigration(this.address, status.version, wallet, nextConfig); + if (!signed2) return false; + await this.tracker.saveWalletConfig({ + config: nextConfig }); - return (id2) => requestMap[id2] || client2.request; -} -async function createBlockFilter(client2) { - const getRequest = createFilterRequestScope(client2, { - method: "eth_newBlockFilter" - }); - const id2 = await client2.request({ - method: "eth_newBlockFilter" - }); - return { id: id2, request: getRequest(id2), type: "block" }; -} -class FilterTypeNotSupportedError extends BaseError$3 { - constructor(type) { - super(`Filter type "${type}" is not supported.`, { - name: "FilterTypeNotSupportedError" + const nextCoder = index$6.coderFor(nextConfig.version).config; + const nextImageHash = nextCoder.imageHashOf(nextConfig); + const reverseConfig = await this.tracker.configOfImageHash({ + imageHash: nextImageHash, + noCache: true }); - } -} -const docsPath$1 = "/docs/contract/encodeEventTopics"; -function encodeEventTopics(parameters) { - var _a2; - const { abi: abi2, eventName, args } = parameters; - let abiItem = abi2[0]; - if (eventName) { - const item2 = getAbiItem({ abi: abi2, name: eventName }); - if (!item2) - throw new AbiEventNotFoundError(eventName, { docsPath: docsPath$1 }); - abiItem = item2; - } - if (abiItem.type !== "event") - throw new AbiEventNotFoundError(void 0, { docsPath: docsPath$1 }); - const definition = formatAbiItem$1(abiItem); - const signature2 = toEventSelector(definition); - let topics = []; - if (args && "inputs" in abiItem) { - const indexedInputs = (_a2 = abiItem.inputs) == null ? void 0 : _a2.filter((param) => "indexed" in param && param.indexed); - const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? (indexedInputs == null ? void 0 : indexedInputs.map((x2) => args[x2.name])) ?? [] : []; - if (args_.length > 0) { - topics = (indexedInputs == null ? void 0 : indexedInputs.map((param, i) => { - if (Array.isArray(args_[i])) - return args_[i].map((_, j2) => encodeArg({ param, value: args_[i][j2] })); - return args_[i] ? encodeArg({ param, value: args_[i] }) : null; - })) ?? []; + if (!reverseConfig || nextCoder.imageHashOf(reverseConfig) !== nextImageHash) { + throw Error(`Reverse lookup failed for imageHash ${nextImageHash}`); } + await this.tracker.saveMigration(this.address, signed2, this.contexts); + return true; } - return [signature2, ...topics]; -} -function encodeArg({ param, value }) { - if (param.type === "string" || param.type === "bytes") - return keccak256(toBytes$1(value)); - if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) - throw new FilterTypeNotSupportedError(param.type); - return encodeAbiParameters([param], [value]); -} -async function createContractEventFilter(client2, parameters) { - const { address, abi: abi2, args, eventName, fromBlock, strict, toBlock } = parameters; - const getRequest = createFilterRequestScope(client2, { - method: "eth_newFilter" - }); - const topics = eventName ? encodeEventTopics({ - abi: abi2, - args, - eventName - }) : void 0; - const id2 = await client2.request({ - method: "eth_newFilter", - params: [ - { - address, - fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, - toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, - topics + async signAllMigrations(editConfig) { + var _this2 = this; + const failedChains = []; + const signedMigrations = await Promise.all(this.networks.map(async function(n2) { + try { + return await _this2.signMigrations(n2.chainId, editConfig); + } catch (error) { + console.warn(`Failed to sign migrations for chain ${n2.chainId}`, error); + failedChains.push(n2.chainId); + return null; } - ] - }); - return { - abi: abi2, - args, - eventName, - id: id2, - request: getRequest(id2), - strict: Boolean(strict), - type: "event" - }; -} -async function createEventFilter(client2, { address, args, event, events: events_, fromBlock, strict, toBlock } = {}) { - const events = events_ ?? (event ? [event] : void 0); - const getRequest = createFilterRequestScope(client2, { - method: "eth_newFilter" - }); - let topics = []; - if (events) { - const encoded = events.flatMap((event2) => encodeEventTopics({ - abi: [event2], - eventName: event2.name, - args })); - topics = [encoded]; - if (event) - topics = topics[0]; + const successfulSignedMigrations = signedMigrations.filter((migration2) => migration2 !== null); + return { + signedMigrations: successfulSignedMigrations, + failedChains + }; } - const id2 = await client2.request({ - method: "eth_newFilter", - params: [ - { - address, - fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, - toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, - ...topics.length ? { topics } : {} + async isMigratedAllChains() { + var _this3 = this; + const failedChains = []; + const statuses = await Promise.all(this.networks.map(async function(n2) { + try { + return await _this3.status(n2.chainId); + } catch (error) { + failedChains.push(n2.chainId); + console.warn(`Failed to get status for chain ${n2.chainId}`, error); + return { + fullyMigrated: true + }; } - ] - }); - return { - abi: events, - args, - eventName: event ? event.name : void 0, - fromBlock, - id: id2, - request: getRequest(id2), - strict: Boolean(strict), - toBlock, - type: "event" - }; -} -async function createPendingTransactionFilter(client2) { - const getRequest = createFilterRequestScope(client2, { - method: "eth_newPendingTransactionFilter" - }); - const id2 = await client2.request({ - method: "eth_newPendingTransactionFilter" - }); - return { id: id2, request: getRequest(id2), type: "transaction" }; -} -async function estimateContractGas(client2, parameters) { - const { abi: abi2, address, args, functionName, ...request } = parameters; - const data = encodeFunctionData({ - abi: abi2, - args, - functionName - }); - try { - const gas = await getAction$1(client2, estimateGas, "estimateGas")({ - data, - to: address, - ...request - }); - return gas; - } catch (error) { - const account2 = request.account ? parseAccount(request.account) : void 0; - throw getContractError(error, { - abi: abi2, - address, - args, - docsPath: "/docs/contract/estimateContractGas", - functionName, - sender: account2 == null ? void 0 : account2.address + })); + const migratedAllChains = statuses.every((s2) => s2.fullyMigrated); + return { + migratedAllChains, + failedChains + }; + } + async sendSignedTransactions(signedBundle, chainId, quote, pstatus, callback) { + if (!Array.isArray(signedBundle)) { + return this.sendSignedTransactions([signedBundle], chainId, quote, pstatus, callback); + } + const status = pstatus || await this.status(chainId); + this.mustBeFullyMigrated(status); + const decoratedBundle = await this.decorateTransactions(signedBundle, status, chainId); + callback == null || callback(decoratedBundle); + return this.relayer(chainId).relay(decoratedBundle, quote); + } + async fillGasLimits(txs, chainId, status) { + const wallet = this.walletForStatus(chainId, status || await this.status(chainId)); + return wallet.fillGasLimits(txs); + } + async gasRefundQuotes(txs, chainId, stubSignatureOverrides, status, options) { + const wstatus = status || await this.status(chainId); + const wallet = this.walletForStatus(chainId, wstatus); + const predecorated = await this.predecorateTransactions(txs, wstatus, chainId); + const transactions2 = index$1$1.transaction.fromTransactionish(this.address, predecorated); + const stubSignature = wallet.coders.config.buildStubSignature(wallet.config, stubSignatureOverrides); + const intentId = hexlify(randomBytes(32)); + const signedBundle = { + chainId, + intent: { + id: intentId, + wallet: this.address + }, + signature: stubSignature, + transactions: transactions2, + entrypoint: this.address, + nonce: 0 + // The relayer also ignored the nonce + }; + const decoratedBundle = await this.decorateTransactions(signedBundle, wstatus); + const data = index$1$1.transaction.encodeBundleExecData(decoratedBundle); + const res = await this.relayer(chainId).getFeeOptionsRaw(decoratedBundle.entrypoint, data, options); + return _extends$8({}, res, { + decorated: decoratedBundle }); } -} -async function getBlobBaseFee(client2) { - const baseFee = await client2.request({ - method: "eth_blobBaseFee" - }); - return BigInt(baseFee); -} -const promiseCache$1 = /* @__PURE__ */ new Map(); -const responseCache = /* @__PURE__ */ new Map(); -function getCache(cacheKey2) { - const buildCache = (cacheKey3, cache2) => ({ - clear: () => cache2.delete(cacheKey3), - get: () => cache2.get(cacheKey3), - set: (data) => cache2.set(cacheKey3, data) - }); - const promise = buildCache(cacheKey2, promiseCache$1); - const response = buildCache(cacheKey2, responseCache); - return { - clear: () => { - promise.clear(); - response.clear(); - }, - promise, - response - }; -} -async function withCache(fn, { cacheKey: cacheKey2, cacheTime = Number.POSITIVE_INFINITY }) { - const cache2 = getCache(cacheKey2); - const response = cache2.response.get(); - if (response && cacheTime > 0) { - const age = (/* @__PURE__ */ new Date()).getTime() - response.created.getTime(); - if (age < cacheTime) - return response.data; + async prepareTransactions(args) { + const status = await this.status(args.chainId); + const transactions2 = await this.fillGasLimits(args.txs, args.chainId, status); + const gasRefundQuote = await this.gasRefundQuotes(transactions2, args.chainId, args.stubSignatureOverrides, status, { + simulate: args.simulateForFeeOptions + }); + const flatDecorated = index$1$1.transaction.unwind(this.address, gasRefundQuote.decorated.transactions); + return { + transactions: transactions2, + flatDecorated, + feeOptions: gasRefundQuote.options, + feeQuote: gasRefundQuote.quote + }; } - let promise = cache2.promise.get(); - if (!promise) { - promise = fn(); - cache2.promise.set(promise); + async sendTransaction(txs, chainId, quote, skipPreDecorate = false, callback, options) { + const status = await this.status(chainId); + const predecorated = skipPreDecorate ? txs : await this.predecorateTransactions(txs, status, chainId); + const hasTxs = index$1$1.transaction.fromTransactionish(this.address, predecorated).length > 0; + const signed2 = hasTxs ? await this.signTransactions(predecorated, chainId, void 0, options) : void 0; + const childBundles = await this.orchestrator.predecorateSignedTransactions({ + chainId + }); + const bundles = []; + if (signed2 !== void 0 && signed2.transactions.length > 0) { + bundles.push(signed2); + } + bundles.push(...childBundles.filter((b2) => b2.transactions.length > 0)); + return this.sendSignedTransactions(bundles, chainId, quote, void 0, callback); } - try { - const data = await promise; - cache2.response.set({ created: /* @__PURE__ */ new Date(), data }); - return data; - } finally { - cache2.promise.clear(); + async signTypedData(domain2, types2, message, chainId, cantValidateBehavior = "ignore") { + const digest = encodeTypedDataDigest({ + domain: domain2, + types: types2, + message + }); + return this.signDigest(digest, chainId, true, cantValidateBehavior); } -} -const cacheKey = (id2) => `blockNumber.${id2}`; -async function getBlockNumber(client2, { cacheTime = client2.cacheTime } = {}) { - const blockNumberHex = await withCache(() => client2.request({ - method: "eth_blockNumber" - }), { cacheKey: cacheKey(client2.uid), cacheTime }); - return BigInt(blockNumberHex); -} -async function getBlockTransactionCount(client2, { blockHash, blockNumber, blockTag = "latest" } = {}) { - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - let count2; - if (blockHash) { - count2 = await client2.request({ - method: "eth_getBlockTransactionCountByHash", - params: [blockHash] - }, { dedupe: true }); - } else { - count2 = await client2.request({ - method: "eth_getBlockTransactionCountByNumber", - params: [blockNumberHex || blockTag] - }, { dedupe: Boolean(blockNumberHex) }); + async getSigners() { + var _this4 = this; + const last = (ts) => ts.length ? ts[ts.length - 1] : void 0; + return (await Promise.all(this.networks.map(async function({ + chainId, + name: name2 + }) { + try { + var _last; + const status = await _this4.status(chainId); + let latestImageHash = (_last = last(status.presignedConfigurations)) == null ? void 0 : _last.nextImageHash; + if (!latestImageHash) { + if (status.onChain.version !== status.version) { + const migration2 = last(status.signedMigrations); + if (migration2) { + const { + toVersion, + toConfig + } = migration2; + const _coder = index$6.genericCoderFor(toVersion); + latestImageHash = _coder.config.imageHashOf(toConfig); + } + } + } + if (!latestImageHash) { + latestImageHash = status.onChain.imageHash; + } + const latestConfig = await _this4.tracker.configOfImageHash({ + imageHash: latestImageHash + }); + if (!latestConfig) { + throw new Error(`unable to find config for image hash ${latestImageHash}`); + } + const coder = index$6.genericCoderFor(latestConfig.version); + const signers = coder.config.signersOf(latestConfig); + return signers.map((signer2) => _extends$8({}, signer2, { + network: chainId + })); + } catch (error) { + console.warn(`unable to get signers on network ${chainId} ${name2}`, error); + return []; + } + }))).flat(); + } + async getAllSigners() { + var _this5 = this; + const allSigners = []; + await Promise.all(this.networks.map(async function(network2) { + const chainId = network2.chainId; + const status = await _this5.status(chainId, true); + const fullChain = [status.onChain.imageHash, ...status.onChain.version !== status.version ? status.signedMigrations.map((m2) => index$6.coderFor(m2.toVersion).config.imageHashOf(m2.toConfig)) : [], ...status.presignedConfigurations.map((update) => update.nextImageHash)]; + return Promise.all(fullChain.map(async function(nextImageHash, iconf) { + const isLast = iconf === fullChain.length - 1; + const config2 = await _this5.tracker.configOfImageHash({ + imageHash: nextImageHash + }); + if (!config2) { + console.warn(`AllSigners may be incomplete, config not found for imageHash ${nextImageHash}`); + return; + } + const coder = index$6.genericCoderFor(config2.version); + const signers = coder.config.signersOf(config2); + signers.forEach((signer2) => { + const exists2 = allSigners.find((s2) => s2.address === signer2.address && s2.network === chainId); + if (exists2 && isLast && exists2.flaggedForRemoval) { + exists2.flaggedForRemoval = false; + return; + } + if (exists2) return; + allSigners.push({ + address: signer2.address, + weight: signer2.weight, + network: chainId, + flaggedForRemoval: !isLast + }); + }); + })); + })); + return allSigners; } - return hexToNumber$1(count2); } -async function getCode(client2, { address, blockNumber, blockTag = "latest" }) { - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - const hex2 = await client2.request({ - method: "eth_getCode", - params: [address, blockNumberHex || blockTag] - }, { dedupe: Boolean(blockNumberHex) }); - if (hex2 === "0x") - return void 0; - return hex2; +function isAccount(value) { + return value instanceof Account; } -function isAddressEqual(a2, b2) { - if (!isAddress(a2, { strict: false })) - throw new InvalidAddressError({ address: a2 }); - if (!isAddress(b2, { strict: false })) - throw new InvalidAddressError({ address: b2 }); - return a2.toLowerCase() === b2.toLowerCase(); +const account$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Account, + isAccount +}, Symbol.toStringTag, { value: "Module" })); +function _extends$7() { + _extends$7 = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends$7.apply(this, arguments); } -const docsPath = "/docs/contract/decodeEventLog"; -function decodeEventLog(parameters) { - const { abi: abi2, data, strict: strict_, topics } = parameters; - const strict = strict_ ?? true; - const [signature2, ...argTopics] = topics; - if (!signature2) - throw new AbiEventSignatureEmptyTopicsError({ docsPath }); - const abiItem = (() => { - if (abi2.length === 1) - return abi2[0]; - return abi2.find((x2) => x2.type === "event" && signature2 === toEventSelector(formatAbiItem$1(x2))); - })(); - if (!(abiItem && "name" in abiItem) || abiItem.type !== "event") - throw new AbiEventSignatureNotFoundError(signature2, { docsPath }); - const { name: name2, inputs } = abiItem; - const isUnnamed = inputs == null ? void 0 : inputs.some((x2) => !("name" in x2 && x2.name)); - let args = isUnnamed ? [] : {}; - const indexedInputs = inputs.filter((x2) => "indexed" in x2 && x2.indexed); - for (let i = 0; i < indexedInputs.length; i++) { - const param = indexedInputs[i]; - const topic = argTopics[i]; - if (!topic) - throw new DecodeLogTopicsMismatch({ - abiItem, - param +const WebRPCVersion$1 = "v1"; +const WebRPCSchemaVersion$1 = "v0.4.0"; +const WebRPCSchemaHash$1 = "9accea267e7db3d66f40d5e0f27db92eb5a29e2f"; +let ContractType$1 = /* @__PURE__ */ function(ContractType2) { + ContractType2["UNKNOWN"] = "UNKNOWN"; + ContractType2["NATIVE"] = "NATIVE"; + ContractType2["ERC20"] = "ERC20"; + ContractType2["ERC721"] = "ERC721"; + ContractType2["ERC1155"] = "ERC1155"; + ContractType2["SEQUENCE_WALLET"] = "SEQUENCE_WALLET"; + ContractType2["ERC20_BRIDGE"] = "ERC20_BRIDGE"; + ContractType2["ERC721_BRIDGE"] = "ERC721_BRIDGE"; + ContractType2["ERC1155_BRIDGE"] = "ERC1155_BRIDGE"; + ContractType2["SEQ_MARKETPLACE"] = "SEQ_MARKETPLACE"; + return ContractType2; +}({}); +let EventLogType = /* @__PURE__ */ function(EventLogType2) { + EventLogType2["UNKNOWN"] = "UNKNOWN"; + EventLogType2["BLOCK_ADDED"] = "BLOCK_ADDED"; + EventLogType2["BLOCK_REMOVED"] = "BLOCK_REMOVED"; + return EventLogType2; +}({}); +let EventLogDataType = /* @__PURE__ */ function(EventLogDataType2) { + EventLogDataType2["EVENT"] = "EVENT"; + EventLogDataType2["TOKEN_TRANSFER"] = "TOKEN_TRANSFER"; + EventLogDataType2["NATIVE_TOKEN_TRANSFER"] = "NATIVE_TOKEN_TRANSFER"; + EventLogDataType2["SEQUENCE_TXN"] = "SEQUENCE_TXN"; + return EventLogDataType2; +}({}); +let OrderStatus = /* @__PURE__ */ function(OrderStatus2) { + OrderStatus2["OPEN"] = "OPEN"; + OrderStatus2["CLOSED"] = "CLOSED"; + OrderStatus2["CANCELLED"] = "CANCELLED"; + return OrderStatus2; +}({}); +let TxnTransferType = /* @__PURE__ */ function(TxnTransferType2) { + TxnTransferType2["UNKNOWN"] = "UNKNOWN"; + TxnTransferType2["SEND"] = "SEND"; + TxnTransferType2["RECEIVE"] = "RECEIVE"; + return TxnTransferType2; +}({}); +let TransactionStatus = /* @__PURE__ */ function(TransactionStatus2) { + TransactionStatus2["FAILED"] = "FAILED"; + TransactionStatus2["SUCCESSFUL"] = "SUCCESSFUL"; + return TransactionStatus2; +}({}); +let TransactionType = /* @__PURE__ */ function(TransactionType2) { + TransactionType2["LegacyTxnType"] = "LegacyTxnType"; + TransactionType2["AccessListTxnType"] = "AccessListTxnType"; + TransactionType2["DynamicFeeTxnType"] = "DynamicFeeTxnType"; + return TransactionType2; +}({}); +let SortOrder = /* @__PURE__ */ function(SortOrder2) { + SortOrder2["DESC"] = "DESC"; + SortOrder2["ASC"] = "ASC"; + return SortOrder2; +}({}); +class Indexer { + constructor(hostname, fetch2) { + this.hostname = void 0; + this.fetch = void 0; + this.path = "/rpc/Indexer/"; + this.ping = (headers, signal) => { + return this.fetch(this.url("Ping"), createHTTPRequest$5({}, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - args[isUnnamed ? i : param.name || i] = decodeTopic({ param, value: topic }); + }; + this.version = (headers, signal) => { + return this.fetch(this.url("Version"), createHTTPRequest$5({}, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + version: _data6.version + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.runtimeStatus = (headers, signal) => { + return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$5({}, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getChainID = (headers, signal) => { + return this.fetch(this.url("GetChainID"), createHTTPRequest$5({}, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + chainID: _data6.chainID + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getEtherBalance = (args, headers, signal) => { + return this.fetch(this.url("GetEtherBalance"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + balance: _data6.balance + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getTokenBalances = (args, headers, signal) => { + return this.fetch(this.url("GetTokenBalances"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + page: _data6.page, + balances: _data6.balances + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getTokenSupplies = (args, headers, signal) => { + return this.fetch(this.url("GetTokenSupplies"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + page: _data6.page, + contractType: _data6.contractType, + tokenIDs: _data6.tokenIDs + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getTokenSuppliesMap = (args, headers, signal) => { + return this.fetch(this.url("GetTokenSuppliesMap"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + supplies: _data6.supplies + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getBalanceUpdates = (args, headers, signal) => { + return this.fetch(this.url("GetBalanceUpdates"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + page: _data6.page, + balances: _data6.balances + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getTransactionHistory = (args, headers, signal) => { + return this.fetch(this.url("GetTransactionHistory"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + page: _data6.page, + transactions: _data6.transactions + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.syncBalance = (args, headers, signal) => { + return this.fetch(this.url("SyncBalance"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.fetchTransactionReceipt = (args, headers, signal) => { + return this.fetch(this.url("FetchTransactionReceipt"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + receipt: _data6.receipt + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getOrderbookOrders = (args, headers, signal) => { + return this.fetch(this.url("GetOrderbookOrders"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + page: _data6.page, + orders: _data6.orders + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getTopOrders = (args, headers, signal) => { + return this.fetch(this.url("GetTopOrders"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + orders: _data6.orders + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.fetchTransactionReceiptWithFilter = (args, headers, signal) => { + return this.fetch(this.url("FetchTransactionReceiptWithFilter"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + receipt: _data6.receipt + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getAllWebhookListeners = (args, headers, signal) => { + return this.fetch(this.url("GetAllWebhookListeners"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + listeners: _data6.listeners + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getWebhookListener = (args, headers, signal) => { + return this.fetch(this.url("GetWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + listener: _data6.listener + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.addWebhookListener = (args, headers, signal) => { + return this.fetch(this.url("AddWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + status: _data6.status, + listener: _data6.listener + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.updateWebhookListener = (args, headers, signal) => { + return this.fetch(this.url("UpdateWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.removeWebhookListener = (args, headers, signal) => { + return this.fetch(this.url("RemoveWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.toggleWebhookListener = (args, headers, signal) => { + return this.fetch(this.url("ToggleWebhookListener"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + webhookListener: _data6.webhookListener + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.pauseAllWebhookListeners = (args, headers, signal) => { + return this.fetch(this.url("PauseAllWebhookListeners"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.resumeAllWebhookListeners = (args, headers, signal) => { + return this.fetch(this.url("ResumeAllWebhookListeners"), createHTTPRequest$5(args, headers, signal)).then((res) => { + return buildResponse$5(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$5.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.subscribeReceipts = (args, options) => { + const _fetch = () => this.fetch(this.url("SubscribeReceipts"), createHTTPRequest$5(args, options.headers, options.signal)).then(async function(res) { + await sseResponse(res, options, _fetch); + }, (error) => { + options.onError(error, _fetch); + }); + return _fetch(); + }; + this.subscribeEvents = (args, options) => { + const _fetch = () => this.fetch(this.url("SubscribeEvents"), createHTTPRequest$5(args, options.headers, options.signal)).then(async function(res) { + await sseResponse(res, options, _fetch); + }, (error) => { + options.onError(error, _fetch); + }); + return _fetch(); + }; + this.subscribeBalanceUpdates = (args, options) => { + const _fetch = () => this.fetch(this.url("SubscribeBalanceUpdates"), createHTTPRequest$5(args, options.headers, options.signal)).then(async function(res) { + await sseResponse(res, options, _fetch); + }, (error) => { + options.onError(error, _fetch); + }); + return _fetch(); + }; + this.hostname = hostname; + this.fetch = (input2, init2) => fetch2(input2, init2); + } + url(name2) { + return this.hostname + this.path + name2; + } +} +const sseResponse = async (res, options, retryFetch) => { + const { + onMessage, + onOpen, + onClose, + onError + } = options; + if (!res.ok) { + try { + await buildResponse$5(res); + } catch (error) { + onError(error, retryFetch); + } + return; } - const nonIndexedInputs = inputs.filter((x2) => !("indexed" in x2 && x2.indexed)); - if (nonIndexedInputs.length > 0) { - if (data && data !== "0x") { + if (!res.body) { + onError(WebrpcBadResponseError$5.new({ + status: res.status, + cause: "Invalid response, missing body" + }), retryFetch); + return; + } + onOpen && onOpen(); + const reader2 = res.body.getReader(); + const decoder = new TextDecoder(); + let buffer2 = ""; + let lastReadTime = Date.now(); + const timeout = (10 + 1) * 1e3; + let intervalId; + try { + intervalId = setInterval(() => { + if (Date.now() - lastReadTime > timeout) { + throw WebrpcStreamLostError$5.new({ + cause: "Stream timed out" + }); + } + }, timeout); + while (true) { + let value; + let done; try { - const decodedData = decodeAbiParameters(nonIndexedInputs, data); - if (decodedData) { - if (isUnnamed) - args = [...args, ...decodedData]; - else { - for (let i = 0; i < nonIndexedInputs.length; i++) { - args[nonIndexedInputs[i].name] = decodedData[i]; - } - } + ; + ({ + value, + done + } = await reader2.read()); + lastReadTime = Date.now(); + buffer2 += decoder.decode(value, { + stream: true + }); + } catch (error) { + let message = ""; + if (error instanceof Error) { + message = error.message; } - } catch (err) { - if (strict) { - if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError) - throw new DecodeLogDataMismatch({ - abiItem, - data, - params: nonIndexedInputs, - size: size$5(data) - }); - throw err; + if (error instanceof DOMException && error.name === "AbortError") { + onError(WebrpcRequestFailedError$5.new({ + message: "AbortError", + cause: `AbortError: ${message}` + }), () => { + throw new Error("Abort signal cannot be used to reconnect"); + }); + } else { + onError(WebrpcStreamLostError$5.new({ + cause: `reader.read(): ${message}` + }), retryFetch); } + return; } - } else if (strict) { - throw new DecodeLogDataMismatch({ - abiItem, - data: "0x", - params: nonIndexedInputs, - size: 0 - }); + let lines = buffer2.split("\n"); + for (let i = 0; i < lines.length - 1; i++) { + if (lines[i].length == 0) { + continue; + } + let data; + try { + data = JSON.parse(lines[i]); + if (data.hasOwnProperty("webrpcError")) { + const error = data.webrpcError; + const code2 = typeof error.code === "number" ? error.code : 0; + onError((webrpcErrorByCode$5[code2] || WebrpcError$5).new(error), retryFetch); + return; + } + } catch (error) { + if (error instanceof Error && error.message === "Abort signal cannot be used to reconnect") { + throw error; + } + onError(WebrpcBadResponseError$5.new({ + status: res.status, + // @ts-ignore + cause: `JSON.parse(): ${error.message}` + }), retryFetch); + } + onMessage(data); + } + if (!done) { + buffer2 = lines[lines.length - 1]; + continue; + } + onClose && onClose(); + return; + } + } catch (error) { + if (error instanceof WebrpcStreamLostError$5) { + onError(error, retryFetch); + } else { + throw error; } + } finally { + clearInterval(intervalId); } +}; +const createHTTPRequest$5 = (body = {}, headers = {}, signal = null) => { return { - eventName: name2, - args: Object.values(args).length > 0 ? args : void 0 + method: "POST", + headers: _extends$7({}, headers, { + "Content-Type": "application/json" + }), + body: JSON.stringify(body || {}), + signal }; -} -function decodeTopic({ param, value }) { - if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) - return value; - const decodedArg = decodeAbiParameters([param], value) || []; - return decodedArg[0]; -} -function parseEventLogs(parameters) { - const { abi: abi2, args, logs, strict = true } = parameters; - const eventName = (() => { - if (!parameters.eventName) - return void 0; - if (Array.isArray(parameters.eventName)) - return parameters.eventName; - return [parameters.eventName]; - })(); - return logs.map((log) => { - var _a2; +}; +const buildResponse$5 = (res) => { + return res.text().then((text2) => { + let data; try { - const abiItem = abi2.find((abiItem2) => abiItem2.type === "event" && log.topics[0] === toEventSelector(abiItem2)); - if (!abiItem) - return null; - const event = decodeEventLog({ - ...log, - abi: [abiItem], - strict - }); - if (eventName && !eventName.includes(event.eventName)) - return null; - if (!includesArgs({ - args: event.args, - inputs: abiItem.inputs, - matchArgs: args - })) - return null; - return { ...event, ...log }; - } catch (err) { - let eventName2; - let isUnnamed; - if (err instanceof AbiEventSignatureNotFoundError) - return null; - if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { - if (strict) - return null; - eventName2 = err.abiItem.name; - isUnnamed = (_a2 = err.abiItem.inputs) == null ? void 0 : _a2.some((x2) => !("name" in x2 && x2.name)); + data = JSON.parse(text2); + } catch (error) { + let message = ""; + if (error instanceof Error) { + message = error.message; } - return { ...log, args: isUnnamed ? [] : {}, eventName: eventName2 }; + throw WebrpcBadResponseError$5.new({ + status: res.status, + cause: `JSON.parse(): ${message}: response text: ${text2}` + }); } - }).filter(Boolean); -} -function includesArgs(parameters) { - const { args, inputs, matchArgs } = parameters; - if (!matchArgs) - return true; - if (!args) - return false; - function isEqual(input2, value, arg) { - try { - if (input2.type === "address") - return isAddressEqual(value, arg); - if (input2.type === "string" || input2.type === "bytes") - return keccak256(toBytes$1(value)) === arg; - return value === arg; - } catch { - return false; + if (!res.ok) { + const code2 = typeof data.code === "number" ? data.code : 0; + throw (webrpcErrorByCode$5[code2] || WebrpcError$5).new(data); } + return data; + }); +}; +let WebrpcError$5 = class WebrpcError3 extends Error { + constructor(name2, code2, message, status, cause) { + super(message); + this.name = void 0; + this.code = void 0; + this.message = void 0; + this.status = void 0; + this.cause = void 0; + this.msg = void 0; + this.name = name2 || "WebrpcError"; + this.code = typeof code2 === "number" ? code2 : 0; + this.message = message || `endpoint error ${this.code}`; + this.msg = this.message; + this.status = typeof status === "number" ? status : 0; + this.cause = cause; + Object.setPrototypeOf(this, WebrpcError3.prototype); } - if (Array.isArray(args) && Array.isArray(matchArgs)) { - return matchArgs.every((value, index2) => { - if (value === null) - return true; - const input2 = inputs[index2]; - if (!input2) - return false; - const value_ = Array.isArray(value) ? value : [value]; - return value_.some((value2) => isEqual(input2, value2, args[index2])); - }); + static new(payload) { + return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + } +}; +let WebrpcEndpointError$5 = class WebrpcEndpointError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcEndpointError3.prototype); + } +}; +let WebrpcRequestFailedError$5 = class WebrpcRequestFailedError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcRequestFailedError3.prototype); + } +}; +let WebrpcBadRouteError$5 = class WebrpcBadRouteError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRouteError3.prototype); + } +}; +let WebrpcBadMethodError$5 = class WebrpcBadMethodError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadMethodError3.prototype); + } +}; +let WebrpcBadRequestError$5 = class WebrpcBadRequestError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRequestError3.prototype); + } +}; +let WebrpcBadResponseError$5 = class WebrpcBadResponseError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadResponseError3.prototype); + } +}; +let WebrpcServerPanicError$5 = class WebrpcServerPanicError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcServerPanicError3.prototype); + } +}; +let WebrpcInternalErrorError$5 = class WebrpcInternalErrorError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcInternalErrorError3.prototype); + } +}; +let WebrpcClientDisconnectedError$5 = class WebrpcClientDisconnectedError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcClientDisconnectedError3.prototype); + } +}; +let WebrpcStreamLostError$5 = class WebrpcStreamLostError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamLostError3.prototype); + } +}; +let WebrpcStreamFinishedError$5 = class WebrpcStreamFinishedError3 extends WebrpcError$5 { + constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamFinishedError3.prototype); + } +}; +let UnauthorizedError$4 = class UnauthorizedError3 extends WebrpcError$5 { + constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, UnauthorizedError3.prototype); + } +}; +let PermissionDeniedError$2 = class PermissionDeniedError3 extends WebrpcError$5 { + constructor(name2 = "PermissionDenied", code2 = 1001, message = "Permission denied", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, PermissionDeniedError3.prototype); + } +}; +let SessionExpiredError$3 = class SessionExpiredError2 extends WebrpcError$5 { + constructor(name2 = "SessionExpired", code2 = 1002, message = "Session expired", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, SessionExpiredError2.prototype); + } +}; +let MethodNotFoundError$1 = class MethodNotFoundError2 extends WebrpcError$5 { + constructor(name2 = "MethodNotFound", code2 = 1003, message = "Method not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, MethodNotFoundError2.prototype); + } +}; +let RequestConflictError$1 = class RequestConflictError extends WebrpcError$5 { + constructor(name2 = "RequestConflict", code2 = 1004, message = "Conflict with target resource", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, RequestConflictError.prototype); + } +}; +let AbortedError$1 = class AbortedError3 extends WebrpcError$5 { + constructor(name2 = "Aborted", code2 = 1005, message = "Request aborted", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, AbortedError3.prototype); + } +}; +let TimeoutError$1 = class TimeoutError2 extends WebrpcError$5 { + constructor(name2 = "Timeout", code2 = 2e3, message = "Request timed out", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, TimeoutError2.prototype); + } +}; +let InvalidArgumentError$3 = class InvalidArgumentError3 extends WebrpcError$5 { + constructor(name2 = "InvalidArgument", code2 = 2001, message = "Invalid argument", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, InvalidArgumentError3.prototype); + } +}; +let UnavailableError$1 = class UnavailableError3 extends WebrpcError$5 { + constructor(name2 = "Unavailable", code2 = 2002, message = "Unavailable resource", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, UnavailableError3.prototype); + } +}; +let QueryFailedError$3 = class QueryFailedError3 extends WebrpcError$5 { + constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, QueryFailedError3.prototype); + } +}; +class ResourceExhaustedError extends WebrpcError$5 { + constructor(name2 = "ResourceExhausted", code2 = 2004, message = "Resource exhausted", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, ResourceExhaustedError.prototype); } - if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs)) - return Object.entries(matchArgs).every(([key, value]) => { - if (value === null) - return true; - const input2 = inputs.find((input3) => input3.name === key); - if (!input2) - return false; - const value_ = Array.isArray(value) ? value : [value]; - return value_.some((value2) => isEqual(input2, value2, args[key])); - }); - return false; -} -function formatLog(log, { args, eventName } = {}) { - return { - ...log, - blockHash: log.blockHash ? log.blockHash : null, - blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null, - logIndex: log.logIndex ? Number(log.logIndex) : null, - transactionHash: log.transactionHash ? log.transactionHash : null, - transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null, - ...eventName ? { args, eventName } : {} - }; } -async function getLogs(client2, { address, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) { - const strict = strict_ ?? false; - const events = events_ ?? (event ? [event] : void 0); - let topics = []; - if (events) { - const encoded = events.flatMap((event2) => encodeEventTopics({ - abi: [event2], - eventName: event2.name, - args: events_ ? void 0 : args - })); - topics = [encoded]; - if (event) - topics = topics[0]; +let NotFoundError$4 = class NotFoundError3 extends WebrpcError$5 { + constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, NotFoundError3.prototype); } - let logs; - if (blockHash) { - logs = await client2.request({ - method: "eth_getLogs", - params: [{ address, topics, blockHash }] - }); - } else { - logs = await client2.request({ - method: "eth_getLogs", - params: [ - { - address, - topics, - fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, - toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock - } - ] - }); +}; +let ProjectNotFoundError$1 = class ProjectNotFoundError extends WebrpcError$5 { + constructor(name2 = "ProjectNotFound", code2 = 3002, message = "Project not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, ProjectNotFoundError.prototype); + } +}; +class MetadataCallFailedError extends WebrpcError$5 { + constructor(name2 = "MetadataCallFailed", code2 = 3003, message = "Metadata service call failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, MetadataCallFailedError.prototype); + } +} +let errors$1 = /* @__PURE__ */ function(errors2) { + errors2["WebrpcEndpoint"] = "WebrpcEndpoint"; + errors2["WebrpcRequestFailed"] = "WebrpcRequestFailed"; + errors2["WebrpcBadRoute"] = "WebrpcBadRoute"; + errors2["WebrpcBadMethod"] = "WebrpcBadMethod"; + errors2["WebrpcBadRequest"] = "WebrpcBadRequest"; + errors2["WebrpcBadResponse"] = "WebrpcBadResponse"; + errors2["WebrpcServerPanic"] = "WebrpcServerPanic"; + errors2["WebrpcInternalError"] = "WebrpcInternalError"; + errors2["WebrpcClientDisconnected"] = "WebrpcClientDisconnected"; + errors2["WebrpcStreamLost"] = "WebrpcStreamLost"; + errors2["WebrpcStreamFinished"] = "WebrpcStreamFinished"; + errors2["Unauthorized"] = "Unauthorized"; + errors2["PermissionDenied"] = "PermissionDenied"; + errors2["SessionExpired"] = "SessionExpired"; + errors2["MethodNotFound"] = "MethodNotFound"; + errors2["RequestConflict"] = "RequestConflict"; + errors2["Aborted"] = "Aborted"; + errors2["Timeout"] = "Timeout"; + errors2["InvalidArgument"] = "InvalidArgument"; + errors2["Unavailable"] = "Unavailable"; + errors2["QueryFailed"] = "QueryFailed"; + errors2["ResourceExhausted"] = "ResourceExhausted"; + errors2["NotFound"] = "NotFound"; + errors2["ProjectNotFound"] = "ProjectNotFound"; + errors2["MetadataCallFailed"] = "MetadataCallFailed"; + return errors2; +}({}); +const webrpcErrorByCode$5 = { + [0]: WebrpcEndpointError$5, + [-1]: WebrpcRequestFailedError$5, + [-2]: WebrpcBadRouteError$5, + [-3]: WebrpcBadMethodError$5, + [-4]: WebrpcBadRequestError$5, + [-5]: WebrpcBadResponseError$5, + [-6]: WebrpcServerPanicError$5, + [-7]: WebrpcInternalErrorError$5, + [-8]: WebrpcClientDisconnectedError$5, + [-9]: WebrpcStreamLostError$5, + [-10]: WebrpcStreamFinishedError$5, + [1e3]: UnauthorizedError$4, + [1001]: PermissionDeniedError$2, + [1002]: SessionExpiredError$3, + [1003]: MethodNotFoundError$1, + [1004]: RequestConflictError$1, + [1005]: AbortedError$1, + [2e3]: TimeoutError$1, + [2001]: InvalidArgumentError$3, + [2002]: UnavailableError$1, + [2003]: QueryFailedError$3, + [2004]: ResourceExhaustedError, + [3e3]: NotFoundError$4, + [3002]: ProjectNotFoundError$1, + [3003]: MetadataCallFailedError +}; +const fetch$4 = globalThis.fetch; +class SequenceIndexer extends Indexer { + constructor(hostname, projectAccessKey2, jwtAuth) { + super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, fetch$4); + this.projectAccessKey = projectAccessKey2; + this.jwtAuth = jwtAuth; + this._fetch = (input2, init2) => { + const headers = {}; + const jwtAuth2 = this.jwtAuth; + const projectAccessKey3 = this.projectAccessKey; + if (jwtAuth2 && jwtAuth2.length > 0) { + headers["Authorization"] = `BEARER ${jwtAuth2}`; + } + if (projectAccessKey3 && projectAccessKey3.length > 0) { + headers["X-Access-Key"] = projectAccessKey3; + } + init2.headers = _extends$7({}, init2.headers, headers); + return fetch$4(input2, init2); + }; + this.fetch = this._fetch; } - const formattedLogs = logs.map((log) => formatLog(log)); - if (!events) - return formattedLogs; - return parseEventLogs({ - abi: events, - args, - logs: formattedLogs, - strict - }); -} -async function getContractEvents(client2, parameters) { - const { abi: abi2, address, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters; - const event = eventName ? getAbiItem({ abi: abi2, name: eventName }) : void 0; - const events = !event ? abi2.filter((x2) => x2.type === "event") : void 0; - return getAction$1(client2, getLogs, "getLogs")({ - address, - args, - blockHash, - event, - events, - fromBlock, - toBlock, - strict - }); } -class Eip712DomainNotFoundError extends BaseError$3 { - constructor({ address }) { - super(`No EIP-712 domain found on contract "${address}".`, { - metaMessages: [ - "Ensure that:", - `- The contract is deployed at the address "${address}".`, - "- `eip712Domain()` function exists on the contract.", - "- `eip712Domain()` function matches signature to ERC-5267 specification." - ], - name: "Eip712DomainNotFoundError" - }); - } +const indexer$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + AbortedError: AbortedError$1, + ContractType: ContractType$1, + EventLogDataType, + EventLogType, + Indexer, + InvalidArgumentError: InvalidArgumentError$3, + MetadataCallFailedError, + MethodNotFoundError: MethodNotFoundError$1, + NotFoundError: NotFoundError$4, + OrderStatus, + PermissionDeniedError: PermissionDeniedError$2, + ProjectNotFoundError: ProjectNotFoundError$1, + QueryFailedError: QueryFailedError$3, + RequestConflictError: RequestConflictError$1, + ResourceExhaustedError, + SequenceIndexer, + SessionExpiredError: SessionExpiredError$3, + SortOrder, + TimeoutError: TimeoutError$1, + TransactionStatus, + TransactionType, + TxnTransferType, + UnauthorizedError: UnauthorizedError$4, + UnavailableError: UnavailableError$1, + WebRPCSchemaHash: WebRPCSchemaHash$1, + WebRPCSchemaVersion: WebRPCSchemaVersion$1, + WebRPCVersion: WebRPCVersion$1, + WebrpcBadMethodError: WebrpcBadMethodError$5, + WebrpcBadRequestError: WebrpcBadRequestError$5, + WebrpcBadResponseError: WebrpcBadResponseError$5, + WebrpcBadRouteError: WebrpcBadRouteError$5, + WebrpcClientDisconnectedError: WebrpcClientDisconnectedError$5, + WebrpcEndpointError: WebrpcEndpointError$5, + WebrpcError: WebrpcError$5, + WebrpcInternalErrorError: WebrpcInternalErrorError$5, + WebrpcRequestFailedError: WebrpcRequestFailedError$5, + WebrpcServerPanicError: WebrpcServerPanicError$5, + WebrpcStreamFinishedError: WebrpcStreamFinishedError$5, + WebrpcStreamLostError: WebrpcStreamLostError$5, + errors: errors$1 +}, Symbol.toStringTag, { value: "Module" })); +function _extends$6() { + _extends$6 = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends$6.apply(this, arguments); } -async function getEip712Domain(client2, parameters) { - const { address, factory: factory2, factoryData } = parameters; - try { - const [fields, name2, version2, chainId, verifyingContract, salt, extensions] = await getAction$1(client2, readContract$1, "readContract")({ - abi: abi$1, - address, - functionName: "eip712Domain", - factory: factory2, - factoryData - }); - return { - domain: { - name: name2, - version: version2, - chainId: Number(chainId), - verifyingContract, - salt - }, - extensions, - fields +const WebRPCVersion = "v1"; +const WebRPCSchemaVersion = "v0.4.0"; +const WebRPCSchemaHash = "9d0976f6ff345b6a688b69cff647454e7fd0e3a6"; +let ContractType = /* @__PURE__ */ function(ContractType2) { + ContractType2["UNKNOWN"] = "UNKNOWN"; + ContractType2["ERC20"] = "ERC20"; + ContractType2["ERC721"] = "ERC721"; + ContractType2["ERC1155"] = "ERC1155"; + return ContractType2; +}({}); +let PropertyType = /* @__PURE__ */ function(PropertyType2) { + PropertyType2["INT"] = "INT"; + PropertyType2["STRING"] = "STRING"; + PropertyType2["ARRAY"] = "ARRAY"; + PropertyType2["GENERIC"] = "GENERIC"; + return PropertyType2; +}({}); +let SwapType = /* @__PURE__ */ function(SwapType2) { + SwapType2["UNKNOWN"] = "UNKNOWN"; + SwapType2["BUY"] = "BUY"; + SwapType2["SELL"] = "SELL"; + return SwapType2; +}({}); +let TaskStatus = /* @__PURE__ */ function(TaskStatus2) { + TaskStatus2["PENDING"] = "PENDING"; + TaskStatus2["PAUSED"] = "PAUSED"; + TaskStatus2["FAILED"] = "FAILED"; + TaskStatus2["COMPLETED"] = "COMPLETED"; + TaskStatus2["DISABLED"] = "DISABLED"; + return TaskStatus2; +}({}); +class Metadata { + constructor(hostname, fetch2) { + this.hostname = void 0; + this.fetch = void 0; + this.path = "/rpc/Metadata/"; + this.ping = (headers, signal) => { + return this.fetch(this.url("Ping"), createHTTPRequest$4({}, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.version = (headers, signal) => { + return this.fetch(this.url("Version"), createHTTPRequest$4({}, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + version: _data6.version + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.runtimeStatus = (headers, signal) => { + return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$4({}, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getTokenMetadata = (args, headers, signal) => { + return this.fetch(this.url("GetTokenMetadata"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + tokenMetadata: _data6.tokenMetadata + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.refreshTokenMetadata = (args, headers, signal) => { + return this.fetch(this.url("RefreshTokenMetadata"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + taskId: _data6.taskId + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.enqueueTokensForRefresh = (args, headers, signal) => { + return this.fetch(this.url("EnqueueTokensForRefresh"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + taskId: _data6.taskId + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getTokenRefreshStatus = (args, headers, signal) => { + return this.fetch(this.url("GetTokenRefreshStatus"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getTokenRefreshResult = (args, headers, signal) => { + return this.fetch(this.url("GetTokenRefreshResult"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + status: _data6.status, + tokens: _data6.tokens, + failureReasons: _data6.failureReasons + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.cancelRefreshJob = (args, headers, signal) => { + return this.fetch(this.url("CancelRefreshJob"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getTokenMetadataBatch = (args, headers, signal) => { + return this.fetch(this.url("GetTokenMetadataBatch"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + contractTokenMetadata: _data6.contractTokenMetadata + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.searchTokenMetadata = (args, headers, signal) => { + return this.fetch(this.url("SearchTokenMetadata"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + page: _data6.page, + tokenMetadata: _data6.tokenMetadata + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.searchTokenIDs = (args, headers, signal) => { + return this.fetch(this.url("SearchTokenIDs"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + page: _data6.page, + tokenIds: _data6.tokenIds + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.tokenCollectionFilters = (args, headers, signal) => { + return this.fetch(this.url("TokenCollectionFilters"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + filters: _data6.filters + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getContractInfo = (args, headers, signal) => { + return this.fetch(this.url("GetContractInfo"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + contractInfo: _data6.contractInfo + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getContractInfoBatch = (args, headers, signal) => { + return this.fetch(this.url("GetContractInfoBatch"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + contractInfoMap: _data6.contractInfoMap + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.searchContractInfo = (args, headers, signal) => { + return this.fetch(this.url("SearchContractInfo"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + contractInfoList: _data6.contractInfoList + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.searchContractInfoBatch = (args, headers, signal) => { + return this.fetch(this.url("SearchContractInfoBatch"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + contractInfoByChain: _data6.contractInfoByChain + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.searchMetadata = (args, headers, signal) => { + return this.fetch(this.url("SearchMetadata"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + tokenMetadata: _data6.tokenMetadata, + contractInfo: _data6.contractInfo + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.searchTokens = (args, headers, signal) => { + return this.fetch(this.url("SearchTokens"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + tokenMetadata: _data6.tokenMetadata, + nextPage: _data6.nextPage + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.searchContracts = (args, headers, signal) => { + return this.fetch(this.url("SearchContracts"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + contractInfo: _data6.contractInfo, + nextPage: _data6.nextPage + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getNiftyswapTokenQuantity = (args, headers, signal) => { + return this.fetch(this.url("GetNiftyswapTokenQuantity"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + quantity: _data6.quantity + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getNiftyswapUnitPrices = (args, headers, signal) => { + return this.fetch(this.url("GetNiftyswapUnitPrices"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + prices: _data6.prices + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getNiftyswapUnitPricesWithQuantities = (args, headers, signal) => { + return this.fetch(this.url("GetNiftyswapUnitPricesWithQuantities"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + prices: _data6.prices + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.addContractToMintMonitor = (args, headers, signal) => { + return this.fetch(this.url("AddContractToMintMonitor"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.removeContractFromMintMonitor = (args, headers, signal) => { + return this.fetch(this.url("RemoveContractFromMintMonitor"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.mintMonitorJobStatus = (args, headers, signal) => { + return this.fetch(this.url("MintMonitorJobStatus"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + task: _data6.task + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.mintMonitorTriggerJob = (args, headers, signal) => { + return this.fetch(this.url("MintMonitorTriggerJob"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); }; - } catch (e2) { - const error = e2; - if (error.name === "ContractFunctionExecutionError" && error.cause.name === "ContractFunctionZeroDataError") { - throw new Eip712DomainNotFoundError({ address }); - } - throw error; - } -} -const abi$1 = [ - { - inputs: [], - name: "eip712Domain", - outputs: [ - { name: "fields", type: "bytes1" }, - { name: "name", type: "string" }, - { name: "version", type: "string" }, - { name: "chainId", type: "uint256" }, - { name: "verifyingContract", type: "address" }, - { name: "salt", type: "bytes32" }, - { name: "extensions", type: "uint256[]" } - ], - stateMutability: "view", - type: "function" + this.syncContractTokens = (args, headers, signal) => { + return this.fetch(this.url("SyncContractTokens"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + taskID: _data6.taskID + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.abortContractSync = (args, headers, signal) => { + return this.fetch(this.url("AbortContractSync"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.contractSyncJobStatus = (args, headers, signal) => { + return this.fetch(this.url("ContractSyncJobStatus"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + refreshTask: _data6.refreshTask, + syncTask: _data6.syncTask + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.directoryGetNetworks = (args, headers, signal) => { + return this.fetch(this.url("DirectoryGetNetworks"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + networks: _data6.networks + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.directoryGetCollections = (args, headers, signal) => { + return this.fetch(this.url("DirectoryGetCollections"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + collections: _data6.collections, + page: _data6.page + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.directorySearchCollections = (args, headers, signal) => { + return this.fetch(this.url("DirectorySearchCollections"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + collections: _data6.collections, + page: _data6.page + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.hostname = hostname; + this.fetch = (input2, init2) => fetch2(input2, init2); } -]; -function formatFeeHistory(feeHistory) { - var _a2; - return { - baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)), - gasUsedRatio: feeHistory.gasUsedRatio, - oldestBlock: BigInt(feeHistory.oldestBlock), - reward: (_a2 = feeHistory.reward) == null ? void 0 : _a2.map((reward) => reward.map((value) => BigInt(value))) - }; -} -async function getFeeHistory(client2, { blockCount, blockNumber, blockTag = "latest", rewardPercentiles }) { - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const feeHistory = await client2.request({ - method: "eth_feeHistory", - params: [ - numberToHex(blockCount), - blockNumberHex || blockTag, - rewardPercentiles - ] - }, { dedupe: Boolean(blockNumberHex) }); - return formatFeeHistory(feeHistory); -} -async function getFilterChanges(_client3, { filter: filter2 }) { - const strict = "strict" in filter2 && filter2.strict; - const logs = await filter2.request({ - method: "eth_getFilterChanges", - params: [filter2.id] - }); - if (typeof logs[0] === "string") - return logs; - const formattedLogs = logs.map((log) => formatLog(log)); - if (!("abi" in filter2) || !filter2.abi) - return formattedLogs; - return parseEventLogs({ - abi: filter2.abi, - logs: formattedLogs, - strict - }); -} -async function getFilterLogs(_client3, { filter: filter2 }) { - const strict = filter2.strict ?? false; - const logs = await filter2.request({ - method: "eth_getFilterLogs", - params: [filter2.id] - }); - const formattedLogs = logs.map((log) => formatLog(log)); - if (!filter2.abi) - return formattedLogs; - return parseEventLogs({ - abi: filter2.abi, - logs: formattedLogs, - strict - }); -} -async function getStorageAt(client2, { address, blockNumber, blockTag = "latest", slot }) { - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - const data = await client2.request({ - method: "eth_getStorageAt", - params: [address, slot, blockNumberHex || blockTag] - }); - return data; -} -async function getTransaction(client2, { blockHash, blockNumber, blockTag: blockTag_, hash: hash2, index: index2 }) { - var _a2, _b2, _c2; - const blockTag = blockTag_ || "latest"; - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - let transaction2 = null; - if (hash2) { - transaction2 = await client2.request({ - method: "eth_getTransactionByHash", - params: [hash2] - }, { dedupe: true }); - } else if (blockHash) { - transaction2 = await client2.request({ - method: "eth_getTransactionByBlockHashAndIndex", - params: [blockHash, numberToHex(index2)] - }, { dedupe: true }); - } else if (blockNumberHex || blockTag) { - transaction2 = await client2.request({ - method: "eth_getTransactionByBlockNumberAndIndex", - params: [blockNumberHex || blockTag, numberToHex(index2)] - }, { dedupe: Boolean(blockNumberHex) }); + url(name2) { + return this.hostname + this.path + name2; } - if (!transaction2) - throw new TransactionNotFoundError({ - blockHash, - blockNumber, - blockTag, - hash: hash2, - index: index2 - }); - const format2 = ((_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.transaction) == null ? void 0 : _c2.format) || formatTransaction; - return format2(transaction2); -} -async function getTransactionConfirmations(client2, { hash: hash2, transactionReceipt }) { - const [blockNumber, transaction2] = await Promise.all([ - getAction$1(client2, getBlockNumber, "getBlockNumber")({}), - hash2 ? getAction$1(client2, getTransaction, "getTransaction")({ hash: hash2 }) : void 0 - ]); - const transactionBlockNumber = (transactionReceipt == null ? void 0 : transactionReceipt.blockNumber) || (transaction2 == null ? void 0 : transaction2.blockNumber); - if (!transactionBlockNumber) - return 0n; - return blockNumber - transactionBlockNumber + 1n; -} -const receiptStatuses = { - "0x0": "reverted", - "0x1": "success" -}; -function formatTransactionReceipt(transactionReceipt) { - const receipt = { - ...transactionReceipt, - blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null, - contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null, - cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null, - effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null, - gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null, - logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null, - to: transactionReceipt.to ? transactionReceipt.to : null, - transactionIndex: transactionReceipt.transactionIndex ? hexToNumber$1(transactionReceipt.transactionIndex) : null, - status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null, - type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null - }; - if (transactionReceipt.blobGasPrice) - receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice); - if (transactionReceipt.blobGasUsed) - receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed); - return receipt; -} -async function getTransactionReceipt$1(client2, { hash: hash2 }) { - var _a2, _b2, _c2; - const receipt = await client2.request({ - method: "eth_getTransactionReceipt", - params: [hash2] - }, { dedupe: true }); - if (!receipt) - throw new TransactionReceiptNotFoundError({ hash: hash2 }); - const format2 = ((_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.transactionReceipt) == null ? void 0 : _c2.format) || formatTransactionReceipt; - return format2(receipt); } -async function multicall(client2, parameters) { - var _a2; - const { allowFailure = true, batchSize: batchSize_, blockNumber, blockTag, multicallAddress: multicallAddress_, stateOverride } = parameters; - const contracts = parameters.contracts; - const batchSize = batchSize_ ?? (typeof ((_a2 = client2.batch) == null ? void 0 : _a2.multicall) === "object" && client2.batch.multicall.batchSize || 1024); - let multicallAddress = multicallAddress_; - if (!multicallAddress) { - if (!client2.chain) - throw new Error("client chain not configured. multicallAddress is required."); - multicallAddress = getChainContractAddress({ - blockNumber, - chain: client2.chain, - contract: "multicall3" - }); - } - const chunkedCalls = [[]]; - let currentChunk = 0; - let currentChunkSize = 0; - for (let i = 0; i < contracts.length; i++) { - const { abi: abi2, address, args, functionName } = contracts[i]; - try { - const callData = encodeFunctionData({ abi: abi2, args, functionName }); - currentChunkSize += (callData.length - 2) / 2; - if ( - // Check if batching is enabled. - batchSize > 0 && // Check if the current size of the batch exceeds the size limit. - currentChunkSize > batchSize && // Check if the current chunk is not already empty. - chunkedCalls[currentChunk].length > 0 - ) { - currentChunk++; - currentChunkSize = (callData.length - 2) / 2; - chunkedCalls[currentChunk] = []; - } - chunkedCalls[currentChunk] = [ - ...chunkedCalls[currentChunk], - { - allowFailure: true, - callData, - target: address - } - ]; - } catch (err) { - const error = getContractError(err, { - abi: abi2, - address, - args, - docsPath: "/docs/contract/multicall", - functionName +class Collections { + constructor(hostname, fetch2) { + this.hostname = void 0; + this.fetch = void 0; + this.path = "/rpc/Collections/"; + this.createCollection = (args, headers, signal) => { + return this.fetch(this.url("CreateCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + collection: _data6.collection + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - if (!allowFailure) - throw error; - chunkedCalls[currentChunk] = [ - ...chunkedCalls[currentChunk], - { - allowFailure: true, - callData: "0x", - target: address - } - ]; - } - } - const aggregate3Results = await Promise.allSettled(chunkedCalls.map((calls) => getAction$1(client2, readContract$1, "readContract")({ - abi: multicall3Abi, - address: multicallAddress, - args: [calls], - blockNumber, - blockTag, - functionName: "aggregate3", - stateOverride - }))); - const results2 = []; - for (let i = 0; i < aggregate3Results.length; i++) { - const result = aggregate3Results[i]; - if (result.status === "rejected") { - if (!allowFailure) - throw result.reason; - for (let j2 = 0; j2 < chunkedCalls[i].length; j2++) { - results2.push({ - status: "failure", - error: result.reason, - result: void 0 + }; + this.getCollection = (args, headers, signal) => { + return this.fetch(this.url("GetCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + collection: _data6.collection + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.listCollections = (args, headers, signal) => { + return this.fetch(this.url("ListCollections"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + page: _data6.page, + collections: _data6.collections + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.updateCollection = (args, headers, signal) => { + return this.fetch(this.url("UpdateCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + collection: _data6.collection + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.deleteCollection = (args, headers, signal) => { + return this.fetch(this.url("DeleteCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.publishCollection = (args, headers, signal) => { + return this.fetch(this.url("PublishCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + collection: _data6.collection + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.unpublishCollection = (args, headers, signal) => { + return this.fetch(this.url("UnpublishCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + collection: _data6.collection + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.createContractCollection = (args, headers, signal) => { + return this.fetch(this.url("CreateContractCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + contractCollection: _data6.contractCollection + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getContractCollection = (args, headers, signal) => { + return this.fetch(this.url("GetContractCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + contractCollection: _data6.contractCollection + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.listContractCollections = (args, headers, signal) => { + return this.fetch(this.url("ListContractCollections"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + contractCollections: _data6.contractCollections, + collections: _data6.collections, + page: _data6.page + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.updateContractCollection = (args, headers, signal) => { + return this.fetch(this.url("UpdateContractCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.deleteContractCollection = (args, headers, signal) => { + return this.fetch(this.url("DeleteContractCollection"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.createToken = (args, headers, signal) => { + return this.fetch(this.url("CreateToken"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + token: _data6.token, + assets: _data6.assets + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getToken = (args, headers, signal) => { + return this.fetch(this.url("GetToken"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + token: _data6.token, + assets: _data6.assets + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.listTokens = (args, headers, signal) => { + return this.fetch(this.url("ListTokens"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + page: _data6.page, + tokens: _data6.tokens + }; }); - } - continue; - } - const aggregate3Result = result.value; - for (let j2 = 0; j2 < aggregate3Result.length; j2++) { - const { returnData, success } = aggregate3Result[j2]; - const { callData } = chunkedCalls[i][j2]; - const { abi: abi2, address, functionName, args } = contracts[results2.length]; - try { - if (callData === "0x") - throw new AbiDecodingZeroDataError(); - if (!success) - throw new RawContractError({ data: returnData }); - const result2 = decodeFunctionResult({ - abi: abi2, - args, - data: returnData, - functionName + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` }); - results2.push(allowFailure ? { result: result2, status: "success" } : result2); - } catch (err) { - const error = getContractError(err, { - abi: abi2, - address, - args, - docsPath: "/docs/contract/multicall", - functionName + }); + }; + this.updateToken = (args, headers, signal) => { + return this.fetch(this.url("UpdateToken"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + token: _data6.token + }; }); - if (!allowFailure) - throw error; - results2.push({ error, result: void 0, status: "failure" }); - } - } - } - if (results2.length !== contracts.length) - throw new BaseError$3("multicall results mismatch"); - return results2; -} -const listenersCache = /* @__PURE__ */ new Map(); -const cleanupCache = /* @__PURE__ */ new Map(); -let callbackCount = 0; -function observe(observerId, callbacks, fn) { - const callbackId = ++callbackCount; - const getListeners = () => listenersCache.get(observerId) || []; - const unsubscribe = () => { - const listeners2 = getListeners(); - listenersCache.set(observerId, listeners2.filter((cb2) => cb2.id !== callbackId)); - }; - const unwatch = () => { - const cleanup2 = cleanupCache.get(observerId); - if (getListeners().length === 1 && cleanup2) - cleanup2(); - unsubscribe(); - }; - const listeners = getListeners(); - listenersCache.set(observerId, [ - ...listeners, - { id: callbackId, fns: callbacks } - ]); - if (listeners && listeners.length > 0) - return unwatch; - const emit2 = {}; - for (const key in callbacks) { - emit2[key] = (...args) => { - var _a2, _b2; - const listeners2 = getListeners(); - if (listeners2.length === 0) - return; - for (const listener of listeners2) - (_b2 = (_a2 = listener.fns)[key]) == null ? void 0 : _b2.call(_a2, ...args); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); }; - } - const cleanup = fn(emit2); - if (typeof cleanup === "function") - cleanupCache.set(observerId, cleanup); - return unwatch; -} -async function wait(time2) { - return new Promise((res) => setTimeout(res, time2)); -} -function poll(fn, { emitOnBegin, initialWaitTime, interval }) { - let active = true; - const unwatch = () => active = false; - const watch = async () => { - let data = void 0; - if (emitOnBegin) - data = await fn({ unpoll: unwatch }); - const initialWait = await (initialWaitTime == null ? void 0 : initialWaitTime(data)) ?? interval; - await wait(initialWait); - const poll2 = async () => { - if (!active) - return; - await fn({ unpoll: unwatch }); - await wait(interval); - poll2(); + this.deleteToken = (args, headers, signal) => { + return this.fetch(this.url("DeleteToken"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); }; - poll2(); - }; - watch(); - return unwatch; -} -function watchBlocks(client2, { blockTag = "latest", emitMissed = false, emitOnBegin = false, onBlock, onError, includeTransactions: includeTransactions_, poll: poll_, pollingInterval = client2.pollingInterval }) { - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (client2.transport.type === "webSocket") - return false; - if (client2.transport.type === "fallback" && client2.transport.transports[0].config.type === "webSocket") - return false; - return true; - })(); - const includeTransactions = includeTransactions_ ?? false; - let prevBlock; - const pollBlocks = () => { - const observerId = stringify([ - "watchBlocks", - client2.uid, - blockTag, - emitMissed, - emitOnBegin, - includeTransactions, - pollingInterval - ]); - return observe(observerId, { onBlock, onError }, (emit2) => poll(async () => { - var _a2; - try { - const block = await getAction$1(client2, getBlock, "getBlock")({ - blockTag, - includeTransactions + this.createAsset = (args, headers, signal) => { + return this.fetch(this.url("CreateAsset"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + asset: _data6.asset + }; }); - if (block.number && (prevBlock == null ? void 0 : prevBlock.number)) { - if (block.number === prevBlock.number) - return; - if (block.number - prevBlock.number > 1 && emitMissed) { - for (let i = (prevBlock == null ? void 0 : prevBlock.number) + 1n; i < block.number; i++) { - const block2 = await getAction$1(client2, getBlock, "getBlock")({ - blockNumber: i, - includeTransactions - }); - emit2.onBlock(block2, prevBlock); - prevBlock = block2; - } - } - } - if ( - // If no previous block exists, emit. - !(prevBlock == null ? void 0 : prevBlock.number) || // If the block tag is "pending" with no block number, emit. - blockTag === "pending" && !(block == null ? void 0 : block.number) || // If the next block number is greater than the previous block number, emit. - // We don't want to emit blocks in the past. - block.number && block.number > prevBlock.number - ) { - emit2.onBlock(block, prevBlock); - prevBlock = block; - } - } catch (err) { - (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); - } - }, { - emitOnBegin, - interval: pollingInterval - })); - }; - const subscribeBlocks = () => { - let active = true; - let emitFetched = true; - let unsubscribe = () => active = false; - (async () => { - try { - if (emitOnBegin) { - getAction$1(client2, getBlock, "getBlock")({ - blockTag, - includeTransactions - }).then((block) => { - if (!active) - return; - if (!emitFetched) - return; - onBlock(block, void 0); - emitFetched = false; - }); - } - const transport = (() => { - if (client2.transport.type === "fallback") { - const transport2 = client2.transport.transports.find((transport3) => transport3.config.type === "webSocket"); - if (!transport2) - return client2.transport; - return transport2.value; - } - return client2.transport; - })(); - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["newHeads"], - onData(data) { - var _a2, _b2, _c2; - if (!active) - return; - const format2 = ((_c2 = (_b2 = (_a2 = client2.chain) == null ? void 0 : _a2.formatters) == null ? void 0 : _b2.block) == null ? void 0 : _c2.format) || formatBlock; - const block = format2(data.result); - onBlock(block, prevBlock); - emitFetched = false; - prevBlock = block; - }, - onError(error) { - onError == null ? void 0 : onError(error); - } + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError == null ? void 0 : onError(err); - } - })(); - return () => unsubscribe(); - }; - return enablePolling ? pollBlocks() : subscribeBlocks(); -} -function watchBlockNumber(client2, { emitOnBegin = false, emitMissed = false, onBlockNumber, onError, poll: poll_, pollingInterval = client2.pollingInterval }) { - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (client2.transport.type === "webSocket") - return false; - if (client2.transport.type === "fallback" && client2.transport.transports[0].config.type === "webSocket") - return false; - return true; - })(); - let prevBlockNumber; - const pollBlockNumber = () => { - const observerId = stringify([ - "watchBlockNumber", - client2.uid, - emitOnBegin, - emitMissed, - pollingInterval - ]); - return observe(observerId, { onBlockNumber, onError }, (emit2) => poll(async () => { - var _a2; - try { - const blockNumber = await getAction$1(client2, getBlockNumber, "getBlockNumber")({ cacheTime: 0 }); - if (prevBlockNumber) { - if (blockNumber === prevBlockNumber) - return; - if (blockNumber - prevBlockNumber > 1 && emitMissed) { - for (let i = prevBlockNumber + 1n; i < blockNumber; i++) { - emit2.onBlockNumber(i, prevBlockNumber); - prevBlockNumber = i; - } - } - } - if (!prevBlockNumber || blockNumber > prevBlockNumber) { - emit2.onBlockNumber(blockNumber, prevBlockNumber); - prevBlockNumber = blockNumber; - } - } catch (err) { - (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); - } - }, { - emitOnBegin, - interval: pollingInterval - })); - }; - const subscribeBlockNumber = () => { - const observerId = stringify([ - "watchBlockNumber", - client2.uid, - emitOnBegin, - emitMissed - ]); - return observe(observerId, { onBlockNumber, onError }, (emit2) => { - let active = true; - let unsubscribe = () => active = false; - (async () => { - try { - const transport = (() => { - if (client2.transport.type === "fallback") { - const transport2 = client2.transport.transports.find((transport3) => transport3.config.type === "webSocket"); - if (!transport2) - return client2.transport; - return transport2.value; - } - return client2.transport; - })(); - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["newHeads"], - onData(data) { - var _a2; - if (!active) - return; - const blockNumber = hexToBigInt((_a2 = data.result) == null ? void 0 : _a2.number); - emit2.onBlockNumber(blockNumber, prevBlockNumber); - prevBlockNumber = blockNumber; - }, - onError(error) { - var _a2; - (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError == null ? void 0 : onError(err); - } - })(); - return () => unsubscribe(); - }); - }; - return enablePolling ? pollBlockNumber() : subscribeBlockNumber(); -} -async function uninstallFilter(_client3, { filter: filter2 }) { - return filter2.request({ - method: "eth_uninstallFilter", - params: [filter2.id] - }); -} -function watchEvent(client2, { address, args, batch = true, event, events, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client2.pollingInterval, strict: strict_ }) { - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (typeof fromBlock === "bigint") - return true; - if (client2.transport.type === "webSocket") - return false; - if (client2.transport.type === "fallback" && client2.transport.transports[0].config.type === "webSocket") - return false; - return true; - })(); - const strict = strict_ ?? false; - const pollEvent = () => { - const observerId = stringify([ - "watchEvent", - address, - args, - batch, - client2.uid, - event, - pollingInterval, - fromBlock - ]); - return observe(observerId, { onLogs, onError }, (emit2) => { - let previousBlockNumber; - if (fromBlock !== void 0) - previousBlockNumber = fromBlock - 1n; - let filter2; - let initialized = false; - const unwatch = poll(async () => { - var _a2; - if (!initialized) { - try { - filter2 = await getAction$1(client2, createEventFilter, "createEventFilter")({ - address, - args, - event, - events, - strict, - fromBlock - }); - } catch { - } - initialized = true; - return; - } - try { - let logs; - if (filter2) { - logs = await getAction$1(client2, getFilterChanges, "getFilterChanges")({ filter: filter2 }); - } else { - const blockNumber = await getAction$1(client2, getBlockNumber, "getBlockNumber")({}); - if (previousBlockNumber && previousBlockNumber !== blockNumber) { - logs = await getAction$1(client2, getLogs, "getLogs")({ - address, - args, - event, - events, - fromBlock: previousBlockNumber + 1n, - toBlock: blockNumber - }); - } else { - logs = []; - } - previousBlockNumber = blockNumber; - } - if (logs.length === 0) - return; - if (batch) - emit2.onLogs(logs); - else - for (const log of logs) - emit2.onLogs([log]); - } catch (err) { - if (filter2 && err instanceof InvalidInputRpcError) - initialized = false; - (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); - } - }, { - emitOnBegin: true, - interval: pollingInterval }); - return async () => { - if (filter2) - await getAction$1(client2, uninstallFilter, "uninstallFilter")({ filter: filter2 }); - unwatch(); - }; - }); - }; - const subscribeEvent = () => { - let active = true; - let unsubscribe = () => active = false; - (async () => { - try { - const transport = (() => { - if (client2.transport.type === "fallback") { - const transport2 = client2.transport.transports.find((transport3) => transport3.config.type === "webSocket"); - if (!transport2) - return client2.transport; - return transport2.value; - } - return client2.transport; - })(); - const events_ = events ?? (event ? [event] : void 0); - let topics = []; - if (events_) { - const encoded = events_.flatMap((event2) => encodeEventTopics({ - abi: [event2], - eventName: event2.name, - args - })); - topics = [encoded]; - if (event) - topics = topics[0]; - } - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["logs", { address, topics }], - onData(data) { - var _a2; - if (!active) - return; - const log = data.result; - try { - const { eventName, args: args2 } = decodeEventLog({ - abi: events_ ?? [], - data: log.data, - topics: log.topics, - strict - }); - const formatted = formatLog(log, { args: args2, eventName }); - onLogs([formatted]); - } catch (err) { - let eventName; - let isUnnamed; - if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { - if (strict_) - return; - eventName = err.abiItem.name; - isUnnamed = (_a2 = err.abiItem.inputs) == null ? void 0 : _a2.some((x2) => !("name" in x2 && x2.name)); - } - const formatted = formatLog(log, { - args: isUnnamed ? [] : {}, - eventName - }); - onLogs([formatted]); - } - }, - onError(error) { - onError == null ? void 0 : onError(error); - } + }; + this.getAsset = (args, headers, signal) => { + return this.fetch(this.url("GetAsset"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + asset: _data6.asset + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.updateAsset = (args, headers, signal) => { + return this.fetch(this.url("UpdateAsset"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + asset: _data6.asset + }; }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError == null ? void 0 : onError(err); - } - })(); - return () => unsubscribe(); - }; - return enablePolling ? pollEvent() : subscribeEvent(); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.deleteAsset = (args, headers, signal) => { + return this.fetch(this.url("DeleteAsset"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.hostname = hostname; + this.fetch = (input2, init2) => fetch2(input2, init2); + } + url(name2) { + return this.hostname + this.path + name2; + } } -function watchPendingTransactions(client2, { batch = true, onError, onTransactions, poll: poll_, pollingInterval = client2.pollingInterval }) { - const enablePolling = typeof poll_ !== "undefined" ? poll_ : client2.transport.type !== "webSocket"; - const pollPendingTransactions = () => { - const observerId = stringify([ - "watchPendingTransactions", - client2.uid, - batch, - pollingInterval - ]); - return observe(observerId, { onTransactions, onError }, (emit2) => { - let filter2; - const unwatch = poll(async () => { - var _a2; - try { - if (!filter2) { - try { - filter2 = await getAction$1(client2, createPendingTransactionFilter, "createPendingTransactionFilter")({}); - return; - } catch (err) { - unwatch(); - throw err; - } - } - const hashes = await getAction$1(client2, getFilterChanges, "getFilterChanges")({ filter: filter2 }); - if (hashes.length === 0) - return; - if (batch) - emit2.onTransactions(hashes); - else - for (const hash2 of hashes) - emit2.onTransactions([hash2]); - } catch (err) { - (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); - } - }, { - emitOnBegin: true, - interval: pollingInterval +class Admin { + constructor(hostname, fetch2) { + this.hostname = void 0; + this.fetch = void 0; + this.path = "/rpc/Admin/"; + this.addContractsToTokenDirectory = (args, headers, signal) => { + return this.fetch(this.url("AddContractsToTokenDirectory"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); }); - return async () => { - if (filter2) - await getAction$1(client2, uninstallFilter, "uninstallFilter")({ filter: filter2 }); - unwatch(); - }; - }); - }; - const subscribePendingTransactions = () => { - let active = true; - let unsubscribe = () => active = false; - (async () => { - try { - const { unsubscribe: unsubscribe_ } = await client2.transport.subscribe({ - params: ["newPendingTransactions"], - onData(data) { - if (!active) - return; - const transaction2 = data.result; - onTransactions([transaction2]); - }, - onError(error) { - onError == null ? void 0 : onError(error); - } + }; + this.removeContractsFromTokenDirectory = (args, headers, signal) => { + return this.fetch(this.url("RemoveContractsFromTokenDirectory"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError == null ? void 0 : onError(err); - } - })(); - return () => unsubscribe(); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.modifyFeatureIndex = (args, headers, signal) => { + return this.fetch(this.url("ModifyFeatureIndex"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getFeatureIndex = (args, headers, signal) => { + return this.fetch(this.url("GetFeatureIndex"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + featured: _data6.featured + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.listTokenDirectory = (args, headers, signal) => { + return this.fetch(this.url("ListTokenDirectory"), createHTTPRequest$4(args, headers, signal)).then((res) => { + return buildResponse$4(res).then((_data6) => { + return { + page: _data6.page, + collections: _data6.collections + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$4.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.hostname = hostname; + this.fetch = (input2, init2) => fetch2(input2, init2); + } + url(name2) { + return this.hostname + this.path + name2; + } +} +const createHTTPRequest$4 = (body = {}, headers = {}, signal = null) => { + return { + method: "POST", + headers: _extends$6({}, headers, { + "Content-Type": "application/json" + }), + body: JSON.stringify(body || {}), + signal }; - return enablePolling ? pollPendingTransactions() : subscribePendingTransactions(); +}; +const buildResponse$4 = (res) => { + return res.text().then((text2) => { + let data; + try { + data = JSON.parse(text2); + } catch (error) { + let message = ""; + if (error instanceof Error) { + message = error.message; + } + throw WebrpcBadResponseError$4.new({ + status: res.status, + cause: `JSON.parse(): ${message}: response text: ${text2}` + }); + } + if (!res.ok) { + const code2 = typeof data.code === "number" ? data.code : 0; + throw (webrpcErrorByCode$4[code2] || WebrpcError$4).new(data); + } + return data; + }); +}; +let WebrpcError$4 = class WebrpcError4 extends Error { + constructor(name2, code2, message, status, cause) { + super(message); + this.name = void 0; + this.code = void 0; + this.message = void 0; + this.status = void 0; + this.cause = void 0; + this.msg = void 0; + this.name = name2 || "WebrpcError"; + this.code = typeof code2 === "number" ? code2 : 0; + this.message = message || `endpoint error ${this.code}`; + this.msg = this.message; + this.status = typeof status === "number" ? status : 0; + this.cause = cause; + Object.setPrototypeOf(this, WebrpcError4.prototype); + } + static new(payload) { + return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + } +}; +let WebrpcEndpointError$4 = class WebrpcEndpointError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcEndpointError4.prototype); + } +}; +let WebrpcRequestFailedError$4 = class WebrpcRequestFailedError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcRequestFailedError4.prototype); + } +}; +let WebrpcBadRouteError$4 = class WebrpcBadRouteError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRouteError4.prototype); + } +}; +let WebrpcBadMethodError$4 = class WebrpcBadMethodError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadMethodError4.prototype); + } +}; +let WebrpcBadRequestError$4 = class WebrpcBadRequestError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRequestError4.prototype); + } +}; +let WebrpcBadResponseError$4 = class WebrpcBadResponseError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadResponseError4.prototype); + } +}; +let WebrpcServerPanicError$4 = class WebrpcServerPanicError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcServerPanicError4.prototype); + } +}; +let WebrpcInternalErrorError$4 = class WebrpcInternalErrorError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcInternalErrorError4.prototype); + } +}; +let WebrpcClientDisconnectedError$4 = class WebrpcClientDisconnectedError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcClientDisconnectedError4.prototype); + } +}; +let WebrpcStreamLostError$4 = class WebrpcStreamLostError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamLostError4.prototype); + } +}; +let WebrpcStreamFinishedError$4 = class WebrpcStreamFinishedError4 extends WebrpcError$4 { + constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamFinishedError4.prototype); + } +}; +let UnauthorizedError$3 = class UnauthorizedError4 extends WebrpcError$4 { + constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, UnauthorizedError4.prototype); + } +}; +let PermissionDeniedError$1 = class PermissionDeniedError4 extends WebrpcError$4 { + constructor(name2 = "PermissionDenied", code2 = 1001, message = "Permission denied", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, PermissionDeniedError4.prototype); + } +}; +let SessionExpiredError$2 = class SessionExpiredError3 extends WebrpcError$4 { + constructor(name2 = "SessionExpired", code2 = 1002, message = "Session expired", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, SessionExpiredError3.prototype); + } +}; +class MethodNotFoundError3 extends WebrpcError$4 { + constructor(name2 = "MethodNotFound", code2 = 1003, message = "Method not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, MethodNotFoundError3.prototype); + } } -async function getAddresses(client2) { - var _a2; - if (((_a2 = client2.account) == null ? void 0 : _a2.type) === "local") - return [client2.account.address]; - const addresses = await client2.request({ method: "eth_accounts" }, { dedupe: true }); - return addresses.map((address) => checksumAddress(address)); +class RequestConflictError2 extends WebrpcError$4 { + constructor(name2 = "RequestConflict", code2 = 1004, message = "Conflict with target resource", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, RequestConflictError2.prototype); + } } -async function getPermissions(client2) { - const permissions = await client2.request({ method: "wallet_getPermissions" }, { dedupe: true }); - return permissions; +class FailError extends WebrpcError$4 { + constructor(name2 = "Fail", code2 = 1005, message = "Request Failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, FailError.prototype); + } } -const promiseCache = /* @__PURE__ */ new LruMap(8192); -function withDedupe(fn, { enabled = true, id: id2 }) { - if (!enabled || !id2) - return fn(); - if (promiseCache.get(id2)) - return promiseCache.get(id2); - const promise = fn().finally(() => promiseCache.delete(id2)); - promiseCache.set(id2, promise); - return promise; +class GeoblockedError2 extends WebrpcError$4 { + constructor(name2 = "Geoblocked", code2 = 1006, message = "Geoblocked region", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, GeoblockedError2.prototype); + } } -function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) { - return new Promise((resolve, reject) => { - const attemptRetry = async ({ count: count2 = 0 } = {}) => { - const retry = async ({ error }) => { - const delay2 = typeof delay_ === "function" ? delay_({ count: count2, error }) : delay_; - if (delay2) - await wait(delay2); - attemptRetry({ count: count2 + 1 }); - }; - try { - const data = await fn(); - resolve(data); - } catch (err) { - if (count2 < retryCount && await shouldRetry2({ count: count2, error: err })) - return retry({ error: err }); - reject(err); +class TimeoutError3 extends WebrpcError$4 { + constructor(name2 = "Timeout", code2 = 2e3, message = "Request timed out", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, TimeoutError3.prototype); + } +} +let InvalidArgumentError$2 = class InvalidArgumentError4 extends WebrpcError$4 { + constructor(name2 = "InvalidArgument", code2 = 2001, message = "Invalid argument", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, InvalidArgumentError4.prototype); + } +}; +class RequiredArgumentError extends WebrpcError$4 { + constructor(name2 = "RequiredArgument", code2 = 2002, message = "Required argument missing", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, RequiredArgumentError.prototype); + } +} +let QueryFailedError$2 = class QueryFailedError4 extends WebrpcError$4 { + constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, QueryFailedError4.prototype); + } +}; +let ValidationFailedError$1 = class ValidationFailedError extends WebrpcError$4 { + constructor(name2 = "ValidationFailed", code2 = 2004, message = "Validation failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, ValidationFailedError.prototype); + } +}; +class RateLimitedError extends WebrpcError$4 { + constructor(name2 = "RateLimited", code2 = 2005, message = "Rate limited", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, RateLimitedError.prototype); + } +} +let NotFoundError$3 = class NotFoundError4 extends WebrpcError$4 { + constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, NotFoundError4.prototype); + } +}; +class ProjectNotFoundError2 extends WebrpcError$4 { + constructor(name2 = "ProjectNotFound", code2 = 3002, message = "Project not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, ProjectNotFoundError2.prototype); + } +} +class ChainNotFoundError2 extends WebrpcError$4 { + constructor(name2 = "ChainNotFound", code2 = 3003, message = "Chain not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, ChainNotFoundError2.prototype); + } +} +class TokenDirectoryDisabledError extends WebrpcError$4 { + constructor(name2 = "TokenDirectoryDisabled", code2 = 4001, message = "Token Directory is disabled", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, TokenDirectoryDisabledError.prototype); + } +} +let errors = /* @__PURE__ */ function(errors2) { + errors2["WebrpcEndpoint"] = "WebrpcEndpoint"; + errors2["WebrpcRequestFailed"] = "WebrpcRequestFailed"; + errors2["WebrpcBadRoute"] = "WebrpcBadRoute"; + errors2["WebrpcBadMethod"] = "WebrpcBadMethod"; + errors2["WebrpcBadRequest"] = "WebrpcBadRequest"; + errors2["WebrpcBadResponse"] = "WebrpcBadResponse"; + errors2["WebrpcServerPanic"] = "WebrpcServerPanic"; + errors2["WebrpcInternalError"] = "WebrpcInternalError"; + errors2["WebrpcClientDisconnected"] = "WebrpcClientDisconnected"; + errors2["WebrpcStreamLost"] = "WebrpcStreamLost"; + errors2["WebrpcStreamFinished"] = "WebrpcStreamFinished"; + errors2["Unauthorized"] = "Unauthorized"; + errors2["PermissionDenied"] = "PermissionDenied"; + errors2["SessionExpired"] = "SessionExpired"; + errors2["MethodNotFound"] = "MethodNotFound"; + errors2["RequestConflict"] = "RequestConflict"; + errors2["Fail"] = "Fail"; + errors2["Geoblocked"] = "Geoblocked"; + errors2["Timeout"] = "Timeout"; + errors2["InvalidArgument"] = "InvalidArgument"; + errors2["RequiredArgument"] = "RequiredArgument"; + errors2["QueryFailed"] = "QueryFailed"; + errors2["ValidationFailed"] = "ValidationFailed"; + errors2["RateLimited"] = "RateLimited"; + errors2["NotFound"] = "NotFound"; + errors2["ProjectNotFound"] = "ProjectNotFound"; + errors2["ChainNotFound"] = "ChainNotFound"; + errors2["TokenDirectoryDisabled"] = "TokenDirectoryDisabled"; + return errors2; +}({}); +const webrpcErrorByCode$4 = { + [0]: WebrpcEndpointError$4, + [-1]: WebrpcRequestFailedError$4, + [-2]: WebrpcBadRouteError$4, + [-3]: WebrpcBadMethodError$4, + [-4]: WebrpcBadRequestError$4, + [-5]: WebrpcBadResponseError$4, + [-6]: WebrpcServerPanicError$4, + [-7]: WebrpcInternalErrorError$4, + [-8]: WebrpcClientDisconnectedError$4, + [-9]: WebrpcStreamLostError$4, + [-10]: WebrpcStreamFinishedError$4, + [1e3]: UnauthorizedError$3, + [1001]: PermissionDeniedError$1, + [1002]: SessionExpiredError$2, + [1003]: MethodNotFoundError3, + [1004]: RequestConflictError2, + [1005]: FailError, + [1006]: GeoblockedError2, + [2e3]: TimeoutError3, + [2001]: InvalidArgumentError$2, + [2002]: RequiredArgumentError, + [2003]: QueryFailedError$2, + [2004]: ValidationFailedError$1, + [2005]: RateLimitedError, + [3e3]: NotFoundError$3, + [3002]: ProjectNotFoundError2, + [3003]: ChainNotFoundError2, + [4001]: TokenDirectoryDisabledError +}; +const fetch$3 = globalThis.fetch; +class SequenceMetadata extends Metadata { + constructor(hostname = "https://metadata.sequence.app", projectAccessKey2, jwtAuth) { + super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, fetch$3); + this.projectAccessKey = projectAccessKey2; + this.jwtAuth = jwtAuth; + this._fetch = (input2, init2) => { + const headers = {}; + const jwtAuth2 = this.jwtAuth; + const projectAccessKey3 = this.projectAccessKey; + if (jwtAuth2 && jwtAuth2.length > 0) { + headers["Authorization"] = `BEARER ${jwtAuth2}`; + } + if (projectAccessKey3 && projectAccessKey3.length > 0) { + headers["X-Access-Key"] = projectAccessKey3; + } + init2.headers = _extends$6({}, init2.headers, headers); + return fetch$3(input2, init2); + }; + this.fetch = this._fetch; + } +} +class SequenceCollections extends Collections { + constructor(hostname = "https://metadata.sequence.app", jwtAuth) { + super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, fetch$3); + this.jwtAuth = jwtAuth; + this._fetch = (input2, init2) => { + const headers = {}; + const jwtAuth2 = this.jwtAuth; + if (jwtAuth2 && jwtAuth2.length > 0) { + headers["Authorization"] = `BEARER ${jwtAuth2}`; } + init2.headers = _extends$6({}, init2.headers, headers); + return fetch$3(input2, init2); }; - attemptRetry(); - }); + this.fetch = this._fetch; + } + // TODO: add uploadAsset() method similar to, + // https://github.com/0xsequence/go-sequence/blob/master/metadata/collections.go#L52 } -function buildRequest(request, options = {}) { - return async (args, overrideOptions = {}) => { - const { dedupe = false, retryDelay = 150, retryCount = 3, uid: uid2 } = { - ...options, - ...overrideOptions - }; - const requestId = dedupe ? keccak256(stringToHex(`${uid2}.${stringify(args)}`)) : void 0; - return withDedupe(() => withRetry(async () => { - try { - return await request(args); - } catch (err_) { - const err = err_; - switch (err.code) { - case ParseRpcError.code: - throw new ParseRpcError(err); - case InvalidRequestRpcError.code: - throw new InvalidRequestRpcError(err); - case MethodNotFoundRpcError.code: - throw new MethodNotFoundRpcError(err, { method: args.method }); - case InvalidParamsRpcError.code: - throw new InvalidParamsRpcError(err); - case InternalRpcError.code: - throw new InternalRpcError(err); - case InvalidInputRpcError.code: - throw new InvalidInputRpcError(err); - case ResourceNotFoundRpcError.code: - throw new ResourceNotFoundRpcError(err); - case ResourceUnavailableRpcError.code: - throw new ResourceUnavailableRpcError(err); - case TransactionRejectedRpcError.code: - throw new TransactionRejectedRpcError(err); - case MethodNotSupportedRpcError.code: - throw new MethodNotSupportedRpcError(err, { - method: args.method - }); - case LimitExceededRpcError.code: - throw new LimitExceededRpcError(err); - case JsonRpcVersionUnsupportedError.code: - throw new JsonRpcVersionUnsupportedError(err); - case UserRejectedRequestError.code: - throw new UserRejectedRequestError(err); - case UnauthorizedProviderError.code: - throw new UnauthorizedProviderError(err); - case UnsupportedProviderMethodError.code: - throw new UnsupportedProviderMethodError(err); - case ProviderDisconnectedError.code: - throw new ProviderDisconnectedError(err); - case ChainDisconnectedError.code: - throw new ChainDisconnectedError(err); - case SwitchChainError.code: - throw new SwitchChainError(err); - case 5e3: - throw new UserRejectedRequestError(err); - default: - if (err_ instanceof BaseError$3) - throw err_; - throw new UnknownRpcError(err); - } - } - }, { - delay: ({ count: count2, error }) => { - var _a2; - if (error && error instanceof HttpRequestError) { - const retryAfter = (_a2 = error == null ? void 0 : error.headers) == null ? void 0 : _a2.get("Retry-After"); - if (retryAfter == null ? void 0 : retryAfter.match(/\d/)) - return Number.parseInt(retryAfter) * 1e3; - } - return ~~(1 << count2) * retryDelay; - }, - retryCount, - shouldRetry: ({ error }) => shouldRetry(error) - }), { enabled: dedupe, id: requestId }); - }; +const metadata$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Admin, + ChainNotFoundError: ChainNotFoundError2, + Collections, + ContractType, + FailError, + GeoblockedError: GeoblockedError2, + InvalidArgumentError: InvalidArgumentError$2, + Metadata, + MethodNotFoundError: MethodNotFoundError3, + NotFoundError: NotFoundError$3, + PermissionDeniedError: PermissionDeniedError$1, + ProjectNotFoundError: ProjectNotFoundError2, + PropertyType, + QueryFailedError: QueryFailedError$2, + RateLimitedError, + RequestConflictError: RequestConflictError2, + RequiredArgumentError, + SequenceCollections, + SequenceMetadata, + SessionExpiredError: SessionExpiredError$2, + SwapType, + TaskStatus, + TimeoutError: TimeoutError3, + TokenDirectoryDisabledError, + UnauthorizedError: UnauthorizedError$3, + ValidationFailedError: ValidationFailedError$1, + WebRPCSchemaHash, + WebRPCSchemaVersion, + WebRPCVersion, + WebrpcBadMethodError: WebrpcBadMethodError$4, + WebrpcBadRequestError: WebrpcBadRequestError$4, + WebrpcBadResponseError: WebrpcBadResponseError$4, + WebrpcBadRouteError: WebrpcBadRouteError$4, + WebrpcClientDisconnectedError: WebrpcClientDisconnectedError$4, + WebrpcEndpointError: WebrpcEndpointError$4, + WebrpcError: WebrpcError$4, + WebrpcInternalErrorError: WebrpcInternalErrorError$4, + WebrpcRequestFailedError: WebrpcRequestFailedError$4, + WebrpcServerPanicError: WebrpcServerPanicError$4, + WebrpcStreamFinishedError: WebrpcStreamFinishedError$4, + WebrpcStreamLostError: WebrpcStreamLostError$4, + errors +}, Symbol.toStringTag, { value: "Module" })); +function useGateway(uri, gateway) { + const clean = uri.replace("ipfs://ipfs/", "").replace("ipfs://", ""); + if (uri.startsWith("ipfs://")) return `${gateway}${clean}`; + return uri; } -function shouldRetry(error) { - if ("code" in error && typeof error.code === "number") { - if (error.code === -1) - return true; - if (error.code === LimitExceededRpcError.code) - return true; - if (error.code === InternalRpcError.code) - return true; - return false; +function isIPFS(uri) { + return uri.startsWith("ipfs://"); +} +class CachedEIP5719 { + constructor(provider2, solver, window2 = 1e3) { + this.provider = provider2; + this.solver = solver; + this.window = window2; + this.pending = /* @__PURE__ */ new Map(); } - if (error instanceof HttpRequestError && error.status) { - if (error.status === 403) - return true; - if (error.status === 408) - return true; - if (error.status === 413) - return true; - if (error.status === 429) - return true; - if (error.status === 500) - return true; - if (error.status === 502) - return true; - if (error.status === 503) - return true; - if (error.status === 504) - return true; - return false; + async runByEIP5719(address, digest, signature2) { + const key = `${address}-${digest}-${signature2}`; + const now = Date.now(); + if (this.pending.has(key) && now - this.pending.get(key).timestamp < this.window) { + return this.pending.get(key).promise; + } + const promise = runByEIP5719(address, this.provider, digest, signature2, this.solver); + this.pending.set(key, { + timestamp: now, + promise + }); + return promise; } - return true; } -function defineChain(chain) { - return { - formatters: void 0, - fees: void 0, - serializers: void 0, - ...chain - }; +function eip5719Contract(address, provider2) { + const abi2 = [{ + inputs: [{ + internalType: "bytes32", + type: "bytes32" + }], + name: "getAlternativeSignature", + outputs: [{ + internalType: "string", + type: "string" + }], + stateMutability: "view", + type: "function" + }]; + return new Contract(address, abi2, provider2); } -const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; -const integerRegex = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; -function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, signal }) { - return new Promise((resolve, reject) => { - (async () => { - let timeoutId; - try { - const controller = new AbortController(); - if (timeout > 0) { - timeoutId = setTimeout(() => { - if (signal) { - controller.abort(); - } else { - reject(errorInstance); - } - }, timeout); - } - resolve(await fn({ signal: (controller == null ? void 0 : controller.signal) || null })); - } catch (err) { - if ((err == null ? void 0 : err.name) === "AbortError") - reject(errorInstance); - reject(err); - } finally { - clearTimeout(timeoutId); - } - })(); - }); +async function tryAwait(promise) { + try { + return await promise; + } catch (_unused3) { + return void 0; + } } -function createIdStore() { - return { - current: 0, - take() { - return this.current++; - }, - reset() { - this.current = 0; +async function runByEIP5719(address, provider2, digest, signature2, solver, tries = 0) { + if (tries > 10) throw new Error("EIP5719 - Too many tries"); + if (index$1$1.signer.canRecover(signature2)) { + const recoveredAddr = index$1$1.signer.recoverSigner(digest, signature2); + if (recoveredAddr && recoveredAddr.toLowerCase() === address.toLowerCase()) return signature2; + } + try { + if (await index$1$1.signer.isValidSignature(address, digest, signature2, provider2)) { + return signature2; } - }; + } catch (_unused4) { + } + const altUri = await tryAwait(eip5719Contract(address, provider2).getAlternativeSignature(digest)); + if (!altUri || altUri === "") throw new Error("EIP5719 - Invalid signature and no alternative signature"); + const altSignature = hexlify(await (solver || new URISolverIPFS()).resolve(altUri)); + if (!altSignature || altSignature === "") throw new Error("EIP5719 - Empty alternative signature"); + if (altSignature === hexlify(signature2)) { + throw new Error("EIP5719 - Alternative signature is invalid or the same"); + } + return runByEIP5719(address, provider2, digest, altSignature, solver, tries + 1); } -const idCache = /* @__PURE__ */ createIdStore(); -function getHttpRpcClient(url, options = {}) { - return { - async request(params) { - var _a2; - const { body, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params; - const fetchOptions = { - ...options.fetchOptions ?? {}, - ...params.fetchOptions ?? {} - }; - const { headers, method, signal: signal_ } = fetchOptions; - try { - const response = await withTimeout(async ({ signal }) => { - const init2 = { - ...fetchOptions, - body: Array.isArray(body) ? stringify(body.map((body2) => ({ - jsonrpc: "2.0", - id: body2.id ?? idCache.take(), - ...body2 - }))) : stringify({ - jsonrpc: "2.0", - id: body.id ?? idCache.take(), - ...body - }), - headers: { - "Content-Type": "application/json", - ...headers - }, - method: method || "POST", - signal: signal_ || (timeout > 0 ? signal : null) - }; - const request = new Request(url, init2); - if (onRequest) - await onRequest(request); - const response2 = await fetch(url, init2); - return response2; - }, { - errorInstance: new TimeoutError3({ body, url }), - timeout, - signal: true - }); - if (onResponse) - await onResponse(response); - let data; - if ((_a2 = response.headers.get("Content-Type")) == null ? void 0 : _a2.startsWith("application/json")) - data = await response.json(); - else { - data = await response.text(); - data = JSON.parse(data || "{}"); - } - if (!response.ok) { - throw new HttpRequestError({ - body, - details: stringify(data.error) || response.statusText, - headers: response.headers, - status: response.status, - url - }); - } - return data; - } catch (err) { - if (err instanceof HttpRequestError) - throw err; - if (err instanceof TimeoutError3) - throw err; - throw new HttpRequestError({ - body, - cause: err, - url - }); - } - } - }; +class URISolverIPFS { + constructor(gateway = "https://cloudflare-ipfs.com/ipfs/") { + var _this = this; + this.gateway = gateway; + this.uri = (uri) => { + if (isIPFS(uri)) return useGateway(uri, this.gateway); + return uri; + }; + this.resolve = async function(uri) { + const url = _this.uri(uri); + const res = await fetch(url); + if (!res.ok) throw new Error(`URISolverIPFS - Failed to fetch ${url}`); + return await res.text(); + }; + } +} +const instanceOfAny = (object2, constructors) => constructors.some((c2) => object2 instanceof c2); +let idbProxyableTypes; +let cursorAdvanceMethods; +function getIdbProxyableTypes() { + return idbProxyableTypes || (idbProxyableTypes = [ + IDBDatabase, + IDBObjectStore, + IDBIndex, + IDBCursor, + IDBTransaction + ]); +} +function getCursorAdvanceMethods() { + return cursorAdvanceMethods || (cursorAdvanceMethods = [ + IDBCursor.prototype.advance, + IDBCursor.prototype.continue, + IDBCursor.prototype.continuePrimaryKey + ]); } -function webSocket(socketClient, { body, onError, onResponse }) { - socketClient.request({ - body, - onError, - onResponse +const cursorRequestMap = /* @__PURE__ */ new WeakMap(); +const transactionDoneMap = /* @__PURE__ */ new WeakMap(); +const transactionStoreNamesMap = /* @__PURE__ */ new WeakMap(); +const transformCache = /* @__PURE__ */ new WeakMap(); +const reverseTransformCache = /* @__PURE__ */ new WeakMap(); +function promisifyRequest(request) { + const promise = new Promise((resolve, reject) => { + const unlisten = () => { + request.removeEventListener("success", success); + request.removeEventListener("error", error); + }; + const success = () => { + resolve(wrap(request.result)); + unlisten(); + }; + const error = () => { + reject(request.error); + unlisten(); + }; + request.addEventListener("success", success); + request.addEventListener("error", error); + }); + promise.then((value) => { + if (value instanceof IDBCursor) { + cursorRequestMap.set(value, request); + } + }).catch(() => { }); - return socketClient; + reverseTransformCache.set(promise, request); + return promise; } -async function webSocketAsync(socketClient, { body, timeout = 1e4 }) { - return socketClient.requestAsync({ - body, - timeout +function cacheDonePromiseForTransaction(tx) { + if (transactionDoneMap.has(tx)) + return; + const done = new Promise((resolve, reject) => { + const unlisten = () => { + tx.removeEventListener("complete", complete); + tx.removeEventListener("error", error); + tx.removeEventListener("abort", error); + }; + const complete = () => { + resolve(); + unlisten(); + }; + const error = () => { + reject(tx.error || new DOMException("AbortError", "AbortError")); + unlisten(); + }; + tx.addEventListener("complete", complete); + tx.addEventListener("error", error); + tx.addEventListener("abort", error); }); + transactionDoneMap.set(tx, done); } -const rpc = { - /** - * @deprecated use `getHttpRpcClient` instead. - * - * ```diff - * -import { rpc } from 'viem/utils' - * +import { getHttpRpcClient } from 'viem/utils' - * - * -rpc.http(url, params) - * +const httpClient = getHttpRpcClient(url) - * +httpClient.request(params) - * ``` - */ - http(url, params) { - return getHttpRpcClient(url).request(params); +let idbProxyTraps = { + get(target, prop, receiver) { + if (target instanceof IDBTransaction) { + if (prop === "done") + return transactionDoneMap.get(target); + if (prop === "objectStoreNames") { + return target.objectStoreNames || transactionStoreNamesMap.get(target); + } + if (prop === "store") { + return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]); + } + } + return wrap(target[prop]); }, - /** - * @deprecated use `getWebSocketRpcClient` instead. - * - * ```diff - * -import { rpc } from 'viem/utils' - * +import { getWebSocketRpcClient } from 'viem/utils' - * - * -rpc.webSocket(url, params) - * +const webSocketClient = getWebSocketRpcClient(url) - * +webSocketClient.request(params) - * ``` - */ - webSocket, - /** - * @deprecated use `getWebSocketRpcClient` instead. - * - * ```diff - * -import { rpc } from 'viem/utils' - * +import { getWebSocketRpcClient } from 'viem/utils' - * - * -const response = await rpc.webSocketAsync(url, params) - * +const webSocketClient = getWebSocketRpcClient(url) - * +const response = await webSocketClient.requestAsync(params) - * ``` - */ - webSocketAsync + set(target, prop, value) { + target[prop] = value; + return true; + }, + has(target, prop) { + if (target instanceof IDBTransaction && (prop === "done" || prop === "store")) { + return true; + } + return prop in target; + } }; -function hashTypedData(parameters) { - const { domain: domain2 = {}, message, primaryType } = parameters; - const types2 = { - EIP712Domain: getTypesForEIP712Domain({ domain: domain2 }), - ...parameters.types - }; - validateTypedData({ - domain: domain2, - message, - primaryType, - types: types2 - }); - const parts = ["0x1901"]; - if (domain2) - parts.push(hashDomain({ - domain: domain2, - types: types2 - })); - if (primaryType !== "EIP712Domain") - parts.push(hashStruct({ - data: message, - primaryType, - types: types2 - })); - return keccak256(concat(parts)); +function replaceTraps(callback) { + idbProxyTraps = callback(idbProxyTraps); } -function hashDomain({ domain: domain2, types: types2 }) { - return hashStruct({ - data: domain2, - primaryType: "EIP712Domain", - types: types2 - }); +function wrapFunction(func) { + if (func === IDBDatabase.prototype.transaction && !("objectStoreNames" in IDBTransaction.prototype)) { + return function(storeNames, ...args) { + const tx = func.call(unwrap(this), storeNames, ...args); + transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); + return wrap(tx); + }; + } + if (getCursorAdvanceMethods().includes(func)) { + return function(...args) { + func.apply(unwrap(this), args); + return wrap(cursorRequestMap.get(this)); + }; + } + return function(...args) { + return wrap(func.apply(unwrap(this), args)); + }; } -function hashStruct({ data, primaryType, types: types2 }) { - const encoded = encodeData({ - data, - primaryType, - types: types2 - }); - return keccak256(encoded); +function transformCachableValue(value) { + if (typeof value === "function") + return wrapFunction(value); + if (value instanceof IDBTransaction) + cacheDonePromiseForTransaction(value); + if (instanceOfAny(value, getIdbProxyableTypes())) + return new Proxy(value, idbProxyTraps); + return value; } -function encodeData({ data, primaryType, types: types2 }) { - const encodedTypes = [{ type: "bytes32" }]; - const encodedValues = [hashType({ primaryType, types: types2 })]; - for (const field of types2[primaryType]) { - const [type, value] = encodeField({ - types: types2, - name: field.name, - type: field.type, - value: data[field.name] +function wrap(value) { + if (value instanceof IDBRequest) + return promisifyRequest(value); + if (transformCache.has(value)) + return transformCache.get(value); + const newValue = transformCachableValue(value); + if (newValue !== value) { + transformCache.set(value, newValue); + reverseTransformCache.set(newValue, value); + } + return newValue; +} +const unwrap = (value) => reverseTransformCache.get(value); +function openDB(name2, version2, { blocked, upgrade, blocking, terminated } = {}) { + const request = indexedDB.open(name2, version2); + const openPromise = wrap(request); + if (upgrade) { + request.addEventListener("upgradeneeded", (event) => { + upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event); }); - encodedTypes.push(type); - encodedValues.push(value); } - return encodeAbiParameters(encodedTypes, encodedValues); + if (blocked) { + request.addEventListener("blocked", (event) => blocked( + // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 + event.oldVersion, + event.newVersion, + event + )); + } + openPromise.then((db2) => { + if (terminated) + db2.addEventListener("close", () => terminated()); + if (blocking) { + db2.addEventListener("versionchange", (event) => blocking(event.oldVersion, event.newVersion, event)); + } + }).catch(() => { + }); + return openPromise; } -function hashType({ primaryType, types: types2 }) { - const encodedHashType = toHex$1(encodeType({ primaryType, types: types2 })); - return keccak256(encodedHashType); +const readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"]; +const writeMethods = ["put", "add", "delete", "clear"]; +const cachedMethods = /* @__PURE__ */ new Map(); +function getMethod(target, prop) { + if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === "string")) { + return; + } + if (cachedMethods.get(prop)) + return cachedMethods.get(prop); + const targetFuncName = prop.replace(/FromIndex$/, ""); + const useIndex = prop !== targetFuncName; + const isWrite = writeMethods.includes(targetFuncName); + if ( + // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. + !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName)) + ) { + return; + } + const method = async function(storeName, ...args) { + const tx = this.transaction(storeName, isWrite ? "readwrite" : "readonly"); + let target2 = tx.store; + if (useIndex) + target2 = target2.index(args.shift()); + return (await Promise.all([ + target2[targetFuncName](...args), + isWrite && tx.done + ]))[0]; + }; + cachedMethods.set(prop, method); + return method; } -function encodeType({ primaryType, types: types2 }) { - let result = ""; - const unsortedDeps = findTypeDependencies({ primaryType, types: types2 }); - unsortedDeps.delete(primaryType); - const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; - for (const type of deps) { - result += `${type}(${types2[type].map(({ name: name2, type: t2 }) => `${t2} ${name2}`).join(",")})`; +replaceTraps((oldTraps) => ({ + ...oldTraps, + get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), + has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop) +})); +class ConfigTracker { + constructor() { + this.loadPresignedConfiguration = void 0; + this.savePresignedConfiguration = void 0; + this.saveWitnesses = void 0; + this.configOfImageHash = void 0; + this.saveWalletConfig = void 0; + this.imageHashOfCounterfactualWallet = void 0; + this.saveCounterfactualWallet = void 0; + this.walletsOfSigner = void 0; } - return result; } -function findTypeDependencies({ primaryType: primaryType_, types: types2 }, results2 = /* @__PURE__ */ new Set()) { - const match = primaryType_.match(/^\w*/u); - const primaryType = match == null ? void 0 : match[0]; - if (results2.has(primaryType) || types2[primaryType] === void 0) { - return results2; +var tracker = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ConfigTracker +}); +class DebugConfigTracker { + constructor(tracker2) { + this.tracker = tracker2; } - results2.add(primaryType); - for (const field of types2[primaryType]) { - findTypeDependencies({ primaryType: field.type, types: types2 }, results2); + async loadPresignedConfiguration(args) { + console.debug("? loadPresignedConfiguration"); + debug(args, "? "); + return debug(await this.tracker.loadPresignedConfiguration(args), "! "); } - return results2; -} -function encodeField({ types: types2, name: name2, type, value }) { - if (types2[type] !== void 0) { - return [ - { type: "bytes32" }, - keccak256(encodeData({ data: value, primaryType: type, types: types2 })) - ]; + savePresignedConfiguration(args) { + console.debug("? savePresignedConfiguration"); + debug(args, "? "); + return this.tracker.savePresignedConfiguration(args); } - if (type === "bytes") { - const prepend = value.length % 2 ? "0" : ""; - value = `0x${prepend + value.slice(2)}`; - return [{ type: "bytes32" }, keccak256(value)]; + saveWitnesses(args) { + console.debug("? saveWitnesses"); + debug(args, "? "); + return this.tracker.saveWitnesses(args); } - if (type === "string") - return [{ type: "bytes32" }, keccak256(toHex$1(value))]; - if (type.lastIndexOf("]") === type.length - 1) { - const parsedType = type.slice(0, type.lastIndexOf("[")); - const typeValuePairs = value.map((item2) => encodeField({ - name: name2, - type: parsedType, - types: types2, - value: item2 - })); - return [ - { type: "bytes32" }, - keccak256(encodeAbiParameters(typeValuePairs.map(([t2]) => t2), typeValuePairs.map(([, v3]) => v3))) - ]; + async configOfImageHash(args) { + console.debug("? configOfImageHash"); + debug(args, "? "); + return debug(await this.tracker.configOfImageHash(args), "! "); + } + saveWalletConfig(args) { + console.debug("? saveWalletConfig"); + debug(args, "? "); + return this.tracker.saveWalletConfig(args); + } + async imageHashOfCounterfactualWallet(args) { + console.debug("? imageHashOfCounterfactualWallet"); + debug(args, "? "); + return debug(await this.tracker.imageHashOfCounterfactualWallet(args), "! "); + } + saveCounterfactualWallet(args) { + console.debug("? saveCounterfactualWallet"); + debug(args, "? "); + return this.tracker.saveCounterfactualWallet(args); + } + async walletsOfSigner(args) { + console.debug("? walletsOfSigner"); + debug(args, "? "); + return debug(await this.tracker.walletsOfSigner(args), "! "); + } + async getMigration(address, fromImageHash, fromVersion, chainId) { + console.debug("? getMigration"); + debug({ + address, + fromImageHash, + fromVersion, + chainId + }, "? "); + return debug(await this.tracker.getMigration(address, fromImageHash, fromVersion, chainId), "! "); + } + saveMigration(address, signed2, contexts) { + console.debug("? saveMigration"); + debug({ + address, + signed: signed2, + contexts + }, "? "); + return this.tracker.saveMigration(address, signed2, contexts); } - return [{ type }, value]; } -function serializeTypedData(parameters) { - const { domain: domain_, message: message_, primaryType, types: types2 } = parameters; - const normalizeData = (struct, data_) => { - const data = { ...data_ }; - for (const param of struct) { - const { name: name2, type } = param; - if (type === "address") - data[name2] = data[name2].toLowerCase(); - } - return data; - }; - const domain2 = (() => { - if (!types2.EIP712Domain) - return {}; - if (!domain_) - return {}; - return normalizeData(types2.EIP712Domain, domain_); - })(); - const message = (() => { - if (primaryType === "EIP712Domain") - return void 0; - return normalizeData(types2[primaryType], message_); - })(); - return stringify({ domain: domain2, message, primaryType, types: types2 }); +function debug(value, prefix = "") { + switch (value) { + case void 0: + console.debug(prefix + "undefined"); + break; + default: + JSON.stringify(value, bigintReplacer, 2).split("\n").map((line) => prefix + line).forEach((line) => console.debug(line)); + break; + } + return value; } -function validateTypedData(parameters) { - const { domain: domain2, message, primaryType, types: types2 } = parameters; - const validateData = (struct, data) => { - for (const param of struct) { - const { name: name2, type } = param; - const value = data[name2]; - const integerMatch = type.match(integerRegex); - if (integerMatch && (typeof value === "number" || typeof value === "bigint")) { - const [_type2, base, size_] = integerMatch; - numberToHex(value, { - signed: base === "int", - size: Number.parseInt(size_) / 8 - }); - } - if (type === "address" && typeof value === "string" && !isAddress(value)) - throw new InvalidAddressError({ address: value }); - const bytesMatch = type.match(bytesRegex); - if (bytesMatch) { - const [_type2, size_] = bytesMatch; - if (size_ && size$5(value) !== Number.parseInt(size_)) - throw new BytesSizeMismatchError({ - expectedSize: Number.parseInt(size_), - givenSize: size$5(value) - }); +var debug$1 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + DebugConfigTracker +}); +function _extends$5() { + _extends$5 = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } } - const struct2 = types2[type]; - if (struct2) - validateData(struct2, value); } + return target; }; - if (types2.EIP712Domain && domain2) - validateData(types2.EIP712Domain, domain2); - if (primaryType !== "EIP712Domain") - validateData(types2[primaryType], message); -} -function getTypesForEIP712Domain({ domain: domain2 }) { - return [ - typeof (domain2 == null ? void 0 : domain2.name) === "string" && { name: "name", type: "string" }, - (domain2 == null ? void 0 : domain2.version) && { name: "version", type: "string" }, - typeof (domain2 == null ? void 0 : domain2.chainId) === "number" && { - name: "chainId", - type: "uint256" - }, - (domain2 == null ? void 0 : domain2.verifyingContract) && { - name: "verifyingContract", - type: "address" - }, - (domain2 == null ? void 0 : domain2.salt) && { name: "salt", type: "bytes32" } - ].filter(Boolean); -} -const presignMessagePrefix = "Ethereum Signed Message:\n"; -function toPrefixedMessage(message_) { - const message = (() => { - if (typeof message_ === "string") - return stringToHex(message_); - if (typeof message_.raw === "string") - return message_.raw; - return bytesToHex$1(message_.raw); - })(); - const prefix = stringToHex(`${presignMessagePrefix}${size$5(message)}`); - return concat([prefix, message]); -} -function hashMessage(message, to_) { - return keccak256(toPrefixedMessage(message), to_); -} -const erc6492MagicBytes = "0x6492649264926492649264926492649264926492649264926492649264926492"; -function isErc6492Signature(signature2) { - return sliceHex(signature2, -32) === erc6492MagicBytes; -} -function serializeErc6492Signature(parameters) { - const { address, data, signature: signature2, to = "hex" } = parameters; - const signature_ = concatHex([ - encodeAbiParameters([{ type: "address" }, { type: "bytes" }, { type: "bytes" }], [address, data, signature2]), - erc6492MagicBytes - ]); - if (to === "hex") - return signature_; - return hexToBytes$1(signature_); + return _extends$5.apply(this, arguments); } -class InvalidDecimalNumberError extends BaseError$3 { - constructor({ value }) { - super(`Number \`${value}\` is not a valid decimal number.`, { - name: "InvalidDecimalNumberError" - }); +class MemoryTrackerStore { + constructor() { + this.configs = {}; + this.v2Nodes = {}; + this.counterfactualWallets = {}; + this.payloads = {}; + this.signatures = {}; + this.migrations = {}; + this.loadConfig = (imageHash2) => { + return Promise.resolve(this.configs[imageHash2]); + }; + this.saveConfig = (imageHash2, config2) => { + this.configs[imageHash2] = config2; + return Promise.resolve(); + }; + this.loadV2Node = (nodeHash) => { + return Promise.resolve(this.v2Nodes[nodeHash]); + }; + this.saveV2Node = (nodeHash, node) => { + this.v2Nodes[nodeHash] = node; + return Promise.resolve(); + }; + this.loadCounterfactualWallet = (wallet) => { + return Promise.resolve(this.counterfactualWallets[wallet]); + }; + this.saveCounterfactualWallet = (wallet, imageHash2, context2) => { + this.counterfactualWallets[wallet] = { + imageHash: imageHash2, + context: context2 + }; + return Promise.resolve(); + }; + this.loadPayloadOfSubdigest = (subdigest) => { + return Promise.resolve(this.payloads[subdigest]); + }; + this.savePayloadOfSubdigest = (subdigest, payload) => { + this.payloads[subdigest] = payload; + return Promise.resolve(); + }; + this.loadSubdigestsOfSigner = (signer2) => { + return Promise.resolve(Object.keys(this.signatures[signer2] || {})); + }; + this.loadSignatureOfSubdigest = (signer2, subdigest) => { + var _this$signatures$sign; + return Promise.resolve((_this$signatures$sign = this.signatures[signer2]) == null ? void 0 : _this$signatures$sign[subdigest]); + }; + this.saveSignatureOfSubdigest = (signer2, subdigest, payload) => { + if (!this.signatures[signer2]) this.signatures[signer2] = {}; + this.signatures[signer2][subdigest] = payload; + return Promise.resolve(); + }; + this.loadMigrationsSubdigest = (wallet, fromVersion, toVersion) => { + var _this$migrations$wall; + return Promise.resolve(((_this$migrations$wall = this.migrations[wallet]) == null || (_this$migrations$wall = _this$migrations$wall[fromVersion]) == null ? void 0 : _this$migrations$wall[toVersion]) || []); + }; + this.saveMigrationsSubdigest = (wallet, fromVersion, toVersion, subdigest, toImageHash) => { + if (!this.migrations[wallet]) this.migrations[wallet] = {}; + if (!this.migrations[wallet][fromVersion]) this.migrations[wallet][fromVersion] = {}; + if (!this.migrations[wallet][fromVersion][toVersion]) this.migrations[wallet][fromVersion][toVersion] = []; + this.migrations[wallet][fromVersion][toVersion].push({ + subdigest, + toImageHash + }); + return Promise.resolve(); + }; } } -function parseUnits(value, decimals) { - if (!/^(-?)([0-9]*)\.?([0-9]*)$/.test(value)) - throw new InvalidDecimalNumberError({ value }); - let [integer, fraction = "0"] = value.split("."); - const negative = integer.startsWith("-"); - if (negative) - integer = integer.slice(1); - fraction = fraction.replace(/(0+)$/, ""); - if (decimals === 0) { - if (Math.round(Number(`.${fraction}`)) === 1) - integer = `${BigInt(integer) + 1n}`; - fraction = ""; - } else if (fraction.length > decimals) { - const [left, unit, right] = [ - fraction.slice(0, decimals - 1), - fraction.slice(decimals - 1, decimals), - fraction.slice(decimals) - ]; - const rounded = Math.round(Number(`${unit}.${right}`)); - if (rounded > 9) - fraction = `${BigInt(left) + BigInt(1)}0`.padStart(left.length + 1, "0"); - else - fraction = `${left}${rounded}`; - if (fraction.length > decimals) { - fraction = fraction.slice(1); - integer = `${BigInt(integer) + 1n}`; +function recreateBigNumbers(object2) { + if (object2 === void 0) return void 0; + const result = {}; + for (const key of Object.keys(object2)) { + const val = object2[key]; + if (val._isBigNumber === true && val._hex !== void 0 && typeof val._hex === "string" && val._hex.length !== "") { + result[key] = BigInt(val._hex); + } else if (Array.isArray(val)) { + result[key] = val.map((v3) => recreateBigNumbers(v3)); + } else if (typeof val === "object" && val !== null) { + result[key] = recreateBigNumbers(val); + } else { + result[key] = val; } - fraction = fraction.slice(0, decimals); - } else { - fraction = fraction.padEnd(decimals, "0"); } - return BigInt(`${negative ? "-" : ""}${integer}${fraction}`); + return result; +} +class IndexedDBStore { + constructor(dbName) { + var _this = this; + this.dbName = dbName; + this._lazyDb = void 0; + this.loadConfig = async function(imageHash2) { + const db2 = await _this.getDb(); + return db2.get("configs", imageHash2).then((c2) => recreateBigNumbers(c2)); + }; + this.saveConfig = async function(imageHash2, config2) { + const db2 = await _this.getDb(); + await db2.put("configs", config2, imageHash2); + }; + this.loadV2Node = async function(nodeHash) { + const db2 = await _this.getDb(); + return db2.get("v2Nodes", nodeHash).then((c2) => recreateBigNumbers(c2)); + }; + this.saveV2Node = async function(nodeHash, node) { + const db2 = await _this.getDb(); + await db2.put("v2Nodes", node, nodeHash); + }; + this.loadCounterfactualWallet = async function(wallet) { + const db2 = await _this.getDb(); + return db2.get("counterfactualWallets", wallet); + }; + this.saveCounterfactualWallet = async function(wallet, imageHash2, context2) { + const db2 = await _this.getDb(); + await db2.put("counterfactualWallets", { + imageHash: imageHash2, + context: context2 + }, wallet); + }; + this.loadPayloadOfSubdigest = async function(subdigest) { + const db2 = await _this.getDb(); + return db2.get("payloads", subdigest).then((c2) => recreateBigNumbers(c2)); + }; + this.savePayloadOfSubdigest = async function(subdigest, payload) { + const db2 = await _this.getDb(); + await db2.put("payloads", payload, subdigest); + }; + this.loadSubdigestsOfSigner = async function(signer2) { + const db2 = await _this.getDb(); + const index2 = await db2.getAllKeysFromIndex("signatures", "signer", IDBKeyRange.only(signer2)); + return index2.map((key) => key.split("-")[0]); + }; + this.loadSignatureOfSubdigest = async function(signer2, subdigest) { + const db2 = await _this.getDb(); + const signature2 = await db2.get("signatures", [subdigest, signer2].join("-")); + return signature2 == null ? void 0 : signature2.signature; + }; + this.saveSignatureOfSubdigest = async function(signer2, subdigest, payload) { + const db2 = await _this.getDb(); + await db2.put("signatures", { + signature: payload, + signer: signer2 + }, [subdigest, signer2].join("-")); + }; + this.loadMigrationsSubdigest = async function(wallet, fromVersion, toVersion) { + const db2 = await _this.getDb(); + const index2 = await db2.getAllFromIndex("migrations", "jump", IDBKeyRange.only([wallet, fromVersion, toVersion])); + return index2.map((key) => ({ + subdigest: key.subdigest, + toImageHash: key.toImageHash + })); + }; + this.saveMigrationsSubdigest = async function(wallet, fromVersion, toVersion, subdigest, toImageHash) { + const db2 = await _this.getDb(); + await db2.put("migrations", { + wallet, + fromVersion, + toVersion, + subdigest, + toImageHash + }, subdigest); + }; + } + async getDb() { + if (this._lazyDb) return this._lazyDb; + const dbName = this.dbName; + this._lazyDb = await openDB(dbName, 1, { + upgrade(db2, oldVersion, newVersion, transaction2) { + console.log(`upgrading ${dbName} from ${oldVersion} to ${newVersion} - ${transaction2}`); + if (oldVersion === 0) { + db2.createObjectStore("configs"); + db2.createObjectStore("v2Nodes"); + db2.createObjectStore("counterfactualWallets"); + db2.createObjectStore("payloads"); + const signatures = db2.createObjectStore("signatures"); + signatures.createIndex("signer", "signer", { + unique: false + }); + const migrations = db2.createObjectStore("migrations"); + migrations.createIndex("jump", ["wallet", "fromVersion", "toVersion"]); + } + } + }); + return this._lazyDb; + } } -function formatStorageProof(storageProof) { - return storageProof.map((proof) => ({ - ...proof, - value: BigInt(proof.value) - })); +function isPlainNode(node) { + return node.left !== void 0 && node.right !== void 0; } -function formatProof(proof) { - return { - ...proof, - balance: proof.balance ? BigInt(proof.balance) : void 0, - nonce: proof.nonce ? hexToNumber$1(proof.nonce) : void 0, - storageProof: proof.storageProof ? formatStorageProof(proof.storageProof) : void 0 - }; +function isPlainNested(node) { + return node.weight !== void 0 && node.threshold !== void 0 && node.tree !== void 0; } -async function getProof(client2, { address, blockNumber, blockTag: blockTag_, storageKeys }) { - const blockTag = blockTag_ ?? "latest"; - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - const proof = await client2.request({ - method: "eth_getProof", - params: [address, storageKeys, blockNumberHex || blockTag] - }); - return formatProof(proof); +function isPlainV2Config(config2) { + return config2.version === 2 && config2.threshold !== void 0 && config2.checkpoint !== void 0 && config2.tree !== void 0 && typeof config2.tree === "string"; } -async function waitForTransactionReceipt(client2, { - confirmations = 1, - hash: hash2, - onReplaced, - pollingInterval = client2.pollingInterval, - retryCount = 6, - retryDelay = ({ count: count2 }) => ~~(1 << count2) * 200, - // exponential backoff - timeout -}) { - const observerId = stringify(["waitForTransactionReceipt", client2.uid, hash2]); - let count2 = 0; - let transaction2; - let replacedTransaction; - let receipt; - let retrying = false; - return new Promise((resolve, reject) => { - if (timeout) - setTimeout(() => reject(new WaitForTransactionReceiptTimeoutError({ hash: hash2 })), timeout); - const _unobserve = observe(observerId, { onReplaced, resolve, reject }, (emit2) => { - const _unwatch = getAction$1(client2, watchBlockNumber, "watchBlockNumber")({ - emitMissed: true, - emitOnBegin: true, - poll: true, - pollingInterval, - async onBlockNumber(blockNumber_) { - const done = (fn) => { - _unwatch(); - fn(); - _unobserve(); - }; - let blockNumber = blockNumber_; - if (retrying) - return; - if (count2 > retryCount) - done(() => emit2.reject(new WaitForTransactionReceiptTimeoutError({ hash: hash2 }))); - try { - if (receipt) { - if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) - return; - done(() => emit2.resolve(receipt)); - return; - } - if (!transaction2) { - retrying = true; - await withRetry(async () => { - transaction2 = await getAction$1(client2, getTransaction, "getTransaction")({ hash: hash2 }); - if (transaction2.blockNumber) - blockNumber = transaction2.blockNumber; - }, { - delay: retryDelay, - retryCount - }); - retrying = false; - } - receipt = await getAction$1(client2, getTransactionReceipt$1, "getTransactionReceipt")({ hash: hash2 }); - if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) - return; - done(() => emit2.resolve(receipt)); - } catch (err) { - if (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError) { - if (!transaction2) { - retrying = false; - return; - } - try { - replacedTransaction = transaction2; - retrying = true; - const block = await withRetry(() => getAction$1(client2, getBlock, "getBlock")({ - blockNumber, - includeTransactions: true - }), { - delay: retryDelay, - retryCount, - shouldRetry: ({ error }) => error instanceof BlockNotFoundError - }); - retrying = false; - const replacementTransaction = block.transactions.find(({ from, nonce }) => from === replacedTransaction.from && nonce === replacedTransaction.nonce); - if (!replacementTransaction) - return; - receipt = await getAction$1(client2, getTransactionReceipt$1, "getTransactionReceipt")({ - hash: replacementTransaction.hash - }); - if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) - return; - let reason = "replaced"; - if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value) { - reason = "repriced"; - } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) { - reason = "cancelled"; - } - done(() => { - var _a2; - (_a2 = emit2.onReplaced) == null ? void 0 : _a2.call(emit2, { - reason, - replacedTransaction, - transaction: replacementTransaction, - transactionReceipt: receipt - }); - emit2.resolve(receipt); - }); - } catch (err_) { - done(() => emit2.reject(err_)); - } - } else { - done(() => emit2.reject(err)); - } - } finally { - count2++; - } +var index$2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + isPlainNode, + isPlainNested, + isPlainV2Config, + MemoryTrackerStore, + recreateBigNumbers, + IndexedDBStore +}); +class LocalConfigTracker { + constructor(provider2, store = new MemoryTrackerStore(), useEIP5719 = false) { + var _this = this; + this.provider = provider2; + this.store = store; + this.useEIP5719 = useEIP5719; + this.cachedEIP5719 = void 0; + this.loadTopology = async function(hash2) { + const node = await _this.store.loadV2Node(hash2); + if (!node) return { + nodeHash: hash2 + }; + if (isPlainNode(node)) { + const [left, right] = await Promise.all([_this.loadTopology(node.left), _this.loadTopology(node.right)]); + return { + left, + right + }; + } + if (isPlainNested(node)) { + return { + weight: BigInt(node.weight), + threshold: BigInt(node.threshold), + tree: await _this.loadTopology(node.tree) + }; + } + return node; + }; + this.saveTopology = async function(node) { + if (v2.config.isNodeLeaf(node)) { + return; + } + const hash2 = v2.config.hashNode(node); + if (v2.config.isNode(node)) { + const saveLeft = _this.saveTopology(node.left); + const saveRight = _this.saveTopology(node.right); + const saveThis = _this.store.saveV2Node(hash2, { + left: v2.config.hashNode(node.left), + right: v2.config.hashNode(node.right) + }); + await Promise.all([saveLeft, saveRight, saveThis]); + return; + } + if (v2.config.isNestedLeaf(node)) { + const saveTree = _this.saveTopology(node.tree); + const saveThis = _this.store.saveV2Node(hash2, { + weight: BigInt(node.weight).toString(), + threshold: BigInt(node.threshold).toString(), + tree: v2.config.hashNode(node.tree) + }); + await Promise.all([saveTree, saveThis]); + return; + } + if (v2.config.isSignerLeaf(node)) { + return _this.store.saveV2Node(hash2, { + address: node.address, + weight: node.weight + }); + } + if (v2.config.isSubdigestLeaf(node)) { + return _this.store.saveV2Node(hash2, { + subdigest: node.subdigest + }); + } + throw new Error(`Unknown topology type: ${node}`); + }; + this.saveWalletConfig = async function(args) { + const { + config: config2 + } = args; + if (v1.config.ConfigCoder.isWalletConfig(config2)) { + const imageHash2 = v1.config.ConfigCoder.imageHashOf(config2); + return _this.store.saveConfig(imageHash2, config2); + } + if (v2.config.ConfigCoder.isWalletConfig(config2)) { + const imageHash2 = v2.config.ConfigCoder.imageHashOf(config2); + if (v2.config.isComplete(config2.tree)) { + return _this.store.saveConfig(imageHash2, config2); } + } + return; + }; + this.configOfImageHashCache = {}; + this.configOfImageHash = async function(args) { + const { + imageHash: imageHash2 + } = args; + if (_this.configOfImageHashCache[args.imageHash]) { + return _this.configOfImageHashCache[args.imageHash]; + } + const config2 = await _this.store.loadConfig(imageHash2); + if (!config2) { + return void 0; + } + if (config2.version === 1 || config2.version === 2 && !isPlainV2Config(config2)) { + _this.configOfImageHashCache[args.imageHash] = config2; + return config2; + } + if (isPlainV2Config(config2)) { + const fullConfig = { + version: 2, + threshold: BigInt(config2.threshold), + checkpoint: BigInt(config2.checkpoint), + tree: await _this.loadTopology(config2.tree) + }; + _this.configOfImageHashCache[args.imageHash] = fullConfig; + return fullConfig; + } + throw new Error(`Unknown config type: ${config2}`); + }; + this.saveCounterfactualWallet = async function(args) { + const { + config: config2, + context: context2 + } = args; + const imageHash2 = index$6.genericCoderFor(config2.version).config.imageHashOf(config2); + await Promise.all([_this.saveWalletConfig({ + config: config2 + }), ...context2.map((ctx) => { + const address = index$1$1.context.addressOf(ctx, imageHash2); + return _this.store.saveCounterfactualWallet(address, imageHash2, ctx); + })]); + }; + this.imageHashOfCounterfactualWallet = async function(args) { + const { + wallet + } = args; + const result = await _this.store.loadCounterfactualWallet(wallet); + if (!result) return void 0; + return { + imageHash: result.imageHash, + context: result.context + }; + }; + this.savePayload = async function(args) { + const { + payload + } = args; + const subdigest = index$1$1.signature.subdigestOf(payload); + await _this.store.savePayloadOfSubdigest(subdigest, payload); + }; + this.payloadOfSubdigestCache = {}; + this.payloadOfSubdigest = async function(args) { + if (_this.payloadOfSubdigestCache[args.subdigest]) { + return _this.payloadOfSubdigestCache[args.subdigest]; + } + const { + subdigest + } = args; + const res = await _this.store.loadPayloadOfSubdigest(subdigest); + if (res) { + _this.payloadOfSubdigestCache[subdigest] = res; + } + return res; + }; + this.savePresignedConfiguration = async function(args) { + const decoded = v2.signature.SignatureCoder.decode(args.signature); + const nextImageHash = index$6.genericCoderFor(args.nextConfig.version).config.imageHashOf(args.nextConfig); + const message = v2.chained.messageSetImageHash(nextImageHash); + const digest = keccak256(message); + const payload = { + message, + address: args.wallet, + chainId: 0, + digest + }; + const savePayload = _this.savePayload({ + payload }); - }); - }); -} -async function requestAddresses(client2) { - const addresses = await client2.request({ method: "eth_requestAccounts" }, { dedupe: true, retryCount: 0 }); - return addresses.map((address) => getAddress(address)); -} -async function requestPermissions(client2, permissions) { - return client2.request({ - method: "wallet_requestPermissions", - params: [permissions] - }, { retryCount: 0 }); -} -async function signTransaction(client2, parameters) { - var _a2, _b2, _c2, _d2; - const { account: account_ = client2.account, chain = client2.chain, ...transaction2 } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/signTransaction" - }); - const account2 = parseAccount(account_); - assertRequest({ - account: account2, - ...parameters - }); - const chainId = await getAction$1(client2, getChainId$1, "getChainId")({}); - if (chain !== null) - assertCurrentChain({ - currentChainId: chainId, - chain - }); - const formatters = (chain == null ? void 0 : chain.formatters) || ((_a2 = client2.chain) == null ? void 0 : _a2.formatters); - const format2 = ((_b2 = formatters == null ? void 0 : formatters.transactionRequest) == null ? void 0 : _b2.format) || formatTransactionRequest; - if (account2.signTransaction) - return account2.signTransaction({ - ...transaction2, - chainId - }, { serializer: (_d2 = (_c2 = client2.chain) == null ? void 0 : _c2.serializers) == null ? void 0 : _d2.transaction }); - return await client2.request({ - method: "eth_signTransaction", - params: [ - { - ...format2(transaction2), - chainId: numberToHex(chainId), - from: account2.address + const saveNextConfig = _this.saveWalletConfig({ + config: args.nextConfig + }); + const recovered = await v2.signature.SignatureCoder.recover(decoded, payload, _this.provider); + const signatures = v2.signature.signaturesOf(recovered.config.tree); + await Promise.all([savePayload, saveNextConfig, _this.saveWalletConfig({ + config: recovered.config + }), ...signatures.map((sig) => _this.store.saveSignatureOfSubdigest(sig.address, recovered.subdigest, sig.signature))]); + }; + this.loadPresignedConfiguration = async function(args) { + const { + wallet, + fromImageHash, + longestPath + } = args; + const fromConfig = await _this.configOfImageHash({ + imageHash: fromImageHash + }); + if (!fromConfig || !v2.config.ConfigCoder.isWalletConfig(fromConfig)) { + return []; } - ] - }, { retryCount: 0 }); -} -async function signMessage$1(client2, { account: account_ = client2.account, message }) { - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/signMessage" - }); - const account2 = parseAccount(account_); - if (account2.signMessage) - return account2.signMessage({ message }); - const message_ = (() => { - if (typeof message === "string") - return stringToHex(message); - if (message.raw instanceof Uint8Array) - return toHex$1(message.raw); - return message.raw; - })(); - return client2.request({ - method: "personal_sign", - params: [message_, account2.address] - }, { retryCount: 0 }); -} -async function signTypedData(client2, parameters) { - const { account: account_ = client2.account, domain: domain2, message, primaryType } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/signTypedData" - }); - const account2 = parseAccount(account_); - const types2 = { - EIP712Domain: getTypesForEIP712Domain({ domain: domain2 }), - ...parameters.types - }; - validateTypedData({ domain: domain2, message, primaryType, types: types2 }); - if (account2.signTypedData) - return account2.signTypedData({ domain: domain2, message, primaryType, types: types2 }); - const typedData = serializeTypedData({ domain: domain2, message, primaryType, types: types2 }); - return client2.request({ - method: "eth_signTypedData_v4", - params: [account2.address, typedData] - }, { retryCount: 0 }); -} -async function simulateContract$1(client2, parameters) { - const { abi: abi2, address, args, dataSuffix, functionName, ...callRequest } = parameters; - const account2 = callRequest.account ? parseAccount(callRequest.account) : client2.account; - const calldata = encodeFunctionData({ abi: abi2, args, functionName }); - try { - const { data } = await getAction$1(client2, call, "call")({ - batch: false, - data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, - to: address, - ...callRequest, - account: account2 - }); - const result = decodeFunctionResult({ - abi: abi2, - args, - functionName, - data: data || "0x" - }); - const minimizedAbi = abi2.filter((abiItem) => "name" in abiItem && abiItem.name === parameters.functionName); - return { - result, - request: { - abi: minimizedAbi, - address, - args, - dataSuffix, - functionName, - ...callRequest, - account: account2 + const signers = v2.config.signersOf(fromConfig.tree).map((s2) => s2.address); + const subdigestsOfSigner = await Promise.all(signers.map((s2) => _this.store.loadSubdigestsOfSigner(s2))); + const subdigests = [...new Set(subdigestsOfSigner.flat())]; + const payloads = await Promise.all([...new Set(subdigests)].map(async function(s2) { + return _extends$5({}, await _this.payloadOfSubdigest({ + subdigest: s2 + }), { + subdigest: s2 + }); + })); + const nextImageHashes = payloads.filter((p2) => (p2 == null ? void 0 : p2.message) && (p2 == null ? void 0 : p2.address) && p2.address === wallet).map((p2) => ({ + payload: p2, + nextImageHash: v2.chained.decodeMessageSetImageHash(p2.message) + })).filter((p2) => p2 == null ? void 0 : p2.nextImageHash); + let bestCandidate; + const nextConfigsAndCheckpoints = await Promise.all(nextImageHashes.map(async function({ + nextImageHash, + payload + }) { + const nextConfig = await _this.configOfImageHash({ + imageHash: nextImageHash + }); + if (!nextConfig || !v2.config.isWalletConfig(nextConfig)) return void 0; + const nextCheckpoint = BigInt(nextConfig.checkpoint); + return { + nextConfig, + nextCheckpoint, + nextImageHash, + payload + }; + })); + const sortedNextConfigsAndCheckpoints = nextConfigsAndCheckpoints.filter((c2) => c2 !== void 0).filter((c2) => c2.nextCheckpoint > BigInt(fromConfig.checkpoint)).sort((a2, b2) => ( + // If we are looking for the longest path, sort by ascending checkpoint + // because we want to find the smalles jump, and we should start with the + // closest one. If we are not looking for the longest path, sort by + // descending checkpoint, because we want to find the largest jump. + // + // We don't have a guarantee that all "next configs" will be valid + // so worst case scenario we will need to try all of them. + // But we can try to optimize for the most common case. + a2.nextCheckpoint > b2.nextCheckpoint ? longestPath ? 1 : -1 : longestPath ? -1 : 1 + )); + for (const entry of sortedNextConfigsAndCheckpoints) { + const { + nextConfig, + nextCheckpoint, + nextImageHash, + payload + } = entry; + if (bestCandidate) { + const bestCheckpoint = bestCandidate.checkpoint; + if (longestPath) { + if (nextCheckpoint >= bestCheckpoint) continue; + } else { + if (nextCheckpoint <= bestCheckpoint) continue; + } + } + const signatures = new Map((await Promise.all(signers.map(async function(signer2) { + const signature2 = await _this.store.loadSignatureOfSubdigest(signer2, payload.subdigest); + if (!signature2) { + return [signer2, void 0]; + } + const replacedSignature = hexlify(_this.useEIP5719 ? await _this.cachedEIP5719.runByEIP5719(signer2, payload.subdigest, signature2) : signature2); + const isDynamic = index$1$1.signer.tryRecoverSigner(payload.subdigest, replacedSignature) !== signer2; + return [signer2, { + isDynamic, + signature: replacedSignature + }]; + }))).filter((signature2) => Boolean(signature2[1]))); + if (signatures.size === 0) continue; + const encoded = v2.signature.SignatureCoder.encodeSigners(fromConfig, signatures, [], 0); + if (encoded.weight < BigInt(fromConfig.threshold)) continue; + bestCandidate = { + nextImageHash, + checkpoint: BigInt(nextConfig.checkpoint), + signature: encoded.encoded + }; + } + if (!bestCandidate) { + return []; } + const nextStep = await _this.loadPresignedConfiguration({ + wallet, + fromImageHash: bestCandidate.nextImageHash, + longestPath + }); + return [{ + wallet, + nextImageHash: bestCandidate.nextImageHash, + signature: bestCandidate.signature + }, ...nextStep]; }; - } catch (error) { - throw getContractError(error, { - abi: abi2, + this.saveWitnesses = async function(args) { + const payload = { + digest: args.digest, + address: args.wallet, + chainId: args.chainId + }; + const subdigest = index$1$1.signature.subdigestOf(payload); + await Promise.all([_this.savePayload({ + payload + }), ...args.signatures.filter((signature2) => { + return index$1$1.signer.canRecover(signature2); + }).map((signature2) => { + const signer2 = index$1$1.signer.recoverSigner(subdigest, signature2); + return _this.store.saveSignatureOfSubdigest(signer2, subdigest, signature2); + })]); + }; + this.walletsOfSigner = async function(args) { + const subdigests = await _this.store.loadSubdigestsOfSigner(args.signer); + const payloads = await Promise.all(subdigests.map((s2) => _this.payloadOfSubdigest({ + subdigest: s2 + }))).then((p2) => p2.filter((p3) => p3 !== void 0)); + const result = []; + for (const payload of payloads) { + const wallet = payload.address; + if (result.find((r2) => r2.wallet === wallet)) continue; + const subdigest = index$1$1.signature.subdigestOf(payload); + const signature2 = await _this.store.loadSignatureOfSubdigest(args.signer, subdigest); + if (!signature2) continue; + result.push({ + wallet, + proof: { + digest: payload.digest, + chainId: BigInt(payload.chainId), + signature: hexlify(signature2) + } + }); + } + return result; + }; + this.cachedEIP5719 = new CachedEIP5719(provider2); + } + async saveMigration(address, signed2, contexts) { + const fromVersion = signed2.fromVersion; + if (fromVersion !== 1) throw new Error("Migration not supported"); + if (!v2.config.isWalletConfig(signed2.toConfig)) throw new Error("Invalid to config"); + const { + newImageHash, + address: decodedAddress + } = index$5.v1v2.decodeTransaction(signed2.tx, contexts); + if (decodedAddress !== address) throw new Error("Invalid migration transaction - address"); + if (v2.config.ConfigCoder.imageHashOf(signed2.toConfig) != newImageHash) throw new Error("Invalid migration transaction - config"); + const message = index$1$1.transaction.packMetaTransactionsData(signed2.tx.nonce, signed2.tx.transactions); + const digest = keccak256(message); + const payload = { + chainId: signed2.tx.chainId, + message, address, - args, - docsPath: "/docs/contract/simulateContract", - functionName, - sender: account2 == null ? void 0 : account2.address + digest + }; + const subdigest = index$1$1.signature.subdigestOf(payload); + const savePayload = this.savePayload({ + payload }); + const saveToConfig = this.saveWalletConfig({ + config: signed2.toConfig + }); + const decoded = v1.signature.SignatureCoder.decode(signed2.tx.signature); + const recovered = await v1.signature.SignatureCoder.recover(decoded, payload, this.provider); + const signatures = v1.signature.SignatureCoder.signaturesOf(recovered.config); + await Promise.all([savePayload, saveToConfig, this.saveWalletConfig({ + config: recovered.config + }), this.store.saveMigrationsSubdigest(address, fromVersion, fromVersion + 1, subdigest, newImageHash), ...signatures.map((sig) => this.store.saveSignatureOfSubdigest(sig.address, recovered.subdigest, sig.signature))]); } -} -async function switchChain$1(client2, { id: id2 }) { - await client2.request({ - method: "wallet_switchEthereumChain", - params: [ - { - chainId: numberToHex(id2) - } - ] - }, { retryCount: 0 }); -} -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const _0n$3 = BigInt(0); -const _1n$4 = BigInt(1); -const _2n$2 = BigInt(2); -function isBytes(a2) { - return a2 instanceof Uint8Array || a2 != null && typeof a2 === "object" && a2.constructor.name === "Uint8Array"; -} -function abytes(item2) { - if (!isBytes(item2)) - throw new Error("Uint8Array expected"); -} -const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); -function bytesToHex(bytes2) { - abytes(bytes2); - let hex2 = ""; - for (let i = 0; i < bytes2.length; i++) { - hex2 += hexes[bytes2[i]]; - } - return hex2; -} -function numberToHexUnpadded(num) { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; -} -function hexToNumber(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - return BigInt(hex2 === "" ? "0" : `0x${hex2}`); -} -const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; -function asciiToBase16(char) { - if (char >= asciis._0 && char <= asciis._9) - return char - asciis._0; - if (char >= asciis._A && char <= asciis._F) - return char - (asciis._A - 10); - if (char >= asciis._a && char <= asciis._f) - return char - (asciis._a - 10); - return; -} -function hexToBytes(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - const hl2 = hex2.length; - const al2 = hl2 / 2; - if (hl2 % 2) - throw new Error("padded hex string expected, got unpadded hex of length " + hl2); - const array = new Uint8Array(al2); - for (let ai2 = 0, hi2 = 0; ai2 < al2; ai2++, hi2 += 2) { - const n1 = asciiToBase16(hex2.charCodeAt(hi2)); - const n2 = asciiToBase16(hex2.charCodeAt(hi2 + 1)); - if (n1 === void 0 || n2 === void 0) { - const char = hex2[hi2] + hex2[hi2 + 1]; - throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi2); + async getMigration(address, fromImageHash, fromVersion, chainId) { + var _this2 = this; + const [currentConfig, txs] = await Promise.all([this.configOfImageHash({ + imageHash: fromImageHash + }), this.store.loadMigrationsSubdigest(address, fromVersion, fromVersion + 1)]); + const coder = index$6.coderFor(fromVersion); + if (!currentConfig) { + return void 0; } - array[ai2] = n1 * 16 + n2; - } - return array; -} -function bytesToNumberBE(bytes2) { - return hexToNumber(bytesToHex(bytes2)); -} -function bytesToNumberLE(bytes2) { - abytes(bytes2); - return hexToNumber(bytesToHex(Uint8Array.from(bytes2).reverse())); -} -function numberToBytesBE(n2, len) { - return hexToBytes(n2.toString(16).padStart(len * 2, "0")); -} -function numberToBytesLE(n2, len) { - return numberToBytesBE(n2, len).reverse(); -} -function numberToVarBytesBE(n2) { - return hexToBytes(numberToHexUnpadded(n2)); -} -function ensureBytes(title, hex2, expectedLength) { - let res; - if (typeof hex2 === "string") { - try { - res = hexToBytes(hex2); - } catch (e2) { - throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e2}`); + if (!coder.config.isWalletConfig(currentConfig)) { + return void 0; } - } else if (isBytes(hex2)) { - res = Uint8Array.from(hex2); - } else { - throw new Error(`${title} must be hex string or Uint8Array`); - } - const len = res.length; - if (typeof expectedLength === "number" && len !== expectedLength) - throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); - return res; -} -function concatBytes(...arrays) { - let sum = 0; - for (let i = 0; i < arrays.length; i++) { - const a2 = arrays[i]; - abytes(a2); - sum += a2.length; + const candidates = await Promise.all(txs.map(async function(tx) { + const { + subdigest, + toImageHash + } = tx; + const payload = await _this2.payloadOfSubdigest({ + subdigest + }); + if (!payload || !payload.message) return void 0; + if (BigInt(chainId) !== BigInt(payload.chainId)) return void 0; + const signers = coder.config.signersOf(currentConfig).map((s2) => s2.address); + const signatures = new Map((await Promise.all(signers.map(async function(signer2) { + const signature2 = await _this2.store.loadSignatureOfSubdigest(signer2, subdigest); + if (!signature2) { + return [signer2, void 0]; + } + const replacedSignature = hexlify(_this2.useEIP5719 ? await _this2.cachedEIP5719.runByEIP5719(signer2, subdigest, signature2) : signature2); + const isDynamic = index$1$1.signer.tryRecoverSigner(subdigest, replacedSignature) !== signer2; + return [signer2, { + isDynamic, + signature: replacedSignature + }]; + }))).filter((signature2) => Boolean(signature2[1]))); + const encoded = coder.signature.encodeSigners(currentConfig, signatures, [], chainId); + if (!encoded || encoded.weight < BigInt(currentConfig.threshold)) return void 0; + const [nonce, transactions2] = index$1$1.transaction.unpackMetaTransactionsData(payload.message); + return { + tx: { + entrypoint: address, + transactions: index$1$1.transaction.fromTxAbiEncode(transactions2), + chainId, + nonce, + signature: encoded.encoded, + intent: { + id: subdigest, + wallet: address + } + }, + toConfig: await _this2.configOfImageHash({ + imageHash: toImageHash + }), + fromVersion, + toVersion: fromVersion + 1 + }; + })).then((c2) => c2.filter((c3) => c3 !== void 0)); + return candidates[0]; } - const res = new Uint8Array(sum); - for (let i = 0, pad2 = 0; i < arrays.length; i++) { - const a2 = arrays[i]; - res.set(a2, pad2); - pad2 += a2.length; + updateProvider(provider2) { + this.provider = provider2; } - return res; -} -function equalBytes(a2, b2) { - if (a2.length !== b2.length) - return false; - let diff = 0; - for (let i = 0; i < a2.length; i++) - diff |= a2[i] ^ b2[i]; - return diff === 0; -} -function utf8ToBytes(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); -} -function bitLen(n2) { - let len; - for (len = 0; n2 > _0n$3; n2 >>= _1n$4, len += 1) - ; - return len; -} -function bitGet(n2, pos) { - return n2 >> BigInt(pos) & _1n$4; -} -function bitSet(n2, pos, value) { - return n2 | (value ? _1n$4 : _0n$3) << BigInt(pos); -} -const bitMask = (n2) => (_2n$2 << BigInt(n2 - 1)) - _1n$4; -const u8n = (data) => new Uint8Array(data); -const u8fr = (arr) => Uint8Array.from(arr); -function createHmacDrbg(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== "number" || hashLen < 2) - throw new Error("hashLen must be a number"); - if (typeof qByteLen !== "number" || qByteLen < 2) - throw new Error("qByteLen must be a number"); - if (typeof hmacFn !== "function") - throw new Error("hmacFn must be a function"); - let v3 = u8n(hashLen); - let k2 = u8n(hashLen); - let i = 0; - const reset = () => { - v3.fill(1); - k2.fill(0); - i = 0; - }; - const h2 = (...b2) => hmacFn(k2, v3, ...b2); - const reseed = (seed = u8n()) => { - k2 = h2(u8fr([0]), seed); - v3 = h2(); - if (seed.length === 0) - return; - k2 = h2(u8fr([1]), seed); - v3 = h2(); - }; - const gen2 = () => { - if (i++ >= 1e3) - throw new Error("drbg: tried 1000 values"); - let len = 0; - const out = []; - while (len < qByteLen) { - v3 = h2(); - const sl2 = v3.slice(); - out.push(sl2); - len += v3.length; - } - return concatBytes(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); - let res = void 0; - while (!(res = pred(gen2()))) - reseed(); - reset(); - return res; - }; - return genUntil; -} -const validatorFns = { - bigint: (val) => typeof val === "bigint", - function: (val) => typeof val === "function", - boolean: (val) => typeof val === "boolean", - string: (val) => typeof val === "string", - stringOrUint8Array: (val) => typeof val === "string" || isBytes(val), - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object2) => object2.Fp.isValid(val), - hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) -}; -function validateObject(object2, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== "function") - throw new Error(`Invalid validator "${type}", expected function`); - const val = object2[fieldName]; - if (isOptional && val === void 0) - return; - if (!checkVal(val, object2)) { - throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); - } - }; - for (const [fieldName, type] of Object.entries(validators)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object2; } -const ut = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +var local = /* @__PURE__ */ Object.freeze({ __proto__: null, - abytes, - bitGet, - bitLen, - bitMask, - bitSet, - bytesToHex, - bytesToNumberBE, - bytesToNumberLE, - concatBytes, - createHmacDrbg, - ensureBytes, - equalBytes, - hexToBytes, - hexToNumber, - isBytes, - numberToBytesBE, - numberToBytesLE, - numberToHexUnpadded, - numberToVarBytesBE, - utf8ToBytes, - validateObject -}, Symbol.toStringTag, { value: "Module" })); -function isBytesEqual(a_, b_) { - const a2 = isHex(a_) ? toBytes$1(a_) : a_; - const b2 = isHex(b_) ? toBytes$1(b_) : b_; - return equalBytes(a2, b2); -} -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const _0n$2 = BigInt(0), _1n$3 = BigInt(1), _2n$1 = BigInt(2), _3n$1 = BigInt(3); -const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); -BigInt(9); -BigInt(16); -function mod(a2, b2) { - const result = a2 % b2; - return result >= _0n$2 ? result : b2 + result; -} -function pow(num, power, modulo) { - if (modulo <= _0n$2 || power < _0n$2) - throw new Error("Expected power/modulo > 0"); - if (modulo === _1n$3) - return _0n$2; - let res = _1n$3; - while (power > _0n$2) { - if (power & _1n$3) - res = res * num % modulo; - num = num * num % modulo; - power >>= _1n$3; - } - return res; -} -function pow2(x2, power, modulo) { - let res = x2; - while (power-- > _0n$2) { - res *= res; - res %= modulo; - } - return res; -} -function invert(number2, modulo) { - if (number2 === _0n$2 || modulo <= _0n$2) { - throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`); - } - let a2 = mod(number2, modulo); - let b2 = modulo; - let x2 = _0n$2, u2 = _1n$3; - while (a2 !== _0n$2) { - const q2 = b2 / a2; - const r2 = b2 % a2; - const m2 = x2 - u2 * q2; - b2 = a2, a2 = r2, x2 = u2, u2 = m2; - } - const gcd = b2; - if (gcd !== _1n$3) - throw new Error("invert: does not exist"); - return mod(x2, modulo); -} -function tonelliShanks(P2) { - const legendreC = (P2 - _1n$3) / _2n$1; - let Q2, S2, Z2; - for (Q2 = P2 - _1n$3, S2 = 0; Q2 % _2n$1 === _0n$2; Q2 /= _2n$1, S2++) - ; - for (Z2 = _2n$1; Z2 < P2 && pow(Z2, legendreC, P2) !== P2 - _1n$3; Z2++) - ; - if (S2 === 1) { - const p1div4 = (P2 + _1n$3) / _4n; - return function tonelliFast(Fp2, n2) { - const root2 = Fp2.pow(n2, p1div4); - if (!Fp2.eql(Fp2.sqr(root2), n2)) - throw new Error("Cannot find square root"); - return root2; + LocalConfigTracker +}); +let SignatureType = /* @__PURE__ */ function(SignatureType2) { + SignatureType2["EIP712"] = "EIP712"; + SignatureType2["EthSign"] = "EthSign"; + SignatureType2["EIP1271"] = "EIP1271"; + return SignatureType2; +}({}); +class Sessions { + constructor(hostname, fetch2) { + this.hostname = void 0; + this.fetch = void 0; + this.path = "/rpc/Sessions/"; + this.ping = (headers, signal) => { + return this.fetch(this.url("Ping"), createHTTPRequest$3({}, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.config = (args, headers, signal) => { + return this.fetch(this.url("Config"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return { + version: _data6.version, + config: _data6.config + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.wallets = (args, headers, signal) => { + return this.fetch(this.url("Wallets"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return { + wallets: _data6.wallets + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.deployHash = (args, headers, signal) => { + return this.fetch(this.url("DeployHash"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return { + deployHash: _data6.deployHash, + context: _data6.context + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); }; - } - const Q1div2 = (Q2 + _1n$3) / _2n$1; - return function tonelliSlow(Fp2, n2) { - if (Fp2.pow(n2, legendreC) === Fp2.neg(Fp2.ONE)) - throw new Error("Cannot find square root"); - let r2 = S2; - let g2 = Fp2.pow(Fp2.mul(Fp2.ONE, Z2), Q2); - let x2 = Fp2.pow(n2, Q1div2); - let b2 = Fp2.pow(n2, Q2); - while (!Fp2.eql(b2, Fp2.ONE)) { - if (Fp2.eql(b2, Fp2.ZERO)) - return Fp2.ZERO; - let m2 = 1; - for (let t2 = Fp2.sqr(b2); m2 < r2; m2++) { - if (Fp2.eql(t2, Fp2.ONE)) - break; - t2 = Fp2.sqr(t2); - } - const ge2 = Fp2.pow(g2, _1n$3 << BigInt(r2 - m2 - 1)); - g2 = Fp2.sqr(ge2); - x2 = Fp2.mul(x2, ge2); - b2 = Fp2.mul(b2, g2); - r2 = m2; - } - return x2; - }; -} -function FpSqrt(P2) { - if (P2 % _4n === _3n$1) { - const p1div4 = (P2 + _1n$3) / _4n; - return function sqrt3mod4(Fp2, n2) { - const root2 = Fp2.pow(n2, p1div4); - if (!Fp2.eql(Fp2.sqr(root2), n2)) - throw new Error("Cannot find square root"); - return root2; + this.configUpdates = (args, headers, signal) => { + return this.fetch(this.url("ConfigUpdates"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return { + updates: _data6.updates + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); }; - } - if (P2 % _8n === _5n) { - const c1 = (P2 - _5n) / _8n; - return function sqrt5mod8(Fp2, n2) { - const n22 = Fp2.mul(n2, _2n$1); - const v3 = Fp2.pow(n22, c1); - const nv = Fp2.mul(n2, v3); - const i = Fp2.mul(Fp2.mul(nv, _2n$1), v3); - const root2 = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); - if (!Fp2.eql(Fp2.sqr(root2), n2)) - throw new Error("Cannot find square root"); - return root2; + this.migrations = (args, headers, signal) => { + return this.fetch(this.url("Migrations"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return { + migrations: _data6.migrations + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.saveConfig = (args, headers, signal) => { + return this.fetch(this.url("SaveConfig"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.saveWallet = (args, headers, signal) => { + return this.fetch(this.url("SaveWallet"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.saveSignature = (args, headers, signal) => { + return this.fetch(this.url("SaveSignature"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.saveSignerSignatures = (args, headers, signal) => { + return this.fetch(this.url("SaveSignerSignatures"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.saveMigration = (args, headers, signal) => { + return this.fetch(this.url("SaveMigration"), createHTTPRequest$3(args, headers, signal)).then((res) => { + return buildResponse$3(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$3.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); }; + this.hostname = hostname; + this.fetch = (input2, init2) => fetch2(input2, init2); } - return tonelliShanks(P2); -} -const FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" -]; -function validateField(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "isSafeInteger", - BITS: "isSafeInteger" - }; - const opts = FIELD_FIELDS.reduce((map, val) => { - map[val] = "function"; - return map; - }, initial); - return validateObject(field, opts); -} -function FpPow(f2, num, power) { - if (power < _0n$2) - throw new Error("Expected power > 0"); - if (power === _0n$2) - return f2.ONE; - if (power === _1n$3) - return num; - let p2 = f2.ONE; - let d2 = num; - while (power > _0n$2) { - if (power & _1n$3) - p2 = f2.mul(p2, d2); - d2 = f2.sqr(d2); - power >>= _1n$3; + url(name2) { + return this.hostname + this.path + name2; } - return p2; -} -function FpInvertBatch(f2, nums) { - const tmp = new Array(nums.length); - const lastMultiplied = nums.reduce((acc, num, i) => { - if (f2.is0(num)) - return acc; - tmp[i] = acc; - return f2.mul(acc, num); - }, f2.ONE); - const inverted = f2.inv(lastMultiplied); - nums.reduceRight((acc, num, i) => { - if (f2.is0(num)) - return acc; - tmp[i] = f2.mul(acc, tmp[i]); - return f2.mul(acc, num); - }, inverted); - return tmp; -} -function nLength(n2, nBitLength) { - const _nBitLength = nBitLength !== void 0 ? nBitLength : n2.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; -} -function Field(ORDER, bitLen2, isLE2 = false, redef = {}) { - if (ORDER <= _0n$2) - throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); - if (BYTES > 2048) - throw new Error("Field lengths over 2048 bytes are not supported"); - const sqrtP = FpSqrt(ORDER); - const f2 = Object.freeze({ - ORDER, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n$2, - ONE: _1n$3, - create: (num) => mod(num, ORDER), - isValid: (num) => { - if (typeof num !== "bigint") - throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); - return _0n$2 <= num && num < ORDER; - }, - is0: (num) => num === _0n$2, - isOdd: (num) => (num & _1n$3) === _1n$3, - neg: (num) => mod(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod(num * num, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num, power) => FpPow(f2, num, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - // Same as above, but doesn't normalize - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert(num, ORDER), - sqrt: redef.sqrt || ((n2) => sqrtP(f2, n2)), - invertBatch: (lst) => FpInvertBatch(f2, lst), - // TODO: do we really need constant cmov? - // We don't have const-time bigints anyway, so probably will be not very useful - cmov: (a2, b2, c2) => c2 ? b2 : a2, - toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), - fromBytes: (bytes2) => { - if (bytes2.length !== BYTES) - throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`); - return isLE2 ? bytesToNumberLE(bytes2) : bytesToNumberBE(bytes2); - } - }); - return Object.freeze(f2); -} -function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); -} -function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); -} -function mapHashToField(key, fieldOrder, isLE2 = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - if (len < 16 || len < minLen || len > 1024) - throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); - const num = isLE2 ? bytesToNumberBE(key) : bytesToNumberLE(key); - const reduced = mod(num, fieldOrder - _1n$3) + _1n$3; - return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); } -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const _0n$1 = BigInt(0); -const _1n$2 = BigInt(1); -function wNAF(c2, bits) { - const constTimeNegate = (condition, item2) => { - const neg = item2.negate(); - return condition ? neg : item2; - }; - const opts = (W2) => { - const windows = Math.ceil(bits / W2) + 1; - const windowSize = 2 ** (W2 - 1); - return { windows, windowSize }; - }; +const createHTTPRequest$3 = (body = {}, headers = {}, signal = null) => { return { - constTimeNegate, - // non-const time multiplication ladder - unsafeLadder(elm, n2) { - let p2 = c2.ZERO; - let d2 = elm; - while (n2 > _0n$1) { - if (n2 & _1n$2) - p2 = p2.add(d2); - d2 = d2.double(); - n2 >>= _1n$2; - } - return p2; - }, - /** - * Creates a wNAF precomputation window. Used for caching. - * Default window size is set by `utils.precompute()` and is equal to 8. - * Number of precomputed points depends on the curve size: - * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: - * - 𝑊 is the window size - * - 𝑛 is the bitlength of the curve order. - * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. - * @returns precomputed point tables flattened to a single array - */ - precomputeWindow(elm, W2) { - const { windows, windowSize } = opts(W2); - const points = []; - let p2 = elm; - let base = p2; - for (let window2 = 0; window2 < windows; window2++) { - base = p2; - points.push(base); - for (let i = 1; i < windowSize; i++) { - base = base.add(p2); - points.push(base); - } - p2 = base.double(); - } - return points; - }, - /** - * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. - * @param W window size - * @param precomputes precomputed tables - * @param n scalar (we don't check here, but should be less than curve order) - * @returns real and fake (for const-time) points - */ - wNAF(W2, precomputes, n2) { - const { windows, windowSize } = opts(W2); - let p2 = c2.ZERO; - let f2 = c2.BASE; - const mask2 = BigInt(2 ** W2 - 1); - const maxNumber = 2 ** W2; - const shiftBy = BigInt(W2); - for (let window2 = 0; window2 < windows; window2++) { - const offset2 = window2 * windowSize; - let wbits = Number(n2 & mask2); - n2 >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n2 += _1n$2; - } - const offset1 = offset2; - const offset22 = offset2 + Math.abs(wbits) - 1; - const cond1 = window2 % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - f2 = f2.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p2 = p2.add(constTimeNegate(cond2, precomputes[offset22])); - } - } - return { p: p2, f: f2 }; - }, - wNAFCached(P2, precomputesMap, n2, transform) { - const W2 = P2._WINDOW_SIZE || 1; - let comp = precomputesMap.get(P2); - if (!comp) { - comp = this.precomputeWindow(P2, W2); - if (W2 !== 1) { - precomputesMap.set(P2, transform(comp)); - } - } - return this.wNAF(W2, comp, n2); - } + method: "POST", + headers: _extends$5({}, headers, { + "Content-Type": "application/json" + }), + body: JSON.stringify(body || {}), + signal }; -} -function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); -} -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: "field", - b: "field" - }, { - allowedPrivateKeyLengths: "array", - wrapPrivateKey: "boolean", - isTorsionFree: "function", - clearCofactor: "function", - allowInfinityPoint: "boolean", - fromBytes: "function", - toBytes: "function" - }); - const { endo, Fp: Fp2, a: a2 } = opts; - if (endo) { - if (!Fp2.eql(a2, Fp2.ZERO)) { - throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); +}; +const buildResponse$3 = (res) => { + return res.text().then((text2) => { + let data; + try { + data = JSON.parse(text2); + } catch (error) { + let message = ""; + if (error instanceof Error) { + message = error.message; + } + throw WebrpcBadResponseError$3.new({ + status: res.status, + cause: `JSON.parse(): ${message}: response text: ${text2}` + }); } - if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { - throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); + if (!res.ok) { + const code2 = typeof data.code === "number" ? data.code : 0; + throw (webrpcErrorByCode$3[code2] || WebrpcError$3).new(data); } + return data; + }); +}; +let WebrpcError$3 = class WebrpcError5 extends Error { + constructor(name2, code2, message, status, cause) { + super(message); + this.name = void 0; + this.code = void 0; + this.message = void 0; + this.status = void 0; + this.cause = void 0; + this.msg = void 0; + this.name = name2 || "WebrpcError"; + this.code = typeof code2 === "number" ? code2 : 0; + this.message = message || `endpoint error ${this.code}`; + this.msg = this.message; + this.status = typeof status === "number" ? status : 0; + this.cause = cause; + Object.setPrototypeOf(this, WebrpcError5.prototype); + } + static new(payload) { + return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + } +}; +let WebrpcEndpointError$3 = class WebrpcEndpointError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcEndpointError5.prototype); + } +}; +let WebrpcRequestFailedError$3 = class WebrpcRequestFailedError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcRequestFailedError5.prototype); + } +}; +let WebrpcBadRouteError$3 = class WebrpcBadRouteError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRouteError5.prototype); + } +}; +let WebrpcBadMethodError$3 = class WebrpcBadMethodError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadMethodError5.prototype); + } +}; +let WebrpcBadRequestError$3 = class WebrpcBadRequestError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRequestError5.prototype); + } +}; +let WebrpcBadResponseError$3 = class WebrpcBadResponseError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadResponseError5.prototype); + } +}; +let WebrpcServerPanicError$3 = class WebrpcServerPanicError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcServerPanicError5.prototype); + } +}; +let WebrpcInternalErrorError$3 = class WebrpcInternalErrorError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcInternalErrorError5.prototype); + } +}; +let WebrpcClientDisconnectedError$3 = class WebrpcClientDisconnectedError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcClientDisconnectedError5.prototype); + } +}; +let WebrpcStreamLostError$3 = class WebrpcStreamLostError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamLostError5.prototype); } - return Object.freeze({ ...opts }); -} -const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; -const DER = { - // asn.1 DER encoding utils - Err: class DERErr2 extends Error { - constructor(m2 = "") { - super(m2); - } - }, - _parseInt(data) { - const { Err: E2 } = DER; - if (data.length < 2 || data[0] !== 2) - throw new E2("Invalid signature integer tag"); - const len = data[1]; - const res = data.subarray(2, len + 2); - if (!len || res.length !== len) - throw new E2("Invalid signature integer: wrong length"); - if (res[0] & 128) - throw new E2("Invalid signature integer: negative"); - if (res[0] === 0 && !(res[1] & 128)) - throw new E2("Invalid signature integer: unnecessary leading zero"); - return { d: b2n(res), l: data.subarray(len + 2) }; - }, - toSig(hex2) { - const { Err: E2 } = DER; - const data = typeof hex2 === "string" ? h2b(hex2) : hex2; - abytes(data); - let l2 = data.length; - if (l2 < 2 || data[0] != 48) - throw new E2("Invalid signature tag"); - if (data[1] !== l2 - 2) - throw new E2("Invalid signature: incorrect length"); - const { d: r2, l: sBytes } = DER._parseInt(data.subarray(2)); - const { d: s2, l: rBytesLeft } = DER._parseInt(sBytes); - if (rBytesLeft.length) - throw new E2("Invalid signature: left bytes after parsing"); - return { r: r2, s: s2 }; - }, - hexFromSig(sig) { - const slice2 = (s3) => Number.parseInt(s3[0], 16) & 8 ? "00" + s3 : s3; - const h2 = (num) => { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; - }; - const s2 = slice2(h2(sig.s)); - const r2 = slice2(h2(sig.r)); - const shl = s2.length / 2; - const rhl = r2.length / 2; - const sl2 = h2(shl); - const rl2 = h2(rhl); - return `30${h2(rhl + shl + 4)}02${rl2}${r2}02${sl2}${s2}`; +}; +let WebrpcStreamFinishedError$3 = class WebrpcStreamFinishedError5 extends WebrpcError$3 { + constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamFinishedError5.prototype); } }; -const _0n = BigInt(0), _1n$1 = BigInt(1); -BigInt(2); -const _3n = BigInt(3); -BigInt(4); -function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp: Fp2 } = CURVE; - const toBytes2 = CURVE.toBytes || ((_c2, point, _isCompressed) => { - const a2 = point.toAffine(); - return concatBytes(Uint8Array.from([4]), Fp2.toBytes(a2.x), Fp2.toBytes(a2.y)); - }); - const fromBytes = CURVE.fromBytes || ((bytes2) => { - const tail = bytes2.subarray(1); - const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x: x2, y: y2 }; - }); - function weierstrassEquation(x2) { - const { a: a2, b: b2 } = CURVE; - const x22 = Fp2.sqr(x2); - const x3 = Fp2.mul(x22, x2); - return Fp2.add(Fp2.add(x3, Fp2.mul(x2, a2)), b2); +let InvalidArgumentError$1 = class InvalidArgumentError5 extends WebrpcError$3 { + constructor(name2 = "InvalidArgument", code2 = 1, message = "invalid argument", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, InvalidArgumentError5.prototype); } - if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error("bad generator point: equation left != right"); - function isWithinCurveOrder(num) { - return typeof num === "bigint" && _0n < num && num < CURVE.n; +}; +let NotFoundError$2 = class NotFoundError5 extends WebrpcError$3 { + constructor(name2 = "NotFound", code2 = 2, message = "not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, NotFoundError5.prototype); } - function assertGE(num) { - if (!isWithinCurveOrder(num)) - throw new Error("Expected valid bigint: 0 < bigint < curve.n"); +}; +const webrpcErrorByCode$3 = { + [0]: WebrpcEndpointError$3, + [-1]: WebrpcRequestFailedError$3, + [-2]: WebrpcBadRouteError$3, + [-3]: WebrpcBadMethodError$3, + [-4]: WebrpcBadRequestError$3, + [-5]: WebrpcBadResponseError$3, + [-6]: WebrpcServerPanicError$3, + [-7]: WebrpcInternalErrorError$3, + [-8]: WebrpcClientDisconnectedError$3, + [-9]: WebrpcStreamLostError$3, + [-10]: WebrpcStreamFinishedError$3, + [1]: InvalidArgumentError$1, + [2]: NotFoundError$2 +}; +class RemoteConfigTracker { + constructor(hostname, onlyRecoverable = true) { + this.onlyRecoverable = onlyRecoverable; + this.sessions = void 0; + this.sessions = new Sessions(hostname, fetch); } - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: n2 } = CURVE; - if (lengths && typeof key !== "bigint") { - if (isBytes(key)) - key = bytesToHex(key); - if (typeof key !== "string" || !lengths.includes(key.length)) - throw new Error("Invalid key"); - key = key.padStart(nByteLength * 2, "0"); - } - let num; + async loadPresignedConfiguration(args) { try { - num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + const { + updates + } = await this.sessions.configUpdates({ + wallet: args.wallet, + fromImageHash: args.fromImageHash, + allUpdates: args.longestPath + }); + return updates.map(({ + toImageHash, + signature: signature2 + }) => ({ + wallet: args.wallet, + nextImageHash: toImageHash, + signature: signature2 + })); } catch (error) { - throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + if (is404NotFound(error)) { + return []; + } else { + throw error; + } } - if (wrapPrivateKey) - num = mod(num, n2); - assertGE(num); - return num; } - const pointPrecomputes = /* @__PURE__ */ new Map(); - function assertPrjPoint(other) { - if (!(other instanceof Point)) - throw new Error("ProjectivePoint expected"); + async savePresignedConfiguration(args) { + const config2 = args.nextConfig; + const imageHash2 = index$6.genericCoderFor(config2.version).config.imageHashOf(config2); + const message = v2.signature.setImageHashStruct(imageHash2); + const digest = keccak256(message); + await this.sessions.saveSignature({ + wallet: args.wallet, + digest, + chainID: "0", + signature: args.signature, + toConfig: encodeConfig(config2) + }); } - class Point { - constructor(px2, py, pz) { - this.px = px2; - this.py = py; - this.pz = pz; - if (px2 == null || !Fp2.isValid(px2)) - throw new Error("x required"); - if (py == null || !Fp2.isValid(py)) - throw new Error("y required"); - if (pz == null || !Fp2.isValid(pz)) - throw new Error("z required"); - } - // Does not validate if the point is on-curve. - // Use fromHex instead, or call assertValidity() later. - static fromAffine(p2) { - const { x: x2, y: y2 } = p2 || {}; - if (!p2 || !Fp2.isValid(x2) || !Fp2.isValid(y2)) - throw new Error("invalid affine point"); - if (p2 instanceof Point) - throw new Error("projective point not allowed"); - const is0 = (i) => Fp2.eql(i, Fp2.ZERO); - if (is0(x2) && is0(y2)) - return Point.ZERO; - return new Point(x2, y2, Fp2.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - /** - * Takes a bunch of Projective Points but executes only one - * inversion on all of them. Inversion is very slow operation, - * so this improves performance massively. - * Optimization: converts a list of projective points to a list of identical points with Z=1. - */ - static normalizeZ(points) { - const toInv = Fp2.invertBatch(points.map((p2) => p2.pz)); - return points.map((p2, i) => p2.toAffine(toInv[i])).map(Point.fromAffine); - } - /** - * Converts hash string or Uint8Array to Point. - * @param hex short/long ECDSA hex - */ - static fromHex(hex2) { - const P2 = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex2))); - P2.assertValidity(); - return P2; - } - // Multiplies generator point by privateKey. - static fromPrivateKey(privateKey) { - return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - // "Private method", don't use it directly - _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes.delete(this); + async saveWitnesses(args) { + let filteredSignatures = args.signatures; + if (this.onlyRecoverable) { + filteredSignatures = filteredSignatures.filter((signature2) => { + return index$1$1.signer.canRecover(signature2); + }); } - // A point on curve is valid if it conforms to equation. - assertValidity() { - if (this.is0()) { - if (CURVE.allowInfinityPoint && !Fp2.is0(this.py)) - return; - throw new Error("bad point: ZERO"); + await this.sessions.saveSignerSignatures({ + wallet: args.wallet, + digest: args.digest, + chainID: numberString(args.chainId), + signatures: filteredSignatures + }); + } + async configOfImageHash(args) { + try { + const { + version: version2, + config: config2 + } = await this.sessions.config(args); + return decodeConfig(version2, config2); + } catch (error) { + if (is404NotFound(error)) { + return; + } else { + throw error; } - const { x: x2, y: y2 } = this.toAffine(); - if (!Fp2.isValid(x2) || !Fp2.isValid(y2)) - throw new Error("bad point: x or y not FE"); - const left = Fp2.sqr(y2); - const right = weierstrassEquation(x2); - if (!Fp2.eql(left, right)) - throw new Error("bad point: equation left != right"); - if (!this.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - } - hasEvenY() { - const { y: y2 } = this.toAffine(); - if (Fp2.isOdd) - return !Fp2.isOdd(y2); - throw new Error("Field doesn't support isOdd"); - } - /** - * Compare one point to another. - */ - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U12 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); - const U22 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); - return U12 && U22; - } - /** - * Flips point to one corresponding to (x, -y) in Affine coordinates. - */ - negate() { - return new Point(this.px, Fp2.neg(this.py), this.pz); - } - // Renes-Costello-Batina exception-free doubling formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 3 - // Cost: 8M + 3S + 3*a + 2*b3 + 15add. - double() { - const { a: a2, b: b2 } = CURVE; - const b3 = Fp2.mul(b2, _3n); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - let t0 = Fp2.mul(X1, X1); - let t1 = Fp2.mul(Y1, Y1); - let t2 = Fp2.mul(Z1, Z1); - let t3 = Fp2.mul(X1, Y1); - t3 = Fp2.add(t3, t3); - Z3 = Fp2.mul(X1, Z1); - Z3 = Fp2.add(Z3, Z3); - X3 = Fp2.mul(a2, Z3); - Y3 = Fp2.mul(b3, t2); - Y3 = Fp2.add(X3, Y3); - X3 = Fp2.sub(t1, Y3); - Y3 = Fp2.add(t1, Y3); - Y3 = Fp2.mul(X3, Y3); - X3 = Fp2.mul(t3, X3); - Z3 = Fp2.mul(b3, Z3); - t2 = Fp2.mul(a2, t2); - t3 = Fp2.sub(t0, t2); - t3 = Fp2.mul(a2, t3); - t3 = Fp2.add(t3, Z3); - Z3 = Fp2.add(t0, t0); - t0 = Fp2.add(Z3, t0); - t0 = Fp2.add(t0, t2); - t0 = Fp2.mul(t0, t3); - Y3 = Fp2.add(Y3, t0); - t2 = Fp2.mul(Y1, Z1); - t2 = Fp2.add(t2, t2); - t0 = Fp2.mul(t2, t3); - X3 = Fp2.sub(X3, t0); - Z3 = Fp2.mul(t2, t1); - Z3 = Fp2.add(Z3, Z3); - Z3 = Fp2.add(Z3, Z3); - return new Point(X3, Y3, Z3); - } - // Renes-Costello-Batina exception-free addition formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 1 - // Cost: 12M + 0S + 3*a + 3*b3 + 23add. - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - const a2 = CURVE.a; - const b3 = Fp2.mul(CURVE.b, _3n); - let t0 = Fp2.mul(X1, X2); - let t1 = Fp2.mul(Y1, Y2); - let t2 = Fp2.mul(Z1, Z2); - let t3 = Fp2.add(X1, Y1); - let t4 = Fp2.add(X2, Y2); - t3 = Fp2.mul(t3, t4); - t4 = Fp2.add(t0, t1); - t3 = Fp2.sub(t3, t4); - t4 = Fp2.add(X1, Z1); - let t5 = Fp2.add(X2, Z2); - t4 = Fp2.mul(t4, t5); - t5 = Fp2.add(t0, t2); - t4 = Fp2.sub(t4, t5); - t5 = Fp2.add(Y1, Z1); - X3 = Fp2.add(Y2, Z2); - t5 = Fp2.mul(t5, X3); - X3 = Fp2.add(t1, t2); - t5 = Fp2.sub(t5, X3); - Z3 = Fp2.mul(a2, t4); - X3 = Fp2.mul(b3, t2); - Z3 = Fp2.add(X3, Z3); - X3 = Fp2.sub(t1, Z3); - Z3 = Fp2.add(t1, Z3); - Y3 = Fp2.mul(X3, Z3); - t1 = Fp2.add(t0, t0); - t1 = Fp2.add(t1, t0); - t2 = Fp2.mul(a2, t2); - t4 = Fp2.mul(b3, t4); - t1 = Fp2.add(t1, t2); - t2 = Fp2.sub(t0, t2); - t2 = Fp2.mul(a2, t2); - t4 = Fp2.add(t4, t2); - t0 = Fp2.mul(t1, t4); - Y3 = Fp2.add(Y3, t0); - t0 = Fp2.mul(t5, t4); - X3 = Fp2.mul(t3, X3); - X3 = Fp2.sub(X3, t0); - t0 = Fp2.mul(t3, t1); - Z3 = Fp2.mul(t5, Z3); - Z3 = Fp2.add(Z3, t0); - return new Point(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point.ZERO); } - wNAF(n2) { - return wnaf.wNAFCached(this, pointPrecomputes, n2, (comp) => { - const toInv = Fp2.invertBatch(comp.map((p2) => p2.pz)); - return comp.map((p2, i) => p2.toAffine(toInv[i])).map(Point.fromAffine); - }); + } + async saveWalletConfig(args) { + const config2 = encodeConfig(args.config); + await this.sessions.saveConfig({ + version: args.config.version, + config: config2 + }); + } + async imageHashOfCounterfactualWallet(args) { + try { + const { + deployHash, + context: context2 + } = await this.sessions.deployHash(args); + return { + imageHash: deployHash, + context: context2 + }; + } catch (error) { + if (is404NotFound(error)) { + return; + } else { + throw error; + } } - /** - * Non-constant-time multiplication. Uses double-and-add algorithm. - * It's faster, but should only be used when you don't care about - * an exposed private key e.g. sig verification, which works over *public* keys. - */ - multiplyUnsafe(n2) { - const I2 = Point.ZERO; - if (n2 === _0n) - return I2; - assertGE(n2); - if (n2 === _1n$1) - return this; - const { endo } = CURVE; - if (!endo) - return wnaf.unsafeLadder(this, n2); - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n2); - let k1p = I2; - let k2p = I2; - let d2 = this; - while (k1 > _0n || k2 > _0n) { - if (k1 & _1n$1) - k1p = k1p.add(d2); - if (k2 & _1n$1) - k2p = k2p.add(d2); - d2 = d2.double(); - k1 >>= _1n$1; - k2 >>= _1n$1; + } + async saveCounterfactualWallet(args) { + const deployConfig = encodeConfig(args.config); + await this.sessions.saveWallet({ + version: args.config.version, + deployConfig + }); + } + async walletsOfSigner(args) { + const { + wallets + } = await this.sessions.wallets(args); + return Object.entries(wallets).map(([wallet, { + digest, + chainID, + type, + signature: signature2 + }]) => { + switch (type) { + case SignatureType.EIP712: + signature2 += toBeHex(index$1$1.signer.SigType.EIP712).slice(2); + break; + case SignatureType.EthSign: + signature2 += toBeHex(index$1$1.signer.SigType.ETH_SIGN).slice(2); + break; + case SignatureType.EIP1271: + signature2 += toBeHex(index$1$1.signer.SigType.WALLET_BYTES32).slice(2); + break; + } + return { + wallet, + proof: { + digest, + signature: signature2, + chainId: BigInt(chainID) + } + }; + }); + } + async getMigration(wallet, fromImageHash, fromVersion, chainId) { + var _this = this; + const chainIdString = numberString(chainId); + const { + migrations + } = await this.sessions.migrations({ + wallet, + fromVersion, + fromImageHash, + chainID: chainIdString + }); + const chooseMigration = async function chooseMigration2(chainId2) { + const migrations_ = migrations[chainId2]; + if (migrations_) { + const toVersions = Object.keys(migrations_).map(Number).sort((a2, b2) => b2 - a2); + for (const toVersion of toVersions) { + for (const [toHash, transactions2] of Object.entries(migrations_[toVersion])) { + try { + const toConfig = await _this.configOfImageHash({ + imageHash: toHash + }); + if (toConfig) { + return { + fromVersion, + toVersion, + toConfig, + tx: { + entrypoint: transactions2.executor, + transactions: transactions2.transactions, + nonce: transactions2.nonce, + signature: transactions2.signature, + chainId: chainId2, + intent: { + id: index$1$1.transaction.subdigestOfTransactions(wallet, chainId2, transactions2.nonce, transactions2.transactions), + wallet + } + } + }; + } + } catch (error) { + console.error(error); + } + } + } } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); + return; + }; + const migration2 = await chooseMigration(chainIdString); + if (migration2) { + return migration2; } - /** - * Constant time multiplication. - * Uses wNAF method. Windowed method may be 10% faster, - * but takes 2x longer to generate and consumes 2x memory. - * Uses precomputes when available. - * Uses endomorphism for Koblitz curves. - * @param scalar by which the point would be multiplied - * @returns New point - */ - multiply(scalar) { - assertGE(scalar); - let n2 = scalar; - let point, fake; - const { endo } = CURVE; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n2); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - const { p: p2, f: f2 } = this.wNAF(n2); - point = p2; - fake = f2; + for (const _chainId4 in migrations) { + if (_chainId4 !== chainIdString) { + const _migration = await chooseMigration(_chainId4); + if (_migration) { + return _migration; + } } - return Point.normalizeZ([point, fake])[0]; - } - /** - * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. - * Not using Strauss-Shamir trick: precomputation tables are faster. - * The trick could be useful if both P and Q are not G (not in our case). - * @returns non-zero affine point - */ - multiplyAndAddUnsafe(Q2, a2, b2) { - const G2 = Point.BASE; - const mul = (P2, a3) => a3 === _0n || a3 === _1n$1 || !P2.equals(G2) ? P2.multiplyUnsafe(a3) : P2.multiply(a3); - const sum = mul(this, a2).add(mul(Q2, b2)); - return sum.is0() ? void 0 : sum; - } - // Converts Projective point to affine (x, y) coordinates. - // Can accept precomputed Z^-1 - for example, from invertBatch. - // (x, y, z) ∋ (x=x/z, y=y/z) - toAffine(iz) { - const { px: x2, py: y2, pz: z2 } = this; - const is0 = this.is0(); - if (iz == null) - iz = is0 ? Fp2.ONE : Fp2.inv(z2); - const ax = Fp2.mul(x2, iz); - const ay = Fp2.mul(y2, iz); - const zz = Fp2.mul(z2, iz); - if (is0) - return { x: Fp2.ZERO, y: Fp2.ZERO }; - if (!Fp2.eql(zz, Fp2.ONE)) - throw new Error("invZ was invalid"); - return { x: ax, y: ay }; - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n$1) - return true; - if (isTorsionFree) - return isTorsionFree(Point, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n$1) - return this; - if (clearCofactor) - return clearCofactor(Point, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - this.assertValidity(); - return toBytes2(Point, this, isCompressed); - } - toHex(isCompressed = true) { - return bytesToHex(this.toRawBytes(isCompressed)); } + return; } - Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE); - Point.ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + async saveMigration(wallet, signed2, _contexts) { + await this.sessions.saveMigration({ + wallet, + fromVersion: signed2.fromVersion, + toVersion: signed2.toVersion, + toConfig: encodeConfig(signed2.toConfig), + executor: signed2.tx.entrypoint, + transactions: signed2.tx.transactions.map(encodeTransaction), + nonce: numberString(signed2.tx.nonce), + signature: signed2.tx.signature, + chainID: numberString(signed2.tx.chainId) + }); + } +} +function encodeConfig(config2) { + switch (config2.version) { + case 1: + if (v1.config.ConfigCoder.isWalletConfig(config2)) { + return { + threshold: numberNumber(config2.threshold), + signers: config2.signers.map(({ + weight, + address + }) => ({ + weight: numberNumber(weight), + address + })) + }; + } else { + throw new Error(`not a v${config2.version} config: ${config2}`); + } + case 2: + if (v2.config.ConfigCoder.isWalletConfig(config2)) { + return { + threshold: numberNumber(config2.threshold), + checkpoint: numberNumber(config2.checkpoint), + tree: encodeV2ConfigTree(config2.tree) + }; + } else { + throw new Error(`not a v${config2.version} config: ${config2}`); + } + default: + throw new Error(`unknown version ${config2.version}`); + } +} +function encodeV2ConfigTree(tree) { + if (v2.config.isNode(tree)) { + return { + left: encodeV2ConfigTree(tree.left), + right: encodeV2ConfigTree(tree.right) + }; + } else if (v2.config.isSignerLeaf(tree)) { + return { + weight: numberNumber(tree.weight), + address: tree.address + }; + } else if (v2.config.isNestedLeaf(tree)) { + return { + weight: numberNumber(tree.weight), + threshold: numberNumber(tree.threshold), + tree: encodeV2ConfigTree(tree.tree) + }; + } else if (v2.config.isNodeLeaf(tree)) { + return { + node: tree.nodeHash + }; + } else { + return _extends$5({}, tree); + } +} +function decodeConfig(version2, config2) { + switch (version2) { + case 1: + return _extends$5({}, config2, { + version: version2 + }); + case 2: + return _extends$5({}, config2, { + version: version2, + tree: decodeV2ConfigTree(config2.tree) + }); + default: + throw new Error(`unknown version ${version2}`); + } +} +function decodeV2ConfigTree(tree) { + switch (typeof tree) { + case "object": + const tree_ = _extends$5({}, tree); + if (tree_.left !== void 0) { + tree_.left = decodeV2ConfigTree(tree_.left); + } + if (tree_.right !== void 0) { + tree_.right = decodeV2ConfigTree(tree_.right); + } + if (tree_.tree !== void 0) { + tree_.tree = decodeV2ConfigTree(tree_.tree); + } + if (tree_.node !== void 0) { + tree_.nodeHash = tree_.node; + delete tree_.node; + } + return tree_; + default: + throw new Error(`v2 config tree ${tree} is not an object`); + } +} +function encodeTransaction(transaction2) { return { - CURVE, - ProjectivePoint: Point, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder + to: transaction2.to, + value: transaction2.value !== void 0 ? numberString(transaction2.value) : void 0, + data: transaction2.data !== void 0 ? hexlify(transaction2.data) : void 0, + gasLimit: transaction2.gasLimit !== void 0 ? numberString(transaction2.gasLimit) : void 0, + delegateCall: transaction2.delegateCall, + revertOnError: transaction2.revertOnError }; } -function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" +function numberNumber(n2) { + return Number(n2); +} +function numberString(n2) { + return BigInt(n2).toString(); +} +function is404NotFound(error) { + return typeof error === "object" && error.status === 404; +} +var index$1 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + RemoteConfigTracker +}); +function raceUntil(promises, fallback2, evalRes) { + return new Promise((resolve) => { + let count2 = 0; + promises.forEach((p2) => p2.then((val) => { + if (evalRes(val)) { + resolve(val); + } else { + count2++; + if (count2 === promises.length) { + resolve(fallback2); + } + } + }).catch(() => { + count2++; + if (count2 === promises.length) { + resolve(fallback2); + } + })); }); - return Object.freeze({ lowS: true, ...opts }); } -function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp: Fp2, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp2.BYTES + 1; - const uncompressedLen = 2 * Fp2.BYTES + 1; - function isValidFieldElement(num) { - return _0n < num && num < Fp2.ORDER; +async function allSafe(promises, fallback2) { + return Promise.all(promises.map((promise) => promise.catch(() => fallback2))); +} +class MultipleTracker { + constructor(trackers) { + this.trackers = trackers; } - function modN(a2) { - return mod(a2, CURVE_ORDER); + async configOfImageHash(args) { + const requests = this.trackers.map(async function(t2, i) { + return { + res: await t2.configOfImageHash(args), + i + }; + }); + const result1 = await raceUntil(requests, void 0, (val) => { + if ((val == null ? void 0 : val.res) === void 0) return false; + return index$6.genericCoderFor(val.res.version).config.isComplete(val.res); + }); + if (result1 != null && result1.res) { + this.saveWalletConfig({ + config: result1.res, + skipTracker: result1.i + }); + return result1.res; + } + const tmptracker = new LocalConfigTracker(void 0); + const results2 = await allSafe(requests, void 0); + for (const r2 of results2) { + if (r2 != null && r2.res) await tmptracker.saveWalletConfig({ + config: r2.res + }); + } + const result2 = await tmptracker.configOfImageHash(args); + if (result2) this.saveWalletConfig({ + config: result2 + }); + return result2; } - function invN(a2) { - return invert(a2, CURVE_ORDER); + async saveWalletConfig(args) { + await Promise.all(this.trackers.map((t2, i) => { + if (i === args.skipTracker) return; + return t2.saveWalletConfig(args); + })); } - const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ - ...CURVE, - toBytes(_c2, point, isCompressed) { - const a2 = point.toAffine(); - const x2 = Fp2.toBytes(a2.x); - const cat = concatBytes; - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x2); - } else { - return cat(Uint8Array.from([4]), x2, Fp2.toBytes(a2.y)); - } - }, - fromBytes(bytes2) { - const len = bytes2.length; - const head = bytes2[0]; - const tail = bytes2.subarray(1); - if (len === compressedLen && (head === 2 || head === 3)) { - const x2 = bytesToNumberBE(tail); - if (!isValidFieldElement(x2)) - throw new Error("Point is not on curve"); - const y2 = weierstrassEquation(x2); - let y3; - try { - y3 = Fp2.sqrt(y2); - } catch (sqrtError) { - const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; - throw new Error("Point is not on curve" + suffix); + async imageHashOfCounterfactualWallet(args) { + const imageHash2 = await raceUntil(this.trackers.map((t2) => t2.imageHashOfCounterfactualWallet(args)), void 0, (result) => Boolean(result)); + if (imageHash2) { + this.configOfImageHash({ + imageHash: imageHash2.imageHash + }).then((config2) => { + if (config2) { + this.saveCounterfactualWallet({ + config: config2, + context: [imageHash2.context] + }); } - const isYOdd = (y3 & _1n$1) === _1n$1; - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y3 = Fp2.neg(y3); - return { x: x2, y: y3 }; - } else if (len === uncompressedLen && head === 4) { - const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x: x2, y: y2 }; - } else { - throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + }); + } + return imageHash2; + } + async saveCounterfactualWallet(args) { + await Promise.all(this.trackers.map((t2, i) => { + if (i === args.skipTracker) return; + return t2.saveCounterfactualWallet(args); + })); + } + async walletsOfSigner(args) { + const results2 = await allSafe(this.trackers.map((t2) => t2.walletsOfSigner(args)), []).then((r2) => r2.flat()); + const wallets = {}; + for (const r2 of results2) { + wallets[r2.wallet] = r2.proof; + } + const result = Object.keys(wallets).map((w2) => ({ + wallet: w2, + proof: wallets[w2] + })); + const witnesses = /* @__PURE__ */ new Map(); + result.forEach(({ + wallet, + proof: { + digest, + chainId, + signature: signature2 + } + }) => { + const key = `${wallet}-${digest}-${chainId}`; + let signatures = witnesses.get(key); + if (!signatures) { + signatures = { + wallet, + digest, + chainId, + signatures: [] + }; + witnesses.set(key, signatures); + } + signatures.signatures.push(signature2); + }); + witnesses.forEach((witnesses2) => this.saveWitnesses(witnesses2)); + return result; + } + async saveWitnesses(args) { + await Promise.all(this.trackers.map((t2) => t2.saveWitnesses(args))); + } + async loadPresignedConfiguration(args) { + var _this = this; + const results2 = await allSafe(this.trackers.map((t2) => t2.loadPresignedConfiguration(args)), []); + const checkpoints = await allSafe(results2.map(async function(r2) { + const last = r2[r2.length - 1]; + const config3 = await _this.configOfImageHash({ + imageHash: last.nextImageHash + }); + if (!config3) return void 0; + return { + checkpoint: index$6.genericCoderFor(config3.version).config.checkpointOf(config3), + result: r2 + }; + }), void 0); + const best = checkpoints.reduce((acc, val) => { + if (!val) return acc; + if (!acc) return val; + if (val.checkpoint > acc.checkpoint) return val; + return acc; + }); + if (!best) return []; + const configs = /* @__PURE__ */ new Map(); + const config2 = (imageHash2) => { + if (!configs.has(imageHash2)) { + configs.set(imageHash2, this.configOfImageHash({ + imageHash: imageHash2 + })); + } + return configs.get(imageHash2); + }; + best.result.forEach(async function(res) { + const nextConfig = await config2(res.nextImageHash); + if (nextConfig) { + _this.savePresignedConfiguration({ + wallet: args.wallet, + nextConfig, + signature: res.signature + }); } + }); + return best.result; + } + async savePresignedConfiguration(args) { + await Promise.all(this.trackers.map((t2) => t2.savePresignedConfiguration(args))); + } + async getMigration(address, fromImageHash, fromVersion, chainId) { + const results2 = await Promise.all(this.trackers.map((t2) => t2.getMigration(address, fromImageHash, fromVersion, chainId))); + return results2.find((r2) => !!r2); + } + async saveMigration(address, signed2, contexts) { + await Promise.all(this.trackers.map((t2) => t2.saveMigration(address, signed2, contexts))); + } +} +class CachedTracker { + constructor(tracker2, cache2, contexts) { + this.tracker = tracker2; + this.cache = cache2; + this.contexts = contexts; + } + async loadPresignedConfiguration(args) { + var _this = this; + const results2 = [this.tracker.loadPresignedConfiguration(args), this.cache.loadPresignedConfiguration(args)]; + let best; + const [result1, result2] = await Promise.all(results2); + if (result1.length > 0 && result2.length > 0 && result1[result1.length - 1].nextImageHash === result2[result2.length - 1].nextImageHash) { + best = args.longestPath === true ? result1.length > result2.length ? result1 : result2 : result1.length < result2.length ? result1 : result2; + } else { + var _checkpoints$reduce$r, _checkpoints$reduce; + const checkpoints = await Promise.all(results2.map(async function(result) { + const r2 = await result; + const last = r2[r2.length - 1]; + if (!last) return void 0; + const config2 = await _this.configOfImageHash({ + imageHash: last.nextImageHash + }); + if (!config2) return void 0; + return { + checkpoint: index$6.genericCoderFor(config2.version).config.checkpointOf(config2), + result: r2 + }; + })); + best = (_checkpoints$reduce$r = (_checkpoints$reduce = checkpoints.reduce((acc, val) => { + if (!val) return acc; + if (!acc) return val; + if (val.checkpoint > acc.checkpoint) return val; + return acc; + })) == null ? void 0 : _checkpoints$reduce.result) != null ? _checkpoints$reduce$r : []; } - }); - const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number2) { - const HALF = CURVE_ORDER >> _1n$1; - return number2 > HALF; + if (!best) return []; + return best; } - function normalizeS(s2) { - return isBiggerThanHalfOrder(s2) ? modN(-s2) : s2; + async savePresignedConfiguration(args) { + await Promise.all([this.tracker.savePresignedConfiguration(args), this.cache.savePresignedConfiguration(args)]); } - const slcNum = (b2, from, to) => bytesToNumberBE(b2.slice(from, to)); - class Signature2 { - constructor(r2, s2, recovery) { - this.r = r2; - this.s = s2; - this.recovery = recovery; - this.assertValidity(); - } - // pair (bytes of r, bytes of s) - static fromCompact(hex2) { - const l2 = CURVE.nByteLength; - hex2 = ensureBytes("compactSignature", hex2, l2 * 2); - return new Signature2(slcNum(hex2, 0, l2), slcNum(hex2, l2, 2 * l2)); - } - // DER encoded ECDSA signature - // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script - static fromDER(hex2) { - const { r: r2, s: s2 } = DER.toSig(ensureBytes("DER", hex2)); - return new Signature2(r2, s2); - } - assertValidity() { - if (!isWithinCurveOrder(this.r)) - throw new Error("r must be 0 < r < CURVE.n"); - if (!isWithinCurveOrder(this.s)) - throw new Error("s must be 0 < s < CURVE.n"); - } - addRecoveryBit(recovery) { - return new Signature2(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r: r2, s: s2, recovery: rec } = this; - const h2 = bits2int_modN(ensureBytes("msgHash", msgHash)); - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const radj = rec === 2 || rec === 3 ? r2 + CURVE.n : r2; - if (radj >= Fp2.ORDER) - throw new Error("recovery id 2 or 3 invalid"); - const prefix = (rec & 1) === 0 ? "02" : "03"; - const R2 = Point.fromHex(prefix + numToNByteStr(radj)); - const ir = invN(radj); - const u1 = modN(-h2 * ir); - const u2 = modN(s2 * ir); - const Q2 = Point.BASE.multiplyAndAddUnsafe(R2, u1, u2); - if (!Q2) - throw new Error("point at infinify"); - Q2.assertValidity(); - return Q2; + async configOfImageHash(args) { + if (args.noCache !== true) { + const config3 = await this.cache.configOfImageHash(args); + if (config3) return config3; } - // Signatures should be low-s, to prevent malleability. - hasHighS() { - return isBiggerThanHalfOrder(this.s); + const config2 = await this.tracker.configOfImageHash(args); + if (config2) { + await this.cache.saveWalletConfig({ + config: config2 + }); } - normalizeS() { - return this.hasHighS() ? new Signature2(this.r, modN(-this.s), this.recovery) : this; + return config2; + } + async saveWalletConfig(args) { + await Promise.all([this.tracker.saveWalletConfig(args), this.cache.saveWalletConfig(args)]); + } + async imageHashOfCounterfactualWallet(args) { + if (args.noCache !== true) { + const result1 = await this.cache.imageHashOfCounterfactualWallet(args); + if (result1) return result1; } - // DER-encoded - toDERRawBytes() { - return hexToBytes(this.toDERHex()); + const result2 = await this.tracker.imageHashOfCounterfactualWallet(args); + if (result2) { + const config2 = await this.configOfImageHash({ + imageHash: result2.imageHash + }); + if (config2) { + await this.cache.saveCounterfactualWallet({ + config: config2, + context: [result2.context] + }); + } } - toDERHex() { - return DER.hexFromSig({ r: this.r, s: this.s }); + return result2; + } + async saveCounterfactualWallet(args) { + await Promise.all([this.tracker.saveCounterfactualWallet(args), this.cache.saveCounterfactualWallet(args)]); + } + async walletsOfSigner(args) { + if (args.noCache) { + return this.tracker.walletsOfSigner(args); } - // padded bytes of r, then padded bytes of s - toCompactRawBytes() { - return hexToBytes(this.toCompactHex()); + const results2 = await Promise.all([this.tracker.walletsOfSigner(args), this.cache.walletsOfSigner(args)]); + const wallets = /* @__PURE__ */ new Map(); + for (const result of results2) { + for (const wallet of result) { + wallets.set(wallet.wallet, wallet); + } } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); + return Array.from(wallets.values()); + } + async saveWitnesses(args) { + await Promise.all([this.tracker.saveWitnesses(args), this.cache.saveWitnesses(args)]); + } + async getMigration(address, fromImageHash, fromVersion, chainId) { + const migration1 = await this.cache.getMigration(address, fromImageHash, fromVersion, chainId); + if (migration1) return migration1; + const migration2 = await this.tracker.getMigration(address, fromImageHash, fromVersion, chainId); + if (migration2) { + await this.cache.saveMigration(address, migration2, this.contexts); } + return migration2; } - const utils2 = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } catch (error) { - return false; + async saveMigration(address, signed2, contexts) { + await Promise.all([this.tracker.saveMigration(address, signed2, contexts), this.cache.saveMigration(address, signed2, contexts)]); + } +} +class PromiseCache2 { + constructor() { + this.cache = void 0; + this.cache = /* @__PURE__ */ new Map(); + } + do(key, validMilliseconds, task, ...args) { + key = `${key}:${id$1(JSON.stringify(args, deterministically))}`; + let entry = this.cache.get(key); + if (entry) { + if (entry.expiration) { + if (/* @__PURE__ */ new Date() >= entry.expiration) { + entry = void 0; + this.cache.delete(key); + } } - }, - normPrivateKeyToScalar, - /** - * Produces cryptographically secure private key from random of size - * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. - */ - randomPrivateKey: () => { - const length = getMinHashLength(CURVE.n); - return mapHashToField(CURVE.randomBytes(length), CURVE.n); - }, - /** - * Creates precompute table for an arbitrary EC point. Makes point "cached". - * Allows to massively speed-up `point.multiply(scalar)`. - * @returns cached point - * @example - * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); - * fast.multiply(privKey); // much faster ECDH now - */ - precompute(windowSize = 8, point = Point.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); - return point; } - }; - function getPublicKey(privateKey, isCompressed = true) { - return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + if (!entry) { + const entry_ = { + promise: task(...args) + }; + if (validMilliseconds !== void 0) { + entry_.promise = entry_.promise.then((result) => { + entry_.expiration = new Date(Date.now() + validMilliseconds); + return result; + }); + } + entry = entry_; + this.cache.set(key, entry); + } + return entry.promise; } - function isProbPub(item2) { - const arr = isBytes(item2); - const str = typeof item2 === "string"; - const len = (arr || str) && item2.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item2 instanceof Point) - return true; - return false; +} +function deterministically(_key, value) { + if (typeof value === "object" && value !== null && !Array.isArray(value)) { + return Object.fromEntries(Object.entries(value).sort()); + } else if (typeof value === "bigint") { + return value.toString(); } - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error("first arg must be private key"); - if (!isProbPub(publicB)) - throw new Error("second arg must be public key"); - const b2 = Point.fromHex(publicB); - return b2.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + return value; +} +function isDedupedTracker(tracker2) { + return tracker2 instanceof DedupedTracker; +} +class DedupedTracker { + constructor(tracker2, window2 = 50, verbose = false) { + this.tracker = tracker2; + this.window = window2; + this.verbose = verbose; + this.cache = new PromiseCache2(); } - const bits2int = CURVE.bits2int || function(bytes2) { - const num = bytesToNumberBE(bytes2); - const delta = bytes2.length * 8 - CURVE.nBitLength; - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE.bits2int_modN || function(bytes2) { - return modN(bits2int(bytes2)); - }; - const ORDER_MASK = bitMask(CURVE.nBitLength); - function int2octets(num) { - if (typeof num !== "bigint") - throw new Error("bigint expected"); - if (!(_0n <= num && num < ORDER_MASK)) - throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); - return numberToBytesBE(num, CURVE.nByteLength); + invalidateCache() { + this.cache = new PromiseCache2(); } - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (["recovered", "canonical"].some((k2) => k2 in opts)) - throw new Error("sign() legacy options not supported"); - const { hash: hash2, randomBytes: randomBytes2 } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; - msgHash = ensureBytes("msgHash", msgHash); - if (prehash) - msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); - const h1int = bits2int_modN(msgHash); - const d2 = normPrivateKeyToScalar(privateKey); - const seedArgs = [int2octets(d2), int2octets(h1int)]; - if (ent != null && ent !== false) { - const e2 = ent === true ? randomBytes2(Fp2.BYTES) : ent; - seedArgs.push(ensureBytes("extraEntropy", e2)); - } - const seed = concatBytes(...seedArgs); - const m2 = h1int; - function k2sig(kBytes) { - const k2 = bits2int(kBytes); - if (!isWithinCurveOrder(k2)) - return; - const ik2 = invN(k2); - const q2 = Point.BASE.multiply(k2).toAffine(); - const r2 = modN(q2.x); - if (r2 === _0n) - return; - const s2 = modN(ik2 * modN(m2 + r2 * d2)); - if (s2 === _0n) - return; - let recovery = (q2.x === r2 ? 0 : 2) | Number(q2.y & _1n$1); - let normS = s2; - if (lowS && isBiggerThanHalfOrder(s2)) { - normS = normalizeS(s2); - recovery ^= 1; - } - return new Signature2(r2, normS, recovery); + configOfImageHash(args) { + return this.cache.do("configOfImageHash", this.window, (args2) => this.tracker.configOfImageHash(args2), args); + } + getMigration(address, fromImageHash, fromVersion, chainId) { + return this.cache.do("getMigration", this.window, (...args) => this.tracker.getMigration(...args), address, fromImageHash, fromVersion, chainId); + } + saveMigration(address, signed2, contexts) { + return this.cache.do("saveMigration", void 0, (...args) => this.tracker.saveMigration(...args), address, signed2, contexts); + } + loadPresignedConfiguration(args) { + return this.cache.do("loadPresignedConfiguration", this.window, (args2) => this.tracker.loadPresignedConfiguration(args2), args); + } + savePresignedConfiguration(args) { + return this.cache.do("savePresignedConfiguration", void 0, (args2) => this.tracker.savePresignedConfiguration(args2), args); + } + saveWitnesses(args) { + return this.cache.do("saveWitnesses", void 0, (args2) => this.tracker.saveWitnesses(args2), args); + } + saveWalletConfig(args) { + return this.cache.do("saveWalletConfig", void 0, (args2) => this.tracker.saveWalletConfig(args2), args); + } + imageHashOfCounterfactualWallet(args) { + return this.cache.do("imageHashOfCounterfactualWallet", void 0, (args2) => this.tracker.imageHashOfCounterfactualWallet(args2), args); + } + saveCounterfactualWallet(args) { + return this.cache.do("saveCounterfactualWallet", void 0, (args2) => this.tracker.saveCounterfactualWallet(args2), args); + } + walletsOfSigner(args) { + return this.cache.do("walletsOfSigner", this.window, (args2) => this.tracker.walletsOfSigner(args2), args); + } + updateProvider(provider2) { + if (this.tracker instanceof LocalConfigTracker) { + this.tracker.updateProvider(provider2); } - return { seed, k2sig }; } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); - const C2 = CURVE; - const drbg = createHmacDrbg(C2.hash.outputLen, C2.nByteLength, C2.hmac); - return drbg(seed, k2sig); +} +var index$3 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + debug: debug$1, + local, + remote: index$1, + stores: index$2, + raceUntil, + allSafe, + MultipleTracker, + CachedTracker, + isDedupedTracker, + DedupedTracker +}); +const sessions$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + tracker, + trackers: index$3 +}, Symbol.toStringTag, { value: "Module" })); +const DEFAULT_SESSION_EXPIRATION$1 = 60 * 60 * 24 * 7; +const EXPIRATION_JWT_MARGIN = 60; +class Services { + constructor(account2, settings, status = {}, projectAccessKey2) { + this.account = account2; + this.settings = settings; + this.status = status; + this._initialAuthRequest = void 0; + this.proofStrings = /* @__PURE__ */ new Map(); + this.onAuthCallbacks = []; + this.apiClient = void 0; + this.metadataClient = void 0; + this.indexerClients = /* @__PURE__ */ new Map(); + this.projectAccessKey = void 0; + this.projectAccessKey = projectAccessKey2; } - Point.BASE._setWindowSize(8); - function verify(signature2, msgHash, publicKey, opts = defaultVerOpts) { - var _a2; - const sg2 = signature2; - msgHash = ensureBytes("msgHash", msgHash); - publicKey = ensureBytes("publicKey", publicKey); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - const { lowS, prehash } = opts; - let _sig2 = void 0; - let P2; - try { - if (typeof sg2 === "string" || isBytes(sg2)) { + now() { + return Math.floor(Date.now() / 1e3); + } + get expiration() { + var _this$settings$metada; + return Math.max((_this$settings$metada = this.settings.metadata.expiration) != null ? _this$settings$metada : DEFAULT_SESSION_EXPIRATION$1, 120); + } + onAuth(cb2) { + this.onAuthCallbacks.push(cb2); + return () => this.onAuthCallbacks = this.onAuthCallbacks.filter((c2) => c2 !== cb2); + } + async dump() { + if (!this.status.jwt) return { + metadata: this.settings.metadata + }; + return { + jwt: { + token: await this.status.jwt.token, + expiration: this.status.jwt.expiration + }, + metadata: this.status.metadata + }; + } + auth(maxTries = 5) { + var _this = this; + if (this._initialAuthRequest) return this._initialAuthRequest; + this._initialAuthRequest = async function() { + const url = _this.settings.sequenceApiUrl; + if (!url) throw Error("No sequence api url"); + let jwtAuth; + for (let i = 1; ; i++) { try { - _sig2 = Signature2.fromDER(sg2); - } catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; - _sig2 = Signature2.fromCompact(sg2); + jwtAuth = (await _this.getJWT(true)).token; + break; + } catch (error) { + if (i === maxTries) { + console.error(`couldn't authenticate after ${maxTries} attempts`, error); + throw error; + } } - } else if (typeof sg2 === "object" && typeof sg2.r === "bigint" && typeof sg2.s === "bigint") { - const { r: r3, s: s3 } = sg2; - _sig2 = new Signature2(r3, s3); - } else { - throw new Error("PARSE"); } - P2 = Point.fromHex(publicKey); - } catch (error) { - if (error.message === "PARSE") - throw new Error(`signature must be Signature instance, Uint8Array or hex string`); - return false; + return new SequenceAPIClient(url, void 0, jwtAuth); + }(); + return this._initialAuthRequest; + } + async getJWT(tryAuth) { + var _this2 = this; + const url = this.settings.sequenceApiUrl; + if (!url) throw Error("No sequence api url"); + if (this.status.jwt) { + const _jwt = this.status.jwt; + const _token = await _jwt.token; + if (this.now() < _jwt.expiration) { + return { + token: _token, + expiration: _jwt.expiration + }; + } + this.status.jwt = void 0; } - if (lowS && _sig2.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r: r2, s: s2 } = _sig2; - const h2 = bits2int_modN(msgHash); - const is = invN(s2); - const u1 = modN(h2 * is); - const u2 = modN(r2 * is); - const R2 = (_a2 = Point.BASE.multiplyAndAddUnsafe(P2, u1, u2)) == null ? void 0 : _a2.toAffine(); - if (!R2) + if (!tryAuth) { + throw new Error("no auth token in memory"); + } + const proofStringKey = this.getProofStringKey(); + const { + proofString, + expiration + } = this.getProofString(proofStringKey); + const jwt = { + token: proofString.then(async function(proofString2) { + const api2 = new SequenceAPIClient(url); + const authResp = await api2.getAuthToken({ + ewtString: proofString2 + }); + if ((authResp == null ? void 0 : authResp.status) === true && authResp.jwtToken.length !== 0) { + return authResp.jwtToken; + } else { + if (!await _this2.isProofStringValid(proofString2)) { + _this2.proofStrings.delete(proofStringKey); + } + throw new Error("no auth token from server"); + } + }).catch((reason) => { + this.status.jwt = void 0; + throw reason; + }), + expiration + }; + this.status.jwt = jwt; + jwt.token.then((token2) => { + this.onAuthCallbacks.forEach((cb2) => { + try { + cb2({ + status: "fulfilled", + value: token2 + }); + } catch (_unused) { + } + }); + }).catch((reason) => { + this.onAuthCallbacks.forEach((cb2) => { + try { + cb2({ + status: "rejected", + reason + }); + } catch (_unused2) { + } + }); + }); + const token = await jwt.token; + return { + token, + expiration + }; + } + getProofStringKey() { + return `${this.account.address} - ${this.settings.metadata.name}`; + } + async isProofStringValid(proofString) { + try { + const ethAuth = new ETHAuth(); + const chainId = BigInt(this.settings.sequenceApiChainId); + const found = findNetworkConfig(this.account.networks, chainId); + if (!found) { + throw Error("No network found"); + } + ethAuth.chainId = Number(chainId); + const network2 = new Network(found.name, chainId); + ethAuth.provider = new JsonRpcProvider$1(getFetchRequest(found.rpcUrl, this.projectAccessKey), network2, { + staticNetwork: network2 + }); + await ethAuth.decodeProof(proofString); + return true; + } catch (_unused3) { return false; - const v3 = modN(R2.x); - return v3 === r2; + } } - return { - CURVE, - getPublicKey, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point, - Signature: Signature2, - utils: utils2 - }; -} -class HMAC2 extends Hash3 { - constructor(hash2, _key) { - super(); - this.finished = false; - this.destroyed = false; - hash$1(hash2); - const key = toBytes(_key); - this.iHash = hash2.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad2 = new Uint8Array(blockLen); - pad2.set(key.length > blockLen ? hash2.create().update(key).digest() : key); - for (let i = 0; i < pad2.length; i++) - pad2[i] ^= 54; - this.iHash.update(pad2); - this.oHash = hash2.create(); - for (let i = 0; i < pad2.length; i++) - pad2[i] ^= 54 ^ 92; - this.oHash.update(pad2); - pad2.fill(0); + async getAPIClient(tryAuth = true) { + if (!this.apiClient) { + const url = this.settings.sequenceApiUrl; + if (!url) throw Error("No sequence api url"); + const jwtAuth = (await this.getJWT(tryAuth)).token; + this.apiClient = new SequenceAPIClient(url, void 0, jwtAuth); + } + return this.apiClient; } - update(buf) { - exists(this); - this.iHash.update(buf); - return this; + async getMetadataClient(tryAuth = true) { + if (!this.metadataClient) { + const jwtAuth = (await this.getJWT(tryAuth)).token; + this.metadataClient = new SequenceMetadata(this.settings.sequenceMetadataUrl, void 0, jwtAuth); + } + return this.metadataClient; } - digestInto(out) { - exists(this); - bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); + async getIndexerClient(chainId, tryAuth = true) { + const network2 = findNetworkConfig(this.account.networks, chainId); + if (!network2) { + throw Error(`No network for chain ${chainId}`); + } + if (!this.indexerClients.has(network2.chainId)) { + if (network2.indexer) { + this.indexerClients.set(network2.chainId, network2.indexer); + } else if (network2.indexerUrl) { + const jwtAuth = (await this.getJWT(tryAuth)).token; + this.indexerClients.set(network2.chainId, new SequenceIndexer(network2.indexerUrl, void 0, jwtAuth)); + } else { + throw Error(`No indexer url for chain ${chainId}`); + } + } + return this.indexerClients.get(network2.chainId); } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; + getProofString(key) { + if (this.proofStrings.has(key)) { + const _proofString = this.proofStrings.get(key); + if (this.now() < _proofString.expiration) { + return _proofString; + } + this.proofStrings.delete(key); + } + const proof = new Proof({ + address: this.account.address + }); + proof.claims.app = this.settings.metadata.name; + if (typeof window === "object") { + proof.claims.ogn = window.location.origin; + } + proof.setExpiryIn(this.expiration); + const ethAuth = new ETHAuth(); + const chainId = BigInt(this.settings.sequenceApiChainId); + const found = findNetworkConfig(this.account.networks, chainId); + if (!found) { + throw Error("No network found"); + } + ethAuth.chainId = Number(chainId); + const network2 = new Network(found.name, chainId); + ethAuth.provider = new JsonRpcProvider$1(getFetchRequest(found.rpcUrl, this.projectAccessKey), network2, { + staticNetwork: network2 + }); + const expiration = this.now() + this.expiration - EXPIRATION_JWT_MARGIN; + const proofString = { + proofString: Promise.resolve( + // NOTICE: TODO: Here we ask the account to sign the message + // using whatever configuration we have ON-CHAIN, this means + // that the account will still use the v1 wallet, even if the migration + // was signed. + // + // This works for Sequence webapp v1 -> v2 because all v1 configurations share the same formula + // (torus + guard), but if we ever decide to allow cross-device login, then it will not work, because + // those other signers may not be part of the configuration. + // + this.account.signDigest(proof.messageDigest(), this.settings.sequenceApiChainId, true, "eip6492") + ).then((s2) => { + proof.signature = s2; + return ethAuth.encodeProof(proof, true); + }).catch((reason) => { + this.proofStrings.delete(key); + throw reason; + }), + expiration + }; + this.proofStrings.set(key, proofString); + return proofString; } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; +} +const signAuthorization = async (signer2, chainId, options) => { + const address = getAddress(await signer2.getAddress()); + if (!address || address === "" || address === "0x") { + throw ErrAccountIsRequired; } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); + const proof = new Proof(); + proof.address = address; + if (!options || !options.app || options.app === "") { + throw new AuthError("authorization options requires app to be set"); } -} -const hmac$1 = (hash2, key, message) => new HMAC2(hash2, key).update(message).digest(); -hmac$1.create = (hash2, key) => new HMAC2(hash2, key); -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -function getHash(hash2) { + proof.claims.app = options.app; + proof.claims.ogn = options.origin; + proof.claims.n = options.nonce; + proof.setExpiryIn(options.expiry ? Math.max(options.expiry, 200) : DEFAULT_SESSION_EXPIRATION$1); + const typedData = proof.messageTypedData(); + const chainIdNumber = toChainIdNumber(chainId); + proof.signature = await (signer2 instanceof Account ? ( + // Account can sign EIP-6492 signatures, so it doesn't require deploying the wallet + signer2.signTypedData(typedData.domain, typedData.types, typedData.message, chainIdNumber, "eip6492") + ) : signer2.signTypedData(typedData.domain, typedData.types, typedData.message, chainIdNumber)); + const ethAuth = new ETHAuth(); + const proofString = await ethAuth.encodeProof(proof, true); return { - hash: hash2, - hmac: (key, ...msgs) => hmac$1(hash2, key, concatBytes$1(...msgs)), - randomBytes + typedData, + proofString }; +}; +class AuthError extends Error { + constructor(message) { + super(message); + this.name = "AuthError"; + } } -function createCurve(curveDef, defHash) { - const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); - return Object.freeze({ ...create(defHash), create }); -} -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); -const secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); -const _1n = BigInt(1); -const _2n = BigInt(2); -const divNearest = (a2, b2) => (a2 + b2 / _2n) / b2; -function sqrtMod(y2) { - const P2 = secp256k1P; - const _3n2 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y2 * y2 * y2 % P2; - const b3 = b2 * b2 * y2 % P2; - const b6 = pow2(b3, _3n2, P2) * b3 % P2; - const b9 = pow2(b6, _3n2, P2) * b3 % P2; - const b11 = pow2(b9, _2n, P2) * b2 % P2; - const b22 = pow2(b11, _11n, P2) * b11 % P2; - const b44 = pow2(b22, _22n, P2) * b22 % P2; - const b88 = pow2(b44, _44n, P2) * b44 % P2; - const b176 = pow2(b88, _88n, P2) * b88 % P2; - const b220 = pow2(b176, _44n, P2) * b44 % P2; - const b223 = pow2(b220, _3n2, P2) * b3 % P2; - const t1 = pow2(b223, _23n, P2) * b22 % P2; - const t2 = pow2(t1, _6n, P2) * b2 % P2; - const root2 = pow2(t2, _2n, P2); - if (!Fp.eql(Fp.sqr(root2), y2)) - throw new Error("Cannot find square root"); - return root2; -} -const Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); -const secp256k1 = createCurve({ - a: BigInt(0), - // equation params: a, b - b: BigInt(7), - // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 - Fp, - // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n - n: secp256k1N, - // Curve order, total count of valid points in the field - // Base point (x, y) aka generator point - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - // Cofactor - lowS: true, - // Allow only low-S signatures by default in sign() and verify() - /** - * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. - * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. - * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. - * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 - */ - endo: { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k2) => { - const n2 = secp256k1N; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest(b2 * k2, n2); - const c2 = divNearest(-b1 * k2, n2); - let k1 = mod(k2 - c1 * a1 - c2 * a2, n2); - let k22 = mod(-c1 * b1 - c2 * b2, n2); - const k1neg = k1 > POW_2_128; - const k2neg = k22 > POW_2_128; - if (k1neg) - k1 = n2 - k1; - if (k2neg) - k22 = n2 - k22; - if (k1 > POW_2_128 || k22 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k2); +const ErrAccountIsRequired = new AuthError("auth error: account address is empty"); +function _extends$4() { + _extends$4 = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } } - return { k1neg, k1, k2neg, k2: k22 }; } - } -}, sha256$1); -BigInt(0); -secp256k1.ProjectivePoint; -const secp256k1$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - secp256k1 -}, Symbol.toStringTag, { value: "Module" })); -function serializeSignature({ r: r2, s: s2, to = "hex", v: v3, yParity }) { - const yParity_ = (() => { - if (yParity === 0 || yParity === 1) - return yParity; - if (v3 && (v3 === 27n || v3 === 28n || v3 >= 35n)) - return v3 % 2n === 0n ? 1 : 0; - throw new Error("Invalid `v` or `yParity` value"); - })(); - const signature2 = `0x${new secp256k1.Signature(hexToBigInt(r2), hexToBigInt(s2)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`; - if (to === "hex") - return signature2; - return hexToBytes$1(signature2); + return target; + }; + return _extends$4.apply(this, arguments); } -async function verifyHash(client2, parameters) { - const { address, factory: factory2, factoryData, hash: hash2, signature: signature2, ...rest } = parameters; - const signatureHex = (() => { - if (isHex(signature2)) - return signature2; - if (typeof signature2 === "object" && "r" in signature2 && "s" in signature2) - return serializeSignature(signature2); - return bytesToHex$1(signature2); - })(); - const wrappedSignature = await (async () => { - if (!factory2 && !factoryData) - return signatureHex; - if (isErc6492Signature(signatureHex)) - return signatureHex; - return serializeErc6492Signature({ - address: factory2, - data: factoryData, - signature: signatureHex - }); - })(); - try { - const { data } = await getAction$1(client2, call, "call")({ - data: encodeDeployData({ - abi: universalSignatureValidatorAbi, - args: [address, hash2, wrappedSignature], - bytecode: universalSignatureValidatorByteCode - }), - ...rest - }); - return isBytesEqual(data ?? "0x0", "0x1"); - } catch (error) { - try { - const verified = isAddressEqual(getAddress(address), await recoverAddress({ hash: hash2, signature: signature2 })); - if (verified) - return true; - } catch { +function isSessionDumpV1(obj) { + return obj.config && obj.metadata && obj.version === void 0; +} +function isSessionDumpV2(obj) { + return obj.version === 2 && obj.address; +} +const CRITICAL_CHAINS = [1, 137]; +const SessionSettingsDefault = { + contexts: index$1$1.context.defaultContexts, + networks: allNetworks, + tracker: new index$3.remote.RemoteConfigTracker("https://sessions.sequence.app") +}; +class Session { + constructor(networks2, contexts, account2, services) { + this.networks = networks2; + this.contexts = contexts; + this.account = account2; + this.services = services; + } + async dump() { + const base = { + version: 2, + address: this.account.address + }; + if (this.services) { + return _extends$4({}, base, await this.services.dump()); } - if (error instanceof CallExecutionError) { - return false; + return base; + } + static async singleSigner(args) { + let { + signer: signer2 + } = args; + if (typeof signer2 === "string") { + signer2 = new Wallet$1(signer2); } - throw error; + const orchestrator = new Orchestrator([signer2]); + const referenceSigner = await signer2.getAddress(); + const threshold = 1; + const addSigners = [{ + weight: 1, + address: referenceSigner + }]; + const selectWallet = args.selectWallet || async function(wallets) { + var _args$settings$tracke, _args$settings; + if (wallets.length === 0) return void 0; + const tracker2 = (_args$settings$tracke = (_args$settings = args.settings) == null ? void 0 : _args$settings.tracker) != null ? _args$settings$tracke : SessionSettingsDefault.tracker; + const configs = await Promise.all(wallets.map(async function(wallet) { + const imageHash2 = await tracker2.imageHashOfCounterfactualWallet({ + wallet + }); + return { + wallet, + config: imageHash2 && await tracker2.configOfImageHash({ + imageHash: imageHash2.imageHash + }) + }; + })); + for (const config2 of configs) { + if (!config2.config) { + continue; + } + const coder = index$6.genericCoderFor(config2.config.version); + const signers = coder.config.signersOf(config2.config); + if (signers.length === 1 && signers[0].address === referenceSigner) { + return config2.wallet; + } + } + return void 0; + }; + return Session.open(_extends$4({}, args, { + orchestrator, + referenceSigner, + threshold, + addSigners, + selectWallet + })); } -} -async function verifyMessage(client2, { address, message, factory: factory2, factoryData, signature: signature2, ...callRequest }) { - const hash2 = hashMessage(message); - return verifyHash(client2, { - address, - factory: factory2, - factoryData, - hash: hash2, - signature: signature2, - ...callRequest - }); -} -async function verifyTypedData(client2, parameters) { - const { address, factory: factory2, factoryData, signature: signature2, message, primaryType, types: types2, domain: domain2, ...callRequest } = parameters; - const hash2 = hashTypedData({ message, primaryType, types: types2, domain: domain2 }); - return verifyHash(client2, { - address, - factory: factory2, - factoryData, - hash: hash2, - signature: signature2, - ...callRequest - }); -} -async function watchAsset(client2, params) { - const added = await client2.request({ - method: "wallet_watchAsset", - params - }, { retryCount: 0 }); - return added; -} -function watchContractEvent(client2, parameters) { - const { abi: abi2, address, args, batch = true, eventName, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client2.pollingInterval, strict: strict_ } = parameters; - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (typeof fromBlock === "bigint") - return true; - if (client2.transport.type === "webSocket") - return false; - if (client2.transport.type === "fallback" && client2.transport.transports[0].config.type === "webSocket") - return false; - return true; - })(); - const pollContractEvent = () => { - const strict = strict_ ?? false; - const observerId = stringify([ - "watchContractEvent", - address, - args, - batch, - client2.uid, - eventName, - pollingInterval, - strict, - fromBlock - ]); - return observe(observerId, { onLogs, onError }, (emit2) => { - let previousBlockNumber; - if (fromBlock !== void 0) - previousBlockNumber = fromBlock - 1n; - let filter2; - let initialized = false; - const unwatch = poll(async () => { - var _a2; - if (!initialized) { - try { - filter2 = await getAction$1(client2, createContractEventFilter, "createContractEventFilter")({ - abi: abi2, - address, - args, - eventName, - strict, - fromBlock - }); - } catch { + static async open(args) { + var _findNetworkConfig$ch, _findNetworkConfig, _settings$services$se, _settings$services, _networks$; + const { + referenceSigner, + threshold, + addSigners, + selectWallet, + onAccountAddress, + settings, + editConfigOnMigration, + onMigration, + orchestrator, + projectAccessKey: projectAccessKey2 + } = args; + const { + contexts, + networks: networks2, + tracker: tracker2, + services + } = _extends$4({}, SessionSettingsDefault, settings); + const referenceChainId = (_findNetworkConfig$ch = (_findNetworkConfig = findNetworkConfig(networks2, (_settings$services$se = settings == null || (_settings$services = settings.services) == null ? void 0 : _settings$services.sequenceApiChainId) != null ? _settings$services$se : ChainId.MAINNET)) == null ? void 0 : _findNetworkConfig.chainId) != null ? _findNetworkConfig$ch : (_networks$ = networks2[0]) == null ? void 0 : _networks$.chainId; + if (!referenceChainId) throw Error("No reference chain found"); + const foundWallets = await tracker2.walletsOfSigner({ + signer: referenceSigner + }); + const selectedWallet = await selectWallet(foundWallets.map((w2) => w2.wallet)); + let account2; + if (selectedWallet) { + onAccountAddress == null || onAccountAddress(selectedWallet); + account2 = new Account({ + address: selectedWallet, + tracker: tracker2, + networks: networks2, + contexts, + orchestrator, + projectAccessKey: projectAccessKey2 + }); + if (addSigners && addSigners.length > 0) { + let status = await account2.status(referenceChainId); + if (status.original.version !== status.version || account2.version !== status.version) { + const { + migratedAllChains: isFullyMigrated, + failedChains + } = await account2.isMigratedAllChains(); + if (failedChains.some((c2) => CRITICAL_CHAINS.includes(c2))) { + throw Error(`Failed to fetch account status on ${failedChains.join(", ")}`); } - initialized = true; - return; - } - try { - let logs; - if (filter2) { - logs = await getAction$1(client2, getFilterChanges, "getFilterChanges")({ filter: filter2 }); - } else { - const blockNumber = await getAction$1(client2, getBlockNumber, "getBlockNumber")({}); - if (previousBlockNumber && previousBlockNumber < blockNumber) { - logs = await getAction$1(client2, getContractEvents, "getContractEvents")({ - abi: abi2, - address, - args, - eventName, - fromBlock: previousBlockNumber + 1n, - toBlock: blockNumber, - strict - }); - } else { - logs = []; + if (!isFullyMigrated) { + if (onMigration && !await onMigration(account2)) { + throw Error("Migration cancelled, cannot open session"); } - previousBlockNumber = blockNumber; + const { + failedChains: _failedChains + } = await account2.signAllMigrations(editConfigOnMigration || ((c2) => c2)); + if (_failedChains.some((c2) => CRITICAL_CHAINS.includes(c2))) { + throw Error(`Failed to sign migrations on ${_failedChains.join(", ")}`); + } + if (index$3.isDedupedTracker(tracker2)) { + tracker2.invalidateCache(); + } + let isFullyMigrated2; + [isFullyMigrated2, status] = await Promise.all([account2.isMigratedAllChains().then((r2) => r2.migratedAllChains), account2.status(referenceChainId)]); + if (!isFullyMigrated2) throw Error("Failed to migrate account"); } - if (logs.length === 0) - return; - if (batch) - emit2.onLogs(logs); - else - for (const log of logs) - emit2.onLogs([log]); - } catch (err) { - if (filter2 && err instanceof InvalidInputRpcError) - initialized = false; - (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, err); } - }, { - emitOnBegin: true, - interval: pollingInterval + if (status.onChain.version !== status.version) { + await account2.doBootstrap(referenceChainId, void 0, status); + } + const prevConfig = status.config; + const nextConfig = account2.coders.config.editConfig(prevConfig, { + add: addSigners, + threshold + }); + if (account2.coders.config.imageHashOf(prevConfig) !== account2.coders.config.imageHashOf(nextConfig)) { + const newConfig = account2.coders.config.editConfig(nextConfig, { + checkpoint: account2.coders.config.checkpointOf(prevConfig) + 1n + }); + await account2.updateConfig(newConfig); + } + } + } else { + if (!addSigners || addSigners.length === 0) { + throw Error("Cannot create new account without signers"); + } + if (!threshold) { + throw Error("Cannot create new account without threshold"); + } + account2 = await Account.new({ + config: { + threshold, + checkpoint: 0, + signers: addSigners + }, + tracker: tracker2, + contexts, + orchestrator, + networks: networks2, + projectAccessKey: projectAccessKey2 }); - return async () => { - if (filter2) - await getAction$1(client2, uninstallFilter, "uninstallFilter")({ filter: filter2 }); - unwatch(); - }; - }); + onAccountAddress == null || onAccountAddress(account2.address); + await account2.publishWitness(); + const _foundWallets = await tracker2.walletsOfSigner({ + signer: referenceSigner, + noCache: true + }); + if (!_foundWallets.some((w2) => w2.wallet === account2.address)) { + throw Error("Account not found on tracker"); + } + } + let servicesObj; + if (services) { + servicesObj = new Services(account2, services); + servicesObj.auth(); + servicesObj.onAuth((result) => { + if (result.status === "fulfilled") { + account2.setJwt(result.value); + } + }); + } + return new Session(networks2, contexts, account2, servicesObj); + } + static async load(args) { + const { + dump, + settings, + editConfigOnMigration, + onMigration, + orchestrator + } = args; + const { + contexts, + networks: networks2, + tracker: tracker2, + services + } = _extends$4({}, SessionSettingsDefault, settings); + let account2; + if (isSessionDumpV1(dump)) { + var _dump$jwt$expiration, _dump$jwt, _dump$jwt2; + const oldAddress = dump.config.address || index$1$1.context.addressOf(contexts[1], v1.config.ConfigCoder.imageHashOf(_extends$4({}, dump.config, { + version: 1 + }))); + const jwtExpired = ((_dump$jwt$expiration = (_dump$jwt = dump.jwt) == null ? void 0 : _dump$jwt.expiration) != null ? _dump$jwt$expiration : 0) < Math.floor(Date.now() / 1e3); + account2 = new Account({ + address: oldAddress, + tracker: tracker2, + networks: networks2, + contexts, + orchestrator, + jwt: jwtExpired ? void 0 : (_dump$jwt2 = dump.jwt) == null ? void 0 : _dump$jwt2.token + }); + if (!await account2.isMigratedAllChains().then((r2) => r2.migratedAllChains)) { + if (onMigration && !await onMigration(account2)) { + throw Error("Migration cancelled, cannot open session"); + } + console.log("Migrating account..."); + await account2.signAllMigrations(editConfigOnMigration); + if (!await account2.isMigratedAllChains().then((r2) => r2.migratedAllChains)) throw Error("Failed to migrate account"); + } + } else if (isSessionDumpV2(dump)) { + var _dump$jwt$expiration2, _dump$jwt3, _dump$jwt4; + const jwtExpired = ((_dump$jwt$expiration2 = (_dump$jwt3 = dump.jwt) == null ? void 0 : _dump$jwt3.expiration) != null ? _dump$jwt$expiration2 : 0) < Math.floor(Date.now() / 1e3); + account2 = new Account({ + address: dump.address, + tracker: tracker2, + networks: networks2, + contexts, + orchestrator, + jwt: jwtExpired ? void 0 : (_dump$jwt4 = dump.jwt) == null ? void 0 : _dump$jwt4.token + }); + } else { + throw Error("Invalid dump format"); + } + let servicesObj; + if (services) { + var _dump$jwt$expiration3; + servicesObj = new Services(account2, services, dump.jwt && { + jwt: { + token: Promise.resolve(dump.jwt.token), + expiration: (_dump$jwt$expiration3 = dump.jwt.expiration) != null ? _dump$jwt$expiration3 : jwtDecodeClaims(dump.jwt.token).exp + }, + metadata: dump.metadata + }); + } + return new Session(networks2, contexts, account2, servicesObj); + } +} +const ValidateSequenceWalletProof = (readerFor, tracker2, context2) => { + return async (_provider6, chainId, proof) => { + const digest = proof.messageDigest(); + const isValid2 = await readerFor(chainId).isValidSignature(proof.address, digest, proof.signature); + return { + isValid: isValid2 + }; }; - const subscribeContractEvent = () => { - const strict = strict_ ?? false; - const observerId = stringify([ - "watchContractEvent", - address, - args, - batch, - client2.uid, - eventName, - pollingInterval, - strict - ]); - let active = true; - let unsubscribe = () => active = false; - return observe(observerId, { onLogs, onError }, (emit2) => { - (async () => { - try { - const transport = (() => { - if (client2.transport.type === "fallback") { - const transport2 = client2.transport.transports.find((transport3) => transport3.config.type === "webSocket"); - if (!transport2) - return client2.transport; - return transport2.value; - } - return client2.transport; - })(); - const topics = eventName ? encodeEventTopics({ - abi: abi2, - eventName, - args - }) : []; - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["logs", { address, topics }], - onData(data) { - var _a2; - if (!active) - return; - const log = data.result; - try { - const { eventName: eventName2, args: args2 } = decodeEventLog({ - abi: abi2, - data: log.data, - topics: log.topics, - strict: strict_ - }); - const formatted = formatLog(log, { - args: args2, - eventName: eventName2 - }); - emit2.onLogs([formatted]); - } catch (err) { - let eventName2; - let isUnnamed; - if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { - if (strict_) - return; - eventName2 = err.abiItem.name; - isUnnamed = (_a2 = err.abiItem.inputs) == null ? void 0 : _a2.some((x2) => !("name" in x2 && x2.name)); - } - const formatted = formatLog(log, { - args: isUnnamed ? [] : {}, - eventName: eventName2 - }); - emit2.onLogs([formatted]); - } - }, - onError(error) { - var _a2; - (_a2 = emit2.onError) == null ? void 0 : _a2.call(emit2, error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError == null ? void 0 : onError(err); +}; +const auth$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + AuthError, + CRITICAL_CHAINS, + ErrAccountIsRequired, + Session, + SessionSettingsDefault, + ValidateSequenceWalletProof, + isSessionDumpV1, + isSessionDumpV2, + signAuthorization +}, Symbol.toStringTag, { value: "Module" })); +function _extends$3() { + _extends$3 = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; } - })(); - return () => unsubscribe(); - }); + } + } + return target; }; - return enablePolling ? pollContractEvent() : subscribeContractEvent(); + return _extends$3.apply(this, arguments); } -async function writeContract$1(client2, parameters) { - const { abi: abi2, account: account_ = client2.account, address, args, dataSuffix, functionName, ...request } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/contract/writeContract" - }); - const account2 = parseAccount(account_); - const data = encodeFunctionData({ - abi: abi2, - args, - functionName - }); - try { - return await getAction$1(client2, sendTransaction$1, "sendTransaction")({ - data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, - to: address, - account: account2, - ...request - }); - } catch (error) { - throw getContractError(error, { - abi: abi2, - address, - args, - docsPath: "/docs/contract/writeContract", - functionName, - sender: account2.address - }); +class Guard { + constructor(hostname, fetch2) { + this.hostname = void 0; + this.fetch = void 0; + this.path = "/rpc/Guard/"; + this.ping = (headers, signal) => { + return this.fetch(this.url("Ping"), createHTTPRequest$2({}, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.version = (headers, signal) => { + return this.fetch(this.url("Version"), createHTTPRequest$2({}, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + version: _data6.version + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.runtimeStatus = (headers, signal) => { + return this.fetch(this.url("RuntimeStatus"), createHTTPRequest$2({}, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.getSignerConfig = (args, headers, signal) => { + return this.fetch(this.url("GetSignerConfig"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + signerConfig: _data6.signerConfig + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.sign = (args, headers, signal) => { + return this.fetch(this.url("Sign"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + sig: _data6.sig + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.signWith = (args, headers, signal) => { + return this.fetch(this.url("SignWith"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + sig: _data6.sig + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.patch = (args, headers, signal) => { + return this.fetch(this.url("Patch"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + txs: _data6.txs + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.authMethods = (args, headers, signal) => { + return this.fetch(this.url("AuthMethods"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + methods: _data6.methods, + active: _data6.active + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.setPIN = (args, headers, signal) => { + return this.fetch(this.url("SetPIN"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.resetPIN = (args, headers, signal) => { + return this.fetch(this.url("ResetPIN"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.createTOTP = (args, headers, signal) => { + return this.fetch(this.url("CreateTOTP"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + uri: _data6.uri + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.commitTOTP = (args, headers, signal) => { + return this.fetch(this.url("CommitTOTP"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + codes: _data6.codes + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.resetTOTP = (args, headers, signal) => { + return this.fetch(this.url("ResetTOTP"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.reset2FA = (args, headers, signal) => { + return this.fetch(this.url("Reset2FA"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return {}; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.recoveryCodes = (args, headers, signal) => { + return this.fetch(this.url("RecoveryCodes"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + codes: _data6.codes + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.resetRecoveryCodes = (args, headers, signal) => { + return this.fetch(this.url("ResetRecoveryCodes"), createHTTPRequest$2(args, headers, signal)).then((res) => { + return buildResponse$2(res).then((_data6) => { + return { + codes: _data6.codes + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$2.new({ + cause: `fetch(): ${error.message || ""}` + }); + }); + }; + this.hostname = hostname; + this.fetch = (input2, init2) => fetch2(input2, init2); + } + url(name2) { + return this.hostname + this.path + name2; } } -function getAction(client2, actionFn, name2) { - const action_implicit = client2[actionFn.name]; - if (typeof action_implicit === "function") - return action_implicit; - const action_explicit = client2[name2]; - if (typeof action_explicit === "function") - return action_explicit; - return (params) => actionFn(client2, params); -} -const version$3 = "2.13.5"; -const getVersion$1 = () => `@wagmi/core@${version$3}`; -var __classPrivateFieldGet = function(receiver, state, kind, f2) { - if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver); +const createHTTPRequest$2 = (body = {}, headers = {}, signal = null) => { + return { + method: "POST", + headers: _extends$3({}, headers, { + "Content-Type": "application/json" + }), + body: JSON.stringify(body || {}), + signal + }; }; -var _BaseError_instances, _BaseError_walk; -let BaseError$1 = class BaseError3 extends Error { - get docsBaseUrl() { - return "https://wagmi.sh/core"; +const buildResponse$2 = (res) => { + return res.text().then((text2) => { + let data; + try { + data = JSON.parse(text2); + } catch (error) { + let message = ""; + if (error instanceof Error) { + message = error.message; + } + throw WebrpcBadResponseError$2.new({ + status: res.status, + cause: `JSON.parse(): ${message}: response text: ${text2}` + }); + } + if (!res.ok) { + const code2 = typeof data.code === "number" ? data.code : 0; + throw (webrpcErrorByCode$2[code2] || WebrpcError$2).new(data); + } + return data; + }); +}; +let WebrpcError$2 = class WebrpcError6 extends Error { + constructor(name2, code2, message, status, cause) { + super(message); + this.name = void 0; + this.code = void 0; + this.message = void 0; + this.status = void 0; + this.cause = void 0; + this.msg = void 0; + this.name = name2 || "WebrpcError"; + this.code = typeof code2 === "number" ? code2 : 0; + this.message = message || `endpoint error ${this.code}`; + this.msg = this.message; + this.status = typeof status === "number" ? status : 0; + this.cause = cause; + Object.setPrototypeOf(this, WebrpcError6.prototype); } - get version() { - return getVersion$1(); + static new(payload) { + return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); } - constructor(shortMessage, options = {}) { - var _a2; - super(); - _BaseError_instances.add(this); - Object.defineProperty(this, "details", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "docsPath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "metaMessages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "shortMessage", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "WagmiCoreError" - }); - const details = options.cause instanceof BaseError3 ? options.cause.details : ((_a2 = options.cause) == null ? void 0 : _a2.message) ? options.cause.message : options.details; - const docsPath2 = options.cause instanceof BaseError3 ? options.cause.docsPath || options.docsPath : options.docsPath; - this.message = [ - shortMessage || "An error occurred.", - "", - ...options.metaMessages ? [...options.metaMessages, ""] : [], - ...docsPath2 ? [ - `Docs: ${this.docsBaseUrl}${docsPath2}.html${options.docsSlug ? `#${options.docsSlug}` : ""}` - ] : [], - ...details ? [`Details: ${details}`] : [], - `Version: ${this.version}` - ].join("\n"); - if (options.cause) - this.cause = options.cause; - this.details = details; - this.docsPath = docsPath2; - this.metaMessages = options.metaMessages; - this.shortMessage = shortMessage; +}; +let WebrpcEndpointError$2 = class WebrpcEndpointError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcEndpointError6.prototype); } - walk(fn) { - return __classPrivateFieldGet(this, _BaseError_instances, "m", _BaseError_walk).call(this, this, fn); +}; +let WebrpcRequestFailedError$2 = class WebrpcRequestFailedError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcRequestFailedError6.prototype); } }; -_BaseError_instances = /* @__PURE__ */ new WeakSet(), _BaseError_walk = function _BaseError_walk2(err, fn) { - if (fn == null ? void 0 : fn(err)) - return err; - if (err.cause) - return __classPrivateFieldGet(this, _BaseError_instances, "m", _BaseError_walk2).call(this, err.cause, fn); - return err; +let WebrpcBadRouteError$2 = class WebrpcBadRouteError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRouteError6.prototype); + } }; -class ChainNotConfiguredError extends BaseError$1 { - constructor() { - super("Chain not configured."); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "ChainNotConfiguredError" - }); +let WebrpcBadMethodError$2 = class WebrpcBadMethodError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadMethodError6.prototype); } -} -class ConnectorAlreadyConnectedError extends BaseError$1 { - constructor() { - super("Connector already connected."); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "ConnectorAlreadyConnectedError" - }); +}; +let WebrpcBadRequestError$2 = class WebrpcBadRequestError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadRequestError6.prototype); } -} -class ConnectorNotConnectedError extends BaseError$1 { - constructor() { - super("Connector not connected."); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "ConnectorNotConnectedError" - }); +}; +let WebrpcBadResponseError$2 = class WebrpcBadResponseError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcBadResponseError6.prototype); } -} -class ConnectorAccountNotFoundError extends BaseError$1 { - constructor({ address, connector }) { - super(`Account "${address}" not found for connector "${connector.name}".`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "ConnectorAccountNotFoundError" - }); +}; +let WebrpcServerPanicError$2 = class WebrpcServerPanicError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcServerPanicError6.prototype); + } +}; +let WebrpcInternalErrorError$2 = class WebrpcInternalErrorError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcInternalErrorError6.prototype); + } +}; +let WebrpcClientDisconnectedError$2 = class WebrpcClientDisconnectedError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcClientDisconnectedError6.prototype); + } +}; +let WebrpcStreamLostError$2 = class WebrpcStreamLostError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamLostError6.prototype); + } +}; +let WebrpcStreamFinishedError$2 = class WebrpcStreamFinishedError6 extends WebrpcError$2 { + constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, WebrpcStreamFinishedError6.prototype); + } +}; +let UnauthorizedError$2 = class UnauthorizedError5 extends WebrpcError$2 { + constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, UnauthorizedError5.prototype); + } +}; +let SessionExpiredError$1 = class SessionExpiredError4 extends WebrpcError$2 { + constructor(name2 = "SessionExpired", code2 = 1002, message = "Session expired", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, SessionExpiredError4.prototype); + } +}; +class AbortedError4 extends WebrpcError$2 { + constructor(name2 = "Aborted", code2 = 1005, message = "Request aborted", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, AbortedError4.prototype); } } -class ConnectorChainMismatchError extends BaseError$1 { - constructor({ connectionChainId, connectorChainId }) { - super(`The current chain of the connector (id: ${connectorChainId}) does not match the connection's chain (id: ${connectionChainId}).`, { - metaMessages: [ - `Current Chain ID: ${connectorChainId}`, - `Expected Chain ID: ${connectionChainId}` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "ConnectorChainMismatchError" - }); +class InvalidArgumentError6 extends WebrpcError$2 { + constructor(name2 = "InvalidArgument", code2 = 2001, message = "Invalid argument", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, InvalidArgumentError6.prototype); } } -class ConnectorUnavailableReconnectingError extends BaseError$1 { - constructor({ connector }) { - super(`Connector "${connector.name}" unavailable while reconnecting.`, { - details: [ - "During the reconnection step, the only connector methods guaranteed to be available are: `id`, `name`, `type`, `uuid`.", - "All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored.", - "This error commonly occurs for connectors that asynchronously inject after reconnection has already started." - ].join(" ") - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "ConnectorUnavailableReconnectingError" - }); +class UnavailableError4 extends WebrpcError$2 { + constructor(name2 = "Unavailable", code2 = 2002, message = "Unavailable resource", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, UnavailableError4.prototype); } } -async function connect(config2, parameters) { - var _a2; - let connector; - if (typeof parameters.connector === "function") { - connector = config2._internal.connectors.setup(parameters.connector); - } else - connector = parameters.connector; - if (connector.uid === config2.state.current) - throw new ConnectorAlreadyConnectedError(); - try { - config2.setState((x2) => ({ ...x2, status: "connecting" })); - connector.emitter.emit("message", { type: "connecting" }); - const data = await connector.connect({ chainId: parameters.chainId }); - const accounts = data.accounts; - connector.emitter.off("connect", config2._internal.events.connect); - connector.emitter.on("change", config2._internal.events.change); - connector.emitter.on("disconnect", config2._internal.events.disconnect); - await ((_a2 = config2.storage) == null ? void 0 : _a2.setItem("recentConnectorId", connector.id)); - config2.setState((x2) => ({ - ...x2, - connections: new Map(x2.connections).set(connector.uid, { - accounts, - chainId: data.chainId, - connector - }), - current: connector.uid, - status: "connected" - })); - return { accounts, chainId: data.chainId }; - } catch (error) { - config2.setState((x2) => ({ - ...x2, - // Keep existing connector connected in case of error - status: x2.current ? "connected" : "disconnected" - })); - throw error; +let QueryFailedError$1 = class QueryFailedError5 extends WebrpcError$2 { + constructor(name2 = "QueryFailed", code2 = 2003, message = "Query failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, QueryFailedError5.prototype); + } +}; +class ValidationFailedError2 extends WebrpcError$2 { + constructor(name2 = "ValidationFailed", code2 = 2004, message = "Validation Failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, ValidationFailedError2.prototype); } } -const size$4 = 256; -let index$2 = size$4; -let buffer$1; -function uid$1(length = 11) { - if (!buffer$1 || index$2 + length > size$4 * 2) { - buffer$1 = ""; - index$2 = 0; - for (let i = 0; i < size$4; i++) { - buffer$1 += (256 + Math.random() * 256 | 0).toString(16).substring(1); +let NotFoundError$1 = class NotFoundError6 extends WebrpcError$2 { + constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, NotFoundError6.prototype); + } +}; +const webrpcErrorByCode$2 = { + [0]: WebrpcEndpointError$2, + [-1]: WebrpcRequestFailedError$2, + [-2]: WebrpcBadRouteError$2, + [-3]: WebrpcBadMethodError$2, + [-4]: WebrpcBadRequestError$2, + [-5]: WebrpcBadResponseError$2, + [-6]: WebrpcServerPanicError$2, + [-7]: WebrpcInternalErrorError$2, + [-8]: WebrpcClientDisconnectedError$2, + [-9]: WebrpcStreamLostError$2, + [-10]: WebrpcStreamFinishedError$2, + [1e3]: UnauthorizedError$2, + [1002]: SessionExpiredError$1, + [1005]: AbortedError4, + [2001]: InvalidArgumentError6, + [2002]: UnavailableError4, + [2003]: QueryFailedError$1, + [2004]: ValidationFailedError2, + [3e3]: NotFoundError$1 +}; +const fetch$2 = globalThis.fetch; +class GuardSigner { + constructor(address, url, appendSuffix = false) { + this.address = address; + this.url = url; + this.appendSuffix = appendSuffix; + this.guard = void 0; + this.guard = new Guard(url, fetch$2); + } + async getAddress() { + return this.address; + } + async buildDeployTransaction(_metadata) { + return void 0; + } + async predecorateSignedTransactions(_metadata) { + return []; + } + async decorateTransactions(bundle, _metadata) { + return bundle; + } + async sign(message, metadata2) { + var _metadata$parts; + if (!index$1$1.isWalletSignRequestMetadata(metadata2)) { + throw new Error("expected sequence signature request metadata"); } + const guardTotpCode = metadata2.guardTotpCode; + const coder = index$6.genericCoderFor(metadata2.config.version); + const { + encoded + } = coder.signature.encodeSigners(metadata2.config, (_metadata$parts = metadata2.parts) != null ? _metadata$parts : /* @__PURE__ */ new Map(), [], metadata2.chainId); + return (await this.guard.signWith({ + signer: this.address, + request: { + msg: hexlify(message), + auxData: this.packMsgAndSig(metadata2.address, metadata2.digest, encoded, metadata2.chainId), + chainId: Number(metadata2.chainId) + }, + token: guardTotpCode ? { + id: AuthMethod.TOTP, + token: guardTotpCode + } : void 0 + })).sig; } - return buffer$1.substring(index$2, index$2++ + length); -} -function createClient(parameters) { - const { batch, cacheTime = parameters.pollingInterval ?? 4e3, ccipRead, key = "base", name: name2 = "Base Client", pollingInterval = 4e3, type = "base" } = parameters; - const chain = parameters.chain; - const account2 = parameters.account ? parseAccount(parameters.account) : void 0; - const { config: config2, request, value } = parameters.transport({ - chain, - pollingInterval - }); - const transport = { ...config2, ...value }; - const client2 = { - account: account2, - batch, - cacheTime, - ccipRead, - chain, - key, - name: name2, - pollingInterval, - request, - transport, - type, - uid: uid$1() - }; - function extend(base) { - return (extendFn) => { - const extended = extendFn(base); - for (const key2 in client2) - delete extended[key2]; - const combined = { ...base, ...extended }; - return Object.assign(combined, { extend: extend(combined) }); - }; + notifyStatusChange(_id, _status, _metadata) { + } + async getAuthMethods(proof) { + let response; + if ("jwt" in proof) { + response = await this.guard.authMethods({}, { + Authorization: `BEARER ${proof.jwt}` + }); + } else { + const signedProof = await signOwnershipProof(proof); + response = await this.guard.authMethods({ + proof: { + wallet: signedProof.walletAddress, + timestamp: signedProof.timestamp.getTime(), + signer: signedProof.signerAddress, + signature: signedProof.signature + } + }); + } + return _extends$3({}, response, { + methods: response.methods.map(parseAuthMethod) + }); + } + async setPin(pin, proof) { + const signedProof = await signAuthUpdateProof(proof); + if (pin === void 0) { + await this.guard.resetPIN({ + timestamp: signedProof.timestamp.getTime(), + signature: signedProof.signature + }, { + Authorization: `BEARER ${proof.jwt}` + }); + } else { + await this.guard.setPIN({ + pin, + timestamp: signedProof.timestamp.getTime(), + signature: signedProof.signature + }, { + Authorization: `BEARER ${proof.jwt}` + }); + } + } + resetPin(proof) { + return this.setPin(void 0, proof); + } + async createTotp(proof) { + const signedProof = await signAuthUpdateProof(proof); + const { + uri + } = await this.guard.createTOTP({ + timestamp: signedProof.timestamp.getTime(), + signature: signedProof.signature + }, { + Authorization: `BEARER ${proof.jwt}` + }); + return new URL(uri); + } + async commitTotp(token, jwt) { + const { + codes + } = await this.guard.commitTOTP({ + token + }, { + Authorization: `BEARER ${jwt}` + }); + return codes; } - return Object.assign(client2, { extend: extend(client2) }); -} -function createTransport({ key, name: name2, request, retryCount = 3, retryDelay = 150, timeout, type }, value) { - const uid2 = uid$1(); - return { - config: { - key, - name: name2, - request, - retryCount, - retryDelay, - timeout, - type - }, - request: buildRequest(request, { retryCount, retryDelay, uid: uid2 }), - value - }; -} -function custom(provider2, config2 = {}) { - const { key = "custom", name: name2 = "Custom Provider", retryDelay } = config2; - return ({ retryCount: defaultRetryCount }) => createTransport({ - key, - name: name2, - request: provider2.request.bind(provider2), - retryCount: config2.retryCount ?? defaultRetryCount, - retryDelay, - type: "custom" - }); -} -class UrlRequiredError extends BaseError$3 { - constructor() { - super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", { - docsPath: "/docs/clients/intro", - name: "UrlRequiredError" + async resetTotp(proof) { + const signedProof = await signAuthUpdateProof(proof); + await this.guard.resetTOTP({ + timestamp: signedProof.timestamp.getTime(), + signature: signedProof.signature + }, { + Authorization: `BEARER ${proof.jwt}` }); } -} -function http(url, config2 = {}) { - const { batch, fetchOptions, key = "http", name: name2 = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay } = config2; - return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => { - const { batchSize = 1e3, wait: wait2 = 0 } = typeof batch === "object" ? batch : {}; - const retryCount = config2.retryCount ?? retryCount_; - const timeout = timeout_ ?? config2.timeout ?? 1e4; - const url_ = chain == null ? void 0 : chain.rpcUrls.default.http[0]; - if (!url_) - throw new UrlRequiredError(); - const rpcClient = getHttpRpcClient(url_, { - fetchOptions, - onRequest: onFetchRequest, - onResponse: onFetchResponse, - timeout + async reset2fa(recoveryCode, proof) { + if ("jwt" in proof) { + await this.guard.reset2FA({ + code: recoveryCode + }, { + Authorization: `BEARER ${proof.jwt}` + }); + } else { + const signedProof = await signOwnershipProof(proof); + await this.guard.reset2FA({ + code: recoveryCode, + proof: { + wallet: signedProof.walletAddress, + timestamp: signedProof.timestamp.getTime(), + signer: signedProof.signerAddress, + signature: signedProof.signature + } + }); + } + } + async getRecoveryCodes(proof) { + const signedProof = await signAuthUpdateProof(proof); + const { + codes + } = await this.guard.recoveryCodes({ + timestamp: signedProof.timestamp.getTime(), + signature: signedProof.signature + }, { + Authorization: `BEARER ${proof.jwt}` }); - return createTransport({ - key, - name: name2, - async request({ method, params }) { - const body = { method, params }; - const { schedule } = createBatchScheduler({ - id: url_, - wait: wait2, - shouldSplitBatch(requests) { - return requests.length > batchSize; - }, - fn: (body2) => rpcClient.request({ - body: body2 - }), - sort: (a2, b2) => a2.id - b2.id - }); - const fn = async (body2) => batch ? schedule(body2) : [ - await rpcClient.request({ - body: body2 - }) - ]; - const [{ error, result }] = await fn(body); - if (error) - throw new RpcRequestError({ - body, - error, - url: url_ - }); - return result; - }, - retryCount, - retryDelay, - timeout, - type: "http" + return codes; + } + async resetRecoveryCodes(proof) { + const signedProof = await signAuthUpdateProof(proof); + const { + codes + } = await this.guard.resetRecoveryCodes({ + timestamp: signedProof.timestamp.getTime(), + signature: signedProof.signature }, { - fetchOptions, - url: url_ + Authorization: `BEARER ${proof.jwt}` }); - }; + return codes; + } + packMsgAndSig(address, msg, sig, chainId) { + return AbiCoder.defaultAbiCoder().encode(["address", "uint256", "bytes", "bytes"], [address, chainId, msg, sig]); + } + suffix() { + return new Uint8Array(this.appendSuffix ? [3] : []); + } } -function parseSiweMessage(message) { - var _a2, _b2, _c2; - const { scheme, statement, ...prefix } = ((_a2 = message.match(prefixRegex)) == null ? void 0 : _a2.groups) ?? {}; - const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = ((_b2 = message.match(suffixRegex)) == null ? void 0 : _b2.groups) ?? {}; - const resources = (_c2 = message.split("Resources:")[1]) == null ? void 0 : _c2.split("\n- ").slice(1); - return { - ...prefix, - ...suffix, - ...chainId ? { chainId: Number(chainId) } : {}, - ...expirationTime ? { expirationTime: new Date(expirationTime) } : {}, - ...issuedAt ? { issuedAt: new Date(issuedAt) } : {}, - ...notBefore ? { notBefore: new Date(notBefore) } : {}, - ...requestId ? { requestId } : {}, - ...resources ? { resources } : {}, - ...scheme ? { scheme } : {}, - ...statement ? { statement } : {} - }; +let AuthMethod = /* @__PURE__ */ function(AuthMethod2) { + AuthMethod2["PIN"] = "PIN"; + AuthMethod2["TOTP"] = "TOTP"; + return AuthMethod2; +}({}); +function parseAuthMethod(method) { + switch (method) { + case AuthMethod.PIN: + case AuthMethod.TOTP: + return method; + default: + throw new Error(`unknown auth method '${method}'`); + } } -const prefixRegex = /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/; -const suffixRegex = /(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/; -function validateSiweMessage(parameters) { - const { address, domain: domain2, message, nonce, scheme, time: time2 = /* @__PURE__ */ new Date() } = parameters; - if (domain2 && message.domain !== domain2) - return false; - if (nonce && message.nonce !== nonce) - return false; - if (scheme && message.scheme !== scheme) - return false; - if (message.expirationTime && time2 >= message.expirationTime) - return false; - if (message.notBefore && time2 < message.notBefore) - return false; - try { - if (!message.address) - return false; - if (address && !isAddressEqual(message.address, address)) - return false; - } catch { - return false; +function isSignedOwnershipProof(proof) { + return "signerAddress" in proof && typeof proof.signerAddress === "string"; +} +async function signOwnershipProof(proof) { + if (isSignedOwnershipProof(proof)) { + return proof; + } else { + const signer2 = index$4.isSapientSigner(proof.signer) ? proof.signer : new index$4.SignerWrapper(proof.signer); + const signerAddress = await signer2.getAddress(); + const timestamp = /* @__PURE__ */ new Date(); + const typedData = getOwnershipProofTypedData(proof.walletAddress, timestamp); + const digest = encodeTypedDataDigest(typedData); + return { + walletAddress: proof.walletAddress, + timestamp, + signerAddress, + signature: hexlify(await signer2.sign(digest, {})) + }; } - return true; } -async function verifySiweMessage(client2, parameters) { - const { address, domain: domain2, message, nonce, scheme, signature: signature2, time: time2 = /* @__PURE__ */ new Date(), ...callRequest } = parameters; - const parsed = parseSiweMessage(message); - if (!parsed.address) - return false; - const isValid2 = validateSiweMessage({ - address, - domain: domain2, - message: parsed, - nonce, - scheme, - time: time2 - }); - if (!isValid2) - return false; - const hash2 = hashMessage(message); - return verifyHash(client2, { - address: parsed.address, - hash: hash2, - signature: signature2, - ...callRequest - }); +async function signAuthUpdateProof(proof) { + if ("wallet" in proof) { + var _typedData$domain$cha; + const timestamp = /* @__PURE__ */ new Date(); + const typedData = getAuthUpdateProofTypedData(timestamp); + const signature2 = await proof.wallet.signTypedData(typedData.domain, typedData.types, typedData.message, (_typedData$domain$cha = typedData.domain.chainId) != null ? _typedData$domain$cha : 1, "eip6492"); + return { + jwt: proof.jwt, + timestamp, + signature: signature2 + }; + } else { + return proof; + } } -function publicActions(client2) { +function getOwnershipProofTypedData(wallet, timestamp) { return { - call: (args) => call(client2, args), - createBlockFilter: () => createBlockFilter(client2), - createContractEventFilter: (args) => createContractEventFilter(client2, args), - createEventFilter: (args) => createEventFilter(client2, args), - createPendingTransactionFilter: () => createPendingTransactionFilter(client2), - estimateContractGas: (args) => estimateContractGas(client2, args), - estimateGas: (args) => estimateGas(client2, args), - getBalance: (args) => getBalance(client2, args), - getBlobBaseFee: () => getBlobBaseFee(client2), - getBlock: (args) => getBlock(client2, args), - getBlockNumber: (args) => getBlockNumber(client2, args), - getBlockTransactionCount: (args) => getBlockTransactionCount(client2, args), - getBytecode: (args) => getCode(client2, args), - getChainId: () => getChainId$1(client2), - getCode: (args) => getCode(client2, args), - getContractEvents: (args) => getContractEvents(client2, args), - getEip712Domain: (args) => getEip712Domain(client2, args), - getEnsAddress: (args) => getEnsAddress(client2, args), - getEnsAvatar: (args) => getEnsAvatar(client2, args), - getEnsName: (args) => getEnsName(client2, args), - getEnsResolver: (args) => getEnsResolver(client2, args), - getEnsText: (args) => getEnsText(client2, args), - getFeeHistory: (args) => getFeeHistory(client2, args), - estimateFeesPerGas: (args) => estimateFeesPerGas(client2, args), - getFilterChanges: (args) => getFilterChanges(client2, args), - getFilterLogs: (args) => getFilterLogs(client2, args), - getGasPrice: () => getGasPrice(client2), - getLogs: (args) => getLogs(client2, args), - getProof: (args) => getProof(client2, args), - estimateMaxPriorityFeePerGas: (args) => estimateMaxPriorityFeePerGas(client2, args), - getStorageAt: (args) => getStorageAt(client2, args), - getTransaction: (args) => getTransaction(client2, args), - getTransactionConfirmations: (args) => getTransactionConfirmations(client2, args), - getTransactionCount: (args) => getTransactionCount(client2, args), - getTransactionReceipt: (args) => getTransactionReceipt$1(client2, args), - multicall: (args) => multicall(client2, args), - prepareTransactionRequest: (args) => prepareTransactionRequest(client2, args), - readContract: (args) => readContract$1(client2, args), - sendRawTransaction: (args) => sendRawTransaction(client2, args), - simulateContract: (args) => simulateContract$1(client2, args), - verifyMessage: (args) => verifyMessage(client2, args), - verifySiweMessage: (args) => verifySiweMessage(client2, args), - verifyTypedData: (args) => verifyTypedData(client2, args), - uninstallFilter: (args) => uninstallFilter(client2, args), - waitForTransactionReceipt: (args) => waitForTransactionReceipt(client2, args), - watchBlocks: (args) => watchBlocks(client2, args), - watchBlockNumber: (args) => watchBlockNumber(client2, args), - watchContractEvent: (args) => watchContractEvent(client2, args), - watchEvent: (args) => watchEvent(client2, args), - watchPendingTransactions: (args) => watchPendingTransactions(client2, args) + domain, + types: { + AuthMethods: [{ + name: "wallet", + type: "address" + }, { + name: "timestamp", + type: "string" + }] + }, + message: { + wallet: getAddress(wallet), + timestamp: toUTCString(timestamp) + } }; } -function walletActions(client2) { +function getAuthUpdateProofTypedData(timestamp) { return { - addChain: (args) => addChain(client2, args), - deployContract: (args) => deployContract(client2, args), - getAddresses: () => getAddresses(client2), - getChainId: () => getChainId$1(client2), - getPermissions: () => getPermissions(client2), - prepareTransactionRequest: (args) => prepareTransactionRequest(client2, args), - requestAddresses: () => requestAddresses(client2), - requestPermissions: (args) => requestPermissions(client2, args), - sendRawTransaction: (args) => sendRawTransaction(client2, args), - sendTransaction: (args) => sendTransaction$1(client2, args), - signMessage: (args) => signMessage$1(client2, args), - signTransaction: (args) => signTransaction(client2, args), - signTypedData: (args) => signTypedData(client2, args), - switchChain: (args) => switchChain$1(client2, args), - watchAsset: (args) => watchAsset(client2, args), - writeContract: (args) => writeContract$1(client2, args) + domain, + types: { + AuthUpdate: [{ + name: "timestamp", + type: "string" + }] + }, + message: { + timestamp: toUTCString(timestamp) + } }; } -const zeroAddress = "0x0000000000000000000000000000000000000000"; -async function getConnectorClient(config2, parameters = {}) { - let connection; - if (parameters.connector) { - const { connector: connector2 } = parameters; - if (config2.state.status === "reconnecting" && !connector2.getAccounts && !connector2.getChainId) - throw new ConnectorUnavailableReconnectingError({ connector: connector2 }); - const [accounts, chainId2] = await Promise.all([ - connector2.getAccounts(), - connector2.getChainId() - ]); - connection = { - accounts, - chainId: chainId2, - connector: connector2 +const domain = { + name: "Sequence Guard", + version: "1", + chainId: 1 +}; +function toUTCString(date) { + return date.toUTCString().replace("GMT", "UTC"); +} +const guard$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + AuthMethod, + Guard, + GuardSigner, + getAuthUpdateProofTypedData, + getOwnershipProofTypedData, + isSignedOwnershipProof, + signOwnershipProof +}, Symbol.toStringTag, { value: "Module" })); +var eventemitter2 = { exports: {} }; +(function(module2, exports) { + !function(undefined$1) { + var hasOwnProperty = Object.hasOwnProperty; + var isArray2 = Array.isArray ? Array.isArray : function _isArray(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; }; - } else - connection = config2.state.connections.get(config2.state.current); - if (!connection) - throw new ConnectorNotConnectedError(); - const chainId = parameters.chainId ?? connection.chainId; - const connectorChainId = await connection.connector.getChainId(); - if (connectorChainId !== connection.chainId) - throw new ConnectorChainMismatchError({ - connectionChainId: connection.chainId, - connectorChainId - }); - const connector = connection.connector; - if (connector.getClient) - return connector.getClient({ chainId }); - const account2 = parseAccount(parameters.account ?? connection.accounts[0]); - account2.address = getAddress(account2.address); - if (parameters.account && !connection.accounts.some((x2) => x2.toLowerCase() === account2.address.toLowerCase())) - throw new ConnectorAccountNotFoundError({ - address: account2.address, - connector + var defaultMaxListeners = 10; + var nextTickSupported = typeof process$1 == "object" && typeof process$1.nextTick == "function"; + var symbolsSupported = typeof Symbol === "function"; + var reflectSupported = typeof Reflect === "object"; + var setImmediateSupported = typeof setImmediate === "function"; + var _setImmediate = setImmediateSupported ? setImmediate : setTimeout; + var ownKeys2 = symbolsSupported ? reflectSupported && typeof Reflect.ownKeys === "function" ? Reflect.ownKeys : function(obj) { + var arr = Object.getOwnPropertyNames(obj); + arr.push.apply(arr, Object.getOwnPropertySymbols(obj)); + return arr; + } : Object.keys; + function init2() { + this._events = {}; + if (this._conf) { + configure.call(this, this._conf); + } + } + function configure(conf) { + if (conf) { + this._conf = conf; + conf.delimiter && (this.delimiter = conf.delimiter); + if (conf.maxListeners !== undefined$1) { + this._maxListeners = conf.maxListeners; + } + conf.wildcard && (this.wildcard = conf.wildcard); + conf.newListener && (this._newListener = conf.newListener); + conf.removeListener && (this._removeListener = conf.removeListener); + conf.verboseMemoryLeak && (this.verboseMemoryLeak = conf.verboseMemoryLeak); + conf.ignoreErrors && (this.ignoreErrors = conf.ignoreErrors); + if (this.wildcard) { + this.listenerTree = {}; + } + } + } + function logPossibleMemoryLeak(count2, eventName) { + var errorMsg = "(node) warning: possible EventEmitter memory leak detected. " + count2 + " listeners added. Use emitter.setMaxListeners() to increase limit."; + if (this.verboseMemoryLeak) { + errorMsg += " Event name: " + eventName + "."; + } + if (typeof process$1 !== "undefined" && process$1.emitWarning) { + var e2 = new Error(errorMsg); + e2.name = "MaxListenersExceededWarning"; + e2.emitter = this; + e2.count = count2; + process$1.emitWarning(e2); + } else { + console.error(errorMsg); + if (console.trace) { + console.trace(); + } + } + } + var toArray = function(a2, b2, c2) { + var n2 = arguments.length; + switch (n2) { + case 0: + return []; + case 1: + return [a2]; + case 2: + return [a2, b2]; + case 3: + return [a2, b2, c2]; + default: + var arr = new Array(n2); + while (n2--) { + arr[n2] = arguments[n2]; + } + return arr; + } + }; + function toObject2(keys, values) { + var obj = {}; + var key; + var len = keys.length; + var valuesCount = 0; + for (var i = 0; i < len; i++) { + key = keys[i]; + obj[key] = i < valuesCount ? values[i] : undefined$1; + } + return obj; + } + function TargetObserver(emitter, target, options) { + this._emitter = emitter; + this._target = target; + this._listeners = {}; + this._listenersCount = 0; + var on, off; + if (options.on || options.off) { + on = options.on; + off = options.off; + } + if (target.addEventListener) { + on = target.addEventListener; + off = target.removeEventListener; + } else if (target.addListener) { + on = target.addListener; + off = target.removeListener; + } else if (target.on) { + on = target.on; + off = target.off; + } + if (!on && !off) { + throw Error("target does not implement any known event API"); + } + if (typeof on !== "function") { + throw TypeError("on method must be a function"); + } + if (typeof off !== "function") { + throw TypeError("off method must be a function"); + } + this._on = on; + this._off = off; + var _observers2 = emitter._observers; + if (_observers2) { + _observers2.push(this); + } else { + emitter._observers = [this]; + } + } + Object.assign(TargetObserver.prototype, { + subscribe: function(event, localEvent, reducer) { + var observer = this; + var target = this._target; + var emitter = this._emitter; + var listeners = this._listeners; + var handler = function() { + var args = toArray.apply(null, arguments); + var eventObj = { + data: args, + name: localEvent, + original: event + }; + if (reducer) { + var result = reducer.call(target, eventObj); + if (result !== false) { + emitter.emit.apply(emitter, [eventObj.name].concat(args)); + } + return; + } + emitter.emit.apply(emitter, [localEvent].concat(args)); + }; + if (listeners[event]) { + throw Error("Event '" + event + "' is already listening"); + } + this._listenersCount++; + if (emitter._newListener && emitter._removeListener && !observer._onNewListener) { + this._onNewListener = function(_event2) { + if (_event2 === localEvent && listeners[event] === null) { + listeners[event] = handler; + observer._on.call(target, event, handler); + } + }; + emitter.on("newListener", this._onNewListener); + this._onRemoveListener = function(_event2) { + if (_event2 === localEvent && !emitter.hasListeners(_event2) && listeners[event]) { + listeners[event] = null; + observer._off.call(target, event, handler); + } + }; + listeners[event] = null; + emitter.on("removeListener", this._onRemoveListener); + } else { + listeners[event] = handler; + observer._on.call(target, event, handler); + } + }, + unsubscribe: function(event) { + var observer = this; + var listeners = this._listeners; + var emitter = this._emitter; + var handler; + var events; + var off = this._off; + var target = this._target; + var i; + if (event && typeof event !== "string") { + throw TypeError("event must be a string"); + } + function clearRefs() { + if (observer._onNewListener) { + emitter.off("newListener", observer._onNewListener); + emitter.off("removeListener", observer._onRemoveListener); + observer._onNewListener = null; + observer._onRemoveListener = null; + } + var index2 = findTargetIndex.call(emitter, observer); + emitter._observers.splice(index2, 1); + } + if (event) { + handler = listeners[event]; + if (!handler) return; + off.call(target, event, handler); + delete listeners[event]; + if (!--this._listenersCount) { + clearRefs(); + } + } else { + events = ownKeys2(listeners); + i = events.length; + while (i-- > 0) { + event = events[i]; + off.call(target, event, listeners[event]); + } + this._listeners = {}; + this._listenersCount = 0; + clearRefs(); + } + } }); - const chain = config2.chains.find((chain2) => chain2.id === chainId); - const provider2 = await connection.connector.getProvider({ chainId }); - return createClient({ - account: account2, - chain, - name: "Connector Client", - transport: (opts) => custom(provider2)({ ...opts, retryCount: 0 }) - }); -} -async function disconnect(config2, parameters = {}) { - var _a2, _b2; - let connector; - if (parameters.connector) - connector = parameters.connector; - else { - const { connections: connections2, current } = config2.state; - const connection = connections2.get(current); - connector = connection == null ? void 0 : connection.connector; - } - const connections = config2.state.connections; - if (connector) { - await connector.disconnect(); - connector.emitter.off("change", config2._internal.events.change); - connector.emitter.off("disconnect", config2._internal.events.disconnect); - connector.emitter.on("connect", config2._internal.events.connect); - connections.delete(connector.uid); - } - config2.setState((x2) => { - if (connections.size === 0) - return { - ...x2, - connections: /* @__PURE__ */ new Map(), - current: null, - status: "disconnected" - }; - const nextConnection = connections.values().next().value; - return { - ...x2, - connections: new Map(connections), - current: nextConnection.connector.uid - }; - }); - { - const current = config2.state.current; - if (!current) - return; - const connector2 = (_a2 = config2.state.connections.get(current)) == null ? void 0 : _a2.connector; - if (!connector2) - return; - await ((_b2 = config2.storage) == null ? void 0 : _b2.setItem("recentConnectorId", connector2.id)); - } -} -function getAccount(config2) { - const uid2 = config2.state.current; - const connection = config2.state.connections.get(uid2); - const addresses = connection == null ? void 0 : connection.accounts; - const address = addresses == null ? void 0 : addresses[0]; - const chain = config2.chains.find((chain2) => chain2.id === (connection == null ? void 0 : connection.chainId)); - const status = config2.state.status; - switch (status) { - case "connected": - return { - address, - addresses, - chain, - chainId: connection == null ? void 0 : connection.chainId, - connector: connection == null ? void 0 : connection.connector, - isConnected: true, - isConnecting: false, - isDisconnected: false, - isReconnecting: false, - status - }; - case "reconnecting": - return { - address, - addresses, - chain, - chainId: connection == null ? void 0 : connection.chainId, - connector: connection == null ? void 0 : connection.connector, - isConnected: !!address, - isConnecting: false, - isDisconnected: false, - isReconnecting: true, - status - }; - case "connecting": - return { - address, - addresses, - chain, - chainId: connection == null ? void 0 : connection.chainId, - connector: connection == null ? void 0 : connection.connector, - isConnected: false, - isConnecting: true, - isDisconnected: false, - isReconnecting: false, - status - }; - case "disconnected": - return { - address: void 0, - addresses: void 0, - chain: void 0, - chainId: void 0, - connector: void 0, - isConnected: false, - isConnecting: false, - isDisconnected: true, - isReconnecting: false, - status + function resolveOptions(options, schema, reducers, allowUnknown) { + var computedOptions = Object.assign({}, schema); + if (!options) return computedOptions; + if (typeof options !== "object") { + throw TypeError("options must be an object"); + } + var keys = Object.keys(options); + var length = keys.length; + var option, value; + var reducer; + function reject(reason) { + throw Error('Invalid "' + option + '" option value' + (reason ? ". Reason: " + reason : "")); + } + for (var i = 0; i < length; i++) { + option = keys[i]; + if (!hasOwnProperty.call(schema, option)) { + throw Error('Unknown "' + option + '" option'); + } + value = options[option]; + if (value !== undefined$1) { + reducer = reducers[option]; + computedOptions[option] = reducer ? reducer(value, reject) : value; + } + } + return computedOptions; + } + function constructorReducer(value, reject) { + if (typeof value !== "function" || !value.hasOwnProperty("prototype")) { + reject("value must be a constructor"); + } + return value; + } + function makeTypeReducer(types2) { + var message = "value must be type of " + types2.join("|"); + var len = types2.length; + var firstType = types2[0]; + var secondType = types2[1]; + if (len === 1) { + return function(v3, reject) { + if (typeof v3 === firstType) { + return v3; + } + reject(message); + }; + } + if (len === 2) { + return function(v3, reject) { + var kind = typeof v3; + if (kind === firstType || kind === secondType) return v3; + reject(message); + }; + } + return function(v3, reject) { + var kind = typeof v3; + var i = len; + while (i-- > 0) { + if (kind === types2[i]) return v3; + } + reject(message); }; - } -} -function readContract(config2, parameters) { - const { chainId, ...rest } = parameters; - const client2 = config2.getClient({ chainId }); - const action = getAction(client2, readContract$1, "readContract"); - return action(rest); -} -function getChainId(config2) { - return config2.state.chainId; -} -function deepEqual$1(a2, b2) { - if (a2 === b2) - return true; - if (a2 && b2 && typeof a2 === "object" && typeof b2 === "object") { - if (a2.constructor !== b2.constructor) - return false; - let length; - let i; - if (Array.isArray(a2) && Array.isArray(b2)) { - length = a2.length; - if (length !== b2.length) - return false; - for (i = length; i-- !== 0; ) - if (!deepEqual$1(a2[i], b2[i])) - return false; + } + var functionReducer = makeTypeReducer(["function"]); + var objectFunctionReducer = makeTypeReducer(["object", "function"]); + function makeCancelablePromise(Promise2, executor, options) { + var isCancelable; + var callbacks; + var timer = 0; + var subscriptionClosed; + var promise = new Promise2(function(resolve, reject, onCancel) { + options = resolveOptions(options, { + timeout: 0, + overload: false + }, { + timeout: function(value, reject2) { + value *= 1; + if (typeof value !== "number" || value < 0 || !Number.isFinite(value)) { + reject2("timeout must be a positive number"); + } + return value; + } + }); + isCancelable = !options.overload && typeof Promise2.prototype.cancel === "function" && typeof onCancel === "function"; + function cleanup() { + if (callbacks) { + callbacks = null; + } + if (timer) { + clearTimeout(timer); + timer = 0; + } + } + var _resolve = function(value) { + cleanup(); + resolve(value); + }; + var _reject = function(err) { + cleanup(); + reject(err); + }; + if (isCancelable) { + executor(_resolve, _reject, onCancel); + } else { + callbacks = [function(reason) { + _reject(reason || Error("canceled")); + }]; + executor(_resolve, _reject, function(cb2) { + if (subscriptionClosed) { + throw Error("Unable to subscribe on cancel event asynchronously"); + } + if (typeof cb2 !== "function") { + throw TypeError("onCancel callback must be a function"); + } + callbacks.push(cb2); + }); + subscriptionClosed = true; + } + if (options.timeout > 0) { + timer = setTimeout(function() { + var reason = Error("timeout"); + reason.code = "ETIMEDOUT"; + timer = 0; + promise.cancel(reason); + reject(reason); + }, options.timeout); + } + }); + if (!isCancelable) { + promise.cancel = function(reason) { + if (!callbacks) { + return; + } + var length = callbacks.length; + for (var i = 1; i < length; i++) { + callbacks[i](reason); + } + callbacks[0](reason); + callbacks = null; + }; + } + return promise; + } + function findTargetIndex(observer) { + var observers2 = this._observers; + if (!observers2) { + return -1; + } + var len = observers2.length; + for (var i = 0; i < len; i++) { + if (observers2[i]._target === observer) return i; + } + return -1; + } + function searchListenerTree(handlers, type, tree, i, typeLength) { + if (!tree) { + return null; + } + if (i === 0) { + var kind = typeof type; + if (kind === "string") { + var ns, n2, l2 = 0, j2 = 0, delimiter = this.delimiter, dl2 = delimiter.length; + if ((n2 = type.indexOf(delimiter)) !== -1) { + ns = new Array(5); + do { + ns[l2++] = type.slice(j2, n2); + j2 = n2 + dl2; + } while ((n2 = type.indexOf(delimiter, j2)) !== -1); + ns[l2++] = type.slice(j2); + type = ns; + typeLength = l2; + } else { + type = [type]; + typeLength = 1; + } + } else if (kind === "object") { + typeLength = type.length; + } else { + type = [type]; + typeLength = 1; + } + } + var listeners = null, branch, xTree, xxTree, isolatedBranch, endReached, currentType = type[i], nextType = type[i + 1], branches, _listeners2; + if (i === typeLength) { + if (tree._listeners) { + if (typeof tree._listeners === "function") { + handlers && handlers.push(tree._listeners); + listeners = [tree]; + } else { + handlers && handlers.push.apply(handlers, tree._listeners); + listeners = [tree]; + } + } + } else { + if (currentType === "*") { + branches = ownKeys2(tree); + n2 = branches.length; + while (n2-- > 0) { + branch = branches[n2]; + if (branch !== "_listeners") { + _listeners2 = searchListenerTree(handlers, type, tree[branch], i + 1, typeLength); + if (_listeners2) { + if (listeners) { + listeners.push.apply(listeners, _listeners2); + } else { + listeners = _listeners2; + } + } + } + } + return listeners; + } else if (currentType === "**") { + endReached = i + 1 === typeLength || i + 2 === typeLength && nextType === "*"; + if (endReached && tree._listeners) { + listeners = searchListenerTree(handlers, type, tree, typeLength, typeLength); + } + branches = ownKeys2(tree); + n2 = branches.length; + while (n2-- > 0) { + branch = branches[n2]; + if (branch !== "_listeners") { + if (branch === "*" || branch === "**") { + if (tree[branch]._listeners && !endReached) { + _listeners2 = searchListenerTree(handlers, type, tree[branch], typeLength, typeLength); + if (_listeners2) { + if (listeners) { + listeners.push.apply(listeners, _listeners2); + } else { + listeners = _listeners2; + } + } + } + _listeners2 = searchListenerTree(handlers, type, tree[branch], i, typeLength); + } else if (branch === nextType) { + _listeners2 = searchListenerTree(handlers, type, tree[branch], i + 2, typeLength); + } else { + _listeners2 = searchListenerTree(handlers, type, tree[branch], i, typeLength); + } + if (_listeners2) { + if (listeners) { + listeners.push.apply(listeners, _listeners2); + } else { + listeners = _listeners2; + } + } + } + } + return listeners; + } else if (tree[currentType]) { + listeners = searchListenerTree(handlers, type, tree[currentType], i + 1, typeLength); + } + } + xTree = tree["*"]; + if (xTree) { + searchListenerTree(handlers, type, xTree, i + 1, typeLength); + } + xxTree = tree["**"]; + if (xxTree) { + if (i < typeLength) { + if (xxTree._listeners) { + searchListenerTree(handlers, type, xxTree, typeLength, typeLength); + } + branches = ownKeys2(xxTree); + n2 = branches.length; + while (n2-- > 0) { + branch = branches[n2]; + if (branch !== "_listeners") { + if (branch === nextType) { + searchListenerTree(handlers, type, xxTree[branch], i + 2, typeLength); + } else if (branch === currentType) { + searchListenerTree(handlers, type, xxTree[branch], i + 1, typeLength); + } else { + isolatedBranch = {}; + isolatedBranch[branch] = xxTree[branch]; + searchListenerTree(handlers, type, { "**": isolatedBranch }, i + 1, typeLength); + } + } + } + } else if (xxTree._listeners) { + searchListenerTree(handlers, type, xxTree, typeLength, typeLength); + } else if (xxTree["*"] && xxTree["*"]._listeners) { + searchListenerTree(handlers, type, xxTree["*"], typeLength, typeLength); + } + } + return listeners; + } + function growListenerTree(type, listener, prepend) { + var len = 0, j2 = 0, i, delimiter = this.delimiter, dl2 = delimiter.length, ns; + if (typeof type === "string") { + if ((i = type.indexOf(delimiter)) !== -1) { + ns = new Array(5); + do { + ns[len++] = type.slice(j2, i); + j2 = i + dl2; + } while ((i = type.indexOf(delimiter, j2)) !== -1); + ns[len++] = type.slice(j2); + } else { + ns = [type]; + len = 1; + } + } else { + ns = type; + len = type.length; + } + if (len > 1) { + for (i = 0; i + 1 < len; i++) { + if (ns[i] === "**" && ns[i + 1] === "**") { + return; + } + } + } + var tree = this.listenerTree, name2; + for (i = 0; i < len; i++) { + name2 = ns[i]; + tree = tree[name2] || (tree[name2] = {}); + if (i === len - 1) { + if (!tree._listeners) { + tree._listeners = listener; + } else { + if (typeof tree._listeners === "function") { + tree._listeners = [tree._listeners]; + } + if (prepend) { + tree._listeners.unshift(listener); + } else { + tree._listeners.push(listener); + } + if (!tree._listeners.warned && this._maxListeners > 0 && tree._listeners.length > this._maxListeners) { + tree._listeners.warned = true; + logPossibleMemoryLeak.call(this, tree._listeners.length, name2); + } + } + return true; + } + } return true; } - if (a2.valueOf !== Object.prototype.valueOf) - return a2.valueOf() === b2.valueOf(); - if (a2.toString !== Object.prototype.toString) - return a2.toString() === b2.toString(); - const keys = Object.keys(a2); - length = keys.length; - if (length !== Object.keys(b2).length) - return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b2, keys[i])) - return false; - for (i = length; i-- !== 0; ) { - const key = keys[i]; - if (key && !deepEqual$1(a2[key], b2[key])) - return false; - } - return true; - } - return a2 !== a2 && b2 !== b2; -} -let previousChains = []; -function getChains(config2) { - const chains2 = config2.chains; - if (deepEqual$1(previousChains, chains2)) - return previousChains; - previousChains = chains2; - return chains2; -} -function getClient(config2, parameters = {}) { - let client2 = void 0; - try { - client2 = config2.getClient(parameters); - } catch { - } - return client2; -} -let previousConnections = []; -function getConnections(config2) { - const connections = [...config2.state.connections.values()]; - if (config2.state.status === "reconnecting") - return previousConnections; - if (deepEqual$1(previousConnections, connections)) - return previousConnections; - previousConnections = connections; - return connections; -} -let previousConnectors = []; -function getConnectors(config2) { - const connectors = config2.connectors; - if (deepEqual$1(previousConnectors, connectors)) - return previousConnectors; - previousConnectors = connectors; - return connectors; -} -function getPublicClient(config2, parameters = {}) { - const client2 = getClient(config2, parameters); - return client2 == null ? void 0 : client2.extend(publicActions); -} -async function getWalletClient(config2, parameters = {}) { - const client2 = await getConnectorClient(config2, parameters); - client2.extend(walletActions); - return client2.extend(walletActions); -} -let isReconnecting = false; -async function reconnect(config2, parameters = {}) { - var _a2, _b2; - if (isReconnecting) - return []; - isReconnecting = true; - config2.setState((x2) => ({ - ...x2, - status: x2.current ? "reconnecting" : "connecting" - })); - const connectors = []; - if ((_a2 = parameters.connectors) == null ? void 0 : _a2.length) { - for (const connector_ of parameters.connectors) { - let connector; - if (typeof connector_ === "function") - connector = config2._internal.connectors.setup(connector_); - else - connector = connector_; - connectors.push(connector); + function collectTreeEvents(tree, events, root2, asArray) { + var branches = ownKeys2(tree); + var i = branches.length; + var branch, branchName, path; + var hasListeners = tree["_listeners"]; + var isArrayPath; + while (i-- > 0) { + branchName = branches[i]; + branch = tree[branchName]; + if (branchName === "_listeners") { + path = root2; + } else { + path = root2 ? root2.concat(branchName) : [branchName]; + } + isArrayPath = asArray || typeof branchName === "symbol"; + hasListeners && events.push(isArrayPath ? path : path.join(this.delimiter)); + if (typeof branch === "object") { + collectTreeEvents.call(this, branch, events, path, isArrayPath); + } + } + return events; } - } else - connectors.push(...config2.connectors); - let recentConnectorId; - try { - recentConnectorId = await ((_b2 = config2.storage) == null ? void 0 : _b2.getItem("recentConnectorId")); - } catch { - } - const scores = {}; - for (const [, connection] of config2.state.connections) { - scores[connection.connector.id] = 1; - } - if (recentConnectorId) - scores[recentConnectorId] = 0; - const sorted = Object.keys(scores).length > 0 ? ( - // .toSorted() - [...connectors].sort((a2, b2) => (scores[a2.id] ?? 10) - (scores[b2.id] ?? 10)) - ) : connectors; - let connected = false; - const connections = []; - const providers = []; - for (const connector of sorted) { - const provider2 = await connector.getProvider().catch(() => void 0); - if (!provider2) - continue; - if (providers.some((x2) => x2 === provider2)) - continue; - const isAuthorized = await connector.isAuthorized(); - if (!isAuthorized) - continue; - const data = await connector.connect({ isReconnecting: true }).catch(() => null); - if (!data) - continue; - connector.emitter.off("connect", config2._internal.events.connect); - connector.emitter.on("change", config2._internal.events.change); - connector.emitter.on("disconnect", config2._internal.events.disconnect); - config2.setState((x2) => { - const connections2 = new Map(connected ? x2.connections : /* @__PURE__ */ new Map()).set(connector.uid, { accounts: data.accounts, chainId: data.chainId, connector }); - return { - ...x2, - current: connected ? x2.current : connector.uid, - connections: connections2 - }; - }); - connections.push({ - accounts: data.accounts, - chainId: data.chainId, - connector - }); - providers.push(provider2); - connected = true; - } - if (config2.state.status === "reconnecting" || config2.state.status === "connecting") { - if (!connected) - config2.setState((x2) => ({ - ...x2, - connections: /* @__PURE__ */ new Map(), - current: null, - status: "disconnected" - })); - else - config2.setState((x2) => ({ ...x2, status: "connected" })); - } - isReconnecting = false; - return connections; -} -async function sendTransaction(config2, parameters) { - const { account: account2, chainId, connector, gas: gas_, ...rest } = parameters; - let client2; - if (typeof account2 === "object" && account2.type === "local") - client2 = config2.getClient({ chainId }); - else - client2 = await getConnectorClient(config2, { account: account2, chainId, connector }); - const { connector: activeConnector } = getAccount(config2); - const gas = await (async () => { - var _a2; - if (!("data" in parameters) || !parameters.data) - return void 0; - if ((_a2 = connector ?? activeConnector) == null ? void 0 : _a2.supportsSimulation) - return void 0; - if (gas_ === null) - return void 0; - if (gas_ === void 0) { - const action2 = getAction(client2, estimateGas, "estimateGas"); - return action2({ - ...rest, - account: account2, - chain: chainId ? { id: chainId } : null - }); + function recursivelyGarbageCollect(root2) { + var keys = ownKeys2(root2); + var i = keys.length; + var obj, key, flag; + while (i-- > 0) { + key = keys[i]; + obj = root2[key]; + if (obj) { + flag = true; + if (key !== "_listeners" && !recursivelyGarbageCollect(obj)) { + delete root2[key]; + } + } + } + return flag; } - return gas_; - })(); - const action = getAction(client2, sendTransaction$1, "sendTransaction"); - const hash2 = await action({ - ...rest, - ...account2 ? { account: account2 } : {}, - gas, - chain: chainId ? { id: chainId } : null - }); - return hash2; -} -async function simulateContract(config2, parameters) { - const { abi: abi2, chainId, connector, ...rest } = parameters; - let account2; - if (parameters.account) - account2 = parameters.account; - else { - const connectorClient = await getConnectorClient(config2, { - chainId, - connector - }); - account2 = connectorClient.account; - } - const client2 = config2.getClient({ chainId }); - const action = getAction(client2, simulateContract$1, "simulateContract"); - const { result, request } = await action({ ...rest, abi: abi2, account: account2 }); - return { - chainId: client2.chain.id, - result, - request: { __mode: "prepared", ...request, chainId } - }; -} -class ProviderNotFoundError extends BaseError$1 { - constructor() { - super("Provider not found."); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "ProviderNotFoundError" - }); - } -} -class SwitchChainNotSupportedError extends BaseError$1 { - constructor({ connector }) { - super(`"${connector.name}" does not support programmatic chain switching.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "SwitchChainNotSupportedError" - }); - } -} -async function switchChain(config2, parameters) { - var _a2; - const { addEthereumChainParameter, chainId } = parameters; - const connection = config2.state.connections.get(((_a2 = parameters.connector) == null ? void 0 : _a2.uid) ?? config2.state.current); - if (connection) { - const connector = connection.connector; - if (!connector.switchChain) - throw new SwitchChainNotSupportedError({ connector }); - const chain2 = await connector.switchChain({ - addEthereumChainParameter, - chainId - }); - return chain2; - } - const chain = config2.chains.find((x2) => x2.id === chainId); - if (!chain) - throw new ChainNotConfiguredError(); - config2.setState((x2) => ({ ...x2, chainId })); - return chain; -} -function watchAccount(config2, parameters) { - const { onChange } = parameters; - return config2.subscribe(() => getAccount(config2), onChange, { - equalityFn(a2, b2) { - const { connector: aConnector, ...aRest } = a2; - const { connector: bConnector, ...bRest } = b2; - return deepEqual$1(aRest, bRest) && // check connector separately - (aConnector == null ? void 0 : aConnector.id) === (bConnector == null ? void 0 : bConnector.id) && (aConnector == null ? void 0 : aConnector.uid) === (bConnector == null ? void 0 : bConnector.uid); + function Listener(emitter, event, listener) { + this.emitter = emitter; + this.event = event; + this.listener = listener; } - }); -} -function watchChainId(config2, parameters) { - const { onChange } = parameters; - return config2.subscribe((state) => state.chainId, onChange); -} -function watchConnections(config2, parameters) { - const { onChange } = parameters; - return config2.subscribe(() => getConnections(config2), onChange, { - equalityFn: deepEqual$1 - }); -} -function watchConnectors(config2, parameters) { - const { onChange } = parameters; - return config2._internal.connectors.subscribe((connectors, prevConnectors) => { - onChange(Object.values(connectors), prevConnectors); - }); -} -function watchPublicClient(config2, parameters) { - const { onChange } = parameters; - return config2.subscribe(() => getPublicClient(config2), onChange, { - equalityFn(a2, b2) { - return (a2 == null ? void 0 : a2.uid) === (b2 == null ? void 0 : b2.uid); + Listener.prototype.off = function() { + this.emitter.off(this.event, this.listener); + return this; + }; + function setupListener(event, listener, options) { + if (options === true) { + promisify2 = true; + } else if (options === false) { + async = true; + } else { + if (!options || typeof options !== "object") { + throw TypeError("options should be an object or true"); + } + var async = options.async; + var promisify2 = options.promisify; + var nextTick2 = options.nextTick; + var objectify = options.objectify; + } + if (async || nextTick2 || promisify2) { + var _listener2 = listener; + var _origin = listener._origin || listener; + if (nextTick2 && !nextTickSupported) { + throw Error("process.nextTick is not supported"); + } + if (promisify2 === undefined$1) { + promisify2 = listener.constructor.name === "AsyncFunction"; + } + listener = function() { + var args = arguments; + var context2 = this; + var event2 = this.event; + return promisify2 ? nextTick2 ? Promise.resolve() : new Promise(function(resolve) { + _setImmediate(resolve); + }).then(function() { + context2.event = event2; + return _listener2.apply(context2, args); + }) : (nextTick2 ? process$1.nextTick : _setImmediate)(function() { + context2.event = event2; + _listener2.apply(context2, args); + }); + }; + listener._async = true; + listener._origin = _origin; + } + return [listener, objectify ? new Listener(this, event, listener) : this]; } - }); -} -async function writeContract(config2, parameters) { - const { account: account2, chainId, connector, __mode, ...rest } = parameters; - let client2; - if (typeof account2 === "object" && account2.type === "local") - client2 = config2.getClient({ chainId }); - else - client2 = await getConnectorClient(config2, { account: account2, chainId, connector }); - const { connector: activeConnector } = getAccount(config2); - let request; - if (__mode === "prepared" || (activeConnector == null ? void 0 : activeConnector.supportsSimulation)) - request = rest; - else { - const { request: simulateRequest } = await simulateContract(config2, { - ...rest, - account: account2, - chainId - }); - request = simulateRequest; - } - const action = getAction(client2, writeContract$1, "writeContract"); - const hash2 = await action({ - ...request, - ...account2 ? { account: account2 } : {}, - chain: chainId ? { id: chainId } : null - }); - return hash2; -} -function createConnector(createConnectorFn) { - return createConnectorFn; -} -const supportsSimulationIdRegex = /(rabby|trustwallet)/; -const targetMap = { - coinbaseWallet: { - id: "coinbaseWallet", - name: "Coinbase Wallet", - provider(window2) { - if (window2 == null ? void 0 : window2.coinbaseWalletExtension) - return window2.coinbaseWalletExtension; - return findProvider(window2, "isCoinbaseWallet"); + function EventEmitter2(conf) { + this._events = {}; + this._newListener = false; + this._removeListener = false; + this.verboseMemoryLeak = false; + configure.call(this, conf); } - }, - metaMask: { - id: "metaMask", - name: "MetaMask", - provider(window2) { - return findProvider(window2, (provider2) => { - if (!provider2.isMetaMask) - return false; - if (provider2.isBraveWallet && !provider2._events && !provider2._state) + EventEmitter2.EventEmitter2 = EventEmitter2; + EventEmitter2.prototype.listenTo = function(target, events, options) { + if (typeof target !== "object") { + throw TypeError("target musts be an object"); + } + var emitter = this; + options = resolveOptions(options, { + on: undefined$1, + off: undefined$1, + reducers: undefined$1 + }, { + on: functionReducer, + off: functionReducer, + reducers: objectFunctionReducer + }); + function listen(events2) { + if (typeof events2 !== "object") { + throw TypeError("events must be an object"); + } + var reducers = options.reducers; + var index2 = findTargetIndex.call(emitter, target); + var observer; + if (index2 === -1) { + observer = new TargetObserver(emitter, target, options); + } else { + observer = emitter._observers[index2]; + } + var keys = ownKeys2(events2); + var len = keys.length; + var event; + var isSingleReducer = typeof reducers === "function"; + for (var i = 0; i < len; i++) { + event = keys[i]; + observer.subscribe( + event, + events2[event] || event, + isSingleReducer ? reducers : reducers && reducers[event] + ); + } + } + isArray2(events) ? listen(toObject2(events)) : typeof events === "string" ? listen(toObject2(events.split(/\s+/))) : listen(events); + return this; + }; + EventEmitter2.prototype.stopListeningTo = function(target, event) { + var observers2 = this._observers; + if (!observers2) { + return false; + } + var i = observers2.length; + var observer; + var matched = false; + if (target && typeof target !== "object") { + throw TypeError("target should be an object"); + } + while (i-- > 0) { + observer = observers2[i]; + if (!target || observer._target === target) { + observer.unsubscribe(event); + matched = true; + } + } + return matched; + }; + EventEmitter2.prototype.delimiter = "."; + EventEmitter2.prototype.setMaxListeners = function(n2) { + if (n2 !== undefined$1) { + this._maxListeners = n2; + if (!this._conf) this._conf = {}; + this._conf.maxListeners = n2; + } + }; + EventEmitter2.prototype.getMaxListeners = function() { + return this._maxListeners; + }; + EventEmitter2.prototype.event = ""; + EventEmitter2.prototype.once = function(event, fn, options) { + return this._once(event, fn, false, options); + }; + EventEmitter2.prototype.prependOnceListener = function(event, fn, options) { + return this._once(event, fn, true, options); + }; + EventEmitter2.prototype._once = function(event, fn, prepend, options) { + return this._many(event, 1, fn, prepend, options); + }; + EventEmitter2.prototype.many = function(event, ttl, fn, options) { + return this._many(event, ttl, fn, false, options); + }; + EventEmitter2.prototype.prependMany = function(event, ttl, fn, options) { + return this._many(event, ttl, fn, true, options); + }; + EventEmitter2.prototype._many = function(event, ttl, fn, prepend, options) { + var self2 = this; + if (typeof fn !== "function") { + throw new Error("many only accepts instances of Function"); + } + function listener() { + if (--ttl === 0) { + self2.off(event, listener); + } + return fn.apply(this, arguments); + } + listener._origin = fn; + return this._on(event, listener, prepend, options); + }; + EventEmitter2.prototype.emit = function() { + if (!this._events && !this._all) { + return false; + } + this._events || init2.call(this); + var type = arguments[0], ns, wildcard = this.wildcard; + var args, l2, i, j2, containsSymbol; + if (type === "newListener" && !this._newListener) { + if (!this._events.newListener) { return false; - const flags = [ - "isApexWallet", - "isAvalanche", - "isBitKeep", - "isBlockWallet", - "isKuCoinWallet", - "isMathWallet", - "isOkxWallet", - "isOKExWallet", - "isOneInchIOSWallet", - "isOneInchAndroidWallet", - "isOpera", - "isPortal", - "isRabby", - "isTokenPocket", - "isTokenary", - "isZerion" - ]; - for (const flag of flags) - if (provider2[flag]) - return false; + } + } + if (wildcard) { + ns = type; + if (type !== "newListener" && type !== "removeListener") { + if (typeof type === "object") { + l2 = type.length; + if (symbolsSupported) { + for (i = 0; i < l2; i++) { + if (typeof type[i] === "symbol") { + containsSymbol = true; + break; + } + } + } + if (!containsSymbol) { + type = type.join(this.delimiter); + } + } + } + } + var al2 = arguments.length; + var handler; + if (this._all && this._all.length) { + handler = this._all.slice(); + for (i = 0, l2 = handler.length; i < l2; i++) { + this.event = type; + switch (al2) { + case 1: + handler[i].call(this, type); + break; + case 2: + handler[i].call(this, type, arguments[1]); + break; + case 3: + handler[i].call(this, type, arguments[1], arguments[2]); + break; + default: + handler[i].apply(this, arguments); + } + } + } + if (wildcard) { + handler = []; + searchListenerTree.call(this, handler, ns, this.listenerTree, 0, l2); + } else { + handler = this._events[type]; + if (typeof handler === "function") { + this.event = type; + switch (al2) { + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + default: + args = new Array(al2 - 1); + for (j2 = 1; j2 < al2; j2++) args[j2 - 1] = arguments[j2]; + handler.apply(this, args); + } + return true; + } else if (handler) { + handler = handler.slice(); + } + } + if (handler && handler.length) { + if (al2 > 3) { + args = new Array(al2 - 1); + for (j2 = 1; j2 < al2; j2++) args[j2 - 1] = arguments[j2]; + } + for (i = 0, l2 = handler.length; i < l2; i++) { + this.event = type; + switch (al2) { + case 1: + handler[i].call(this); + break; + case 2: + handler[i].call(this, arguments[1]); + break; + case 3: + handler[i].call(this, arguments[1], arguments[2]); + break; + default: + handler[i].apply(this, args); + } + } return true; - }); - } - }, - phantom: { - id: "phantom", - name: "Phantom", - provider(window2) { - var _a2, _b2; - if ((_a2 = window2 == null ? void 0 : window2.phantom) == null ? void 0 : _a2.ethereum) - return (_b2 = window2.phantom) == null ? void 0 : _b2.ethereum; - return findProvider(window2, "isPhantom"); - } - } -}; -injected.type = "injected"; -function injected(parameters = {}) { - const { shimDisconnect = true, unstable_shimAsyncInject } = parameters; - function getTarget() { - const target = parameters.target; - if (typeof target === "function") { - const result = target(); - if (result) - return result; - } - if (typeof target === "object") - return target; - if (typeof target === "string") - return { - ...targetMap[target] ?? { - id: target, - name: `${target[0].toUpperCase()}${target.slice(1)}`, - provider: `is${target[0].toUpperCase()}${target.slice(1)}` + } else if (!this.ignoreErrors && !this._all && type === "error") { + if (arguments[1] instanceof Error) { + throw arguments[1]; + } else { + throw new Error("Uncaught, unspecified 'error' event."); } - }; - return { - id: "injected", - name: "Injected", - provider(window2) { - return window2 == null ? void 0 : window2.ethereum; } + return !!this._all; }; - } - let accountsChanged; - let chainChanged; - let connect2; - let disconnect2; - return createConnector((config2) => ({ - get icon() { - return getTarget().icon; - }, - get id() { - return getTarget().id; - }, - get name() { - return getTarget().name; - }, - get supportsSimulation() { - return supportsSimulationIdRegex.test(this.id.toLowerCase()); - }, - type: injected.type, - async setup() { - const provider2 = await this.getProvider(); - if (provider2 && parameters.target) { - if (!connect2) { - connect2 = this.onConnect.bind(this); - provider2.on("connect", connect2); + EventEmitter2.prototype.emitAsync = function() { + if (!this._events && !this._all) { + return false; + } + this._events || init2.call(this); + var type = arguments[0], wildcard = this.wildcard, ns, containsSymbol; + var args, l2, i, j2; + if (type === "newListener" && !this._newListener) { + if (!this._events.newListener) { + return Promise.resolve([false]); } - if (!accountsChanged) { - accountsChanged = this.onAccountsChanged.bind(this); - provider2.on("accountsChanged", accountsChanged); + } + if (wildcard) { + ns = type; + if (type !== "newListener" && type !== "removeListener") { + if (typeof type === "object") { + l2 = type.length; + if (symbolsSupported) { + for (i = 0; i < l2; i++) { + if (typeof type[i] === "symbol") { + containsSymbol = true; + break; + } + } + } + if (!containsSymbol) { + type = type.join(this.delimiter); + } + } } } - }, - async connect({ chainId, isReconnecting: isReconnecting2 } = {}) { - var _a2, _b2, _c2, _d2, _e2, _f2; - const provider2 = await this.getProvider(); - if (!provider2) - throw new ProviderNotFoundError(); - let accounts = []; - if (isReconnecting2) - accounts = await this.getAccounts().catch(() => []); - else if (shimDisconnect) { - try { - const permissions = await provider2.request({ - method: "wallet_requestPermissions", - params: [{ eth_accounts: {} }] - }); - accounts = (_d2 = (_c2 = (_b2 = (_a2 = permissions[0]) == null ? void 0 : _a2.caveats) == null ? void 0 : _b2[0]) == null ? void 0 : _c2.value) == null ? void 0 : _d2.map((x2) => getAddress(x2)); - if (accounts.length > 0) { - const sortedAccounts = await this.getAccounts(); - accounts = sortedAccounts; + var promises = []; + var al2 = arguments.length; + var handler; + if (this._all) { + for (i = 0, l2 = this._all.length; i < l2; i++) { + this.event = type; + switch (al2) { + case 1: + promises.push(this._all[i].call(this, type)); + break; + case 2: + promises.push(this._all[i].call(this, type, arguments[1])); + break; + case 3: + promises.push(this._all[i].call(this, type, arguments[1], arguments[2])); + break; + default: + promises.push(this._all[i].apply(this, arguments)); } - } catch (err) { - const error = err; - if (error.code === UserRejectedRequestError.code) - throw new UserRejectedRequestError(error); - if (error.code === ResourceUnavailableRpcError.code) - throw error; } } - try { - if (!(accounts == null ? void 0 : accounts.length) && !isReconnecting2) { - const requestedAccounts = await provider2.request({ - method: "eth_requestAccounts" - }); - accounts = requestedAccounts.map((x2) => getAddress(x2)); + if (wildcard) { + handler = []; + searchListenerTree.call(this, handler, ns, this.listenerTree, 0); + } else { + handler = this._events[type]; + } + if (typeof handler === "function") { + this.event = type; + switch (al2) { + case 1: + promises.push(handler.call(this)); + break; + case 2: + promises.push(handler.call(this, arguments[1])); + break; + case 3: + promises.push(handler.call(this, arguments[1], arguments[2])); + break; + default: + args = new Array(al2 - 1); + for (j2 = 1; j2 < al2; j2++) args[j2 - 1] = arguments[j2]; + promises.push(handler.apply(this, args)); + } + } else if (handler && handler.length) { + handler = handler.slice(); + if (al2 > 3) { + args = new Array(al2 - 1); + for (j2 = 1; j2 < al2; j2++) args[j2 - 1] = arguments[j2]; + } + for (i = 0, l2 = handler.length; i < l2; i++) { + this.event = type; + switch (al2) { + case 1: + promises.push(handler[i].call(this)); + break; + case 2: + promises.push(handler[i].call(this, arguments[1])); + break; + case 3: + promises.push(handler[i].call(this, arguments[1], arguments[2])); + break; + default: + promises.push(handler[i].apply(this, args)); + } + } + } else if (!this.ignoreErrors && !this._all && type === "error") { + if (arguments[1] instanceof Error) { + return Promise.reject(arguments[1]); + } else { + return Promise.reject("Uncaught, unspecified 'error' event."); + } + } + return Promise.all(promises); + }; + EventEmitter2.prototype.on = function(type, listener, options) { + return this._on(type, listener, false, options); + }; + EventEmitter2.prototype.prependListener = function(type, listener, options) { + return this._on(type, listener, true, options); + }; + EventEmitter2.prototype.onAny = function(fn) { + return this._onAny(fn, false); + }; + EventEmitter2.prototype.prependAny = function(fn) { + return this._onAny(fn, true); + }; + EventEmitter2.prototype.addListener = EventEmitter2.prototype.on; + EventEmitter2.prototype._onAny = function(fn, prepend) { + if (typeof fn !== "function") { + throw new Error("onAny only accepts instances of Function"); + } + if (!this._all) { + this._all = []; + } + if (prepend) { + this._all.unshift(fn); + } else { + this._all.push(fn); + } + return this; + }; + EventEmitter2.prototype._on = function(type, listener, prepend, options) { + if (typeof type === "function") { + this._onAny(type, listener); + return this; + } + if (typeof listener !== "function") { + throw new Error("on only accepts instances of Function"); + } + this._events || init2.call(this); + var returnValue = this, temp; + if (options !== undefined$1) { + temp = setupListener.call(this, type, listener, options); + listener = temp[0]; + returnValue = temp[1]; + } + if (this._newListener) { + this.emit("newListener", type, listener); + } + if (this.wildcard) { + growListenerTree.call(this, type, listener, prepend); + return returnValue; + } + if (!this._events[type]) { + this._events[type] = listener; + } else { + if (typeof this._events[type] === "function") { + this._events[type] = [this._events[type]]; + } + if (prepend) { + this._events[type].unshift(listener); + } else { + this._events[type].push(listener); + } + if (!this._events[type].warned && this._maxListeners > 0 && this._events[type].length > this._maxListeners) { + this._events[type].warned = true; + logPossibleMemoryLeak.call(this, this._events[type].length, type); + } + } + return returnValue; + }; + EventEmitter2.prototype.off = function(type, listener) { + if (typeof listener !== "function") { + throw new Error("removeListener only takes instances of Function"); + } + var handlers, leafs = []; + if (this.wildcard) { + var ns = typeof type === "string" ? type.split(this.delimiter) : type.slice(); + leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); + if (!leafs) return this; + } else { + if (!this._events[type]) return this; + handlers = this._events[type]; + leafs.push({ _listeners: handlers }); + } + for (var iLeaf = 0; iLeaf < leafs.length; iLeaf++) { + var leaf = leafs[iLeaf]; + handlers = leaf._listeners; + if (isArray2(handlers)) { + var position = -1; + for (var i = 0, length = handlers.length; i < length; i++) { + if (handlers[i] === listener || handlers[i].listener && handlers[i].listener === listener || handlers[i]._origin && handlers[i]._origin === listener) { + position = i; + break; + } + } + if (position < 0) { + continue; + } + if (this.wildcard) { + leaf._listeners.splice(position, 1); + } else { + this._events[type].splice(position, 1); + } + if (handlers.length === 0) { + if (this.wildcard) { + delete leaf._listeners; + } else { + delete this._events[type]; + } + } + if (this._removeListener) + this.emit("removeListener", type, listener); + return this; + } else if (handlers === listener || handlers.listener && handlers.listener === listener || handlers._origin && handlers._origin === listener) { + if (this.wildcard) { + delete leaf._listeners; + } else { + delete this._events[type]; + } + if (this._removeListener) + this.emit("removeListener", type, listener); + } + } + this.listenerTree && recursivelyGarbageCollect(this.listenerTree); + return this; + }; + EventEmitter2.prototype.offAny = function(fn) { + var i = 0, l2 = 0, fns; + if (fn && this._all && this._all.length > 0) { + fns = this._all; + for (i = 0, l2 = fns.length; i < l2; i++) { + if (fn === fns[i]) { + fns.splice(i, 1); + if (this._removeListener) + this.emit("removeListenerAny", fn); + return this; + } + } + } else { + fns = this._all; + if (this._removeListener) { + for (i = 0, l2 = fns.length; i < l2; i++) + this.emit("removeListenerAny", fns[i]); + } + this._all = []; + } + return this; + }; + EventEmitter2.prototype.removeListener = EventEmitter2.prototype.off; + EventEmitter2.prototype.removeAllListeners = function(type) { + if (type === undefined$1) { + !this._events || init2.call(this); + return this; + } + if (this.wildcard) { + var leafs = searchListenerTree.call(this, null, type, this.listenerTree, 0), leaf, i; + if (!leafs) return this; + for (i = 0; i < leafs.length; i++) { + leaf = leafs[i]; + leaf._listeners = null; + } + this.listenerTree && recursivelyGarbageCollect(this.listenerTree); + } else if (this._events) { + this._events[type] = null; + } + return this; + }; + EventEmitter2.prototype.listeners = function(type) { + var _events2 = this._events; + var keys, listeners, allListeners; + var i; + var listenerTree; + if (type === undefined$1) { + if (this.wildcard) { + throw Error("event name required for wildcard emitter"); } - if (connect2) { - provider2.removeListener("connect", connect2); - connect2 = void 0; + if (!_events2) { + return []; } - if (!accountsChanged) { - accountsChanged = this.onAccountsChanged.bind(this); - provider2.on("accountsChanged", accountsChanged); + keys = ownKeys2(_events2); + i = keys.length; + allListeners = []; + while (i-- > 0) { + listeners = _events2[keys[i]]; + if (typeof listeners === "function") { + allListeners.push(listeners); + } else { + allListeners.push.apply(allListeners, listeners); + } } - if (!chainChanged) { - chainChanged = this.onChainChanged.bind(this); - provider2.on("chainChanged", chainChanged); + return allListeners; + } else { + if (this.wildcard) { + listenerTree = this.listenerTree; + if (!listenerTree) return []; + var handlers = []; + var ns = typeof type === "string" ? type.split(this.delimiter) : type.slice(); + searchListenerTree.call(this, handlers, ns, listenerTree, 0); + return handlers; } - if (!disconnect2) { - disconnect2 = this.onDisconnect.bind(this); - provider2.on("disconnect", disconnect2); + if (!_events2) { + return []; } - let currentChainId = await this.getChainId(); - if (chainId && currentChainId !== chainId) { - const chain = await this.switchChain({ chainId }).catch((error) => { - if (error.code === UserRejectedRequestError.code) - throw error; - return { id: currentChainId }; - }); - currentChainId = (chain == null ? void 0 : chain.id) ?? currentChainId; + listeners = _events2[type]; + if (!listeners) { + return []; } - if (shimDisconnect) - await ((_e2 = config2.storage) == null ? void 0 : _e2.removeItem(`${this.id}.disconnected`)); - if (!parameters.target) - await ((_f2 = config2.storage) == null ? void 0 : _f2.setItem("injected.connected", true)); - return { accounts, chainId: currentChainId }; - } catch (err) { - const error = err; - if (error.code === UserRejectedRequestError.code) - throw new UserRejectedRequestError(error); - if (error.code === ResourceUnavailableRpcError.code) - throw new ResourceUnavailableRpcError(error); - throw error; - } - }, - async disconnect() { - var _a2, _b2; - const provider2 = await this.getProvider(); - if (!provider2) - throw new ProviderNotFoundError(); - if (chainChanged) { - provider2.removeListener("chainChanged", chainChanged); - chainChanged = void 0; - } - if (disconnect2) { - provider2.removeListener("disconnect", disconnect2); - disconnect2 = void 0; - } - if (!connect2) { - connect2 = this.onConnect.bind(this); - provider2.on("connect", connect2); + return typeof listeners === "function" ? [listeners] : listeners; } - try { - await withTimeout(() => ( - // TODO: Remove explicit type for viem@3 - provider2.request({ - // `'wallet_revokePermissions'` added in `viem@2.10.3` - method: "wallet_revokePermissions", - params: [{ eth_accounts: {} }] - }) - ), { timeout: 100 }); - } catch { + }; + EventEmitter2.prototype.eventNames = function(nsAsArray) { + var _events2 = this._events; + return this.wildcard ? collectTreeEvents.call(this, this.listenerTree, [], null, nsAsArray) : _events2 ? ownKeys2(_events2) : []; + }; + EventEmitter2.prototype.listenerCount = function(type) { + return this.listeners(type).length; + }; + EventEmitter2.prototype.hasListeners = function(type) { + if (this.wildcard) { + var handlers = []; + var ns = typeof type === "string" ? type.split(this.delimiter) : type.slice(); + searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); + return handlers.length > 0; } - if (shimDisconnect) { - await ((_a2 = config2.storage) == null ? void 0 : _a2.setItem(`${this.id}.disconnected`, true)); + var _events2 = this._events; + var _all = this._all; + return !!(_all && _all.length || _events2 && (type === undefined$1 ? ownKeys2(_events2).length : _events2[type])); + }; + EventEmitter2.prototype.listenersAny = function() { + if (this._all) { + return this._all; + } else { + return []; } - if (!parameters.target) - await ((_b2 = config2.storage) == null ? void 0 : _b2.removeItem("injected.connected")); - }, - async getAccounts() { - const provider2 = await this.getProvider(); - if (!provider2) - throw new ProviderNotFoundError(); - const accounts = await provider2.request({ method: "eth_accounts" }); - return accounts.map((x2) => getAddress(x2)); - }, - async getChainId() { - const provider2 = await this.getProvider(); - if (!provider2) - throw new ProviderNotFoundError(); - const hexChainId = await provider2.request({ method: "eth_chainId" }); - return Number(hexChainId); - }, - async getProvider() { - if (typeof window === "undefined") - return void 0; - let provider2; - const target = getTarget(); - if (typeof target.provider === "function") - provider2 = target.provider(window); - else if (typeof target.provider === "string") - provider2 = findProvider(window, target.provider); - else - provider2 = target.provider; - if (provider2 && !provider2.removeListener) { - if ("off" in provider2 && typeof provider2.off === "function") - provider2.removeListener = provider2.off; - else - provider2.removeListener = () => { - }; + }; + EventEmitter2.prototype.waitFor = function(event, options) { + var self2 = this; + var type = typeof options; + if (type === "number") { + options = { timeout: options }; + } else if (type === "function") { + options = { filter: options }; } - return provider2; - }, - async isAuthorized() { - var _a2, _b2; - try { - const isDisconnected = shimDisconnect && // If shim exists in storage, connector is disconnected - await ((_a2 = config2.storage) == null ? void 0 : _a2.getItem(`${this.id}.disconnected`)); - if (isDisconnected) - return false; - if (!parameters.target) { - const connected = await ((_b2 = config2.storage) == null ? void 0 : _b2.getItem("injected.connected")); - if (!connected) - return false; - } - const provider2 = await this.getProvider(); - if (!provider2) { - if (unstable_shimAsyncInject !== void 0 && unstable_shimAsyncInject !== false) { - const handleEthereum = async () => { - if (typeof window !== "undefined") - window.removeEventListener("ethereum#initialized", handleEthereum); - const provider3 = await this.getProvider(); - return !!provider3; - }; - const timeout = typeof unstable_shimAsyncInject === "number" ? unstable_shimAsyncInject : 1e3; - const res = await Promise.race([ - ...typeof window !== "undefined" ? [ - new Promise((resolve) => window.addEventListener("ethereum#initialized", () => resolve(handleEthereum()), { once: true })) - ] : [], - new Promise((resolve) => setTimeout(() => resolve(handleEthereum()), timeout)) - ]); - if (res) - return true; + options = resolveOptions(options, { + timeout: 0, + filter: undefined$1, + handleError: false, + Promise, + overload: false + }, { + filter: functionReducer, + Promise: constructorReducer + }); + return makeCancelablePromise(options.Promise, function(resolve, reject, onCancel) { + function listener() { + var filter2 = options.filter; + if (filter2 && !filter2.apply(self2, arguments)) { + return; } - throw new ProviderNotFoundError(); - } - const accounts = await withRetry(() => this.getAccounts()); - return !!accounts.length; - } catch { - return false; - } - }, - async switchChain({ addEthereumChainParameter, chainId }) { - var _a2, _b2, _c2, _d2; - const provider2 = await this.getProvider(); - if (!provider2) - throw new ProviderNotFoundError(); - const chain = config2.chains.find((x2) => x2.id === chainId); - if (!chain) - throw new SwitchChainError(new ChainNotConfiguredError()); - try { - await Promise.all([ - provider2.request({ - method: "wallet_switchEthereumChain", - params: [{ chainId: numberToHex(chainId) }] - }).then(async () => { - const currentChainId = await this.getChainId(); - if (currentChainId === chainId) - config2.emitter.emit("change", { chainId }); - }), - new Promise((resolve) => config2.emitter.once("change", ({ chainId: currentChainId }) => { - if (currentChainId === chainId) - resolve(); - })) - ]); - return chain; - } catch (err) { - const error = err; - if (error.code === 4902 || // Unwrapping for MetaMask Mobile - // https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719 - ((_b2 = (_a2 = error == null ? void 0 : error.data) == null ? void 0 : _a2.originalError) == null ? void 0 : _b2.code) === 4902) { - try { - const { default: blockExplorer, ...blockExplorers } = chain.blockExplorers ?? {}; - let blockExplorerUrls; - if (addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.blockExplorerUrls) - blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls; - else if (blockExplorer) - blockExplorerUrls = [ - blockExplorer.url, - ...Object.values(blockExplorers).map((x2) => x2.url) - ]; - let rpcUrls; - if ((_c2 = addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.rpcUrls) == null ? void 0 : _c2.length) - rpcUrls = addEthereumChainParameter.rpcUrls; - else - rpcUrls = [((_d2 = chain.rpcUrls.default) == null ? void 0 : _d2.http[0]) ?? ""]; - const addEthereumChain = { - blockExplorerUrls, - chainId: numberToHex(chainId), - chainName: (addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.chainName) ?? chain.name, - iconUrls: addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.iconUrls, - nativeCurrency: (addEthereumChainParameter == null ? void 0 : addEthereumChainParameter.nativeCurrency) ?? chain.nativeCurrency, - rpcUrls - }; - await provider2.request({ - method: "wallet_addEthereumChain", - params: [addEthereumChain] - }); - const currentChainId = await this.getChainId(); - if (currentChainId !== chainId) - throw new UserRejectedRequestError(new Error("User rejected switch after adding network.")); - return chain; - } catch (error2) { - throw new UserRejectedRequestError(error2); + self2.off(event, listener); + if (options.handleError) { + var err = arguments[0]; + err ? reject(err) : resolve(toArray.apply(null, arguments).slice(1)); + } else { + resolve(toArray.apply(null, arguments)); } } - if (error.code === UserRejectedRequestError.code) - throw new UserRejectedRequestError(error); - throw new SwitchChainError(error); - } - }, - async onAccountsChanged(accounts) { - var _a2; - if (accounts.length === 0) - this.onDisconnect(); - else if (config2.emitter.listenerCount("connect")) { - const chainId = (await this.getChainId()).toString(); - this.onConnect({ chainId }); - if (shimDisconnect) - await ((_a2 = config2.storage) == null ? void 0 : _a2.removeItem(`${this.id}.disconnected`)); - } else - config2.emitter.emit("change", { - accounts: accounts.map((x2) => getAddress(x2)) + onCancel(function() { + self2.off(event, listener); }); - }, - onChainChanged(chain) { - const chainId = Number(chain); - config2.emitter.emit("change", { chainId }); - }, - async onConnect(connectInfo) { - const accounts = await this.getAccounts(); - if (accounts.length === 0) - return; - const chainId = Number(connectInfo.chainId); - config2.emitter.emit("connect", { accounts, chainId }); - const provider2 = await this.getProvider(); - if (provider2) { - if (connect2) { - provider2.removeListener("connect", connect2); - connect2 = void 0; - } - if (!accountsChanged) { - accountsChanged = this.onAccountsChanged.bind(this); - provider2.on("accountsChanged", accountsChanged); - } - if (!chainChanged) { - chainChanged = this.onChainChanged.bind(this); - provider2.on("chainChanged", chainChanged); + self2._on(event, listener, false); + }, { + timeout: options.timeout, + overload: options.overload + }); + }; + function once(emitter, name2, options) { + options = resolveOptions(options, { + Promise, + timeout: 0, + overload: false + }, { + Promise: constructorReducer + }); + var _Promise = options.Promise; + return makeCancelablePromise(_Promise, function(resolve, reject, onCancel) { + var handler; + if (typeof emitter.addEventListener === "function") { + handler = function() { + resolve(toArray.apply(null, arguments)); + }; + onCancel(function() { + emitter.removeEventListener(name2, handler); + }); + emitter.addEventListener( + name2, + handler, + { once: true } + ); + return; } - if (!disconnect2) { - disconnect2 = this.onDisconnect.bind(this); - provider2.on("disconnect", disconnect2); + var eventListener = function() { + errorListener && emitter.removeListener("error", errorListener); + resolve(toArray.apply(null, arguments)); + }; + var errorListener; + if (name2 !== "error") { + errorListener = function(err) { + emitter.removeListener(name2, eventListener); + reject(err); + }; + emitter.once("error", errorListener); } + onCancel(function() { + errorListener && emitter.removeListener("error", errorListener); + emitter.removeListener(name2, eventListener); + }); + emitter.once(name2, eventListener); + }, { + timeout: options.timeout, + overload: options.overload + }); + } + var prototype = EventEmitter2.prototype; + Object.defineProperties(EventEmitter2, { + defaultMaxListeners: { + get: function() { + return prototype._maxListeners; + }, + set: function(n2) { + if (typeof n2 !== "number" || n2 < 0 || Number.isNaN(n2)) { + throw TypeError("n must be a non-negative number"); + } + prototype._maxListeners = n2; + }, + enumerable: true + }, + once: { + value: once, + writable: true, + configurable: true } - }, - async onDisconnect(error) { - const provider2 = await this.getProvider(); - if (error && error.code === 1013) { - if (provider2 && !!(await this.getAccounts()).length) - return; + }); + Object.defineProperties(prototype, { + _maxListeners: { + value: defaultMaxListeners, + writable: true, + configurable: true + }, + _observers: { value: null, writable: true, configurable: true } + }); + { + module2.exports = EventEmitter2; + } + }(); +})(eventemitter2); +var eventemitter2Exports = eventemitter2.exports; +function isBytes(a2) { + return a2 instanceof Uint8Array || a2 != null && typeof a2 === "object" && a2.constructor.name === "Uint8Array"; +} +function bytes(b2, ...lengths) { + if (!isBytes(b2)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b2.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b2.length}`); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function output(out, instance) { + bytes(out); + const min2 = instance.outputLen; + if (out.length < min2) { + throw new Error(`digestInto() expects output buffer of length at least ${min2}`); + } +} +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +const rotr = (word, shift2) => word << 32 - shift2 | word >>> shift2; +new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +function bytesToHex(bytes$12) { + bytes(bytes$12); + let hex2 = ""; + for (let i = 0; i < bytes$12.length; i++) { + hex2 += hexes[bytes$12[i]]; + } + return hex2; +} +function utf8ToBytes(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes(data) { + if (typeof data === "string") + data = utf8ToBytes(data); + bytes(data); + return data; +} +class Hash3 { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function setBigUint64(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh2 = Number(value >> _32n2 & _u32_max); + const wl = Number(value & _u32_max); + const h2 = isLE2 ? 4 : 0; + const l2 = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h2, wh2, isLE2); + view.setUint32(byteOffset + l2, wl, isLE2); +} +const Chi = (a2, b2, c2) => a2 & b2 ^ ~a2 & c2; +const Maj = (a2, b2, c2) => a2 & b2 ^ a2 & c2 ^ b2 & c2; +class HashMD2 extends Hash3 { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer: buffer2, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; } - config2.emitter.emit("disconnect"); - if (provider2) { - if (chainChanged) { - provider2.removeListener("chainChanged", chainChanged); - chainChanged = void 0; - } - if (disconnect2) { - provider2.removeListener("disconnect", disconnect2); - disconnect2 = void 0; - } - if (!connect2) { - connect2 = this.onConnect.bind(this); - provider2.on("connect", connect2); - } + buffer2.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; } } - })); + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer2[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer2[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer2); + return to; + } } -function findProvider(window2, select) { - function isProvider(provider2) { - if (typeof select === "function") - return select(provider2); - if (typeof select === "string") - return provider2[select]; - return true; +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA2563 extends HashMD2 { + constructor() { + super(64, 32, 8, false); + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; + return [A2, B2, C2, D2, E2, F2, G2, H2]; + } + // prettier-ignore + set(A2, B2, C2, D2, E2, F2, G2, H2) { + this.A = A2 | 0; + this.B = B2 | 0; + this.C = C2 | 0; + this.D = D2 | 0; + this.E = E2 | 0; + this.F = F2 | 0; + this.G = G2 | 0; + this.H = H2 | 0; + } + process(view, offset2) { + for (let i = 0; i < 16; i++, offset2 += 4) + SHA256_W[i] = view.getUint32(offset2, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E2, 6) ^ rotr(E2, 11) ^ rotr(E2, 25); + const T12 = H2 + sigma1 + Chi(E2, F2, G2) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A2, 2) ^ rotr(A2, 13) ^ rotr(A2, 22); + const T22 = sigma0 + Maj(A2, B2, C2) | 0; + H2 = G2; + G2 = F2; + F2 = E2; + E2 = D2 + T12 | 0; + D2 = C2; + C2 = B2; + B2 = A2; + A2 = T12 + T22 | 0; + } + A2 = A2 + this.A | 0; + B2 = B2 + this.B | 0; + C2 = C2 + this.C | 0; + D2 = D2 + this.D | 0; + E2 = E2 + this.E | 0; + F2 = F2 + this.F | 0; + G2 = G2 + this.G | 0; + H2 = H2 + this.H | 0; + this.set(A2, B2, C2, D2, E2, F2, G2, H2); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); } - const ethereum = window2.ethereum; - if (ethereum == null ? void 0 : ethereum.providers) - return ethereum.providers.find((provider2) => isProvider(provider2)); - if (ethereum && isProvider(ethereum)) - return ethereum; - return void 0; } -mock$1.type = "mock"; -function mock$1(parameters) { - const transactionCache = /* @__PURE__ */ new Map(); - const features = parameters.features ?? {}; - let connected = false; - let connectedChainId; - return createConnector((config2) => ({ - id: "mock", - name: "Mock Connector", - type: mock$1.type, - async setup() { - connectedChainId = config2.chains[0].id; - }, - async connect({ chainId } = {}) { - if (features.connectError) { - if (typeof features.connectError === "boolean") - throw new UserRejectedRequestError(new Error("Failed to connect.")); - throw features.connectError; - } - const provider2 = await this.getProvider(); - const accounts = await provider2.request({ - method: "eth_requestAccounts" +const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA2563()); +var Databeat = class { + constructor(hostname, fetch2) { + __publicField(this, "hostname"); + __publicField(this, "fetch"); + __publicField(this, "path", "/rpc/Databeat/"); + __publicField(this, "ping", (headers, signal) => { + return this.fetch( + this.url("Ping"), + createHTTPRequest$1({}, headers, signal) + ).then((res) => { + return buildResponse$1(res).then((_data6) => { + return { + status: _data6.status + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); }); - let currentChainId = await this.getChainId(); - if (chainId && currentChainId !== chainId) { - const chain = await this.switchChain({ chainId }); - currentChainId = chain.id; - } - connected = true; - return { - accounts: accounts.map((x2) => getAddress(x2)), - chainId: currentChainId - }; - }, - async disconnect() { - connected = false; - }, - async getAccounts() { - if (!connected) - throw new ConnectorNotConnectedError(); - const provider2 = await this.getProvider(); - const accounts = await provider2.request({ method: "eth_accounts" }); - return accounts.map((x2) => getAddress(x2)); - }, - async getChainId() { - const provider2 = await this.getProvider(); - const hexChainId = await provider2.request({ method: "eth_chainId" }); - return fromHex$1(hexChainId, "number"); - }, - async isAuthorized() { - if (!features.reconnect) - return false; - if (!connected) - return false; - const accounts = await this.getAccounts(); - return !!accounts.length; - }, - async switchChain({ chainId }) { - const provider2 = await this.getProvider(); - const chain = config2.chains.find((x2) => x2.id === chainId); - if (!chain) - throw new SwitchChainError(new ChainNotConfiguredError()); - await provider2.request({ - method: "wallet_switchEthereumChain", - params: [{ chainId: numberToHex(chainId) }] + }); + __publicField(this, "version", (headers, signal) => { + return this.fetch( + this.url("Version"), + createHTTPRequest$1({}, headers, signal) + ).then((res) => { + return buildResponse$1(res).then((_data6) => { + return { + version: _data6.version + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); }); - return chain; - }, - onAccountsChanged(accounts) { - if (accounts.length === 0) - this.onDisconnect(); - else - config2.emitter.emit("change", { - accounts: accounts.map((x2) => getAddress(x2)) + }); + __publicField(this, "runtimeStatus", (headers, signal) => { + return this.fetch( + this.url("RuntimeStatus"), + createHTTPRequest$1({}, headers, signal) + ).then((res) => { + return buildResponse$1(res).then((_data6) => { + return { + status: _data6.status + }; }); - }, - onChainChanged(chain) { - const chainId = Number(chain); - config2.emitter.emit("change", { chainId }); - }, - async onDisconnect(_error2) { - config2.emitter.emit("disconnect"); - connected = false; - }, - async getProvider({ chainId } = {}) { - const chain = config2.chains.find((x2) => x2.id === chainId) ?? config2.chains[0]; - const url = chain.rpcUrls.default.http[0]; - const request = async ({ method, params }) => { - if (method === "eth_chainId") - return numberToHex(connectedChainId); - if (method === "eth_requestAccounts") - return parameters.accounts; - if (method === "eth_signTypedData_v4") { - if (features.signTypedDataError) { - if (typeof features.signTypedDataError === "boolean") - throw new UserRejectedRequestError(new Error("Failed to sign typed data.")); - throw features.signTypedDataError; - } - } - if (method === "wallet_switchEthereumChain") { - if (features.switchChainError) { - if (typeof features.switchChainError === "boolean") - throw new UserRejectedRequestError(new Error("Failed to switch chain.")); - throw features.switchChainError; - } - connectedChainId = fromHex$1(params[0].chainId, "number"); - this.onChainChanged(connectedChainId.toString()); - return; - } - if (method === "wallet_watchAsset") { - if (features.watchAssetError) { - if (typeof features.watchAssetError === "boolean") - throw new UserRejectedRequestError(new Error("Failed to switch chain.")); - throw features.watchAssetError; - } - return connected; - } - if (method === "wallet_getCapabilities") + }, (error) => { + throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); + }); + }); + __publicField(this, "tick", (args, headers, signal) => { + return this.fetch( + this.url("Tick"), + createHTTPRequest$1(args, headers, signal) + ).then((res) => { + return buildResponse$1(res).then((_data6) => { return { - "0x2105": { - paymasterService: { - supported: params[0] === "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" - }, - sessionKeys: { - supported: true - } - }, - "0x14A34": { - paymasterService: { - supported: params[0] === "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" - } - } + ok: _data6.ok }; - if (method === "wallet_sendCalls") { - const hashes = []; - const calls = params[0].calls; - for (const call2 of calls) { - const { result: result2, error: error2 } = await rpc.http(url, { - body: { - method: "eth_sendTransaction", - params: [call2] - } - }); - if (error2) - throw new RpcRequestError({ - body: { method, params }, - error: error2, - url - }); - hashes.push(result2); - } - const id2 = keccak256(stringToHex(JSON.stringify(calls))); - transactionCache.set(id2, hashes); - return id2; - } - if (method === "wallet_getCallsStatus") { - const hashes = transactionCache.get(params[0]); - if (!hashes) - return null; - const receipts = await Promise.all(hashes.map(async (hash2) => { - const { result: result2, error: error2 } = await rpc.http(url, { - body: { - method: "eth_getTransactionReceipt", - params: [hash2], - id: 0 - } - }); - if (error2) - throw new RpcRequestError({ - body: { method, params }, - error: error2, - url - }); - if (!result2) - return null; - return { - blockHash: result2.blockHash, - blockNumber: result2.blockNumber, - gasUsed: result2.gasUsed, - logs: result2.logs, - status: result2.status, - transactionHash: result2.transactionHash - }; - })); - if (receipts.some((x2) => !x2)) - return { status: "PENDING", receipts: [] }; - return { status: "CONFIRMED", receipts }; - } - if (method === "wallet_showCallsStatus") - return; - if (method === "personal_sign") { - if (features.signMessageError) { - if (typeof features.signMessageError === "boolean") - throw new UserRejectedRequestError(new Error("Failed to sign message.")); - throw features.signMessageError; - } - method = "eth_sign"; - params = [params[1], params[0]]; - } - const body = { method, params }; - const { error, result } = await rpc.http(url, { body }); - if (error) - throw new RpcRequestError({ body, error, url }); - return result; - }; - return custom({ request })({ retryCount: 0 }); - } - })); -} -function requestProviders(listener) { - if (typeof window === "undefined") - return; - const handler = (event) => listener(event.detail); - window.addEventListener("eip6963:announceProvider", handler); - window.dispatchEvent(new CustomEvent("eip6963:requestProvider")); - return () => window.removeEventListener("eip6963:announceProvider", handler); -} -function createStore$1() { - const listeners = /* @__PURE__ */ new Set(); - let providerDetails = []; - const request = () => requestProviders((providerDetail) => { - if (providerDetails.some(({ info }) => info.uuid === providerDetail.info.uuid)) - return; - providerDetails = [...providerDetails, providerDetail]; - listeners.forEach((listener) => listener(providerDetails, { added: [providerDetail] })); - }); - let unwatch = request(); + }); + }, (error) => { + throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); + }); + }); + __publicField(this, "rawEvents", (args, headers, signal) => { + return this.fetch( + this.url("RawEvents"), + createHTTPRequest$1(args, headers, signal) + ).then((res) => { + return buildResponse$1(res).then((_data6) => { + return { + ok: _data6.ok + }; + }); + }, (error) => { + throw WebrpcRequestFailedError$1.new({ cause: `fetch(): ${error.message || ""}` }); + }); + }); + this.hostname = hostname; + this.fetch = (input2, init2) => fetch2(input2, init2); + } + url(name2) { + return this.hostname + this.path + name2; + } +}; +var createHTTPRequest$1 = (body = {}, headers = {}, signal = null) => { return { - _listeners() { - return listeners; - }, - clear() { - listeners.forEach((listener) => listener([], { removed: [...providerDetails] })); - providerDetails = []; - }, - destroy() { - this.clear(); - listeners.clear(); - unwatch == null ? void 0 : unwatch(); - }, - findProvider({ rdns }) { - return providerDetails.find((providerDetail) => providerDetail.info.rdns === rdns); - }, - getProviders() { - return providerDetails; - }, - reset() { - this.clear(); - unwatch == null ? void 0 : unwatch(); - unwatch = request(); - }, - subscribe(listener, { emitImmediately } = {}) { - listeners.add(listener); - if (emitImmediately) - listener(providerDetails, { added: providerDetails }); - return () => listeners.delete(listener); - } + method: "POST", + headers: { ...headers, "Content-Type": "application/json" }, + body: JSON.stringify(body || {}), + signal }; -} -const __vite_import_meta_env__$1 = { "BASE_URL": "./", "DEV": false, "MODE": "production", "PROD": true, "SSR": false }; -const subscribeWithSelectorImpl = (fn) => (set, get2, api2) => { - const origSubscribe = api2.subscribe; - api2.subscribe = (selector2, optListener, options) => { - let listener = selector2; - if (optListener) { - const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is; - let currentSlice = selector2(api2.getState()); - listener = (state) => { - const nextSlice = selector2(state); - if (!equalityFn(currentSlice, nextSlice)) { - const previousSlice = currentSlice; - optListener(currentSlice = nextSlice, previousSlice); - } - }; - if (options == null ? void 0 : options.fireImmediately) { - optListener(currentSlice, currentSlice); +}; +var buildResponse$1 = (res) => { + return res.text().then((text2) => { + let data; + try { + data = JSON.parse(text2); + } catch (error) { + let message = ""; + if (error instanceof Error) { + message = error.message; } + throw WebrpcBadResponseError$1.new( + { + status: res.status, + cause: `JSON.parse(): ${message}: response text: ${text2}` + } + ); } - return origSubscribe(listener); - }; - const initialState = fn(set, get2, api2); - return initialState; + if (!res.ok) { + const code2 = typeof data.code === "number" ? data.code : 0; + throw (webrpcErrorByCode$1[code2] || WebrpcError$1).new(data); + } + return data; + }); +}; +var WebrpcError$1 = class _WebrpcError extends Error { + constructor(name2, code2, message, status, cause) { + super(message); + __publicField(this, "name"); + __publicField(this, "code"); + __publicField(this, "message"); + __publicField(this, "status"); + __publicField(this, "cause"); + /** @deprecated Use message instead of msg. Deprecated in webrpc v0.11.0. */ + __publicField(this, "msg"); + this.name = name2 || "WebrpcError"; + this.code = typeof code2 === "number" ? code2 : 0; + this.message = message || `endpoint error ${this.code}`; + this.msg = this.message; + this.status = typeof status === "number" ? status : 0; + this.cause = cause; + Object.setPrototypeOf(this, _WebrpcError.prototype); + } + static new(payload) { + return new this(payload.error, payload.code, payload.message || payload.msg, payload.status, payload.cause); + } }; -const subscribeWithSelector = subscribeWithSelectorImpl; -function createJSONStorage(getStorage, options) { - let storage; - try { - storage = getStorage(); - } catch (e2) { - return; +var WebrpcEndpointError$1 = class _WebrpcEndpointError extends WebrpcError$1 { + constructor(name2 = "WebrpcEndpoint", code2 = 0, message = "endpoint error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcEndpointError.prototype); } - const persistStorage = { - getItem: (name2) => { +}; +var WebrpcRequestFailedError$1 = class _WebrpcRequestFailedError extends WebrpcError$1 { + constructor(name2 = "WebrpcRequestFailed", code2 = -1, message = "request failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcRequestFailedError.prototype); + } +}; +var WebrpcBadRouteError$1 = class _WebrpcBadRouteError extends WebrpcError$1 { + constructor(name2 = "WebrpcBadRoute", code2 = -2, message = "bad route", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcBadRouteError.prototype); + } +}; +var WebrpcBadMethodError$1 = class _WebrpcBadMethodError extends WebrpcError$1 { + constructor(name2 = "WebrpcBadMethod", code2 = -3, message = "bad method", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcBadMethodError.prototype); + } +}; +var WebrpcBadRequestError$1 = class _WebrpcBadRequestError extends WebrpcError$1 { + constructor(name2 = "WebrpcBadRequest", code2 = -4, message = "bad request", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcBadRequestError.prototype); + } +}; +var WebrpcBadResponseError$1 = class _WebrpcBadResponseError extends WebrpcError$1 { + constructor(name2 = "WebrpcBadResponse", code2 = -5, message = "bad response", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcBadResponseError.prototype); + } +}; +var WebrpcServerPanicError$1 = class _WebrpcServerPanicError extends WebrpcError$1 { + constructor(name2 = "WebrpcServerPanic", code2 = -6, message = "server panic", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcServerPanicError.prototype); + } +}; +var WebrpcInternalErrorError$1 = class _WebrpcInternalErrorError extends WebrpcError$1 { + constructor(name2 = "WebrpcInternalError", code2 = -7, message = "internal error", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcInternalErrorError.prototype); + } +}; +var WebrpcClientDisconnectedError$1 = class _WebrpcClientDisconnectedError extends WebrpcError$1 { + constructor(name2 = "WebrpcClientDisconnected", code2 = -8, message = "client disconnected", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcClientDisconnectedError.prototype); + } +}; +var WebrpcStreamLostError$1 = class _WebrpcStreamLostError extends WebrpcError$1 { + constructor(name2 = "WebrpcStreamLost", code2 = -9, message = "stream lost", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcStreamLostError.prototype); + } +}; +var WebrpcStreamFinishedError$1 = class _WebrpcStreamFinishedError extends WebrpcError$1 { + constructor(name2 = "WebrpcStreamFinished", code2 = -10, message = "stream finished", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _WebrpcStreamFinishedError.prototype); + } +}; +var UnauthorizedError$1 = class _UnauthorizedError extends WebrpcError$1 { + constructor(name2 = "Unauthorized", code2 = 1e3, message = "Unauthorized access", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _UnauthorizedError.prototype); + } +}; +var PermissionDeniedError5 = class _PermissionDeniedError extends WebrpcError$1 { + constructor(name2 = "PermissionDenied", code2 = 2e3, message = "Permission denied", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _PermissionDeniedError.prototype); + } +}; +var SessionExpiredError5 = class _SessionExpiredError extends WebrpcError$1 { + constructor(name2 = "SessionExpired", code2 = 2001, message = "Session expired", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _SessionExpiredError.prototype); + } +}; +var NotFoundError7 = class _NotFoundError extends WebrpcError$1 { + constructor(name2 = "NotFound", code2 = 3e3, message = "Resource not found", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _NotFoundError.prototype); + } +}; +var InvalidAppKeyError = class _InvalidAppKeyError extends WebrpcError$1 { + constructor(name2 = "InvalidAppKey", code2 = 4e3, message = "Invalid app key", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _InvalidAppKeyError.prototype); + } +}; +var QueryFailedError6 = class _QueryFailedError extends WebrpcError$1 { + constructor(name2 = "QueryFailed", code2 = 4001, message = "DB query failed", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _QueryFailedError.prototype); + } +}; +var InvalidProjectIdError = class _InvalidProjectIdError extends WebrpcError$1 { + constructor(name2 = "InvalidProjectId", code2 = 4002, message = "Invalid project id", status = 0, cause) { + super(name2, code2, message, status, cause); + Object.setPrototypeOf(this, _InvalidProjectIdError.prototype); + } +}; +var webrpcErrorByCode$1 = { + [0]: WebrpcEndpointError$1, + [-1]: WebrpcRequestFailedError$1, + [-2]: WebrpcBadRouteError$1, + [-3]: WebrpcBadMethodError$1, + [-4]: WebrpcBadRequestError$1, + [-5]: WebrpcBadResponseError$1, + [-6]: WebrpcServerPanicError$1, + [-7]: WebrpcInternalErrorError$1, + [-8]: WebrpcClientDisconnectedError$1, + [-9]: WebrpcStreamLostError$1, + [-10]: WebrpcStreamFinishedError$1, + [1e3]: UnauthorizedError$1, + [2e3]: PermissionDeniedError5, + [2001]: SessionExpiredError5, + [3e3]: NotFoundError7, + [4e3]: InvalidAppKeyError, + [4001]: QueryFailedError6, + [4002]: InvalidProjectIdError +}; +var DatabeatRpcClient = class extends Databeat { + constructor(hostname, auth2) { + const globalFetch = globalThis.fetch.bind(globalThis); + super(hostname.endsWith("/") ? hostname.slice(0, -1) : hostname, globalFetch); + __publicField(this, "_globalFetch"); + __publicField(this, "_fetch", (input2, init2) => { var _a2; - const parse2 = (str2) => { - if (str2 === null) { - return null; + if (this.auth) { + let headers = {}; + if (((_a2 = this.auth.jwt) == null ? void 0 : _a2.length) > 0) { + headers["Authorization"] = `BEARER ${this.auth.jwt}`; } - return JSON.parse(str2, void 0); - }; - const str = (_a2 = storage.getItem(name2)) != null ? _a2 : null; - if (str instanceof Promise) { - return str.then(parse2); - } - return parse2(str); - }, - setItem: (name2, newValue) => storage.setItem( - name2, - JSON.stringify(newValue, void 0) - ), - removeItem: (name2) => storage.removeItem(name2) - }; - return persistStorage; -} -const toThenable = (fn) => (input2) => { - try { - const result = fn(input2); - if (result instanceof Promise) { - return result; - } - return { - then(onFulfilled) { - return toThenable(onFulfilled)(result); - }, - catch(_onRejected) { - return this; - } - }; - } catch (e2) { - return { - then(_onFulfilled) { - return this; - }, - catch(onRejected) { - return toThenable(onRejected)(e2); + if (this.auth.headers) { + headers = { ...headers, ...this.auth.headers }; + } + init2.headers = { ...init2.headers, ...headers }; } - }; + return this._globalFetch(input2, init2); + }); + this.auth = auth2; + this._globalFetch = globalFetch; + this.fetch = this._fetch; } }; -const oldImpl = (config2, baseOptions) => (set, get2, api2) => { - let options = { - getStorage: () => localStorage, - serialize: JSON.stringify, - deserialize: JSON.parse, - partialize: (state) => state, - version: 0, - merge: (persistedState, currentState) => ({ - ...currentState, - ...persistedState - }), - ...baseOptions - }; - let hasHydrated = false; - const hydrationListeners = /* @__PURE__ */ new Set(); - const finishHydrationListeners = /* @__PURE__ */ new Set(); - let storage; - try { - storage = options.getStorage(); - } catch (e2) { - } - if (!storage) { - return config2( - (...args) => { - console.warn( - `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.` - ); - set(...args); - }, - get2, - api2 - ); +var MAX_QUEUE_SIZE = 150; +var defaultDatabeatOptions = { + defaultEnabled: true, + noop: false, + privacy: { userIdHash: true, userAgentSalt: false }, + userIdentTracking: false, + strictMode: false, + flushInterval: 500, + initProps: () => { + return {}; } - const thenableSerialize = toThenable(options.serialize); - const setItem = () => { - const state = options.partialize({ ...get2() }); - let errorInSync; - const thenable = thenableSerialize({ state, version: options.version }).then( - (serializedValue) => storage.setItem(options.name, serializedValue) - ).catch((e2) => { - errorInSync = e2; - }); - if (errorInSync) { - throw errorInSync; - } - return thenable; - }; - const savedSetState = api2.setState; - api2.setState = (state, replace) => { - savedSetState(state, replace); - void setItem(); - }; - const configResult = config2( - (...args) => { - set(...args); - void setItem(); - }, - get2, - api2 - ); - let stateFromStorage; - const hydrate2 = () => { - var _a2; - if (!storage) - return; - hasHydrated = false; - hydrationListeners.forEach((cb2) => cb2(get2())); - const postRehydrationCallback = ((_a2 = options.onRehydrateStorage) == null ? void 0 : _a2.call(options, get2())) || void 0; - return toThenable(storage.getItem.bind(storage))(options.name).then((storageValue) => { - if (storageValue) { - return options.deserialize(storageValue); +}; +var Databeat2 = class { + constructor(host, auth2, options) { + __publicField(this, "rpc"); + __publicField(this, "auth"); + __publicField(this, "options"); + __publicField(this, "enabled"); + __publicField(this, "ident"); + __publicField(this, "userId"); + __publicField(this, "sessionId"); + __publicField(this, "allowUserTracking"); + __publicField(this, "projectId"); + __publicField(this, "queue"); + __publicField(this, "flushTimeout"); + __publicField(this, "defaultProps"); + __publicField(this, "previousPageKey"); + __publicField(this, "ts"); + __publicField(this, "flush", async () => { + if (this.flushTimeout !== null) { + clearTimeout(this.flushTimeout); + this.flushTimeout = null; } - }).then((deserializedStorageValue) => { - if (deserializedStorageValue) { - if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) { - if (options.migrate) { - return options.migrate( - deserializedStorageValue.state, - deserializedStorageValue.version - ); - } - console.error( - `State loaded from storage couldn't be migrated since no migrate function was provided` - ); - } else { - return deserializedStorageValue.state; - } + if (!this.enabled) + return; + if (this.options.noop) + return; + if (this.options.strictMode && !this.allowUserTracking) + return; + if (this.queue.length === 0) + return; + const events = this.dedupedQueue(); + this.queue = []; + try { + await this.rpc.tick({ events }); + } catch (err) { + console.warn(`databeat flush failed: ${err}`); } - }).then((migratedState) => { - var _a22; - stateFromStorage = options.merge( - migratedState, - (_a22 = get2()) != null ? _a22 : configResult - ); - set(stateFromStorage, true); - return setItem(); - }).then(() => { - postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0); - hasHydrated = true; - finishHydrationListeners.forEach((cb2) => cb2(stateFromStorage)); - }).catch((e2) => { - postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e2); }); - }; - api2.persist = { - setOptions: (newOptions) => { - options = { - ...options, - ...newOptions - }; - if (newOptions.getStorage) { - storage = newOptions.getStorage(); + __publicField(this, "dedupedQueue", () => { + const uniqEvents = /* @__PURE__ */ new Map(); + for (let i = 0; i < this.queue.length; i++) { + const ev = this.queue[i]; + const key = `${ev.event}:${ev.source}:${ev.userId}:${ev.sessionId}:${JSON.stringify(ev.props)}:${JSON.stringify(ev.nums)}`; + if (!uniqEvents.has(key)) { + uniqEvents.set(key, ev); + } } - }, - clearStorage: () => { - storage == null ? void 0 : storage.removeItem(options.name); - }, - getOptions: () => options, - rehydrate: () => hydrate2(), - hasHydrated: () => hasHydrated, - onHydrate: (cb2) => { - hydrationListeners.add(cb2); - return () => { - hydrationListeners.delete(cb2); - }; - }, - onFinishHydration: (cb2) => { - finishHydrationListeners.add(cb2); - return () => { - finishHydrationListeners.delete(cb2); + return Array.from(uniqEvents.values()); + }); + this.auth = auth2; + this.rpc = new DatabeatRpcClient(host, auth2); + this.options = defaultDatabeatOptions; + if (options) { + this.options = { + defaultEnabled: options.defaultEnabled || defaultDatabeatOptions.defaultEnabled, + projectId: options.projectId || null, + privacy: options.privacy || defaultDatabeatOptions.privacy, + userIdentTracking: options.userIdentTracking || defaultDatabeatOptions.userIdentTracking, + strictMode: options.strictMode || defaultDatabeatOptions.strictMode, + flushInterval: options.flushInterval || defaultDatabeatOptions.flushInterval, + noop: options.noop || false, + initProps: options.initProps || defaultDatabeatOptions.initProps }; } - }; - hydrate2(); - return stateFromStorage || configResult; -}; -const newImpl = (config2, baseOptions) => (set, get2, api2) => { - let options = { - storage: createJSONStorage(() => localStorage), - partialize: (state) => state, - version: 0, - merge: (persistedState, currentState) => ({ - ...currentState, - ...persistedState - }), - ...baseOptions - }; - let hasHydrated = false; - const hydrationListeners = /* @__PURE__ */ new Set(); - const finishHydrationListeners = /* @__PURE__ */ new Set(); - let storage = options.storage; - if (!storage) { - return config2( - (...args) => { - console.warn( - `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.` - ); - set(...args); - }, - get2, - api2 - ); + this.init(); } - const setItem = () => { - const state = options.partialize({ ...get2() }); - return storage.setItem(options.name, { - state, - version: options.version - }); - }; - const savedSetState = api2.setState; - api2.setState = (state, replace) => { - savedSetState(state, replace); - void setItem(); - }; - const configResult = config2( - (...args) => { - set(...args); - void setItem(); - }, - get2, - api2 - ); - let stateFromStorage; - const hydrate2 = () => { - var _a2, _b2; - if (!storage) + // init is called on load by the constructor and also by reset(). + init() { + this.enabled = isEnabled(this.options.defaultEnabled, this.auth); + this.projectId = this.options.projectId || null; + this.userId = null; + this.sessionId = genSessionId(); + this.queue = []; + this.flushTimeout = null; + this.defaultProps = { ...getDefaultProps(), ...this.options.initProps() }; + this.identify(); + } + // reset will reset the user_id and session_id details. Similar to a "logout" action. + reset(skipInit) { + this.enabled = isEnabled(this.options.defaultEnabled, this.auth); + if (this.userId && !this.isAnon()) { + this.userId = null; + } + this.ident = 0; + this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); + if (skipInit === true) { return; - hasHydrated = false; - hydrationListeners.forEach((cb2) => { - var _a22; - return cb2((_a22 = get2()) != null ? _a22 : configResult); - }); - const postRehydrationCallback = ((_b2 = options.onRehydrateStorage) == null ? void 0 : _b2.call(options, (_a2 = get2()) != null ? _a2 : configResult)) || void 0; - return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => { - if (deserializedStorageValue) { - if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) { - if (options.migrate) { - return options.migrate( - deserializedStorageValue.state, - deserializedStorageValue.version - ); + } + this.init(); + } + // identify can be called to seed the userId, where the behaviour changes + // depending on privacy or strict modes. identify is also called on init, + // where we load the data from localStorage. + identify(userId, options) { + if (!isBrowser()) + return; + if (options && options.allowTracking !== void 0) { + this.allowTracking(options.allowTracking); + } + if (!userId) { + const val = getStorageVal(); + if (val !== null && val.id !== null) { + this.userId = val.id; + this.ident = val.it; + this.allowUserTracking = val.ut; + if (val.it === void 0) { + if (this.userId.startsWith("anon:")) { + this.ident = 0; + } else { + this.ident = 1; } - console.error( - `State loaded from storage couldn't be migrated since no migrate function was provided` - ); + this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); } else { - return deserializedStorageValue.state; + this.ident = val.it; } } - }).then((migratedState) => { - var _a22; - stateFromStorage = options.merge( - migratedState, - (_a22 = get2()) != null ? _a22 : configResult - ); - set(stateFromStorage, true); - return setItem(); - }).then(() => { - postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0); - stateFromStorage = get2(); - hasHydrated = true; - finishHydrationListeners.forEach((cb2) => cb2(stateFromStorage)); - }).catch((e2) => { - postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e2); - }); - }; - api2.persist = { - setOptions: (newOptions) => { - options = { - ...options, - ...newOptions - }; - if (newOptions.storage) { - storage = newOptions.storage; - } - }, - clearStorage: () => { - storage == null ? void 0 : storage.removeItem(options.name); - }, - getOptions: () => options, - rehydrate: () => hydrate2(), - hasHydrated: () => hasHydrated, - onHydrate: (cb2) => { - hydrationListeners.add(cb2); - return () => { - hydrationListeners.delete(cb2); - }; - }, - onFinishHydration: (cb2) => { - finishHydrationListeners.add(cb2); - return () => { - finishHydrationListeners.delete(cb2); - }; } - }; - if (!options.skipHydration) { - hydrate2(); + if (userId || this.userId === null) { + const v3 = genUserId(userId, this.allowUserTracking, this.options); + this.userId = v3.userId; + this.ident = v3.ident; + this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); + } + this.track({ event: "INIT", source: getPagePath(), props: this.defaultProps }); + this.flush(); } - return stateFromStorage || configResult; -}; -const persistImpl = (config2, baseOptions) => { - if ("getStorage" in baseOptions || "serialize" in baseOptions || "deserialize" in baseOptions) { - if ((__vite_import_meta_env__$1 ? "production" : void 0) !== "production") { - console.warn( - "[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead." - ); + // allowTracking is used by strict mode to enable/disable tracking. + allowTracking(allowTracking) { + this.allowUserTracking = allowTracking; + setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); + if (this.options.strictMode) { + if (allowTracking) { + this.enable(); + } else { + this.disable(); + } } - return oldImpl(config2, baseOptions); } - return newImpl(config2, baseOptions); -}; -const persist = persistImpl; -const __vite_import_meta_env__ = { "BASE_URL": "./", "DEV": false, "MODE": "production", "PROD": true, "SSR": false }; -const createStoreImpl = (createState2) => { - let state; - const listeners = /* @__PURE__ */ new Set(); - const setState = (partial, replace) => { - const nextState = typeof partial === "function" ? partial(state) : partial; - if (!Object.is(nextState, state)) { - const previousState = state; - state = (replace != null ? replace : typeof nextState !== "object") ? nextState : Object.assign({}, state, nextState); - listeners.forEach((listener) => listener(state, previousState)); + async track(events, options) { + if (isBrowser() && this.userId === null) { + throw new Error("databeat: init first"); } - }; - const getState2 = () => state; - const subscribe = (listener) => { - listeners.add(listener); - return () => listeners.delete(listener); - }; - const destroy = () => { - if ((__vite_import_meta_env__ ? "production" : void 0) !== "production") { - console.warn( - "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected." - ); + if (Array.isArray(events)) { + for (let i = 0; i < events.length; i++) { + events[i].ident = this.ident; + events[i].userId = this.userId; + events[i].sessionId = this.sessionId; + if (!events[i].projectId && this.projectId) { + events[i].projectId = this.projectId; + } + } + this.queue.push(...events); + } else { + events.ident = this.ident; + events.userId = this.userId; + events.sessionId = this.sessionId; + if (!events.projectId && this.projectId) { + events.projectId = this.projectId; + } + this.queue.push(events); + } + if (this.queue.length > MAX_QUEUE_SIZE) { + this.queue = this.queue.splice(this.queue.length - MAX_QUEUE_SIZE); + } + if (!this.enabled) + return; + if (options && options.flush) { + await this.flush(); + } else if (this.flushTimeout === null) { + this.flushTimeout = setTimeout(() => { + this.flush(); + }, this.options.flushInterval); } - listeners.clear(); - }; - const api2 = { setState, getState: getState2, subscribe, destroy }; - state = createState2(setState, getState2, api2); - return api2; -}; -const createStore = (createState2) => createState2 ? createStoreImpl(createState2) : createStoreImpl; -var eventemitter3 = { exports: {} }; -(function(module2) { - var has = Object.prototype.hasOwnProperty, prefix = "~"; - function Events() { } - if (Object.create) { - Events.prototype = /* @__PURE__ */ Object.create(null); - if (!new Events().__proto__) prefix = false; + trackView(props = {}) { + const eventProps = { ...this.defaultProps, ...props }; + const eventSource = getPagePath(); + const pageKey = `${eventSource}:${JSON.stringify(eventProps)}:${this.userId}:${this.sessionId}`; + if (this.previousPageKey === pageKey) + return; + this.previousPageKey = pageKey; + this.track({ event: "VIEW", source: eventSource, props: eventProps }); } - function EE(fn, context2, once) { - this.fn = fn; - this.context = context2; - this.once = once || false; + isEnabled() { + return this.enabled; } - function addListener(emitter, event, fn, context2, once) { - if (typeof fn !== "function") { - throw new TypeError("The listener must be a function"); - } - var listener = new EE(fn, context2 || emitter, once), evt = prefix ? prefix + event : event; - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; - return emitter; + isAnon() { + return this.ident === 0; } - function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; + getIdent() { + return this.ident; } - function EventEmitter2() { - this._events = new Events(); - this._eventsCount = 0; + getUserId() { + return this.userId; } - EventEmitter2.prototype.eventNames = function eventNames() { - var names2 = [], events, name2; - if (this._eventsCount === 0) return names2; - for (name2 in events = this._events) { - if (has.call(events, name2)) names2.push(prefix ? name2.slice(1) : name2); + getSessionId() { + return this.sessionId; + } + getStorageTS() { + if (this.ts) { + return this.ts; } - if (Object.getOwnPropertySymbols) { - return names2.concat(Object.getOwnPropertySymbols(events)); + const val = getStorageVal(); + if (val === void 0 || val === null || val.id === null) { + return void 0; } - return names2; - }; - EventEmitter2.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event, handlers = this._events[evt]; - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; - for (var i = 0, l2 = handlers.length, ee2 = new Array(l2); i < l2; i++) { - ee2[i] = handlers[i].fn; + this.ts = val.ts; + return this.ts; + } + enable() { + if (!isAuthEnabled(this.auth)) { + this.enabled = false; + return; } - return ee2; - }; - EventEmitter2.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event, listeners = this._events[evt]; - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; - }; - EventEmitter2.prototype.emit = function emit2(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) return false; - var listeners = this._events[evt], len = arguments.length, args, i; - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); - switch (len) { - case 1: - return listeners.fn.call(listeners.context), true; - case 2: - return listeners.fn.call(listeners.context, a1), true; - case 3: - return listeners.fn.call(listeners.context, a1, a2), true; - case 4: - return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: - return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: - return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - for (i = 1, args = new Array(len - 1); i < len; i++) { - args[i - 1] = arguments[i]; - } - listeners.fn.apply(listeners.context, args); + if (!isBrowser()) + return; + this.enabled = true; + this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); + this.identify(); + } + disable() { + if (!isBrowser()) + return; + this.enabled = false; + this.ts = setStorageVal({ on: this.enabled, id: this.userId, it: this.ident, ut: this.allowUserTracking }); + } +}; +var isBrowser = () => { + return typeof window === "object" && typeof window.localStorage === "object" && typeof window.localStorage.getItem === "function" && typeof window.localStorage.setItem === "function"; +}; +var isEnabled = (defaultEnabled, auth2) => { + if (!isAuthEnabled(auth2)) { + return false; + } + if (!isBrowser()) { + return true; + } + const val = getStorageVal(); + if (val === null) { + if (defaultEnabled !== null && defaultEnabled !== void 0) { + return defaultEnabled; } else { - var length = listeners.length, j2; - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); - switch (len) { - case 1: - listeners[i].fn.call(listeners[i].context); - break; - case 2: - listeners[i].fn.call(listeners[i].context, a1); - break; - case 3: - listeners[i].fn.call(listeners[i].context, a1, a2); - break; - case 4: - listeners[i].fn.call(listeners[i].context, a1, a2, a3); - break; - default: - if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) { - args[j2 - 1] = arguments[j2]; - } - listeners[i].fn.apply(listeners[i].context, args); - } - } + return true; } + } else { + return val.on; + } +}; +var isAuthEnabled = (auth2) => { + var _a2; + if (((_a2 = auth2 == null ? void 0 : auth2.jwt) == null ? void 0 : _a2.length) > 0) { return true; - }; - EventEmitter2.prototype.on = function on(event, fn, context2) { - return addListener(this, event, fn, context2, false); - }; - EventEmitter2.prototype.once = function once(event, fn, context2) { - return addListener(this, event, fn, context2, true); - }; - EventEmitter2.prototype.removeListener = function removeListener(event, fn, context2, once) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; + } + if ((auth2 == null ? void 0 : auth2.headers) && Object.keys(auth2.headers).length > 0) { + return true; + } + return false; +}; +var getPagePath = () => { + try { + return window.location.pathname; + } catch (err) { + return ""; + } +}; +var getDefaultProps = () => { + if (!isBrowser()) + return {}; + const params = new URL(window.location.href).searchParams; + const props = {}; + props["origin"] = window.location.origin; + if (params.get("ref") && params.get("ref") !== "") { + props["ref"] = params.get("ref") || ""; + } + if (params.get("source") && params.get("source") !== "") { + props["source"] = params.get("source") || ""; + } + if (params.get("utm_source") && params.get("utm_source") !== "") { + props["utmSource"] = params.get("utm_source") || ""; + } + if (params.get("utm_campaign") && params.get("utm_campaign") !== "") { + props["utmCampaign"] = params.get("utm_campaign") || ""; + } + if (params.get("utm_medium") && params.get("utm_medium") !== "") { + props["utmMedium"] = params.get("utm_medium") || ""; + } + if (params.get("utm_content") && params.get("utm_content") !== "") { + props["utmContent"] = params.get("utm_content") || ""; + } + if (params.get("utm_term") && params.get("utm_term") !== "") { + props["utmTerm"] = params.get("utm_term") || ""; + } + if (document.referrer && document.referrer !== "") { + props["referrer"] = document.referrer; + } + if (params.get("gclid") && params.get("gclid") !== "") { + props["gclid"] = params.get("gclid") || ""; + } + if (params.get("wbraid") && params.get("wbraid") !== "") { + props["wbraid"] = params.get("wbraid") || ""; + } + return props; +}; +var storageKey = "_dbeat"; +var getStorageVal = () => { + try { + return JSON.parse(window.localStorage.getItem(storageKey)); + } catch (err) { + return null; + } +}; +var setStorageVal = (val) => { + try { + if (!val.ts) { + val.ts = Math.floor(Date.now() / 1e3); } - var listeners = this._events[evt]; - if (listeners.fn) { - if (listeners.fn === fn && (!once || listeners.once) && (!context2 || listeners.context === context2)) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if (listeners[i].fn !== fn || once && !listeners[i].once || context2 && listeners[i].context !== context2) { - events.push(listeners[i]); - } - } - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); + window.localStorage.setItem(storageKey, JSON.stringify(val)); + return val.ts; + } catch (err) { + return; + } +}; +var genUserId = (seed, allowUserTracking, options) => { + if (!seed || seed === null || seed === "") { + const id2 = Math.floor(Math.random() * 1e14); + return { + userId: `${id2}`, + ident: 0 + /* ANON */ + }; + } + if (options.userIdentTracking && allowUserTracking) { + return { + userId: seed, + ident: 2 + /* USER */ + }; + } + if (options.privacy.userIdHash === true || !options.userIdentTracking || !allowUserTracking) { + if (isBrowser() && options.privacy.userAgentSalt === true) { + seed = seed + ":" + navigator.userAgent; } - return this; - }; - EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; + if (options.privacy.extraSalt && options.privacy.extraSalt.length > 0) { + seed = seed + ":" + options.privacy.extraSalt; } - return this; - }; - EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; - EventEmitter2.prototype.addListener = EventEmitter2.prototype.on; - EventEmitter2.prefixed = prefix; - EventEmitter2.EventEmitter = EventEmitter2; - { - module2.exports = EventEmitter2; + return { + userId: bytesToHex(sha256(seed)).substring(0, 50), + ident: 1 + /* PRIVATE */ + }; + } else { + throw new Error("invalid configuration"); } -})(eventemitter3); -var eventemitter3Exports = eventemitter3.exports; -const EventEmitter = /* @__PURE__ */ getDefaultExportFromCjs$1(eventemitter3Exports); -class Emitter { - constructor(uid2) { - Object.defineProperty(this, "uid", { - enumerable: true, - configurable: true, - writable: true, - value: uid2 - }); - Object.defineProperty(this, "_emitter", { - enumerable: true, - configurable: true, - writable: true, - value: new EventEmitter() - }); +}; +var genSessionId = () => { + const isSessionStorageAvail = isBrowser() && typeof window.sessionStorage === "object" && typeof window.sessionStorage.getItem === "function" && typeof window.sessionStorage.setItem === "function"; + if (!isSessionStorageAvail) { + return genRandHex(16); + } else { + const sid = window.sessionStorage.getItem(storageKey); + if (!!sid && sid.length > 0) { + return sid; + } else { + const sid2 = genRandHex(16); + window.sessionStorage.setItem(storageKey, sid2); + return sid2; + } } - on(eventName, fn) { - this._emitter.on(eventName, fn); +}; +var genRandHex = (n2) => { + let hexString = ""; + for (let i = 0; i < n2; i++) { + hexString += Math.floor(Math.random() * 16).toString(16); } - once(eventName, fn) { - this._emitter.once(eventName, fn); + return "0x" + hexString; +}; +if (typeof process$1 === "object" && process$1.version && process$1.version < "v18") { + console.error(`ERROR! expecting node v18+ but your node version is reporting ${process$1.version}`); + if (process$1 && process$1.exit) { + process$1.exit(1); } - off(eventName, fn) { - this._emitter.off(eventName, fn); +} +const PROHIBITED_FUNCTIONS = new Map(["addHook(bytes4,address)", "clearExtraImageHashes(bytes32[])", "removeHook(bytes4)", "setExtraImageHash(bytes32,uint256)", "updateIPFSRoot(bytes32)", "updateImageHash(bytes32)", "updateImageHashAndIPFS(bytes32,bytes32)", "updateImplementation(address)"].map((signature2) => [id$1(signature2).slice(0, 10), signature2])); +function validateTransactionRequest(wallet, transaction2) { + const transactions2 = index$1$1.transaction.fromTransactionish(wallet, transaction2); + const unwound = index$1$1.transaction.unwind(wallet, transactions2); + unwound.forEach((transaction22) => validateTransaction(wallet, transaction22)); +} +function validateTransaction(wallet, transaction2) { + if (transaction2.to.toLowerCase() === wallet.toLowerCase()) { + if (transaction2.data) { + const data = getBytes(transaction2.data); + if (data.length >= 4 && !isCreateContractCall(data)) { + throw new Error("self calls are forbidden"); + } + } } - emit(eventName, ...params) { - const data = params[0]; - this._emitter.emit(eventName, { uid: this.uid, ...data }); + if (transaction2.delegateCall) { + throw new Error("delegate calls are forbidden"); } - listenerCount(eventName) { - return this._emitter.listenerCount(eventName); + if (transaction2.data) { + const data = hexlify(transaction2.data); + const selector2 = data.slice(0, 10); + const signature2 = PROHIBITED_FUNCTIONS.get(selector2); + if (signature2) { + const name2 = signature2.slice(0, signature2.indexOf("(")); + throw new Error(`${name2} calls are forbidden`); + } } } -function createEmitter(uid2) { - return new Emitter(uid2); -} -function deserialize(value, reviver) { - return JSON.parse(value, (key, value_) => { - let value2 = value_; - if ((value2 == null ? void 0 : value2.__type) === "bigint") - value2 = BigInt(value2.value); - if ((value2 == null ? void 0 : value2.__type) === "Map") - value2 = new Map(value2.value); - return (reviver == null ? void 0 : reviver(key, value2)) ?? value2; - }); -} -function getReferenceKey(keys, cutoff) { - return keys.slice(0, cutoff).join(".") || "."; -} -function getCutoff(array, value) { - const { length } = array; - for (let index2 = 0; index2 < length; ++index2) { - if (array[index2] === value) { - return index2 + 1; - } +function isCreateContractCall(data) { + const walletInterface = new Interface(walletContracts.mainModule.abi); + try { + walletInterface.decodeFunctionData("createContract", data); + return true; + } catch (_unused) { + return false; } - return 0; } -function createReplacer(replacer, circularReplacer) { - const hasReplacer = typeof replacer === "function"; - const hasCircularReplacer = typeof circularReplacer === "function"; - const cache2 = []; - const keys = []; - return function replace(key, value) { - if (typeof value === "object") { - if (cache2.length) { - const thisCutoff = getCutoff(cache2, this); - if (thisCutoff === 0) { - cache2[cache2.length] = this; - } else { - cache2.splice(thisCutoff); - keys.splice(thisCutoff); - } - keys[keys.length] = key; - const valueCutoff = getCutoff(cache2, value); - if (valueCutoff !== 0) { - return hasCircularReplacer ? circularReplacer.call(this, key, value, getReferenceKey(keys, valueCutoff)) : `[ref=${getReferenceKey(keys, valueCutoff)}]`; +function _extends$2() { + _extends$2 = Object.assign ? Object.assign.bind() : function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; } - } else { - cache2[0] = value; - keys[0] = key; } } - return hasReplacer ? replacer.call(this, key, value) : value; + return target; }; + return _extends$2.apply(this, arguments); } -function serialize(value, replacer, indent, circularReplacer) { - return JSON.stringify(value, createReplacer((key, value_) => { - let value2 = value_; - if (typeof value2 === "bigint") - value2 = { __type: "bigint", value: value_.toString() }; - if (value2 instanceof Map) - value2 = { __type: "Map", value: Array.from(value_.entries()) }; - return (replacer == null ? void 0 : replacer(key, value2)) ?? value2; - }, circularReplacer), indent ?? void 0); +function isProviderTransport(transport) { + return transport && typeof transport === "object" && typeof transport.register === "function" && typeof transport.unregister === "function" && typeof transport.openWallet === "function" && typeof transport.closeWallet === "function" && typeof transport.isOpened === "function" && typeof transport.isConnected === "function" && typeof transport.on === "function"; } -function createStorage(parameters) { - const { deserialize: deserialize$1 = deserialize, key: prefix = "wagmi", serialize: serialize$1 = serialize, storage = noopStorage } = parameters; - function unwrap2(value) { - if (value instanceof Promise) - return value.then((x2) => x2).catch(() => null); - return value; +class WindowSessionParams extends URLSearchParams { + static new(init2) { + return new URLSearchParams(init2); } - return { - ...storage, - key: prefix, - async getItem(key, defaultValue) { - const value = storage.getItem(`${prefix}.${key}`); - const unwrapped = await unwrap2(value); - if (unwrapped) - return deserialize$1(unwrapped) ?? null; - return defaultValue ?? null; - }, - async setItem(key, value) { - const storageKey2 = `${prefix}.${key}`; - if (value === null) - await unwrap2(storage.removeItem(storageKey2)); - else - await unwrap2(storage.setItem(storageKey2, serialize$1(value))); - }, - async removeItem(key) { - await unwrap2(storage.removeItem(`${prefix}.${key}`)); - } - }; } -const noopStorage = { - getItem: () => null, - setItem: () => { - }, - removeItem: () => { - } -}; -const size$3 = 256; -let index$1 = size$3; -let buffer; -function uid(length = 11) { - if (!buffer || index$1 + length > size$3 * 2) { - buffer = ""; - index$1 = 0; - for (let i = 0; i < size$3; i++) { - buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1); - } +let EventType = /* @__PURE__ */ function(EventType2) { + EventType2["OPEN"] = "open"; + EventType2["CLOSE"] = "close"; + EventType2["MESSAGE"] = "message"; + EventType2["CONNECT"] = "connect"; + EventType2["DISCONNECT"] = "disconnect"; + EventType2["ACCOUNTS_CHANGED"] = "accountsChanged"; + EventType2["CHAIN_CHANGED"] = "chainChanged"; + EventType2["NETWORKS"] = "networks"; + EventType2["WALLET_CONTEXT"] = "walletContext"; + EventType2["INIT"] = "init"; + EventType2["DEBUG"] = "_debug"; + return EventType2; +}({}); +let OpenState = /* @__PURE__ */ function(OpenState2) { + OpenState2[OpenState2["CLOSED"] = 0] = "CLOSED"; + OpenState2[OpenState2["OPENING"] = 1] = "OPENING"; + OpenState2[OpenState2["OPENED"] = 2] = "OPENED"; + return OpenState2; +}({}); +let InitState = /* @__PURE__ */ function(InitState2) { + InitState2[InitState2["NIL"] = 0] = "NIL"; + InitState2[InitState2["SENT_NONCE"] = 1] = "SENT_NONCE"; + InitState2[InitState2["OK"] = 2] = "OK"; + return InitState2; +}({}); +class ProviderError extends Error { + constructor(message) { + super(message); + this.name = "ProviderError"; } - return buffer.substring(index$1, index$1++ + length); } -function createConfig(parameters) { - const { multiInjectedProviderDiscovery = true, storage = createStorage({ - storage: typeof window !== "undefined" && window.localStorage ? window.localStorage : noopStorage - }), syncConnectedChain = true, ssr = false, ...rest } = parameters; - const mipd = typeof window !== "undefined" && multiInjectedProviderDiscovery ? createStore$1() : void 0; - const chains2 = createStore(() => rest.chains); - const connectors = createStore(() => [ - ...rest.connectors ?? [], - ...!ssr ? (mipd == null ? void 0 : mipd.getProviders().map(providerDetailToConnector)) ?? [] : [] - ].map(setup)); - function setup(connectorFn) { - var _a2; - const emitter = createEmitter(uid()); - const connector = { - ...connectorFn({ - emitter, - chains: chains2.getState(), - storage, - transports: rest.transports - }), - emitter, - uid: emitter.uid +const ErrSignedInRequired = new ProviderError("Wallet is not signed in. Connect a wallet and try again."); +const PROVIDER_OPEN_TIMEOUT = 3e4; +let _messageIdx = 0; +const nextMessageIdx = () => ++_messageIdx; +class BaseProviderTransport { + constructor() { + var _this = this; + this.pendingMessageRequests = []; + this.responseCallbacks = /* @__PURE__ */ new Map(); + this.state = void 0; + this.confirmationOnly = false; + this.events = new eventemitter2Exports.EventEmitter2(); + this.openPayload = void 0; + this.connectPayload = void 0; + this.accountsChangedPayload = void 0; + this.networksPayload = void 0; + this.walletContextPayload = void 0; + this._sessionId = void 0; + this._init = void 0; + this._registered = void 0; + this.sendMessageRequest = async function(message) { + return new Promise((resolve, reject) => { + if ((!message.idx || message.idx <= 0) && message.type !== "init") { + reject(new Error("message idx not set")); + } + const responseCallback = (error, response) => { + if (error) { + reject(error); + } else if (response) { + resolve(response); + } else { + throw new Error("no valid response to return"); + } + }; + const idx = message.idx; + if (!_this.responseCallbacks.get(idx)) { + _this.responseCallbacks.set(idx, responseCallback); + } else { + reject(new Error("duplicate message idx, should never happen")); + } + if (!_this.isOpened()) { + logger.debug("pushing to pending requests", message); + _this.pendingMessageRequests.push(message); + } else { + _this.sendMessage(message); + } + }); }; - emitter.on("connect", connect2); - (_a2 = connector.setup) == null ? void 0 : _a2.call(connector); - return connector; - } - function providerDetailToConnector(providerDetail) { - const { info } = providerDetail; - const provider2 = providerDetail.provider; - return injected({ target: { ...info, id: info.rdns, provider: provider2 } }); - } - const clients = /* @__PURE__ */ new Map(); - function getClient2(config2 = {}) { - const chainId = config2.chainId ?? store.getState().chainId; - const chain = chains2.getState().find((x2) => x2.id === chainId); - if (config2.chainId && !chain) - throw new ChainNotConfiguredError(); - { - const client3 = clients.get(store.getState().chainId); - if (client3 && !chain) - return client3; - if (!chain) - throw new ChainNotConfiguredError(); - } - { - const client3 = clients.get(chainId); - if (client3) - return client3; - } - let client2; - if (rest.client) - client2 = rest.client({ chain }); - else { - const chainId2 = chain.id; - const chainIds = chains2.getState().map((x2) => x2.id); - const properties = {}; - const entries = Object.entries(rest); - for (const [key, value] of entries) { - if (key === "chains" || key === "client" || key === "connectors" || key === "transports") - continue; - if (typeof value === "object") { - if (chainId2 in value) - properties[key] = value[chainId2]; - else { - const hasChainSpecificValue = chainIds.some((x2) => x2 in value); - if (hasChainSpecificValue) - continue; - properties[key] = value; + this.waitUntilOpened = async function(openTimeout = PROVIDER_OPEN_TIMEOUT) { + let opened = false; + return Promise.race([new Promise((_, reject) => { + const timeout = setTimeout(() => { + clearTimeout(timeout); + if (!opened) { + _this.state = OpenState.CLOSED; + _this.events.emit("close", { + code: 1005, + message: "opening wallet timed out" + }); } - } else - properties[key] = value; - } - client2 = createClient({ - ...properties, - chain, - batch: properties.batch ?? { multicall: true }, - transport: (parameters2) => rest.transports[chainId2]({ ...parameters2, connectors }) + reject(new Error("opening wallet timed out")); + }, openTimeout); + }), new Promise((resolve) => { + if (_this.isOpened()) { + var _this$openPayload; + opened = true; + resolve((_this$openPayload = _this.openPayload) == null ? void 0 : _this$openPayload.session); + return; + } + _this.events.once("open", (openInfo) => { + _this.openPayload = openInfo; + opened = true; + resolve(openInfo.session); + }); + })]); + }; + this.waitUntilConnected = async function() { + await _this.waitUntilOpened(); + const connect2 = new Promise((resolve) => { + if (_this.connectPayload) { + resolve(_this.connectPayload); + return; + } + _this.events.once("connect", (connectDetails) => { + _this.connectPayload = connectDetails; + resolve(connectDetails); + }); }); - } - clients.set(chainId, client2); - return client2; - } - function getInitialState() { - return { - chainId: chains2.getState()[0].id, - connections: /* @__PURE__ */ new Map(), - current: null, - status: "disconnected" + const closeWallet = new Promise((_, reject) => { + _this.events.once("close", (error) => { + if (error) { + reject(new Error(`wallet closed due to ${JSON.stringify(error)}`)); + } else { + reject(new Error(`user closed the wallet`)); + } + }); + }); + return Promise.race([connect2, closeWallet]); }; + this.state = OpenState.CLOSED; + this._registered = false; + this._init = InitState.NIL; } - let currentVersion; - const prefix = "0.0.0-canary-"; - if (version$3.startsWith(prefix)) - currentVersion = Number.parseInt(version$3.replace(prefix, "")); - else - currentVersion = Number.parseInt(version$3.split(".")[0] ?? "0"); - const store = createStore(subscribeWithSelector( - // only use persist middleware if storage exists - storage ? persist(getInitialState, { - migrate(persistedState, version2) { - if (version2 === currentVersion) - return persistedState; - const initialState = getInitialState(); - const chainId = validatePersistedChainId(persistedState, initialState.chainId); - return { ...initialState, chainId }; - }, - name: "store", - partialize(state) { - return { - connections: { - __type: "Map", - value: Array.from(state.connections.entries()).map(([key, connection]) => { - const { id: id2, name: name2, type, uid: uid2 } = connection.connector; - const connector = { id: id2, name: name2, type, uid: uid2 }; - return [key, { ...connection, connector }]; - }) - }, - chainId: state.chainId, - current: state.current - }; - }, - merge(persistedState, currentState) { - if (typeof persistedState === "object" && persistedState && "status" in persistedState) - delete persistedState.status; - const chainId = validatePersistedChainId(persistedState, currentState.chainId); - return { - ...currentState, - ...persistedState, - chainId - }; - }, - skipHydration: ssr, - storage, - version: currentVersion - }) : getInitialState - )); - function validatePersistedChainId(persistedState, defaultChainId) { - return persistedState && typeof persistedState === "object" && "chainId" in persistedState && typeof persistedState.chainId === "number" && chains2.getState().some((x2) => x2.id === persistedState.chainId) ? persistedState.chainId : defaultChainId; + get registered() { + return this._registered; } - if (syncConnectedChain) - store.subscribe(({ connections, current }) => { - var _a2; - return current ? (_a2 = connections.get(current)) == null ? void 0 : _a2.chainId : void 0; - }, (chainId) => { - const isChainConfigured = chains2.getState().some((x2) => x2.id === chainId); - if (!isChainConfigured) - return; - return store.setState((x2) => ({ - ...x2, - chainId: chainId ?? x2.chainId - })); - }); - mipd == null ? void 0 : mipd.subscribe((providerDetails) => { - const currentConnectorIds = /* @__PURE__ */ new Map(); - for (const connector of connectors.getState()) { - currentConnectorIds.set(connector.id, true); - } - const newConnectors = []; - for (const providerDetail of providerDetails) { - const connector = setup(providerDetailToConnector(providerDetail)); - if (currentConnectorIds.has(connector.id)) - continue; - newConnectors.push(connector); - } - if (storage && !store.persist.hasHydrated()) - return; - connectors.setState((x2) => [...x2, ...newConnectors], true); - }); - function change(data) { - store.setState((x2) => { - const connection = x2.connections.get(data.uid); - if (!connection) - return x2; - return { - ...x2, - connections: new Map(x2.connections).set(data.uid, { - accounts: data.accounts ?? connection.accounts, - chainId: data.chainId ?? connection.chainId, - connector: connection.connector - }) - }; - }); + register() { + throw new Error("abstract method"); } - function connect2(data) { - if (store.getState().status === "connecting" || store.getState().status === "reconnecting") - return; - store.setState((x2) => { - const connector = connectors.getState().find((x3) => x3.uid === data.uid); - if (!connector) - return x2; - if (connector.emitter.listenerCount("connect")) - connector.emitter.off("connect", change); - if (!connector.emitter.listenerCount("change")) - connector.emitter.on("change", change); - if (!connector.emitter.listenerCount("disconnect")) - connector.emitter.on("disconnect", disconnect2); - return { - ...x2, - connections: new Map(x2.connections).set(data.uid, { - accounts: data.accounts, - chainId: data.chainId, - connector - }), - current: data.uid, - status: "connected" - }; - }); + unregister() { + throw new Error("abstract method"); } - function disconnect2(data) { - store.setState((x2) => { - const connection = x2.connections.get(data.uid); - if (connection) { - const connector = connection.connector; - if (connector.emitter.listenerCount("change")) - connection.connector.emitter.off("change", change); - if (connector.emitter.listenerCount("disconnect")) - connection.connector.emitter.off("disconnect", disconnect2); - if (!connector.emitter.listenerCount("connect")) - connection.connector.emitter.on("connect", connect2); - } - x2.connections.delete(data.uid); - if (x2.connections.size === 0) - return { - ...x2, - connections: /* @__PURE__ */ new Map(), - current: null, - status: "disconnected" - }; - const nextConnection = x2.connections.values().next().value; - return { - ...x2, - connections: new Map(x2.connections), - current: nextConnection.connector.uid - }; + openWallet(path, intent, networkId) { + throw new Error("abstract method"); + } + closeWallet() { + throw new Error("abstract method"); + } + isOpened() { + return this.registered && this.state === OpenState.OPENED; + } + isConnected() { + var _this$openPayload2; + const session = (_this$openPayload2 = this.openPayload) == null ? void 0 : _this$openPayload2.session; + return this.registered && session !== void 0 && !!session.accountAddress && session.accountAddress.length === 42 && !!session.networks && session.networks.length > 0; + } + async request(request) { + if (this.state === OpenState.CLOSED) { + this.confirmationOnly = true; + } + this.openWallet(void 0, { + type: "jsonRpcRequest", + method: request.method + }, request.chainId); + if (!this.isOpened()) { + await this.waitUntilOpened(); + } + const response = await this.sendMessageRequest({ + idx: nextMessageIdx(), + type: EventType.MESSAGE, + data: request, + chainId: request.chainId, + clientVersion: VERSION$1 }); + return response.data; } - return { - get chains() { - return chains2.getState(); - }, - get connectors() { - return connectors.getState(); - }, - storage, - getClient: getClient2, - get state() { - return store.getState(); - }, - setState(value) { - let newState; - if (typeof value === "function") - newState = value(store.getState()); - else - newState = value; - const initialState = getInitialState(); - if (typeof newState !== "object") - newState = initialState; - const isCorrupt = Object.keys(initialState).some((x2) => !(x2 in newState)); - if (isCorrupt) - newState = initialState; - store.setState(newState, true); - }, - subscribe(selector2, listener, options) { - return store.subscribe(selector2, listener, options ? { - ...options, - fireImmediately: options.emitImmediately - // Workaround cast since Zustand does not support `'exactOptionalPropertyTypes'` - } : void 0); - }, - _internal: { - mipd, - store, - ssr: Boolean(ssr), - syncConnectedChain, - transports: rest.transports, - chains: { - setState(value) { - const nextChains = typeof value === "function" ? value(chains2.getState()) : value; - if (nextChains.length === 0) - return; - return chains2.setState(nextChains, true); - }, - subscribe(listener) { - return chains2.subscribe(listener); - } - }, - connectors: { - providerDetailToConnector, - setup, - setState(value) { - return connectors.setState(typeof value === "function" ? value(connectors.getState()) : value, true); + // handleMessage will handle message received from the remote wallet + handleMessage(message) { + var _this2 = this; + if (message.type === EventType.INIT) { + logger.debug("MessageProvider, received INIT message", message); + const { + nonce + } = message.data; + if (!nonce || nonce.length == 0) { + logger.error("invalid init nonce"); + return; + } + this._init = InitState.OK; + this.sendMessage({ + idx: -1, + type: EventType.INIT, + data: { + sessionId: this._sessionId, + nonce }, - subscribe(listener) { - return connectors.subscribe(listener); - } - }, - events: { change, connect: connect2, disconnect: disconnect2 } + clientVersion: VERSION$1 + }); } - }; -} -function hydrate(config2, parameters) { - const { initialState, reconnectOnMount } = parameters; - if (initialState && !config2._internal.store.persist.hasHydrated()) - config2.setState({ - ...initialState, - chainId: config2.chains.some((x2) => x2.id === initialState.chainId) ? initialState.chainId : config2.chains[0].id, - connections: reconnectOnMount ? initialState.connections : /* @__PURE__ */ new Map(), - status: reconnectOnMount ? "reconnecting" : "disconnected" - }); - return { - async onMount() { - var _a2; - if (config2._internal.ssr) { - await config2._internal.store.persist.rehydrate(); - const mipdConnectors = (_a2 = config2._internal.mipd) == null ? void 0 : _a2.getProviders().map(config2._internal.connectors.providerDetailToConnector).map(config2._internal.connectors.setup); - config2._internal.connectors.setState((connectors) => [ - ...connectors, - ...mipdConnectors ?? [] - ]); + if (this._init !== InitState.OK) { + return; + } + logger.debug("RECEIVED MESSAGE FROM WALLET", message.idx, message); + const requestIdx = message.idx; + const responseCallback = this.responseCallbacks.get(requestIdx); + if (requestIdx) { + this.responseCallbacks.delete(requestIdx); + } + if (message.type === EventType.OPEN && !this.isOpened()) { + var _message$data, _message$data2; + if (this._sessionId && this._sessionId !== ((_message$data = message.data) == null ? void 0 : _message$data.sessionId)) { + logger.debug("open event received from wallet, but does not match sessionId", this._sessionId); + return; } - if (reconnectOnMount) - reconnect(config2); - else if (config2.storage) - config2.setState((x2) => ({ - ...x2, - connections: /* @__PURE__ */ new Map() - })); + if ((_message$data2 = message.data) != null && _message$data2.error) { + var _message$data3; + const err = new Error(`opening wallet failed: received ${(_message$data3 = message.data) == null ? void 0 : _message$data3.error}`); + logger.error(err); + this.close(); + throw err; + } + this.state = OpenState.OPENED; + this.openPayload = message.data; + this.events.emit("open", this.openPayload); + if (this.pendingMessageRequests.length !== 0) { + const pendingMessageRequests = this.pendingMessageRequests.splice(0, this.pendingMessageRequests.length); + pendingMessageRequests.forEach(async function(pendingMessageRequest) { + _this2.sendMessage(pendingMessageRequest); + }); + } + return; } - }; -} -function extractRpcUrls(parameters) { - var _a2, _b2, _c2; - const { chain } = parameters; - const fallbackUrl = chain.rpcUrls.default.http[0]; - if (!parameters.transports) - return [fallbackUrl]; - const transport = (_b2 = (_a2 = parameters.transports) == null ? void 0 : _a2[chain.id]) == null ? void 0 : _b2.call(_a2, { chain }); - const transports2 = ((_c2 = transport == null ? void 0 : transport.value) == null ? void 0 : _c2.transports) || [transport]; - return transports2.map(({ value }) => (value == null ? void 0 : value.url) || fallbackUrl); -} -function Hydrate(parameters) { - const { children, config: config2, initialState, reconnectOnMount = true } = parameters; - const { onMount } = hydrate(config2, { - initialState, - reconnectOnMount - }); - if (!config2._internal.ssr) - onMount(); - const active = reactExports.useRef(true); - reactExports.useEffect(() => { - if (!active.current) + if (message.type === EventType.MESSAGE) { + if (this.confirmationOnly) { + setTimeout(() => { + if (this.responseCallbacks.size === 0) { + this.closeWallet(); + } + }, 500); + } + if (!responseCallback) { + throw new Error("impossible state"); + } + if (responseCallback) { + this.events.emit("message", message); + responseCallback(message.data.error, message); + return; + } + } + if (message.type === EventType.ACCOUNTS_CHANGED) { + this.accountsChangedPayload = { + accounts: [] + }; + if (message.data && message.data.length > 0) { + this.accountsChangedPayload = { + accounts: [getAddress(message.data[0])], + origin: message.origin + }; + this.events.emit("accountsChanged", this.accountsChangedPayload.accounts, this.accountsChangedPayload.origin); + } else { + this.events.emit("accountsChanged", [], message.origin); + } return; - if (!config2._internal.ssr) + } + if (message.type === EventType.CHAIN_CHANGED) { + this.events.emit("chainChanged", message.data, message.origin); return; - onMount(); - return () => { - active.current = false; - }; - }, []); - return children; -} -const WagmiContext = reactExports.createContext(void 0); -function WagmiProvider(parameters) { - const { children, config: config2 } = parameters; - const props = { value: config2 }; - return reactExports.createElement(Hydrate, parameters, reactExports.createElement(WagmiContext.Provider, props, children)); -} -const version$2 = "2.12.12"; -const getVersion = () => `wagmi@${version$2}`; -class BaseError4 extends BaseError$1 { - constructor() { - super(...arguments); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "WagmiError" - }); + } + if (message.type === EventType.NETWORKS) { + this.networksPayload = message.data; + this.events.emit("networks", this.networksPayload); + return; + } + if (message.type === EventType.WALLET_CONTEXT) { + this.walletContextPayload = message.data; + this.events.emit("walletContext", this.walletContextPayload); + return; + } + if (message.type === EventType.CLOSE) { + if (this.state !== OpenState.CLOSED) { + this.close(message.data); + } + } + if (message.type === EventType.CONNECT) { + this.connectPayload = message.data; + this.events.emit("connect", this.connectPayload); + } + if (message.type === EventType.DISCONNECT) { + if (this.isConnected()) { + this.events.emit("disconnect", message.data, message.origin); + this.close(); + } + } } - get docsBaseUrl() { - return "https://wagmi.sh/react"; + sendMessage(message) { + throw new Error("abstract method"); } - get version() { - return getVersion(); + on(event, fn) { + this.events.on(event, fn); } -} -class WagmiProviderNotFoundError extends BaseError4 { - constructor() { - super("`useConfig` must be used within `WagmiProvider`.", { - docsPath: "/api/WagmiProvider" - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "WagmiProviderNotFoundError" + once(event, fn) { + this.events.once(event, fn); + } + emit(event, ...args) { + return this.events.emit(event, ...args); + } + close(error) { + if (this.state === OpenState.CLOSED) return; + this.state = OpenState.CLOSED; + this.confirmationOnly = false; + this._sessionId = void 0; + logger.info("closing wallet and flushing!"); + this.pendingMessageRequests.length = 0; + this.responseCallbacks.forEach((responseCallback) => { + responseCallback(_extends$2({}, new Error("wallet closed"), { + code: 4001 + })); }); + this.responseCallbacks.clear(); + this.connectPayload = void 0; + this.openPayload = void 0; + this.accountsChangedPayload = void 0; + this.networksPayload = void 0; + this.walletContextPayload = void 0; + this.events.emit("close", error); } } -function useConfig(parameters = {}) { - const config2 = parameters.config ?? reactExports.useContext(WagmiContext); - if (!config2) - throw new WagmiProviderNotFoundError(); - return config2; -} -function watchChains(config2, parameters) { - const { onChange } = parameters; - return config2._internal.chains.subscribe((chains2, prevChains) => { - onChange(chains2, prevChains); - }); -} -var withSelector = { exports: {} }; -var withSelector_production_min = {}; -var shim = { exports: {} }; -var useSyncExternalStoreShim_production_min = {}; -/** - * @license React - * use-sync-external-store-shim.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -var e$1 = reactExports; -function h$2(a2, b2) { - return a2 === b2 && (0 !== a2 || 1 / a2 === 1 / b2) || a2 !== a2 && b2 !== b2; -} -var k$1 = "function" === typeof Object.is ? Object.is : h$2, l$1 = e$1.useState, m$1 = e$1.useEffect, n$2 = e$1.useLayoutEffect, p$2 = e$1.useDebugValue; -function q$2(a2, b2) { - var d2 = b2(), f2 = l$1({ inst: { value: d2, getSnapshot: b2 } }), c2 = f2[0].inst, g2 = f2[1]; - n$2(function() { - c2.value = d2; - c2.getSnapshot = b2; - r$2(c2) && g2({ inst: c2 }); - }, [a2, d2, b2]); - m$1(function() { - r$2(c2) && g2({ inst: c2 }); - return a2(function() { - r$2(c2) && g2({ inst: c2 }); - }); - }, [a2]); - p$2(d2); - return d2; +function messageIsExemptFromEIP191Prefix(message) { + return EIP_191_PREFIX_EXCEPTIONS.some((e2) => e2.predicate(message)); } -function r$2(a2) { - var b2 = a2.getSnapshot; - a2 = a2.value; +const EIP_191_PREFIX_EXCEPTIONS = [ + // NOTE: Decentraland does not support 191 correctly. + { + name: "Decentraland Exception", + predicate: isDecentralandLoginMessage + }, + // NOTE: 0x v3 does not support 191 correctly. + // See https://gov.0x.org/t/zeip-proposal-fix-v3-eip-191-non-compliance-when-validating-eip-1271-signatures/3396 for more info. + { + name: "0x v3 Exception", + predicate: isZeroExV3Order + } +]; +const DCL_REGEX = /^Decentraland Login\nEphemeral address: 0x[a-fA-F0-9]{40}\nExpiration: (\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)((-(\d{2}):(\d{2})|Z)?)$/; +function isDecentralandLoginMessage(bytes2) { try { - var d2 = b2(); - return !k$1(a2, d2); - } catch (f2) { - return true; + const stringified = toUtf8String(bytes2); + return DCL_REGEX.test(stringified); + } catch (_unused) { + return false; } } -function t$2(a2, b2) { - return b2(); -} -var u$2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? t$2 : q$2; -useSyncExternalStoreShim_production_min.useSyncExternalStore = void 0 !== e$1.useSyncExternalStore ? e$1.useSyncExternalStore : u$2; -{ - shim.exports = useSyncExternalStoreShim_production_min; -} -var shimExports = shim.exports; -/** - * @license React - * use-sync-external-store-shim/with-selector.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -var h$1 = reactExports, n$1 = shimExports; -function p$1(a2, b2) { - return a2 === b2 && (0 !== a2 || 1 / a2 === 1 / b2) || a2 !== a2 && b2 !== b2; -} -var q$1 = "function" === typeof Object.is ? Object.is : p$1, r$1 = n$1.useSyncExternalStore, t$1 = h$1.useRef, u$1 = h$1.useEffect, v$1 = h$1.useMemo, w = h$1.useDebugValue; -withSelector_production_min.useSyncExternalStoreWithSelector = function(a2, b2, e2, l2, g2) { - var c2 = t$1(null); - if (null === c2.current) { - var f2 = { hasValue: false, value: null }; - c2.current = f2; - } else f2 = c2.current; - c2 = v$1(function() { - function a3(a4) { - if (!c3) { - c3 = true; - d3 = a4; - a4 = l2(a4); - if (void 0 !== g2 && f2.hasValue) { - var b3 = f2.value; - if (g2(b3, a4)) return k2 = b3; - } - return k2 = a4; - } - b3 = k2; - if (q$1(d3, a4)) return b3; - var e3 = l2(a4); - if (void 0 !== g2 && g2(b3, e3)) return b3; - d3 = a4; - return k2 = e3; - } - var c3 = false, d3, k2, m2 = void 0 === e2 ? null : e2; - return [function() { - return a3(b2()); - }, null === m2 ? void 0 : function() { - return a3(m2()); - }]; - }, [b2, e2, l2, g2]); - var d2 = r$1(a2, c2[0], c2[1]); - u$1(function() { - f2.hasValue = true; - f2.value = d2; - }, [d2]); - w(d2); - return d2; -}; -{ - withSelector.exports = withSelector_production_min; -} -var withSelectorExports = withSelector.exports; -const isPlainObject$2 = (obj) => typeof obj === "object" && !Array.isArray(obj); -function useSyncExternalStoreWithTracked(subscribe, getSnapshot, getServerSnapshot = getSnapshot, isEqual = deepEqual$1) { - const trackedKeys = reactExports.useRef([]); - const result = withSelectorExports.useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, (x2) => x2, (a2, b2) => { - if (isPlainObject$2(a2) && isPlainObject$2(b2) && trackedKeys.current.length) { - for (const key of trackedKeys.current) { - const equal = isEqual(a2[key], b2[key]); - if (!equal) - return false; - } - return true; - } - return isEqual(a2, b2); - }); - if (isPlainObject$2(result)) { - const trackedResult = { ...result }; - let properties = {}; - for (const [key, value] of Object.entries(trackedResult)) { - properties = { - ...properties, - [key]: { - configurable: false, - enumerable: true, - get: () => { - if (!trackedKeys.current.includes(key)) { - trackedKeys.current.push(key); - } - return value; - } - } - }; - } - Object.defineProperties(trackedResult, properties); - return trackedResult; +function isZeroExV3Order(bytes2) { + const abi2 = new Interface(ZeroXV3EIP1271OrderWithHashAbi); + try { + abi2.decodeFunctionData("OrderWithHash", bytes2); + return true; + } catch (err) { + return false; } - return result; -} -function useAccount(parameters = {}) { - const config2 = useConfig(parameters); - return useSyncExternalStoreWithTracked((onChange) => watchAccount(config2, { onChange }), () => getAccount(config2)); } -var Subscribable = class { - constructor() { - this.listeners = /* @__PURE__ */ new Set(); - this.subscribe = this.subscribe.bind(this); +const ZeroXV3EIP1271OrderWithHashAbi = [{ + inputs: [{ + components: [{ + internalType: "address", + name: "makerAddress", + type: "address" + }, { + internalType: "address", + name: "takerAddress", + type: "address" + }, { + internalType: "address", + name: "feeRecipientAddress", + type: "address" + }, { + internalType: "address", + name: "senderAddress", + type: "address" + }, { + internalType: "uint256", + name: "makerAssetAmount", + type: "uint256" + }, { + internalType: "uint256", + name: "takerAssetAmount", + type: "uint256" + }, { + internalType: "uint256", + name: "makerFee", + type: "uint256" + }, { + internalType: "uint256", + name: "takerFee", + type: "uint256" + }, { + internalType: "uint256", + name: "expirationTimeSeconds", + type: "uint256" + }, { + internalType: "uint256", + name: "salt", + type: "uint256" + }, { + internalType: "bytes", + name: "makerAssetData", + type: "bytes" + }, { + internalType: "bytes", + name: "takerAssetData", + type: "bytes" + }, { + internalType: "bytes", + name: "makerFeeAssetData", + type: "bytes" + }, { + internalType: "bytes", + name: "takerFeeAssetData", + type: "bytes" + }], + internalType: "struct IEIP1271Data.Order", + name: "order", + type: "tuple" + }, { + internalType: "bytes32", + name: "orderHash", + type: "bytes32" + }], + name: "OrderWithHash", + outputs: [], + stateMutability: "pure", + type: "function" +}]; +const eip191prefix = toUtf8Bytes("Ethereum Signed Message:\n"); +const messageToBytes = (message) => { + if (isBytesLike(message)) { + return getBytes(message); } - subscribe(listener) { - this.listeners.add(listener); - this.onSubscribe(); - return () => { - this.listeners.delete(listener); - this.onUnsubscribe(); - }; + return toUtf8Bytes(message); +}; +const prefixEIP191Message = (message) => { + const messageBytes = messageToBytes(message); + if (messageIsExemptFromEIP191Prefix(messageBytes)) { + return messageBytes; + } else { + return getBytes(concat([eip191prefix, toUtf8Bytes(String(messageBytes.length)), messageBytes])); } - hasListeners() { - return this.listeners.size > 0; +}; +const trimEIP191Prefix = (prefixedMessage) => { + if (JSON.stringify(prefixedMessage.slice(0, eip191prefix.length)) !== JSON.stringify(eip191prefix)) { + return prefixedMessage; } - onSubscribe() { + const ethereumSignedMessagePartSlicedArray = prefixedMessage.slice(eip191prefix.length); + const maxPrefixCharLength = String(ethereumSignedMessagePartSlicedArray.length).length; + let prefixCharLenght; + let prefixAsNumber; + try { + prefixAsNumber = Number(toUtf8String(ethereumSignedMessagePartSlicedArray.slice(0, maxPrefixCharLength))); + } catch (_unused) { + prefixAsNumber = Number(hexlify(ethereumSignedMessagePartSlicedArray.slice(0, maxPrefixCharLength))); } - onUnsubscribe() { + if (prefixAsNumber > ethereumSignedMessagePartSlicedArray.length || !Number.isInteger(prefixAsNumber)) { + prefixCharLenght = maxPrefixCharLength - 1; + } else { + prefixCharLenght = maxPrefixCharLength; } + const prefixRevertedMessage = ethereumSignedMessagePartSlicedArray.slice(prefixCharLenght); + return prefixRevertedMessage; }; -var isServer = typeof window === "undefined" || "Deno" in globalThis; -function noop$1() { - return void 0; -} -function functionalUpdate(updater, input2) { - return typeof updater === "function" ? updater(input2) : updater; -} -function isValidTimeout(value) { - return typeof value === "number" && value >= 0 && value !== Infinity; -} -function timeUntilStale(updatedAt, staleTime) { - return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0); -} -function resolveStaleTime(staleTime, query) { - return typeof staleTime === "function" ? staleTime(query) : staleTime; -} -function resolveEnabled(enabled, query) { - return typeof enabled === "function" ? enabled(query) : enabled; -} -function matchQuery(filters, query) { - const { - type = "all", - exact, - fetchStatus, - predicate, - queryKey, - stale - } = filters; - if (queryKey) { - if (exact) { - if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) { - return false; - } - } else if (!partialMatchKey(query.queryKey, queryKey)) { - return false; - } +const isValidSignature = async (address, digest, sig, provider2) => { + const reader2 = new index$1$1.reader.OnChainReader(provider2); + return reader2.isValidSignature(address, digest, sig); +}; +const isValidMessageSignature = async (address, message, signature2, provider2) => { + const prefixed = prefixEIP191Message(message); + const digest = encodeMessageDigest(prefixed); + return isValidSignature(address, digest, signature2, provider2); +}; +const isValidTypedDataSignature = (address, typedData, signature2, provider2) => { + return isValidSignature(address, encodeTypedDataDigest(typedData), signature2, provider2); +}; +const isBrowserExtension = () => window.location.protocol === "chrome-extension:" || window.location.protocol === "moz-extension:"; +const isUnityPlugin = () => !!navigator.userAgent.match(/UnitySequence/i); +const isWalletUpToDate = (status) => { + return status.onChain.deployed && status.fullyMigrated; +}; +class MemoryItemStore { + constructor() { + this.callbacks = []; + this.store = {}; } - if (type !== "all") { - const isActive = query.isActive(); - if (type === "active" && !isActive) { - return false; - } - if (type === "inactive" && isActive) { - return false; - } + getItem(key) { + return this.store[key] || null; } - if (typeof stale === "boolean" && query.isStale() !== stale) { - return false; + setItem(key, value) { + this.store[key] = value; + this.callbacks.filter((c2) => c2.key === key).forEach((c2) => c2.cb(value)); } - if (fetchStatus && fetchStatus !== query.state.fetchStatus) { - return false; + removeItem(key) { + delete this.store[key]; } - if (predicate && !predicate(query)) { - return false; + onItemChange(key, cb2) { + this.callbacks.push({ + key, + cb: cb2 + }); + return () => { + this.callbacks = this.callbacks.filter((c2) => c2.cb !== cb2); + }; } - return true; } -function matchMutation(filters, mutation) { - const { exact, status, predicate, mutationKey } = filters; - if (mutationKey) { - if (!mutation.options.mutationKey) { - return false; - } - if (exact) { - if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) { - return false; - } - } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) { - return false; +class LocalStorage { + static isAvailable() { + return typeof window === "object" && typeof window.localStorage === "object"; + } + constructor() { + this.callbacks = []; + if (!LocalStorage.isAvailable()) { + throw new Error("LocalStorage is not available"); } + window.addEventListener("storage", (e2) => { + const { + key + } = e2; + const cb2 = this.callbacks.filter((c2) => c2.key === key); + cb2.forEach((c2) => c2.cb(this.getItem(key))); + }); } - if (status && mutation.state.status !== status) { - return false; + getItem(key) { + return window.localStorage.getItem(key); } - if (predicate && !predicate(mutation)) { - return false; + setItem(key, value) { + window.localStorage.setItem(key, value); + this.callbacks.filter((c2) => c2.key === key).forEach((c2) => c2.cb(value)); } - return true; -} -function hashQueryKeyByOptions(queryKey, options) { - const hashFn2 = (options == null ? void 0 : options.queryKeyHashFn) || hashKey; - return hashFn2(queryKey); -} -function hashKey(queryKey) { - return JSON.stringify( - queryKey, - (_, val) => isPlainObject$1(val) ? Object.keys(val).sort().reduce((result, key) => { - result[key] = val[key]; - return result; - }, {}) : val - ); -} -function partialMatchKey(a2, b2) { - if (a2 === b2) { - return true; + removeItem(key) { + window.localStorage.removeItem(key); + this.callbacks.filter((c2) => c2.key === key).forEach((c2) => c2.cb(null)); } - if (typeof a2 !== typeof b2) { - return false; + onItemChange(key, cb2) { + this.callbacks.push({ + key, + cb: cb2 + }); + return () => { + this.callbacks = this.callbacks.filter((c2) => c2.cb !== cb2); + }; } - if (a2 && b2 && typeof a2 === "object" && typeof b2 === "object") { - return !Object.keys(b2).some((key) => !partialMatchKey(a2[key], b2[key])); +} +function useBestStore() { + if (LocalStorage.isAvailable()) { + return new LocalStorage(); } - return false; + return new MemoryItemStore(); } -function replaceEqualDeep(a2, b2) { - if (a2 === b2) { - return a2; +async function resolveArrayProperties(object2) { + if (Array.isArray(object2)) { + return Promise.all(object2.map((o2) => resolveProperties$1(o2))); } - const array = isPlainArray(a2) && isPlainArray(b2); - if (array || isPlainObject$1(a2) && isPlainObject$1(b2)) { - const aItems = array ? a2 : Object.keys(a2); - const aSize = aItems.length; - const bItems = array ? b2 : Object.keys(b2); - const bSize = bItems.length; - const copy2 = array ? [] : {}; - let equalItems = 0; - for (let i = 0; i < bSize; i++) { - const key = array ? i : bItems[i]; - if ((!array && aItems.includes(key) || array) && a2[key] === void 0 && b2[key] === void 0) { - copy2[key] = void 0; - equalItems++; + return resolveProperties$1(object2); +} +const TRANSPORT_SESSION_LS_KEY = "@sequence.transportSession"; +class BaseWalletTransport { + constructor(walletRequestHandler) { + var _this = this; + this.walletRequestHandler = void 0; + this._sessionId = void 0; + this._registered = void 0; + this._init = void 0; + this._initNonce = void 0; + this._initCallback = void 0; + this.appOrigin = void 0; + this.handleMessage = async function(message) { + const request = message; + if (_this._init !== InitState.OK) { + if (request.type === EventType.INIT) { + if (_this.isValidInitAck(message)) { + if (_this._initCallback) _this._initCallback(); + } else { + if (_this._initCallback) _this._initCallback("invalid init"); + return; + } + } + return; + } + switch (request.type) { + case EventType.OPEN: { + if (_this._init !== InitState.OK) return; + const session = { + sessionId: request.data.sessionId, + intent: request.data.intent, + networkId: request.data.networkId + }; + await _this.open(session); + return; + } + case EventType.CLOSE: { + if (_this._init !== InitState.OK) return; + return; + } + case EventType.MESSAGE: { + const response = await _this.walletRequestHandler.sendMessageRequest(request); + _this.sendMessage(response); + if (response.data.error) ; + return; + } + default: { + logger.error(`unexpected payload type ${request.type}`); + } + } + }; + this.sendMessageRequest = async function(message) { + return _this.walletRequestHandler.sendMessageRequest(message); + }; + this.open = async function({ + sessionId, + intent, + networkId + }) { + if (sessionId) { + _this._sessionId = sanitizeNumberString(sessionId); + _this.saveTransportSession({ + sessionId, + intent, + networkId + }); + } + _this.walletRequestHandler.setOpenIntent(intent); + await _this.init(); + let chainId = void 0; + try { + if (networkId) { + const network2 = findSupportedNetwork(networkId); + if (network2) { + chainId = network2.chainId; + } else { + throw new Error(`unknown network ${networkId}`); + } + } else { + chainId = _this.walletRequestHandler.defaultChainId(); + } + } catch (err) { + console.error(err); + } + if (intent && intent.type === "connect" && intent.options) { + const connectOptions = intent.options; + const authorizeOptions = connectOptions; + if (_this.appOrigin && authorizeOptions != null && authorizeOptions.origin) { + if (!isBrowserExtension()) { + if (authorizeOptions.origin !== _this.appOrigin) { + throw new Error("origin is invalid"); + } + } + } else if (!_this.appOrigin && authorizeOptions != null && authorizeOptions.origin) { + connectOptions.origin = sanitizeHost(authorizeOptions.origin); + } else if (_this.appOrigin) { + connectOptions.origin = _this.appOrigin; + } + if (connectOptions.app) { + connectOptions.app = sanitizeAlphanumeric(connectOptions.app); + } + if (connectOptions.networkId) { + networkId = connectOptions.networkId; + } else if (networkId) { + connectOptions.networkId = networkId; + } + _this.walletRequestHandler.setConnectOptions(connectOptions); } else { - copy2[key] = replaceEqualDeep(a2[key], b2[key]); - if (copy2[key] === a2[key] && a2[key] !== void 0) { - equalItems++; + _this.walletRequestHandler.setConnectOptions(void 0); + } + await _this.walletRequestHandler.getAccount(); + if (!await _this.walletRequestHandler.isSignedIn()) { + _this.notifyOpen({ + sessionId: _this._sessionId + }); + return true; + } else { + if (intent && intent.type === "connect") { + if (!chainId || chainId <= 0) { + console.log("Failed to set default network on open"); + } + _this.notifyOpen({ + sessionId: _this._sessionId + }); + try { + const connectDetails = await _this.walletRequestHandler.promptConnect(intent.options); + if (connectDetails.connected) { + _this.walletRequestHandler.notifyConnect(connectDetails); + } + } catch (err) { + logger.warn("promptConnect not connected:", err); + } finally { + if (!intent.options || intent.options.keepWalletOpened !== true) { + _this.notifyClose(); + } + } + } else { + if (!chainId || chainId <= 0) { + _this.notifyOpen({ + sessionId: _this._sessionId, + error: `failed to open wallet on network ${networkId}` + }); + return false; + } + _this.notifyOpen({ + sessionId: _this._sessionId, + chainId: `${chainId}`, + session: await _this.walletRequestHandler.walletSession(chainId) + }); } } - } - return aSize === bSize && equalItems === aSize ? a2 : copy2; + return true; + }; + this.saveTransportSession = (session) => { + useBestStore().setItem(TRANSPORT_SESSION_LS_KEY, JSON.stringify(session)); + }; + this.getCachedTransportSession = async function() { + const session = useBestStore().getItem(TRANSPORT_SESSION_LS_KEY); + try { + return session ? JSON.parse(session) : null; + } catch (err) { + console.error(`unable to parse transport session: ${session}`); + return null; + } + }; + this.walletRequestHandler = walletRequestHandler; + this._init = InitState.NIL; + this.walletRequestHandler.on("connect", (connectDetails) => { + if (!this.registered) return; + this.notifyConnect(connectDetails); + }); + this.walletRequestHandler.on("disconnect", (error, origin) => { + if (!this.registered) return; + this.notifyDisconnect(error, origin); + }); + this.walletRequestHandler.on("accountsChanged", (accounts, origin) => { + if (!this.registered) return; + this.notifyAccountsChanged(accounts, origin); + }); + this.walletRequestHandler.on("networks", (networks2) => { + if (!this.registered) return; + this.notifyNetworks(networks2); + if (!networks2 || networks2.length === 0) { + this.notifyChainChanged("0x0"); + } else { + this.notifyChainChanged(toQuantity(networks2.find((network2) => network2.isDefaultChain).chainId)); + } + }); + this.walletRequestHandler.on("chainChanged", (chainIdHex, origin) => { + this.notifyChainChanged(chainIdHex, origin); + }); + this.walletRequestHandler.on("walletContext", (walletContext) => { + if (!this.registered || !walletContext) return; + this.notifyWalletContext(walletContext); + }); + this.walletRequestHandler.on("close", (error) => { + if (!this.registered) return; + this.notifyClose(error); + }); } - return b2; -} -function shallowEqualObjects(a2, b2) { - if (!b2 || Object.keys(a2).length !== Object.keys(b2).length) { - return false; + get registered() { + return this._registered; + } + register() { + throw new Error("abstract method"); + } + unregister() { + throw new Error("abstract method"); + } + request(request) { + throw new Error("abstract method"); + } + sendMessage(message) { + throw new Error("abstract method"); + } + notifyOpen(openInfo) { + const { + chainId, + sessionId, + session, + error + } = openInfo; + this.sendMessage({ + idx: -1, + type: EventType.OPEN, + data: { + chainId, + sessionId, + session, + error + }, + clientVersion: VERSION$1 + }); + } + notifyClose(error) { + this.sendMessage({ + idx: -1, + type: EventType.CLOSE, + data: error ? { + error + } : null, + clientVersion: VERSION$1 + }); + } + notifyConnect(connectDetails) { + this.sendMessage({ + idx: -1, + type: EventType.CONNECT, + data: connectDetails, + clientVersion: VERSION$1 + }); } - for (const key in a2) { - if (a2[key] !== b2[key]) { - return false; - } + notifyDisconnect(error, origin) { + this.sendMessage({ + idx: -1, + type: EventType.DISCONNECT, + data: error ? { + error + } : null, + origin, + clientVersion: VERSION$1 + }); } - return true; -} -function isPlainArray(value) { - return Array.isArray(value) && value.length === Object.keys(value).length; -} -function isPlainObject$1(o2) { - if (!hasObjectPrototype$1(o2)) { - return false; + notifyAccountsChanged(accounts, origin) { + this.sendMessage({ + idx: -1, + type: EventType.ACCOUNTS_CHANGED, + data: accounts, + origin, + clientVersion: VERSION$1 + }); } - const ctor = o2.constructor; - if (ctor === void 0) { - return true; + notifyChainChanged(chainIdHex, origin) { + this.sendMessage({ + idx: -1, + type: EventType.CHAIN_CHANGED, + data: chainIdHex, + origin, + clientVersion: VERSION$1 + }); } - const prot = ctor.prototype; - if (!hasObjectPrototype$1(prot)) { - return false; + notifyNetworks(networks2) { + this.sendMessage({ + idx: -1, + type: EventType.NETWORKS, + data: networks2, + clientVersion: VERSION$1 + }); } - if (!prot.hasOwnProperty("isPrototypeOf")) { - return false; + notifyWalletContext(walletContext) { + this.sendMessage({ + idx: -1, + type: EventType.WALLET_CONTEXT, + data: walletContext, + clientVersion: VERSION$1 + }); } - if (Object.getPrototypeOf(o2) !== Object.prototype) { - return false; + isValidInitAck(message) { + if (this._init === InitState.OK) { + logger.warn("isValidInitAck, already in init'd state, so inquiry is invalid."); + return false; + } + if (message.type !== EventType.INIT) { + logger.warn("isValidInitAck, invalid message type, expecting init"); + return false; + } + const { + sessionId, + nonce + } = message.data; + if (!sessionId || sessionId.length === 0 || !nonce || nonce.length === 0) { + logger.error("invalid init ack"); + return false; + } + if (sessionId !== this._sessionId || nonce !== this._initNonce) { + logger.error("invalid init ack match"); + return false; + } + return true; } - return true; -} -function hasObjectPrototype$1(o2) { - return Object.prototype.toString.call(o2) === "[object Object]"; -} -function sleep(timeout) { - return new Promise((resolve) => { - setTimeout(resolve, timeout); - }); -} -function replaceData(prevData, data, options) { - if (typeof options.structuralSharing === "function") { - return options.structuralSharing(prevData, data); - } else if (options.structuralSharing !== false) { - return replaceEqualDeep(prevData, data); + init() { + return new Promise((resolve, reject) => { + if (this._init === InitState.OK) { + resolve(); + return; + } + if (this._init !== InitState.NIL || this._initCallback) { + reject("transport init is in progress"); + return; + } + const initTimeout = setTimeout(() => { + logger.warn("transport init timed out"); + if (this._initCallback) { + this._initCallback("transport init timed out"); + } + }, PROVIDER_OPEN_TIMEOUT / 2); + this._initCallback = (error) => { + this._initCallback = void 0; + clearTimeout(initTimeout); + if (error) { + reject(error); + } else { + this._init = InitState.OK; + resolve(); + } + }; + this._initNonce = `${performance.now()}`; + this.sendMessage({ + idx: -1, + type: EventType.INIT, + data: { + nonce: this._initNonce + }, + clientVersion: VERSION$1 + }); + this._init = InitState.SENT_NONCE; + }); } - return data; -} -function addToEnd(items, item2, max2 = 0) { - const newItems = [...items, item2]; - return max2 && newItems.length > max2 ? newItems.slice(1) : newItems; -} -function addToStart(items, item2, max2 = 0) { - const newItems = [item2, ...items]; - return max2 && newItems.length > max2 ? newItems.slice(0, -1) : newItems; } -var skipToken = Symbol(); -function ensureQueryFn(options, fetchOptions) { - if (!options.queryFn && (fetchOptions == null ? void 0 : fetchOptions.initialPromise)) { - return () => fetchOptions.initialPromise; - } - if (!options.queryFn || options.queryFn === skipToken) { - return () => Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`)); +class ProxyMessageChannel { + constructor() { + this.app = void 0; + this.wallet = void 0; + const port1 = new ProxyMessageChannelPort(); + const port2 = new ProxyMessageChannelPort(); + port1.conn = port2; + port2.conn = port1; + this.app = port1; + this.wallet = port2; } - return options.queryFn; } -var FocusManager = (_d = class extends Subscribable { +class ProxyMessageChannelPort { constructor() { - super(); - __privateAdd(this, _focused); - __privateAdd(this, _cleanup); - __privateAdd(this, _setup); - __privateSet(this, _setup, (onFocus) => { - if (!isServer && window.addEventListener) { - const listener = () => onFocus(); - window.addEventListener("visibilitychange", listener, false); - return () => { - window.removeEventListener("visibilitychange", listener); - }; + this.conn = void 0; + this.events = new eventemitter2Exports.EventEmitter2(); + this.handleMessage = (message) => { + throw new Error("ProxyMessageChannelPort is not registered"); + }; + this.sendMessage = (message) => { + this.conn.handleMessage(message); + if (message.type === "open") { + this.events.emit("open", message); } - return; - }); + if (message.type === "close") { + this.events.emit("close", message); + } + if (message.type === "connect") { + this.events.emit("connect", message); + } + if (message.type === "disconnect") { + this.events.emit("disconnect", message); + } + }; } - onSubscribe() { - if (!__privateGet(this, _cleanup)) { - this.setEventListener(__privateGet(this, _setup)); - } + on(event, fn) { + this.events.on(event, fn); } - onUnsubscribe() { - var _a2; - if (!this.hasListeners()) { - (_a2 = __privateGet(this, _cleanup)) == null ? void 0 : _a2.call(this); - __privateSet(this, _cleanup, void 0); - } + once(event, fn) { + this.events.once(event, fn); } - setEventListener(setup) { - var _a2; - __privateSet(this, _setup, setup); - (_a2 = __privateGet(this, _cleanup)) == null ? void 0 : _a2.call(this); - __privateSet(this, _cleanup, setup((focused) => { - if (typeof focused === "boolean") { - this.setFocused(focused); - } else { - this.onFocus(); +} +class ProxyMessageProvider extends BaseProviderTransport { + constructor(port) { + super(); + this.port = void 0; + this.register = () => { + this.port.handleMessage = (message) => { + this.handleMessage(message); + }; + this.on("open", (...args) => { + this.port.events.emit("open", ...args); + }); + this.on("close", (...args) => { + this.port.events.emit("close", ...args); + }); + this.on("connect", (...args) => { + this.port.events.emit("connect", ...args); + }); + this.on("disconnect", (...args) => { + this.port.events.emit("disconnect", ...args); + }); + this._registered = true; + }; + this.unregister = () => { + this._registered = false; + this.closeWallet(); + this.events.removeAllListeners(); + this.port.handleMessage = void 0; + }; + this.openWallet = (path, intent, networkId) => { + if (this.state === OpenState.CLOSED) { + this.state = OpenState.OPENING; + const sessionId = `${performance.now()}`; + this._sessionId = sessionId; + this.sendMessage({ + idx: -1, + type: EventType.OPEN, + data: { + path, + intent, + networkId, + sessionId + }, + clientVersion: VERSION$1 + }); } - })); - } - setFocused(focused) { - const changed = __privateGet(this, _focused) !== focused; - if (changed) { - __privateSet(this, _focused, focused); - this.onFocus(); + }; + this.state = OpenState.CLOSED; + this.port = port; + if (!port) { + throw new Error("port argument cannot be empty"); } + this._init = InitState.OK; } - onFocus() { - const isFocused = this.isFocused(); - this.listeners.forEach((listener) => { - listener(isFocused); + closeWallet() { + this.sendMessage({ + idx: -1, + type: EventType.CLOSE, + data: null, + clientVersion: VERSION$1 }); + this.close(); } - isFocused() { - var _a2; - if (typeof __privateGet(this, _focused) === "boolean") { - return __privateGet(this, _focused); + sendMessage(message) { + if (!message.idx) { + throw new Error("message idx is empty"); } - return ((_a2 = globalThis.document) == null ? void 0 : _a2.visibilityState) !== "hidden"; + this.port.sendMessage(message); } -}, _focused = new WeakMap(), _cleanup = new WeakMap(), _setup = new WeakMap(), _d); -var focusManager = new FocusManager(); -var OnlineManager = (_e = class extends Subscribable { - constructor() { - super(); - __privateAdd(this, _online, true); - __privateAdd(this, _cleanup2); - __privateAdd(this, _setup2); - __privateSet(this, _setup2, (onOnline) => { - if (!isServer && window.addEventListener) { - const onlineListener = () => onOnline(true); - const offlineListener = () => onOnline(false); - window.addEventListener("online", onlineListener, false); - window.addEventListener("offline", offlineListener, false); - return () => { - window.removeEventListener("online", onlineListener); - window.removeEventListener("offline", offlineListener); - }; - } - return; - }); +} +class ProxyMessageHandler extends BaseWalletTransport { + constructor(walletRequestHandler, port) { + super(walletRequestHandler); + this.port = void 0; + this.port = port; + this._init = InitState.OK; } - onSubscribe() { - if (!__privateGet(this, _cleanup2)) { - this.setEventListener(__privateGet(this, _setup2)); - } + register() { + this.port.handleMessage = (message) => { + this.handleMessage(message); + }; + this._registered = true; } - onUnsubscribe() { - var _a2; - if (!this.hasListeners()) { - (_a2 = __privateGet(this, _cleanup2)) == null ? void 0 : _a2.call(this); - __privateSet(this, _cleanup2, void 0); + // note: we can't decide whether to restore the session within register(), because session info is + // received asyncronously via EventType.OPEN after register() is executed. + // And in the case of a redirect/reload, EventType.OPEN is not sent at all, + // because the wallet is already open. + // + // call this method from wallet redirect hander when a session restore is needed + async restoreSession() { + const cachedSession = await this.getCachedTransportSession(); + if (cachedSession) { + this.open(cachedSession); } } - setEventListener(setup) { - var _a2; - __privateSet(this, _setup2, setup); - (_a2 = __privateGet(this, _cleanup2)) == null ? void 0 : _a2.call(this); - __privateSet(this, _cleanup2, setup(this.setOnline.bind(this))); - } - setOnline(online) { - const changed = __privateGet(this, _online) !== online; - if (changed) { - __privateSet(this, _online, online); - this.listeners.forEach((listener) => { - listener(online); - }); - } + unregister() { + this.port.handleMessage = void 0; + this._registered = false; } - isOnline() { - return __privateGet(this, _online); + sendMessage(message) { + this.port.sendMessage(message); } -}, _online = new WeakMap(), _cleanup2 = new WeakMap(), _setup2 = new WeakMap(), _e); -var onlineManager = new OnlineManager(); -function defaultRetryDelay(failureCount) { - return Math.min(1e3 * 2 ** failureCount, 3e4); -} -function canFetch(networkMode) { - return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true; } -var CancelledError = class extends Error { - constructor(options) { - super("CancelledError"); - this.revert = options == null ? void 0 : options.revert; - this.silent = options == null ? void 0 : options.silent; +function overrideLogs(side) { + var _window$ue; + if ((_window$ue = window.ue) != null && _window$ue.sequencewallettransport && !window.logsOverriddenForUnreal) { + var _window$ue2; + const t2 = (_window$ue2 = window.ue) == null ? void 0 : _window$ue2.sequencewallettransport; + console.log = (...args) => { + t2.logfromjs(`${side}: ${stringify(args)}`); + }; + console.warn = (...args) => { + t2.warnfromjs(`${side}: ${stringify(args)}`); + }; + console.error = (...args) => { + t2.errorfromjs(`${side}: ${stringify(args)}`); + }; + window.logsOverriddenForUnreal = true; } -}; -function isCancelledError(value) { - return value instanceof CancelledError; } -function createRetryer(config2) { - let isRetryCancelled = false; - let failureCount = 0; - let isResolved = false; - let continueFn; - let promiseResolve; - let promiseReject; - const promise = new Promise((outerResolve, outerReject) => { - promiseResolve = outerResolve; - promiseReject = outerReject; - }); - const cancel = (cancelOptions) => { - var _a2; - if (!isResolved) { - reject(new CancelledError(cancelOptions)); - (_a2 = config2.abort) == null ? void 0 : _a2.call(config2); - } - }; - const cancelRetry = () => { - isRetryCancelled = true; - }; - const continueRetry = () => { - isRetryCancelled = false; - }; - const canContinue = () => focusManager.isFocused() && (config2.networkMode === "always" || onlineManager.isOnline()) && config2.canRun(); - const canStart = () => canFetch(config2.networkMode) && config2.canRun(); - const resolve = (value) => { - var _a2; - if (!isResolved) { - isResolved = true; - (_a2 = config2.onSuccess) == null ? void 0 : _a2.call(config2, value); - continueFn == null ? void 0 : continueFn(); - promiseResolve(value); - } - }; - const reject = (value) => { - var _a2; - if (!isResolved) { - isResolved = true; - (_a2 = config2.onError) == null ? void 0 : _a2.call(config2, value); - continueFn == null ? void 0 : continueFn(); - promiseReject(value); - } - }; - const pause = () => { - return new Promise((continueResolve) => { - var _a2; - continueFn = (value) => { - if (isResolved || canContinue()) { - continueResolve(value); - } - }; - (_a2 = config2.onPause) == null ? void 0 : _a2.call(config2); - }).then(() => { - var _a2; - continueFn = void 0; - if (!isResolved) { - (_a2 = config2.onContinue) == null ? void 0 : _a2.call(config2); +function stringify(things) { + return things.map((a2) => typeof a2 === "object" ? a2 instanceof Error ? a2.message : JSON.stringify(a2) : String(a2)).join(" "); +} +let registeredUnrealMessageProvider; +class UnrealMessageProvider extends BaseProviderTransport { + constructor(walletAppURL) { + super(); + this.walletURL = void 0; + this.register = () => { + var _window$ue; + overrideLogs("dapp"); + if (registeredUnrealMessageProvider) { + registeredUnrealMessageProvider.unregister(); + registeredUnrealMessageProvider = this; } - }); - }; - const run = () => { - if (isResolved) { - return; - } - let promiseOrValue; - const initialPromise = failureCount === 0 ? config2.initialPromise : void 0; - try { - promiseOrValue = initialPromise ?? config2.fn(); - } catch (error) { - promiseOrValue = Promise.reject(error); - } - Promise.resolve(promiseOrValue).then(resolve).catch((error) => { - var _a2; - if (isResolved) { + if ((_window$ue = window.ue) != null && _window$ue.sequencewallettransport) { + window.ue.sequencewallettransport.onmessagefromwallet = this.onUnrealCallback; + } + registeredUnrealMessageProvider = this; + this._registered = true; + console.log("registering transport!"); + }; + this.unregister = () => { + var _window$ue2; + this._registered = false; + this.closeWallet(); + if (registeredUnrealMessageProvider === this) { + registeredUnrealMessageProvider = void 0; + } + if (((_window$ue2 = window.ue) == null || (_window$ue2 = _window$ue2.sequencewallettransport) == null ? void 0 : _window$ue2.onmessagefromwallet) === this.onUnrealCallback) { + delete window.ue.sequencewallettransport.onmessagefromwallet; + } + this.events.removeAllListeners(); + }; + this.openWallet = (path, intent, networkId) => { + if (this.isOpened()) { + console.log("wallet already open!"); return; } - const retry = config2.retry ?? (isServer ? 0 : 3); - const retryDelay = config2.retryDelay ?? defaultRetryDelay; - const delay2 = typeof retryDelay === "function" ? retryDelay(failureCount, error) : retryDelay; - const shouldRetry2 = retry === true || typeof retry === "number" && failureCount < retry || typeof retry === "function" && retry(failureCount, error); - if (isRetryCancelled || !shouldRetry2) { - reject(error); - return; + console.log("opening wallet!"); + const walletURL = new URL(this.walletURL.href); + const windowSessionParams = new WindowSessionParams(); + if (path) { + walletURL.pathname = path.toLowerCase(); + } + this._init = InitState.NIL; + this._sessionId = `${performance.now()}`; + windowSessionParams.set("sid", this._sessionId); + if (intent) { + windowSessionParams.set("intent", base64EncodeObject(intent)); + } + if (networkId) { + windowSessionParams.set("net", `${networkId}`); } - failureCount++; - (_a2 = config2.onFail) == null ? void 0 : _a2.call(config2, failureCount, error); - sleep(delay2).then(() => { - return canContinue() ? void 0 : pause(); - }).then(() => { - if (isRetryCancelled) { - reject(error); - } else { - run(); - } - }); - }); - }; - return { - promise, - cancel, - continue: () => { - continueFn == null ? void 0 : continueFn(); - return promise; - }, - cancelRetry, - continueRetry, - canStart, - start: () => { - if (canStart()) { - run(); - } else { - pause().then(run); + walletURL.search = windowSessionParams.toString(); + console.log("opening wallet to", walletURL.href); + window.open(walletURL.href); + }; + this.onUnrealCallback = (message) => { + if (!message) { + throw new Error("ProviderMessage object is empty"); } - return promise; - } - }; + this.handleMessage(message); + }; + this.walletURL = new URL(walletAppURL); + } + closeWallet() { + this.close(); + } + // all lowercase is an annoying limitation of Unreal CEF BindUObject + sendMessage(message) { + var _window$ue3; + const postedMessage = typeof message !== "string" ? JSON.stringify(message, bigintReplacer) : message; + console.log("Sending message to wallet:", postedMessage); + (_window$ue3 = window.ue) == null || (_window$ue3 = _window$ue3.sequencewallettransport) == null || _window$ue3.sendmessagetowallet(postedMessage); + } } -function createNotifyManager() { - let queue2 = []; - let transactions2 = 0; - let notifyFn = (callback) => { - callback(); - }; - let batchNotifyFn = (callback) => { - callback(); - }; - let scheduleFn = (cb2) => setTimeout(cb2, 0); - const schedule = (callback) => { - if (transactions2) { - queue2.push(callback); - } else { - scheduleFn(() => { - notifyFn(callback); - }); +class UnrealMessageHandler extends BaseWalletTransport { + constructor(walletRequestHandler) { + super(walletRequestHandler); + this.onMessageFromUnreal = (request) => { + logger.debug("RECEIVED MESSAGE", request); + this.handleMessage(request); + }; + this.getUnrealTransportSession = (windowParams) => { + const params = new WindowSessionParams(windowParams); + return { + sessionId: params.get("sid"), + networkId: params.get("net"), + intent: base64DecodeObject(params.get("intent")) + }; + }; + this._init = InitState.NIL; + } + async register(windowHref) { + var _window$ue; + if (((_window$ue = window.ue) == null ? void 0 : _window$ue.sequencewallettransport) === void 0) { + return; } - }; - const flush = () => { - const originalQueue = queue2; - queue2 = []; - if (originalQueue.length) { - scheduleFn(() => { - batchNotifyFn(() => { - originalQueue.forEach((callback) => { - notifyFn(callback); - }); - }); - }); + overrideLogs("wallet"); + const { + search: rawParams + } = new URL(windowHref || window.location.href); + let session = this.getUnrealTransportSession(rawParams); + const isNewWindowSession = !!session.sessionId; + if (!isNewWindowSession) { + session = await this.getCachedTransportSession(); } - }; - return { - batch: (callback) => { - let result; - transactions2++; - try { - result = callback(); - } finally { - transactions2--; - if (!transactions2) { - flush(); - } - } - return result; - }, - /** - * All calls to the wrapped function will be batched. - */ - batchCalls: (callback) => { - return (...args) => { - schedule(() => { - callback(...args); - }); - }; - }, - schedule, - /** - * Use this method to set a custom notify function. - * This can be used to for example wrap notifications with `React.act` while running tests. - */ - setNotifyFunction: (fn) => { - notifyFn = fn; - }, - /** - * Use this method to set a custom function to batch notifications together into a single tick. - * By default React Query will use the batch function provided by ReactDOM or React Native. - */ - setBatchNotifyFunction: (fn) => { - batchNotifyFn = fn; - }, - setScheduler: (fn) => { - scheduleFn = fn; + if (!session) { + logger.error("unreal session is undefined"); + return; } - }; -} -var notifyManager = createNotifyManager(); -var Removable = (_f = class { - constructor() { - __privateAdd(this, _gcTimeout); + window.ue.sequencewallettransport.onmessagefromsequencejs = this.onMessageFromUnreal; + this._registered = true; + this.open(session).then((opened) => { + if (!opened) { + var _session; + const err = `failed to open to network ${(_session = session) == null ? void 0 : _session.networkId}`; + logger.error(err); + this.notifyClose({ + message: err + }); + window.close(); + } + }).catch((e2) => { + var _session2; + const err = `failed to open to network ${(_session2 = session) == null ? void 0 : _session2.networkId}, due to: ${e2}`; + logger.error(err); + this.notifyClose({ + message: err + }); + window.close(); + }); } - destroy() { - this.clearGcTimeout(); + unregister() { + var _window$ue2; + if (((_window$ue2 = window.ue) == null || (_window$ue2 = _window$ue2.sequencewallettransport) == null ? void 0 : _window$ue2.onmessagefromsequencejs) === this.onMessageFromUnreal) { + delete window.ue.sequencewallettransport.onmessagefromsequencejs; + } + this._registered = false; } - scheduleGc() { - this.clearGcTimeout(); - if (isValidTimeout(this.gcTime)) { - __privateSet(this, _gcTimeout, setTimeout(() => { - this.optionalRemove(); - }, this.gcTime)); + // sendMessage sends message to the dapp window + sendMessage(message) { + var _window$ue3; + if (message.type !== EventType.INIT && this._init !== InitState.OK) { + logger.error("impossible state, should not be calling postMessage until inited"); + return; } + const payload = JSON.stringify(message, bigintReplacer); + (_window$ue3 = window.ue) == null || (_window$ue3 = _window$ue3.sequencewallettransport) == null || _window$ue3.sendmessagetosequencejs(payload); } - updateGcTime(newGcTime) { - this.gcTime = Math.max( - this.gcTime || 0, - newGcTime ?? (isServer ? Infinity : 5 * 60 * 1e3) - ); +} +const CHANNEL_ID = "sequence-extension-message-handler"; +class ExtensionMessageHandler extends BaseWalletTransport { + constructor(walletRequestHandler, runtime) { + super(walletRequestHandler); + this.runtime = runtime; + this.port = void 0; + this._init = InitState.OK; } - clearGcTimeout() { - if (__privateGet(this, _gcTimeout)) { - clearTimeout(__privateGet(this, _gcTimeout)); - __privateSet(this, _gcTimeout, void 0); - } + register() { + this._registered = true; + this.port = this.runtime.connect({ + name: CHANNEL_ID + }); } -}, _gcTimeout = new WeakMap(), _f); -var Query = (_g = class extends Removable { - constructor(config2) { - super(); - __privateAdd(this, _Query_instances); - __privateAdd(this, _initialState); - __privateAdd(this, _revertState); - __privateAdd(this, _cache); - __privateAdd(this, _retryer); - __privateAdd(this, _defaultOptions); - __privateAdd(this, _abortSignalConsumed); - __privateSet(this, _abortSignalConsumed, false); - __privateSet(this, _defaultOptions, config2.defaultOptions); - this.setOptions(config2.options); - this.observers = []; - __privateSet(this, _cache, config2.cache); - this.queryKey = config2.queryKey; - this.queryHash = config2.queryHash; - __privateSet(this, _initialState, getDefaultState$1(this.options)); - this.state = config2.state ?? __privateGet(this, _initialState); - this.scheduleGc(); + sendMessage(message) { + logger.info("[ExtensionMessageHandler send]", message); + this.port.postMessage(message); } - get meta() { - return this.options.meta; +} +class ExtensionMessageProvider extends BaseProviderTransport { + constructor(runtime) { + super(); + this.register = () => { + this._registered = true; + }; + runtime.onConnect.addListener((port) => { + if (port.name === CHANNEL_ID) { + this._init = InitState.OK; + port.onMessage.addListener((message) => { + this.handleMessage(message); + }); + } + }); } - get promise() { - var _a2; - return (_a2 = __privateGet(this, _retryer)) == null ? void 0 : _a2.promise; + sendMessage(message) { } - setOptions(options) { - this.options = { ...__privateGet(this, _defaultOptions), ...options }; - this.updateGcTime(this.options.gcTime); + unregister() { } - optionalRemove() { - if (!this.observers.length && this.state.fetchStatus === "idle") { - __privateGet(this, _cache).remove(this); - } + openWallet(path, intent, networkId) { } - setData(newData, options) { - const data = replaceData(this.state.data, newData, this.options); - __privateMethod(this, _Query_instances, dispatch_fn).call(this, { - data, - type: "success", - dataUpdatedAt: options == null ? void 0 : options.updatedAt, - manual: options == null ? void 0 : options.manual - }); - return data; + closeWallet() { } - setState(state, setStateOptions) { - __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "setState", state, setStateOptions }); +} +class BaseInjectedTransport extends eventemitter2Exports.EventEmitter2 { + constructor(stream) { + var _this; + super(); + _this = this; + this.stream = stream; + this.responseCallbacks = /* @__PURE__ */ new Map(); + this._messageIdx = 0; + this.nextMessageIdx = () => ++this._messageIdx; + this.handleMessage = (message) => { + if (!message.type || !message.data) { + return; + } + logger.info("[received message]", message); + const requestIdx = message.idx; + const responseCallback = this.responseCallbacks.get(requestIdx); + if (requestIdx) { + this.responseCallbacks.delete(requestIdx); + } + switch (message.type) { + case EventType.MESSAGE: + if (responseCallback) { + this.emit(EventType.MESSAGE, message); + responseCallback(message.data.error, message); + } else { + throw new Error("impossible state"); + } + break; + case EventType.DISCONNECT: + case EventType.ACCOUNTS_CHANGED: + case EventType.CHAIN_CHANGED: + this.emit(message.type, message.data); + break; + default: + console.error("unknown message type", message); + break; + } + }; + this.sendMessageRequest = async function(message) { + return new Promise((resolve, reject) => { + if (!message.idx || message.idx <= 0) { + reject(new Error("message idx not set")); + } + const responseCallback = (error, response) => { + if (error) { + reject(error); + } else if (response) { + resolve(response); + } else { + throw new Error("no valid response to return"); + } + }; + const { + idx + } = message; + if (!_this.responseCallbacks.get(idx)) { + _this.responseCallbacks.set(idx, responseCallback); + } else { + reject(new Error("duplicate message idx, should never happen")); + } + _this.sendMessage(message); + }); + }; + this.stream.on("data", this.handleMessage); } - cancel(options) { - var _a2, _b2; - const promise = (_a2 = __privateGet(this, _retryer)) == null ? void 0 : _a2.promise; - (_b2 = __privateGet(this, _retryer)) == null ? void 0 : _b2.cancel(options); - return promise ? promise.then(noop$1).catch(noop$1) : Promise.resolve(); + sendMessage(message) { + if (!this.stream.writable) { + console.error("window post message stream is not writable"); + } + this.stream.write(message); } - destroy() { - super.destroy(); - this.cancel({ silent: true }); +} +let registeredWindowMessageProvider; +class WindowMessageProvider extends BaseProviderTransport { + constructor(walletAppURL) { + super(); + this.walletURL = void 0; + this.walletWindow = void 0; + this.register = () => { + if (registeredWindowMessageProvider) { + registeredWindowMessageProvider.unregister(); + registeredWindowMessageProvider = this; + } + window.addEventListener("message", this.onWindowEvent); + registeredWindowMessageProvider = this; + this.on("open", () => { + const popup = this.walletWindow; + const interval = setInterval(() => { + if (popup && popup.closed) { + clearInterval(interval); + this.close(); + } + }, 500); + }); + this.on("close", () => { + if (this.walletWindow) { + this.walletWindow.close(); + this.walletWindow = null; + } + }); + this._registered = true; + }; + this.unregister = () => { + this._registered = false; + this.closeWallet(); + if (registeredWindowMessageProvider === this) { + registeredWindowMessageProvider = void 0; + } + window.removeEventListener("message", this.onWindowEvent); + this.events.removeAllListeners(); + }; + this.openWallet = (path, intent, networkId) => { + if (this.walletWindow && this.isOpened()) { + this.walletWindow.focus(); + return; + } + const walletURL = new URL(this.walletURL.href); + const windowSessionParams = new WindowSessionParams(); + if (path && path !== "") { + walletURL.pathname = path.toLowerCase(); + } + this._init = InitState.NIL; + this._sessionId = `${performance.now()}`; + windowSessionParams.set("sid", this._sessionId); + if (intent) { + if (intent.type === "connect") { + if (!intent.options) intent.options = { + app: window.location.origin + }; + if (!isBrowserExtension() && !isUnityPlugin() && intent.options) { + intent.options.origin = window.location.origin; + } + } + windowSessionParams.set("intent", base64EncodeObject(intent)); + } + if (networkId) { + windowSessionParams.set("net", `${networkId}`); + } + let windowSize; + let windowPos; + if (isBrowserExtension()) { + windowSize = [450, 750]; + windowPos = [Math.abs(window.screen.width / 2 - windowSize[0] / 2), Math.abs(window.screen.height / 2 - windowSize[1] / 2)]; + } else { + windowSize = [450, 750]; + windowPos = [Math.abs(window.screenX + window.innerWidth / 2 - windowSize[0] / 2), Math.abs(window.screenY + window.innerHeight / 2 - windowSize[1] / 2)]; + } + const windowFeatures = `toolbar=0,location=0,menubar=0,scrollbars=yes,status=yes,width=${windowSize[0]},height=${windowSize[1]},left=${windowPos[0]},top=${windowPos[1]}`; + walletURL.search = windowSessionParams.toString(); + this.walletWindow = window.open(walletURL.href, "sequence.app", windowFeatures); + }; + this.onWindowEvent = (event) => { + if (event.origin !== this.walletURL.origin) { + return; + } + let message; + try { + message = JSON.parse(event.data, bigintReviver); + } catch (err) { + return; + } + if (!message) { + throw new Error("ProviderMessage object is empty"); + } + this.handleMessage(message); + }; + this.walletURL = new URL(walletAppURL); } - reset() { - this.destroy(); - this.setState(__privateGet(this, _initialState)); + closeWallet() { + var _this$walletWindow; + this.close(); + (_this$walletWindow = this.walletWindow) == null || _this$walletWindow.close(); } - isActive() { - return this.observers.some( - (observer) => resolveEnabled(observer.options.enabled, this) !== false - ); + sendMessage(message) { + if (!this.walletWindow) { + logger.warn("WindowMessageProvider: sendMessage failed as walletWindow is unavailable"); + return; + } + const postedMessage = typeof message !== "string" ? JSON.stringify(message, bigintReplacer) : message; + this.walletWindow.postMessage(postedMessage, this.walletURL.origin); } - isDisabled() { - return this.getObserversCount() > 0 && !this.isActive(); +} +class WindowMessageHandler extends BaseWalletTransport { + constructor(walletRequestHandler) { + var _this; + super(walletRequestHandler); + _this = this; + this.parentWindow = void 0; + this._isPopup = false; + this.onWindowEvent = async function(event) { + if (!event.origin || event.origin === "") { + return; + } + if (_this.appOrigin && event.origin !== _this.appOrigin) { + return; + } + let request; + try { + request = JSON.parse(event.data, bigintReviver); + } catch (err) { + return; + } + logger.debug("RECEIVED MESSAGE", request); + if (_this._init !== InitState.OK && _this.isValidInitAck(request)) { + _this.appOrigin = event.origin; + } + if (_this._init === InitState.OK && (!_this.appOrigin || _this.appOrigin.length < 8)) { + logger.error("impossible state, init.OK and appOrigin required"); + return; + } + _this.handleMessage(request); + }; + this.getWindowTransportSession = (windowParams) => { + const params = new WindowSessionParams(windowParams); + return { + sessionId: params.get("sid"), + networkId: params.get("net"), + intent: base64DecodeObject(params.get("intent")) + }; + }; + this._init = InitState.NIL; } - isStale() { - if (this.state.isInvalidated) { - return true; + async register(windowHref) { + const isPopup = parent.window.opener !== null; + this._isPopup = isPopup; + if (isPopup !== true) { + return; } - if (this.getObserversCount() > 0) { - return this.observers.some( - (observer) => observer.getCurrentResult().isStale - ); + const { + search: rawParams + } = new URL(windowHref || window.location.href); + let session = this.getWindowTransportSession(rawParams); + const isNewWindowSession = !!session.sessionId; + if (!isNewWindowSession) { + session = await this.getCachedTransportSession(); } - return this.state.data === void 0; - } - isStaleByTime(staleTime = 0) { - return this.state.isInvalidated || this.state.data === void 0 || !timeUntilStale(this.state.dataUpdatedAt, staleTime); - } - onFocus() { - var _a2; - const observer = this.observers.find((x2) => x2.shouldFetchOnWindowFocus()); - observer == null ? void 0 : observer.refetch({ cancelRefetch: false }); - (_a2 = __privateGet(this, _retryer)) == null ? void 0 : _a2.continue(); - } - onOnline() { - var _a2; - const observer = this.observers.find((x2) => x2.shouldFetchOnReconnect()); - observer == null ? void 0 : observer.refetch({ cancelRefetch: false }); - (_a2 = __privateGet(this, _retryer)) == null ? void 0 : _a2.continue(); - } - addObserver(observer) { - if (!this.observers.includes(observer)) { - this.observers.push(observer); - this.clearGcTimeout(); - __privateGet(this, _cache).notify({ type: "observerAdded", query: this, observer }); + if (!session) { + logger.error("window session is undefined"); + return; } - } - removeObserver(observer) { - if (this.observers.includes(observer)) { - this.observers = this.observers.filter((x2) => x2 !== observer); - if (!this.observers.length) { - if (__privateGet(this, _retryer)) { - if (__privateGet(this, _abortSignalConsumed)) { - __privateGet(this, _retryer).cancel({ revert: true }); - } else { - __privateGet(this, _retryer).cancelRetry(); - } - } - this.scheduleGc(); + this.parentWindow = parent.window.opener; + window.addEventListener("message", this.onWindowEvent, false); + this._registered = true; + this.open(session).then((opened) => { + if (!opened) { + var _session; + const err = `failed to open to network ${(_session = session) == null ? void 0 : _session.networkId}`; + logger.error(err); + this.notifyClose({ + message: err + }); + window.close(); } - __privateGet(this, _cache).notify({ type: "observerRemoved", query: this, observer }); - } + }).catch((e2) => { + var _session2; + const err = `failed to open to network ${(_session2 = session) == null ? void 0 : _session2.networkId}, due to: ${e2}`; + logger.error(err); + this.notifyClose({ + message: err + }); + window.close(); + }); } - getObserversCount() { - return this.observers.length; + unregister() { + window.removeEventListener("message", this.onWindowEvent); + this._registered = false; } - invalidate() { - if (!this.state.isInvalidated) { - __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "invalidate" }); + // postMessage sends message to the dapp window + sendMessage(message) { + const payload = JSON.stringify(message, bigintReplacer); + if (message.type === EventType.INIT) { + this.postMessage(payload, true); + } else { + this.postMessage(payload); } } - fetch(options, fetchOptions) { - var _a2, _b2, _c2; - if (this.state.fetchStatus !== "idle") { - if (this.state.data !== void 0 && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) { - this.cancel({ silent: true }); - } else if (__privateGet(this, _retryer)) { - __privateGet(this, _retryer).continueRetry(); - return __privateGet(this, _retryer).promise; - } - } - if (options) { - this.setOptions(options); + get isPopup() { + return this._isPopup; + } + postMessage(message, init2 = false) { + if (init2 !== true && this._init !== InitState.OK) { + logger.error("impossible state, should not be calling postMessage until inited"); + return; } - if (!this.options.queryFn) { - const observer = this.observers.find((x2) => x2.options.queryFn); - if (observer) { - this.setOptions(observer.options); + if (init2) { + this.parentWindow.postMessage(message, "*"); + } else { + if (this.appOrigin && this.appOrigin.length > 4) { + this.parentWindow.postMessage(message, this.appOrigin); + } else { + logger.error("unable to postMessage as parentOrigin is invalid"); } } - const abortController = new AbortController(); - const addSignalProperty = (object2) => { - Object.defineProperty(object2, "signal", { - enumerable: true, - get: () => { - __privateSet(this, _abortSignalConsumed, true); - return abortController.signal; - } + } +} +function isMuxTransportTemplate(obj) { + return obj && typeof obj === "object" && (obj.windowTransport && typeof obj.windowTransport === "object" || obj.proxyTransport && typeof obj.proxyTransport === "object" || obj.extensionTransport && typeof obj.extensionTransport === "object" || obj.unrealTransport && typeof obj.unrealTransport === "object") && // One of the transports must be enabled + (obj.windowTransport && obj.windowTransport.enabled || obj.proxyTransport && obj.proxyTransport.enabled || obj.extensionTransport && obj.extensionTransport.enabled || obj.unrealTransport && obj.unrealTransport.enabled); +} +class MuxMessageProvider { + constructor(...messageProviders) { + var _this = this; + this.messageProviders = void 0; + this.provider = void 0; + this.register = () => { + if (this.messageProviders.length === 1) { + this.provider = this.messageProviders[0]; + this.provider.register(); + return; + } + this.messageProviders.forEach((m2) => { + m2.register(); + m2.once("open", () => { + if (!this.provider) { + this.provider = m2; + this.messageProviders.forEach((m22) => { + if (this.provider !== m22) { + m22.unregister(); + } + }); + } + }); }); }; - const fetchFn = () => { - const queryFn = ensureQueryFn(this.options, fetchOptions); - const queryFnContext = { - queryKey: this.queryKey, - meta: this.meta - }; - addSignalProperty(queryFnContext); - __privateSet(this, _abortSignalConsumed, false); - if (this.options.persister) { - return this.options.persister( - queryFn, - queryFnContext, - this - ); - } - return queryFn(queryFnContext); + this.unregister = () => { + this.messageProviders.forEach((m2) => m2.unregister()); + this.provider = void 0; }; - const context2 = { - fetchOptions, - options: this.options, - queryKey: this.queryKey, - state: this.state, - fetchFn + this.openWallet = (path, intent, networkId) => { + if (this.provider) { + this.provider.openWallet(path, intent, networkId); + return; + } + this.messageProviders.forEach((m2) => m2.openWallet(path, intent, networkId)); }; - addSignalProperty(context2); - (_a2 = this.options.behavior) == null ? void 0 : _a2.onFetch( - context2, - this - ); - __privateSet(this, _revertState, this.state); - if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((_b2 = context2.fetchOptions) == null ? void 0 : _b2.meta)) { - __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "fetch", meta: (_c2 = context2.fetchOptions) == null ? void 0 : _c2.meta }); - } - const onError = (error) => { - var _a3, _b3, _c3, _d2; - if (!(isCancelledError(error) && error.silent)) { - __privateMethod(this, _Query_instances, dispatch_fn).call(this, { - type: "error", - error - }); + this.sendMessageRequest = async function(message) { + if (_this.provider) { + return _this.provider.sendMessageRequest(message); } - if (!isCancelledError(error)) { - (_b3 = (_a3 = __privateGet(this, _cache).config).onError) == null ? void 0 : _b3.call( - _a3, - error, - this - ); - (_d2 = (_c3 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d2.call( - _c3, - this.state.data, - error, - this - ); + throw new Error("impossible state, wallet must be opened first"); + }; + this.waitUntilOpened = async function() { + if (_this.provider) { + return _this.provider.waitUntilOpened(); } - if (!this.isFetchingOptimistic) { - this.scheduleGc(); + return Promise.race(_this.messageProviders.map((p2) => p2.waitUntilOpened())); + }; + this.waitUntilConnected = async function() { + if (_this.provider) { + return _this.provider.waitUntilConnected(); } - this.isFetchingOptimistic = false; + throw new Error("impossible state, wallet must be opened first"); }; - __privateSet(this, _retryer, createRetryer({ - initialPromise: fetchOptions == null ? void 0 : fetchOptions.initialPromise, - fn: context2.fetchFn, - abort: abortController.abort.bind(abortController), - onSuccess: (data) => { - var _a3, _b3, _c3, _d2; - if (data === void 0) { - onError(new Error(`${this.queryHash} data is undefined`)); - return; - } - try { - this.setData(data); - } catch (error) { - onError(error); - return; - } - (_b3 = (_a3 = __privateGet(this, _cache).config).onSuccess) == null ? void 0 : _b3.call(_a3, data, this); - (_d2 = (_c3 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _d2.call( - _c3, - data, - this.state.error, - this - ); - if (!this.isFetchingOptimistic) { - this.scheduleGc(); - } - this.isFetchingOptimistic = false; - }, - onError, - onFail: (failureCount, error) => { - __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "failed", failureCount, error }); - }, - onPause: () => { - __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "pause" }); - }, - onContinue: () => { - __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "continue" }); - }, - retry: context2.options.retry, - retryDelay: context2.options.retryDelay, - networkMode: context2.options.networkMode, - canRun: () => true - })); - return __privateGet(this, _retryer).start(); + this.messageProviders = messageProviders; + this.provider = void 0; } -}, _initialState = new WeakMap(), _revertState = new WeakMap(), _cache = new WeakMap(), _retryer = new WeakMap(), _defaultOptions = new WeakMap(), _abortSignalConsumed = new WeakMap(), _Query_instances = new WeakSet(), dispatch_fn = function(action) { - const reducer = (state) => { - switch (action.type) { - case "failed": - return { - ...state, - fetchFailureCount: action.failureCount, - fetchFailureReason: action.error - }; - case "pause": - return { - ...state, - fetchStatus: "paused" - }; - case "continue": - return { - ...state, - fetchStatus: "fetching" - }; - case "fetch": - return { - ...state, - ...fetchState(state.data, this.options), - fetchMeta: action.meta ?? null - }; - case "success": - return { - ...state, - data: action.data, - dataUpdateCount: state.dataUpdateCount + 1, - dataUpdatedAt: action.dataUpdatedAt ?? Date.now(), - error: null, - isInvalidated: false, - status: "success", - ...!action.manual && { - fetchStatus: "idle", - fetchFailureCount: 0, - fetchFailureReason: null - } - }; - case "error": - const error = action.error; - if (isCancelledError(error) && error.revert && __privateGet(this, _revertState)) { - return { ...__privateGet(this, _revertState), fetchStatus: "idle" }; - } - return { - ...state, - error, - errorUpdateCount: state.errorUpdateCount + 1, - errorUpdatedAt: Date.now(), - fetchFailureCount: state.fetchFailureCount + 1, - fetchFailureReason: error, - fetchStatus: "idle", - status: "error" - }; - case "invalidate": - return { - ...state, - isInvalidated: true - }; - case "setState": - return { - ...state, - ...action.state - }; + static new(template) { + var _template$windowTrans, _template$proxyTransp, _template$extensionTr, _template$unrealTrans; + const muxMessageProvider = new MuxMessageProvider(); + if ((_template$windowTrans = template.windowTransport) != null && _template$windowTrans.enabled && typeof window === "object" && template.walletAppURL) { + const windowMessageProvider = new WindowMessageProvider(template.walletAppURL); + muxMessageProvider.add(windowMessageProvider); } - }; - this.state = reducer(this.state); - notifyManager.batch(() => { - this.observers.forEach((observer) => { - observer.onQueryUpdate(); - }); - __privateGet(this, _cache).notify({ query: this, type: "updated", action }); - }); -}, _g); -function fetchState(data, options) { - return { - fetchFailureCount: 0, - fetchFailureReason: null, - fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused", - ...data === void 0 && { - error: null, - status: "pending" + if ((_template$proxyTransp = template.proxyTransport) != null && _template$proxyTransp.enabled) { + const proxyMessageProvider = new ProxyMessageProvider(template.proxyTransport.appPort); + muxMessageProvider.add(proxyMessageProvider); } - }; -} -function getDefaultState$1(options) { - const data = typeof options.initialData === "function" ? options.initialData() : options.initialData; - const hasData = data !== void 0; - const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0; - return { - data, - dataUpdateCount: 0, - dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0, - error: null, - errorUpdateCount: 0, - errorUpdatedAt: 0, - fetchFailureCount: 0, - fetchFailureReason: null, - fetchMeta: null, - isInvalidated: false, - status: hasData ? "success" : "pending", - fetchStatus: "idle" - }; -} -var QueryCache = (_h = class extends Subscribable { - constructor(config2 = {}) { - super(); - __privateAdd(this, _queries); - this.config = config2; - __privateSet(this, _queries, /* @__PURE__ */ new Map()); + if ((_template$extensionTr = template.extensionTransport) != null && _template$extensionTr.enabled) { + const extensionMessageProvider = new ExtensionMessageProvider(template.extensionTransport.runtime); + muxMessageProvider.add(extensionMessageProvider); + } + if ((_template$unrealTrans = template.unrealTransport) != null && _template$unrealTrans.enabled && template.windowTransport && template.walletAppURL) { + const unrealMessageProvider = new UnrealMessageProvider(template.walletAppURL); + muxMessageProvider.add(unrealMessageProvider); + } + muxMessageProvider.register(); + return muxMessageProvider; } - build(client2, options, state) { - const queryKey = options.queryKey; - const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options); - let query = this.get(queryHash); - if (!query) { - query = new Query({ - cache: this, - queryKey, - queryHash, - options: client2.defaultQueryOptions(options), - state, - defaultOptions: client2.getQueryDefaults(queryKey) - }); - this.add(query); + add(...messageProviders) { + this.messageProviders.push(...messageProviders); + } + closeWallet() { + if (this.provider) { + this.provider.closeWallet(); } - return query; } - add(query) { - if (!__privateGet(this, _queries).has(query.queryHash)) { - __privateGet(this, _queries).set(query.queryHash, query); - this.notify({ - type: "added", - query - }); + isOpened() { + if (this.provider) { + return this.provider.isOpened(); } + return false; } - remove(query) { - const queryInMap = __privateGet(this, _queries).get(query.queryHash); - if (queryInMap) { - query.destroy(); - if (queryInMap === query) { - __privateGet(this, _queries).delete(query.queryHash); - } - this.notify({ type: "removed", query }); + isConnected() { + if (this.provider) { + return this.provider.isConnected(); } + return false; } - clear() { - notifyManager.batch(() => { - this.getAll().forEach((query) => { - this.remove(query); - }); + on(event, fn) { + if (this.provider) { + this.provider.on(event, fn); + return; + } + this.messageProviders.forEach((m2) => { + m2.on(event, fn); }); } - get(queryHash) { - return __privateGet(this, _queries).get(queryHash); + once(event, fn) { + if (this.provider) { + this.provider.once(event, fn); + return; + } + this.messageProviders.forEach((m2) => { + m2.once(event, fn); + }); } - getAll() { - return [...__privateGet(this, _queries).values()]; + emit(event, ...args) { + if (this.provider) { + return this.provider.emit(event, ...args); + } + for (let i = 0; i < this.messageProviders.length; i++) { + this.messageProviders[i].emit(event, ...args); + } + return true; } - find(filters) { - const defaultedFilters = { exact: true, ...filters }; - return this.getAll().find( - (query) => matchQuery(defaultedFilters, query) - ); + request(request) { + if (!this.provider) { + throw new Error("impossible state, wallet must be opened first"); + } + return this.provider.request(request); } - findAll(filters = {}) { - const queries = this.getAll(); - return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries; + sendMessage(message) { + if (!message.idx || message.idx <= 0) { + throw new Error("message idx is empty"); + } + if (this.provider) { + this.provider.sendMessage(message); + } else { + throw new Error("impossible state, wallet must be opened first"); + } } - notify(event) { - notifyManager.batch(() => { - this.listeners.forEach((listener) => { - listener(event); - }); - }); + handleMessage(message) { + if (this.provider) { + this.provider.handleMessage(message); + return; + } + throw new Error("impossible state, wallet must be opened first"); } - onFocus() { - notifyManager.batch(() => { - this.getAll().forEach((query) => { - query.onFocus(); - }); - }); +} +function toExtended(transactions2) { + if (transactions2.length === 0) { + throw new Error("No transaction provided"); } - onOnline() { - notifyManager.batch(() => { - this.getAll().forEach((query) => { - query.onOnline(); + const [first, ...rest] = transactions2; + return _extends$2({}, first, { + auxiliary: rest + }); +} +function fromExtended(transaction2) { + return [transaction2, ...transaction2.auxiliary || []]; +} +const SIGNER_READY_TIMEOUT = 1e4; +class WalletRequestHandler { + constructor(account2, prompter, networks2) { + var _this = this; + this.account = void 0; + this.signerReadyCallbacks = []; + this.prompter = void 0; + this.networks = void 0; + this._openIntent = void 0; + this._connectOptions = void 0; + this.events = new eventemitter2Exports.EventEmitter2(); + this.onConnectOptionsChange = void 0; + this.promptConnect = async function(options) { + if (!options && !_this._connectOptions) { + throw new Error("prompter connect options are empty"); + } + if (!_this.prompter) { + return _this.connect(options); + } + const promptConnectDetails = await _this.prompter.promptConnect(options || _this._connectOptions).catch((_) => { + return { + connected: false + }; }); - }); - } -}, _queries = new WeakMap(), _h); -var Mutation = (_i = class extends Removable { - constructor(config2) { - super(); - __privateAdd(this, _Mutation_instances); - __privateAdd(this, _observers); - __privateAdd(this, _mutationCache); - __privateAdd(this, _retryer2); - this.mutationId = config2.mutationId; - __privateSet(this, _mutationCache, config2.mutationCache); - __privateSet(this, _observers, []); - this.state = config2.state || getDefaultState(); - this.setOptions(config2.options); - this.scheduleGc(); + const connectDetails = promptConnectDetails; + if (connectDetails.connected && !connectDetails.session) { + connectDetails.session = await _this.walletSession(options == null ? void 0 : options.networkId); + } + return promptConnectDetails; + }; + this.isSignedIn = async function() { + await _this.signerReady(); + return !!_this.account; + }; + this.getAccount = async function() { + await _this.signerReady(); + if (_this.account === void 0) { + throw new Error("signerReady failed resolve"); + } + return _this.account; + }; + this.account = account2; + this.prompter = prompter; + this.networks = networks2; } - setOptions(options) { - this.options = options; - this.updateGcTime(this.options.gcTime); + defaultChainId() { + var _this$prompter$getDef, _this$prompter; + return (_this$prompter$getDef = (_this$prompter = this.prompter) == null ? void 0 : _this$prompter.getDefaultChainId()) != null ? _this$prompter$getDef : this.networks[0].chainId; } - get meta() { - return this.options.meta; + async signIn(account2, options = {}) { + this.setAccount(account2); + const { + connect: connect2, + defaultNetworkId + } = options; + if (connect2) { + const connectOptions = this._connectOptions; + let connectDetails; + if (this.prompter !== null) { + var _this$prompter2; + connectDetails = await ((_this$prompter2 = this.prompter) == null ? void 0 : _this$prompter2.promptSignInConnect(connectOptions)); + } else { + connectDetails = await this.connect(connectOptions); + } + this.notifyConnect(connectDetails); + if (!connectOptions || connectOptions.keepWalletOpened !== true) { + this.notifyClose(); + } + } + if (defaultNetworkId && this.defaultChainId() !== defaultNetworkId) { + var _this$prompter3; + await ((_this$prompter3 = this.prompter) == null ? void 0 : _this$prompter3.promptChangeNetwork(defaultNetworkId)); + } } - addObserver(observer) { - if (!__privateGet(this, _observers).includes(observer)) { - __privateGet(this, _observers).push(observer); - this.clearGcTimeout(); - __privateGet(this, _mutationCache).notify({ - type: "observerAdded", - mutation: this, - observer - }); + signOut() { + if (this.account) { + this.notifyDisconnect(); } + this.setAccount(null); } - removeObserver(observer) { - __privateSet(this, _observers, __privateGet(this, _observers).filter((x2) => x2 !== observer)); - this.scheduleGc(); - __privateGet(this, _mutationCache).notify({ - type: "observerRemoved", - mutation: this, - observer - }); + signerReset() { + this.account = void 0; } - optionalRemove() { - if (!__privateGet(this, _observers).length) { - if (this.state.status === "pending") { - this.scheduleGc(); + signerReady(timeout = SIGNER_READY_TIMEOUT) { + return new Promise((resolve, reject) => { + if (this.account !== void 0) { + resolve(); } else { - __privateGet(this, _mutationCache).remove(this); + setTimeout(() => { + if (this.account === void 0) { + this.signerReadyCallbacks = []; + reject(`signerReady timed out`); + } + }, timeout); + this.signerReadyCallbacks.push(resolve); } - } + }); } - continue() { - var _a2; - return ((_a2 = __privateGet(this, _retryer2)) == null ? void 0 : _a2.continue()) ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before - this.execute(this.state.variables); + async connect(options) { + var _ref, _options$networkId; + if (!this.account) { + return { + connected: false, + chainId: "0x0", + error: "unable to connect without signed in account" + }; + } + const networkId = (_ref = (_options$networkId = options == null ? void 0 : options.networkId) != null ? _options$networkId : this.defaultChainId()) != null ? _ref : ChainId.MAINNET; + const chainId = findSupportedNetwork(networkId).chainId; + const connectDetails = { + connected: true, + chainId: toQuantity(chainId) + }; + if (options && options.authorize) { + const authOptions = { + app: options.app, + origin: options.origin, + expiry: options.expiry, + nonce: options.authorizeNonce + }; + try { + connectDetails.proof = await signAuthorization(this.account, chainId, authOptions); + } catch (err) { + logger.warn(`connect, signAuthorization failed for options: ${JSON.stringify(options)}, due to: ${err.message}`); + return { + connected: false, + chainId: "0x0", + error: `signAuthorization failed: ${err.message}` + }; + } + } + connectDetails.session = this.walletSession(chainId); + return connectDetails; } - async execute(variables) { - var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m2, _n, _o, _p, _q, _r2, _s2, _t; - __privateSet(this, _retryer2, createRetryer({ - fn: () => { - if (!this.options.mutationFn) { - return Promise.reject(new Error("No mutationFn found")); + // sendMessageRequest will unwrap the ProviderMessageRequest and send it to the JsonRpcHandler + // (aka, the signer in this instance) and then responds with a wrapped response of + // ProviderMessageResponse to be sent over the transport + async sendMessageRequest(message) { + var _message$clientVersio; + const majorVersion = Number(((_message$clientVersio = message.clientVersion) == null ? void 0 : _message$clientVersio.split(".")[0]) || "0"); + const isJsonRpcResponse = majorVersion < 2; + const jsonRpcResponse = { + id: message.data.id, + jsonrpc: "2.0", + result: null, + error: void 0 + }; + try { + const result = await this.request({ + method: message.data.method, + params: message.data.params, + chainId: message.chainId + }); + return _extends$2({}, message, { + data: isJsonRpcResponse ? _extends$2({}, jsonRpcResponse, { + result + }) : result + }); + } catch (error) { + return _extends$2({}, message, { + data: isJsonRpcResponse ? _extends$2({}, jsonRpcResponse, { + error + }) : { + error } - return this.options.mutationFn(variables); - }, - onFail: (failureCount, error) => { - __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "failed", failureCount, error }); - }, - onPause: () => { - __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "pause" }); - }, - onContinue: () => { - __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "continue" }); - }, - retry: this.options.retry ?? 0, - retryDelay: this.options.retryDelay, - networkMode: this.options.networkMode, - canRun: () => __privateGet(this, _mutationCache).canRun(this) - })); - const restored = this.state.status === "pending"; - const isPaused = !__privateGet(this, _retryer2).canStart(); + }); + } + } + async request(request) { + await this.getAccount(); try { - if (!restored) { - __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "pending", variables, isPaused }); - await ((_b2 = (_a2 = __privateGet(this, _mutationCache).config).onMutate) == null ? void 0 : _b2.call( - _a2, - variables, - this - )); - const context2 = await ((_d2 = (_c2 = this.options).onMutate) == null ? void 0 : _d2.call(_c2, variables)); - if (context2 !== this.state.context) { - __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { - type: "pending", - context: context2, - variables, - isPaused + var _this$account, _request$chainId; + if ((!this.account || this.account === null) && !permittedJsonRpcMethods.includes(request.method)) { + throw ErrSignedInRequired; + } + const account2 = this.account; + if (!account2) { + throw new Error("WalletRequestHandler: wallet account is not configured"); + } + const provider2 = (_this$account = this.account) == null ? void 0 : _this$account.providerFor((_request$chainId = request.chainId) != null ? _request$chainId : this.defaultChainId()); + if (!provider2) { + throw new Error(`WalletRequestHandler: wallet provider is not configured for chainId ${request.chainId}`); + } + const jsonRpcProvider = provider2 instanceof JsonRpcProvider$1 ? provider2 : void 0; + switch (request.method) { + case "net_version": { + if (!jsonRpcProvider) { + throw new Error(`Account provider doesn't support send method`); + } + return await jsonRpcProvider.send("net_version", []); + } + case "eth_chainId": { + if (!jsonRpcProvider) { + throw new Error(`Account provider doesn't support send method`); + } + return await jsonRpcProvider.send("eth_chainId", []); + } + case "eth_accounts": { + return [account2.address]; + } + case "eth_getBalance": { + const [accountAddress, blockTag] = request.params; + const walletBalance = await provider2.getBalance(accountAddress, blockTag); + return toHexString(walletBalance); + } + case "sequence_sign": + case "personal_sign": + case "eth_sign": { + let message; + switch (request.method) { + case "sequence_sign": + case "personal_sign": { + const [data, _address] = request.params; + message = data; + break; + } + case "eth_sign": { + const [_address, data] = request.params; + message = data; + break; + } + } + let sig = ""; + const prefixedMessage = prefixEIP191Message(message); + const sequenceVerified = request.method === "sequence_sign"; + if (this.prompter === null) { + var _request$chainId2; + sig = await account2.signMessage(prefixedMessage, (_request$chainId2 = request.chainId) != null ? _request$chainId2 : this.defaultChainId(), sequenceVerified ? "eip6492" : "ignore"); + } else { + sig = await this.prompter.promptSignMessage({ + chainId: request.chainId, + message: getBytes(prefixedMessage), + eip6492: sequenceVerified + }, this.connectOptions); + } + if (sig && sig.length > 0) { + return sig; + } else { + throw new Error("declined by user"); + } + } + case "sequence_signTypedData_v4": + case "eth_signTypedData": + case "eth_signTypedData_v4": { + const [signingAddress, typedDataObject] = request.params; + let typedData = void 0; + if (typeof typedDataObject === "string") { + try { + typedData = JSON.parse(typedDataObject); + } catch (e2) { + console.warn("walletRequestHandler: error parsing typedData", e2); + } + } else { + typedData = typedDataObject; + } + if (!typedData || !typedData.domain || !typedData.types || !typedData.message) { + throw new Error("invalid typedData object"); + } + let sig = ""; + const sequenceVerified = request.method === "sequence_signTypedData_v4"; + if (this.prompter === null) { + var _request$chainId3; + sig = await account2.signTypedData(typedData.domain, typedData.types, typedData.message, (_request$chainId3 = request.chainId) != null ? _request$chainId3 : this.defaultChainId(), sequenceVerified ? "eip6492" : "ignore"); + } else { + sig = await this.prompter.promptSignMessage({ + chainId: request.chainId, + typedData, + eip6492: sequenceVerified + }, this.connectOptions); + } + if (sig && sig.length > 0) { + return sig; + } else { + throw new Error("declined by user"); + } + } + case "eth_sendTransaction": { + const transactionParams = fromExtended(request.params[0]).map((tx) => { + if ("gas" in tx && tx.gasLimit === void 0) { + tx.gasLimit = tx.gas; + delete tx.gas; + } + return tx; }); + validateTransactionRequest(account2.address, transactionParams); + let txnHash = ""; + if (this.prompter === null) { + var _request$chainId4, _txnResponse$hash; + const txnResponse = await account2.sendTransaction(transactionParams, (_request$chainId4 = request.chainId) != null ? _request$chainId4 : this.defaultChainId()); + txnHash = (_txnResponse$hash = txnResponse == null ? void 0 : txnResponse.hash) != null ? _txnResponse$hash : ""; + } else { + txnHash = await this.prompter.promptSendTransaction(transactionParams, request.chainId, this.connectOptions); + } + if (txnHash) { + return txnHash; + } else { + throw new Error("declined by user"); + } + } + case "eth_signTransaction": { + const [transaction2] = request.params; + const sender = getAddress(transaction2.from); + if (sender !== account2.address) { + throw new Error("sender address does not match wallet"); + } + validateTransactionRequest(account2.address, transaction2); + if (this.prompter === null) { + var _request$chainId5; + return await account2.signTransactions(transaction2, (_request$chainId5 = request.chainId) != null ? _request$chainId5 : this.defaultChainId()); + } else { + return await this.prompter.promptSignTransaction(transaction2, request.chainId, this.connectOptions); + } + } + case "eth_sendRawTransaction": { + if (index$1$1.transaction.isSignedTransactionBundle(request.params[0])) { + const txChainId = Number(request.params[0].chainId); + const tx = await account2.relayer(txChainId).relay(request.params[0]); + return tx.hash; + } else { + const tx = await provider2.broadcastTransaction(request.params[0]); + return tx.hash; + } + } + case "eth_getTransactionCount": { + const address = getAddress(request.params[0]); + const tag = request.params[1]; + const count2 = await provider2.getTransactionCount(address, tag); + return toHexString(BigInt(count2)); + } + case "eth_blockNumber": { + return await provider2.getBlockNumber(); + } + case "eth_getBlockByNumber": { + return await provider2.getBlock( + request.params[0] + /* , jsonRpcRequest.params[1] */ + ); + } + case "eth_getBlockByHash": { + return await provider2.getBlock( + request.params[0] + /* , jsonRpcRequest.params[1] */ + ); + } + case "eth_getTransactionByHash": { + return await provider2.getTransaction(request.params[0]); + } + case "eth_call": { + const [transactionObject, blockTag] = request.params; + return await provider2.call(_extends$2({}, transactionObject, { + blockTag + })); + } + case "eth_getCode": { + const [contractAddress, blockTag] = request.params; + return await provider2.getCode(contractAddress, blockTag); + } + case "eth_estimateGas": { + const [transactionObject] = request.params; + return await provider2.estimateGas(transactionObject); + } + case "eth_gasPrice": { + const feeData = await provider2.getFeeData(); + return feeData.gasPrice === null ? null : toHexString(feeData.gasPrice); + } + case "wallet_switchEthereumChain": { + const [switchParams] = request.params; + if (!switchParams.chainId || switchParams.chainId.length === 0) { + throw new Error("invalid chainId"); + } + const chainId = BigInt(switchParams.chainId); + this.setDefaultChainId(Number(chainId)); + return null; + } + case "sequence_getWalletContext": { + return account2.contexts; + } + case "sequence_getWalletConfig": { + const [chainId] = request.params; + if (chainId) { + return [(await account2.status(chainId)).onChain.config]; + } else { + return await Promise.all(account2.networks.map(async function(network2) { + const status = await account2.status(network2.chainId); + return status.onChain.config; + })); + } + } + case "sequence_getWalletState": { + const [chainId] = request.params; + if (chainId) { + return [getLegacyWalletState(chainId, await account2.status(chainId))]; + } else { + return await Promise.all(account2.networks.map(async function(network2) { + const status = await account2.status(network2.chainId); + return getLegacyWalletState(network2.chainId, status); + })); + } + } + case "sequence_getNetworks": { + return await this.getNetworks(true); + } + case "sequence_isSequence": { + return true; + } + case "sequence_updateConfig": { + throw new Error("sequence_updateConfig method is not allowed from a dapp"); + } + case "sequence_publishConfig": { + throw new Error("sequence_publishConfig method is not allowed from a dapp"); + } + case "sequence_gasRefundOptions": { + break; + } + case "sequence_getNonce": { + break; + } + case "sequence_relay": { + break; + } + case "sequence_setDefaultNetwork": { + const [defaultChainId] = request.params; + if (!defaultChainId) { + throw new Error("invalid request, method argument defaultChainId cannot be empty"); + } + this.setDefaultChainId(defaultChainId); + return await this.getNetworks(true); + } + default: { + if (!jsonRpcProvider) { + throw new Error(`Account provider doesn't support send method`); + } + return await jsonRpcProvider.send(request.method, request.params); } } - const data = await __privateGet(this, _retryer2).start(); - await ((_f2 = (_e2 = __privateGet(this, _mutationCache).config).onSuccess) == null ? void 0 : _f2.call( - _e2, - data, - variables, - this.state.context, - this - )); - await ((_h2 = (_g2 = this.options).onSuccess) == null ? void 0 : _h2.call(_g2, data, variables, this.state.context)); - await ((_j2 = (_i2 = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _j2.call( - _i2, - data, - null, - this.state.variables, - this.state.context, - this - )); - await ((_l2 = (_k2 = this.options).onSettled) == null ? void 0 : _l2.call(_k2, data, null, variables, this.state.context)); - __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "success", data }); - return data; - } catch (error) { - try { - await ((_n = (_m2 = __privateGet(this, _mutationCache).config).onError) == null ? void 0 : _n.call( - _m2, - error, - variables, - this.state.context, - this - )); - await ((_p = (_o = this.options).onError) == null ? void 0 : _p.call( - _o, - error, - variables, - this.state.context - )); - await ((_r2 = (_q = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _r2.call( - _q, - void 0, - error, - this.state.variables, - this.state.context, - this - )); - await ((_t = (_s2 = this.options).onSettled) == null ? void 0 : _t.call( - _s2, - void 0, - error, - variables, - this.state.context - )); - throw error; - } finally { - __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "error", error }); - } - } finally { - __privateGet(this, _mutationCache).runNext(this); + } catch (err) { + logger.error(err); + throw { + message: typeof err == "string" ? err : (err == null ? void 0 : err.message) || "unkown error", + code: 4001 + }; } } -}, _observers = new WeakMap(), _mutationCache = new WeakMap(), _retryer2 = new WeakMap(), _Mutation_instances = new WeakSet(), dispatch_fn2 = function(action) { - const reducer = (state) => { - switch (action.type) { - case "failed": - return { - ...state, - failureCount: action.failureCount, - failureReason: action.error - }; - case "pause": - return { - ...state, - isPaused: true - }; - case "continue": - return { - ...state, - isPaused: false - }; - case "pending": - return { - ...state, - context: action.context, - data: void 0, - failureCount: 0, - failureReason: null, - error: null, - isPaused: action.isPaused, - status: "pending", - variables: action.variables, - submittedAt: Date.now() - }; - case "success": - return { - ...state, - data: action.data, - failureCount: 0, - failureReason: null, - error: null, - status: "success", - isPaused: false - }; - case "error": - return { - ...state, - data: void 0, - error: action.error, - failureCount: state.failureCount + 1, - failureReason: action.error, - isPaused: false, - status: "error" - }; - } - }; - this.state = reducer(this.state); - notifyManager.batch(() => { - __privateGet(this, _observers).forEach((observer) => { - observer.onMutationUpdate(action); - }); - __privateGet(this, _mutationCache).notify({ - mutation: this, - type: "updated", - action - }); - }); -}, _i); -function getDefaultState() { - return { - context: void 0, - data: void 0, - error: null, - failureCount: 0, - failureReason: null, - isPaused: false, - status: "idle", - variables: void 0, - submittedAt: 0 - }; -} -var MutationCache = (_j = class extends Subscribable { - constructor(config2 = {}) { - super(); - __privateAdd(this, _mutations); - __privateAdd(this, _mutationId); - this.config = config2; - __privateSet(this, _mutations, /* @__PURE__ */ new Map()); - __privateSet(this, _mutationId, Date.now()); + on(event, fn) { + this.events.on(event, fn); } - build(client2, options, state) { - const mutation = new Mutation({ - mutationCache: this, - mutationId: ++__privateWrapper(this, _mutationId)._, - options: client2.defaultMutationOptions(options), - state - }); - this.add(mutation); - return mutation; + once(event, fn) { + this.events.once(event, fn); } - add(mutation) { - const scope = scopeFor(mutation); - const mutations = __privateGet(this, _mutations).get(scope) ?? []; - mutations.push(mutation); - __privateGet(this, _mutations).set(scope, mutations); - this.notify({ type: "added", mutation }); + async getAddress() { + var _this$account$address, _this$account2; + return (_this$account$address = (_this$account2 = this.account) == null ? void 0 : _this$account2.address) != null ? _this$account$address : ""; } - remove(mutation) { - var _a2; - const scope = scopeFor(mutation); - if (__privateGet(this, _mutations).has(scope)) { - const mutations = (_a2 = __privateGet(this, _mutations).get(scope)) == null ? void 0 : _a2.filter((x2) => x2 !== mutation); - if (mutations) { - if (mutations.length === 0) { - __privateGet(this, _mutations).delete(scope); - } else { - __privateGet(this, _mutations).set(scope, mutations); - } - } - } - this.notify({ type: "removed", mutation }); + get openIntent() { + return this._openIntent; } - canRun(mutation) { - var _a2; - const firstPendingMutation = (_a2 = __privateGet(this, _mutations).get(scopeFor(mutation))) == null ? void 0 : _a2.find((m2) => m2.state.status === "pending"); - return !firstPendingMutation || firstPendingMutation === mutation; + setOpenIntent(intent) { + this._openIntent = intent; } - runNext(mutation) { - var _a2; - const foundMutation = (_a2 = __privateGet(this, _mutations).get(scopeFor(mutation))) == null ? void 0 : _a2.find((m2) => m2 !== mutation && m2.state.isPaused); - return (foundMutation == null ? void 0 : foundMutation.continue()) ?? Promise.resolve(); + get connectOptions() { + return this._connectOptions; } - clear() { - notifyManager.batch(() => { - this.getAll().forEach((mutation) => { - this.remove(mutation); - }); - }); + setConnectOptions(options) { + var _this$onConnectOption; + this._connectOptions = options; + (_this$onConnectOption = this.onConnectOptionsChange) == null || _this$onConnectOption.call(this, options); } - getAll() { - return [...__privateGet(this, _mutations).values()].flat(); + async setDefaultChainId(chainId) { + var _this$prompter4; + await ((_this$prompter4 = this.prompter) == null ? void 0 : _this$prompter4.promptChangeNetwork(chainId)); + return this.defaultChainId(); } - find(filters) { - const defaultedFilters = { exact: true, ...filters }; - return this.getAll().find( - (mutation) => matchMutation(defaultedFilters, mutation) - ); + async getNetworks(jsonRpcResponse) { + if (!this.account) { + logger.warn("signer not set: getNetworks is returning an empty list"); + return []; + } + if (jsonRpcResponse) { + return this.account.networks.map((n2) => { + const network2 = _extends$2({}, n2); + network2.provider = void 0; + network2.relayer = void 0; + return network2; + }); + } else { + return this.account.networks; + } } - findAll(filters = {}) { - return this.getAll().filter((mutation) => matchMutation(filters, mutation)); + walletSession(networkId) { + if (!this.account) { + return void 0; + } + const session = { + walletContext: this.account.contexts, + accountAddress: this.account.address, + // The dapp shouldn't access the relayer directly, and the provider (as an object) is not serializable. + networks: this.account.networks.map((n2) => _extends$2({}, n2, { + provider: void 0, + relayer: void 0 + })) + }; + if (networkId) { + const network2 = findNetworkConfig(session.networks, networkId); + if (network2) { + var _session$networks; + (_session$networks = session.networks) == null || _session$networks.forEach((n2) => delete n2.isDefaultChain); + network2.isDefaultChain = true; + } + } + return session; } - notify(event) { - notifyManager.batch(() => { - this.listeners.forEach((listener) => { - listener(event); - }); - }); + notifyConnect(connectDetails, origin) { + var _connectDetails$sessi; + console.log("emit connect", connectDetails); + this.events.emit("connect", connectDetails); + if ((_connectDetails$sessi = connectDetails.session) != null && _connectDetails$sessi.accountAddress) { + var _connectDetails$sessi2; + this.events.emit("accountsChanged", [(_connectDetails$sessi2 = connectDetails.session) == null ? void 0 : _connectDetails$sessi2.accountAddress], origin); + } } - resumePausedMutations() { - const pausedMutations = this.getAll().filter((x2) => x2.state.isPaused); - return notifyManager.batch( - () => Promise.all( - pausedMutations.map((mutation) => mutation.continue().catch(noop$1)) - ) - ); + notifyDisconnect(origin) { + this.events.emit("accountsChanged", [], origin); + this.events.emit("disconnect", void 0, origin); } -}, _mutations = new WeakMap(), _mutationId = new WeakMap(), _j); -function scopeFor(mutation) { - var _a2; - return ((_a2 = mutation.options.scope) == null ? void 0 : _a2.id) ?? String(mutation.mutationId); -} -function infiniteQueryBehavior(pages) { - return { - onFetch: (context2, query) => { - var _a2, _b2, _c2, _d2, _e2; - const options = context2.options; - const direction = (_c2 = (_b2 = (_a2 = context2.fetchOptions) == null ? void 0 : _a2.meta) == null ? void 0 : _b2.fetchMore) == null ? void 0 : _c2.direction; - const oldPages = ((_d2 = context2.state.data) == null ? void 0 : _d2.pages) || []; - const oldPageParams = ((_e2 = context2.state.data) == null ? void 0 : _e2.pageParams) || []; - let result = { pages: [], pageParams: [] }; - let currentPage = 0; - const fetchFn = async () => { - let cancelled = false; - const addSignalProperty = (object2) => { - Object.defineProperty(object2, "signal", { - enumerable: true, - get: () => { - if (context2.signal.aborted) { - cancelled = true; - } else { - context2.signal.addEventListener("abort", () => { - cancelled = true; - }); - } - return context2.signal; - } - }); - }; - const queryFn = ensureQueryFn(context2.options, context2.fetchOptions); - const fetchPage = async (data, param, previous) => { - if (cancelled) { - return Promise.reject(); - } - if (param == null && data.pages.length) { - return Promise.resolve(data); - } - const queryFnContext = { - queryKey: context2.queryKey, - pageParam: param, - direction: previous ? "backward" : "forward", - meta: context2.options.meta - }; - addSignalProperty(queryFnContext); - const page = await queryFn( - queryFnContext - ); - const { maxPages } = context2.options; - const addTo = previous ? addToStart : addToEnd; - return { - pages: addTo(data.pages, page, maxPages), - pageParams: addTo(data.pageParams, param, maxPages) - }; - }; - if (direction && oldPages.length) { - const previous = direction === "backward"; - const pageParamFn = previous ? getPreviousPageParam : getNextPageParam; - const oldData = { - pages: oldPages, - pageParams: oldPageParams - }; - const param = pageParamFn(options, oldData); - result = await fetchPage(oldData, param, previous); - } else { - const remainingPages = pages ?? oldPages.length; - do { - const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result); - if (currentPage > 0 && param == null) { - break; - } - result = await fetchPage(result, param); - currentPage++; - } while (currentPage < remainingPages); - } - return result; - }; - if (context2.options.persister) { - context2.fetchFn = () => { - var _a3, _b3; - return (_b3 = (_a3 = context2.options).persister) == null ? void 0 : _b3.call( - _a3, - fetchFn, - { - queryKey: context2.queryKey, - meta: context2.options.meta, - signal: context2.signal - }, - query - ); - }; - } else { - context2.fetchFn = fetchFn; + notifyChainChanged(chainId, origin) { + this.events.emit("chainChanged", toQuantity(chainId), origin); + } + async notifyNetworks(networks2) { + const n2 = networks2 || await this.getNetworks(true); + this.events.emit("networks", n2); + if (n2.length > 0) { + const defaultNetwork = n2.find((network2) => network2.chainId === this.defaultChainId()); + if (defaultNetwork) { + this.events.emit("chainChanged", toQuantity(defaultNetwork.chainId)); } + } else { + this.events.emit("chainChanged", "0x0"); } - }; -} -function getNextPageParam(options, { pages, pageParams }) { - const lastIndex = pages.length - 1; - return pages.length > 0 ? options.getNextPageParam( - pages[lastIndex], - pages, - pageParams[lastIndex], - pageParams - ) : void 0; -} -function getPreviousPageParam(options, { pages, pageParams }) { - var _a2; - return pages.length > 0 ? (_a2 = options.getPreviousPageParam) == null ? void 0 : _a2.call(options, pages[0], pages, pageParams[0], pageParams) : void 0; -} -function hasNextPage(options, data) { - if (!data) - return false; - return getNextPageParam(options, data) != null; -} -function hasPreviousPage(options, data) { - if (!data || !options.getPreviousPageParam) - return false; - return getPreviousPageParam(options, data) != null; -} -var QueryClient = (_k = class { - constructor(config2 = {}) { - __privateAdd(this, _queryCache); - __privateAdd(this, _mutationCache2); - __privateAdd(this, _defaultOptions2); - __privateAdd(this, _queryDefaults); - __privateAdd(this, _mutationDefaults); - __privateAdd(this, _mountCount); - __privateAdd(this, _unsubscribeFocus); - __privateAdd(this, _unsubscribeOnline); - __privateSet(this, _queryCache, config2.queryCache || new QueryCache()); - __privateSet(this, _mutationCache2, config2.mutationCache || new MutationCache()); - __privateSet(this, _defaultOptions2, config2.defaultOptions || {}); - __privateSet(this, _queryDefaults, /* @__PURE__ */ new Map()); - __privateSet(this, _mutationDefaults, /* @__PURE__ */ new Map()); - __privateSet(this, _mountCount, 0); } - mount() { - __privateWrapper(this, _mountCount)._++; - if (__privateGet(this, _mountCount) !== 1) + async notifyWalletContext() { + if (!this.account) { + logger.warn("signer not set: skipping to notify wallet context"); return; - __privateSet(this, _unsubscribeFocus, focusManager.subscribe(async (focused) => { - if (focused) { - await this.resumePausedMutations(); - __privateGet(this, _queryCache).onFocus(); + } + const walletContext = this.account.contexts; + this.events.emit("walletContext", walletContext); + } + notifyClose(error) { + this.events.emit("close", error); + } + setAccount(account2) { + this.account = account2; + if (account2 !== void 0) { + for (let i = 0; i < this.signerReadyCallbacks.length; i++) { + this.signerReadyCallbacks[i](); } - })); - __privateSet(this, _unsubscribeOnline, onlineManager.subscribe(async (online) => { - if (online) { - await this.resumePausedMutations(); - __privateGet(this, _queryCache).onOnline(); + this.signerReadyCallbacks = []; + } + } + async handleConfirmWalletDeployPrompt(prompter, account2, sequenceVerified, chainId) { + if (!chainId) { + return true; + } + const skipsDeploy = (status2) => { + return status2.canOnchainValidate || status2.original.version === 2 && sequenceVerified; + }; + const status = await account2.status(chainId); + if (skipsDeploy(status)) { + return true; + } + const promptResult = await prompter.promptConfirmWalletDeploy(chainId, this.connectOptions); + if (promptResult) { + const status2 = await account2.status(chainId); + if (skipsDeploy(status2)) { + return true; + } else { + logger.error("WalletRequestHandler: result for promptConfirmWalletDeploy is not correct"); + return false; } - })); + } + return false; } - unmount() { - var _a2, _b2; - __privateWrapper(this, _mountCount)._--; - if (__privateGet(this, _mountCount) !== 0) - return; - (_a2 = __privateGet(this, _unsubscribeFocus)) == null ? void 0 : _a2.call(this); - __privateSet(this, _unsubscribeFocus, void 0); - (_b2 = __privateGet(this, _unsubscribeOnline)) == null ? void 0 : _b2.call(this); - __privateSet(this, _unsubscribeOnline, void 0); +} +function getLegacyWalletState(chainId, status) { + return { + context: status.original.context, + config: status.onChain.config, + address: index$1$1.context.addressOf(status.original.context, status.original.imageHash), + chainId, + deployed: status.onChain.deployed, + imageHash: status.imageHash, + lastImageHash: status.onChain.imageHash, + published: true, + status + }; +} +const permittedJsonRpcMethods = ["net_version", "eth_chainId", "eth_getBalance", "eth_getTransactionCount", "eth_blockNumber", "eth_getBlockByNumber", "eth_getBlockByHash", "eth_getTransactionByHash", "eth_getCode", "eth_estimateGas", "eth_gasPrice", "sequence_getWalletContext", "sequence_getNetworks", "sequence_setDefaultNetwork"]; +function _objectWithoutPropertiesLoose$3(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; } - isFetching(filters) { - return __privateGet(this, _queryCache).findAll({ ...filters, fetchStatus: "fetching" }).length; + return target; +} +class SequenceSigner { + get utils() { + return this.provider.utils; } - isMutating(filters) { - return __privateGet(this, _mutationCache2).findAll({ ...filters, status: "pending" }).length; + constructor(client2, provider2) { + this.client = client2; + this.provider = provider2; + this.singleNetworkSigners = {}; + this._isSequenceSigner = true; } - getQueryData(queryKey) { - var _a2; - const options = this.defaultQueryOptions({ queryKey }); - return (_a2 = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a2.state.data; + async getAddress() { + return this.client.getAddress(); } - ensureQueryData(options) { - const cachedData = this.getQueryData(options.queryKey); - if (cachedData === void 0) - return this.fetchQuery(options); - else { - const defaultedOptions = this.defaultQueryOptions(options); - const query = __privateGet(this, _queryCache).build(this, defaultedOptions); - if (options.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) { - void this.prefetchQuery(defaultedOptions); - } - return Promise.resolve(cachedData); + // This method shouldn't be used directly + // it exists to maintain compatibility with ethers.Signer + connect(provider2) { + if (!SequenceProvider.is(provider2)) { + throw new Error("SequenceSigner can only be connected to a SequenceProvider"); } + return new SequenceSigner(this.client, provider2); } - getQueriesData(filters) { - return __privateGet(this, _queryCache).findAll(filters).map(({ queryKey, state }) => { - const data = state.data; - return [queryKey, data]; - }); - } - setQueryData(queryKey, updater, options) { - const defaultedOptions = this.defaultQueryOptions({ queryKey }); - const query = __privateGet(this, _queryCache).get( - defaultedOptions.queryHash - ); - const prevData = query == null ? void 0 : query.state.data; - const data = functionalUpdate(updater, prevData); - if (data === void 0) { - return void 0; + getSigner(chainId) { + if (!chainId) { + return this; } - return __privateGet(this, _queryCache).build(this, defaultedOptions).setData(data, { ...options, manual: true }); - } - setQueriesData(filters, updater, options) { - return notifyManager.batch( - () => __privateGet(this, _queryCache).findAll(filters).map(({ queryKey }) => [ - queryKey, - this.setQueryData(queryKey, updater, options) - ]) - ); + const useChainId2 = this.provider.toChainId(chainId); + if (!this.singleNetworkSigners[useChainId2]) { + this.singleNetworkSigners[useChainId2] = new SingleNetworkSequenceSigner(this.client, this.provider, useChainId2); + } + return this.singleNetworkSigners[useChainId2]; } - getQueryState(queryKey) { - var _a2; - const options = this.defaultQueryOptions({ queryKey }); - return (_a2 = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a2.state; + /** + * Resolves the chainId to use for the given request. If no chainId is provided, + * it uses the chainId defined by the client (default chainId). This can be + * overriden to build a single-network SequenceProvider. + */ + useChainId(chainId) { + return this.provider.toChainId(chainId) || this.client.getChainId(); } - removeQueries(filters) { - const queryCache = __privateGet(this, _queryCache); - notifyManager.batch(() => { - queryCache.findAll(filters).forEach((query) => { - queryCache.remove(query); - }); + async signMessage(message, options) { + const { + eip6492 = true + } = options || {}; + const chainId = this.useChainId(options == null ? void 0 : options.chainId); + return this.client.signMessage(message, { + eip6492, + chainId }); } - resetQueries(filters, options) { - const queryCache = __privateGet(this, _queryCache); - const refetchFilters = { - type: "active", - ...filters - }; - return notifyManager.batch(() => { - queryCache.findAll(filters).forEach((query) => { - query.reset(); - }); - return this.refetchQueries(refetchFilters, options); + async signTypedData(domain2, types2, message, options) { + const { + eip6492 = true + } = options || {}; + const chainId = this.useChainId(options == null ? void 0 : options.chainId); + return this.client.signTypedData({ + domain: domain2, + types: types2, + message + }, { + eip6492, + chainId }); } - cancelQueries(filters = {}, cancelOptions = {}) { - const defaultedCancelOptions = { revert: true, ...cancelOptions }; - const promises = notifyManager.batch( - () => __privateGet(this, _queryCache).findAll(filters).map((query) => query.cancel(defaultedCancelOptions)) - ); - return Promise.all(promises).then(noop$1).catch(noop$1); + getProvider(chainId) { + return this.provider.getProvider(chainId); } - invalidateQueries(filters = {}, options = {}) { - return notifyManager.batch(() => { - __privateGet(this, _queryCache).findAll(filters).forEach((query) => { - query.invalidate(); + async sendTransaction(transaction2, options) { + const chainId = this.useChainId(options == null ? void 0 : options.chainId); + const resolved = await resolveArrayProperties(transaction2); + const txHash = await this.client.sendTransaction(resolved, { + chainId + }); + const provider2 = this.getProvider(chainId); + try { + const result = await new Promise((resolve) => { + const check = async function check2() { + const tx = await provider2.getTransaction(txHash); + if (tx !== null) { + return resolve(tx); + } + await provider2.once("block", check2); + }; + check(); }); - if (filters.refetchType === "none") { - return Promise.resolve(); - } - const refetchFilters = { - ...filters, - type: filters.refetchType ?? filters.type ?? "active" - }; - return this.refetchQueries(refetchFilters, options); + return result; + } catch (err) { + err.transactionHash = txHash; + throw err; + } + } + async getWalletConfig(chainId) { + const useChainId2 = this.useChainId(chainId); + return this.client.getOnchainWalletConfig({ + chainId: useChainId2 }); } - refetchQueries(filters = {}, options) { - const fetchOptions = { - ...options, - cancelRefetch: (options == null ? void 0 : options.cancelRefetch) ?? true - }; - const promises = notifyManager.batch( - () => __privateGet(this, _queryCache).findAll(filters).filter((query) => !query.isDisabled()).map((query) => { - let promise = query.fetch(void 0, fetchOptions); - if (!fetchOptions.throwOnError) { - promise = promise.catch(noop$1); - } - return query.state.fetchStatus === "paused" ? Promise.resolve() : promise; - }) - ); - return Promise.all(promises).then(noop$1); + getNetworks() { + return this.client.getNetworks(); } - fetchQuery(options) { - const defaultedOptions = this.defaultQueryOptions(options); - if (defaultedOptions.retry === void 0) { - defaultedOptions.retry = false; - } - const query = __privateGet(this, _queryCache).build(this, defaultedOptions); - return query.isStaleByTime( - resolveStaleTime(defaultedOptions.staleTime, query) - ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data); + async getBalance(blockTag, optionals) { + const provider2 = this.getProvider(optionals == null ? void 0 : optionals.chainId); + return provider2.getBalance(this.getAddress(), blockTag); } - prefetchQuery(options) { - return this.fetchQuery(options).then(noop$1).catch(noop$1); + async estimateGas(transaction2, optionals) { + return this.getProvider(optionals == null ? void 0 : optionals.chainId).estimateGas(transaction2); } - fetchInfiniteQuery(options) { - options.behavior = infiniteQueryBehavior(options.pages); - return this.fetchQuery(options); + async call(transaction2, optionals) { + return this.getProvider(optionals == null ? void 0 : optionals.chainId).call(transaction2); } - prefetchInfiniteQuery(options) { - return this.fetchInfiniteQuery(options).then(noop$1).catch(noop$1); + getChainId() { + return Promise.resolve(this.client.getChainId()); } - ensureInfiniteQueryData(options) { - options.behavior = infiniteQueryBehavior(options.pages); - return this.ensureQueryData(options); + async getFeeData(optionals) { + return this.getProvider(optionals == null ? void 0 : optionals.chainId).getFeeData(); } - resumePausedMutations() { - if (onlineManager.isOnline()) { - return __privateGet(this, _mutationCache2).resumePausedMutations(); + async resolveName(name2) { + const res = await this.provider.resolveName(name2); + if (res === null) { + throw new Error(`ENS name not found: ${name2}`); } - return Promise.resolve(); + return res; } - getQueryCache() { - return __privateGet(this, _queryCache); + _checkProvider(_operation) { } - getMutationCache() { - return __privateGet(this, _mutationCache2); + getNonce(_blockTag) { + throw new Error("SequenceSigner does not support getNonce"); } - getDefaultOptions() { - return __privateGet(this, _defaultOptions2); + populateCall(_transaction) { + throw new Error("SequenceSigner does not support populateCall"); } - setDefaultOptions(options) { - __privateSet(this, _defaultOptions2, options); + populateTransaction(_transaction) { + throw new Error("SequenceSigner does not support populateTransaction"); } - setQueryDefaults(queryKey, options) { - __privateGet(this, _queryDefaults).set(hashKey(queryKey), { - queryKey, - defaultOptions: options - }); + checkTransaction(_transaction) { + throw new Error("SequenceSigner does not support checkTransaction"); } - getQueryDefaults(queryKey) { - const defaults2 = [...__privateGet(this, _queryDefaults).values()]; - let result = {}; - defaults2.forEach((queryDefault) => { - if (partialMatchKey(queryKey, queryDefault.queryKey)) { - result = { ...result, ...queryDefault.defaultOptions }; - } - }); - return result; + getTransactionCount(_blockTag) { + throw new Error("SequenceSigner does not support getTransactionCount"); } - setMutationDefaults(mutationKey, options) { - __privateGet(this, _mutationDefaults).set(hashKey(mutationKey), { - mutationKey, - defaultOptions: options - }); + signTransaction(_transaction) { + throw new Error("SequenceWallet does not support signTransaction, use sendTransaction instead."); } - getMutationDefaults(mutationKey) { - const defaults2 = [...__privateGet(this, _mutationDefaults).values()]; - let result = {}; - defaults2.forEach((queryDefault) => { - if (partialMatchKey(mutationKey, queryDefault.mutationKey)) { - result = { ...result, ...queryDefault.defaultOptions }; - } - }); - return result; + static is(cand) { + return cand && typeof cand === "object" && cand._isSequenceSigner === true; } - defaultQueryOptions(options) { - if (options._defaulted) { - return options; - } - const defaultedOptions = { - ...__privateGet(this, _defaultOptions2).queries, - ...this.getQueryDefaults(options.queryKey), - ...options, - _defaulted: true - }; - if (!defaultedOptions.queryHash) { - defaultedOptions.queryHash = hashQueryKeyByOptions( - defaultedOptions.queryKey, - defaultedOptions - ); - } - if (defaultedOptions.refetchOnReconnect === void 0) { - defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always"; - } - if (defaultedOptions.throwOnError === void 0) { - defaultedOptions.throwOnError = !!defaultedOptions.suspense; - } - if (!defaultedOptions.networkMode && defaultedOptions.persister) { - defaultedOptions.networkMode = "offlineFirst"; +} +class SingleNetworkSequenceSigner extends SequenceSigner { + constructor(client2, provider2, chainId) { + super(client2, provider2.getProvider(chainId)); + this.chainId = chainId; + this._isSingleNetworkSequenceSigner = true; + } + _useChainId(chainId) { + const provided = this.provider.toChainId(chainId); + if (provided && provided !== this.chainId) { + throw new Error(`This signer only supports the network ${this.chainId}, but ${provided} was requested.`); } - if (defaultedOptions.enabled !== true && defaultedOptions.queryFn === skipToken) { - defaultedOptions.enabled = false; + return provided || this.provider.toChainId(this.chainId); + } + useChainId(chainId) { + return this._useChainId(chainId); + } + getChainId() { + return Promise.resolve(this.provider.toChainId(this.chainId)); + } + /** + * Override getProvider and getSigner so they always use `useChainId` + * this way they can't return providers and signers that can switch networks, + * or that don't match the chainId of this signer. + */ + getProvider(chainId) { + return super.getProvider(this._useChainId(chainId)); + } + getSigner(chainId) { + if (this._useChainId(chainId) !== this.chainId) { + throw new Error(`Unreachable code`); } - return defaultedOptions; + return this; } - defaultMutationOptions(options) { - if (options == null ? void 0 : options._defaulted) { - return options; + static is(cand) { + return cand && typeof cand === "object" && cand._isSingleNetworkSequenceSigner === true; + } +} +class WalletUtils { + constructor(signer2) { + this.signer = signer2; + if (SingleNetworkSequenceSigner.is(signer2)) { + throw new Error("WalletUtils does not support SingleNetworkSequenceSigner"); } - return { - ...__privateGet(this, _defaultOptions2).mutations, - ...(options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey), - ...options, - _defaulted: true - }; } - clear() { - __privateGet(this, _queryCache).clear(); - __privateGet(this, _mutationCache2).clear(); + // Sign message on a specified chain, or DefaultChain by default + signMessage(message, chainId, eip6492) { + return this.signer.signMessage(message, { + chainId, + eip6492 + }); } -}, _queryCache = new WeakMap(), _mutationCache2 = new WeakMap(), _defaultOptions2 = new WeakMap(), _queryDefaults = new WeakMap(), _mutationDefaults = new WeakMap(), _mountCount = new WeakMap(), _unsubscribeFocus = new WeakMap(), _unsubscribeOnline = new WeakMap(), _k); -var QueryObserver = (_l = class extends Subscribable { - constructor(client2, options) { - super(); - __privateAdd(this, _QueryObserver_instances); - __privateAdd(this, _client); - __privateAdd(this, _currentQuery); - __privateAdd(this, _currentQueryInitialState); - __privateAdd(this, _currentResult); - __privateAdd(this, _currentResultState); - __privateAdd(this, _currentResultOptions); - __privateAdd(this, _selectError); - __privateAdd(this, _selectFn); - __privateAdd(this, _selectResult); - // This property keeps track of the last query with defined data. - // It will be used to pass the previous data and query to the placeholder function between renders. - __privateAdd(this, _lastQueryWithDefinedData); - __privateAdd(this, _staleTimeoutId); - __privateAdd(this, _refetchIntervalId); - __privateAdd(this, _currentRefetchInterval); - __privateAdd(this, _trackedProps, /* @__PURE__ */ new Set()); + // Sign EIP-712 TypedData on a specified chain, or DefaultChain by default + signTypedData(domain2, types2, message, chainId, eip6492) { + return this.signer.signTypedData(domain2, types2, message, { + chainId, + eip6492 + }); + } + // Verify signature of a digest, one of a message, typedData or other + async isValidSignature(address, digest, signature2, chainId) { + return isValidSignature(address, digest, signature2, this.signer.getProvider(chainId)); + } + // Verify message signature + async isValidMessageSignature(address, message, signature2, chainId) { + const provider2 = this.signer.getProvider(chainId); + const prefixed = prefixEIP191Message(message); + const digest = encodeMessageDigest(prefixed); + return isValidSignature(address, digest, signature2, provider2); + } + // Verify typedData signature + isValidTypedDataSignature(address, typedData, signature2, chainId) { + return this.isValidSignature(address, encodeTypedDataDigest(typedData), signature2, chainId); + } + // sendTransaction() + // sendTransactions() + // sendETH() + // sendToken() + // sendCoin() -- sugar for sendToken() + // sendCollectible() -- sugar for sendToken() + // callContract() + // transactionHistory() + // getReceipt() + // getLogs() + // // .. + // validateSignature() + // recoverWalletConfig() + // recoverAddress() +} +const _excluded$5 = ["method"]; +const EIP1193EventTypes = ["connect", "disconnect", "chainChanged", "accountsChanged"]; +class SequenceProvider extends AbstractProvider { + constructor(client2, providerFor, networks2 = allNetworks, options) { + super(client2.getChainId(), options); + this.client = client2; + this.providerFor = providerFor; + this.networks = networks2; this.options = options; - __privateSet(this, _client, client2); - __privateSet(this, _selectError, null); - this.bindMethods(); - this.setOptions(options); + this.singleNetworkProviders = {}; + this._isSequenceProvider = true; + this.utils = void 0; + this.signer = void 0; + this.eip1193EventListeners = /* @__PURE__ */ new Map(); + client2.onConnect((details) => { + var _this$eip1193EventLis; + (_this$eip1193EventLis = this.eip1193EventListeners.get("connect")) == null || _this$eip1193EventLis.forEach((listener) => listener(details)); + }); + client2.onDisconnect((error) => { + var _this$eip1193EventLis2; + (_this$eip1193EventLis2 = this.eip1193EventListeners.get("disconnect")) == null || _this$eip1193EventLis2.forEach((listener) => listener(error)); + }); + client2.onDefaultChainIdChanged((chainId) => { + var _this$eip1193EventLis3; + (_this$eip1193EventLis3 = this.eip1193EventListeners.get("chainChanged")) == null || _this$eip1193EventLis3.forEach((listener) => listener(chainId)); + }); + client2.onAccountsChanged((accounts) => { + var _this$eip1193EventLis4; + (_this$eip1193EventLis4 = this.eip1193EventListeners.get("accountsChanged")) == null || _this$eip1193EventLis4.forEach((listener) => listener(accounts)); + }); + this.signer = new SequenceSigner(this.client, this); + this.utils = new WalletUtils(this.signer); } - bindMethods() { - this.refetch = this.refetch.bind(this); + async on(event, listener) { + if (EIP1193EventTypes.includes(event)) { + const listeners = this.eip1193EventListeners.get(event) || /* @__PURE__ */ new Set(); + listeners.add(listener); + this.eip1193EventListeners.set(event, listeners); + return this; + } + return super.on(event, listener); } - onSubscribe() { - if (this.listeners.size === 1) { - __privateGet(this, _currentQuery).addObserver(this); - if (shouldFetchOnMount(__privateGet(this, _currentQuery), this.options)) { - __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this); - } else { - this.updateResult(); + async off(event, listener) { + if (EIP1193EventTypes.includes(event)) { + const listeners = this.eip1193EventListeners.get(event); + if (listeners) { + if (listener) { + listeners.delete(listener); + } else { + listeners.clear(); + } } - __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this); + return this; } + return super.off(event, listener); + } + getSigner(chainId) { + return this.signer.getSigner(chainId); + } + connect(options) { + return this.client.connect(options); } - onUnsubscribe() { - if (!this.hasListeners()) { - this.destroy(); - } + disconnect() { + return this.client.disconnect(); } - shouldFetchOnReconnect() { - return shouldFetchOn( - __privateGet(this, _currentQuery), - this.options, - this.options.refetchOnReconnect - ); + isConnected() { + return this.client.isConnected(); } - shouldFetchOnWindowFocus() { - return shouldFetchOn( - __privateGet(this, _currentQuery), - this.options, - this.options.refetchOnWindowFocus - ); + getSession() { + return this.client.getSession(); } - destroy() { - this.listeners = /* @__PURE__ */ new Set(); - __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this); - __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this); - __privateGet(this, _currentQuery).removeObserver(this); + listAccounts() { + return [this.client.getAddress()]; } - setOptions(options, notifyOptions) { - const prevOptions = this.options; - const prevQuery = __privateGet(this, _currentQuery); - this.options = __privateGet(this, _client).defaultQueryOptions(options); - if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== "boolean") { - throw new Error( - "Expected enabled to be a boolean or a callback that returns a boolean" - ); - } - __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this); - __privateGet(this, _currentQuery).setOptions(this.options); - if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) { - __privateGet(this, _client).getQueryCache().notify({ - type: "observerOptionsUpdated", - query: __privateGet(this, _currentQuery), - observer: this - }); - } - const mounted = this.hasListeners(); - if (mounted && shouldFetchOptionally( - __privateGet(this, _currentQuery), - prevQuery, - this.options, - prevOptions - )) { - __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this); - } - this.updateResult(notifyOptions); - if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || resolveStaleTime(this.options.staleTime, __privateGet(this, _currentQuery)) !== resolveStaleTime(prevOptions.staleTime, __privateGet(this, _currentQuery)))) { - __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this); - } - const nextRefetchInterval = __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this); - if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || nextRefetchInterval !== __privateGet(this, _currentRefetchInterval))) { - __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, nextRefetchInterval); - } + // @deprecated use getSigner() instead + getAddress() { + return this.client.getAddress(); } - getOptimisticResult(options) { - const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), options); - const result = this.createResult(query, options); - if (shouldAssignObserverCurrentProperties(this, result)) { - __privateSet(this, _currentResult, result); - __privateSet(this, _currentResultOptions, this.options); - __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state); - } - return result; + getNetworks() { + return this.client.getNetworks(); } - getCurrentResult() { - return __privateGet(this, _currentResult); + getChainId() { + return this.client.getChainId(); } - trackResult(result, onPropTracked) { - const trackedResult = {}; - Object.keys(result).forEach((key) => { - Object.defineProperty(trackedResult, key, { - configurable: false, - enumerable: true, - get: () => { - this.trackProp(key); - onPropTracked == null ? void 0 : onPropTracked(key); - return result[key]; - } - }); - }); - return trackedResult; + setDefaultChainId(chainId) { + return this.client.setDefaultChainId(this.toChainId(chainId)); } - trackProp(key) { - __privateGet(this, _trackedProps).add(key); + isOpened() { + return this.client.isOpened(); } - getCurrentQuery() { - return __privateGet(this, _currentQuery); + closeWallet() { + return this.client.closeWallet(); } - refetch({ ...options } = {}) { - return this.fetch({ - ...options + getWalletContext() { + return this.client.getWalletContext(); + } + // @deprecated use getSigner() instead + async getWalletConfig(chainId) { + const useChainId2 = await this.useChainId(chainId); + return this.client.getOnchainWalletConfig({ + chainId: useChainId2 }); } - fetchOptimistic(options) { - const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options); - const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), defaultedOptions); - query.isFetchingOptimistic = true; - return query.fetch().then(() => this.createResult(query, defaultedOptions)); + authorize(options) { + return this.client.connect(_extends$2({}, options, { + authorize: true + })); } - fetch(fetchOptions) { - return __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this, { - ...fetchOptions, - cancelRefetch: fetchOptions.cancelRefetch ?? true - }).then(() => { - this.updateResult(); - return __privateGet(this, _currentResult); - }); + async openWallet(path, intent) { + await this.client.openWallet(path, intent); + return true; } - createResult(query, options) { - var _a2; - const prevQuery = __privateGet(this, _currentQuery); - const prevOptions = this.options; - const prevResult = __privateGet(this, _currentResult); - const prevResultState = __privateGet(this, _currentResultState); - const prevResultOptions = __privateGet(this, _currentResultOptions); - const queryChange = query !== prevQuery; - const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState); - const { state } = query; - let newState = { ...state }; - let isPlaceholderData = false; - let data; - if (options._optimisticResults) { - const mounted = this.hasListeners(); - const fetchOnMount = !mounted && shouldFetchOnMount(query, options); - const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions); - if (fetchOnMount || fetchOptionally) { - newState = { - ...newState, - ...fetchState(state.data, query.options) - }; - } - if (options._optimisticResults === "isRestoring") { - newState.fetchStatus = "idle"; - } + toChainId(chainId) { + if (chainId === void 0) { + return void 0; } - let { error, errorUpdatedAt, status } = newState; - if (options.select && newState.data !== void 0) { - if (prevResult && newState.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === __privateGet(this, _selectFn)) { - data = __privateGet(this, _selectResult); - } else { - try { - __privateSet(this, _selectFn, options.select); - data = options.select(newState.data); - data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options); - __privateSet(this, _selectResult, data); - __privateSet(this, _selectError, null); - } catch (selectError) { - __privateSet(this, _selectError, selectError); - } - } - } else { - data = newState.data; + const resolved = findNetworkConfig(this.networks, chainId); + if (!resolved) { + throw new Error(`Unsupported network ${chainId}`); } - if (options.placeholderData !== void 0 && data === void 0 && status === "pending") { - let placeholderData; - if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) { - placeholderData = prevResult.data; - } else { - placeholderData = typeof options.placeholderData === "function" ? options.placeholderData( - (_a2 = __privateGet(this, _lastQueryWithDefinedData)) == null ? void 0 : _a2.state.data, - __privateGet(this, _lastQueryWithDefinedData) - ) : options.placeholderData; - if (options.select && placeholderData !== void 0) { - try { - placeholderData = options.select(placeholderData); - __privateSet(this, _selectError, null); - } catch (selectError) { - __privateSet(this, _selectError, selectError); - } - } - } - if (placeholderData !== void 0) { - status = "success"; - data = replaceData( - prevResult == null ? void 0 : prevResult.data, - placeholderData, - options - ); - isPlaceholderData = true; - } + return resolved.chainId; + } + /** + * Resolves the chainId to use for the given request. If no chainId is provided, + * it uses the chainId defined by the client (default chainId). This can be + * overriden to build a single-network SequenceProvider. + */ + async useChainId(chainId) { + return this.toChainId(chainId) || this.client.getChainId(); + } + /** + * This generates a provider that ONLY works for the given chainId. + * the generated provider can't switch networks, and can't handle requests + * for other networks. + */ + getProvider(chainId) { + if (!chainId) { + return this; } - if (__privateGet(this, _selectError)) { - error = __privateGet(this, _selectError); - data = __privateGet(this, _selectResult); - errorUpdatedAt = Date.now(); - status = "error"; + const useChainId2 = this.toChainId(chainId); + if (!this.singleNetworkProviders[useChainId2]) { + this.singleNetworkProviders[useChainId2] = new SingleNetworkSequenceProvider(this.client, this.providerFor, useChainId2, this.options); } - const isFetching = newState.fetchStatus === "fetching"; - const isPending = status === "pending"; - const isError2 = status === "error"; - const isLoading = isPending && isFetching; - const hasData = data !== void 0; - const result = { - status, - fetchStatus: newState.fetchStatus, - isPending, - isSuccess: status === "success", - isError: isError2, - isInitialLoading: isLoading, - isLoading, - data, - dataUpdatedAt: newState.dataUpdatedAt, - error, - errorUpdatedAt, - failureCount: newState.fetchFailureCount, - failureReason: newState.fetchFailureReason, - errorUpdateCount: newState.errorUpdateCount, - isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0, - isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount, - isFetching, - isRefetching: isFetching && !isPending, - isLoadingError: isError2 && !hasData, - isPaused: newState.fetchStatus === "paused", - isPlaceholderData, - isRefetchError: isError2 && hasData, - isStale: isStale(query, options), - refetch: this.refetch + return this.singleNetworkProviders[useChainId2]; + } + /** + * This returns a subprovider, this is a regular non-sequence provider that + * can be used to fulfill read only requests on a given network. + */ + async _getSubprovider(chainId) { + const useChainId2 = await this.useChainId(chainId); + const provider2 = this.providerFor(useChainId2); + if (!provider2) { + throw new Error(`Unsupported network ${useChainId2}`); + } + return provider2; + } + async _perform(req) { + var _provider$getRpcReque; + const { + method + } = req, args = _objectWithoutPropertiesLoose$3(req, _excluded$5); + const provider2 = await this._getSubprovider(); + const prepared = (_provider$getRpcReque = provider2.getRpcRequest(req)) != null ? _provider$getRpcReque : { + method, + args: Object.values(args) }; - return result; + if (!prepared) { + throw new Error(`Unsupported method ${req.method}`); + } + return provider2.send(prepared.method, prepared.args); } - updateResult(notifyOptions) { - const prevResult = __privateGet(this, _currentResult); - const nextResult = this.createResult(__privateGet(this, _currentQuery), this.options); - __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state); - __privateSet(this, _currentResultOptions, this.options); - if (__privateGet(this, _currentResultState).data !== void 0) { - __privateSet(this, _lastQueryWithDefinedData, __privateGet(this, _currentQuery)); + async perform(method, params) { + if (method === "eth_chainId") { + return toQuantity(await this.useChainId()); } - if (shallowEqualObjects(nextResult, prevResult)) { - return; + if (method === "eth_accounts") { + return [this.client.getAddress()]; } - __privateSet(this, _currentResult, nextResult); - const defaultNotifyOptions = {}; - const shouldNotifyListeners = () => { - if (!prevResult) { - return true; - } - const { notifyOnChangeProps } = this.options; - const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps; - if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !__privateGet(this, _trackedProps).size) { - return true; - } - const includedProps = new Set( - notifyOnChangePropsValue ?? __privateGet(this, _trackedProps) - ); - if (this.options.throwOnError) { - includedProps.add("error"); - } - return Object.keys(__privateGet(this, _currentResult)).some((key) => { - const typedKey = key; - const changed = __privateGet(this, _currentResult)[typedKey] !== prevResult[typedKey]; - return changed && includedProps.has(typedKey); + if (method === "wallet_switchEthereumChain") { + const args = params[0]; + const chainId = normalizeChainId$2(args); + return this.setDefaultChainId(chainId); + } + if (method === "eth_sendTransaction" || method === "eth_sign" || method === "eth_signTypedData" || method === "eth_signTypedData_v4" || method === "personal_sign" || // These methods will use EIP-6492 + // but this is handled directly by the wallet + method === "sequence_sign" || method === "sequence_signTypedData_v4") { + return this.client.request({ + method, + params, + chainId: this.getChainId() }); - }; - if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) { - defaultNotifyOptions.listeners = true; } - __privateMethod(this, _QueryObserver_instances, notify_fn).call(this, { ...defaultNotifyOptions, ...notifyOptions }); + return this._perform(_extends$2({ + method + }, params)); } - onQueryUpdate() { - this.updateResult(); - if (this.hasListeners()) { - __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this); + send(method, params) { + return this.perform(method, params); + } + request(request) { + return this.perform(request.method, request.params); + } + async _detectNetwork() { + const chainId = this.client.getChainId(); + const found = findNetworkConfig(this.networks, chainId); + if (!found) { + throw new Error(`Unknown network ${chainId}`); } + const network2 = new Network(found.name, found.chainId); + return network2; } -}, _client = new WeakMap(), _currentQuery = new WeakMap(), _currentQueryInitialState = new WeakMap(), _currentResult = new WeakMap(), _currentResultState = new WeakMap(), _currentResultOptions = new WeakMap(), _selectError = new WeakMap(), _selectFn = new WeakMap(), _selectResult = new WeakMap(), _lastQueryWithDefinedData = new WeakMap(), _staleTimeoutId = new WeakMap(), _refetchIntervalId = new WeakMap(), _currentRefetchInterval = new WeakMap(), _trackedProps = new WeakMap(), _QueryObserver_instances = new WeakSet(), executeFetch_fn = function(fetchOptions) { - __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this); - let promise = __privateGet(this, _currentQuery).fetch( - this.options, - fetchOptions - ); - if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) { - promise = promise.catch(noop$1); + async detectNetwork() { + return this._detectNetwork(); } - return promise; -}, updateStaleTimeout_fn = function() { - __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this); - const staleTime = resolveStaleTime( - this.options.staleTime, - __privateGet(this, _currentQuery) - ); - if (isServer || __privateGet(this, _currentResult).isStale || !isValidTimeout(staleTime)) { - return; + // Override most of the methods, so we add support for an optional chainId + // argument, which is used to select the provider to use. + // + // NOTICE: We could use generics to avoid repeating the same code + // but this would make the code harder to read, and it's not worth it + // since we only have a few methods to override. + async waitForTransaction(transactionHash, confirmations, timeout, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.waitForTransaction(transactionHash, confirmations, timeout); } - const time2 = timeUntilStale(__privateGet(this, _currentResult).dataUpdatedAt, staleTime); - const timeout = time2 + 1; - __privateSet(this, _staleTimeoutId, setTimeout(() => { - if (!__privateGet(this, _currentResult).isStale) { - this.updateResult(); - } - }, timeout)); -}, computeRefetchInterval_fn = function() { - return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(__privateGet(this, _currentQuery)) : this.options.refetchInterval) ?? false; -}, updateRefetchInterval_fn = function(nextInterval) { - __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this); - __privateSet(this, _currentRefetchInterval, nextInterval); - if (isServer || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) === false || !isValidTimeout(__privateGet(this, _currentRefetchInterval)) || __privateGet(this, _currentRefetchInterval) === 0) { - return; + async getBlockNumber(optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.getBlockNumber(); } - __privateSet(this, _refetchIntervalId, setInterval(() => { - if (this.options.refetchIntervalInBackground || focusManager.isFocused()) { - __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this); - } - }, __privateGet(this, _currentRefetchInterval))); -}, updateTimers_fn = function() { - __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this); - __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this)); -}, clearStaleTimeout_fn = function() { - if (__privateGet(this, _staleTimeoutId)) { - clearTimeout(__privateGet(this, _staleTimeoutId)); - __privateSet(this, _staleTimeoutId, void 0); + async getFeeData(optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.getFeeData(); } -}, clearRefetchInterval_fn = function() { - if (__privateGet(this, _refetchIntervalId)) { - clearInterval(__privateGet(this, _refetchIntervalId)); - __privateSet(this, _refetchIntervalId, void 0); + async getBalance(addressOrName, blockTag, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.getBalance(addressOrName, blockTag); } -}, updateQuery_fn = function() { - const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), this.options); - if (query === __privateGet(this, _currentQuery)) { - return; + async getTransactionCount(addressOrName, blockTag, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.getTransactionCount(addressOrName, blockTag); } - const prevQuery = __privateGet(this, _currentQuery); - __privateSet(this, _currentQuery, query); - __privateSet(this, _currentQueryInitialState, query.state); - if (this.hasListeners()) { - prevQuery == null ? void 0 : prevQuery.removeObserver(this); - query.addObserver(this); + async getCode(addressOrName, blockTag, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.getCode(addressOrName, blockTag); } -}, notify_fn = function(notifyOptions) { - notifyManager.batch(() => { - if (notifyOptions.listeners) { - this.listeners.forEach((listener) => { - listener(__privateGet(this, _currentResult)); - }); + async getStorage(addressOrName, position, blockTag, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.getStorage(addressOrName, position, blockTag); + } + async call(transaction2, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.call(transaction2); + } + async estimateGas(transaction2, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.estimateGas(transaction2); + } + async getBlock(blockHashOrBlockTag, prefetchTxs, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.getBlock(blockHashOrBlockTag, prefetchTxs); + } + async getTransaction(transactionHash, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.getTransaction(transactionHash); + } + async getLogs(filter2, optionals) { + const provider2 = await this._getSubprovider(optionals == null ? void 0 : optionals.chainId); + return provider2.getLogs(filter2); + } + // ENS methods + async supportsENS() { + const networks2 = await this.getNetworks(); + return networks2.some((n2) => n2.chainId === 1); + } + async getResolver(name2) { + if (!await this.supportsENS()) { + return null; + } + const provider2 = await this._getSubprovider(1); + return provider2.getResolver(name2); + } + async resolveName(name2) { + if (isAddress(name2)) { + return name2; + } + if (!await this.supportsENS()) { + return null; + } + const provider2 = await this._getSubprovider(1); + return provider2.resolveName(name2); + } + async lookupAddress(address) { + if (!await this.supportsENS()) { + return null; + } + const provider2 = await this._getSubprovider(1); + return provider2.lookupAddress(address); + } + async getAvatar(nameOrAddress) { + if (!await this.supportsENS()) { + return null; } - __privateGet(this, _client).getQueryCache().notify({ - query: __privateGet(this, _currentQuery), - type: "observerResultsUpdated" - }); - }); -}, _l); -function shouldLoadOnMount(query, options) { - return resolveEnabled(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && options.retryOnMount === false); -} -function shouldFetchOnMount(query, options) { - return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount); -} -function shouldFetchOn(query, options, field) { - if (resolveEnabled(options.enabled, query) !== false) { - const value = typeof field === "function" ? field(query) : field; - return value === "always" || value !== false && isStale(query, options); + const provider2 = await this._getSubprovider(1); + return provider2.getAvatar(nameOrAddress); } - return false; -} -function shouldFetchOptionally(query, prevQuery, options, prevOptions) { - return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options); } -function isStale(query, options) { - return resolveEnabled(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query)); +SequenceProvider.is = (provider2) => { + return provider2 && typeof provider2 === "object" && provider2._isSequenceProvider === true; +}; +function normalizeChainId$2(chainId) { + if (typeof chainId === "object") return normalizeChainId$2(chainId.chainId); + return Number(chainId); } -function shouldAssignObserverCurrentProperties(observer, optimisticResult) { - if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) { - return true; +class SingleNetworkSequenceProvider extends SequenceProvider { + constructor(client2, providerFor, chainId, options) { + super(client2, providerFor, void 0, options); + this.chainId = chainId; + this._isSingleNetworkSequenceProvider = true; } - return false; -} -var InfiniteQueryObserver = class extends QueryObserver { - constructor(client2, options) { - super(client2, options); + _useChainId(chainId) { + const provided = this.toChainId(chainId); + if (provided && provided !== this.chainId) { + throw new Error(`This provider only supports the network ${this.chainId}, but ${provided} was requested.`); + } + return provided || super.toChainId(this.chainId); } - bindMethods() { - super.bindMethods(); - this.fetchNextPage = this.fetchNextPage.bind(this); - this.fetchPreviousPage = this.fetchPreviousPage.bind(this); + useChainId(chainId) { + return Promise.resolve(this._useChainId(chainId)); } - setOptions(options, notifyOptions) { - super.setOptions( - { - ...options, - behavior: infiniteQueryBehavior() - }, - notifyOptions - ); + getChainId() { + return super.toChainId(this.chainId); } - getOptimisticResult(options) { - options.behavior = infiniteQueryBehavior(); - return super.getOptimisticResult(options); + async getNetwork() { + const networks2 = await this.client.getNetworks(); + const found = findNetworkConfig(networks2, this.chainId); + if (!found) { + throw new Error(`Unsupported network ${this.chainId}`); + } + return new Network(found.name, found.chainId); } - fetchNextPage(options) { - return this.fetch({ - ...options, - meta: { - fetchMore: { direction: "forward" } - } - }); + /** + * Override getProvider and getSigner so they always use `useChainId` + * this way they can't return providers and signers that can switch networks, + * or that don't match the chainId of this signer. + */ + getProvider(chainId) { + if (this._useChainId(chainId) !== this.chainId) { + throw new Error(`Unreachable code`); + } + return this; } - fetchPreviousPage(options) { - return this.fetch({ - ...options, - meta: { - fetchMore: { direction: "backward" } - } - }); + getSigner(chainId) { + return super.getSigner(this._useChainId(chainId)); } - createResult(query, options) { - var _a2, _b2; - const { state } = query; - const parentResult = super.createResult(query, options); - const { isFetching, isRefetching, isError: isError2, isRefetchError } = parentResult; - const fetchDirection = (_b2 = (_a2 = state.fetchMeta) == null ? void 0 : _a2.fetchMore) == null ? void 0 : _b2.direction; - const isFetchNextPageError = isError2 && fetchDirection === "forward"; - const isFetchingNextPage = isFetching && fetchDirection === "forward"; - const isFetchPreviousPageError = isError2 && fetchDirection === "backward"; - const isFetchingPreviousPage = isFetching && fetchDirection === "backward"; - const result = { - ...parentResult, - fetchNextPage: this.fetchNextPage, - fetchPreviousPage: this.fetchPreviousPage, - hasNextPage: hasNextPage(options, state.data), - hasPreviousPage: hasPreviousPage(options, state.data), - isFetchNextPageError, - isFetchingNextPage, - isFetchPreviousPageError, - isFetchingPreviousPage, - isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError, - isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage - }; - return result; + setDefaultChainId(_chainId4) { + throw new Error(`This provider only supports the network ${this.chainId}; use the parent provider to switch networks.`); } -}; -var MutationObserver$1 = (_m = class extends Subscribable { - constructor(client2, options) { - super(); - __privateAdd(this, _MutationObserver_instances); - __privateAdd(this, _client2); - __privateAdd(this, _currentResult2); - __privateAdd(this, _currentMutation); - __privateAdd(this, _mutateOptions); - __privateSet(this, _client2, client2); - this.setOptions(options); - this.bindMethods(); - __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this); + static is(cand) { + return cand && typeof cand === "object" && cand._isSingleNetworkSequenceProvider === true; } - bindMethods() { - this.mutate = this.mutate.bind(this); - this.reset = this.reset.bind(this); +} +class Analytics extends Databeat2 { +} +const setupAnalytics = (projectAccessKey2, server) => { + if (!server) { + server = "https://nodes.sequence.app"; } - setOptions(options) { - var _a2; - const prevOptions = this.options; - this.options = __privateGet(this, _client2).defaultMutationOptions(options); - if (!shallowEqualObjects(this.options, prevOptions)) { - __privateGet(this, _client2).getMutationCache().notify({ - type: "observerOptionsUpdated", - mutation: __privateGet(this, _currentMutation), - observer: this - }); - } - if ((prevOptions == null ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) { - this.reset(); - } else if (((_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.state.status) === "pending") { - __privateGet(this, _currentMutation).setOptions(this.options); + const noop2 = !projectAccessKey2; + const auth2 = {}; + if (projectAccessKey2) { + auth2.headers = { + "X-Access-Key": projectAccessKey2 + }; + } + return new Analytics(server, auth2, { + noop: noop2, + defaultEnabled: true, + privacy: { + userIdHash: true, + userAgentSalt: false + }, + initProps: () => { + if (!isBrowser()) { + return {}; + } else { + return { + origin: window.location.origin + }; + } } + }); +}; +class SequenceClientSession { + constructor(store) { + this.store = store; } - onUnsubscribe() { - var _a2; - if (!this.hasListeners()) { - (_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.removeObserver(this); + connectedSession() { + const session = this.getSession(); + if (session && session.accountAddress && session.walletContext && session.networks) { + return { + accountAddress: session.accountAddress, + walletContext: session.walletContext, + networks: session.networks + }; } + throw new Error("Sequence session not connected"); } - onMutationUpdate(action) { - __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this); - __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this, action); + hasSession() { + var _this$getSession; + return ((_this$getSession = this.getSession()) == null ? void 0 : _this$getSession.accountAddress) !== void 0; } - getCurrentResult() { - return __privateGet(this, _currentResult2); + setSession(session) { + return this.store.setItem(SequenceClientSession.SESSION_LOCALSTORE_KEY, JSON.stringify(session)); } - reset() { - var _a2; - (_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.removeObserver(this); - __privateSet(this, _currentMutation, void 0); - __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this); - __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this); + getSession() { + const session = this.store.getItem(SequenceClientSession.SESSION_LOCALSTORE_KEY); + if (session) { + return JSON.parse(session); + } + return void 0; } - mutate(variables, options) { - var _a2; - __privateSet(this, _mutateOptions, options); - (_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.removeObserver(this); - __privateSet(this, _currentMutation, __privateGet(this, _client2).getMutationCache().build(__privateGet(this, _client2), this.options)); - __privateGet(this, _currentMutation).addObserver(this); - return __privateGet(this, _currentMutation).execute(variables); + async clearSession() { + return this.store.removeItem(SequenceClientSession.SESSION_LOCALSTORE_KEY); } -}, _client2 = new WeakMap(), _currentResult2 = new WeakMap(), _currentMutation = new WeakMap(), _mutateOptions = new WeakMap(), _MutationObserver_instances = new WeakSet(), updateResult_fn = function() { - var _a2; - const state = ((_a2 = __privateGet(this, _currentMutation)) == null ? void 0 : _a2.state) ?? getDefaultState(); - __privateSet(this, _currentResult2, { - ...state, - isPending: state.status === "pending", - isSuccess: state.status === "success", - isError: state.status === "error", - isIdle: state.status === "idle", - mutate: this.mutate, - reset: this.reset - }); -}, notify_fn2 = function(action) { - notifyManager.batch(() => { - var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2; - if (__privateGet(this, _mutateOptions) && this.hasListeners()) { - const variables = __privateGet(this, _currentResult2).variables; - const context2 = __privateGet(this, _currentResult2).context; - if ((action == null ? void 0 : action.type) === "success") { - (_b2 = (_a2 = __privateGet(this, _mutateOptions)).onSuccess) == null ? void 0 : _b2.call(_a2, action.data, variables, context2); - (_d2 = (_c2 = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _d2.call(_c2, action.data, null, variables, context2); - } else if ((action == null ? void 0 : action.type) === "error") { - (_f2 = (_e2 = __privateGet(this, _mutateOptions)).onError) == null ? void 0 : _f2.call(_e2, action.error, variables, context2); - (_h2 = (_g2 = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _h2.call( - _g2, - void 0, - action.error, - variables, - context2 - ); +} +SequenceClientSession.SESSION_LOCALSTORE_KEY = "@sequence.session"; +class DefaultChainIdTracker { + constructor(store, startingChainId = 1) { + this.store = store; + this.startingChainId = startingChainId; + this.callbacks = []; + store.onItemChange(DefaultChainIdTracker.SESSION_CHAIN_ID_KEY, (value) => { + if (value) { + const chainId = parseInt(value); + this.callbacks.forEach((cb2) => cb2(chainId)); } - } - this.listeners.forEach((listener) => { - listener(__privateGet(this, _currentResult2)); }); - }); -}, _m); -function structuralSharing(oldData, newData) { - if (deepEqual$1(oldData, newData)) - return oldData; - return replaceEqualDeep(oldData, newData); -} -function hashFn(queryKey) { - return JSON.stringify(queryKey, (_, value) => { - if (isPlainObject(value)) - return Object.keys(value).sort().reduce((result, key) => { - result[key] = value[key]; - return result; - }, {}); - if (typeof value === "bigint") - return value.toString(); - return value; - }); -} -function isPlainObject(value) { - if (!hasObjectPrototype(value)) { - return false; } - const ctor = value.constructor; - if (typeof ctor === "undefined") - return true; - const prot = ctor.prototype; - if (!hasObjectPrototype(prot)) - return false; - if (!prot.hasOwnProperty("isPrototypeOf")) - return false; - return true; -} -function hasObjectPrototype(o2) { - return Object.prototype.toString.call(o2) === "[object Object]"; -} -function filterQueryOptions(options) { - const { - // import('@tanstack/query-core').QueryOptions - _defaulted, - behavior, - gcTime, - initialData, - initialDataUpdatedAt, - maxPages, - meta, - networkMode, - queryFn, - queryHash, - queryKey, - queryKeyHashFn, - retry, - retryDelay, - structuralSharing: structuralSharing2, - // import('@tanstack/query-core').InfiniteQueryObserverOptions - getPreviousPageParam: getPreviousPageParam2, - getNextPageParam: getNextPageParam2, - initialPageParam, - // import('@tanstack/react-query').UseQueryOptions - _optimisticResults, - enabled, - notifyOnChangeProps, - placeholderData, - refetchInterval, - refetchIntervalInBackground, - refetchOnMount, - refetchOnReconnect, - refetchOnWindowFocus, - retryOnMount, - select, - staleTime, - suspense, - throwOnError, - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // wagmi - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - config: config2, - connector, - query, - ...rest - } = options; - return rest; -} -function connectMutationOptions(config2) { - return { - mutationFn(variables) { - return connect(config2, variables); - }, - mutationKey: ["connect"] - }; -} -function disconnectMutationOptions(config2) { - return { - mutationFn(variables) { - return disconnect(config2, variables); - }, - mutationKey: ["disconnect"] - }; -} -function getWalletClientQueryOptions(config2, options = {}) { - return { - gcTime: 0, - async queryFn({ queryKey }) { - const { connector } = options; - const { connectorUid: _, scopeKey: _s2, ...parameters } = queryKey[1]; - return getWalletClient(config2, { ...parameters, connector }); - }, - queryKey: getWalletClientQueryKey(options) - }; -} -function getWalletClientQueryKey(options = {}) { - const { connector, ...parameters } = options; - return [ - "walletClient", - { ...filterQueryOptions(parameters), connectorUid: connector == null ? void 0 : connector.uid } - ]; -} -function readContractQueryOptions(config2, options = {}) { - return { - // TODO: Support `signal` once Viem actions allow passthrough - // https://tkdodo.eu/blog/why-you-want-react-query#bonus-cancellation - async queryFn({ queryKey }) { - const abi2 = options.abi; - if (!abi2) - throw new Error("abi is required"); - const { functionName, scopeKey: _, ...parameters } = queryKey[1]; - const addressOrCodeParams = (() => { - const params = queryKey[1]; - if (params.address) - return { address: params.address }; - if (params.code) - return { code: params.code }; - throw new Error("address or code is required"); - })(); - if (!functionName) - throw new Error("functionName is required"); - return readContract(config2, { - abi: abi2, - functionName, - args: parameters.args, - ...addressOrCodeParams, - ...parameters - }); - }, - queryKey: readContractQueryKey(options) - }; -} -function readContractQueryKey(options = {}) { - const { abi: _, ...rest } = options; - return ["readContract", filterQueryOptions(rest)]; -} -function sendTransactionMutationOptions(config2) { - return { - mutationFn(variables) { - return sendTransaction(config2, variables); - }, - mutationKey: ["sendTransaction"] - }; -} -function switchChainMutationOptions(config2) { - return { - mutationFn(variables) { - return switchChain(config2, variables); - }, - mutationKey: ["switchChain"] - }; -} -function writeContractMutationOptions(config2) { - return { - mutationFn(variables) { - return writeContract(config2, variables); - }, - mutationKey: ["writeContract"] - }; + onDefaultChainIdChanged(callback) { + this.callbacks.push(callback); + return () => { + this.callbacks = this.callbacks.filter((cb2) => cb2 !== callback); + }; + } + setDefaultChainId(chainId) { + if (chainId !== this.getDefaultChainId()) { + this.store.setItem(DefaultChainIdTracker.SESSION_CHAIN_ID_KEY, chainId.toString()); + } + } + getDefaultChainId() { + const read = this.store.getItem(DefaultChainIdTracker.SESSION_CHAIN_ID_KEY); + if (!read || read.length === 0) { + return this.startingChainId; + } + return parseInt(read); + } } -var QueryClientContext = reactExports.createContext( - void 0 -); -var useQueryClient = (queryClient2) => { - const client2 = reactExports.useContext(QueryClientContext); - if (!client2) { - throw new Error("No QueryClient set, use QueryClientProvider to set one"); +DefaultChainIdTracker.SESSION_CHAIN_ID_KEY = "@sequence.session.defaultChainId"; +class SequenceClient { + constructor(transport, store, options) { + var _options$defaultEIP, _this$session$getSess; + this.session = void 0; + this.defaultChainId = void 0; + this.callbacks = {}; + this.transport = void 0; + this.defaultEIP6492 = void 0; + this.projectAccessKey = void 0; + this.analytics = void 0; + if (isMuxTransportTemplate(transport)) { + this.transport = MuxMessageProvider.new(transport); + } else if (isProviderTransport(transport)) { + this.transport = transport; + } else { + throw new Error("Invalid transport"); + } + const defaultChainId = options == null ? void 0 : options.defaultChainId; + this.defaultEIP6492 = (_options$defaultEIP = options == null ? void 0 : options.defaultEIP6492) != null ? _options$defaultEIP : false; + this.session = new SequenceClientSession(store); + this.defaultChainId = new DefaultChainIdTracker(store, defaultChainId); + this.transport.on("accountsChanged", (accounts) => { + var _this$callbacks$accou; + if (accounts.length > 1) { + console.warn("SequenceClient: wallet-webapp returned more than one account"); + } + (_this$callbacks$accou = this.callbacks.accountsChanged) == null || _this$callbacks$accou.forEach((cb2) => cb2(accounts)); + }); + this.transport.on("connect", (response) => { + var _this$callbacks$conne; + const chainIdHex = toQuantity(this.getChainId()); + (_this$callbacks$conne = this.callbacks.connect) == null || _this$callbacks$conne.forEach((cb2) => cb2(_extends$2({}, response, { + // Ignore the full connect response + // use the chainId defined locally + chainId: chainIdHex + }))); + }); + this.transport.on("disconnect", (error, origin) => { + var _this$callbacks$disco; + (_this$callbacks$disco = this.callbacks.disconnect) == null || _this$callbacks$disco.forEach((cb2) => cb2(error, origin)); + }); + this.transport.on("networks", (networks2) => { + var _this$callbacks$netwo; + (_this$callbacks$netwo = this.callbacks.networks) == null || _this$callbacks$netwo.forEach((cb2) => cb2(networks2)); + }); + this.transport.on("walletContext", (context2) => { + var _this$callbacks$walle; + (_this$callbacks$walle = this.callbacks.walletContext) == null || _this$callbacks$walle.forEach((cb2) => cb2(context2)); + }); + this.transport.on("open", (info) => { + var _this$callbacks$open; + (_this$callbacks$open = this.callbacks.open) == null || _this$callbacks$open.forEach((cb2) => cb2(info)); + }); + this.transport.on("close", () => { + var _this$callbacks$close; + (_this$callbacks$close = this.callbacks.close) == null || _this$callbacks$close.forEach((cb2) => cb2()); + }); + this.transport.on("chainChanged", (chainIdHex, origin) => { + var _this$callbacks$chain; + (_this$callbacks$chain = this.callbacks.chainChanged) == null || _this$callbacks$chain.forEach((cb2) => cb2(chainIdHex, origin)); + }); + this.defaultChainId.onDefaultChainIdChanged((chainId) => { + var _this$callbacks$chain2; + const chainIdHex = toQuantity(chainId); + (_this$callbacks$chain2 = this.callbacks.chainChanged) == null || _this$callbacks$chain2.forEach((cb2) => cb2(chainIdHex)); + }); + if (options != null && options.projectAccessKey) { + this.projectAccessKey = options.projectAccessKey; + } + if (this.projectAccessKey && options != null && options.analytics) { + this.analytics = setupAnalytics(this.projectAccessKey); + } + if ((_this$session$getSess = this.session.getSession()) != null && _this$session$getSess.accountAddress) { + var _this$analytics, _this$session$getSess2; + (_this$analytics = this.analytics) == null || _this$analytics.identify((_this$session$getSess2 = this.session.getSession()) == null || (_this$session$getSess2 = _this$session$getSess2.accountAddress) == null ? void 0 : _this$session$getSess2.toLowerCase()); + } } - return client2; -}; -var QueryClientProvider = ({ - client: client2, - children -}) => { - reactExports.useEffect(() => { - client2.mount(); + // Callbacks + registerCallback(eventName, callback) { + if (!this.callbacks[eventName]) { + this.callbacks[eventName] = []; + } + this.callbacks[eventName].push(callback); return () => { - client2.unmount(); + this.callbacks[eventName] = this.callbacks[eventName].filter((c2) => c2 !== callback); }; - }, [client2]); - return /* @__PURE__ */ jsxRuntimeExports$1.jsx(QueryClientContext.Provider, { value: client2, children }); -}; -var IsRestoringContext = reactExports.createContext(false); -var useIsRestoring = () => reactExports.useContext(IsRestoringContext); -IsRestoringContext.Provider; -function createValue() { - let isReset = false; - return { - clearReset: () => { - isReset = false; - }, - reset: () => { - isReset = true; - }, - isReset: () => { - return isReset; + } + // Individual callbacks lead to more idiomatic code + onOpen(callback) { + return this.registerCallback("open", callback); + } + onClose(callback) { + return this.registerCallback("close", callback); + } + onConnect(callback) { + return this.registerCallback("connect", callback); + } + onDisconnect(callback) { + return this.registerCallback("disconnect", callback); + } + onNetworks(callback) { + return this.registerCallback("networks", callback); + } + onAccountsChanged(callback) { + return this.registerCallback("accountsChanged", callback); + } + // @deprecated + onWalletContext(callback) { + return this.registerCallback("walletContext", callback); + } + onChainChanged(callback) { + return this.registerCallback("chainChanged", callback); + } + onDefaultChainIdChanged(callback) { + return this.registerCallback("chainChanged", callback); + } + getChainId() { + return this.defaultChainId.getDefaultChainId(); + } + setDefaultChainId(chainId) { + return this.defaultChainId.setDefaultChainId(chainId); + } + // Proxy transport methods + async openWallet(path, intent) { + this.transport.openWallet(path, intent, this.getChainId()); + await this.transport.waitUntilOpened(); + return this.isOpened(); + } + closeWallet() { + return this.transport.closeWallet(); + } + isOpened() { + return this.transport.isOpened(); + } + isConnected() { + return this.session.hasSession(); + } + getSession() { + return this.session.getSession(); + } + // Basic API + getAddress() { + const session = this.session.connectedSession(); + return session.accountAddress; + } + async connect(options) { + if ((options == null ? void 0 : options.authorizeVersion) === void 0) { + options.authorizeVersion = 2; } - }; -} -var QueryErrorResetBoundaryContext = reactExports.createContext(createValue()); -var useQueryErrorResetBoundary = () => reactExports.useContext(QueryErrorResetBoundaryContext); -function shouldThrowError(throwError2, params) { - if (typeof throwError2 === "function") { - return throwError2(...params); + if ((options == null ? void 0 : options.refresh) === true) { + this.disconnect(); + } + options.projectAccessKey = this.projectAccessKey; + if (options) { + if (options.authorize) { + if (!options.app) { + throw new Error(`connecting with 'authorize' option also requires 'app' to be set`); + } + if (options.authorizeVersion === void 0) { + options.authorizeVersion = 2; + } + } + } + await this.openWallet(void 0, { + type: "connect", + options: _extends$2({}, options, { + networkId: this.getChainId(), + clientVersion: VERSION$1 + }) + }); + const connectDetails = await this.transport.waitUntilConnected().catch((error) => { + if (error instanceof Error) { + return { + connected: false, + error: error.message + }; + } else { + return { + connected: false, + error: JSON.stringify(error) + }; + } + }); + if (connectDetails.chainId) { + connectDetails.chainId = BigInt(connectDetails.chainId).toString(); + } + if (connectDetails.connected) { + var _connectDetails$sessi; + if (!connectDetails.session) { + throw new Error("impossible state, connect response is missing session"); + } + this.session.setSession(connectDetails.session); + if ((_connectDetails$sessi = connectDetails.session) != null && _connectDetails$sessi.accountAddress) { + var _this$analytics2; + (_this$analytics2 = this.analytics) == null || _this$analytics2.identify(connectDetails.session.accountAddress.toLowerCase()); + } + } + return connectDetails; } - return !!throwError2; -} -function noop() { -} -var ensurePreventErrorBoundaryRetry = (options, errorResetBoundary) => { - if (options.suspense || options.throwOnError) { - if (!errorResetBoundary.isReset()) { - options.retryOnMount = false; + disconnect() { + var _this$analytics3; + if (this.isOpened()) { + this.closeWallet(); } + (_this$analytics3 = this.analytics) == null || _this$analytics3.reset(); + return this.session.clearSession(); } -}; -var useClearResetErrorBoundary = (errorResetBoundary) => { - reactExports.useEffect(() => { - errorResetBoundary.clearReset(); - }, [errorResetBoundary]); -}; -var getHasError = ({ - result, - errorResetBoundary, - throwOnError, - query -}) => { - return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && shouldThrowError(throwOnError, [result.error, query]); -}; -var ensureSuspenseTimers = (defaultedOptions) => { - if (defaultedOptions.suspense) { - if (typeof defaultedOptions.staleTime !== "number") { - defaultedOptions.staleTime = 1e3; + // Higher level API + async request(request) { + request.method = this.mapSignMethod(request.method); + const result = await this.transport.request(request); + return unwrapJsonRpcResponse(result); + } + async getNetworks(pull) { + const connectedSession = this.session.connectedSession(); + if (pull) { + connectedSession.networks = await this.request({ + method: "sequence_getNetworks" + }); + this.session.setSession(connectedSession); } - if (typeof defaultedOptions.gcTime === "number") { - defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, 1e3); + return connectedSession.networks; + } + // NOTICE: `legacy_sign` will get overriden by `send` + // it is done this way to ensure that: + // - `send` handles `personal_sign` as a request for the default sign method + // - explicit `personal_sign` is not replaced by `sequence_sign` (if default is EI6492) + signMethod(options) { + if ((options == null ? void 0 : options.eip6492) === void 0) { + return "personal_sign"; } + return options.eip6492 ? "sequence_sign" : "legacy_sign"; } -}; -var shouldSuspend = (defaultedOptions, result) => (defaultedOptions == null ? void 0 : defaultedOptions.suspense) && result.isPending; -var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => { - errorResetBoundary.clearReset(); -}); -function useBaseQuery(options, Observer, queryClient2) { - var _a2, _b2, _c2, _d2; - const client2 = useQueryClient(); - const isRestoring = useIsRestoring(); - const errorResetBoundary = useQueryErrorResetBoundary(); - const defaultedOptions = client2.defaultQueryOptions(options); - (_b2 = (_a2 = client2.getDefaultOptions().queries) == null ? void 0 : _a2._experimental_beforeQuery) == null ? void 0 : _b2.call( - _a2, - defaultedOptions - ); - defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic"; - ensureSuspenseTimers(defaultedOptions); - ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary); - useClearResetErrorBoundary(errorResetBoundary); - const [observer] = reactExports.useState( - () => new Observer( - client2, - defaultedOptions - ) - ); - const result = observer.getOptimisticResult(defaultedOptions); - reactExports.useSyncExternalStore( - reactExports.useCallback( - (onStoreChange) => { - const unsubscribe = isRestoring ? () => void 0 : observer.subscribe(notifyManager.batchCalls(onStoreChange)); - observer.updateResult(); - return unsubscribe; - }, - [observer, isRestoring] - ), - () => observer.getCurrentResult(), - () => observer.getCurrentResult() - ); - reactExports.useEffect(() => { - observer.setOptions(defaultedOptions, { listeners: false }); - }, [defaultedOptions, observer]); - if (shouldSuspend(defaultedOptions, result)) { - throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary); + signTypedDataMethod(options) { + if ((options == null ? void 0 : options.eip6492) === void 0) { + return "eth_signTypedData_v4"; + } + return options.eip6492 ? "sequence_signTypedData_v4" : "legacy_signTypedData_v4"; } - if (getHasError({ - result, - errorResetBoundary, - throwOnError: defaultedOptions.throwOnError, - query: client2.getQueryCache().get(defaultedOptions.queryHash) - })) { - throw result.error; + mapSignMethod(method) { + if (method === "personal_sign") { + if (this.defaultEIP6492) { + return "sequence_sign"; + } else { + return "personal_sign"; + } + } + if (method === "eth_signTypedData_v4") { + if (this.defaultEIP6492) { + return "sequence_signTypedData_v4"; + } else { + return "eth_signTypedData_v4"; + } + } + if (method === "legacy_sign") { + return "personal_sign"; + } + if (method === "legacy_signTypedData_v4") { + return "eth_signTypedData_v4"; + } + return method; } - (_d2 = (_c2 = client2.getDefaultOptions().queries) == null ? void 0 : _c2._experimental_afterQuery) == null ? void 0 : _d2.call( - _c2, - defaultedOptions, - result - ); - return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result; -} -function useQuery$1(options, queryClient2) { - return useBaseQuery(options, QueryObserver); + async signMessage(message, options) { + var _this$analytics4; + const method = this.signMethod(options); + (_this$analytics4 = this.analytics) == null || _this$analytics4.track({ + event: "SIGN_MESSAGE_REQUEST", + props: { + chainId: `${(options == null ? void 0 : options.chainId) || this.getChainId()}` + } + }); + message = hexlify(messageToBytes(message)); + return this.request({ + method, + params: [message, this.getAddress()], + chainId: options == null ? void 0 : options.chainId + }); + } + async signTypedData(typedData, options) { + var _this$analytics5; + const method = this.signTypedDataMethod(options); + const encoded = TypedDataEncoder.getPayload(typedData.domain, typedData.types, typedData.message); + (_this$analytics5 = this.analytics) == null || _this$analytics5.track({ + event: "SIGN_TYPED_DATA_REQUEST", + props: { + chainId: `${(options == null ? void 0 : options.chainId) || this.getChainId()}` + } + }); + return this.request({ + method, + params: [this.getAddress(), encoded], + chainId: (options == null ? void 0 : options.chainId) || typedData.domain.chainId && Number(typedData.domain.chainId) || this.getChainId() + }); + } + async sendTransaction(tx, options) { + var _this$analytics6; + const sequenceTxs = Array.isArray(tx) ? tx : [tx]; + const extendedTxs = toExtended(sequenceTxs); + (_this$analytics6 = this.analytics) == null || _this$analytics6.track({ + event: "SEND_TRANSACTION_REQUEST", + props: { + chainId: `${(options == null ? void 0 : options.chainId) || this.getChainId()}` + } + }); + return this.request({ + method: "eth_sendTransaction", + params: [extendedTxs], + chainId: options == null ? void 0 : options.chainId + }); + } + async getWalletContext() { + return this.request({ + method: "sequence_getWalletContext" + }); + } + async getOnchainWalletConfig(options) { + const res = await this.request({ + method: "sequence_getWalletConfig", + params: [(options == null ? void 0 : options.chainId) || this.getChainId()], + chainId: options == null ? void 0 : options.chainId + }); + return Array.isArray(res) ? res[0] : res; + } + // NOTICE: We are leaving out all the "regular" methods os a tipical + // JSON RPC Provider (eth_getBlockByNumber, eth_call, etc) + // wallet-webapp does implement them, but this client is meant to be + // exclusively used for Sequence specific methods } -function useMutation(options, queryClient2) { - const client2 = useQueryClient(); - const [observer] = reactExports.useState( - () => new MutationObserver$1( - client2, - options - ) - ); - reactExports.useEffect(() => { - observer.setOptions(options); - }, [observer, options]); - const result = reactExports.useSyncExternalStore( - reactExports.useCallback( - (onStoreChange) => observer.subscribe(notifyManager.batchCalls(onStoreChange)), - [observer] - ), - () => observer.getCurrentResult(), - () => observer.getCurrentResult() - ); - const mutate = reactExports.useCallback( - (variables, mutateOptions) => { - observer.mutate(variables, mutateOptions).catch(noop); +const unwrapJsonRpcResponse = (response) => { + if (response && typeof response === "object" && "jsonrpc" in response && "result" in response) { + return response.result; + } + return response; +}; +const DefaultProviderConfig = { + transports: { + walletAppURL: "https://sequence.app", + windowTransport: { + enabled: true }, - [observer] - ); - if (result.error && shouldThrowError(observer.options.throwOnError, [result.error])) { - throw result.error; + proxyTransport: { + enabled: false + } + }, + defaultNetwork: 1, + analytics: true +}; +let sequenceWalletProvider; +const initWallet = (projectAccessKey2, partialConfig) => { + var _config$networks$filt, _config$networks, _findNetworkConfig; + if (!projectAccessKey2 || typeof projectAccessKey2 !== "string") { + throw new Error("Please pass a projectAccessKey in initWallet."); } - return { ...result, mutate, mutateAsync: result.mutate }; -} -function useInfiniteQuery(options, queryClient2) { - return useBaseQuery( - options, - InfiniteQueryObserver - ); -} -function useQuery(parameters) { - const result = useQuery$1({ - ...parameters, - queryKeyHashFn: hashFn - // for bigint support + if (sequenceWalletProvider) { + return sequenceWalletProvider; + } + const config2 = _extends$2({}, DefaultProviderConfig, partialConfig, { + transports: _extends$2({}, DefaultProviderConfig.transports, partialConfig == null ? void 0 : partialConfig.transports) }); - result.queryKey = parameters.queryKey; - return result; -} -function useChainId(parameters = {}) { - const config2 = useConfig(parameters); - return reactExports.useSyncExternalStore((onChange) => watchChainId(config2, { onChange }), () => getChainId(config2), () => getChainId(config2)); -} -function useChains(parameters = {}) { - const config2 = useConfig(parameters); - return reactExports.useSyncExternalStore((onChange) => watchChains(config2, { onChange }), () => getChains(config2), () => getChains(config2)); -} -function useConnectors(parameters = {}) { - const config2 = useConfig(parameters); - return reactExports.useSyncExternalStore((onChange) => watchConnectors(config2, { onChange }), () => getConnectors(config2), () => getConnectors(config2)); -} -function useConnect(parameters = {}) { - const { mutation } = parameters; - const config2 = useConfig(parameters); - const mutationOptions = connectMutationOptions(config2); - const { mutate, mutateAsync, ...result } = useMutation({ - ...mutation, - ...mutationOptions + const rpcProviders = {}; + const newNetworks = (_config$networks$filt = (_config$networks = config2.networks) == null ? void 0 : _config$networks.filter((n2) => { + n2.rpcUrl !== void 0 && n2.chainId !== void 0 && !allNetworks.find((an) => an.chainId === n2.chainId); + })) != null ? _config$networks$filt : []; + const combinedNetworks = allNetworks.map((n2) => { + var _config$networks2; + const network2 = (_config$networks2 = config2.networks) == null ? void 0 : _config$networks2.find((cn) => cn.chainId === n2.chainId); + return network2 ? _extends$2({}, n2, network2) : n2; + }).concat(newNetworks).map((network2) => { + if (network2.rpcUrl.includes(projectAccessKey2)) { + return network2; + } + network2.rpcUrl = network2.rpcUrl + `/${projectAccessKey2}`; + return network2; + }); + const providerForChainId = (chainId) => { + if (!rpcProviders[chainId]) { + var _combinedNetworks$fin; + const rpcUrl = (_combinedNetworks$fin = combinedNetworks.find((n2) => n2.chainId === chainId)) == null ? void 0 : _combinedNetworks$fin.rpcUrl; + if (!rpcUrl) { + throw new Error(`no rpcUrl found for chainId: ${chainId}`); + } + rpcProviders[chainId] = new JsonRpcProvider(rpcUrl, { + middlewares: [loggingProviderMiddleware, exceptionProviderMiddleware, new CachedProvider()] + }, { + cacheTimeout: -1 + }); + } + return rpcProviders[chainId]; + }; + const defaultNetwork = config2.defaultNetwork ? (_findNetworkConfig = findNetworkConfig(combinedNetworks, config2.defaultNetwork)) == null ? void 0 : _findNetworkConfig.chainId : void 0; + if (!defaultNetwork && config2.defaultNetwork) { + throw new Error(`defaultNetwork not found for chainId: ${config2.defaultNetwork}`); + } + const itemStore = config2.localStorage || useBestStore(); + const client2 = new SequenceClient(config2.transports, itemStore, { + defaultChainId: defaultNetwork, + defaultEIP6492: config2.defaultEIP6492, + projectAccessKey: projectAccessKey2, + analytics: config2.analytics }); - reactExports.useEffect(() => { - return config2.subscribe(({ status }) => status, (status, previousStatus) => { - if (previousStatus === "connected" && status === "disconnected") - result.reset(); + sequenceWalletProvider = new SequenceProvider(client2, providerForChainId); + return sequenceWalletProvider; +}; +const unregisterWallet = () => { + if (!sequenceWalletProvider) return; + sequenceWalletProvider.client.closeWallet(); + sequenceWalletProvider.client.transport.unregister(); + sequenceWalletProvider = void 0; +}; +const getWallet = () => { + if (!sequenceWalletProvider) { + throw new Error("Wallet has not been initialized, call sequence.initWallet(config) first."); + } + return sequenceWalletProvider; +}; +const provider$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + BaseInjectedTransport, + BaseProviderTransport, + BaseWalletTransport, + CHANNEL_ID, + DefaultChainIdTracker, + DefaultProviderConfig, + ErrSignedInRequired, + EventType, + ExtensionMessageHandler, + ExtensionMessageProvider, + InitState, + LocalStorage, + MemoryItemStore, + MuxMessageProvider, + OpenState, + PROVIDER_OPEN_TIMEOUT, + ProviderError, + ProxyMessageChannel, + ProxyMessageChannelPort, + ProxyMessageHandler, + ProxyMessageProvider, + SequenceClient, + SequenceClientSession, + SequenceProvider, + SequenceSigner, + SingleNetworkSequenceProvider, + SingleNetworkSequenceSigner, + UnrealMessageHandler, + UnrealMessageProvider, + WalletRequestHandler, + WindowMessageHandler, + WindowMessageProvider, + WindowSessionParams, + getWallet, + initWallet, + isBrowserExtension, + isMuxTransportTemplate, + isProviderTransport, + isUnityPlugin, + isValidMessageSignature, + isValidSignature, + isValidTypedDataSignature, + isWalletUpToDate, + messageToBytes, + nextMessageIdx, + prefixEIP191Message, + resolveArrayProperties, + trimEIP191Prefix, + unregisterWallet, + useBestStore, + validateTransactionRequest +}, Symbol.toStringTag, { value: "Module" })); +function _mergeNamespaces$1(n2, m2) { + m2.forEach(function(e2) { + e2 && typeof e2 !== "string" && !Array.isArray(e2) && Object.keys(e2).forEach(function(k2) { + if (k2 !== "default" && !(k2 in n2)) { + var d2 = Object.getOwnPropertyDescriptor(e2, k2); + Object.defineProperty(n2, k2, d2.get ? d2 : { + enumerable: true, + get: function() { + return e2[k2]; + } + }); + } }); - }, [config2, result.reset]); - return { - ...result, - connect: mutate, - connectAsync: mutateAsync, - connectors: useConnectors({ config: config2 }) - }; -} -function useConnections(parameters = {}) { - const config2 = useConfig(parameters); - return reactExports.useSyncExternalStore((onChange) => watchConnections(config2, { onChange }), () => getConnections(config2), () => getConnections(config2)); -} -function useDisconnect(parameters = {}) { - const { mutation } = parameters; - const config2 = useConfig(parameters); - const mutationOptions = disconnectMutationOptions(config2); - const { mutate, mutateAsync, ...result } = useMutation({ - ...mutation, - ...mutationOptions }); - return { - ...result, - connectors: useConnections({ config: config2 }).map((connection) => connection.connector), - disconnect: mutate, - disconnectAsync: mutateAsync - }; + return Object.freeze(n2); } -function usePublicClient(parameters = {}) { - const config2 = useConfig(parameters); - return withSelectorExports.useSyncExternalStoreWithSelector((onChange) => watchPublicClient(config2, { onChange }), () => getPublicClient(config2, parameters), () => getPublicClient(config2, parameters), (x2) => x2, (a2, b2) => (a2 == null ? void 0 : a2.uid) === (b2 == null ? void 0 : b2.uid)); +var abi$1 = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [abi$1$2]); +var api = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [api$1]); +var auth = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [auth$1]); +var guard = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [guard$1]); +var indexer = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [indexer$1]); +var metadata = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [metadata$1]); +var network = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [network$1]); +var provider = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [provider$1]); +var relayer = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [relayer$1]); +const transactions = index$1$1.transaction; +var transactions$1 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + transactions +}); +var utils = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null, + isValidSignature, + isValidMessageSignature, + isValidTypedDataSignature, + isWalletUpToDate +}, [utils$1]); +var core = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [core$1]); +var signhub = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [signhub$1]); +var sessions = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [sessions$1]); +var migration = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [migration$1]); +var account = /* @__PURE__ */ _mergeNamespaces$1({ + __proto__: null +}, [account$1]); +var sequence$1 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + abi: abi$1, + api, + auth, + guard, + indexer, + metadata, + network, + provider, + relayer, + transactions: transactions$1, + utils, + core, + signhub, + sessions, + migration, + account, + initWallet, + getWallet, + unregisterWallet, + SequenceProvider, + SequenceClient, + SequenceSigner +}); +function useLoadGsiScript(options = {}) { + const { nonce, onScriptLoadSuccess, onScriptLoadError } = options; + const [scriptLoadedSuccessfully, setScriptLoadedSuccessfully] = reactExports.useState(false); + const onScriptLoadSuccessRef = reactExports.useRef(onScriptLoadSuccess); + onScriptLoadSuccessRef.current = onScriptLoadSuccess; + const onScriptLoadErrorRef = reactExports.useRef(onScriptLoadError); + onScriptLoadErrorRef.current = onScriptLoadError; + reactExports.useEffect(() => { + const scriptTag = document.createElement("script"); + scriptTag.src = "https://accounts.google.com/gsi/client"; + scriptTag.async = true; + scriptTag.defer = true; + scriptTag.nonce = nonce; + scriptTag.onload = () => { + var _a2; + setScriptLoadedSuccessfully(true); + (_a2 = onScriptLoadSuccessRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(onScriptLoadSuccessRef); + }; + scriptTag.onerror = () => { + var _a2; + setScriptLoadedSuccessfully(false); + (_a2 = onScriptLoadErrorRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(onScriptLoadErrorRef); + }; + document.body.appendChild(scriptTag); + return () => { + document.body.removeChild(scriptTag); + }; + }, [nonce]); + return scriptLoadedSuccessfully; } -function useReadContract(parameters = {}) { - const { abi: abi2, address, functionName, query = {} } = parameters; - const code2 = parameters.code; - const config2 = useConfig(parameters); - const chainId = useChainId({ config: config2 }); - const options = readContractQueryOptions(config2, { ...parameters, chainId: parameters.chainId ?? chainId }); - const enabled = Boolean((address || code2) && abi2 && functionName && (query.enabled ?? true)); - return useQuery({ - ...query, - ...options, - enabled, - structuralSharing: query.structuralSharing ?? structuralSharing +const GoogleOAuthContext = reactExports.createContext(null); +function GoogleOAuthProvider({ clientId, nonce, onScriptLoadSuccess, onScriptLoadError, children }) { + const scriptLoadedSuccessfully = useLoadGsiScript({ + nonce, + onScriptLoadSuccess, + onScriptLoadError }); + const contextValue = reactExports.useMemo(() => ({ + clientId, + scriptLoadedSuccessfully + }), [clientId, scriptLoadedSuccessfully]); + return React.createElement(GoogleOAuthContext.Provider, { value: contextValue }, children); } -function useSendTransaction(parameters = {}) { - const { mutation } = parameters; - const config2 = useConfig(parameters); - const mutationOptions = sendTransactionMutationOptions(config2); - const { mutate, mutateAsync, ...result } = useMutation({ - ...mutation, - ...mutationOptions - }); - return { - ...result, - sendTransaction: mutate, - sendTransactionAsync: mutateAsync - }; +function useGoogleOAuth() { + const context2 = reactExports.useContext(GoogleOAuthContext); + if (!context2) { + throw new Error("Google OAuth components must be used within GoogleOAuthProvider"); + } + return context2; } -function useSwitchChain(parameters = {}) { - const { mutation } = parameters; - const config2 = useConfig(parameters); - const mutationOptions = switchChainMutationOptions(config2); - const { mutate, mutateAsync, ...result } = useMutation({ - ...mutation, - ...mutationOptions - }); - return { - ...result, - chains: useChains({ config: config2 }), - switchChain: mutate, - switchChainAsync: mutateAsync - }; +function extractClientId(credentialResponse) { + var _a2; + const clientId = (_a2 = credentialResponse === null || credentialResponse === void 0 ? void 0 : credentialResponse.clientId) !== null && _a2 !== void 0 ? _a2 : credentialResponse === null || credentialResponse === void 0 ? void 0 : credentialResponse.client_id; + return clientId; } -function useWalletClient(parameters = {}) { - const { query = {}, ...rest } = parameters; - const config2 = useConfig(rest); - const queryClient2 = useQueryClient(); - const { address, connector, status } = useAccount({ config: config2 }); - const chainId = useChainId({ config: config2 }); - const activeConnector = parameters.connector ?? connector; - const { queryKey, ...options } = getWalletClientQueryOptions(config2, { - ...parameters, - chainId: parameters.chainId ?? chainId, - connector: parameters.connector ?? connector - }); - const enabled = Boolean((status === "connected" || status === "reconnecting" && (activeConnector == null ? void 0 : activeConnector.getProvider)) && (query.enabled ?? true)); - const addressRef = reactExports.useRef(address); +const containerHeightMap = { large: 40, medium: 32, small: 20 }; +function GoogleLogin({ onSuccess, onError, useOneTap, promptMomentNotification, type = "standard", theme = "outline", size: size2 = "large", text: text2, shape, logo_alignment, width, locale, click_listener, containerProps, ...props }) { + const btnContainerRef = reactExports.useRef(null); + const { clientId, scriptLoadedSuccessfully } = useGoogleOAuth(); + const onSuccessRef = reactExports.useRef(onSuccess); + onSuccessRef.current = onSuccess; + const onErrorRef = reactExports.useRef(onError); + onErrorRef.current = onError; + const promptMomentNotificationRef = reactExports.useRef(promptMomentNotification); + promptMomentNotificationRef.current = promptMomentNotification; reactExports.useEffect(() => { - const previousAddress = addressRef.current; - if (!address && previousAddress) { - queryClient2.removeQueries({ queryKey }); - addressRef.current = void 0; - } else if (address !== previousAddress) { - queryClient2.invalidateQueries({ queryKey }); - addressRef.current = address; - } - }, [address, queryClient2]); - return useQuery({ - ...query, - ...options, - queryKey, - enabled, - staleTime: Number.POSITIVE_INFINITY - }); -} -function useWriteContract(parameters = {}) { - const { mutation } = parameters; - const config2 = useConfig(parameters); - const mutationOptions = writeContractMutationOptions(config2); - const { mutate, mutateAsync, ...result } = useMutation({ - ...mutation, - ...mutationOptions - }); - return { - ...result, - writeContract: mutate, - writeContractAsync: mutateAsync - }; + var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _j2; + if (!scriptLoadedSuccessfully) + return; + (_c2 = (_b2 = (_a2 = window === null || window === void 0 ? void 0 : window.google) === null || _a2 === void 0 ? void 0 : _a2.accounts) === null || _b2 === void 0 ? void 0 : _b2.id) === null || _c2 === void 0 ? void 0 : _c2.initialize({ + client_id: clientId, + callback: (credentialResponse) => { + var _a3; + if (!(credentialResponse === null || credentialResponse === void 0 ? void 0 : credentialResponse.credential)) { + return (_a3 = onErrorRef.current) === null || _a3 === void 0 ? void 0 : _a3.call(onErrorRef); + } + const { credential, select_by } = credentialResponse; + onSuccessRef.current({ + credential, + clientId: extractClientId(credentialResponse), + select_by + }); + }, + ...props + }); + (_f2 = (_e2 = (_d2 = window === null || window === void 0 ? void 0 : window.google) === null || _d2 === void 0 ? void 0 : _d2.accounts) === null || _e2 === void 0 ? void 0 : _e2.id) === null || _f2 === void 0 ? void 0 : _f2.renderButton(btnContainerRef.current, { + type, + theme, + size: size2, + text: text2, + shape, + logo_alignment, + width, + locale, + click_listener + }); + if (useOneTap) + (_j2 = (_h2 = (_g2 = window === null || window === void 0 ? void 0 : window.google) === null || _g2 === void 0 ? void 0 : _g2.accounts) === null || _h2 === void 0 ? void 0 : _h2.id) === null || _j2 === void 0 ? void 0 : _j2.prompt(promptMomentNotificationRef.current); + return () => { + var _a3, _b3, _c3; + if (useOneTap) + (_c3 = (_b3 = (_a3 = window === null || window === void 0 ? void 0 : window.google) === null || _a3 === void 0 ? void 0 : _a3.accounts) === null || _b3 === void 0 ? void 0 : _b3.id) === null || _c3 === void 0 ? void 0 : _c3.cancel(); + }; + }, [ + clientId, + scriptLoadedSuccessfully, + useOneTap, + type, + theme, + size2, + text2, + shape, + logo_alignment, + width, + locale + ]); + return React.createElement("div", { ...containerProps, ref: btnContainerRef, style: { height: containerHeightMap[size2], ...containerProps === null || containerProps === void 0 ? void 0 : containerProps.style } }); } var LocalStorageKey; (function(LocalStorageKey2) { @@ -94143,7 +93839,7 @@ function hashIntent(intent) { data }; const encoded = toUtf8Bytes(canonicalize(hashableIntent)); - return getBytes(keccak256$1(encoded)); + return getBytes(keccak256(encoded)); } function changeIntentTime(intent, now) { const unsignedIntent = _objectWithoutPropertiesLoose$2(intent, _excluded$3); @@ -96854,7 +96550,7 @@ function sequenceWallet(params) { async getAccounts() { const provider2 = await this.getProvider(); const signer2 = provider2.getSigner(); - const account2 = getAddress(await signer2.getAddress()); + const account2 = getAddress$1(await signer2.getAddress()); return [account2]; }, async getProvider() { @@ -97048,7 +96744,7 @@ function sequenceWaasWallet(params) { const isSignedIn = await provider2.sequenceWaas.isSignedIn(); if (isSignedIn) { const address = await provider2.sequenceWaas.getAddress(); - return [getAddress(address)]; + return [getAddress$1(address)]; } } catch (err) { return []; @@ -97133,7 +96829,7 @@ class SequenceWaasProvider extends AbstractProvider { } if (method === "eth_accounts") { const address = await this.sequenceWaas.getAddress(); - const account2 = getAddress(address); + const account2 = getAddress$1(address); return [account2]; } if (method === "eth_sendTransaction") { @@ -97387,12 +97083,12 @@ const GoogleWaasConnectButton = (props) => { const AppleWaasConnectButton = (props) => { const { connector, onConnect } = props; const storage = useStorage(); - const { data: appleClientId2 } = useStorageItem(LocalStorageKey.WaasAppleClientID); + const { data: appleClientId } = useStorageItem(LocalStorageKey.WaasAppleClientID); const { data: appleRedirectUri } = useStorageItem(LocalStorageKey.WaasAppleRedirectURI); - return appleClientId2 && appleRedirectUri ? jsxRuntimeExports$1.jsx(ConnectButton, { connector, onConnect: () => { + return appleClientId && appleRedirectUri ? jsxRuntimeExports$1.jsx(ConnectButton, { connector, onConnect: () => { dist.appleAuthHelpers.signIn({ authOptions: { - clientId: appleClientId2, + clientId: appleClientId, redirectURI: appleRedirectUri, scope: "openid email", usePopup: true @@ -98013,7 +97709,7 @@ const useSwapQuotes = (args) => { enabled }); }; -const chains$1 = allNetworks.reduce((acc, network2) => { +const chains = allNetworks.reduce((acc, network2) => { if (network2.deprecated) { return acc; } @@ -98047,7 +97743,7 @@ const chains$1 = allNetworks.reduce((acc, network2) => { }, {}); const getNativeTokenInfoByChainId = (chainId, wagmiChains) => { var _a2, _b2; - const chain = wagmiChains.find((chain2) => chain2.id === chainId) || chains$1[chainId]; + const chain = wagmiChains.find((chain2) => chain2.id === chainId) || chains[chainId]; if (chain) { return { chainId: chain.id, @@ -98172,7 +97868,7 @@ const decodeTxnData = async (apiClient, txns) => { const decodeTransactions = async (apiClient, accountAddress, txns) => { const encodedTxns = encodeTransactions(txns); const decodedTxnDatas = (await decodeTxnData(apiClient, encodedTxns)).objs; - const from = getAddress$1(accountAddress); + const from = getAddress(accountAddress); const txnProps = encodedTxns.map((txn, i) => { const decodedTxnData = decodedTxnDatas[i]; const data = txn.data.toString(); @@ -98188,7 +97884,7 @@ const decodeTransactions = async (apiClient, accountAddress, txns) => { contractAddress: ZeroAddress, contractType: ContractType$1.UNKNOWN, from, - to: getAddress$1(txn.target), + to: getAddress(txn.target), tokenIds: ["0"], amounts: [value], target, @@ -98198,7 +97894,7 @@ const decodeTransactions = async (apiClient, accountAddress, txns) => { if (!decodedTxnData) { return void 0; } - const contractAddress = getAddress$1(txn.target); + const contractAddress = getAddress(txn.target); const baseDecoding = { type: DecodingType.UNIMPLEMENTED, signature: decodedTxnData.signature, @@ -98217,7 +97913,7 @@ const decodeTransactions = async (apiClient, accountAddress, txns) => { contractAddress, contractType: ContractType$1.ERC20, from, - to: getAddress$1(args.recipient), + to: getAddress(args.recipient), tokenIds: ["0"], amounts: [String(args.amount)] }; @@ -98232,7 +97928,7 @@ const decodeTransactions = async (apiClient, accountAddress, txns) => { contractAddress, contractType: ContractType$1.ERC721, from, - to: getAddress$1(args.to), + to: getAddress(args.to), tokenIds: [args.tokenId], amounts: ["1"] }; @@ -98246,7 +97942,7 @@ const decodeTransactions = async (apiClient, accountAddress, txns) => { contractAddress, contractType: ContractType$1.ERC1155, from, - to: getAddress$1(args._to), + to: getAddress(args._to), tokenIds: [args._id], amounts: [args._amount] }; @@ -98260,7 +97956,7 @@ const decodeTransactions = async (apiClient, accountAddress, txns) => { contractAddress, contractType: ContractType$1.ERC1155, from, - to: getAddress$1(args._to), + to: getAddress(args._to), tokenIds: args._ids, amounts: args._amounts }; @@ -98271,7 +97967,7 @@ const decodeTransactions = async (apiClient, accountAddress, txns) => { ...baseDecoding, type: DecodingType.AWARD_ITEM, contractAddress, - to: getAddress$1(args._0), + to: getAddress(args._0), amount: "1" }; } @@ -98504,7 +98200,7 @@ const TransferItemInfo = ({ address, transferProps, chainId }) => { const symbol = isNativeCoin ? nativeTokenInfo.symbol : isNFT ? "" : ((_f2 = tokenBalance == null ? void 0 : tokenBalance.contractInfo) == null ? void 0 : _f2.symbol) || ""; const amountSending = transferProps.amounts[0] ?? transferProps.value; const showSquareImage = isNFT; - return jsxRuntimeExports$1.jsxs(Card, { children: [jsxRuntimeExports$1.jsx(Box, { marginBottom: "2", children: jsxRuntimeExports$1.jsx(Text, { variant: "medium", color: "text100", children: capitalize(transferProps.type ?? "") }) }), jsxRuntimeExports$1.jsx(Box, { alignItems: "flex-end", justifyContent: "space-between", marginBottom: "2", children: jsxRuntimeExports$1.jsxs(Box, { justifyContent: "space-between", alignItems: "center", gap: "2", children: [showSquareImage ? jsxRuntimeExports$1.jsx(Box, { style: { width: "40px" }, children: jsxRuntimeExports$1.jsx(CollectibleTileImage$1, { imageUrl }) }) : jsxRuntimeExports$1.jsx(TokenImage, { src: imageUrl, symbol, size: "md" }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", alignItems: "flex-start", children: [jsxRuntimeExports$1.jsx(Box, { flexDirection: "row", alignItems: "center", gap: "1", children: jsxRuntimeExports$1.jsx(Text, { variant: "medium", color: "text100", children: name2 }) }), jsxRuntimeExports$1.jsxs(Text, { color: "text50", variant: "normal", children: [" ", `${formatUnits$2(amountSending, is1155 ? (_g2 = tokenMetadata == null ? void 0 : tokenMetadata[0]) == null ? void 0 : _g2.decimals : isNFT ? 0 : decimals)} ${symbol} `] })] })] }) }), toAddress !== void 0 && jsxRuntimeExports$1.jsxs(Box, { children: [jsxRuntimeExports$1.jsx(Text, { variant: "normal", color: "text50", children: "To" }), jsxRuntimeExports$1.jsx(Box, { marginTop: "2", borderRadius: "md", background: "backgroundSecondary", width: "full", flexDirection: "row", justifyContent: "space-between", alignItems: "center", padding: "4", style: { height: "52px" }, children: jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", justifyContent: "center", alignItems: "center", gap: "2", children: [jsxRuntimeExports$1.jsx(GradientAvatar, { address: toAddress, style: { width: "20px" } }), jsxRuntimeExports$1.jsx(Text, { color: "text100", children: `0x${truncateAtMiddle$1(toAddress.substring(2), 12)}` })] }) })] })] }); + return jsxRuntimeExports$1.jsxs(Card, { children: [jsxRuntimeExports$1.jsx(Box, { marginBottom: "2", children: jsxRuntimeExports$1.jsx(Text, { variant: "medium", color: "text100", children: capitalize(transferProps.type ?? "") }) }), jsxRuntimeExports$1.jsx(Box, { alignItems: "flex-end", justifyContent: "space-between", marginBottom: "2", children: jsxRuntimeExports$1.jsxs(Box, { justifyContent: "space-between", alignItems: "center", gap: "2", children: [showSquareImage ? jsxRuntimeExports$1.jsx(Box, { style: { width: "40px" }, children: jsxRuntimeExports$1.jsx(CollectibleTileImage$1, { imageUrl }) }) : jsxRuntimeExports$1.jsx(TokenImage, { src: imageUrl, symbol, size: "md" }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", alignItems: "flex-start", children: [jsxRuntimeExports$1.jsx(Box, { flexDirection: "row", alignItems: "center", gap: "1", children: jsxRuntimeExports$1.jsx(Text, { variant: "medium", color: "text100", children: name2 }) }), jsxRuntimeExports$1.jsxs(Text, { color: "text50", variant: "normal", children: [" ", `${formatUnits$1(amountSending, is1155 ? (_g2 = tokenMetadata == null ? void 0 : tokenMetadata[0]) == null ? void 0 : _g2.decimals : isNFT ? 0 : decimals)} ${symbol} `] })] })] }) }), toAddress !== void 0 && jsxRuntimeExports$1.jsxs(Box, { children: [jsxRuntimeExports$1.jsx(Text, { variant: "normal", color: "text50", children: "To" }), jsxRuntimeExports$1.jsx(Box, { marginTop: "2", borderRadius: "md", background: "backgroundSecondary", width: "full", flexDirection: "row", justifyContent: "space-between", alignItems: "center", padding: "4", style: { height: "52px" }, children: jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", justifyContent: "center", alignItems: "center", gap: "2", children: [jsxRuntimeExports$1.jsx(GradientAvatar, { address: toAddress, style: { width: "20px" } }), jsxRuntimeExports$1.jsx(Text, { color: "text100", children: `0x${truncateAtMiddle$1(toAddress.substring(2), 12)}` })] }) })] })] }); }; const AwardItemInfo = ({ awardItemProps }) => { return jsxRuntimeExports$1.jsxs(Card, { children: [jsxRuntimeExports$1.jsx(Box, { marginBottom: "2", children: jsxRuntimeExports$1.jsx(Text, { variant: "medium", color: "text100", children: "Mint" }) }), jsxRuntimeExports$1.jsx(Box, { alignItems: "flex-end", justifyContent: "space-between", marginBottom: "2", children: jsxRuntimeExports$1.jsxs(Box, { justifyContent: "space-between", alignItems: "center", gap: "2", children: [jsxRuntimeExports$1.jsx(Box, { style: { width: "40px" }, children: jsxRuntimeExports$1.jsx(CollectibleTileImage$1, { imageUrl: "https://dev-metadata.sequence.app/projects/277/collections/62/tokens/0/image.jpeg" }) }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", alignItems: "flex-start", children: [jsxRuntimeExports$1.jsx(Box, { flexDirection: "row", alignItems: "center", gap: "1", children: jsxRuntimeExports$1.jsx(Text, { variant: "medium", color: "text100", children: "Waas Demo NFT" }) }), jsxRuntimeExports$1.jsx(Text, { color: "text50", variant: "normal", children: awardItemProps.amount })] })] }) }), awardItemProps.to !== void 0 && jsxRuntimeExports$1.jsxs(Box, { children: [jsxRuntimeExports$1.jsx(Text, { variant: "normal", color: "text50", children: "To" }), jsxRuntimeExports$1.jsx(Box, { marginTop: "2", borderRadius: "md", background: "backgroundSecondary", width: "full", flexDirection: "row", justifyContent: "space-between", alignItems: "center", padding: "4", style: { height: "52px" }, children: jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", justifyContent: "center", alignItems: "center", gap: "2", children: [jsxRuntimeExports$1.jsx(GradientAvatar, { address: awardItemProps.to, style: { width: "20px" } }), jsxRuntimeExports$1.jsx(Text, { color: "text100", children: `0x${truncateAtMiddle$1(awardItemProps.to.substring(2), 12)}` })] }) })] })] }); @@ -98528,13 +98224,13 @@ const KitProvider = (props) => { const [displayedAssets, setDisplayedAssets] = reactExports.useState(displayedAssetsSetting); const [analytics, setAnalytics] = reactExports.useState(); const { address, isConnected } = useAccount(); - const wagmiConfig2 = useConfig(); + const wagmiConfig = useConfig(); const storage = useStorage(); const connections = useConnections(); const waasConnector = (_a2 = connections.find((c2) => c2.connector.id.includes("waas"))) == null ? void 0 : _a2.connector; const [pendingRequestConfirmation, confirmPendingRequest, rejectPendingRequest] = useWaasConfirmationHandler(waasConnector); - const googleWaasConnector = wagmiConfig2.connectors.find((c2) => c2.id === "sequence-waas" && c2._wallet.id === "google-waas"); - const googleClientId2 = ((_b2 = googleWaasConnector == null ? void 0 : googleWaasConnector.params) == null ? void 0 : _b2.googleClientId) || ""; + const googleWaasConnector = wagmiConfig.connectors.find((c2) => c2.id === "sequence-waas" && c2._wallet.id === "google-waas"); + const googleClientId = ((_b2 = googleWaasConnector == null ? void 0 : googleWaasConnector.params) == null ? void 0 : _b2.googleClientId) || ""; const setupAnalytics2 = (projectAccessKey2) => { const s2 = sequence$1.initWallet(projectAccessKey2); const sequenceAnalytics = s2.client.analytics; @@ -98585,7 +98281,7 @@ const KitProvider = (props) => { setTheme, position: modalPosition, setPosition: setModalPosition - }, children: jsxRuntimeExports$1.jsx(GoogleOAuthProvider, { clientId: googleClientId2, children: jsxRuntimeExports$1.jsx(ConnectModalContextProvider, { value: { setOpenConnectModal, openConnectModalState: openConnectModal }, children: jsxRuntimeExports$1.jsx(WalletConfigContextProvider, { value: { setDisplayedAssets, displayedAssets }, children: jsxRuntimeExports$1.jsxs(AnalyticsContextProvider, { value: { setAnalytics, analytics }, children: [jsxRuntimeExports$1.jsx("div", { id: "kit-provider", children: jsxRuntimeExports$1.jsx(ThemeProvider, { root: "#kit-provider", scope: "kit", theme, children: jsxRuntimeExports$1.jsxs(AnimatePresence, { children: [openConnectModal && jsxRuntimeExports$1.jsx(Modal, { scroll: false, backdropColor: "backgroundBackdrop", size: "sm", contentProps: { + }, children: jsxRuntimeExports$1.jsx(GoogleOAuthProvider, { clientId: googleClientId, children: jsxRuntimeExports$1.jsx(ConnectModalContextProvider, { value: { setOpenConnectModal, openConnectModalState: openConnectModal }, children: jsxRuntimeExports$1.jsx(WalletConfigContextProvider, { value: { setDisplayedAssets, displayedAssets }, children: jsxRuntimeExports$1.jsxs(AnalyticsContextProvider, { value: { setAnalytics, analytics }, children: [jsxRuntimeExports$1.jsx("div", { id: "kit-provider", children: jsxRuntimeExports$1.jsx(ThemeProvider, { root: "#kit-provider", scope: "kit", theme, children: jsxRuntimeExports$1.jsxs(AnimatePresence, { children: [openConnectModal && jsxRuntimeExports$1.jsx(Modal, { scroll: false, backdropColor: "backgroundBackdrop", size: "sm", contentProps: { style: { maxWidth: "364px", ...getModalPositionCss(position) @@ -98605,6 +98301,24 @@ const KitProvider = (props) => { confirmPendingRequest(pendingRequestConfirmation == null ? void 0 : pendingRequestConfirmation.id); } })] })] }), jsxRuntimeExports$1.jsx(PoweredBySequence, {})] }) }), isEmailConflictOpen && emailConflictInfo && jsxRuntimeExports$1.jsx(Modal, { size: "sm", scroll: false, onClose: () => toggleEmailConflictModal(false), children: jsxRuntimeExports$1.jsxs(Box, { padding: "4", children: [jsxRuntimeExports$1.jsx(PageHeading, { children: "Email already in use" }), jsxRuntimeExports$1.jsxs(Box, { children: [jsxRuntimeExports$1.jsxs(Text, { variant: "normal", color: "text80", textAlign: "center", children: ["Another account with this email address ", jsxRuntimeExports$1.jsxs(Text, { color: "text100", children: ["(", emailConflictInfo.email, ")"] }), " ", "already exists with account type ", jsxRuntimeExports$1.jsxs(Text, { color: "text100", children: ["(", emailConflictInfo.type, ")"] }), ". Please sign in again with the correct account."] }), jsxRuntimeExports$1.jsx(Box, { marginTop: "4", gap: "2", alignItems: "center", justifyContent: "center", children: jsxRuntimeExports$1.jsx(Button, { label: "OK", onClick: () => toggleEmailConflictModal(false) }) })] })] }) })] }) }) }), children] }) }) }) }) }) }); }; +const defaultQueryClient = new QueryClient(); +const SequenceKit = (props) => { + const { config: config2, queryClient, children } = props; + const { kitConfig: kitConfig2, wagmiConfig } = config2; + return jsxRuntimeExports$1.jsx(WagmiProvider, { config: wagmiConfig, children: jsxRuntimeExports$1.jsx(QueryClientProvider, { client: queryClient || defaultQueryClient, children: jsxRuntimeExports$1.jsx(KitProvider, { config: kitConfig2, children }) }) }); +}; +const getDefaultChains = (chainIdsFilter) => { + if (chainIdsFilter) { + return chainIdsFilter.map((chainId) => { + const chain = chains[chainId]; + if (!chain) { + throw new Error(`Chain with id ${chainId} not supported by Sequence`); + } + return chain; + }); + } + return Object.values(chains); +}; const getAppleLogo = ({ isDarkMode }) => { const fillColor = isDarkMode ? "white" : "black"; const AppleLogo = (props) => { @@ -98683,7 +98397,7 @@ function version4(parameters) { const provider2 = await this.getProvider(); const accounts = (await provider2.request({ method: "eth_requestAccounts" - })).map((x2) => getAddress(x2)); + })).map((x2) => getAddress$1(x2)); if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this); provider2.on("accountsChanged", accountsChanged); @@ -98734,7 +98448,7 @@ function version4(parameters) { const provider2 = await this.getProvider(); return (await provider2.request({ method: "eth_accounts" - })).map((x2) => getAddress(x2)); + })).map((x2) => getAddress$1(x2)); }, async getChainId() { const provider2 = await this.getProvider(); @@ -98747,7 +98461,7 @@ function version4(parameters) { if (!walletProvider) { const CoinbaseWalletSDK = await (async () => { const { default: SDK } = await __vitePreload(async () => { - const { default: SDK2 } = await import("./index-CnSoKQxV.js").then((n2) => n2.i); + const { default: SDK2 } = await import("./index-wr_HNsXy.js").then((n2) => n2.i); return { default: SDK2 }; }, true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); if (typeof SDK !== "function" && typeof SDK.default === "function") @@ -98823,7 +98537,7 @@ function version4(parameters) { this.onDisconnect(); else config2.emitter.emit("change", { - accounts: accounts.map((x2) => getAddress(x2)) + accounts: accounts.map((x2) => getAddress$1(x2)) }); }, onChainChanged(chain) { @@ -98865,7 +98579,7 @@ function version3(parameters) { const provider2 = await this.getProvider(); const accounts = (await provider2.request({ method: "eth_requestAccounts" - })).map((x2) => getAddress(x2)); + })).map((x2) => getAddress$1(x2)); if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this); provider2.on("accountsChanged", accountsChanged); @@ -98915,7 +98629,7 @@ function version3(parameters) { const provider2 = await this.getProvider(); return (await provider2.request({ method: "eth_accounts" - })).map((x2) => getAddress(x2)); + })).map((x2) => getAddress$1(x2)); }, async getChainId() { const provider2 = await this.getProvider(); @@ -98929,7 +98643,7 @@ function version3(parameters) { if (!walletProvider) { const CoinbaseWalletSDK = await (async () => { const { default: SDK } = await __vitePreload(async () => { - const { default: SDK2 } = await import("./index-CeEs98iF.js").then((n2) => n2.i); + const { default: SDK2 } = await import("./index-BT7PrVMP.js").then((n2) => n2.i); return { default: SDK2 }; }, true ? __vite__mapDeps([3,2,1]) : void 0, import.meta.url); if (typeof SDK !== "function" && typeof SDK.default === "function") @@ -99003,7 +98717,7 @@ function version3(parameters) { this.onDisconnect(); else config2.emitter.emit("change", { - accounts: accounts.map((x2) => getAddress(x2)) + accounts: accounts.map((x2) => getAddress$1(x2)) }); }, onChainChanged(chain) { @@ -99089,7 +98803,7 @@ function walletConnect$1(parameters) { }); this.setRequestedChainsIds(config2.chains.map((x2) => x2.id)); } - const accounts = (await provider2.enable()).map((x2) => getAddress(x2)); + const accounts = (await provider2.enable()).map((x2) => getAddress$1(x2)); const currentChainId = await this.getChainId(); if (displayUri) { provider2.removeListener("display_uri", displayUri); @@ -99156,7 +98870,7 @@ function walletConnect$1(parameters) { }, async getAccounts() { const provider2 = await this.getProvider(); - return provider2.accounts.map((x2) => getAddress(x2)); + return provider2.accounts.map((x2) => getAddress$1(x2)); }, async getProvider({ chainId } = {}) { var _a2; @@ -99165,7 +98879,7 @@ function walletConnect$1(parameters) { if (!optionalChains.length) return; const { EthereumProvider } = await __vitePreload(async () => { - const { EthereumProvider: EthereumProvider2 } = await import("./index.es-B9PQPdl4.js"); + const { EthereumProvider: EthereumProvider2 } = await import("./index.es-cfKIWXoD.js"); return { EthereumProvider: EthereumProvider2 }; }, true ? __vite__mapDeps([4,2]) : void 0, import.meta.url); return await EthereumProvider.init({ @@ -99283,7 +98997,7 @@ function walletConnect$1(parameters) { this.onDisconnect(); else config2.emitter.emit("change", { - accounts: accounts.map((x2) => getAddress(x2)) + accounts: accounts.map((x2) => getAddress$1(x2)) }); }, onChainChanged(chain) { @@ -99606,7 +99320,55 @@ const getKitConnectWallets = (projectAccessKey2, wallets) => { }); return connectors; }; -const getDefaultConnectors = ({ walletConnectProjectId, defaultChainId, projectAccessKey: projectAccessKey2, appName }) => { +const getDefaultConnectors = (walletType2, options) => { + if (walletType2 === "waas") { + return getDefaultWaasConnectors(options); + } else if (walletType2 === "universal") { + return getDefaultUniversalConnectors(options); + } +}; +const getDefaultWaasConnectors = ({ appName, projectAccessKey: projectAccessKey2, walletConnectProjectId: walletConnectProjectId2, defaultChainId, waasConfigKey, googleClientId, appleClientId, appleRedirectURI, enableConfirmationModal, legacyEmailAuth = false, isDev = false }) => { + const wallets = [ + emailWaas({ + projectAccessKey: projectAccessKey2, + waasConfigKey, + enableConfirmationModal, + network: defaultChainId, + legacyEmailAuth, + isDev + }), + coinbaseWallet({ + appName + }), + walletConnect({ + projectId: walletConnectProjectId2 + }) + ]; + if (googleClientId) { + wallets.push(googleWaas({ + projectAccessKey: projectAccessKey2, + googleClientId, + waasConfigKey, + enableConfirmationModal, + network: defaultChainId, + isDev + })); + } + if (appleClientId && appleRedirectURI) { + wallets.push(appleWaas({ + projectAccessKey: projectAccessKey2, + appleClientId, + appleRedirectURI, + waasConfigKey, + enableConfirmationModal, + network: defaultChainId, + isDev + })); + } + const connectors = getKitConnectWallets(projectAccessKey2, wallets); + return connectors; +}; +const getDefaultUniversalConnectors = ({ appName, projectAccessKey: projectAccessKey2, walletConnectProjectId: walletConnectProjectId2, defaultChainId }) => { const connectors = getKitConnectWallets(projectAccessKey2, [ email({ defaultNetwork: defaultChainId, @@ -99645,63 +99407,31 @@ const getDefaultConnectors = ({ walletConnectProjectId, defaultChainId, projectA } }), walletConnect({ - projectId: walletConnectProjectId + projectId: walletConnectProjectId2 }) ]); return connectors; }; -const getDefaultWaasConnectors = ({ projectAccessKey: projectAccessKey2, waasConfigKey: waasConfigKey2, googleClientId: googleClientId2, appleClientId: appleClientId2, appleRedirectURI: appleRedirectURI2, walletConnectProjectId, appName, defaultChainId, enableConfirmationModal, legacyEmailAuth = false, isDev = false }) => { - const wallets = [ - emailWaas({ +const getDefaultTransports = (chains2) => { + return Object.fromEntries(chains2.map((chain) => [chain.id, http()])); +}; +const createConfig = (walletType2, options) => { + const { projectAccessKey: projectAccessKey2, chainIds, wagmiConfig, ...rest } = options; + const chains2 = (wagmiConfig == null ? void 0 : wagmiConfig.chains) || getDefaultChains(chainIds); + const transports = (wagmiConfig == null ? void 0 : wagmiConfig.transports) || getDefaultTransports(chains2); + const connectors = (wagmiConfig == null ? void 0 : wagmiConfig.connectors) || getDefaultConnectors(walletType2, options); + return { + kitConfig: { projectAccessKey: projectAccessKey2, - waasConfigKey: waasConfigKey2, - enableConfirmationModal, - network: defaultChainId, - legacyEmailAuth, - isDev - }), - coinbaseWallet({ - appName - }), - walletConnect({ - projectId: walletConnectProjectId + ...rest + }, + wagmiConfig: createConfig$1({ + ...wagmiConfig, + chains: chains2, + transports, + connectors }) - ]; - if (googleClientId2) { - wallets.push(googleWaas({ - projectAccessKey: projectAccessKey2, - googleClientId: googleClientId2, - waasConfigKey: waasConfigKey2, - enableConfirmationModal, - network: defaultChainId, - isDev - })); - } - if (appleClientId2 && appleRedirectURI2) { - wallets.push(appleWaas({ - projectAccessKey: projectAccessKey2, - appleClientId: appleClientId2, - appleRedirectURI: appleRedirectURI2, - waasConfigKey: waasConfigKey2, - enableConfirmationModal, - network: defaultChainId, - isDev - })); - } - const connectors = getKitConnectWallets(projectAccessKey2, wallets); - return connectors; -}; -const getDefaultChains = (chainIdsFilter) => { - if (chainIdsFilter) { - return chainIdsFilter.map((chainId) => { - const chain = chains$1[chainId]; - if (!chain) { - throw new Error(`Chain with id ${chainId} not supported by Sequence`); - } - return chain; - }); - } - return Object.values(chains$1); + }; }; const walletClientToSigner = async (walletClient) => { var _a2, _b2; @@ -99821,19 +99551,6 @@ const sendTransactions = async ({ chainId, senderAddress, publicClient, walletCl return txHash; } }; -const mock = (options) => ({ - id: "mock", - isSequenceBased: true, - logoDark: SequenceLogo, - logoLight: SequenceLogo, - // iconBackground: '#777', - name: "Mock", - type: "wallet", - createConnector: () => { - const connector = mock$1(options); - return connector; - } -}); const useOpenConnectModal = () => { const { setOpenConnectModal, openConnectModalState } = useConnectModalContext(); return { setOpenConnectModal, openConnectModalState }; @@ -100131,10 +99848,10 @@ const useERC1155SaleContractPaymentModal = () => { }; }; const useClearCachedBalances = () => { - const queryClient2 = useQueryClient(); + const queryClient = useQueryClient(); return { clearCachedBalances: () => { - queryClient2.invalidateQueries({ + queryClient.invalidateQueries({ queryKey: ["balances"] }); } @@ -100273,7 +99990,7 @@ const OrderSummaryItem = ({ contractAddress, tokenId, quantityRaw, chainId }) => } const { name: name2 = "unknown", image, decimals = 0 } = (tokenMetadata == null ? void 0 : tokenMetadata[0]) ?? {}; const { logoURI: collectionLogoURI, name: collectionName = "Unknown Collection" } = contractInfo || {}; - const balanceFormatted = formatUnits$2(quantityRaw, decimals); + const balanceFormatted = formatUnits$1(quantityRaw, decimals); return jsxRuntimeExports$1.jsxs(Card, { flexDirection: "row", alignItems: "flex-start", justifyContent: "space-between", children: [jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: "2", children: [jsxRuntimeExports$1.jsx(Box, { aspectRatio: "1/1", height: "full", justifyContent: "center", alignItems: "center", style: { width: "80px" }, children: jsxRuntimeExports$1.jsx(Image$1, { src: image, borderRadius: "md", style: { maxWidth: "80px", height: "80px", objectFit: "cover" } }) }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", alignItems: "flex-start", justifyContent: "center", gap: "2", children: [jsxRuntimeExports$1.jsxs(Box, { gap: "1", alignItems: "center", children: [jsxRuntimeExports$1.jsx(TokenImage, { src: collectionLogoURI, size: "xs" }), jsxRuntimeExports$1.jsx(Text, { marginLeft: "1", variant: "small", color: "text80", fontWeight: "bold", children: collectionName }), jsxRuntimeExports$1.jsx(NetworkImage, { chainId, size: "xs" })] }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", alignItems: "flex-start", justifyContent: "center", style: { width: "180px" }, children: [jsxRuntimeExports$1.jsx(Text, { variant: "normal", color: "text100", children: name2 }), jsxRuntimeExports$1.jsx(Text, { variant: "normal", color: "text50", children: `#${tokenId}` })] })] })] }), jsxRuntimeExports$1.jsx(Box, { height: "full", children: jsxRuntimeExports$1.jsx(Text, { variant: "small", color: "text50", fontWeight: "bold", children: `x${formatDisplay$1(balanceFormatted)}` }) })] }); @@ -100308,8 +100025,8 @@ const CheckoutSelection = () => { }); const userBalanceRaw = coinBalance ? coinBalance.balance : "0"; const requestedAmountRaw = ((_c2 = cryptoCheckoutSettings == null ? void 0 : cryptoCheckoutSettings.coinQuantity) == null ? void 0 : _c2.amountRequiredRaw) || "0"; - const userBalance = formatUnits$2(userBalanceRaw, coinDecimals); - const requestAmount = formatUnits$2(requestedAmountRaw, coinDecimals); + const userBalance = formatUnits$1(userBalanceRaw, coinDecimals); + const requestAmount = formatUnits$1(requestedAmountRaw, coinDecimals); const isInsufficientBalance = BigInt(userBalanceRaw) < BigInt(requestedAmountRaw); const orderSummaryItems = (settings == null ? void 0 : settings.orderSummaryItems) || []; const chainId = ((_d2 = settings == null ? void 0 : settings.cryptoCheckout) == null ? void 0 : _d2.chainId) || ((_e2 = settings == null ? void 0 : settings.creditCardCheckout) == null ? void 0 : _e2.chainId) || 1; @@ -101931,12 +101648,12 @@ const PayWithCrypto = ({ settings, disableButtons, setDisableButtons }) => { keys: ["name", "symbol", "currencyAddress"] }); const foundCoins = search2 === "" ? indexedCoins : fuzzySearchCoins.search(search2).map((result) => result.item); - const priceFormatted = formatUnits(BigInt(price), (currencyInfoData == null ? void 0 : currencyInfoData.decimals) || 0); + const priceFormatted = formatUnits$2(BigInt(price), (currencyInfoData == null ? void 0 : currencyInfoData.decimals) || 0); const isNativeToken = compareAddress$2(currencyAddress, zeroAddress); const isApproved = allowanceData >= BigInt(price) || isNativeToken; const balanceInfo = currencyBalanceData == null ? void 0 : currencyBalanceData.find((balanceData) => compareAddress$2(currencyAddress, balanceData.contractAddress)); const balance = BigInt((balanceInfo == null ? void 0 : balanceInfo.balance) || "0"); - let balanceFormatted = Number(formatUnits(balance, (currencyInfoData == null ? void 0 : currencyInfoData.decimals) || 0)); + let balanceFormatted = Number(formatUnits$2(balance, (currencyInfoData == null ? void 0 : currencyInfoData.decimals) || 0)); balanceFormatted = Math.trunc(Number(balanceFormatted) * 1e4) / 1e4; const isNotEnoughFunds = BigInt(price) > balance; reactExports.useEffect(() => { @@ -102085,8 +101802,8 @@ const PayWithCrypto = ({ settings, disableButtons, setDisableButtons }) => { if (currencyInfoNotFound || !enableSwapPayments) { return null; } - const swapQuotePriceFormatted = formatUnits(BigInt(swapQuote.quote.price), ((_e2 = swapQuote.info) == null ? void 0 : _e2.decimals) || 18); - const balanceFormatted2 = formatUnits(BigInt(((_f2 = swapQuote.balance) == null ? void 0 : _f2.balance) || 0), ((_g2 = swapQuote.info) == null ? void 0 : _g2.decimals) || 18); + const swapQuotePriceFormatted = formatUnits$2(BigInt(swapQuote.quote.price), ((_e2 = swapQuote.info) == null ? void 0 : _e2.decimals) || 18); + const balanceFormatted2 = formatUnits$2(BigInt(((_f2 = swapQuote.balance) == null ? void 0 : _f2.balance) || 0), ((_g2 = swapQuote.info) == null ? void 0 : _g2.decimals) || 18); const swapQuoteAddress = ((_h2 = swapQuote.info) == null ? void 0 : _h2.address) || ""; const priceFiat = (exchangeRate * Number(swapQuotePriceFormatted)).toFixed(2); return jsxRuntimeExports$1.jsx(CryptoOption, { currencyName: ((_i2 = swapQuote.info) == null ? void 0 : _i2.name) || "Unknown", chainId, iconUrl: (_j2 = swapQuote.info) == null ? void 0 : _j2.logoURI, symbol: ((_k2 = swapQuote.info) == null ? void 0 : _k2.symbol) || "", onClick: () => { @@ -102133,7 +101850,7 @@ const Price = () => { const tokenLogo = currencyInfo == null ? void 0 : currencyInfo.logoURI; const tokenSymbol = currencyInfo == null ? void 0 : currencyInfo.symbol; const tokenDecimals = currencyInfo == null ? void 0 : currencyInfo.decimals; - const formattedPrice = formatUnits(fullPrice, tokenDecimals || 0); + const formattedPrice = formatUnits$2(fullPrice, tokenDecimals || 0); const fiatConversionRate = ((_a2 = coinPricesData == null ? void 0 : coinPricesData[0].price) == null ? void 0 : _a2.value) || 0; const priceFiat = fiatConversionRate * Number(formattedPrice); const priceFiatFormatted = `~${Number(priceFiat).toFixed(2)} USD`; @@ -103615,8 +103332,8 @@ const TransferToWallet = () => { return jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", gap: "2", alignItems: "center", justifyContent: "center", width: "full", paddingX: "4", paddingBottom: "4", height: "full", style: { paddingTop: HEADER_HEIGHT$1 }, children: jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", alignItems: "center", paddingX: "4", paddingBottom: "4", minHeight: "full", children: jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", placeItems: "center", width: "full", children: [jsxRuntimeExports$1.jsx(Text, { as: "p", variant: "normal", color: "text50", textAlign: "center", children: "Share your wallet address to receive coins" }), jsxRuntimeExports$1.jsx(Box, { marginY: "4", children: jsxRuntimeExports$1.jsx(QRCode, { value: address, "data-id": "receiveQR" }) }), jsxRuntimeExports$1.jsx(Text, { as: "div", width: "full", variant: "normal", color: "text50", textAlign: "center", "data-id": "receiveAddress", children: address })] }) }) }); }; const KitCheckoutProvider = (props) => { - const queryClient2 = new QueryClient(); - return jsxRuntimeExports$1.jsx(QueryClientProvider, { client: queryClient2, children: jsxRuntimeExports$1.jsx(KitCheckoutContent, { ...props }) }); + const queryClient = new QueryClient(); + return jsxRuntimeExports$1.jsx(QueryClientProvider, { client: queryClient, children: jsxRuntimeExports$1.jsx(KitCheckoutContent, { ...props }) }); }; const KitCheckoutContent = ({ children }) => { const { theme, position } = useTheme(); @@ -104037,7 +103754,7 @@ const computeBalanceFiat = ({ balance, prices, decimals, conversionRate }) => { return "0.00"; } const priceFiat = ((_a2 = priceForToken.price) == null ? void 0 : _a2.value) || 0; - const valueFormatted = formatUnits$2(balance.balance, decimals); + const valueFormatted = formatUnits$1(balance.balance, decimals); const usdValue = parseFloat(valueFormatted) * priceFiat; totalUsd += usdValue; const fiatValue = totalUsd * conversionRate; @@ -104202,8 +103919,8 @@ const getBalancesAssetsSummary = async (apiClient, metadataClient, indexerClient const bPrice = (bPriceData == null ? void 0 : bPriceData.price) ? bPriceData.price.value : 0; const aDecimals = (_a2 = contractInfoMapByChainId[a2.chainId].contractInfoMap[a2.contractAddress]) == null ? void 0 : _a2.decimals; const bDecimals = (_b2 = contractInfoMapByChainId[b2.chainId].contractInfoMap[b2.contractAddress]) == null ? void 0 : _b2.decimals; - const aFormattedBalance = aDecimals === void 0 ? 0 : Number(formatUnits$2(a2.balance, aDecimals)); - const bFormattedBalance = bDecimals === void 0 ? 0 : Number(formatUnits$2(b2.balance, bDecimals)); + const aFormattedBalance = aDecimals === void 0 ? 0 : Number(formatUnits$1(a2.balance, aDecimals)); + const bFormattedBalance = bDecimals === void 0 ? 0 : Number(formatUnits$1(b2.balance, bDecimals)); const aValue = aFormattedBalance * aPrice; const bValue = bFormattedBalance * bPrice; return bValue - aValue; @@ -104402,7 +104119,7 @@ const CoinTile = ({ balance }) => { decimals: nativeTokenInfo.decimals }); const priceChangePercentage2 = getPercentagePriceChange(balance, dataCoinPrices); - const formattedBalance2 = formatUnits$2(balance.balance, nativeTokenInfo.decimals); + const formattedBalance2 = formatUnits$1(balance.balance, nativeTokenInfo.decimals); const balanceDisplayed2 = formatDisplay(formattedBalance2); return jsxRuntimeExports$1.jsx(CoinTileContent, { chainId: balance.chainId, logoUrl: nativeTokenInfo.logoURI, tokenName: nativeTokenInfo.name, balance: balanceDisplayed2, balanceFiat: computedBalance2, priceChangePercentage: priceChangePercentage2, symbol: nativeTokenInfo.symbol }); } @@ -104414,7 +104131,7 @@ const CoinTile = ({ balance }) => { decimals }); const priceChangePercentage = getPercentagePriceChange(balance, dataCoinPrices); - const formattedBalance = formatUnits$2(balance.balance, decimals); + const formattedBalance = formatUnits$1(balance.balance, decimals); const balanceDisplayed = formatDisplay(formattedBalance); const name2 = (contractInfo == null ? void 0 : contractInfo.name) || "Unknown"; const symbol = (contractInfo == null ? void 0 : contractInfo.name) || "TOKEN"; @@ -104527,7 +104244,7 @@ const Receive = () => { }; const SendItemInfo = ({ imageUrl, name: name2, decimals, balance, symbol, fiatValue, chainId, showSquareImage }) => { const { fiatCurrency } = useSettings(); - const formattedBalance = formatUnits$2(balance, decimals); + const formattedBalance = formatUnits$1(balance, decimals); const balanceDisplayed = formatDisplay(formattedBalance); return jsxRuntimeExports$1.jsxs(Box, { alignItems: "flex-end", justifyContent: "space-between", children: [jsxRuntimeExports$1.jsxs(Box, { justifyContent: "space-between", alignItems: "center", gap: "2", children: [showSquareImage ? jsxRuntimeExports$1.jsx(Box, { style: { width: "40px" }, children: jsxRuntimeExports$1.jsx(CollectibleTileImage, { imageUrl }) }) : jsxRuntimeExports$1.jsx(TokenImage, { src: imageUrl, size: "lg" }), jsxRuntimeExports$1.jsxs(Box, { flexDirection: "column", alignItems: "flex-start", children: [jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", alignItems: "center", gap: "1", children: [jsxRuntimeExports$1.jsx(Text, { variant: "medium", color: "text100", children: name2 }), jsxRuntimeExports$1.jsx(NetworkImage, { chainId, size: "xs" })] }), jsxRuntimeExports$1.jsxs(Text, { color: "text50", variant: "normal", children: [" ", `${balanceDisplayed} ${symbol} available`] })] })] }), jsxRuntimeExports$1.jsx(Box, { flexDirection: "column", alignItems: "flex-end", justifyContent: "flex-end", children: fiatValue && jsxRuntimeExports$1.jsx(Text, { variant: "normal", color: "text100", children: `${fiatCurrency.sign}${fiatValue}` }) })] }); }; @@ -104572,7 +104289,7 @@ const SendCoin = ({ chainId, contractAddress }) => { const imageUrl = isNativeCoin ? nativeTokenInfo.logoURI : (_d2 = tokenBalance == null ? void 0 : tokenBalance.contractInfo) == null ? void 0 : _d2.logoURI; const symbol = isNativeCoin ? nativeTokenInfo.symbol : ((_e2 = tokenBalance == null ? void 0 : tokenBalance.contractInfo) == null ? void 0 : _e2.symbol) || ""; const amountToSendFormatted = amount === "" ? "0" : amount; - const amountRaw = parseUnits$3(amountToSendFormatted, decimals); + const amountRaw = parseUnits$2(amountToSendFormatted, decimals); const amountToSendFiat = computeBalanceFiat({ balance: { ...tokenBalance, @@ -104592,7 +104309,7 @@ const SendCoin = ({ chainId, contractAddress }) => { const handleMax = () => { var _a3; (_a3 = amountInputRef.current) == null ? void 0 : _a3.focus(); - const maxAmount = formatUnits$2((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals).toString(); + const maxAmount = formatUnits$1((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals).toString(); setAmount(maxAmount); }; const handlePaste = async () => { @@ -104608,7 +104325,7 @@ const SendCoin = ({ chainId, contractAddress }) => { await switchChainAsync({ chainId }); } e2.preventDefault(); - const sendAmount = parseUnits$3(amountToSendFormatted, decimals); + const sendAmount = parseUnits$2(amountToSendFormatted, decimals); if (isNativeCoin) { analytics == null ? void 0 : analytics.track({ event: "SEND_TRANSACTION_REQUEST", @@ -104700,7 +104417,7 @@ const SendCollectible = ({ chainId, contractAddress, tokenId }) => { setAmount("1"); setShowAmountControls(false); } else if (contractType === "ERC1155") { - if (Number(formatUnits$2((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals)) >= 1) { + if (Number(formatUnits$1((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals)) >= 1) { setAmount("1"); } setShowAmountControls(true); @@ -104716,7 +104433,7 @@ const SendCollectible = ({ chainId, contractAddress, tokenId }) => { const name2 = ((_c2 = tokenBalance == null ? void 0 : tokenBalance.tokenMetadata) == null ? void 0 : _c2.name) || "Unknown"; const imageUrl = ((_d2 = tokenBalance == null ? void 0 : tokenBalance.tokenMetadata) == null ? void 0 : _d2.image) || ((_e2 = tokenBalance == null ? void 0 : tokenBalance.contractInfo) == null ? void 0 : _e2.logoURI) || ""; const amountToSendFormatted = amount === "" ? "0" : amount; - const amountRaw = parseUnits$3(amountToSendFormatted, decimals); + const amountRaw = parseUnits$2(amountToSendFormatted, decimals); const insufficientFunds = amountRaw > BigInt((tokenBalance == null ? void 0 : tokenBalance.balance) || "0"); const isNonZeroAmount = amountRaw > 0n; const handleChangeAmount = (ev) => { @@ -104735,14 +104452,14 @@ const SendCollectible = ({ chainId, contractAddress, tokenId }) => { var _a3; (_a3 = amountInputRef.current) == null ? void 0 : _a3.focus(); const incrementedAmount = Number(amount) + 1; - const maxAmount2 = Number(formatUnits$2((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals)); + const maxAmount2 = Number(formatUnits$1((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals)); const newAmount = Math.min(incrementedAmount, maxAmount2).toString(); setAmount(newAmount); }; const handleMax = () => { var _a3; (_a3 = amountInputRef.current) == null ? void 0 : _a3.focus(); - const maxAmount2 = formatUnits$2((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals).toString(); + const maxAmount2 = formatUnits$1((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals).toString(); setAmount(maxAmount2); }; const handlePaste = async () => { @@ -104758,7 +104475,7 @@ const SendCollectible = ({ chainId, contractAddress, tokenId }) => { if (!isCorrectChainId && isConnectorSequenceBased) { switchChain2({ chainId }); } - const sendAmount = parseUnits$3(amountToSendFormatted, decimals); + const sendAmount = parseUnits$2(amountToSendFormatted, decimals); switch (contractType) { case "ERC721": analytics == null ? void 0 : analytics.track({ @@ -104820,7 +104537,7 @@ const SendCollectible = ({ chainId, contractAddress, tokenId }) => { }); } }; - const maxAmount = formatUnits$2((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals).toString(); + const maxAmount = formatUnits$1((tokenBalance == null ? void 0 : tokenBalance.balance) || 0, decimals).toString(); const isMinimum = Number(amount) === 0; const isMaximum = Number(amount) >= Number(maxAmount); return jsxRuntimeExports$1.jsxs(Box, { padding: "5", paddingTop: "3", style: { @@ -105190,7 +104907,7 @@ const TransactionHistoryItem = ({ transaction: transaction2 }) => { } else { decimals = isNativeToken ? nativeTokenInfo.decimals : (_f2 = transfer.contractInfo) == null ? void 0 : _f2.decimals; } - const amountValue = formatUnits$2(amount, decimals); + const amountValue = formatUnits$1(amount, decimals); const symbol = isNativeToken ? nativeTokenInfo.symbol : ((_g2 = transfer.contractInfo) == null ? void 0 : _g2.symbol) || ""; const tokenLogoUri = isNativeToken ? nativeTokenInfo.logoURI : (_h2 = transfer.contractInfo) == null ? void 0 : _h2.logoURI; const fiatConversionRate = (_j2 = (_i2 = coinPrices.find((coinPrice) => compareAddress(coinPrice.token.contractAddress, transfer.contractAddress))) == null ? void 0 : _i2.price) == null ? void 0 : _j2.value; @@ -105314,7 +105031,7 @@ const BalanceItem = ({ balance }) => { return balance.balance; } const decimals = isNativeToken ? nativeTokenInfo.decimals : (_a3 = balance == null ? void 0 : balance.contractInfo) == null ? void 0 : _a3.decimals; - const bal = formatUnits$2(balance.balance, decimals || 0); + const bal = formatUnits$1(balance.balance, decimals || 0); const displayBalance = formatDisplay(bal); const symbol2 = isNativeToken ? nativeTokenInfo.symbol : (_b3 = balance == null ? void 0 : balance.contractInfo) == null ? void 0 : _b3.symbol; return `${displayBalance} ${symbol2}`; @@ -105684,7 +105401,7 @@ const CoinDetails = ({ contractAddress, chainId }) => { const symbol = isNativeToken ? getNativeTokenInfoByChainId(chainId, chains2).symbol : (_b2 = dataCoinBalance == null ? void 0 : dataCoinBalance.contractInfo) == null ? void 0 : _b2.symbol; const name2 = isNativeToken ? getNativeTokenInfoByChainId(chainId, chains2).name : (_c2 = dataCoinBalance == null ? void 0 : dataCoinBalance.contractInfo) == null ? void 0 : _c2.name; const decimals = isNativeToken ? getNativeTokenInfoByChainId(chainId, chains2).decimals : (_d2 = dataCoinBalance == null ? void 0 : dataCoinBalance.contractInfo) == null ? void 0 : _d2.decimals; - const formattedBalance = formatUnits$2((dataCoinBalance == null ? void 0 : dataCoinBalance.balance) || "0", decimals); + const formattedBalance = formatUnits$1((dataCoinBalance == null ? void 0 : dataCoinBalance.balance) || "0", decimals); const balanceDisplayed = formatDisplay(formattedBalance); const coinBalanceFiat = dataCoinBalance ? computeBalanceFiat({ balance: dataCoinBalance, @@ -105742,7 +105459,7 @@ const CollectionDetails = ({ chainId, contractAddress }) => { var _a3, _b2, _c2; const unformattedBalance = balance.balance; const decimals = ((_a3 = balance == null ? void 0 : balance.tokenMetadata) == null ? void 0 : _a3.decimals) || 0; - const formattedBalance = formatDisplay(formatUnits$2(unformattedBalance, decimals)); + const formattedBalance = formatDisplay(formatUnits$1(unformattedBalance, decimals)); return jsxRuntimeExports$1.jsxs(Box, { onClick: () => onClickItem(balance), userSelect: "none", cursor: "pointer", opacity: { hover: "80" }, children: [jsxRuntimeExports$1.jsx(Box, { background: "backgroundSecondary", aspectRatio: "1/1", width: "full", borderRadius: "md", justifyContent: "center", alignItems: "center", marginBottom: "2", children: jsxRuntimeExports$1.jsx(Image$1, { style: { height: "100%" }, src: (_b2 = balance.tokenMetadata) == null ? void 0 : _b2.image }) }), jsxRuntimeExports$1.jsx(Box, { children: jsxRuntimeExports$1.jsx(Text, { variant: "normal", fontWeight: "bold", color: "text100", children: `${(_c2 = balance.tokenMetadata) == null ? void 0 : _c2.name}` }) }), jsxRuntimeExports$1.jsx(Box, { children: jsxRuntimeExports$1.jsxs(Text, { variant: "normal", marginTop: "1", fontWeight: "medium", color: "text50", children: [formattedBalance, " Owned"] }) })] }, index2); }) })] })] }); }; @@ -105797,7 +105514,7 @@ const CollectibleDetails = ({ contractAddress, chainId, tokenId }) => { const collectionName = ((_b2 = dataCollectibleBalance == null ? void 0 : dataCollectibleBalance.contractInfo) == null ? void 0 : _b2.name) || "Unknown Collection"; const decimals = ((_c2 = dataCollectibleBalance == null ? void 0 : dataCollectibleBalance.tokenMetadata) == null ? void 0 : _c2.decimals) || 0; const rawBalance = (dataCollectibleBalance == null ? void 0 : dataCollectibleBalance.balance) || "0"; - const balance = formatUnits$2(rawBalance, decimals); + const balance = formatUnits$1(rawBalance, decimals); const formattedBalance = formatDisplay(Number(balance)); const valueFiat = dataCollectibleBalance ? computeBalanceFiat({ balance: dataCollectibleBalance, @@ -105887,7 +105604,7 @@ const TransactionDetails = ({ transaction: transaction2 }) => { const collectibleDecimals = ((_c3 = (_b4 = transfer == null ? void 0 : transfer.tokenMetadata) == null ? void 0 : _b4[tokenId]) == null ? void 0 : _c3.decimals) || 0; const coinDecimals = isNativeToken ? nativeTokenInfo.decimals : ((_d3 = transfer == null ? void 0 : transfer.contractInfo) == null ? void 0 : _d3.decimals) || 0; const decimals = isCollectible ? collectibleDecimals : coinDecimals; - const formattedBalance = formatUnits$2(amount, decimals); + const formattedBalance = formatUnits$1(amount, decimals); const balanceDisplayed = formatDisplay(formattedBalance); const fiatPrice = isCollectible ? (_f2 = (_e2 = collectiblePricesData == null ? void 0 : collectiblePricesData.find((collectible) => { var _a5, _b5; @@ -110054,8 +109771,8 @@ const DEFAULT_LOCATION = { location: "home" }; const KitWalletProvider = (props) => { - const queryClient2 = new QueryClient(); - return jsxRuntimeExports$1.jsx(QueryClientProvider, { client: queryClient2, children: jsxRuntimeExports$1.jsx(KitWalletContent, { ...props }) }); + const queryClient = new QueryClient(); + return jsxRuntimeExports$1.jsx(QueryClientProvider, { client: queryClient, children: jsxRuntimeExports$1.jsx(KitWalletContent, { ...props }) }); }; const KitWalletContent = ({ children }) => { const { theme, position } = useTheme(); @@ -110068,7 +109785,7 @@ const KitWalletContent = ({ children }) => { setHistory([]); } }, [openWalletModal]); - return jsxRuntimeExports$1.jsx(WalletModalContextProvider, { value: { setOpenWalletModal, openWalletModalState: openWalletModal }, children: jsxRuntimeExports$1.jsxs(NavigationContextProvider, { value: { setHistory, history }, children: [jsxRuntimeExports$1.jsx("div", { id: "kit-provider", children: jsxRuntimeExports$1.jsx(ThemeProvider, { root: "#kit-provider", scope: "kit", theme, children: jsxRuntimeExports$1.jsx(AnimatePresence, { children: openWalletModal && jsxRuntimeExports$1.jsx(Modal, { contentProps: { + return jsxRuntimeExports$1.jsx(WalletModalContextProvider, { value: { setOpenWalletModal, openWalletModalState: openWalletModal }, children: jsxRuntimeExports$1.jsxs(NavigationContextProvider, { value: { setHistory, history }, children: [jsxRuntimeExports$1.jsx("div", { id: "kit-wallet", children: jsxRuntimeExports$1.jsx(ThemeProvider, { root: "#kit-wallet", scope: "kit", theme, children: jsxRuntimeExports$1.jsx(AnimatePresence, { children: openWalletModal && jsxRuntimeExports$1.jsx(Modal, { contentProps: { style: { maxWidth: "400px", height: "fit-content", @@ -110635,7 +110352,7 @@ const Connected = () => { }, [pendingFeeOptionConfirmation]); reactExports.useEffect(() => { if (error == null ? void 0 : error.message) { - console.log(error == null ? void 0 : error.message); + console.log(error.message); } }, [error]); const chainId = useChainId(); @@ -110955,7 +110672,7 @@ const Connected = () => { "): " ] }), " ", - /* @__PURE__ */ jsxRuntimeExports$1.jsx(Text, { variant: "xsmall", children: formatUnits(BigInt(option.value), option.token.decimals || 0) }) + /* @__PURE__ */ jsxRuntimeExports$1.jsx(Text, { variant: "xsmall", children: formatUnits$2(BigInt(option.value), option.token.decimals || 0) }) ] }), /* @__PURE__ */ jsxRuntimeExports$1.jsxs(Box, { flexDirection: "row", children: [ /* @__PURE__ */ jsxRuntimeExports$1.jsxs(Text, { children: [ @@ -110964,7 +110681,7 @@ const Connected = () => { ": " ] }), " ", - /* @__PURE__ */ jsxRuntimeExports$1.jsx(Text, { children: formatUnits( + /* @__PURE__ */ jsxRuntimeExports$1.jsx(Text, { children: formatUnits$2( BigInt(((_a3 = feeOptionBalances.find((b2) => b2.tokenName === option.token.name)) == null ? void 0 : _a3.balance) || "0"), option.token.decimals || 0 ) }) @@ -110986,11 +110703,11 @@ const Connected = () => { (option) => option.token.name === selectedFeeOptionTokenName ); if ((selected == null ? void 0 : selected.token.contractAddress) !== void 0) { - const balance = parseUnits( + const balance = parseUnits$3( ((_b2 = feeOptionBalances.find((b2) => b2.tokenName === selected.token.name)) == null ? void 0 : _b2.balance) || "0", selected.token.decimals || 0 ); - const feeOptionValue = parseUnits(selected.value, selected.token.decimals || 0); + const feeOptionValue = parseUnits$3(selected.value, selected.token.decimals || 0); if (balance && balance < feeOptionValue) { setFeeOptionAlert({ title: "Insufficient balance", @@ -111131,14 +110848,14 @@ const Alert = ({ title, description: description2, secondaryDescription, variant ) }); }; const searchParams$1 = new URLSearchParams(location.search); -const connectionMode$1 = searchParams$1.get("mode") === "universal" ? "universal" : "waas"; +const walletType$1 = searchParams$1.get("type") === "universal" ? "universal" : "waas"; const Homepage = () => { const { theme } = useTheme$1(); const { isConnected } = useAccount(); const { setOpenConnectModal } = useOpenConnectModal(); - const handleSwitchConnectionMode = (mode) => { + const handleSwitchWalletType = (type) => { const searchParams2 = new URLSearchParams(); - searchParams2.set("mode", mode); + searchParams2.set("type", type); window.location.search = searchParams2.toString(); }; const onClickConnect = () => { @@ -111162,21 +110879,21 @@ const Homepage = () => { /* @__PURE__ */ jsxRuntimeExports$1.jsx(Box, { gap: "2", flexDirection: "row", alignItems: "center", children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(Button, { onClick: onClickConnect, variant: "feature", label: "Connect" }) }), /* @__PURE__ */ jsxRuntimeExports$1.jsxs(Box, { gap: "2", flexDirection: "column", paddingX: "4", marginTop: "10", width: "full", style: { maxWidth: breakpoints.md }, children: [ /* @__PURE__ */ jsxRuntimeExports$1.jsx( - ConnectionModeSelect, + WalletTypeSelect, { - mode: "waas", + type: "waas", title: "Embedded Wallet (WaaS)", description: "Connect to an embedded wallet for a seamless experience.", - onClick: handleSwitchConnectionMode + onClick: handleSwitchWalletType } ), /* @__PURE__ */ jsxRuntimeExports$1.jsx( - ConnectionModeSelect, + WalletTypeSelect, { - mode: "universal", + type: "universal", title: "Universal Wallet", description: "Connect to the universal sequence wallet or EIP6963 Injected wallet providers (web extension wallets).", - onClick: handleSwitchConnectionMode + onClick: handleSwitchWalletType } ) ] }) @@ -111184,9 +110901,9 @@ const Homepage = () => { /* @__PURE__ */ jsxRuntimeExports$1.jsx(Footer, {}) ] }); }; -const ConnectionModeSelect = (props) => { - const { mode, title, description: description2, onClick } = props; - const isSelected = connectionMode$1 === mode; +const WalletTypeSelect = (props) => { + const { type, title, description: description2, onClick } = props; + const isSelected = walletType$1 === type; return /* @__PURE__ */ jsxRuntimeExports$1.jsx( Card, { @@ -111198,7 +110915,7 @@ const ConnectionModeSelect = (props) => { boxShadow: isSelected ? "0 0 24px rgb(127 59 158 / 0.8)" : "none", borderColor: isSelected ? "rgb(127 59 200)" : "var(--seq-colors-border-normal)" }, - onClick: () => onClick(mode), + onClick: () => onClick(type), children: /* @__PURE__ */ jsxRuntimeExports$1.jsxs(Box, { gap: "2", children: [ /* @__PURE__ */ jsxRuntimeExports$1.jsxs(Box, { children: [ /* @__PURE__ */ jsxRuntimeExports$1.jsx(Text, { variant: "normal", fontWeight: "bold", color: isSelected ? "text100" : "text80", children: title }), @@ -111210,73 +110927,18 @@ const ConnectionModeSelect = (props) => { ); }; const searchParams = new URLSearchParams(location.search); -const connectionMode = searchParams.get("mode") === "universal" ? "universal" : "waas"; +const walletType = searchParams.get("type") === "universal" ? "universal" : "waas"; const isDebugMode = searchParams.has("debug"); const projectAccessKey = isDebugMode ? "AQAAAAAAAAK2JvvZhWqZ51riasWBftkrVXE" : "AQAAAAAAAEGvyZiWA9FMslYeG_yayXaHnSI"; -const chains = getDefaultChains([ChainId.ARBITRUM_NOVA, ChainId.ARBITRUM_SEPOLIA, ChainId.POLYGON]); -const transports = chains.reduce((acc, chain) => { - acc[chain.id] = http(); - return acc; -}, {}); -const waasConfigKey = isDebugMode ? "eyJwcm9qZWN0SWQiOjY5NCwicnBjU2VydmVyIjoiaHR0cHM6Ly9kZXYtd2Fhcy5zZXF1ZW5jZS5hcHAiLCJlbWFpbFJlZ2lvbiI6ImNhLWNlbnRyYWwtMSIsImVtYWlsQ2xpZW50SWQiOiI1NGF0bjV1cGk2M3FjNTlhMWVtM3ZiaHJzbiJ9" : "eyJwcm9qZWN0SWQiOjE2ODE1LCJlbWFpbFJlZ2lvbiI6ImNhLWNlbnRyYWwtMSIsImVtYWlsQ2xpZW50SWQiOiI2N2V2NXVvc3ZxMzVmcGI2OXI3NnJoYnVoIiwicnBjU2VydmVyIjoiaHR0cHM6Ly93YWFzLnNlcXVlbmNlLmFwcCJ9"; -const googleClientId = isDebugMode ? "603294233249-6h5saeg2uiu8akpcbar3r2aqjp6j7oem.apps.googleusercontent.com" : "970987756660-35a6tc48hvi8cev9cnknp0iugv9poa23.apps.googleusercontent.com"; -const appleClientId = "com.horizon.sequence.waas"; -const appleRedirectURI = window.location.origin + window.location.pathname; -const getWaasConnectors = () => { - const connectors = [ - ...getDefaultWaasConnectors({ - walletConnectProjectId: "c65a6cb1aa83c4e24500130f23a437d8", - defaultChainId: ChainId.ARBITRUM_NOVA, - waasConfigKey, - googleClientId, - appleClientId, - appleRedirectURI, - appName: "Kit Demo", - projectAccessKey, - // legacyEmailAuth: true, - enableConfirmationModal: localStorage.getItem("confirmationEnabled") === "true", - isDev: isDebugMode - }) - // ...(isDebugMode - // ? getKitConnectWallets(projectAccessKey, [ - // mock({ - // accounts: ['0xCb88b6315507e9d8c35D81AFB7F190aB6c3227C9'] - // }) - // ]) - // : []) - ]; - return connectors; -}; -const getUniversalConnectors = () => { - const connectors = [ - ...getDefaultConnectors({ - walletConnectProjectId: "c65a6cb1aa83c4e24500130f23a437d8", - defaultChainId: ChainId.ARBITRUM_NOVA, - appName: "demo app", - projectAccessKey - }), - ...isDebugMode ? getKitConnectWallets(projectAccessKey, [ - mock({ - accounts: ["0xCb88b6315507e9d8c35D81AFB7F190aB6c3227C9"] - }) - ]) : [] - ]; - return connectors; -}; -const wagmiConfig = createConfig({ - transports, - chains, - connectors: connectionMode === "waas" ? getWaasConnectors() : getUniversalConnectors() -}); +const walletConnectProjectId = "c65a6cb1aa83c4e24500130f23a437d8"; const kitConfig = { - isDev: isDebugMode, projectAccessKey, defaultTheme: "dark", signIn: { - projectName: "Kit Demo" - // logoUrl: 'sw-logo-white.svg', - // useMock: isDebugMode + projectName: "Kit Demo", + useMock: isDebugMode }, + isDev: isDebugMode, displayedAssets: [ // Native token { @@ -111305,9 +110967,26 @@ const kitConfig = { } ] }; -const queryClient = new QueryClient(); +const config = walletType === "waas" ? createConfig("waas", { + ...kitConfig, + appName: "Kit Demo", + walletConnectProjectId, + chainIds: [ChainId.ARBITRUM_NOVA, ChainId.ARBITRUM_SEPOLIA, ChainId.POLYGON], + defaultChainId: ChainId.ARBITRUM_NOVA, + waasConfigKey: isDebugMode ? "eyJwcm9qZWN0SWQiOjY5NCwicnBjU2VydmVyIjoiaHR0cHM6Ly9kZXYtd2Fhcy5zZXF1ZW5jZS5hcHAiLCJlbWFpbFJlZ2lvbiI6ImNhLWNlbnRyYWwtMSIsImVtYWlsQ2xpZW50SWQiOiI1NGF0bjV1cGk2M3FjNTlhMWVtM3ZiaHJzbiJ9" : "eyJwcm9qZWN0SWQiOjE2ODE1LCJlbWFpbFJlZ2lvbiI6ImNhLWNlbnRyYWwtMSIsImVtYWlsQ2xpZW50SWQiOiI2N2V2NXVvc3ZxMzVmcGI2OXI3NnJoYnVoIiwicnBjU2VydmVyIjoiaHR0cHM6Ly93YWFzLnNlcXVlbmNlLmFwcCJ9", + googleClientId: isDebugMode ? "603294233249-6h5saeg2uiu8akpcbar3r2aqjp6j7oem.apps.googleusercontent.com" : "970987756660-35a6tc48hvi8cev9cnknp0iugv9poa23.apps.googleusercontent.com", + appleClientId: "com.horizon.sequence.waas", + appleRedirectURI: window.location.origin + window.location.pathname, + enableConfirmationModal: localStorage.getItem("confirmationEnabled") === "true" +}) : createConfig("universal", { + ...kitConfig, + appName: "Kit Demo", + walletConnectProjectId, + chainIds: [ChainId.ARBITRUM_NOVA, ChainId.ARBITRUM_SEPOLIA, ChainId.POLYGON], + defaultChainId: ChainId.ARBITRUM_NOVA +}); const App = () => { - return /* @__PURE__ */ jsxRuntimeExports$1.jsx(WagmiProvider, { config: wagmiConfig, children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(KitProvider, { config: kitConfig, children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(KitWalletProvider, { children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(KitCheckoutProvider, { children: /* @__PURE__ */ jsxRuntimeExports$1.jsx("div", { id: "app", children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(ThemeProvider, { root: "#app", scope: "app", theme: "dark", children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(Homepage, {}) }) }) }) }) }) }) }); + return /* @__PURE__ */ jsxRuntimeExports$1.jsx(ThemeProvider, { theme: "dark", children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(SequenceKit, { config, children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(KitWalletProvider, { children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(KitCheckoutProvider, { children: /* @__PURE__ */ jsxRuntimeExports$1.jsx(Homepage, {}) }) }) }) }); }; console.log("VERSION:", "1.0.4"); const root = client.createRoot(document.getElementById("root")); @@ -111329,10 +111008,10 @@ export { decodeErrorResult as i, isAddressEqual as j, call as k, - concat as l, + concat$1 as l, encodeAbiParameters as m, isHex as n, process$1 as p, - stringify as s, + stringify$3 as s, tslib_es6$1 as t }; diff --git a/assets/index-DjpO9esu.js b/assets/index-Dh05DiNn.js similarity index 99% rename from assets/index-DjpO9esu.js rename to assets/index-Dh05DiNn.js index 23956da1..04c4e576 100644 --- a/assets/index-DjpO9esu.js +++ b/assets/index-Dh05DiNn.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-CN13kjv_.js","./index-eVNd97lK.js","./index-g_cLYwVj.css"])))=>i.map(i=>d[i]); -import { _ as __vitePreload } from "./index-eVNd97lK.js"; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-C_hKV8dq.js","./index-CaRdSd9P.js","./index-g_cLYwVj.css"])))=>i.map(i=>d[i]); +import { _ as __vitePreload } from "./index-CaRdSd9P.js"; const t = Symbol(); const s = Object.getPrototypeOf, c$1 = /* @__PURE__ */ new WeakMap(), l = (e) => e && (c$1.has(e) ? c$1.get(e) : s(e) === Object.prototype || s(e) === Array.prototype), y$1 = (e) => l(e) && e[t] || null, h = (e, t2 = true) => { c$1.set(e, t2); @@ -472,7 +472,7 @@ class d { } async initUi() { if (typeof window < "u") { - await __vitePreload(() => import("./index-CN13kjv_.js"), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); + await __vitePreload(() => import("./index-C_hKV8dq.js"), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); const e = document.createElement("wcm-modal"); document.body.insertAdjacentElement("beforeend", e), p.setIsUiLoaded(true); } diff --git a/assets/index-CnSoKQxV.js b/assets/index-wr_HNsXy.js similarity index 99% rename from assets/index-CnSoKQxV.js rename to assets/index-wr_HNsXy.js index 7b1bbc8a..7db03621 100644 --- a/assets/index-CnSoKQxV.js +++ b/assets/index-wr_HNsXy.js @@ -1,5 +1,5 @@ -import { B as Buffer, c as commonjsGlobal, e as eventemitter3Exports, g as getDefaultExportFromCjs } from "./index-eVNd97lK.js"; -import { j as js, s as sha_jsExports, r as require$$0, a as require$$1, b as require$$2 } from "./hooks.module-D1qE_AJG.js"; +import { B as Buffer, c as commonjsGlobal, e as eventemitter3Exports, g as getDefaultExportFromCjs } from "./index-CaRdSd9P.js"; +import { j as js, s as sha_jsExports, r as require$$0, a as require$$1, b as require$$2 } from "./hooks.module-BnzzsFhJ.js"; var dist = {}; var CoinbaseWalletSDK$1 = {}; var walletLogo$1 = {}; diff --git a/assets/index.es-B9PQPdl4.js b/assets/index.es-cfKIWXoD.js similarity index 99% rename from assets/index.es-B9PQPdl4.js rename to assets/index.es-cfKIWXoD.js index 8987fd2d..49e99ca8 100644 --- a/assets/index.es-B9PQPdl4.js +++ b/assets/index.es-cfKIWXoD.js @@ -1,6 +1,6 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DjpO9esu.js","./index-eVNd97lK.js","./index-g_cLYwVj.css"])))=>i.map(i=>d[i]); -import { p as process$1, a as getAugmentedNamespace, c as commonjsGlobal, b as global, B as Buffer, g as getDefaultExportFromCjs, _ as __vitePreload } from "./index-eVNd97lK.js"; -import { a as require$$0$2, r as require$$0$3, i as inherits_browserExports, e as eventsExports, G as Gg } from "./inherits_browser-Dwap8BoW.js"; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-Dh05DiNn.js","./index-CaRdSd9P.js","./index-g_cLYwVj.css"])))=>i.map(i=>d[i]); +import { p as process$1, a as getAugmentedNamespace, c as commonjsGlobal, b as global, B as Buffer, g as getDefaultExportFromCjs, _ as __vitePreload } from "./index-CaRdSd9P.js"; +import { a as require$$0$2, r as require$$0$3, i as inherits_browserExports, e as eventsExports, G as Gg } from "./inherits_browser-D3e42oki.js"; var __spreadArray = function(to2, from2, pack) { if (pack || arguments.length === 2) for (var i3 = 0, l2 = from2.length, ar2; i3 < l2; i3++) { if (ar2 || !(i3 in from2)) { @@ -27392,7 +27392,7 @@ class C2 { if (this.rpc = this.getRpcConfig(t), this.chainId = this.rpc.chains.length ? m2(this.rpc.chains) : m2(this.rpc.optionalChains), this.signer = await Iv.init({ projectId: this.rpc.projectId, metadata: this.rpc.metadata, disableProviderPing: t.disableProviderPing, relayUrl: t.relayUrl, storageOptions: t.storageOptions, customStoragePrefix: t.customStoragePrefix, telemetryEnabled: t.telemetryEnabled }), this.registerEventListeners(), await this.loadPersistedSession(), this.rpc.showQrModal) { let s2; try { - const { WalletConnectModal: i3 } = await __vitePreload(() => import("./index-DjpO9esu.js").then((n4) => n4.i), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); + const { WalletConnectModal: i3 } = await __vitePreload(() => import("./index-Dh05DiNn.js").then((n4) => n4.i), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url); s2 = i3; } catch { throw new Error("To use QR modal, please install @walletconnect/modal package"); diff --git a/assets/inherits_browser-Dwap8BoW.js b/assets/inherits_browser-D3e42oki.js similarity index 99% rename from assets/inherits_browser-Dwap8BoW.js rename to assets/inherits_browser-D3e42oki.js index ae9a9428..e8f4bbd3 100644 --- a/assets/inherits_browser-Dwap8BoW.js +++ b/assets/inherits_browser-D3e42oki.js @@ -1,4 +1,4 @@ -import { g as getDefaultExportFromCjs, a as getAugmentedNamespace, d as dist } from "./index-eVNd97lK.js"; +import { g as getDefaultExportFromCjs, a as getAugmentedNamespace, d as dist } from "./index-CaRdSd9P.js"; var events = { exports: {} }; var R = typeof Reflect === "object" ? Reflect : null; var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { diff --git a/index.html b/index.html index 9a281c09..99fffe43 100644 --- a/index.html +++ b/index.html @@ -24,7 +24,7 @@ Learn how to configure a non-root public URL by running `npm run build`. --> Sequence Kit Demo - +