diff --git a/src/app/modules/main/wallet_section/module.nim b/src/app/modules/main/wallet_section/module.nim index cab75374d3b..8de6c42cf42 100644 --- a/src/app/modules/main/wallet_section/module.nim +++ b/src/app/modules/main/wallet_section/module.nim @@ -14,6 +14,8 @@ import ./overview/module as overview_module import ./send/module as send_module import ./activity/controller as activityc +import ./wallet_connect/controller as wcc + import app/modules/shared_modules/collectibles/controller as collectiblesc import app/modules/shared_modules/collectible_details/controller as collectible_detailsc @@ -81,6 +83,8 @@ type # instance to be used in temporary, short-lived, workflows (e.g. send popup) tmpActivityController: activityc.Controller + wcController: wcc.Controller + ## Forward declaration proc onUpdatedKeypairsOperability*(self: Module, updatedKeypairs: seq[KeypairDto]) proc onLocalPairingStatusUpdate*(self: Module, data: LocalPairingStatus) @@ -137,7 +141,9 @@ proc newModule*( result.collectibleDetailsController = collectible_detailsc.newController(int32(backend_collectibles.CollectiblesRequestID.WalletAccount), networkService, events) result.filter = initFilter(result.controller) - result.view = newView(result, result.activityController, result.tmpActivityController, result.collectiblesController, result.collectibleDetailsController) + result.wcController = wcc.newController(events) + + result.view = newView(result, result.activityController, result.tmpActivityController, result.collectiblesController, result.collectibleDetailsController, result.wcController) method delete*(self: Module) = self.accountsModule.delete @@ -152,6 +158,7 @@ method delete*(self: Module) = self.tmpActivityController.delete self.collectiblesController.delete self.collectibleDetailsController.delete + self.wcController.delete if not self.addAccountModule.isNil: self.addAccountModule.delete diff --git a/src/app/modules/main/wallet_section/view.nim b/src/app/modules/main/wallet_section/view.nim index 427a96f011a..73145854e12 100644 --- a/src/app/modules/main/wallet_section/view.nim +++ b/src/app/modules/main/wallet_section/view.nim @@ -5,6 +5,7 @@ import app/modules/shared_modules/collectibles/controller as collectiblesc import app/modules/shared_modules/collectible_details/controller as collectible_detailsc import ./io_interface import ../../shared_models/currency_amount +import ./wallet_connect/controller as wcc QtObject: type @@ -21,6 +22,7 @@ QtObject: collectibleDetailsController: collectible_detailsc.Controller isNonArchivalNode: bool keypairOperabilityForObservedAccount: string + wcController: wcc.Controller proc setup(self: View) = self.QObject.setup @@ -28,13 +30,15 @@ QtObject: proc delete*(self: View) = self.QObject.delete - proc newView*(delegate: io_interface.AccessInterface, activityController: activityc.Controller, tmpActivityController: activityc.Controller, collectiblesController: collectiblesc.Controller, collectibleDetailsController: collectible_detailsc.Controller): View = + proc newView*(delegate: io_interface.AccessInterface, activityController: activityc.Controller, tmpActivityController: activityc.Controller, collectiblesController: collectiblesc.Controller, collectibleDetailsController: collectible_detailsc.Controller, wcController: wcc.Controller): View = new(result, delete) result.delegate = delegate result.activityController = activityController result.tmpActivityController = tmpActivityController result.collectiblesController = collectiblesController result.collectibleDetailsController = collectibleDetailsController + result.wcController = wcController + result.setup() proc load*(self: View) = @@ -203,3 +207,8 @@ QtObject: proc destroyKeypairImportPopup*(self: View) {.signal.} proc emitDestroyKeypairImportPopup*(self: View) = self.destroyKeypairImportPopup() + + proc getWalletConnectController(self: View): QVariant {.slot.} = + return newQVariant(self.wcController) + QtProperty[QVariant] walletConnectController: + read = getWalletConnectController diff --git a/src/app/modules/main/wallet_section/wallet_connect/controller.nim b/src/app/modules/main/wallet_section/wallet_connect/controller.nim new file mode 100644 index 00000000000..ad45720e2f7 --- /dev/null +++ b/src/app/modules/main/wallet_section/wallet_connect/controller.nim @@ -0,0 +1,52 @@ +import NimQml, logging, json + +import backend/wallet_connect as backend + +import app/core/eventemitter +import app/core/signals/types + +import constants + +QtObject: + type + Controller* = ref object of QObject + events: EventEmitter + + proc setup(self: Controller) = + self.QObject.setup + + proc delete*(self: Controller) = + self.QObject.delete + + proc newController*(events: EventEmitter): Controller = + new(result, delete) + + result.events = events + + result.setup() + + # Register for wallet events + result.events.on(SignalType.Wallet.event, proc(e: Args) = + # TODO #12434: async processing + discard + ) + + # supportedNamespaces is a Namespace as defined in status-go: services/wallet/walletconnect/walletconnect.go + proc proposeUserPair*(self: Controller, sessionProposalJson: string, supportedNamespacesJson: string) {.signal.} + + proc pairSessionProposal(self: Controller, sessionProposalJson: string) {.slot.} = + let ok = backend.pair(sessionProposalJson, proc (res: JsonNode) = + let sessionProposalJson = if res.hasKey("sessionProposal"): $res["sessionProposal"] else: "" + let supportedNamespacesJson = if res.hasKey("supportedNamespaces"): $res["supportedNamespaces"] else: "" + + self.proposeUserPair(sessionProposalJson, supportedNamespacesJson) + ) + + if not ok: + error "Failed to pair session" + + proc getProjectId*(self: Controller): string {.slot.} = + return constants.WALLET_CONNECT_PROJECT_ID + + QtProperty[string] projectId: + read = getProjectId \ No newline at end of file diff --git a/src/backend/wallet_connect.nim b/src/backend/wallet_connect.nim index e69de29bb2d..cbba1790c69 100644 --- a/src/backend/wallet_connect.nim +++ b/src/backend/wallet_connect.nim @@ -0,0 +1,26 @@ +import options +import json +import core, response_type + +from gen import rpc +import backend + +# Declared in services/wallet/walletconnect/walletconnect.go +#const eventWCTODO*: string = "wallet-wc-todo" + +# Declared in services/wallet/walletconnect/walletconnect.go +const ErrorChainsNotSupported*: string = "chains not supported" + +rpc(wCPairSessionProposal, "wallet"): + sessionProposalJson: string + +# TODO #12434: async answer +proc pair*(sessionProposalJson: string, callback: proc(response: JsonNode): void): bool = + try: + let response = wCPairSessionProposal(sessionProposalJson) + if response.error == nil and response.result != nil: + callback(response.result) + return response.error == nil + except Exception as e: + echo "@dd wCPairSessionProposal response: ", e.msg + return false diff --git a/src/constants.nim b/src/constants.nim index 12da4c63f85..36c472010bf 100644 --- a/src/constants.nim +++ b/src/constants.nim @@ -53,4 +53,5 @@ let ALCHEMY_ARBITRUM_GOERLI_TOKEN_RESOLVED* = desktopConfig.alchemyArbitrumGoerliToken ALCHEMY_OPTIMISM_MAINNET_TOKEN_RESOLVED* = desktopConfig.alchemyOptimismMainnetToken ALCHEMY_OPTIMISM_GOERLI_TOKEN_RESOLVED* = desktopConfig.alchemyOptimismGoerliToken - OPENSEA_API_KEY_RESOLVED* = desktopConfig.openseaApiKey \ No newline at end of file + OPENSEA_API_KEY_RESOLVED* = desktopConfig.openseaApiKey + WALLET_CONNECT_PROJECT_ID* = BUILD_WALLET_CONNECT_PROJECT_ID \ No newline at end of file diff --git a/src/env_cli_vars.nim b/src/env_cli_vars.nim index 1e755942ab9..0ca8878037b 100644 --- a/src/env_cli_vars.nim +++ b/src/env_cli_vars.nim @@ -20,6 +20,7 @@ const BASE_NAME_ALCHEMY_ARBITRUM_MAINNET_TOKEN = "ALCHEMY_ARBITRUM_MAINNET_TOKEN const BASE_NAME_ALCHEMY_ARBITRUM_GOERLI_TOKEN = "ALCHEMY_ARBITRUM_GOERLI_TOKEN" const BASE_NAME_ALCHEMY_OPTIMISM_MAINNET_TOKEN = "ALCHEMY_OPTIMISM_MAINNET_TOKEN" const BASE_NAME_ALCHEMY_OPTIMISM_GOERLI_TOKEN = "ALCHEMY_OPTIMISM_GOERLI_TOKEN" +const BASE_NAME_WALLET_CONNECT_PROJECT_ID = "WALLET_CONNECT_PROJECT_ID" ################################################################################ @@ -36,6 +37,9 @@ const BUILD_ALCHEMY_ARBITRUM_MAINNET_TOKEN = getEnv(BUILD_TIME_PREFIX & BASE_NAM const BUILD_ALCHEMY_ARBITRUM_GOERLI_TOKEN = getEnv(BUILD_TIME_PREFIX & BASE_NAME_ALCHEMY_ARBITRUM_GOERLI_TOKEN) const BUILD_ALCHEMY_OPTIMISM_MAINNET_TOKEN = getEnv(BUILD_TIME_PREFIX & BASE_NAME_ALCHEMY_OPTIMISM_MAINNET_TOKEN) const BUILD_ALCHEMY_OPTIMISM_GOERLI_TOKEN = getEnv(BUILD_TIME_PREFIX & BASE_NAME_ALCHEMY_OPTIMISM_GOERLI_TOKEN) +const + WALLET_CONNECT_STATUS_PROJECT_ID = "87815d72a81d739d2a7ce15c2cfdefb3" + BUILD_WALLET_CONNECT_PROJECT_ID = getEnv(BUILD_TIME_PREFIX & BASE_NAME_WALLET_CONNECT_PROJECT_ID, WALLET_CONNECT_STATUS_PROJECT_ID) ################################################################################ # Run time evaluated variables diff --git a/storybook/pages/WalletConnectPage.qml b/storybook/pages/WalletConnectPage.qml index 2183922ade4..68f831b13ce 100644 --- a/storybook/pages/WalletConnectPage.qml +++ b/storybook/pages/WalletConnectPage.qml @@ -19,6 +19,8 @@ import SortFilterProxyModel 0.2 import utils 1.0 +import nim 1.0 + Item { id: root @@ -29,11 +31,17 @@ Item { WalletConnect { id: walletConnect - SplitView.preferredWidth: 400 + SplitView.fillWidth: true - projectId: SystemUtils.getEnvVar("WALLET_CONNECT_PROJECT_ID") backgroundColor: Theme.palette.statusAppLayout.backgroundColor + controller: WalletConnectController { + pairSessionProposal: function(sessionProposalJson) { + proposeUserPair(sessionProposalJson, `{"eip155":{"methods":["eth_sendTransaction","personal_sign"],"chains":["eip155:5"],"events":["accountsChanged","chainChanged"],"accounts":["eip155:5:0x53780d79E83876dAA21beB8AFa87fd64CC29990b","eip155:5:0xBd54A96c0Ae19a220C8E1234f54c940DFAB34639","eip155:5:0x5D7905390b77A937Ae8c444aA8BF7Fa9a6A7DBA0"]}}`) + } + projectId: SystemUtils.getEnvVar("STATUS_BUILD_WALLET_CONNECT_PROJECT_ID") + } + clip: true } @@ -45,7 +53,8 @@ Item { Text { text: "projectId" } Text { - text: walletConnect.projectId.substring(0, 3) + "..." + walletConnect.projectId.substring(walletConnect.projectId.length - 3) + readonly property string projectId: walletConnect.controller.projectId + text: projectId.substring(0, 3) + "..." + projectId.substring(projectId.length - 3) font.bold: true } } diff --git a/storybook/stubs/nim/WalletConnectController.qml b/storybook/stubs/nim/WalletConnectController.qml new file mode 100644 index 00000000000..bf795e58623 --- /dev/null +++ b/storybook/stubs/nim/WalletConnectController.qml @@ -0,0 +1,15 @@ +import QtQuick 2.15 +import QtQuick.Controls 2.15 +import QtQuick.Layouts 1.15 + +// Stub for Controller QObject defined in src/app/modules/main/wallet_section/wallet_connect/controller.nim +Item { + id: root + + signal proposeUserPair(string sessionProposalJson, string supportedNamespacesJson) + + // function pairSessionProposal(/*string*/ sessionProposalJson) + required property var pairSessionProposal + + required property string projectId +} \ No newline at end of file diff --git a/storybook/stubs/nim/qmldir b/storybook/stubs/nim/qmldir new file mode 100644 index 00000000000..2981d63a0f7 --- /dev/null +++ b/storybook/stubs/nim/qmldir @@ -0,0 +1 @@ +WalletConnectController 1.0 WalletConnectController.qml \ No newline at end of file diff --git a/test/go/test-wallet_connect/helpers.go b/test/go/test-wallet_connect/helpers.go index 4bac1b3a5b5..b61d823097c 100644 --- a/test/go/test-wallet_connect/helpers.go +++ b/test/go/test-wallet_connect/helpers.go @@ -20,7 +20,7 @@ func loginToAccount(hashedPassword, userFolder, nodeConfigJson string) error { } accountsJson := statusgo.OpenAccounts(absUserFolder) accounts := make([]multiaccounts.Account, 0) - err = getApiResponse(accountsJson, &accounts) + err = getCAPIResponse(accountsJson, &accounts) if err != nil { return err } @@ -33,7 +33,7 @@ func loginToAccount(hashedPassword, userFolder, nodeConfigJson string) error { keystorePath := filepath.Join(filepath.Join(absUserFolder, "keystore/"), account.KeyUID) initKeystoreJson := statusgo.InitKeystore(keystorePath) apiResponse := statusgo.APIResponse{} - err = getApiResponse(initKeystoreJson, &apiResponse) + err = getCAPIResponse(initKeystoreJson, &apiResponse) if err != nil { return err } @@ -44,7 +44,7 @@ func loginToAccount(hashedPassword, userFolder, nodeConfigJson string) error { return err } loginJson := statusgo.LoginWithConfig(string(accountJson), hashedPassword, nodeConfigJson) - err = getApiResponse(loginJson, &apiResponse) + err = getCAPIResponse(loginJson, &apiResponse) if err != nil { return err } @@ -64,7 +64,7 @@ type jsonrpcRequest struct { Params json.RawMessage `json:"params,omitempty"` } -func callPrivateMethod(method string, params interface{}) string { +func callPrivateMethod(method string, params []interface{}) string { var paramsJson json.RawMessage var err error if params != nil { @@ -131,7 +131,7 @@ func processConfigArgs() (config *Config, nodeConfigJson string, userFolder stri return } -func getApiResponse[T any](responseJson string, res T) error { +func getCAPIResponse[T any](responseJson string, res T) error { apiResponse := statusgo.APIResponse{} err := json.Unmarshal([]byte(responseJson), &apiResponse) if err == nil { @@ -154,3 +154,48 @@ func getApiResponse[T any](responseJson string, res T) error { return nil } + +type jsonrpcSuccessfulResponse struct { + jsonrpcMessage + Result json.RawMessage `json:"result"` +} + +type jsonrpcErrorResponse struct { + jsonrpcMessage + Error jsonError `json:"error"` +} + +// jsonError represents Error message for JSON-RPC responses. +type jsonError struct { + Code int `json:"code"` + Message string `json:"message"` + Data interface{} `json:"data,omitempty"` +} + +func getRPCAPIResponse[T any](responseJson string, res T) error { + errApiResponse := jsonrpcErrorResponse{} + err := json.Unmarshal([]byte(responseJson), &errApiResponse) + if err == nil && errApiResponse.Error.Code != 0 { + return fmt.Errorf("API error: %#v", errApiResponse.Error) + } + + apiResponse := jsonrpcSuccessfulResponse{} + err = json.Unmarshal([]byte(responseJson), &apiResponse) + if err != nil { + return fmt.Errorf("failed to unmarshal jsonrpcSuccessfulResponse: %w", err) + } + + typeOfT := reflect.TypeOf(res) + kindOfT := typeOfT.Kind() + + // Check for valid types: pointer, slice, map + if kindOfT != reflect.Ptr && kindOfT != reflect.Slice && kindOfT != reflect.Map { + return fmt.Errorf("type T must be a pointer, slice, or map") + } + + if err := json.Unmarshal(apiResponse.Result, &res); err != nil { + return fmt.Errorf("failed to unmarshal data: %w", err) + } + + return nil +} diff --git a/test/go/test-wallet_connect/index.html b/test/go/test-wallet_connect/index.html index e0cff76b112..47f42c024be 100644 --- a/test/go/test-wallet_connect/index.html +++ b/test/go/test-wallet_connect/index.html @@ -13,7 +13,8 @@ />
- + + @@ -75,64 +76,27 @@ pairButton.addEventListener("click", function () { setStatus("Pairing..."); try { + // TODO DEV: remove harcode wc.pair(pairLinkInput.value) .then((sessionProposal) => { + //let sessionProposal = JSON.parse(`{"id":1698771618724119,"params":{"id":1698771618724119,"pairingTopic":"4c36da43ac0d351336663276de6b5e2182f42068b7021e3cd1a460d9d7077e20","expiry":1698771923,"requiredNamespaces":{"eip155":{"methods":["eth_sendTransaction","personal_sign"],"chains":["eip155:5"],"events":["chainChanged","accountsChanged"]}},"optionalNamespaces":{"eip155":{"methods":["eth_signTransaction","eth_sign","eth_signTypedData","eth_signTypedData_v4"],"chains":["eip155:5"],"events":[]}},"relays":[{"protocol":"irn"}],"proposer":{"publicKey":"5d648503f2ec0e5a263578c347e490dcacb4e4359f59d66f12905bb91b9f182d","metadata":{"description":"React App for WalletConnect","url":"https://react-app.walletconnect.com","icons":["https://github.com/avatars/u/37784886"],"name":"React App","verifyUrl":"https://verify.walletconnect.com"}}},"verifyContext":{"verified":{"verifyUrl":"https://verify.walletconnect.com","validation":"UNKNOWN","origin":"https://react-app.walletconnect.com"}}}`); setStatus(`Wait user pair`); setDetails( `Pair ID: ${sessionProposal.id} ; Topic: ${sessionProposal.params.pairingTopic}` ); - acceptButton.addEventListener("click", function () { - window.wc.approveSession(sessionProposal).then( - () => { - goEcho(`Session ${sessionProposal.id} approved`); - setStatus( - `Session ${sessionProposal.id} approved` - ); - acceptButton.style.display = "none"; - rejectButton.style.display = "none"; - }, - (err) => { + + window + .pairSessionProposal(JSON.stringify(sessionProposal)) + .then((success) => { + if (!success) { goEcho( - `Session ${sessionProposal.id} approve error: ${err.message}` - ); - setStatus( - `Session ${sessionProposal.id} approve error: ${err.message}` + `GO.pairSessionProposal call failed ${sessionProposal.id}` ); + setGoStatus(`GO.pairSessionProposal failed`, "red"); + return; } - ); - }); - - rejectButton.addEventListener("click", function () { - try { - window.wc.rejectSession(sessionProposal.id).then( - () => { - goEcho(`Session ${sessionProposal.id} rejected`); - setStatus( - `Session ${sessionProposal.id} rejected` - ); - acceptButton.style.display = "none"; - rejectButton.style.display = "none"; - }, - (err) => { - goEcho( - `Session ${sessionProposal.id} reject error` - ); - setStatus( - `Session ${sessionProposal.id} reject error` - ); - } - ); - } catch (err) { - goEcho( - `Session ${sessionProposal.id} reject error: ${err.message}` - ); - setStatus( - `Session ${sessionProposal.id} reject error: ${err.message}` - ); - } - }); - acceptButton.style.display = "inline"; - rejectButton.style.display = "inline"; + }); + // Waiting for "proposeUserPair" event }) .catch((error) => { goEcho(`Pairing error ${JSON.stringify(error)}`); @@ -149,9 +113,17 @@ window.auth(); }); - window.wc.registerForSessionRequest(event => { + window.wc.registerForSessionRequest((event) => { setStatus(`Session topic ${event.topic}`); - }) + window.sessionRequest(event).then((success) => { + if (!success) { + goEcho(`Session request status-go call failed ${event.topic}`); + setGoStatus(`Session ${event.id} rejected`, "purple"); + return; + } + // Waiting for userApproveSession event + }); + }); } function goEcho(message) { @@ -188,8 +160,65 @@ setGoStatus("ready"); statusGoReady(); break; - case "tokensAvailable": - setDetails(`${JSON.stringify(event.payload)}\n`); + case "proposeUserPair": + setGoStatus("Session proposed"); + setDetails(JSON.stringify(event.payload.supportedNamespaces)); + let sessionProposal = event.payload.sessionProposal; + acceptButton.addEventListener("click", function () { + try { + window.wc + .approveSession( + sessionProposal, + event.payload.supportedNamespaces + ) + .then( + () => { + goEcho(`Session ${sessionProposal.id} approved`); + setStatus(`Session ${sessionProposal.id} approved`); + acceptButton.style.display = "none"; + rejectButton.style.display = "none"; + }, + (err) => { + goEcho( + `Session ${sessionProposal.id} approve error: ${err}` + ); + setStatus( + `Session ${sessionProposal.id} approve error: ${err}` + ); + } + ); + } catch (err) { + goEcho(`WTF error: ${err.message}`); + setStatus(`WTF error: ${err.message}`); + } + }); + + rejectButton.addEventListener("click", function () { + try { + window.wc.rejectSession(sessionProposal.id).then( + () => { + goEcho(`Session ${sessionProposal.id} rejected`); + setStatus(`Session ${sessionProposal.id} rejected`); + acceptButton.style.display = "none"; + rejectButton.style.display = "none"; + }, + (err) => { + goEcho(`Session ${sessionProposal.id} reject error`); + setStatus(`Session ${sessionProposal.id} reject error`); + } + ); + } catch (err) { + goEcho( + `Session ${sessionProposal.id} reject error: ${err.message}` + ); + setStatus( + `Session ${sessionProposal.id} reject error: ${err.message}` + ); + } + }); + + acceptButton.style.display = "inline"; + rejectButton.style.display = "inline"; break; default: await new Promise((resolve) => setTimeout(resolve, 100)); diff --git a/test/go/test-wallet_connect/main.go b/test/go/test-wallet_connect/main.go index 9fa63b524e6..e7886c3da36 100644 --- a/test/go/test-wallet_connect/main.go +++ b/test/go/test-wallet_connect/main.go @@ -6,9 +6,11 @@ import ( "net/http" "os" + "github.com/ethereum/go-ethereum/log" webview "github.com/webview/webview_go" statusgo "github.com/status-im/status-go/mobile" + wc "github.com/status-im/status-go/services/wallet/walletconnect" "github.com/status-im/status-go/services/wallet/walletevent" "github.com/status-im/status-go/signal" ) @@ -22,8 +24,8 @@ type Configuration struct { } type GoEvent struct { - Name string `json:"name"` - Payload string `json:"payload"` + Name string `json:"name"` + Payload interface{} `json:"payload"` } var eventQueue chan GoEvent = make(chan GoEvent, 10000) @@ -44,10 +46,25 @@ func signalHandler(jsonEvent string) { if envelope.Type == signal.EventNodeReady { eventQueue <- GoEvent{Name: "nodeReady", Payload: ""} + } else if envelope.Type == "wallet" { + // parse envelope.Event to json + walletEvent := walletevent.Event{} + err := json.Unmarshal([]byte(jsonEvent), &walletEvent) + if err != nil { + fmt.Println("@dd Error parsing the wallet event: ", err) + return + } + // TODO: continue from here + if walletEvent.Type == "WalletConnectProposeUserPair" { + eventQueue <- GoEvent{Name: "proposeUserPair", Payload: walletEvent.Message} + } } } func main() { + // Setup status-go logger + log.Root().SetHandler(log.StdoutHandler) + signal.SetDefaultNodeNotificationHandler(signalHandler) config, nodeConfigJson, userFolder, err := processConfigArgs() if err != nil { @@ -64,10 +81,26 @@ func main() { w := webview.New(true) defer w.Destroy() w.SetTitle("WC status-go test") - w.SetSize(480, 320, webview.HintNone) + w.SetSize(620, 480, webview.HintNone) + + w.Bind("pairSessionProposal", func(sessionProposalJson string) bool { + sessionReqRes := callPrivateMethod("wallet_wCPairSessionProposal", []interface{}{sessionProposalJson}) + var apiResponse wc.PairSessionResponse + err = getRPCAPIResponse(sessionReqRes, &apiResponse) + if err != nil { + log.Error("Error parsing the API response", "error", err) + return false + } + + go func() { + eventQueue <- GoEvent{Name: "proposeUserPair", Payload: apiResponse} + }() + + return true + }) w.Bind("getConfiguration", func() Configuration { - projectID := os.Getenv("WALLET_CONNECT_PROJECT_ID") + projectID := os.Getenv("STATUS_BUILD_WALLET_CONNECT_PROJECT_ID") return Configuration{ProjectId: projectID} }) @@ -88,11 +121,13 @@ func main() { // Start a local server to serve the files http.HandleFunc("/bundle.js", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0") http.ServeFile(w, r, "../../../ui/app/AppLayouts/Wallet/views/walletconnect/sdk/generated/bundle.js") }) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - http.ServeFile(w, r, "index.html") + w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0") + http.ServeFile(w, r, "./index.html") }) go http.ListenAndServe(":8080", nil) diff --git a/ui/app/AppLayouts/Profile/views/AdvancedView.qml b/ui/app/AppLayouts/Profile/views/AdvancedView.qml index b86b8e367f3..c079c027913 100644 --- a/ui/app/AppLayouts/Profile/views/AdvancedView.qml +++ b/ui/app/AppLayouts/Profile/views/AdvancedView.qml @@ -24,6 +24,11 @@ import "../controls" import "../popups" import "../panels" +// TODO: remove DEV import +import AppLayouts.Wallet.stores 1.0 as WalletStores +import AppLayouts.Wallet.views.walletconnect 1.0 +// TODO end + SettingsContentBase { id: root @@ -151,6 +156,55 @@ SettingsContentBase { } } + StatusSettingsLineButton { + anchors.leftMargin: 0 + anchors.rightMargin: 0 + text: qsTr("Debug Wallet Connect") + visible: root.advancedStore.isDebugEnabled + + onClicked: { + wcLoader.active = true + } + + Component { + id: wcDialogComponent + StatusDialog { + id: wcDialog + + onOpenedChanged: { + if (!opened) { + wcLoader.active = false + } + } + + WalletConnect { + SplitView.preferredWidth: 400 + SplitView.preferredHeight: 600 + + backgroundColor: wcDialog.backgroundColor + + controller: WalletStores.RootStore.walletConnectController + } + + clip: true + } + } + + Loader { + id: wcLoader + + active: false + + onStatusChanged: { + if (status === Loader.Ready) { + wcLoader.item.open() + } + } + + sourceComponent: wcDialogComponent + } + } + Separator { width: parent.width } diff --git a/ui/app/AppLayouts/Wallet/stores/RootStore.qml b/ui/app/AppLayouts/Wallet/stores/RootStore.qml index 5b9fa8358d5..2f4d4c9f718 100644 --- a/ui/app/AppLayouts/Wallet/stores/RootStore.qml +++ b/ui/app/AppLayouts/Wallet/stores/RootStore.qml @@ -27,12 +27,14 @@ QtObject { property var accountSensitiveSettings: localAccountSensitiveSettings property bool hideSignPhraseModal: accountSensitiveSettings.hideSignPhraseModal + // "walletSection" is a context property slow to lookup, so we cache it here property var walletSectionInst: walletSection - property var totalCurrencyBalance: walletSection.totalCurrencyBalance - property var activityController: walletSection.activityController - property var tmpActivityController: walletSection.tmpActivityController - property string signingPhrase: walletSection.signingPhrase - property string mnemonicBackedUp: walletSection.isMnemonicBackedUp + property var totalCurrencyBalance: walletSectionInst.totalCurrencyBalance + property var activityController: walletSectionInst.activityController + property var tmpActivityController: walletSectionInst.tmpActivityController + property string signingPhrase: walletSectionInst.signingPhrase + property string mnemonicBackedUp: walletSectionInst.isMnemonicBackedUp + property var walletConnectController: walletSectionInst.walletConnectController property CollectiblesStore collectiblesStore: CollectiblesStore {} diff --git a/ui/app/AppLayouts/Wallet/views/walletconnect/RequestCodes.qml b/ui/app/AppLayouts/Wallet/views/walletconnect/RequestCodes.qml new file mode 100644 index 00000000000..afc4b775ce8 --- /dev/null +++ b/ui/app/AppLayouts/Wallet/views/walletconnect/RequestCodes.qml @@ -0,0 +1,17 @@ +import QtQuick 2.15 + +QtObject { + enum RequestCodes { + SdkInitSuccess, + SdkInitError, + + PairSuccess, + PairError, + + ApprovePairSuccess, + ApprovePairError, + + RejectPairSuccess, + RejectPairError + } +} \ No newline at end of file diff --git a/ui/app/AppLayouts/Wallet/views/walletconnect/WalletConnect.qml b/ui/app/AppLayouts/Wallet/views/walletconnect/WalletConnect.qml index 4f47ca892b5..eb169d61418 100644 --- a/ui/app/AppLayouts/Wallet/views/walletconnect/WalletConnect.qml +++ b/ui/app/AppLayouts/Wallet/views/walletconnect/WalletConnect.qml @@ -13,11 +13,10 @@ Item { implicitWidth: Math.min(mainLayout.implicitWidth, 400) implicitHeight: Math.min(mainLayout.implicitHeight, 700) - - required property string projectId required property color backgroundColor - property alias optionalSdkPath: sdkView.optionalSdkPath + // wallet_connect.Controller \see wallet_section/wallet_connect/controller.nim + required property var controller ColumnLayout { id: mainLayout @@ -45,7 +44,7 @@ Item { statusText.text = "Pairing..." sdkView.pair(pairLinkInput.text) } - enabled: pairLinkInput.text.length > 0 && sdkView.state === sdkView.disconnectedState + enabled: pairLinkInput.text.length > 0 && sdkView.sdkReady } StatusButton { @@ -54,30 +53,50 @@ Item { statusText.text = "Authenticating..." sdkView.auth() } - enabled: false && pairLinkInput.text.length > 0 && sdkView.state === sdkView.disconnectedState + enabled: false && pairLinkInput.text.length > 0 && sdkView.sdkReady } StatusButton { text: "Accept" onClicked: { - sdkView.acceptPairing() + sdkView.approvePairSession(d.sessionProposal, d.supportedNamespaces) } - visible: sdkView.state === sdkView.waitingPairState + visible: root.state === d.waitingPairState } StatusButton { text: "Reject" onClicked: { - sdkView.rejectPairing() + sdkView.rejectPairSession(d.sessionProposal.id) } - visible: sdkView.state === sdkView.waitingPairState + visible: root.state === d.waitingPairState } } - RowLayout { + ColumnLayout { StatusBaseText { id: statusText text: "-" } + Flickable { + Layout.fillWidth: true + Layout.preferredHeight: 200 + Layout.maximumHeight: 400 + + contentWidth: detailsText.width + contentHeight: detailsText.height + + StatusBaseText { + id: detailsText + text: "" + visible: text.length > 0 + + color: "#FF00FF" + } + + ScrollBar.vertical: ScrollBar {} + + clip: true + } } // TODO: DEBUG JS Loading in DMG @@ -126,16 +145,104 @@ Item { WalletConnectSDK { id: sdkView - projectId: root.projectId + projectId: controller.projectId backgroundColor: root.backgroundColor Layout.fillWidth: true // Note that a too smaller height might cause the webview to generate rendering errors Layout.preferredHeight: 10 + onSdkInit: function(success, info) { + d.setDetailsText(info) + if (success) { + d.setStatusText("Ready to pair or auth") + root.state = d.sdkReadyState + } else { + d.setStatusText("SDK Error", "red") + root.state = "" + } + } + + onPairSessionProposal: function(success, sessionProposal) { + d.setDetailsText(sessionProposal) + if (success) { + d.setStatusText("Pair ID: " + sessionProposal.id + "; Topic: " + sessionProposal.params.pairingTopic) + root.controller.pairSessionProposal(JSON.stringify(sessionProposal)) + // Expecting signal onProposeUserPair from controller + } else { + d.setStatusText("Pairing error", "red") + } + } + + onPairAcceptedResult: function(success, result) { + d.setDetailsText(result) + if (success) { + d.setStatusText("Pairing OK") + root.state = d.pairedState + } else { + d.setStatusText("Pairing error", "red") + root.state = d.sdkReadyState + } + } + + onPairRejectedResult: function(success, result) { + d.setDetailsText(result) + root.state = d.sdkReadyState + if (success) { + d.setStatusText("Pairing rejected") + } else { + d.setStatusText("Rejecting pairing error", "red") + } + } + onStatusChanged: function(message) { statusText.text = message } + + onResponseTimeout: { + d.setStatusText(`Timeout waiting for response. Reusing URI?`, "red") + } + } + } + + QtObject { + id: d + + property var sessionProposal: null + property var supportedNamespaces: null + + readonly property string sdkReadyState: "sdk_ready" + readonly property string waitingPairState: "waiting_pairing" + readonly property string pairedState: "paired" + + function setStatusText(message, textColor) { + statusText.text = message + if (textColor === undefined) { + textColor = "green" + } + statusText.color = textColor + } + function setDetailsText(message) { + if (message === undefined) { + message = "undefined" + } else if (typeof message !== "string") { + message = JSON.stringify(message, null, 2) + } + detailsText.text = message + } + } + + Connections { + target: root.controller + function onProposeUserPair(sessionProposalJson, supportedNamespacesJson) { + d.setStatusText("Waiting user accept") + + d.sessionProposal = JSON.parse(sessionProposalJson) + d.supportedNamespaces = JSON.parse(supportedNamespacesJson) + + d.setDetailsText(JSON.stringify(d.supportedNamespaces, null, 2)) + + root.state = d.waitingPairState } } } diff --git a/ui/app/AppLayouts/Wallet/views/walletconnect/WalletConnectSDK.qml b/ui/app/AppLayouts/Wallet/views/walletconnect/WalletConnectSDK.qml index 7dcd62fa7c0..40cbcdafc23 100644 --- a/ui/app/AppLayouts/Wallet/views/walletconnect/WalletConnectSDK.qml +++ b/ui/app/AppLayouts/Wallet/views/walletconnect/WalletConnectSDK.qml @@ -22,30 +22,32 @@ WebView { required property string projectId required property color backgroundColor - readonly property string notReadyState: "not-ready" - readonly property string disconnectedState: "disconnected" - readonly property string waitingPairState: "waiting_pairing" - readonly property string pairedState: "paired" + readonly property alias sdkReady: d.sdkReady - state: root.notReadyState - - property string optionalSdkPath: "" + signal sdkInit(bool success, var result) + signal pairSessionProposal(bool success, var sessionProposal) + signal pairAcceptedResult(bool success, var sessionType) + signal pairRejectedResult(bool success, var result) + signal responseTimeout() // TODO: proper report signal statusChanged(string message) function pair(pairLink) { - d.requestSdk( - "wcResult = {error: null}; try { wc.pair(\"" + pairLink + "\").then((sessionProposal) => { wcResult = {state: \"" + root.waitingPairState + "\", error: null, sessionProposal: sessionProposal}; }).catch((error) => { wcResult = {error: error}; }); } catch (e) { wcResult = {error: \"Exception: \" + e.message}; }; wcResult" - ) + let callStr = d.generateSdkCall("pair", `"${pairLink}"`, RequestCodes.PairSuccess, RequestCodes.PairError) + d.requestSdk(callStr) } - function acceptPairing() { - d.acceptPair(d.sessionProposal) + function approvePairSession(sessionProposal, supportedNamespaces) { + let callStr = d.generateSdkCall("approvePairSession", `${JSON.stringify(sessionProposal)}, ${JSON.stringify(supportedNamespaces)}`, RequestCodes.ApprovePairSuccess, RequestCodes.ApprovePairSuccess) + + d.requestSdk(callStr) } - function rejectPairing() { - d.rejectPair(d.sessionProposal.id) + function rejectPairSession(id) { + let callStr = d.generateSdkCall("rejectPairSession", id, RequestCodes.RejectPairSuccess, RequestCodes.RejectPairError) + + d.requestSdk(callStr) } // TODO #12434: remove debugging WebEngineView code @@ -101,47 +103,55 @@ WebView { onTriggered: { root.runJavaScript( "wcResult", - function(result) { - if (!result) { + function(wcResult) { + if (!wcResult) { return } let done = false - if (result.error) { + if (wcResult.error) { + console.debug(`@dd wcResult - ${JSON.stringify(wcResult)}`) done = true - if (root.state === root.notReadyState) { - root.statusChanged(`[${timer.errorCount++}] Failed SDK init; error: ${result.error}`) + if (!d.sdkReady) { + root.statusChanged(`[${timer.errorCount++}] Failed SDK init; error: ${wcResult.error}`) } else { - root.state = root.disconnectedState - root.statusChanged(`[${timer.errorCount++}] Operation error: ${result.error}`) + root.statusChanged(`[${timer.errorCount++}] Operation error: ${wcResult.error}`) } - } else if (result.state) { - switch (result.state) { - case root.disconnectedState: { - root.statusChanged(`Ready to pair or auth`) + } + + if (wcResult.state !== undefined) { + switch (wcResult.state) { + case RequestCodes.SdkInitSuccess: + d.sdkReady = true + root.sdkInit(true, "") break - } - case root.waitingPairState: { - d.sessionProposal = result.sessionProposal - root.statusChanged("Pair ID: " + result.sessionProposal.id + "; Topic: " + result.sessionProposal.params.pairingTopic) + case RequestCodes.SdkInitError: + d.sdkReady = false + root.sdkInit(false, wcResult.error) break - } - case root.pairedState: { - d.sessionType = result.sessionType - root.statusChanged(`Paired: ${JSON.stringify(result.sessionType)}`) + case RequestCodes.PairSuccess: + root.pairSessionProposal(true, wcResult.result) break - } - case root.disconnectedState: { - root.statusChanged(`User rejected PairID ${d.sessionProposal.id}`) + case RequestCodes.PairError: + root.pairSessionProposal(false, wcResult.error) + break + case RequestCodes.ApprovePairSuccess: + root.pairAcceptedResult(true, "") + break + case RequestCodes.ApprovePairError: + root.pairAcceptedResult(false, wcResult.error) + break + case RequestCodes.RejectPairSuccess: + root.pairRejectedResult(true, "") + break + case RequestCodes.RejectPairError: + root.pairRejectedResult(false, wcResult.error) break - } default: { - root.statusChanged(`[${timer.errorCount++}] Unknown state: ${result.state}`) - result.state = root.disconnectedState + root.statusChanged(`[${timer.errorCount++}] Unknown state: ${wcResult.state}`) } } - root.state = result.state done = true } @@ -162,8 +172,7 @@ WebView { onTriggered: { timer.stop() - root.state = root.disconnectedState - root.statusChanged(`Timeout waiting for response. The pairing might have been already attempted for the URI.`) + root.responseTimeout() } } @@ -172,37 +181,27 @@ WebView { property var sessionProposal: null property var sessionType: null + property bool sdkReady: false function isWaitingForSdk() { return timer.running } + + function generateSdkCall(methodName, paramsStr, successState, errorState) { + return "wcResult = {error: null}; try { wc." + methodName + "(" + paramsStr + ").then((callRes) => { wcResult = {state: " + successState + ", error: null, result: callRes}; }).catch((error) => { wcResult = {state: " + errorState + ", error: error}; }); } catch (e) { wcResult = {state: " + errorState + ", error: \"Exception: \" + e.message}; }; wcResult" + } function requestSdk(jsCode) { - console.debug(`@dd WalletConnectSDK.requestSdk; jsCode: ${jsCode}`) root.runJavaScript(jsCode, function(result) { - console.debug(`@dd WalletConnectSDK.requestSdk; result: ${JSON.stringify(result)}`) timer.restart() } ) } function init(projectId) { - d.requestSdk( - "wcResult = {error: null}; try { wc.init(\"" + projectId + "\").then((wc) => { wcResult = {state: \"" + root.disconnectedState + "\", error: null}; }).catch((error) => { wcResult = {error: error}; }); } catch (e) { wcResult = {error: \"Exception: \" + e.message}; }; wcResult" - ) - } - - function acceptPair(sessionProposal) { - d.requestSdk( - "wcResult = {error: null}; try { wc.approveSession(" + JSON.stringify(sessionProposal) + ").then((sessionType) => { wcResult = {state: \"" + root.pairedState + "\", error: null, sessionType: sessionType}; }).catch((error) => { wcResult = {error: error}; }); } catch (e) { wcResult = {error: \"Exception: \" + e.message}; }; wcResult" - ) - } - - function rejectPair(id) { - d.requestSdk( - "wcResult = {error: null}; try { wc.rejectSession(" + JSON.stringify(id) + ").then(() => { wcResult = {state: \"" + root.disconnectedState + "\", error: null}; }).catch((error) => { wcResult = {error: error}; }); } catch (e) { wcResult = {error: \"Exception: \" + e.message}; }; wcResult" - ) + console.debug(`@dd WC projectId - ${projectId}`) + d.requestSdk(generateSdkCall("init", `"${projectId}"`, RequestCodes.SdkInitSuccess, RequestCodes.SdkInitError)) } } } \ No newline at end of file diff --git a/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/README.md b/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/README.md index 844ec6e5762..1d2ab316147 100644 --- a/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/README.md +++ b/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/README.md @@ -1,5 +1,25 @@ # Wallet Connect Integration +## TODO + +- [ ] test namespaces implementation https://se-sdk-dapp.vercel.app/ + +Design questions + +- [ ] Do we report all chains and all accounts combination or let user select? + - Wallet Connect require to report all chainIDs that were requested + - Show error to user workflow. +- [ ] Can't respond to sign messages if the wallet-connect dialog/view is closed (app is minimized) + - Only apps that use deep links are expected to work seamlessly +- [ ] Do we report **disabled chains**? **Update session** in case of enabled/disabled chains? +- [ ] Allow user to **disconnect session**? +- [ ] Support update session if one account is added/removed? +- [ ] User awareness of session expiration? + - Support extend session? +- [ ] User error workflow: retry? +- [ ] Check the `Auth` request for verifyContext +- [ ] What `description` and `icons` to use for the app? See `metadata` parameter in `Web3Wallet.init` call + ## WalletConnect SDK management Install dependencies steps by executing commands in this directory: @@ -17,9 +37,6 @@ Install dependencies steps by executing commands in this directory: Use the web demo test client https://react-app.walletconnect.com/ for wallet pairing and https://react-auth-dapp.walletconnect.com/ for authentication -## TODO - -- [ ] test namespaces implementation https://se-sdk-dapp.vercel.app/ ## Log @@ -37,6 +54,7 @@ npm run build To test SDK loading add the following to `ui/app/mainui/AppMain.qml` ```qml +import AppLayouts.Wallet.stores 1.0 as WalletStores import AppLayouts.Wallet.views.walletconnect 1.0 // ... @@ -49,8 +67,10 @@ StatusDialog { SplitView.preferredWidth: 400 SplitView.preferredHeight: 600 - projectId: "" backgroundColor: wcHelperDialog.backgroundColor + + projectId: "" + controller: WalletStores.RootStore.wcController } clip: true diff --git a/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/generated/bundle.js b/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/generated/bundle.js index d7e05e1090d..052a0c7a235 100644 --- a/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/generated/bundle.js +++ b/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/generated/bundle.js @@ -1,2 +1,2 @@ /*! For license information please see bundle.js.LICENSE.txt */ -var e={8099:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});var i=r(7117);function n(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>8,t[r+1]=e>>>0,t}function s(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t}function o(e,t){return void 0===t&&(t=0),e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function a(e,t){return void 0===t&&(t=0),(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function h(e,t){return void 0===t&&(t=0),e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}function c(e,t){return void 0===t&&(t=0),(e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t])>>>0}function u(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>24,t[r+1]=e>>>16,t[r+2]=e>>>8,t[r+3]=e>>>0,t}function l(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24,t}function f(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),u(e/4294967296>>>0,t,r),u(e>>>0,t,r+4),t}function d(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),l(e>>>0,t,r),l(e/4294967296>>>0,t,r+4),t}t.readInt16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])<<16>>16},t.readUint16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])>>>0},t.readInt16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])<<16>>16},t.readUint16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])>>>0},t.writeUint16BE=n,t.writeInt16BE=n,t.writeUint16LE=s,t.writeInt16LE=s,t.readInt32BE=o,t.readUint32BE=a,t.readInt32LE=h,t.readUint32LE=c,t.writeUint32BE=u,t.writeInt32BE=u,t.writeUint32LE=l,t.writeInt32LE=l,t.readInt64BE=function(e,t){void 0===t&&(t=0);var r=o(e,t),i=o(e,t+4);return 4294967296*r+i-4294967296*(i>>31)},t.readUint64BE=function(e,t){return void 0===t&&(t=0),4294967296*a(e,t)+a(e,t+4)},t.readInt64LE=function(e,t){void 0===t&&(t=0);var r=h(e,t);return 4294967296*h(e,t+4)+r-4294967296*(r>>31)},t.readUint64LE=function(e,t){void 0===t&&(t=0);var r=c(e,t);return 4294967296*c(e,t+4)+r},t.writeUint64BE=f,t.writeInt64BE=f,t.writeUint64LE=d,t.writeInt64LE=d,t.readUintBE=function(e,t,r){if(void 0===r&&(r=0),e%8!=0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var i=0,n=1,s=e/8+r-1;s>=r;s--)i+=t[s]*n,n*=256;return i},t.readUintLE=function(e,t,r){if(void 0===r&&(r=0),e%8!=0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var i=0,n=1,s=r;s=n;o--)r[o]=t/s&255,s*=256;return r},t.writeUintLE=function(e,t,r,n){if(void 0===r&&(r=new Uint8Array(e/8)),void 0===n&&(n=0),e%8!=0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!i.isSafeInteger(t))throw new Error("writeUintLE value must be an integer");for(var s=1,o=n;o{Object.defineProperty(t,"__esModule",{value:!0});var i=r(8099),n=r(7309),s=20;function o(e,t,r){for(var n=1634760805,o=857760878,a=2036477234,h=1797285236,c=r[3]<<24|r[2]<<16|r[1]<<8|r[0],u=r[7]<<24|r[6]<<16|r[5]<<8|r[4],l=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],p=r[23]<<24|r[22]<<16|r[21]<<8|r[20],g=r[27]<<24|r[26]<<16|r[25]<<8|r[24],y=r[31]<<24|r[30]<<16|r[29]<<8|r[28],m=t[3]<<24|t[2]<<16|t[1]<<8|t[0],v=t[7]<<24|t[6]<<16|t[5]<<8|t[4],w=t[11]<<24|t[10]<<16|t[9]<<8|t[8],b=t[15]<<24|t[14]<<16|t[13]<<8|t[12],_=n,E=o,S=a,M=h,I=c,A=u,O=l,x=f,P=d,N=p,R=g,T=y,L=m,C=v,U=w,k=b,j=0;j>>16|L<<16)|0)>>>20|I<<12,A=(A^=N=N+(C=(C^=E=E+A|0)>>>16|C<<16)|0)>>>20|A<<12,O=(O^=R=R+(U=(U^=S=S+O|0)>>>16|U<<16)|0)>>>20|O<<12,x=(x^=T=T+(k=(k^=M=M+x|0)>>>16|k<<16)|0)>>>20|x<<12,O=(O^=R=R+(U=(U^=S=S+O|0)>>>24|U<<8)|0)>>>25|O<<7,x=(x^=T=T+(k=(k^=M=M+x|0)>>>24|k<<8)|0)>>>25|x<<7,A=(A^=N=N+(C=(C^=E=E+A|0)>>>24|C<<8)|0)>>>25|A<<7,I=(I^=P=P+(L=(L^=_=_+I|0)>>>24|L<<8)|0)>>>25|I<<7,A=(A^=R=R+(k=(k^=_=_+A|0)>>>16|k<<16)|0)>>>20|A<<12,O=(O^=T=T+(L=(L^=E=E+O|0)>>>16|L<<16)|0)>>>20|O<<12,x=(x^=P=P+(C=(C^=S=S+x|0)>>>16|C<<16)|0)>>>20|x<<12,I=(I^=N=N+(U=(U^=M=M+I|0)>>>16|U<<16)|0)>>>20|I<<12,x=(x^=P=P+(C=(C^=S=S+x|0)>>>24|C<<8)|0)>>>25|x<<7,I=(I^=N=N+(U=(U^=M=M+I|0)>>>24|U<<8)|0)>>>25|I<<7,O=(O^=T=T+(L=(L^=E=E+O|0)>>>24|L<<8)|0)>>>25|O<<7,A=(A^=R=R+(k=(k^=_=_+A|0)>>>24|k<<8)|0)>>>25|A<<7;i.writeUint32LE(_+n|0,e,0),i.writeUint32LE(E+o|0,e,4),i.writeUint32LE(S+a|0,e,8),i.writeUint32LE(M+h|0,e,12),i.writeUint32LE(I+c|0,e,16),i.writeUint32LE(A+u|0,e,20),i.writeUint32LE(O+l|0,e,24),i.writeUint32LE(x+f|0,e,28),i.writeUint32LE(P+d|0,e,32),i.writeUint32LE(N+p|0,e,36),i.writeUint32LE(R+g|0,e,40),i.writeUint32LE(T+y|0,e,44),i.writeUint32LE(L+m|0,e,48),i.writeUint32LE(C+v|0,e,52),i.writeUint32LE(U+w|0,e,56),i.writeUint32LE(k+b|0,e,60)}function a(e,t,r,i,s){if(void 0===s&&(s=0),32!==e.length)throw new Error("ChaCha: key size must be 32 bytes");if(i.length>>=8,t++;if(i>0)throw new Error("ChaCha: counter overflow")}t.streamXOR=a,t.stream=function(e,t,r,i){return void 0===i&&(i=0),n.wipe(r),a(e,t,r,r,i)}},5501:(e,t,r)=>{var i=r(5439),n=r(3027),s=r(7309),o=r(8099),a=r(4153);t.Cv=32,t.WH=12,t.pg=16;var h=new Uint8Array(16),c=function(){function e(e){if(this.nonceLength=t.WH,this.tagLength=t.pg,e.length!==t.Cv)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return e.prototype.seal=function(e,t,r,n){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var o=new Uint8Array(16);o.set(e,o.length-e.length);var a=new Uint8Array(32);i.stream(this._key,o,a,4);var h,c=t.length+this.tagLength;if(n){if(n.length!==c)throw new Error("ChaCha20Poly1305: incorrect destination length");h=n}else h=new Uint8Array(c);return i.streamXOR(this._key,o,t,h,4),this._authenticate(h.subarray(h.length-this.tagLength,h.length),a,h.subarray(0,h.length-this.tagLength),r),s.wipe(o),h},e.prototype.open=function(e,t,r,n){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(t.length0&&a.update(h.subarray(i.length%16))),a.update(r),r.length%16>0&&a.update(h.subarray(r.length%16));var c=new Uint8Array(8);i&&o.writeUint64LE(i.length,c),a.update(c),o.writeUint64LE(r.length,c),a.update(c);for(var u=a.digest(),l=0;l{function r(e,t){if(e.length!==t.length)return 0;for(var r=0,i=0;i>>8}Object.defineProperty(t,"__esModule",{value:!0}),t.select=function(e,t,r){return~(e-1)&t|e-1&r},t.lessOrEqual=function(e,t){return(0|e)-(0|t)-1>>>31&1},t.compare=r,t.equal=function(e,t){return 0!==e.length&&0!==t.length&&0!==r(e,t)}},1050:(e,t,r)=>{t.Xx=t._w=t.aP=t.KS=t.jQ=void 0;r(1416);const i=r(3350);r(7309);function n(e){const t=new Float64Array(16);if(e)for(let r=0;r>16&1),r[e-1]&=65535;r[15]=i[15]-32767-(r[14]>>16&1);const e=r[15]>>16&1;r[14]&=65535,f(i,r,1-e)}for(let t=0;t<16;t++)e[2*t]=255&i[t],e[2*t+1]=i[t]>>8}function p(e){const t=new Uint8Array(32);return d(t,e),1&t[0]}function g(e,t,r){for(let i=0;i<16;i++)e[i]=t[i]+r[i]}function y(e,t,r){for(let i=0;i<16;i++)e[i]=t[i]-r[i]}function m(e,t,r){let i,n,s=0,o=0,a=0,h=0,c=0,u=0,l=0,f=0,d=0,p=0,g=0,y=0,m=0,v=0,w=0,b=0,_=0,E=0,S=0,M=0,I=0,A=0,O=0,x=0,P=0,N=0,R=0,T=0,L=0,C=0,U=0,k=r[0],j=r[1],q=r[2],D=r[3],z=r[4],$=r[5],B=r[6],K=r[7],F=r[8],V=r[9],H=r[10],W=r[11],G=r[12],J=r[13],Y=r[14],X=r[15];i=t[0],s+=i*k,o+=i*j,a+=i*q,h+=i*D,c+=i*z,u+=i*$,l+=i*B,f+=i*K,d+=i*F,p+=i*V,g+=i*H,y+=i*W,m+=i*G,v+=i*J,w+=i*Y,b+=i*X,i=t[1],o+=i*k,a+=i*j,h+=i*q,c+=i*D,u+=i*z,l+=i*$,f+=i*B,d+=i*K,p+=i*F,g+=i*V,y+=i*H,m+=i*W,v+=i*G,w+=i*J,b+=i*Y,_+=i*X,i=t[2],a+=i*k,h+=i*j,c+=i*q,u+=i*D,l+=i*z,f+=i*$,d+=i*B,p+=i*K,g+=i*F,y+=i*V,m+=i*H,v+=i*W,w+=i*G,b+=i*J,_+=i*Y,E+=i*X,i=t[3],h+=i*k,c+=i*j,u+=i*q,l+=i*D,f+=i*z,d+=i*$,p+=i*B,g+=i*K,y+=i*F,m+=i*V,v+=i*H,w+=i*W,b+=i*G,_+=i*J,E+=i*Y,S+=i*X,i=t[4],c+=i*k,u+=i*j,l+=i*q,f+=i*D,d+=i*z,p+=i*$,g+=i*B,y+=i*K,m+=i*F,v+=i*V,w+=i*H,b+=i*W,_+=i*G,E+=i*J,S+=i*Y,M+=i*X,i=t[5],u+=i*k,l+=i*j,f+=i*q,d+=i*D,p+=i*z,g+=i*$,y+=i*B,m+=i*K,v+=i*F,w+=i*V,b+=i*H,_+=i*W,E+=i*G,S+=i*J,M+=i*Y,I+=i*X,i=t[6],l+=i*k,f+=i*j,d+=i*q,p+=i*D,g+=i*z,y+=i*$,m+=i*B,v+=i*K,w+=i*F,b+=i*V,_+=i*H,E+=i*W,S+=i*G,M+=i*J,I+=i*Y,A+=i*X,i=t[7],f+=i*k,d+=i*j,p+=i*q,g+=i*D,y+=i*z,m+=i*$,v+=i*B,w+=i*K,b+=i*F,_+=i*V,E+=i*H,S+=i*W,M+=i*G,I+=i*J,A+=i*Y,O+=i*X,i=t[8],d+=i*k,p+=i*j,g+=i*q,y+=i*D,m+=i*z,v+=i*$,w+=i*B,b+=i*K,_+=i*F,E+=i*V,S+=i*H,M+=i*W,I+=i*G,A+=i*J,O+=i*Y,x+=i*X,i=t[9],p+=i*k,g+=i*j,y+=i*q,m+=i*D,v+=i*z,w+=i*$,b+=i*B,_+=i*K,E+=i*F,S+=i*V,M+=i*H,I+=i*W,A+=i*G,O+=i*J,x+=i*Y,P+=i*X,i=t[10],g+=i*k,y+=i*j,m+=i*q,v+=i*D,w+=i*z,b+=i*$,_+=i*B,E+=i*K,S+=i*F,M+=i*V,I+=i*H,A+=i*W,O+=i*G,x+=i*J,P+=i*Y,N+=i*X,i=t[11],y+=i*k,m+=i*j,v+=i*q,w+=i*D,b+=i*z,_+=i*$,E+=i*B,S+=i*K,M+=i*F,I+=i*V,A+=i*H,O+=i*W,x+=i*G,P+=i*J,N+=i*Y,R+=i*X,i=t[12],m+=i*k,v+=i*j,w+=i*q,b+=i*D,_+=i*z,E+=i*$,S+=i*B,M+=i*K,I+=i*F,A+=i*V,O+=i*H,x+=i*W,P+=i*G,N+=i*J,R+=i*Y,T+=i*X,i=t[13],v+=i*k,w+=i*j,b+=i*q,_+=i*D,E+=i*z,S+=i*$,M+=i*B,I+=i*K,A+=i*F,O+=i*V,x+=i*H,P+=i*W,N+=i*G,R+=i*J,T+=i*Y,L+=i*X,i=t[14],w+=i*k,b+=i*j,_+=i*q,E+=i*D,S+=i*z,M+=i*$,I+=i*B,A+=i*K,O+=i*F,x+=i*V,P+=i*H,N+=i*W,R+=i*G,T+=i*J,L+=i*Y,C+=i*X,i=t[15],b+=i*k,_+=i*j,E+=i*q,S+=i*D,M+=i*z,I+=i*$,A+=i*B,O+=i*K,x+=i*F,P+=i*V,N+=i*H,R+=i*W,T+=i*G,L+=i*J,C+=i*Y,U+=i*X,s+=38*_,o+=38*E,a+=38*S,h+=38*M,c+=38*I,u+=38*A,l+=38*O,f+=38*x,d+=38*P,p+=38*N,g+=38*R,y+=38*T,m+=38*L,v+=38*C,w+=38*U,n=1,i=s+n+65535,n=Math.floor(i/65536),s=i-65536*n,i=o+n+65535,n=Math.floor(i/65536),o=i-65536*n,i=a+n+65535,n=Math.floor(i/65536),a=i-65536*n,i=h+n+65535,n=Math.floor(i/65536),h=i-65536*n,i=c+n+65535,n=Math.floor(i/65536),c=i-65536*n,i=u+n+65535,n=Math.floor(i/65536),u=i-65536*n,i=l+n+65535,n=Math.floor(i/65536),l=i-65536*n,i=f+n+65535,n=Math.floor(i/65536),f=i-65536*n,i=d+n+65535,n=Math.floor(i/65536),d=i-65536*n,i=p+n+65535,n=Math.floor(i/65536),p=i-65536*n,i=g+n+65535,n=Math.floor(i/65536),g=i-65536*n,i=y+n+65535,n=Math.floor(i/65536),y=i-65536*n,i=m+n+65535,n=Math.floor(i/65536),m=i-65536*n,i=v+n+65535,n=Math.floor(i/65536),v=i-65536*n,i=w+n+65535,n=Math.floor(i/65536),w=i-65536*n,i=b+n+65535,n=Math.floor(i/65536),b=i-65536*n,s+=n-1+37*(n-1),n=1,i=s+n+65535,n=Math.floor(i/65536),s=i-65536*n,i=o+n+65535,n=Math.floor(i/65536),o=i-65536*n,i=a+n+65535,n=Math.floor(i/65536),a=i-65536*n,i=h+n+65535,n=Math.floor(i/65536),h=i-65536*n,i=c+n+65535,n=Math.floor(i/65536),c=i-65536*n,i=u+n+65535,n=Math.floor(i/65536),u=i-65536*n,i=l+n+65535,n=Math.floor(i/65536),l=i-65536*n,i=f+n+65535,n=Math.floor(i/65536),f=i-65536*n,i=d+n+65535,n=Math.floor(i/65536),d=i-65536*n,i=p+n+65535,n=Math.floor(i/65536),p=i-65536*n,i=g+n+65535,n=Math.floor(i/65536),g=i-65536*n,i=y+n+65535,n=Math.floor(i/65536),y=i-65536*n,i=m+n+65535,n=Math.floor(i/65536),m=i-65536*n,i=v+n+65535,n=Math.floor(i/65536),v=i-65536*n,i=w+n+65535,n=Math.floor(i/65536),w=i-65536*n,i=b+n+65535,n=Math.floor(i/65536),b=i-65536*n,s+=n-1+37*(n-1),e[0]=s,e[1]=o,e[2]=a,e[3]=h,e[4]=c,e[5]=u,e[6]=l,e[7]=f,e[8]=d,e[9]=p,e[10]=g,e[11]=y,e[12]=m,e[13]=v,e[14]=w,e[15]=b}function v(e,t){m(e,t,t)}function w(e,t){const r=n(),i=n(),s=n(),o=n(),h=n(),c=n(),u=n(),l=n(),f=n();y(r,e[1],e[0]),y(f,t[1],t[0]),m(r,r,f),g(i,e[0],e[1]),g(f,t[0],t[1]),m(i,i,f),m(s,e[3],t[3]),m(s,s,a),m(o,e[2],t[2]),g(o,o,o),y(h,i,r),y(c,o,s),g(u,o,s),g(l,i,r),m(e[0],h,c),m(e[1],l,u),m(e[2],u,c),m(e[3],h,l)}function b(e,t,r){for(let i=0;i<4;i++)f(e[i],t[i],r)}function _(e,t){const r=n(),i=n(),s=n();(function(e,t){const r=n();let i;for(i=0;i<16;i++)r[i]=t[i];for(i=253;i>=0;i--)v(r,r),2!==i&&4!==i&&m(r,r,t);for(i=0;i<16;i++)e[i]=r[i]})(s,t[2]),m(r,t[0],s),m(i,t[1],s),d(e,i),e[31]^=p(r)<<7}function E(e,t){const r=[n(),n(),n(),n()];u(r[0],h),u(r[1],c),u(r[2],o),m(r[3],h,c),function(e,t,r){u(e[0],s),u(e[1],o),u(e[2],o),u(e[3],s);for(let i=255;i>=0;--i){const n=r[i/8|0]>>(7&i)&1;b(e,t,n),w(t,e),w(e,e),b(e,t,n)}}(e,r,t)}t._w=function(e){if(e.length!==t.aP)throw new Error(`ed25519: seed must be ${t.aP} bytes`);const r=(0,i.hash)(e);r[0]&=248,r[31]&=127,r[31]|=64;const s=new Uint8Array(32),o=[n(),n(),n(),n()];E(o,r),_(s,o);const a=new Uint8Array(64);return a.set(e),a.set(s,32),{publicKey:s,secretKey:a}};const S=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function M(e,t){let r,i,n,s;for(i=63;i>=32;--i){for(r=0,n=i-32,s=i-12;n>4)*S[n],r=t[n]>>8,t[n]&=255;for(n=0;n<32;n++)t[n]-=r*S[n];for(i=0;i<32;i++)t[i+1]+=t[i]>>8,e[i]=255&t[i]}function I(e){const t=new Float64Array(64);for(let r=0;r<64;r++)t[r]=e[r];for(let t=0;t<64;t++)e[t]=0;M(e,t)}t.Xx=function(e,t){const r=new Float64Array(64),s=[n(),n(),n(),n()],o=(0,i.hash)(e.subarray(0,32));o[0]&=248,o[31]&=127,o[31]|=64;const a=new Uint8Array(64);a.set(o.subarray(32),32);const h=new i.SHA512;h.update(a.subarray(32)),h.update(t);const c=h.digest();h.clean(),I(c),E(s,c),_(a,s),h.reset(),h.update(a.subarray(0,32)),h.update(e.subarray(32)),h.update(t);const u=h.digest();I(u);for(let e=0;e<32;e++)r[e]=c[e];for(let e=0;e<32;e++)for(let t=0;t<32;t++)r[e+t]+=u[e]*o[t];return M(a.subarray(32),r),a}},9984:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSerializableHash=function(e){return void 0!==e.saveState&&void 0!==e.restoreState&&void 0!==e.cleanSavedState}},512:(e,t,r)=>{var i=r(5629),n=r(7309),s=function(){function e(e,t,r,n){void 0===r&&(r=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=n;var s=i.hmac(this._hash,r,t);this._hmac=new i.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return e.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(0===e)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},e.prototype.expand=function(e){for(var t=new Uint8Array(e),r=0;r{Object.defineProperty(t,"__esModule",{value:!0});var i=r(9984),n=r(4153),s=r(7309),o=function(){function e(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var r=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(r).clean():r.set(t);for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.mul=Math.imul||function(e,t){var r=65535&e,i=65535&t;return r*i+((e>>>16&65535)*i+r*(t>>>16&65535)<<16>>>0)|0},t.add=function(e,t){return e+t|0},t.sub=function(e,t){return e-t|0},t.rotl=function(e,t){return e<>>32-t},t.rotr=function(e,t){return e<<32-t|e>>>t},t.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.MAX_SAFE_INTEGER=9007199254740991,t.isSafeInteger=function(e){return t.isInteger(e)&&e>=-t.MAX_SAFE_INTEGER&&e<=t.MAX_SAFE_INTEGER}},3027:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});var i=r(4153),n=r(7309);t.DIGEST_LENGTH=16;var s=function(){function e(e){this.digestLength=t.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=8191&r;var i=e[2]|e[3]<<8;this._r[1]=8191&(r>>>13|i<<3);var n=e[4]|e[5]<<8;this._r[2]=7939&(i>>>10|n<<6);var s=e[6]|e[7]<<8;this._r[3]=8191&(n>>>7|s<<9);var o=e[8]|e[9]<<8;this._r[4]=255&(s>>>4|o<<12),this._r[5]=o>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=8191&(o>>>14|a<<2);var h=e[12]|e[13]<<8;this._r[7]=8065&(a>>>11|h<<5);var c=e[14]|e[15]<<8;this._r[8]=8191&(h>>>8|c<<8),this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return e.prototype._blocks=function(e,t,r){for(var i=this._fin?0:2048,n=this._h[0],s=this._h[1],o=this._h[2],a=this._h[3],h=this._h[4],c=this._h[5],u=this._h[6],l=this._h[7],f=this._h[8],d=this._h[9],p=this._r[0],g=this._r[1],y=this._r[2],m=this._r[3],v=this._r[4],w=this._r[5],b=this._r[6],_=this._r[7],E=this._r[8],S=this._r[9];r>=16;){var M=e[t+0]|e[t+1]<<8;n+=8191&M;var I=e[t+2]|e[t+3]<<8;s+=8191&(M>>>13|I<<3);var A=e[t+4]|e[t+5]<<8;o+=8191&(I>>>10|A<<6);var O=e[t+6]|e[t+7]<<8;a+=8191&(A>>>7|O<<9);var x=e[t+8]|e[t+9]<<8;h+=8191&(O>>>4|x<<12),c+=x>>>1&8191;var P=e[t+10]|e[t+11]<<8;u+=8191&(x>>>14|P<<2);var N=e[t+12]|e[t+13]<<8;l+=8191&(P>>>11|N<<5);var R=e[t+14]|e[t+15]<<8,T=0,L=T;L+=n*p,L+=s*(5*S),L+=o*(5*E),L+=a*(5*_),T=(L+=h*(5*b))>>>13,L&=8191,L+=c*(5*w),L+=u*(5*v),L+=l*(5*m),L+=(f+=8191&(N>>>8|R<<8))*(5*y);var C=T+=(L+=(d+=R>>>5|i)*(5*g))>>>13;C+=n*g,C+=s*p,C+=o*(5*S),C+=a*(5*E),T=(C+=h*(5*_))>>>13,C&=8191,C+=c*(5*b),C+=u*(5*w),C+=l*(5*v),C+=f*(5*m),T+=(C+=d*(5*y))>>>13,C&=8191;var U=T;U+=n*y,U+=s*g,U+=o*p,U+=a*(5*S),T=(U+=h*(5*E))>>>13,U&=8191,U+=c*(5*_),U+=u*(5*b),U+=l*(5*w),U+=f*(5*v);var k=T+=(U+=d*(5*m))>>>13;k+=n*m,k+=s*y,k+=o*g,k+=a*p,T=(k+=h*(5*S))>>>13,k&=8191,k+=c*(5*E),k+=u*(5*_),k+=l*(5*b),k+=f*(5*w);var j=T+=(k+=d*(5*v))>>>13;j+=n*v,j+=s*m,j+=o*y,j+=a*g,T=(j+=h*p)>>>13,j&=8191,j+=c*(5*S),j+=u*(5*E),j+=l*(5*_),j+=f*(5*b);var q=T+=(j+=d*(5*w))>>>13;q+=n*w,q+=s*v,q+=o*m,q+=a*y,T=(q+=h*g)>>>13,q&=8191,q+=c*p,q+=u*(5*S),q+=l*(5*E),q+=f*(5*_);var D=T+=(q+=d*(5*b))>>>13;D+=n*b,D+=s*w,D+=o*v,D+=a*m,T=(D+=h*y)>>>13,D&=8191,D+=c*g,D+=u*p,D+=l*(5*S),D+=f*(5*E);var z=T+=(D+=d*(5*_))>>>13;z+=n*_,z+=s*b,z+=o*w,z+=a*v,T=(z+=h*m)>>>13,z&=8191,z+=c*y,z+=u*g,z+=l*p,z+=f*(5*S);var $=T+=(z+=d*(5*E))>>>13;$+=n*E,$+=s*_,$+=o*b,$+=a*w,T=($+=h*v)>>>13,$&=8191,$+=c*m,$+=u*y,$+=l*g,$+=f*p;var B=T+=($+=d*(5*S))>>>13;B+=n*S,B+=s*E,B+=o*_,B+=a*b,T=(B+=h*w)>>>13,B&=8191,B+=c*v,B+=u*m,B+=l*y,B+=f*g,n=L=8191&(T=(T=((T+=(B+=d*p)>>>13)<<2)+T|0)+(L&=8191)|0),s=C+=T>>>=13,o=U&=8191,a=k&=8191,h=j&=8191,c=q&=8191,u=D&=8191,l=z&=8191,f=$&=8191,d=B&=8191,t+=16,r-=16}this._h[0]=n,this._h[1]=s,this._h[2]=o,this._h[3]=a,this._h[4]=h,this._h[5]=c,this._h[6]=u,this._h[7]=l,this._h[8]=f,this._h[9]=d},e.prototype.finish=function(e,t){void 0===t&&(t=0);var r,i,n,s,o=new Uint16Array(10);if(this._leftover){for(s=this._leftover,this._buffer[s++]=1;s<16;s++)this._buffer[s]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(r=this._h[1]>>>13,this._h[1]&=8191,s=2;s<10;s++)this._h[s]+=r,r=this._h[s]>>>13,this._h[s]&=8191;for(this._h[0]+=5*r,r=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=r,r=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=r,o[0]=this._h[0]+5,r=o[0]>>>13,o[0]&=8191,s=1;s<10;s++)o[s]=this._h[s]+r,r=o[s]>>>13,o[s]&=8191;for(o[9]-=8192,i=(1^r)-1,s=0;s<10;s++)o[s]&=i;for(i=~i,s=0;s<10;s++)this._h[s]=this._h[s]&i|o[s];for(this._h[0]=65535&(this._h[0]|this._h[1]<<13),this._h[1]=65535&(this._h[1]>>>3|this._h[2]<<10),this._h[2]=65535&(this._h[2]>>>6|this._h[3]<<7),this._h[3]=65535&(this._h[3]>>>9|this._h[4]<<4),this._h[4]=65535&(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14),this._h[5]=65535&(this._h[6]>>>2|this._h[7]<<11),this._h[6]=65535&(this._h[7]>>>5|this._h[8]<<8),this._h[7]=65535&(this._h[8]>>>8|this._h[9]<<5),n=this._h[0]+this._pad[0],this._h[0]=65535&n,s=1;s<8;s++)n=(this._h[s]+this._pad[s]|0)+(n>>>16)|0,this._h[s]=65535&n;return e[t+0]=this._h[0]>>>0,e[t+1]=this._h[0]>>>8,e[t+2]=this._h[1]>>>0,e[t+3]=this._h[1]>>>8,e[t+4]=this._h[2]>>>0,e[t+5]=this._h[2]>>>8,e[t+6]=this._h[3]>>>0,e[t+7]=this._h[3]>>>8,e[t+8]=this._h[4]>>>0,e[t+9]=this._h[4]>>>8,e[t+10]=this._h[5]>>>0,e[t+11]=this._h[5]>>>8,e[t+12]=this._h[6]>>>0,e[t+13]=this._h[6]>>>8,e[t+14]=this._h[7]>>>0,e[t+15]=this._h[7]>>>8,this._finished=!0,this},e.prototype.update=function(e){var t,r=0,i=e.length;if(this._leftover){(t=16-this._leftover)>i&&(t=i);for(var n=0;n=16&&(t=i-i%16,this._blocks(e,r,t),r+=t,i-=t),i){for(n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.randomStringForEntropy=t.randomString=t.randomUint32=t.randomBytes=t.defaultRandomSource=void 0;const i=r(6008),n=r(8099),s=r(7309);function o(e,r=t.defaultRandomSource){return r.randomBytes(e)}t.defaultRandomSource=new i.SystemRandomSource,t.randomBytes=o,t.randomUint32=function(e=t.defaultRandomSource){const r=o(4,e),i=(0,n.readUint32LE)(r);return(0,s.wipe)(r),i};const a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function h(e,r=a,i=t.defaultRandomSource){if(r.length<2)throw new Error("randomString charset is too short");if(r.length>256)throw new Error("randomString charset is too long");let n="";const h=r.length,c=256-256%h;for(;e>0;){const t=o(Math.ceil(256*e/c),i);for(let i=0;i0;i++){const s=t[i];s{Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserRandomSource=void 0,t.BrowserRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;const e="undefined"!=typeof self?self.crypto||self.msCrypto:null;e&&void 0!==e.getRandomValues&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");const t=new Uint8Array(e);for(let e=0;e{Object.defineProperty(t,"__esModule",{value:!0}),t.NodeRandomSource=void 0;const i=r(7309);t.NodeRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;{const e=r(5883);e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let t=this._crypto.randomBytes(e);if(t.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");const r=new Uint8Array(e);for(let e=0;e{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemRandomSource=void 0;const i=r(5455),n=r(8871);t.SystemRandomSource=class{constructor(){return this.isAvailable=!1,this.name="",this._source=new i.BrowserRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Browser")):(this._source=new n.NodeRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Node")):void 0)}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}}},3294:(e,t,r)=>{var i=r(8099),n=r(7309);t.k=32,t.cn=64;var s=function(){function e(){this.digestLength=t.k,this.blockSize=t.cn,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return e.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},e.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},e.prototype.clean=function(){n.wipe(this._buffer),n.wipe(this._temp),this.reset()},e.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var r=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[r++],t--;this._bufferLength===this.blockSize&&(a(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(r=a(this._temp,this._state,e,r,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[r++],t--;return this},e.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,r=this._bufferLength,n=t/536870912|0,s=t<<3,o=t%64<56?64:128;this._buffer[r]=128;for(var h=r+1;h0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},e.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},e.prototype.cleanSavedState=function(e){n.wipe(e.state),e.buffer&&n.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},e}();t.mE=s;var o=new Int32Array([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]);function a(e,t,r,n,s){for(;s>=64;){for(var a=t[0],h=t[1],c=t[2],u=t[3],l=t[4],f=t[5],d=t[6],p=t[7],g=0;g<16;g++){var y=n+4*g;e[g]=i.readUint32BE(r,y)}for(g=16;g<64;g++){var m=e[g-2],v=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,w=((m=e[g-15])>>>7|m<<25)^(m>>>18|m<<14)^m>>>3;e[g]=(v+e[g-7]|0)+(w+e[g-16]|0)}for(g=0;g<64;g++)v=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&f^~l&d)|0)+(p+(o[g]+e[g]|0)|0)|0,w=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&h^a&c^h&c)|0,p=d,d=f,f=l,l=u+v|0,u=c,c=h,h=a,a=v+w|0;t[0]+=a,t[1]+=h,t[2]+=c,t[3]+=u,t[4]+=l,t[5]+=f,t[6]+=d,t[7]+=p,n+=64,s-=64}return n}t.vp=function(e){var t=new s;t.update(e);var r=t.digest();return t.clean(),r}},3350:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});var i=r(8099),n=r(7309);t.DIGEST_LENGTH=64,t.BLOCK_SIZE=128;var s=function(){function e(){this.digestLength=t.DIGEST_LENGTH,this.blockSize=t.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return e.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},e.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},e.prototype.clean=function(){n.wipe(this._buffer),n.wipe(this._tempHi),n.wipe(this._tempLo),this.reset()},e.prototype.update=function(e,r){if(void 0===r&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var i=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[i++],r--;this._bufferLength===this.blockSize&&(a(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(i=a(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,i,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[i++],r--;return this},e.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,r=this._bufferLength,n=t/536870912|0,s=t<<3,o=t%128<112?128:256;this._buffer[r]=128;for(var h=r+1;h0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},e.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},e.prototype.cleanSavedState=function(e){n.wipe(e.stateHi),n.wipe(e.stateLo),e.buffer&&n.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},e}();t.SHA512=s;var o=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function a(e,t,r,n,s,a,h){for(var c,u,l,f,d,p,g,y,m=r[0],v=r[1],w=r[2],b=r[3],_=r[4],E=r[5],S=r[6],M=r[7],I=n[0],A=n[1],O=n[2],x=n[3],P=n[4],N=n[5],R=n[6],T=n[7];h>=128;){for(var L=0;L<16;L++){var C=8*L+a;e[L]=i.readUint32BE(s,C),t[L]=i.readUint32BE(s,C+4)}for(L=0;L<80;L++){var U,k,j=m,q=v,D=w,z=b,$=_,B=E,K=S,F=I,V=A,H=O,W=x,G=P,J=N,Y=R;if(d=65535&(u=T),p=u>>>16,g=65535&(c=M),y=c>>>16,d+=65535&(u=(P>>>14|_<<18)^(P>>>18|_<<14)^(_>>>9|P<<23)),p+=u>>>16,g+=65535&(c=(_>>>14|P<<18)^(_>>>18|P<<14)^(P>>>9|_<<23)),y+=c>>>16,d+=65535&(u=P&N^~P&R),p+=u>>>16,g+=65535&(c=_&E^~_&S),y+=c>>>16,c=o[2*L],d+=65535&(u=o[2*L+1]),p+=u>>>16,g+=65535&c,y+=c>>>16,c=e[L%16],p+=(u=t[L%16])>>>16,g+=65535&c,y+=c>>>16,g+=(p+=(d+=65535&u)>>>16)>>>16,d=65535&(u=f=65535&d|p<<16),p=u>>>16,g=65535&(c=l=65535&g|(y+=g>>>16)<<16),y=c>>>16,d+=65535&(u=(I>>>28|m<<4)^(m>>>2|I<<30)^(m>>>7|I<<25)),p+=u>>>16,g+=65535&(c=(m>>>28|I<<4)^(I>>>2|m<<30)^(I>>>7|m<<25)),y+=c>>>16,p+=(u=I&A^I&O^A&O)>>>16,g+=65535&(c=m&v^m&w^v&w),y+=c>>>16,U=65535&(g+=(p+=(d+=65535&u)>>>16)>>>16)|(y+=g>>>16)<<16,k=65535&d|p<<16,d=65535&(u=W),p=u>>>16,g=65535&(c=z),y=c>>>16,p+=(u=f)>>>16,g+=65535&(c=l),y+=c>>>16,v=j,w=q,b=D,_=z=65535&(g+=(p+=(d+=65535&u)>>>16)>>>16)|(y+=g>>>16)<<16,E=$,S=B,M=K,m=U,A=F,O=V,x=H,P=W=65535&d|p<<16,N=G,R=J,T=Y,I=k,L%16==15)for(C=0;C<16;C++)c=e[C],d=65535&(u=t[C]),p=u>>>16,g=65535&c,y=c>>>16,c=e[(C+9)%16],d+=65535&(u=t[(C+9)%16]),p+=u>>>16,g+=65535&c,y+=c>>>16,l=e[(C+1)%16],d+=65535&(u=((f=t[(C+1)%16])>>>1|l<<31)^(f>>>8|l<<24)^(f>>>7|l<<25)),p+=u>>>16,g+=65535&(c=(l>>>1|f<<31)^(l>>>8|f<<24)^l>>>7),y+=c>>>16,l=e[(C+14)%16],p+=(u=((f=t[(C+14)%16])>>>19|l<<13)^(l>>>29|f<<3)^(f>>>6|l<<26))>>>16,g+=65535&(c=(l>>>19|f<<13)^(f>>>29|l<<3)^l>>>6),y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,e[C]=65535&g|y<<16,t[C]=65535&d|p<<16}d=65535&(u=I),p=u>>>16,g=65535&(c=m),y=c>>>16,c=r[0],p+=(u=n[0])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[0]=m=65535&g|y<<16,n[0]=I=65535&d|p<<16,d=65535&(u=A),p=u>>>16,g=65535&(c=v),y=c>>>16,c=r[1],p+=(u=n[1])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[1]=v=65535&g|y<<16,n[1]=A=65535&d|p<<16,d=65535&(u=O),p=u>>>16,g=65535&(c=w),y=c>>>16,c=r[2],p+=(u=n[2])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[2]=w=65535&g|y<<16,n[2]=O=65535&d|p<<16,d=65535&(u=x),p=u>>>16,g=65535&(c=b),y=c>>>16,c=r[3],p+=(u=n[3])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[3]=b=65535&g|y<<16,n[3]=x=65535&d|p<<16,d=65535&(u=P),p=u>>>16,g=65535&(c=_),y=c>>>16,c=r[4],p+=(u=n[4])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[4]=_=65535&g|y<<16,n[4]=P=65535&d|p<<16,d=65535&(u=N),p=u>>>16,g=65535&(c=E),y=c>>>16,c=r[5],p+=(u=n[5])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[5]=E=65535&g|y<<16,n[5]=N=65535&d|p<<16,d=65535&(u=R),p=u>>>16,g=65535&(c=S),y=c>>>16,c=r[6],p+=(u=n[6])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[6]=S=65535&g|y<<16,n[6]=R=65535&d|p<<16,d=65535&(u=T),p=u>>>16,g=65535&(c=M),y=c>>>16,c=r[7],p+=(u=n[7])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[7]=M=65535&g|y<<16,n[7]=T=65535&d|p<<16,a+=128,h-=128}return a}t.hash=function(e){var t=new s;t.update(e);var r=t.digest();return t.clean(),r}},7309:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wipe=function(e){for(var t=0;t{t.gi=t.Au=t.KS=t.kz=void 0;const i=r(1416),n=r(7309);function s(e){const t=new Float64Array(16);if(e)for(let r=0;r=0;--e){const t=r[e>>>3]>>>(7&e)&1;c(n,o,t),c(p,g,t),u(y,n,p),l(n,n,p),u(p,o,g),l(o,o,g),d(g,y),d(m,n),f(n,p,n),f(p,o,y),u(y,n,p),l(n,n,p),d(o,n),l(p,g,m),f(n,p,a),u(n,n,g),f(p,p,n),f(n,g,m),f(g,o,i),d(o,y),c(n,o,t),c(p,g,t)}for(let e=0;e<16;e++)i[e+16]=n[e],i[e+32]=p[e],i[e+48]=o[e],i[e+64]=g[e];const v=i.subarray(32),w=i.subarray(16);!function(e,t){const r=s();for(let e=0;e<16;e++)r[e]=t[e];for(let e=253;e>=0;e--)d(r,r),2!==e&&4!==e&&f(r,r,t);for(let t=0;t<16;t++)e[t]=r[t]}(v,v),f(w,w,v);const b=new Uint8Array(32);return function(e,t){const r=s(),i=s();for(let e=0;e<16;e++)i[e]=t[e];h(i),h(i),h(i);for(let e=0;e<2;e++){r[0]=i[0]-65517;for(let e=1;e<15;e++)r[e]=i[e]-65535-(r[e-1]>>16&1),r[e-1]&=65535;r[15]=i[15]-32767-(r[14]>>16&1);const e=r[15]>>16&1;r[14]&=65535,c(i,r,1-e)}for(let t=0;t<16;t++)e[2*t]=255&i[t],e[2*t+1]=i[t]>>8}(b,w),b}t.Au=function(e){const r=(0,i.randomBytes)(32,e),s=function(e){if(e.length!==t.KS)throw new Error(`x25519: seed must be ${t.KS} bytes`);const r=new Uint8Array(e);return{publicKey:(i=r,p(i,o)),secretKey:r};var i}(r);return(0,n.wipe)(r),s},t.gi=function(e,r,i=!1){if(e.length!==t.kz)throw new Error("X25519: incorrect secret key length");if(r.length!==t.kz)throw new Error("X25519: incorrect public key length");const n=p(e,r);if(i){let e=0;for(let t=0;t{function i(){return(null===r.g||void 0===r.g?void 0:r.g.crypto)||(null===r.g||void 0===r.g?void 0:r.g.msCrypto)||{}}function n(){const e=i();return e.subtle||e.webkitSubtle}Object.defineProperty(t,"__esModule",{value:!0}),t.isBrowserCryptoAvailable=t.getSubtleCrypto=t.getBrowerCrypto=void 0,t.getBrowerCrypto=i,t.getSubtleCrypto=n,t.isBrowserCryptoAvailable=function(){return!!i()&&!!n()}},8618:(e,t)=>{function r(){return"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product}function i(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node}Object.defineProperty(t,"__esModule",{value:!0}),t.isBrowser=t.isNode=t.isReactNative=void 0,t.isReactNative=r,t.isNode=i,t.isBrowser=function(){return!r()&&!i()}},1468:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(926),t),i.__exportStar(r(8618),t)},8200:(e,t,r)=>{r.d(t,{q:()=>i});class i{}},997:(e,t,r)=>{r.r(t),r.d(t,{IEvents:()=>i.q});var i=r(8200)},2568:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HEARTBEAT_EVENTS=t.HEARTBEAT_INTERVAL=void 0;const i=r(6736);t.HEARTBEAT_INTERVAL=i.FIVE_SECONDS,t.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}},3401:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),r(655).__exportStar(r(2568),t)},8969:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HeartBeat=void 0;const i=r(655),n=r(7187),s=r(6736),o=r(1614),a=r(3401);class h extends o.IHeartBeat{constructor(e){super(e),this.events=new n.EventEmitter,this.interval=a.HEARTBEAT_INTERVAL,this.interval=(null==e?void 0:e.interval)||a.HEARTBEAT_INTERVAL}static init(e){return i.__awaiter(this,void 0,void 0,(function*(){const t=new h(e);return yield t.init(),t}))}init(){return i.__awaiter(this,void 0,void 0,(function*(){yield this.initialize()}))}stop(){clearInterval(this.intervalRef)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}initialize(){return i.__awaiter(this,void 0,void 0,(function*(){this.intervalRef=setInterval((()=>this.pulse()),s.toMiliseconds(this.interval))}))}pulse(){this.events.emit(a.HEARTBEAT_EVENTS.pulse)}}t.HeartBeat=h},159:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(8969),t),i.__exportStar(r(1614),t),i.__exportStar(r(3401),t)},4174:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IHeartBeat=void 0;const i=r(997);class n extends i.IEvents{constructor(e){super()}}t.IHeartBeat=n},1614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),r(655).__exportStar(r(4174),t)},2030:e=>{e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},5150:(e,t,r)=>{const i=r(655),n=r(3954),s=i.__importDefault(r(653)),o=r(9728);t.ZP=class{constructor(){this.localStorage=s.default}getKeys(){return i.__awaiter(this,void 0,void 0,(function*(){return Object.keys(this.localStorage)}))}getEntries(){return i.__awaiter(this,void 0,void 0,(function*(){return Object.entries(this.localStorage).map(o.parseEntry)}))}getItem(e){return i.__awaiter(this,void 0,void 0,(function*(){const t=this.localStorage.getItem(e);if(null!==t)return n.safeJsonParse(t)}))}setItem(e,t){return i.__awaiter(this,void 0,void 0,(function*(){this.localStorage.setItem(e,n.safeJsonStringify(t))}))}removeItem(e){return i.__awaiter(this,void 0,void 0,(function*(){this.localStorage.removeItem(e)}))}}},653:(e,t,r)=>{!function(){let t;function i(){}t=i,t.prototype.getItem=function(e){return this.hasOwnProperty(e)?String(this[e]):null},t.prototype.setItem=function(e,t){this[e]=String(t)},t.prototype.removeItem=function(e){delete this[e]},t.prototype.clear=function(){const e=this;Object.keys(e).forEach((function(t){e[t]=void 0,delete e[t]}))},t.prototype.key=function(e){return e=e||0,Object.keys(this)[e]},t.prototype.__defineGetter__("length",(function(){return Object.keys(this).length})),void 0!==r.g&&r.g.localStorage?e.exports=r.g.localStorage:"undefined"!=typeof window&&window.localStorage?e.exports=window.localStorage:e.exports=new i}()},9728:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(9076),t),i.__exportStar(r(496),t)},9076:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IKeyValueStorage=void 0,t.IKeyValueStorage=class{}},496:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEntry=void 0;const i=r(3954);t.parseEntry=function(e){var t;return[e[0],i.safeJsonParse(null!==(t=e[1])&&void 0!==t?t:"")]}},5727:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PINO_CUSTOM_CONTEXT_KEY=t.PINO_LOGGER_DEFAULTS=void 0,t.PINO_LOGGER_DEFAULTS={level:"info"},t.PINO_CUSTOM_CONTEXT_KEY="custom_context"},9107:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pino=void 0;const i=r(655),n=i.__importDefault(r(6559));Object.defineProperty(t,"pino",{enumerable:!0,get:function(){return n.default}}),i.__exportStar(r(5727),t),i.__exportStar(r(8048),t)},8048:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.generateChildLogger=t.formatChildLoggerContext=t.getLoggerContext=t.setBrowserLoggerContext=t.getBrowserLoggerContext=t.getDefaultLoggerOptions=void 0;const i=r(5727);function n(e,t=i.PINO_CUSTOM_CONTEXT_KEY){return e[t]||""}function s(e,t,r=i.PINO_CUSTOM_CONTEXT_KEY){return e[r]=t,e}function o(e,t=i.PINO_CUSTOM_CONTEXT_KEY){let r="";return r=void 0===e.bindings?n(e,t):e.bindings().context||"",r}function a(e,t,r=i.PINO_CUSTOM_CONTEXT_KEY){const n=o(e,r);return n.trim()?`${n}/${t}`:t}t.getDefaultLoggerOptions=function(e){return Object.assign(Object.assign({},e),{level:(null==e?void 0:e.level)||i.PINO_LOGGER_DEFAULTS.level})},t.getBrowserLoggerContext=n,t.setBrowserLoggerContext=s,t.getLoggerContext=o,t.formatChildLoggerContext=a,t.generateChildLogger=function(e,t,r=i.PINO_CUSTOM_CONTEXT_KEY){const n=a(e,t,r);return s(e.child({context:n}),n,r)}},1882:()=>{},3014:()=>{},6900:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(6869),t),i.__exportStar(r(8033),t)},6869:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_THOUSAND=t.ONE_HUNDRED=void 0,t.ONE_HUNDRED=100,t.ONE_THOUSAND=1e3},8033:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=5*t.ONE_MINUTE,t.TEN_MINUTES=10*t.ONE_MINUTE,t.THIRTY_MINUTES=30*t.ONE_MINUTE,t.SIXTY_MINUTES=60*t.ONE_MINUTE,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=3*t.ONE_HOUR,t.SIX_HOURS=6*t.ONE_HOUR,t.TWELVE_HOURS=12*t.ONE_HOUR,t.TWENTY_FOUR_HOURS=24*t.ONE_HOUR,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=3*t.ONE_DAY,t.FIVE_DAYS=5*t.ONE_DAY,t.SEVEN_DAYS=7*t.ONE_DAY,t.THIRTY_DAYS=30*t.ONE_DAY,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=2*t.ONE_WEEK,t.THREE_WEEKS=3*t.ONE_WEEK,t.FOUR_WEEKS=4*t.ONE_WEEK,t.ONE_YEAR=365*t.ONE_DAY},6736:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(4273),t),i.__exportStar(r(7001),t),i.__exportStar(r(2939),t),i.__exportStar(r(6900),t)},2939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),r(655).__exportStar(r(8766),t)},8766:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IWatch=void 0,t.IWatch=class{}},3207:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fromMiliseconds=t.toMiliseconds=void 0;const i=r(6900);t.toMiliseconds=function(e){return e*i.ONE_THOUSAND},t.fromMiliseconds=function(e){return Math.floor(e/i.ONE_THOUSAND)}},3873:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.delay=void 0,t.delay=function(e){return new Promise((t=>{setTimeout((()=>{t(!0)}),e)}))}},4273:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(3873),t),i.__exportStar(r(3207),t)},7001:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Watch=void 0;class r{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){const t=this.get(e);if(void 0!==t.elapsed)throw new Error(`Watch already stopped for label: ${e}`);const r=Date.now()-t.started;this.timestamps.set(e,{started:t.started,elapsed:r})}get(e){const t=this.timestamps.get(e);if(void 0===t)throw new Error(`No timestamp found for label: ${e}`);return t}elapsed(e){const t=this.get(e);return t.elapsed||Date.now()-t.started}}t.Watch=r,t.default=r},2873:(e,t)=>{function r(e){let t;return"undefined"!=typeof window&&void 0!==window[e]&&(t=window[e]),t}function i(e){const t=r(e);if(!t)throw new Error(`${e} is not defined in Window`);return t}Object.defineProperty(t,"__esModule",{value:!0}),t.getLocalStorage=t.getLocalStorageOrThrow=t.getCrypto=t.getCryptoOrThrow=t.getLocation=t.getLocationOrThrow=t.getNavigator=t.getNavigatorOrThrow=t.getDocument=t.getDocumentOrThrow=t.getFromWindowOrThrow=t.getFromWindow=void 0,t.getFromWindow=r,t.getFromWindowOrThrow=i,t.getDocumentOrThrow=function(){return i("document")},t.getDocument=function(){return r("document")},t.getNavigatorOrThrow=function(){return i("navigator")},t.getNavigator=function(){return r("navigator")},t.getLocationOrThrow=function(){return i("location")},t.getLocation=function(){return r("location")},t.getCryptoOrThrow=function(){return i("crypto")},t.getCrypto=function(){return r("crypto")},t.getLocalStorageOrThrow=function(){return i("localStorage")},t.getLocalStorage=function(){return r("localStorage")}},5755:(e,t,r)=>{t.D=void 0;const i=r(2873);t.D=function(){let e,t;try{e=i.getDocumentOrThrow(),t=i.getLocationOrThrow()}catch(e){return null}function r(...t){const r=e.getElementsByTagName("meta");for(let e=0;ei.getAttribute(e))).filter((e=>!!e&&t.includes(e)));if(n.length&&n){const e=i.getAttribute("content");if(e)return e}}return""}const n=function(){let t=r("name","og:site_name","og:title","twitter:title");return t||(t=e.title),t}();return{description:r("description","og:description","twitter:description","keywords"),url:t.origin,icons:function(){const r=e.getElementsByTagName("link"),i=[];for(let e=0;e-1){const e=n.getAttribute("href");if(e)if(-1===e.toLowerCase().indexOf("https:")&&-1===e.toLowerCase().indexOf("http:")&&0!==e.indexOf("//")){let r=t.protocol+"//"+t.host;if(0===e.indexOf("/"))r+=e;else{const i=t.pathname.split("/");i.pop(),r+=i.join("/")+"/"+e}i.push(r)}else if(0===e.indexOf("//")){const r=t.protocol+e;i.push(r)}else i.push(e)}}return i}(),name:n}}},3550:function(e,t,r){!function(e,t){function i(e,t){if(!e)throw new Error(t||"Assertion failed")}function n(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function s(e,t,r){if(s.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var o;"object"==typeof e?e.exports=s:t.BN=s,s.BN=s,s.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:r(6601).Buffer}catch(e){}function a(e,t){var r=e.charCodeAt(t);return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void i(!1,"Invalid character in "+e)}function h(e,t,r){var i=a(e,r);return r-1>=t&&(i|=a(e,r-1)<<4),i}function c(e,t,r,n){for(var s=0,o=0,a=Math.min(e.length,r),h=t;h=49?c-49+10:c>=17?c-17+10:c,i(c>=0&&o0?e:t},s.min=function(e,t){return e.cmp(t)<0?e:t},s.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),i(t===(0|t)&&t>=2&&t<=36);var n=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(n++,this.negative=1),n=0;n-=3)o=e[n]|e[n-1]<<8|e[n-2]<<16,this.words[s]|=o<>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);else if("le"===r)for(n=0,s=0;n>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);return this._strip()},s.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var i=0;i=t;i-=2)n=h(e,t,i)<=18?(s-=18,o+=1,this.words[o]|=n>>>26):s+=8;else for(i=(e.length-t)%2==0?t+1:t;i=18?(s-=18,o+=1,this.words[o]|=n>>>26):s+=8;this._strip()},s.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var i=0,n=1;n<=67108863;n*=t)i++;i--,n=n/t|0;for(var s=e.length-r,o=s%i,a=Math.min(s,s-o)+r,h=0,u=r;u1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=l}catch(e){s.prototype.inspect=l}else s.prototype.inspect=l;function l(){return(this.red?""}var f=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function g(e,t,r){r.negative=t.negative^e.negative;var i=e.length+t.length|0;r.length=i,i=i-1|0;var n=0|e.words[0],s=0|t.words[0],o=n*s,a=67108863&o,h=o/67108864|0;r.words[0]=a;for(var c=1;c>>26,l=67108863&h,f=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=f;d++){var p=c-d|0;u+=(o=(n=0|e.words[p])*(s=0|t.words[d])+l)/67108864|0,l=67108863&o}r.words[c]=0|l,h=0|u}return 0!==h?r.words[c]=0|h:r.length--,r._strip()}s.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var n=0,s=0,o=0;o>>24-n&16777215,(n+=2)>=26&&(n-=26,o--),r=0!==s||o!==this.length-1?f[6-h.length]+h+r:h+r}for(0!==s&&(r=s.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var c=d[e],u=p[e];r="";var l=this.clone();for(l.negative=0;!l.isZero();){var g=l.modrn(u).toString(e);r=(l=l.idivn(u)).isZero()?g+r:f[c-g.length]+g+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}i(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(e,t){return this.toArrayLike(o,e,t)}),s.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},s.prototype.toArrayLike=function(e,t,r){this._strip();var n=this.byteLength(),s=r||Math.max(1,n);i(n<=s,"byte array longer than desired length"),i(s>0,"Requested array length <= 0");var o=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,s);return this["_toArrayLike"+("le"===t?"LE":"BE")](o,n),o},s.prototype._toArrayLikeLE=function(e,t){for(var r=0,i=0,n=0,s=0;n>8&255),r>16&255),6===s?(r>24&255),i=0,s=0):(i=o>>>24,s+=2)}if(r=0&&(e[r--]=o>>8&255),r>=0&&(e[r--]=o>>16&255),6===s?(r>=0&&(e[r--]=o>>24&255),i=0,s=0):(i=o>>>24,s+=2)}if(r>=0)for(e[r--]=i;r>=0;)e[r--]=0},Math.clz32?s.prototype._countBits=function(e){return 32-Math.clz32(e)}:s.prototype._countBits=function(e){var t=e,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},s.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},s.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},s.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},s.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},s.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},s.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var i=0;ie.length?this.clone().ixor(e):e.clone().ixor(this)},s.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},s.prototype.inotn=function(e){i("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var n=0;n0&&(this.words[n]=~this.words[n]&67108863>>26-r),this._strip()},s.prototype.notn=function(e){return this.clone().inotn(e)},s.prototype.setn=function(e,t){i("number"==typeof e&&e>=0);var r=e/26|0,n=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,i=e):(r=e,i=this);for(var n=0,s=0;s>>26;for(;0!==n&&s>>26;if(this.length=r.length,0!==n)this.words[this.length]=n,this.length++;else if(r!==this)for(;se.length?this.clone().iadd(e):e.clone().iadd(this)},s.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,i,n=this.cmp(e);if(0===n)return this.negative=0,this.length=1,this.words[0]=0,this;n>0?(r=this,i=e):(r=e,i=this);for(var s=0,o=0;o>26,this.words[o]=67108863&t;for(;0!==s&&o>26,this.words[o]=67108863&t;if(0===s&&o>>13,d=0|o[1],p=8191&d,g=d>>>13,y=0|o[2],m=8191&y,v=y>>>13,w=0|o[3],b=8191&w,_=w>>>13,E=0|o[4],S=8191&E,M=E>>>13,I=0|o[5],A=8191&I,O=I>>>13,x=0|o[6],P=8191&x,N=x>>>13,R=0|o[7],T=8191&R,L=R>>>13,C=0|o[8],U=8191&C,k=C>>>13,j=0|o[9],q=8191&j,D=j>>>13,z=0|a[0],$=8191&z,B=z>>>13,K=0|a[1],F=8191&K,V=K>>>13,H=0|a[2],W=8191&H,G=H>>>13,J=0|a[3],Y=8191&J,X=J>>>13,Q=0|a[4],Z=8191&Q,ee=Q>>>13,te=0|a[5],re=8191&te,ie=te>>>13,ne=0|a[6],se=8191&ne,oe=ne>>>13,ae=0|a[7],he=8191&ae,ce=ae>>>13,ue=0|a[8],le=8191&ue,fe=ue>>>13,de=0|a[9],pe=8191&de,ge=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(i=Math.imul(l,$))|0)+((8191&(n=(n=Math.imul(l,B))+Math.imul(f,$)|0))<<13)|0;c=((s=Math.imul(f,B))+(n>>>13)|0)+(ye>>>26)|0,ye&=67108863,i=Math.imul(p,$),n=(n=Math.imul(p,B))+Math.imul(g,$)|0,s=Math.imul(g,B);var me=(c+(i=i+Math.imul(l,F)|0)|0)+((8191&(n=(n=n+Math.imul(l,V)|0)+Math.imul(f,F)|0))<<13)|0;c=((s=s+Math.imul(f,V)|0)+(n>>>13)|0)+(me>>>26)|0,me&=67108863,i=Math.imul(m,$),n=(n=Math.imul(m,B))+Math.imul(v,$)|0,s=Math.imul(v,B),i=i+Math.imul(p,F)|0,n=(n=n+Math.imul(p,V)|0)+Math.imul(g,F)|0,s=s+Math.imul(g,V)|0;var ve=(c+(i=i+Math.imul(l,W)|0)|0)+((8191&(n=(n=n+Math.imul(l,G)|0)+Math.imul(f,W)|0))<<13)|0;c=((s=s+Math.imul(f,G)|0)+(n>>>13)|0)+(ve>>>26)|0,ve&=67108863,i=Math.imul(b,$),n=(n=Math.imul(b,B))+Math.imul(_,$)|0,s=Math.imul(_,B),i=i+Math.imul(m,F)|0,n=(n=n+Math.imul(m,V)|0)+Math.imul(v,F)|0,s=s+Math.imul(v,V)|0,i=i+Math.imul(p,W)|0,n=(n=n+Math.imul(p,G)|0)+Math.imul(g,W)|0,s=s+Math.imul(g,G)|0;var we=(c+(i=i+Math.imul(l,Y)|0)|0)+((8191&(n=(n=n+Math.imul(l,X)|0)+Math.imul(f,Y)|0))<<13)|0;c=((s=s+Math.imul(f,X)|0)+(n>>>13)|0)+(we>>>26)|0,we&=67108863,i=Math.imul(S,$),n=(n=Math.imul(S,B))+Math.imul(M,$)|0,s=Math.imul(M,B),i=i+Math.imul(b,F)|0,n=(n=n+Math.imul(b,V)|0)+Math.imul(_,F)|0,s=s+Math.imul(_,V)|0,i=i+Math.imul(m,W)|0,n=(n=n+Math.imul(m,G)|0)+Math.imul(v,W)|0,s=s+Math.imul(v,G)|0,i=i+Math.imul(p,Y)|0,n=(n=n+Math.imul(p,X)|0)+Math.imul(g,Y)|0,s=s+Math.imul(g,X)|0;var be=(c+(i=i+Math.imul(l,Z)|0)|0)+((8191&(n=(n=n+Math.imul(l,ee)|0)+Math.imul(f,Z)|0))<<13)|0;c=((s=s+Math.imul(f,ee)|0)+(n>>>13)|0)+(be>>>26)|0,be&=67108863,i=Math.imul(A,$),n=(n=Math.imul(A,B))+Math.imul(O,$)|0,s=Math.imul(O,B),i=i+Math.imul(S,F)|0,n=(n=n+Math.imul(S,V)|0)+Math.imul(M,F)|0,s=s+Math.imul(M,V)|0,i=i+Math.imul(b,W)|0,n=(n=n+Math.imul(b,G)|0)+Math.imul(_,W)|0,s=s+Math.imul(_,G)|0,i=i+Math.imul(m,Y)|0,n=(n=n+Math.imul(m,X)|0)+Math.imul(v,Y)|0,s=s+Math.imul(v,X)|0,i=i+Math.imul(p,Z)|0,n=(n=n+Math.imul(p,ee)|0)+Math.imul(g,Z)|0,s=s+Math.imul(g,ee)|0;var _e=(c+(i=i+Math.imul(l,re)|0)|0)+((8191&(n=(n=n+Math.imul(l,ie)|0)+Math.imul(f,re)|0))<<13)|0;c=((s=s+Math.imul(f,ie)|0)+(n>>>13)|0)+(_e>>>26)|0,_e&=67108863,i=Math.imul(P,$),n=(n=Math.imul(P,B))+Math.imul(N,$)|0,s=Math.imul(N,B),i=i+Math.imul(A,F)|0,n=(n=n+Math.imul(A,V)|0)+Math.imul(O,F)|0,s=s+Math.imul(O,V)|0,i=i+Math.imul(S,W)|0,n=(n=n+Math.imul(S,G)|0)+Math.imul(M,W)|0,s=s+Math.imul(M,G)|0,i=i+Math.imul(b,Y)|0,n=(n=n+Math.imul(b,X)|0)+Math.imul(_,Y)|0,s=s+Math.imul(_,X)|0,i=i+Math.imul(m,Z)|0,n=(n=n+Math.imul(m,ee)|0)+Math.imul(v,Z)|0,s=s+Math.imul(v,ee)|0,i=i+Math.imul(p,re)|0,n=(n=n+Math.imul(p,ie)|0)+Math.imul(g,re)|0,s=s+Math.imul(g,ie)|0;var Ee=(c+(i=i+Math.imul(l,se)|0)|0)+((8191&(n=(n=n+Math.imul(l,oe)|0)+Math.imul(f,se)|0))<<13)|0;c=((s=s+Math.imul(f,oe)|0)+(n>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,i=Math.imul(T,$),n=(n=Math.imul(T,B))+Math.imul(L,$)|0,s=Math.imul(L,B),i=i+Math.imul(P,F)|0,n=(n=n+Math.imul(P,V)|0)+Math.imul(N,F)|0,s=s+Math.imul(N,V)|0,i=i+Math.imul(A,W)|0,n=(n=n+Math.imul(A,G)|0)+Math.imul(O,W)|0,s=s+Math.imul(O,G)|0,i=i+Math.imul(S,Y)|0,n=(n=n+Math.imul(S,X)|0)+Math.imul(M,Y)|0,s=s+Math.imul(M,X)|0,i=i+Math.imul(b,Z)|0,n=(n=n+Math.imul(b,ee)|0)+Math.imul(_,Z)|0,s=s+Math.imul(_,ee)|0,i=i+Math.imul(m,re)|0,n=(n=n+Math.imul(m,ie)|0)+Math.imul(v,re)|0,s=s+Math.imul(v,ie)|0,i=i+Math.imul(p,se)|0,n=(n=n+Math.imul(p,oe)|0)+Math.imul(g,se)|0,s=s+Math.imul(g,oe)|0;var Se=(c+(i=i+Math.imul(l,he)|0)|0)+((8191&(n=(n=n+Math.imul(l,ce)|0)+Math.imul(f,he)|0))<<13)|0;c=((s=s+Math.imul(f,ce)|0)+(n>>>13)|0)+(Se>>>26)|0,Se&=67108863,i=Math.imul(U,$),n=(n=Math.imul(U,B))+Math.imul(k,$)|0,s=Math.imul(k,B),i=i+Math.imul(T,F)|0,n=(n=n+Math.imul(T,V)|0)+Math.imul(L,F)|0,s=s+Math.imul(L,V)|0,i=i+Math.imul(P,W)|0,n=(n=n+Math.imul(P,G)|0)+Math.imul(N,W)|0,s=s+Math.imul(N,G)|0,i=i+Math.imul(A,Y)|0,n=(n=n+Math.imul(A,X)|0)+Math.imul(O,Y)|0,s=s+Math.imul(O,X)|0,i=i+Math.imul(S,Z)|0,n=(n=n+Math.imul(S,ee)|0)+Math.imul(M,Z)|0,s=s+Math.imul(M,ee)|0,i=i+Math.imul(b,re)|0,n=(n=n+Math.imul(b,ie)|0)+Math.imul(_,re)|0,s=s+Math.imul(_,ie)|0,i=i+Math.imul(m,se)|0,n=(n=n+Math.imul(m,oe)|0)+Math.imul(v,se)|0,s=s+Math.imul(v,oe)|0,i=i+Math.imul(p,he)|0,n=(n=n+Math.imul(p,ce)|0)+Math.imul(g,he)|0,s=s+Math.imul(g,ce)|0;var Me=(c+(i=i+Math.imul(l,le)|0)|0)+((8191&(n=(n=n+Math.imul(l,fe)|0)+Math.imul(f,le)|0))<<13)|0;c=((s=s+Math.imul(f,fe)|0)+(n>>>13)|0)+(Me>>>26)|0,Me&=67108863,i=Math.imul(q,$),n=(n=Math.imul(q,B))+Math.imul(D,$)|0,s=Math.imul(D,B),i=i+Math.imul(U,F)|0,n=(n=n+Math.imul(U,V)|0)+Math.imul(k,F)|0,s=s+Math.imul(k,V)|0,i=i+Math.imul(T,W)|0,n=(n=n+Math.imul(T,G)|0)+Math.imul(L,W)|0,s=s+Math.imul(L,G)|0,i=i+Math.imul(P,Y)|0,n=(n=n+Math.imul(P,X)|0)+Math.imul(N,Y)|0,s=s+Math.imul(N,X)|0,i=i+Math.imul(A,Z)|0,n=(n=n+Math.imul(A,ee)|0)+Math.imul(O,Z)|0,s=s+Math.imul(O,ee)|0,i=i+Math.imul(S,re)|0,n=(n=n+Math.imul(S,ie)|0)+Math.imul(M,re)|0,s=s+Math.imul(M,ie)|0,i=i+Math.imul(b,se)|0,n=(n=n+Math.imul(b,oe)|0)+Math.imul(_,se)|0,s=s+Math.imul(_,oe)|0,i=i+Math.imul(m,he)|0,n=(n=n+Math.imul(m,ce)|0)+Math.imul(v,he)|0,s=s+Math.imul(v,ce)|0,i=i+Math.imul(p,le)|0,n=(n=n+Math.imul(p,fe)|0)+Math.imul(g,le)|0,s=s+Math.imul(g,fe)|0;var Ie=(c+(i=i+Math.imul(l,pe)|0)|0)+((8191&(n=(n=n+Math.imul(l,ge)|0)+Math.imul(f,pe)|0))<<13)|0;c=((s=s+Math.imul(f,ge)|0)+(n>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,i=Math.imul(q,F),n=(n=Math.imul(q,V))+Math.imul(D,F)|0,s=Math.imul(D,V),i=i+Math.imul(U,W)|0,n=(n=n+Math.imul(U,G)|0)+Math.imul(k,W)|0,s=s+Math.imul(k,G)|0,i=i+Math.imul(T,Y)|0,n=(n=n+Math.imul(T,X)|0)+Math.imul(L,Y)|0,s=s+Math.imul(L,X)|0,i=i+Math.imul(P,Z)|0,n=(n=n+Math.imul(P,ee)|0)+Math.imul(N,Z)|0,s=s+Math.imul(N,ee)|0,i=i+Math.imul(A,re)|0,n=(n=n+Math.imul(A,ie)|0)+Math.imul(O,re)|0,s=s+Math.imul(O,ie)|0,i=i+Math.imul(S,se)|0,n=(n=n+Math.imul(S,oe)|0)+Math.imul(M,se)|0,s=s+Math.imul(M,oe)|0,i=i+Math.imul(b,he)|0,n=(n=n+Math.imul(b,ce)|0)+Math.imul(_,he)|0,s=s+Math.imul(_,ce)|0,i=i+Math.imul(m,le)|0,n=(n=n+Math.imul(m,fe)|0)+Math.imul(v,le)|0,s=s+Math.imul(v,fe)|0;var Ae=(c+(i=i+Math.imul(p,pe)|0)|0)+((8191&(n=(n=n+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;c=((s=s+Math.imul(g,ge)|0)+(n>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,i=Math.imul(q,W),n=(n=Math.imul(q,G))+Math.imul(D,W)|0,s=Math.imul(D,G),i=i+Math.imul(U,Y)|0,n=(n=n+Math.imul(U,X)|0)+Math.imul(k,Y)|0,s=s+Math.imul(k,X)|0,i=i+Math.imul(T,Z)|0,n=(n=n+Math.imul(T,ee)|0)+Math.imul(L,Z)|0,s=s+Math.imul(L,ee)|0,i=i+Math.imul(P,re)|0,n=(n=n+Math.imul(P,ie)|0)+Math.imul(N,re)|0,s=s+Math.imul(N,ie)|0,i=i+Math.imul(A,se)|0,n=(n=n+Math.imul(A,oe)|0)+Math.imul(O,se)|0,s=s+Math.imul(O,oe)|0,i=i+Math.imul(S,he)|0,n=(n=n+Math.imul(S,ce)|0)+Math.imul(M,he)|0,s=s+Math.imul(M,ce)|0,i=i+Math.imul(b,le)|0,n=(n=n+Math.imul(b,fe)|0)+Math.imul(_,le)|0,s=s+Math.imul(_,fe)|0;var Oe=(c+(i=i+Math.imul(m,pe)|0)|0)+((8191&(n=(n=n+Math.imul(m,ge)|0)+Math.imul(v,pe)|0))<<13)|0;c=((s=s+Math.imul(v,ge)|0)+(n>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,i=Math.imul(q,Y),n=(n=Math.imul(q,X))+Math.imul(D,Y)|0,s=Math.imul(D,X),i=i+Math.imul(U,Z)|0,n=(n=n+Math.imul(U,ee)|0)+Math.imul(k,Z)|0,s=s+Math.imul(k,ee)|0,i=i+Math.imul(T,re)|0,n=(n=n+Math.imul(T,ie)|0)+Math.imul(L,re)|0,s=s+Math.imul(L,ie)|0,i=i+Math.imul(P,se)|0,n=(n=n+Math.imul(P,oe)|0)+Math.imul(N,se)|0,s=s+Math.imul(N,oe)|0,i=i+Math.imul(A,he)|0,n=(n=n+Math.imul(A,ce)|0)+Math.imul(O,he)|0,s=s+Math.imul(O,ce)|0,i=i+Math.imul(S,le)|0,n=(n=n+Math.imul(S,fe)|0)+Math.imul(M,le)|0,s=s+Math.imul(M,fe)|0;var xe=(c+(i=i+Math.imul(b,pe)|0)|0)+((8191&(n=(n=n+Math.imul(b,ge)|0)+Math.imul(_,pe)|0))<<13)|0;c=((s=s+Math.imul(_,ge)|0)+(n>>>13)|0)+(xe>>>26)|0,xe&=67108863,i=Math.imul(q,Z),n=(n=Math.imul(q,ee))+Math.imul(D,Z)|0,s=Math.imul(D,ee),i=i+Math.imul(U,re)|0,n=(n=n+Math.imul(U,ie)|0)+Math.imul(k,re)|0,s=s+Math.imul(k,ie)|0,i=i+Math.imul(T,se)|0,n=(n=n+Math.imul(T,oe)|0)+Math.imul(L,se)|0,s=s+Math.imul(L,oe)|0,i=i+Math.imul(P,he)|0,n=(n=n+Math.imul(P,ce)|0)+Math.imul(N,he)|0,s=s+Math.imul(N,ce)|0,i=i+Math.imul(A,le)|0,n=(n=n+Math.imul(A,fe)|0)+Math.imul(O,le)|0,s=s+Math.imul(O,fe)|0;var Pe=(c+(i=i+Math.imul(S,pe)|0)|0)+((8191&(n=(n=n+Math.imul(S,ge)|0)+Math.imul(M,pe)|0))<<13)|0;c=((s=s+Math.imul(M,ge)|0)+(n>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,i=Math.imul(q,re),n=(n=Math.imul(q,ie))+Math.imul(D,re)|0,s=Math.imul(D,ie),i=i+Math.imul(U,se)|0,n=(n=n+Math.imul(U,oe)|0)+Math.imul(k,se)|0,s=s+Math.imul(k,oe)|0,i=i+Math.imul(T,he)|0,n=(n=n+Math.imul(T,ce)|0)+Math.imul(L,he)|0,s=s+Math.imul(L,ce)|0,i=i+Math.imul(P,le)|0,n=(n=n+Math.imul(P,fe)|0)+Math.imul(N,le)|0,s=s+Math.imul(N,fe)|0;var Ne=(c+(i=i+Math.imul(A,pe)|0)|0)+((8191&(n=(n=n+Math.imul(A,ge)|0)+Math.imul(O,pe)|0))<<13)|0;c=((s=s+Math.imul(O,ge)|0)+(n>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,i=Math.imul(q,se),n=(n=Math.imul(q,oe))+Math.imul(D,se)|0,s=Math.imul(D,oe),i=i+Math.imul(U,he)|0,n=(n=n+Math.imul(U,ce)|0)+Math.imul(k,he)|0,s=s+Math.imul(k,ce)|0,i=i+Math.imul(T,le)|0,n=(n=n+Math.imul(T,fe)|0)+Math.imul(L,le)|0,s=s+Math.imul(L,fe)|0;var Re=(c+(i=i+Math.imul(P,pe)|0)|0)+((8191&(n=(n=n+Math.imul(P,ge)|0)+Math.imul(N,pe)|0))<<13)|0;c=((s=s+Math.imul(N,ge)|0)+(n>>>13)|0)+(Re>>>26)|0,Re&=67108863,i=Math.imul(q,he),n=(n=Math.imul(q,ce))+Math.imul(D,he)|0,s=Math.imul(D,ce),i=i+Math.imul(U,le)|0,n=(n=n+Math.imul(U,fe)|0)+Math.imul(k,le)|0,s=s+Math.imul(k,fe)|0;var Te=(c+(i=i+Math.imul(T,pe)|0)|0)+((8191&(n=(n=n+Math.imul(T,ge)|0)+Math.imul(L,pe)|0))<<13)|0;c=((s=s+Math.imul(L,ge)|0)+(n>>>13)|0)+(Te>>>26)|0,Te&=67108863,i=Math.imul(q,le),n=(n=Math.imul(q,fe))+Math.imul(D,le)|0,s=Math.imul(D,fe);var Le=(c+(i=i+Math.imul(U,pe)|0)|0)+((8191&(n=(n=n+Math.imul(U,ge)|0)+Math.imul(k,pe)|0))<<13)|0;c=((s=s+Math.imul(k,ge)|0)+(n>>>13)|0)+(Le>>>26)|0,Le&=67108863;var Ce=(c+(i=Math.imul(q,pe))|0)+((8191&(n=(n=Math.imul(q,ge))+Math.imul(D,pe)|0))<<13)|0;return c=((s=Math.imul(D,ge))+(n>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,h[0]=ye,h[1]=me,h[2]=ve,h[3]=we,h[4]=be,h[5]=_e,h[6]=Ee,h[7]=Se,h[8]=Me,h[9]=Ie,h[10]=Ae,h[11]=Oe,h[12]=xe,h[13]=Pe,h[14]=Ne,h[15]=Re,h[16]=Te,h[17]=Le,h[18]=Ce,0!==c&&(h[19]=c,r.length++),r};function m(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var i=0,n=0,s=0;s>>26)|0)>>>26,o&=67108863}r.words[s]=a,i=o,o=n}return 0!==i?r.words[s]=i:r.length--,r._strip()}function v(e,t,r){return m(e,t,r)}function w(e,t){this.x=e,this.y=t}Math.imul||(y=g),s.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?y(this,e,t):r<63?g(this,e,t):r<1024?m(this,e,t):v(this,e,t)},w.prototype.makeRBT=function(e){for(var t=new Array(e),r=s.prototype._countBits(e)-1,i=0;i>=1;return i},w.prototype.permute=function(e,t,r,i,n,s){for(var o=0;o>>=1)n++;return 1<>>=13,r[2*o+1]=8191&s,s>>>=13;for(o=2*t;o>=26,r+=s/67108864|0,r+=o>>>26,this.words[n]=67108863&o}return 0!==r&&(this.words[n]=r,this.length++),t?this.ineg():this},s.prototype.muln=function(e){return this.clone().imuln(e)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>n&1}return t}(e);if(0===t.length)return new s(1);for(var r=this,i=0;i=0);var t,r=e%26,n=(e-r)/26,s=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(t=0;t>>26-r}o&&(this.words[t]=o,this.length++)}if(0!==n){for(t=this.length-1;t>=0;t--)this.words[t+n]=this.words[t];for(t=0;t=0),n=t?(t-t%26)/26:0;var s=e%26,o=Math.min((e-s)/26,this.length),a=67108863^67108863>>>s<o)for(this.length-=o,c=0;c=0&&(0!==u||c>=n);c--){var l=0|this.words[c];this.words[c]=u<<26-s|l>>>s,u=l&a}return h&&0!==u&&(h.words[h.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(e,t,r){return i(0===this.negative),this.iushrn(e,t,r)},s.prototype.shln=function(e){return this.clone().ishln(e)},s.prototype.ushln=function(e){return this.clone().iushln(e)},s.prototype.shrn=function(e){return this.clone().ishrn(e)},s.prototype.ushrn=function(e){return this.clone().iushrn(e)},s.prototype.testn=function(e){i("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,n=1<=0);var t=e%26,r=(e-t)/26;if(i(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var n=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},s.prototype.isubn=function(e){if(i("number"==typeof e),i(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(h/67108864|0),this.words[n+r]=67108863&s}for(;n>26,this.words[n+r]=67108863&s;if(0===a)return this._strip();for(i(-1===a),a=0,n=0;n>26,this.words[n]=67108863&s;return this.negative=1,this._strip()},s.prototype._wordDiv=function(e,t){var r=(this.length,e.length),i=this.clone(),n=e,o=0|n.words[n.length-1];0!=(r=26-this._countBits(o))&&(n=n.ushln(r),i.iushln(r),o=0|n.words[n.length-1]);var a,h=i.length-n.length;if("mod"!==t){(a=new s(null)).length=h+1,a.words=new Array(a.length);for(var c=0;c=0;l--){var f=67108864*(0|i.words[n.length+l])+(0|i.words[n.length+l-1]);for(f=Math.min(f/o|0,67108863),i._ishlnsubmul(n,f,l);0!==i.negative;)f--,i.negative=0,i._ishlnsubmul(n,1,l),i.isZero()||(i.negative^=1);a&&(a.words[l]=f)}return a&&a._strip(),i._strip(),"div"!==t&&0!==r&&i.iushrn(r),{div:a||null,mod:i}},s.prototype.divmod=function(e,t,r){return i(!e.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(n=a.div.neg()),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.iadd(e)),{div:n,mod:o}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(n=a.div.neg()),{div:n,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.isub(e)),{div:a.div,mod:o}):e.length>this.length||this.cmp(e)<0?{div:new s(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new s(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new s(this.modrn(e.words[0]))}:this._wordDiv(e,t);var n,o,a},s.prototype.div=function(e){return this.divmod(e,"div",!1).div},s.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},s.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},s.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,i=e.ushrn(1),n=e.andln(1),s=r.cmp(i);return s<0||1===n&&0===s?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},s.prototype.modrn=function(e){var t=e<0;t&&(e=-e),i(e<=67108863);for(var r=(1<<26)%e,n=0,s=this.length-1;s>=0;s--)n=(r*n+(0|this.words[s]))%e;return t?-n:n},s.prototype.modn=function(e){return this.modrn(e)},s.prototype.idivn=function(e){var t=e<0;t&&(e=-e),i(e<=67108863);for(var r=0,n=this.length-1;n>=0;n--){var s=(0|this.words[n])+67108864*r;this.words[n]=s/e|0,r=s%e}return this._strip(),t?this.ineg():this},s.prototype.divn=function(e){return this.clone().idivn(e)},s.prototype.egcd=function(e){i(0===e.negative),i(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var n=new s(1),o=new s(0),a=new s(0),h=new s(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var u=r.clone(),l=t.clone();!t.isZero();){for(var f=0,d=1;0==(t.words[0]&d)&&f<26;++f,d<<=1);if(f>0)for(t.iushrn(f);f-- >0;)(n.isOdd()||o.isOdd())&&(n.iadd(u),o.isub(l)),n.iushrn(1),o.iushrn(1);for(var p=0,g=1;0==(r.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||h.isOdd())&&(a.iadd(u),h.isub(l)),a.iushrn(1),h.iushrn(1);t.cmp(r)>=0?(t.isub(r),n.isub(a),o.isub(h)):(r.isub(t),a.isub(n),h.isub(o))}return{a,b:h,gcd:r.iushln(c)}},s.prototype._invmp=function(e){i(0===e.negative),i(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var n,o=new s(1),a=new s(0),h=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,u=1;0==(t.words[0]&u)&&c<26;++c,u<<=1);if(c>0)for(t.iushrn(c);c-- >0;)o.isOdd()&&o.iadd(h),o.iushrn(1);for(var l=0,f=1;0==(r.words[0]&f)&&l<26;++l,f<<=1);if(l>0)for(r.iushrn(l);l-- >0;)a.isOdd()&&a.iadd(h),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),o.isub(a)):(r.isub(t),a.isub(o))}return(n=0===t.cmpn(1)?o:a).cmpn(0)<0&&n.iadd(e),n},s.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var i=0;t.isEven()&&r.isEven();i++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var n=t.cmp(r);if(n<0){var s=t;t=r,r=s}else if(0===n||0===r.cmpn(1))break;t.isub(r)}return r.iushln(i)},s.prototype.invm=function(e){return this.egcd(e).a.umod(e)},s.prototype.isEven=function(){return 0==(1&this.words[0])},s.prototype.isOdd=function(){return 1==(1&this.words[0])},s.prototype.andln=function(e){return this.words[0]&e},s.prototype.bincn=function(e){i("number"==typeof e);var t=e%26,r=(e-t)/26,n=1<>>26,a&=67108863,this.words[o]=a}return 0!==s&&(this.words[o]=s,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),i(e<=67108863,"Number is too big");var n=0|this.words[0];t=n===e?0:ne.length)return 1;if(this.length=0;r--){var i=0|this.words[r],n=0|e.words[r];if(i!==n){in&&(t=1);break}}return t},s.prototype.gtn=function(e){return 1===this.cmpn(e)},s.prototype.gt=function(e){return 1===this.cmp(e)},s.prototype.gten=function(e){return this.cmpn(e)>=0},s.prototype.gte=function(e){return this.cmp(e)>=0},s.prototype.ltn=function(e){return-1===this.cmpn(e)},s.prototype.lt=function(e){return-1===this.cmp(e)},s.prototype.lten=function(e){return this.cmpn(e)<=0},s.prototype.lte=function(e){return this.cmp(e)<=0},s.prototype.eqn=function(e){return 0===this.cmpn(e)},s.prototype.eq=function(e){return 0===this.cmp(e)},s.red=function(e){return new A(e)},s.prototype.toRed=function(e){return i(!this.red,"Already a number in reduction context"),i(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},s.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(e){return this.red=e,this},s.prototype.forceRed=function(e){return i(!this.red,"Already a number in reduction context"),this._forceRed(e)},s.prototype.redAdd=function(e){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},s.prototype.redIAdd=function(e){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},s.prototype.redSub=function(e){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},s.prototype.redISub=function(e){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},s.prototype.redShl=function(e){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},s.prototype.redMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},s.prototype.redIMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},s.prototype.redSqr=function(){return i(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return i(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return i(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return i(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return i(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(e){return i(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var b={k256:null,p224:null,p192:null,p25519:null};function _(e,t){this.name=e,this.p=new s(t,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function E(){_.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function S(){_.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function M(){_.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function I(){_.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=s._prime(e);this.m=t.p,this.prime=t}else i(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function O(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}_.prototype._tmp=function(){var e=new s(null);return e.words=new Array(Math.ceil(this.n/13)),e},_.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var i=t0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},_.prototype.split=function(e,t){e.iushrn(this.n,0,t)},_.prototype.imulK=function(e){return e.imul(this.k)},n(E,_),E.prototype.split=function(e,t){for(var r=4194303,i=Math.min(e.length,9),n=0;n>>22,s=o}s>>>=22,e.words[n-10]=s,0===s&&e.length>10?e.length-=10:e.length-=9},E.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=n,t=i}return 0!==t&&(e.words[e.length++]=t),e},s._prime=function(e){if(b[e])return b[e];var t;if("k256"===e)t=new E;else if("p224"===e)t=new S;else if("p192"===e)t=new M;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new I}return b[e]=t,t},A.prototype._verify1=function(e){i(0===e.negative,"red works only with positives"),i(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){i(0==(e.negative|t.negative),"red works only with positives"),i(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(u(e,e.umod(this.m)._forceRed(this)),e)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(i(t%2==1),3===t){var r=this.m.add(new s(1)).iushrn(2);return this.pow(e,r)}for(var n=this.m.subn(1),o=0;!n.isZero()&&0===n.andln(1);)o++,n.iushrn(1);i(!n.isZero());var a=new s(1).toRed(this),h=a.redNeg(),c=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new s(2*u*u).toRed(this);0!==this.pow(u,c).cmp(h);)u.redIAdd(h);for(var l=this.pow(u,n),f=this.pow(e,n.addn(1).iushrn(1)),d=this.pow(e,n),p=o;0!==d.cmp(a);){for(var g=d,y=0;0!==g.cmp(a);y++)g=g.redSqr();i(y=0;i--){for(var c=t.words[i],u=h-1;u>=0;u--){var l=c>>u&1;n!==r[0]&&(n=this.sqr(n)),0!==l||0!==o?(o<<=1,o|=l,(4==++a||0===i&&0===u)&&(n=this.mul(n,r[o]),a=0,o=0)):a=0}h=26}return n},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},s.mont=function(e){return new O(e)},n(O,A),O.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},O.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},O.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):n.cmpn(0)<0&&(s=n.iadd(this.m)),s._forceRed(this)},O.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new s(0)._forceRed(this);var r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),o=n;return n.cmp(this.m)>=0?o=n.isub(this.m):n.cmpn(0)<0&&(o=n.iadd(this.m)),o._forceRed(this)},O.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e=r.nmd(e),this)},4020:e=>{var t="%[a-f0-9]{2}",r=new RegExp("("+t+")|([^%]+?)","gi"),i=new RegExp("("+t+")+","gi");function n(e,t){try{return[decodeURIComponent(e.join(""))]}catch(e){}if(1===e.length)return e;t=t||1;var r=e.slice(0,t),i=e.slice(t);return Array.prototype.concat.call([],n(r),n(i))}function s(e){try{return decodeURIComponent(e)}catch(s){for(var t=e.match(r)||[],i=1;i{var t,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}g(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&g(e,"error",t,{once:!0})}(e,n)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,r,i){var n,s,o,c;if(a(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=h(e))>0&&o.length>n&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,c=u,console&&console.warn&&console.warn(c)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=u.bind(i);return n.listener=r,i.wrapFn=n,n}function f(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var h=s[e];if(void 0===h)return!1;if("function"==typeof h)i(h,this,t);else{var c=h.length,u=p(h,c);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},s.prototype.listeners=function(e){return f(this,e,!0)},s.prototype.rawListeners=function(e){return f(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):d.call(e,t)},s.prototype.listenerCount=d,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},2806:e=>{e.exports=function(e,t){for(var r={},i=Object.keys(e),n=Array.isArray(t),s=0;s{var i=t;i.utils=r(6436),i.common=r(5772),i.sha=r(9041),i.ripemd=r(2949),i.hmac=r(2344),i.sha1=i.sha.sha1,i.sha256=i.sha.sha256,i.sha224=i.sha.sha224,i.sha384=i.sha.sha384,i.sha512=i.sha.sha512,i.ripemd160=i.ripemd.ripemd160},5772:(e,t,r)=>{var i=r(6436),n=r(9746);function s(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}t.BlockHash=s,s.prototype.update=function(e,t){if(e=i.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=i.join32(e,0,e.length-r,this.endian);for(var n=0;n>>24&255,i[n++]=e>>>16&255,i[n++]=e>>>8&255,i[n++]=255&e}else for(i[n++]=255&e,i[n++]=e>>>8&255,i[n++]=e>>>16&255,i[n++]=e>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,s=8;s{var i=r(6436),n=r(9746);function s(e,t,r){if(!(this instanceof s))return new s(e,t,r);this.Hash=e,this.blockSize=e.blockSize/8,this.outSize=e.outSize/8,this.inner=null,this.outer=null,this._init(i.toArray(t,r))}e.exports=s,s.prototype._init=function(e){e.length>this.blockSize&&(e=(new this.Hash).update(e).digest()),n(e.length<=this.blockSize);for(var t=e.length;t{var i=r(6436),n=r(5772),s=i.rotl32,o=i.sum32,a=i.sum32_3,h=i.sum32_4,c=n.BlockHash;function u(){if(!(this instanceof u))return new u;c.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}function l(e,t,r,i){return e<=15?t^r^i:e<=31?t&r|~t&i:e<=47?(t|~r)^i:e<=63?t&i|r&~i:t^(r|~i)}function f(e){return e<=15?0:e<=31?1518500249:e<=47?1859775393:e<=63?2400959708:2840853838}function d(e){return e<=15?1352829926:e<=31?1548603684:e<=47?1836072691:e<=63?2053994217:0}i.inherits(u,c),t.ripemd160=u,u.blockSize=512,u.outSize=160,u.hmacStrength=192,u.padLength=64,u.prototype._update=function(e,t){for(var r=this.h[0],i=this.h[1],n=this.h[2],c=this.h[3],u=this.h[4],v=r,w=i,b=n,_=c,E=u,S=0;S<80;S++){var M=o(s(h(r,l(S,i,n,c),e[p[S]+t],f(S)),y[S]),u);r=u,u=c,c=s(n,10),n=i,i=M,M=o(s(h(v,l(79-S,w,b,_),e[g[S]+t],d(S)),m[S]),E),v=E,E=_,_=s(b,10),b=w,w=M}M=a(this.h[1],n,_),this.h[1]=a(this.h[2],c,E),this.h[2]=a(this.h[3],u,v),this.h[3]=a(this.h[4],r,w),this.h[4]=a(this.h[0],i,b),this.h[0]=M},u.prototype._digest=function(e){return"hex"===e?i.toHex32(this.h,"little"):i.split32(this.h,"little")};var p=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],g=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],y=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],m=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]},9041:(e,t,r)=>{t.sha1=r(4761),t.sha224=r(799),t.sha256=r(9344),t.sha384=r(772),t.sha512=r(5900)},4761:(e,t,r)=>{var i=r(6436),n=r(5772),s=r(7038),o=i.rotl32,a=i.sum32,h=i.sum32_5,c=s.ft_1,u=n.BlockHash,l=[1518500249,1859775393,2400959708,3395469782];function f(){if(!(this instanceof f))return new f;u.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}i.inherits(f,u),e.exports=f,f.blockSize=512,f.outSize=160,f.hmacStrength=80,f.padLength=64,f.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;i{var i=r(6436),n=r(9344);function s(){if(!(this instanceof s))return new s;n.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}i.inherits(s,n),e.exports=s,s.blockSize=512,s.outSize=224,s.hmacStrength=192,s.padLength=64,s.prototype._digest=function(e){return"hex"===e?i.toHex32(this.h.slice(0,7),"big"):i.split32(this.h.slice(0,7),"big")}},9344:(e,t,r)=>{var i=r(6436),n=r(5772),s=r(7038),o=r(9746),a=i.sum32,h=i.sum32_4,c=i.sum32_5,u=s.ch32,l=s.maj32,f=s.s0_256,d=s.s1_256,p=s.g0_256,g=s.g1_256,y=n.BlockHash,m=[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];function v(){if(!(this instanceof v))return new v;y.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=m,this.W=new Array(64)}i.inherits(v,y),e.exports=v,v.blockSize=512,v.outSize=256,v.hmacStrength=192,v.padLength=64,v.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;i{var i=r(6436),n=r(5900);function s(){if(!(this instanceof s))return new s;n.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}i.inherits(s,n),e.exports=s,s.blockSize=1024,s.outSize=384,s.hmacStrength=192,s.padLength=128,s.prototype._digest=function(e){return"hex"===e?i.toHex32(this.h.slice(0,12),"big"):i.split32(this.h.slice(0,12),"big")}},5900:(e,t,r)=>{var i=r(6436),n=r(5772),s=r(9746),o=i.rotr64_hi,a=i.rotr64_lo,h=i.shr64_hi,c=i.shr64_lo,u=i.sum64,l=i.sum64_hi,f=i.sum64_lo,d=i.sum64_4_hi,p=i.sum64_4_lo,g=i.sum64_5_hi,y=i.sum64_5_lo,m=n.BlockHash,v=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function w(){if(!(this instanceof w))return new w;m.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=v,this.W=new Array(160)}function b(e,t,r,i,n){var s=e&r^~e&n;return s<0&&(s+=4294967296),s}function _(e,t,r,i,n,s){var o=t&i^~t&s;return o<0&&(o+=4294967296),o}function E(e,t,r,i,n){var s=e&r^e&n^r&n;return s<0&&(s+=4294967296),s}function S(e,t,r,i,n,s){var o=t&i^t&s^i&s;return o<0&&(o+=4294967296),o}function M(e,t){var r=o(e,t,28)^o(t,e,2)^o(t,e,7);return r<0&&(r+=4294967296),r}function I(e,t){var r=a(e,t,28)^a(t,e,2)^a(t,e,7);return r<0&&(r+=4294967296),r}function A(e,t){var r=a(e,t,14)^a(e,t,18)^a(t,e,9);return r<0&&(r+=4294967296),r}function O(e,t){var r=o(e,t,1)^o(e,t,8)^h(e,t,7);return r<0&&(r+=4294967296),r}function x(e,t){var r=a(e,t,1)^a(e,t,8)^c(e,t,7);return r<0&&(r+=4294967296),r}function P(e,t){var r=a(e,t,19)^a(t,e,29)^c(e,t,6);return r<0&&(r+=4294967296),r}i.inherits(w,m),e.exports=w,w.blockSize=1024,w.outSize=512,w.hmacStrength=192,w.padLength=128,w.prototype._prepareBlock=function(e,t){for(var r=this.W,i=0;i<32;i++)r[i]=e[t+i];for(;i{var i=r(6436).rotr32;function n(e,t,r){return e&t^~e&r}function s(e,t,r){return e&t^e&r^t&r}function o(e,t,r){return e^t^r}t.ft_1=function(e,t,r,i){return 0===e?n(t,r,i):1===e||3===e?o(t,r,i):2===e?s(t,r,i):void 0},t.ch32=n,t.maj32=s,t.p32=o,t.s0_256=function(e){return i(e,2)^i(e,13)^i(e,22)},t.s1_256=function(e){return i(e,6)^i(e,11)^i(e,25)},t.g0_256=function(e){return i(e,7)^i(e,18)^e>>>3},t.g1_256=function(e){return i(e,17)^i(e,19)^e>>>10}},6436:(e,t,r)=>{var i=r(9746),n=r(5717);function s(e,t){return 55296==(64512&e.charCodeAt(t))&&!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1))}function o(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function h(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}t.inherits=n,t.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),n=0;n>6|192,r[i++]=63&o|128):s(e,n)?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++n)),r[i++]=o>>18|240,r[i++]=o>>12&63|128,r[i++]=o>>6&63|128,r[i++]=63&o|128):(r[i++]=o>>12|224,r[i++]=o>>6&63|128,r[i++]=63&o|128)}else for(n=0;n>>0}return o},t.split32=function(e,t){for(var r=new Array(4*e.length),i=0,n=0;i>>24,r[n+1]=s>>>16&255,r[n+2]=s>>>8&255,r[n+3]=255&s):(r[n+3]=s>>>24,r[n+2]=s>>>16&255,r[n+1]=s>>>8&255,r[n]=255&s)}return r},t.rotr32=function(e,t){return e>>>t|e<<32-t},t.rotl32=function(e,t){return e<>>32-t},t.sum32=function(e,t){return e+t>>>0},t.sum32_3=function(e,t,r){return e+t+r>>>0},t.sum32_4=function(e,t,r,i){return e+t+r+i>>>0},t.sum32_5=function(e,t,r,i,n){return e+t+r+i+n>>>0},t.sum64=function(e,t,r,i){var n=e[t],s=i+e[t+1]>>>0,o=(s>>0,e[t+1]=s},t.sum64_hi=function(e,t,r,i){return(t+i>>>0>>0},t.sum64_lo=function(e,t,r,i){return t+i>>>0},t.sum64_4_hi=function(e,t,r,i,n,s,o,a){var h=0,c=t;return h+=(c=c+i>>>0)>>0)>>0)>>0},t.sum64_4_lo=function(e,t,r,i,n,s,o,a){return t+i+s+a>>>0},t.sum64_5_hi=function(e,t,r,i,n,s,o,a,h,c){var u=0,l=t;return u+=(l=l+i>>>0)>>0)>>0)>>0)>>0},t.sum64_5_lo=function(e,t,r,i,n,s,o,a,h,c){return t+i+s+a+c>>>0},t.rotr64_hi=function(e,t,r){return(t<<32-r|e>>>r)>>>0},t.rotr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0},t.shr64_hi=function(e,t,r){return e>>>r},t.shr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0}},5717:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},204:(e,t,r)=>{e.exports=self.fetch||(self.fetch=r(5869).default||r(5869))},1094:(e,t,r)=>{var i;!function(){var n="input is invalid type",s="object"==typeof window,o=s?window:{};o.JS_SHA3_NO_WINDOW&&(s=!1);var a=!s&&"object"==typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?o=r.g:a&&(o=self);var h=!o.JS_SHA3_NO_COMMON_JS&&e.exports,c=r.amdO,u=!o.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,l="0123456789abcdef".split(""),f=[4,1024,262144,67108864],d=[0,8,16,24],p=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],y=[128,256],m=["hex","buffer","arrayBuffer","array","digest"],v={128:168,256:136};!o.JS_SHA3_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!u||!o.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});for(var w=function(e,t,r){return function(i){return new C(e,t,e).update(i)[r]()}},b=function(e,t,r){return function(i,n){return new C(e,t,n).update(i)[r]()}},_=function(e,t,r){return function(t,i,n,s){return A["cshake"+e].update(t,i,n,s)[r]()}},E=function(e,t,r){return function(t,i,n,s){return A["kmac"+e].update(t,i,n,s)[r]()}},S=function(e,t,r,i){for(var n=0;n>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var i=0;i<50;++i)this.s[i]=0}function U(e,t,r){C.call(this,e,t,r)}C.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(n);if(null===e)throw new Error(n);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||u&&ArrayBuffer.isView(e)))throw new Error(n);t=!0}for(var i,s,o=this.blocks,a=this.byteCount,h=e.length,c=this.blockCount,l=0,f=this.s;l>2]|=e[l]<>2]|=s<>2]|=(192|s>>6)<>2]|=(128|63&s)<=57344?(o[i>>2]|=(224|s>>12)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<>2]|=(240|s>>18)<>2]|=(128|s>>12&63)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<=a){for(this.start=i-a,this.block=o[c],i=0;i>=8);r>0;)n.unshift(r),r=255&(e>>=8),++i;return t?n.push(i):n.unshift(i),this.update(n),n.length},C.prototype.encodeString=function(e){var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(n);if(null===e)throw new Error(n);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||u&&ArrayBuffer.isView(e)))throw new Error(n);t=!0}var i=0,s=e.length;if(t)i=s;else for(var o=0;o=57344?i+=3:(a=65536+((1023&a)<<10|1023&e.charCodeAt(++o)),i+=4)}return i+=this.encode(8*i),this.update(e),i},C.prototype.bytepad=function(e,t){for(var r=this.encode(t),i=0;i>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+l[15&e]+l[e>>12&15]+l[e>>8&15]+l[e>>20&15]+l[e>>16&15]+l[e>>28&15]+l[e>>24&15];o%t==0&&(k(r),s=0)}return n&&(e=r[s],a+=l[e>>4&15]+l[15&e],n>1&&(a+=l[e>>12&15]+l[e>>8&15]),n>2&&(a+=l[e>>20&15]+l[e>>16&15])),a},C.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,i=this.outputBlocks,n=this.extraBytes,s=0,o=0,a=this.outputBits>>3;e=n?new ArrayBuffer(i+1<<2):new ArrayBuffer(a);for(var h=new Uint32Array(e);o>8&255,h[e+2]=t>>16&255,h[e+3]=t>>24&255;a%r==0&&k(i)}return s&&(e=a<<2,t=i[o],h[e]=255&t,s>1&&(h[e+1]=t>>8&255),s>2&&(h[e+2]=t>>16&255)),h},U.prototype=new C,U.prototype.finalize=function(){return this.encode(this.outputBits,!0),C.prototype.finalize.call(this)};var k=function(e){var t,r,i,n,s,o,a,h,c,u,l,f,d,g,y,m,v,w,b,_,E,S,M,I,A,O,x,P,N,R,T,L,C,U,k,j,q,D,z,$,B,K,F,V,H,W,G,J,Y,X,Q,Z,ee,te,re,ie,ne,se,oe,ae,he,ce,ue;for(i=0;i<48;i+=2)n=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],h=e[4]^e[14]^e[24]^e[34]^e[44],c=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(f=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(d=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=n^(h<<1|c>>>31),r=s^(c<<1|h>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(u<<1|l>>>31),r=a^(l<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=h^(f<<1|d>>>31),r=c^(d<<1|f>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(n<<1|s>>>31),r=l^(s<<1|n>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,G=e[10]<<4|e[11]>>>28,P=e[20]<<3|e[21]>>>29,N=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,he=e[30]<<9|e[31]>>>23,K=e[40]<<18|e[41]>>>14,F=e[41]<<18|e[40]>>>14,U=e[2]<<1|e[3]>>>31,k=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,J=e[22]<<10|e[23]>>>22,Y=e[23]<<10|e[22]>>>22,R=e[33]<<13|e[32]>>>19,T=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,j=e[14]<<6|e[15]>>>26,q=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,b=e[24]<<11|e[25]>>>21,X=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,L=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,I=e[6]<<28|e[7]>>>4,A=e[7]<<28|e[6]>>>4,ie=e[17]<<23|e[16]>>>9,ne=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,z=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,E=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,H=e[9]<<27|e[8]>>>5,O=e[18]<<20|e[19]>>>12,x=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,$=e[38]<<8|e[39]>>>24,B=e[39]<<8|e[38]>>>24,S=e[48]<<14|e[49]>>>18,M=e[49]<<14|e[48]>>>18,e[0]=g^~m&w,e[1]=y^~v&b,e[10]=I^~O&P,e[11]=A^~x&N,e[20]=U^~j&D,e[21]=k^~q&z,e[30]=V^~W&J,e[31]=H^~G&Y,e[40]=te^~ie&se,e[41]=re^~ne&oe,e[2]=m^~w&_,e[3]=v^~b&E,e[12]=O^~P&R,e[13]=x^~N&T,e[22]=j^~D&$,e[23]=q^~z&B,e[32]=W^~J&X,e[33]=G^~Y&Q,e[42]=ie^~se&ae,e[43]=ne^~oe&he,e[4]=w^~_&S,e[5]=b^~E&M,e[14]=P^~R&L,e[15]=N^~T&C,e[24]=D^~$&K,e[25]=z^~B&F,e[34]=J^~X&Z,e[35]=Y^~Q&ee,e[44]=se^~ae&ce,e[45]=oe^~he&ue,e[6]=_^~S&g,e[7]=E^~M&y,e[16]=R^~L&I,e[17]=T^~C&A,e[26]=$^~K&U,e[27]=B^~F&k,e[36]=X^~Z&V,e[37]=Q^~ee&H,e[46]=ae^~ce&te,e[47]=he^~ue&re,e[8]=S^~g&m,e[9]=M^~y&v,e[18]=L^~I&O,e[19]=C^~A&x,e[28]=K^~U&j,e[29]=F^~k&q,e[38]=Z^~V&W,e[39]=ee^~H&G,e[48]=ce^~te&ie,e[49]=ue^~re&ne,e[0]^=p[i],e[1]^=p[i+1]};if(h)e.exports=A;else{for(x=0;x{e=r.nmd(e);var i="__lodash_hash_undefined__",n=1,s=2,o=9007199254740991,a="[object Arguments]",h="[object Array]",c="[object AsyncFunction]",u="[object Boolean]",l="[object Date]",f="[object Error]",d="[object Function]",p="[object GeneratorFunction]",g="[object Map]",y="[object Number]",m="[object Null]",v="[object Object]",w="[object Promise]",b="[object Proxy]",_="[object RegExp]",E="[object Set]",S="[object String]",M="[object Undefined]",I="[object WeakMap]",A="[object ArrayBuffer]",O="[object DataView]",x=/^\[object .+?Constructor\]$/,P=/^(?:0|[1-9]\d*)$/,N={};N["[object Float32Array]"]=N["[object Float64Array]"]=N["[object Int8Array]"]=N["[object Int16Array]"]=N["[object Int32Array]"]=N["[object Uint8Array]"]=N["[object Uint8ClampedArray]"]=N["[object Uint16Array]"]=N["[object Uint32Array]"]=!0,N[a]=N[h]=N[A]=N[u]=N[O]=N[l]=N[f]=N[d]=N[g]=N[y]=N[v]=N[_]=N[E]=N[S]=N[I]=!1;var R="object"==typeof r.g&&r.g&&r.g.Object===Object&&r.g,T="object"==typeof self&&self&&self.Object===Object&&self,L=R||T||Function("return this")(),C=t&&!t.nodeType&&t,U=C&&e&&!e.nodeType&&e,k=U&&U.exports===C,j=k&&R.process,q=function(){try{return j&&j.binding&&j.binding("util")}catch(e){}}(),D=q&&q.isTypedArray;function z(e,t){for(var r=-1,i=null==e?0:e.length;++rc))return!1;var l=a.get(e);if(l&&a.get(t))return l==t;var f=-1,d=!0,p=r&s?new Ae:void 0;for(a.set(e,t),a.set(t,e);++f-1},Me.prototype.set=function(e,t){var r=this.__data__,i=xe(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this},Ie.prototype.clear=function(){this.size=0,this.__data__={hash:new Se,map:new(le||Me),string:new Se}},Ie.prototype.delete=function(e){var t=Ce(this,e).delete(e);return this.size-=t?1:0,t},Ie.prototype.get=function(e){return Ce(this,e).get(e)},Ie.prototype.has=function(e){return Ce(this,e).has(e)},Ie.prototype.set=function(e,t){var r=Ce(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this},Ae.prototype.add=Ae.prototype.push=function(e){return this.__data__.set(e,i),this},Ae.prototype.has=function(e){return this.__data__.has(e)},Oe.prototype.clear=function(){this.__data__=new Me,this.size=0},Oe.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Oe.prototype.get=function(e){return this.__data__.get(e)},Oe.prototype.has=function(e){return this.__data__.has(e)},Oe.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Me){var i=r.__data__;if(!le||i.length<199)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new Ie(i)}return r.set(e,t),this.size=r.size,this};var ke=ae?function(e){return null==e?[]:(e=Object(e),function(t,r){for(var i=-1,n=null==t?0:t.length,s=0,o=[];++i-1&&e%1==0&&e-1&&e%1==0&&e<=o}function He(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function We(e){return null!=e&&"object"==typeof e}var Ge=D?function(e){return function(t){return e(t)}}(D):function(e){return We(e)&&Ve(e.length)&&!!N[Pe(e)]};function Je(e){return null!=(t=e)&&Ve(t.length)&&!Fe(t)?function(e,t){var r=Be(e),i=!r&&$e(e),n=!r&&!i&&Ke(e),s=!r&&!i&&!n&&Ge(e),o=r||i||n||s,a=o?function(e,t){for(var r=-1,i=Array(e);++r{function t(e,t){if(!e)throw new Error(t||"Assertion failed")}e.exports=t,t.equal=function(e,t,r){if(e!=t)throw new Error(r||"Assertion failed: "+e+" != "+t)}},7563:(e,t,r)=>{const i=r(610),n=r(4020),s=r(500),o=r(2806),a=Symbol("encodeFragmentIdentifier");function h(e){if("string"!=typeof e||1!==e.length)throw new TypeError("arrayFormatSeparator must be single character string")}function c(e,t){return t.encode?t.strict?i(e):encodeURIComponent(e):e}function u(e,t){return t.decode?n(e):e}function l(e){return Array.isArray(e)?e.sort():"object"==typeof e?l(Object.keys(e)).sort(((e,t)=>Number(e)-Number(t))).map((t=>e[t])):e}function f(e){const t=e.indexOf("#");return-1!==t&&(e=e.slice(0,t)),e}function d(e){const t=(e=f(e)).indexOf("?");return-1===t?"":e.slice(t+1)}function p(e,t){return t.parseNumbers&&!Number.isNaN(Number(e))&&"string"==typeof e&&""!==e.trim()?e=Number(e):!t.parseBooleans||null===e||"true"!==e.toLowerCase()&&"false"!==e.toLowerCase()||(e="true"===e.toLowerCase()),e}function g(e,t){h((t=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},t)).arrayFormatSeparator);const r=function(e){let t;switch(e.arrayFormat){case"index":return(e,r,i)=>{t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),t?(void 0===i[e]&&(i[e]={}),i[e][t[1]]=r):i[e]=r};case"bracket":return(e,r,i)=>{t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),t?void 0!==i[e]?i[e]=[].concat(i[e],r):i[e]=[r]:i[e]=r};case"colon-list-separator":return(e,r,i)=>{t=/(:list)$/.exec(e),e=e.replace(/:list$/,""),t?void 0!==i[e]?i[e]=[].concat(i[e],r):i[e]=[r]:i[e]=r};case"comma":case"separator":return(t,r,i)=>{const n="string"==typeof r&&r.includes(e.arrayFormatSeparator),s="string"==typeof r&&!n&&u(r,e).includes(e.arrayFormatSeparator);r=s?u(r,e):r;const o=n||s?r.split(e.arrayFormatSeparator).map((t=>u(t,e))):null===r?r:u(r,e);i[t]=o};case"bracket-separator":return(t,r,i)=>{const n=/(\[\])$/.test(t);if(t=t.replace(/\[\]$/,""),!n)return void(i[t]=r?u(r,e):r);const s=null===r?[]:r.split(e.arrayFormatSeparator).map((t=>u(t,e)));void 0!==i[t]?i[t]=[].concat(i[t],s):i[t]=s};default:return(e,t,r)=>{void 0!==r[e]?r[e]=[].concat(r[e],t):r[e]=t}}}(t),i=Object.create(null);if("string"!=typeof e)return i;if(!(e=e.trim().replace(/^[?#&]/,"")))return i;for(const n of e.split("&")){if(""===n)continue;let[e,o]=s(t.decode?n.replace(/\+/g," "):n,"=");o=void 0===o?null:["comma","separator","bracket-separator"].includes(t.arrayFormat)?o:u(o,t),r(u(e,t),o,i)}for(const e of Object.keys(i)){const r=i[e];if("object"==typeof r&&null!==r)for(const e of Object.keys(r))r[e]=p(r[e],t);else i[e]=p(r,t)}return!1===t.sort?i:(!0===t.sort?Object.keys(i).sort():Object.keys(i).sort(t.sort)).reduce(((e,t)=>{const r=i[t];return Boolean(r)&&"object"==typeof r&&!Array.isArray(r)?e[t]=l(r):e[t]=r,e}),Object.create(null))}t.extract=d,t.parse=g,t.stringify=(e,t)=>{if(!e)return"";h((t=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},t)).arrayFormatSeparator);const r=r=>t.skipNull&&null==e[r]||t.skipEmptyString&&""===e[r],i=function(e){switch(e.arrayFormat){case"index":return t=>(r,i)=>{const n=r.length;return void 0===i||e.skipNull&&null===i||e.skipEmptyString&&""===i?r:null===i?[...r,[c(t,e),"[",n,"]"].join("")]:[...r,[c(t,e),"[",c(n,e),"]=",c(i,e)].join("")]};case"bracket":return t=>(r,i)=>void 0===i||e.skipNull&&null===i||e.skipEmptyString&&""===i?r:null===i?[...r,[c(t,e),"[]"].join("")]:[...r,[c(t,e),"[]=",c(i,e)].join("")];case"colon-list-separator":return t=>(r,i)=>void 0===i||e.skipNull&&null===i||e.skipEmptyString&&""===i?r:null===i?[...r,[c(t,e),":list="].join("")]:[...r,[c(t,e),":list=",c(i,e)].join("")];case"comma":case"separator":case"bracket-separator":{const t="bracket-separator"===e.arrayFormat?"[]=":"=";return r=>(i,n)=>void 0===n||e.skipNull&&null===n||e.skipEmptyString&&""===n?i:(n=null===n?"":n,0===i.length?[[c(r,e),t,c(n,e)].join("")]:[[i,c(n,e)].join(e.arrayFormatSeparator)])}default:return t=>(r,i)=>void 0===i||e.skipNull&&null===i||e.skipEmptyString&&""===i?r:null===i?[...r,c(t,e)]:[...r,[c(t,e),"=",c(i,e)].join("")]}}(t),n={};for(const t of Object.keys(e))r(t)||(n[t]=e[t]);const s=Object.keys(n);return!1!==t.sort&&s.sort(t.sort),s.map((r=>{const n=e[r];return void 0===n?"":null===n?c(r,t):Array.isArray(n)?0===n.length&&"bracket-separator"===t.arrayFormat?c(r,t)+"[]":n.reduce(i(r),[]).join("&"):c(r,t)+"="+c(n,t)})).filter((e=>e.length>0)).join("&")},t.parseUrl=(e,t)=>{t=Object.assign({decode:!0},t);const[r,i]=s(e,"#");return Object.assign({url:r.split("?")[0]||"",query:g(d(e),t)},t&&t.parseFragmentIdentifier&&i?{fragmentIdentifier:u(i,t)}:{})},t.stringifyUrl=(e,r)=>{r=Object.assign({encode:!0,strict:!0,[a]:!0},r);const i=f(e.url).split("?")[0]||"",n=t.extract(e.url),s=t.parse(n,{sort:!1}),o=Object.assign(s,e.query);let h=t.stringify(o,r);h&&(h=`?${h}`);let u=function(e){let t="";const r=e.indexOf("#");return-1!==r&&(t=e.slice(r)),t}(e.url);return e.fragmentIdentifier&&(u=`#${r[a]?c(e.fragmentIdentifier,r):e.fragmentIdentifier}`),`${i}${h}${u}`},t.pick=(e,r,i)=>{i=Object.assign({parseFragmentIdentifier:!0,[a]:!1},i);const{url:n,query:s,fragmentIdentifier:h}=t.parseUrl(e,i);return t.stringifyUrl({url:n,query:o(s,r),fragmentIdentifier:h},i)},t.exclude=(e,r,i)=>{const n=Array.isArray(r)?e=>!r.includes(e):(e,t)=>!r(e,t);return t.pick(e,n,i)}},5346:e=>{function t(e){try{return JSON.stringify(e)}catch(e){return'"[Circular]"'}}e.exports=function(e,r,i){var n=i&&i.stringify||t;if("object"==typeof e&&null!==e){var s=r.length+1;if(1===s)return e;var o=new Array(s);o[0]=n(e);for(var a=1;a-1?l:0,e.charCodeAt(d+1)){case 100:case 102:if(u>=h)break;if(null==r[u])break;l=h)break;if(null==r[u])break;l=h)break;if(void 0===r[u])break;l",l=d+2,d++;break}c+=n(r[u]),l=d+2,d++;break;case 115:if(u>=h)break;l{Object.defineProperty(t,"__esModule",{value:!0}),t.safeJsonParse=function(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return JSON.parse(e)}catch(t){return e}},t.safeJsonStringify=function(e){return"string"==typeof e?e:JSON.stringify(e,((e,t)=>void 0===t?null:t))}},500:e=>{e.exports=(e,t)=>{if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Expected the arguments to be of type `string`");if(""===t)return[e];const r=e.indexOf(t);return-1===r?[e]:[e.slice(0,r),e.slice(r+t.length)]}},610:e=>{e.exports=e=>encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))},655:(e,t,r)=>{r.r(t),r.d(t,{__assign:()=>s,__asyncDelegator:()=>b,__asyncGenerator:()=>w,__asyncValues:()=>_,__await:()=>v,__awaiter:()=>u,__classPrivateFieldGet:()=>I,__classPrivateFieldSet:()=>A,__createBinding:()=>f,__decorate:()=>a,__exportStar:()=>d,__extends:()=>n,__generator:()=>l,__importDefault:()=>M,__importStar:()=>S,__makeTemplateObject:()=>E,__metadata:()=>c,__param:()=>h,__read:()=>g,__rest:()=>o,__spread:()=>y,__spreadArrays:()=>m,__values:()=>p});var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},i(e,t)};function n(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var s=function(){return s=Object.assign||function(e){for(var t,r=1,i=arguments.length;r=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}function h(e,t){return function(r,i){t(r,i,e)}}function c(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function u(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{h(i.next(e))}catch(e){s(e)}}function a(e){try{h(i.throw(e))}catch(e){s(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((i=i.apply(e,t||[])).next())}))}function l(e,t){var r,i,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,i&&(n=2&s[0]?i.return:s[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,s[1])).done)return n;switch(i=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((n=(n=o.trys).length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function g(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,s=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return o}function y(){for(var e=[],t=0;t1||a(e,t)}))})}function a(e,t){try{(r=n[e](t)).value instanceof v?Promise.resolve(r.value.v).then(h,c):u(s[0][2],r)}catch(e){u(s[0][3],e)}var r}function h(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function b(e){var t,r;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,n){t[i]=e[i]?function(t){return(r=!r)?{value:v(e[i](t)),done:"return"===i}:n?n(t):t}:n}}function _(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=p(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=e[r]&&function(t){return new Promise((function(i,n){!function(e,t,r,i){Promise.resolve(i).then((function(t){e({value:t,done:r})}),t)}(i,n,(t=e[r](t)).done,t.value)}))}}}function E(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function S(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function M(e){return e&&e.__esModule?e:{default:e}}function I(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function A(e,t,r){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,r),r}},5869:(e,t,r)=>{function i(e,t){return t=t||{},new Promise((function(r,i){var n=new XMLHttpRequest,s=[],o=[],a={},h=function(){return{ok:2==(n.status/100|0),statusText:n.statusText,status:n.status,url:n.responseURL,text:function(){return Promise.resolve(n.responseText)},json:function(){return Promise.resolve(n.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([n.response]))},clone:h,headers:{keys:function(){return s},entries:function(){return o},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var c in n.open(t.method||"get",e,!0),n.onload=function(){n.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(e,t,r){s.push(t=t.toLowerCase()),o.push([t,r]),a[t]=a[t]?a[t]+","+r:r})),r(h())},n.onerror=i,n.withCredentials="include"==t.credentials,t.headers)n.setRequestHeader(c,t.headers[c]);n.send(t.body||null)}))}r.r(t),r.d(t,{default:()=>i})},5883:()=>{},6601:()=>{},6559:(e,t,r)=>{const i=r(5346);e.exports=o;const n=function(){function e(e){return void 0!==e&&e}try{return"undefined"!=typeof globalThis||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch(t){return e(self)||e(window)||e(this)||{}}}().console||{},s={mapHttpRequest:f,mapHttpResponse:f,wrapRequestSerializer:d,wrapResponseSerializer:d,wrapErrorSerializer:d,req:f,res:f,err:function(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const r in e)void 0===t[r]&&(t[r]=e[r]);return t}};function o(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const r=e.browser.write||n;e.browser.write&&(e.browser.asObject=!0);const i=e.serializers||{},s=function(e,t){return Array.isArray(e)?e.filter((function(e){return"!stdSerializers.err"!==e})):!0===e&&Object.keys(t)}(e.browser.serialize,i);let f=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(f=!1),"function"==typeof r&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),!1===e.enabled&&(e.level="silent");const d=e.level||"info",g=Object.create(r);g.log||(g.log=p),Object.defineProperty(g,"levelVal",{get:function(){return"silent"===this.level?1/0:this.levels.values[this.level]}}),Object.defineProperty(g,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,a(y,g,"error","log"),a(y,g,"fatal","error"),a(y,g,"warn","error"),a(y,g,"info","log"),a(y,g,"debug","log"),a(y,g,"trace","log")}});const y={transmit:t,serialize:s,asObject:e.browser.asObject,levels:["error","fatal","warn","info","debug","trace"],timestamp:l(e)};return g.levels=o.levels,g.level=d,g.setMaxListeners=g.getMaxListeners=g.emit=g.addListener=g.on=g.prependListener=g.once=g.prependOnceListener=g.removeListener=g.removeAllListeners=g.listeners=g.listenerCount=g.eventNames=g.write=g.flush=p,g.serializers=i,g._serialize=s,g._stdErrSerialize=f,g.child=function(r,n){if(!r)throw new Error("missing bindings for child Pino");n=n||{},s&&r.serializers&&(n.serializers=r.serializers);const o=n.serializers;if(s&&o){var a=Object.assign({},i,o),l=!0===e.browser.serialize?Object.keys(a):s;delete r.serializers,h([r],l,a,this._stdErrSerialize)}function f(e){this._childLevel=1+(0|e._childLevel),this.error=c(e,r,"error"),this.fatal=c(e,r,"fatal"),this.warn=c(e,r,"warn"),this.info=c(e,r,"info"),this.debug=c(e,r,"debug"),this.trace=c(e,r,"trace"),a&&(this.serializers=a,this._serialize=l),t&&(this._logEvent=u([].concat(e._logEvent.bindings,r)))}return f.prototype=this,new f(this)},t&&(g._logEvent=u()),g}function a(e,t,r,s){const a=Object.getPrototypeOf(t);t[r]=t.levelVal>t.levels.values[r]?p:a[r]?a[r]:n[r]||n[s]||p,function(e,t,r){var s;(e.transmit||t[r]!==p)&&(t[r]=(s=t[r],function(){const a=e.timestamp(),c=new Array(arguments.length),l=Object.getPrototypeOf&&Object.getPrototypeOf(this)===n?n:this;for(var f=0;f-1&&i in r&&(e[n][i]=r[i](e[n][i]))}function c(e,t,r){return function(){const i=new Array(1+arguments.length);i[0]=t;for(var n=1;n{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{var e={};r.r(e),r.d(e,{identity:()=>se});var t={};r.r(t),r.d(t,{base2:()=>oe});var i={};r.r(i),r.d(i,{base8:()=>ae});var n={};r.r(n),r.d(n,{base10:()=>he});var s={};r.r(s),r.d(s,{base16:()=>ce,base16upper:()=>ue});var o={};r.r(o),r.d(o,{base32:()=>le,base32hex:()=>ge,base32hexpad:()=>me,base32hexpadupper:()=>ve,base32hexupper:()=>ye,base32pad:()=>de,base32padupper:()=>pe,base32upper:()=>fe,base32z:()=>we});var a={};r.r(a),r.d(a,{base36:()=>be,base36upper:()=>_e});var h={};r.r(h),r.d(h,{base58btc:()=>Ee,base58flickr:()=>Se});var c={};r.r(c),r.d(c,{base64:()=>Me,base64pad:()=>Ie,base64url:()=>Ae,base64urlpad:()=>Oe});var u={};r.r(u),r.d(u,{base256emoji:()=>Re});var l={};r.r(l),r.d(l,{sha256:()=>Ze,sha512:()=>et});var f={};r.r(f),r.d(f,{identity:()=>rt});var d={};r.r(d),r.d(d,{code:()=>nt,decode:()=>ot,encode:()=>st,name:()=>it});var p={};r.r(p),r.d(p,{code:()=>ut,decode:()=>ft,encode:()=>lt,name:()=>ct});var g=r(7187),y=r.n(g),m=r(5150),v=r(159),w=r(9107),b=r(8200);class _ extends b.q{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class E extends b.q{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}}class S{constructor(e,t){this.logger=e,this.core=t}}class M extends b.q{constructor(e,t){super(),this.relayer=e,this.logger=t}}class I extends b.q{constructor(e){super()}}class A{constructor(e,t,r,i){this.core=e,this.logger=t,this.name=r}}class O extends b.q{constructor(e,t){super(),this.relayer=e,this.logger=t}}class x extends b.q{constructor(e,t){super(),this.core=e,this.logger=t}}class P{constructor(e,t){this.projectId=e,this.logger=t}}class N{constructor(e){this.opts=e,this.protocol="wc",this.version=2}}class R{constructor(e){this.client=e}}const T=e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t));function L(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return(e=>{const t=e.replace(/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,'$1"$2n"$3');return JSON.parse(t,((e,t)=>"string"==typeof t&&t.match(/^\d+n$/)?BigInt(t.substring(0,t.length-1)):t))})(e)}catch(t){return e}}function C(e){return"string"==typeof e?e:T(e)||""}var U=r(1050),k=r(1416),j=r(6736);const q="base64url",D="utf8",z=":",$="did",B="key",K="base58btc",F="z",V="K36";function H(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function W(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?H(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function G(e,t){t||(t=e.reduce(((e,t)=>e+t.length),0));const r=W(t);let i=0;for(const t of e)r.set(t,i),i+=t.length;return H(r)}const J=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i>>0,o=new Uint8Array(s);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var l=0,f=s-1;(0!==u||l>>0,o[f]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");n=l,t++}if(" "!==e[t]){for(var d=s-n;d!==s&&0===o[d];)d++;for(var p=new Uint8Array(i+(s-d)),g=i;d!==s;)p[g++]=o[d++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,i=0,n=0,s=t.length;n!==s&&0===t[n];)n++,r++;for(var o=(s-n)*u+1>>>0,c=new Uint8Array(o);n!==s;){for(var l=t[n],f=0,d=o-1;(0!==l||f>>0,c[d]=l%a>>>0,l=l/a>>>0;if(0!==l)throw new Error("Non-zero carry");i=f,n++}for(var p=o-i;p!==o&&0===c[p];)p++;for(var g=h.repeat(r);p{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")});class X{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Q{constructor(e,t,r){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return ee(this,e)}}class Z{constructor(e){this.decoders=e}or(e){return ee(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ee=(e,t)=>new Z({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class te{constructor(e,t,r,i){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=i,this.encoder=new X(e,t,r),this.decoder=new Q(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const re=({name:e,prefix:t,encode:r,decode:i})=>new te(e,t,r,i),ie=({prefix:e,name:t,alphabet:r})=>{const{encode:i,decode:n}=J(r,t);return re({prefix:e,name:t,encode:i,decode:e=>Y(n(e))})},ne=({name:e,prefix:t,bitsPerChar:r,alphabet:i})=>re({prefix:t,name:e,encode:e=>((e,t,r)=>{const i="="===t[t.length-1],n=(1<r;)o-=r,s+=t[n&a>>o];if(o&&(s+=t[n&a<((e,t,r,i)=>{const n={};for(let e=0;e=8&&(a-=8,o[c++]=255&h>>a)}if(a>=r||255&h<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,i,r,e)}),se=re({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)}),oe=ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),ae=ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),he=ie({prefix:"9",name:"base10",alphabet:"0123456789"}),ce=ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ue=ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),le=ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fe=ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),de=ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pe=ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ge=ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ye=ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),me=ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ve=ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),we=ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),be=ie({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_e=ie({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Ee=ie({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Se=ie({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Me=ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ie=ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ae=ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Oe=ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),xe=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Pe=xe.reduce(((e,t,r)=>(e[r]=t,e)),[]),Ne=xe.reduce(((e,t,r)=>(e[t.codePointAt(0)]=r,e)),[]),Re=re({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+Pe[t]),"")},decode:function(e){const t=[];for(const r of e){const e=Ne[r.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}});var Te=128,Le=-128,Ce=Math.pow(2,31),Ue=Math.pow(2,7),ke=Math.pow(2,14),je=Math.pow(2,21),qe=Math.pow(2,28),De=Math.pow(2,35),ze=Math.pow(2,42),$e=Math.pow(2,49),Be=Math.pow(2,56),Ke=Math.pow(2,63);const Fe=function e(t,r,i){r=r||[];for(var n=i=i||0;t>=Ce;)r[i++]=255&t|Te,t/=128;for(;t&Le;)r[i++]=255&t|Te,t>>>=7;return r[i]=0|t,e.bytes=i-n+1,r},Ve=function(e){return e(Fe(e,t,r),t),We=e=>Ve(e),Ge=(e,t)=>{const r=t.byteLength,i=We(e),n=i+We(r),s=new Uint8Array(n+r);return He(e,s,0),He(r,s,i),s.set(t,n),new Je(e,r,t,s)};class Je{constructor(e,t,r,i){this.code=e,this.size=t,this.digest=r,this.bytes=i}}const Ye=({name:e,code:t,encode:r})=>new Xe(e,t,r);class Xe{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Ge(this.code,t):t.then((e=>Ge(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Qe=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Ze=Ye({name:"sha2-256",code:18,encode:Qe("SHA-256")}),et=Ye({name:"sha2-512",code:19,encode:Qe("SHA-512")}),tt=Y,rt={code:0,name:"identity",encode:tt,digest:e=>Ge(0,tt(e))},it="raw",nt=85,st=e=>Y(e),ot=e=>Y(e),at=new TextEncoder,ht=new TextDecoder,ct="json",ut=512,lt=e=>at.encode(JSON.stringify(e)),ft=e=>JSON.parse(ht.decode(e));Symbol.toStringTag,Symbol.for("nodejs.util.inspect.custom"),Symbol.for("@ipld/js-cid/CID");const dt={...e,...t,...i,...n,...s,...o,...a,...h,...c,...u};function pt(e,t,r,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:i}}}const gt=pt("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),yt=pt("ascii","a",(e=>{let t="a";for(let r=0;r{const t=W((e=e.substring(1)).length);for(let r=0;r"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function Zt(e){return 1===e.type&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}var er=Object.defineProperty,tr=Object.getOwnPropertySymbols,rr=Object.prototype.hasOwnProperty,ir=Object.prototype.propertyIsEnumerable,nr=(e,t,r)=>t in e?er(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,sr=(e,t)=>{for(var r in t||(t={}))rr.call(t,r)&&nr(e,r,t[r]);if(tr)for(var r of tr(t))ir.call(t,r)&&nr(e,r,t[r]);return e};const or="ReactNative",ar={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},hr="js";function cr(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function ur(){return!(0,qt.getDocument)()&&!!(0,qt.getNavigator)()&&navigator.product===or}function lr(){return!cr()&&!!(0,qt.getNavigator)()}function fr(){return ur()?ar.reactNative:cr()?ar.node:lr()?ar.browser:ar.unknown}function dr(e,t,i){const n=function(){if(fr()===ar.reactNative&&typeof r.g<"u"&&typeof(null==r.g?void 0:r.g.Platform)<"u"){const{OS:e,Version:t}=r.g.Platform;return[e,t].join("-")}const e=t?jt(t):"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new Tt:"undefined"!=typeof navigator?jt(navigator.userAgent):"undefined"!=typeof process&&process.version?new Pt(process.version.slice(1)):null;var t;if(null===e)return"unknown";const i=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[i,e.name,e.version].join("-"):[i,e.version].join("-")}(),s=function(){var e;const t=fr();return t===ar.browser?[t,(null==(e=(0,qt.getLocation)())?void 0:e.host)||"unknown"].join(":"):t}();return[[e,t].join("-"),[hr,i].join("-"),n,s].join("/")}function pr(e,t){return e.filter((e=>t.includes(e))).length===e.length}function gr(e){return Object.fromEntries(e.entries())}function yr(e){return new Map(Object.entries(e))}function mr(e=j.FIVE_MINUTES,t){const r=(0,j.toMiliseconds)(e||j.FIVE_MINUTES);let i,n,s;return{resolve:e=>{s&&i&&(clearTimeout(s),i(e))},reject:e=>{s&&n&&(clearTimeout(s),n(e))},done:()=>new Promise(((e,o)=>{s=setTimeout((()=>{o(new Error(t))}),r),i=e,n=o}))}}function vr(e,t,r){return new Promise((async(i,n)=>{const s=setTimeout((()=>n(new Error(r))),t);try{i(await e)}catch(e){n(e)}clearTimeout(s)}))}function wr(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function br(e){const[t,r]=e.split(":"),i={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof r)i.topic=r;else{if("id"!==t||!Number.isInteger(Number(r)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`);i.id=Number(r)}return i}function _r(e,t){return(0,j.fromMiliseconds)((t||Date.now())+(0,j.toMiliseconds)(e))}function Er(e){return Date.now()>=(0,j.toMiliseconds)(e)}function Sr(e,t){return`${e}${t?`:${t}`:""}`}function Mr(e=[],t=[]){return[...new Set([...e,...t])]}function Ir(e){return e?.relay||{protocol:"irn"}}function Ar(e){const t=$t[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}var Or=Object.defineProperty,xr=Object.getOwnPropertySymbols,Pr=Object.prototype.hasOwnProperty,Nr=Object.prototype.propertyIsEnumerable,Rr=(e,t,r)=>t in e?Or(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;function Tr(e,t="-"){const r={},i="relay"+t;return Object.keys(e).forEach((t=>{if(t.startsWith(i)){const n=t.replace(i,""),s=e[t];r[n]=s}})),r}function Lr(e){return e.startsWith("//")?e.substring(2):e}var Cr=Object.defineProperty,Ur=Object.defineProperties,kr=Object.getOwnPropertyDescriptors,jr=Object.getOwnPropertySymbols,qr=Object.prototype.hasOwnProperty,Dr=Object.prototype.propertyIsEnumerable,zr=(e,t,r)=>t in e?Cr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$r=(e,t)=>{for(var r in t||(t={}))qr.call(t,r)&&zr(e,r,t[r]);if(jr)for(var r of jr(t))Dr.call(t,r)&&zr(e,r,t[r]);return e},Br=(e,t)=>Ur(e,kr(t));function Kr(e){const t=[];return e.forEach((e=>{const[r,i]=e.split(":");t.push(`${r}:${i}`)})),t}function Fr(e){return e.includes(":")}function Vr(e){return Fr(e)?e.split(":")[0]:e}function Hr(e){var t,r,i;const n={};if(!Qr(e))return n;for(const[s,o]of Object.entries(e)){const e=Fr(s)?[s]:o.chains,a=o.methods||[],h=o.events||[],c=Vr(s);n[c]=Br($r({},n[c]),{chains:Mr(e,null==(t=n[c])?void 0:t.chains),methods:Mr(a,null==(r=n[c])?void 0:r.methods),events:Mr(h,null==(i=n[c])?void 0:i.events)})}return n}const Wr={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},Gr={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Jr(e,t){const{message:r,code:i}=Gr[e];return{message:t?`${r} ${t}`:r,code:i}}function Yr(e,t){const{message:r,code:i}=Wr[e];return{message:t?`${r} ${t}`:r,code:i}}function Xr(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function Qr(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Zr(e){return typeof e>"u"}function ei(e,t){return!(!t||!Zr(e))||"string"==typeof e&&!!e.trim().length}function ti(e,t){return!(!t||!Zr(e))||"number"==typeof e&&!isNaN(e)}function ri(e){return!(!ei(e,!1)||!e.includes(":"))&&2===e.split(":").length}function ii(e){if(ei(e,!1))try{return typeof new URL(e)<"u"}catch{return!1}return!1}function ni(e){let t=!0;return Xr(e)?e.length&&(t=e.every((e=>ei(e,!1)))):t=!1,t}function si(e,t){let r=null;return Object.values(e).forEach((e=>{if(r)return;const i=function(e,t){let r=null;return ni(e?.methods)?ni(e?.events)||(r=Yr("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):r=Yr("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),r}(e,`${t}, namespace`);i&&(r=i)})),r}function oi(e,t){let r=null;if(e&&Qr(e)){const i=si(e,t);i&&(r=i);const n=function(e,t){let r=null;return Object.values(e).forEach((e=>{if(r)return;const i=function(e,t){let r=null;return Xr(e)?e.forEach((e=>{r||function(e){if(ei(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&ri(e)}}return!1}(e)||(r=Yr("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))})):r=Yr("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}(e?.accounts,`${t} namespace`);i&&(r=i)})),r}(e,t);n&&(r=n)}else r=Jr("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return r}function ai(e){return ei(e.protocol,!0)}function hi(e){return typeof e<"u"&&null!==typeof e}function ci(e,t){return!(!ri(t)||!function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...Kr(e.accounts))})),t}(e).includes(t))}function ui(e,t,r){let i=null;const n=function(e){const t={};return Object.keys(e).forEach((r=>{var i;r.includes(":")?t[r]=e[r]:null==(i=e[r].chains)||i.forEach((i=>{t[i]={methods:e[r].methods,events:e[r].events}}))})),t}(e),s=function(e){const t={};return Object.keys(e).forEach((r=>{if(r.includes(":"))t[r]=e[r];else{const i=Kr(e[r].accounts);i?.forEach((i=>{t[i]={accounts:e[r].accounts.filter((e=>e.includes(`${i}:`))),methods:e[r].methods,events:e[r].events}}))}})),t}(t),o=Object.keys(n),a=Object.keys(s),h=li(Object.keys(e)),c=li(Object.keys(t)),u=h.filter((e=>!c.includes(e)));return u.length&&(i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.\n Required: ${u.toString()}\n Received: ${Object.keys(t).toString()}`)),pr(o,a)||(i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach((e=>{if(!e.includes(":")||i)return;const n=Kr(t[e].accounts);n.includes(e)||(i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${n.toString()}`))})),o.forEach((e=>{i||(pr(n[e].methods,s[e].methods)?pr(n[e].events,s[e].events)||(i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${e}`)):i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${e}`))})),i}function li(e){return[...new Set(e.map((e=>e.includes(":")?e.split(":")[0]:e)))]}function fi(e,t){return ti(e,!1)&&e<=t.max&&e>=t.min}function di(){const e=fr();return new Promise((t=>{switch(e){case ar.browser:t(lr()&&navigator?.onLine);break;case ar.reactNative:t(async function(){if(ur()&&typeof r.g<"u"&&null!=r.g&&r.g.NetInfo){const e=await(null==r.g?void 0:r.g.NetInfo.fetch());return e?.isConnected}return!0}());break;case ar.node:default:t(!0)}}))}const pi={};class gi{static get(e){return pi[e]}static set(e,t){pi[e]=t}static delete(e){delete pi[e]}}const yi="INTERNAL_ERROR",mi="SERVER_ERROR",vi=[-32700,-32600,-32601,-32602,-32603],wi={PARSE_ERROR:{code:-32700,message:"Parse error"},INVALID_REQUEST:{code:-32600,message:"Invalid Request"},METHOD_NOT_FOUND:{code:-32601,message:"Method not found"},INVALID_PARAMS:{code:-32602,message:"Invalid params"},[yi]:{code:-32603,message:"Internal error"},[mi]:{code:-32e3,message:"Server error"}},bi=mi;function _i(e){return Object.keys(wi).includes(e)?wi[e]:wi[bi]}var Ei=r(1468);function Si(e=3){return Date.now()*Math.pow(10,e)+Math.floor(Math.random()*Math.pow(10,e))}function Mi(e=6){return BigInt(Si(e))}function Ii(e,t,r){return{id:r||Si(),jsonrpc:"2.0",method:e,params:t}}function Ai(e,t){return{id:e,jsonrpc:"2.0",result:t}}function Oi(e,t,r){return{id:e,jsonrpc:"2.0",error:xi(t,r)}}function xi(e,t){return void 0===e?_i(yi):("string"==typeof e&&(e=Object.assign(Object.assign({},_i(mi)),{message:e})),void 0!==t&&(e.data=t),r=e.code,vi.includes(r)&&(e=function(e){return Object.values(wi).find((t=>t.code===e))||wi[bi]}(e.code)),e);var r}class Pi{}class Ni extends Pi{constructor(){super()}}class Ri extends Ni{constructor(e){super()}}function Ti(e){return function(e,t){const r=function(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(t&&t.length)return t[0]}(e);return void 0!==r&&new RegExp(t).test(r)}(e,"^wss?:")}function Li(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function Ci(e){return"object"==typeof e&&"id"in e&&"jsonrpc"in e&&"2.0"===e.jsonrpc}function Ui(e){return Ci(e)&&"method"in e}function ki(e){return Ci(e)&&(ji(e)||qi(e))}function ji(e){return"result"in e}function qi(e){return"error"in e}class Di extends Ri{constructor(e){super(e),this.events=new g.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(Ii(e.method,e.params||[],e.id||Mi().toString()),t)}async requestStrict(e,t){return new Promise((async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(e){i(e)}this.events.on(`${e.id}`,(e=>{qi(e)?i(e.error):r(e.result)}));try{await this.connection.send(e,t)}catch(e){i(e)}}))}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ki(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&3e3===e.code&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),"string"==typeof e&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",(e=>this.onPayload(e))),this.connection.on("close",(e=>this.onClose(e))),this.connection.on("error",(e=>this.events.emit("error",e))),this.connection.on("register_error",(e=>this.onClose())),this.hasRegisteredEventListeners=!0)}}const zi=e=>e.split("?")[0],$i="undefined"!=typeof WebSocket?WebSocket:void 0!==r.g&&void 0!==r.g.WebSocket?r.g.WebSocket:"undefined"!=typeof window&&void 0!==window.WebSocket?window.WebSocket:"undefined"!=typeof self&&void 0!==self.WebSocket?self.WebSocket:r(2030),Bi=class{constructor(e){if(this.url=e,this.events=new g.EventEmitter,this.registering=!1,!Ti(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return void 0!==this.socket}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise(((e,t)=>{void 0!==this.socket?(this.socket.onclose=t=>{this.onClose(t),e()},this.socket.close()):t(new Error("Connection already closed"))}))}async send(e,t){void 0===this.socket&&(this.socket=await this.register());try{this.socket.send(C(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Ti(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise(((e,t)=>{this.events.once("register_error",(e=>{this.resetMaxListeners(),t(e)})),this.events.once("open",(()=>{if(this.resetMaxListeners(),void 0===this.socket)return t(new Error("WebSocket connection is missing or invalid"));e(this.socket)}))}))}return this.url=e,this.registering=!0,new Promise(((t,i)=>{const n=(0,Ei.isReactNative)()?void 0:{rejectUnauthorized:!Li(e)},s=new $i(e,[],n);"undefined"!=typeof WebSocket||void 0!==r.g&&void 0!==r.g.WebSocket||"undefined"!=typeof window&&void 0!==window.WebSocket||"undefined"!=typeof self&&void 0!==self.WebSocket?s.onerror=e=>{const t=e;i(this.emitError(t.error))}:s.on("error",(e=>{i(this.emitError(e))})),s.onopen=()=>{this.onOpen(s),t(s)}}))}onOpen(e){e.onmessage=e=>this.onPayload(e),e.onclose=e=>this.onClose(e),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(void 0===e.data)return;const t="string"==typeof e.data?L(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const r=this.parseError(t),i=Oi(e,r.message||r.toString());this.events.emit("payload",i)}parseError(e,t=this.url){return function(e,t,r){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable WS RPC url at ${t}`):e}(e,zi(t))}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}emitError(e){const t=this.parseError(new Error((null==e?void 0:e.message)||`WebSocket connection failed for host: ${zi(this.url)}`));return this.events.emit("register_error",t),t}};var Ki=r(2307),Fi=r.n(Ki),Vi=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i>>0,o=new Uint8Array(s);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var l=0,f=s-1;(0!==u||l>>0,o[f]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");n=l,t++}if(" "!==e[t]){for(var d=s-n;d!==s&&0===o[d];)d++;for(var p=new Uint8Array(i+(s-d)),g=i;d!==s;)p[g++]=o[d++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,i=0,n=0,s=t.length;n!==s&&0===t[n];)n++,r++;for(var o=(s-n)*u+1>>>0,c=new Uint8Array(o);n!==s;){for(var l=t[n],f=0,d=o-1;(0!==l||f>>0,c[d]=l%a>>>0,l=l/a>>>0;if(0!==l)throw new Error("Non-zero carry");i=f,n++}for(var p=o-i;p!==o&&0===c[p];)p++;for(var g=h.repeat(r);p{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class Wi{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Gi{constructor(e,t,r){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Yi(this,e)}}class Ji{constructor(e){this.decoders=e}or(e){return Yi(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yi=(e,t)=>new Ji({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Xi{constructor(e,t,r,i){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=i,this.encoder=new Wi(e,t,r),this.decoder=new Gi(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Qi=({name:e,prefix:t,encode:r,decode:i})=>new Xi(e,t,r,i),Zi=({prefix:e,name:t,alphabet:r})=>{const{encode:i,decode:n}=Vi(r,t);return Qi({prefix:e,name:t,encode:i,decode:e=>Hi(n(e))})},en=({name:e,prefix:t,bitsPerChar:r,alphabet:i})=>Qi({prefix:t,name:e,encode:e=>((e,t,r)=>{const i="="===t[t.length-1],n=(1<r;)o-=r,s+=t[n&a>>o];if(o&&(s+=t[n&a<((e,t,r,i)=>{const n={};for(let e=0;e=8&&(a-=8,o[c++]=255&h>>a)}if(a>=r||255&h<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,i,r,e)}),tn=Qi({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var rn=Object.freeze({__proto__:null,identity:tn});const nn=en({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sn=Object.freeze({__proto__:null,base2:nn});const on=en({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var an=Object.freeze({__proto__:null,base8:on});const hn=Zi({prefix:"9",name:"base10",alphabet:"0123456789"});var cn=Object.freeze({__proto__:null,base10:hn});const un=en({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ln=en({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var fn=Object.freeze({__proto__:null,base16:un,base16upper:ln});const dn=en({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),pn=en({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gn=en({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yn=en({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mn=en({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vn=en({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wn=en({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),bn=en({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_n=en({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var En=Object.freeze({__proto__:null,base32:dn,base32upper:pn,base32pad:gn,base32padupper:yn,base32hex:mn,base32hexupper:vn,base32hexpad:wn,base32hexpadupper:bn,base32z:_n});const Sn=Zi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mn=Zi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var In=Object.freeze({__proto__:null,base36:Sn,base36upper:Mn});const An=Zi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),On=Zi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xn=Object.freeze({__proto__:null,base58btc:An,base58flickr:On});const Pn=en({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Nn=en({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Rn=en({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Tn=en({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ln=Object.freeze({__proto__:null,base64:Pn,base64pad:Nn,base64url:Rn,base64urlpad:Tn});const Cn=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Un=Cn.reduce(((e,t,r)=>(e[r]=t,e)),[]),kn=Cn.reduce(((e,t,r)=>(e[t.codePointAt(0)]=r,e)),[]),jn=Qi({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+Un[t]),"")},decode:function(e){const t=[];for(const r of e){const e=kn[r.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}});var qn=Object.freeze({__proto__:null,base256emoji:jn}),Dn=128,zn=-128,$n=Math.pow(2,31),Bn=Math.pow(2,7),Kn=Math.pow(2,14),Fn=Math.pow(2,21),Vn=Math.pow(2,28),Hn=Math.pow(2,35),Wn=Math.pow(2,42),Gn=Math.pow(2,49),Jn=Math.pow(2,56),Yn=Math.pow(2,63),Xn=function e(t,r,i){r=r||[];for(var n=i=i||0;t>=$n;)r[i++]=255&t|Dn,t/=128;for(;t&zn;)r[i++]=255&t|Dn,t>>>=7;return r[i]=0|t,e.bytes=i-n+1,r},Qn=function(e){return e(Xn(e,t,r),t),es=e=>Qn(e),ts=(e,t)=>{const r=t.byteLength,i=es(e),n=i+es(r),s=new Uint8Array(n+r);return Zn(e,s,0),Zn(r,s,i),s.set(t,n),new rs(e,r,t,s)};class rs{constructor(e,t,r,i){this.code=e,this.size=t,this.digest=r,this.bytes=i}}const is=({name:e,code:t,encode:r})=>new ns(e,t,r);class ns{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?ts(this.code,t):t.then((e=>ts(this.code,e)))}throw Error("Unknown type, must be binary type")}}const ss=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),os=is({name:"sha2-256",code:18,encode:ss("SHA-256")}),as=is({name:"sha2-512",code:19,encode:ss("SHA-512")});Object.freeze({__proto__:null,sha256:os,sha512:as});const hs=Hi,cs={code:0,name:"identity",encode:hs,digest:e=>ts(0,hs(e))};Object.freeze({__proto__:null,identity:cs}),new TextEncoder,new TextDecoder;const us={...rn,...sn,...an,...cn,...fn,...En,...In,...xn,...Ln,...qn};function ls(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function fs(e,t,r,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:i}}}const ds=fs("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),ps=fs("ascii","a",(e=>{let t="a";for(let r=0;r{const t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?ls(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}((e=e.substring(1)).length);for(let r=0;r{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}},this.has=e=>(this.isInitialized(),this.keychain.has(e)),this.set=async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()},this.get=e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t},this.del=async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()},this.core=e,this.logger=(0,w.generateChildLogger)(t,this.name)}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,gr(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?yr(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Xs{constructor(e,t,r){this.core=e,this.logger=t,this.name="crypto",this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=e=>(this.isInitialized(),this.keychain.has(e)),this.getClientId=async()=>(this.isInitialized(),_t(Et(await this.getClientSeed()).publicKey)),this.generateKeyPair=()=>{this.isInitialized();const e=function(){const e=At.Au();return{privateKey:vt(e.secretKey,Ft),publicKey:vt(e.publicKey,Ft)}}();return this.setPrivateKey(e.publicKey,e.privateKey)},this.signJWT=async e=>{this.isInitialized();const t=Et(await this.getClientSeed()),r=Wt(),i=bs;return await async function(e,t,r,i,n=(0,j.fromMiliseconds)(Date.now())){const s={alg:"EdDSA",typ:"JWT"},o={iss:_t(i.publicKey),sub:e,aud:t,iat:n,exp:n+r},a=wt([bt((h={header:s,payload:o}).header),bt(h.payload)].join("."),"utf8");var h;return function(e){return[bt(e.header),bt(e.payload),(t=e.signature,vt(t,q))].join(".");var t}({header:s,payload:o,signature:U.Xx(i.secretKey,a)})}(r,e,i,t)},this.generateSharedKey=(e,t,r)=>{this.isInitialized();const i=function(e,t){const r=At.gi(wt(e,Ft),wt(t,Ft),!0);return vt(new Mt.t(It.mE,r).expand(32),Ft)}(this.getPrivateKey(e),t);return this.setSymKey(i,r)},this.setSymKey=async(e,t)=>{this.isInitialized();const r=t||Gt(e);return await this.keychain.set(r,e),r},this.deleteKeyPair=async e=>{this.isInitialized(),await this.keychain.del(e)},this.deleteSymKey=async e=>{this.isInitialized(),await this.keychain.del(e)},this.encode=async(e,t,r)=>{this.isInitialized();const i=Qt(r),n=C(t);if(Zt(i)){const t=i.senderPublicKey,r=i.receiverPublicKey;e=await this.generateSharedKey(t,r)}const s=this.getSymKey(e),{type:o,senderPublicKey:a}=i;return function(e){const t=function(e){return wt(`${e}`,Kt)}(typeof e.type<"u"?e.type:0);if(1===Yt(t)&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof e.senderPublicKey<"u"?wt(e.senderPublicKey,Ft):void 0,i=typeof e.iv<"u"?wt(e.iv,Ft):(0,k.randomBytes)(12);return function(e){if(1===Yt(e.type)){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return vt(G([e.type,e.senderPublicKey,e.iv,e.sealed]),Vt)}return vt(G([e.type,e.iv,e.sealed]),Vt)}({type:t,sealed:new St.OK(wt(e.symKey,Ft)).seal(i,wt(e.message,Ht)),iv:i,senderPublicKey:r})}({type:o,symKey:s,message:n,senderPublicKey:a})},this.decode=async(e,t,r)=>{this.isInitialized();const i=function(e,t){const r=Xt(e);return Qt({type:Yt(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?vt(r.senderPublicKey,Ft):void 0,receiverPublicKey:t?.receiverPublicKey})}(t,r);if(Zt(i)){const t=i.receiverPublicKey,r=i.senderPublicKey;e=await this.generateSharedKey(t,r)}try{const r=function(e){const t=new St.OK(wt(e.symKey,Ft)),{sealed:r,iv:i}=Xt(e.encoded),n=t.open(i,r);if(null===n)throw new Error("Failed to decrypt");return vt(n,Ht)}({symKey:this.getSymKey(e),encoded:t});return L(r)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}},this.getPayloadType=e=>Yt(Xt(e).type),this.getPayloadSenderPublicKey=e=>{const t=Xt(e);return t.senderPublicKey?vt(t.senderPublicKey,Ft):void 0},this.core=e,this.logger=(0,w.generateChildLogger)(t,this.name),this.keychain=r||new Ys(this.core,this.logger)}get context(){return(0,w.getLoggerContext)(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ws)}catch{e=Wt(),await this.keychain.set(ws,e)}return function(e,t="utf8"){const r=gs[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?r.decoder.decode(`${r.prefix}${e}`):ls(globalThis.Buffer.from(e,"utf-8"))}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Qs extends S{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name="messages",this.version="0.3",this.initialized=!1,this.storagePrefix=ms,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}},this.set=async(e,t)=>{this.isInitialized();const r=Jt(t);let i=this.messages.get(e);return typeof i>"u"&&(i={}),typeof i[r]<"u"||(i[r]=t,this.messages.set(e,i),await this.persist()),r},this.get=e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t},this.has=(e,t)=>(this.isInitialized(),typeof this.get(e)[Jt(t)]<"u"),this.del=async e=>{this.isInitialized(),this.messages.delete(e),await this.persist()},this.logger=(0,w.generateChildLogger)(e,this.name),this.core=t}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,gr(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?yr(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Zs extends M{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new g.EventEmitter,this.name="publisher",this.queue=new Map,this.publishTimeout=(0,j.toMiliseconds)(j.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(e,t,r)=>{var i;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:r}});try{const n=r?.ttl||_s,s=Ir(r),o=r?.prompt||!1,a=r?.tag||0,h=r?.id||Mi().toString(),c={topic:e,message:t,opts:{ttl:n,relay:s,prompt:o,tag:a,id:h}},u=setTimeout((()=>this.queue.set(h,c)),this.publishTimeout);try{await await vr(this.rpcPublish(e,t,n,s,o,a,h),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(h),this.relayer.events.emit(Ps,c)}catch(e){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,null!=(i=r?.internal)&&i.throwOnFailedPublish)throw this.removeRequestFromQueue(h),e;return}finally{clearTimeout(u)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:r}})}catch(e){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(e),e}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.relayer=e,this.logger=(0,w.generateChildLogger)(t,this.name),this.registerEventListeners()}get context(){return(0,w.getLoggerContext)(this.logger)}rpcPublish(e,t,r,i,n,s,o){var a,h,c,u;const l={method:Ar(i.protocol).publish,params:{topic:e,message:t,ttl:r,prompt:n,tag:s},id:o};return Zr(null==(a=l.params)?void 0:a.prompt)&&(null==(h=l.params)||delete h.prompt),Zr(null==(c=l.params)?void 0:c.tag)&&(null==(u=l.params)||delete u.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:l}),this.relayer.request(l)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach((async e=>{const{topic:t,message:r,opts:i}=e;await this.publish(t,r,i)}))}registerEventListeners(){this.relayer.core.heartbeat.on(v.HEARTBEAT_EVENTS.pulse,(()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(xs);this.checkQueue()})),this.relayer.on(Is,(e=>{this.removeRequestFromQueue(e.id.toString())}))}}class eo{constructor(){this.map=new Map,this.set=(e,t)=>{const r=this.get(e);this.exists(e,t)||this.map.set(e,[...r,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,t))return;const i=r.filter((e=>e!==t));i.length?this.map.set(e,i):this.map.delete(e)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var to=Object.defineProperty,ro=Object.defineProperties,io=Object.getOwnPropertyDescriptors,no=Object.getOwnPropertySymbols,so=Object.prototype.hasOwnProperty,oo=Object.prototype.propertyIsEnumerable,ao=(e,t,r)=>t in e?to(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ho=(e,t)=>{for(var r in t||(t={}))so.call(t,r)&&ao(e,r,t[r]);if(no)for(var r of no(t))oo.call(t,r)&&ao(e,r,t[r]);return e},co=(e,t)=>ro(e,io(t));class uo extends O{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new eo,this.events=new g.EventEmitter,this.name="subscription",this.version="0.3",this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=ms,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(e,t)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const r=Ir(t),i={topic:e,relay:r};this.pending.set(e,i);const n=await this.rpcSubscribe(e,r);return this.onSubscribe(n,i),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}}),n}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}},this.unsubscribe=async(e,t)=>{await this.restartToComplete(),this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)},this.isSubscribed=async e=>!!this.topics.includes(e)||await new Promise(((t,r)=>{const i=new j.Watch;i.start(this.pendingSubscriptionWatchLabel);const n=setInterval((()=>{!this.pending.has(e)&&this.topics.includes(e)&&(clearInterval(n),i.stop(this.pendingSubscriptionWatchLabel),t(!0)),i.elapsed(this.pendingSubscriptionWatchLabel)>=qs&&(clearInterval(n),i.stop(this.pendingSubscriptionWatchLabel),r(new Error("Subscription resolution timeout")))}),this.pollingInterval)})).catch((()=>!1)),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=(0,w.generateChildLogger)(t,this.name),this.clientId=""}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,t){let r=!1;try{r=this.getSubscription(e).topic===t}catch{}return r}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const r=this.topicMap.get(e);await Promise.all(r.map((async r=>await this.unsubscribeById(e,r,t))))}async unsubscribeById(e,t,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:r}});try{const i=Ir(r);await this.rpcUnsubscribe(e,t,i);const n=Yr("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:r}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t){const r={method:Ar(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await vr(this.relayer.request(r),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(xs)}return Jt(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const t={method:Ar(e[0].relay.protocol).batchSubscribe,params:{topics:e.map((e=>e.topic))}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{return await await vr(this.relayer.request(t),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(xs)}}rpcUnsubscribe(e,t,r){const i={method:Ar(r.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,t){this.setSubscription(e,co(ho({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach((e=>{this.setSubscription(e.id,ho({},e)),this.pending.delete(e.topic)}))}async onUnsubscribe(e,t,r){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t))}addSubscription(e,t){this.subscriptions.set(e,ho({},t)),this.topicMap.set(t.topic,e),this.events.emit(Us,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(ks,co(ho({},r),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit("subscription_sync")}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t"u"||!e.length)return;if(this.subscriptions.size){const{message:e}=Jr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const t=await this.rpcBatchSubscribe(e);Xr(t)&&this.onBatchSubscribe(t.map(((t,r)=>co(ho({},e[r]),{id:t}))))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach((t=>{e.push(t)})),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(v.HEARTBEAT_EVENTS.pulse,(async()=>{await this.checkPending()})),this.relayer.on(As,(async()=>{await this.onConnect()})),this.relayer.on(Os,(()=>{this.onDisconnect()})),this.events.on(Us,(async e=>{const t=Us;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})),this.events.on(ks,(async e=>{const t=ks;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise((e=>{const t=setInterval((()=>{this.restartInProgress||(clearInterval(t),e())}),this.pollingInterval)}))}}var lo=Object.defineProperty,fo=Object.getOwnPropertySymbols,po=Object.prototype.hasOwnProperty,go=Object.prototype.propertyIsEnumerable,yo=(e,t,r)=>t in e?lo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;class mo extends I{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new g.EventEmitter,this.name="relayer",this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.request=async e=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(e)}catch(e){throw this.logger.debug("Failed to Publish Request"),this.logger.error(e),e}},this.onPayloadHandler=e=>{this.onProviderPayload(e)},this.onConnectHandler=()=>{this.events.emit(As)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=e=>{this.logger.error(e),this.events.emit("relayer_error",e),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Ns,this.onPayloadHandler),this.provider.on(Rs,this.onConnectHandler),this.provider.on(Ts,this.onDisconnectHandler),this.provider.on(Ls,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&"string"!=typeof e.logger?(0,w.generateChildLogger)(e.logger,this.name):(0,w.pino)((0,w.getDefaultLoggerOptions)({level:e.logger||"error"})),this.messages=new Qs(this.logger,e.core),this.subscriber=new uo(this,this.logger),this.publisher=new Zs(this,this.logger),this.relayUrl=e?.relayUrl||Es,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${Ss}...`),await this.restartTransport(Ss)}this.initialized=!0,setTimeout((async()=>{0===this.subscriber.topics.length&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)}),1e4)}get context(){return(0,w.getLoggerContext)(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,t,r){this.isInitialized(),await this.publisher.publish(e,t,r),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now()})}async subscribe(e,t){var r;this.isInitialized();let i,n=(null==(r=this.subscriber.topicMap.get(e))?void 0:r[0])||"";if(n)return n;const s=t=>{t.topic===e&&(this.subscriber.off(Us,s),i())};return await Promise.all([new Promise((e=>{i=e,this.subscriber.on(Us,s)})),new Promise((async r=>{n=await this.subscriber.subscribe(e,t),r()}))]),n}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportClose(){this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await vr(this.provider.disconnect(),1e3,"provider.disconnect()").catch((()=>this.onProviderDisconnect())):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise((e=>{if(!this.initialized)return e();this.subscriber.once(js,(()=>{e()}))})),new Promise((async(e,t)=>{try{await vr(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(e){return void t(e)}e()}))])}catch(e){this.logger.error(e);const t=e;if(!this.isConnectionStalled(t.message))throw e;this.provider.events.emit(Ts)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await di())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some((t=>e.includes(t)))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Di(new Bi(function({protocol:e,version:t,relayUrl:r,sdkVersion:i,auth:n,projectId:s,useOnCloseEvent:o}){const a=r.split("?"),h={auth:n,ua:dr(e,t,i),projectId:s,useOnCloseEvent:o||void 0},c=function(e,t){let r=zt.parse(e);return r=sr(sr({},r),t),zt.stringify(r)}(a[1]||"",h);return a[0]+"?"+c}({sdkVersion:"2.10.2",protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:r}=e;await this.messages.set(t,r)}async shouldIgnoreMessageEvent(e){const{topic:t,message:r}=e;if(!r||0===r.length)return this.logger.debug(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const i=this.messages.has(t,r);return i&&this.logger.debug(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Ui(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:r,message:i,publishedAt:n}=t.data,s={topic:r,message:i,publishedAt:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(((e,t)=>{for(var r in t||(t={}))po.call(t,r)&&yo(e,r,t[r]);if(fo)for(var r of fo(t))go.call(t,r)&&yo(e,r,t[r]);return e})({type:"event",event:t.id},s)),this.events.emit(t.id,s),await this.acknowledgePayload(e),await this.onMessageEvent(s)}else ki(e)&&this.events.emit(Is,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Ms,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=Ai(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Ns,this.onPayloadHandler),this.provider.off(Rs,this.onConnectHandler),this.provider.off(Ts,this.onDisconnectHandler),this.provider.off(Ls,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(xs,(()=>{this.restartTransport().catch((e=>this.logger.error(e)))}));let e=await di();!function(e){switch(fr()){case ar.browser:!function(e){!ur()&&lr()&&(window.addEventListener("online",(()=>e(!0))),window.addEventListener("offline",(()=>e(!1))))}(e);break;case ar.reactNative:!function(e){ur()&&typeof r.g<"u"&&null!=r.g&&r.g.NetInfo&&r.g?.NetInfo.addEventListener((t=>e(t?.isConnected)))}(e);case ar.node:}}((async t=>{this.initialized&&e!==t&&(e=t,t?await this.restartTransport().catch((e=>this.logger.error(e))):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch((e=>this.logger.error(e)))))}))}onProviderDisconnect(){this.events.emit(Os),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout((async()=>{await this.restartTransport().catch((e=>this.logger.error(e)))}),(0,j.toMiliseconds)(Cs)))}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise((e=>{const t=setInterval((()=>{this.connected&&(clearInterval(t),e())}),this.connectionStatusPollingInterval)}));await this.restartTransport()}}}var vo=Object.defineProperty,wo=Object.getOwnPropertySymbols,bo=Object.prototype.hasOwnProperty,_o=Object.prototype.propertyIsEnumerable,Eo=(e,t,r)=>t in e?vo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,So=(e,t)=>{for(var r in t||(t={}))bo.call(t,r)&&Eo(e,r,t[r]);if(wo)for(var r of wo(t))_o.call(t,r)&&Eo(e,r,t[r]);return e};class Mo extends A{constructor(e,t,r,i=ms,n=void 0){super(e,t,r,i),this.core=e,this.logger=t,this.name=r,this.map=new Map,this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ms,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>{this.getKey&&null!==e&&!Zr(e)?this.map.set(this.getKey(e),e):function(e){var t;return null==(t=e?.proposer)?void 0:t.publicKey}(e)?this.map.set(e.id,e):function(e){return e?.topic}(e)&&this.map.set(e.topic,e)})),this.cached=[],this.initialized=!0)},this.set=async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())},this.get=e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)),this.getAll=e=>(this.isInitialized(),e?this.values.filter((t=>Object.keys(e).every((r=>Fi()(t[r],e[r]))))):this.values),this.update=async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const r=So(So({},this.getData(e)),t);this.map.set(e,r),await this.persist()},this.delete=async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),await this.persist())},this.logger=(0,w.generateChildLogger)(t,this.name),this.storagePrefix=i,this.getKey=n}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:e}=Jr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Io{constructor(e,t){this.core=e,this.logger=t,this.name="pairing",this.version="0.3",this.events=new(y()),this.initialized=!1,this.storagePrefix=ms,this.ignoredPayloadTypes=[1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]},this.create=async()=>{this.isInitialized();const e=Wt(),t=await this.core.crypto.setSymKey(e),r=_r(j.FIVE_MINUTES),i={protocol:"irn"},n={topic:t,expiry:r,relay:i,active:!1},s=function(e){return`${e.protocol}:${e.topic}@${e.version}?`+zt.stringify(((e,t)=>{for(var r in t||(t={}))Pr.call(t,r)&&Rr(e,r,t[r]);if(xr)for(var r of xr(t))Nr.call(t,r)&&Rr(e,r,t[r]);return e})({symKey:e.symKey},function(e,t="-"){const r={};return Object.keys(e).forEach((i=>{const n="relay"+t+i;e[i]&&(r[n]=e[i])})),r}(e.relay)))}({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:e,relay:i});return await this.pairings.set(t,n),await this.core.relayer.subscribe(t),this.core.expirer.set(t,r),{topic:t,uri:s}},this.pair=async e=>{this.isInitialized(),this.isValidPair(e);const{topic:t,symKey:r,relay:i}=function(e){const t=e.indexOf(":"),r=-1!==e.indexOf("?")?e.indexOf("?"):void 0,i=e.substring(0,t),n=e.substring(t+1,r).split("@"),s=typeof r<"u"?e.substring(r):"",o=zt.parse(s);return{protocol:i,topic:Lr(n[0]),version:parseInt(n[1],10),symKey:o.symKey,relay:Tr(o)}}(e.uri);let n;if(this.pairings.keys.includes(t)&&(n=this.pairings.get(t),n.active))throw new Error(`Pairing already exists: ${t}. Please try again with a new connection URI.`);this.core.crypto.keychain.has(t)||(await this.core.crypto.setSymKey(r,t),await this.core.relayer.subscribe(t,{relay:i}));const s=_r(j.FIVE_MINUTES),o={topic:t,relay:i,expiry:s,active:!1};return await this.pairings.set(t,o),this.core.expirer.set(t,s),e.activatePairing&&await this.activate({topic:t}),this.events.emit(zs,o),o},this.activate=async({topic:e})=>{this.isInitialized();const t=_r(j.THIRTY_DAYS);await this.pairings.update(e,{active:!0,expiry:t}),this.core.expirer.set(e,t)},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:r,resolve:i,reject:n}=mr();this.events.once(Sr("pairing_ping",e),(({error:e})=>{e?n(e):i()})),await r()}},this.updateExpiry=async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})},this.updateMetadata=async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",Yr("USER_DISCONNECTED")),await this.deletePairing(t))},this.sendRequest=async(e,t,r)=>{const i=Ii(t,r),n=await this.core.crypto.encode(e,i),s=Ds[t].req;return this.core.history.set(e,i),this.core.relayer.publish(e,n,s),i.id},this.sendResult=async(e,t,r)=>{const i=Ai(e,r),n=await this.core.crypto.encode(t,i),s=await this.core.history.get(t,e),o=Ds[s.request.method].res;await this.core.relayer.publish(t,n,o),await this.core.history.resolve(i)},this.sendError=async(e,t,r)=>{const i=Oi(e,r),n=await this.core.crypto.encode(t,i),s=await this.core.history.get(t,e),o=Ds[s.request.method]?Ds[s.request.method].res:Ds.unregistered_method.res;await this.core.relayer.publish(t,n,o),await this.core.history.resolve(i)},this.deletePairing=async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Yr("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])},this.cleanup=async()=>{const e=this.pairings.getAll().filter((e=>Er(e.expiry)));await Promise.all(e.map((e=>this.deletePairing(e.topic))))},this.onRelayEventRequest=e=>{const{topic:t,payload:r}=e;switch(r.method){case"wc_pairingPing":return this.onPairingPingRequest(t,r);case"wc_pairingDelete":return this.onPairingDeleteRequest(t,r);default:return this.onUnknownRpcMethodRequest(t,r)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:r}=e,i=(await this.core.history.get(t,r.id)).request.method;return"wc_pairingPing"===i?this.onPairingPingResponse(t,r):this.onUnknownRpcMethodResponse(i)},this.onPairingPingRequest=async(e,t)=>{const{id:r}=t;try{this.isValidPing({topic:e}),await this.sendResult(r,e,!0),this.events.emit("pairing_ping",{id:r,topic:e})}catch(t){await this.sendError(r,e,t),this.logger.error(t)}},this.onPairingPingResponse=(e,t)=>{const{id:r}=t;setTimeout((()=>{ji(t)?this.events.emit(Sr("pairing_ping",r),{}):qi(t)&&this.events.emit(Sr("pairing_ping",r),{error:t.error})}),500)},this.onPairingDeleteRequest=async(e,t)=>{const{id:r}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit("pairing_delete",{id:r,topic:e})}catch(t){await this.sendError(r,e,t),this.logger.error(t)}},this.onUnknownRpcMethodRequest=async(e,t)=>{const{id:r,method:i}=t;try{if(this.registeredMethods.includes(i))return;const t=Yr("WC_METHOD_UNSUPPORTED",i);await this.sendError(r,e,t),this.logger.error(t)}catch(t){await this.sendError(r,e,t),this.logger.error(t)}},this.onUnknownRpcMethodResponse=e=>{this.registeredMethods.includes(e)||this.logger.error(Yr("WC_METHOD_UNSUPPORTED",e))},this.isValidPair=e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`pair() params: ${e}`);throw new Error(t)}if(!ii(e.uri)){const{message:t}=Jr("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw new Error(t)}},this.isValidPing=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidDisconnect=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidPairingTopic=async e=>{if(!ei(e,!1)){const{message:t}=Jr("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=Jr("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Er(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=Jr("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}},this.core=e,this.logger=(0,w.generateChildLogger)(t,this.name),this.pairings=new Mo(this.core,this.logger,this.name,this.storagePrefix)}get context(){return(0,w.getLoggerContext)(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ms,(async e=>{const{topic:t,message:r}=e;if(!this.pairings.keys.includes(t)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))return;const i=await this.core.crypto.decode(t,r);try{Ui(i)?(this.core.history.set(t,i),this.onRelayEventRequest({topic:t,payload:i})):ki(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:t,payload:i}),this.core.history.delete(t,i.id))}catch(e){this.logger.error(e)}}))}registerExpirerEvents(){this.core.expirer.on(Hs,(async e=>{const{topic:t}=br(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit("pairing_expire",{topic:t}))}))}}class Ao extends E{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new g.EventEmitter,this.name="history",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ms,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.records.set(e.id,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(e,t,r)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:r}),this.records.has(t.id))return;const i={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:r,expiry:_r(j.THIRTY_DAYS)};this.records.set(i.id,i),this.events.emit($s,i)},this.resolve=async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=qi(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.events.emit(Bs,t))},this.get=async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)),this.delete=(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach((r=>{if(r.topic===e){if(typeof t<"u"&&r.id!==t)return;this.records.delete(r.id),this.events.emit(Ks,r)}}))},this.exists=async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=(0,w.generateChildLogger)(t,this.name)}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach((t=>{if(typeof t.response<"u")return;const r={topic:t.topic,request:Ii(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(r)})),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit("history_sync")}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=Jr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on($s,(e=>{const t=$s;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.events.on(Bs,(e=>{const t=Bs;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.events.on(Ks,(e=>{const t=Ks;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.core.heartbeat.on(v.HEARTBEAT_EVENTS.pulse,(()=>{this.cleanup()}))}cleanup(){try{this.records.forEach((e=>{(0,j.toMiliseconds)(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))}))}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Oo extends x{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new g.EventEmitter,this.name="expirer",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ms,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.expirations.set(e.target,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}},this.set=(e,t)=>{this.isInitialized();const r=this.formatTarget(e),i={target:r,expiry:t};this.expirations.set(r,i),this.checkExpiry(r,i),this.events.emit(Fs,{target:r,expiration:i})},this.get=e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)},this.del=e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),r=this.getExpiration(t);this.expirations.delete(t),this.events.emit(Vs,{target:t,expiration:r})}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=(0,w.generateChildLogger)(t,this.name)}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if("string"==typeof e)return function(e){return wr("topic",e)}(e);if("number"==typeof e)return function(e){return wr("id",e)}(e);const{message:t}=Jr("UNKNOWN_TYPE","Target type: "+typeof e);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit("expirer_sync")}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=Jr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:r}=t;(0,j.toMiliseconds)(r)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Hs,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach(((e,t)=>this.checkExpiry(t,e)))}registerEventListeners(){this.core.heartbeat.on(v.HEARTBEAT_EVENTS.pulse,(()=>this.checkExpirations())),this.events.on(Fs,(e=>{const t=Fs;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(Hs,(e=>{const t=Hs;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(Vs,(e=>{const t=Vs;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class xo extends P{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.name=Ws,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async()=>{if(this.verifyDisabled||ur()||!lr())return;const e=Gs;this.verifyUrl!==e&&this.removeIframe(),this.verifyUrl=e;try{await this.createIframe()}catch(e){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(e)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Js;try{await this.createIframe()}catch(e){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(e),this.verifyDisabled=!0}}},this.register=async e=>{this.initialized?this.sendPost(e.attestationId):(this.addToQueue(e.attestationId),await this.init())},this.resolve=async e=>{if(this.isDevEnv)return"";const t=e?.verifyUrl||Gs;let r;try{r=await this.fetchAttestation(e.attestationId,t)}catch(i){this.logger.info(`failed to resolve attestation: ${e.attestationId} from url: ${t}`),this.logger.info(i),r=await this.fetchAttestation(e.attestationId,Js)}return r},this.fetchAttestation=async(e,t)=>{this.logger.info(`resolving attestation: ${e} from url: ${t}`);const r=this.startAbortTimer(2*j.ONE_SECOND),i=await fetch(`${t}/attestation/${e}`,{signal:this.abortController.signal});return clearTimeout(r),200===i.status?await i.json():void 0},this.addToQueue=e=>{this.queue.push(e)},this.processQueue=()=>{0!==this.queue.length&&(this.queue.forEach((e=>this.sendPost(e))),this.queue=[])},this.sendPost=e=>{var t;try{if(!this.iframe)return;null==(t=this.iframe.contentWindow)||t.postMessage(e,"*"),this.logger.info(`postMessage sent: ${e} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let e;const t=r=>{"verify_ready"===r.data&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",t),e())};await Promise.race([new Promise((r=>{if(document.getElementById(Ws))return r();window.addEventListener("message",t);const i=document.createElement("iframe");i.id=Ws,i.src=`${this.verifyUrl}/${this.projectId}`,i.style.display="none",document.body.append(i),this.iframe=i,e=r})),new Promise(((e,r)=>setTimeout((()=>{window.removeEventListener("message",t),r("verify iframe load timeout")}),(0,j.toMiliseconds)(j.FIVE_SECONDS))))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.logger=(0,w.generateChildLogger)(t,this.name),this.verifyUrl=Gs,this.abortController=new AbortController,this.isDevEnv=cr()&&process.env.IS_VITEST}get context(){return(0,w.getLoggerContext)(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout((()=>this.abortController.abort()),(0,j.toMiliseconds)(e))}}var Po=Object.defineProperty,No=Object.getOwnPropertySymbols,Ro=Object.prototype.hasOwnProperty,To=Object.prototype.propertyIsEnumerable,Lo=(e,t,r)=>t in e?Po(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Co=(e,t)=>{for(var r in t||(t={}))Ro.call(t,r)&&Lo(e,r,t[r]);if(No)for(var r of No(t))To.call(t,r)&&Lo(e,r,t[r]);return e};class Uo extends _{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=ys,this.events=new g.EventEmitter,this.initialized=!1,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Es,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const t=typeof e?.logger<"u"&&"string"!=typeof e?.logger?e.logger:(0,w.pino)((0,w.getDefaultLoggerOptions)({level:e?.logger||"error"}));this.logger=(0,w.generateChildLogger)(t,this.name),this.heartbeat=new v.HeartBeat,this.crypto=new Xs(this,this.logger,e?.keychain),this.history=new Ao(this,this.logger),this.expirer=new Oo(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new m.ZP(Co(Co({},vs),e?.storageOptions)),this.relayer=new mo({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Io(this,this.logger),this.verify=new xo(this.projectId||"",this.logger)}static async init(e){const t=new Uo(e);await t.initialize();const r=await t.crypto.getClientId();return await t.storage.setItem("WALLETCONNECT_CLIENT_ID",r),t}get context(){return(0,w.getLoggerContext)(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const ko=Uo;let jo=!1,qo=!1;const Do={debug:1,default:2,info:2,warning:3,error:4,off:5};let zo=Do.default,$o=null;const Bo=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw new Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw new Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(e){return e.message}return null}();var Ko,Fo;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(Ko||(Ko={})),function(e){e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"}(Fo||(Fo={}));const Vo="0123456789abcdef";class Ho{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==Do[r]&&this.throwArgumentError("invalid log level name","logLevel",e),zo>Do[r]||console.log.apply(console,t)}debug(...e){this._log(Ho.levels.DEBUG,e)}info(...e){this._log(Ho.levels.INFO,e)}warn(...e){this._log(Ho.levels.WARNING,e)}makeError(e,t,r){if(qo)return this.makeError("censored error",t,{});t||(t=Ho.errors.UNKNOWN_ERROR),r||(r={});const i=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e>4],r+=Vo[15&t[e]];i.push(e+"=Uint8Array(0x"+r+")")}else i.push(e+"="+JSON.stringify(t))}catch(t){i.push(e+"="+JSON.stringify(r[e].toString()))}})),i.push(`code=${t}`),i.push(`version=${this.version}`);const n=e;let s="";switch(t){case Fo.NUMERIC_FAULT:{s="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":s+="-"+t;break;case"negative-power":case"negative-width":s+="-unsupported";break;case"unbound-bitwise-result":s+="-unbound-result"}break}case Fo.CALL_EXCEPTION:case Fo.INSUFFICIENT_FUNDS:case Fo.MISSING_NEW:case Fo.NONCE_EXPIRED:case Fo.REPLACEMENT_UNDERPRICED:case Fo.TRANSACTION_REPLACED:case Fo.UNPREDICTABLE_GAS_LIMIT:s=t}s&&(e+=" [ See: https://links.ethers.org/v5-errors-"+s+" ]"),i.length&&(e+=" ("+i.join(", ")+")");const o=new Error(e);return o.reason=n,o.code=t,Object.keys(r).forEach((function(e){o[e]=r[e]})),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,Ho.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,i){e||this.throwError(t,r,i)}assertArgument(e,t,r,i){e||this.throwArgumentError(t,r,i)}checkNormalize(e){null==e&&(e="platform missing String.prototype.normalize"),Bo&&this.throwError("platform missing String.prototype.normalize",Ho.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Bo})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,Ho.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,Ho.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",et&&this.throwError("too many arguments"+r,Ho.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",Ho.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",Ho.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",Ho.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return $o||($o=new Ho("logger/5.7.0")),$o}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",Ho.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),jo){if(!e)return;this.globalLogger().throwError("error censorship permanent",Ho.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}qo=!!e,jo=!!t}static setLogLevel(e){const t=Do[e.toLowerCase()];null!=t?zo=t:Ho.globalLogger().warn("invalid log level - "+e)}static from(e){return new Ho(e)}}Ho.errors=Fo,Ho.levels=Ko;const Wo=new Ho("bytes/5.7.0");function Go(e){return!!e.toHexString}function Jo(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return Jo(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function Yo(e){return"number"==typeof e&&e==e&&e%1==0}function Xo(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!Yo(e.length)||e.length<0)return!1;for(let t=0;t=256)return!1}return!0}function Qo(e,t){if(t||(t={}),"number"==typeof e){Wo.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),Jo(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),Go(e)&&(e=e.toHexString()),Zo(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":Wo.throwArgumentError("hex data is odd-length","value",e));const i=[];for(let e=0;e>4]+ea[15&i]}return t}return Wo.throwArgumentError("invalid hexlify value","value",e)}function ra(e,t,r){return"string"!=typeof e?e=ta(e):(!Zo(e)||e.length%2)&&Wo.throwArgumentError("invalid hexData","value",e),t=2+2*t,null!=r?"0x"+e.substring(t,2+2*r):"0x"+e.substring(t)}function ia(e,t){for("string"!=typeof e?e=ta(e):Zo(e)||Wo.throwArgumentError("invalid hex string","value",e),e.length>2*t+2&&Wo.throwArgumentError("value out of range","value",arguments[1]);e.length<2*t+2;)e="0x0"+e.substring(2);return e}function na(e){const t={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(Zo(r=e)&&!(r.length%2)||Xo(r)){let r=Qo(e);64===r.length?(t.v=27+(r[32]>>7),r[32]&=127,t.r=ta(r.slice(0,32)),t.s=ta(r.slice(32,64))):65===r.length?(t.r=ta(r.slice(0,32)),t.s=ta(r.slice(32,64)),t.v=r[64]):Wo.throwArgumentError("invalid signature string","signature",e),t.v<27&&(0===t.v||1===t.v?t.v+=27:Wo.throwArgumentError("signature invalid v byte","signature",e)),t.recoveryParam=1-t.v%2,t.recoveryParam&&(r[32]|=128),t._vs=ta(r.slice(32,64))}else{if(t.r=e.r,t.s=e.s,t.v=e.v,t.recoveryParam=e.recoveryParam,t._vs=e._vs,null!=t._vs){const r=function(e,t){(e=Qo(e)).length>t&&Wo.throwArgumentError("value out of range","value",arguments[0]);const r=new Uint8Array(t);return r.set(e,t-e.length),Jo(r)}(Qo(t._vs),32);t._vs=ta(r);const i=r[0]>=128?1:0;null==t.recoveryParam?t.recoveryParam=i:t.recoveryParam!==i&&Wo.throwArgumentError("signature recoveryParam mismatch _vs","signature",e),r[0]&=127;const n=ta(r);null==t.s?t.s=n:t.s!==n&&Wo.throwArgumentError("signature v mismatch _vs","signature",e)}if(null==t.recoveryParam)null==t.v?Wo.throwArgumentError("signature missing v and recoveryParam","signature",e):0===t.v||1===t.v?t.recoveryParam=t.v:t.recoveryParam=1-t.v%2;else if(null==t.v)t.v=27+t.recoveryParam;else{const r=0===t.v||1===t.v?t.v:1-t.v%2;t.recoveryParam!==r&&Wo.throwArgumentError("signature recoveryParam mismatch v","signature",e)}null!=t.r&&Zo(t.r)?t.r=ia(t.r,32):Wo.throwArgumentError("signature missing or invalid r","signature",e),null!=t.s&&Zo(t.s)?t.s=ia(t.s,32):Wo.throwArgumentError("signature missing or invalid s","signature",e);const r=Qo(t.s);r[0]>=128&&Wo.throwArgumentError("signature s out of range","signature",e),t.recoveryParam&&(r[0]|=128);const i=ta(r);t._vs&&(Zo(t._vs)||Wo.throwArgumentError("signature invalid _vs","signature",e),t._vs=ia(t._vs,32)),null==t._vs?t._vs=i:t._vs!==i&&Wo.throwArgumentError("signature _vs mismatch v and s","signature",e)}var r;return t.yParityAndS=t._vs,t.compact=t.r+t.yParityAndS.substring(2),t}var sa=r(1094),oa=r.n(sa);function aa(e){return"0x"+oa().keccak_256(Qo(e))}const ha=new Ho("strings/5.7.0");var ca,ua;function la(e,t,r,i,n){if(e===ua.BAD_PREFIX||e===ua.UNEXPECTED_CONTINUE){let e=0;for(let i=t+1;i>6==2;i++)e++;return e}return e===ua.OVERRUN?r.length-t-1:0}function fa(e,t=ca.current){t!=ca.current&&(ha.checkNormalize(),e=e.normalize(t));let r=[];for(let t=0;t>6|192),r.push(63&i|128);else if(55296==(64512&i)){t++;const n=e.charCodeAt(t);if(t>=e.length||56320!=(64512&n))throw new Error("invalid utf-8 string");const s=65536+((1023&i)<<10)+(1023&n);r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(63&s|128)}else r.push(i>>12|224),r.push(i>>6&63|128),r.push(63&i|128)}return Qo(r)}!function(e){e.current="",e.NFC="NFC",e.NFD="NFD",e.NFKC="NFKC",e.NFKD="NFKD"}(ca||(ca={})),function(e){e.UNEXPECTED_CONTINUE="unexpected continuation byte",e.BAD_PREFIX="bad codepoint prefix",e.OVERRUN="string overrun",e.MISSING_CONTINUE="missing continuation byte",e.OUT_OF_RANGE="out of UTF-8 range",e.UTF16_SURROGATE="UTF-16 surrogate",e.OVERLONG="overlong representation"}(ua||(ua={})),Object.freeze({error:function(e,t,r,i,n){return ha.throwArgumentError(`invalid codepoint at offset ${t}; ${e}`,"bytes",r)},ignore:la,replace:function(e,t,r,i,n){return e===ua.OVERLONG?(i.push(n),0):(i.push(65533),la(e,t,r))}});const da="Ethereum Signed Message:\n";function pa(e){return"string"==typeof e&&(e=fa(e)),aa(function(e){const t=e.map((e=>Qo(e))),r=t.reduce(((e,t)=>e+t.length),0),i=new Uint8Array(r);return t.reduce(((e,t)=>(i.set(t,e),e+t.length)),0),Jo(i)}([fa(da),fa(String(e.length)),e]))}var ga=r(3550),ya=r.n(ga),ma=ya().BN;new Ho("bignumber/5.7.0");const va=new Ho("address/5.7.0");function wa(e){Zo(e,20)||va.throwArgumentError("invalid address","address",e);const t=(e=e.toLowerCase()).substring(2).split(""),r=new Uint8Array(40);for(let e=0;e<40;e++)r[e]=t[e].charCodeAt(0);const i=Qo(aa(r));for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&(t[e]=t[e].toUpperCase()),(15&i[e>>1])>=8&&(t[e+1]=t[e+1].toUpperCase());return"0x"+t.join("")}const ba={};for(let e=0;e<10;e++)ba[String(e)]=String(e);for(let e=0;e<26;e++)ba[String.fromCharCode(65+e)]=String(10+e);const _a=Math.floor((Ea=9007199254740991,Math.log10?Math.log10(Ea):Math.log(Ea)/Math.LN10));var Ea;function Sa(e){let t=null;if("string"!=typeof e&&va.throwArgumentError("invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/))"0x"!==e.substring(0,2)&&(e="0x"+e),t=wa(e),e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&t!==e&&va.throwArgumentError("bad address checksum","address",e);else if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(e.substring(2,4)!==function(e){let t=(e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00").split("").map((e=>ba[e])).join("");for(;t.length>=_a;){let e=t.substring(0,_a);t=parseInt(e,10)%97+t.substring(e.length)}let r=String(98-parseInt(t,10)%97);for(;r.length<2;)r="0"+r;return r}(e)&&va.throwArgumentError("bad icap checksum","address",e),r=e.substring(4),t=new ma(r,36).toString(16);t.length<40;)t="0"+t;t=wa("0x"+t)}else va.throwArgumentError("invalid address","address",e);var r;return t}var Ma=r(3715),Ia=r.n(Ma);function Aa(e,t,r){return e(r={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&r.path)}},r.exports),r.exports}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r.g?r.g:"undefined"!=typeof self&&self;var Oa=xa;function xa(e,t){if(!e)throw new Error(t||"Assertion failed")}xa.equal=function(e,t,r){if(e!=t)throw new Error(r||"Assertion failed: "+e+" != "+t)};var Pa=Aa((function(e,t){var r=t;function i(e){return 1===e.length?"0"+e:e}function n(e){for(var t="",r=0;r>8,o=255&n;s?r.push(s,o):r.push(o)}return r},r.zero2=i,r.toHex=n,r.encode=function(e,t){return"hex"===t?n(e):e}})),Na=Aa((function(e,t){var r=t;r.assert=Oa,r.toArray=Pa.toArray,r.zero2=Pa.zero2,r.toHex=Pa.toHex,r.encode=Pa.encode,r.getNAF=function(e,t,r){var i=new Array(Math.max(e.bitLength(),r)+1);i.fill(0);for(var n=1<(n>>1)-1?(n>>1)-h:h,s.isubn(a)):a=0,i[o]=a,s.iushrn(1)}return i},r.getJSF=function(e,t){var r=[[],[]];e=e.clone(),t=t.clone();for(var i,n=0,s=0;e.cmpn(-n)>0||t.cmpn(-s)>0;){var o,a,h=e.andln(3)+n&3,c=t.andln(3)+s&3;3===h&&(h=-1),3===c&&(c=-1),o=0==(1&h)?0:3!=(i=e.andln(7)+n&7)&&5!==i||2!==c?h:-h,r[0].push(o),a=0==(1&c)?0:3!=(i=t.andln(7)+s&7)&&5!==i||2!==h?c:-c,r[1].push(a),2*n===o+1&&(n=1-n),2*s===a+1&&(s=1-s),e.iushrn(1),t.iushrn(1)}return r},r.cachedProperty=function(e,t,r){var i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}},r.parseBytes=function(e){return"string"==typeof e?r.toArray(e,"hex"):e},r.intFromLE=function(e){return new(ya())(e,"hex","le")}})),Ra=Na.getNAF,Ta=Na.getJSF,La=Na.assert;function Ca(e,t){this.type=e,this.p=new(ya())(t.p,16),this.red=t.prime?ya().red(t.prime):ya().mont(this.p),this.zero=new(ya())(0).toRed(this.red),this.one=new(ya())(1).toRed(this.red),this.two=new(ya())(2).toRed(this.red),this.n=t.n&&new(ya())(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Ua=Ca;function ka(e,t){this.curve=e,this.type=t,this.precomputed=null}Ca.prototype.point=function(){throw new Error("Not implemented")},Ca.prototype.validate=function(){throw new Error("Not implemented")},Ca.prototype._fixedNafMul=function(e,t){La(e.precomputed);var r=e._getDoubles(),i=Ra(t,1,this._bitLength),n=(1<=s;h--)o=(o<<1)+i[h];a.push(o)}for(var c=this.jpoint(null,null,null),u=this.jpoint(null,null,null),l=n;l>0;l--){for(s=0;s=0;a--){for(var h=0;a>=0&&0===s[a];a--)h++;if(a>=0&&h++,o=o.dblp(h),a<0)break;var c=s[a];La(0!==c),o="affine"===e.type?c>0?o.mixedAdd(n[c-1>>1]):o.mixedAdd(n[-c-1>>1].neg()):c>0?o.add(n[c-1>>1]):o.add(n[-c-1>>1].neg())}return"affine"===e.type?o.toP():o},Ca.prototype._wnafMulAdd=function(e,t,r,i,n){var s,o,a,h=this._wnafT1,c=this._wnafT2,u=this._wnafT3,l=0;for(s=0;s=1;s-=2){var d=s-1,p=s;if(1===h[d]&&1===h[p]){var g=[t[d],null,null,t[p]];0===t[d].y.cmp(t[p].y)?(g[1]=t[d].add(t[p]),g[2]=t[d].toJ().mixedAdd(t[p].neg())):0===t[d].y.cmp(t[p].y.redNeg())?(g[1]=t[d].toJ().mixedAdd(t[p]),g[2]=t[d].add(t[p].neg())):(g[1]=t[d].toJ().mixedAdd(t[p]),g[2]=t[d].toJ().mixedAdd(t[p].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],m=Ta(r[d],r[p]);for(l=Math.max(m[0].length,l),u[d]=new Array(l),u[p]=new Array(l),o=0;o=0;s--){for(var E=0;s>=0;){var S=!0;for(o=0;o=0&&E++,b=b.dblp(E),s<0)break;for(o=0;o0?a=c[o][M-1>>1]:M<0&&(a=c[o][-M-1>>1].neg()),b="affine"===a.type?b.mixedAdd(a):b.add(a))}}for(s=0;s=Math.ceil((e.bitLength()+1)/t.step)},ka.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],i=this,n=0;n=0&&(s=t,o=r),i.negative&&(i=i.neg(),n=n.neg()),s.negative&&(s=s.neg(),o=o.neg()),[{a:i,b:n},{a:s,b:o}]},Da.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),s=r.b.neg().mul(e).divRound(this.n),o=n.mul(r.a),a=s.mul(i.a),h=n.mul(r.b),c=s.mul(i.b);return{k1:e.sub(o).sub(a),k2:h.add(c).neg()}},Da.prototype.pointFromX=function(e,t){(e=new(ya())(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),i=r.redSqrt();if(0!==i.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var n=i.fromRed().isOdd();return(t&&!n||!t&&n)&&(i=i.redNeg()),this.point(e,i)},Da.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)},Da.prototype._endoWnafMulAdd=function(e,t,r){for(var i=this._endoWnafT1,n=this._endoWnafT2,s=0;s":""},$a.prototype.isInfinity=function(){return this.inf},$a.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),i=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,i)},$a.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),i=e.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(i),s=n.redSqr().redISub(this.x.redAdd(this.x)),o=n.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},$a.prototype.getX=function(){return this.x.fromRed()},$a.prototype.getY=function(){return this.y.fromRed()},$a.prototype.mul=function(e){return e=new(ya())(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},$a.prototype.mulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n):this.curve._wnafMulAdd(1,i,n,2)},$a.prototype.jmulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n,!0):this.curve._wnafMulAdd(1,i,n,2,!0)},$a.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},$a.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,i=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(i)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(i)}}}return t},$a.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},ja(Ba,Ua.BasePoint),Da.prototype.jpoint=function(e,t,r){return new Ba(this,e,t,r)},Ba.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),i=this.y.redMul(t).redMul(e);return this.curve.point(r,i)},Ba.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Ba.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),s=this.y.redMul(t.redMul(e.z)),o=e.y.redMul(r.redMul(this.z)),a=i.redSub(n),h=s.redSub(o);if(0===a.cmpn(0))return 0!==h.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=a.redSqr(),u=c.redMul(a),l=i.redMul(c),f=h.redSqr().redIAdd(u).redISub(l).redISub(l),d=h.redMul(l.redISub(f)).redISub(s.redMul(u)),p=this.z.redMul(e.z).redMul(a);return this.curve.jpoint(f,d,p)},Ba.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,s=e.y.redMul(t).redMul(this.z),o=r.redSub(i),a=n.redSub(s);if(0===o.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=o.redSqr(),c=h.redMul(o),u=r.redMul(h),l=a.redSqr().redIAdd(c).redISub(u).redISub(u),f=a.redMul(u.redISub(l)).redISub(n.redMul(c)),d=this.z.redMul(o);return this.curve.jpoint(l,f,d)},Ba.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var r=this;for(t=0;t=0)return!1;if(r.redIAdd(n),0===this.x.cmp(r))return!0}},Ba.prototype.inspect=function(){return this.isInfinity()?"":""},Ba.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var Ka=Aa((function(e,t){var r=t;r.base=Ua,r.short=za,r.mont=null,r.edwards=null})),Fa=Aa((function(e,t){var r,i=t,n=Na.assert;function s(e){"short"===e.type?this.curve=new Ka.short(e):"edwards"===e.type?this.curve=new Ka.edwards(e):this.curve=new Ka.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,n(this.g.validate(),"Invalid curve"),n(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function o(e,t){Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get:function(){var r=new s(t);return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:r}),r}})}i.PresetCurve=s,o("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:Ia().sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),o("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:Ia().sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),o("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:Ia().sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),o("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:Ia().sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),o("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:Ia().sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),o("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Ia().sha256,gRed:!1,g:["9"]}),o("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Ia().sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{r=null.crash()}catch(e){r=void 0}o("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:Ia().sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",r]})}));function Va(e){if(!(this instanceof Va))return new Va(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=Pa.toArray(e.entropy,e.entropyEnc||"hex"),r=Pa.toArray(e.nonce,e.nonceEnc||"hex"),i=Pa.toArray(e.pers,e.persEnc||"hex");Oa(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,i)}var Ha=Va;Va.prototype._init=function(e,t,r){var i=e.concat(t).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var n=0;n=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},Va.prototype.generate=function(e,t,r,i){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(i=r,r=t,t=null),r&&(r=Pa.toArray(r,i||"hex"),this._update(r));for(var n=[];n.length"};var Ya=Na.assert;function Xa(e,t){if(e instanceof Xa)return e;this._importDER(e,t)||(Ya(e.r&&e.s,"Signature without r or s"),this.r=new(ya())(e.r,16),this.s=new(ya())(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}var Qa=Xa;function Za(){this.place=0}function eh(e,t){var r=e[t.place++];if(!(128&r))return r;var i=15&r;if(0===i||i>4)return!1;for(var n=0,s=0,o=t.place;s>>=0;return!(n<=127)&&(t.place=o,n)}function th(e){for(var t=0,r=e.length-1;!e[t]&&!(128&e[t+1])&&t>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}Xa.prototype._importDER=function(e,t){e=Na.toArray(e,t);var r=new Za;if(48!==e[r.place++])return!1;var i=eh(e,r);if(!1===i)return!1;if(i+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var n=eh(e,r);if(!1===n)return!1;var s=e.slice(r.place,n+r.place);if(r.place+=n,2!==e[r.place++])return!1;var o=eh(e,r);if(!1===o)return!1;if(e.length!==o+r.place)return!1;var a=e.slice(r.place,o+r.place);if(0===s[0]){if(!(128&s[1]))return!1;s=s.slice(1)}if(0===a[0]){if(!(128&a[1]))return!1;a=a.slice(1)}return this.r=new(ya())(s),this.s=new(ya())(a),this.recoveryParam=null,!0},Xa.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=th(t),r=th(r);!(r[0]||128&r[1]);)r=r.slice(1);var i=[2];rh(i,t.length),(i=i.concat(t)).push(2),rh(i,r.length);var n=i.concat(r),s=[48];return rh(s,n.length),s=s.concat(n),Na.encode(s,e)};var ih=function(){throw new Error("unsupported")},nh=Na.assert;function sh(e){if(!(this instanceof sh))return new sh(e);"string"==typeof e&&(nh(Object.prototype.hasOwnProperty.call(Fa,e),"Unknown curve "+e),e=Fa[e]),e instanceof Fa.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}var oh=sh;sh.prototype.keyPair=function(e){return new Ja(this,e)},sh.prototype.keyFromPrivate=function(e,t){return Ja.fromPrivate(this,e,t)},sh.prototype.keyFromPublic=function(e,t){return Ja.fromPublic(this,e,t)},sh.prototype.genKeyPair=function(e){e||(e={});for(var t=new Ha({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||ih(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),i=this.n.sub(new(ya())(2));;){var n=new(ya())(t.generate(r));if(!(n.cmp(i)>0))return n.iaddn(1),this.keyFromPrivate(n)}},sh.prototype._truncateToN=function(e,t){var r=8*e.byteLength()-this.n.bitLength();return r>0&&(e=e.ushrn(r)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},sh.prototype.sign=function(e,t,r,i){"object"==typeof r&&(i=r,r=null),i||(i={}),t=this.keyFromPrivate(t,r),e=this._truncateToN(new(ya())(e,16));for(var n=this.n.byteLength(),s=t.getPrivate().toArray("be",n),o=e.toArray("be",n),a=new Ha({hash:this.hash,entropy:s,nonce:o,pers:i.pers,persEnc:i.persEnc||"utf8"}),h=this.n.sub(new(ya())(1)),c=0;;c++){var u=i.k?i.k(c):new(ya())(a.generate(this.n.byteLength()));if(!((u=this._truncateToN(u,!0)).cmpn(1)<=0||u.cmp(h)>=0)){var l=this.g.mul(u);if(!l.isInfinity()){var f=l.getX(),d=f.umod(this.n);if(0!==d.cmpn(0)){var p=u.invm(this.n).mul(d.mul(t.getPrivate()).iadd(e));if(0!==(p=p.umod(this.n)).cmpn(0)){var g=(l.getY().isOdd()?1:0)|(0!==f.cmp(d)?2:0);return i.canonical&&p.cmp(this.nh)>0&&(p=this.n.sub(p),g^=1),new Qa({r:d,s:p,recoveryParam:g})}}}}}},sh.prototype.verify=function(e,t,r,i){e=this._truncateToN(new(ya())(e,16)),r=this.keyFromPublic(r,i);var n=(t=new Qa(t,"hex")).r,s=t.s;if(n.cmpn(1)<0||n.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var o,a=s.invm(this.n),h=a.mul(e).umod(this.n),c=a.mul(n).umod(this.n);return this.curve._maxwellTrick?!(o=this.g.jmulAdd(h,r.getPublic(),c)).isInfinity()&&o.eqXToP(n):!(o=this.g.mulAdd(h,r.getPublic(),c)).isInfinity()&&0===o.getX().umod(this.n).cmp(n)},sh.prototype.recoverPubKey=function(e,t,r,i){nh((3&r)===r,"The recovery param is more than two bits"),t=new Qa(t,i);var n=this.n,s=new(ya())(e),o=t.r,a=t.s,h=1&r,c=r>>1;if(o.cmp(this.curve.p.umod(this.curve.n))>=0&&c)throw new Error("Unable to find sencond key candinate");o=c?this.curve.pointFromX(o.add(this.curve.n),h):this.curve.pointFromX(o,h);var u=t.r.invm(n),l=n.sub(s).mul(u).umod(n),f=a.mul(u).umod(n);return this.g.mulAdd(l,o,f)},sh.prototype.getKeyRecoveryParam=function(e,t,r,i){if(null!==(t=new Qa(t,i)).recoveryParam)return t.recoveryParam;for(var n=0;n<4;n++){var s;try{s=this.recoverPubKey(e,t,n)}catch(e){continue}if(s.eq(r))return n}throw new Error("Unable to find valid recovery factor")};var ah=Aa((function(e,t){var r=t;r.version="6.5.4",r.utils=Na,r.rand=function(){throw new Error("unsupported")},r.curve=Ka,r.curves=Fa,r.ec=oh,r.eddsa=null})).ec;function hh(e,t,r){Object.defineProperty(e,t,{enumerable:!0,value:r,writable:!1})}new Ho("properties/5.7.0");const ch=new Ho("signing-key/5.7.0");let uh=null;function lh(){return uh||(uh=new ah("secp256k1")),uh}class fh{constructor(e){hh(this,"curve","secp256k1"),hh(this,"privateKey",ta(e)),32!==function(e){if("string"!=typeof e)e=ta(e);else if(!Zo(e)||e.length%2)return null;return(e.length-2)/2}(this.privateKey)&&ch.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");const t=lh().keyFromPrivate(Qo(this.privateKey));hh(this,"publicKey","0x"+t.getPublic(!1,"hex")),hh(this,"compressedPublicKey","0x"+t.getPublic(!0,"hex")),hh(this,"_isSigningKey",!0)}_addPoint(e){const t=lh().keyFromPublic(Qo(this.publicKey)),r=lh().keyFromPublic(Qo(e));return"0x"+t.pub.add(r.pub).encodeCompressed("hex")}signDigest(e){const t=lh().keyFromPrivate(Qo(this.privateKey)),r=Qo(e);32!==r.length&&ch.throwArgumentError("bad digest length","digest",e);const i=t.sign(r,{canonical:!0});return na({recoveryParam:i.recoveryParam,r:ia("0x"+i.r.toString(16),32),s:ia("0x"+i.s.toString(16),32)})}computeSharedSecret(e){const t=lh().keyFromPrivate(Qo(this.privateKey)),r=lh().keyFromPublic(Qo(dh(e)));return ia("0x"+t.derive(r.getPublic()).toString(16),32)}static isSigningKey(e){return!(!e||!e._isSigningKey)}}function dh(e,t){const r=Qo(e);if(32===r.length){const e=new fh(r);return t?"0x"+lh().keyFromPrivate(r).getPublic(!0,"hex"):e.publicKey}return 33===r.length?t?ta(r):"0x"+lh().keyFromPublic(r).getPublic(!1,"hex"):65===r.length?t?"0x"+lh().keyFromPublic(r).getPublic(!0,"hex"):ta(r):ch.throwArgumentError("invalid public or private key","key","[REDACTED]")}var ph;new Ho("transactions/5.7.0"),function(e){e[e.legacy=0]="legacy",e[e.eip2930=1]="eip2930",e[e.eip1559=2]="eip1559"}(ph||(ph={}));var gh=r(204),yh=r.n(gh);class mh{constructor(e){this.client=e}}class vh{constructor(e){this.opts=e}}const wh={wc_authRequest:{req:{ttl:j.ONE_DAY,prompt:!0,tag:3e3},res:{ttl:j.ONE_DAY,prompt:!1,tag:3001}}},bh={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},_h="authClient",Eh="wc@1:auth:",Sh=`${Eh}:PUB_KEY`;function Mh(e){return e?.split(":")}function Ih(e){const t=e&&Mh(e);if(t)return t.pop()}async function Ah(e,t,r,i,n){switch(r.t){case"eip191":return function(e,t,r){return function(e,t){return function(e){return Sa(ra(aa(ra(dh(e),1)),12))}(function(e,t){const r=na(t),i={r:Qo(r.r),s:Qo(r.s)};return"0x"+lh().recoverPubKey(Qo(e),i,r.recoveryParam).encode("hex",!1)}(Qo(e),t))}(pa(t),r).toLowerCase()===e.toLowerCase()}(e,t,r.s);case"eip1271":return await async function(e,t,r,i,n){try{const s="0x1626ba7e",o="0000000000000000000000000000000000000000000000000000000000000040",a="0000000000000000000000000000000000000000000000000000000000000041",h=r.substring(2),c=s+pa(t).substring(2)+o+a+h,u=await yh()(`https://rpc.walletconnect.com/v1/?chainId=${i}&projectId=${n}`,{method:"POST",body:JSON.stringify({id:Date.now()+Math.floor(1e3*Math.random()),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:c},"latest"]})}),{result:l}=await u.json();return!!l&&l.slice(0,s.length).toLowerCase()===s.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}(e,t,r.s,i,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function Oh(e){return e.getAll().filter((e=>"requester"in e))}function xh(e,t){return Oh(e).find((e=>e.id===t))}var Ph=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i>>0,o=new Uint8Array(s);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var l=0,f=s-1;(0!==u||l>>0,o[f]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");n=l,t++}if(" "!==e[t]){for(var d=s-n;d!==s&&0===o[d];)d++;for(var p=new Uint8Array(i+(s-d)),g=i;d!==s;)p[g++]=o[d++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,i=0,n=0,s=t.length;n!==s&&0===t[n];)n++,r++;for(var o=(s-n)*u+1>>>0,c=new Uint8Array(o);n!==s;){for(var l=t[n],f=0,d=o-1;(0!==l||f>>0,c[d]=l%a>>>0,l=l/a>>>0;if(0!==l)throw new Error("Non-zero carry");i=f,n++}for(var p=o-i;p!==o&&0===c[p];)p++;for(var g=h.repeat(r);p{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class Rh{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Th{constructor(e,t,r){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Ch(this,e)}}class Lh{constructor(e){this.decoders=e}or(e){return Ch(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Ch=(e,t)=>new Lh({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Uh{constructor(e,t,r,i){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=i,this.encoder=new Rh(e,t,r),this.decoder=new Th(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const kh=({name:e,prefix:t,encode:r,decode:i})=>new Uh(e,t,r,i),jh=({prefix:e,name:t,alphabet:r})=>{const{encode:i,decode:n}=Ph(r,t);return kh({prefix:e,name:t,encode:i,decode:e=>Nh(n(e))})},qh=({name:e,prefix:t,bitsPerChar:r,alphabet:i})=>kh({prefix:t,name:e,encode:e=>((e,t,r)=>{const i="="===t[t.length-1],n=(1<r;)o-=r,s+=t[n&a>>o];if(o&&(s+=t[n&a<((e,t,r,i)=>{const n={};for(let e=0;e=8&&(a-=8,o[c++]=255&h>>a)}if(a>=r||255&h<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,i,r,e)}),Dh=kh({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var zh=Object.freeze({__proto__:null,identity:Dh});const $h=qh({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Bh=Object.freeze({__proto__:null,base2:$h});const Kh=qh({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Fh=Object.freeze({__proto__:null,base8:Kh});const Vh=jh({prefix:"9",name:"base10",alphabet:"0123456789"});var Hh=Object.freeze({__proto__:null,base10:Vh});const Wh=qh({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Gh=qh({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Jh=Object.freeze({__proto__:null,base16:Wh,base16upper:Gh});const Yh=qh({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xh=qh({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Qh=qh({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zh=qh({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ec=qh({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),tc=qh({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rc=qh({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ic=qh({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nc=qh({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var sc=Object.freeze({__proto__:null,base32:Yh,base32upper:Xh,base32pad:Qh,base32padupper:Zh,base32hex:ec,base32hexupper:tc,base32hexpad:rc,base32hexpadupper:ic,base32z:nc});const oc=jh({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ac=jh({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hc=Object.freeze({__proto__:null,base36:oc,base36upper:ac});const cc=jh({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),uc=jh({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lc=Object.freeze({__proto__:null,base58btc:cc,base58flickr:uc});const fc=qh({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dc=qh({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pc=qh({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gc=qh({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var yc=Object.freeze({__proto__:null,base64:fc,base64pad:dc,base64url:pc,base64urlpad:gc});const mc=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),vc=mc.reduce(((e,t,r)=>(e[r]=t,e)),[]),wc=mc.reduce(((e,t,r)=>(e[t.codePointAt(0)]=r,e)),[]),bc=kh({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+vc[t]),"")},decode:function(e){const t=[];for(const r of e){const e=wc[r.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}});var _c=Object.freeze({__proto__:null,base256emoji:bc}),Ec=128,Sc=-128,Mc=Math.pow(2,31),Ic=Math.pow(2,7),Ac=Math.pow(2,14),Oc=Math.pow(2,21),xc=Math.pow(2,28),Pc=Math.pow(2,35),Nc=Math.pow(2,42),Rc=Math.pow(2,49),Tc=Math.pow(2,56),Lc=Math.pow(2,63),Cc=function e(t,r,i){r=r||[];for(var n=i=i||0;t>=Mc;)r[i++]=255&t|Ec,t/=128;for(;t⪼)r[i++]=255&t|Ec,t>>>=7;return r[i]=0|t,e.bytes=i-n+1,r},Uc=function(e){return e(Cc(e,t,r),t),jc=e=>Uc(e),qc=(e,t)=>{const r=t.byteLength,i=jc(e),n=i+jc(r),s=new Uint8Array(n+r);return kc(e,s,0),kc(r,s,i),s.set(t,n),new Dc(e,r,t,s)};class Dc{constructor(e,t,r,i){this.code=e,this.size=t,this.digest=r,this.bytes=i}}const zc=({name:e,code:t,encode:r})=>new $c(e,t,r);class $c{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?qc(this.code,t):t.then((e=>qc(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Bc=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Kc=zc({name:"sha2-256",code:18,encode:Bc("SHA-256")}),Fc=zc({name:"sha2-512",code:19,encode:Bc("SHA-512")});Object.freeze({__proto__:null,sha256:Kc,sha512:Fc});const Vc=Nh,Hc={code:0,name:"identity",encode:Vc,digest:e=>qc(0,Vc(e))};Object.freeze({__proto__:null,identity:Hc}),new TextEncoder,new TextDecoder;const Wc={...zh,...Bh,...Fh,...Hh,...Jh,...sc,...hc,...lc,...yc,..._c};function Gc(e,t,r,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:i}}}const Jc=Gc("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Yc=Gc("ascii","a",(e=>{let t="a";for(let r=0;r{const t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?globalThis.Buffer.allocUnsafe(e):new Uint8Array(e)}((e=e.substring(1)).length);for(let r=0;rt in e?Zc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ou=(e,t)=>{for(var r in t||(t={}))iu.call(t,r)&&su(e,r,t[r]);if(ru)for(var r of ru(t))nu.call(t,r)&&su(e,r,t[r]);return e},au=(e,t)=>eu(e,tu(t));class hu extends mh{constructor(e){super(e),this.initialized=!1,this.name="authEngine",this.init=()=>{this.initialized||(this.registerRelayerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(wh)}),this.initialized=!0)},this.request=async(e,t)=>{if(this.isInitialized(),!function(e){const t=ii(e.aud),r=new RegExp(`${e.domain}`).test(e.aud),i=!!e.nonce,n=!e.type||"eip4361"===e.type,s=e.expiry;if(s&&!fi(s,bh)){const{message:e}=Jr("MISSING_OR_INVALID",`request() expiry: ${s}. Expiry must be a number (in seconds) between ${bh.min} and ${bh.max}`);throw new Error(e)}return!!(t&&r&&i&&n)}(e))throw new Error("Invalid request");if(null!=t&&t.topic)return await this.requestOnKnownPairing(t.topic,e);const{chainId:r,statement:i,aud:n,domain:s,nonce:o,type:a,exp:h,nbf:c}=e,{topic:u,uri:l}=await this.client.core.pairing.create();this.client.logger.info({message:"Generated new pairing",pairing:{topic:u,uri:l}});const f=await this.client.core.crypto.generateKeyPair(),d=Gt(f);await this.client.authKeys.set(Sh,{responseTopic:d,publicKey:f}),await this.client.pairingTopics.set(d,{topic:d,pairingTopic:u}),await this.client.core.relayer.subscribe(d),this.client.logger.info(`sending request to new pairing topic: ${u}`);const p=await this.sendRequest(u,"wc_authRequest",{payloadParams:{type:a??"eip4361",chainId:r,statement:i,aud:n,domain:s,version:"1",nonce:o,iat:(new Date).toISOString(),exp:h,nbf:c},requester:{publicKey:f,metadata:this.client.metadata}},{},e.expiry);return this.client.logger.info(`sent request to new pairing topic: ${u}`),{uri:l,id:p}},this.respond=async(e,t)=>{if(this.isInitialized(),!function(e,t){return!!xh(t,e.id)}(e,this.client.requests))throw new Error("Invalid response");const r=xh(this.client.requests,e.id);if(!r)throw new Error(`Could not find pending auth request with id ${e.id}`);const i=r.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),s=Gt(i),o={type:1,receiverPublicKey:i,senderPublicKey:n};if("error"in e)return void await this.sendError(r.id,s,e,o);const a={h:{t:"eip4361"},p:au(ou({},r.cacaoPayload),{iss:t}),s:e.signature};await this.sendResult(r.id,s,a,o),await this.client.core.pairing.activate({topic:r.pairingTopic}),await this.client.requests.update(r.id,ou({},a))},this.getPendingRequests=()=>Oh(this.client.requests),this.formatMessage=(e,t)=>{this.client.logger.debug(`formatMessage, cacao is: ${JSON.stringify(e)}`);const r=`${e.domain} wants you to sign in with your Ethereum account:`,i=Ih(t),n=e.statement,s=`URI: ${e.aud}`,o=`Version: ${e.version}`,a=`Chain ID: ${function(e){const t=e&&Mh(e);if(t)return t[3]}(t)}`,h=`Nonce: ${e.nonce}`,c=`Issued At: ${e.iat}`,u=e.exp?`Expiry: ${e.exp}`:void 0,l=e.resources&&e.resources.length>0?`Resources:\n${e.resources.map((e=>`- ${e}`)).join("\n")}`:void 0;return[r,i,"",n,"",s,o,a,h,c,u,l].filter((e=>null!=e)).join("\n")},this.setExpiry=async(e,t)=>{this.client.core.pairing.pairings.keys.includes(e)&&await this.client.core.pairing.updateExpiry({topic:e,expiry:t}),this.client.core.expirer.set(e,t)},this.sendRequest=async(e,t,r,i,n)=>{const s=Ii(t,r),o=await this.client.core.crypto.encode(e,s,i),a=wh[t].req;if(n&&(a.ttl=n),this.client.core.history.set(e,s),lr()){const e=Qc(JSON.stringify(s));this.client.core.verify.register({attestationId:e})}return await this.client.core.relayer.publish(e,o,au(ou({},a),{internal:{throwOnFailedPublish:!0}})),s.id},this.sendResult=async(e,t,r,i)=>{const n=Ai(e,r),s=await this.client.core.crypto.encode(t,n,i),o=await this.client.core.history.get(t,e),a=wh[o.request.method].res;return await this.client.core.relayer.publish(t,s,au(ou({},a),{internal:{throwOnFailedPublish:!0}})),await this.client.core.history.resolve(n),n.id},this.sendError=async(e,t,r,i)=>{const n=Oi(e,r.error),s=await this.client.core.crypto.encode(t,n,i),o=await this.client.core.history.get(t,e),a=wh[o.request.method].res;return await this.client.core.relayer.publish(t,s,a),await this.client.core.history.resolve(n),n.id},this.requestOnKnownPairing=async(e,t)=>{const r=this.client.core.pairing.pairings.getAll({active:!0}).find((t=>t.topic===e));if(!r)throw new Error(`Could not find pairing for provided topic ${e}`);const{publicKey:i}=this.client.authKeys.get(Sh),{chainId:n,statement:s,aud:o,domain:a,nonce:h,type:c}=t,u=await this.sendRequest(r.topic,"wc_authRequest",{payloadParams:{type:c??"eip4361",chainId:n,statement:s,aud:o,domain:a,version:"1",nonce:h,iat:(new Date).toISOString()},requester:{publicKey:i,metadata:this.client.metadata}},{},t.expiry);return this.client.logger.info(`sent request to known pairing topic: ${r.topic}`),{id:u}},this.onPairingCreated=e=>{const t=this.getPendingRequests();if(t){const r=Object.values(t).find((t=>t.pairingTopic===e.topic));r&&this.handleAuthRequest(r)}},this.onRelayEventRequest=e=>{const{topic:t,payload:r}=e,i=r.method;return"wc_authRequest"===i?this.onAuthRequest(t,r):this.client.logger.info(`Unsupported request method ${i}`)},this.onRelayEventResponse=async e=>{const{topic:t,payload:r}=e,i=(await this.client.core.history.get(t,r.id)).request.method;return"wc_authRequest"===i?this.onAuthResponse(t,r):this.client.logger.info(`Unsupported response method ${i}`)},this.onAuthRequest=async(e,t)=>{const{requester:r,payloadParams:i}=t.params;this.client.logger.info({type:"onAuthRequest",topic:e,payload:t});const n=Qc(JSON.stringify(t)),s=await this.getVerifyContext(n,this.client.metadata),o={requester:r,pairingTopic:e,id:t.id,cacaoPayload:i,verifyContext:s};await this.client.requests.set(t.id,o),this.handleAuthRequest(o)},this.handleAuthRequest=async e=>{const{id:t,pairingTopic:r,requester:i,cacaoPayload:n,verifyContext:s}=e;try{this.client.emit("auth_request",{id:t,topic:r,params:{requester:i,cacaoPayload:n},verifyContext:s})}catch(t){await this.sendError(e.id,e.pairingTopic,t),this.client.logger.error(t)}},this.onAuthResponse=async(e,t)=>{const{id:r}=t;if(this.client.logger.info({type:"onAuthResponse",topic:e,response:t}),ji(t)){const{pairingTopic:i}=this.client.pairingTopics.get(e);await this.client.core.pairing.activate({topic:i});const{s:n,p:s}=t.result;await this.client.requests.set(r,ou({id:r,pairingTopic:i},t.result));const o=this.formatMessage(s,s.iss);this.client.logger.debug("reconstructed message:\n",JSON.stringify(o)),this.client.logger.debug("payload.iss:",s.iss),this.client.logger.debug("signature:",n);const a=Ih(s.iss),h=function(e){const t=e&&Mh(e);if(t)return t[2]+":"+t[3]}(s.iss);if(!a)throw new Error("Could not derive address from `payload.iss`");if(!h)throw new Error("Could not derive chainId from `payload.iss`");this.client.logger.debug("walletAddress extracted from `payload.iss`:",a),await Ah(a,o,n,h,this.client.projectId)?this.client.emit("auth_response",{id:r,topic:e,params:t}):this.client.emit("auth_response",{id:r,topic:e,params:{message:"Invalid signature",code:-1}})}else qi(t)&&this.client.emit("auth_response",{id:r,topic:e,params:t})},this.getVerifyContext=async(e,t)=>{const r={verified:{verifyUrl:t.verifyUrl||"",validation:"UNKNOWN",origin:t.url||""}};try{const i=await this.client.core.verify.resolve({attestationId:e,verifyUrl:t.verifyUrl});i&&(r.verified.origin=i.origin,r.verified.isScam=i.isScam,r.verified.validation=origin===new URL(t.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.error(e)}return this.client.logger.info(`Verify context: ${JSON.stringify(r)}`),r}}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(Ms,(async e=>{const{topic:t,message:r}=e,{responseTopic:i,publicKey:n}=this.client.authKeys.keys.includes(Sh)?this.client.authKeys.get(Sh):{responseTopic:void 0,publicKey:void 0};if(i&&t!==i)return void this.client.logger.debug("[Auth] Ignoring message from unknown topic",t);const s=await this.client.core.crypto.decode(t,r,{receiverPublicKey:n});Ui(s)?(this.client.core.history.set(t,s),this.onRelayEventRequest({topic:t,payload:s})):ki(s)&&(await this.client.core.history.resolve(s),this.onRelayEventResponse({topic:t,payload:s}))}))}registerPairingEvents(){this.client.core.pairing.events.on(zs,(e=>this.onPairingCreated(e)))}}class cu extends vh{constructor(e){super(e),this.protocol="wc",this.version=1,this.name=_h,this.events=new g.EventEmitter,this.emit=(e,t)=>this.events.emit(e,t),this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.request=async(e,t)=>{try{return await this.engine.request(e,t)}catch(e){throw this.logger.error(e.message),e}},this.respond=async(e,t)=>{try{return await this.engine.respond(e,t)}catch(e){throw this.logger.error(e.message),e}},this.getPendingRequests=()=>{try{return this.engine.getPendingRequests()}catch(e){throw this.logger.error(e.message),e}},this.formatMessage=(e,t)=>{try{return this.engine.formatMessage(e,t)}catch(e){throw this.logger.error(e.message),e}};const t=typeof e.logger<"u"&&"string"!=typeof e.logger?e.logger:(0,w.pino)((0,w.getDefaultLoggerOptions)({level:e.logger||"error"}));this.name=e?.name||_h,this.metadata=e.metadata,this.projectId=e.projectId,this.core=e.core||new ko(e),this.logger=(0,w.generateChildLogger)(t,this.name),this.authKeys=new Mo(this.core,this.logger,"authKeys",Eh,(()=>Sh)),this.pairingTopics=new Mo(this.core,this.logger,"pairingTopics",Eh),this.requests=new Mo(this.core,this.logger,"requests",Eh,(e=>e.id)),this.engine=new hu(this)}static async init(e){const t=new cu(e);return await t.initialize(),t}get context(){return(0,w.getLoggerContext)(this.logger)}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.authKeys.init(),await this.requests.init(),await this.pairingTopics.init(),await this.engine.init(),this.logger.info("AuthClient Initialization Success"),this.logger.info({authClient:this})}catch(e){throw this.logger.info("AuthClient Initialization Failure"),this.logger.error(e.message),e}}}const uu=cu,lu="client",fu=`wc@2:${lu}:`,du=lu,pu="WALLETCONNECT_DEEPLINK_CHOICE",gu=j.SEVEN_DAYS,yu={wc_sessionPropose:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1104},res:{ttl:j.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1106},res:{ttl:j.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1112},res:{ttl:j.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1115}}},mu={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},vu="IDLE",wu="ACTIVE",bu=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var _u=Object.defineProperty,Eu=Object.defineProperties,Su=Object.getOwnPropertyDescriptors,Mu=Object.getOwnPropertySymbols,Iu=Object.prototype.hasOwnProperty,Au=Object.prototype.propertyIsEnumerable,Ou=(e,t,r)=>t in e?_u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,xu=(e,t)=>{for(var r in t||(t={}))Iu.call(t,r)&&Ou(e,r,t[r]);if(Mu)for(var r of Mu(t))Au.call(t,r)&&Ou(e,r,t[r]);return e},Pu=(e,t)=>Eu(e,Su(t));class Nu extends R{constructor(e){super(e),this.name="engine",this.events=new(y()),this.initialized=!1,this.ignoredPayloadTypes=[1],this.requestQueue={state:vu,queue:[]},this.sessionRequestQueue={state:vu,queue:[]},this.requestQueueDelay=j.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(yu)}),this.initialized=!0,setTimeout((()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()}),(0,j.toMiliseconds)(this.requestQueueDelay)))},this.connect=async e=>{await this.isInitialized();const t=Pu(xu({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t);const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:n,sessionProperties:s,relays:o}=t;let a,h=r,c=!1;if(h&&(c=this.client.core.pairing.pairings.get(h).active),!h||!c){const{topic:e,uri:t}=await this.client.core.pairing.create();h=e,a=t}const u=await this.client.core.crypto.generateKeyPair(),l=xu({requiredNamespaces:i,optionalNamespaces:n,relays:o??[{protocol:"irn"}],proposer:{publicKey:u,metadata:this.client.metadata}},s&&{sessionProperties:s}),{reject:f,resolve:d,done:p}=mr(j.FIVE_MINUTES,"Proposal expired");if(this.events.once(Sr("session_connect"),(async({error:e,session:t})=>{if(e)f(e);else if(t){t.self.publicKey=u;const e=Pu(xu({},t),{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces});await this.client.session.set(t.topic,e),await this.setExpiry(t.topic,t.expiry),h&&await this.client.core.pairing.updateMetadata({topic:h,metadata:t.peer.metadata}),d(e)}})),!h){const{message:e}=Jr("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(e)}const g=await this.sendRequest({topic:h,method:"wc_sessionPropose",params:l}),y=_r(j.FIVE_MINUTES);return await this.setProposal(g,xu({id:g,expiry:y},l)),{uri:a,approval:p}},this.pair=async e=>(await this.isInitialized(),await this.client.core.pairing.pair(e)),this.approve=async e=>{await this.isInitialized(),await this.isValidApprove(e);const{id:t,relayProtocol:r,namespaces:i,sessionProperties:n}=e,s=this.client.proposal.get(t);let{pairingTopic:o,proposer:a,requiredNamespaces:h,optionalNamespaces:c}=s;o=o||"",Qr(h)||(h=function(e,t){const r=oi(e,"approve()");if(r)throw new Error(r.message);const i={};for(const[t,r]of Object.entries(e))i[t]={methods:r.methods,events:r.events,chains:r.accounts.map((e=>`${e.split(":")[0]}:${e.split(":")[1]}`))};return i}(i));const u=await this.client.core.crypto.generateKeyPair(),l=a.publicKey,f=await this.client.core.crypto.generateSharedKey(u,l);o&&t&&(await this.client.core.pairing.updateMetadata({topic:o,metadata:a.metadata}),await this.sendResult({id:t,topic:o,result:{relay:{protocol:r??"irn"},responderPublicKey:u}}),await this.client.proposal.delete(t,Yr("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:o}));const d=xu({relay:{protocol:r??"irn"},namespaces:i,requiredNamespaces:h,optionalNamespaces:c,pairingTopic:o,controller:{publicKey:u,metadata:this.client.metadata},expiry:_r(gu)},n&&{sessionProperties:n});await this.client.core.relayer.subscribe(f),await this.sendRequest({topic:f,method:"wc_sessionSettle",params:d,throwOnFailedPublish:!0});const p=Pu(xu({},d),{topic:f,pairingTopic:o,acknowledged:!1,self:d.controller,peer:{publicKey:a.publicKey,metadata:a.metadata},controller:u});return await this.client.session.set(f,p),await this.setExpiry(f,_r(gu)),{topic:f,acknowledged:()=>new Promise((e=>setTimeout((()=>e(this.client.session.get(f))),500)))}},this.reject=async e=>{await this.isInitialized(),await this.isValidReject(e);const{id:t,reason:r}=e,{pairingTopic:i}=this.client.proposal.get(t);i&&(await this.sendError(t,i,r),await this.client.proposal.delete(t,Yr("USER_DISCONNECTED")))},this.update=async e=>{await this.isInitialized(),await this.isValidUpdate(e);const{topic:t,namespaces:r}=e,i=await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:r}}),{done:n,resolve:s,reject:o}=mr();return this.events.once(Sr("session_update",i),(({error:e})=>{e?o(e):s()})),await this.client.session.update(t,{namespaces:r}),{acknowledged:n}},this.extend=async e=>{await this.isInitialized(),await this.isValidExtend(e);const{topic:t}=e,r=await this.sendRequest({topic:t,method:"wc_sessionExtend",params:{}}),{done:i,resolve:n,reject:s}=mr();return this.events.once(Sr("session_extend",r),(({error:e})=>{e?s(e):n()})),await this.setExpiry(t,_r(gu)),{acknowledged:i}},this.request=async e=>{await this.isInitialized(),await this.isValidRequest(e);const{chainId:t,request:i,topic:n,expiry:s}=e,o=Si(),{done:a,resolve:h,reject:c}=mr(s,"Request expired. Please try again.");return this.events.once(Sr("session_request",o),(({error:e,result:t})=>{e?c(e):h(t)})),await Promise.all([new Promise((async e=>{await this.sendRequest({clientRpcId:o,topic:n,method:"wc_sessionRequest",params:{request:i,chainId:t},expiry:s,throwOnFailedPublish:!0}).catch((e=>c(e))),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:t,id:o}),e()})),new Promise((async e=>{const t=await this.client.core.storage.getItem(pu);(async function({id:e,topic:t,wcDeepLink:i}){try{if(!i)return;const n="string"==typeof i?JSON.parse(i):i;let s=n?.href;if("string"!=typeof s)return;s.endsWith("/")&&(s=s.slice(0,-1));const o=`${s}/wc?requestId=${e}&sessionTopic=${t}`,a=fr();a===ar.browser?o.startsWith("https://")?window.open(o,"_blank","noreferrer noopener"):window.open(o,"_self","noreferrer noopener"):a===ar.reactNative&&typeof(null==r.g?void 0:r.g.Linking)<"u"&&await r.g.Linking.openURL(o)}catch(e){console.error(e)}})({id:o,topic:n,wcDeepLink:t}),e()})),a()]).then((e=>e[2]))},this.respond=async e=>{await this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:r}=e,{id:i}=r;ji(r)?await this.sendResult({id:i,topic:t,result:r.result,throwOnFailedPublish:!0}):qi(r)&&await this.sendError(i,t,r.error),this.cleanupAfterResponse(e)},this.ping=async e=>{await this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=await this.sendRequest({topic:t,method:"wc_sessionPing",params:{}}),{done:r,resolve:i,reject:n}=mr();this.events.once(Sr("session_ping",e),(({error:e})=>{e?n(e):i()})),await r()}else this.client.core.pairing.pairings.keys.includes(t)&&await this.client.core.pairing.ping({topic:t})},this.emit=async e=>{await this.isInitialized(),await this.isValidEmit(e);const{topic:t,event:r,chainId:i}=e;await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:r,chainId:i}})},this.disconnect=async e=>{await this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.client.session.keys.includes(t)?(await this.sendRequest({topic:t,method:"wc_sessionDelete",params:Yr("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(t)):await this.client.core.pairing.disconnect({topic:t})},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter((t=>function(e,t){const{requiredNamespaces:r}=t,i=Object.keys(e.namespaces),n=Object.keys(r);let s=!0;return!!pr(n,i)&&(i.forEach((t=>{const{accounts:i,methods:n,events:o}=e.namespaces[t],a=Kr(i),h=r[t];pr(Bt(t,h),a)&&pr(h.methods,n)&&pr(h.events,o)||(s=!1)})),s)}(t,e)))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter((r=>{var i,n;return(null==(i=r.peerMetadata)?void 0:i.url)&&(null==(n=r.peerMetadata)?void 0:n.url)===e.peer.metadata.url&&r.topic&&r.topic!==t.topic}));if(0===r.length)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map((e=>this.client.core.pairing.disconnect({topic:e.topic})))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}},this.deleteSession=async(e,t)=>{const{self:r}=this.client.session.get(e);await this.client.core.relayer.unsubscribe(e),this.client.session.delete(e,Yr("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(r.publicKey)&&await this.client.core.crypto.deleteKeyPair(r.publicKey),this.client.core.crypto.keychain.has(e)&&await this.client.core.crypto.deleteSymKey(e),t||this.client.core.expirer.del(e),this.client.core.storage.removeItem(pu).catch((e=>this.client.logger.warn(e)))},this.deleteProposal=async(e,t)=>{await Promise.all([this.client.proposal.delete(e,Yr("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)])},this.deletePendingSessionRequest=async(e,t,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),r?Promise.resolve():this.client.core.expirer.del(e)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter((t=>t.id!==e)),r&&(this.sessionRequestQueue.state=vu)},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&await this.client.session.update(e,{expiry:t}),this.client.core.expirer.set(e,t)},this.setProposal=async(e,t)=>{await this.client.proposal.set(e,t),this.client.core.expirer.set(e,t.expiry)},this.setPendingSessionRequest=async e=>{const t=yu.wc_sessionRequest.req.ttl,{id:r,topic:i,params:n,verifyContext:s}=e;await this.client.pendingRequest.set(r,{id:r,topic:i,params:n,verifyContext:s}),t&&this.client.core.expirer.set(r,_r(t))},this.sendRequest=async e=>{const{topic:t,method:r,params:i,expiry:n,relayRpcId:s,clientRpcId:o,throwOnFailedPublish:a}=e,h=Ii(r,i,o);if(lr()&&bu.includes(r)){const e=Jt(JSON.stringify(h));this.client.core.verify.register({attestationId:e})}const c=await this.client.core.crypto.encode(t,h),u=yu[r].req;return n&&(u.ttl=n),s&&(u.id=s),this.client.core.history.set(t,h),a?(u.internal=Pu(xu({},u.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,c,u)):this.client.core.relayer.publish(t,c,u).catch((e=>this.client.logger.error(e))),h.id},this.sendResult=async e=>{const{id:t,topic:r,result:i,throwOnFailedPublish:n}=e,s=Ai(t,i),o=await this.client.core.crypto.encode(r,s),a=await this.client.core.history.get(r,t),h=yu[a.request.method].res;n?(h.internal=Pu(xu({},h.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,o,h)):this.client.core.relayer.publish(r,o,h).catch((e=>this.client.logger.error(e))),await this.client.core.history.resolve(s)},this.sendError=async(e,t,r)=>{const i=Oi(e,r),n=await this.client.core.crypto.encode(t,i),s=await this.client.core.history.get(t,e),o=yu[s.request.method].res;this.client.core.relayer.publish(t,n,o),await this.client.core.history.resolve(i)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach((t=>{Er(t.expiry)&&e.push(t.topic)})),this.client.proposal.getAll().forEach((e=>{Er(e.expiry)&&t.push(e.id)})),await Promise.all([...e.map((e=>this.deleteSession(e))),...t.map((e=>this.deleteProposal(e)))])},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state!==wu){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=wu;const e=this.requestQueue.queue.shift();if(e)try{this.processRequest(e),await new Promise((e=>setTimeout(e,300)))}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=vu}else this.client.logger.info("Request queue already active, skipping...")},this.processRequest=e=>{const{topic:t,payload:r}=e,i=r.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeRequest(t,r);case"wc_sessionSettle":return this.onSessionSettleRequest(t,r);case"wc_sessionUpdate":return this.onSessionUpdateRequest(t,r);case"wc_sessionExtend":return this.onSessionExtendRequest(t,r);case"wc_sessionPing":return this.onSessionPingRequest(t,r);case"wc_sessionDelete":return this.onSessionDeleteRequest(t,r);case"wc_sessionRequest":return this.onSessionRequest(t,r);case"wc_sessionEvent":return this.onSessionEventRequest(t,r);default:return this.client.logger.info(`Unsupported request method ${i}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:r}=e,i=(await this.client.core.history.get(t,r.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(t,r);case"wc_sessionSettle":return this.onSessionSettleResponse(t,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,r);case"wc_sessionExtend":return this.onSessionExtendResponse(t,r);case"wc_sessionPing":return this.onSessionPingResponse(t,r);case"wc_sessionRequest":return this.onSessionRequestResponse(t,r);default:return this.client.logger.info(`Unsupported response method ${i}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:r}=Jr("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)},this.onSessionProposeRequest=async(e,t)=>{const{params:r,id:i}=t;try{this.isValidConnect(xu({},t.params));const n=_r(j.FIVE_MINUTES),s=xu({id:i,pairingTopic:e,expiry:n},r);await this.setProposal(i,s);const o=Jt(JSON.stringify(t)),a=await this.getVerifyContext(o,s.proposer.metadata);this.client.events.emit("session_proposal",{id:i,params:s,verifyContext:a})}catch(t){await this.sendError(i,e,t),this.client.logger.error(t)}},this.onSessionProposeResponse=async(e,t)=>{const{id:r}=t;if(ji(t)){const{result:i}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});const n=this.client.proposal.get(r);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const s=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:s});const o=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:o});const a=await this.client.core.crypto.generateSharedKey(s,o);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:a});const h=await this.client.core.relayer.subscribe(a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:e})}else qi(t)&&(await this.client.proposal.delete(r,Yr("USER_DISCONNECTED")),this.events.emit(Sr("session_connect"),{error:t.error}))},this.onSessionSettleRequest=async(e,t)=>{const{id:r,params:i}=t;try{this.isValidSessionSettleRequest(i);const{relay:r,controller:n,expiry:s,namespaces:o,requiredNamespaces:a,optionalNamespaces:h,sessionProperties:c,pairingTopic:u}=t.params,l=xu({topic:e,relay:r,expiry:s,namespaces:o,acknowledged:!0,pairingTopic:u,requiredNamespaces:a,optionalNamespaces:h,controller:n.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:n.publicKey,metadata:n.metadata}},c&&{sessionProperties:c});await this.sendResult({id:t.id,topic:e,result:!0}),this.events.emit(Sr("session_connect"),{session:l}),this.cleanupDuplicatePairings(l)}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.onSessionSettleResponse=async(e,t)=>{const{id:r}=t;ji(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Sr("session_approve",r),{})):qi(t)&&(await this.client.session.delete(e,Yr("USER_DISCONNECTED")),this.events.emit(Sr("session_approve",r),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:r,id:i}=t;try{const t=`${e}_session_update`,n=gi.get(t);if(n&&this.isRequestOutOfSync(n,i))return void this.client.logger.info(`Discarding out of sync request - ${i}`);this.isValidUpdate(xu({topic:e},r)),await this.client.session.update(e,{namespaces:r.namespaces}),await this.sendResult({id:i,topic:e,result:!0}),this.client.events.emit("session_update",{id:i,topic:e,params:r}),gi.set(t,i)}catch(t){await this.sendError(i,e,t),this.client.logger.error(t)}},this.isRequestOutOfSync=(e,t)=>parseInt(t.toString().slice(0,-3))<=parseInt(e.toString().slice(0,-3)),this.onSessionUpdateResponse=(e,t)=>{const{id:r}=t;ji(t)?this.events.emit(Sr("session_update",r),{}):qi(t)&&this.events.emit(Sr("session_update",r),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:r}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,_r(gu)),await this.sendResult({id:r,topic:e,result:!0}),this.client.events.emit("session_extend",{id:r,topic:e})}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.onSessionExtendResponse=(e,t)=>{const{id:r}=t;ji(t)?this.events.emit(Sr("session_extend",r),{}):qi(t)&&this.events.emit(Sr("session_extend",r),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:r}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:r,topic:e,result:!0}),this.client.events.emit("session_ping",{id:r,topic:e})}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.onSessionPingResponse=(e,t)=>{const{id:r}=t;setTimeout((()=>{ji(t)?this.events.emit(Sr("session_ping",r),{}):qi(t)&&this.events.emit(Sr("session_ping",r),{error:t.error})}),500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:r}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await Promise.all([new Promise((t=>{this.client.core.relayer.once(Ps,(async()=>{t(await this.deleteSession(e))}))})),this.sendResult({id:r,topic:e,result:!0})]),this.client.events.emit("session_delete",{id:r,topic:e})}catch(e){this.client.logger.error(e)}},this.onSessionRequest=async(e,t)=>{const{id:r,params:i}=t;try{this.isValidRequest(xu({topic:e},i));const t=Jt(JSON.stringify(Ii("wc_sessionRequest",i,r))),n=this.client.session.get(e),s={id:r,topic:e,params:i,verifyContext:await this.getVerifyContext(t,n.peer.metadata)};await this.setPendingSessionRequest(s),this.addSessionRequestToSessionRequestQueue(s),this.processSessionRequestQueue()}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.onSessionRequestResponse=(e,t)=>{const{id:r}=t;ji(t)?this.events.emit(Sr("session_request",r),{result:t.result}):qi(t)&&this.events.emit(Sr("session_request",r),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:r,params:i}=t;try{const t=`${e}_session_event_${i.event.name}`,n=gi.get(t);if(n&&this.isRequestOutOfSync(n,r))return void this.client.logger.info(`Discarding out of sync request - ${r}`);this.isValidEmit(xu({topic:e},i)),this.client.events.emit("session_event",{id:r,topic:e,params:i}),gi.set(t,r)}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout((()=>{this.sessionRequestQueue.state=vu,this.processSessionRequestQueue()}),(0,j.toMiliseconds)(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===wu)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.sessionRequestQueue.state=wu,this.client.events.emit("session_request",e)}catch(e){this.client.logger.error(e)}else this.client.logger.info("session request queue is empty.")},this.onPairingCreated=e=>{if(e.active)return;const t=this.client.proposal.getAll().find((t=>t.pairingTopic===e.topic));t&&this.onSessionProposeRequest(e.topic,Ii("wc_sessionPropose",{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer},t.id))},this.isValidConnect=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:r,optionalNamespaces:i,sessionProperties:n,relays:s}=e;if(Zr(t)||await this.isValidPairingTopic(t),!function(e,t){let r=!1;return e?e&&Xr(e)&&e.length&&e.forEach((e=>{r=ai(e)})):r=!0,r}(s)){const{message:e}=Jr("MISSING_OR_INVALID",`connect() relays: ${s}`);throw new Error(e)}!Zr(r)&&0!==Qr(r)&&this.validateNamespaces(r,"requiredNamespaces"),!Zr(i)&&0!==Qr(i)&&this.validateNamespaces(i,"optionalNamespaces"),Zr(n)||this.validateSessionProps(n,"sessionProperties")},this.validateNamespaces=(e,t)=>{const r=function(e,t,r){let i=null;if(e&&Qr(e)){const n=si(e,t);n&&(i=n);const s=function(e,t,r){let i=null;return Object.entries(e).forEach((([e,n])=>{if(i)return;const s=function(e,t,r){let i=null;return Xr(t)&&t.length?t.forEach((e=>{i||ri(e)||(i=Yr("UNSUPPORTED_CHAINS",`${r}, chain ${e} should be a string and conform to "namespace:chainId" format`))})):ri(e)||(i=Yr("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}(e,Bt(e,n),`${t} ${r}`);s&&(i=s)})),i}(e,t,r);s&&(i=s)}else i=Jr("MISSING_OR_INVALID",`${t}, ${r} should be an object with data`);return i}(e,"connect()",t);if(r)throw new Error(r.message)},this.isValidApprove=async e=>{if(!hi(e))throw new Error(Jr("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:r,relayProtocol:i,sessionProperties:n}=e;await this.isValidProposalId(t);const s=this.client.proposal.get(t),o=oi(r,"approve()");if(o)throw new Error(o.message);const a=ui(s.requiredNamespaces,r,"approve()");if(a)throw new Error(a.message);if(!ei(i,!0)){const{message:e}=Jr("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(e)}Zr(n)||this.validateSessionProps(n,"sessionProperties")},this.isValidReject=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:r}=e;if(await this.isValidProposalId(t),!function(e){return!!(e&&"object"==typeof e&&e.code&&ti(e.code,!1)&&e.message&&ei(e.message,!1))}(r)){const{message:e}=Jr("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(e)}},this.isValidSessionSettleRequest=e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:r,namespaces:i,expiry:n}=e;if(!ai(t)){const{message:e}=Jr("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const s=function(e,t){let r=null;return ei(e?.publicKey,!1)||(r=Jr("MISSING_OR_INVALID","onSessionSettleRequest() controller public key should be a string")),r}(r);if(s)throw new Error(s.message);const o=oi(i,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(Er(n)){const{message:e}=Jr("EXPIRED","onSessionSettleRequest()");throw new Error(e)}},this.isValidUpdate=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:r}=e;await this.isValidSessionTopic(t);const i=this.client.session.get(t),n=oi(r,"update()");if(n)throw new Error(n.message);const s=ui(i.requiredNamespaces,r,"update()");if(s)throw new Error(s.message)},this.isValidExtend=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:r,chainId:i,expiry:n}=e;await this.isValidSessionTopic(t);const{namespaces:s}=this.client.session.get(t);if(!ci(s,i)){const{message:e}=Jr("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(e)}if(!function(e){return!(Zr(e)||!ei(e.method,!1))}(r)){const{message:e}=Jr("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(e)}if(!function(e,t,r){return!!ei(r,!1)&&function(e,t){const r=[];return Object.values(e).forEach((e=>{Kr(e.accounts).includes(t)&&r.push(...e.methods)})),r}(e,t).includes(r)}(s,i,r.method)){const{message:e}=Jr("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(e)}if(n&&!fi(n,mu)){const{message:e}=Jr("MISSING_OR_INVALID",`request() expiry: ${n}. Expiry must be a number (in seconds) between ${mu.min} and ${mu.max}`);throw new Error(e)}},this.isValidRespond=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:t,response:r}=e;if(await this.isValidSessionTopic(t),!function(e){return!(Zr(e)||Zr(e.result)&&Zr(e.error)||!ti(e.id,!1)||!ei(e.jsonrpc,!1))}(r)){const{message:e}=Jr("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(r)}`);throw new Error(e)}},this.isValidPing=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:r,chainId:i}=e;await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!ci(n,i)){const{message:e}=Jr("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(e)}if(!function(e){return!(Zr(e)||!ei(e.name,!1))}(r)){const{message:e}=Jr("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(e)}if(!function(e,t,r){return!!ei(r,!1)&&function(e,t){const r=[];return Object.values(e).forEach((e=>{Kr(e.accounts).includes(t)&&r.push(...e.events)})),r}(e,t).includes(r)}(n,i,r.name)){const{message:e}=Jr("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(e)}},this.isValidDisconnect=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.getVerifyContext=async(e,t)=>{const r={verified:{verifyUrl:t.verifyUrl||Gs,validation:"UNKNOWN",origin:t.url||""}};try{const i=await this.client.core.verify.resolve({attestationId:e,verifyUrl:t.verifyUrl});i&&(r.verified.origin=i.origin,r.verified.isScam=i.isScam,r.verified.validation=i.origin===new URL(t.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.info(e)}return this.client.logger.info(`Verify context: ${JSON.stringify(r)}`),r},this.validateSessionProps=(e,t)=>{Object.values(e).forEach((e=>{if(!ei(e,!1)){const{message:r}=Jr("MISSING_OR_INVALID",`${t} must be in Record format. Received: ${JSON.stringify(e)}`);throw new Error(r)}}))}}async isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ms,(async e=>{const{topic:t,message:r}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(r)))return;const i=await this.client.core.crypto.decode(t,r);try{Ui(i)?(this.client.core.history.set(t,i),this.onRelayEventRequest({topic:t,payload:i})):ki(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:t,payload:i}),this.client.core.history.delete(t,i.id)):this.onRelayEventUnknownPayload({topic:t,payload:i})}catch(e){this.client.logger.error(e)}}))}registerExpirerEvents(){this.client.core.expirer.on(Hs,(async e=>{const{topic:t,id:r}=br(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,Jr("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession(t,!0),this.client.events.emit("session_expire",{topic:t})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))}))}registerPairingEvents(){this.client.core.pairing.events.on(zs,(e=>this.onPairingCreated(e)))}isValidPairingTopic(e){if(!ei(e,!1)){const{message:t}=Jr("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=Jr("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Er(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=Jr("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ei(e,!1)){const{message:t}=Jr("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(!this.client.session.keys.includes(e)){const{message:t}=Jr("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Er(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:t}=Jr("EXPIRED",`session topic: ${e}`);throw new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else{if(!this.client.core.pairing.pairings.keys.includes(e)){if(ei(e,!1)){const{message:t}=Jr("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=Jr("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if("number"!=typeof e){const{message:t}=Jr("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=Jr("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Er(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:t}=Jr("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class Ru extends Mo{constructor(e,t){super(e,t,"proposal",fu),this.core=e,this.logger=t}}class Tu extends Mo{constructor(e,t){super(e,t,"session",fu),this.core=e,this.logger=t}}class Lu extends Mo{constructor(e,t){super(e,t,"request",fu,(e=>e.id)),this.core=e,this.logger=t}}class Cu extends N{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=du,this.events=new g.EventEmitter,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.removeAllListeners=e=>this.events.removeAllListeners(e),this.connect=async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}},this.pair=async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}},this.approve=async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}},this.reject=async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}},this.update=async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}},this.extend=async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}},this.request=async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}},this.respond=async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}},this.ping=async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}},this.emit=async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}},this.disconnect=async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}},this.find=e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.name=e?.name||du,this.metadata=e?.metadata||(0,Dt.D)()||{name:"",description:"",url:"",icons:[""]};const t=typeof e?.logger<"u"&&"string"!=typeof e?.logger?e.logger:(0,w.pino)((0,w.getDefaultLoggerOptions)({level:e?.logger||"error"}));this.core=e?.core||new ko(e),this.logger=(0,w.generateChildLogger)(t,this.name),this.session=new Tu(this.core,this.logger),this.proposal=new Ru(this.core,this.logger),this.pendingRequest=new Lu(this.core,this.logger),this.engine=new Nu(this)}static async init(e){const t=new Cu(e);return await t.initialize(),t}get context(){return(0,w.getLoggerContext)(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const Uu=Cu;var ku,ju={exports:{}},qu="object"==typeof Reflect?Reflect:null,Du=qu&&"function"==typeof qu.apply?qu.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};ku=qu&&"function"==typeof qu.ownKeys?qu.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var zu=Number.isNaN||function(e){return e!=e};function $u(){$u.init.call(this)}ju.exports=$u,ju.exports.once=function(e,t){return new Promise((function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}Xu(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Xu(e,"error",t,{once:!0})}(e,n)}))},$u.EventEmitter=$u,$u.prototype._events=void 0,$u.prototype._eventsCount=0,$u.prototype._maxListeners=void 0;var Bu=10;function Ku(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Fu(e){return void 0===e._maxListeners?$u.defaultMaxListeners:e._maxListeners}function Vu(e,t,r,i){var n,s,o;if(Ku(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=Fu(e))>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,function(e){console&&console.warn&&console.warn(e)}(a)}return e}function Hu(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Wu(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=Hu.bind(i);return n.listener=r,i.wrapFn=n,n}function Gu(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)Du(a,this,t);else{var h=a.length,c=Yu(a,h);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},$u.prototype.listeners=function(e){return Gu(this,e,!0)},$u.prototype.rawListeners=function(e){return Gu(this,e,!1)},$u.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Ju.call(e,t)},$u.prototype.listenerCount=Ju,$u.prototype.eventNames=function(){return this._eventsCount>0?ku(this._events):[]};ju.exports;class Qu{constructor(e){this.opts=e}}class Zu{constructor(e){this.client=e}}class el extends Zu{constructor(e){super(e),this.init=async()=>{this.signClient=await Uu.init({core:this.client.core,metadata:this.client.metadata}),this.authClient=await uu.init({core:this.client.core,projectId:"",metadata:this.client.metadata}),this.initializeEventListeners()},this.pair=async e=>{await this.client.core.pairing.pair(e)},this.approveSession=async e=>{const{topic:t,acknowledged:r}=await this.signClient.approve({id:e.id,namespaces:e.namespaces});return await r(),this.signClient.session.get(t)},this.rejectSession=async e=>await this.signClient.reject(e),this.updateSession=async e=>await(await this.signClient.update(e)).acknowledged(),this.extendSession=async e=>await(await this.signClient.extend(e)).acknowledged(),this.respondSessionRequest=async e=>await this.signClient.respond(e),this.disconnectSession=async e=>await this.signClient.disconnect(e),this.emitSessionEvent=async e=>await this.signClient.emit(e),this.getActiveSessions=()=>this.signClient.session.getAll().reduce(((e,t)=>(e[t.topic]=t,e)),{}),this.getPendingSessionProposals=()=>this.signClient.proposal.getAll(),this.getPendingSessionRequests=()=>this.signClient.getPendingSessionRequests(),this.respondAuthRequest=async(e,t)=>await this.authClient.respond(e,t),this.getPendingAuthRequests=()=>this.authClient.requests.getAll().filter((e=>"requester"in e)),this.formatMessage=(e,t)=>this.authClient.formatMessage(e,t),this.onSessionRequest=e=>{this.client.events.emit("session_request",e)},this.onSessionProposal=e=>{this.client.events.emit("session_proposal",e)},this.onSessionDelete=e=>{this.client.events.emit("session_delete",e)},this.onAuthRequest=e=>{this.client.events.emit("auth_request",e)},this.initializeEventListeners=()=>{this.signClient.events.on("session_proposal",this.onSessionProposal),this.signClient.events.on("session_request",this.onSessionRequest),this.signClient.events.on("session_delete",this.onSessionDelete),this.authClient.on("auth_request",this.onAuthRequest)},this.signClient={},this.authClient={}}}class tl extends Qu{constructor(e){super(e),this.events=new ju.exports,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.pair=async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}},this.approveSession=async e=>{try{return await this.engine.approveSession(e)}catch(e){throw this.logger.error(e.message),e}},this.rejectSession=async e=>{try{return await this.engine.rejectSession(e)}catch(e){throw this.logger.error(e.message),e}},this.updateSession=async e=>{try{return await this.engine.updateSession(e)}catch(e){throw this.logger.error(e.message),e}},this.extendSession=async e=>{try{return await this.engine.extendSession(e)}catch(e){throw this.logger.error(e.message),e}},this.respondSessionRequest=async e=>{try{return await this.engine.respondSessionRequest(e)}catch(e){throw this.logger.error(e.message),e}},this.disconnectSession=async e=>{try{return await this.engine.disconnectSession(e)}catch(e){throw this.logger.error(e.message),e}},this.emitSessionEvent=async e=>{try{return await this.engine.emitSessionEvent(e)}catch(e){throw this.logger.error(e.message),e}},this.getActiveSessions=()=>{try{return this.engine.getActiveSessions()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionProposals=()=>{try{return this.engine.getPendingSessionProposals()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.respondAuthRequest=async(e,t)=>{try{return await this.engine.respondAuthRequest(e,t)}catch(e){throw this.logger.error(e.message),e}},this.getPendingAuthRequests=()=>{try{return this.engine.getPendingAuthRequests()}catch(e){throw this.logger.error(e.message),e}},this.formatMessage=(e,t)=>{try{return this.engine.formatMessage(e,t)}catch(e){throw this.logger.error(e.message),e}},this.metadata=e.metadata,this.name=e.name||"Web3Wallet",this.core=e.core,this.logger=this.core.logger,this.engine=new el(this)}static async init(e){const t=new tl(e);return await t.initialize(),t}async initialize(){this.logger.trace("Initialized");try{await this.engine.init(),this.logger.info("Web3Wallet Initialization Success")}catch(e){throw this.logger.info("Web3Wallet Initialization Failure"),this.logger.error(e.message),e}}}const rl=tl;function il(e){if(!e.startsWith("wc:"))return null;const t=e.indexOf("@");return t<0?null:e.slice(3,t)}window.wc={core:null,web3wallet:null,authClient:null,init:function(e){return new Promise((async t=>{window.wc.core=new ko({projectId:e}),window.wc.web3wallet=await rl.init({core:window.wc.core,metadata:{name:"Prototype",description:"Prototype Wallet/Peer",url:"https://github.com/status-im/status-desktop",icons:["https://status.im/img/status-footer-logo.svg"]}}),window.wc.authClient=await cu.init({projectId:e,metadata:window.wc.web3wallet.metadata}),t(window.wc)}))},alreadyPaired:new Error("Already paired"),waitingForApproval:new Error("Waiting for approval"),pair:function(e){let t=il(e),r=window.wc.web3wallet.pair({uri:e}).catch((e=>console.error(e)));const i=window.wc.core.pairing.getPairings().find((e=>e.topic===t));return i&&i.active?new Promise(((e,t)=>{t(window.wc.alreadyPaired)})):new Promise(((e,t)=>{r.then((()=>{window.wc.web3wallet.on("session_proposal",(async t=>{e(t)}))})).catch((e=>{t(e)}))}))},registerForSessionRequest:function(e){window.wc.web3wallet.on("session_request",e)},approveSession:function(e){const{id:t,params:r}=e,i=function(e){const{proposal:{requiredNamespaces:t,optionalNamespaces:r={}},supportedNamespaces:i}=e,n=Hr(t),s=Hr(r),o={};Object.keys(i).forEach((e=>{const t=i[e].chains,r=i[e].methods,n=i[e].events,s=i[e].accounts;t.forEach((t=>{if(!s.some((e=>e.includes(t))))throw new Error(`No accounts provided for chain ${t} in namespace ${e}`)})),o[e]={chains:t,methods:r,events:n,accounts:s}}));const a=ui(t,o,"approve()");if(a)throw new Error(a.message);const h={};return Object.keys(t).length||Object.keys(r).length?(Object.keys(n).forEach((e=>{const t=i[e].chains.filter((t=>{var r,i;return null==(i=null==(r=n[e])?void 0:r.chains)?void 0:i.includes(t)})),r=i[e].methods.filter((t=>{var r,i;return null==(i=null==(r=n[e])?void 0:r.methods)?void 0:i.includes(t)})),s=i[e].events.filter((t=>{var r,i;return null==(i=null==(r=n[e])?void 0:r.events)?void 0:i.includes(t)})),o=t.map((t=>i[e].accounts.filter((e=>e.includes(`${t}:`))))).flat();h[e]={chains:t,methods:r,events:s,accounts:o}})),Object.keys(s).forEach((e=>{var t,r,n,o,a,c;if(!i[e])return;const u=null==(r=null==(t=s[e])?void 0:t.chains)?void 0:r.filter((t=>i[e].chains.includes(t))),l=i[e].methods.filter((t=>{var r,i;return null==(i=null==(r=s[e])?void 0:r.methods)?void 0:i.includes(t)})),f=i[e].events.filter((t=>{var r,i;return null==(i=null==(r=s[e])?void 0:r.events)?void 0:i.includes(t)})),d=u?.map((t=>i[e].accounts.filter((e=>e.includes(`${t}:`))))).flat();h[e]={chains:Mr(null==(n=h[e])?void 0:n.chains,u),methods:Mr(null==(o=h[e])?void 0:o.methods,l),events:Mr(null==(a=h[e])?void 0:a.events,f),accounts:Mr(null==(c=h[e])?void 0:c.accounts,d)}})),h):o}({proposal:r,supportedNamespaces:{eip155:{chains:["eip155:1","eip155:5"],methods:["eth_sendTransaction","personal_sign"],events:["accountsChanged","chainChanged"],accounts:["eip155:1:0x0000000000000000000000000000000000000001","eip155:5:0xe74E17D586227691Cb7b64ed78b1b7B14828B034"]}}});return window.wc.web3wallet.approveSession({id:t,namespaces:i})},rejectSession:function(e){return window.wc.web3wallet.rejectSession({id:e,reason:Yr("USER_REJECTED")})},auth:function(e){let t=il(e),r=window.wc.authClient.core.pairing.pair({uri:e}).catch((e=>console.error(e)));const i=window.wc.core.pairing.getPairings().find((e=>e.topic===t));return i&&i.active?new Promise(((e,t)=>{t(window.wc.alreadyPaired)})):new Promise(((e,t)=>{r.then((()=>{window.wc.authClient.on("auth_request",(async t=>{e(t)}))})).catch((e=>{t(e)}))}))},approveAuth:function(e){const{id:t,params:r}=e,i="did:pkh:eip155:1:0x0123456789";return window.wc.authClient.formatMessage(r.cacaoPayload,i),window.wc.authClient.respond({id:t,signature:{s:"0x123456789",t:"eip191"}},i)},rejectAuth:function(e){return window.wc.authClient.reject(e)},respondSessionRequest:function(e,t){window.wc.web3wallet.respondSessionRequest({topic:e,response:t})},disconnectAll:function(){window.wc.core.pairing.getPairings().forEach((e=>{window.wc.core.pairing.disconnect({topic:e.topic})}))}}})(); \ No newline at end of file +var e={8099:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});var i=r(7117);function n(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>8,t[r+1]=e>>>0,t}function s(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t}function o(e,t){return void 0===t&&(t=0),e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function a(e,t){return void 0===t&&(t=0),(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function h(e,t){return void 0===t&&(t=0),e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}function c(e,t){return void 0===t&&(t=0),(e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t])>>>0}function u(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>24,t[r+1]=e>>>16,t[r+2]=e>>>8,t[r+3]=e>>>0,t}function l(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24,t}function f(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),u(e/4294967296>>>0,t,r),u(e>>>0,t,r+4),t}function d(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),l(e>>>0,t,r),l(e/4294967296>>>0,t,r+4),t}t.readInt16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])<<16>>16},t.readUint16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])>>>0},t.readInt16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])<<16>>16},t.readUint16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])>>>0},t.writeUint16BE=n,t.writeInt16BE=n,t.writeUint16LE=s,t.writeInt16LE=s,t.readInt32BE=o,t.readUint32BE=a,t.readInt32LE=h,t.readUint32LE=c,t.writeUint32BE=u,t.writeInt32BE=u,t.writeUint32LE=l,t.writeInt32LE=l,t.readInt64BE=function(e,t){void 0===t&&(t=0);var r=o(e,t),i=o(e,t+4);return 4294967296*r+i-4294967296*(i>>31)},t.readUint64BE=function(e,t){return void 0===t&&(t=0),4294967296*a(e,t)+a(e,t+4)},t.readInt64LE=function(e,t){void 0===t&&(t=0);var r=h(e,t);return 4294967296*h(e,t+4)+r-4294967296*(r>>31)},t.readUint64LE=function(e,t){void 0===t&&(t=0);var r=c(e,t);return 4294967296*c(e,t+4)+r},t.writeUint64BE=f,t.writeInt64BE=f,t.writeUint64LE=d,t.writeInt64LE=d,t.readUintBE=function(e,t,r){if(void 0===r&&(r=0),e%8!=0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var i=0,n=1,s=e/8+r-1;s>=r;s--)i+=t[s]*n,n*=256;return i},t.readUintLE=function(e,t,r){if(void 0===r&&(r=0),e%8!=0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var i=0,n=1,s=r;s=n;o--)r[o]=t/s&255,s*=256;return r},t.writeUintLE=function(e,t,r,n){if(void 0===r&&(r=new Uint8Array(e/8)),void 0===n&&(n=0),e%8!=0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!i.isSafeInteger(t))throw new Error("writeUintLE value must be an integer");for(var s=1,o=n;o{Object.defineProperty(t,"__esModule",{value:!0});var i=r(8099),n=r(7309),s=20;function o(e,t,r){for(var n=1634760805,o=857760878,a=2036477234,h=1797285236,c=r[3]<<24|r[2]<<16|r[1]<<8|r[0],u=r[7]<<24|r[6]<<16|r[5]<<8|r[4],l=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],p=r[23]<<24|r[22]<<16|r[21]<<8|r[20],g=r[27]<<24|r[26]<<16|r[25]<<8|r[24],y=r[31]<<24|r[30]<<16|r[29]<<8|r[28],m=t[3]<<24|t[2]<<16|t[1]<<8|t[0],v=t[7]<<24|t[6]<<16|t[5]<<8|t[4],w=t[11]<<24|t[10]<<16|t[9]<<8|t[8],b=t[15]<<24|t[14]<<16|t[13]<<8|t[12],_=n,E=o,S=a,M=h,I=c,A=u,O=l,x=f,P=d,N=p,R=g,T=y,L=m,C=v,U=w,k=b,j=0;j>>16|L<<16)|0)>>>20|I<<12,A=(A^=N=N+(C=(C^=E=E+A|0)>>>16|C<<16)|0)>>>20|A<<12,O=(O^=R=R+(U=(U^=S=S+O|0)>>>16|U<<16)|0)>>>20|O<<12,x=(x^=T=T+(k=(k^=M=M+x|0)>>>16|k<<16)|0)>>>20|x<<12,O=(O^=R=R+(U=(U^=S=S+O|0)>>>24|U<<8)|0)>>>25|O<<7,x=(x^=T=T+(k=(k^=M=M+x|0)>>>24|k<<8)|0)>>>25|x<<7,A=(A^=N=N+(C=(C^=E=E+A|0)>>>24|C<<8)|0)>>>25|A<<7,I=(I^=P=P+(L=(L^=_=_+I|0)>>>24|L<<8)|0)>>>25|I<<7,A=(A^=R=R+(k=(k^=_=_+A|0)>>>16|k<<16)|0)>>>20|A<<12,O=(O^=T=T+(L=(L^=E=E+O|0)>>>16|L<<16)|0)>>>20|O<<12,x=(x^=P=P+(C=(C^=S=S+x|0)>>>16|C<<16)|0)>>>20|x<<12,I=(I^=N=N+(U=(U^=M=M+I|0)>>>16|U<<16)|0)>>>20|I<<12,x=(x^=P=P+(C=(C^=S=S+x|0)>>>24|C<<8)|0)>>>25|x<<7,I=(I^=N=N+(U=(U^=M=M+I|0)>>>24|U<<8)|0)>>>25|I<<7,O=(O^=T=T+(L=(L^=E=E+O|0)>>>24|L<<8)|0)>>>25|O<<7,A=(A^=R=R+(k=(k^=_=_+A|0)>>>24|k<<8)|0)>>>25|A<<7;i.writeUint32LE(_+n|0,e,0),i.writeUint32LE(E+o|0,e,4),i.writeUint32LE(S+a|0,e,8),i.writeUint32LE(M+h|0,e,12),i.writeUint32LE(I+c|0,e,16),i.writeUint32LE(A+u|0,e,20),i.writeUint32LE(O+l|0,e,24),i.writeUint32LE(x+f|0,e,28),i.writeUint32LE(P+d|0,e,32),i.writeUint32LE(N+p|0,e,36),i.writeUint32LE(R+g|0,e,40),i.writeUint32LE(T+y|0,e,44),i.writeUint32LE(L+m|0,e,48),i.writeUint32LE(C+v|0,e,52),i.writeUint32LE(U+w|0,e,56),i.writeUint32LE(k+b|0,e,60)}function a(e,t,r,i,s){if(void 0===s&&(s=0),32!==e.length)throw new Error("ChaCha: key size must be 32 bytes");if(i.length>>=8,t++;if(i>0)throw new Error("ChaCha: counter overflow")}t.streamXOR=a,t.stream=function(e,t,r,i){return void 0===i&&(i=0),n.wipe(r),a(e,t,r,r,i)}},5501:(e,t,r)=>{var i=r(5439),n=r(3027),s=r(7309),o=r(8099),a=r(4153);t.Cv=32,t.WH=12,t.pg=16;var h=new Uint8Array(16),c=function(){function e(e){if(this.nonceLength=t.WH,this.tagLength=t.pg,e.length!==t.Cv)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return e.prototype.seal=function(e,t,r,n){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var o=new Uint8Array(16);o.set(e,o.length-e.length);var a=new Uint8Array(32);i.stream(this._key,o,a,4);var h,c=t.length+this.tagLength;if(n){if(n.length!==c)throw new Error("ChaCha20Poly1305: incorrect destination length");h=n}else h=new Uint8Array(c);return i.streamXOR(this._key,o,t,h,4),this._authenticate(h.subarray(h.length-this.tagLength,h.length),a,h.subarray(0,h.length-this.tagLength),r),s.wipe(o),h},e.prototype.open=function(e,t,r,n){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(t.length0&&a.update(h.subarray(i.length%16))),a.update(r),r.length%16>0&&a.update(h.subarray(r.length%16));var c=new Uint8Array(8);i&&o.writeUint64LE(i.length,c),a.update(c),o.writeUint64LE(r.length,c),a.update(c);for(var u=a.digest(),l=0;l{function r(e,t){if(e.length!==t.length)return 0;for(var r=0,i=0;i>>8}Object.defineProperty(t,"__esModule",{value:!0}),t.select=function(e,t,r){return~(e-1)&t|e-1&r},t.lessOrEqual=function(e,t){return(0|e)-(0|t)-1>>>31&1},t.compare=r,t.equal=function(e,t){return 0!==e.length&&0!==t.length&&0!==r(e,t)}},1050:(e,t,r)=>{t.Xx=t._w=t.aP=t.KS=t.jQ=void 0;r(1416);const i=r(3350);r(7309);function n(e){const t=new Float64Array(16);if(e)for(let r=0;r>16&1),r[e-1]&=65535;r[15]=i[15]-32767-(r[14]>>16&1);const e=r[15]>>16&1;r[14]&=65535,f(i,r,1-e)}for(let t=0;t<16;t++)e[2*t]=255&i[t],e[2*t+1]=i[t]>>8}function p(e){const t=new Uint8Array(32);return d(t,e),1&t[0]}function g(e,t,r){for(let i=0;i<16;i++)e[i]=t[i]+r[i]}function y(e,t,r){for(let i=0;i<16;i++)e[i]=t[i]-r[i]}function m(e,t,r){let i,n,s=0,o=0,a=0,h=0,c=0,u=0,l=0,f=0,d=0,p=0,g=0,y=0,m=0,v=0,w=0,b=0,_=0,E=0,S=0,M=0,I=0,A=0,O=0,x=0,P=0,N=0,R=0,T=0,L=0,C=0,U=0,k=r[0],j=r[1],q=r[2],D=r[3],z=r[4],$=r[5],B=r[6],K=r[7],F=r[8],V=r[9],H=r[10],W=r[11],G=r[12],J=r[13],Y=r[14],X=r[15];i=t[0],s+=i*k,o+=i*j,a+=i*q,h+=i*D,c+=i*z,u+=i*$,l+=i*B,f+=i*K,d+=i*F,p+=i*V,g+=i*H,y+=i*W,m+=i*G,v+=i*J,w+=i*Y,b+=i*X,i=t[1],o+=i*k,a+=i*j,h+=i*q,c+=i*D,u+=i*z,l+=i*$,f+=i*B,d+=i*K,p+=i*F,g+=i*V,y+=i*H,m+=i*W,v+=i*G,w+=i*J,b+=i*Y,_+=i*X,i=t[2],a+=i*k,h+=i*j,c+=i*q,u+=i*D,l+=i*z,f+=i*$,d+=i*B,p+=i*K,g+=i*F,y+=i*V,m+=i*H,v+=i*W,w+=i*G,b+=i*J,_+=i*Y,E+=i*X,i=t[3],h+=i*k,c+=i*j,u+=i*q,l+=i*D,f+=i*z,d+=i*$,p+=i*B,g+=i*K,y+=i*F,m+=i*V,v+=i*H,w+=i*W,b+=i*G,_+=i*J,E+=i*Y,S+=i*X,i=t[4],c+=i*k,u+=i*j,l+=i*q,f+=i*D,d+=i*z,p+=i*$,g+=i*B,y+=i*K,m+=i*F,v+=i*V,w+=i*H,b+=i*W,_+=i*G,E+=i*J,S+=i*Y,M+=i*X,i=t[5],u+=i*k,l+=i*j,f+=i*q,d+=i*D,p+=i*z,g+=i*$,y+=i*B,m+=i*K,v+=i*F,w+=i*V,b+=i*H,_+=i*W,E+=i*G,S+=i*J,M+=i*Y,I+=i*X,i=t[6],l+=i*k,f+=i*j,d+=i*q,p+=i*D,g+=i*z,y+=i*$,m+=i*B,v+=i*K,w+=i*F,b+=i*V,_+=i*H,E+=i*W,S+=i*G,M+=i*J,I+=i*Y,A+=i*X,i=t[7],f+=i*k,d+=i*j,p+=i*q,g+=i*D,y+=i*z,m+=i*$,v+=i*B,w+=i*K,b+=i*F,_+=i*V,E+=i*H,S+=i*W,M+=i*G,I+=i*J,A+=i*Y,O+=i*X,i=t[8],d+=i*k,p+=i*j,g+=i*q,y+=i*D,m+=i*z,v+=i*$,w+=i*B,b+=i*K,_+=i*F,E+=i*V,S+=i*H,M+=i*W,I+=i*G,A+=i*J,O+=i*Y,x+=i*X,i=t[9],p+=i*k,g+=i*j,y+=i*q,m+=i*D,v+=i*z,w+=i*$,b+=i*B,_+=i*K,E+=i*F,S+=i*V,M+=i*H,I+=i*W,A+=i*G,O+=i*J,x+=i*Y,P+=i*X,i=t[10],g+=i*k,y+=i*j,m+=i*q,v+=i*D,w+=i*z,b+=i*$,_+=i*B,E+=i*K,S+=i*F,M+=i*V,I+=i*H,A+=i*W,O+=i*G,x+=i*J,P+=i*Y,N+=i*X,i=t[11],y+=i*k,m+=i*j,v+=i*q,w+=i*D,b+=i*z,_+=i*$,E+=i*B,S+=i*K,M+=i*F,I+=i*V,A+=i*H,O+=i*W,x+=i*G,P+=i*J,N+=i*Y,R+=i*X,i=t[12],m+=i*k,v+=i*j,w+=i*q,b+=i*D,_+=i*z,E+=i*$,S+=i*B,M+=i*K,I+=i*F,A+=i*V,O+=i*H,x+=i*W,P+=i*G,N+=i*J,R+=i*Y,T+=i*X,i=t[13],v+=i*k,w+=i*j,b+=i*q,_+=i*D,E+=i*z,S+=i*$,M+=i*B,I+=i*K,A+=i*F,O+=i*V,x+=i*H,P+=i*W,N+=i*G,R+=i*J,T+=i*Y,L+=i*X,i=t[14],w+=i*k,b+=i*j,_+=i*q,E+=i*D,S+=i*z,M+=i*$,I+=i*B,A+=i*K,O+=i*F,x+=i*V,P+=i*H,N+=i*W,R+=i*G,T+=i*J,L+=i*Y,C+=i*X,i=t[15],b+=i*k,_+=i*j,E+=i*q,S+=i*D,M+=i*z,I+=i*$,A+=i*B,O+=i*K,x+=i*F,P+=i*V,N+=i*H,R+=i*W,T+=i*G,L+=i*J,C+=i*Y,U+=i*X,s+=38*_,o+=38*E,a+=38*S,h+=38*M,c+=38*I,u+=38*A,l+=38*O,f+=38*x,d+=38*P,p+=38*N,g+=38*R,y+=38*T,m+=38*L,v+=38*C,w+=38*U,n=1,i=s+n+65535,n=Math.floor(i/65536),s=i-65536*n,i=o+n+65535,n=Math.floor(i/65536),o=i-65536*n,i=a+n+65535,n=Math.floor(i/65536),a=i-65536*n,i=h+n+65535,n=Math.floor(i/65536),h=i-65536*n,i=c+n+65535,n=Math.floor(i/65536),c=i-65536*n,i=u+n+65535,n=Math.floor(i/65536),u=i-65536*n,i=l+n+65535,n=Math.floor(i/65536),l=i-65536*n,i=f+n+65535,n=Math.floor(i/65536),f=i-65536*n,i=d+n+65535,n=Math.floor(i/65536),d=i-65536*n,i=p+n+65535,n=Math.floor(i/65536),p=i-65536*n,i=g+n+65535,n=Math.floor(i/65536),g=i-65536*n,i=y+n+65535,n=Math.floor(i/65536),y=i-65536*n,i=m+n+65535,n=Math.floor(i/65536),m=i-65536*n,i=v+n+65535,n=Math.floor(i/65536),v=i-65536*n,i=w+n+65535,n=Math.floor(i/65536),w=i-65536*n,i=b+n+65535,n=Math.floor(i/65536),b=i-65536*n,s+=n-1+37*(n-1),n=1,i=s+n+65535,n=Math.floor(i/65536),s=i-65536*n,i=o+n+65535,n=Math.floor(i/65536),o=i-65536*n,i=a+n+65535,n=Math.floor(i/65536),a=i-65536*n,i=h+n+65535,n=Math.floor(i/65536),h=i-65536*n,i=c+n+65535,n=Math.floor(i/65536),c=i-65536*n,i=u+n+65535,n=Math.floor(i/65536),u=i-65536*n,i=l+n+65535,n=Math.floor(i/65536),l=i-65536*n,i=f+n+65535,n=Math.floor(i/65536),f=i-65536*n,i=d+n+65535,n=Math.floor(i/65536),d=i-65536*n,i=p+n+65535,n=Math.floor(i/65536),p=i-65536*n,i=g+n+65535,n=Math.floor(i/65536),g=i-65536*n,i=y+n+65535,n=Math.floor(i/65536),y=i-65536*n,i=m+n+65535,n=Math.floor(i/65536),m=i-65536*n,i=v+n+65535,n=Math.floor(i/65536),v=i-65536*n,i=w+n+65535,n=Math.floor(i/65536),w=i-65536*n,i=b+n+65535,n=Math.floor(i/65536),b=i-65536*n,s+=n-1+37*(n-1),e[0]=s,e[1]=o,e[2]=a,e[3]=h,e[4]=c,e[5]=u,e[6]=l,e[7]=f,e[8]=d,e[9]=p,e[10]=g,e[11]=y,e[12]=m,e[13]=v,e[14]=w,e[15]=b}function v(e,t){m(e,t,t)}function w(e,t){const r=n(),i=n(),s=n(),o=n(),h=n(),c=n(),u=n(),l=n(),f=n();y(r,e[1],e[0]),y(f,t[1],t[0]),m(r,r,f),g(i,e[0],e[1]),g(f,t[0],t[1]),m(i,i,f),m(s,e[3],t[3]),m(s,s,a),m(o,e[2],t[2]),g(o,o,o),y(h,i,r),y(c,o,s),g(u,o,s),g(l,i,r),m(e[0],h,c),m(e[1],l,u),m(e[2],u,c),m(e[3],h,l)}function b(e,t,r){for(let i=0;i<4;i++)f(e[i],t[i],r)}function _(e,t){const r=n(),i=n(),s=n();(function(e,t){const r=n();let i;for(i=0;i<16;i++)r[i]=t[i];for(i=253;i>=0;i--)v(r,r),2!==i&&4!==i&&m(r,r,t);for(i=0;i<16;i++)e[i]=r[i]})(s,t[2]),m(r,t[0],s),m(i,t[1],s),d(e,i),e[31]^=p(r)<<7}function E(e,t){const r=[n(),n(),n(),n()];u(r[0],h),u(r[1],c),u(r[2],o),m(r[3],h,c),function(e,t,r){u(e[0],s),u(e[1],o),u(e[2],o),u(e[3],s);for(let i=255;i>=0;--i){const n=r[i/8|0]>>(7&i)&1;b(e,t,n),w(t,e),w(e,e),b(e,t,n)}}(e,r,t)}t._w=function(e){if(e.length!==t.aP)throw new Error(`ed25519: seed must be ${t.aP} bytes`);const r=(0,i.hash)(e);r[0]&=248,r[31]&=127,r[31]|=64;const s=new Uint8Array(32),o=[n(),n(),n(),n()];E(o,r),_(s,o);const a=new Uint8Array(64);return a.set(e),a.set(s,32),{publicKey:s,secretKey:a}};const S=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function M(e,t){let r,i,n,s;for(i=63;i>=32;--i){for(r=0,n=i-32,s=i-12;n>4)*S[n],r=t[n]>>8,t[n]&=255;for(n=0;n<32;n++)t[n]-=r*S[n];for(i=0;i<32;i++)t[i+1]+=t[i]>>8,e[i]=255&t[i]}function I(e){const t=new Float64Array(64);for(let r=0;r<64;r++)t[r]=e[r];for(let t=0;t<64;t++)e[t]=0;M(e,t)}t.Xx=function(e,t){const r=new Float64Array(64),s=[n(),n(),n(),n()],o=(0,i.hash)(e.subarray(0,32));o[0]&=248,o[31]&=127,o[31]|=64;const a=new Uint8Array(64);a.set(o.subarray(32),32);const h=new i.SHA512;h.update(a.subarray(32)),h.update(t);const c=h.digest();h.clean(),I(c),E(s,c),_(a,s),h.reset(),h.update(a.subarray(0,32)),h.update(e.subarray(32)),h.update(t);const u=h.digest();I(u);for(let e=0;e<32;e++)r[e]=c[e];for(let e=0;e<32;e++)for(let t=0;t<32;t++)r[e+t]+=u[e]*o[t];return M(a.subarray(32),r),a}},9984:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSerializableHash=function(e){return void 0!==e.saveState&&void 0!==e.restoreState&&void 0!==e.cleanSavedState}},512:(e,t,r)=>{var i=r(5629),n=r(7309),s=function(){function e(e,t,r,n){void 0===r&&(r=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=n;var s=i.hmac(this._hash,r,t);this._hmac=new i.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return e.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(0===e)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},e.prototype.expand=function(e){for(var t=new Uint8Array(e),r=0;r{Object.defineProperty(t,"__esModule",{value:!0});var i=r(9984),n=r(4153),s=r(7309),o=function(){function e(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var r=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(r).clean():r.set(t);for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.mul=Math.imul||function(e,t){var r=65535&e,i=65535&t;return r*i+((e>>>16&65535)*i+r*(t>>>16&65535)<<16>>>0)|0},t.add=function(e,t){return e+t|0},t.sub=function(e,t){return e-t|0},t.rotl=function(e,t){return e<>>32-t},t.rotr=function(e,t){return e<<32-t|e>>>t},t.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.MAX_SAFE_INTEGER=9007199254740991,t.isSafeInteger=function(e){return t.isInteger(e)&&e>=-t.MAX_SAFE_INTEGER&&e<=t.MAX_SAFE_INTEGER}},3027:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});var i=r(4153),n=r(7309);t.DIGEST_LENGTH=16;var s=function(){function e(e){this.digestLength=t.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=8191&r;var i=e[2]|e[3]<<8;this._r[1]=8191&(r>>>13|i<<3);var n=e[4]|e[5]<<8;this._r[2]=7939&(i>>>10|n<<6);var s=e[6]|e[7]<<8;this._r[3]=8191&(n>>>7|s<<9);var o=e[8]|e[9]<<8;this._r[4]=255&(s>>>4|o<<12),this._r[5]=o>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=8191&(o>>>14|a<<2);var h=e[12]|e[13]<<8;this._r[7]=8065&(a>>>11|h<<5);var c=e[14]|e[15]<<8;this._r[8]=8191&(h>>>8|c<<8),this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return e.prototype._blocks=function(e,t,r){for(var i=this._fin?0:2048,n=this._h[0],s=this._h[1],o=this._h[2],a=this._h[3],h=this._h[4],c=this._h[5],u=this._h[6],l=this._h[7],f=this._h[8],d=this._h[9],p=this._r[0],g=this._r[1],y=this._r[2],m=this._r[3],v=this._r[4],w=this._r[5],b=this._r[6],_=this._r[7],E=this._r[8],S=this._r[9];r>=16;){var M=e[t+0]|e[t+1]<<8;n+=8191&M;var I=e[t+2]|e[t+3]<<8;s+=8191&(M>>>13|I<<3);var A=e[t+4]|e[t+5]<<8;o+=8191&(I>>>10|A<<6);var O=e[t+6]|e[t+7]<<8;a+=8191&(A>>>7|O<<9);var x=e[t+8]|e[t+9]<<8;h+=8191&(O>>>4|x<<12),c+=x>>>1&8191;var P=e[t+10]|e[t+11]<<8;u+=8191&(x>>>14|P<<2);var N=e[t+12]|e[t+13]<<8;l+=8191&(P>>>11|N<<5);var R=e[t+14]|e[t+15]<<8,T=0,L=T;L+=n*p,L+=s*(5*S),L+=o*(5*E),L+=a*(5*_),T=(L+=h*(5*b))>>>13,L&=8191,L+=c*(5*w),L+=u*(5*v),L+=l*(5*m),L+=(f+=8191&(N>>>8|R<<8))*(5*y);var C=T+=(L+=(d+=R>>>5|i)*(5*g))>>>13;C+=n*g,C+=s*p,C+=o*(5*S),C+=a*(5*E),T=(C+=h*(5*_))>>>13,C&=8191,C+=c*(5*b),C+=u*(5*w),C+=l*(5*v),C+=f*(5*m),T+=(C+=d*(5*y))>>>13,C&=8191;var U=T;U+=n*y,U+=s*g,U+=o*p,U+=a*(5*S),T=(U+=h*(5*E))>>>13,U&=8191,U+=c*(5*_),U+=u*(5*b),U+=l*(5*w),U+=f*(5*v);var k=T+=(U+=d*(5*m))>>>13;k+=n*m,k+=s*y,k+=o*g,k+=a*p,T=(k+=h*(5*S))>>>13,k&=8191,k+=c*(5*E),k+=u*(5*_),k+=l*(5*b),k+=f*(5*w);var j=T+=(k+=d*(5*v))>>>13;j+=n*v,j+=s*m,j+=o*y,j+=a*g,T=(j+=h*p)>>>13,j&=8191,j+=c*(5*S),j+=u*(5*E),j+=l*(5*_),j+=f*(5*b);var q=T+=(j+=d*(5*w))>>>13;q+=n*w,q+=s*v,q+=o*m,q+=a*y,T=(q+=h*g)>>>13,q&=8191,q+=c*p,q+=u*(5*S),q+=l*(5*E),q+=f*(5*_);var D=T+=(q+=d*(5*b))>>>13;D+=n*b,D+=s*w,D+=o*v,D+=a*m,T=(D+=h*y)>>>13,D&=8191,D+=c*g,D+=u*p,D+=l*(5*S),D+=f*(5*E);var z=T+=(D+=d*(5*_))>>>13;z+=n*_,z+=s*b,z+=o*w,z+=a*v,T=(z+=h*m)>>>13,z&=8191,z+=c*y,z+=u*g,z+=l*p,z+=f*(5*S);var $=T+=(z+=d*(5*E))>>>13;$+=n*E,$+=s*_,$+=o*b,$+=a*w,T=($+=h*v)>>>13,$&=8191,$+=c*m,$+=u*y,$+=l*g,$+=f*p;var B=T+=($+=d*(5*S))>>>13;B+=n*S,B+=s*E,B+=o*_,B+=a*b,T=(B+=h*w)>>>13,B&=8191,B+=c*v,B+=u*m,B+=l*y,B+=f*g,n=L=8191&(T=(T=((T+=(B+=d*p)>>>13)<<2)+T|0)+(L&=8191)|0),s=C+=T>>>=13,o=U&=8191,a=k&=8191,h=j&=8191,c=q&=8191,u=D&=8191,l=z&=8191,f=$&=8191,d=B&=8191,t+=16,r-=16}this._h[0]=n,this._h[1]=s,this._h[2]=o,this._h[3]=a,this._h[4]=h,this._h[5]=c,this._h[6]=u,this._h[7]=l,this._h[8]=f,this._h[9]=d},e.prototype.finish=function(e,t){void 0===t&&(t=0);var r,i,n,s,o=new Uint16Array(10);if(this._leftover){for(s=this._leftover,this._buffer[s++]=1;s<16;s++)this._buffer[s]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(r=this._h[1]>>>13,this._h[1]&=8191,s=2;s<10;s++)this._h[s]+=r,r=this._h[s]>>>13,this._h[s]&=8191;for(this._h[0]+=5*r,r=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=r,r=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=r,o[0]=this._h[0]+5,r=o[0]>>>13,o[0]&=8191,s=1;s<10;s++)o[s]=this._h[s]+r,r=o[s]>>>13,o[s]&=8191;for(o[9]-=8192,i=(1^r)-1,s=0;s<10;s++)o[s]&=i;for(i=~i,s=0;s<10;s++)this._h[s]=this._h[s]&i|o[s];for(this._h[0]=65535&(this._h[0]|this._h[1]<<13),this._h[1]=65535&(this._h[1]>>>3|this._h[2]<<10),this._h[2]=65535&(this._h[2]>>>6|this._h[3]<<7),this._h[3]=65535&(this._h[3]>>>9|this._h[4]<<4),this._h[4]=65535&(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14),this._h[5]=65535&(this._h[6]>>>2|this._h[7]<<11),this._h[6]=65535&(this._h[7]>>>5|this._h[8]<<8),this._h[7]=65535&(this._h[8]>>>8|this._h[9]<<5),n=this._h[0]+this._pad[0],this._h[0]=65535&n,s=1;s<8;s++)n=(this._h[s]+this._pad[s]|0)+(n>>>16)|0,this._h[s]=65535&n;return e[t+0]=this._h[0]>>>0,e[t+1]=this._h[0]>>>8,e[t+2]=this._h[1]>>>0,e[t+3]=this._h[1]>>>8,e[t+4]=this._h[2]>>>0,e[t+5]=this._h[2]>>>8,e[t+6]=this._h[3]>>>0,e[t+7]=this._h[3]>>>8,e[t+8]=this._h[4]>>>0,e[t+9]=this._h[4]>>>8,e[t+10]=this._h[5]>>>0,e[t+11]=this._h[5]>>>8,e[t+12]=this._h[6]>>>0,e[t+13]=this._h[6]>>>8,e[t+14]=this._h[7]>>>0,e[t+15]=this._h[7]>>>8,this._finished=!0,this},e.prototype.update=function(e){var t,r=0,i=e.length;if(this._leftover){(t=16-this._leftover)>i&&(t=i);for(var n=0;n=16&&(t=i-i%16,this._blocks(e,r,t),r+=t,i-=t),i){for(n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.randomStringForEntropy=t.randomString=t.randomUint32=t.randomBytes=t.defaultRandomSource=void 0;const i=r(6008),n=r(8099),s=r(7309);function o(e,r=t.defaultRandomSource){return r.randomBytes(e)}t.defaultRandomSource=new i.SystemRandomSource,t.randomBytes=o,t.randomUint32=function(e=t.defaultRandomSource){const r=o(4,e),i=(0,n.readUint32LE)(r);return(0,s.wipe)(r),i};const a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function h(e,r=a,i=t.defaultRandomSource){if(r.length<2)throw new Error("randomString charset is too short");if(r.length>256)throw new Error("randomString charset is too long");let n="";const h=r.length,c=256-256%h;for(;e>0;){const t=o(Math.ceil(256*e/c),i);for(let i=0;i0;i++){const s=t[i];s{Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserRandomSource=void 0,t.BrowserRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;const e="undefined"!=typeof self?self.crypto||self.msCrypto:null;e&&void 0!==e.getRandomValues&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");const t=new Uint8Array(e);for(let e=0;e{Object.defineProperty(t,"__esModule",{value:!0}),t.NodeRandomSource=void 0;const i=r(7309);t.NodeRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;{const e=r(5883);e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let t=this._crypto.randomBytes(e);if(t.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");const r=new Uint8Array(e);for(let e=0;e{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemRandomSource=void 0;const i=r(5455),n=r(8871);t.SystemRandomSource=class{constructor(){return this.isAvailable=!1,this.name="",this._source=new i.BrowserRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Browser")):(this._source=new n.NodeRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Node")):void 0)}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}}},3294:(e,t,r)=>{var i=r(8099),n=r(7309);t.k=32,t.cn=64;var s=function(){function e(){this.digestLength=t.k,this.blockSize=t.cn,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return e.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},e.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},e.prototype.clean=function(){n.wipe(this._buffer),n.wipe(this._temp),this.reset()},e.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var r=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[r++],t--;this._bufferLength===this.blockSize&&(a(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(r=a(this._temp,this._state,e,r,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[r++],t--;return this},e.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,r=this._bufferLength,n=t/536870912|0,s=t<<3,o=t%64<56?64:128;this._buffer[r]=128;for(var h=r+1;h0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},e.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},e.prototype.cleanSavedState=function(e){n.wipe(e.state),e.buffer&&n.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},e}();t.mE=s;var o=new Int32Array([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]);function a(e,t,r,n,s){for(;s>=64;){for(var a=t[0],h=t[1],c=t[2],u=t[3],l=t[4],f=t[5],d=t[6],p=t[7],g=0;g<16;g++){var y=n+4*g;e[g]=i.readUint32BE(r,y)}for(g=16;g<64;g++){var m=e[g-2],v=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,w=((m=e[g-15])>>>7|m<<25)^(m>>>18|m<<14)^m>>>3;e[g]=(v+e[g-7]|0)+(w+e[g-16]|0)}for(g=0;g<64;g++)v=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&f^~l&d)|0)+(p+(o[g]+e[g]|0)|0)|0,w=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&h^a&c^h&c)|0,p=d,d=f,f=l,l=u+v|0,u=c,c=h,h=a,a=v+w|0;t[0]+=a,t[1]+=h,t[2]+=c,t[3]+=u,t[4]+=l,t[5]+=f,t[6]+=d,t[7]+=p,n+=64,s-=64}return n}t.vp=function(e){var t=new s;t.update(e);var r=t.digest();return t.clean(),r}},3350:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});var i=r(8099),n=r(7309);t.DIGEST_LENGTH=64,t.BLOCK_SIZE=128;var s=function(){function e(){this.digestLength=t.DIGEST_LENGTH,this.blockSize=t.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return e.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},e.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},e.prototype.clean=function(){n.wipe(this._buffer),n.wipe(this._tempHi),n.wipe(this._tempLo),this.reset()},e.prototype.update=function(e,r){if(void 0===r&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var i=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[i++],r--;this._bufferLength===this.blockSize&&(a(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(i=a(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,i,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[i++],r--;return this},e.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,r=this._bufferLength,n=t/536870912|0,s=t<<3,o=t%128<112?128:256;this._buffer[r]=128;for(var h=r+1;h0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},e.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},e.prototype.cleanSavedState=function(e){n.wipe(e.stateHi),n.wipe(e.stateLo),e.buffer&&n.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},e}();t.SHA512=s;var o=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function a(e,t,r,n,s,a,h){for(var c,u,l,f,d,p,g,y,m=r[0],v=r[1],w=r[2],b=r[3],_=r[4],E=r[5],S=r[6],M=r[7],I=n[0],A=n[1],O=n[2],x=n[3],P=n[4],N=n[5],R=n[6],T=n[7];h>=128;){for(var L=0;L<16;L++){var C=8*L+a;e[L]=i.readUint32BE(s,C),t[L]=i.readUint32BE(s,C+4)}for(L=0;L<80;L++){var U,k,j=m,q=v,D=w,z=b,$=_,B=E,K=S,F=I,V=A,H=O,W=x,G=P,J=N,Y=R;if(d=65535&(u=T),p=u>>>16,g=65535&(c=M),y=c>>>16,d+=65535&(u=(P>>>14|_<<18)^(P>>>18|_<<14)^(_>>>9|P<<23)),p+=u>>>16,g+=65535&(c=(_>>>14|P<<18)^(_>>>18|P<<14)^(P>>>9|_<<23)),y+=c>>>16,d+=65535&(u=P&N^~P&R),p+=u>>>16,g+=65535&(c=_&E^~_&S),y+=c>>>16,c=o[2*L],d+=65535&(u=o[2*L+1]),p+=u>>>16,g+=65535&c,y+=c>>>16,c=e[L%16],p+=(u=t[L%16])>>>16,g+=65535&c,y+=c>>>16,g+=(p+=(d+=65535&u)>>>16)>>>16,d=65535&(u=f=65535&d|p<<16),p=u>>>16,g=65535&(c=l=65535&g|(y+=g>>>16)<<16),y=c>>>16,d+=65535&(u=(I>>>28|m<<4)^(m>>>2|I<<30)^(m>>>7|I<<25)),p+=u>>>16,g+=65535&(c=(m>>>28|I<<4)^(I>>>2|m<<30)^(I>>>7|m<<25)),y+=c>>>16,p+=(u=I&A^I&O^A&O)>>>16,g+=65535&(c=m&v^m&w^v&w),y+=c>>>16,U=65535&(g+=(p+=(d+=65535&u)>>>16)>>>16)|(y+=g>>>16)<<16,k=65535&d|p<<16,d=65535&(u=W),p=u>>>16,g=65535&(c=z),y=c>>>16,p+=(u=f)>>>16,g+=65535&(c=l),y+=c>>>16,v=j,w=q,b=D,_=z=65535&(g+=(p+=(d+=65535&u)>>>16)>>>16)|(y+=g>>>16)<<16,E=$,S=B,M=K,m=U,A=F,O=V,x=H,P=W=65535&d|p<<16,N=G,R=J,T=Y,I=k,L%16==15)for(C=0;C<16;C++)c=e[C],d=65535&(u=t[C]),p=u>>>16,g=65535&c,y=c>>>16,c=e[(C+9)%16],d+=65535&(u=t[(C+9)%16]),p+=u>>>16,g+=65535&c,y+=c>>>16,l=e[(C+1)%16],d+=65535&(u=((f=t[(C+1)%16])>>>1|l<<31)^(f>>>8|l<<24)^(f>>>7|l<<25)),p+=u>>>16,g+=65535&(c=(l>>>1|f<<31)^(l>>>8|f<<24)^l>>>7),y+=c>>>16,l=e[(C+14)%16],p+=(u=((f=t[(C+14)%16])>>>19|l<<13)^(l>>>29|f<<3)^(f>>>6|l<<26))>>>16,g+=65535&(c=(l>>>19|f<<13)^(f>>>29|l<<3)^l>>>6),y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,e[C]=65535&g|y<<16,t[C]=65535&d|p<<16}d=65535&(u=I),p=u>>>16,g=65535&(c=m),y=c>>>16,c=r[0],p+=(u=n[0])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[0]=m=65535&g|y<<16,n[0]=I=65535&d|p<<16,d=65535&(u=A),p=u>>>16,g=65535&(c=v),y=c>>>16,c=r[1],p+=(u=n[1])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[1]=v=65535&g|y<<16,n[1]=A=65535&d|p<<16,d=65535&(u=O),p=u>>>16,g=65535&(c=w),y=c>>>16,c=r[2],p+=(u=n[2])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[2]=w=65535&g|y<<16,n[2]=O=65535&d|p<<16,d=65535&(u=x),p=u>>>16,g=65535&(c=b),y=c>>>16,c=r[3],p+=(u=n[3])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[3]=b=65535&g|y<<16,n[3]=x=65535&d|p<<16,d=65535&(u=P),p=u>>>16,g=65535&(c=_),y=c>>>16,c=r[4],p+=(u=n[4])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[4]=_=65535&g|y<<16,n[4]=P=65535&d|p<<16,d=65535&(u=N),p=u>>>16,g=65535&(c=E),y=c>>>16,c=r[5],p+=(u=n[5])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[5]=E=65535&g|y<<16,n[5]=N=65535&d|p<<16,d=65535&(u=R),p=u>>>16,g=65535&(c=S),y=c>>>16,c=r[6],p+=(u=n[6])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[6]=S=65535&g|y<<16,n[6]=R=65535&d|p<<16,d=65535&(u=T),p=u>>>16,g=65535&(c=M),y=c>>>16,c=r[7],p+=(u=n[7])>>>16,g+=65535&c,y+=c>>>16,y+=(g+=(p+=(d+=65535&u)>>>16)>>>16)>>>16,r[7]=M=65535&g|y<<16,n[7]=T=65535&d|p<<16,a+=128,h-=128}return a}t.hash=function(e){var t=new s;t.update(e);var r=t.digest();return t.clean(),r}},7309:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wipe=function(e){for(var t=0;t{t.gi=t.Au=t.KS=t.kz=void 0;const i=r(1416),n=r(7309);function s(e){const t=new Float64Array(16);if(e)for(let r=0;r=0;--e){const t=r[e>>>3]>>>(7&e)&1;c(n,o,t),c(p,g,t),u(y,n,p),l(n,n,p),u(p,o,g),l(o,o,g),d(g,y),d(m,n),f(n,p,n),f(p,o,y),u(y,n,p),l(n,n,p),d(o,n),l(p,g,m),f(n,p,a),u(n,n,g),f(p,p,n),f(n,g,m),f(g,o,i),d(o,y),c(n,o,t),c(p,g,t)}for(let e=0;e<16;e++)i[e+16]=n[e],i[e+32]=p[e],i[e+48]=o[e],i[e+64]=g[e];const v=i.subarray(32),w=i.subarray(16);!function(e,t){const r=s();for(let e=0;e<16;e++)r[e]=t[e];for(let e=253;e>=0;e--)d(r,r),2!==e&&4!==e&&f(r,r,t);for(let t=0;t<16;t++)e[t]=r[t]}(v,v),f(w,w,v);const b=new Uint8Array(32);return function(e,t){const r=s(),i=s();for(let e=0;e<16;e++)i[e]=t[e];h(i),h(i),h(i);for(let e=0;e<2;e++){r[0]=i[0]-65517;for(let e=1;e<15;e++)r[e]=i[e]-65535-(r[e-1]>>16&1),r[e-1]&=65535;r[15]=i[15]-32767-(r[14]>>16&1);const e=r[15]>>16&1;r[14]&=65535,c(i,r,1-e)}for(let t=0;t<16;t++)e[2*t]=255&i[t],e[2*t+1]=i[t]>>8}(b,w),b}t.Au=function(e){const r=(0,i.randomBytes)(32,e),s=function(e){if(e.length!==t.KS)throw new Error(`x25519: seed must be ${t.KS} bytes`);const r=new Uint8Array(e);return{publicKey:(i=r,p(i,o)),secretKey:r};var i}(r);return(0,n.wipe)(r),s},t.gi=function(e,r,i=!1){if(e.length!==t.kz)throw new Error("X25519: incorrect secret key length");if(r.length!==t.kz)throw new Error("X25519: incorrect public key length");const n=p(e,r);if(i){let e=0;for(let t=0;t{function i(){return(null===r.g||void 0===r.g?void 0:r.g.crypto)||(null===r.g||void 0===r.g?void 0:r.g.msCrypto)||{}}function n(){const e=i();return e.subtle||e.webkitSubtle}Object.defineProperty(t,"__esModule",{value:!0}),t.isBrowserCryptoAvailable=t.getSubtleCrypto=t.getBrowerCrypto=void 0,t.getBrowerCrypto=i,t.getSubtleCrypto=n,t.isBrowserCryptoAvailable=function(){return!!i()&&!!n()}},8618:(e,t)=>{function r(){return"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product}function i(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node}Object.defineProperty(t,"__esModule",{value:!0}),t.isBrowser=t.isNode=t.isReactNative=void 0,t.isReactNative=r,t.isNode=i,t.isBrowser=function(){return!r()&&!i()}},1468:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(926),t),i.__exportStar(r(8618),t)},8200:(e,t,r)=>{r.d(t,{q:()=>i});class i{}},997:(e,t,r)=>{r.r(t),r.d(t,{IEvents:()=>i.q});var i=r(8200)},2568:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HEARTBEAT_EVENTS=t.HEARTBEAT_INTERVAL=void 0;const i=r(6736);t.HEARTBEAT_INTERVAL=i.FIVE_SECONDS,t.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}},3401:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),r(655).__exportStar(r(2568),t)},8969:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HeartBeat=void 0;const i=r(655),n=r(7187),s=r(6736),o=r(1614),a=r(3401);class h extends o.IHeartBeat{constructor(e){super(e),this.events=new n.EventEmitter,this.interval=a.HEARTBEAT_INTERVAL,this.interval=(null==e?void 0:e.interval)||a.HEARTBEAT_INTERVAL}static init(e){return i.__awaiter(this,void 0,void 0,(function*(){const t=new h(e);return yield t.init(),t}))}init(){return i.__awaiter(this,void 0,void 0,(function*(){yield this.initialize()}))}stop(){clearInterval(this.intervalRef)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}initialize(){return i.__awaiter(this,void 0,void 0,(function*(){this.intervalRef=setInterval((()=>this.pulse()),s.toMiliseconds(this.interval))}))}pulse(){this.events.emit(a.HEARTBEAT_EVENTS.pulse)}}t.HeartBeat=h},159:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(8969),t),i.__exportStar(r(1614),t),i.__exportStar(r(3401),t)},4174:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IHeartBeat=void 0;const i=r(997);class n extends i.IEvents{constructor(e){super()}}t.IHeartBeat=n},1614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),r(655).__exportStar(r(4174),t)},2030:e=>{e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},5150:(e,t,r)=>{const i=r(655),n=r(3954),s=i.__importDefault(r(653)),o=r(9728);t.ZP=class{constructor(){this.localStorage=s.default}getKeys(){return i.__awaiter(this,void 0,void 0,(function*(){return Object.keys(this.localStorage)}))}getEntries(){return i.__awaiter(this,void 0,void 0,(function*(){return Object.entries(this.localStorage).map(o.parseEntry)}))}getItem(e){return i.__awaiter(this,void 0,void 0,(function*(){const t=this.localStorage.getItem(e);if(null!==t)return n.safeJsonParse(t)}))}setItem(e,t){return i.__awaiter(this,void 0,void 0,(function*(){this.localStorage.setItem(e,n.safeJsonStringify(t))}))}removeItem(e){return i.__awaiter(this,void 0,void 0,(function*(){this.localStorage.removeItem(e)}))}}},653:(e,t,r)=>{!function(){let t;function i(){}t=i,t.prototype.getItem=function(e){return this.hasOwnProperty(e)?String(this[e]):null},t.prototype.setItem=function(e,t){this[e]=String(t)},t.prototype.removeItem=function(e){delete this[e]},t.prototype.clear=function(){const e=this;Object.keys(e).forEach((function(t){e[t]=void 0,delete e[t]}))},t.prototype.key=function(e){return e=e||0,Object.keys(this)[e]},t.prototype.__defineGetter__("length",(function(){return Object.keys(this).length})),void 0!==r.g&&r.g.localStorage?e.exports=r.g.localStorage:"undefined"!=typeof window&&window.localStorage?e.exports=window.localStorage:e.exports=new i}()},9728:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(9076),t),i.__exportStar(r(496),t)},9076:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IKeyValueStorage=void 0,t.IKeyValueStorage=class{}},496:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEntry=void 0;const i=r(3954);t.parseEntry=function(e){var t;return[e[0],i.safeJsonParse(null!==(t=e[1])&&void 0!==t?t:"")]}},5727:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PINO_CUSTOM_CONTEXT_KEY=t.PINO_LOGGER_DEFAULTS=void 0,t.PINO_LOGGER_DEFAULTS={level:"info"},t.PINO_CUSTOM_CONTEXT_KEY="custom_context"},9107:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pino=void 0;const i=r(655),n=i.__importDefault(r(6559));Object.defineProperty(t,"pino",{enumerable:!0,get:function(){return n.default}}),i.__exportStar(r(5727),t),i.__exportStar(r(8048),t)},8048:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.generateChildLogger=t.formatChildLoggerContext=t.getLoggerContext=t.setBrowserLoggerContext=t.getBrowserLoggerContext=t.getDefaultLoggerOptions=void 0;const i=r(5727);function n(e,t=i.PINO_CUSTOM_CONTEXT_KEY){return e[t]||""}function s(e,t,r=i.PINO_CUSTOM_CONTEXT_KEY){return e[r]=t,e}function o(e,t=i.PINO_CUSTOM_CONTEXT_KEY){let r="";return r=void 0===e.bindings?n(e,t):e.bindings().context||"",r}function a(e,t,r=i.PINO_CUSTOM_CONTEXT_KEY){const n=o(e,r);return n.trim()?`${n}/${t}`:t}t.getDefaultLoggerOptions=function(e){return Object.assign(Object.assign({},e),{level:(null==e?void 0:e.level)||i.PINO_LOGGER_DEFAULTS.level})},t.getBrowserLoggerContext=n,t.setBrowserLoggerContext=s,t.getLoggerContext=o,t.formatChildLoggerContext=a,t.generateChildLogger=function(e,t,r=i.PINO_CUSTOM_CONTEXT_KEY){const n=a(e,t,r);return s(e.child({context:n}),n,r)}},1882:()=>{},3014:()=>{},6900:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(6869),t),i.__exportStar(r(8033),t)},6869:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_THOUSAND=t.ONE_HUNDRED=void 0,t.ONE_HUNDRED=100,t.ONE_THOUSAND=1e3},8033:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=5*t.ONE_MINUTE,t.TEN_MINUTES=10*t.ONE_MINUTE,t.THIRTY_MINUTES=30*t.ONE_MINUTE,t.SIXTY_MINUTES=60*t.ONE_MINUTE,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=3*t.ONE_HOUR,t.SIX_HOURS=6*t.ONE_HOUR,t.TWELVE_HOURS=12*t.ONE_HOUR,t.TWENTY_FOUR_HOURS=24*t.ONE_HOUR,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=3*t.ONE_DAY,t.FIVE_DAYS=5*t.ONE_DAY,t.SEVEN_DAYS=7*t.ONE_DAY,t.THIRTY_DAYS=30*t.ONE_DAY,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=2*t.ONE_WEEK,t.THREE_WEEKS=3*t.ONE_WEEK,t.FOUR_WEEKS=4*t.ONE_WEEK,t.ONE_YEAR=365*t.ONE_DAY},6736:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(4273),t),i.__exportStar(r(7001),t),i.__exportStar(r(2939),t),i.__exportStar(r(6900),t)},2939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),r(655).__exportStar(r(8766),t)},8766:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IWatch=void 0,t.IWatch=class{}},3207:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fromMiliseconds=t.toMiliseconds=void 0;const i=r(6900);t.toMiliseconds=function(e){return e*i.ONE_THOUSAND},t.fromMiliseconds=function(e){return Math.floor(e/i.ONE_THOUSAND)}},3873:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.delay=void 0,t.delay=function(e){return new Promise((t=>{setTimeout((()=>{t(!0)}),e)}))}},4273:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=r(655);i.__exportStar(r(3873),t),i.__exportStar(r(3207),t)},7001:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Watch=void 0;class r{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){const t=this.get(e);if(void 0!==t.elapsed)throw new Error(`Watch already stopped for label: ${e}`);const r=Date.now()-t.started;this.timestamps.set(e,{started:t.started,elapsed:r})}get(e){const t=this.timestamps.get(e);if(void 0===t)throw new Error(`No timestamp found for label: ${e}`);return t}elapsed(e){const t=this.get(e);return t.elapsed||Date.now()-t.started}}t.Watch=r,t.default=r},2873:(e,t)=>{function r(e){let t;return"undefined"!=typeof window&&void 0!==window[e]&&(t=window[e]),t}function i(e){const t=r(e);if(!t)throw new Error(`${e} is not defined in Window`);return t}Object.defineProperty(t,"__esModule",{value:!0}),t.getLocalStorage=t.getLocalStorageOrThrow=t.getCrypto=t.getCryptoOrThrow=t.getLocation=t.getLocationOrThrow=t.getNavigator=t.getNavigatorOrThrow=t.getDocument=t.getDocumentOrThrow=t.getFromWindowOrThrow=t.getFromWindow=void 0,t.getFromWindow=r,t.getFromWindowOrThrow=i,t.getDocumentOrThrow=function(){return i("document")},t.getDocument=function(){return r("document")},t.getNavigatorOrThrow=function(){return i("navigator")},t.getNavigator=function(){return r("navigator")},t.getLocationOrThrow=function(){return i("location")},t.getLocation=function(){return r("location")},t.getCryptoOrThrow=function(){return i("crypto")},t.getCrypto=function(){return r("crypto")},t.getLocalStorageOrThrow=function(){return i("localStorage")},t.getLocalStorage=function(){return r("localStorage")}},5755:(e,t,r)=>{t.D=void 0;const i=r(2873);t.D=function(){let e,t;try{e=i.getDocumentOrThrow(),t=i.getLocationOrThrow()}catch(e){return null}function r(...t){const r=e.getElementsByTagName("meta");for(let e=0;ei.getAttribute(e))).filter((e=>!!e&&t.includes(e)));if(n.length&&n){const e=i.getAttribute("content");if(e)return e}}return""}const n=function(){let t=r("name","og:site_name","og:title","twitter:title");return t||(t=e.title),t}();return{description:r("description","og:description","twitter:description","keywords"),url:t.origin,icons:function(){const r=e.getElementsByTagName("link"),i=[];for(let e=0;e-1){const e=n.getAttribute("href");if(e)if(-1===e.toLowerCase().indexOf("https:")&&-1===e.toLowerCase().indexOf("http:")&&0!==e.indexOf("//")){let r=t.protocol+"//"+t.host;if(0===e.indexOf("/"))r+=e;else{const i=t.pathname.split("/");i.pop(),r+=i.join("/")+"/"+e}i.push(r)}else if(0===e.indexOf("//")){const r=t.protocol+e;i.push(r)}else i.push(e)}}return i}(),name:n}}},3550:function(e,t,r){!function(e,t){function i(e,t){if(!e)throw new Error(t||"Assertion failed")}function n(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function s(e,t,r){if(s.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var o;"object"==typeof e?e.exports=s:t.BN=s,s.BN=s,s.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:r(6601).Buffer}catch(e){}function a(e,t){var r=e.charCodeAt(t);return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void i(!1,"Invalid character in "+e)}function h(e,t,r){var i=a(e,r);return r-1>=t&&(i|=a(e,r-1)<<4),i}function c(e,t,r,n){for(var s=0,o=0,a=Math.min(e.length,r),h=t;h=49?c-49+10:c>=17?c-17+10:c,i(c>=0&&o0?e:t},s.min=function(e,t){return e.cmp(t)<0?e:t},s.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),i(t===(0|t)&&t>=2&&t<=36);var n=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(n++,this.negative=1),n=0;n-=3)o=e[n]|e[n-1]<<8|e[n-2]<<16,this.words[s]|=o<>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);else if("le"===r)for(n=0,s=0;n>>26-a&67108863,(a+=24)>=26&&(a-=26,s++);return this._strip()},s.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var i=0;i=t;i-=2)n=h(e,t,i)<=18?(s-=18,o+=1,this.words[o]|=n>>>26):s+=8;else for(i=(e.length-t)%2==0?t+1:t;i=18?(s-=18,o+=1,this.words[o]|=n>>>26):s+=8;this._strip()},s.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var i=0,n=1;n<=67108863;n*=t)i++;i--,n=n/t|0;for(var s=e.length-r,o=s%i,a=Math.min(s,s-o)+r,h=0,u=r;u1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=l}catch(e){s.prototype.inspect=l}else s.prototype.inspect=l;function l(){return(this.red?""}var f=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function g(e,t,r){r.negative=t.negative^e.negative;var i=e.length+t.length|0;r.length=i,i=i-1|0;var n=0|e.words[0],s=0|t.words[0],o=n*s,a=67108863&o,h=o/67108864|0;r.words[0]=a;for(var c=1;c>>26,l=67108863&h,f=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=f;d++){var p=c-d|0;u+=(o=(n=0|e.words[p])*(s=0|t.words[d])+l)/67108864|0,l=67108863&o}r.words[c]=0|l,h=0|u}return 0!==h?r.words[c]=0|h:r.length--,r._strip()}s.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var n=0,s=0,o=0;o>>24-n&16777215,(n+=2)>=26&&(n-=26,o--),r=0!==s||o!==this.length-1?f[6-h.length]+h+r:h+r}for(0!==s&&(r=s.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var c=d[e],u=p[e];r="";var l=this.clone();for(l.negative=0;!l.isZero();){var g=l.modrn(u).toString(e);r=(l=l.idivn(u)).isZero()?g+r:f[c-g.length]+g+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}i(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(e,t){return this.toArrayLike(o,e,t)}),s.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},s.prototype.toArrayLike=function(e,t,r){this._strip();var n=this.byteLength(),s=r||Math.max(1,n);i(n<=s,"byte array longer than desired length"),i(s>0,"Requested array length <= 0");var o=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,s);return this["_toArrayLike"+("le"===t?"LE":"BE")](o,n),o},s.prototype._toArrayLikeLE=function(e,t){for(var r=0,i=0,n=0,s=0;n>8&255),r>16&255),6===s?(r>24&255),i=0,s=0):(i=o>>>24,s+=2)}if(r=0&&(e[r--]=o>>8&255),r>=0&&(e[r--]=o>>16&255),6===s?(r>=0&&(e[r--]=o>>24&255),i=0,s=0):(i=o>>>24,s+=2)}if(r>=0)for(e[r--]=i;r>=0;)e[r--]=0},Math.clz32?s.prototype._countBits=function(e){return 32-Math.clz32(e)}:s.prototype._countBits=function(e){var t=e,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},s.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},s.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},s.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},s.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},s.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},s.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var i=0;ie.length?this.clone().ixor(e):e.clone().ixor(this)},s.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},s.prototype.inotn=function(e){i("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var n=0;n0&&(this.words[n]=~this.words[n]&67108863>>26-r),this._strip()},s.prototype.notn=function(e){return this.clone().inotn(e)},s.prototype.setn=function(e,t){i("number"==typeof e&&e>=0);var r=e/26|0,n=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,i=e):(r=e,i=this);for(var n=0,s=0;s>>26;for(;0!==n&&s>>26;if(this.length=r.length,0!==n)this.words[this.length]=n,this.length++;else if(r!==this)for(;se.length?this.clone().iadd(e):e.clone().iadd(this)},s.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,i,n=this.cmp(e);if(0===n)return this.negative=0,this.length=1,this.words[0]=0,this;n>0?(r=this,i=e):(r=e,i=this);for(var s=0,o=0;o>26,this.words[o]=67108863&t;for(;0!==s&&o>26,this.words[o]=67108863&t;if(0===s&&o>>13,d=0|o[1],p=8191&d,g=d>>>13,y=0|o[2],m=8191&y,v=y>>>13,w=0|o[3],b=8191&w,_=w>>>13,E=0|o[4],S=8191&E,M=E>>>13,I=0|o[5],A=8191&I,O=I>>>13,x=0|o[6],P=8191&x,N=x>>>13,R=0|o[7],T=8191&R,L=R>>>13,C=0|o[8],U=8191&C,k=C>>>13,j=0|o[9],q=8191&j,D=j>>>13,z=0|a[0],$=8191&z,B=z>>>13,K=0|a[1],F=8191&K,V=K>>>13,H=0|a[2],W=8191&H,G=H>>>13,J=0|a[3],Y=8191&J,X=J>>>13,Q=0|a[4],Z=8191&Q,ee=Q>>>13,te=0|a[5],re=8191&te,ie=te>>>13,ne=0|a[6],se=8191&ne,oe=ne>>>13,ae=0|a[7],he=8191&ae,ce=ae>>>13,ue=0|a[8],le=8191&ue,fe=ue>>>13,de=0|a[9],pe=8191&de,ge=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(i=Math.imul(l,$))|0)+((8191&(n=(n=Math.imul(l,B))+Math.imul(f,$)|0))<<13)|0;c=((s=Math.imul(f,B))+(n>>>13)|0)+(ye>>>26)|0,ye&=67108863,i=Math.imul(p,$),n=(n=Math.imul(p,B))+Math.imul(g,$)|0,s=Math.imul(g,B);var me=(c+(i=i+Math.imul(l,F)|0)|0)+((8191&(n=(n=n+Math.imul(l,V)|0)+Math.imul(f,F)|0))<<13)|0;c=((s=s+Math.imul(f,V)|0)+(n>>>13)|0)+(me>>>26)|0,me&=67108863,i=Math.imul(m,$),n=(n=Math.imul(m,B))+Math.imul(v,$)|0,s=Math.imul(v,B),i=i+Math.imul(p,F)|0,n=(n=n+Math.imul(p,V)|0)+Math.imul(g,F)|0,s=s+Math.imul(g,V)|0;var ve=(c+(i=i+Math.imul(l,W)|0)|0)+((8191&(n=(n=n+Math.imul(l,G)|0)+Math.imul(f,W)|0))<<13)|0;c=((s=s+Math.imul(f,G)|0)+(n>>>13)|0)+(ve>>>26)|0,ve&=67108863,i=Math.imul(b,$),n=(n=Math.imul(b,B))+Math.imul(_,$)|0,s=Math.imul(_,B),i=i+Math.imul(m,F)|0,n=(n=n+Math.imul(m,V)|0)+Math.imul(v,F)|0,s=s+Math.imul(v,V)|0,i=i+Math.imul(p,W)|0,n=(n=n+Math.imul(p,G)|0)+Math.imul(g,W)|0,s=s+Math.imul(g,G)|0;var we=(c+(i=i+Math.imul(l,Y)|0)|0)+((8191&(n=(n=n+Math.imul(l,X)|0)+Math.imul(f,Y)|0))<<13)|0;c=((s=s+Math.imul(f,X)|0)+(n>>>13)|0)+(we>>>26)|0,we&=67108863,i=Math.imul(S,$),n=(n=Math.imul(S,B))+Math.imul(M,$)|0,s=Math.imul(M,B),i=i+Math.imul(b,F)|0,n=(n=n+Math.imul(b,V)|0)+Math.imul(_,F)|0,s=s+Math.imul(_,V)|0,i=i+Math.imul(m,W)|0,n=(n=n+Math.imul(m,G)|0)+Math.imul(v,W)|0,s=s+Math.imul(v,G)|0,i=i+Math.imul(p,Y)|0,n=(n=n+Math.imul(p,X)|0)+Math.imul(g,Y)|0,s=s+Math.imul(g,X)|0;var be=(c+(i=i+Math.imul(l,Z)|0)|0)+((8191&(n=(n=n+Math.imul(l,ee)|0)+Math.imul(f,Z)|0))<<13)|0;c=((s=s+Math.imul(f,ee)|0)+(n>>>13)|0)+(be>>>26)|0,be&=67108863,i=Math.imul(A,$),n=(n=Math.imul(A,B))+Math.imul(O,$)|0,s=Math.imul(O,B),i=i+Math.imul(S,F)|0,n=(n=n+Math.imul(S,V)|0)+Math.imul(M,F)|0,s=s+Math.imul(M,V)|0,i=i+Math.imul(b,W)|0,n=(n=n+Math.imul(b,G)|0)+Math.imul(_,W)|0,s=s+Math.imul(_,G)|0,i=i+Math.imul(m,Y)|0,n=(n=n+Math.imul(m,X)|0)+Math.imul(v,Y)|0,s=s+Math.imul(v,X)|0,i=i+Math.imul(p,Z)|0,n=(n=n+Math.imul(p,ee)|0)+Math.imul(g,Z)|0,s=s+Math.imul(g,ee)|0;var _e=(c+(i=i+Math.imul(l,re)|0)|0)+((8191&(n=(n=n+Math.imul(l,ie)|0)+Math.imul(f,re)|0))<<13)|0;c=((s=s+Math.imul(f,ie)|0)+(n>>>13)|0)+(_e>>>26)|0,_e&=67108863,i=Math.imul(P,$),n=(n=Math.imul(P,B))+Math.imul(N,$)|0,s=Math.imul(N,B),i=i+Math.imul(A,F)|0,n=(n=n+Math.imul(A,V)|0)+Math.imul(O,F)|0,s=s+Math.imul(O,V)|0,i=i+Math.imul(S,W)|0,n=(n=n+Math.imul(S,G)|0)+Math.imul(M,W)|0,s=s+Math.imul(M,G)|0,i=i+Math.imul(b,Y)|0,n=(n=n+Math.imul(b,X)|0)+Math.imul(_,Y)|0,s=s+Math.imul(_,X)|0,i=i+Math.imul(m,Z)|0,n=(n=n+Math.imul(m,ee)|0)+Math.imul(v,Z)|0,s=s+Math.imul(v,ee)|0,i=i+Math.imul(p,re)|0,n=(n=n+Math.imul(p,ie)|0)+Math.imul(g,re)|0,s=s+Math.imul(g,ie)|0;var Ee=(c+(i=i+Math.imul(l,se)|0)|0)+((8191&(n=(n=n+Math.imul(l,oe)|0)+Math.imul(f,se)|0))<<13)|0;c=((s=s+Math.imul(f,oe)|0)+(n>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,i=Math.imul(T,$),n=(n=Math.imul(T,B))+Math.imul(L,$)|0,s=Math.imul(L,B),i=i+Math.imul(P,F)|0,n=(n=n+Math.imul(P,V)|0)+Math.imul(N,F)|0,s=s+Math.imul(N,V)|0,i=i+Math.imul(A,W)|0,n=(n=n+Math.imul(A,G)|0)+Math.imul(O,W)|0,s=s+Math.imul(O,G)|0,i=i+Math.imul(S,Y)|0,n=(n=n+Math.imul(S,X)|0)+Math.imul(M,Y)|0,s=s+Math.imul(M,X)|0,i=i+Math.imul(b,Z)|0,n=(n=n+Math.imul(b,ee)|0)+Math.imul(_,Z)|0,s=s+Math.imul(_,ee)|0,i=i+Math.imul(m,re)|0,n=(n=n+Math.imul(m,ie)|0)+Math.imul(v,re)|0,s=s+Math.imul(v,ie)|0,i=i+Math.imul(p,se)|0,n=(n=n+Math.imul(p,oe)|0)+Math.imul(g,se)|0,s=s+Math.imul(g,oe)|0;var Se=(c+(i=i+Math.imul(l,he)|0)|0)+((8191&(n=(n=n+Math.imul(l,ce)|0)+Math.imul(f,he)|0))<<13)|0;c=((s=s+Math.imul(f,ce)|0)+(n>>>13)|0)+(Se>>>26)|0,Se&=67108863,i=Math.imul(U,$),n=(n=Math.imul(U,B))+Math.imul(k,$)|0,s=Math.imul(k,B),i=i+Math.imul(T,F)|0,n=(n=n+Math.imul(T,V)|0)+Math.imul(L,F)|0,s=s+Math.imul(L,V)|0,i=i+Math.imul(P,W)|0,n=(n=n+Math.imul(P,G)|0)+Math.imul(N,W)|0,s=s+Math.imul(N,G)|0,i=i+Math.imul(A,Y)|0,n=(n=n+Math.imul(A,X)|0)+Math.imul(O,Y)|0,s=s+Math.imul(O,X)|0,i=i+Math.imul(S,Z)|0,n=(n=n+Math.imul(S,ee)|0)+Math.imul(M,Z)|0,s=s+Math.imul(M,ee)|0,i=i+Math.imul(b,re)|0,n=(n=n+Math.imul(b,ie)|0)+Math.imul(_,re)|0,s=s+Math.imul(_,ie)|0,i=i+Math.imul(m,se)|0,n=(n=n+Math.imul(m,oe)|0)+Math.imul(v,se)|0,s=s+Math.imul(v,oe)|0,i=i+Math.imul(p,he)|0,n=(n=n+Math.imul(p,ce)|0)+Math.imul(g,he)|0,s=s+Math.imul(g,ce)|0;var Me=(c+(i=i+Math.imul(l,le)|0)|0)+((8191&(n=(n=n+Math.imul(l,fe)|0)+Math.imul(f,le)|0))<<13)|0;c=((s=s+Math.imul(f,fe)|0)+(n>>>13)|0)+(Me>>>26)|0,Me&=67108863,i=Math.imul(q,$),n=(n=Math.imul(q,B))+Math.imul(D,$)|0,s=Math.imul(D,B),i=i+Math.imul(U,F)|0,n=(n=n+Math.imul(U,V)|0)+Math.imul(k,F)|0,s=s+Math.imul(k,V)|0,i=i+Math.imul(T,W)|0,n=(n=n+Math.imul(T,G)|0)+Math.imul(L,W)|0,s=s+Math.imul(L,G)|0,i=i+Math.imul(P,Y)|0,n=(n=n+Math.imul(P,X)|0)+Math.imul(N,Y)|0,s=s+Math.imul(N,X)|0,i=i+Math.imul(A,Z)|0,n=(n=n+Math.imul(A,ee)|0)+Math.imul(O,Z)|0,s=s+Math.imul(O,ee)|0,i=i+Math.imul(S,re)|0,n=(n=n+Math.imul(S,ie)|0)+Math.imul(M,re)|0,s=s+Math.imul(M,ie)|0,i=i+Math.imul(b,se)|0,n=(n=n+Math.imul(b,oe)|0)+Math.imul(_,se)|0,s=s+Math.imul(_,oe)|0,i=i+Math.imul(m,he)|0,n=(n=n+Math.imul(m,ce)|0)+Math.imul(v,he)|0,s=s+Math.imul(v,ce)|0,i=i+Math.imul(p,le)|0,n=(n=n+Math.imul(p,fe)|0)+Math.imul(g,le)|0,s=s+Math.imul(g,fe)|0;var Ie=(c+(i=i+Math.imul(l,pe)|0)|0)+((8191&(n=(n=n+Math.imul(l,ge)|0)+Math.imul(f,pe)|0))<<13)|0;c=((s=s+Math.imul(f,ge)|0)+(n>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,i=Math.imul(q,F),n=(n=Math.imul(q,V))+Math.imul(D,F)|0,s=Math.imul(D,V),i=i+Math.imul(U,W)|0,n=(n=n+Math.imul(U,G)|0)+Math.imul(k,W)|0,s=s+Math.imul(k,G)|0,i=i+Math.imul(T,Y)|0,n=(n=n+Math.imul(T,X)|0)+Math.imul(L,Y)|0,s=s+Math.imul(L,X)|0,i=i+Math.imul(P,Z)|0,n=(n=n+Math.imul(P,ee)|0)+Math.imul(N,Z)|0,s=s+Math.imul(N,ee)|0,i=i+Math.imul(A,re)|0,n=(n=n+Math.imul(A,ie)|0)+Math.imul(O,re)|0,s=s+Math.imul(O,ie)|0,i=i+Math.imul(S,se)|0,n=(n=n+Math.imul(S,oe)|0)+Math.imul(M,se)|0,s=s+Math.imul(M,oe)|0,i=i+Math.imul(b,he)|0,n=(n=n+Math.imul(b,ce)|0)+Math.imul(_,he)|0,s=s+Math.imul(_,ce)|0,i=i+Math.imul(m,le)|0,n=(n=n+Math.imul(m,fe)|0)+Math.imul(v,le)|0,s=s+Math.imul(v,fe)|0;var Ae=(c+(i=i+Math.imul(p,pe)|0)|0)+((8191&(n=(n=n+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;c=((s=s+Math.imul(g,ge)|0)+(n>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,i=Math.imul(q,W),n=(n=Math.imul(q,G))+Math.imul(D,W)|0,s=Math.imul(D,G),i=i+Math.imul(U,Y)|0,n=(n=n+Math.imul(U,X)|0)+Math.imul(k,Y)|0,s=s+Math.imul(k,X)|0,i=i+Math.imul(T,Z)|0,n=(n=n+Math.imul(T,ee)|0)+Math.imul(L,Z)|0,s=s+Math.imul(L,ee)|0,i=i+Math.imul(P,re)|0,n=(n=n+Math.imul(P,ie)|0)+Math.imul(N,re)|0,s=s+Math.imul(N,ie)|0,i=i+Math.imul(A,se)|0,n=(n=n+Math.imul(A,oe)|0)+Math.imul(O,se)|0,s=s+Math.imul(O,oe)|0,i=i+Math.imul(S,he)|0,n=(n=n+Math.imul(S,ce)|0)+Math.imul(M,he)|0,s=s+Math.imul(M,ce)|0,i=i+Math.imul(b,le)|0,n=(n=n+Math.imul(b,fe)|0)+Math.imul(_,le)|0,s=s+Math.imul(_,fe)|0;var Oe=(c+(i=i+Math.imul(m,pe)|0)|0)+((8191&(n=(n=n+Math.imul(m,ge)|0)+Math.imul(v,pe)|0))<<13)|0;c=((s=s+Math.imul(v,ge)|0)+(n>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,i=Math.imul(q,Y),n=(n=Math.imul(q,X))+Math.imul(D,Y)|0,s=Math.imul(D,X),i=i+Math.imul(U,Z)|0,n=(n=n+Math.imul(U,ee)|0)+Math.imul(k,Z)|0,s=s+Math.imul(k,ee)|0,i=i+Math.imul(T,re)|0,n=(n=n+Math.imul(T,ie)|0)+Math.imul(L,re)|0,s=s+Math.imul(L,ie)|0,i=i+Math.imul(P,se)|0,n=(n=n+Math.imul(P,oe)|0)+Math.imul(N,se)|0,s=s+Math.imul(N,oe)|0,i=i+Math.imul(A,he)|0,n=(n=n+Math.imul(A,ce)|0)+Math.imul(O,he)|0,s=s+Math.imul(O,ce)|0,i=i+Math.imul(S,le)|0,n=(n=n+Math.imul(S,fe)|0)+Math.imul(M,le)|0,s=s+Math.imul(M,fe)|0;var xe=(c+(i=i+Math.imul(b,pe)|0)|0)+((8191&(n=(n=n+Math.imul(b,ge)|0)+Math.imul(_,pe)|0))<<13)|0;c=((s=s+Math.imul(_,ge)|0)+(n>>>13)|0)+(xe>>>26)|0,xe&=67108863,i=Math.imul(q,Z),n=(n=Math.imul(q,ee))+Math.imul(D,Z)|0,s=Math.imul(D,ee),i=i+Math.imul(U,re)|0,n=(n=n+Math.imul(U,ie)|0)+Math.imul(k,re)|0,s=s+Math.imul(k,ie)|0,i=i+Math.imul(T,se)|0,n=(n=n+Math.imul(T,oe)|0)+Math.imul(L,se)|0,s=s+Math.imul(L,oe)|0,i=i+Math.imul(P,he)|0,n=(n=n+Math.imul(P,ce)|0)+Math.imul(N,he)|0,s=s+Math.imul(N,ce)|0,i=i+Math.imul(A,le)|0,n=(n=n+Math.imul(A,fe)|0)+Math.imul(O,le)|0,s=s+Math.imul(O,fe)|0;var Pe=(c+(i=i+Math.imul(S,pe)|0)|0)+((8191&(n=(n=n+Math.imul(S,ge)|0)+Math.imul(M,pe)|0))<<13)|0;c=((s=s+Math.imul(M,ge)|0)+(n>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,i=Math.imul(q,re),n=(n=Math.imul(q,ie))+Math.imul(D,re)|0,s=Math.imul(D,ie),i=i+Math.imul(U,se)|0,n=(n=n+Math.imul(U,oe)|0)+Math.imul(k,se)|0,s=s+Math.imul(k,oe)|0,i=i+Math.imul(T,he)|0,n=(n=n+Math.imul(T,ce)|0)+Math.imul(L,he)|0,s=s+Math.imul(L,ce)|0,i=i+Math.imul(P,le)|0,n=(n=n+Math.imul(P,fe)|0)+Math.imul(N,le)|0,s=s+Math.imul(N,fe)|0;var Ne=(c+(i=i+Math.imul(A,pe)|0)|0)+((8191&(n=(n=n+Math.imul(A,ge)|0)+Math.imul(O,pe)|0))<<13)|0;c=((s=s+Math.imul(O,ge)|0)+(n>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,i=Math.imul(q,se),n=(n=Math.imul(q,oe))+Math.imul(D,se)|0,s=Math.imul(D,oe),i=i+Math.imul(U,he)|0,n=(n=n+Math.imul(U,ce)|0)+Math.imul(k,he)|0,s=s+Math.imul(k,ce)|0,i=i+Math.imul(T,le)|0,n=(n=n+Math.imul(T,fe)|0)+Math.imul(L,le)|0,s=s+Math.imul(L,fe)|0;var Re=(c+(i=i+Math.imul(P,pe)|0)|0)+((8191&(n=(n=n+Math.imul(P,ge)|0)+Math.imul(N,pe)|0))<<13)|0;c=((s=s+Math.imul(N,ge)|0)+(n>>>13)|0)+(Re>>>26)|0,Re&=67108863,i=Math.imul(q,he),n=(n=Math.imul(q,ce))+Math.imul(D,he)|0,s=Math.imul(D,ce),i=i+Math.imul(U,le)|0,n=(n=n+Math.imul(U,fe)|0)+Math.imul(k,le)|0,s=s+Math.imul(k,fe)|0;var Te=(c+(i=i+Math.imul(T,pe)|0)|0)+((8191&(n=(n=n+Math.imul(T,ge)|0)+Math.imul(L,pe)|0))<<13)|0;c=((s=s+Math.imul(L,ge)|0)+(n>>>13)|0)+(Te>>>26)|0,Te&=67108863,i=Math.imul(q,le),n=(n=Math.imul(q,fe))+Math.imul(D,le)|0,s=Math.imul(D,fe);var Le=(c+(i=i+Math.imul(U,pe)|0)|0)+((8191&(n=(n=n+Math.imul(U,ge)|0)+Math.imul(k,pe)|0))<<13)|0;c=((s=s+Math.imul(k,ge)|0)+(n>>>13)|0)+(Le>>>26)|0,Le&=67108863;var Ce=(c+(i=Math.imul(q,pe))|0)+((8191&(n=(n=Math.imul(q,ge))+Math.imul(D,pe)|0))<<13)|0;return c=((s=Math.imul(D,ge))+(n>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,h[0]=ye,h[1]=me,h[2]=ve,h[3]=we,h[4]=be,h[5]=_e,h[6]=Ee,h[7]=Se,h[8]=Me,h[9]=Ie,h[10]=Ae,h[11]=Oe,h[12]=xe,h[13]=Pe,h[14]=Ne,h[15]=Re,h[16]=Te,h[17]=Le,h[18]=Ce,0!==c&&(h[19]=c,r.length++),r};function m(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var i=0,n=0,s=0;s>>26)|0)>>>26,o&=67108863}r.words[s]=a,i=o,o=n}return 0!==i?r.words[s]=i:r.length--,r._strip()}function v(e,t,r){return m(e,t,r)}function w(e,t){this.x=e,this.y=t}Math.imul||(y=g),s.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?y(this,e,t):r<63?g(this,e,t):r<1024?m(this,e,t):v(this,e,t)},w.prototype.makeRBT=function(e){for(var t=new Array(e),r=s.prototype._countBits(e)-1,i=0;i>=1;return i},w.prototype.permute=function(e,t,r,i,n,s){for(var o=0;o>>=1)n++;return 1<>>=13,r[2*o+1]=8191&s,s>>>=13;for(o=2*t;o>=26,r+=s/67108864|0,r+=o>>>26,this.words[n]=67108863&o}return 0!==r&&(this.words[n]=r,this.length++),t?this.ineg():this},s.prototype.muln=function(e){return this.clone().imuln(e)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>n&1}return t}(e);if(0===t.length)return new s(1);for(var r=this,i=0;i=0);var t,r=e%26,n=(e-r)/26,s=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(t=0;t>>26-r}o&&(this.words[t]=o,this.length++)}if(0!==n){for(t=this.length-1;t>=0;t--)this.words[t+n]=this.words[t];for(t=0;t=0),n=t?(t-t%26)/26:0;var s=e%26,o=Math.min((e-s)/26,this.length),a=67108863^67108863>>>s<o)for(this.length-=o,c=0;c=0&&(0!==u||c>=n);c--){var l=0|this.words[c];this.words[c]=u<<26-s|l>>>s,u=l&a}return h&&0!==u&&(h.words[h.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(e,t,r){return i(0===this.negative),this.iushrn(e,t,r)},s.prototype.shln=function(e){return this.clone().ishln(e)},s.prototype.ushln=function(e){return this.clone().iushln(e)},s.prototype.shrn=function(e){return this.clone().ishrn(e)},s.prototype.ushrn=function(e){return this.clone().iushrn(e)},s.prototype.testn=function(e){i("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,n=1<=0);var t=e%26,r=(e-t)/26;if(i(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var n=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},s.prototype.isubn=function(e){if(i("number"==typeof e),i(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(h/67108864|0),this.words[n+r]=67108863&s}for(;n>26,this.words[n+r]=67108863&s;if(0===a)return this._strip();for(i(-1===a),a=0,n=0;n>26,this.words[n]=67108863&s;return this.negative=1,this._strip()},s.prototype._wordDiv=function(e,t){var r=(this.length,e.length),i=this.clone(),n=e,o=0|n.words[n.length-1];0!=(r=26-this._countBits(o))&&(n=n.ushln(r),i.iushln(r),o=0|n.words[n.length-1]);var a,h=i.length-n.length;if("mod"!==t){(a=new s(null)).length=h+1,a.words=new Array(a.length);for(var c=0;c=0;l--){var f=67108864*(0|i.words[n.length+l])+(0|i.words[n.length+l-1]);for(f=Math.min(f/o|0,67108863),i._ishlnsubmul(n,f,l);0!==i.negative;)f--,i.negative=0,i._ishlnsubmul(n,1,l),i.isZero()||(i.negative^=1);a&&(a.words[l]=f)}return a&&a._strip(),i._strip(),"div"!==t&&0!==r&&i.iushrn(r),{div:a||null,mod:i}},s.prototype.divmod=function(e,t,r){return i(!e.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(n=a.div.neg()),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.iadd(e)),{div:n,mod:o}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(n=a.div.neg()),{div:n,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(o=a.mod.neg(),r&&0!==o.negative&&o.isub(e)),{div:a.div,mod:o}):e.length>this.length||this.cmp(e)<0?{div:new s(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new s(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new s(this.modrn(e.words[0]))}:this._wordDiv(e,t);var n,o,a},s.prototype.div=function(e){return this.divmod(e,"div",!1).div},s.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},s.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},s.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,i=e.ushrn(1),n=e.andln(1),s=r.cmp(i);return s<0||1===n&&0===s?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},s.prototype.modrn=function(e){var t=e<0;t&&(e=-e),i(e<=67108863);for(var r=(1<<26)%e,n=0,s=this.length-1;s>=0;s--)n=(r*n+(0|this.words[s]))%e;return t?-n:n},s.prototype.modn=function(e){return this.modrn(e)},s.prototype.idivn=function(e){var t=e<0;t&&(e=-e),i(e<=67108863);for(var r=0,n=this.length-1;n>=0;n--){var s=(0|this.words[n])+67108864*r;this.words[n]=s/e|0,r=s%e}return this._strip(),t?this.ineg():this},s.prototype.divn=function(e){return this.clone().idivn(e)},s.prototype.egcd=function(e){i(0===e.negative),i(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var n=new s(1),o=new s(0),a=new s(0),h=new s(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var u=r.clone(),l=t.clone();!t.isZero();){for(var f=0,d=1;0==(t.words[0]&d)&&f<26;++f,d<<=1);if(f>0)for(t.iushrn(f);f-- >0;)(n.isOdd()||o.isOdd())&&(n.iadd(u),o.isub(l)),n.iushrn(1),o.iushrn(1);for(var p=0,g=1;0==(r.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||h.isOdd())&&(a.iadd(u),h.isub(l)),a.iushrn(1),h.iushrn(1);t.cmp(r)>=0?(t.isub(r),n.isub(a),o.isub(h)):(r.isub(t),a.isub(n),h.isub(o))}return{a,b:h,gcd:r.iushln(c)}},s.prototype._invmp=function(e){i(0===e.negative),i(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var n,o=new s(1),a=new s(0),h=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,u=1;0==(t.words[0]&u)&&c<26;++c,u<<=1);if(c>0)for(t.iushrn(c);c-- >0;)o.isOdd()&&o.iadd(h),o.iushrn(1);for(var l=0,f=1;0==(r.words[0]&f)&&l<26;++l,f<<=1);if(l>0)for(r.iushrn(l);l-- >0;)a.isOdd()&&a.iadd(h),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),o.isub(a)):(r.isub(t),a.isub(o))}return(n=0===t.cmpn(1)?o:a).cmpn(0)<0&&n.iadd(e),n},s.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var i=0;t.isEven()&&r.isEven();i++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var n=t.cmp(r);if(n<0){var s=t;t=r,r=s}else if(0===n||0===r.cmpn(1))break;t.isub(r)}return r.iushln(i)},s.prototype.invm=function(e){return this.egcd(e).a.umod(e)},s.prototype.isEven=function(){return 0==(1&this.words[0])},s.prototype.isOdd=function(){return 1==(1&this.words[0])},s.prototype.andln=function(e){return this.words[0]&e},s.prototype.bincn=function(e){i("number"==typeof e);var t=e%26,r=(e-t)/26,n=1<>>26,a&=67108863,this.words[o]=a}return 0!==s&&(this.words[o]=s,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),i(e<=67108863,"Number is too big");var n=0|this.words[0];t=n===e?0:ne.length)return 1;if(this.length=0;r--){var i=0|this.words[r],n=0|e.words[r];if(i!==n){in&&(t=1);break}}return t},s.prototype.gtn=function(e){return 1===this.cmpn(e)},s.prototype.gt=function(e){return 1===this.cmp(e)},s.prototype.gten=function(e){return this.cmpn(e)>=0},s.prototype.gte=function(e){return this.cmp(e)>=0},s.prototype.ltn=function(e){return-1===this.cmpn(e)},s.prototype.lt=function(e){return-1===this.cmp(e)},s.prototype.lten=function(e){return this.cmpn(e)<=0},s.prototype.lte=function(e){return this.cmp(e)<=0},s.prototype.eqn=function(e){return 0===this.cmpn(e)},s.prototype.eq=function(e){return 0===this.cmp(e)},s.red=function(e){return new A(e)},s.prototype.toRed=function(e){return i(!this.red,"Already a number in reduction context"),i(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},s.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(e){return this.red=e,this},s.prototype.forceRed=function(e){return i(!this.red,"Already a number in reduction context"),this._forceRed(e)},s.prototype.redAdd=function(e){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},s.prototype.redIAdd=function(e){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},s.prototype.redSub=function(e){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},s.prototype.redISub=function(e){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},s.prototype.redShl=function(e){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},s.prototype.redMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},s.prototype.redIMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},s.prototype.redSqr=function(){return i(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return i(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return i(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return i(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return i(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(e){return i(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var b={k256:null,p224:null,p192:null,p25519:null};function _(e,t){this.name=e,this.p=new s(t,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function E(){_.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function S(){_.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function M(){_.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function I(){_.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=s._prime(e);this.m=t.p,this.prime=t}else i(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function O(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}_.prototype._tmp=function(){var e=new s(null);return e.words=new Array(Math.ceil(this.n/13)),e},_.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var i=t0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},_.prototype.split=function(e,t){e.iushrn(this.n,0,t)},_.prototype.imulK=function(e){return e.imul(this.k)},n(E,_),E.prototype.split=function(e,t){for(var r=4194303,i=Math.min(e.length,9),n=0;n>>22,s=o}s>>>=22,e.words[n-10]=s,0===s&&e.length>10?e.length-=10:e.length-=9},E.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=n,t=i}return 0!==t&&(e.words[e.length++]=t),e},s._prime=function(e){if(b[e])return b[e];var t;if("k256"===e)t=new E;else if("p224"===e)t=new S;else if("p192"===e)t=new M;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new I}return b[e]=t,t},A.prototype._verify1=function(e){i(0===e.negative,"red works only with positives"),i(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){i(0==(e.negative|t.negative),"red works only with positives"),i(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(u(e,e.umod(this.m)._forceRed(this)),e)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(i(t%2==1),3===t){var r=this.m.add(new s(1)).iushrn(2);return this.pow(e,r)}for(var n=this.m.subn(1),o=0;!n.isZero()&&0===n.andln(1);)o++,n.iushrn(1);i(!n.isZero());var a=new s(1).toRed(this),h=a.redNeg(),c=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new s(2*u*u).toRed(this);0!==this.pow(u,c).cmp(h);)u.redIAdd(h);for(var l=this.pow(u,n),f=this.pow(e,n.addn(1).iushrn(1)),d=this.pow(e,n),p=o;0!==d.cmp(a);){for(var g=d,y=0;0!==g.cmp(a);y++)g=g.redSqr();i(y=0;i--){for(var c=t.words[i],u=h-1;u>=0;u--){var l=c>>u&1;n!==r[0]&&(n=this.sqr(n)),0!==l||0!==o?(o<<=1,o|=l,(4==++a||0===i&&0===u)&&(n=this.mul(n,r[o]),a=0,o=0)):a=0}h=26}return n},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},s.mont=function(e){return new O(e)},n(O,A),O.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},O.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},O.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):n.cmpn(0)<0&&(s=n.iadd(this.m)),s._forceRed(this)},O.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new s(0)._forceRed(this);var r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),o=n;return n.cmp(this.m)>=0?o=n.isub(this.m):n.cmpn(0)<0&&(o=n.iadd(this.m)),o._forceRed(this)},O.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e=r.nmd(e),this)},4020:e=>{var t="%[a-f0-9]{2}",r=new RegExp("("+t+")|([^%]+?)","gi"),i=new RegExp("("+t+")+","gi");function n(e,t){try{return[decodeURIComponent(e.join(""))]}catch(e){}if(1===e.length)return e;t=t||1;var r=e.slice(0,t),i=e.slice(t);return Array.prototype.concat.call([],n(r),n(i))}function s(e){try{return decodeURIComponent(e)}catch(s){for(var t=e.match(r)||[],i=1;i{var t,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}g(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&g(e,"error",t,{once:!0})}(e,n)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,r,i){var n,s,o,c;if(a(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=h(e))>0&&o.length>n&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,c=u,console&&console.warn&&console.warn(c)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=u.bind(i);return n.listener=r,i.wrapFn=n,n}function f(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var h=s[e];if(void 0===h)return!1;if("function"==typeof h)i(h,this,t);else{var c=h.length,u=p(h,c);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},s.prototype.listeners=function(e){return f(this,e,!0)},s.prototype.rawListeners=function(e){return f(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):d.call(e,t)},s.prototype.listenerCount=d,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},2806:e=>{e.exports=function(e,t){for(var r={},i=Object.keys(e),n=Array.isArray(t),s=0;s{var i=t;i.utils=r(6436),i.common=r(5772),i.sha=r(9041),i.ripemd=r(2949),i.hmac=r(2344),i.sha1=i.sha.sha1,i.sha256=i.sha.sha256,i.sha224=i.sha.sha224,i.sha384=i.sha.sha384,i.sha512=i.sha.sha512,i.ripemd160=i.ripemd.ripemd160},5772:(e,t,r)=>{var i=r(6436),n=r(9746);function s(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}t.BlockHash=s,s.prototype.update=function(e,t){if(e=i.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=i.join32(e,0,e.length-r,this.endian);for(var n=0;n>>24&255,i[n++]=e>>>16&255,i[n++]=e>>>8&255,i[n++]=255&e}else for(i[n++]=255&e,i[n++]=e>>>8&255,i[n++]=e>>>16&255,i[n++]=e>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,s=8;s{var i=r(6436),n=r(9746);function s(e,t,r){if(!(this instanceof s))return new s(e,t,r);this.Hash=e,this.blockSize=e.blockSize/8,this.outSize=e.outSize/8,this.inner=null,this.outer=null,this._init(i.toArray(t,r))}e.exports=s,s.prototype._init=function(e){e.length>this.blockSize&&(e=(new this.Hash).update(e).digest()),n(e.length<=this.blockSize);for(var t=e.length;t{var i=r(6436),n=r(5772),s=i.rotl32,o=i.sum32,a=i.sum32_3,h=i.sum32_4,c=n.BlockHash;function u(){if(!(this instanceof u))return new u;c.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}function l(e,t,r,i){return e<=15?t^r^i:e<=31?t&r|~t&i:e<=47?(t|~r)^i:e<=63?t&i|r&~i:t^(r|~i)}function f(e){return e<=15?0:e<=31?1518500249:e<=47?1859775393:e<=63?2400959708:2840853838}function d(e){return e<=15?1352829926:e<=31?1548603684:e<=47?1836072691:e<=63?2053994217:0}i.inherits(u,c),t.ripemd160=u,u.blockSize=512,u.outSize=160,u.hmacStrength=192,u.padLength=64,u.prototype._update=function(e,t){for(var r=this.h[0],i=this.h[1],n=this.h[2],c=this.h[3],u=this.h[4],v=r,w=i,b=n,_=c,E=u,S=0;S<80;S++){var M=o(s(h(r,l(S,i,n,c),e[p[S]+t],f(S)),y[S]),u);r=u,u=c,c=s(n,10),n=i,i=M,M=o(s(h(v,l(79-S,w,b,_),e[g[S]+t],d(S)),m[S]),E),v=E,E=_,_=s(b,10),b=w,w=M}M=a(this.h[1],n,_),this.h[1]=a(this.h[2],c,E),this.h[2]=a(this.h[3],u,v),this.h[3]=a(this.h[4],r,w),this.h[4]=a(this.h[0],i,b),this.h[0]=M},u.prototype._digest=function(e){return"hex"===e?i.toHex32(this.h,"little"):i.split32(this.h,"little")};var p=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],g=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],y=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],m=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]},9041:(e,t,r)=>{t.sha1=r(4761),t.sha224=r(799),t.sha256=r(9344),t.sha384=r(772),t.sha512=r(5900)},4761:(e,t,r)=>{var i=r(6436),n=r(5772),s=r(7038),o=i.rotl32,a=i.sum32,h=i.sum32_5,c=s.ft_1,u=n.BlockHash,l=[1518500249,1859775393,2400959708,3395469782];function f(){if(!(this instanceof f))return new f;u.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}i.inherits(f,u),e.exports=f,f.blockSize=512,f.outSize=160,f.hmacStrength=80,f.padLength=64,f.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;i{var i=r(6436),n=r(9344);function s(){if(!(this instanceof s))return new s;n.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}i.inherits(s,n),e.exports=s,s.blockSize=512,s.outSize=224,s.hmacStrength=192,s.padLength=64,s.prototype._digest=function(e){return"hex"===e?i.toHex32(this.h.slice(0,7),"big"):i.split32(this.h.slice(0,7),"big")}},9344:(e,t,r)=>{var i=r(6436),n=r(5772),s=r(7038),o=r(9746),a=i.sum32,h=i.sum32_4,c=i.sum32_5,u=s.ch32,l=s.maj32,f=s.s0_256,d=s.s1_256,p=s.g0_256,g=s.g1_256,y=n.BlockHash,m=[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];function v(){if(!(this instanceof v))return new v;y.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=m,this.W=new Array(64)}i.inherits(v,y),e.exports=v,v.blockSize=512,v.outSize=256,v.hmacStrength=192,v.padLength=64,v.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;i{var i=r(6436),n=r(5900);function s(){if(!(this instanceof s))return new s;n.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}i.inherits(s,n),e.exports=s,s.blockSize=1024,s.outSize=384,s.hmacStrength=192,s.padLength=128,s.prototype._digest=function(e){return"hex"===e?i.toHex32(this.h.slice(0,12),"big"):i.split32(this.h.slice(0,12),"big")}},5900:(e,t,r)=>{var i=r(6436),n=r(5772),s=r(9746),o=i.rotr64_hi,a=i.rotr64_lo,h=i.shr64_hi,c=i.shr64_lo,u=i.sum64,l=i.sum64_hi,f=i.sum64_lo,d=i.sum64_4_hi,p=i.sum64_4_lo,g=i.sum64_5_hi,y=i.sum64_5_lo,m=n.BlockHash,v=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function w(){if(!(this instanceof w))return new w;m.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=v,this.W=new Array(160)}function b(e,t,r,i,n){var s=e&r^~e&n;return s<0&&(s+=4294967296),s}function _(e,t,r,i,n,s){var o=t&i^~t&s;return o<0&&(o+=4294967296),o}function E(e,t,r,i,n){var s=e&r^e&n^r&n;return s<0&&(s+=4294967296),s}function S(e,t,r,i,n,s){var o=t&i^t&s^i&s;return o<0&&(o+=4294967296),o}function M(e,t){var r=o(e,t,28)^o(t,e,2)^o(t,e,7);return r<0&&(r+=4294967296),r}function I(e,t){var r=a(e,t,28)^a(t,e,2)^a(t,e,7);return r<0&&(r+=4294967296),r}function A(e,t){var r=a(e,t,14)^a(e,t,18)^a(t,e,9);return r<0&&(r+=4294967296),r}function O(e,t){var r=o(e,t,1)^o(e,t,8)^h(e,t,7);return r<0&&(r+=4294967296),r}function x(e,t){var r=a(e,t,1)^a(e,t,8)^c(e,t,7);return r<0&&(r+=4294967296),r}function P(e,t){var r=a(e,t,19)^a(t,e,29)^c(e,t,6);return r<0&&(r+=4294967296),r}i.inherits(w,m),e.exports=w,w.blockSize=1024,w.outSize=512,w.hmacStrength=192,w.padLength=128,w.prototype._prepareBlock=function(e,t){for(var r=this.W,i=0;i<32;i++)r[i]=e[t+i];for(;i{var i=r(6436).rotr32;function n(e,t,r){return e&t^~e&r}function s(e,t,r){return e&t^e&r^t&r}function o(e,t,r){return e^t^r}t.ft_1=function(e,t,r,i){return 0===e?n(t,r,i):1===e||3===e?o(t,r,i):2===e?s(t,r,i):void 0},t.ch32=n,t.maj32=s,t.p32=o,t.s0_256=function(e){return i(e,2)^i(e,13)^i(e,22)},t.s1_256=function(e){return i(e,6)^i(e,11)^i(e,25)},t.g0_256=function(e){return i(e,7)^i(e,18)^e>>>3},t.g1_256=function(e){return i(e,17)^i(e,19)^e>>>10}},6436:(e,t,r)=>{var i=r(9746),n=r(5717);function s(e,t){return 55296==(64512&e.charCodeAt(t))&&!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1))}function o(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function h(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}t.inherits=n,t.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),n=0;n>6|192,r[i++]=63&o|128):s(e,n)?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++n)),r[i++]=o>>18|240,r[i++]=o>>12&63|128,r[i++]=o>>6&63|128,r[i++]=63&o|128):(r[i++]=o>>12|224,r[i++]=o>>6&63|128,r[i++]=63&o|128)}else for(n=0;n>>0}return o},t.split32=function(e,t){for(var r=new Array(4*e.length),i=0,n=0;i>>24,r[n+1]=s>>>16&255,r[n+2]=s>>>8&255,r[n+3]=255&s):(r[n+3]=s>>>24,r[n+2]=s>>>16&255,r[n+1]=s>>>8&255,r[n]=255&s)}return r},t.rotr32=function(e,t){return e>>>t|e<<32-t},t.rotl32=function(e,t){return e<>>32-t},t.sum32=function(e,t){return e+t>>>0},t.sum32_3=function(e,t,r){return e+t+r>>>0},t.sum32_4=function(e,t,r,i){return e+t+r+i>>>0},t.sum32_5=function(e,t,r,i,n){return e+t+r+i+n>>>0},t.sum64=function(e,t,r,i){var n=e[t],s=i+e[t+1]>>>0,o=(s>>0,e[t+1]=s},t.sum64_hi=function(e,t,r,i){return(t+i>>>0>>0},t.sum64_lo=function(e,t,r,i){return t+i>>>0},t.sum64_4_hi=function(e,t,r,i,n,s,o,a){var h=0,c=t;return h+=(c=c+i>>>0)>>0)>>0)>>0},t.sum64_4_lo=function(e,t,r,i,n,s,o,a){return t+i+s+a>>>0},t.sum64_5_hi=function(e,t,r,i,n,s,o,a,h,c){var u=0,l=t;return u+=(l=l+i>>>0)>>0)>>0)>>0)>>0},t.sum64_5_lo=function(e,t,r,i,n,s,o,a,h,c){return t+i+s+a+c>>>0},t.rotr64_hi=function(e,t,r){return(t<<32-r|e>>>r)>>>0},t.rotr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0},t.shr64_hi=function(e,t,r){return e>>>r},t.shr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0}},5717:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},204:(e,t,r)=>{e.exports=self.fetch||(self.fetch=r(5869).default||r(5869))},1094:(e,t,r)=>{var i;!function(){var n="input is invalid type",s="object"==typeof window,o=s?window:{};o.JS_SHA3_NO_WINDOW&&(s=!1);var a=!s&&"object"==typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?o=r.g:a&&(o=self);var h=!o.JS_SHA3_NO_COMMON_JS&&e.exports,c=r.amdO,u=!o.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,l="0123456789abcdef".split(""),f=[4,1024,262144,67108864],d=[0,8,16,24],p=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],y=[128,256],m=["hex","buffer","arrayBuffer","array","digest"],v={128:168,256:136};!o.JS_SHA3_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!u||!o.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});for(var w=function(e,t,r){return function(i){return new C(e,t,e).update(i)[r]()}},b=function(e,t,r){return function(i,n){return new C(e,t,n).update(i)[r]()}},_=function(e,t,r){return function(t,i,n,s){return A["cshake"+e].update(t,i,n,s)[r]()}},E=function(e,t,r){return function(t,i,n,s){return A["kmac"+e].update(t,i,n,s)[r]()}},S=function(e,t,r,i){for(var n=0;n>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var i=0;i<50;++i)this.s[i]=0}function U(e,t,r){C.call(this,e,t,r)}C.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(n);if(null===e)throw new Error(n);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||u&&ArrayBuffer.isView(e)))throw new Error(n);t=!0}for(var i,s,o=this.blocks,a=this.byteCount,h=e.length,c=this.blockCount,l=0,f=this.s;l>2]|=e[l]<>2]|=s<>2]|=(192|s>>6)<>2]|=(128|63&s)<=57344?(o[i>>2]|=(224|s>>12)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<>2]|=(240|s>>18)<>2]|=(128|s>>12&63)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<=a){for(this.start=i-a,this.block=o[c],i=0;i>=8);r>0;)n.unshift(r),r=255&(e>>=8),++i;return t?n.push(i):n.unshift(i),this.update(n),n.length},C.prototype.encodeString=function(e){var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(n);if(null===e)throw new Error(n);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||u&&ArrayBuffer.isView(e)))throw new Error(n);t=!0}var i=0,s=e.length;if(t)i=s;else for(var o=0;o=57344?i+=3:(a=65536+((1023&a)<<10|1023&e.charCodeAt(++o)),i+=4)}return i+=this.encode(8*i),this.update(e),i},C.prototype.bytepad=function(e,t){for(var r=this.encode(t),i=0;i>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+l[15&e]+l[e>>12&15]+l[e>>8&15]+l[e>>20&15]+l[e>>16&15]+l[e>>28&15]+l[e>>24&15];o%t==0&&(k(r),s=0)}return n&&(e=r[s],a+=l[e>>4&15]+l[15&e],n>1&&(a+=l[e>>12&15]+l[e>>8&15]),n>2&&(a+=l[e>>20&15]+l[e>>16&15])),a},C.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,i=this.outputBlocks,n=this.extraBytes,s=0,o=0,a=this.outputBits>>3;e=n?new ArrayBuffer(i+1<<2):new ArrayBuffer(a);for(var h=new Uint32Array(e);o>8&255,h[e+2]=t>>16&255,h[e+3]=t>>24&255;a%r==0&&k(i)}return s&&(e=a<<2,t=i[o],h[e]=255&t,s>1&&(h[e+1]=t>>8&255),s>2&&(h[e+2]=t>>16&255)),h},U.prototype=new C,U.prototype.finalize=function(){return this.encode(this.outputBits,!0),C.prototype.finalize.call(this)};var k=function(e){var t,r,i,n,s,o,a,h,c,u,l,f,d,g,y,m,v,w,b,_,E,S,M,I,A,O,x,P,N,R,T,L,C,U,k,j,q,D,z,$,B,K,F,V,H,W,G,J,Y,X,Q,Z,ee,te,re,ie,ne,se,oe,ae,he,ce,ue;for(i=0;i<48;i+=2)n=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],h=e[4]^e[14]^e[24]^e[34]^e[44],c=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(f=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(d=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=n^(h<<1|c>>>31),r=s^(c<<1|h>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(u<<1|l>>>31),r=a^(l<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=h^(f<<1|d>>>31),r=c^(d<<1|f>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(n<<1|s>>>31),r=l^(s<<1|n>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,G=e[10]<<4|e[11]>>>28,P=e[20]<<3|e[21]>>>29,N=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,he=e[30]<<9|e[31]>>>23,K=e[40]<<18|e[41]>>>14,F=e[41]<<18|e[40]>>>14,U=e[2]<<1|e[3]>>>31,k=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,J=e[22]<<10|e[23]>>>22,Y=e[23]<<10|e[22]>>>22,R=e[33]<<13|e[32]>>>19,T=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,j=e[14]<<6|e[15]>>>26,q=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,b=e[24]<<11|e[25]>>>21,X=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,L=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,I=e[6]<<28|e[7]>>>4,A=e[7]<<28|e[6]>>>4,ie=e[17]<<23|e[16]>>>9,ne=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,z=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,E=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,H=e[9]<<27|e[8]>>>5,O=e[18]<<20|e[19]>>>12,x=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,$=e[38]<<8|e[39]>>>24,B=e[39]<<8|e[38]>>>24,S=e[48]<<14|e[49]>>>18,M=e[49]<<14|e[48]>>>18,e[0]=g^~m&w,e[1]=y^~v&b,e[10]=I^~O&P,e[11]=A^~x&N,e[20]=U^~j&D,e[21]=k^~q&z,e[30]=V^~W&J,e[31]=H^~G&Y,e[40]=te^~ie&se,e[41]=re^~ne&oe,e[2]=m^~w&_,e[3]=v^~b&E,e[12]=O^~P&R,e[13]=x^~N&T,e[22]=j^~D&$,e[23]=q^~z&B,e[32]=W^~J&X,e[33]=G^~Y&Q,e[42]=ie^~se&ae,e[43]=ne^~oe&he,e[4]=w^~_&S,e[5]=b^~E&M,e[14]=P^~R&L,e[15]=N^~T&C,e[24]=D^~$&K,e[25]=z^~B&F,e[34]=J^~X&Z,e[35]=Y^~Q&ee,e[44]=se^~ae&ce,e[45]=oe^~he&ue,e[6]=_^~S&g,e[7]=E^~M&y,e[16]=R^~L&I,e[17]=T^~C&A,e[26]=$^~K&U,e[27]=B^~F&k,e[36]=X^~Z&V,e[37]=Q^~ee&H,e[46]=ae^~ce&te,e[47]=he^~ue&re,e[8]=S^~g&m,e[9]=M^~y&v,e[18]=L^~I&O,e[19]=C^~A&x,e[28]=K^~U&j,e[29]=F^~k&q,e[38]=Z^~V&W,e[39]=ee^~H&G,e[48]=ce^~te&ie,e[49]=ue^~re&ne,e[0]^=p[i],e[1]^=p[i+1]};if(h)e.exports=A;else{for(x=0;x{e=r.nmd(e);var i="__lodash_hash_undefined__",n=1,s=2,o=9007199254740991,a="[object Arguments]",h="[object Array]",c="[object AsyncFunction]",u="[object Boolean]",l="[object Date]",f="[object Error]",d="[object Function]",p="[object GeneratorFunction]",g="[object Map]",y="[object Number]",m="[object Null]",v="[object Object]",w="[object Promise]",b="[object Proxy]",_="[object RegExp]",E="[object Set]",S="[object String]",M="[object Undefined]",I="[object WeakMap]",A="[object ArrayBuffer]",O="[object DataView]",x=/^\[object .+?Constructor\]$/,P=/^(?:0|[1-9]\d*)$/,N={};N["[object Float32Array]"]=N["[object Float64Array]"]=N["[object Int8Array]"]=N["[object Int16Array]"]=N["[object Int32Array]"]=N["[object Uint8Array]"]=N["[object Uint8ClampedArray]"]=N["[object Uint16Array]"]=N["[object Uint32Array]"]=!0,N[a]=N[h]=N[A]=N[u]=N[O]=N[l]=N[f]=N[d]=N[g]=N[y]=N[v]=N[_]=N[E]=N[S]=N[I]=!1;var R="object"==typeof r.g&&r.g&&r.g.Object===Object&&r.g,T="object"==typeof self&&self&&self.Object===Object&&self,L=R||T||Function("return this")(),C=t&&!t.nodeType&&t,U=C&&e&&!e.nodeType&&e,k=U&&U.exports===C,j=k&&R.process,q=function(){try{return j&&j.binding&&j.binding("util")}catch(e){}}(),D=q&&q.isTypedArray;function z(e,t){for(var r=-1,i=null==e?0:e.length;++rc))return!1;var l=a.get(e);if(l&&a.get(t))return l==t;var f=-1,d=!0,p=r&s?new Ae:void 0;for(a.set(e,t),a.set(t,e);++f-1},Me.prototype.set=function(e,t){var r=this.__data__,i=xe(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this},Ie.prototype.clear=function(){this.size=0,this.__data__={hash:new Se,map:new(le||Me),string:new Se}},Ie.prototype.delete=function(e){var t=Ce(this,e).delete(e);return this.size-=t?1:0,t},Ie.prototype.get=function(e){return Ce(this,e).get(e)},Ie.prototype.has=function(e){return Ce(this,e).has(e)},Ie.prototype.set=function(e,t){var r=Ce(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this},Ae.prototype.add=Ae.prototype.push=function(e){return this.__data__.set(e,i),this},Ae.prototype.has=function(e){return this.__data__.has(e)},Oe.prototype.clear=function(){this.__data__=new Me,this.size=0},Oe.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Oe.prototype.get=function(e){return this.__data__.get(e)},Oe.prototype.has=function(e){return this.__data__.has(e)},Oe.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Me){var i=r.__data__;if(!le||i.length<199)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new Ie(i)}return r.set(e,t),this.size=r.size,this};var ke=ae?function(e){return null==e?[]:(e=Object(e),function(t,r){for(var i=-1,n=null==t?0:t.length,s=0,o=[];++i-1&&e%1==0&&e-1&&e%1==0&&e<=o}function He(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function We(e){return null!=e&&"object"==typeof e}var Ge=D?function(e){return function(t){return e(t)}}(D):function(e){return We(e)&&Ve(e.length)&&!!N[Pe(e)]};function Je(e){return null!=(t=e)&&Ve(t.length)&&!Fe(t)?function(e,t){var r=Be(e),i=!r&&$e(e),n=!r&&!i&&Ke(e),s=!r&&!i&&!n&&Ge(e),o=r||i||n||s,a=o?function(e,t){for(var r=-1,i=Array(e);++r{function t(e,t){if(!e)throw new Error(t||"Assertion failed")}e.exports=t,t.equal=function(e,t,r){if(e!=t)throw new Error(r||"Assertion failed: "+e+" != "+t)}},7563:(e,t,r)=>{const i=r(610),n=r(4020),s=r(500),o=r(2806),a=Symbol("encodeFragmentIdentifier");function h(e){if("string"!=typeof e||1!==e.length)throw new TypeError("arrayFormatSeparator must be single character string")}function c(e,t){return t.encode?t.strict?i(e):encodeURIComponent(e):e}function u(e,t){return t.decode?n(e):e}function l(e){return Array.isArray(e)?e.sort():"object"==typeof e?l(Object.keys(e)).sort(((e,t)=>Number(e)-Number(t))).map((t=>e[t])):e}function f(e){const t=e.indexOf("#");return-1!==t&&(e=e.slice(0,t)),e}function d(e){const t=(e=f(e)).indexOf("?");return-1===t?"":e.slice(t+1)}function p(e,t){return t.parseNumbers&&!Number.isNaN(Number(e))&&"string"==typeof e&&""!==e.trim()?e=Number(e):!t.parseBooleans||null===e||"true"!==e.toLowerCase()&&"false"!==e.toLowerCase()||(e="true"===e.toLowerCase()),e}function g(e,t){h((t=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},t)).arrayFormatSeparator);const r=function(e){let t;switch(e.arrayFormat){case"index":return(e,r,i)=>{t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),t?(void 0===i[e]&&(i[e]={}),i[e][t[1]]=r):i[e]=r};case"bracket":return(e,r,i)=>{t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),t?void 0!==i[e]?i[e]=[].concat(i[e],r):i[e]=[r]:i[e]=r};case"colon-list-separator":return(e,r,i)=>{t=/(:list)$/.exec(e),e=e.replace(/:list$/,""),t?void 0!==i[e]?i[e]=[].concat(i[e],r):i[e]=[r]:i[e]=r};case"comma":case"separator":return(t,r,i)=>{const n="string"==typeof r&&r.includes(e.arrayFormatSeparator),s="string"==typeof r&&!n&&u(r,e).includes(e.arrayFormatSeparator);r=s?u(r,e):r;const o=n||s?r.split(e.arrayFormatSeparator).map((t=>u(t,e))):null===r?r:u(r,e);i[t]=o};case"bracket-separator":return(t,r,i)=>{const n=/(\[\])$/.test(t);if(t=t.replace(/\[\]$/,""),!n)return void(i[t]=r?u(r,e):r);const s=null===r?[]:r.split(e.arrayFormatSeparator).map((t=>u(t,e)));void 0!==i[t]?i[t]=[].concat(i[t],s):i[t]=s};default:return(e,t,r)=>{void 0!==r[e]?r[e]=[].concat(r[e],t):r[e]=t}}}(t),i=Object.create(null);if("string"!=typeof e)return i;if(!(e=e.trim().replace(/^[?#&]/,"")))return i;for(const n of e.split("&")){if(""===n)continue;let[e,o]=s(t.decode?n.replace(/\+/g," "):n,"=");o=void 0===o?null:["comma","separator","bracket-separator"].includes(t.arrayFormat)?o:u(o,t),r(u(e,t),o,i)}for(const e of Object.keys(i)){const r=i[e];if("object"==typeof r&&null!==r)for(const e of Object.keys(r))r[e]=p(r[e],t);else i[e]=p(r,t)}return!1===t.sort?i:(!0===t.sort?Object.keys(i).sort():Object.keys(i).sort(t.sort)).reduce(((e,t)=>{const r=i[t];return Boolean(r)&&"object"==typeof r&&!Array.isArray(r)?e[t]=l(r):e[t]=r,e}),Object.create(null))}t.extract=d,t.parse=g,t.stringify=(e,t)=>{if(!e)return"";h((t=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},t)).arrayFormatSeparator);const r=r=>t.skipNull&&null==e[r]||t.skipEmptyString&&""===e[r],i=function(e){switch(e.arrayFormat){case"index":return t=>(r,i)=>{const n=r.length;return void 0===i||e.skipNull&&null===i||e.skipEmptyString&&""===i?r:null===i?[...r,[c(t,e),"[",n,"]"].join("")]:[...r,[c(t,e),"[",c(n,e),"]=",c(i,e)].join("")]};case"bracket":return t=>(r,i)=>void 0===i||e.skipNull&&null===i||e.skipEmptyString&&""===i?r:null===i?[...r,[c(t,e),"[]"].join("")]:[...r,[c(t,e),"[]=",c(i,e)].join("")];case"colon-list-separator":return t=>(r,i)=>void 0===i||e.skipNull&&null===i||e.skipEmptyString&&""===i?r:null===i?[...r,[c(t,e),":list="].join("")]:[...r,[c(t,e),":list=",c(i,e)].join("")];case"comma":case"separator":case"bracket-separator":{const t="bracket-separator"===e.arrayFormat?"[]=":"=";return r=>(i,n)=>void 0===n||e.skipNull&&null===n||e.skipEmptyString&&""===n?i:(n=null===n?"":n,0===i.length?[[c(r,e),t,c(n,e)].join("")]:[[i,c(n,e)].join(e.arrayFormatSeparator)])}default:return t=>(r,i)=>void 0===i||e.skipNull&&null===i||e.skipEmptyString&&""===i?r:null===i?[...r,c(t,e)]:[...r,[c(t,e),"=",c(i,e)].join("")]}}(t),n={};for(const t of Object.keys(e))r(t)||(n[t]=e[t]);const s=Object.keys(n);return!1!==t.sort&&s.sort(t.sort),s.map((r=>{const n=e[r];return void 0===n?"":null===n?c(r,t):Array.isArray(n)?0===n.length&&"bracket-separator"===t.arrayFormat?c(r,t)+"[]":n.reduce(i(r),[]).join("&"):c(r,t)+"="+c(n,t)})).filter((e=>e.length>0)).join("&")},t.parseUrl=(e,t)=>{t=Object.assign({decode:!0},t);const[r,i]=s(e,"#");return Object.assign({url:r.split("?")[0]||"",query:g(d(e),t)},t&&t.parseFragmentIdentifier&&i?{fragmentIdentifier:u(i,t)}:{})},t.stringifyUrl=(e,r)=>{r=Object.assign({encode:!0,strict:!0,[a]:!0},r);const i=f(e.url).split("?")[0]||"",n=t.extract(e.url),s=t.parse(n,{sort:!1}),o=Object.assign(s,e.query);let h=t.stringify(o,r);h&&(h=`?${h}`);let u=function(e){let t="";const r=e.indexOf("#");return-1!==r&&(t=e.slice(r)),t}(e.url);return e.fragmentIdentifier&&(u=`#${r[a]?c(e.fragmentIdentifier,r):e.fragmentIdentifier}`),`${i}${h}${u}`},t.pick=(e,r,i)=>{i=Object.assign({parseFragmentIdentifier:!0,[a]:!1},i);const{url:n,query:s,fragmentIdentifier:h}=t.parseUrl(e,i);return t.stringifyUrl({url:n,query:o(s,r),fragmentIdentifier:h},i)},t.exclude=(e,r,i)=>{const n=Array.isArray(r)?e=>!r.includes(e):(e,t)=>!r(e,t);return t.pick(e,n,i)}},5346:e=>{function t(e){try{return JSON.stringify(e)}catch(e){return'"[Circular]"'}}e.exports=function(e,r,i){var n=i&&i.stringify||t;if("object"==typeof e&&null!==e){var s=r.length+1;if(1===s)return e;var o=new Array(s);o[0]=n(e);for(var a=1;a-1?l:0,e.charCodeAt(d+1)){case 100:case 102:if(u>=h)break;if(null==r[u])break;l=h)break;if(null==r[u])break;l=h)break;if(void 0===r[u])break;l",l=d+2,d++;break}c+=n(r[u]),l=d+2,d++;break;case 115:if(u>=h)break;l{Object.defineProperty(t,"__esModule",{value:!0}),t.safeJsonParse=function(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return JSON.parse(e)}catch(t){return e}},t.safeJsonStringify=function(e){return"string"==typeof e?e:JSON.stringify(e,((e,t)=>void 0===t?null:t))}},500:e=>{e.exports=(e,t)=>{if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Expected the arguments to be of type `string`");if(""===t)return[e];const r=e.indexOf(t);return-1===r?[e]:[e.slice(0,r),e.slice(r+t.length)]}},610:e=>{e.exports=e=>encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))},655:(e,t,r)=>{r.r(t),r.d(t,{__assign:()=>s,__asyncDelegator:()=>b,__asyncGenerator:()=>w,__asyncValues:()=>_,__await:()=>v,__awaiter:()=>u,__classPrivateFieldGet:()=>I,__classPrivateFieldSet:()=>A,__createBinding:()=>f,__decorate:()=>a,__exportStar:()=>d,__extends:()=>n,__generator:()=>l,__importDefault:()=>M,__importStar:()=>S,__makeTemplateObject:()=>E,__metadata:()=>c,__param:()=>h,__read:()=>g,__rest:()=>o,__spread:()=>y,__spreadArrays:()=>m,__values:()=>p});var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},i(e,t)};function n(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var s=function(){return s=Object.assign||function(e){for(var t,r=1,i=arguments.length;r=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}function h(e,t){return function(r,i){t(r,i,e)}}function c(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function u(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{h(i.next(e))}catch(e){s(e)}}function a(e){try{h(i.throw(e))}catch(e){s(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((i=i.apply(e,t||[])).next())}))}function l(e,t){var r,i,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,i&&(n=2&s[0]?i.return:s[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,s[1])).done)return n;switch(i=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((n=(n=o.trys).length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function g(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,s=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return o}function y(){for(var e=[],t=0;t1||a(e,t)}))})}function a(e,t){try{(r=n[e](t)).value instanceof v?Promise.resolve(r.value.v).then(h,c):u(s[0][2],r)}catch(e){u(s[0][3],e)}var r}function h(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function b(e){var t,r;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,n){t[i]=e[i]?function(t){return(r=!r)?{value:v(e[i](t)),done:"return"===i}:n?n(t):t}:n}}function _(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=p(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=e[r]&&function(t){return new Promise((function(i,n){!function(e,t,r,i){Promise.resolve(i).then((function(t){e({value:t,done:r})}),t)}(i,n,(t=e[r](t)).done,t.value)}))}}}function E(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function S(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function M(e){return e&&e.__esModule?e:{default:e}}function I(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function A(e,t,r){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,r),r}},5869:(e,t,r)=>{function i(e,t){return t=t||{},new Promise((function(r,i){var n=new XMLHttpRequest,s=[],o=[],a={},h=function(){return{ok:2==(n.status/100|0),statusText:n.statusText,status:n.status,url:n.responseURL,text:function(){return Promise.resolve(n.responseText)},json:function(){return Promise.resolve(n.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([n.response]))},clone:h,headers:{keys:function(){return s},entries:function(){return o},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var c in n.open(t.method||"get",e,!0),n.onload=function(){n.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(e,t,r){s.push(t=t.toLowerCase()),o.push([t,r]),a[t]=a[t]?a[t]+","+r:r})),r(h())},n.onerror=i,n.withCredentials="include"==t.credentials,t.headers)n.setRequestHeader(c,t.headers[c]);n.send(t.body||null)}))}r.r(t),r.d(t,{default:()=>i})},5883:()=>{},6601:()=>{},6559:(e,t,r)=>{const i=r(5346);e.exports=o;const n=function(){function e(e){return void 0!==e&&e}try{return"undefined"!=typeof globalThis||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch(t){return e(self)||e(window)||e(this)||{}}}().console||{},s={mapHttpRequest:f,mapHttpResponse:f,wrapRequestSerializer:d,wrapResponseSerializer:d,wrapErrorSerializer:d,req:f,res:f,err:function(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const r in e)void 0===t[r]&&(t[r]=e[r]);return t}};function o(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const r=e.browser.write||n;e.browser.write&&(e.browser.asObject=!0);const i=e.serializers||{},s=function(e,t){return Array.isArray(e)?e.filter((function(e){return"!stdSerializers.err"!==e})):!0===e&&Object.keys(t)}(e.browser.serialize,i);let f=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(f=!1),"function"==typeof r&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),!1===e.enabled&&(e.level="silent");const d=e.level||"info",g=Object.create(r);g.log||(g.log=p),Object.defineProperty(g,"levelVal",{get:function(){return"silent"===this.level?1/0:this.levels.values[this.level]}}),Object.defineProperty(g,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,a(y,g,"error","log"),a(y,g,"fatal","error"),a(y,g,"warn","error"),a(y,g,"info","log"),a(y,g,"debug","log"),a(y,g,"trace","log")}});const y={transmit:t,serialize:s,asObject:e.browser.asObject,levels:["error","fatal","warn","info","debug","trace"],timestamp:l(e)};return g.levels=o.levels,g.level=d,g.setMaxListeners=g.getMaxListeners=g.emit=g.addListener=g.on=g.prependListener=g.once=g.prependOnceListener=g.removeListener=g.removeAllListeners=g.listeners=g.listenerCount=g.eventNames=g.write=g.flush=p,g.serializers=i,g._serialize=s,g._stdErrSerialize=f,g.child=function(r,n){if(!r)throw new Error("missing bindings for child Pino");n=n||{},s&&r.serializers&&(n.serializers=r.serializers);const o=n.serializers;if(s&&o){var a=Object.assign({},i,o),l=!0===e.browser.serialize?Object.keys(a):s;delete r.serializers,h([r],l,a,this._stdErrSerialize)}function f(e){this._childLevel=1+(0|e._childLevel),this.error=c(e,r,"error"),this.fatal=c(e,r,"fatal"),this.warn=c(e,r,"warn"),this.info=c(e,r,"info"),this.debug=c(e,r,"debug"),this.trace=c(e,r,"trace"),a&&(this.serializers=a,this._serialize=l),t&&(this._logEvent=u([].concat(e._logEvent.bindings,r)))}return f.prototype=this,new f(this)},t&&(g._logEvent=u()),g}function a(e,t,r,s){const a=Object.getPrototypeOf(t);t[r]=t.levelVal>t.levels.values[r]?p:a[r]?a[r]:n[r]||n[s]||p,function(e,t,r){var s;(e.transmit||t[r]!==p)&&(t[r]=(s=t[r],function(){const a=e.timestamp(),c=new Array(arguments.length),l=Object.getPrototypeOf&&Object.getPrototypeOf(this)===n?n:this;for(var f=0;f-1&&i in r&&(e[n][i]=r[i](e[n][i]))}function c(e,t,r){return function(){const i=new Array(1+arguments.length);i[0]=t;for(var n=1;n{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{var e={};r.r(e),r.d(e,{identity:()=>se});var t={};r.r(t),r.d(t,{base2:()=>oe});var i={};r.r(i),r.d(i,{base8:()=>ae});var n={};r.r(n),r.d(n,{base10:()=>he});var s={};r.r(s),r.d(s,{base16:()=>ce,base16upper:()=>ue});var o={};r.r(o),r.d(o,{base32:()=>le,base32hex:()=>ge,base32hexpad:()=>me,base32hexpadupper:()=>ve,base32hexupper:()=>ye,base32pad:()=>de,base32padupper:()=>pe,base32upper:()=>fe,base32z:()=>we});var a={};r.r(a),r.d(a,{base36:()=>be,base36upper:()=>_e});var h={};r.r(h),r.d(h,{base58btc:()=>Ee,base58flickr:()=>Se});var c={};r.r(c),r.d(c,{base64:()=>Me,base64pad:()=>Ie,base64url:()=>Ae,base64urlpad:()=>Oe});var u={};r.r(u),r.d(u,{base256emoji:()=>Re});var l={};r.r(l),r.d(l,{sha256:()=>Ze,sha512:()=>et});var f={};r.r(f),r.d(f,{identity:()=>rt});var d={};r.r(d),r.d(d,{code:()=>nt,decode:()=>ot,encode:()=>st,name:()=>it});var p={};r.r(p),r.d(p,{code:()=>ut,decode:()=>ft,encode:()=>lt,name:()=>ct});var g=r(7187),y=r.n(g),m=r(5150),v=r(159),w=r(9107),b=r(8200);class _ extends b.q{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class E extends b.q{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}}class S{constructor(e,t){this.logger=e,this.core=t}}class M extends b.q{constructor(e,t){super(),this.relayer=e,this.logger=t}}class I extends b.q{constructor(e){super()}}class A{constructor(e,t,r,i){this.core=e,this.logger=t,this.name=r}}class O extends b.q{constructor(e,t){super(),this.relayer=e,this.logger=t}}class x extends b.q{constructor(e,t){super(),this.core=e,this.logger=t}}class P{constructor(e,t){this.projectId=e,this.logger=t}}class N{constructor(e){this.opts=e,this.protocol="wc",this.version=2}}class R{constructor(e){this.client=e}}const T=e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t));function L(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return(e=>{const t=e.replace(/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,'$1"$2n"$3');return JSON.parse(t,((e,t)=>"string"==typeof t&&t.match(/^\d+n$/)?BigInt(t.substring(0,t.length-1)):t))})(e)}catch(t){return e}}function C(e){return"string"==typeof e?e:T(e)||""}var U=r(1050),k=r(1416),j=r(6736);const q="base64url",D="utf8",z=":",$="did",B="key",K="base58btc",F="z",V="K36";function H(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function W(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?H(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function G(e,t){t||(t=e.reduce(((e,t)=>e+t.length),0));const r=W(t);let i=0;for(const t of e)r.set(t,i),i+=t.length;return H(r)}const J=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i>>0,o=new Uint8Array(s);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var l=0,f=s-1;(0!==u||l>>0,o[f]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");n=l,t++}if(" "!==e[t]){for(var d=s-n;d!==s&&0===o[d];)d++;for(var p=new Uint8Array(i+(s-d)),g=i;d!==s;)p[g++]=o[d++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,i=0,n=0,s=t.length;n!==s&&0===t[n];)n++,r++;for(var o=(s-n)*u+1>>>0,c=new Uint8Array(o);n!==s;){for(var l=t[n],f=0,d=o-1;(0!==l||f>>0,c[d]=l%a>>>0,l=l/a>>>0;if(0!==l)throw new Error("Non-zero carry");i=f,n++}for(var p=o-i;p!==o&&0===c[p];)p++;for(var g=h.repeat(r);p{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")});class X{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Q{constructor(e,t,r){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return ee(this,e)}}class Z{constructor(e){this.decoders=e}or(e){return ee(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ee=(e,t)=>new Z({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class te{constructor(e,t,r,i){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=i,this.encoder=new X(e,t,r),this.decoder=new Q(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const re=({name:e,prefix:t,encode:r,decode:i})=>new te(e,t,r,i),ie=({prefix:e,name:t,alphabet:r})=>{const{encode:i,decode:n}=J(r,t);return re({prefix:e,name:t,encode:i,decode:e=>Y(n(e))})},ne=({name:e,prefix:t,bitsPerChar:r,alphabet:i})=>re({prefix:t,name:e,encode:e=>((e,t,r)=>{const i="="===t[t.length-1],n=(1<r;)o-=r,s+=t[n&a>>o];if(o&&(s+=t[n&a<((e,t,r,i)=>{const n={};for(let e=0;e=8&&(a-=8,o[c++]=255&h>>a)}if(a>=r||255&h<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,i,r,e)}),se=re({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)}),oe=ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),ae=ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),he=ie({prefix:"9",name:"base10",alphabet:"0123456789"}),ce=ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ue=ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),le=ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fe=ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),de=ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pe=ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ge=ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ye=ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),me=ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ve=ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),we=ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),be=ie({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_e=ie({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Ee=ie({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Se=ie({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Me=ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ie=ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ae=ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Oe=ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),xe=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Pe=xe.reduce(((e,t,r)=>(e[r]=t,e)),[]),Ne=xe.reduce(((e,t,r)=>(e[t.codePointAt(0)]=r,e)),[]),Re=re({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+Pe[t]),"")},decode:function(e){const t=[];for(const r of e){const e=Ne[r.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}});var Te=128,Le=-128,Ce=Math.pow(2,31),Ue=Math.pow(2,7),ke=Math.pow(2,14),je=Math.pow(2,21),qe=Math.pow(2,28),De=Math.pow(2,35),ze=Math.pow(2,42),$e=Math.pow(2,49),Be=Math.pow(2,56),Ke=Math.pow(2,63);const Fe=function e(t,r,i){r=r||[];for(var n=i=i||0;t>=Ce;)r[i++]=255&t|Te,t/=128;for(;t&Le;)r[i++]=255&t|Te,t>>>=7;return r[i]=0|t,e.bytes=i-n+1,r},Ve=function(e){return e(Fe(e,t,r),t),We=e=>Ve(e),Ge=(e,t)=>{const r=t.byteLength,i=We(e),n=i+We(r),s=new Uint8Array(n+r);return He(e,s,0),He(r,s,i),s.set(t,n),new Je(e,r,t,s)};class Je{constructor(e,t,r,i){this.code=e,this.size=t,this.digest=r,this.bytes=i}}const Ye=({name:e,code:t,encode:r})=>new Xe(e,t,r);class Xe{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Ge(this.code,t):t.then((e=>Ge(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Qe=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Ze=Ye({name:"sha2-256",code:18,encode:Qe("SHA-256")}),et=Ye({name:"sha2-512",code:19,encode:Qe("SHA-512")}),tt=Y,rt={code:0,name:"identity",encode:tt,digest:e=>Ge(0,tt(e))},it="raw",nt=85,st=e=>Y(e),ot=e=>Y(e),at=new TextEncoder,ht=new TextDecoder,ct="json",ut=512,lt=e=>at.encode(JSON.stringify(e)),ft=e=>JSON.parse(ht.decode(e));Symbol.toStringTag,Symbol.for("nodejs.util.inspect.custom"),Symbol.for("@ipld/js-cid/CID");const dt={...e,...t,...i,...n,...s,...o,...a,...h,...c,...u};function pt(e,t,r,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:i}}}const gt=pt("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),yt=pt("ascii","a",(e=>{let t="a";for(let r=0;r{const t=W((e=e.substring(1)).length);for(let r=0;r"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function Zt(e){return 1===e.type&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}var er=Object.defineProperty,tr=Object.getOwnPropertySymbols,rr=Object.prototype.hasOwnProperty,ir=Object.prototype.propertyIsEnumerable,nr=(e,t,r)=>t in e?er(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,sr=(e,t)=>{for(var r in t||(t={}))rr.call(t,r)&&nr(e,r,t[r]);if(tr)for(var r of tr(t))ir.call(t,r)&&nr(e,r,t[r]);return e};const or="ReactNative",ar={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},hr="js";function cr(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function ur(){return!(0,qt.getDocument)()&&!!(0,qt.getNavigator)()&&navigator.product===or}function lr(){return!cr()&&!!(0,qt.getNavigator)()}function fr(){return ur()?ar.reactNative:cr()?ar.node:lr()?ar.browser:ar.unknown}function dr(e,t,i){const n=function(){if(fr()===ar.reactNative&&typeof r.g<"u"&&typeof(null==r.g?void 0:r.g.Platform)<"u"){const{OS:e,Version:t}=r.g.Platform;return[e,t].join("-")}const e=t?jt(t):"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new Tt:"undefined"!=typeof navigator?jt(navigator.userAgent):"undefined"!=typeof process&&process.version?new Pt(process.version.slice(1)):null;var t;if(null===e)return"unknown";const i=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[i,e.name,e.version].join("-"):[i,e.version].join("-")}(),s=function(){var e;const t=fr();return t===ar.browser?[t,(null==(e=(0,qt.getLocation)())?void 0:e.host)||"unknown"].join(":"):t}();return[[e,t].join("-"),[hr,i].join("-"),n,s].join("/")}function pr(e,t){return e.filter((e=>t.includes(e))).length===e.length}function gr(e){return Object.fromEntries(e.entries())}function yr(e){return new Map(Object.entries(e))}function mr(e=j.FIVE_MINUTES,t){const r=(0,j.toMiliseconds)(e||j.FIVE_MINUTES);let i,n,s;return{resolve:e=>{s&&i&&(clearTimeout(s),i(e))},reject:e=>{s&&n&&(clearTimeout(s),n(e))},done:()=>new Promise(((e,o)=>{s=setTimeout((()=>{o(new Error(t))}),r),i=e,n=o}))}}function vr(e,t,r){return new Promise((async(i,n)=>{const s=setTimeout((()=>n(new Error(r))),t);try{i(await e)}catch(e){n(e)}clearTimeout(s)}))}function wr(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function br(e){const[t,r]=e.split(":"),i={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof r)i.topic=r;else{if("id"!==t||!Number.isInteger(Number(r)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`);i.id=Number(r)}return i}function _r(e,t){return(0,j.fromMiliseconds)((t||Date.now())+(0,j.toMiliseconds)(e))}function Er(e){return Date.now()>=(0,j.toMiliseconds)(e)}function Sr(e,t){return`${e}${t?`:${t}`:""}`}function Mr(e=[],t=[]){return[...new Set([...e,...t])]}function Ir(e){return e?.relay||{protocol:"irn"}}function Ar(e){const t=$t[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}var Or=Object.defineProperty,xr=Object.getOwnPropertySymbols,Pr=Object.prototype.hasOwnProperty,Nr=Object.prototype.propertyIsEnumerable,Rr=(e,t,r)=>t in e?Or(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;function Tr(e,t="-"){const r={},i="relay"+t;return Object.keys(e).forEach((t=>{if(t.startsWith(i)){const n=t.replace(i,""),s=e[t];r[n]=s}})),r}function Lr(e){return e.startsWith("//")?e.substring(2):e}var Cr=Object.defineProperty,Ur=Object.defineProperties,kr=Object.getOwnPropertyDescriptors,jr=Object.getOwnPropertySymbols,qr=Object.prototype.hasOwnProperty,Dr=Object.prototype.propertyIsEnumerable,zr=(e,t,r)=>t in e?Cr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$r=(e,t)=>{for(var r in t||(t={}))qr.call(t,r)&&zr(e,r,t[r]);if(jr)for(var r of jr(t))Dr.call(t,r)&&zr(e,r,t[r]);return e},Br=(e,t)=>Ur(e,kr(t));function Kr(e){const t=[];return e.forEach((e=>{const[r,i]=e.split(":");t.push(`${r}:${i}`)})),t}function Fr(e){return e.includes(":")}function Vr(e){return Fr(e)?e.split(":")[0]:e}function Hr(e){var t,r,i;const n={};if(!Qr(e))return n;for(const[s,o]of Object.entries(e)){const e=Fr(s)?[s]:o.chains,a=o.methods||[],h=o.events||[],c=Vr(s);n[c]=Br($r({},n[c]),{chains:Mr(e,null==(t=n[c])?void 0:t.chains),methods:Mr(a,null==(r=n[c])?void 0:r.methods),events:Mr(h,null==(i=n[c])?void 0:i.events)})}return n}const Wr={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},Gr={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Jr(e,t){const{message:r,code:i}=Gr[e];return{message:t?`${r} ${t}`:r,code:i}}function Yr(e,t){const{message:r,code:i}=Wr[e];return{message:t?`${r} ${t}`:r,code:i}}function Xr(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function Qr(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Zr(e){return typeof e>"u"}function ei(e,t){return!(!t||!Zr(e))||"string"==typeof e&&!!e.trim().length}function ti(e,t){return!(!t||!Zr(e))||"number"==typeof e&&!isNaN(e)}function ri(e){return!(!ei(e,!1)||!e.includes(":"))&&2===e.split(":").length}function ii(e){if(ei(e,!1))try{return typeof new URL(e)<"u"}catch{return!1}return!1}function ni(e){let t=!0;return Xr(e)?e.length&&(t=e.every((e=>ei(e,!1)))):t=!1,t}function si(e,t){let r=null;return Object.values(e).forEach((e=>{if(r)return;const i=function(e,t){let r=null;return ni(e?.methods)?ni(e?.events)||(r=Yr("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):r=Yr("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),r}(e,`${t}, namespace`);i&&(r=i)})),r}function oi(e,t){let r=null;if(e&&Qr(e)){const i=si(e,t);i&&(r=i);const n=function(e,t){let r=null;return Object.values(e).forEach((e=>{if(r)return;const i=function(e,t){let r=null;return Xr(e)?e.forEach((e=>{r||function(e){if(ei(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&ri(e)}}return!1}(e)||(r=Yr("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))})):r=Yr("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}(e?.accounts,`${t} namespace`);i&&(r=i)})),r}(e,t);n&&(r=n)}else r=Jr("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return r}function ai(e){return ei(e.protocol,!0)}function hi(e){return typeof e<"u"&&null!==typeof e}function ci(e,t){return!(!ri(t)||!function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...Kr(e.accounts))})),t}(e).includes(t))}function ui(e,t,r){let i=null;const n=function(e){const t={};return Object.keys(e).forEach((r=>{var i;r.includes(":")?t[r]=e[r]:null==(i=e[r].chains)||i.forEach((i=>{t[i]={methods:e[r].methods,events:e[r].events}}))})),t}(e),s=function(e){const t={};return Object.keys(e).forEach((r=>{if(r.includes(":"))t[r]=e[r];else{const i=Kr(e[r].accounts);i?.forEach((i=>{t[i]={accounts:e[r].accounts.filter((e=>e.includes(`${i}:`))),methods:e[r].methods,events:e[r].events}}))}})),t}(t),o=Object.keys(n),a=Object.keys(s),h=li(Object.keys(e)),c=li(Object.keys(t)),u=h.filter((e=>!c.includes(e)));return u.length&&(i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.\n Required: ${u.toString()}\n Received: ${Object.keys(t).toString()}`)),pr(o,a)||(i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach((e=>{if(!e.includes(":")||i)return;const n=Kr(t[e].accounts);n.includes(e)||(i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${n.toString()}`))})),o.forEach((e=>{i||(pr(n[e].methods,s[e].methods)?pr(n[e].events,s[e].events)||(i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${e}`)):i=Jr("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${e}`))})),i}function li(e){return[...new Set(e.map((e=>e.includes(":")?e.split(":")[0]:e)))]}function fi(e,t){return ti(e,!1)&&e<=t.max&&e>=t.min}function di(){const e=fr();return new Promise((t=>{switch(e){case ar.browser:t(lr()&&navigator?.onLine);break;case ar.reactNative:t(async function(){if(ur()&&typeof r.g<"u"&&null!=r.g&&r.g.NetInfo){const e=await(null==r.g?void 0:r.g.NetInfo.fetch());return e?.isConnected}return!0}());break;case ar.node:default:t(!0)}}))}const pi={};class gi{static get(e){return pi[e]}static set(e,t){pi[e]=t}static delete(e){delete pi[e]}}const yi="INTERNAL_ERROR",mi="SERVER_ERROR",vi=[-32700,-32600,-32601,-32602,-32603],wi={PARSE_ERROR:{code:-32700,message:"Parse error"},INVALID_REQUEST:{code:-32600,message:"Invalid Request"},METHOD_NOT_FOUND:{code:-32601,message:"Method not found"},INVALID_PARAMS:{code:-32602,message:"Invalid params"},[yi]:{code:-32603,message:"Internal error"},[mi]:{code:-32e3,message:"Server error"}},bi=mi;function _i(e){return Object.keys(wi).includes(e)?wi[e]:wi[bi]}var Ei=r(1468);function Si(e=3){return Date.now()*Math.pow(10,e)+Math.floor(Math.random()*Math.pow(10,e))}function Mi(e=6){return BigInt(Si(e))}function Ii(e,t,r){return{id:r||Si(),jsonrpc:"2.0",method:e,params:t}}function Ai(e,t){return{id:e,jsonrpc:"2.0",result:t}}function Oi(e,t,r){return{id:e,jsonrpc:"2.0",error:xi(t,r)}}function xi(e,t){return void 0===e?_i(yi):("string"==typeof e&&(e=Object.assign(Object.assign({},_i(mi)),{message:e})),void 0!==t&&(e.data=t),r=e.code,vi.includes(r)&&(e=function(e){return Object.values(wi).find((t=>t.code===e))||wi[bi]}(e.code)),e);var r}class Pi{}class Ni extends Pi{constructor(){super()}}class Ri extends Ni{constructor(e){super()}}function Ti(e){return function(e,t){const r=function(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(t&&t.length)return t[0]}(e);return void 0!==r&&new RegExp(t).test(r)}(e,"^wss?:")}function Li(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function Ci(e){return"object"==typeof e&&"id"in e&&"jsonrpc"in e&&"2.0"===e.jsonrpc}function Ui(e){return Ci(e)&&"method"in e}function ki(e){return Ci(e)&&(ji(e)||qi(e))}function ji(e){return"result"in e}function qi(e){return"error"in e}class Di extends Ri{constructor(e){super(e),this.events=new g.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(Ii(e.method,e.params||[],e.id||Mi().toString()),t)}async requestStrict(e,t){return new Promise((async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(e){i(e)}this.events.on(`${e.id}`,(e=>{qi(e)?i(e.error):r(e.result)}));try{await this.connection.send(e,t)}catch(e){i(e)}}))}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ki(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&3e3===e.code&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),"string"==typeof e&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",(e=>this.onPayload(e))),this.connection.on("close",(e=>this.onClose(e))),this.connection.on("error",(e=>this.events.emit("error",e))),this.connection.on("register_error",(e=>this.onClose())),this.hasRegisteredEventListeners=!0)}}const zi=e=>e.split("?")[0],$i="undefined"!=typeof WebSocket?WebSocket:void 0!==r.g&&void 0!==r.g.WebSocket?r.g.WebSocket:"undefined"!=typeof window&&void 0!==window.WebSocket?window.WebSocket:"undefined"!=typeof self&&void 0!==self.WebSocket?self.WebSocket:r(2030),Bi=class{constructor(e){if(this.url=e,this.events=new g.EventEmitter,this.registering=!1,!Ti(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return void 0!==this.socket}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise(((e,t)=>{void 0!==this.socket?(this.socket.onclose=t=>{this.onClose(t),e()},this.socket.close()):t(new Error("Connection already closed"))}))}async send(e,t){void 0===this.socket&&(this.socket=await this.register());try{this.socket.send(C(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Ti(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise(((e,t)=>{this.events.once("register_error",(e=>{this.resetMaxListeners(),t(e)})),this.events.once("open",(()=>{if(this.resetMaxListeners(),void 0===this.socket)return t(new Error("WebSocket connection is missing or invalid"));e(this.socket)}))}))}return this.url=e,this.registering=!0,new Promise(((t,i)=>{const n=(0,Ei.isReactNative)()?void 0:{rejectUnauthorized:!Li(e)},s=new $i(e,[],n);"undefined"!=typeof WebSocket||void 0!==r.g&&void 0!==r.g.WebSocket||"undefined"!=typeof window&&void 0!==window.WebSocket||"undefined"!=typeof self&&void 0!==self.WebSocket?s.onerror=e=>{const t=e;i(this.emitError(t.error))}:s.on("error",(e=>{i(this.emitError(e))})),s.onopen=()=>{this.onOpen(s),t(s)}}))}onOpen(e){e.onmessage=e=>this.onPayload(e),e.onclose=e=>this.onClose(e),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(void 0===e.data)return;const t="string"==typeof e.data?L(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const r=this.parseError(t),i=Oi(e,r.message||r.toString());this.events.emit("payload",i)}parseError(e,t=this.url){return function(e,t,r){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable WS RPC url at ${t}`):e}(e,zi(t))}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}emitError(e){const t=this.parseError(new Error((null==e?void 0:e.message)||`WebSocket connection failed for host: ${zi(this.url)}`));return this.events.emit("register_error",t),t}};var Ki=r(2307),Fi=r.n(Ki),Vi=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i>>0,o=new Uint8Array(s);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var l=0,f=s-1;(0!==u||l>>0,o[f]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");n=l,t++}if(" "!==e[t]){for(var d=s-n;d!==s&&0===o[d];)d++;for(var p=new Uint8Array(i+(s-d)),g=i;d!==s;)p[g++]=o[d++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,i=0,n=0,s=t.length;n!==s&&0===t[n];)n++,r++;for(var o=(s-n)*u+1>>>0,c=new Uint8Array(o);n!==s;){for(var l=t[n],f=0,d=o-1;(0!==l||f>>0,c[d]=l%a>>>0,l=l/a>>>0;if(0!==l)throw new Error("Non-zero carry");i=f,n++}for(var p=o-i;p!==o&&0===c[p];)p++;for(var g=h.repeat(r);p{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class Wi{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Gi{constructor(e,t,r){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Yi(this,e)}}class Ji{constructor(e){this.decoders=e}or(e){return Yi(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yi=(e,t)=>new Ji({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Xi{constructor(e,t,r,i){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=i,this.encoder=new Wi(e,t,r),this.decoder=new Gi(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Qi=({name:e,prefix:t,encode:r,decode:i})=>new Xi(e,t,r,i),Zi=({prefix:e,name:t,alphabet:r})=>{const{encode:i,decode:n}=Vi(r,t);return Qi({prefix:e,name:t,encode:i,decode:e=>Hi(n(e))})},en=({name:e,prefix:t,bitsPerChar:r,alphabet:i})=>Qi({prefix:t,name:e,encode:e=>((e,t,r)=>{const i="="===t[t.length-1],n=(1<r;)o-=r,s+=t[n&a>>o];if(o&&(s+=t[n&a<((e,t,r,i)=>{const n={};for(let e=0;e=8&&(a-=8,o[c++]=255&h>>a)}if(a>=r||255&h<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,i,r,e)}),tn=Qi({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var rn=Object.freeze({__proto__:null,identity:tn});const nn=en({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sn=Object.freeze({__proto__:null,base2:nn});const on=en({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var an=Object.freeze({__proto__:null,base8:on});const hn=Zi({prefix:"9",name:"base10",alphabet:"0123456789"});var cn=Object.freeze({__proto__:null,base10:hn});const un=en({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ln=en({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var fn=Object.freeze({__proto__:null,base16:un,base16upper:ln});const dn=en({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),pn=en({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gn=en({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yn=en({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mn=en({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vn=en({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wn=en({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),bn=en({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_n=en({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var En=Object.freeze({__proto__:null,base32:dn,base32upper:pn,base32pad:gn,base32padupper:yn,base32hex:mn,base32hexupper:vn,base32hexpad:wn,base32hexpadupper:bn,base32z:_n});const Sn=Zi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mn=Zi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var In=Object.freeze({__proto__:null,base36:Sn,base36upper:Mn});const An=Zi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),On=Zi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xn=Object.freeze({__proto__:null,base58btc:An,base58flickr:On});const Pn=en({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Nn=en({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Rn=en({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Tn=en({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ln=Object.freeze({__proto__:null,base64:Pn,base64pad:Nn,base64url:Rn,base64urlpad:Tn});const Cn=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Un=Cn.reduce(((e,t,r)=>(e[r]=t,e)),[]),kn=Cn.reduce(((e,t,r)=>(e[t.codePointAt(0)]=r,e)),[]),jn=Qi({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+Un[t]),"")},decode:function(e){const t=[];for(const r of e){const e=kn[r.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}});var qn=Object.freeze({__proto__:null,base256emoji:jn}),Dn=128,zn=-128,$n=Math.pow(2,31),Bn=Math.pow(2,7),Kn=Math.pow(2,14),Fn=Math.pow(2,21),Vn=Math.pow(2,28),Hn=Math.pow(2,35),Wn=Math.pow(2,42),Gn=Math.pow(2,49),Jn=Math.pow(2,56),Yn=Math.pow(2,63),Xn=function e(t,r,i){r=r||[];for(var n=i=i||0;t>=$n;)r[i++]=255&t|Dn,t/=128;for(;t&zn;)r[i++]=255&t|Dn,t>>>=7;return r[i]=0|t,e.bytes=i-n+1,r},Qn=function(e){return e(Xn(e,t,r),t),es=e=>Qn(e),ts=(e,t)=>{const r=t.byteLength,i=es(e),n=i+es(r),s=new Uint8Array(n+r);return Zn(e,s,0),Zn(r,s,i),s.set(t,n),new rs(e,r,t,s)};class rs{constructor(e,t,r,i){this.code=e,this.size=t,this.digest=r,this.bytes=i}}const is=({name:e,code:t,encode:r})=>new ns(e,t,r);class ns{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?ts(this.code,t):t.then((e=>ts(this.code,e)))}throw Error("Unknown type, must be binary type")}}const ss=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),os=is({name:"sha2-256",code:18,encode:ss("SHA-256")}),as=is({name:"sha2-512",code:19,encode:ss("SHA-512")});Object.freeze({__proto__:null,sha256:os,sha512:as});const hs=Hi,cs={code:0,name:"identity",encode:hs,digest:e=>ts(0,hs(e))};Object.freeze({__proto__:null,identity:cs}),new TextEncoder,new TextDecoder;const us={...rn,...sn,...an,...cn,...fn,...En,...In,...xn,...Ln,...qn};function ls(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function fs(e,t,r,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:i}}}const ds=fs("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),ps=fs("ascii","a",(e=>{let t="a";for(let r=0;r{const t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?ls(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}((e=e.substring(1)).length);for(let r=0;r{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}},this.has=e=>(this.isInitialized(),this.keychain.has(e)),this.set=async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()},this.get=e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t},this.del=async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()},this.core=e,this.logger=(0,w.generateChildLogger)(t,this.name)}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,gr(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?yr(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Xs{constructor(e,t,r){this.core=e,this.logger=t,this.name="crypto",this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=e=>(this.isInitialized(),this.keychain.has(e)),this.getClientId=async()=>(this.isInitialized(),_t(Et(await this.getClientSeed()).publicKey)),this.generateKeyPair=()=>{this.isInitialized();const e=function(){const e=At.Au();return{privateKey:vt(e.secretKey,Ft),publicKey:vt(e.publicKey,Ft)}}();return this.setPrivateKey(e.publicKey,e.privateKey)},this.signJWT=async e=>{this.isInitialized();const t=Et(await this.getClientSeed()),r=Wt(),i=bs;return await async function(e,t,r,i,n=(0,j.fromMiliseconds)(Date.now())){const s={alg:"EdDSA",typ:"JWT"},o={iss:_t(i.publicKey),sub:e,aud:t,iat:n,exp:n+r},a=wt([bt((h={header:s,payload:o}).header),bt(h.payload)].join("."),"utf8");var h;return function(e){return[bt(e.header),bt(e.payload),(t=e.signature,vt(t,q))].join(".");var t}({header:s,payload:o,signature:U.Xx(i.secretKey,a)})}(r,e,i,t)},this.generateSharedKey=(e,t,r)=>{this.isInitialized();const i=function(e,t){const r=At.gi(wt(e,Ft),wt(t,Ft),!0);return vt(new Mt.t(It.mE,r).expand(32),Ft)}(this.getPrivateKey(e),t);return this.setSymKey(i,r)},this.setSymKey=async(e,t)=>{this.isInitialized();const r=t||Gt(e);return await this.keychain.set(r,e),r},this.deleteKeyPair=async e=>{this.isInitialized(),await this.keychain.del(e)},this.deleteSymKey=async e=>{this.isInitialized(),await this.keychain.del(e)},this.encode=async(e,t,r)=>{this.isInitialized();const i=Qt(r),n=C(t);if(Zt(i)){const t=i.senderPublicKey,r=i.receiverPublicKey;e=await this.generateSharedKey(t,r)}const s=this.getSymKey(e),{type:o,senderPublicKey:a}=i;return function(e){const t=function(e){return wt(`${e}`,Kt)}(typeof e.type<"u"?e.type:0);if(1===Yt(t)&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof e.senderPublicKey<"u"?wt(e.senderPublicKey,Ft):void 0,i=typeof e.iv<"u"?wt(e.iv,Ft):(0,k.randomBytes)(12);return function(e){if(1===Yt(e.type)){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return vt(G([e.type,e.senderPublicKey,e.iv,e.sealed]),Vt)}return vt(G([e.type,e.iv,e.sealed]),Vt)}({type:t,sealed:new St.OK(wt(e.symKey,Ft)).seal(i,wt(e.message,Ht)),iv:i,senderPublicKey:r})}({type:o,symKey:s,message:n,senderPublicKey:a})},this.decode=async(e,t,r)=>{this.isInitialized();const i=function(e,t){const r=Xt(e);return Qt({type:Yt(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?vt(r.senderPublicKey,Ft):void 0,receiverPublicKey:t?.receiverPublicKey})}(t,r);if(Zt(i)){const t=i.receiverPublicKey,r=i.senderPublicKey;e=await this.generateSharedKey(t,r)}try{const r=function(e){const t=new St.OK(wt(e.symKey,Ft)),{sealed:r,iv:i}=Xt(e.encoded),n=t.open(i,r);if(null===n)throw new Error("Failed to decrypt");return vt(n,Ht)}({symKey:this.getSymKey(e),encoded:t});return L(r)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}},this.getPayloadType=e=>Yt(Xt(e).type),this.getPayloadSenderPublicKey=e=>{const t=Xt(e);return t.senderPublicKey?vt(t.senderPublicKey,Ft):void 0},this.core=e,this.logger=(0,w.generateChildLogger)(t,this.name),this.keychain=r||new Ys(this.core,this.logger)}get context(){return(0,w.getLoggerContext)(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ws)}catch{e=Wt(),await this.keychain.set(ws,e)}return function(e,t="utf8"){const r=gs[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?r.decoder.decode(`${r.prefix}${e}`):ls(globalThis.Buffer.from(e,"utf-8"))}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Qs extends S{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name="messages",this.version="0.3",this.initialized=!1,this.storagePrefix=ms,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}},this.set=async(e,t)=>{this.isInitialized();const r=Jt(t);let i=this.messages.get(e);return typeof i>"u"&&(i={}),typeof i[r]<"u"||(i[r]=t,this.messages.set(e,i),await this.persist()),r},this.get=e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t},this.has=(e,t)=>(this.isInitialized(),typeof this.get(e)[Jt(t)]<"u"),this.del=async e=>{this.isInitialized(),this.messages.delete(e),await this.persist()},this.logger=(0,w.generateChildLogger)(e,this.name),this.core=t}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,gr(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?yr(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Zs extends M{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new g.EventEmitter,this.name="publisher",this.queue=new Map,this.publishTimeout=(0,j.toMiliseconds)(j.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(e,t,r)=>{var i;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:r}});try{const n=r?.ttl||_s,s=Ir(r),o=r?.prompt||!1,a=r?.tag||0,h=r?.id||Mi().toString(),c={topic:e,message:t,opts:{ttl:n,relay:s,prompt:o,tag:a,id:h}},u=setTimeout((()=>this.queue.set(h,c)),this.publishTimeout);try{await await vr(this.rpcPublish(e,t,n,s,o,a,h),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(h),this.relayer.events.emit(Ps,c)}catch(e){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,null!=(i=r?.internal)&&i.throwOnFailedPublish)throw this.removeRequestFromQueue(h),e;return}finally{clearTimeout(u)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:r}})}catch(e){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(e),e}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.relayer=e,this.logger=(0,w.generateChildLogger)(t,this.name),this.registerEventListeners()}get context(){return(0,w.getLoggerContext)(this.logger)}rpcPublish(e,t,r,i,n,s,o){var a,h,c,u;const l={method:Ar(i.protocol).publish,params:{topic:e,message:t,ttl:r,prompt:n,tag:s},id:o};return Zr(null==(a=l.params)?void 0:a.prompt)&&(null==(h=l.params)||delete h.prompt),Zr(null==(c=l.params)?void 0:c.tag)&&(null==(u=l.params)||delete u.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:l}),this.relayer.request(l)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach((async e=>{const{topic:t,message:r,opts:i}=e;await this.publish(t,r,i)}))}registerEventListeners(){this.relayer.core.heartbeat.on(v.HEARTBEAT_EVENTS.pulse,(()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(xs);this.checkQueue()})),this.relayer.on(Is,(e=>{this.removeRequestFromQueue(e.id.toString())}))}}class eo{constructor(){this.map=new Map,this.set=(e,t)=>{const r=this.get(e);this.exists(e,t)||this.map.set(e,[...r,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,t))return;const i=r.filter((e=>e!==t));i.length?this.map.set(e,i):this.map.delete(e)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var to=Object.defineProperty,ro=Object.defineProperties,io=Object.getOwnPropertyDescriptors,no=Object.getOwnPropertySymbols,so=Object.prototype.hasOwnProperty,oo=Object.prototype.propertyIsEnumerable,ao=(e,t,r)=>t in e?to(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ho=(e,t)=>{for(var r in t||(t={}))so.call(t,r)&&ao(e,r,t[r]);if(no)for(var r of no(t))oo.call(t,r)&&ao(e,r,t[r]);return e},co=(e,t)=>ro(e,io(t));class uo extends O{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new eo,this.events=new g.EventEmitter,this.name="subscription",this.version="0.3",this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=ms,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(e,t)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const r=Ir(t),i={topic:e,relay:r};this.pending.set(e,i);const n=await this.rpcSubscribe(e,r);return this.onSubscribe(n,i),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}}),n}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}},this.unsubscribe=async(e,t)=>{await this.restartToComplete(),this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)},this.isSubscribed=async e=>!!this.topics.includes(e)||await new Promise(((t,r)=>{const i=new j.Watch;i.start(this.pendingSubscriptionWatchLabel);const n=setInterval((()=>{!this.pending.has(e)&&this.topics.includes(e)&&(clearInterval(n),i.stop(this.pendingSubscriptionWatchLabel),t(!0)),i.elapsed(this.pendingSubscriptionWatchLabel)>=qs&&(clearInterval(n),i.stop(this.pendingSubscriptionWatchLabel),r(new Error("Subscription resolution timeout")))}),this.pollingInterval)})).catch((()=>!1)),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=(0,w.generateChildLogger)(t,this.name),this.clientId=""}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,t){let r=!1;try{r=this.getSubscription(e).topic===t}catch{}return r}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const r=this.topicMap.get(e);await Promise.all(r.map((async r=>await this.unsubscribeById(e,r,t))))}async unsubscribeById(e,t,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:r}});try{const i=Ir(r);await this.rpcUnsubscribe(e,t,i);const n=Yr("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:r}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t){const r={method:Ar(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await vr(this.relayer.request(r),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(xs)}return Jt(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const t={method:Ar(e[0].relay.protocol).batchSubscribe,params:{topics:e.map((e=>e.topic))}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{return await await vr(this.relayer.request(t),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(xs)}}rpcUnsubscribe(e,t,r){const i={method:Ar(r.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,t){this.setSubscription(e,co(ho({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach((e=>{this.setSubscription(e.id,ho({},e)),this.pending.delete(e.topic)}))}async onUnsubscribe(e,t,r){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t))}addSubscription(e,t){this.subscriptions.set(e,ho({},t)),this.topicMap.set(t.topic,e),this.events.emit(Us,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(ks,co(ho({},r),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit("subscription_sync")}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t"u"||!e.length)return;if(this.subscriptions.size){const{message:e}=Jr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const t=await this.rpcBatchSubscribe(e);Xr(t)&&this.onBatchSubscribe(t.map(((t,r)=>co(ho({},e[r]),{id:t}))))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach((t=>{e.push(t)})),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(v.HEARTBEAT_EVENTS.pulse,(async()=>{await this.checkPending()})),this.relayer.on(As,(async()=>{await this.onConnect()})),this.relayer.on(Os,(()=>{this.onDisconnect()})),this.events.on(Us,(async e=>{const t=Us;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})),this.events.on(ks,(async e=>{const t=ks;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise((e=>{const t=setInterval((()=>{this.restartInProgress||(clearInterval(t),e())}),this.pollingInterval)}))}}var lo=Object.defineProperty,fo=Object.getOwnPropertySymbols,po=Object.prototype.hasOwnProperty,go=Object.prototype.propertyIsEnumerable,yo=(e,t,r)=>t in e?lo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;class mo extends I{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new g.EventEmitter,this.name="relayer",this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.request=async e=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(e)}catch(e){throw this.logger.debug("Failed to Publish Request"),this.logger.error(e),e}},this.onPayloadHandler=e=>{this.onProviderPayload(e)},this.onConnectHandler=()=>{this.events.emit(As)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=e=>{this.logger.error(e),this.events.emit("relayer_error",e),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Ns,this.onPayloadHandler),this.provider.on(Rs,this.onConnectHandler),this.provider.on(Ts,this.onDisconnectHandler),this.provider.on(Ls,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&"string"!=typeof e.logger?(0,w.generateChildLogger)(e.logger,this.name):(0,w.pino)((0,w.getDefaultLoggerOptions)({level:e.logger||"error"})),this.messages=new Qs(this.logger,e.core),this.subscriber=new uo(this,this.logger),this.publisher=new Zs(this,this.logger),this.relayUrl=e?.relayUrl||Es,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${Ss}...`),await this.restartTransport(Ss)}this.initialized=!0,setTimeout((async()=>{0===this.subscriber.topics.length&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)}),1e4)}get context(){return(0,w.getLoggerContext)(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,t,r){this.isInitialized(),await this.publisher.publish(e,t,r),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now()})}async subscribe(e,t){var r;this.isInitialized();let i,n=(null==(r=this.subscriber.topicMap.get(e))?void 0:r[0])||"";if(n)return n;const s=t=>{t.topic===e&&(this.subscriber.off(Us,s),i())};return await Promise.all([new Promise((e=>{i=e,this.subscriber.on(Us,s)})),new Promise((async r=>{n=await this.subscriber.subscribe(e,t),r()}))]),n}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportClose(){this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await vr(this.provider.disconnect(),1e3,"provider.disconnect()").catch((()=>this.onProviderDisconnect())):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise((e=>{if(!this.initialized)return e();this.subscriber.once(js,(()=>{e()}))})),new Promise((async(e,t)=>{try{await vr(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(e){return void t(e)}e()}))])}catch(e){this.logger.error(e);const t=e;if(!this.isConnectionStalled(t.message))throw e;this.provider.events.emit(Ts)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await di())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some((t=>e.includes(t)))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Di(new Bi(function({protocol:e,version:t,relayUrl:r,sdkVersion:i,auth:n,projectId:s,useOnCloseEvent:o}){const a=r.split("?"),h={auth:n,ua:dr(e,t,i),projectId:s,useOnCloseEvent:o||void 0},c=function(e,t){let r=zt.parse(e);return r=sr(sr({},r),t),zt.stringify(r)}(a[1]||"",h);return a[0]+"?"+c}({sdkVersion:"2.10.2",protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:r}=e;await this.messages.set(t,r)}async shouldIgnoreMessageEvent(e){const{topic:t,message:r}=e;if(!r||0===r.length)return this.logger.debug(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const i=this.messages.has(t,r);return i&&this.logger.debug(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Ui(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:r,message:i,publishedAt:n}=t.data,s={topic:r,message:i,publishedAt:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(((e,t)=>{for(var r in t||(t={}))po.call(t,r)&&yo(e,r,t[r]);if(fo)for(var r of fo(t))go.call(t,r)&&yo(e,r,t[r]);return e})({type:"event",event:t.id},s)),this.events.emit(t.id,s),await this.acknowledgePayload(e),await this.onMessageEvent(s)}else ki(e)&&this.events.emit(Is,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Ms,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=Ai(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Ns,this.onPayloadHandler),this.provider.off(Rs,this.onConnectHandler),this.provider.off(Ts,this.onDisconnectHandler),this.provider.off(Ls,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(xs,(()=>{this.restartTransport().catch((e=>this.logger.error(e)))}));let e=await di();!function(e){switch(fr()){case ar.browser:!function(e){!ur()&&lr()&&(window.addEventListener("online",(()=>e(!0))),window.addEventListener("offline",(()=>e(!1))))}(e);break;case ar.reactNative:!function(e){ur()&&typeof r.g<"u"&&null!=r.g&&r.g.NetInfo&&r.g?.NetInfo.addEventListener((t=>e(t?.isConnected)))}(e);case ar.node:}}((async t=>{this.initialized&&e!==t&&(e=t,t?await this.restartTransport().catch((e=>this.logger.error(e))):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch((e=>this.logger.error(e)))))}))}onProviderDisconnect(){this.events.emit(Os),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout((async()=>{await this.restartTransport().catch((e=>this.logger.error(e)))}),(0,j.toMiliseconds)(Cs)))}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise((e=>{const t=setInterval((()=>{this.connected&&(clearInterval(t),e())}),this.connectionStatusPollingInterval)}));await this.restartTransport()}}}var vo=Object.defineProperty,wo=Object.getOwnPropertySymbols,bo=Object.prototype.hasOwnProperty,_o=Object.prototype.propertyIsEnumerable,Eo=(e,t,r)=>t in e?vo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,So=(e,t)=>{for(var r in t||(t={}))bo.call(t,r)&&Eo(e,r,t[r]);if(wo)for(var r of wo(t))_o.call(t,r)&&Eo(e,r,t[r]);return e};class Mo extends A{constructor(e,t,r,i=ms,n=void 0){super(e,t,r,i),this.core=e,this.logger=t,this.name=r,this.map=new Map,this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ms,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>{this.getKey&&null!==e&&!Zr(e)?this.map.set(this.getKey(e),e):function(e){var t;return null==(t=e?.proposer)?void 0:t.publicKey}(e)?this.map.set(e.id,e):function(e){return e?.topic}(e)&&this.map.set(e.topic,e)})),this.cached=[],this.initialized=!0)},this.set=async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())},this.get=e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)),this.getAll=e=>(this.isInitialized(),e?this.values.filter((t=>Object.keys(e).every((r=>Fi()(t[r],e[r]))))):this.values),this.update=async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const r=So(So({},this.getData(e)),t);this.map.set(e,r),await this.persist()},this.delete=async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),await this.persist())},this.logger=(0,w.generateChildLogger)(t,this.name),this.storagePrefix=i,this.getKey=n}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:e}=Jr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Io{constructor(e,t){this.core=e,this.logger=t,this.name="pairing",this.version="0.3",this.events=new(y()),this.initialized=!1,this.storagePrefix=ms,this.ignoredPayloadTypes=[1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]},this.create=async()=>{this.isInitialized();const e=Wt(),t=await this.core.crypto.setSymKey(e),r=_r(j.FIVE_MINUTES),i={protocol:"irn"},n={topic:t,expiry:r,relay:i,active:!1},s=function(e){return`${e.protocol}:${e.topic}@${e.version}?`+zt.stringify(((e,t)=>{for(var r in t||(t={}))Pr.call(t,r)&&Rr(e,r,t[r]);if(xr)for(var r of xr(t))Nr.call(t,r)&&Rr(e,r,t[r]);return e})({symKey:e.symKey},function(e,t="-"){const r={};return Object.keys(e).forEach((i=>{const n="relay"+t+i;e[i]&&(r[n]=e[i])})),r}(e.relay)))}({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:e,relay:i});return await this.pairings.set(t,n),await this.core.relayer.subscribe(t),this.core.expirer.set(t,r),{topic:t,uri:s}},this.pair=async e=>{this.isInitialized(),this.isValidPair(e);const{topic:t,symKey:r,relay:i}=function(e){const t=e.indexOf(":"),r=-1!==e.indexOf("?")?e.indexOf("?"):void 0,i=e.substring(0,t),n=e.substring(t+1,r).split("@"),s=typeof r<"u"?e.substring(r):"",o=zt.parse(s);return{protocol:i,topic:Lr(n[0]),version:parseInt(n[1],10),symKey:o.symKey,relay:Tr(o)}}(e.uri);let n;if(this.pairings.keys.includes(t)&&(n=this.pairings.get(t),n.active))throw new Error(`Pairing already exists: ${t}. Please try again with a new connection URI.`);this.core.crypto.keychain.has(t)||(await this.core.crypto.setSymKey(r,t),await this.core.relayer.subscribe(t,{relay:i}));const s=_r(j.FIVE_MINUTES),o={topic:t,relay:i,expiry:s,active:!1};return await this.pairings.set(t,o),this.core.expirer.set(t,s),e.activatePairing&&await this.activate({topic:t}),this.events.emit(zs,o),o},this.activate=async({topic:e})=>{this.isInitialized();const t=_r(j.THIRTY_DAYS);await this.pairings.update(e,{active:!0,expiry:t}),this.core.expirer.set(e,t)},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:r,resolve:i,reject:n}=mr();this.events.once(Sr("pairing_ping",e),(({error:e})=>{e?n(e):i()})),await r()}},this.updateExpiry=async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})},this.updateMetadata=async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",Yr("USER_DISCONNECTED")),await this.deletePairing(t))},this.sendRequest=async(e,t,r)=>{const i=Ii(t,r),n=await this.core.crypto.encode(e,i),s=Ds[t].req;return this.core.history.set(e,i),this.core.relayer.publish(e,n,s),i.id},this.sendResult=async(e,t,r)=>{const i=Ai(e,r),n=await this.core.crypto.encode(t,i),s=await this.core.history.get(t,e),o=Ds[s.request.method].res;await this.core.relayer.publish(t,n,o),await this.core.history.resolve(i)},this.sendError=async(e,t,r)=>{const i=Oi(e,r),n=await this.core.crypto.encode(t,i),s=await this.core.history.get(t,e),o=Ds[s.request.method]?Ds[s.request.method].res:Ds.unregistered_method.res;await this.core.relayer.publish(t,n,o),await this.core.history.resolve(i)},this.deletePairing=async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Yr("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])},this.cleanup=async()=>{const e=this.pairings.getAll().filter((e=>Er(e.expiry)));await Promise.all(e.map((e=>this.deletePairing(e.topic))))},this.onRelayEventRequest=e=>{const{topic:t,payload:r}=e;switch(r.method){case"wc_pairingPing":return this.onPairingPingRequest(t,r);case"wc_pairingDelete":return this.onPairingDeleteRequest(t,r);default:return this.onUnknownRpcMethodRequest(t,r)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:r}=e,i=(await this.core.history.get(t,r.id)).request.method;return"wc_pairingPing"===i?this.onPairingPingResponse(t,r):this.onUnknownRpcMethodResponse(i)},this.onPairingPingRequest=async(e,t)=>{const{id:r}=t;try{this.isValidPing({topic:e}),await this.sendResult(r,e,!0),this.events.emit("pairing_ping",{id:r,topic:e})}catch(t){await this.sendError(r,e,t),this.logger.error(t)}},this.onPairingPingResponse=(e,t)=>{const{id:r}=t;setTimeout((()=>{ji(t)?this.events.emit(Sr("pairing_ping",r),{}):qi(t)&&this.events.emit(Sr("pairing_ping",r),{error:t.error})}),500)},this.onPairingDeleteRequest=async(e,t)=>{const{id:r}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit("pairing_delete",{id:r,topic:e})}catch(t){await this.sendError(r,e,t),this.logger.error(t)}},this.onUnknownRpcMethodRequest=async(e,t)=>{const{id:r,method:i}=t;try{if(this.registeredMethods.includes(i))return;const t=Yr("WC_METHOD_UNSUPPORTED",i);await this.sendError(r,e,t),this.logger.error(t)}catch(t){await this.sendError(r,e,t),this.logger.error(t)}},this.onUnknownRpcMethodResponse=e=>{this.registeredMethods.includes(e)||this.logger.error(Yr("WC_METHOD_UNSUPPORTED",e))},this.isValidPair=e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`pair() params: ${e}`);throw new Error(t)}if(!ii(e.uri)){const{message:t}=Jr("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw new Error(t)}},this.isValidPing=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidDisconnect=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidPairingTopic=async e=>{if(!ei(e,!1)){const{message:t}=Jr("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=Jr("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Er(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=Jr("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}},this.core=e,this.logger=(0,w.generateChildLogger)(t,this.name),this.pairings=new Mo(this.core,this.logger,this.name,this.storagePrefix)}get context(){return(0,w.getLoggerContext)(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ms,(async e=>{const{topic:t,message:r}=e;if(!this.pairings.keys.includes(t)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))return;const i=await this.core.crypto.decode(t,r);try{Ui(i)?(this.core.history.set(t,i),this.onRelayEventRequest({topic:t,payload:i})):ki(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:t,payload:i}),this.core.history.delete(t,i.id))}catch(e){this.logger.error(e)}}))}registerExpirerEvents(){this.core.expirer.on(Hs,(async e=>{const{topic:t}=br(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit("pairing_expire",{topic:t}))}))}}class Ao extends E{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new g.EventEmitter,this.name="history",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ms,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.records.set(e.id,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(e,t,r)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:r}),this.records.has(t.id))return;const i={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:r,expiry:_r(j.THIRTY_DAYS)};this.records.set(i.id,i),this.events.emit($s,i)},this.resolve=async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=qi(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.events.emit(Bs,t))},this.get=async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)),this.delete=(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach((r=>{if(r.topic===e){if(typeof t<"u"&&r.id!==t)return;this.records.delete(r.id),this.events.emit(Ks,r)}}))},this.exists=async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=(0,w.generateChildLogger)(t,this.name)}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach((t=>{if(typeof t.response<"u")return;const r={topic:t.topic,request:Ii(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(r)})),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit("history_sync")}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=Jr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on($s,(e=>{const t=$s;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.events.on(Bs,(e=>{const t=Bs;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.events.on(Ks,(e=>{const t=Ks;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.core.heartbeat.on(v.HEARTBEAT_EVENTS.pulse,(()=>{this.cleanup()}))}cleanup(){try{this.records.forEach((e=>{(0,j.toMiliseconds)(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))}))}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Oo extends x{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new g.EventEmitter,this.name="expirer",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=ms,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.expirations.set(e.target,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}},this.set=(e,t)=>{this.isInitialized();const r=this.formatTarget(e),i={target:r,expiry:t};this.expirations.set(r,i),this.checkExpiry(r,i),this.events.emit(Fs,{target:r,expiration:i})},this.get=e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)},this.del=e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),r=this.getExpiration(t);this.expirations.delete(t),this.events.emit(Vs,{target:t,expiration:r})}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=(0,w.generateChildLogger)(t,this.name)}get context(){return(0,w.getLoggerContext)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if("string"==typeof e)return function(e){return wr("topic",e)}(e);if("number"==typeof e)return function(e){return wr("id",e)}(e);const{message:t}=Jr("UNKNOWN_TYPE","Target type: "+typeof e);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit("expirer_sync")}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=Jr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:t}=Jr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:r}=t;(0,j.toMiliseconds)(r)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Hs,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach(((e,t)=>this.checkExpiry(t,e)))}registerEventListeners(){this.core.heartbeat.on(v.HEARTBEAT_EVENTS.pulse,(()=>this.checkExpirations())),this.events.on(Fs,(e=>{const t=Fs;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(Hs,(e=>{const t=Hs;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(Vs,(e=>{const t=Vs;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}}class xo extends P{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.name=Ws,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async()=>{if(this.verifyDisabled||ur()||!lr())return;const e=Gs;this.verifyUrl!==e&&this.removeIframe(),this.verifyUrl=e;try{await this.createIframe()}catch(e){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(e)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Js;try{await this.createIframe()}catch(e){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(e),this.verifyDisabled=!0}}},this.register=async e=>{this.initialized?this.sendPost(e.attestationId):(this.addToQueue(e.attestationId),await this.init())},this.resolve=async e=>{if(this.isDevEnv)return"";const t=e?.verifyUrl||Gs;let r;try{r=await this.fetchAttestation(e.attestationId,t)}catch(i){this.logger.info(`failed to resolve attestation: ${e.attestationId} from url: ${t}`),this.logger.info(i),r=await this.fetchAttestation(e.attestationId,Js)}return r},this.fetchAttestation=async(e,t)=>{this.logger.info(`resolving attestation: ${e} from url: ${t}`);const r=this.startAbortTimer(2*j.ONE_SECOND),i=await fetch(`${t}/attestation/${e}`,{signal:this.abortController.signal});return clearTimeout(r),200===i.status?await i.json():void 0},this.addToQueue=e=>{this.queue.push(e)},this.processQueue=()=>{0!==this.queue.length&&(this.queue.forEach((e=>this.sendPost(e))),this.queue=[])},this.sendPost=e=>{var t;try{if(!this.iframe)return;null==(t=this.iframe.contentWindow)||t.postMessage(e,"*"),this.logger.info(`postMessage sent: ${e} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let e;const t=r=>{"verify_ready"===r.data&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",t),e())};await Promise.race([new Promise((r=>{if(document.getElementById(Ws))return r();window.addEventListener("message",t);const i=document.createElement("iframe");i.id=Ws,i.src=`${this.verifyUrl}/${this.projectId}`,i.style.display="none",document.body.append(i),this.iframe=i,e=r})),new Promise(((e,r)=>setTimeout((()=>{window.removeEventListener("message",t),r("verify iframe load timeout")}),(0,j.toMiliseconds)(j.FIVE_SECONDS))))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.logger=(0,w.generateChildLogger)(t,this.name),this.verifyUrl=Gs,this.abortController=new AbortController,this.isDevEnv=cr()&&process.env.IS_VITEST}get context(){return(0,w.getLoggerContext)(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout((()=>this.abortController.abort()),(0,j.toMiliseconds)(e))}}var Po=Object.defineProperty,No=Object.getOwnPropertySymbols,Ro=Object.prototype.hasOwnProperty,To=Object.prototype.propertyIsEnumerable,Lo=(e,t,r)=>t in e?Po(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Co=(e,t)=>{for(var r in t||(t={}))Ro.call(t,r)&&Lo(e,r,t[r]);if(No)for(var r of No(t))To.call(t,r)&&Lo(e,r,t[r]);return e};class Uo extends _{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=ys,this.events=new g.EventEmitter,this.initialized=!1,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Es,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const t=typeof e?.logger<"u"&&"string"!=typeof e?.logger?e.logger:(0,w.pino)((0,w.getDefaultLoggerOptions)({level:e?.logger||"error"}));this.logger=(0,w.generateChildLogger)(t,this.name),this.heartbeat=new v.HeartBeat,this.crypto=new Xs(this,this.logger,e?.keychain),this.history=new Ao(this,this.logger),this.expirer=new Oo(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new m.ZP(Co(Co({},vs),e?.storageOptions)),this.relayer=new mo({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Io(this,this.logger),this.verify=new xo(this.projectId||"",this.logger)}static async init(e){const t=new Uo(e);await t.initialize();const r=await t.crypto.getClientId();return await t.storage.setItem("WALLETCONNECT_CLIENT_ID",r),t}get context(){return(0,w.getLoggerContext)(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const ko=Uo;let jo=!1,qo=!1;const Do={debug:1,default:2,info:2,warning:3,error:4,off:5};let zo=Do.default,$o=null;const Bo=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw new Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw new Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(e){return e.message}return null}();var Ko,Fo;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(Ko||(Ko={})),function(e){e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"}(Fo||(Fo={}));const Vo="0123456789abcdef";class Ho{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==Do[r]&&this.throwArgumentError("invalid log level name","logLevel",e),zo>Do[r]||console.log.apply(console,t)}debug(...e){this._log(Ho.levels.DEBUG,e)}info(...e){this._log(Ho.levels.INFO,e)}warn(...e){this._log(Ho.levels.WARNING,e)}makeError(e,t,r){if(qo)return this.makeError("censored error",t,{});t||(t=Ho.errors.UNKNOWN_ERROR),r||(r={});const i=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e>4],r+=Vo[15&t[e]];i.push(e+"=Uint8Array(0x"+r+")")}else i.push(e+"="+JSON.stringify(t))}catch(t){i.push(e+"="+JSON.stringify(r[e].toString()))}})),i.push(`code=${t}`),i.push(`version=${this.version}`);const n=e;let s="";switch(t){case Fo.NUMERIC_FAULT:{s="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":s+="-"+t;break;case"negative-power":case"negative-width":s+="-unsupported";break;case"unbound-bitwise-result":s+="-unbound-result"}break}case Fo.CALL_EXCEPTION:case Fo.INSUFFICIENT_FUNDS:case Fo.MISSING_NEW:case Fo.NONCE_EXPIRED:case Fo.REPLACEMENT_UNDERPRICED:case Fo.TRANSACTION_REPLACED:case Fo.UNPREDICTABLE_GAS_LIMIT:s=t}s&&(e+=" [ See: https://links.ethers.org/v5-errors-"+s+" ]"),i.length&&(e+=" ("+i.join(", ")+")");const o=new Error(e);return o.reason=n,o.code=t,Object.keys(r).forEach((function(e){o[e]=r[e]})),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,Ho.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,i){e||this.throwError(t,r,i)}assertArgument(e,t,r,i){e||this.throwArgumentError(t,r,i)}checkNormalize(e){null==e&&(e="platform missing String.prototype.normalize"),Bo&&this.throwError("platform missing String.prototype.normalize",Ho.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Bo})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,Ho.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,Ho.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",et&&this.throwError("too many arguments"+r,Ho.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",Ho.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",Ho.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",Ho.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return $o||($o=new Ho("logger/5.7.0")),$o}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",Ho.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),jo){if(!e)return;this.globalLogger().throwError("error censorship permanent",Ho.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}qo=!!e,jo=!!t}static setLogLevel(e){const t=Do[e.toLowerCase()];null!=t?zo=t:Ho.globalLogger().warn("invalid log level - "+e)}static from(e){return new Ho(e)}}Ho.errors=Fo,Ho.levels=Ko;const Wo=new Ho("bytes/5.7.0");function Go(e){return!!e.toHexString}function Jo(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return Jo(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function Yo(e){return"number"==typeof e&&e==e&&e%1==0}function Xo(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!Yo(e.length)||e.length<0)return!1;for(let t=0;t=256)return!1}return!0}function Qo(e,t){if(t||(t={}),"number"==typeof e){Wo.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),Jo(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),Go(e)&&(e=e.toHexString()),Zo(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":Wo.throwArgumentError("hex data is odd-length","value",e));const i=[];for(let e=0;e>4]+ea[15&i]}return t}return Wo.throwArgumentError("invalid hexlify value","value",e)}function ra(e,t,r){return"string"!=typeof e?e=ta(e):(!Zo(e)||e.length%2)&&Wo.throwArgumentError("invalid hexData","value",e),t=2+2*t,null!=r?"0x"+e.substring(t,2+2*r):"0x"+e.substring(t)}function ia(e,t){for("string"!=typeof e?e=ta(e):Zo(e)||Wo.throwArgumentError("invalid hex string","value",e),e.length>2*t+2&&Wo.throwArgumentError("value out of range","value",arguments[1]);e.length<2*t+2;)e="0x0"+e.substring(2);return e}function na(e){const t={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(Zo(r=e)&&!(r.length%2)||Xo(r)){let r=Qo(e);64===r.length?(t.v=27+(r[32]>>7),r[32]&=127,t.r=ta(r.slice(0,32)),t.s=ta(r.slice(32,64))):65===r.length?(t.r=ta(r.slice(0,32)),t.s=ta(r.slice(32,64)),t.v=r[64]):Wo.throwArgumentError("invalid signature string","signature",e),t.v<27&&(0===t.v||1===t.v?t.v+=27:Wo.throwArgumentError("signature invalid v byte","signature",e)),t.recoveryParam=1-t.v%2,t.recoveryParam&&(r[32]|=128),t._vs=ta(r.slice(32,64))}else{if(t.r=e.r,t.s=e.s,t.v=e.v,t.recoveryParam=e.recoveryParam,t._vs=e._vs,null!=t._vs){const r=function(e,t){(e=Qo(e)).length>t&&Wo.throwArgumentError("value out of range","value",arguments[0]);const r=new Uint8Array(t);return r.set(e,t-e.length),Jo(r)}(Qo(t._vs),32);t._vs=ta(r);const i=r[0]>=128?1:0;null==t.recoveryParam?t.recoveryParam=i:t.recoveryParam!==i&&Wo.throwArgumentError("signature recoveryParam mismatch _vs","signature",e),r[0]&=127;const n=ta(r);null==t.s?t.s=n:t.s!==n&&Wo.throwArgumentError("signature v mismatch _vs","signature",e)}if(null==t.recoveryParam)null==t.v?Wo.throwArgumentError("signature missing v and recoveryParam","signature",e):0===t.v||1===t.v?t.recoveryParam=t.v:t.recoveryParam=1-t.v%2;else if(null==t.v)t.v=27+t.recoveryParam;else{const r=0===t.v||1===t.v?t.v:1-t.v%2;t.recoveryParam!==r&&Wo.throwArgumentError("signature recoveryParam mismatch v","signature",e)}null!=t.r&&Zo(t.r)?t.r=ia(t.r,32):Wo.throwArgumentError("signature missing or invalid r","signature",e),null!=t.s&&Zo(t.s)?t.s=ia(t.s,32):Wo.throwArgumentError("signature missing or invalid s","signature",e);const r=Qo(t.s);r[0]>=128&&Wo.throwArgumentError("signature s out of range","signature",e),t.recoveryParam&&(r[0]|=128);const i=ta(r);t._vs&&(Zo(t._vs)||Wo.throwArgumentError("signature invalid _vs","signature",e),t._vs=ia(t._vs,32)),null==t._vs?t._vs=i:t._vs!==i&&Wo.throwArgumentError("signature _vs mismatch v and s","signature",e)}var r;return t.yParityAndS=t._vs,t.compact=t.r+t.yParityAndS.substring(2),t}var sa=r(1094),oa=r.n(sa);function aa(e){return"0x"+oa().keccak_256(Qo(e))}const ha=new Ho("strings/5.7.0");var ca,ua;function la(e,t,r,i,n){if(e===ua.BAD_PREFIX||e===ua.UNEXPECTED_CONTINUE){let e=0;for(let i=t+1;i>6==2;i++)e++;return e}return e===ua.OVERRUN?r.length-t-1:0}function fa(e,t=ca.current){t!=ca.current&&(ha.checkNormalize(),e=e.normalize(t));let r=[];for(let t=0;t>6|192),r.push(63&i|128);else if(55296==(64512&i)){t++;const n=e.charCodeAt(t);if(t>=e.length||56320!=(64512&n))throw new Error("invalid utf-8 string");const s=65536+((1023&i)<<10)+(1023&n);r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(63&s|128)}else r.push(i>>12|224),r.push(i>>6&63|128),r.push(63&i|128)}return Qo(r)}!function(e){e.current="",e.NFC="NFC",e.NFD="NFD",e.NFKC="NFKC",e.NFKD="NFKD"}(ca||(ca={})),function(e){e.UNEXPECTED_CONTINUE="unexpected continuation byte",e.BAD_PREFIX="bad codepoint prefix",e.OVERRUN="string overrun",e.MISSING_CONTINUE="missing continuation byte",e.OUT_OF_RANGE="out of UTF-8 range",e.UTF16_SURROGATE="UTF-16 surrogate",e.OVERLONG="overlong representation"}(ua||(ua={})),Object.freeze({error:function(e,t,r,i,n){return ha.throwArgumentError(`invalid codepoint at offset ${t}; ${e}`,"bytes",r)},ignore:la,replace:function(e,t,r,i,n){return e===ua.OVERLONG?(i.push(n),0):(i.push(65533),la(e,t,r))}});const da="Ethereum Signed Message:\n";function pa(e){return"string"==typeof e&&(e=fa(e)),aa(function(e){const t=e.map((e=>Qo(e))),r=t.reduce(((e,t)=>e+t.length),0),i=new Uint8Array(r);return t.reduce(((e,t)=>(i.set(t,e),e+t.length)),0),Jo(i)}([fa(da),fa(String(e.length)),e]))}var ga=r(3550),ya=r.n(ga),ma=ya().BN;new Ho("bignumber/5.7.0");const va=new Ho("address/5.7.0");function wa(e){Zo(e,20)||va.throwArgumentError("invalid address","address",e);const t=(e=e.toLowerCase()).substring(2).split(""),r=new Uint8Array(40);for(let e=0;e<40;e++)r[e]=t[e].charCodeAt(0);const i=Qo(aa(r));for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&(t[e]=t[e].toUpperCase()),(15&i[e>>1])>=8&&(t[e+1]=t[e+1].toUpperCase());return"0x"+t.join("")}const ba={};for(let e=0;e<10;e++)ba[String(e)]=String(e);for(let e=0;e<26;e++)ba[String.fromCharCode(65+e)]=String(10+e);const _a=Math.floor((Ea=9007199254740991,Math.log10?Math.log10(Ea):Math.log(Ea)/Math.LN10));var Ea;function Sa(e){let t=null;if("string"!=typeof e&&va.throwArgumentError("invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/))"0x"!==e.substring(0,2)&&(e="0x"+e),t=wa(e),e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&t!==e&&va.throwArgumentError("bad address checksum","address",e);else if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(e.substring(2,4)!==function(e){let t=(e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00").split("").map((e=>ba[e])).join("");for(;t.length>=_a;){let e=t.substring(0,_a);t=parseInt(e,10)%97+t.substring(e.length)}let r=String(98-parseInt(t,10)%97);for(;r.length<2;)r="0"+r;return r}(e)&&va.throwArgumentError("bad icap checksum","address",e),r=e.substring(4),t=new ma(r,36).toString(16);t.length<40;)t="0"+t;t=wa("0x"+t)}else va.throwArgumentError("invalid address","address",e);var r;return t}var Ma=r(3715),Ia=r.n(Ma);function Aa(e,t,r){return e(r={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&r.path)}},r.exports),r.exports}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r.g?r.g:"undefined"!=typeof self&&self;var Oa=xa;function xa(e,t){if(!e)throw new Error(t||"Assertion failed")}xa.equal=function(e,t,r){if(e!=t)throw new Error(r||"Assertion failed: "+e+" != "+t)};var Pa=Aa((function(e,t){var r=t;function i(e){return 1===e.length?"0"+e:e}function n(e){for(var t="",r=0;r>8,o=255&n;s?r.push(s,o):r.push(o)}return r},r.zero2=i,r.toHex=n,r.encode=function(e,t){return"hex"===t?n(e):e}})),Na=Aa((function(e,t){var r=t;r.assert=Oa,r.toArray=Pa.toArray,r.zero2=Pa.zero2,r.toHex=Pa.toHex,r.encode=Pa.encode,r.getNAF=function(e,t,r){var i=new Array(Math.max(e.bitLength(),r)+1);i.fill(0);for(var n=1<(n>>1)-1?(n>>1)-h:h,s.isubn(a)):a=0,i[o]=a,s.iushrn(1)}return i},r.getJSF=function(e,t){var r=[[],[]];e=e.clone(),t=t.clone();for(var i,n=0,s=0;e.cmpn(-n)>0||t.cmpn(-s)>0;){var o,a,h=e.andln(3)+n&3,c=t.andln(3)+s&3;3===h&&(h=-1),3===c&&(c=-1),o=0==(1&h)?0:3!=(i=e.andln(7)+n&7)&&5!==i||2!==c?h:-h,r[0].push(o),a=0==(1&c)?0:3!=(i=t.andln(7)+s&7)&&5!==i||2!==h?c:-c,r[1].push(a),2*n===o+1&&(n=1-n),2*s===a+1&&(s=1-s),e.iushrn(1),t.iushrn(1)}return r},r.cachedProperty=function(e,t,r){var i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}},r.parseBytes=function(e){return"string"==typeof e?r.toArray(e,"hex"):e},r.intFromLE=function(e){return new(ya())(e,"hex","le")}})),Ra=Na.getNAF,Ta=Na.getJSF,La=Na.assert;function Ca(e,t){this.type=e,this.p=new(ya())(t.p,16),this.red=t.prime?ya().red(t.prime):ya().mont(this.p),this.zero=new(ya())(0).toRed(this.red),this.one=new(ya())(1).toRed(this.red),this.two=new(ya())(2).toRed(this.red),this.n=t.n&&new(ya())(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Ua=Ca;function ka(e,t){this.curve=e,this.type=t,this.precomputed=null}Ca.prototype.point=function(){throw new Error("Not implemented")},Ca.prototype.validate=function(){throw new Error("Not implemented")},Ca.prototype._fixedNafMul=function(e,t){La(e.precomputed);var r=e._getDoubles(),i=Ra(t,1,this._bitLength),n=(1<=s;h--)o=(o<<1)+i[h];a.push(o)}for(var c=this.jpoint(null,null,null),u=this.jpoint(null,null,null),l=n;l>0;l--){for(s=0;s=0;a--){for(var h=0;a>=0&&0===s[a];a--)h++;if(a>=0&&h++,o=o.dblp(h),a<0)break;var c=s[a];La(0!==c),o="affine"===e.type?c>0?o.mixedAdd(n[c-1>>1]):o.mixedAdd(n[-c-1>>1].neg()):c>0?o.add(n[c-1>>1]):o.add(n[-c-1>>1].neg())}return"affine"===e.type?o.toP():o},Ca.prototype._wnafMulAdd=function(e,t,r,i,n){var s,o,a,h=this._wnafT1,c=this._wnafT2,u=this._wnafT3,l=0;for(s=0;s=1;s-=2){var d=s-1,p=s;if(1===h[d]&&1===h[p]){var g=[t[d],null,null,t[p]];0===t[d].y.cmp(t[p].y)?(g[1]=t[d].add(t[p]),g[2]=t[d].toJ().mixedAdd(t[p].neg())):0===t[d].y.cmp(t[p].y.redNeg())?(g[1]=t[d].toJ().mixedAdd(t[p]),g[2]=t[d].add(t[p].neg())):(g[1]=t[d].toJ().mixedAdd(t[p]),g[2]=t[d].toJ().mixedAdd(t[p].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],m=Ta(r[d],r[p]);for(l=Math.max(m[0].length,l),u[d]=new Array(l),u[p]=new Array(l),o=0;o=0;s--){for(var E=0;s>=0;){var S=!0;for(o=0;o=0&&E++,b=b.dblp(E),s<0)break;for(o=0;o0?a=c[o][M-1>>1]:M<0&&(a=c[o][-M-1>>1].neg()),b="affine"===a.type?b.mixedAdd(a):b.add(a))}}for(s=0;s=Math.ceil((e.bitLength()+1)/t.step)},ka.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],i=this,n=0;n=0&&(s=t,o=r),i.negative&&(i=i.neg(),n=n.neg()),s.negative&&(s=s.neg(),o=o.neg()),[{a:i,b:n},{a:s,b:o}]},Da.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),s=r.b.neg().mul(e).divRound(this.n),o=n.mul(r.a),a=s.mul(i.a),h=n.mul(r.b),c=s.mul(i.b);return{k1:e.sub(o).sub(a),k2:h.add(c).neg()}},Da.prototype.pointFromX=function(e,t){(e=new(ya())(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),i=r.redSqrt();if(0!==i.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var n=i.fromRed().isOdd();return(t&&!n||!t&&n)&&(i=i.redNeg()),this.point(e,i)},Da.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)},Da.prototype._endoWnafMulAdd=function(e,t,r){for(var i=this._endoWnafT1,n=this._endoWnafT2,s=0;s":""},$a.prototype.isInfinity=function(){return this.inf},$a.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),i=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,i)},$a.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),i=e.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(i),s=n.redSqr().redISub(this.x.redAdd(this.x)),o=n.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},$a.prototype.getX=function(){return this.x.fromRed()},$a.prototype.getY=function(){return this.y.fromRed()},$a.prototype.mul=function(e){return e=new(ya())(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},$a.prototype.mulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n):this.curve._wnafMulAdd(1,i,n,2)},$a.prototype.jmulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n,!0):this.curve._wnafMulAdd(1,i,n,2,!0)},$a.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},$a.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,i=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(i)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(i)}}}return t},$a.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},ja(Ba,Ua.BasePoint),Da.prototype.jpoint=function(e,t,r){return new Ba(this,e,t,r)},Ba.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),i=this.y.redMul(t).redMul(e);return this.curve.point(r,i)},Ba.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Ba.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),s=this.y.redMul(t.redMul(e.z)),o=e.y.redMul(r.redMul(this.z)),a=i.redSub(n),h=s.redSub(o);if(0===a.cmpn(0))return 0!==h.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=a.redSqr(),u=c.redMul(a),l=i.redMul(c),f=h.redSqr().redIAdd(u).redISub(l).redISub(l),d=h.redMul(l.redISub(f)).redISub(s.redMul(u)),p=this.z.redMul(e.z).redMul(a);return this.curve.jpoint(f,d,p)},Ba.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,s=e.y.redMul(t).redMul(this.z),o=r.redSub(i),a=n.redSub(s);if(0===o.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=o.redSqr(),c=h.redMul(o),u=r.redMul(h),l=a.redSqr().redIAdd(c).redISub(u).redISub(u),f=a.redMul(u.redISub(l)).redISub(n.redMul(c)),d=this.z.redMul(o);return this.curve.jpoint(l,f,d)},Ba.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var r=this;for(t=0;t=0)return!1;if(r.redIAdd(n),0===this.x.cmp(r))return!0}},Ba.prototype.inspect=function(){return this.isInfinity()?"":""},Ba.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var Ka=Aa((function(e,t){var r=t;r.base=Ua,r.short=za,r.mont=null,r.edwards=null})),Fa=Aa((function(e,t){var r,i=t,n=Na.assert;function s(e){"short"===e.type?this.curve=new Ka.short(e):"edwards"===e.type?this.curve=new Ka.edwards(e):this.curve=new Ka.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,n(this.g.validate(),"Invalid curve"),n(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function o(e,t){Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get:function(){var r=new s(t);return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:r}),r}})}i.PresetCurve=s,o("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:Ia().sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),o("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:Ia().sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),o("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:Ia().sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),o("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:Ia().sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),o("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:Ia().sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),o("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Ia().sha256,gRed:!1,g:["9"]}),o("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Ia().sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{r=null.crash()}catch(e){r=void 0}o("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:Ia().sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",r]})}));function Va(e){if(!(this instanceof Va))return new Va(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=Pa.toArray(e.entropy,e.entropyEnc||"hex"),r=Pa.toArray(e.nonce,e.nonceEnc||"hex"),i=Pa.toArray(e.pers,e.persEnc||"hex");Oa(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,i)}var Ha=Va;Va.prototype._init=function(e,t,r){var i=e.concat(t).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var n=0;n=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},Va.prototype.generate=function(e,t,r,i){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(i=r,r=t,t=null),r&&(r=Pa.toArray(r,i||"hex"),this._update(r));for(var n=[];n.length"};var Ya=Na.assert;function Xa(e,t){if(e instanceof Xa)return e;this._importDER(e,t)||(Ya(e.r&&e.s,"Signature without r or s"),this.r=new(ya())(e.r,16),this.s=new(ya())(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}var Qa=Xa;function Za(){this.place=0}function eh(e,t){var r=e[t.place++];if(!(128&r))return r;var i=15&r;if(0===i||i>4)return!1;for(var n=0,s=0,o=t.place;s>>=0;return!(n<=127)&&(t.place=o,n)}function th(e){for(var t=0,r=e.length-1;!e[t]&&!(128&e[t+1])&&t>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}Xa.prototype._importDER=function(e,t){e=Na.toArray(e,t);var r=new Za;if(48!==e[r.place++])return!1;var i=eh(e,r);if(!1===i)return!1;if(i+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var n=eh(e,r);if(!1===n)return!1;var s=e.slice(r.place,n+r.place);if(r.place+=n,2!==e[r.place++])return!1;var o=eh(e,r);if(!1===o)return!1;if(e.length!==o+r.place)return!1;var a=e.slice(r.place,o+r.place);if(0===s[0]){if(!(128&s[1]))return!1;s=s.slice(1)}if(0===a[0]){if(!(128&a[1]))return!1;a=a.slice(1)}return this.r=new(ya())(s),this.s=new(ya())(a),this.recoveryParam=null,!0},Xa.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=th(t),r=th(r);!(r[0]||128&r[1]);)r=r.slice(1);var i=[2];rh(i,t.length),(i=i.concat(t)).push(2),rh(i,r.length);var n=i.concat(r),s=[48];return rh(s,n.length),s=s.concat(n),Na.encode(s,e)};var ih=function(){throw new Error("unsupported")},nh=Na.assert;function sh(e){if(!(this instanceof sh))return new sh(e);"string"==typeof e&&(nh(Object.prototype.hasOwnProperty.call(Fa,e),"Unknown curve "+e),e=Fa[e]),e instanceof Fa.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}var oh=sh;sh.prototype.keyPair=function(e){return new Ja(this,e)},sh.prototype.keyFromPrivate=function(e,t){return Ja.fromPrivate(this,e,t)},sh.prototype.keyFromPublic=function(e,t){return Ja.fromPublic(this,e,t)},sh.prototype.genKeyPair=function(e){e||(e={});for(var t=new Ha({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||ih(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),i=this.n.sub(new(ya())(2));;){var n=new(ya())(t.generate(r));if(!(n.cmp(i)>0))return n.iaddn(1),this.keyFromPrivate(n)}},sh.prototype._truncateToN=function(e,t){var r=8*e.byteLength()-this.n.bitLength();return r>0&&(e=e.ushrn(r)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},sh.prototype.sign=function(e,t,r,i){"object"==typeof r&&(i=r,r=null),i||(i={}),t=this.keyFromPrivate(t,r),e=this._truncateToN(new(ya())(e,16));for(var n=this.n.byteLength(),s=t.getPrivate().toArray("be",n),o=e.toArray("be",n),a=new Ha({hash:this.hash,entropy:s,nonce:o,pers:i.pers,persEnc:i.persEnc||"utf8"}),h=this.n.sub(new(ya())(1)),c=0;;c++){var u=i.k?i.k(c):new(ya())(a.generate(this.n.byteLength()));if(!((u=this._truncateToN(u,!0)).cmpn(1)<=0||u.cmp(h)>=0)){var l=this.g.mul(u);if(!l.isInfinity()){var f=l.getX(),d=f.umod(this.n);if(0!==d.cmpn(0)){var p=u.invm(this.n).mul(d.mul(t.getPrivate()).iadd(e));if(0!==(p=p.umod(this.n)).cmpn(0)){var g=(l.getY().isOdd()?1:0)|(0!==f.cmp(d)?2:0);return i.canonical&&p.cmp(this.nh)>0&&(p=this.n.sub(p),g^=1),new Qa({r:d,s:p,recoveryParam:g})}}}}}},sh.prototype.verify=function(e,t,r,i){e=this._truncateToN(new(ya())(e,16)),r=this.keyFromPublic(r,i);var n=(t=new Qa(t,"hex")).r,s=t.s;if(n.cmpn(1)<0||n.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var o,a=s.invm(this.n),h=a.mul(e).umod(this.n),c=a.mul(n).umod(this.n);return this.curve._maxwellTrick?!(o=this.g.jmulAdd(h,r.getPublic(),c)).isInfinity()&&o.eqXToP(n):!(o=this.g.mulAdd(h,r.getPublic(),c)).isInfinity()&&0===o.getX().umod(this.n).cmp(n)},sh.prototype.recoverPubKey=function(e,t,r,i){nh((3&r)===r,"The recovery param is more than two bits"),t=new Qa(t,i);var n=this.n,s=new(ya())(e),o=t.r,a=t.s,h=1&r,c=r>>1;if(o.cmp(this.curve.p.umod(this.curve.n))>=0&&c)throw new Error("Unable to find sencond key candinate");o=c?this.curve.pointFromX(o.add(this.curve.n),h):this.curve.pointFromX(o,h);var u=t.r.invm(n),l=n.sub(s).mul(u).umod(n),f=a.mul(u).umod(n);return this.g.mulAdd(l,o,f)},sh.prototype.getKeyRecoveryParam=function(e,t,r,i){if(null!==(t=new Qa(t,i)).recoveryParam)return t.recoveryParam;for(var n=0;n<4;n++){var s;try{s=this.recoverPubKey(e,t,n)}catch(e){continue}if(s.eq(r))return n}throw new Error("Unable to find valid recovery factor")};var ah=Aa((function(e,t){var r=t;r.version="6.5.4",r.utils=Na,r.rand=function(){throw new Error("unsupported")},r.curve=Ka,r.curves=Fa,r.ec=oh,r.eddsa=null})).ec;function hh(e,t,r){Object.defineProperty(e,t,{enumerable:!0,value:r,writable:!1})}new Ho("properties/5.7.0");const ch=new Ho("signing-key/5.7.0");let uh=null;function lh(){return uh||(uh=new ah("secp256k1")),uh}class fh{constructor(e){hh(this,"curve","secp256k1"),hh(this,"privateKey",ta(e)),32!==function(e){if("string"!=typeof e)e=ta(e);else if(!Zo(e)||e.length%2)return null;return(e.length-2)/2}(this.privateKey)&&ch.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");const t=lh().keyFromPrivate(Qo(this.privateKey));hh(this,"publicKey","0x"+t.getPublic(!1,"hex")),hh(this,"compressedPublicKey","0x"+t.getPublic(!0,"hex")),hh(this,"_isSigningKey",!0)}_addPoint(e){const t=lh().keyFromPublic(Qo(this.publicKey)),r=lh().keyFromPublic(Qo(e));return"0x"+t.pub.add(r.pub).encodeCompressed("hex")}signDigest(e){const t=lh().keyFromPrivate(Qo(this.privateKey)),r=Qo(e);32!==r.length&&ch.throwArgumentError("bad digest length","digest",e);const i=t.sign(r,{canonical:!0});return na({recoveryParam:i.recoveryParam,r:ia("0x"+i.r.toString(16),32),s:ia("0x"+i.s.toString(16),32)})}computeSharedSecret(e){const t=lh().keyFromPrivate(Qo(this.privateKey)),r=lh().keyFromPublic(Qo(dh(e)));return ia("0x"+t.derive(r.getPublic()).toString(16),32)}static isSigningKey(e){return!(!e||!e._isSigningKey)}}function dh(e,t){const r=Qo(e);if(32===r.length){const e=new fh(r);return t?"0x"+lh().keyFromPrivate(r).getPublic(!0,"hex"):e.publicKey}return 33===r.length?t?ta(r):"0x"+lh().keyFromPublic(r).getPublic(!1,"hex"):65===r.length?t?"0x"+lh().keyFromPublic(r).getPublic(!0,"hex"):ta(r):ch.throwArgumentError("invalid public or private key","key","[REDACTED]")}var ph;new Ho("transactions/5.7.0"),function(e){e[e.legacy=0]="legacy",e[e.eip2930=1]="eip2930",e[e.eip1559=2]="eip1559"}(ph||(ph={}));var gh=r(204),yh=r.n(gh);class mh{constructor(e){this.client=e}}class vh{constructor(e){this.opts=e}}const wh={wc_authRequest:{req:{ttl:j.ONE_DAY,prompt:!0,tag:3e3},res:{ttl:j.ONE_DAY,prompt:!1,tag:3001}}},bh={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},_h="authClient",Eh="wc@1:auth:",Sh=`${Eh}:PUB_KEY`;function Mh(e){return e?.split(":")}function Ih(e){const t=e&&Mh(e);if(t)return t.pop()}async function Ah(e,t,r,i,n){switch(r.t){case"eip191":return function(e,t,r){return function(e,t){return function(e){return Sa(ra(aa(ra(dh(e),1)),12))}(function(e,t){const r=na(t),i={r:Qo(r.r),s:Qo(r.s)};return"0x"+lh().recoverPubKey(Qo(e),i,r.recoveryParam).encode("hex",!1)}(Qo(e),t))}(pa(t),r).toLowerCase()===e.toLowerCase()}(e,t,r.s);case"eip1271":return await async function(e,t,r,i,n){try{const s="0x1626ba7e",o="0000000000000000000000000000000000000000000000000000000000000040",a="0000000000000000000000000000000000000000000000000000000000000041",h=r.substring(2),c=s+pa(t).substring(2)+o+a+h,u=await yh()(`https://rpc.walletconnect.com/v1/?chainId=${i}&projectId=${n}`,{method:"POST",body:JSON.stringify({id:Date.now()+Math.floor(1e3*Math.random()),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:c},"latest"]})}),{result:l}=await u.json();return!!l&&l.slice(0,s.length).toLowerCase()===s.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}(e,t,r.s,i,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function Oh(e){return e.getAll().filter((e=>"requester"in e))}function xh(e,t){return Oh(e).find((e=>e.id===t))}var Ph=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i>>0,o=new Uint8Array(s);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var l=0,f=s-1;(0!==u||l>>0,o[f]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");n=l,t++}if(" "!==e[t]){for(var d=s-n;d!==s&&0===o[d];)d++;for(var p=new Uint8Array(i+(s-d)),g=i;d!==s;)p[g++]=o[d++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,i=0,n=0,s=t.length;n!==s&&0===t[n];)n++,r++;for(var o=(s-n)*u+1>>>0,c=new Uint8Array(o);n!==s;){for(var l=t[n],f=0,d=o-1;(0!==l||f>>0,c[d]=l%a>>>0,l=l/a>>>0;if(0!==l)throw new Error("Non-zero carry");i=f,n++}for(var p=o-i;p!==o&&0===c[p];)p++;for(var g=h.repeat(r);p{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class Rh{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Th{constructor(e,t,r){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Ch(this,e)}}class Lh{constructor(e){this.decoders=e}or(e){return Ch(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Ch=(e,t)=>new Lh({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Uh{constructor(e,t,r,i){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=i,this.encoder=new Rh(e,t,r),this.decoder=new Th(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const kh=({name:e,prefix:t,encode:r,decode:i})=>new Uh(e,t,r,i),jh=({prefix:e,name:t,alphabet:r})=>{const{encode:i,decode:n}=Ph(r,t);return kh({prefix:e,name:t,encode:i,decode:e=>Nh(n(e))})},qh=({name:e,prefix:t,bitsPerChar:r,alphabet:i})=>kh({prefix:t,name:e,encode:e=>((e,t,r)=>{const i="="===t[t.length-1],n=(1<r;)o-=r,s+=t[n&a>>o];if(o&&(s+=t[n&a<((e,t,r,i)=>{const n={};for(let e=0;e=8&&(a-=8,o[c++]=255&h>>a)}if(a>=r||255&h<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,i,r,e)}),Dh=kh({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var zh=Object.freeze({__proto__:null,identity:Dh});const $h=qh({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Bh=Object.freeze({__proto__:null,base2:$h});const Kh=qh({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Fh=Object.freeze({__proto__:null,base8:Kh});const Vh=jh({prefix:"9",name:"base10",alphabet:"0123456789"});var Hh=Object.freeze({__proto__:null,base10:Vh});const Wh=qh({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Gh=qh({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Jh=Object.freeze({__proto__:null,base16:Wh,base16upper:Gh});const Yh=qh({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xh=qh({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Qh=qh({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zh=qh({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ec=qh({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),tc=qh({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rc=qh({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ic=qh({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nc=qh({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var sc=Object.freeze({__proto__:null,base32:Yh,base32upper:Xh,base32pad:Qh,base32padupper:Zh,base32hex:ec,base32hexupper:tc,base32hexpad:rc,base32hexpadupper:ic,base32z:nc});const oc=jh({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ac=jh({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hc=Object.freeze({__proto__:null,base36:oc,base36upper:ac});const cc=jh({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),uc=jh({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lc=Object.freeze({__proto__:null,base58btc:cc,base58flickr:uc});const fc=qh({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dc=qh({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pc=qh({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gc=qh({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var yc=Object.freeze({__proto__:null,base64:fc,base64pad:dc,base64url:pc,base64urlpad:gc});const mc=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),vc=mc.reduce(((e,t,r)=>(e[r]=t,e)),[]),wc=mc.reduce(((e,t,r)=>(e[t.codePointAt(0)]=r,e)),[]),bc=kh({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+vc[t]),"")},decode:function(e){const t=[];for(const r of e){const e=wc[r.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}});var _c=Object.freeze({__proto__:null,base256emoji:bc}),Ec=128,Sc=-128,Mc=Math.pow(2,31),Ic=Math.pow(2,7),Ac=Math.pow(2,14),Oc=Math.pow(2,21),xc=Math.pow(2,28),Pc=Math.pow(2,35),Nc=Math.pow(2,42),Rc=Math.pow(2,49),Tc=Math.pow(2,56),Lc=Math.pow(2,63),Cc=function e(t,r,i){r=r||[];for(var n=i=i||0;t>=Mc;)r[i++]=255&t|Ec,t/=128;for(;t⪼)r[i++]=255&t|Ec,t>>>=7;return r[i]=0|t,e.bytes=i-n+1,r},Uc=function(e){return e(Cc(e,t,r),t),jc=e=>Uc(e),qc=(e,t)=>{const r=t.byteLength,i=jc(e),n=i+jc(r),s=new Uint8Array(n+r);return kc(e,s,0),kc(r,s,i),s.set(t,n),new Dc(e,r,t,s)};class Dc{constructor(e,t,r,i){this.code=e,this.size=t,this.digest=r,this.bytes=i}}const zc=({name:e,code:t,encode:r})=>new $c(e,t,r);class $c{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?qc(this.code,t):t.then((e=>qc(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Bc=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Kc=zc({name:"sha2-256",code:18,encode:Bc("SHA-256")}),Fc=zc({name:"sha2-512",code:19,encode:Bc("SHA-512")});Object.freeze({__proto__:null,sha256:Kc,sha512:Fc});const Vc=Nh,Hc={code:0,name:"identity",encode:Vc,digest:e=>qc(0,Vc(e))};Object.freeze({__proto__:null,identity:Hc}),new TextEncoder,new TextDecoder;const Wc={...zh,...Bh,...Fh,...Hh,...Jh,...sc,...hc,...lc,...yc,..._c};function Gc(e,t,r,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:i}}}const Jc=Gc("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Yc=Gc("ascii","a",(e=>{let t="a";for(let r=0;r{const t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?globalThis.Buffer.allocUnsafe(e):new Uint8Array(e)}((e=e.substring(1)).length);for(let r=0;rt in e?Zc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ou=(e,t)=>{for(var r in t||(t={}))iu.call(t,r)&&su(e,r,t[r]);if(ru)for(var r of ru(t))nu.call(t,r)&&su(e,r,t[r]);return e},au=(e,t)=>eu(e,tu(t));class hu extends mh{constructor(e){super(e),this.initialized=!1,this.name="authEngine",this.init=()=>{this.initialized||(this.registerRelayerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(wh)}),this.initialized=!0)},this.request=async(e,t)=>{if(this.isInitialized(),!function(e){const t=ii(e.aud),r=new RegExp(`${e.domain}`).test(e.aud),i=!!e.nonce,n=!e.type||"eip4361"===e.type,s=e.expiry;if(s&&!fi(s,bh)){const{message:e}=Jr("MISSING_OR_INVALID",`request() expiry: ${s}. Expiry must be a number (in seconds) between ${bh.min} and ${bh.max}`);throw new Error(e)}return!!(t&&r&&i&&n)}(e))throw new Error("Invalid request");if(null!=t&&t.topic)return await this.requestOnKnownPairing(t.topic,e);const{chainId:r,statement:i,aud:n,domain:s,nonce:o,type:a,exp:h,nbf:c}=e,{topic:u,uri:l}=await this.client.core.pairing.create();this.client.logger.info({message:"Generated new pairing",pairing:{topic:u,uri:l}});const f=await this.client.core.crypto.generateKeyPair(),d=Gt(f);await this.client.authKeys.set(Sh,{responseTopic:d,publicKey:f}),await this.client.pairingTopics.set(d,{topic:d,pairingTopic:u}),await this.client.core.relayer.subscribe(d),this.client.logger.info(`sending request to new pairing topic: ${u}`);const p=await this.sendRequest(u,"wc_authRequest",{payloadParams:{type:a??"eip4361",chainId:r,statement:i,aud:n,domain:s,version:"1",nonce:o,iat:(new Date).toISOString(),exp:h,nbf:c},requester:{publicKey:f,metadata:this.client.metadata}},{},e.expiry);return this.client.logger.info(`sent request to new pairing topic: ${u}`),{uri:l,id:p}},this.respond=async(e,t)=>{if(this.isInitialized(),!function(e,t){return!!xh(t,e.id)}(e,this.client.requests))throw new Error("Invalid response");const r=xh(this.client.requests,e.id);if(!r)throw new Error(`Could not find pending auth request with id ${e.id}`);const i=r.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),s=Gt(i),o={type:1,receiverPublicKey:i,senderPublicKey:n};if("error"in e)return void await this.sendError(r.id,s,e,o);const a={h:{t:"eip4361"},p:au(ou({},r.cacaoPayload),{iss:t}),s:e.signature};await this.sendResult(r.id,s,a,o),await this.client.core.pairing.activate({topic:r.pairingTopic}),await this.client.requests.update(r.id,ou({},a))},this.getPendingRequests=()=>Oh(this.client.requests),this.formatMessage=(e,t)=>{this.client.logger.debug(`formatMessage, cacao is: ${JSON.stringify(e)}`);const r=`${e.domain} wants you to sign in with your Ethereum account:`,i=Ih(t),n=e.statement,s=`URI: ${e.aud}`,o=`Version: ${e.version}`,a=`Chain ID: ${function(e){const t=e&&Mh(e);if(t)return t[3]}(t)}`,h=`Nonce: ${e.nonce}`,c=`Issued At: ${e.iat}`,u=e.exp?`Expiry: ${e.exp}`:void 0,l=e.resources&&e.resources.length>0?`Resources:\n${e.resources.map((e=>`- ${e}`)).join("\n")}`:void 0;return[r,i,"",n,"",s,o,a,h,c,u,l].filter((e=>null!=e)).join("\n")},this.setExpiry=async(e,t)=>{this.client.core.pairing.pairings.keys.includes(e)&&await this.client.core.pairing.updateExpiry({topic:e,expiry:t}),this.client.core.expirer.set(e,t)},this.sendRequest=async(e,t,r,i,n)=>{const s=Ii(t,r),o=await this.client.core.crypto.encode(e,s,i),a=wh[t].req;if(n&&(a.ttl=n),this.client.core.history.set(e,s),lr()){const e=Qc(JSON.stringify(s));this.client.core.verify.register({attestationId:e})}return await this.client.core.relayer.publish(e,o,au(ou({},a),{internal:{throwOnFailedPublish:!0}})),s.id},this.sendResult=async(e,t,r,i)=>{const n=Ai(e,r),s=await this.client.core.crypto.encode(t,n,i),o=await this.client.core.history.get(t,e),a=wh[o.request.method].res;return await this.client.core.relayer.publish(t,s,au(ou({},a),{internal:{throwOnFailedPublish:!0}})),await this.client.core.history.resolve(n),n.id},this.sendError=async(e,t,r,i)=>{const n=Oi(e,r.error),s=await this.client.core.crypto.encode(t,n,i),o=await this.client.core.history.get(t,e),a=wh[o.request.method].res;return await this.client.core.relayer.publish(t,s,a),await this.client.core.history.resolve(n),n.id},this.requestOnKnownPairing=async(e,t)=>{const r=this.client.core.pairing.pairings.getAll({active:!0}).find((t=>t.topic===e));if(!r)throw new Error(`Could not find pairing for provided topic ${e}`);const{publicKey:i}=this.client.authKeys.get(Sh),{chainId:n,statement:s,aud:o,domain:a,nonce:h,type:c}=t,u=await this.sendRequest(r.topic,"wc_authRequest",{payloadParams:{type:c??"eip4361",chainId:n,statement:s,aud:o,domain:a,version:"1",nonce:h,iat:(new Date).toISOString()},requester:{publicKey:i,metadata:this.client.metadata}},{},t.expiry);return this.client.logger.info(`sent request to known pairing topic: ${r.topic}`),{id:u}},this.onPairingCreated=e=>{const t=this.getPendingRequests();if(t){const r=Object.values(t).find((t=>t.pairingTopic===e.topic));r&&this.handleAuthRequest(r)}},this.onRelayEventRequest=e=>{const{topic:t,payload:r}=e,i=r.method;return"wc_authRequest"===i?this.onAuthRequest(t,r):this.client.logger.info(`Unsupported request method ${i}`)},this.onRelayEventResponse=async e=>{const{topic:t,payload:r}=e,i=(await this.client.core.history.get(t,r.id)).request.method;return"wc_authRequest"===i?this.onAuthResponse(t,r):this.client.logger.info(`Unsupported response method ${i}`)},this.onAuthRequest=async(e,t)=>{const{requester:r,payloadParams:i}=t.params;this.client.logger.info({type:"onAuthRequest",topic:e,payload:t});const n=Qc(JSON.stringify(t)),s=await this.getVerifyContext(n,this.client.metadata),o={requester:r,pairingTopic:e,id:t.id,cacaoPayload:i,verifyContext:s};await this.client.requests.set(t.id,o),this.handleAuthRequest(o)},this.handleAuthRequest=async e=>{const{id:t,pairingTopic:r,requester:i,cacaoPayload:n,verifyContext:s}=e;try{this.client.emit("auth_request",{id:t,topic:r,params:{requester:i,cacaoPayload:n},verifyContext:s})}catch(t){await this.sendError(e.id,e.pairingTopic,t),this.client.logger.error(t)}},this.onAuthResponse=async(e,t)=>{const{id:r}=t;if(this.client.logger.info({type:"onAuthResponse",topic:e,response:t}),ji(t)){const{pairingTopic:i}=this.client.pairingTopics.get(e);await this.client.core.pairing.activate({topic:i});const{s:n,p:s}=t.result;await this.client.requests.set(r,ou({id:r,pairingTopic:i},t.result));const o=this.formatMessage(s,s.iss);this.client.logger.debug("reconstructed message:\n",JSON.stringify(o)),this.client.logger.debug("payload.iss:",s.iss),this.client.logger.debug("signature:",n);const a=Ih(s.iss),h=function(e){const t=e&&Mh(e);if(t)return t[2]+":"+t[3]}(s.iss);if(!a)throw new Error("Could not derive address from `payload.iss`");if(!h)throw new Error("Could not derive chainId from `payload.iss`");this.client.logger.debug("walletAddress extracted from `payload.iss`:",a),await Ah(a,o,n,h,this.client.projectId)?this.client.emit("auth_response",{id:r,topic:e,params:t}):this.client.emit("auth_response",{id:r,topic:e,params:{message:"Invalid signature",code:-1}})}else qi(t)&&this.client.emit("auth_response",{id:r,topic:e,params:t})},this.getVerifyContext=async(e,t)=>{const r={verified:{verifyUrl:t.verifyUrl||"",validation:"UNKNOWN",origin:t.url||""}};try{const i=await this.client.core.verify.resolve({attestationId:e,verifyUrl:t.verifyUrl});i&&(r.verified.origin=i.origin,r.verified.isScam=i.isScam,r.verified.validation=origin===new URL(t.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.error(e)}return this.client.logger.info(`Verify context: ${JSON.stringify(r)}`),r}}isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(Ms,(async e=>{const{topic:t,message:r}=e,{responseTopic:i,publicKey:n}=this.client.authKeys.keys.includes(Sh)?this.client.authKeys.get(Sh):{responseTopic:void 0,publicKey:void 0};if(i&&t!==i)return void this.client.logger.debug("[Auth] Ignoring message from unknown topic",t);const s=await this.client.core.crypto.decode(t,r,{receiverPublicKey:n});Ui(s)?(this.client.core.history.set(t,s),this.onRelayEventRequest({topic:t,payload:s})):ki(s)&&(await this.client.core.history.resolve(s),this.onRelayEventResponse({topic:t,payload:s}))}))}registerPairingEvents(){this.client.core.pairing.events.on(zs,(e=>this.onPairingCreated(e)))}}class cu extends vh{constructor(e){super(e),this.protocol="wc",this.version=1,this.name=_h,this.events=new g.EventEmitter,this.emit=(e,t)=>this.events.emit(e,t),this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.request=async(e,t)=>{try{return await this.engine.request(e,t)}catch(e){throw this.logger.error(e.message),e}},this.respond=async(e,t)=>{try{return await this.engine.respond(e,t)}catch(e){throw this.logger.error(e.message),e}},this.getPendingRequests=()=>{try{return this.engine.getPendingRequests()}catch(e){throw this.logger.error(e.message),e}},this.formatMessage=(e,t)=>{try{return this.engine.formatMessage(e,t)}catch(e){throw this.logger.error(e.message),e}};const t=typeof e.logger<"u"&&"string"!=typeof e.logger?e.logger:(0,w.pino)((0,w.getDefaultLoggerOptions)({level:e.logger||"error"}));this.name=e?.name||_h,this.metadata=e.metadata,this.projectId=e.projectId,this.core=e.core||new ko(e),this.logger=(0,w.generateChildLogger)(t,this.name),this.authKeys=new Mo(this.core,this.logger,"authKeys",Eh,(()=>Sh)),this.pairingTopics=new Mo(this.core,this.logger,"pairingTopics",Eh),this.requests=new Mo(this.core,this.logger,"requests",Eh,(e=>e.id)),this.engine=new hu(this)}static async init(e){const t=new cu(e);return await t.initialize(),t}get context(){return(0,w.getLoggerContext)(this.logger)}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.authKeys.init(),await this.requests.init(),await this.pairingTopics.init(),await this.engine.init(),this.logger.info("AuthClient Initialization Success"),this.logger.info({authClient:this})}catch(e){throw this.logger.info("AuthClient Initialization Failure"),this.logger.error(e.message),e}}}const uu=cu,lu="client",fu=`wc@2:${lu}:`,du=lu,pu="WALLETCONNECT_DEEPLINK_CHOICE",gu=j.SEVEN_DAYS,yu={wc_sessionPropose:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1104},res:{ttl:j.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1106},res:{ttl:j.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1112},res:{ttl:j.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1115}}},mu={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},vu="IDLE",wu="ACTIVE",bu=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var _u=Object.defineProperty,Eu=Object.defineProperties,Su=Object.getOwnPropertyDescriptors,Mu=Object.getOwnPropertySymbols,Iu=Object.prototype.hasOwnProperty,Au=Object.prototype.propertyIsEnumerable,Ou=(e,t,r)=>t in e?_u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,xu=(e,t)=>{for(var r in t||(t={}))Iu.call(t,r)&&Ou(e,r,t[r]);if(Mu)for(var r of Mu(t))Au.call(t,r)&&Ou(e,r,t[r]);return e},Pu=(e,t)=>Eu(e,Su(t));class Nu extends R{constructor(e){super(e),this.name="engine",this.events=new(y()),this.initialized=!1,this.ignoredPayloadTypes=[1],this.requestQueue={state:vu,queue:[]},this.sessionRequestQueue={state:vu,queue:[]},this.requestQueueDelay=j.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(yu)}),this.initialized=!0,setTimeout((()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()}),(0,j.toMiliseconds)(this.requestQueueDelay)))},this.connect=async e=>{await this.isInitialized();const t=Pu(xu({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t);const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:n,sessionProperties:s,relays:o}=t;let a,h=r,c=!1;if(h&&(c=this.client.core.pairing.pairings.get(h).active),!h||!c){const{topic:e,uri:t}=await this.client.core.pairing.create();h=e,a=t}const u=await this.client.core.crypto.generateKeyPair(),l=xu({requiredNamespaces:i,optionalNamespaces:n,relays:o??[{protocol:"irn"}],proposer:{publicKey:u,metadata:this.client.metadata}},s&&{sessionProperties:s}),{reject:f,resolve:d,done:p}=mr(j.FIVE_MINUTES,"Proposal expired");if(this.events.once(Sr("session_connect"),(async({error:e,session:t})=>{if(e)f(e);else if(t){t.self.publicKey=u;const e=Pu(xu({},t),{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces});await this.client.session.set(t.topic,e),await this.setExpiry(t.topic,t.expiry),h&&await this.client.core.pairing.updateMetadata({topic:h,metadata:t.peer.metadata}),d(e)}})),!h){const{message:e}=Jr("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(e)}const g=await this.sendRequest({topic:h,method:"wc_sessionPropose",params:l}),y=_r(j.FIVE_MINUTES);return await this.setProposal(g,xu({id:g,expiry:y},l)),{uri:a,approval:p}},this.pair=async e=>(await this.isInitialized(),await this.client.core.pairing.pair(e)),this.approve=async e=>{await this.isInitialized(),await this.isValidApprove(e);const{id:t,relayProtocol:r,namespaces:i,sessionProperties:n}=e,s=this.client.proposal.get(t);let{pairingTopic:o,proposer:a,requiredNamespaces:h,optionalNamespaces:c}=s;o=o||"",Qr(h)||(h=function(e,t){const r=oi(e,"approve()");if(r)throw new Error(r.message);const i={};for(const[t,r]of Object.entries(e))i[t]={methods:r.methods,events:r.events,chains:r.accounts.map((e=>`${e.split(":")[0]}:${e.split(":")[1]}`))};return i}(i));const u=await this.client.core.crypto.generateKeyPair(),l=a.publicKey,f=await this.client.core.crypto.generateSharedKey(u,l);o&&t&&(await this.client.core.pairing.updateMetadata({topic:o,metadata:a.metadata}),await this.sendResult({id:t,topic:o,result:{relay:{protocol:r??"irn"},responderPublicKey:u}}),await this.client.proposal.delete(t,Yr("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:o}));const d=xu({relay:{protocol:r??"irn"},namespaces:i,requiredNamespaces:h,optionalNamespaces:c,pairingTopic:o,controller:{publicKey:u,metadata:this.client.metadata},expiry:_r(gu)},n&&{sessionProperties:n});await this.client.core.relayer.subscribe(f),await this.sendRequest({topic:f,method:"wc_sessionSettle",params:d,throwOnFailedPublish:!0});const p=Pu(xu({},d),{topic:f,pairingTopic:o,acknowledged:!1,self:d.controller,peer:{publicKey:a.publicKey,metadata:a.metadata},controller:u});return await this.client.session.set(f,p),await this.setExpiry(f,_r(gu)),{topic:f,acknowledged:()=>new Promise((e=>setTimeout((()=>e(this.client.session.get(f))),500)))}},this.reject=async e=>{await this.isInitialized(),await this.isValidReject(e);const{id:t,reason:r}=e,{pairingTopic:i}=this.client.proposal.get(t);i&&(await this.sendError(t,i,r),await this.client.proposal.delete(t,Yr("USER_DISCONNECTED")))},this.update=async e=>{await this.isInitialized(),await this.isValidUpdate(e);const{topic:t,namespaces:r}=e,i=await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:r}}),{done:n,resolve:s,reject:o}=mr();return this.events.once(Sr("session_update",i),(({error:e})=>{e?o(e):s()})),await this.client.session.update(t,{namespaces:r}),{acknowledged:n}},this.extend=async e=>{await this.isInitialized(),await this.isValidExtend(e);const{topic:t}=e,r=await this.sendRequest({topic:t,method:"wc_sessionExtend",params:{}}),{done:i,resolve:n,reject:s}=mr();return this.events.once(Sr("session_extend",r),(({error:e})=>{e?s(e):n()})),await this.setExpiry(t,_r(gu)),{acknowledged:i}},this.request=async e=>{await this.isInitialized(),await this.isValidRequest(e);const{chainId:t,request:i,topic:n,expiry:s}=e,o=Si(),{done:a,resolve:h,reject:c}=mr(s,"Request expired. Please try again.");return this.events.once(Sr("session_request",o),(({error:e,result:t})=>{e?c(e):h(t)})),await Promise.all([new Promise((async e=>{await this.sendRequest({clientRpcId:o,topic:n,method:"wc_sessionRequest",params:{request:i,chainId:t},expiry:s,throwOnFailedPublish:!0}).catch((e=>c(e))),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:t,id:o}),e()})),new Promise((async e=>{const t=await this.client.core.storage.getItem(pu);(async function({id:e,topic:t,wcDeepLink:i}){try{if(!i)return;const n="string"==typeof i?JSON.parse(i):i;let s=n?.href;if("string"!=typeof s)return;s.endsWith("/")&&(s=s.slice(0,-1));const o=`${s}/wc?requestId=${e}&sessionTopic=${t}`,a=fr();a===ar.browser?o.startsWith("https://")?window.open(o,"_blank","noreferrer noopener"):window.open(o,"_self","noreferrer noopener"):a===ar.reactNative&&typeof(null==r.g?void 0:r.g.Linking)<"u"&&await r.g.Linking.openURL(o)}catch(e){console.error(e)}})({id:o,topic:n,wcDeepLink:t}),e()})),a()]).then((e=>e[2]))},this.respond=async e=>{await this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:r}=e,{id:i}=r;ji(r)?await this.sendResult({id:i,topic:t,result:r.result,throwOnFailedPublish:!0}):qi(r)&&await this.sendError(i,t,r.error),this.cleanupAfterResponse(e)},this.ping=async e=>{await this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=await this.sendRequest({topic:t,method:"wc_sessionPing",params:{}}),{done:r,resolve:i,reject:n}=mr();this.events.once(Sr("session_ping",e),(({error:e})=>{e?n(e):i()})),await r()}else this.client.core.pairing.pairings.keys.includes(t)&&await this.client.core.pairing.ping({topic:t})},this.emit=async e=>{await this.isInitialized(),await this.isValidEmit(e);const{topic:t,event:r,chainId:i}=e;await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:r,chainId:i}})},this.disconnect=async e=>{await this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.client.session.keys.includes(t)?(await this.sendRequest({topic:t,method:"wc_sessionDelete",params:Yr("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(t)):await this.client.core.pairing.disconnect({topic:t})},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter((t=>function(e,t){const{requiredNamespaces:r}=t,i=Object.keys(e.namespaces),n=Object.keys(r);let s=!0;return!!pr(n,i)&&(i.forEach((t=>{const{accounts:i,methods:n,events:o}=e.namespaces[t],a=Kr(i),h=r[t];pr(Bt(t,h),a)&&pr(h.methods,n)&&pr(h.events,o)||(s=!1)})),s)}(t,e)))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter((r=>{var i,n;return(null==(i=r.peerMetadata)?void 0:i.url)&&(null==(n=r.peerMetadata)?void 0:n.url)===e.peer.metadata.url&&r.topic&&r.topic!==t.topic}));if(0===r.length)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map((e=>this.client.core.pairing.disconnect({topic:e.topic})))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}},this.deleteSession=async(e,t)=>{const{self:r}=this.client.session.get(e);await this.client.core.relayer.unsubscribe(e),this.client.session.delete(e,Yr("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(r.publicKey)&&await this.client.core.crypto.deleteKeyPair(r.publicKey),this.client.core.crypto.keychain.has(e)&&await this.client.core.crypto.deleteSymKey(e),t||this.client.core.expirer.del(e),this.client.core.storage.removeItem(pu).catch((e=>this.client.logger.warn(e)))},this.deleteProposal=async(e,t)=>{await Promise.all([this.client.proposal.delete(e,Yr("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)])},this.deletePendingSessionRequest=async(e,t,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),r?Promise.resolve():this.client.core.expirer.del(e)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter((t=>t.id!==e)),r&&(this.sessionRequestQueue.state=vu)},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&await this.client.session.update(e,{expiry:t}),this.client.core.expirer.set(e,t)},this.setProposal=async(e,t)=>{await this.client.proposal.set(e,t),this.client.core.expirer.set(e,t.expiry)},this.setPendingSessionRequest=async e=>{const t=yu.wc_sessionRequest.req.ttl,{id:r,topic:i,params:n,verifyContext:s}=e;await this.client.pendingRequest.set(r,{id:r,topic:i,params:n,verifyContext:s}),t&&this.client.core.expirer.set(r,_r(t))},this.sendRequest=async e=>{const{topic:t,method:r,params:i,expiry:n,relayRpcId:s,clientRpcId:o,throwOnFailedPublish:a}=e,h=Ii(r,i,o);if(lr()&&bu.includes(r)){const e=Jt(JSON.stringify(h));this.client.core.verify.register({attestationId:e})}const c=await this.client.core.crypto.encode(t,h),u=yu[r].req;return n&&(u.ttl=n),s&&(u.id=s),this.client.core.history.set(t,h),a?(u.internal=Pu(xu({},u.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,c,u)):this.client.core.relayer.publish(t,c,u).catch((e=>this.client.logger.error(e))),h.id},this.sendResult=async e=>{const{id:t,topic:r,result:i,throwOnFailedPublish:n}=e,s=Ai(t,i),o=await this.client.core.crypto.encode(r,s),a=await this.client.core.history.get(r,t),h=yu[a.request.method].res;n?(h.internal=Pu(xu({},h.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,o,h)):this.client.core.relayer.publish(r,o,h).catch((e=>this.client.logger.error(e))),await this.client.core.history.resolve(s)},this.sendError=async(e,t,r)=>{const i=Oi(e,r),n=await this.client.core.crypto.encode(t,i),s=await this.client.core.history.get(t,e),o=yu[s.request.method].res;this.client.core.relayer.publish(t,n,o),await this.client.core.history.resolve(i)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach((t=>{Er(t.expiry)&&e.push(t.topic)})),this.client.proposal.getAll().forEach((e=>{Er(e.expiry)&&t.push(e.id)})),await Promise.all([...e.map((e=>this.deleteSession(e))),...t.map((e=>this.deleteProposal(e)))])},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state!==wu){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=wu;const e=this.requestQueue.queue.shift();if(e)try{this.processRequest(e),await new Promise((e=>setTimeout(e,300)))}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=vu}else this.client.logger.info("Request queue already active, skipping...")},this.processRequest=e=>{const{topic:t,payload:r}=e,i=r.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeRequest(t,r);case"wc_sessionSettle":return this.onSessionSettleRequest(t,r);case"wc_sessionUpdate":return this.onSessionUpdateRequest(t,r);case"wc_sessionExtend":return this.onSessionExtendRequest(t,r);case"wc_sessionPing":return this.onSessionPingRequest(t,r);case"wc_sessionDelete":return this.onSessionDeleteRequest(t,r);case"wc_sessionRequest":return this.onSessionRequest(t,r);case"wc_sessionEvent":return this.onSessionEventRequest(t,r);default:return this.client.logger.info(`Unsupported request method ${i}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:r}=e,i=(await this.client.core.history.get(t,r.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(t,r);case"wc_sessionSettle":return this.onSessionSettleResponse(t,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,r);case"wc_sessionExtend":return this.onSessionExtendResponse(t,r);case"wc_sessionPing":return this.onSessionPingResponse(t,r);case"wc_sessionRequest":return this.onSessionRequestResponse(t,r);default:return this.client.logger.info(`Unsupported response method ${i}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:r}=Jr("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)},this.onSessionProposeRequest=async(e,t)=>{const{params:r,id:i}=t;try{this.isValidConnect(xu({},t.params));const n=_r(j.FIVE_MINUTES),s=xu({id:i,pairingTopic:e,expiry:n},r);await this.setProposal(i,s);const o=Jt(JSON.stringify(t)),a=await this.getVerifyContext(o,s.proposer.metadata);this.client.events.emit("session_proposal",{id:i,params:s,verifyContext:a})}catch(t){await this.sendError(i,e,t),this.client.logger.error(t)}},this.onSessionProposeResponse=async(e,t)=>{const{id:r}=t;if(ji(t)){const{result:i}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});const n=this.client.proposal.get(r);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const s=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:s});const o=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:o});const a=await this.client.core.crypto.generateSharedKey(s,o);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:a});const h=await this.client.core.relayer.subscribe(a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:e})}else qi(t)&&(await this.client.proposal.delete(r,Yr("USER_DISCONNECTED")),this.events.emit(Sr("session_connect"),{error:t.error}))},this.onSessionSettleRequest=async(e,t)=>{const{id:r,params:i}=t;try{this.isValidSessionSettleRequest(i);const{relay:r,controller:n,expiry:s,namespaces:o,requiredNamespaces:a,optionalNamespaces:h,sessionProperties:c,pairingTopic:u}=t.params,l=xu({topic:e,relay:r,expiry:s,namespaces:o,acknowledged:!0,pairingTopic:u,requiredNamespaces:a,optionalNamespaces:h,controller:n.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:n.publicKey,metadata:n.metadata}},c&&{sessionProperties:c});await this.sendResult({id:t.id,topic:e,result:!0}),this.events.emit(Sr("session_connect"),{session:l}),this.cleanupDuplicatePairings(l)}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.onSessionSettleResponse=async(e,t)=>{const{id:r}=t;ji(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Sr("session_approve",r),{})):qi(t)&&(await this.client.session.delete(e,Yr("USER_DISCONNECTED")),this.events.emit(Sr("session_approve",r),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:r,id:i}=t;try{const t=`${e}_session_update`,n=gi.get(t);if(n&&this.isRequestOutOfSync(n,i))return void this.client.logger.info(`Discarding out of sync request - ${i}`);this.isValidUpdate(xu({topic:e},r)),await this.client.session.update(e,{namespaces:r.namespaces}),await this.sendResult({id:i,topic:e,result:!0}),this.client.events.emit("session_update",{id:i,topic:e,params:r}),gi.set(t,i)}catch(t){await this.sendError(i,e,t),this.client.logger.error(t)}},this.isRequestOutOfSync=(e,t)=>parseInt(t.toString().slice(0,-3))<=parseInt(e.toString().slice(0,-3)),this.onSessionUpdateResponse=(e,t)=>{const{id:r}=t;ji(t)?this.events.emit(Sr("session_update",r),{}):qi(t)&&this.events.emit(Sr("session_update",r),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:r}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,_r(gu)),await this.sendResult({id:r,topic:e,result:!0}),this.client.events.emit("session_extend",{id:r,topic:e})}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.onSessionExtendResponse=(e,t)=>{const{id:r}=t;ji(t)?this.events.emit(Sr("session_extend",r),{}):qi(t)&&this.events.emit(Sr("session_extend",r),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:r}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:r,topic:e,result:!0}),this.client.events.emit("session_ping",{id:r,topic:e})}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.onSessionPingResponse=(e,t)=>{const{id:r}=t;setTimeout((()=>{ji(t)?this.events.emit(Sr("session_ping",r),{}):qi(t)&&this.events.emit(Sr("session_ping",r),{error:t.error})}),500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:r}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await Promise.all([new Promise((t=>{this.client.core.relayer.once(Ps,(async()=>{t(await this.deleteSession(e))}))})),this.sendResult({id:r,topic:e,result:!0})]),this.client.events.emit("session_delete",{id:r,topic:e})}catch(e){this.client.logger.error(e)}},this.onSessionRequest=async(e,t)=>{const{id:r,params:i}=t;try{this.isValidRequest(xu({topic:e},i));const t=Jt(JSON.stringify(Ii("wc_sessionRequest",i,r))),n=this.client.session.get(e),s={id:r,topic:e,params:i,verifyContext:await this.getVerifyContext(t,n.peer.metadata)};await this.setPendingSessionRequest(s),this.addSessionRequestToSessionRequestQueue(s),this.processSessionRequestQueue()}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.onSessionRequestResponse=(e,t)=>{const{id:r}=t;ji(t)?this.events.emit(Sr("session_request",r),{result:t.result}):qi(t)&&this.events.emit(Sr("session_request",r),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:r,params:i}=t;try{const t=`${e}_session_event_${i.event.name}`,n=gi.get(t);if(n&&this.isRequestOutOfSync(n,r))return void this.client.logger.info(`Discarding out of sync request - ${r}`);this.isValidEmit(xu({topic:e},i)),this.client.events.emit("session_event",{id:r,topic:e,params:i}),gi.set(t,r)}catch(t){await this.sendError(r,e,t),this.client.logger.error(t)}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout((()=>{this.sessionRequestQueue.state=vu,this.processSessionRequestQueue()}),(0,j.toMiliseconds)(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===wu)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.sessionRequestQueue.state=wu,this.client.events.emit("session_request",e)}catch(e){this.client.logger.error(e)}else this.client.logger.info("session request queue is empty.")},this.onPairingCreated=e=>{if(e.active)return;const t=this.client.proposal.getAll().find((t=>t.pairingTopic===e.topic));t&&this.onSessionProposeRequest(e.topic,Ii("wc_sessionPropose",{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer},t.id))},this.isValidConnect=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:r,optionalNamespaces:i,sessionProperties:n,relays:s}=e;if(Zr(t)||await this.isValidPairingTopic(t),!function(e,t){let r=!1;return e?e&&Xr(e)&&e.length&&e.forEach((e=>{r=ai(e)})):r=!0,r}(s)){const{message:e}=Jr("MISSING_OR_INVALID",`connect() relays: ${s}`);throw new Error(e)}!Zr(r)&&0!==Qr(r)&&this.validateNamespaces(r,"requiredNamespaces"),!Zr(i)&&0!==Qr(i)&&this.validateNamespaces(i,"optionalNamespaces"),Zr(n)||this.validateSessionProps(n,"sessionProperties")},this.validateNamespaces=(e,t)=>{const r=function(e,t,r){let i=null;if(e&&Qr(e)){const n=si(e,t);n&&(i=n);const s=function(e,t,r){let i=null;return Object.entries(e).forEach((([e,n])=>{if(i)return;const s=function(e,t,r){let i=null;return Xr(t)&&t.length?t.forEach((e=>{i||ri(e)||(i=Yr("UNSUPPORTED_CHAINS",`${r}, chain ${e} should be a string and conform to "namespace:chainId" format`))})):ri(e)||(i=Yr("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}(e,Bt(e,n),`${t} ${r}`);s&&(i=s)})),i}(e,t,r);s&&(i=s)}else i=Jr("MISSING_OR_INVALID",`${t}, ${r} should be an object with data`);return i}(e,"connect()",t);if(r)throw new Error(r.message)},this.isValidApprove=async e=>{if(!hi(e))throw new Error(Jr("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:r,relayProtocol:i,sessionProperties:n}=e;await this.isValidProposalId(t);const s=this.client.proposal.get(t),o=oi(r,"approve()");if(o)throw new Error(o.message);const a=ui(s.requiredNamespaces,r,"approve()");if(a)throw new Error(a.message);if(!ei(i,!0)){const{message:e}=Jr("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(e)}Zr(n)||this.validateSessionProps(n,"sessionProperties")},this.isValidReject=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:r}=e;if(await this.isValidProposalId(t),!function(e){return!!(e&&"object"==typeof e&&e.code&&ti(e.code,!1)&&e.message&&ei(e.message,!1))}(r)){const{message:e}=Jr("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(e)}},this.isValidSessionSettleRequest=e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:r,namespaces:i,expiry:n}=e;if(!ai(t)){const{message:e}=Jr("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const s=function(e,t){let r=null;return ei(e?.publicKey,!1)||(r=Jr("MISSING_OR_INVALID","onSessionSettleRequest() controller public key should be a string")),r}(r);if(s)throw new Error(s.message);const o=oi(i,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(Er(n)){const{message:e}=Jr("EXPIRED","onSessionSettleRequest()");throw new Error(e)}},this.isValidUpdate=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:r}=e;await this.isValidSessionTopic(t);const i=this.client.session.get(t),n=oi(r,"update()");if(n)throw new Error(n.message);const s=ui(i.requiredNamespaces,r,"update()");if(s)throw new Error(s.message)},this.isValidExtend=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:r,chainId:i,expiry:n}=e;await this.isValidSessionTopic(t);const{namespaces:s}=this.client.session.get(t);if(!ci(s,i)){const{message:e}=Jr("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(e)}if(!function(e){return!(Zr(e)||!ei(e.method,!1))}(r)){const{message:e}=Jr("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(e)}if(!function(e,t,r){return!!ei(r,!1)&&function(e,t){const r=[];return Object.values(e).forEach((e=>{Kr(e.accounts).includes(t)&&r.push(...e.methods)})),r}(e,t).includes(r)}(s,i,r.method)){const{message:e}=Jr("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(e)}if(n&&!fi(n,mu)){const{message:e}=Jr("MISSING_OR_INVALID",`request() expiry: ${n}. Expiry must be a number (in seconds) between ${mu.min} and ${mu.max}`);throw new Error(e)}},this.isValidRespond=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:t,response:r}=e;if(await this.isValidSessionTopic(t),!function(e){return!(Zr(e)||Zr(e.result)&&Zr(e.error)||!ti(e.id,!1)||!ei(e.jsonrpc,!1))}(r)){const{message:e}=Jr("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(r)}`);throw new Error(e)}},this.isValidPing=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:r,chainId:i}=e;await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!ci(n,i)){const{message:e}=Jr("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(e)}if(!function(e){return!(Zr(e)||!ei(e.name,!1))}(r)){const{message:e}=Jr("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(e)}if(!function(e,t,r){return!!ei(r,!1)&&function(e,t){const r=[];return Object.values(e).forEach((e=>{Kr(e.accounts).includes(t)&&r.push(...e.events)})),r}(e,t).includes(r)}(n,i,r.name)){const{message:e}=Jr("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(e)}},this.isValidDisconnect=async e=>{if(!hi(e)){const{message:t}=Jr("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.getVerifyContext=async(e,t)=>{const r={verified:{verifyUrl:t.verifyUrl||Gs,validation:"UNKNOWN",origin:t.url||""}};try{const i=await this.client.core.verify.resolve({attestationId:e,verifyUrl:t.verifyUrl});i&&(r.verified.origin=i.origin,r.verified.isScam=i.isScam,r.verified.validation=i.origin===new URL(t.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.info(e)}return this.client.logger.info(`Verify context: ${JSON.stringify(r)}`),r},this.validateSessionProps=(e,t)=>{Object.values(e).forEach((e=>{if(!ei(e,!1)){const{message:r}=Jr("MISSING_OR_INVALID",`${t} must be in Record format. Received: ${JSON.stringify(e)}`);throw new Error(r)}}))}}async isInitialized(){if(!this.initialized){const{message:e}=Jr("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ms,(async e=>{const{topic:t,message:r}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(r)))return;const i=await this.client.core.crypto.decode(t,r);try{Ui(i)?(this.client.core.history.set(t,i),this.onRelayEventRequest({topic:t,payload:i})):ki(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:t,payload:i}),this.client.core.history.delete(t,i.id)):this.onRelayEventUnknownPayload({topic:t,payload:i})}catch(e){this.client.logger.error(e)}}))}registerExpirerEvents(){this.client.core.expirer.on(Hs,(async e=>{const{topic:t,id:r}=br(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,Jr("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession(t,!0),this.client.events.emit("session_expire",{topic:t})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))}))}registerPairingEvents(){this.client.core.pairing.events.on(zs,(e=>this.onPairingCreated(e)))}isValidPairingTopic(e){if(!ei(e,!1)){const{message:t}=Jr("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=Jr("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Er(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=Jr("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ei(e,!1)){const{message:t}=Jr("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(!this.client.session.keys.includes(e)){const{message:t}=Jr("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Er(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:t}=Jr("EXPIRED",`session topic: ${e}`);throw new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else{if(!this.client.core.pairing.pairings.keys.includes(e)){if(ei(e,!1)){const{message:t}=Jr("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=Jr("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if("number"!=typeof e){const{message:t}=Jr("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=Jr("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Er(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:t}=Jr("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class Ru extends Mo{constructor(e,t){super(e,t,"proposal",fu),this.core=e,this.logger=t}}class Tu extends Mo{constructor(e,t){super(e,t,"session",fu),this.core=e,this.logger=t}}class Lu extends Mo{constructor(e,t){super(e,t,"request",fu,(e=>e.id)),this.core=e,this.logger=t}}class Cu extends N{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=du,this.events=new g.EventEmitter,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.removeAllListeners=e=>this.events.removeAllListeners(e),this.connect=async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}},this.pair=async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}},this.approve=async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}},this.reject=async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}},this.update=async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}},this.extend=async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}},this.request=async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}},this.respond=async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}},this.ping=async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}},this.emit=async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}},this.disconnect=async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}},this.find=e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.name=e?.name||du,this.metadata=e?.metadata||(0,Dt.D)()||{name:"",description:"",url:"",icons:[""]};const t=typeof e?.logger<"u"&&"string"!=typeof e?.logger?e.logger:(0,w.pino)((0,w.getDefaultLoggerOptions)({level:e?.logger||"error"}));this.core=e?.core||new ko(e),this.logger=(0,w.generateChildLogger)(t,this.name),this.session=new Tu(this.core,this.logger),this.proposal=new Ru(this.core,this.logger),this.pendingRequest=new Lu(this.core,this.logger),this.engine=new Nu(this)}static async init(e){const t=new Cu(e);return await t.initialize(),t}get context(){return(0,w.getLoggerContext)(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const Uu=Cu;var ku,ju={exports:{}},qu="object"==typeof Reflect?Reflect:null,Du=qu&&"function"==typeof qu.apply?qu.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};ku=qu&&"function"==typeof qu.ownKeys?qu.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var zu=Number.isNaN||function(e){return e!=e};function $u(){$u.init.call(this)}ju.exports=$u,ju.exports.once=function(e,t){return new Promise((function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}Xu(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Xu(e,"error",t,{once:!0})}(e,n)}))},$u.EventEmitter=$u,$u.prototype._events=void 0,$u.prototype._eventsCount=0,$u.prototype._maxListeners=void 0;var Bu=10;function Ku(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Fu(e){return void 0===e._maxListeners?$u.defaultMaxListeners:e._maxListeners}function Vu(e,t,r,i){var n,s,o;if(Ku(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=Fu(e))>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,function(e){console&&console.warn&&console.warn(e)}(a)}return e}function Hu(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Wu(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=Hu.bind(i);return n.listener=r,i.wrapFn=n,n}function Gu(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)Du(a,this,t);else{var h=a.length,c=Yu(a,h);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},$u.prototype.listeners=function(e){return Gu(this,e,!0)},$u.prototype.rawListeners=function(e){return Gu(this,e,!1)},$u.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Ju.call(e,t)},$u.prototype.listenerCount=Ju,$u.prototype.eventNames=function(){return this._eventsCount>0?ku(this._events):[]};ju.exports;class Qu{constructor(e){this.opts=e}}class Zu{constructor(e){this.client=e}}class el extends Zu{constructor(e){super(e),this.init=async()=>{this.signClient=await Uu.init({core:this.client.core,metadata:this.client.metadata}),this.authClient=await uu.init({core:this.client.core,projectId:"",metadata:this.client.metadata}),this.initializeEventListeners()},this.pair=async e=>{await this.client.core.pairing.pair(e)},this.approveSession=async e=>{const{topic:t,acknowledged:r}=await this.signClient.approve({id:e.id,namespaces:e.namespaces});return await r(),this.signClient.session.get(t)},this.rejectSession=async e=>await this.signClient.reject(e),this.updateSession=async e=>await(await this.signClient.update(e)).acknowledged(),this.extendSession=async e=>await(await this.signClient.extend(e)).acknowledged(),this.respondSessionRequest=async e=>await this.signClient.respond(e),this.disconnectSession=async e=>await this.signClient.disconnect(e),this.emitSessionEvent=async e=>await this.signClient.emit(e),this.getActiveSessions=()=>this.signClient.session.getAll().reduce(((e,t)=>(e[t.topic]=t,e)),{}),this.getPendingSessionProposals=()=>this.signClient.proposal.getAll(),this.getPendingSessionRequests=()=>this.signClient.getPendingSessionRequests(),this.respondAuthRequest=async(e,t)=>await this.authClient.respond(e,t),this.getPendingAuthRequests=()=>this.authClient.requests.getAll().filter((e=>"requester"in e)),this.formatMessage=(e,t)=>this.authClient.formatMessage(e,t),this.onSessionRequest=e=>{this.client.events.emit("session_request",e)},this.onSessionProposal=e=>{this.client.events.emit("session_proposal",e)},this.onSessionDelete=e=>{this.client.events.emit("session_delete",e)},this.onAuthRequest=e=>{this.client.events.emit("auth_request",e)},this.initializeEventListeners=()=>{this.signClient.events.on("session_proposal",this.onSessionProposal),this.signClient.events.on("session_request",this.onSessionRequest),this.signClient.events.on("session_delete",this.onSessionDelete),this.authClient.on("auth_request",this.onAuthRequest)},this.signClient={},this.authClient={}}}class tl extends Qu{constructor(e){super(e),this.events=new ju.exports,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.pair=async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}},this.approveSession=async e=>{try{return await this.engine.approveSession(e)}catch(e){throw this.logger.error(e.message),e}},this.rejectSession=async e=>{try{return await this.engine.rejectSession(e)}catch(e){throw this.logger.error(e.message),e}},this.updateSession=async e=>{try{return await this.engine.updateSession(e)}catch(e){throw this.logger.error(e.message),e}},this.extendSession=async e=>{try{return await this.engine.extendSession(e)}catch(e){throw this.logger.error(e.message),e}},this.respondSessionRequest=async e=>{try{return await this.engine.respondSessionRequest(e)}catch(e){throw this.logger.error(e.message),e}},this.disconnectSession=async e=>{try{return await this.engine.disconnectSession(e)}catch(e){throw this.logger.error(e.message),e}},this.emitSessionEvent=async e=>{try{return await this.engine.emitSessionEvent(e)}catch(e){throw this.logger.error(e.message),e}},this.getActiveSessions=()=>{try{return this.engine.getActiveSessions()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionProposals=()=>{try{return this.engine.getPendingSessionProposals()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.respondAuthRequest=async(e,t)=>{try{return await this.engine.respondAuthRequest(e,t)}catch(e){throw this.logger.error(e.message),e}},this.getPendingAuthRequests=()=>{try{return this.engine.getPendingAuthRequests()}catch(e){throw this.logger.error(e.message),e}},this.formatMessage=(e,t)=>{try{return this.engine.formatMessage(e,t)}catch(e){throw this.logger.error(e.message),e}},this.metadata=e.metadata,this.name=e.name||"Web3Wallet",this.core=e.core,this.logger=this.core.logger,this.engine=new el(this)}static async init(e){const t=new tl(e);return await t.initialize(),t}async initialize(){this.logger.trace("Initialized");try{await this.engine.init(),this.logger.info("Web3Wallet Initialization Success")}catch(e){throw this.logger.info("Web3Wallet Initialization Failure"),this.logger.error(e.message),e}}}const rl=tl;function il(e){if(!e.startsWith("wc:"))return null;const t=e.indexOf("@");return t<0?null:e.slice(3,t)}window.wc={core:null,web3wallet:null,authClient:null,init:function(e){return new Promise((async t=>{window.wc.core=new ko({projectId:e}),window.wc.web3wallet=await rl.init({core:window.wc.core,metadata:{name:"Prototype",description:"Prototype Wallet/Peer",url:"https://github.com/status-im/status-desktop",icons:["https://status.im/img/status-footer-logo.svg"]}}),window.wc.authClient=await cu.init({projectId:e,metadata:window.wc.web3wallet.metadata}),t()}))},alreadyPaired:new Error("Already paired"),waitingForApproval:new Error("Waiting for approval"),pair:function(e){let t=il(e);const r=window.wc.core.pairing.getPairings().find((e=>e.topic===t));if(r&&r.active)return new Promise(((e,t)=>{t(window.wc.alreadyPaired)}));let i=window.wc.web3wallet.pair({uri:e});return new Promise(((e,t)=>{i.then((()=>{window.wc.web3wallet.on("session_proposal",(async t=>{e(t)}))})).catch((e=>{t(e)}))}))},registerForSessionRequest:function(e){window.wc.web3wallet.on("session_request",e)},registerForSessionDelete:function(e){window.wc.web3wallet.on("session_delete",e)},approvePairSession:function(e,t){const{id:r,params:i}=e,n=function(e){const{proposal:{requiredNamespaces:t,optionalNamespaces:r={}},supportedNamespaces:i}=e,n=Hr(t),s=Hr(r),o={};Object.keys(i).forEach((e=>{const t=i[e].chains,r=i[e].methods,n=i[e].events,s=i[e].accounts;t.forEach((t=>{if(!s.some((e=>e.includes(t))))throw new Error(`No accounts provided for chain ${t} in namespace ${e}`)})),o[e]={chains:t,methods:r,events:n,accounts:s}}));const a=ui(t,o,"approve()");if(a)throw new Error(a.message);const h={};return Object.keys(t).length||Object.keys(r).length?(Object.keys(n).forEach((e=>{const t=i[e].chains.filter((t=>{var r,i;return null==(i=null==(r=n[e])?void 0:r.chains)?void 0:i.includes(t)})),r=i[e].methods.filter((t=>{var r,i;return null==(i=null==(r=n[e])?void 0:r.methods)?void 0:i.includes(t)})),s=i[e].events.filter((t=>{var r,i;return null==(i=null==(r=n[e])?void 0:r.events)?void 0:i.includes(t)})),o=t.map((t=>i[e].accounts.filter((e=>e.includes(`${t}:`))))).flat();h[e]={chains:t,methods:r,events:s,accounts:o}})),Object.keys(s).forEach((e=>{var t,r,n,o,a,c;if(!i[e])return;const u=null==(r=null==(t=s[e])?void 0:t.chains)?void 0:r.filter((t=>i[e].chains.includes(t))),l=i[e].methods.filter((t=>{var r,i;return null==(i=null==(r=s[e])?void 0:r.methods)?void 0:i.includes(t)})),f=i[e].events.filter((t=>{var r,i;return null==(i=null==(r=s[e])?void 0:r.events)?void 0:i.includes(t)})),d=u?.map((t=>i[e].accounts.filter((e=>e.includes(`${t}:`))))).flat();h[e]={chains:Mr(null==(n=h[e])?void 0:n.chains,u),methods:Mr(null==(o=h[e])?void 0:o.methods,l),events:Mr(null==(a=h[e])?void 0:a.events,f),accounts:Mr(null==(c=h[e])?void 0:c.accounts,d)}})),h):o}({proposal:i,supportedNamespaces:t});return window.wc.web3wallet.approveSession({id:r,namespaces:n})},rejectPairSession:function(e){return window.wc.web3wallet.rejectSession({id:e,reason:Yr("USER_REJECTED")})},auth:function(e){let t=il(e);const r=window.wc.core.pairing.getPairings().find((e=>e.topic===t));if(r&&r.active)return new Promise(((e,t)=>{t(window.wc.alreadyPaired)}));let i=window.wc.authClient.core.pairing.pair({uri:e});return new Promise(((e,t)=>{i.then((()=>{window.wc.authClient.on("auth_request",(async t=>{e(t)}))})).catch((e=>{t(e)}))}))},approveAuth:function(e){const{id:t,params:r}=e,i="did:pkh:eip155:1:0x0123456789";return window.wc.authClient.formatMessage(r.cacaoPayload,i),window.wc.authClient.respond({id:t,signature:{s:"0x123456789",t:"eip191"}},i)},rejectAuth:function(e){return window.wc.authClient.reject(e)},respondSessionRequest:function(e,t){window.wc.web3wallet.respondSessionRequest({topic:e,response:t})},disconnectAll:function(){window.wc.core.pairing.getPairings().forEach((e=>{window.wc.core.pairing.disconnect({topic:e.topic})}))}}})(); \ No newline at end of file diff --git a/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/src/index.js b/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/src/index.js index 8ee3fe4e419..09a378414a7 100644 --- a/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/src/index.js +++ b/ui/app/AppLayouts/Wallet/views/walletconnect/sdk/src/index.js @@ -22,10 +22,9 @@ window.wc = { window.wc.web3wallet = await Web3Wallet.init({ core: window.wc.core, // <- pass the shared `core` instance metadata: { - // TODO: what values should be here? - name: "Prototype", - description: "Prototype Wallet/Peer", - url: "https://github.com/status-im/status-desktop", + name: "Status", + description: "Status Wallet", + url: "https://status.app", icons: ['https://status.im/img/status-footer-logo.svg'], }, }); @@ -35,7 +34,7 @@ window.wc = { metadata: window.wc.web3wallet.metadata, }) - resolve(window.wc) + resolve() }) }, @@ -45,10 +44,6 @@ window.wc = { pair: function (uri) { let pairingTopic = getPairingTopicFromPairingUrl(uri); - let pairPromise = window.wc.web3wallet - .pair({ uri: uri }) - .catch((error) => console.error(error)); - const pairings = window.wc.core.pairing.getPairings(); // Find pairing by topic const pairing = pairings.find((p) => p.topic === pairingTopic); @@ -60,6 +55,10 @@ window.wc = { } } + let pairPromise = window.wc.web3wallet + .pair({ uri: uri }) + + return new Promise((resolve, reject) => { pairPromise .then(() => { @@ -77,36 +76,24 @@ window.wc = { window.wc.web3wallet.on("session_request", callback); }, - // TODO: ensure if session requests only one account we don't provide all accounts - approveSession: function (sessionProposal) { + registerForSessionDelete: function (callback) { + window.wc.web3wallet.on("session_delete", callback); + }, + + approvePairSession: function (sessionProposal, supportedNamespaces) { const { id, params } = sessionProposal; - // ------- namespaces builder util ------------ // const approvedNamespaces = buildApprovedNamespaces({ proposal: params, - // TODO: source this from wallet - supportedNamespaces: { - eip155: { - chains: ["eip155:1", "eip155:5"], - methods: ["eth_sendTransaction", "personal_sign"], - events: ["accountsChanged", "chainChanged"], - accounts: [ - "eip155:1:0x0000000000000000000000000000000000000001", - "eip155:5:0xe74E17D586227691Cb7b64ed78b1b7B14828B034", - ], - }, - }, + supportedNamespaces: supportedNamespaces, }); - // ------- end namespaces builder util ------------ // - const session = window.wc.web3wallet.approveSession({ + return window.wc.web3wallet.approveSession({ id, namespaces: approvedNamespaces, }); - - return session; }, - rejectSession: function (id) { + rejectPairSession: function (id) { return window.wc.web3wallet.rejectSession({ id: id, reason: getSdkError("USER_REJECTED"), // TODO USER_REJECTED_METHODS, USER_REJECTED_CHAINS, USER_REJECTED_EVENTS @@ -116,10 +103,6 @@ window.wc = { auth: function (uri) { let pairingTopic = getPairingTopicFromPairingUrl(uri); - let pairPromise = window.wc.authClient.core.pairing - .pair({ uri }) - .catch((error) => console.error(error)); - const pairings = window.wc.core.pairing.getPairings(); // Find pairing by topic const pairing = pairings.find((p) => p.topic === pairingTopic); @@ -131,6 +114,9 @@ window.wc = { } } + let pairPromise = window.wc.authClient.core.pairing + .pair({ uri }) + return new Promise((resolve, reject) => { pairPromise .then(() => { diff --git a/vendor/status-go b/vendor/status-go index 1d08b403e68..71f69f2468d 160000 --- a/vendor/status-go +++ b/vendor/status-go @@ -1 +1 @@ -Subproject commit 1d08b403e6818b6efd31785fbc73ece3d44e4926 +Subproject commit 71f69f2468d9eb163b0719fc14c311fb38fd8119